code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
<?php
/*
* This file is part of the HRis Software package.
*
* NOTICE OF LICENSE
*
* Licensed under the 3-clause BSD License.
*
* This source file is subject to the 3-clause BSD License that is
* bundled with this package in the LICENSE file.
*
* @version alpha
*
* @author Bertrand Kintanar <[email protected]>
* @license BSD License (3-clause)
* @copyright (c) 2014-2016, b8 Studios, Ltd
*
* @link http://github.com/HB-Co/HRis
*/
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateEmergencyContactsTable extends Migration
{
/**
* Reverse the migrations.
*
* @return void
*
* @author Bertrand Kintanar
*/
public function down()
{
Schema::drop('emergency_contacts');
}
/**
* Run the migrations.
*
* @return void
*
* @author Bertrand Kintanar
*/
public function up()
{
Schema::create('emergency_contacts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('employee_id');
$table->string('first_name');
$table->string('middle_name')->nullable();
$table->string('last_name');
$table->unsignedInteger('relationship_id');
$table->string('home_phone');
$table->string('mobile_phone');
$table->foreign('employee_id')->references('id')->on('employees')->onDelete('cascade');
$table->foreign('relationship_id')->references('id')->on('relationships')->onDelete('cascade');
});
}
}
|
bkintanar/HRis
|
database/migrations/2014_10_24_143753_create_emergency_contacts_table.php
|
PHP
|
bsd-3-clause
| 1,635 |
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>Komuso2</p>
* <p>A simple JMX monitoring tool</p>
* <p>Copyright: Copyright (c) 2007,2008 Yusuke Yamamoto</p>
* <p>Copyright: Copyright (c) 2014 atWare, Inc.</p>
* @author Yusuke Yamamoto
* @author Koki Kawano
* @version 2.0
*/
public class Komuso2 implements Runnable {
private final String delimiter;
private List<MBeanAttribute> mbeanAttributes;
boolean connected = false;
MBeanServerConnection connection = null;
Logger csvLogger;
Logger statusLogger;
Properties props = new Properties();
public static void main(String[] args) {
args = args.length == 0 ? new String[] { "komuso.properties" } : args;
for (int i = 0; i < args.length; i++) {
new Thread(new Komuso2(args[i]), "Komuso Monitoring Thread for[" + args[i] + "]").start();
}
}
public Komuso2(String propFileName) {
File configFile = new File(propFileName);
try {
props.load(new FileInputStream(configFile));
}
catch (IOException ex) {
System.out.println("Configuration file not found :"
+ configFile.getAbsoluteFile().getPath());
System.exit(-1);
}
csvLogger = LoggerFactory.getLogger(props.getProperty("csvLogger", "csv"));
statusLogger = LoggerFactory.getLogger(props.getProperty("statusLogger", "status"));
delimiter = props.getProperty("delimiter", ",");
}
public void run() {
int count = Integer.parseInt(props.getProperty("count"));
int interval = Integer.parseInt(props.getProperty("interval"));
SimpleDateFormat dateFormat = new SimpleDateFormat(props.getProperty("dateFormat"));
mbeanAttributes = new ArrayList<MBeanAttribute>();
for (String label : props.getProperty("mbeans").split(",")) {
mbeanAttributes.add(
new MBeanAttribute(label,
props.getProperty(label + ".objectName"),
props.getProperty(label + ".attributeName")));
}
StringBuilder sb = new StringBuilder();
// print labels
sb.delete(0, sb.length()).append("Timestamp");
for (int i = 0; i < mbeanAttributes.size(); i++) {
sb.append(delimiter).append(mbeanAttributes.get(i).label);
}
csvLogger.info(sb.toString());
int currentCount = 0;
JMXConnector connector = null;
long next = System.currentTimeMillis() + interval * 1000;
while (-1 == count || currentCount++ < count) {
// get MBeanServerConnection until success
while (!connected) {
statusLogger.info("Trying to connect to the MBean Server.");
try {
try {
// ensure the connection is closed
connector.close();
}
catch (Exception ignore) {
}
connector = JMXConnectorFactory.connect(new JMXServiceURL(props
.getProperty("JMXServiceURL")), new java.util.HashMap(props));
connection = connector.getMBeanServerConnection();
statusLogger.info("Successfully connected to the MBean Server.");
connected = true;
statusLogger.info("Start monitoring.");
}
catch (IOException ioe) {
statusLogger
.warn("IOException throwed while connecting to the MBean server. Will retry 5 seconds later.");
try {
Thread.sleep(5000);
}
catch (InterruptedException ignore) {
}
}
}
// print values
sb.delete(0, sb.length()).append(dateFormat.format(new Date()));
for (MBeanAttribute mbeanAttribute : mbeanAttributes) {
sb.append(delimiter).append(mbeanAttribute.getValue());
if (!connected) {
statusLogger.info("Connection lost.");
break;
}
}
csvLogger.info(sb.toString());
// wait until next sampling
try {
Thread.sleep(next - System.currentTimeMillis());
}
catch (IllegalArgumentException inCaseTheArgumentIsNegative) {
next = System.currentTimeMillis();
}
catch (InterruptedException neverHappen) {
}
next += interval * 1000;
}
}
class MBeanAttribute {
/*package*/String label;
private ObjectName theBean;
private String attributeName;
MBeanAttribute(String label, String objectName, String attributeName) {
this.label = label;
try {
theBean = new ObjectName(objectName);
}
catch (MalformedObjectNameException nsme) {
throw new IllegalArgumentException("Illegal Object Name [" + objectName + "]");
}
this.attributeName = attributeName;
}
public String getValue() {
try {
try {
Object value = connection.getAttribute(theBean, attributeName);
if (value instanceof CompositeDataSupport) {
CompositeDataSupport comp = ((CompositeDataSupport) value);
StringBuilder sb = new StringBuilder();
for (String key : comp.getCompositeType().keySet()) {
if (0 < sb.length()) {
sb.append(" ");
}
sb.append(key).append("=").append(comp.get(key));
}
return sb.toString();
}
return String.valueOf(value);
}
catch (InstanceNotFoundException e) {
System.out.println("(1) [" + attributeName + ":" + theBean + "] " + e.getMessage());
connection.getMBeanInfo(theBean);
}
}
catch (Exception ex) {
System.out.println("(2) [" + attributeName + ":" + theBean + "] " + ex.getMessage());
statusLogger.error("Exception throwed while getting attrbute \""
+ attributeName + "\" of \"" + theBean + "\"", ex);
connected = false;
}
return "n/a";
}
}
}
|
atware/komuso
|
src/Komuso2.java
|
Java
|
bsd-3-clause
| 6,358 |
<?php
use yii\helpers\Html,
yii\helpers\Url;
/* @var $this yii\web\View */
/* @var $limit int */
/* @var $posts */
/* @var $dateFormat string|null */
$this->registerCssFile('/css/news-short-block.css');
$formatter = Yii::$app->getFormatter();
?>
<section>
<div class="row offset-top-20">
<div class="col-xs-12 inline-header">
<h2 class="default">Новости</h2>
</div>
</div>
<div class="row offset-top-10">
<div class="col-sm-9 news">
<div class="row">
<?php for($i=0; $i<3; $i++ ){ ?>
<div class="col-sm-4">
<a href="<?php echo Url::toRoute(['news/view', 'id' => $posts[$i]['id']]); ?>">
<img alt="Изображение" style="width: 200px; height: 140px;" class="img-responsive" onerror="this.src='images/default.jpg'" src="http://services.zagorod.spb.ru/images/preview/290x290x_nocrop_<?php echo $posts[$i]['id'];?>.jpg">
</a>
<span class="news"><?php echo Yii::$app->getFormatter()->asDate($posts[$i]['date'], 'php:d.m.Y'); ?></span>
<a href="<?php echo Url::toRoute(['news/view', 'id' => $posts[$i]['id']]); ?>">
<p class="news"><?php echo Html::encode($posts[$i]['title']); ?></p>
</a>
</div>
<?php } ?>
</div>
<!--<a class="offset-top-10" href="<?php// echo Url::toRoute('news/index'); ?>">Все новости</a>-->
</div>
<div class="col-sm-3 news">
<?php for($i=3; $i<6; $i++ ){ ?>
<div class="row">
<div class="col-sm-12">
<span class="news"><?php echo Yii::$app->getFormatter()->asDate($posts[$i]['date'], 'php:d.m.Y'); ?></span>
<a href="<?php echo Url::toRoute(['news/view', 'id' => $posts[$i]['id']]); ?>">
<p class="news list"><?php echo Html::encode($posts[$i]['title']); ?></p>
</a>
</div>
</div>
<?php } ?>
</div>
</div>
</section>
|
aivankovich/zo
|
widgets/views/newswidget.php
|
PHP
|
bsd-3-clause
| 2,220 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/themes/browser_theme_pack.h"
#include <limits>
#include "base/files/file.h"
#include "base/memory/ref_counted_memory.h"
#include "base/memory/scoped_ptr.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "chrome/browser/themes/theme_properties.h"
#include "chrome/common/extensions/manifest_handlers/theme_handler.h"
#include "components/crx_file/id_util.h"
#include "content/public/browser/browser_thread.h"
#include "grit/theme_resources.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "ui/base/resource/data_pack.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/geometry/size_conversions.h"
#include "ui/gfx/image/canvas_image_source.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_operations.h"
#include "ui/gfx/screen.h"
#include "ui/gfx/skia_util.h"
#include "ui/resources/grit/ui_resources.h"
using content::BrowserThread;
using extensions::Extension;
namespace {
// Version number of the current theme pack. We just throw out and rebuild
// theme packs that aren't int-equal to this. Increment this number if you
// change default theme assets.
const int kThemePackVersion = 36;
// IDs that are in the DataPack won't clash with the positive integer
// uint16. kHeaderID should always have the maximum value because we want the
// "header" to be written last. That way we can detect whether the pack was
// successfully written and ignore and regenerate if it was only partially
// written (i.e. chrome crashed on a different thread while writing the pack).
const int kMaxID = 0x0000FFFF; // Max unsigned 16-bit int.
const int kHeaderID = kMaxID - 1;
const int kTintsID = kMaxID - 2;
const int kColorsID = kMaxID - 3;
const int kDisplayPropertiesID = kMaxID - 4;
const int kSourceImagesID = kMaxID - 5;
const int kScaleFactorsID = kMaxID - 6;
// The sum of kFrameBorderThickness and kNonClientRestoredExtraThickness from
// OpaqueBrowserFrameView.
const int kRestoredTabVerticalOffset = 15;
// Persistent constants for the main images that we need. These have the same
// names as their IDR_* counterparts but these values will always stay the
// same.
const int PRS_THEME_FRAME = 1;
const int PRS_THEME_FRAME_INACTIVE = 2;
const int PRS_THEME_FRAME_INCOGNITO = 3;
const int PRS_THEME_FRAME_INCOGNITO_INACTIVE = 4;
const int PRS_THEME_TOOLBAR = 5;
const int PRS_THEME_TAB_BACKGROUND = 6;
const int PRS_THEME_TAB_BACKGROUND_INCOGNITO = 7;
const int PRS_THEME_TAB_BACKGROUND_V = 8;
const int PRS_THEME_NTP_BACKGROUND = 9;
const int PRS_THEME_FRAME_OVERLAY = 10;
const int PRS_THEME_FRAME_OVERLAY_INACTIVE = 11;
const int PRS_THEME_BUTTON_BACKGROUND = 12;
const int PRS_THEME_NTP_ATTRIBUTION = 13;
const int PRS_THEME_WINDOW_CONTROL_BACKGROUND = 14;
struct PersistingImagesTable {
// A non-changing integer ID meant to be saved in theme packs. This ID must
// not change between versions of chrome.
int persistent_id;
// The IDR that depends on the whims of GRIT and therefore changes whenever
// someone adds a new resource.
int idr_id;
// String to check for when parsing theme manifests or NULL if this isn't
// supposed to be changeable by the user.
const char* const key;
};
// IDR_* resource names change whenever new resources are added; use persistent
// IDs when storing to a cached pack.
//
// TODO(erg): The cocoa port is the last user of the IDR_*_[HP] variants. These
// should be removed once the cocoa port no longer uses them.
PersistingImagesTable kPersistingImages[] = {
{PRS_THEME_FRAME, IDR_THEME_FRAME, "theme_frame"},
{PRS_THEME_FRAME_INACTIVE,
IDR_THEME_FRAME_INACTIVE,
"theme_frame_inactive"},
{PRS_THEME_FRAME_INCOGNITO,
IDR_THEME_FRAME_INCOGNITO,
"theme_frame_incognito"},
{PRS_THEME_FRAME_INCOGNITO_INACTIVE,
IDR_THEME_FRAME_INCOGNITO_INACTIVE,
"theme_frame_incognito_inactive"},
{PRS_THEME_TOOLBAR, IDR_THEME_TOOLBAR, "theme_toolbar"},
{PRS_THEME_TAB_BACKGROUND,
IDR_THEME_TAB_BACKGROUND,
"theme_tab_background"},
#if !defined(OS_MACOSX)
{PRS_THEME_TAB_BACKGROUND_INCOGNITO,
IDR_THEME_TAB_BACKGROUND_INCOGNITO,
"theme_tab_background_incognito"},
#endif
{PRS_THEME_TAB_BACKGROUND_V,
IDR_THEME_TAB_BACKGROUND_V,
"theme_tab_background_v"},
{PRS_THEME_NTP_BACKGROUND,
IDR_THEME_NTP_BACKGROUND,
"theme_ntp_background"},
{PRS_THEME_FRAME_OVERLAY, IDR_THEME_FRAME_OVERLAY, "theme_frame_overlay"},
{PRS_THEME_FRAME_OVERLAY_INACTIVE,
IDR_THEME_FRAME_OVERLAY_INACTIVE,
"theme_frame_overlay_inactive"},
{PRS_THEME_BUTTON_BACKGROUND,
IDR_THEME_BUTTON_BACKGROUND,
"theme_button_background"},
{PRS_THEME_NTP_ATTRIBUTION,
IDR_THEME_NTP_ATTRIBUTION,
"theme_ntp_attribution"},
{PRS_THEME_WINDOW_CONTROL_BACKGROUND,
IDR_THEME_WINDOW_CONTROL_BACKGROUND,
"theme_window_control_background"},
// The rest of these entries have no key because they can't be overridden
// from the json manifest.
{15, IDR_BACK, NULL},
{16, IDR_BACK_D, NULL},
{17, IDR_BACK_H, NULL},
{18, IDR_BACK_P, NULL},
{19, IDR_FORWARD, NULL},
{20, IDR_FORWARD_D, NULL},
{21, IDR_FORWARD_H, NULL},
{22, IDR_FORWARD_P, NULL},
{23, IDR_HOME, NULL},
{24, IDR_HOME_H, NULL},
{25, IDR_HOME_P, NULL},
{26, IDR_RELOAD, NULL},
{27, IDR_RELOAD_H, NULL},
{28, IDR_RELOAD_P, NULL},
{29, IDR_STOP, NULL},
{30, IDR_STOP_D, NULL},
{31, IDR_STOP_H, NULL},
{32, IDR_STOP_P, NULL},
{33, IDR_BROWSER_ACTIONS_OVERFLOW, NULL},
{34, IDR_BROWSER_ACTIONS_OVERFLOW_H, NULL},
{35, IDR_BROWSER_ACTIONS_OVERFLOW_P, NULL},
{36, IDR_TOOLS, NULL},
{37, IDR_TOOLS_H, NULL},
{38, IDR_TOOLS_P, NULL},
{39, IDR_MENU_DROPARROW, NULL},
{40, IDR_TOOLBAR_BEZEL_HOVER, NULL},
{41, IDR_TOOLBAR_BEZEL_PRESSED, NULL},
{42, IDR_TOOLS_BAR, NULL},
};
const size_t kPersistingImagesLength = arraysize(kPersistingImages);
#if defined(USE_ASH) && !defined(OS_CHROMEOS)
// Persistent theme ids for Windows.
const int PRS_THEME_FRAME_DESKTOP = 100;
const int PRS_THEME_FRAME_INACTIVE_DESKTOP = 101;
const int PRS_THEME_FRAME_INCOGNITO_DESKTOP = 102;
const int PRS_THEME_FRAME_INCOGNITO_INACTIVE_DESKTOP = 103;
const int PRS_THEME_TOOLBAR_DESKTOP = 104;
const int PRS_THEME_TAB_BACKGROUND_DESKTOP = 105;
const int PRS_THEME_TAB_BACKGROUND_INCOGNITO_DESKTOP = 106;
// Persistent theme to resource id mapping for Windows AURA.
PersistingImagesTable kPersistingImagesDesktopAura[] = {
{ PRS_THEME_FRAME_DESKTOP, IDR_THEME_FRAME_DESKTOP,
"theme_frame" },
{ PRS_THEME_FRAME_INACTIVE_DESKTOP, IDR_THEME_FRAME_INACTIVE_DESKTOP,
"theme_frame_inactive" },
{ PRS_THEME_FRAME_INCOGNITO_DESKTOP, IDR_THEME_FRAME_INCOGNITO_DESKTOP,
"theme_frame_incognito" },
{ PRS_THEME_FRAME_INCOGNITO_INACTIVE_DESKTOP,
IDR_THEME_FRAME_INCOGNITO_INACTIVE_DESKTOP,
"theme_frame_incognito_inactive" },
{ PRS_THEME_TOOLBAR_DESKTOP, IDR_THEME_TOOLBAR_DESKTOP,
"theme_toolbar" },
{ PRS_THEME_TAB_BACKGROUND_DESKTOP, IDR_THEME_TAB_BACKGROUND_DESKTOP,
"theme_tab_background" },
{ PRS_THEME_TAB_BACKGROUND_INCOGNITO_DESKTOP,
IDR_THEME_TAB_BACKGROUND_INCOGNITO_DESKTOP,
"theme_tab_background_incognito" },
};
const size_t kPersistingImagesDesktopAuraLength =
arraysize(kPersistingImagesDesktopAura);
#endif
int GetPersistentIDByNameHelper(const std::string& key,
const PersistingImagesTable* image_table,
size_t image_table_size) {
for (size_t i = 0; i < image_table_size; ++i) {
if (image_table[i].key &&
base::LowerCaseEqualsASCII(key, image_table[i].key)) {
return image_table[i].persistent_id;
}
}
return -1;
}
int GetPersistentIDByName(const std::string& key) {
return GetPersistentIDByNameHelper(key,
kPersistingImages,
kPersistingImagesLength);
}
int GetPersistentIDByIDR(int idr) {
static std::map<int,int>* lookup_table = new std::map<int,int>();
if (lookup_table->empty()) {
for (size_t i = 0; i < kPersistingImagesLength; ++i) {
int idr = kPersistingImages[i].idr_id;
int prs_id = kPersistingImages[i].persistent_id;
(*lookup_table)[idr] = prs_id;
}
#if defined(USE_ASH) && !defined(OS_CHROMEOS)
for (size_t i = 0; i < kPersistingImagesDesktopAuraLength; ++i) {
int idr = kPersistingImagesDesktopAura[i].idr_id;
int prs_id = kPersistingImagesDesktopAura[i].persistent_id;
(*lookup_table)[idr] = prs_id;
}
#endif
}
std::map<int,int>::iterator it = lookup_table->find(idr);
return (it == lookup_table->end()) ? -1 : it->second;
}
// Returns the maximum persistent id.
int GetMaxPersistentId() {
static int max_prs_id = -1;
if (max_prs_id == -1) {
for (size_t i = 0; i < kPersistingImagesLength; ++i) {
if (kPersistingImages[i].persistent_id > max_prs_id)
max_prs_id = kPersistingImages[i].persistent_id;
}
#if defined(USE_ASH) && !defined(OS_CHROMEOS)
for (size_t i = 0; i < kPersistingImagesDesktopAuraLength; ++i) {
if (kPersistingImagesDesktopAura[i].persistent_id > max_prs_id)
max_prs_id = kPersistingImagesDesktopAura[i].persistent_id;
}
#endif
}
return max_prs_id;
}
// Returns true if the scales in |input| match those in |expected|.
// The order must match as the index is used in determining the raw id.
bool InputScalesValid(const base::StringPiece& input,
const std::vector<ui::ScaleFactor>& expected) {
size_t scales_size = static_cast<size_t>(input.size() / sizeof(float));
if (scales_size != expected.size())
return false;
scoped_ptr<float[]> scales(new float[scales_size]);
// Do a memcpy to avoid misaligned memory access.
memcpy(scales.get(), input.data(), input.size());
for (size_t index = 0; index < scales_size; ++index) {
if (scales[index] != ui::GetScaleForScaleFactor(expected[index]))
return false;
}
return true;
}
// Returns |scale_factors| as a string to be written to disk.
std::string GetScaleFactorsAsString(
const std::vector<ui::ScaleFactor>& scale_factors) {
scoped_ptr<float[]> scales(new float[scale_factors.size()]);
for (size_t i = 0; i < scale_factors.size(); ++i)
scales[i] = ui::GetScaleForScaleFactor(scale_factors[i]);
std::string out_string = std::string(
reinterpret_cast<const char*>(scales.get()),
scale_factors.size() * sizeof(float));
return out_string;
}
struct StringToIntTable {
const char* const key;
ThemeProperties::OverwritableByUserThemeProperty id;
};
// Strings used by themes to identify tints in the JSON.
StringToIntTable kTintTable[] = {
{ "buttons", ThemeProperties::TINT_BUTTONS },
{ "frame", ThemeProperties::TINT_FRAME },
{ "frame_inactive", ThemeProperties::TINT_FRAME_INACTIVE },
{ "frame_incognito", ThemeProperties::TINT_FRAME_INCOGNITO },
{ "frame_incognito_inactive",
ThemeProperties::TINT_FRAME_INCOGNITO_INACTIVE },
{ "background_tab", ThemeProperties::TINT_BACKGROUND_TAB },
};
const size_t kTintTableLength = arraysize(kTintTable);
// Strings used by themes to identify colors in the JSON.
StringToIntTable kColorTable[] = {
{ "frame", ThemeProperties::COLOR_FRAME },
{ "frame_inactive", ThemeProperties::COLOR_FRAME_INACTIVE },
{ "frame_incognito", ThemeProperties::COLOR_FRAME_INCOGNITO },
{ "frame_incognito_inactive",
ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE },
{ "toolbar", ThemeProperties::COLOR_TOOLBAR },
{ "tab_text", ThemeProperties::COLOR_TAB_TEXT },
{ "tab_background_text", ThemeProperties::COLOR_BACKGROUND_TAB_TEXT },
{ "bookmark_text", ThemeProperties::COLOR_BOOKMARK_TEXT },
{ "ntp_background", ThemeProperties::COLOR_NTP_BACKGROUND },
{ "ntp_text", ThemeProperties::COLOR_NTP_TEXT },
{ "ntp_link", ThemeProperties::COLOR_NTP_LINK },
{ "ntp_link_underline", ThemeProperties::COLOR_NTP_LINK_UNDERLINE },
{ "ntp_header", ThemeProperties::COLOR_NTP_HEADER },
{ "ntp_section", ThemeProperties::COLOR_NTP_SECTION },
{ "ntp_section_text", ThemeProperties::COLOR_NTP_SECTION_TEXT },
{ "ntp_section_link", ThemeProperties::COLOR_NTP_SECTION_LINK },
{ "ntp_section_link_underline",
ThemeProperties::COLOR_NTP_SECTION_LINK_UNDERLINE },
{ "button_background", ThemeProperties::COLOR_BUTTON_BACKGROUND },
};
const size_t kColorTableLength = arraysize(kColorTable);
// Strings used by themes to identify display properties keys in JSON.
StringToIntTable kDisplayProperties[] = {
{ "ntp_background_alignment",
ThemeProperties::NTP_BACKGROUND_ALIGNMENT },
{ "ntp_background_repeat", ThemeProperties::NTP_BACKGROUND_TILING },
{ "ntp_logo_alternate", ThemeProperties::NTP_LOGO_ALTERNATE },
};
const size_t kDisplayPropertiesSize = arraysize(kDisplayProperties);
int GetIntForString(const std::string& key,
StringToIntTable* table,
size_t table_length) {
for (size_t i = 0; i < table_length; ++i) {
if (base::LowerCaseEqualsASCII(key, table[i].key)) {
return table[i].id;
}
}
return -1;
}
struct IntToIntTable {
int key;
int value;
};
// Mapping used in CreateFrameImages() to associate frame images with the
// tint ID that should maybe be applied to it.
IntToIntTable kFrameTintMap[] = {
{ PRS_THEME_FRAME, ThemeProperties::TINT_FRAME },
{ PRS_THEME_FRAME_INACTIVE, ThemeProperties::TINT_FRAME_INACTIVE },
{ PRS_THEME_FRAME_OVERLAY, ThemeProperties::TINT_FRAME },
{ PRS_THEME_FRAME_OVERLAY_INACTIVE,
ThemeProperties::TINT_FRAME_INACTIVE },
{ PRS_THEME_FRAME_INCOGNITO, ThemeProperties::TINT_FRAME_INCOGNITO },
{ PRS_THEME_FRAME_INCOGNITO_INACTIVE,
ThemeProperties::TINT_FRAME_INCOGNITO_INACTIVE },
#if defined(USE_ASH) && !defined(OS_CHROMEOS)
{ PRS_THEME_FRAME_DESKTOP, ThemeProperties::TINT_FRAME },
{ PRS_THEME_FRAME_INACTIVE_DESKTOP, ThemeProperties::TINT_FRAME_INACTIVE },
{ PRS_THEME_FRAME_INCOGNITO_DESKTOP, ThemeProperties::TINT_FRAME_INCOGNITO },
{ PRS_THEME_FRAME_INCOGNITO_INACTIVE_DESKTOP,
ThemeProperties::TINT_FRAME_INCOGNITO_INACTIVE },
#endif
};
// Mapping used in GenerateTabBackgroundImages() to associate what frame image
// goes with which tab background.
IntToIntTable kTabBackgroundMap[] = {
{ PRS_THEME_TAB_BACKGROUND, PRS_THEME_FRAME },
{ PRS_THEME_TAB_BACKGROUND_INCOGNITO, PRS_THEME_FRAME_INCOGNITO },
#if defined(USE_ASH) && !defined(OS_CHROMEOS)
{ PRS_THEME_TAB_BACKGROUND_DESKTOP, PRS_THEME_FRAME_DESKTOP },
{ PRS_THEME_TAB_BACKGROUND_INCOGNITO_DESKTOP,
PRS_THEME_FRAME_INCOGNITO_DESKTOP },
#endif
};
struct CropEntry {
int prs_id;
// The maximum useful height of the image at |prs_id|.
int max_height;
// Whether cropping the image at |prs_id| should be skipped on OSes which
// have a frame border to the left and right of the web contents.
// This should be true for images which can be used to decorate the border to
// the left and the right of the web contents.
bool skip_if_frame_border;
};
// The images which should be cropped before being saved to the data pack. The
// maximum heights are meant to be conservative as to give room for the UI to
// change without the maximum heights having to be modified.
// |kThemePackVersion| must be incremented if any of the maximum heights below
// are modified.
struct CropEntry kImagesToCrop[] = {
{ PRS_THEME_FRAME, 120, true },
{ PRS_THEME_FRAME_INACTIVE, 120, true },
{ PRS_THEME_FRAME_INCOGNITO, 120, true },
{ PRS_THEME_FRAME_INCOGNITO_INACTIVE, 120, true },
{ PRS_THEME_FRAME_OVERLAY, 120, true },
{ PRS_THEME_FRAME_OVERLAY_INACTIVE, 120, true },
{ PRS_THEME_TOOLBAR, 200, false },
{ PRS_THEME_BUTTON_BACKGROUND, 60, false },
{ PRS_THEME_WINDOW_CONTROL_BACKGROUND, 50, false },
#if defined(USE_ASH) && !defined(OS_CHROMEOS)
{ PRS_THEME_TOOLBAR_DESKTOP, 200, false }
#endif
};
// A list of images that don't need tinting or any other modification and can
// be byte-copied directly into the finished DataPack. This should contain the
// persistent IDs for all themeable image IDs that aren't in kFrameTintMap,
// kTabBackgroundMap or kImagesToCrop.
const int kPreloadIDs[] = {
PRS_THEME_NTP_BACKGROUND,
PRS_THEME_NTP_ATTRIBUTION,
};
// Returns true if this OS uses a browser frame which has a non zero width to
// the left and the right of the web contents.
bool HasFrameBorder() {
#if defined(OS_CHROMEOS) || defined(OS_MACOSX)
return false;
#else
return true;
#endif
}
// Returns a piece of memory with the contents of the file |path|.
base::RefCountedMemory* ReadFileData(const base::FilePath& path) {
if (!path.empty()) {
base::File file(path, base::File::FLAG_OPEN | base::File::FLAG_READ);
if (file.IsValid()) {
int64 length = file.GetLength();
if (length > 0 && length < INT_MAX) {
int size = static_cast<int>(length);
std::vector<unsigned char> raw_data;
raw_data.resize(size);
char* data = reinterpret_cast<char*>(&(raw_data.front()));
if (file.ReadAtCurrentPos(data, size) == length)
return base::RefCountedBytes::TakeVector(&raw_data);
}
}
}
return NULL;
}
// Shifts an image's HSL values. The caller is responsible for deleting
// the returned image.
gfx::Image CreateHSLShiftedImage(const gfx::Image& image,
const color_utils::HSL& hsl_shift) {
const gfx::ImageSkia* src_image = image.ToImageSkia();
return gfx::Image(gfx::ImageSkiaOperations::CreateHSLShiftedImage(
*src_image, hsl_shift));
}
// Computes a bitmap at one scale from a bitmap at a different scale.
SkBitmap CreateLowQualityResizedBitmap(const SkBitmap& source_bitmap,
ui::ScaleFactor source_scale_factor,
ui::ScaleFactor desired_scale_factor) {
gfx::Size scaled_size = gfx::ToCeiledSize(
gfx::ScaleSize(gfx::Size(source_bitmap.width(),
source_bitmap.height()),
ui::GetScaleForScaleFactor(desired_scale_factor) /
ui::GetScaleForScaleFactor(source_scale_factor)));
SkBitmap scaled_bitmap;
scaled_bitmap.allocN32Pixels(scaled_size.width(), scaled_size.height());
scaled_bitmap.eraseARGB(0, 0, 0, 0);
SkCanvas canvas(scaled_bitmap);
SkRect scaled_bounds = RectToSkRect(gfx::Rect(scaled_size));
// Note(oshima): The following scaling code doesn't work with
// a mask image.
canvas.drawBitmapRect(source_bitmap, scaled_bounds);
return scaled_bitmap;
}
// A ImageSkiaSource that scales 100P image to the target scale factor
// if the ImageSkiaRep for the target scale factor isn't available.
class ThemeImageSource: public gfx::ImageSkiaSource {
public:
explicit ThemeImageSource(const gfx::ImageSkia& source) : source_(source) {
}
~ThemeImageSource() override {}
gfx::ImageSkiaRep GetImageForScale(float scale) override {
if (source_.HasRepresentation(scale))
return source_.GetRepresentation(scale);
const gfx::ImageSkiaRep& rep_100p = source_.GetRepresentation(1.0f);
SkBitmap scaled_bitmap = CreateLowQualityResizedBitmap(
rep_100p.sk_bitmap(),
ui::SCALE_FACTOR_100P,
ui::GetSupportedScaleFactor(scale));
return gfx::ImageSkiaRep(scaled_bitmap, scale);
}
private:
const gfx::ImageSkia source_;
DISALLOW_COPY_AND_ASSIGN(ThemeImageSource);
};
// An ImageSkiaSource that delays decoding PNG data into bitmaps until
// needed. Missing data for a scale factor is computed by scaling data for an
// available scale factor. Computed bitmaps are stored for future look up.
class ThemeImagePngSource : public gfx::ImageSkiaSource {
public:
typedef std::map<ui::ScaleFactor,
scoped_refptr<base::RefCountedMemory> > PngMap;
explicit ThemeImagePngSource(const PngMap& png_map) : png_map_(png_map) {}
~ThemeImagePngSource() override {}
private:
gfx::ImageSkiaRep GetImageForScale(float scale) override {
ui::ScaleFactor scale_factor = ui::GetSupportedScaleFactor(scale);
// Look up the bitmap for |scale factor| in the bitmap map. If found
// return it.
BitmapMap::const_iterator exact_bitmap_it = bitmap_map_.find(scale_factor);
if (exact_bitmap_it != bitmap_map_.end())
return gfx::ImageSkiaRep(exact_bitmap_it->second, scale);
// Look up the raw PNG data for |scale_factor| in the png map. If found,
// decode it, store the result in the bitmap map and return it.
PngMap::const_iterator exact_png_it = png_map_.find(scale_factor);
if (exact_png_it != png_map_.end()) {
SkBitmap bitmap;
if (!gfx::PNGCodec::Decode(exact_png_it->second->front(),
exact_png_it->second->size(),
&bitmap)) {
NOTREACHED();
return gfx::ImageSkiaRep();
}
bitmap_map_[scale_factor] = bitmap;
return gfx::ImageSkiaRep(bitmap, scale);
}
// Find an available PNG for another scale factor. We want to use the
// highest available scale factor.
PngMap::const_iterator available_png_it = png_map_.end();
for (PngMap::const_iterator png_it = png_map_.begin();
png_it != png_map_.end(); ++png_it) {
if (available_png_it == png_map_.end() ||
ui::GetScaleForScaleFactor(png_it->first) >
ui::GetScaleForScaleFactor(available_png_it->first)) {
available_png_it = png_it;
}
}
if (available_png_it == png_map_.end())
return gfx::ImageSkiaRep();
ui::ScaleFactor available_scale_factor = available_png_it->first;
// Look up the bitmap for |available_scale_factor| in the bitmap map.
// If not found, decode the corresponging png data, store the result
// in the bitmap map.
BitmapMap::const_iterator available_bitmap_it =
bitmap_map_.find(available_scale_factor);
if (available_bitmap_it == bitmap_map_.end()) {
SkBitmap available_bitmap;
if (!gfx::PNGCodec::Decode(available_png_it->second->front(),
available_png_it->second->size(),
&available_bitmap)) {
NOTREACHED();
return gfx::ImageSkiaRep();
}
bitmap_map_[available_scale_factor] = available_bitmap;
available_bitmap_it = bitmap_map_.find(available_scale_factor);
}
// Scale the available bitmap to the desired scale factor, store the result
// in the bitmap map and return it.
SkBitmap scaled_bitmap = CreateLowQualityResizedBitmap(
available_bitmap_it->second,
available_scale_factor,
scale_factor);
bitmap_map_[scale_factor] = scaled_bitmap;
return gfx::ImageSkiaRep(scaled_bitmap, scale);
}
PngMap png_map_;
typedef std::map<ui::ScaleFactor, SkBitmap> BitmapMap;
BitmapMap bitmap_map_;
DISALLOW_COPY_AND_ASSIGN(ThemeImagePngSource);
};
class TabBackgroundImageSource: public gfx::CanvasImageSource {
public:
TabBackgroundImageSource(const gfx::ImageSkia& image_to_tint,
const gfx::ImageSkia& overlay,
const color_utils::HSL& hsl_shift,
int vertical_offset)
: gfx::CanvasImageSource(image_to_tint.size(), false),
image_to_tint_(image_to_tint),
overlay_(overlay),
hsl_shift_(hsl_shift),
vertical_offset_(vertical_offset) {
}
~TabBackgroundImageSource() override {}
// Overridden from CanvasImageSource:
void Draw(gfx::Canvas* canvas) override {
gfx::ImageSkia bg_tint =
gfx::ImageSkiaOperations::CreateHSLShiftedImage(image_to_tint_,
hsl_shift_);
canvas->TileImageInt(bg_tint, 0, vertical_offset_, 0, 0,
size().width(), size().height());
// If they've provided a custom image, overlay it.
if (!overlay_.isNull()) {
canvas->TileImageInt(overlay_, 0, 0, size().width(),
overlay_.height());
}
}
private:
const gfx::ImageSkia image_to_tint_;
const gfx::ImageSkia overlay_;
const color_utils::HSL hsl_shift_;
const int vertical_offset_;
DISALLOW_COPY_AND_ASSIGN(TabBackgroundImageSource);
};
} // namespace
BrowserThemePack::~BrowserThemePack() {
if (!data_pack_.get()) {
delete header_;
delete [] tints_;
delete [] colors_;
delete [] display_properties_;
delete [] source_images_;
}
}
// static
scoped_refptr<BrowserThemePack> BrowserThemePack::BuildFromExtension(
const Extension* extension) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(extension);
DCHECK(extension->is_theme());
scoped_refptr<BrowserThemePack> pack(new BrowserThemePack);
pack->BuildHeader(extension);
pack->BuildTintsFromJSON(extensions::ThemeInfo::GetTints(extension));
pack->BuildColorsFromJSON(extensions::ThemeInfo::GetColors(extension));
pack->BuildDisplayPropertiesFromJSON(
extensions::ThemeInfo::GetDisplayProperties(extension));
// Builds the images. (Image building is dependent on tints).
FilePathMap file_paths;
pack->ParseImageNamesFromJSON(
extensions::ThemeInfo::GetImages(extension),
extension->path(),
&file_paths);
pack->BuildSourceImagesArray(file_paths);
if (!pack->LoadRawBitmapsTo(file_paths, &pack->images_on_ui_thread_))
return NULL;
pack->CreateImages(&pack->images_on_ui_thread_);
// Make sure the |images_on_file_thread_| has bitmaps for supported
// scale factors before passing to FILE thread.
pack->images_on_file_thread_ = pack->images_on_ui_thread_;
for (ImageCache::iterator it = pack->images_on_file_thread_.begin();
it != pack->images_on_file_thread_.end(); ++it) {
gfx::ImageSkia* image_skia =
const_cast<gfx::ImageSkia*>(it->second.ToImageSkia());
image_skia->MakeThreadSafe();
}
// Set ThemeImageSource on |images_on_ui_thread_| to resample the source
// image if a caller of BrowserThemePack::GetImageNamed() requests an
// ImageSkiaRep for a scale factor not specified by the theme author.
// Callers of BrowserThemePack::GetImageNamed() to be able to retrieve
// ImageSkiaReps for all supported scale factors.
for (ImageCache::iterator it = pack->images_on_ui_thread_.begin();
it != pack->images_on_ui_thread_.end(); ++it) {
const gfx::ImageSkia source_image_skia = it->second.AsImageSkia();
ThemeImageSource* source = new ThemeImageSource(source_image_skia);
// image_skia takes ownership of source.
gfx::ImageSkia image_skia(source, source_image_skia.size());
it->second = gfx::Image(image_skia);
}
// Generate raw images (for new-tab-page attribution and background) for
// any missing scale from an available scale image.
for (size_t i = 0; i < arraysize(kPreloadIDs); ++i) {
pack->GenerateRawImageForAllSupportedScales(kPreloadIDs[i]);
}
// The BrowserThemePack is now in a consistent state.
return pack;
}
// static
scoped_refptr<BrowserThemePack> BrowserThemePack::BuildFromDataPack(
const base::FilePath& path, const std::string& expected_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// Allow IO on UI thread due to deep-seated theme design issues.
// (see http://crbug.com/80206)
base::ThreadRestrictions::ScopedAllowIO allow_io;
scoped_refptr<BrowserThemePack> pack(new BrowserThemePack);
// Scale factor parameter is moot as data pack has image resources for all
// supported scale factors.
pack->data_pack_.reset(
new ui::DataPack(ui::SCALE_FACTOR_NONE));
if (!pack->data_pack_->LoadFromPath(path)) {
LOG(ERROR) << "Failed to load theme data pack.";
return NULL;
}
base::StringPiece pointer;
if (!pack->data_pack_->GetStringPiece(kHeaderID, &pointer))
return NULL;
pack->header_ = reinterpret_cast<BrowserThemePackHeader*>(const_cast<char*>(
pointer.data()));
if (pack->header_->version != kThemePackVersion) {
DLOG(ERROR) << "BuildFromDataPack failure! Version mismatch!";
return NULL;
}
// TODO(erg): Check endianess once DataPack works on the other endian.
std::string theme_id(reinterpret_cast<char*>(pack->header_->theme_id),
crx_file::id_util::kIdSize);
std::string truncated_id = expected_id.substr(0, crx_file::id_util::kIdSize);
if (theme_id != truncated_id) {
DLOG(ERROR) << "Wrong id: " << theme_id << " vs " << expected_id;
return NULL;
}
if (!pack->data_pack_->GetStringPiece(kTintsID, &pointer))
return NULL;
pack->tints_ = reinterpret_cast<TintEntry*>(const_cast<char*>(
pointer.data()));
if (!pack->data_pack_->GetStringPiece(kColorsID, &pointer))
return NULL;
pack->colors_ =
reinterpret_cast<ColorPair*>(const_cast<char*>(pointer.data()));
if (!pack->data_pack_->GetStringPiece(kDisplayPropertiesID, &pointer))
return NULL;
pack->display_properties_ = reinterpret_cast<DisplayPropertyPair*>(
const_cast<char*>(pointer.data()));
if (!pack->data_pack_->GetStringPiece(kSourceImagesID, &pointer))
return NULL;
pack->source_images_ = reinterpret_cast<int*>(
const_cast<char*>(pointer.data()));
if (!pack->data_pack_->GetStringPiece(kScaleFactorsID, &pointer))
return NULL;
if (!InputScalesValid(pointer, pack->scale_factors_)) {
DLOG(ERROR) << "BuildFromDataPack failure! The pack scale factors differ "
<< "from those supported by platform.";
return NULL;
}
return pack;
}
// static
bool BrowserThemePack::IsPersistentImageID(int id) {
for (size_t i = 0; i < kPersistingImagesLength; ++i)
if (kPersistingImages[i].idr_id == id)
return true;
#if defined(USE_ASH) && !defined(OS_CHROMEOS)
for (size_t i = 0; i < kPersistingImagesDesktopAuraLength; ++i)
if (kPersistingImagesDesktopAura[i].idr_id == id)
return true;
#endif
return false;
}
bool BrowserThemePack::WriteToDisk(const base::FilePath& path) const {
// Add resources for each of the property arrays.
RawDataForWriting resources;
resources[kHeaderID] = base::StringPiece(
reinterpret_cast<const char*>(header_), sizeof(BrowserThemePackHeader));
resources[kTintsID] = base::StringPiece(
reinterpret_cast<const char*>(tints_),
sizeof(TintEntry[kTintTableLength]));
resources[kColorsID] = base::StringPiece(
reinterpret_cast<const char*>(colors_),
sizeof(ColorPair[kColorTableLength]));
resources[kDisplayPropertiesID] = base::StringPiece(
reinterpret_cast<const char*>(display_properties_),
sizeof(DisplayPropertyPair[kDisplayPropertiesSize]));
int source_count = 1;
int* end = source_images_;
for (; *end != -1 ; end++)
source_count++;
resources[kSourceImagesID] = base::StringPiece(
reinterpret_cast<const char*>(source_images_),
source_count * sizeof(*source_images_));
// Store results of GetScaleFactorsAsString() in std::string as
// base::StringPiece does not copy data in constructor.
std::string scale_factors_string = GetScaleFactorsAsString(scale_factors_);
resources[kScaleFactorsID] = scale_factors_string;
AddRawImagesTo(image_memory_, &resources);
RawImages reencoded_images;
RepackImages(images_on_file_thread_, &reencoded_images);
AddRawImagesTo(reencoded_images, &resources);
return ui::DataPack::WritePack(path, resources, ui::DataPack::BINARY);
}
bool BrowserThemePack::GetTint(int id, color_utils::HSL* hsl) const {
if (tints_) {
for (size_t i = 0; i < kTintTableLength; ++i) {
if (tints_[i].id == id) {
hsl->h = tints_[i].h;
hsl->s = tints_[i].s;
hsl->l = tints_[i].l;
return true;
}
}
}
return false;
}
bool BrowserThemePack::GetColor(int id, SkColor* color) const {
if (colors_) {
for (size_t i = 0; i < kColorTableLength; ++i) {
if (colors_[i].id == id) {
*color = colors_[i].color;
return true;
}
}
}
return false;
}
bool BrowserThemePack::GetDisplayProperty(int id, int* result) const {
if (display_properties_) {
for (size_t i = 0; i < kDisplayPropertiesSize; ++i) {
if (display_properties_[i].id == id) {
*result = display_properties_[i].property;
return true;
}
}
}
return false;
}
gfx::Image BrowserThemePack::GetImageNamed(int idr_id) {
int prs_id = GetPersistentIDByIDR(idr_id);
if (prs_id == -1)
return gfx::Image();
// Check if the image is cached.
ImageCache::const_iterator image_iter = images_on_ui_thread_.find(prs_id);
if (image_iter != images_on_ui_thread_.end())
return image_iter->second;
ThemeImagePngSource::PngMap png_map;
for (size_t i = 0; i < scale_factors_.size(); ++i) {
scoped_refptr<base::RefCountedMemory> memory =
GetRawData(idr_id, scale_factors_[i]);
if (memory.get())
png_map[scale_factors_[i]] = memory;
}
if (!png_map.empty()) {
gfx::ImageSkia image_skia(new ThemeImagePngSource(png_map), 1.0f);
// |image_skia| takes ownership of ThemeImagePngSource.
gfx::Image ret = gfx::Image(image_skia);
images_on_ui_thread_[prs_id] = ret;
return ret;
}
return gfx::Image();
}
base::RefCountedMemory* BrowserThemePack::GetRawData(
int idr_id,
ui::ScaleFactor scale_factor) const {
base::RefCountedMemory* memory = NULL;
int prs_id = GetPersistentIDByIDR(idr_id);
int raw_id = GetRawIDByPersistentID(prs_id, scale_factor);
if (raw_id != -1) {
if (data_pack_.get()) {
memory = data_pack_->GetStaticMemory(raw_id);
} else {
RawImages::const_iterator it = image_memory_.find(raw_id);
if (it != image_memory_.end()) {
memory = it->second.get();
}
}
}
return memory;
}
bool BrowserThemePack::HasCustomImage(int idr_id) const {
int prs_id = GetPersistentIDByIDR(idr_id);
if (prs_id == -1)
return false;
int* img = source_images_;
for (; *img != -1; ++img) {
if (*img == prs_id)
return true;
}
return false;
}
// private:
BrowserThemePack::BrowserThemePack()
: CustomThemeSupplier(EXTENSION),
header_(NULL),
tints_(NULL),
colors_(NULL),
display_properties_(NULL),
source_images_(NULL) {
scale_factors_ = ui::GetSupportedScaleFactors();
// On Windows HiDPI SCALE_FACTOR_100P may not be supported by default.
if (std::find(scale_factors_.begin(), scale_factors_.end(),
ui::SCALE_FACTOR_100P) == scale_factors_.end()) {
scale_factors_.push_back(ui::SCALE_FACTOR_100P);
}
}
void BrowserThemePack::BuildHeader(const Extension* extension) {
header_ = new BrowserThemePackHeader;
header_->version = kThemePackVersion;
// TODO(erg): Need to make this endian safe on other computers. Prerequisite
// is that ui::DataPack removes this same check.
#if defined(__BYTE_ORDER)
// Linux check
static_assert(__BYTE_ORDER == __LITTLE_ENDIAN,
"datapack assumes little endian");
#elif defined(__BIG_ENDIAN__)
// Mac check
#error DataPack assumes little endian
#endif
header_->little_endian = 1;
const std::string& id = extension->id();
memcpy(header_->theme_id, id.c_str(), crx_file::id_util::kIdSize);
}
void BrowserThemePack::BuildTintsFromJSON(
const base::DictionaryValue* tints_value) {
tints_ = new TintEntry[kTintTableLength];
for (size_t i = 0; i < kTintTableLength; ++i) {
tints_[i].id = -1;
tints_[i].h = -1;
tints_[i].s = -1;
tints_[i].l = -1;
}
if (!tints_value)
return;
// Parse the incoming data from |tints_value| into an intermediary structure.
std::map<int, color_utils::HSL> temp_tints;
for (base::DictionaryValue::Iterator iter(*tints_value); !iter.IsAtEnd();
iter.Advance()) {
const base::ListValue* tint_list;
if (iter.value().GetAsList(&tint_list) &&
(tint_list->GetSize() == 3)) {
color_utils::HSL hsl = { -1, -1, -1 };
if (tint_list->GetDouble(0, &hsl.h) &&
tint_list->GetDouble(1, &hsl.s) &&
tint_list->GetDouble(2, &hsl.l)) {
MakeHSLShiftValid(&hsl);
int id = GetIntForString(iter.key(), kTintTable, kTintTableLength);
if (id != -1) {
temp_tints[id] = hsl;
}
}
}
}
// Copy data from the intermediary data structure to the array.
size_t count = 0;
for (std::map<int, color_utils::HSL>::const_iterator it =
temp_tints.begin();
it != temp_tints.end() && count < kTintTableLength;
++it, ++count) {
tints_[count].id = it->first;
tints_[count].h = it->second.h;
tints_[count].s = it->second.s;
tints_[count].l = it->second.l;
}
}
void BrowserThemePack::BuildColorsFromJSON(
const base::DictionaryValue* colors_value) {
colors_ = new ColorPair[kColorTableLength];
for (size_t i = 0; i < kColorTableLength; ++i) {
colors_[i].id = -1;
colors_[i].color = SkColorSetRGB(0, 0, 0);
}
std::map<int, SkColor> temp_colors;
if (colors_value)
ReadColorsFromJSON(colors_value, &temp_colors);
GenerateMissingColors(&temp_colors);
// Copy data from the intermediary data structure to the array.
size_t count = 0;
for (std::map<int, SkColor>::const_iterator it = temp_colors.begin();
it != temp_colors.end() && count < kColorTableLength; ++it, ++count) {
colors_[count].id = it->first;
colors_[count].color = it->second;
}
}
void BrowserThemePack::ReadColorsFromJSON(
const base::DictionaryValue* colors_value,
std::map<int, SkColor>* temp_colors) {
// Parse the incoming data from |colors_value| into an intermediary structure.
for (base::DictionaryValue::Iterator iter(*colors_value); !iter.IsAtEnd();
iter.Advance()) {
const base::ListValue* color_list;
if (iter.value().GetAsList(&color_list) &&
((color_list->GetSize() == 3) || (color_list->GetSize() == 4))) {
SkColor color = SK_ColorWHITE;
int r, g, b;
if (color_list->GetInteger(0, &r) &&
color_list->GetInteger(1, &g) &&
color_list->GetInteger(2, &b)) {
if (color_list->GetSize() == 4) {
double alpha;
int alpha_int;
if (color_list->GetDouble(3, &alpha)) {
color = SkColorSetARGB(static_cast<int>(alpha * 255), r, g, b);
} else if (color_list->GetInteger(3, &alpha_int) &&
(alpha_int == 0 || alpha_int == 1)) {
color = SkColorSetARGB(alpha_int ? 255 : 0, r, g, b);
} else {
// Invalid entry for part 4.
continue;
}
} else {
color = SkColorSetRGB(r, g, b);
}
int id = GetIntForString(iter.key(), kColorTable, kColorTableLength);
if (id != -1) {
(*temp_colors)[id] = color;
}
}
}
}
}
void BrowserThemePack::GenerateMissingColors(
std::map<int, SkColor>* colors) {
// Generate link colors, if missing. (See GetColor()).
if (!colors->count(ThemeProperties::COLOR_NTP_HEADER) &&
colors->count(ThemeProperties::COLOR_NTP_SECTION)) {
(*colors)[ThemeProperties::COLOR_NTP_HEADER] =
(*colors)[ThemeProperties::COLOR_NTP_SECTION];
}
if (!colors->count(ThemeProperties::COLOR_NTP_SECTION_LINK_UNDERLINE) &&
colors->count(ThemeProperties::COLOR_NTP_SECTION_LINK)) {
SkColor color_section_link =
(*colors)[ThemeProperties::COLOR_NTP_SECTION_LINK];
(*colors)[ThemeProperties::COLOR_NTP_SECTION_LINK_UNDERLINE] =
SkColorSetA(color_section_link, SkColorGetA(color_section_link) / 3);
}
if (!colors->count(ThemeProperties::COLOR_NTP_LINK_UNDERLINE) &&
colors->count(ThemeProperties::COLOR_NTP_LINK)) {
SkColor color_link = (*colors)[ThemeProperties::COLOR_NTP_LINK];
(*colors)[ThemeProperties::COLOR_NTP_LINK_UNDERLINE] =
SkColorSetA(color_link, SkColorGetA(color_link) / 3);
}
// Generate frame colors, if missing. (See GenerateFrameColors()).
SkColor frame;
std::map<int, SkColor>::const_iterator it =
colors->find(ThemeProperties::COLOR_FRAME);
if (it != colors->end()) {
frame = it->second;
} else {
frame = ThemeProperties::GetDefaultColor(
ThemeProperties::COLOR_FRAME);
}
if (!colors->count(ThemeProperties::COLOR_FRAME)) {
(*colors)[ThemeProperties::COLOR_FRAME] =
HSLShift(frame, GetTintInternal(ThemeProperties::TINT_FRAME));
}
if (!colors->count(ThemeProperties::COLOR_FRAME_INACTIVE)) {
(*colors)[ThemeProperties::COLOR_FRAME_INACTIVE] =
HSLShift(frame, GetTintInternal(
ThemeProperties::TINT_FRAME_INACTIVE));
}
if (!colors->count(ThemeProperties::COLOR_FRAME_INCOGNITO)) {
(*colors)[ThemeProperties::COLOR_FRAME_INCOGNITO] =
HSLShift(frame, GetTintInternal(
ThemeProperties::TINT_FRAME_INCOGNITO));
}
if (!colors->count(ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE)) {
(*colors)[ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE] =
HSLShift(frame, GetTintInternal(
ThemeProperties::TINT_FRAME_INCOGNITO_INACTIVE));
}
}
void BrowserThemePack::BuildDisplayPropertiesFromJSON(
const base::DictionaryValue* display_properties_value) {
display_properties_ = new DisplayPropertyPair[kDisplayPropertiesSize];
for (size_t i = 0; i < kDisplayPropertiesSize; ++i) {
display_properties_[i].id = -1;
display_properties_[i].property = 0;
}
if (!display_properties_value)
return;
std::map<int, int> temp_properties;
for (base::DictionaryValue::Iterator iter(*display_properties_value);
!iter.IsAtEnd(); iter.Advance()) {
int property_id = GetIntForString(iter.key(), kDisplayProperties,
kDisplayPropertiesSize);
switch (property_id) {
case ThemeProperties::NTP_BACKGROUND_ALIGNMENT: {
std::string val;
if (iter.value().GetAsString(&val)) {
temp_properties[ThemeProperties::NTP_BACKGROUND_ALIGNMENT] =
ThemeProperties::StringToAlignment(val);
}
break;
}
case ThemeProperties::NTP_BACKGROUND_TILING: {
std::string val;
if (iter.value().GetAsString(&val)) {
temp_properties[ThemeProperties::NTP_BACKGROUND_TILING] =
ThemeProperties::StringToTiling(val);
}
break;
}
case ThemeProperties::NTP_LOGO_ALTERNATE: {
int val = 0;
if (iter.value().GetAsInteger(&val))
temp_properties[ThemeProperties::NTP_LOGO_ALTERNATE] = val;
break;
}
}
}
// Copy data from the intermediary data structure to the array.
size_t count = 0;
for (std::map<int, int>::const_iterator it = temp_properties.begin();
it != temp_properties.end() && count < kDisplayPropertiesSize;
++it, ++count) {
display_properties_[count].id = it->first;
display_properties_[count].property = it->second;
}
}
void BrowserThemePack::ParseImageNamesFromJSON(
const base::DictionaryValue* images_value,
const base::FilePath& images_path,
FilePathMap* file_paths) const {
if (!images_value)
return;
for (base::DictionaryValue::Iterator iter(*images_value); !iter.IsAtEnd();
iter.Advance()) {
if (iter.value().IsType(base::Value::TYPE_DICTIONARY)) {
const base::DictionaryValue* inner_value = NULL;
if (iter.value().GetAsDictionary(&inner_value)) {
for (base::DictionaryValue::Iterator inner_iter(*inner_value);
!inner_iter.IsAtEnd();
inner_iter.Advance()) {
std::string name;
ui::ScaleFactor scale_factor = ui::SCALE_FACTOR_NONE;
if (GetScaleFactorFromManifestKey(inner_iter.key(), &scale_factor) &&
inner_iter.value().IsType(base::Value::TYPE_STRING) &&
inner_iter.value().GetAsString(&name)) {
AddFileAtScaleToMap(iter.key(),
scale_factor,
images_path.AppendASCII(name),
file_paths);
}
}
}
} else if (iter.value().IsType(base::Value::TYPE_STRING)) {
std::string name;
if (iter.value().GetAsString(&name)) {
AddFileAtScaleToMap(iter.key(),
ui::SCALE_FACTOR_100P,
images_path.AppendASCII(name),
file_paths);
}
}
}
}
void BrowserThemePack::AddFileAtScaleToMap(const std::string& image_name,
ui::ScaleFactor scale_factor,
const base::FilePath& image_path,
FilePathMap* file_paths) const {
int id = GetPersistentIDByName(image_name);
if (id != -1)
(*file_paths)[id][scale_factor] = image_path;
#if defined(USE_ASH) && !defined(OS_CHROMEOS)
id = GetPersistentIDByNameHelper(image_name,
kPersistingImagesDesktopAura,
kPersistingImagesDesktopAuraLength);
if (id != -1)
(*file_paths)[id][scale_factor] = image_path;
#endif
}
void BrowserThemePack::BuildSourceImagesArray(const FilePathMap& file_paths) {
std::vector<int> ids;
for (FilePathMap::const_iterator it = file_paths.begin();
it != file_paths.end(); ++it) {
ids.push_back(it->first);
}
source_images_ = new int[ids.size() + 1];
std::copy(ids.begin(), ids.end(), source_images_);
source_images_[ids.size()] = -1;
}
bool BrowserThemePack::LoadRawBitmapsTo(
const FilePathMap& file_paths,
ImageCache* image_cache) {
// Themes should be loaded on the file thread, not the UI thread.
// http://crbug.com/61838
base::ThreadRestrictions::ScopedAllowIO allow_io;
for (FilePathMap::const_iterator it = file_paths.begin();
it != file_paths.end(); ++it) {
int prs_id = it->first;
// Some images need to go directly into |image_memory_|. No modification is
// necessary or desirable.
bool is_copyable = false;
for (size_t i = 0; i < arraysize(kPreloadIDs); ++i) {
if (kPreloadIDs[i] == prs_id) {
is_copyable = true;
break;
}
}
gfx::ImageSkia image_skia;
for (int pass = 0; pass < 2; ++pass) {
// Two passes: In the first pass, we process only scale factor
// 100% and in the second pass all other scale factors. We
// process scale factor 100% first because the first image added
// in image_skia.AddRepresentation() determines the DIP size for
// all representations.
for (ScaleFactorToFileMap::const_iterator s2f = it->second.begin();
s2f != it->second.end(); ++s2f) {
ui::ScaleFactor scale_factor = s2f->first;
if ((pass == 0 && scale_factor != ui::SCALE_FACTOR_100P) ||
(pass == 1 && scale_factor == ui::SCALE_FACTOR_100P)) {
continue;
}
scoped_refptr<base::RefCountedMemory> raw_data(
ReadFileData(s2f->second));
if (!raw_data.get() || !raw_data->size()) {
LOG(ERROR) << "Could not load theme image"
<< " prs_id=" << prs_id
<< " scale_factor_enum=" << scale_factor
<< " file=" << s2f->second.value()
<< (raw_data.get() ? " (zero size)" : " (read error)");
return false;
}
if (is_copyable) {
int raw_id = GetRawIDByPersistentID(prs_id, scale_factor);
image_memory_[raw_id] = raw_data;
} else {
SkBitmap bitmap;
if (gfx::PNGCodec::Decode(raw_data->front(), raw_data->size(),
&bitmap)) {
image_skia.AddRepresentation(
gfx::ImageSkiaRep(bitmap,
ui::GetScaleForScaleFactor(scale_factor)));
} else {
NOTREACHED() << "Unable to decode theme image resource "
<< it->first;
}
}
}
}
if (!is_copyable && !image_skia.isNull())
(*image_cache)[prs_id] = gfx::Image(image_skia);
}
return true;
}
void BrowserThemePack::CreateImages(ImageCache* images) const {
CropImages(images);
CreateFrameImages(images);
CreateTintedButtons(GetTintInternal(ThemeProperties::TINT_BUTTONS), images);
CreateTabBackgroundImages(images);
}
void BrowserThemePack::CropImages(ImageCache* images) const {
bool has_frame_border = HasFrameBorder();
for (size_t i = 0; i < arraysize(kImagesToCrop); ++i) {
if (has_frame_border && kImagesToCrop[i].skip_if_frame_border)
continue;
int prs_id = kImagesToCrop[i].prs_id;
ImageCache::iterator it = images->find(prs_id);
if (it == images->end())
continue;
int crop_height = kImagesToCrop[i].max_height;
gfx::ImageSkia image_skia = it->second.AsImageSkia();
(*images)[prs_id] = gfx::Image(gfx::ImageSkiaOperations::ExtractSubset(
image_skia, gfx::Rect(0, 0, image_skia.width(), crop_height)));
}
}
void BrowserThemePack::CreateFrameImages(ImageCache* images) const {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
// Create all the output images in a separate cache and move them back into
// the input images because there can be name collisions.
ImageCache temp_output;
for (size_t i = 0; i < arraysize(kFrameTintMap); ++i) {
int prs_id = kFrameTintMap[i].key;
gfx::Image frame;
// If there's no frame image provided for the specified id, then load
// the default provided frame. If that's not provided, skip this whole
// thing and just use the default images.
int prs_base_id = 0;
#if defined(USE_ASH) && !defined(OS_CHROMEOS)
if (prs_id == PRS_THEME_FRAME_INCOGNITO_INACTIVE_DESKTOP) {
prs_base_id = images->count(PRS_THEME_FRAME_INCOGNITO_DESKTOP) ?
PRS_THEME_FRAME_INCOGNITO_DESKTOP : PRS_THEME_FRAME_DESKTOP;
} else if (prs_id == PRS_THEME_FRAME_INACTIVE_DESKTOP) {
prs_base_id = PRS_THEME_FRAME_DESKTOP;
} else if (prs_id == PRS_THEME_FRAME_INCOGNITO_DESKTOP &&
!images->count(PRS_THEME_FRAME_INCOGNITO_DESKTOP)) {
prs_base_id = PRS_THEME_FRAME_DESKTOP;
}
#endif
if (!prs_base_id) {
if (prs_id == PRS_THEME_FRAME_INCOGNITO_INACTIVE) {
prs_base_id = images->count(PRS_THEME_FRAME_INCOGNITO) ?
PRS_THEME_FRAME_INCOGNITO : PRS_THEME_FRAME;
} else if (prs_id == PRS_THEME_FRAME_OVERLAY_INACTIVE) {
prs_base_id = PRS_THEME_FRAME_OVERLAY;
} else if (prs_id == PRS_THEME_FRAME_INACTIVE) {
prs_base_id = PRS_THEME_FRAME;
} else if (prs_id == PRS_THEME_FRAME_INCOGNITO &&
!images->count(PRS_THEME_FRAME_INCOGNITO)) {
prs_base_id = PRS_THEME_FRAME;
} else {
prs_base_id = prs_id;
}
}
if (images->count(prs_id)) {
frame = (*images)[prs_id];
} else if (prs_base_id != prs_id && images->count(prs_base_id)) {
frame = (*images)[prs_base_id];
} else if (prs_base_id == PRS_THEME_FRAME_OVERLAY) {
#if defined(USE_ASH) && !defined(OS_CHROMEOS)
if (images->count(PRS_THEME_FRAME_DESKTOP)) {
#else
if (images->count(PRS_THEME_FRAME)) {
#endif
// If there is no theme overlay, don't tint the default frame,
// because it will overwrite the custom frame image when we cache and
// reload from disk.
frame = gfx::Image();
}
} else {
// If the theme doesn't specify an image, then apply the tint to
// the default frame.
frame = rb.GetImageNamed(IDR_THEME_FRAME);
#if defined(USE_ASH) && !defined(OS_CHROMEOS)
if (prs_id >= PRS_THEME_FRAME_DESKTOP &&
prs_id <= PRS_THEME_FRAME_INCOGNITO_INACTIVE_DESKTOP) {
frame = rb.GetImageNamed(IDR_THEME_FRAME_DESKTOP);
}
#endif
}
if (!frame.IsEmpty()) {
temp_output[prs_id] = CreateHSLShiftedImage(
frame, GetTintInternal(kFrameTintMap[i].value));
}
}
MergeImageCaches(temp_output, images);
}
void BrowserThemePack::CreateTintedButtons(
const color_utils::HSL& button_tint,
ImageCache* processed_images) const {
if (button_tint.h != -1 || button_tint.s != -1 || button_tint.l != -1) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
const std::set<int>& idr_ids =
ThemeProperties::GetTintableToolbarButtons();
for (std::set<int>::const_iterator it = idr_ids.begin();
it != idr_ids.end(); ++it) {
int prs_id = GetPersistentIDByIDR(*it);
DCHECK(prs_id > 0);
// Fetch the image by IDR...
gfx::Image& button = rb.GetImageNamed(*it);
// but save a version with the persistent ID.
(*processed_images)[prs_id] =
CreateHSLShiftedImage(button, button_tint);
}
}
}
void BrowserThemePack::CreateTabBackgroundImages(ImageCache* images) const {
ImageCache temp_output;
for (size_t i = 0; i < arraysize(kTabBackgroundMap); ++i) {
int prs_id = kTabBackgroundMap[i].key;
int prs_base_id = kTabBackgroundMap[i].value;
// We only need to generate the background tab images if we were provided
// with a PRS_THEME_FRAME.
ImageCache::const_iterator it = images->find(prs_base_id);
if (it != images->end()) {
gfx::ImageSkia image_to_tint = (it->second).AsImageSkia();
color_utils::HSL hsl_shift = GetTintInternal(
ThemeProperties::TINT_BACKGROUND_TAB);
int vertical_offset = images->count(prs_id)
? kRestoredTabVerticalOffset : 0;
gfx::ImageSkia overlay;
ImageCache::const_iterator overlay_it = images->find(prs_id);
if (overlay_it != images->end())
overlay = overlay_it->second.AsImageSkia();
gfx::ImageSkiaSource* source = new TabBackgroundImageSource(
image_to_tint, overlay, hsl_shift, vertical_offset);
// ImageSkia takes ownership of |source|.
temp_output[prs_id] = gfx::Image(gfx::ImageSkia(source,
image_to_tint.size()));
}
}
MergeImageCaches(temp_output, images);
}
void BrowserThemePack::RepackImages(const ImageCache& images,
RawImages* reencoded_images) const {
for (ImageCache::const_iterator it = images.begin();
it != images.end(); ++it) {
gfx::ImageSkia image_skia = *it->second.ToImageSkia();
typedef std::vector<gfx::ImageSkiaRep> ImageSkiaReps;
ImageSkiaReps image_reps = image_skia.image_reps();
if (image_reps.empty()) {
NOTREACHED() << "No image reps for resource " << it->first << ".";
}
for (ImageSkiaReps::iterator rep_it = image_reps.begin();
rep_it != image_reps.end(); ++rep_it) {
std::vector<unsigned char> bitmap_data;
if (!gfx::PNGCodec::EncodeBGRASkBitmap(rep_it->sk_bitmap(), false,
&bitmap_data)) {
NOTREACHED() << "Image file for resource " << it->first
<< " could not be encoded.";
}
int raw_id = GetRawIDByPersistentID(
it->first,
ui::GetSupportedScaleFactor(rep_it->scale()));
(*reencoded_images)[raw_id] =
base::RefCountedBytes::TakeVector(&bitmap_data);
}
}
}
void BrowserThemePack::MergeImageCaches(
const ImageCache& source, ImageCache* destination) const {
for (ImageCache::const_iterator it = source.begin(); it != source.end();
++it) {
(*destination)[it->first] = it->second;
}
}
void BrowserThemePack::AddRawImagesTo(const RawImages& images,
RawDataForWriting* out) const {
for (RawImages::const_iterator it = images.begin(); it != images.end();
++it) {
(*out)[it->first] = base::StringPiece(
it->second->front_as<char>(), it->second->size());
}
}
color_utils::HSL BrowserThemePack::GetTintInternal(int id) const {
if (tints_) {
for (size_t i = 0; i < kTintTableLength; ++i) {
if (tints_[i].id == id) {
color_utils::HSL hsl;
hsl.h = tints_[i].h;
hsl.s = tints_[i].s;
hsl.l = tints_[i].l;
return hsl;
}
}
}
return ThemeProperties::GetDefaultTint(id);
}
int BrowserThemePack::GetRawIDByPersistentID(
int prs_id,
ui::ScaleFactor scale_factor) const {
if (prs_id < 0)
return -1;
for (size_t i = 0; i < scale_factors_.size(); ++i) {
if (scale_factors_[i] == scale_factor)
return ((GetMaxPersistentId() + 1) * i) + prs_id;
}
return -1;
}
bool BrowserThemePack::GetScaleFactorFromManifestKey(
const std::string& key,
ui::ScaleFactor* scale_factor) const {
int percent = 0;
if (base::StringToInt(key, &percent)) {
float scale = static_cast<float>(percent) / 100.0f;
for (size_t i = 0; i < scale_factors_.size(); ++i) {
if (fabs(ui::GetScaleForScaleFactor(scale_factors_[i]) - scale)
< 0.001) {
*scale_factor = scale_factors_[i];
return true;
}
}
}
return false;
}
void BrowserThemePack::GenerateRawImageForAllSupportedScales(int prs_id) {
// Compute (by scaling) bitmaps for |prs_id| for any scale factors
// for which the theme author did not provide a bitmap. We compute
// the bitmaps using the highest scale factor that theme author
// provided.
// Note: We use only supported scale factors. For example, if scale
// factor 2x is supported by the current system, but 1.8x is not and
// if the theme author did not provide an image for 2x but one for
// 1.8x, we will not use the 1.8x image here. Here we will only use
// images provided for scale factors supported by the current system.
// See if any image is missing. If not, we're done.
bool image_missing = false;
for (size_t i = 0; i < scale_factors_.size(); ++i) {
int raw_id = GetRawIDByPersistentID(prs_id, scale_factors_[i]);
if (image_memory_.find(raw_id) == image_memory_.end()) {
image_missing = true;
break;
}
}
if (!image_missing)
return;
// Find available scale factor with highest scale.
ui::ScaleFactor available_scale_factor = ui::SCALE_FACTOR_NONE;
for (size_t i = 0; i < scale_factors_.size(); ++i) {
int raw_id = GetRawIDByPersistentID(prs_id, scale_factors_[i]);
if ((available_scale_factor == ui::SCALE_FACTOR_NONE ||
(ui::GetScaleForScaleFactor(scale_factors_[i]) >
ui::GetScaleForScaleFactor(available_scale_factor))) &&
image_memory_.find(raw_id) != image_memory_.end()) {
available_scale_factor = scale_factors_[i];
}
}
// If no scale factor is available, we're done.
if (available_scale_factor == ui::SCALE_FACTOR_NONE)
return;
// Get bitmap for the available scale factor.
int available_raw_id = GetRawIDByPersistentID(prs_id, available_scale_factor);
RawImages::const_iterator it = image_memory_.find(available_raw_id);
SkBitmap available_bitmap;
if (!gfx::PNGCodec::Decode(it->second->front(),
it->second->size(),
&available_bitmap)) {
NOTREACHED() << "Unable to decode theme image for prs_id="
<< prs_id << " for scale_factor=" << available_scale_factor;
return;
}
// Fill in all missing scale factors by scaling the available bitmap.
for (size_t i = 0; i < scale_factors_.size(); ++i) {
int scaled_raw_id = GetRawIDByPersistentID(prs_id, scale_factors_[i]);
if (image_memory_.find(scaled_raw_id) != image_memory_.end())
continue;
SkBitmap scaled_bitmap =
CreateLowQualityResizedBitmap(available_bitmap,
available_scale_factor,
scale_factors_[i]);
std::vector<unsigned char> bitmap_data;
if (!gfx::PNGCodec::EncodeBGRASkBitmap(scaled_bitmap,
false,
&bitmap_data)) {
NOTREACHED() << "Unable to encode theme image for prs_id="
<< prs_id << " for scale_factor=" << scale_factors_[i];
break;
}
image_memory_[scaled_raw_id] =
base::RefCountedBytes::TakeVector(&bitmap_data);
}
}
|
lihui7115/ChromiumGStreamerBackend
|
chrome/browser/themes/browser_theme_pack.cc
|
C++
|
bsd-3-clause
| 60,466 |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'name')->label('Your name') ?>
<?= $form->field($model, 'email')->label('Your email') ?>
<div class="form-group">
<?= Html::submitButton('?????????', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
|
atecloud/atestat
|
views/site/entry.php
|
PHP
|
bsd-3-clause
| 383 |
#!/usr/bin/ruby
## plugins/openstack.rb - provide helper functions for Rouster objects running on OpenStack/Compute
require sprintf('%s/../%s', File.dirname(File.expand_path(__FILE__)), 'path_helper')
require 'fog'
require 'uri'
class Rouster
attr_reader :nova # expose OpenStack workers
attr_reader :instance_data # the result of the runInstances request
# return a hash containing meta-data items
def ostack_get_instance_id ()
# The instance id is kept in @passthrough[:instance] or
# can be obtained from @instance_data which has all instance
# details.
if ! @instance_data.nil? and ! @instance_data.id.nil?
return @instance_data.id # we already know the id
elsif @passthrough.has_key?(:instance)
return @passthrough[:instance] # we know the id we want
else
@logger.debug(sprintf('unable to determine id from instance_data[%s] or passthrough specification[%s]', @instance_data, @passthrough))
return nil # we don't have an id yet, likely a up() call
end
end
def ostack_up
# wait for machine to transition to running state and become sshable (TODO maybe make the second half optional)
self.ostack_connect
# This will check if instance_id has been provided. If so, it will check on status of the instance.
status = self.status()
if status.eql?('running')
self.passthrough[:instance] = self.ostack_get_instance_id
@logger.debug(sprintf('Connecting to running instance [%s] while calling ostack_up()', self.passthrough[:instance]))
self.connect_ssh_tunnel
else
if @passthrough[:openstack_net_id]
# if the user has set a net id, send it along
server = @nova.servers.create(:name => @name, :flavor_ref => @passthrough[:flavor_ref],
:image_ref => @passthrough[:image_ref], :nics => [{:net_id => @passthrough[:openstack_net_id] }],
:key_name => @passthrough[:keypair], :user_data => @passthrough[:user_data])
else
server = @nova.servers.create(:name => @name, :flavor_ref => @passthrough[:flavor_ref],
:image_ref => @passthrough[:image_ref], :key_name => @passthrough[:keypair], :user_data => @passthrough[:user_data])
end
server.wait_for { ready? }
@instance_data = server
server.addresses.each_key do |address_key|
if defined?(server.addresses[address_key])
self.passthrough[:host] = server.addresses[address_key].first['addr']
break
end
end
self.passthrough[:instance] = self.ostack_get_instance_id
@logger.debug(sprintf('Connecting to running instance [%s] while calling ostack_up()', self.passthrough[:instance]))
self.connect_ssh_tunnel
end
self.passthrough[:instance]
end
def ostack_get_ip()
self.passthrough[:host]
end
def ostack_destroy
server = self.ostack_describe_instance
raise sprintf("instance[%s] not found by destroy()", self.ostack_get_instance_id) if server.nil?
server.destroy
@instance_data = nil
self.passthrough.delete(:instance)
end
def ostack_describe_instance(instance_id = ostack_get_instance_id)
if @cache_timeout
if @cache.has_key?(:ostack_describe_instance)
if (Time.now.to_i - @cache[:ostack_describe_instance][:time]) < @cache_timeout
@logger.debug(sprintf('using cached ostack_describe_instance?[%s] from [%s]', @cache[:ostack_describe_instance][:instance], @cache[:ostack_describe_instance][:time]))
return @cache[:ostack_describe_instance][:instance]
end
end
end
# We don't have a instance.
return nil if instance_id.nil?
self.ostack_connect
response = @nova.servers.get(instance_id)
return nil if response.nil?
@instance_data = response
if @cache_timeout
@cache[:ostack_describe_instance] = Hash.new unless @cache[:ostack_describe_instance].class.eql?(Hash)
@cache[:ostack_describe_instance][:time] = Time.now.to_i
@cache[:ostack_describe_instance][:instance] = response
@logger.debug(sprintf('caching is_available_via_ssh?[%s] at [%s]', @cache[:ostack_describe_instance][:instance], @cache[:ostack_describe_instance][:time]))
end
@instance_data
end
def ostack_status
self.ostack_describe_instance
return 'not-created' if @instance_data.nil?
if @instance_data.state.eql?('ACTIVE')
# Make this consistent with AWS response.
return 'running'
else
return @instance_data.state
end
end
# TODO this will throw at the first error - should we catch?
# run some commands, return an array of the output
def ostack_bootstrap (commands)
self.ostack_connect
commands = (commands.is_a?(Array)) ? commands : [ commands ]
output = Array.new
commands.each do |command|
output << self.run(command)
end
return output
end
def ostack_connect
# Instantiates an Object which can communicate with OS Compute.
# No instance specific information is set at this time.
return @nova unless @nova.nil?
config = {
:provider => 'openstack', # OpenStack Fog provider
:openstack_auth_url => self.passthrough[:openstack_auth_url], # OpenStack Keystone endpoint
:openstack_username => self.passthrough[:openstack_username], # Your OpenStack Username
:openstack_tenant => self.passthrough[:openstack_tenant], # Your tenant id
:openstack_api_key => self.passthrough[:openstack_api_key], # Your OpenStack Password
:connection_options => self.passthrough[:connection_options] # Optional
}
@nova = Fog::Compute.new(config)
end
end
|
chorankates/rouster
|
plugins/openstack.rb
|
Ruby
|
bsd-3-clause
| 5,686 |
package abi41_0_0.expo.modules.structuredheaders;
/**
* Common interface for all {@link Type}s that can carry numbers.
*
* @param <T>
* represented Java type
* @see <a href=
* "https://greenbytes.de/tech/webdav/draft-ietf-httpbis-header-structure-19.html#integer">Section
* 3.3.1 of draft-ietf-httpbis-header-structure-19</a>
* @see <a href=
* "https://greenbytes.de/tech/webdav/draft-ietf-httpbis-header-structure-19.html#decimal">Section
* 3.3.2 of draft-ietf-httpbis-header-structure-19</a>
*/
public interface NumberItem<T> extends Item<T>, LongSupplier {
/**
* Returns the divisor to be used to obtain the actual numerical value (as
* opposed to the underlying long value returned by
* {@link LongSupplier#getAsLong()}).
*
* @return the divisor ({@code 1} for Integers, {@code 1000} for Decimals)
*/
public int getDivisor();
public NumberItem<T> withParams(Parameters params);
}
|
exponent/exponent
|
android/versioned-abis/expoview-abi41_0_0/src/main/java/abi41_0_0/expo/modules/structuredheaders/NumberItem.java
|
Java
|
bsd-3-clause
| 973 |
// Copyright (c) 2009 The Chromium Authors. All rights reserved. Use of this
// source code is governed by a BSD-style license that can be found in the
// LICENSE file.
// Some basic utilities for aiding in the management of Tasks and Callbacks.
//
// AutoTaskRunner, and its brother AutoCallbackRunner are the scoped_ptr
// equivalents for callbacks. They are useful for ensuring a callback is
// executed and delete in the face of multiple return points in a function.
//
// TaskToCallbackAdapter converts a Task to a Callback0::Type since the two type
// heirarchies are strangely separate.
//
// CleanupCallback wraps another Callback and provides the ability to register
// objects for deletion as well as cleanup tasks that will be run on the
// callback's destruction. The deletion and cleanup tasks will be run on
// whatever thread the CleanupCallback is destroyed in.
#ifndef MEDIA_BASE_CALLBACK_
#define MEDIA_BASE_CALLBACK_
#include <vector>
#include "base/scoped_ptr.h"
#include "base/task.h"
namespace media {
class AutoTaskRunner {
public:
// Takes ownership of the task.
explicit AutoTaskRunner(Task* task)
: task_(task) {
}
~AutoTaskRunner() {
if (task_.get()) {
task_->Run();
}
}
Task* release() { return task_.release(); }
private:
scoped_ptr<Task> task_;
DISALLOW_COPY_AND_ASSIGN(AutoTaskRunner);
};
class AutoCallbackRunner {
public:
// Takes ownership of the callback.
explicit AutoCallbackRunner(Callback0::Type* callback)
: callback_(callback) {
}
~AutoCallbackRunner() {
if (callback_.get()) {
callback_->Run();
}
}
Callback0::Type* release() { return callback_.release(); }
private:
scoped_ptr<Callback0::Type> callback_;
DISALLOW_COPY_AND_ASSIGN(AutoCallbackRunner);
};
class TaskToCallbackAdapter : public Callback0::Type {
public:
static Callback0::Type* NewCallback(Task* task) {
return new TaskToCallbackAdapter(task);
}
virtual ~TaskToCallbackAdapter() {}
virtual void RunWithParams(const Tuple0& params) { task_->Run(); }
private:
TaskToCallbackAdapter(Task* task) : task_(task) {}
scoped_ptr<Task> task_;
DISALLOW_COPY_AND_ASSIGN(TaskToCallbackAdapter);
};
template <typename CallbackType>
class CleanupCallback : public CallbackType {
public:
explicit CleanupCallback(CallbackType* callback) : callback_(callback) {}
virtual ~CleanupCallback() {
for (size_t i = 0; i < run_when_done_.size(); i++) {
run_when_done_[i]->Run();
delete run_when_done_[i];
}
}
virtual void RunWithParams(const typename CallbackType::TupleType& params) {
callback_->RunWithParams(params);
}
template <typename T>
void DeleteWhenDone(T* ptr) {
RunWhenDone(new DeleteTask<T>(ptr));
}
void RunWhenDone(Task* ptr) {
run_when_done_.push_back(ptr);
}
private:
scoped_ptr<CallbackType> callback_;
std::vector<Task*> run_when_done_;
DISALLOW_COPY_AND_ASSIGN(CleanupCallback);
};
} // namespace media
#endif // MEDIA_BASE_CALLBACK_
|
rwatson/chromium-capsicum
|
media/base/callback.h
|
C
|
bsd-3-clause
| 3,026 |
////////////////////////////////////////////////////////////////////////
// Class: ValidHandleTester
// Module Type: analyzer
// File: ValidHandleTester_module.cc
//
// Generated at Thu Apr 11 13:40:02 2013 by Marc Paterno using artmod
// from cetpkgsupport v1_01_00.
////////////////////////////////////////////////////////////////////////
#include <string>
#include "art/Framework/Core/EDAnalyzer.h"
#include "art/Framework/Core/ModuleMacros.h"
#include "art/Framework/Principal/Event.h"
#include "art/Framework/Principal/Handle.h"
#include "art/Framework/Principal/Run.h"
#include "art/Framework/Principal/SubRun.h"
#include "fhiclcpp/ParameterSet.h"
class ValidHandleTester : public art::EDAnalyzer {
public:
explicit ValidHandleTester(fhicl::ParameterSet const & p);
void analyze(art::Event const & e) override;
private:
art::InputTag input_tag_;
std::string expected_value_;
};
ValidHandleTester::ValidHandleTester(fhicl::ParameterSet const & ps) :
art::EDAnalyzer(ps),
input_tag_(ps.get<std::string>("input_label")),
expected_value_(ps.get<std::string>("expected_value"))
{ }
void ValidHandleTester::analyze(art::Event const & e)
{
// Make sure old-form access works.
art::Handle<std::string> h;
e.getByLabel(input_tag_, h);
assert(h.isValid());
assert(*h == expected_value_);
// Make sure new-form access works.
auto p = e.getValidHandle<std::string>(input_tag_);
assert(*p == expected_value_);
assert(*p.provenance() == *h.provenance());
// Make sure conversion-to-pointer works.
[&](std::string const* x){ assert(*x == expected_value_); }(p);
}
DEFINE_ART_MODULE(ValidHandleTester)
|
gartung/fnal-art
|
art/test/Integration/ValidHandleTester_module.cc
|
C++
|
bsd-3-clause
| 1,652 |
/* Copyright (c) 2002-2005 CrystalClear Software, Inc.
* Use, modification and distribution is subject to the
* Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
* Author: Jeff Garland, Bart Garst
*/
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/time_serialize.hpp>
#include "../testfrmwk.hpp"
#include <sstream>
using namespace pdalboost;
using namespace posix_time;
using namespace gregorian;
template<class archive_type, class temporal_type>
void save_to(archive_type& ar, const temporal_type& tt)
{
ar << tt;
}
int main(){
// originals
date d(2002, Feb, 14);
#if defined(BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG)
time_duration td(12,13,52,123456789);
#else
time_duration td(12,13,52,123456);
#endif
ptime pt(d, td);
time_period tp(pt, ptime(date(2002, Oct, 31), hours(19)));
ptime sv_pt1(not_a_date_time);
ptime sv_pt2(pos_infin);
time_duration sv_td(neg_infin);
// for loading in from archive
date d2(not_a_date_time);
time_duration td2(1,0,0);
ptime pt2(d2, td2);
time_period tp2(pt2, hours(1));
ptime sv_pt3(min_date_time);
ptime sv_pt4(min_date_time);
time_duration sv_td2(0,0,0);
std::ostringstream oss;
// NOTE: DATE_TIME_XML_SERIALIZE is only used in testing and is
// defined in the testing Jamfile
#if defined(DATE_TIME_XML_SERIALIZE)
std::cout << "Running xml archive tests" << std::endl;
archive::xml_oarchive oa(oss);
#else
std::cout << "Running text archive tests" << std::endl;
archive::text_oarchive oa(oss);
#endif // DATE_TIME_XML_SERIALIZE
try{
#if defined(DATE_TIME_XML_SERIALIZE)
save_to(oa, BOOST_SERIALIZATION_NVP(pt));
save_to(oa, BOOST_SERIALIZATION_NVP(sv_pt1));
save_to(oa, BOOST_SERIALIZATION_NVP(sv_pt2));
save_to(oa, BOOST_SERIALIZATION_NVP(tp));
save_to(oa, BOOST_SERIALIZATION_NVP(td));
save_to(oa, BOOST_SERIALIZATION_NVP(sv_td));
#else
save_to(oa, pt);
save_to(oa, sv_pt1);
save_to(oa, sv_pt2);
save_to(oa, tp);
save_to(oa, td);
save_to(oa, sv_td);
#endif // DATE_TIME_XML_SERIALIZE
}catch(archive::archive_exception& ae){
std::string s(ae.what());
check("Error writing to archive: " + s + "\nWritten data: \"" + oss.str() + "\"", false);
return printTestStats();
}
std::istringstream iss(oss.str());
#if defined(DATE_TIME_XML_SERIALIZE)
archive::xml_iarchive ia(iss);
#else
archive::text_iarchive ia(iss);
#endif // DATE_TIME_XML_SERIALIZE
try{
#if defined(DATE_TIME_XML_SERIALIZE)
ia >> BOOST_SERIALIZATION_NVP(pt2);
ia >> BOOST_SERIALIZATION_NVP(sv_pt3);
ia >> BOOST_SERIALIZATION_NVP(sv_pt4);
ia >> BOOST_SERIALIZATION_NVP(tp2);
ia >> BOOST_SERIALIZATION_NVP(td2);
ia >> BOOST_SERIALIZATION_NVP(sv_td2);
#else
ia >> pt2;
ia >> sv_pt3;
ia >> sv_pt4;
ia >> tp2;
ia >> td2;
ia >> sv_td2;
#endif // DATE_TIME_XML_SERIALIZE
}catch(archive::archive_exception& ae){
std::string s(ae.what());
check("Error readng from archive: " + s + "\nWritten data: \"" + oss.str() + "\"", false);
return printTestStats();
}
check("ptime", pt == pt2);
check("special_values ptime (nadt)", sv_pt1 == sv_pt3);
check("special_values ptime (pos_infin)", sv_pt2 == sv_pt4);
check("time_period", tp == tp2);
check("time_duration", td == td2);
check("special_values time_duration (neg_infin)", sv_td == sv_td2);
return printTestStats();
}
|
verma/PDAL
|
boost/libs/date_time/test/posix_time/testtime_serialize.cpp
|
C++
|
bsd-3-clause
| 3,653 |
<?php
$pwd = getcwd();
$dirs = array();
$dirs['pwd'] = $pwd;
$dirs['imgmaps'] = $pwd.'/imgmaps';
$dirs['fonts'] = $pwd.'/fonts';
$dirs['cache'] = $pwd.'/cache';
$dirs['totals'] = $pwd.'/totals';
require("pChart.2/pData.class.php");
require("pChart.2/pDraw.class.php");
require("pChart.2/pImage.class.php");
require("pChart.2/pCache.class.php");
require("pChart.2/pPie.class.php");
function getDataSet($ImageName, $dirs, $hash)
{
$filename = $ImageName;
$data = unserialize(file_get_contents($dirs['totals'].'/'.$filename.'.ser'));
// Dataset definition
$DataSet = new pData;
$points = array();
$labels = array();
$href = array();
foreach($data as $k => $v)
{
// no hash = info for non-detail
if(!isset($hash) || strlen($hash) == 0)
{
$points[] = $v['count'];
$labels[] = $k;
$href[] = 'onclick=chartDetailLoad("'.$filename.'", "'.md5($k).'");';
}
else if(md5($k) == $hash) // hash = info for detail
{
foreach($v as $dk => $dv)
{
if($dk != 'count')
{
$points[] = $dv;
$labels[] = $dk;
//$href[] = 'onclick=chartDetailLoad("'.$filename.'", "'.md5($k).'");';
}
}
}
}
$DataSet->addPoints($points, 'Detail');
if(isset($href) && count($href))
$DataSet->addHref($href, 'Detail');
$DataSet->addPoints($labels, 'Labels');
$DataSet->setAbscissa('Labels');
return $DataSet;
}
function imgrender($ImageName, $DataSet, $dirs, $hash)
{
$filename = $ImageName;
if(isset($hash) && strlen($hash))
$filename = $filename.$hash;
// Initialise the graph
$ImgCache = new pCache(array('CacheFolder'=>$dirs['cache']));
$ImgHash = $ImgCache->getHash($DataSet);
// if ($ImgCache->isInCache($ImgHash) && file_exists($dirs['imgmaps'].'/'.$filename.'.map'))
// $ImgCache->strokeFromCache($ImgHash);
// else
{
$v = 800;
$size = array('w'=>$v, 'h'=> (($v/16) * 9 ));
$Img = new pImage($size['w'],$size['h'], $DataSet);
$Img->initialiseImageMap($filename, IMAGE_MAP_STORAGE_FILE, $filename, $dirs['imgmaps']);
$Img->drawGradientArea(0,0, $size['w'], $size['h'],DIRECTION_VERTICAL);
$fonts = array('Bedizen.ttf', 'GeosansLight.ttf', 'MankSans.ttf', 'calibri.ttf', 'verdana.ttf' );
$Img->setFontProperties(array("FontName"=>$dirs['fonts'].'/'.$fonts[4],"FontSize"=>10, 'R'=>255, 'G'=>255, 'B'=>255));
$Pie = new pPie($Img, $DataSet);
$options = array(
'Radius' => 100,
//'DrawLabels'=>TRUE,
//'ValuePosition' => PIE_VALUE_INSIDE,
'LabelStacked'=>TRUE,
'LabelR' => 255,
'LabelG' => 255,
'LabelB' => 255,
'WriteValues' => PIE_VALUE_PERCENTAGE,
'ValuePadding' => 25,
'RecordImageMap' => TRUE,
);
if(count($DataSet->Data['Series']['Detail']['Data']) < 50)
{
//$options['Border'] = TRUE;
$options['DataGapAngle'] = 5;
$options['DataGapRadius'] = 5;
}
$Pie->draw2DPie($size['w']/2, $size['h']/2, $options);
$Pie->drawPieLegend(15,40,array("Alpha"=>20));
$ImgCache->writeToCache($ImgHash,$Img);
$Img->stroke();
}
}
function imgmap($ImageName, $dirs, $hash)
{
$filename = $ImageName;
if(isset($hash) && strlen($hash))
$filename = $filename.$hash;
$Img = new pImage(1,1);
$Img->dumpImageMap($filename, IMAGE_MAP_STORAGE_FILE, $filename, $dirs['imgmaps']);
}
function html($map, $hash)
{
$self = $_SERVER["PHP_SELF"];
echo "<html> <head></head> <body>\n";
echo "<script src=\"imagemap.js\" type=\"text/javascript\"></script>\n";
echo "<img src=\"".$self."?map=".$map."&action=img\" id=\"testPicture\" alt=\"\" class=\"pChartPicture\"/>\n";
echo "<script>\n";
echo "addImage(\"testPicture\",\"pictureMap\",\"".$self."?map=".$map."&action=imgmap\");\n";
echo "</script>\n";
echo "</body>\n";
}
$action = $_REQUEST['action'];
$map = $_REQUEST['map'];
@$hash = $_REQUEST['hash'];
switch($action)
{
case 'imgmap':
imgmap($map, $dirs, $hash);
break;
case 'img':
imgrender($map, getDataSet($map, $dirs, $hash), $dirs, $hash);
break;
default:
html($map, $hash);
break;
}
?>
|
nkhorman/spamilter
|
ui/www/htdocs/chart/chartpie.php
|
PHP
|
bsd-3-clause
| 3,930 |
<?php namespace Album\Model;
use Zend\Db\TableGateway\TableGateway;
/**
* Class AlbumTable
*
* @package Album\Model
*/
class AlbumTable {
/** @var \Zend\Db\TableGateway\TableGateway $tableGateway */
protected $tableGateway;
/**
* AlbumTable constructor.
*
* @param \Zend\Db\TableGateway\TableGateway $tableGateway
*/
public function __construct(TableGateway $tableGateway) {
$this->tableGateway = $tableGateway;
}
/**
* @param $selectFunc
*
* @return \Zend\Db\ResultSet\ResultSet
*/
public function fetchAll($selectFunc = null) {
return $this->tableGateway->select($selectFunc);
}
public function getAlbum($id) {
$id = (int) $id;
$rowset = $this->tableGateway->select(['id' => $id]);
$row = $rowset->current();
if (!$row) {
throw new \Exception('Couldn\'t find row ' . $id);
}
return $row;
}
public function saveAlbum(Album $album) {
$data = [
'artist' => $album->artist,
'title' => $album->title,
'lastupdate' => date(DATE_RFC3339)
];
$id = (int) $album->id;
if($id === 0) {
$this->tableGateway->insert($data);
} else {
if($this->getAlbum($id)) {
$this->tableGateway->update($data, ['id' => $id]);
} else {
throw new \Exception('Album doesn\t exist');
}
}
}
public function deleteAlbum($id) {
$this->tableGateway->delete(['id' => (int) $id]);
}
}
|
eislek/megs
|
module/Album/src/Album/Model/AlbumTable.php
|
PHP
|
bsd-3-clause
| 1,608 |
/*jslint nomen: true */
/*globals define */
define(function (require, exports, module) {
'use strict';
var _ = require('lib/lodash');
var Backbone = require('backbone');
// We reuse the cartodb layer templates
var infoTemplate = require('text!templates/foreign-layer-info.html');
// Render an infowindow for a selected map item
module.exports = Backbone.View.extend({
template: _.template(infoTemplate),
events: {
'click .close': 'remove'
},
initialize: function (options) {
this.layerOptions = options.layerOptions;
this.data = options.data;
},
render: function () {
var context = {
name: this.data[this.layerOptions.humanReadableField],
raw: this.data
};
var names = this.layerOptions.fieldNames;
context.fields = _.map(_.keys(names), function (name) {
return {
name: names[name],
value: this.data[name]
};
}, this);
this.$el.html(this.template(context));
return this;
}
});
});
|
LocalData/localdata-dashboard
|
src/js/views/maps/item-view.js
|
JavaScript
|
bsd-3-clause
| 1,044 |
module Time (
Time,
fromDays,
fromHours,
fromMinutes,
fromSeconds,
toDays,
toHours,
toMinutes,
toSeconds,
offset,
multiply,
) where
daysToHours :: (RealFrac a) => a -> a
daysToHours = (24 *)
daysToMinutes :: (RealFrac a) => a -> a
daysToMinutes = hoursToMinutes . daysToHours
daysToSeconds :: (RealFrac a) => a -> a
daysToSeconds = minutesToSeconds . daysToMinutes
hoursToDays :: (RealFrac a) => a -> a
hoursToDays = (/ 24)
hoursToMinutes :: (RealFrac a) => a -> a
hoursToMinutes = (60 *)
hoursToSeconds :: (RealFrac a) => a -> a
hoursToSeconds = minutesToSeconds . hoursToMinutes
minutesToDays :: (RealFrac a) => a -> a
minutesToDays = hoursToDays . minutesToHours
minutesToHours :: (RealFrac a) => a -> a
minutesToHours = (/ 60)
minutesToSeconds :: (RealFrac a) => a -> a
minutesToSeconds = (60 *)
secondsToDays :: (RealFrac a) => a -> a
secondsToDays = hoursToDays . secondsToHours
secondsToHours :: (RealFrac a) => a -> a
secondsToHours = minutesToHours . secondsToMinutes
secondsToMinutes :: (RealFrac a) => a -> a
secondsToMinutes = (/ 60)
newtype Time a = Seconds a
fromDays :: (RealFrac a) => a -> Time a
fromDays t = Seconds $ daysToSeconds t
fromHours :: (RealFrac a) => a -> Time a
fromHours t = Seconds $ hoursToSeconds t
fromMinutes :: (RealFrac a) => a -> Time a
fromMinutes t = Seconds $ minutesToSeconds t
fromSeconds :: (RealFrac a) => a -> Time a
fromSeconds t = Seconds t
toDays :: (RealFrac a) => Time a -> a
toDays (Seconds t) = secondsToDays t
toHours :: (RealFrac a) => Time a -> a
toHours (Seconds t) = secondsToHours t
toMinutes :: (RealFrac a) => Time a -> a
toMinutes (Seconds t) = secondsToMinutes t
toSeconds :: (RealFrac a) => Time a -> a
toSeconds (Seconds t) = t
offset :: (RealFrac a) => Time a -> Time a -> Time a
(Seconds t) `offset` (Seconds o) = Seconds $ t + o
multiply :: (RealFrac a) => Time a -> a -> Time a
(Seconds t) `multiply` m = Seconds $ t * m
|
siliconbrain/khaland
|
src/Time.hs
|
Haskell
|
bsd-3-clause
| 1,959 |
"""
Krystek (1985) Correlated Colour Temperature
============================================
Defines the *Krystek (1985)* correlated colour temperature :math:`T_{cp}`
computations objects:
- :func:`colour.temperature.uv_to_CCT_Krystek1985`: Correlated colour
temperature :math:`T_{cp}` computation of given *CIE UCS* colourspace *uv*
chromaticity coordinates using *Krystek (1985)* method.
- :func:`colour.temperature.CCT_to_uv_Krystek1985`: *CIE UCS* colourspace
*uv* chromaticity coordinates computation of given correlated colour
temperature :math:`T_{cp}` using *Krystek (1985)* method.
References
----------
- :cite:`Krystek1985b` : Krystek, M. (1985). An algorithm to calculate
correlated colour temperature. Color Research & Application, 10(1), 38-40.
doi:10.1002/col.5080100109
"""
from __future__ import annotations
import numpy as np
from scipy.optimize import minimize
from colour.hints import (
ArrayLike,
Dict,
FloatingOrArrayLike,
FloatingOrNDArray,
NDArray,
Optional,
)
from colour.utilities import as_float_array, as_float, tstack
__author__ = "Colour Developers"
__copyright__ = "Copyright 2013 Colour Developers"
__license__ = "New BSD License - https://opensource.org/licenses/BSD-3-Clause"
__maintainer__ = "Colour Developers"
__email__ = "[email protected]"
__status__ = "Production"
__all__ = [
"uv_to_CCT_Krystek1985",
"CCT_to_uv_Krystek1985",
]
def uv_to_CCT_Krystek1985(
uv: ArrayLike, optimisation_kwargs: Optional[Dict] = None
) -> FloatingOrNDArray:
"""
Return the correlated colour temperature :math:`T_{cp}` from given
*CIE UCS* colourspace *uv* chromaticity coordinates using *Krystek (1985)*
method.
Parameters
----------
uv
*CIE UCS* colourspace *uv* chromaticity coordinates.
optimisation_kwargs
Parameters for :func:`scipy.optimize.minimize` definition.
Returns
-------
:class:`numpy.floating` or :class:`numpy.ndarray`
Correlated colour temperature :math:`T_{cp}`.
Warnings
--------
*Krystek (1985)* does not give an analytical inverse transformation to
compute the correlated colour temperature :math:`T_{cp}` from given
*CIE UCS* colourspace *uv* chromaticity coordinates, the current
implementation relies on optimization using :func:`scipy.optimize.minimize`
definition and thus has reduced precision and poor performance.
Notes
-----
- *Krystek (1985)* method computations are valid for correlated colour
temperature :math:`T_{cp}` normalised to domain [1000, 15000].
References
----------
:cite:`Krystek1985b`
Examples
--------
>>> uv_to_CCT_Krystek1985(np.array([0.20047203, 0.31029290]))
... # doctest: +ELLIPSIS
6504.3894290...
"""
uv = as_float_array(uv)
shape = uv.shape
uv = np.atleast_1d(uv.reshape([-1, 2]))
def objective_function(
CCT: FloatingOrArrayLike, uv: ArrayLike
) -> FloatingOrNDArray:
"""Objective function."""
objective = np.linalg.norm(CCT_to_uv_Krystek1985(CCT) - uv)
return as_float(objective)
optimisation_settings = {
"method": "Nelder-Mead",
"options": {
"fatol": 1e-10,
},
}
if optimisation_kwargs is not None:
optimisation_settings.update(optimisation_kwargs)
CCT = as_float_array(
[
minimize(
objective_function,
x0=6500,
args=(uv_i,),
**optimisation_settings,
).x
for uv_i in as_float_array(uv)
]
)
return as_float(np.reshape(CCT, shape[:-1]))
def CCT_to_uv_Krystek1985(CCT: FloatingOrArrayLike) -> NDArray:
"""
Return the *CIE UCS* colourspace *uv* chromaticity coordinates from given
correlated colour temperature :math:`T_{cp}` using *Krystek (1985)* method.
Parameters
----------
CCT
Correlated colour temperature :math:`T_{cp}`.
Returns
-------
:class:`numpy.ndarray`
*CIE UCS* colourspace *uv* chromaticity coordinates.
Notes
-----
- *Krystek (1985)* method computations are valid for correlated colour
temperature :math:`T_{cp}` normalised to domain [1000, 15000].
References
----------
:cite:`Krystek1985b`
Examples
--------
>>> CCT_to_uv_Krystek1985(6504.38938305) # doctest: +ELLIPSIS
array([ 0.2004720..., 0.3102929...])
"""
T = as_float_array(CCT)
T_2 = T**2
u = (
0.860117757 + 1.54118254 * 10**-4 * T + 1.28641212 * 10**-7 * T_2
) / (1 + 8.42420235 * 10**-4 * T + 7.08145163 * 10**-7 * T_2)
v = (
0.317398726 + 4.22806245 * 10**-5 * T + 4.20481691 * 10**-8 * T_2
) / (1 - 2.89741816 * 10**-5 * T + 1.61456053 * 10**-7 * T_2)
return tstack([u, v])
|
colour-science/colour
|
colour/temperature/krystek1985.py
|
Python
|
bsd-3-clause
| 4,896 |
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
?>
<h1>Profile</h1>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'title') ?>
<?= $form->field($model, 'name') ?>
<?= $form->field($model, 'surname') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'website') ?>
<div class="form-group">
<?= Html::submitButton('Login', ['class' => 'btn btn-success', 'name' => 'login-button']) ?>
</div>
<?php ActiveForm::end(); ?>
|
dixonsatit/yii2-workshop-rbac-db-02
|
frontend/views/site/profile.php
|
PHP
|
bsd-3-clause
| 466 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html><head><title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>
<script type="text/javascript" src="search.js"></script>
</head>
<body class="SRPage">
<div id="SRIndex">
<div class="SRStatus" id="Loading">Loading...</div>
<div class="SRResult" id="SR_on_5fabandonprintjob_5fclicked">
<div class="SREntry">
<a id="Item0" onkeydown="return searchResults.Nav(event,0)" onkeypress="return searchResults.Nav(event,0)" onkeyup="return searchResults.Nav(event,0)" class="SRSymbol" href="../class_print_panel.html#ae38bc6ba99ecf7fb131d30ca83b5b980" target="_parent">on_abandonPrintJob_clicked</a>
<span class="SRScope">PrintPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5factionabout_5ffabstudio_5ftriggered">
<div class="SREntry">
<a id="Item1" onkeydown="return searchResults.Nav(event,1)" onkeypress="return searchResults.Nav(event,1)" onkeyup="return searchResults.Nav(event,1)" class="SRSymbol" href="../class_main_window.html#a17016617e98b7fbe27a8caa25dfc5620" target="_parent">on_actionAbout_FabStudio_triggered</a>
<span class="SRScope">MainWindow</span>
</div>
</div>
<div class="SRResult" id="SR_on_5factionenable_5fadvanced_5ffeatures_5ftriggered">
<div class="SREntry">
<a id="Item2" onkeydown="return searchResults.Nav(event,2)" onkeypress="return searchResults.Nav(event,2)" onkeyup="return searchResults.Nav(event,2)" class="SRSymbol" href="../class_main_window.html#a2c15c6babe3a29a02953fb93caf85af8" target="_parent">on_actionEnable_Advanced_Features_triggered</a>
<span class="SRScope">MainWindow</span>
</div>
</div>
<div class="SRResult" id="SR_on_5factionexit_5ftriggered">
<div class="SREntry">
<a id="Item3" onkeydown="return searchResults.Nav(event,3)" onkeypress="return searchResults.Nav(event,3)" onkeyup="return searchResults.Nav(event,3)" class="SRSymbol" href="../class_main_window.html#ab4487c4b02224acd4a0193d38b704ddb" target="_parent">on_actionExit_triggered</a>
<span class="SRScope">MainWindow</span>
</div>
</div>
<div class="SRResult" id="SR_on_5factionshow_5finformation_5fat_5fstartup_5ftriggered">
<div class="SREntry">
<a id="Item4" onkeydown="return searchResults.Nav(event,4)" onkeypress="return searchResults.Nav(event,4)" onkeyup="return searchResults.Nav(event,4)" class="SRSymbol" href="../class_main_window.html#a9cf37de4551319613bf318a86e5fbf23" target="_parent">on_actionShow_Information_at_Startup_triggered</a>
<span class="SRScope">MainWindow</span>
</div>
</div>
<div class="SRResult" id="SR_on_5factionvisit_5ffabathome_5forg_5ftriggered">
<div class="SREntry">
<a id="Item5" onkeydown="return searchResults.Nav(event,5)" onkeypress="return searchResults.Nav(event,5)" onkeyup="return searchResults.Nav(event,5)" class="SRSymbol" href="../class_main_window.html#ab1b4afa30acceb39f2629ffe4133c979" target="_parent">on_actionVisit_FabAtHome_org_triggered</a>
<span class="SRScope">MainWindow</span>
</div>
</div>
<div class="SRResult" id="SR_on_5fautoarrange_5fclicked">
<div class="SREntry">
<a id="Item6" onkeydown="return searchResults.Nav(event,6)" onkeypress="return searchResults.Nav(event,6)" onkeyup="return searchResults.Nav(event,6)" class="SRSymbol" href="../class_position_objects_panel.html#afece00056fcf1dc8e630de63881d2e23" target="_parent">on_autoArrange_clicked</a>
<span class="SRScope">PositionObjectsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5fbrowse_5fclicked">
<div class="SREntry">
<a id="Item7" onkeydown="return searchResults.Nav(event,7)" onkeypress="return searchResults.Nav(event,7)" onkeyup="return searchResults.Nav(event,7)" class="SRSymbol" href="../class_load_objects_panel.html#a84671233d587daa2eb3512eec35eae94" target="_parent">on_browse_clicked</a>
<span class="SRScope">LoadObjectsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5fclearfilenametypeahead_5fclicked">
<div class="SREntry">
<a id="Item8" onkeydown="return searchResults.Nav(event,8)" onkeypress="return searchResults.Nav(event,8)" onkeyup="return searchResults.Nav(event,8)" class="SRSymbol" href="../class_load_objects_panel.html#a0d5b0493a7d280330fcfc42a15cbb2e2" target="_parent">on_clearFileNameTypeahead_clicked</a>
<span class="SRScope">LoadObjectsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5fdeleteobject_5fclicked">
<div class="SREntry">
<a id="Item9" onkeydown="return searchResults.Nav(event,9)" onkeypress="return searchResults.Nav(event,9)" onkeyup="return searchResults.Nav(event,9)" class="SRSymbol" href="../class_position_objects_panel.html#adfddf9c44c1d07e5e0b32a799402a76b" target="_parent">on_deleteObject_clicked</a>
<span class="SRScope">PositionObjectsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5ffilenametypeahead_5ftextchanged">
<div class="SREntry">
<a id="Item10" onkeydown="return searchResults.Nav(event,10)" onkeypress="return searchResults.Nav(event,10)" onkeyup="return searchResults.Nav(event,10)" class="SRSymbol" href="../class_load_objects_panel.html#acc497b469a074bc7bb55fec0262c4073" target="_parent">on_fileNameTypeahead_textChanged</a>
<span class="SRScope">LoadObjectsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5ffindbestrotation_5fclicked">
<div class="SREntry">
<a id="Item11" onkeydown="return searchResults.Nav(event,11)" onkeypress="return searchResults.Nav(event,11)" onkeyup="return searchResults.Nav(event,11)" class="SRSymbol" href="../class_position_objects_panel.html#a291b698b909c236558e82840ad4bbd50" target="_parent">on_findBestRotation_clicked</a>
<span class="SRScope">PositionObjectsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5floadobjects_5fclicked">
<div class="SREntry">
<a id="Item12" onkeydown="return searchResults.Nav(event,12)" onkeypress="return searchResults.Nav(event,12)" onkeyup="return searchResults.Nav(event,12)" class="SRSymbol" href="../class_toolbar.html#af2106b47f15f76a9c064d521fa4268e9" target="_parent">on_loadObjects_clicked</a>
<span class="SRScope">Toolbar</span>
</div>
</div>
<div class="SRResult" id="SR_on_5fmodifyprintsettings_5fclicked">
<div class="SREntry">
<a id="Item13" onkeydown="return searchResults.Nav(event,13)" onkeypress="return searchResults.Nav(event,13)" onkeyup="return searchResults.Nav(event,13)" class="SRSymbol" href="../class_print_panel.html#a584ca8f692036814367b8dd52debb28a" target="_parent">on_modifyPrintSettings_clicked</a>
<span class="SRScope">PrintPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5fpickreasonablesize_5fclicked">
<div class="SREntry">
<a id="Item14" onkeydown="return searchResults.Nav(event,14)" onkeypress="return searchResults.Nav(event,14)" onkeyup="return searchResults.Nav(event,14)" class="SRSymbol" href="../class_position_objects_panel.html#a5202adf473aac0bd8d0418b05bbffbeb" target="_parent">on_pickReasonableSize_clicked</a>
<span class="SRScope">PositionObjectsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5fpositionx_5fvaluechanged">
<div class="SREntry">
<a id="Item15" onkeydown="return searchResults.Nav(event,15)" onkeypress="return searchResults.Nav(event,15)" onkeyup="return searchResults.Nav(event,15)" class="SRSymbol" href="../class_position_objects_panel.html#af721a974024e7117bdf94d523e1d3153" target="_parent">on_positionX_valueChanged</a>
<span class="SRScope">PositionObjectsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5fpositiony_5fvaluechanged">
<div class="SREntry">
<a id="Item16" onkeydown="return searchResults.Nav(event,16)" onkeypress="return searchResults.Nav(event,16)" onkeyup="return searchResults.Nav(event,16)" class="SRSymbol" href="../class_position_objects_panel.html#a3330268fecd38e2d4588e351a9279ed0" target="_parent">on_positionY_valueChanged</a>
<span class="SRScope">PositionObjectsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5fpositionz_5fvaluechanged">
<div class="SREntry">
<a id="Item17" onkeydown="return searchResults.Nav(event,17)" onkeypress="return searchResults.Nav(event,17)" onkeyup="return searchResults.Nav(event,17)" class="SRSymbol" href="../class_position_objects_panel.html#a907d1a2b19a6ad6fed75352298a877fc" target="_parent">on_positionZ_valueChanged</a>
<span class="SRScope">PositionObjectsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5fprint_5fclicked">
<div class="SREntry">
<a id="Item18" onkeydown="return searchResults.Nav(event,18)" onkeypress="return searchResults.Nav(event,18)" onkeyup="return searchResults.Nav(event,18)" class="SRSymbol" href="../class_print_panel.html#a23118e802aa5b01cd9b18f4d6de74464" target="_parent">on_print_clicked</a>
<span class="SRScope">PrintPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5fprintercombo_5fcurrentindexchanged">
<div class="SREntry">
<a id="Item19" onkeydown="return searchResults.Nav(event,19)" onkeypress="return searchResults.Nav(event,19)" onkeyup="return searchResults.Nav(event,19)" class="SRSymbol" href="../class_materials_panel.html#a572cf9d59650ce0d9f9bd753c62d8740" target="_parent">on_printerCombo_currentIndexChanged</a>
<span class="SRScope">MaterialsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5fputontray_5fclicked">
<div class="SREntry">
<a id="Item20" onkeydown="return searchResults.Nav(event,20)" onkeypress="return searchResults.Nav(event,20)" onkeyup="return searchResults.Nav(event,20)" class="SRSymbol" href="../class_position_objects_panel.html#a2e3e80ffef37e28f7beb3527b7c675dc" target="_parent">on_putOnTray_clicked</a>
<span class="SRScope">PositionObjectsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5fremovematerial_5fclicked">
<div class="SREntry">
<a id="Item21" onkeydown="return searchResults.Nav(event,21)" onkeypress="return searchResults.Nav(event,21)" onkeyup="return searchResults.Nav(event,21)" class="SRSymbol" href="../class_materials_panel.html#af7e801b616f26b0ec013145a82bd9e89" target="_parent">on_removeMaterial_clicked</a>
<span class="SRScope">MaterialsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5frescan_5fclicked">
<div class="SREntry">
<a id="Item22" onkeydown="return searchResults.Nav(event,22)" onkeypress="return searchResults.Nav(event,22)" onkeyup="return searchResults.Nav(event,22)" class="SRSymbol" href="../class_load_objects_panel.html#a9487b6bfcc9679f4d84009f2641f125a" target="_parent">on_rescan_clicked</a>
<span class="SRScope">LoadObjectsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5frotationx_5fvaluechanged">
<div class="SREntry">
<a id="Item23" onkeydown="return searchResults.Nav(event,23)" onkeypress="return searchResults.Nav(event,23)" onkeyup="return searchResults.Nav(event,23)" class="SRSymbol" href="../class_position_objects_panel.html#adb6ed976f2ae7cbc9ff04b786cded5f4" target="_parent">on_rotationX_valueChanged</a>
<span class="SRScope">PositionObjectsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5frotationy_5fvaluechanged">
<div class="SREntry">
<a id="Item24" onkeydown="return searchResults.Nav(event,24)" onkeypress="return searchResults.Nav(event,24)" onkeyup="return searchResults.Nav(event,24)" class="SRSymbol" href="../class_position_objects_panel.html#a44bf434b2fbc8dda222c64ea59d4cce9" target="_parent">on_rotationY_valueChanged</a>
<span class="SRScope">PositionObjectsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5frotationz_5fvaluechanged">
<div class="SREntry">
<a id="Item25" onkeydown="return searchResults.Nav(event,25)" onkeypress="return searchResults.Nav(event,25)" onkeyup="return searchResults.Nav(event,25)" class="SRSymbol" href="../class_position_objects_panel.html#ab349f279136c1bae37223f577959c82b" target="_parent">on_rotationZ_valueChanged</a>
<span class="SRScope">PositionObjectsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5fsaveprintjob_5fclicked">
<div class="SREntry">
<a id="Item26" onkeydown="return searchResults.Nav(event,26)" onkeypress="return searchResults.Nav(event,26)" onkeyup="return searchResults.Nav(event,26)" class="SRSymbol" href="../class_print_panel.html#a57ba22834086084c09fcaf34c793bdce" target="_parent">on_savePrintJob_clicked</a>
<span class="SRScope">PrintPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5fscalefrominches_5fclicked">
<div class="SREntry">
<a id="Item27" onkeydown="return searchResults.Nav(event,27)" onkeypress="return searchResults.Nav(event,27)" onkeyup="return searchResults.Nav(event,27)" class="SRSymbol" href="../class_position_objects_panel.html#ab07ccef9f7b4518d0f02f7245e50d2e2" target="_parent">on_scaleFromInches_clicked</a>
<span class="SRScope">PositionObjectsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5fscalingx_5fvaluechanged">
<div class="SREntry">
<a id="Item28" onkeydown="return searchResults.Nav(event,28)" onkeypress="return searchResults.Nav(event,28)" onkeyup="return searchResults.Nav(event,28)" class="SRSymbol" href="../class_position_objects_panel.html#a180c5bfc32381896eeeb0607db5580d5" target="_parent">on_scalingX_valueChanged</a>
<span class="SRScope">PositionObjectsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5fscalingy_5fvaluechanged">
<div class="SREntry">
<a id="Item29" onkeydown="return searchResults.Nav(event,29)" onkeypress="return searchResults.Nav(event,29)" onkeyup="return searchResults.Nav(event,29)" class="SRSymbol" href="../class_position_objects_panel.html#ad80f481a233357ca4418b6cfb175dd3e" target="_parent">on_scalingY_valueChanged</a>
<span class="SRScope">PositionObjectsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5fscalingz_5fvaluechanged">
<div class="SREntry">
<a id="Item30" onkeydown="return searchResults.Nav(event,30)" onkeypress="return searchResults.Nav(event,30)" onkeyup="return searchResults.Nav(event,30)" class="SRSymbol" href="../class_position_objects_panel.html#adcd28bd2ca592af686c669f3e14932c5" target="_parent">on_scalingZ_valueChanged</a>
<span class="SRScope">PositionObjectsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5fselectmaterials_5fclicked">
<div class="SREntry">
<a id="Item31" onkeydown="return searchResults.Nav(event,31)" onkeypress="return searchResults.Nav(event,31)" onkeyup="return searchResults.Nav(event,31)" class="SRSymbol" href="../class_toolbar.html#a9b723421d66653cdf1e905ef09f824e6" target="_parent">on_selectMaterials_clicked</a>
<span class="SRScope">Toolbar</span>
</div>
</div>
<div class="SRResult" id="SR_on_5fsendtoprinter_5fclicked">
<div class="SREntry">
<a id="Item32" onkeydown="return searchResults.Nav(event,32)" onkeypress="return searchResults.Nav(event,32)" onkeyup="return searchResults.Nav(event,32)" class="SRSymbol" href="javascript:searchResults.Toggle('SR_on_5fsendtoprinter_5fclicked')">on_sendToPrinter_clicked</a>
<div class="SRChildren">
<a id="Item32_c0" onkeydown="return searchResults.NavChild(event,32,0)" onkeypress="return searchResults.NavChild(event,32,0)" onkeyup="return searchResults.NavChild(event,32,0)" class="SRScope" href="../class_print_panel.html#ac9697c71fe2f7ababd4eb2ee0713f807" target="_parent">PrintPanel::on_sendToPrinter_clicked()</a>
<a id="Item32_c1" onkeydown="return searchResults.NavChild(event,32,1)" onkeypress="return searchResults.NavChild(event,32,1)" onkeyup="return searchResults.NavChild(event,32,1)" class="SRScope" href="../class_toolbar.html#a4f6a56059463148a0b0b0274c8fca77e" target="_parent">Toolbar::on_sendToPrinter_clicked()</a>
</div>
</div>
</div>
<div class="SRResult" id="SR_on_5fstartusingfabstudio_5fclicked">
<div class="SREntry">
<a id="Item33" onkeydown="return searchResults.Nav(event,33)" onkeypress="return searchResults.Nav(event,33)" onkeyup="return searchResults.Nav(event,33)" class="SRSymbol" href="../class_first_execution_dialog.html#a5c0d79d1cb6e588f58180fa2c8fb0b7a" target="_parent">on_startUsingFabStudio_clicked</a>
<span class="SRScope">FirstExecutionDialog</span>
</div>
</div>
<div class="SRResult" id="SR_on_5ftoolcombo_5fcurrentindexchanged">
<div class="SREntry">
<a id="Item34" onkeydown="return searchResults.Nav(event,34)" onkeypress="return searchResults.Nav(event,34)" onkeyup="return searchResults.Nav(event,34)" class="SRSymbol" href="../class_print_panel.html#ad1c490afbc34b5bf7c62792c3f92637f" target="_parent">on_toolCombo_currentIndexChanged</a>
<span class="SRScope">PrintPanel</span>
</div>
</div>
<div class="SRResult" id="SR_on_5funiformscalingcheckbox_5ftoggled">
<div class="SREntry">
<a id="Item35" onkeydown="return searchResults.Nav(event,35)" onkeypress="return searchResults.Nav(event,35)" onkeyup="return searchResults.Nav(event,35)" class="SRSymbol" href="../class_position_objects_panel.html#afa3e4955b0239236d6fff9e766c4e320" target="_parent">on_uniformScalingCheckbox_toggled</a>
<span class="SRScope">PositionObjectsPanel</span>
</div>
</div>
<div class="SRResult" id="SR_onchangedmaterials">
<div class="SREntry">
<a id="Item36" onkeydown="return searchResults.Nav(event,36)" onkeypress="return searchResults.Nav(event,36)" onkeyup="return searchResults.Nav(event,36)" class="SRSymbol" href="../class_print_panel.html#a7299e8359ae3f5e5315fd08e164085b8" target="_parent">onChangedMaterials</a>
<span class="SRScope">PrintPanel</span>
</div>
</div>
<div class="SRResult" id="SR_openglcamera">
<div class="SREntry">
<a id="Item37" onkeydown="return searchResults.Nav(event,37)" onkeypress="return searchResults.Nav(event,37)" onkeyup="return searchResults.Nav(event,37)" class="SRSymbol" href="../class_open_g_l_camera.html#a454640dea32484f16ed68f620b8c0a3b" target="_parent">OpenGLCamera</a>
<span class="SRScope">OpenGLCamera</span>
</div>
</div>
<div class="SRResult" id="SR_openglwidget">
<div class="SREntry">
<a id="Item38" onkeydown="return searchResults.Nav(event,38)" onkeypress="return searchResults.Nav(event,38)" onkeyup="return searchResults.Nav(event,38)" class="SRSymbol" href="../class_open_g_l_widget.html#a21ec3e0d838c7b116ff19eb9a9e84e07" target="_parent">OpenGLWidget</a>
<span class="SRScope">OpenGLWidget</span>
</div>
</div>
<div class="SRResult" id="SR_operator_2a">
<div class="SREntry">
<a id="Item39" onkeydown="return searchResults.Nav(event,39)" onkeypress="return searchResults.Nav(event,39)" onkeyup="return searchResults.Nav(event,39)" class="SRSymbol" href="javascript:searchResults.Toggle('SR_operator_2a')">operator*</a>
<div class="SRChildren">
<a id="Item39_c0" onkeydown="return searchResults.NavChild(event,39,0)" onkeypress="return searchResults.NavChild(event,39,0)" onkeyup="return searchResults.NavChild(event,39,0)" class="SRScope" href="../vector3_8cpp.html#a89bababed5062f0246deedb92a5954c0" target="_parent">operator*(const Math::Vector3 &lhs, Math::Float s): vector3.cpp</a>
<a id="Item39_c1" onkeydown="return searchResults.NavChild(event,39,1)" onkeypress="return searchResults.NavChild(event,39,1)" onkeyup="return searchResults.NavChild(event,39,1)" class="SRScope" href="../vector3_8cpp.html#aef0059a794338688364df400c41cf3e8" target="_parent">operator*(Math::Float s, const Math::Vector3 &v): vector3.cpp</a>
<a id="Item39_c2" onkeydown="return searchResults.NavChild(event,39,2)" onkeypress="return searchResults.NavChild(event,39,2)" onkeyup="return searchResults.NavChild(event,39,2)" class="SRScope" href="../vector3_8h.html#a89bababed5062f0246deedb92a5954c0" target="_parent">operator*(const Math::Vector3 &lhs, Math::Float s): vector3.cpp</a>
<a id="Item39_c3" onkeydown="return searchResults.NavChild(event,39,3)" onkeypress="return searchResults.NavChild(event,39,3)" onkeyup="return searchResults.NavChild(event,39,3)" class="SRScope" href="../vector3_8h.html#aef0059a794338688364df400c41cf3e8" target="_parent">operator*(Math::Float s, const Math::Vector3 &v): vector3.cpp</a>
</div>
</div>
</div>
<div class="SRResult" id="SR_operator_2a_3d">
<div class="SREntry">
<a id="Item40" onkeydown="return searchResults.Nav(event,40)" onkeypress="return searchResults.Nav(event,40)" onkeyup="return searchResults.Nav(event,40)" class="SRSymbol" href="../struct_math_1_1_vector3.html#abb91fd3b71bdbf6417d548ec2a6ebe62" target="_parent">operator*=</a>
<span class="SRScope">Math::Vector3</span>
</div>
</div>
<div class="SRResult" id="SR_operator_2b">
<div class="SREntry">
<a id="Item41" onkeydown="return searchResults.Nav(event,41)" onkeypress="return searchResults.Nav(event,41)" onkeyup="return searchResults.Nav(event,41)" class="SRSymbol" href="../struct_math_1_1_vector3.html#afdd175ff59aa8b56363863c47aae6bf1" target="_parent">operator+</a>
<span class="SRScope">Math::Vector3</span>
</div>
</div>
<div class="SRResult" id="SR_operator_2b_3d">
<div class="SREntry">
<a id="Item42" onkeydown="return searchResults.Nav(event,42)" onkeypress="return searchResults.Nav(event,42)" onkeyup="return searchResults.Nav(event,42)" class="SRSymbol" href="../struct_math_1_1_vector3.html#a80f7478f41fda702324512863c156c32" target="_parent">operator+=</a>
<span class="SRScope">Math::Vector3</span>
</div>
</div>
<div class="SRResult" id="SR_operator_2d">
<div class="SREntry">
<a id="Item43" onkeydown="return searchResults.Nav(event,43)" onkeypress="return searchResults.Nav(event,43)" onkeyup="return searchResults.Nav(event,43)" class="SRSymbol" href="../struct_math_1_1_vector3.html#ab5a1bafd82d5cdc0f7ad27482b2cc52f" target="_parent">operator-</a>
<span class="SRScope">Math::Vector3</span>
</div>
</div>
<div class="SRResult" id="SR_operator_2d_3d">
<div class="SREntry">
<a id="Item44" onkeydown="return searchResults.Nav(event,44)" onkeypress="return searchResults.Nav(event,44)" onkeyup="return searchResults.Nav(event,44)" class="SRSymbol" href="../struct_math_1_1_vector3.html#a056e8a524e7ff063db72703c1838c79b" target="_parent">operator-=</a>
<span class="SRScope">Math::Vector3</span>
</div>
</div>
<div class="SRResult" id="SR_operator_2f">
<div class="SREntry">
<a id="Item45" onkeydown="return searchResults.Nav(event,45)" onkeypress="return searchResults.Nav(event,45)" onkeyup="return searchResults.Nav(event,45)" class="SRSymbol" href="javascript:searchResults.Toggle('SR_operator_2f')">operator/</a>
<div class="SRChildren">
<a id="Item45_c0" onkeydown="return searchResults.NavChild(event,45,0)" onkeypress="return searchResults.NavChild(event,45,0)" onkeyup="return searchResults.NavChild(event,45,0)" class="SRScope" href="../vector3_8cpp.html#a6f750c8607458ec986d98d10b1f5d8af" target="_parent">operator/(const Math::Vector3 &lhs, Math::Float s): vector3.cpp</a>
<a id="Item45_c1" onkeydown="return searchResults.NavChild(event,45,1)" onkeypress="return searchResults.NavChild(event,45,1)" onkeyup="return searchResults.NavChild(event,45,1)" class="SRScope" href="../vector3_8h.html#a6f750c8607458ec986d98d10b1f5d8af" target="_parent">operator/(const Math::Vector3 &lhs, Math::Float s): vector3.cpp</a>
</div>
</div>
</div>
<div class="SRResult" id="SR_operator_2f_3d">
<div class="SREntry">
<a id="Item46" onkeydown="return searchResults.Nav(event,46)" onkeypress="return searchResults.Nav(event,46)" onkeyup="return searchResults.Nav(event,46)" class="SRSymbol" href="../struct_math_1_1_vector3.html#ac660065bc4dcbde9057b6053b7b9d579" target="_parent">operator/=</a>
<span class="SRScope">Math::Vector3</span>
</div>
</div>
<div class="SRResult" id="SR_operator_3c">
<div class="SREntry">
<a id="Item47" onkeydown="return searchResults.Nav(event,47)" onkeypress="return searchResults.Nav(event,47)" onkeyup="return searchResults.Nav(event,47)" class="SRSymbol" href="javascript:searchResults.Toggle('SR_operator_3c')">operator<</a>
<div class="SRChildren">
<a id="Item47_c0" onkeydown="return searchResults.NavChild(event,47,0)" onkeypress="return searchResults.NavChild(event,47,0)" onkeyup="return searchResults.NavChild(event,47,0)" class="SRScope" href="../class_edge_key.html#af22b484475ed3901106298adb9e75841" target="_parent">EdgeKey::operator<()</a>
<a id="Item47_c1" onkeydown="return searchResults.NavChild(event,47,1)" onkeypress="return searchResults.NavChild(event,47,1)" onkeyup="return searchResults.NavChild(event,47,1)" class="SRScope" href="../fabathomemodel2fabwritertsi_8cpp.html#ac8c2abff1030434ef982ff9ff607128a" target="_parent">operator<(): fabathomemodel2fabwritertsi.cpp</a>
</div>
</div>
</div>
<div class="SRResult" id="SR_operator_3d">
<div class="SREntry">
<a id="Item48" onkeydown="return searchResults.Nav(event,48)" onkeypress="return searchResults.Nav(event,48)" onkeyup="return searchResults.Nav(event,48)" class="SRSymbol" href="javascript:searchResults.Toggle('SR_operator_3d')">operator=</a>
<div class="SRChildren">
<a id="Item48_c0" onkeydown="return searchResults.NavChild(event,48,0)" onkeypress="return searchResults.NavChild(event,48,0)" onkeyup="return searchResults.NavChild(event,48,0)" class="SRScope" href="../class_tinman.html#a386ac4d00a37762e6bb047d42e730d04" target="_parent">Tinman::operator=()</a>
<a id="Item48_c1" onkeydown="return searchResults.NavChild(event,48,1)" onkeypress="return searchResults.NavChild(event,48,1)" onkeyup="return searchResults.NavChild(event,48,1)" class="SRScope" href="../class_printable_object.html#a417dae50fd36d658fab6c78ceea1dbe0" target="_parent">PrintableObject::operator=()</a>
<a id="Item48_c2" onkeydown="return searchResults.NavChild(event,48,2)" onkeypress="return searchResults.NavChild(event,48,2)" onkeyup="return searchResults.NavChild(event,48,2)" class="SRScope" href="../class_a_m_f_region.html#a28e3a2fff7bef7cae8c39d7659a19582" target="_parent">AMFRegion::operator=()</a>
<a id="Item48_c3" onkeydown="return searchResults.NavChild(event,48,3)" onkeypress="return searchResults.NavChild(event,48,3)" onkeyup="return searchResults.NavChild(event,48,3)" class="SRScope" href="../struct_math_1_1_vector3.html#a0b984fb449936effa4d536c0d788f385" target="_parent">Math::Vector3::operator=()</a>
<a id="Item48_c4" onkeydown="return searchResults.NavChild(event,48,4)" onkeypress="return searchResults.NavChild(event,48,4)" onkeyup="return searchResults.NavChild(event,48,4)" class="SRScope" href="../class_s_t_l_mesh.html#a7993bbc87c0f8835c16e7b15c3d9d8e1" target="_parent">STLMesh::operator=()</a>
</div>
</div>
</div>
<div class="SRResult" id="SR_operator_5b_5d">
<div class="SREntry">
<a id="Item49" onkeydown="return searchResults.Nav(event,49)" onkeypress="return searchResults.Nav(event,49)" onkeyup="return searchResults.Nav(event,49)" class="SRSymbol" href="javascript:searchResults.Toggle('SR_operator_5b_5d')">operator[]</a>
<div class="SRChildren">
<a id="Item49_c0" onkeydown="return searchResults.NavChild(event,49,0)" onkeypress="return searchResults.NavChild(event,49,0)" onkeyup="return searchResults.NavChild(event,49,0)" class="SRScope" href="../struct_math_1_1_matrix4x4.html#ab18d3ed3360a0cede49e02972974daa1" target="_parent">Math::Matrix4x4::operator[](int ix)</a>
<a id="Item49_c1" onkeydown="return searchResults.NavChild(event,49,1)" onkeypress="return searchResults.NavChild(event,49,1)" onkeyup="return searchResults.NavChild(event,49,1)" class="SRScope" href="../struct_math_1_1_matrix4x4.html#ad63363ad1c19d94f61195d69802e6b93" target="_parent">Math::Matrix4x4::operator[](int ix) const </a>
<a id="Item49_c2" onkeydown="return searchResults.NavChild(event,49,2)" onkeypress="return searchResults.NavChild(event,49,2)" onkeyup="return searchResults.NavChild(event,49,2)" class="SRScope" href="../struct_math_1_1_vector3.html#af774268f5a3691592c7a74b4545fccf9" target="_parent">Math::Vector3::operator[](int ix)</a>
<a id="Item49_c3" onkeydown="return searchResults.NavChild(event,49,3)" onkeypress="return searchResults.NavChild(event,49,3)" onkeyup="return searchResults.NavChild(event,49,3)" class="SRScope" href="../struct_math_1_1_vector3.html#a43a336ae831c3c0c8b40c230a2451776" target="_parent">Math::Vector3::operator[](int ix) const </a>
</div>
</div>
</div>
<div class="SRResult" id="SR_optimizepathorder">
<div class="SREntry">
<a id="Item50" onkeydown="return searchResults.Nav(event,50)" onkeypress="return searchResults.Nav(event,50)" onkeyup="return searchResults.Nav(event,50)" class="SRSymbol" href="../class_path_stack.html#a55dac5dc13ddfd0602380d73dd5ad3df" target="_parent">optimizePathOrder</a>
<span class="SRScope">PathStack</span>
</div>
</div>
<div class="SRResult" id="SR_orbit">
<div class="SREntry">
<a id="Item51" onkeydown="return searchResults.Nav(event,51)" onkeypress="return searchResults.Nav(event,51)" onkeyup="return searchResults.Nav(event,51)" class="SRSymbol" href="../class_open_g_l_camera.html#a4b339e7b2f66b3f52c8165784998d2f9" target="_parent">orbit</a>
<span class="SRScope">OpenGLCamera</span>
</div>
</div>
<div class="SRResult" id="SR_outputlogentry">
<div class="SREntry">
<a id="Item52" onkeydown="return searchResults.Nav(event,52)" onkeypress="return searchResults.Nav(event,52)" onkeyup="return searchResults.Nav(event,52)" class="SRSymbol" href="../class_progress_t_s_i.html#a1f4b3464bdfbc84a782c317208c9459b" target="_parent">outputLogEntry</a>
<span class="SRScope">ProgressTSI</span>
</div>
</div>
<div class="SRResult" id="SR_outputrectangles">
<div class="SREntry">
<a id="Item53" onkeydown="return searchResults.Nav(event,53)" onkeypress="return searchResults.Nav(event,53)" onkeyup="return searchResults.Nav(event,53)" class="SRSymbol" href="../arrangebuildtray_8cpp.html#a2bf356a14e81603d07b9895c3a200956" target="_parent">outputRectangles</a>
<span class="SRScope">arrangebuildtray.cpp</span>
</div>
</div>
<div class="SRStatus" id="Searching">Searching...</div>
<div class="SRStatus" id="NoMatches">No Matches</div>
<script type="text/javascript"><!--
document.getElementById("Loading").style.display="none";
document.getElementById("NoMatches").style.display="none";
var searchResults = new SearchResults("searchResults");
searchResults.Search();
--></script>
</div>
</body>
</html>
|
karlgluck/fabathome
|
Documents/html/search/functions_6f.html
|
HTML
|
bsd-3-clause
| 30,203 |
#---
# Excerpted from "Agile Web Development with Rails, 3rd Ed.",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/rails3 for more book information.
#---
class Order < ActiveRecord::Base
PAYMENT_TYPES = [
# Displayed stored in db
[ "Check", "check" ],
[ "Credit card", "cc" ],
[ "Purchase order", "po" ]
]
# ...
validates_presence_of :name, :address, :email, :pay_type
validates_inclusion_of :pay_type, :in =>
PAYMENT_TYPES.map {|disp, value| value}
# ...
has_many :line_items
# ...
def add_line_items_from_cart(cart)
cart.items.each do |item|
li = LineItem.from_cart_item(item)
line_items << li
end
end
end
|
chad/rubinius
|
test/demo/awdwr/app/models/order.rb
|
Ruby
|
bsd-3-clause
| 983 |
# Dockerfile to build an image with the local version of go.mobile.
#
# > docker build -t mobile $GOPATH/src/golang.org/x/mobile
# > docker run -it --rm -v $GOPATH/src:/src mobile
FROM ubuntu:12.04
# Install system-level dependencies.
ENV DEBIAN_FRONTEND noninteractive
RUN echo "debconf shared/accepted-oracle-license-v1-1 select true" | debconf-set-selections && \
echo "debconf shared/accepted-oracle-license-v1-1 seen true" | debconf-set-selections
RUN apt-get update && \
apt-get -y install build-essential python-software-properties bzip2 unzip curl \
git subversion mercurial bzr \
libncurses5:i386 libstdc++6:i386 zlib1g:i386 && \
add-apt-repository ppa:webupd8team/java && \
apt-get update && \
apt-get -y install oracle-java6-installer
# Install Ant.
RUN curl -L http://archive.apache.org/dist/ant/binaries/apache-ant-1.9.2-bin.tar.gz | tar xz -C /usr/local
ENV ANT_HOME /usr/local/apache-ant-1.9.2
# Install Android SDK.
RUN curl -L http://dl.google.com/android/android-sdk_r23.0.2-linux.tgz | tar xz -C /usr/local
ENV ANDROID_HOME /usr/local/android-sdk-linux
RUN echo y | $ANDROID_HOME/tools/android update sdk --no-ui --all --filter build-tools-19.1.0 && \
echo y | $ANDROID_HOME/tools/android update sdk --no-ui --all --filter platform-tools && \
echo y | $ANDROID_HOME/tools/android update sdk --no-ui --all --filter android-19
# Install Android NDK.
RUN curl -L http://dl.google.com/android/ndk/android-ndk-r9d-linux-x86_64.tar.bz2 | tar xj -C /usr/local
ENV NDK_ROOT /usr/local/android-ndk-r9d
RUN $NDK_ROOT/build/tools/make-standalone-toolchain.sh --platform=android-9 --install-dir=$NDK_ROOT --system=linux-x86_64
# Install Gradle 2.1
# : android-gradle compatibility
# http://tools.android.com/tech-docs/new-build-system/version-compatibility
RUN curl -L http://services.gradle.org/distributions/gradle-2.1-all.zip -o /tmp/gradle-2.1-all.zip && unzip /tmp/gradle-2.1-all.zip -d /usr/local && rm /tmp/gradle-2.1-all.zip
ENV GRADLE_HOME /usr/local/gradle-2.1
# Update PATH for the above.
ENV PATH $PATH:$ANDROID_HOME/tools
ENV PATH $PATH:$ANDROID_HOME/platform-tools
ENV PATH $PATH:$NDK_ROOT
ENV PATH $PATH:$ANT_HOME/bin
ENV PATH $PATH:$GRADLE_HOME/bin
# Install Go.
ENV GOROOT /go
ENV GOPATH /
ENV PATH $PATH:$GOROOT/bin
RUN curl -L https://github.com/golang/go/archive/master.zip -o /tmp/go.zip && \
unzip /tmp/go.zip && \
rm /tmp/go.zip && \
mv /go-master $GOROOT && \
echo devel > $GOROOT/VERSION && \
cd $GOROOT/src && \
./all.bash && \
CC_FOR_TARGET=$NDK_ROOT/bin/arm-linux-androideabi-gcc GOOS=android GOARCH=arm GOARM=7 ./make.bash
# Generate a debug keystore to avoid it being generated on each `docker run`
# and fail `adb install -r <apk>` with a conflicting certificate error.
RUN keytool -genkeypair -alias androiddebugkey -keypass android -keystore ~/.android/debug.keystore -storepass android -dname "CN=Android Debug,O=Android,C=US" -validity 365
WORKDIR $GOPATH/src/golang.org/x/mobile
|
grategames/mobile
|
Dockerfile
|
Dockerfile
|
bsd-3-clause
| 2,954 |
{-# LANGUAGE TemplateHaskell #-}
module Reproduce.StandaloneHaddock where
import Lens.Family.TH
data Foo = Foo { _bar :: Int }
makeLenses ''Foo
|
Gabriel439/min-standalone
|
Reproduce/StandaloneHaddock.hs
|
Haskell
|
bsd-3-clause
| 148 |
// 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.
#ifndef MOJO_SYSTEM_CHANNEL_H_
#define MOJO_SYSTEM_CHANNEL_H_
#include <stdint.h>
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/containers/hash_tables.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/string_piece.h"
#include "base/synchronization/lock.h"
#include "base/threading/thread_checker.h"
#include "mojo/public/system/core.h"
#include "mojo/system/embedder/scoped_platform_handle.h"
#include "mojo/system/message_in_transit.h"
#include "mojo/system/message_pipe.h"
#include "mojo/system/raw_channel.h"
#include "mojo/system/system_impl_export.h"
namespace mojo {
namespace system {
// This class is mostly thread-safe. It must be created on an I/O thread.
// |Init()| must be called on that same thread before it becomes thread-safe (in
// particular, before references are given to any other thread) and |Shutdown()|
// must be called on that same thread before destruction. Its public methods are
// otherwise thread-safe. It may be destroyed on any thread, in the sense that
// the last reference to it may be released on any thread, with the proviso that
// |Shutdown()| must have been called first (so the pattern is that a "main"
// reference is kept on its creation thread and is released after |Shutdown()|
// is called, but other threads may have temporarily "dangling" references).
//
// Note that |MessagePipe| calls into |Channel| and the former's |lock_| must be
// acquired before the latter's. When |Channel| wants to call into a
// |MessagePipe|, it must obtain a reference to the |MessagePipe| (from
// |local_id_to_endpoint_info_map_|) under |Channel::lock_| and then release the
// lock.
//
// Also, care must be taken with respect to references: While a |Channel| has
// references to |MessagePipe|s, |MessagePipe|s (via |ProxyMessagePipeEndpoint|)
// may also have references to |Channel|s. These references are set up by
// calling |AttachMessagePipeEndpoint()|. The reference to |MessagePipe| owned
// by |Channel| must be removed by calling |DetachMessagePipeEndpoint()| (which
// is done by |MessagePipe|/|ProxyMessagePipeEndpoint|, which simultaneously
// removes its reference to |Channel|).
class MOJO_SYSTEM_IMPL_EXPORT Channel
: public base::RefCountedThreadSafe<Channel>,
public RawChannel::Delegate {
public:
// The first message pipe endpoint attached will have this as its local ID.
static const MessageInTransit::EndpointId kBootstrapEndpointId = 1;
Channel();
// This must be called on the creation thread before any other methods are
// called, and before references to this object are given to any other
// threads. |handle| should be a handle to a (platform-appropriate)
// bidirectional communication channel (e.g., a socket on POSIX, a named pipe
// on Windows). Returns true on success. On failure, no other methods should
// be called (including |Shutdown()|).
bool Init(embedder::ScopedPlatformHandle handle);
// This must be called on the creation thread before destruction (which can
// happen on any thread).
void Shutdown();
// Attaches the given message pipe/port's endpoint (which must be a
// |ProxyMessagePipeEndpoint|) to this channel. This assigns it a local ID,
// which it returns. The first message pipe endpoint attached will always have
// |kBootstrapEndpointId| as its local ID. (For bootstrapping, this occurs on
// both sides, so one should use |kBootstrapEndpointId| for the remote ID for
// the first message pipe across a channel.)
MessageInTransit::EndpointId AttachMessagePipeEndpoint(
scoped_refptr<MessagePipe> message_pipe, unsigned port);
void RunMessagePipeEndpoint(MessageInTransit::EndpointId local_id,
MessageInTransit::EndpointId remote_id);
// This forwards |message| verbatim to |raw_channel_|.
bool WriteMessage(MessageInTransit* message);
// This removes the message pipe/port's endpoint (with the given local ID,
// returned by |AttachMessagePipeEndpoint()| from this channel. After this is
// called, |local_id| may be reused for another message pipe.
void DetachMessagePipeEndpoint(MessageInTransit::EndpointId local_id);
private:
friend class base::RefCountedThreadSafe<Channel>;
virtual ~Channel();
// |RawChannel::Delegate| implementation:
virtual void OnReadMessage(const MessageInTransit& message) OVERRIDE;
virtual void OnFatalError(FatalError fatal_error) OVERRIDE;
// Helpers for |OnReadMessage|:
void OnReadMessageForDownstream(const MessageInTransit& message);
void OnReadMessageForChannel(const MessageInTransit& message);
// Handles errors (e.g., invalid messages) from the remote side.
void HandleRemoteError(const base::StringPiece& error_message);
// Handles internal errors/failures from the local side.
void HandleLocalError(const base::StringPiece& error_message);
struct EndpointInfo {
EndpointInfo();
EndpointInfo(scoped_refptr<MessagePipe> message_pipe, unsigned port);
~EndpointInfo();
scoped_refptr<MessagePipe> message_pipe;
unsigned port;
};
base::ThreadChecker creation_thread_checker_;
// Note: |MessagePipe|s MUST NOT be used under |lock_|. I.e., |lock_| can only
// be acquired after |MessagePipe::lock_|, never before. Thus to call into a
// |MessagePipe|, a reference should be acquired from
// |local_id_to_endpoint_info_map_| under |lock_| (e.g., by copying the
// |EndpointInfo|) and then the lock released.
base::Lock lock_; // Protects the members below.
scoped_ptr<RawChannel> raw_channel_;
typedef base::hash_map<MessageInTransit::EndpointId, EndpointInfo>
IdToEndpointInfoMap;
IdToEndpointInfoMap local_id_to_endpoint_info_map_;
// The next local ID to try (when allocating new local IDs). Note: It should
// be checked for existence before use.
MessageInTransit::EndpointId next_local_id_;
DISALLOW_COPY_AND_ASSIGN(Channel);
};
} // namespace system
} // namespace mojo
#endif // MOJO_SYSTEM_CHANNEL_H_
|
ChromiumWebApps/chromium
|
mojo/system/channel.h
|
C
|
bsd-3-clause
| 6,196 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Linq.Expressions;
namespace ProjectExtensions.Azure.ServiceBus.Helpers {
//http://rogeralsing.com/2008/02/28/linq-expressions-creating-objects/
delegate object ObjectActivator(params object[] args);
static class ReflectionHelper {
internal static ObjectActivator GetActivator(ConstructorInfo ctor) {
Type type = ctor.DeclaringType;
ParameterInfo[] paramsInfo = ctor.GetParameters();
//create a single param of type object[]
ParameterExpression param =
Expression.Parameter(typeof(object[]), "args");
Expression[] argsExp =
new Expression[paramsInfo.Length];
//pick each arg from the params array
//and create a typed expression of them
for (int i = 0; i < paramsInfo.Length; i++) {
Expression index = Expression.Constant(i);
Type paramType = paramsInfo[i].ParameterType;
Expression paramAccessorExp =
Expression.ArrayIndex(param, index);
Expression paramCastExp =
Expression.Convert(paramAccessorExp, paramType);
argsExp[i] = paramCastExp;
}
//make a NewExpression that calls the
//ctor with the args we just created
NewExpression newExp = Expression.New(ctor, argsExp);
//create a lambda with the New
//Expression as body and our param object[] as arg
LambdaExpression lambda =
Expression.Lambda(typeof(ObjectActivator), newExp, param);
//compile it
ObjectActivator compiled = (ObjectActivator)lambda.Compile();
return compiled;
}
}
}
|
ProjectExtensions/ProjectExtensions.Azure.ServiceBus
|
src/ProjectExtensions.Azure.ServiceBus/Helpers/ReflectionHelper.cs
|
C#
|
bsd-3-clause
| 1,896 |
"""
GNA base class.
"""
__author__ = """\n""".join(['Jeffrey Schmidt ([email protected]',
'Benjamin Bush ([email protected])',
'Hiroki Sayama ([email protected])'])
__all__ = ['openGraphMLNetwork','runGNA','addGraphToReproducedInput', 'addUserExtractions','addDefaultModels',
'initializeRewritingData','findExtractionMechanism']
# Copyright (C) 2012 by
# Jeffrey Schmidt <[email protected]>
# Benjamin Bush <[email protected]>
# Hiroki Sayama <[email protected]>
# All rights reserved.
# BSD license.
import networkx as nx
import copy
import graphMLRead
import NetworkFrames
import Extraction
import Rewriting
import Simulation
import Models
import csv
import CollectData
import Utility
import MotifExtraction
class gna:
def __init__(self, motif=False):
self.networkFrames = NetworkFrames.NetworkFrames()
self.extraction = Extraction.Extraction()
self.motifExtraction = MotifExtraction.MotifExtraction()
self.rewriting = Rewriting.Rewriting()
self.models = Models.Models()
self.utility = Utility.utility()
self.simulation = Simulation.Simulation(self.motifExtraction, self.rewriting, self.utility, self.networkFrames)
self.simulationIterations = 1
def addDefaultModels(self):
"""Adds the default Model objects to the list of models to try during Extraction
Parameters
----------
void
Returns
-------
void
"""
self.models.addDefaultModelsToList()
def addModel(self, model):
"""Adds a Model object to the list of model objects to try during Extraction
Parameters
----------
model : Model object
Model object to be added to the list
Returns
-------
void
"""
self.models.addModel(model)
def addUserExtractions(self, userExtractionClass):
"""Adds user Model objects to the list of model objects to try during Extraction
Parameters
----------
userExtractionClass : user defined class (inherited from userExtractions object)
Contains model objects to be added to the model list
Returns
-------
void
"""
userObject = userExtractionClass()
super(type(userObject),userObject).buildModels()
for model in super(type(userObject),userObject).getModels():
self.addModel(model)
def openGraphMLNetwork(self, path):
"""Reads a graphML file and stores the data in a list of networkx graph objects.
Parameters
----------
path : string path
Path to the graphml file
Returns
-------
void
"""
print "Reading file...",
self.networkFrames.readGraphML(path)
#self.networkFrames.setInputNetwork([self.networkFrames.inputFrames[index] for index in range(9)])
self.networkFrames.setInputNetwork(self.networkFrames.inputFrames)
print "Done"
print "Analyzing dynamics...",
self.networkFrames.compressNetworkFrames()
print "Done."
self.extraction.setNetworkFrames(self.networkFrames)
self.motifExtraction.setNetworkFrames(self.networkFrames)
def findExtractionMechanism(self):
""" Identify the Extraction mechanism in the input data.
Parameters
----------
none
Returns
-------
void
"""
self.extraction.setModels(self.models.getModelList())
self.extraction.generateExtractionSubgraphs()
self.extraction.identifyExtractionDynamics()
def initializeRewritingData(self):
""" Initialize the Rewriting data structures.
Parameters
----------
none
Returns
-------
void
"""
self.rewriting.setNetworkFrames(self.networkFrames)
self.rewriting.initializeRewritingData()
def readExistingData(self, originalPath, generatedPath):
"""Reads existing input and generated data and produces graphical analysis of the two adaptive networks.
Parameters
----------
None
Returns
-------
None
"""
original = NetworkFrames.NetworkFrames()
generated = NetworkFrames.NetworkFrames()
print "Reading original data..."
original.readGraphML(originalPath)
print "Done."
print "Compressing Network Frames in original data..."
original.compressNetworkFrames()
print "Done."
print "Reading generated data..."
generated.readGraphML(generatedPath)
print "Done."
print "Compressing Network Frames in generated data..."
generated.compressNetworkFrames()
print "Done."
print "Displaying Nodes vs. Edge data..."
collectInputData= CollectData.CollectData(original.getInputNetworks(), generated.getInputNetworks())
collectInputData.nodesVSedges()
print "Done."
print "Displaying Dynamics Information..."
collectCompressedData = CollectData.CollectData(original._getCompressedNetworks(), generated._getCompressedNetworks())
collectCompressedData.dynamicsInfo()
print "Done."
def runGNA(self, iterations, motifSize, motif=False, sampleSize=None):
"""Main GNA function that runs the Automaton
Parameters
----------
None
Returns
-------
None
"""
self.simulation.setIterations(iterations)
#self.simulation.runMotifSimulation(motifSize) if motif else self.simulation.runSimulation()
self.simulation.runIterativeMotifSimulation(motifSize, sampleSize) if motif else self.simulation.runSimulation()
import cProfile, pstats, StringIO, time
if __name__ == "__main__":
myGna = gna(True)
query = raw_input("Do you want to process a new file? (Y/N) ")
if query.strip() == "Y" or query.strip() == "y":
path = raw_input("Enter file name: ")
motifSize = int(raw_input("Enter motif size: "))
iterations = input("Enter number of simulation iterations: ")
sampleSize = int(raw_input("Enter sample size: "))
if iterations <= 0:
iterations = 1
myGna.openGraphMLNetwork(path)
start = time.time()
#myGna.motifExtraction.sampleNetwork(motifSize, sampleSize)
elapsed = time.time() - start
print elapsed
#myGna.addDefaultModels()
#myGna.findExtractionMechanism()
#myGna.initializeRewritingData()
myGna.runGNA(iterations, motifSize, True, sampleSize)
else:
path = raw_input("Enter original data file: ")
pathTwo = raw_input("Enter generated data file: ")
myGna.readExistingData(path, pathTwo)
##Profile code:
#pr = cProfile.Profile()
#pr.enable()
#pr.disable()
#s = StringIO.StringIO()
#sortby = 'cumulative'
#ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
#ps.print_stats()
#print s.getvalue()
|
schmidtj/PyGNA
|
PyGNA/gna.py
|
Python
|
bsd-3-clause
| 7,455 |
/*
*
* 25H7912 (C) COPYRIGHT International Business Machines Corp. 1992,1996,1996
* All Rights Reserved
* Licensed Materials - Property of IBM
* US Government Users Restricted Rights - Use, duplication or
* disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
*
* DISCLAIMER OF WARRANTIES.
* The following [enclosed] code is sample code created by IBM
* Corporation. This sample code is not part of any standard or IBM
* product and is provided to you solely for the purpose of assisting
* you in the development of your applications. The code is provided
* "AS IS". IBM MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE, REGARDING THE FUNCTION OR PERFORMANCE OF
* THIS CODE. IBM shall not be liable for any damages arising out of
* your use of the sample code, even if they have been advised of the
* possibility of such damages.
*
* DISTRIBUTION.
* This sample code can be freely distributed, copied, altered, and
* incorporated into other software, provided that it bears the above
* Copyright notice and DISCLAIMER intact.
*
*/
/*
* This file was generated by the SOM Compiler and Emitter Framework.
* Generated using:
* SOM Emitter emitxtm: 2.44
*/
#ifndef SOM_Module_phone_Source
#define SOM_Module_phone_Source
#endif
#define phoneEntry_Class_Source
#include "phone.xih"
/*
* person's name
*/
SOM_Scope string SOMLINK _get_name(phoneEntry *somSelf, Environment *ev)
{
phoneEntryData *somThis = phoneEntryGetData(somSelf);
phoneEntryMethodDebug("phoneEntry","_get_name");
//+
return(strcpy(((string)SOMMalloc(strlen(somThis->name)+1)) ,somThis->name));
//+
}
/*
* person's name
*/
SOM_Scope void SOMLINK _set_name(phoneEntry *somSelf, Environment *ev,
string name)
{
phoneEntryData *somThis = phoneEntryGetData(somSelf);
phoneEntryMethodDebug("phoneEntry","_set_name");
//+
if (somThis->name != NULL)
SOMFree(somThis->name);
somThis->name = (string) SOMMalloc(strlen(name)+1);
if (somThis->name != NULL)
strcpy(somThis->name, name);
//+
}
/*
* person's phone number
*/
SOM_Scope string SOMLINK _get_phone_number(phoneEntry *somSelf,
Environment *ev)
{
phoneEntryData *somThis = phoneEntryGetData(somSelf);
phoneEntryMethodDebug("phoneEntry","_get_phone_number");
//+
return(strcpy(((string)SOMMalloc(strlen(somThis->phone_number)+1)) ,somThis->phone_number));
//+
}
/*
* person's phone number
*/
SOM_Scope void SOMLINK _set_phone_number(phoneEntry *somSelf,
Environment *ev, string phone_number)
{
phoneEntryData *somThis = phoneEntryGetData(somSelf);
phoneEntryMethodDebug("phoneEntry","_set_phone_number");
//+
if (somThis->phone_number != NULL)
SOMFree(somThis->phone_number);
somThis->phone_number = (string) SOMMalloc(strlen(phone_number)+1);
if (somThis->phone_number != NULL)
strcpy(somThis->phone_number, phone_number);
//+
}
SOM_Scope SOMObject* SOMLINK init_for_object_creation(phoneEntry *somSelf,
Environment *ev)
{
//+
SOMObject* newsomSelf;
//+
phoneEntryData *somThis = phoneEntryGetData(somSelf);
phoneEntryMethodDebug("phoneEntry","init_for_object_creation");
phoneEntry_parent_somPersistencePO_PO_init_for_object_creation(somSelf,
ev);
newsomSelf=phoneEntry_parent_somStream_Streamable_init_for_object_creation(somSelf,
ev);
//+
somThis->name = (string)NULL;
somThis->phone_number = (string)NULL;
somThis->office = 0;
return newsomSelf;
//+
}
SOM_Scope SOMObject* SOMLINK init_for_object_reactivation(phoneEntry *somSelf,
Environment *ev)
{
//+
SOMObject* newsomSelf;
//+
phoneEntryData *somThis = phoneEntryGetData(somSelf);
phoneEntryMethodDebug("phoneEntry","init_for_object_reactivation");
phoneEntry_parent_somPersistencePO_PO_init_for_object_reactivation(somSelf,
ev);
newsomSelf=phoneEntry_parent_somStream_Streamable_init_for_object_reactivation(somSelf,
ev);
//+
somThis->name = (string)NULL;
somThis->phone_number = (string)NULL;
somThis->office = 0;
return newsomSelf;
//+
}
SOM_Scope SOMObject* SOMLINK init_for_object_copy(phoneEntry *somSelf,
Environment *ev)
{
//+
SOMObject* newsomSelf;
//+
phoneEntryData *somThis = phoneEntryGetData(somSelf);
phoneEntryMethodDebug("phoneEntry","init_for_object_copy");
phoneEntry_parent_somPersistencePO_PO_init_for_object_copy(somSelf,
ev);
newsomSelf=phoneEntry_parent_somStream_Streamable_init_for_object_copy(somSelf,
ev);
//+
somThis->name = (string)NULL;
somThis->phone_number = (string)NULL;
somThis->office = 0;
return newsomSelf;
//+
}
SOM_Scope void SOMLINK somDestruct(phoneEntry *somSelf, octet doFree,
som3DestructCtrl* ctrl)
{
phoneEntryData *somThis; /* set in BeginDestructor */
somDestructCtrl globalCtrl;
somBooleanVector myMask;
phoneEntryMethodDebug("phoneEntry","somDestruct");
phoneEntry_BeginDestructor;
/*
* local phoneEntry deinitialization code added by programmer
*/
phoneEntry_EndDestructor;
}
SOM_Scope void SOMLINK uninit_for_object_destruction(phoneEntry *somSelf,
Environment *ev)
{
phoneEntryData *somThis = phoneEntryGetData(somSelf);
phoneEntryMethodDebug("phoneEntry","uninit_for_object_destruction");
//+
if (somThis->name != NULL)
{
SOMFree(somThis->name);
somThis->name = NULL;
}
if (somThis->phone_number != NULL)
{
SOMFree(somThis->phone_number);
somThis->phone_number = NULL;
}
//+
phoneEntry_parent_somPersistencePO_PO_uninit_for_object_destruction(somSelf,
ev);
phoneEntry_parent_somStream_Streamable_uninit_for_object_destruction(somSelf,
ev);
}
SOM_Scope void SOMLINK uninit_for_object_passivation(phoneEntry *somSelf,
Environment *ev)
{
phoneEntryData *somThis = phoneEntryGetData(somSelf);
phoneEntryMethodDebug("phoneEntry","uninit_for_object_passivation");
phoneEntry_parent_somPersistencePO_PO_uninit_for_object_passivation(somSelf,
ev);
phoneEntry_parent_somStream_Streamable_uninit_for_object_passivation(somSelf,
ev);
}
SOM_Scope void SOMLINK uninit_for_object_move(phoneEntry *somSelf,
Environment *ev)
{
phoneEntryData *somThis = phoneEntryGetData(somSelf);
phoneEntryMethodDebug("phoneEntry","uninit_for_object_move");
phoneEntry_parent_somPersistencePO_PO_uninit_for_object_move(somSelf,
ev);
phoneEntry_parent_somStream_Streamable_uninit_for_object_move(somSelf,
ev);
}
SOM_Scope void SOMLINK somDumpSelfInt(phoneEntry *somSelf, long level)
{
phoneEntryData *somThis = phoneEntryGetData(somSelf);
phoneEntryMethodDebug("phoneEntry","somDumpSelfInt");
phoneEntry_parent_somPersistencePO_PO_somDumpSelfInt(somSelf,
level);
phoneEntry_parent_somStream_Streamable_somDumpSelfInt(somSelf,
level);
}
SOM_Scope void SOMLINK externalize_to_stream(phoneEntry *somSelf,
Environment *ev,
CosStream_StreamIO* stream)
{
phoneEntryData *somThis = phoneEntryGetData(somSelf);
phoneEntryMethodDebug("phoneEntry","externalize_to_stream");
phoneEntry_parent_somStream_Streamable_externalize_to_stream(somSelf,
ev,
stream);
//+
stream->write_string(ev, somThis->name);
stream->write_string(ev, somThis->phone_number);
stream->write_short(ev, somThis->office);
//+
}
SOM_Scope void SOMLINK internalize_from_stream(phoneEntry *somSelf,
Environment *ev,
CosStream_StreamIO* stream,
CosLifeCycle_FactoryFinder* ff)
{
phoneEntryData *somThis = phoneEntryGetData(somSelf);
phoneEntryMethodDebug("phoneEntry","internalize_from_stream");
phoneEntry_parent_somStream_Streamable_internalize_from_stream(somSelf,
ev,
stream,
ff);
//+
somThis->name = stream->read_string(ev);
somThis->phone_number = stream->read_string(ev);
somThis->office = stream->read_short(ev);
//+
}
|
OS2World/DEV-SAMPLES-SOM-IBM
|
phonedb2/phone.cpp
|
C++
|
bsd-3-clause
| 9,984 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Report;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
class Module {
public function onBootstrap(MvcEvent $e) {
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
}
public function getConfig() {
return include __DIR__ . '/config/module.config.php';
}
public function getAutoloaderConfig() {
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
'Report' => __DIR__ . '/src/Report',
'Marketing' => __DIR__ . '/src/Marketing',
'Finance' => __DIR__ . '/src/Finance',
'Technology' => __DIR__ . '/src/Technology',
),
),
);
}
}
|
u22al/pmrs
|
module/Report/Module.php
|
PHP
|
bsd-3-clause
| 1,215 |
// Copyright 2011 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 "cc/trees/layer_tree_host_impl.h"
#include <algorithm>
#include <cmath>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/containers/hash_tables.h"
#include "base/containers/scoped_ptr_hash_map.h"
#include "base/location.h"
#include "base/thread_task_runner_handle.h"
#include "cc/animation/scrollbar_animation_controller_thinning.h"
#include "cc/animation/transform_operations.h"
#include "cc/base/math_util.h"
#include "cc/input/page_scale_animation.h"
#include "cc/input/top_controls_manager.h"
#include "cc/layers/append_quads_data.h"
#include "cc/layers/delegated_renderer_layer_impl.h"
#include "cc/layers/heads_up_display_layer_impl.h"
#include "cc/layers/io_surface_layer_impl.h"
#include "cc/layers/layer_impl.h"
#include "cc/layers/painted_scrollbar_layer_impl.h"
#include "cc/layers/render_surface_impl.h"
#include "cc/layers/solid_color_layer_impl.h"
#include "cc/layers/solid_color_scrollbar_layer_impl.h"
#include "cc/layers/texture_layer_impl.h"
#include "cc/layers/video_layer_impl.h"
#include "cc/layers/viewport.h"
#include "cc/output/begin_frame_args.h"
#include "cc/output/compositor_frame_ack.h"
#include "cc/output/compositor_frame_metadata.h"
#include "cc/output/copy_output_request.h"
#include "cc/output/copy_output_result.h"
#include "cc/output/gl_renderer.h"
#include "cc/output/latency_info_swap_promise.h"
#include "cc/quads/render_pass_draw_quad.h"
#include "cc/quads/solid_color_draw_quad.h"
#include "cc/quads/texture_draw_quad.h"
#include "cc/quads/tile_draw_quad.h"
#include "cc/test/animation_test_common.h"
#include "cc/test/begin_frame_args_test.h"
#include "cc/test/fake_layer_tree_host_impl.h"
#include "cc/test/fake_output_surface.h"
#include "cc/test/fake_output_surface_client.h"
#include "cc/test/fake_picture_layer_impl.h"
#include "cc/test/fake_picture_pile_impl.h"
#include "cc/test/fake_proxy.h"
#include "cc/test/fake_video_frame_provider.h"
#include "cc/test/geometry_test_utils.h"
#include "cc/test/gpu_rasterization_enabled_settings.h"
#include "cc/test/layer_test_common.h"
#include "cc/test/layer_tree_test.h"
#include "cc/test/test_gpu_memory_buffer_manager.h"
#include "cc/test/test_shared_bitmap_manager.h"
#include "cc/test/test_task_graph_runner.h"
#include "cc/test/test_web_graphics_context_3d.h"
#include "cc/trees/layer_tree_impl.h"
#include "cc/trees/single_thread_proxy.h"
#include "media/base/media.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkMallocPixelRef.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/size_conversions.h"
#include "ui/gfx/geometry/vector2d_conversions.h"
using ::testing::Mock;
using ::testing::Return;
using ::testing::AnyNumber;
using ::testing::AtLeast;
using ::testing::_;
using media::VideoFrame;
namespace cc {
namespace {
class LayerTreeHostImplTest : public testing::Test,
public LayerTreeHostImplClient {
public:
LayerTreeHostImplTest()
: proxy_(base::ThreadTaskRunnerHandle::Get(),
base::ThreadTaskRunnerHandle::Get()),
always_impl_thread_(&proxy_),
always_main_thread_blocked_(&proxy_),
on_can_draw_state_changed_called_(false),
did_notify_ready_to_activate_(false),
did_request_commit_(false),
did_request_redraw_(false),
did_request_animate_(false),
did_request_prepare_tiles_(false),
did_complete_page_scale_animation_(false),
reduce_memory_result_(true) {
media::InitializeMediaLibrary();
}
LayerTreeSettings DefaultSettings() {
LayerTreeSettings settings;
settings.minimum_occlusion_tracking_size = gfx::Size();
settings.renderer_settings.texture_id_allocation_chunk_size = 1;
settings.gpu_rasterization_enabled = true;
return settings;
}
void SetUp() override {
CreateHostImpl(DefaultSettings(), CreateOutputSurface());
}
void TearDown() override {}
void UpdateRendererCapabilitiesOnImplThread() override {}
void DidLoseOutputSurfaceOnImplThread() override {}
void CommitVSyncParameters(base::TimeTicks timebase,
base::TimeDelta interval) override {}
void SetEstimatedParentDrawTime(base::TimeDelta draw_time) override {}
void SetMaxSwapsPendingOnImplThread(int max) override {}
void DidSwapBuffersOnImplThread() override {}
void DidSwapBuffersCompleteOnImplThread() override {}
void OnCanDrawStateChanged(bool can_draw) override {
on_can_draw_state_changed_called_ = true;
}
void NotifyReadyToActivate() override {
did_notify_ready_to_activate_ = true;
host_impl_->ActivateSyncTree();
}
void NotifyReadyToDraw() override {}
void SetNeedsRedrawOnImplThread() override { did_request_redraw_ = true; }
void SetNeedsRedrawRectOnImplThread(const gfx::Rect& damage_rect) override {
did_request_redraw_ = true;
}
void SetNeedsAnimateOnImplThread() override { did_request_animate_ = true; }
void SetNeedsPrepareTilesOnImplThread() override {
did_request_prepare_tiles_ = true;
}
void SetNeedsCommitOnImplThread() override { did_request_commit_ = true; }
void SetVideoNeedsBeginFrames(bool needs_begin_frames) override {}
void PostAnimationEventsToMainThreadOnImplThread(
scoped_ptr<AnimationEventsVector> events) override {}
bool IsInsideDraw() override { return false; }
void RenewTreePriority() override {}
void PostDelayedAnimationTaskOnImplThread(const base::Closure& task,
base::TimeDelta delay) override {
animation_task_ = task;
requested_animation_delay_ = delay;
}
void DidActivateSyncTree() override {}
void WillPrepareTiles() override {}
void DidPrepareTiles() override {}
void DidCompletePageScaleAnimationOnImplThread() override {
did_complete_page_scale_animation_ = true;
}
void OnDrawForOutputSurface() override {}
void PostFrameTimingEventsOnImplThread(
scoped_ptr<FrameTimingTracker::CompositeTimingSet> composite_events,
scoped_ptr<FrameTimingTracker::MainFrameTimingSet> main_frame_events)
override {}
void set_reduce_memory_result(bool reduce_memory_result) {
reduce_memory_result_ = reduce_memory_result;
}
virtual bool CreateHostImpl(const LayerTreeSettings& settings,
scoped_ptr<OutputSurface> output_surface) {
host_impl_ = LayerTreeHostImpl::Create(
settings, this, &proxy_, &stats_instrumentation_,
&shared_bitmap_manager_, &gpu_memory_buffer_manager_,
&task_graph_runner_, 0);
bool init = host_impl_->InitializeRenderer(output_surface.Pass());
host_impl_->SetViewportSize(gfx::Size(10, 10));
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, 1.f, 1.f);
// Set the BeginFrameArgs so that methods which use it are able to.
host_impl_->WillBeginImplFrame(CreateBeginFrameArgsForTesting(
BEGINFRAME_FROM_HERE,
base::TimeTicks() + base::TimeDelta::FromMilliseconds(1)));
host_impl_->DidFinishImplFrame();
return init;
}
void SetupRootLayerImpl(scoped_ptr<LayerImpl> root) {
root->SetPosition(gfx::PointF());
root->SetBounds(gfx::Size(10, 10));
root->SetDrawsContent(true);
root->draw_properties().visible_layer_rect = gfx::Rect(0, 0, 10, 10);
root->SetHasRenderSurface(true);
host_impl_->active_tree()->SetRootLayer(root.Pass());
}
static void ExpectClearedScrollDeltasRecursive(LayerImpl* layer) {
ASSERT_EQ(layer->ScrollDelta(), gfx::Vector2d());
for (size_t i = 0; i < layer->children().size(); ++i)
ExpectClearedScrollDeltasRecursive(layer->children()[i]);
}
static ::testing::AssertionResult ScrollInfoContains(
const ScrollAndScaleSet& scroll_info,
int id,
const gfx::Vector2d& scroll_delta) {
int times_encountered = 0;
for (size_t i = 0; i < scroll_info.scrolls.size(); ++i) {
if (scroll_info.scrolls[i].layer_id != id)
continue;
if (scroll_delta != scroll_info.scrolls[i].scroll_delta) {
return ::testing::AssertionFailure()
<< "Expected " << scroll_delta.ToString() << ", not "
<< scroll_info.scrolls[i].scroll_delta.ToString();
}
times_encountered++;
}
if (times_encountered != 1)
return ::testing::AssertionFailure() << "No layer found with id " << id;
return ::testing::AssertionSuccess();
}
static void ExpectNone(const ScrollAndScaleSet& scroll_info, int id) {
int times_encountered = 0;
for (size_t i = 0; i < scroll_info.scrolls.size(); ++i) {
if (scroll_info.scrolls[i].layer_id != id)
continue;
times_encountered++;
}
ASSERT_EQ(0, times_encountered);
}
LayerImpl* CreateScrollAndContentsLayers(LayerTreeImpl* layer_tree_impl,
const gfx::Size& content_size) {
// Create both an inner viewport scroll layer and an outer viewport scroll
// layer. The MaxScrollOffset of the outer viewport scroll layer will be
// 0x0, so the scrolls will be applied directly to the inner viewport.
const int kOuterViewportClipLayerId = 116;
const int kOuterViewportScrollLayerId = 117;
const int kContentLayerId = 118;
const int kInnerViewportScrollLayerId = 2;
const int kInnerViewportClipLayerId = 4;
const int kPageScaleLayerId = 5;
scoped_ptr<LayerImpl> root =
LayerImpl::Create(layer_tree_impl, 1);
root->SetBounds(content_size);
root->SetPosition(gfx::PointF());
root->SetHasRenderSurface(true);
scoped_ptr<LayerImpl> inner_scroll =
LayerImpl::Create(layer_tree_impl, kInnerViewportScrollLayerId);
inner_scroll->SetIsContainerForFixedPositionLayers(true);
inner_scroll->PushScrollOffsetFromMainThread(gfx::ScrollOffset());
scoped_ptr<LayerImpl> inner_clip =
LayerImpl::Create(layer_tree_impl, kInnerViewportClipLayerId);
inner_clip->SetBounds(
gfx::Size(content_size.width() / 2, content_size.height() / 2));
scoped_ptr<LayerImpl> page_scale =
LayerImpl::Create(layer_tree_impl, kPageScaleLayerId);
inner_scroll->SetScrollClipLayer(inner_clip->id());
inner_scroll->SetBounds(content_size);
inner_scroll->SetPosition(gfx::PointF());
scoped_ptr<LayerImpl> outer_clip =
LayerImpl::Create(layer_tree_impl, kOuterViewportClipLayerId);
outer_clip->SetBounds(content_size);
outer_clip->SetIsContainerForFixedPositionLayers(true);
scoped_ptr<LayerImpl> outer_scroll =
LayerImpl::Create(layer_tree_impl, kOuterViewportScrollLayerId);
outer_scroll->SetScrollClipLayer(outer_clip->id());
outer_scroll->PushScrollOffsetFromMainThread(gfx::ScrollOffset());
outer_scroll->SetBounds(content_size);
outer_scroll->SetPosition(gfx::PointF());
scoped_ptr<LayerImpl> contents =
LayerImpl::Create(layer_tree_impl, kContentLayerId);
contents->SetDrawsContent(true);
contents->SetBounds(content_size);
contents->SetPosition(gfx::PointF());
outer_scroll->AddChild(contents.Pass());
outer_clip->AddChild(outer_scroll.Pass());
inner_scroll->AddChild(outer_clip.Pass());
page_scale->AddChild(inner_scroll.Pass());
inner_clip->AddChild(page_scale.Pass());
root->AddChild(inner_clip.Pass());
layer_tree_impl->SetRootLayer(root.Pass());
layer_tree_impl->SetViewportLayersFromIds(
Layer::INVALID_ID, kPageScaleLayerId, kInnerViewportScrollLayerId,
kOuterViewportScrollLayerId);
layer_tree_impl->DidBecomeActive();
return layer_tree_impl->InnerViewportScrollLayer();
}
LayerImpl* SetupScrollAndContentsLayers(const gfx::Size& content_size) {
LayerImpl* scroll_layer = CreateScrollAndContentsLayers(
host_impl_->active_tree(), content_size);
host_impl_->active_tree()->DidBecomeActive();
return scroll_layer;
}
// Sets up a typical virtual viewport setup with one child content layer.
// Returns a pointer to the content layer.
LayerImpl* CreateBasicVirtualViewportLayers(const gfx::Size& viewport_size,
const gfx::Size& content_size) {
// CreateScrollAndContentsLayers makes the outer viewport unscrollable and
// the inner a different size from the outer. We'll reuse its layer
// hierarchy but adjust the sizing to our needs.
CreateScrollAndContentsLayers(host_impl_->active_tree(), content_size);
LayerImpl* content_layer =
host_impl_->OuterViewportScrollLayer()->children().back();
content_layer->SetBounds(content_size);
host_impl_->OuterViewportScrollLayer()->SetBounds(content_size);
LayerImpl* outer_clip = host_impl_->OuterViewportScrollLayer()->parent();
outer_clip->SetBounds(viewport_size);
LayerImpl* inner_clip_layer =
host_impl_->InnerViewportScrollLayer()->parent()->parent();
inner_clip_layer->SetBounds(viewport_size);
host_impl_->InnerViewportScrollLayer()->SetBounds(viewport_size);
host_impl_->SetViewportSize(viewport_size);
host_impl_->active_tree()->DidBecomeActive();
return content_layer;
}
scoped_ptr<LayerImpl> CreateScrollableLayer(int id,
const gfx::Size& size,
LayerImpl* clip_layer) {
DCHECK(clip_layer);
DCHECK(id != clip_layer->id());
scoped_ptr<LayerImpl> layer =
LayerImpl::Create(host_impl_->active_tree(), id);
layer->SetScrollClipLayer(clip_layer->id());
layer->SetDrawsContent(true);
layer->SetBounds(size);
clip_layer->SetBounds(gfx::Size(size.width() / 2, size.height() / 2));
return layer.Pass();
}
void DrawFrame() {
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
}
void pinch_zoom_pan_viewport_forces_commit_redraw(float device_scale_factor);
void pinch_zoom_pan_viewport_test(float device_scale_factor);
void pinch_zoom_pan_viewport_and_scroll_test(float device_scale_factor);
void pinch_zoom_pan_viewport_and_scroll_boundary_test(
float device_scale_factor);
void CheckNotifyCalledIfCanDrawChanged(bool always_draw) {
// Note: It is not possible to disable the renderer once it has been set,
// so we do not need to test that disabling the renderer notifies us
// that can_draw changed.
EXPECT_FALSE(host_impl_->CanDraw());
on_can_draw_state_changed_called_ = false;
// Set up the root layer, which allows us to draw.
SetupScrollAndContentsLayers(gfx::Size(100, 100));
EXPECT_TRUE(host_impl_->CanDraw());
EXPECT_TRUE(on_can_draw_state_changed_called_);
on_can_draw_state_changed_called_ = false;
// Toggle the root layer to make sure it toggles can_draw
host_impl_->active_tree()->SetRootLayer(nullptr);
EXPECT_FALSE(host_impl_->CanDraw());
EXPECT_TRUE(on_can_draw_state_changed_called_);
on_can_draw_state_changed_called_ = false;
SetupScrollAndContentsLayers(gfx::Size(100, 100));
EXPECT_TRUE(host_impl_->CanDraw());
EXPECT_TRUE(on_can_draw_state_changed_called_);
on_can_draw_state_changed_called_ = false;
// Toggle the device viewport size to make sure it toggles can_draw.
host_impl_->SetViewportSize(gfx::Size());
if (always_draw) {
EXPECT_TRUE(host_impl_->CanDraw());
} else {
EXPECT_FALSE(host_impl_->CanDraw());
}
EXPECT_TRUE(on_can_draw_state_changed_called_);
on_can_draw_state_changed_called_ = false;
host_impl_->SetViewportSize(gfx::Size(100, 100));
EXPECT_TRUE(host_impl_->CanDraw());
EXPECT_TRUE(on_can_draw_state_changed_called_);
on_can_draw_state_changed_called_ = false;
}
void SetupMouseMoveAtWithDeviceScale(float device_scale_factor);
protected:
virtual scoped_ptr<OutputSurface> CreateOutputSurface() {
return FakeOutputSurface::Create3d();
}
void DrawOneFrame() {
LayerTreeHostImpl::FrameData frame_data;
host_impl_->PrepareToDraw(&frame_data);
host_impl_->DidDrawAllLayers(frame_data);
}
FakeProxy proxy_;
DebugScopedSetImplThread always_impl_thread_;
DebugScopedSetMainThreadBlocked always_main_thread_blocked_;
TestSharedBitmapManager shared_bitmap_manager_;
TestGpuMemoryBufferManager gpu_memory_buffer_manager_;
TestTaskGraphRunner task_graph_runner_;
scoped_ptr<LayerTreeHostImpl> host_impl_;
FakeRenderingStatsInstrumentation stats_instrumentation_;
bool on_can_draw_state_changed_called_;
bool did_notify_ready_to_activate_;
bool did_request_commit_;
bool did_request_redraw_;
bool did_request_animate_;
bool did_request_prepare_tiles_;
bool did_complete_page_scale_animation_;
bool reduce_memory_result_;
base::Closure animation_task_;
base::TimeDelta requested_animation_delay_;
};
// A test fixture for new animation timelines tests.
class LayerTreeHostImplTimelinesTest : public LayerTreeHostImplTest {
public:
void SetUp() override {
LayerTreeSettings settings = DefaultSettings();
settings.use_compositor_animation_timelines = true;
CreateHostImpl(settings, CreateOutputSurface());
}
};
TEST_F(LayerTreeHostImplTest, NotifyIfCanDrawChanged) {
bool always_draw = false;
CheckNotifyCalledIfCanDrawChanged(always_draw);
}
TEST_F(LayerTreeHostImplTest, CanDrawIncompleteFrames) {
CreateHostImpl(DefaultSettings(),
FakeOutputSurface::CreateAlwaysDrawAndSwap3d());
bool always_draw = true;
CheckNotifyCalledIfCanDrawChanged(always_draw);
}
TEST_F(LayerTreeHostImplTest, ScrollDeltaNoLayers) {
ASSERT_FALSE(host_impl_->active_tree()->root_layer());
scoped_ptr<ScrollAndScaleSet> scroll_info = host_impl_->ProcessScrollDeltas();
ASSERT_EQ(scroll_info->scrolls.size(), 0u);
}
TEST_F(LayerTreeHostImplTest, ScrollDeltaTreeButNoChanges) {
{
scoped_ptr<LayerImpl> root =
LayerImpl::Create(host_impl_->active_tree(), 1);
root->AddChild(LayerImpl::Create(host_impl_->active_tree(), 2));
root->AddChild(LayerImpl::Create(host_impl_->active_tree(), 3));
root->children()[1]->AddChild(
LayerImpl::Create(host_impl_->active_tree(), 4));
root->children()[1]->AddChild(
LayerImpl::Create(host_impl_->active_tree(), 5));
root->children()[1]->children()[0]->AddChild(
LayerImpl::Create(host_impl_->active_tree(), 6));
host_impl_->active_tree()->SetRootLayer(root.Pass());
}
LayerImpl* root = host_impl_->active_tree()->root_layer();
ExpectClearedScrollDeltasRecursive(root);
scoped_ptr<ScrollAndScaleSet> scroll_info;
scroll_info = host_impl_->ProcessScrollDeltas();
ASSERT_EQ(scroll_info->scrolls.size(), 0u);
ExpectClearedScrollDeltasRecursive(root);
scroll_info = host_impl_->ProcessScrollDeltas();
ASSERT_EQ(scroll_info->scrolls.size(), 0u);
ExpectClearedScrollDeltasRecursive(root);
}
TEST_F(LayerTreeHostImplTest, ScrollDeltaRepeatedScrolls) {
gfx::ScrollOffset scroll_offset(20, 30);
gfx::Vector2d scroll_delta(11, -15);
{
scoped_ptr<LayerImpl> root_clip =
LayerImpl::Create(host_impl_->active_tree(), 2);
scoped_ptr<LayerImpl> root =
LayerImpl::Create(host_impl_->active_tree(), 1);
root_clip->SetBounds(gfx::Size(10, 10));
LayerImpl* root_layer = root.get();
root_clip->AddChild(root.Pass());
root_layer->SetBounds(gfx::Size(110, 110));
root_layer->SetScrollClipLayer(root_clip->id());
root_layer->PushScrollOffsetFromMainThread(scroll_offset);
root_layer->ScrollBy(scroll_delta);
host_impl_->active_tree()->SetRootLayer(root_clip.Pass());
}
LayerImpl* root = host_impl_->active_tree()->root_layer()->children()[0];
scoped_ptr<ScrollAndScaleSet> scroll_info;
scroll_info = host_impl_->ProcessScrollDeltas();
ASSERT_EQ(scroll_info->scrolls.size(), 1u);
EXPECT_TRUE(ScrollInfoContains(*scroll_info, root->id(), scroll_delta));
gfx::Vector2d scroll_delta2(-5, 27);
root->ScrollBy(scroll_delta2);
scroll_info = host_impl_->ProcessScrollDeltas();
ASSERT_EQ(scroll_info->scrolls.size(), 1u);
EXPECT_TRUE(ScrollInfoContains(*scroll_info, root->id(),
scroll_delta + scroll_delta2));
root->ScrollBy(gfx::Vector2d());
scroll_info = host_impl_->ProcessScrollDeltas();
EXPECT_TRUE(ScrollInfoContains(*scroll_info, root->id(),
scroll_delta + scroll_delta2));
}
TEST_F(LayerTreeHostImplTest, ScrollRootCallsCommitAndRedraw) {
SetupScrollAndContentsLayers(gfx::Size(100, 100));
host_impl_->SetViewportSize(gfx::Size(50, 50));
DrawFrame();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
EXPECT_TRUE(host_impl_->IsCurrentlyScrollingLayerAt(gfx::Point(),
InputHandler::WHEEL));
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, 10));
EXPECT_TRUE(host_impl_->IsCurrentlyScrollingLayerAt(gfx::Point(0, 10),
InputHandler::WHEEL));
host_impl_->ScrollEnd();
EXPECT_FALSE(host_impl_->IsCurrentlyScrollingLayerAt(gfx::Point(),
InputHandler::WHEEL));
EXPECT_TRUE(did_request_redraw_);
EXPECT_TRUE(did_request_commit_);
}
TEST_F(LayerTreeHostImplTest, ScrollActiveOnlyAfterScrollMovement) {
SetupScrollAndContentsLayers(gfx::Size(100, 100));
host_impl_->SetViewportSize(gfx::Size(50, 50));
DrawFrame();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
EXPECT_FALSE(host_impl_->IsActivelyScrolling());
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, 10));
EXPECT_TRUE(host_impl_->IsActivelyScrolling());
host_impl_->ScrollEnd();
EXPECT_FALSE(host_impl_->IsActivelyScrolling());
}
TEST_F(LayerTreeHostImplTest, ScrollWithoutRootLayer) {
// We should not crash when trying to scroll an empty layer tree.
EXPECT_EQ(InputHandler::SCROLL_IGNORED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
}
TEST_F(LayerTreeHostImplTest, ScrollWithoutRenderer) {
scoped_ptr<TestWebGraphicsContext3D> context_owned =
TestWebGraphicsContext3D::Create();
context_owned->set_context_lost(true);
// Initialization will fail.
EXPECT_FALSE(CreateHostImpl(
DefaultSettings(), FakeOutputSurface::Create3d(context_owned.Pass())));
SetupScrollAndContentsLayers(gfx::Size(100, 100));
// We should not crash when trying to scroll after the renderer initialization
// fails.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
}
TEST_F(LayerTreeHostImplTest, ReplaceTreeWhileScrolling) {
LayerImpl* scroll_layer = SetupScrollAndContentsLayers(gfx::Size(100, 100));
host_impl_->SetViewportSize(gfx::Size(50, 50));
DrawFrame();
// We should not crash if the tree is replaced while we are scrolling.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
host_impl_->active_tree()->DetachLayerTree();
scroll_layer = SetupScrollAndContentsLayers(gfx::Size(100, 100));
// We should still be scrolling, because the scrolled layer also exists in the
// new tree.
gfx::Vector2d scroll_delta(0, 10);
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
host_impl_->ScrollEnd();
scoped_ptr<ScrollAndScaleSet> scroll_info = host_impl_->ProcessScrollDeltas();
EXPECT_TRUE(
ScrollInfoContains(*scroll_info, scroll_layer->id(), scroll_delta));
}
TEST_F(LayerTreeHostImplTest, ScrollBlocksOnWheelEventHandlers) {
SetupScrollAndContentsLayers(gfx::Size(100, 100));
host_impl_->SetViewportSize(gfx::Size(50, 50));
DrawFrame();
LayerImpl* root = host_impl_->active_tree()->root_layer();
// With registered event handlers, wheel scrolls don't necessarily
// have to go to the main thread.
root->SetHaveWheelEventHandlers(true);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
host_impl_->ScrollEnd();
// But typically the scroll-blocks-on mode will require them to.
root->SetScrollBlocksOn(SCROLL_BLOCKS_ON_WHEEL_EVENT |
SCROLL_BLOCKS_ON_START_TOUCH);
EXPECT_EQ(InputHandler::SCROLL_ON_MAIN_THREAD,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
// But gesture scrolls can still be handled.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
host_impl_->ScrollEnd();
// And if the handlers go away, wheel scrolls can again be processed
// on impl (despite the scroll-blocks-on mode).
root->SetHaveWheelEventHandlers(false);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
host_impl_->ScrollEnd();
}
TEST_F(LayerTreeHostImplTest, ScrollBlocksOnTouchEventHandlers) {
LayerImpl* scroll = SetupScrollAndContentsLayers(gfx::Size(100, 100));
host_impl_->SetViewportSize(gfx::Size(50, 50));
DrawFrame();
LayerImpl* root = host_impl_->active_tree()->root_layer();
LayerImpl* child = 0;
{
scoped_ptr<LayerImpl> child_layer =
LayerImpl::Create(host_impl_->active_tree(), 6);
child = child_layer.get();
child_layer->SetDrawsContent(true);
child_layer->SetPosition(gfx::PointF(0, 20));
child_layer->SetBounds(gfx::Size(50, 50));
scroll->AddChild(child_layer.Pass());
}
// Touch handler regions determine whether touch events block scroll.
root->SetTouchEventHandlerRegion(gfx::Rect(0, 0, 100, 100));
EXPECT_FALSE(host_impl_->DoTouchEventsBlockScrollAt(gfx::Point(10, 10)));
root->SetScrollBlocksOn(SCROLL_BLOCKS_ON_START_TOUCH |
SCROLL_BLOCKS_ON_WHEEL_EVENT);
EXPECT_TRUE(host_impl_->DoTouchEventsBlockScrollAt(gfx::Point(10, 10)));
// But they don't influence the actual handling of the scroll gestures.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
host_impl_->ScrollEnd();
// It's the union of scroll-blocks-on mode bits across all layers in the
// scroll paret chain that matters.
EXPECT_TRUE(host_impl_->DoTouchEventsBlockScrollAt(gfx::Point(10, 30)));
root->SetScrollBlocksOn(SCROLL_BLOCKS_ON_NONE);
EXPECT_FALSE(host_impl_->DoTouchEventsBlockScrollAt(gfx::Point(10, 30)));
child->SetScrollBlocksOn(SCROLL_BLOCKS_ON_START_TOUCH);
EXPECT_TRUE(host_impl_->DoTouchEventsBlockScrollAt(gfx::Point(10, 30)));
}
TEST_F(LayerTreeHostImplTest, ScrollBlocksOnScrollEventHandlers) {
SetupScrollAndContentsLayers(gfx::Size(100, 100));
host_impl_->SetViewportSize(gfx::Size(50, 50));
DrawFrame();
LayerImpl* root = host_impl_->active_tree()->root_layer();
// With registered scroll handlers, scrolls don't generally have to go
// to the main thread.
root->SetHaveScrollEventHandlers(true);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
host_impl_->ScrollEnd();
// Even the default scroll blocks on mode doesn't require this.
root->SetScrollBlocksOn(SCROLL_BLOCKS_ON_WHEEL_EVENT |
SCROLL_BLOCKS_ON_START_TOUCH);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
host_impl_->ScrollEnd();
// But the page can opt in to blocking on scroll event handlers.
root->SetScrollBlocksOn(SCROLL_BLOCKS_ON_SCROLL_EVENT);
EXPECT_EQ(InputHandler::SCROLL_ON_MAIN_THREAD,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
// GESTURE and WHEEL scrolls behave identically in this regard.
EXPECT_EQ(InputHandler::SCROLL_ON_MAIN_THREAD,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
// And if the handlers go away, scrolls can again be processed on impl
// (despite the scroll-blocks-on mode).
root->SetHaveScrollEventHandlers(false);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
host_impl_->ScrollEnd();
}
TEST_F(LayerTreeHostImplTest, ScrollBlocksOnLayerTopology) {
host_impl_->SetViewportSize(gfx::Size(50, 50));
// Create a normal scrollable root layer
LayerImpl* root_scroll = SetupScrollAndContentsLayers(gfx::Size(100, 100));
LayerImpl* root_child = root_scroll->children()[0];
LayerImpl* root = host_impl_->active_tree()->root_layer();
DrawFrame();
// Create two child scrollable layers
LayerImpl* child1 = 0;
{
scoped_ptr<LayerImpl> scrollable_child_clip_1 =
LayerImpl::Create(host_impl_->active_tree(), 6);
scoped_ptr<LayerImpl> scrollable_child_1 = CreateScrollableLayer(
7, gfx::Size(10, 10), scrollable_child_clip_1.get());
child1 = scrollable_child_1.get();
scrollable_child_1->SetPosition(gfx::Point(5, 5));
scrollable_child_1->SetHaveWheelEventHandlers(true);
scrollable_child_1->SetHaveScrollEventHandlers(true);
scrollable_child_clip_1->AddChild(scrollable_child_1.Pass());
root_child->AddChild(scrollable_child_clip_1.Pass());
}
LayerImpl* child2 = 0;
{
scoped_ptr<LayerImpl> scrollable_child_clip_2 =
LayerImpl::Create(host_impl_->active_tree(), 8);
scoped_ptr<LayerImpl> scrollable_child_2 = CreateScrollableLayer(
9, gfx::Size(10, 10), scrollable_child_clip_2.get());
child2 = scrollable_child_2.get();
scrollable_child_2->SetPosition(gfx::Point(5, 20));
scrollable_child_2->SetHaveWheelEventHandlers(true);
scrollable_child_2->SetHaveScrollEventHandlers(true);
scrollable_child_clip_2->AddChild(scrollable_child_2.Pass());
root_child->AddChild(scrollable_child_clip_2.Pass());
}
// Scroll-blocks-on on a layer affects scrolls that hit that layer.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(10, 10), InputHandler::GESTURE));
host_impl_->ScrollEnd();
child1->SetScrollBlocksOn(SCROLL_BLOCKS_ON_SCROLL_EVENT);
EXPECT_EQ(InputHandler::SCROLL_ON_MAIN_THREAD,
host_impl_->ScrollBegin(gfx::Point(10, 10), InputHandler::GESTURE));
// But not those that hit only other layers.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(10, 25), InputHandler::GESTURE));
host_impl_->ScrollEnd();
// It's the union of bits set across the scroll ancestor chain that matters.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(10, 25), InputHandler::GESTURE));
host_impl_->ScrollEnd();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(10, 25), InputHandler::WHEEL));
host_impl_->ScrollEnd();
root->SetScrollBlocksOn(SCROLL_BLOCKS_ON_WHEEL_EVENT);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(10, 25), InputHandler::GESTURE));
host_impl_->ScrollEnd();
EXPECT_EQ(InputHandler::SCROLL_ON_MAIN_THREAD,
host_impl_->ScrollBegin(gfx::Point(10, 25), InputHandler::WHEEL));
child2->SetScrollBlocksOn(SCROLL_BLOCKS_ON_SCROLL_EVENT);
EXPECT_EQ(InputHandler::SCROLL_ON_MAIN_THREAD,
host_impl_->ScrollBegin(gfx::Point(10, 25), InputHandler::WHEEL));
EXPECT_EQ(InputHandler::SCROLL_ON_MAIN_THREAD,
host_impl_->ScrollBegin(gfx::Point(10, 25), InputHandler::GESTURE));
}
TEST_F(LayerTreeHostImplTest, FlingOnlyWhenScrollingTouchscreen) {
SetupScrollAndContentsLayers(gfx::Size(100, 100));
host_impl_->SetViewportSize(gfx::Size(50, 50));
DrawFrame();
// Ignore the fling since no layer is being scrolled
EXPECT_EQ(InputHandler::SCROLL_IGNORED, host_impl_->FlingScrollBegin());
// Start scrolling a layer
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
// Now the fling should go ahead since we've started scrolling a layer
EXPECT_EQ(InputHandler::SCROLL_STARTED, host_impl_->FlingScrollBegin());
}
TEST_F(LayerTreeHostImplTest, FlingOnlyWhenScrollingTouchpad) {
SetupScrollAndContentsLayers(gfx::Size(100, 100));
host_impl_->SetViewportSize(gfx::Size(50, 50));
DrawFrame();
// Ignore the fling since no layer is being scrolled
EXPECT_EQ(InputHandler::SCROLL_IGNORED, host_impl_->FlingScrollBegin());
// Start scrolling a layer
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
// Now the fling should go ahead since we've started scrolling a layer
EXPECT_EQ(InputHandler::SCROLL_STARTED, host_impl_->FlingScrollBegin());
}
TEST_F(LayerTreeHostImplTest, NoFlingWhenScrollingOnMain) {
SetupScrollAndContentsLayers(gfx::Size(100, 100));
host_impl_->SetViewportSize(gfx::Size(50, 50));
DrawFrame();
LayerImpl* root = host_impl_->active_tree()->root_layer();
root->SetShouldScrollOnMainThread(true);
// Start scrolling a layer
EXPECT_EQ(InputHandler::SCROLL_ON_MAIN_THREAD,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
// The fling should be ignored since there's no layer being scrolled impl-side
EXPECT_EQ(InputHandler::SCROLL_IGNORED, host_impl_->FlingScrollBegin());
}
TEST_F(LayerTreeHostImplTest, ShouldScrollOnMainThread) {
SetupScrollAndContentsLayers(gfx::Size(100, 100));
host_impl_->SetViewportSize(gfx::Size(50, 50));
DrawFrame();
LayerImpl* root = host_impl_->active_tree()->root_layer();
root->SetShouldScrollOnMainThread(true);
EXPECT_EQ(InputHandler::SCROLL_ON_MAIN_THREAD,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
EXPECT_EQ(InputHandler::SCROLL_ON_MAIN_THREAD,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
}
TEST_F(LayerTreeHostImplTest, NonFastScrollableRegionBasic) {
SetupScrollAndContentsLayers(gfx::Size(200, 200));
host_impl_->SetViewportSize(gfx::Size(100, 100));
LayerImpl* root = host_impl_->active_tree()->root_layer();
root->SetNonFastScrollableRegion(gfx::Rect(0, 0, 50, 50));
DrawFrame();
// All scroll types inside the non-fast scrollable region should fail.
EXPECT_EQ(InputHandler::SCROLL_ON_MAIN_THREAD,
host_impl_->ScrollBegin(gfx::Point(25, 25), InputHandler::WHEEL));
EXPECT_FALSE(host_impl_->IsCurrentlyScrollingLayerAt(gfx::Point(25, 25),
InputHandler::WHEEL));
EXPECT_EQ(InputHandler::SCROLL_ON_MAIN_THREAD,
host_impl_->ScrollBegin(gfx::Point(25, 25), InputHandler::GESTURE));
EXPECT_FALSE(host_impl_->IsCurrentlyScrollingLayerAt(gfx::Point(25, 25),
InputHandler::GESTURE));
// All scroll types outside this region should succeed.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(75, 75), InputHandler::WHEEL));
EXPECT_TRUE(host_impl_->IsCurrentlyScrollingLayerAt(gfx::Point(75, 75),
InputHandler::GESTURE));
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, 10));
EXPECT_FALSE(host_impl_->IsCurrentlyScrollingLayerAt(gfx::Point(25, 25),
InputHandler::GESTURE));
host_impl_->ScrollEnd();
EXPECT_FALSE(host_impl_->IsCurrentlyScrollingLayerAt(gfx::Point(75, 75),
InputHandler::GESTURE));
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(75, 75), InputHandler::GESTURE));
EXPECT_TRUE(host_impl_->IsCurrentlyScrollingLayerAt(gfx::Point(75, 75),
InputHandler::GESTURE));
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, 10));
host_impl_->ScrollEnd();
EXPECT_FALSE(host_impl_->IsCurrentlyScrollingLayerAt(gfx::Point(75, 75),
InputHandler::GESTURE));
}
TEST_F(LayerTreeHostImplTest, NonFastScrollableRegionWithOffset) {
SetupScrollAndContentsLayers(gfx::Size(200, 200));
host_impl_->SetViewportSize(gfx::Size(100, 100));
LayerImpl* root = host_impl_->active_tree()->root_layer();
root->SetNonFastScrollableRegion(gfx::Rect(0, 0, 50, 50));
root->SetPosition(gfx::PointF(-25.f, 0.f));
DrawFrame();
// This point would fall into the non-fast scrollable region except that we've
// moved the layer down by 25 pixels.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(40, 10), InputHandler::WHEEL));
EXPECT_TRUE(host_impl_->IsCurrentlyScrollingLayerAt(gfx::Point(40, 10),
InputHandler::WHEEL));
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, 1));
host_impl_->ScrollEnd();
// This point is still inside the non-fast region.
EXPECT_EQ(InputHandler::SCROLL_ON_MAIN_THREAD,
host_impl_->ScrollBegin(gfx::Point(10, 10), InputHandler::WHEEL));
}
TEST_F(LayerTreeHostImplTest, ScrollHandlerNotPresent) {
LayerImpl* scroll_layer = SetupScrollAndContentsLayers(gfx::Size(200, 200));
EXPECT_FALSE(scroll_layer->have_scroll_event_handlers());
host_impl_->SetViewportSize(gfx::Size(50, 50));
DrawFrame();
EXPECT_FALSE(host_impl_->scroll_affects_scroll_handler());
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE);
EXPECT_FALSE(host_impl_->scroll_affects_scroll_handler());
host_impl_->ScrollEnd();
EXPECT_FALSE(host_impl_->scroll_affects_scroll_handler());
}
TEST_F(LayerTreeHostImplTest, ScrollHandlerPresent) {
LayerImpl* scroll_layer = SetupScrollAndContentsLayers(gfx::Size(200, 200));
scroll_layer->SetHaveScrollEventHandlers(true);
host_impl_->SetViewportSize(gfx::Size(50, 50));
DrawFrame();
EXPECT_FALSE(host_impl_->scroll_affects_scroll_handler());
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE);
EXPECT_TRUE(host_impl_->scroll_affects_scroll_handler());
host_impl_->ScrollEnd();
EXPECT_FALSE(host_impl_->scroll_affects_scroll_handler());
}
TEST_F(LayerTreeHostImplTest, ScrollByReturnsCorrectValue) {
SetupScrollAndContentsLayers(gfx::Size(200, 200));
host_impl_->SetViewportSize(gfx::Size(100, 100));
DrawFrame();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
// Trying to scroll to the left/top will not succeed.
EXPECT_FALSE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(-10, 0)).did_scroll);
EXPECT_FALSE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, -10)).did_scroll);
EXPECT_FALSE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(-10, -10)).did_scroll);
// Scrolling to the right/bottom will succeed.
EXPECT_TRUE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(10, 0)).did_scroll);
EXPECT_TRUE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, 10)).did_scroll);
EXPECT_TRUE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(10, 10)).did_scroll);
// Scrolling to left/top will now succeed.
EXPECT_TRUE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(-10, 0)).did_scroll);
EXPECT_TRUE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, -10)).did_scroll);
EXPECT_TRUE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(-10, -10)).did_scroll);
// Scrolling diagonally against an edge will succeed.
EXPECT_TRUE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(10, -10)).did_scroll);
EXPECT_TRUE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(-10, 0)).did_scroll);
EXPECT_TRUE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(-10, 10)).did_scroll);
// Trying to scroll more than the available space will also succeed.
EXPECT_TRUE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(5000, 5000)).did_scroll);
}
TEST_F(LayerTreeHostImplTest, ScrollVerticallyByPageReturnsCorrectValue) {
SetupScrollAndContentsLayers(gfx::Size(200, 2000));
host_impl_->SetViewportSize(gfx::Size(100, 1000));
DrawFrame();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
// Trying to scroll without a vertical scrollbar will fail.
EXPECT_FALSE(host_impl_->ScrollVerticallyByPage(
gfx::Point(), SCROLL_FORWARD));
EXPECT_FALSE(host_impl_->ScrollVerticallyByPage(
gfx::Point(), SCROLL_BACKWARD));
scoped_ptr<PaintedScrollbarLayerImpl> vertical_scrollbar(
PaintedScrollbarLayerImpl::Create(
host_impl_->active_tree(),
20,
VERTICAL));
vertical_scrollbar->SetBounds(gfx::Size(15, 1000));
host_impl_->InnerViewportScrollLayer()->AddScrollbar(
vertical_scrollbar.get());
// Trying to scroll with a vertical scrollbar will succeed.
EXPECT_TRUE(host_impl_->ScrollVerticallyByPage(
gfx::Point(), SCROLL_FORWARD));
EXPECT_FLOAT_EQ(875.f,
host_impl_->InnerViewportScrollLayer()->ScrollDelta().y());
EXPECT_TRUE(host_impl_->ScrollVerticallyByPage(
gfx::Point(), SCROLL_BACKWARD));
}
TEST_F(LayerTreeHostImplTest, ScrollWithUserUnscrollableLayers) {
LayerImpl* scroll_layer = SetupScrollAndContentsLayers(gfx::Size(200, 200));
host_impl_->SetViewportSize(gfx::Size(100, 100));
gfx::Size overflow_size(400, 400);
ASSERT_EQ(1u, scroll_layer->children().size());
LayerImpl* overflow = scroll_layer->children()[0];
overflow->SetBounds(overflow_size);
overflow->SetScrollClipLayer(scroll_layer->parent()->id());
overflow->PushScrollOffsetFromMainThread(gfx::ScrollOffset());
overflow->SetPosition(gfx::PointF());
DrawFrame();
gfx::Point scroll_position(10, 10);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(scroll_position, InputHandler::WHEEL));
EXPECT_VECTOR_EQ(gfx::Vector2dF(), scroll_layer->CurrentScrollOffset());
EXPECT_VECTOR_EQ(gfx::Vector2dF(), overflow->CurrentScrollOffset());
gfx::Vector2dF scroll_delta(10, 10);
host_impl_->ScrollBy(scroll_position, scroll_delta);
host_impl_->ScrollEnd();
EXPECT_VECTOR_EQ(gfx::Vector2dF(), scroll_layer->CurrentScrollOffset());
EXPECT_VECTOR_EQ(gfx::Vector2dF(10, 10), overflow->CurrentScrollOffset());
overflow->set_user_scrollable_horizontal(false);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(scroll_position, InputHandler::WHEEL));
EXPECT_VECTOR_EQ(gfx::Vector2dF(), scroll_layer->CurrentScrollOffset());
EXPECT_VECTOR_EQ(gfx::Vector2dF(10, 10), overflow->CurrentScrollOffset());
host_impl_->ScrollBy(scroll_position, scroll_delta);
host_impl_->ScrollEnd();
EXPECT_VECTOR_EQ(gfx::Vector2dF(10, 0), scroll_layer->CurrentScrollOffset());
EXPECT_VECTOR_EQ(gfx::Vector2dF(10, 20), overflow->CurrentScrollOffset());
overflow->set_user_scrollable_vertical(false);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(scroll_position, InputHandler::WHEEL));
EXPECT_VECTOR_EQ(gfx::Vector2dF(10, 0), scroll_layer->CurrentScrollOffset());
EXPECT_VECTOR_EQ(gfx::Vector2dF(10, 20), overflow->CurrentScrollOffset());
host_impl_->ScrollBy(scroll_position, scroll_delta);
host_impl_->ScrollEnd();
EXPECT_VECTOR_EQ(gfx::Vector2dF(20, 10), scroll_layer->CurrentScrollOffset());
EXPECT_VECTOR_EQ(gfx::Vector2dF(10, 20), overflow->CurrentScrollOffset());
}
TEST_F(LayerTreeHostImplTest, AnimationSchedulingPendingTree) {
host_impl_->SetViewportSize(gfx::Size(50, 50));
host_impl_->CreatePendingTree();
host_impl_->pending_tree()->SetRootLayer(
LayerImpl::Create(host_impl_->pending_tree(), 1));
LayerImpl* root = host_impl_->pending_tree()->root_layer();
root->SetBounds(gfx::Size(50, 50));
root->SetHasRenderSurface(true);
root->AddChild(LayerImpl::Create(host_impl_->pending_tree(), 2));
LayerImpl* child = root->children()[0];
child->SetBounds(gfx::Size(10, 10));
child->draw_properties().visible_layer_rect = gfx::Rect(10, 10);
child->SetDrawsContent(true);
AddAnimatedTransformToLayer(child, 10.0, 3, 0);
EXPECT_FALSE(did_request_animate_);
EXPECT_FALSE(did_request_redraw_);
EXPECT_FALSE(did_request_commit_);
host_impl_->Animate();
// An animation exists on the pending layer. Doing Animate() requests another
// frame.
// In reality, animations without has_set_start_time() == true do not need to
// be continuously ticked on the pending tree, so it should not request
// another animation frame here. But we currently do so blindly if any
// animation exists.
EXPECT_TRUE(did_request_animate_);
// The pending tree with an animation does not need to draw after animating.
EXPECT_FALSE(did_request_redraw_);
EXPECT_FALSE(did_request_commit_);
did_request_animate_ = false;
did_request_redraw_ = false;
did_request_commit_ = false;
host_impl_->ActivateSyncTree();
// When the animation activates, we should request another animation frame
// to keep the animation moving.
EXPECT_TRUE(did_request_animate_);
// On activation we don't need to request a redraw for the animation,
// activating will draw on its own when it's ready.
EXPECT_FALSE(did_request_redraw_);
EXPECT_FALSE(did_request_commit_);
}
TEST_F(LayerTreeHostImplTest, AnimationSchedulingActiveTree) {
host_impl_->SetViewportSize(gfx::Size(50, 50));
host_impl_->active_tree()->SetRootLayer(
LayerImpl::Create(host_impl_->active_tree(), 1));
LayerImpl* root = host_impl_->active_tree()->root_layer();
root->SetBounds(gfx::Size(50, 50));
root->SetHasRenderSurface(true);
root->AddChild(LayerImpl::Create(host_impl_->active_tree(), 2));
LayerImpl* child = root->children()[0];
child->SetBounds(gfx::Size(10, 10));
child->draw_properties().visible_layer_rect = gfx::Rect(10, 10);
child->SetDrawsContent(true);
// Add a translate from 6,7 to 8,9.
TransformOperations start;
start.AppendTranslate(6.f, 7.f, 0.f);
TransformOperations end;
end.AppendTranslate(8.f, 9.f, 0.f);
AddAnimatedTransformToLayer(child, 4.0, start, end);
base::TimeTicks now = base::TimeTicks::Now();
host_impl_->WillBeginImplFrame(
CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE, now));
EXPECT_FALSE(did_request_animate_);
EXPECT_FALSE(did_request_redraw_);
EXPECT_FALSE(did_request_commit_);
host_impl_->ActivateAnimations();
did_request_animate_ = false;
did_request_redraw_ = false;
did_request_commit_ = false;
host_impl_->Animate();
// An animation exists on the active layer. Doing Animate() requests another
// frame after the current one.
EXPECT_TRUE(did_request_animate_);
// TODO(danakj): We also need to draw in the current frame if something
// animated, but this is currently handled by
// SchedulerStateMachine::WillAnimate.
EXPECT_FALSE(did_request_redraw_);
EXPECT_FALSE(did_request_commit_);
}
TEST_F(LayerTreeHostImplTest, ImplPinchZoom) {
LayerImpl* scroll_layer = SetupScrollAndContentsLayers(gfx::Size(100, 100));
host_impl_->SetViewportSize(gfx::Size(50, 50));
DrawFrame();
EXPECT_EQ(scroll_layer, host_impl_->InnerViewportScrollLayer());
LayerImpl* container_layer = scroll_layer->scroll_clip_layer();
EXPECT_EQ(gfx::Size(50, 50), container_layer->bounds());
float min_page_scale = 1.f, max_page_scale = 4.f;
float page_scale_factor = 1.f;
// The impl-based pinch zoom should adjust the max scroll position.
{
host_impl_->active_tree()->PushPageScaleFromMainThread(
page_scale_factor, min_page_scale, max_page_scale);
host_impl_->active_tree()->SetPageScaleOnActiveTree(page_scale_factor);
scroll_layer->SetScrollDelta(gfx::Vector2d());
float page_scale_delta = 2.f;
host_impl_->ScrollBegin(gfx::Point(50, 50), InputHandler::GESTURE);
host_impl_->PinchGestureBegin();
host_impl_->PinchGestureUpdate(page_scale_delta, gfx::Point(50, 50));
host_impl_->PinchGestureEnd();
host_impl_->ScrollEnd();
EXPECT_FALSE(did_request_animate_);
EXPECT_TRUE(did_request_redraw_);
EXPECT_TRUE(did_request_commit_);
EXPECT_EQ(gfx::Size(50, 50), container_layer->bounds());
scoped_ptr<ScrollAndScaleSet> scroll_info =
host_impl_->ProcessScrollDeltas();
EXPECT_EQ(scroll_info->page_scale_delta, page_scale_delta);
EXPECT_EQ(gfx::ScrollOffset(75.0, 75.0).ToString(),
scroll_layer->MaxScrollOffset().ToString());
}
// Scrolling after a pinch gesture should always be in local space. The
// scroll deltas have the page scale factor applied.
{
host_impl_->active_tree()->PushPageScaleFromMainThread(
page_scale_factor, min_page_scale, max_page_scale);
host_impl_->active_tree()->SetPageScaleOnActiveTree(page_scale_factor);
scroll_layer->SetScrollDelta(gfx::Vector2d());
float page_scale_delta = 2.f;
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE);
host_impl_->PinchGestureBegin();
host_impl_->PinchGestureUpdate(page_scale_delta, gfx::Point());
host_impl_->PinchGestureEnd();
host_impl_->ScrollEnd();
gfx::Vector2d scroll_delta(0, 10);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(5, 5), InputHandler::WHEEL));
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
host_impl_->ScrollEnd();
scoped_ptr<ScrollAndScaleSet> scroll_info =
host_impl_->ProcessScrollDeltas();
EXPECT_TRUE(ScrollInfoContains(
*scroll_info.get(), scroll_layer->id(),
gfx::Vector2d(0, scroll_delta.y() / page_scale_delta)));
}
}
TEST_F(LayerTreeHostImplTest, ViewportScrollOrder) {
LayerTreeSettings settings = DefaultSettings();
settings.invert_viewport_scroll_order = true;
CreateHostImpl(settings,
CreateOutputSurface());
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, 0.25f, 4.f);
const gfx::Size content_size(1000, 1000);
const gfx::Size viewport_size(500, 500);
CreateBasicVirtualViewportLayers(viewport_size, content_size);
LayerImpl* outer_scroll_layer = host_impl_->OuterViewportScrollLayer();
LayerImpl* inner_scroll_layer = host_impl_->InnerViewportScrollLayer();
EXPECT_VECTOR_EQ(
gfx::Vector2dF(500, 500),
outer_scroll_layer->MaxScrollOffset());
host_impl_->ScrollBegin(gfx::Point(250, 250), InputHandler::GESTURE);
host_impl_->PinchGestureBegin();
host_impl_->PinchGestureUpdate(2.f, gfx::Point(0, 0));
host_impl_->PinchGestureEnd();
host_impl_->ScrollEnd();
// Sanity check - we're zoomed in, starting from the origin.
EXPECT_VECTOR_EQ(
gfx::Vector2dF(0, 0),
outer_scroll_layer->CurrentScrollOffset());
EXPECT_VECTOR_EQ(
gfx::Vector2dF(0, 0),
inner_scroll_layer->CurrentScrollOffset());
// Scroll down - only the inner viewport should scroll.
host_impl_->ScrollBegin(gfx::Point(0, 0), InputHandler::GESTURE);
host_impl_->ScrollBy(gfx::Point(0, 0), gfx::Vector2dF(100.f, 100.f));
host_impl_->ScrollEnd();
EXPECT_VECTOR_EQ(
gfx::Vector2dF(50, 50),
inner_scroll_layer->CurrentScrollOffset());
EXPECT_VECTOR_EQ(
gfx::Vector2dF(0, 0),
outer_scroll_layer->CurrentScrollOffset());
// Scroll down - outer viewport should start scrolling after the inner is at
// its maximum.
host_impl_->ScrollBegin(gfx::Point(0, 0), InputHandler::GESTURE);
host_impl_->ScrollBy(gfx::Point(0, 0), gfx::Vector2dF(1000.f, 1000.f));
host_impl_->ScrollEnd();
EXPECT_VECTOR_EQ(
gfx::Vector2dF(250, 250),
inner_scroll_layer->CurrentScrollOffset());
EXPECT_VECTOR_EQ(
gfx::Vector2dF(300, 300),
outer_scroll_layer->CurrentScrollOffset());
}
// Tests that scrolls during a pinch gesture (i.e. "two-finger" scrolls) work
// as expected. That is, scrolling during a pinch should bubble from the inner
// to the outer viewport.
TEST_F(LayerTreeHostImplTest, ScrollDuringPinchGesture) {
LayerTreeSettings settings = DefaultSettings();
settings.invert_viewport_scroll_order = true;
CreateHostImpl(settings,
CreateOutputSurface());
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, 1.f, 2.f);
const gfx::Size content_size(1000, 1000);
const gfx::Size viewport_size(500, 500);
CreateBasicVirtualViewportLayers(viewport_size, content_size);
LayerImpl* outer_scroll_layer = host_impl_->OuterViewportScrollLayer();
LayerImpl* inner_scroll_layer = host_impl_->InnerViewportScrollLayer();
EXPECT_VECTOR_EQ(
gfx::Vector2dF(500, 500),
outer_scroll_layer->MaxScrollOffset());
host_impl_->ScrollBegin(gfx::Point(250, 250), InputHandler::GESTURE);
host_impl_->PinchGestureBegin();
host_impl_->PinchGestureUpdate(2, gfx::Point(250, 250));
EXPECT_VECTOR_EQ(
gfx::Vector2dF(0, 0),
outer_scroll_layer->CurrentScrollOffset());
EXPECT_VECTOR_EQ(
gfx::Vector2dF(125, 125),
inner_scroll_layer->CurrentScrollOffset());
// Needed so that the pinch is accounted for in draw properties.
DrawFrame();
host_impl_->ScrollBy(gfx::Point(250, 250), gfx::Vector2dF(10.f, 10.f));
EXPECT_VECTOR_EQ(
gfx::Vector2dF(0, 0),
outer_scroll_layer->CurrentScrollOffset());
EXPECT_VECTOR_EQ(
gfx::Vector2dF(130, 130),
inner_scroll_layer->CurrentScrollOffset());
DrawFrame();
host_impl_->ScrollBy(gfx::Point(250, 250), gfx::Vector2dF(400.f, 400.f));
EXPECT_VECTOR_EQ(
gfx::Vector2dF(80, 80),
outer_scroll_layer->CurrentScrollOffset());
EXPECT_VECTOR_EQ(
gfx::Vector2dF(250, 250),
inner_scroll_layer->CurrentScrollOffset());
host_impl_->PinchGestureEnd();
host_impl_->ScrollEnd();
}
// Tests the "snapping" of pinch-zoom gestures to the screen edge. That is, when
// a pinch zoom is anchored within a certain margin of the screen edge, we
// should assume the user means to scroll into the edge of the screen.
TEST_F(LayerTreeHostImplTest, PinchZoomSnapsToScreenEdge) {
LayerTreeSettings settings = DefaultSettings();
settings.invert_viewport_scroll_order = true;
CreateHostImpl(settings,
CreateOutputSurface());
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, 1.f, 2.f);
const gfx::Size content_size(1000, 1000);
const gfx::Size viewport_size(500, 500);
CreateBasicVirtualViewportLayers(viewport_size, content_size);
int offsetFromEdge = Viewport::kPinchZoomSnapMarginDips - 5;
gfx::Point anchor(viewport_size.width() - offsetFromEdge,
viewport_size.height() - offsetFromEdge);
// Pinch in within the margins. The scroll should stay exactly locked to the
// bottom and right.
host_impl_->ScrollBegin(anchor, InputHandler::GESTURE);
host_impl_->PinchGestureBegin();
host_impl_->PinchGestureUpdate(2, anchor);
host_impl_->PinchGestureEnd();
host_impl_->ScrollEnd();
EXPECT_VECTOR_EQ(
gfx::Vector2dF(250, 250),
host_impl_->InnerViewportScrollLayer()->CurrentScrollOffset());
// Reset.
host_impl_->active_tree()->SetPageScaleOnActiveTree(1.f);
host_impl_->InnerViewportScrollLayer()->SetScrollDelta(gfx::Vector2d());
host_impl_->OuterViewportScrollLayer()->SetScrollDelta(gfx::Vector2d());
// Pinch in within the margins. The scroll should stay exactly locked to the
// top and left.
anchor = gfx::Point(offsetFromEdge, offsetFromEdge);
host_impl_->ScrollBegin(anchor, InputHandler::GESTURE);
host_impl_->PinchGestureBegin();
host_impl_->PinchGestureUpdate(2, anchor);
host_impl_->PinchGestureEnd();
host_impl_->ScrollEnd();
EXPECT_VECTOR_EQ(
gfx::Vector2dF(0, 0),
host_impl_->InnerViewportScrollLayer()->CurrentScrollOffset());
// Reset.
host_impl_->active_tree()->SetPageScaleOnActiveTree(1.f);
host_impl_->InnerViewportScrollLayer()->SetScrollDelta(gfx::Vector2d());
host_impl_->OuterViewportScrollLayer()->SetScrollDelta(gfx::Vector2d());
// Pinch in just outside the margin. There should be no snapping.
offsetFromEdge = Viewport::kPinchZoomSnapMarginDips;
anchor = gfx::Point(offsetFromEdge, offsetFromEdge);
host_impl_->ScrollBegin(anchor, InputHandler::GESTURE);
host_impl_->PinchGestureBegin();
host_impl_->PinchGestureUpdate(2, anchor);
host_impl_->PinchGestureEnd();
host_impl_->ScrollEnd();
EXPECT_VECTOR_EQ(
gfx::Vector2dF(50, 50),
host_impl_->InnerViewportScrollLayer()->CurrentScrollOffset());
// Reset.
host_impl_->active_tree()->SetPageScaleOnActiveTree(1.f);
host_impl_->InnerViewportScrollLayer()->SetScrollDelta(gfx::Vector2d());
host_impl_->OuterViewportScrollLayer()->SetScrollDelta(gfx::Vector2d());
// Pinch in just outside the margin. There should be no snapping.
offsetFromEdge = Viewport::kPinchZoomSnapMarginDips;
anchor = gfx::Point(viewport_size.width() - offsetFromEdge,
viewport_size.height() - offsetFromEdge);
host_impl_->ScrollBegin(anchor, InputHandler::GESTURE);
host_impl_->PinchGestureBegin();
host_impl_->PinchGestureUpdate(2, anchor);
host_impl_->PinchGestureEnd();
host_impl_->ScrollEnd();
EXPECT_VECTOR_EQ(
gfx::Vector2dF(200, 200),
host_impl_->InnerViewportScrollLayer()->CurrentScrollOffset());
}
TEST_F(LayerTreeHostImplTest, ImplPinchZoomWheelBubbleBetweenViewports) {
const gfx::Size content_size(200, 200);
const gfx::Size viewport_size(100, 100);
CreateBasicVirtualViewportLayers(viewport_size, content_size);
LayerImpl* outer_scroll_layer = host_impl_->OuterViewportScrollLayer();
LayerImpl* inner_scroll_layer = host_impl_->InnerViewportScrollLayer();
// Zoom into the page by a 2X factor
float min_page_scale = 1.f, max_page_scale = 4.f;
float page_scale_factor = 2.f;
host_impl_->active_tree()->PushPageScaleFromMainThread(
page_scale_factor, min_page_scale, max_page_scale);
host_impl_->active_tree()->SetPageScaleOnActiveTree(page_scale_factor);
// Scroll by a small amount, there should be no bubbling up to the inner
// viewport.
host_impl_->ScrollBegin(gfx::Point(0, 0), InputHandler::WHEEL);
host_impl_->ScrollBy(gfx::Point(0, 0), gfx::Vector2dF(10.f, 20.f));
host_impl_->ScrollEnd();
EXPECT_VECTOR_EQ(
gfx::Vector2dF(5, 10),
outer_scroll_layer->CurrentScrollOffset());
EXPECT_VECTOR_EQ(
gfx::Vector2dF(),
inner_scroll_layer->CurrentScrollOffset());
// Scroll by the outer viewport's max scroll extent, there the remainder
// should bubble up to the inner viewport.
host_impl_->ScrollBegin(gfx::Point(0, 0), InputHandler::WHEEL);
host_impl_->ScrollBy(gfx::Point(0, 0), gfx::Vector2dF(200.f, 200.f));
host_impl_->ScrollEnd();
EXPECT_VECTOR_EQ(
gfx::Vector2dF(100, 100),
outer_scroll_layer->CurrentScrollOffset());
EXPECT_VECTOR_EQ(
gfx::Vector2dF(5, 10),
inner_scroll_layer->CurrentScrollOffset());
// Scroll by the inner viewport's max scroll extent, it should all go to the
// inner viewport.
host_impl_->ScrollBegin(gfx::Point(0, 0), InputHandler::WHEEL);
host_impl_->ScrollBy(gfx::Point(0, 0), gfx::Vector2dF(90.f, 80.f));
host_impl_->ScrollEnd();
EXPECT_VECTOR_EQ(
gfx::Vector2dF(100, 100),
outer_scroll_layer->CurrentScrollOffset());
EXPECT_VECTOR_EQ(
gfx::Vector2dF(50, 50),
inner_scroll_layer->CurrentScrollOffset());
}
TEST_F(LayerTreeHostImplTest, ScrollWithSwapPromises) {
ui::LatencyInfo latency_info;
latency_info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT, 0,
1234);
scoped_ptr<SwapPromise> swap_promise(
new LatencyInfoSwapPromise(latency_info));
SetupScrollAndContentsLayers(gfx::Size(100, 100));
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, 10));
host_impl_->QueueSwapPromiseForMainThreadScrollUpdate(swap_promise.Pass());
host_impl_->ScrollEnd();
scoped_ptr<ScrollAndScaleSet> scroll_info = host_impl_->ProcessScrollDeltas();
EXPECT_EQ(1u, scroll_info->swap_promises.size());
EXPECT_EQ(latency_info.trace_id(), scroll_info->swap_promises[0]->TraceId());
}
// Test that scrolls targeting a layer with a non-null scroll_parent() bubble
// up to the scroll_parent, rather than the stacking parent.
TEST_F(LayerTreeHostImplTest, ScrollBubblesToScrollParent) {
LayerImpl* viewport_scroll =
SetupScrollAndContentsLayers(gfx::Size(100, 100));
host_impl_->SetViewportSize(gfx::Size(50, 50));
// Set up two scrolling children of the root, one of which is a scroll parent
// to the other. Scrolls bubbling from the child should bubble to the parent,
// not the viewport.
LayerImpl *parent;
LayerImpl *child;
LayerImpl *child_clip;
scoped_ptr<LayerImpl> scroll_parent_clip =
LayerImpl::Create(host_impl_->active_tree(), 6);
scoped_ptr<LayerImpl> scroll_parent = CreateScrollableLayer(
7, gfx::Size(10, 10), scroll_parent_clip.get());
parent = scroll_parent.get();
scroll_parent_clip->AddChild(scroll_parent.Pass());
viewport_scroll->AddChild(scroll_parent_clip.Pass());
scoped_ptr<LayerImpl> scroll_child_clip =
LayerImpl::Create(host_impl_->active_tree(), 8);
scoped_ptr<LayerImpl> scroll_child = CreateScrollableLayer(
9, gfx::Size(10, 10), scroll_child_clip.get());
child = scroll_child.get();
scroll_child->SetPosition(gfx::Point(20, 20));
scroll_child_clip->AddChild(scroll_child.Pass());
child_clip = scroll_child_clip.get();
viewport_scroll->AddChild(scroll_child_clip.Pass());
child_clip->SetScrollParent(parent);
DrawFrame();
{
host_impl_->ScrollBegin(gfx::Point(21, 21), InputHandler::GESTURE);
host_impl_->ScrollBy(gfx::Point(21, 21), gfx::Vector2d(5, 5));
host_impl_->ScrollBy(gfx::Point(21, 21), gfx::Vector2d(2, 1));
host_impl_->ScrollEnd();
// The child should be fully scrolled by the first ScrollBy.
EXPECT_VECTOR_EQ(gfx::Vector2dF(5, 5), child->CurrentScrollOffset());
// The scroll_parent should receive the bubbled up second ScrollBy.
EXPECT_VECTOR_EQ(gfx::Vector2dF(2, 1), parent->CurrentScrollOffset());
// The viewport shouldn't have been scrolled at all.
EXPECT_VECTOR_EQ(
gfx::Vector2dF(0, 0),
host_impl_->InnerViewportScrollLayer()->CurrentScrollOffset());
EXPECT_VECTOR_EQ(
gfx::Vector2dF(0, 0),
host_impl_->OuterViewportScrollLayer()->CurrentScrollOffset());
}
{
host_impl_->ScrollBegin(gfx::Point(21, 21), InputHandler::GESTURE);
host_impl_->ScrollBy(gfx::Point(21, 21), gfx::Vector2d(3, 4));
host_impl_->ScrollBy(gfx::Point(21, 21), gfx::Vector2d(2, 1));
host_impl_->ScrollEnd();
// The first ScrollBy should scroll the parent to its extent.
EXPECT_VECTOR_EQ(gfx::Vector2dF(5, 5), parent->CurrentScrollOffset());
// The viewport should now be next in bubbling order.
EXPECT_VECTOR_EQ(
gfx::Vector2dF(2, 1),
host_impl_->InnerViewportScrollLayer()->CurrentScrollOffset());
EXPECT_VECTOR_EQ(
gfx::Vector2dF(0, 0),
host_impl_->OuterViewportScrollLayer()->CurrentScrollOffset());
}
}
TEST_F(LayerTreeHostImplTest, PinchGesture) {
SetupScrollAndContentsLayers(gfx::Size(100, 100));
host_impl_->SetViewportSize(gfx::Size(50, 50));
DrawFrame();
LayerImpl* scroll_layer = host_impl_->InnerViewportScrollLayer();
DCHECK(scroll_layer);
float min_page_scale = 1.f;
float max_page_scale = 4.f;
// Basic pinch zoom in gesture
{
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, min_page_scale,
max_page_scale);
scroll_layer->SetScrollDelta(gfx::Vector2d());
float page_scale_delta = 2.f;
host_impl_->ScrollBegin(gfx::Point(50, 50), InputHandler::GESTURE);
host_impl_->PinchGestureBegin();
host_impl_->PinchGestureUpdate(page_scale_delta, gfx::Point(50, 50));
host_impl_->PinchGestureEnd();
host_impl_->ScrollEnd();
EXPECT_FALSE(did_request_animate_);
EXPECT_TRUE(did_request_redraw_);
EXPECT_TRUE(did_request_commit_);
scoped_ptr<ScrollAndScaleSet> scroll_info =
host_impl_->ProcessScrollDeltas();
EXPECT_EQ(scroll_info->page_scale_delta, page_scale_delta);
}
// Zoom-in clamping
{
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, min_page_scale,
max_page_scale);
scroll_layer->SetScrollDelta(gfx::Vector2d());
float page_scale_delta = 10.f;
host_impl_->ScrollBegin(gfx::Point(50, 50), InputHandler::GESTURE);
host_impl_->PinchGestureBegin();
host_impl_->PinchGestureUpdate(page_scale_delta, gfx::Point(50, 50));
host_impl_->PinchGestureEnd();
host_impl_->ScrollEnd();
scoped_ptr<ScrollAndScaleSet> scroll_info =
host_impl_->ProcessScrollDeltas();
EXPECT_EQ(scroll_info->page_scale_delta, max_page_scale);
}
// Zoom-out clamping
{
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, min_page_scale,
max_page_scale);
scroll_layer->SetScrollDelta(gfx::Vector2d());
scroll_layer->PullDeltaForMainThread();
scroll_layer->PushScrollOffsetFromMainThread(gfx::ScrollOffset(50, 50));
float page_scale_delta = 0.1f;
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE);
host_impl_->PinchGestureBegin();
host_impl_->PinchGestureUpdate(page_scale_delta, gfx::Point());
host_impl_->PinchGestureEnd();
host_impl_->ScrollEnd();
scoped_ptr<ScrollAndScaleSet> scroll_info =
host_impl_->ProcessScrollDeltas();
EXPECT_EQ(scroll_info->page_scale_delta, min_page_scale);
EXPECT_TRUE(scroll_info->scrolls.empty());
}
// Two-finger panning should not happen based on pinch events only
{
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, min_page_scale,
max_page_scale);
scroll_layer->SetScrollDelta(gfx::Vector2d());
scroll_layer->PullDeltaForMainThread();
scroll_layer->PushScrollOffsetFromMainThread(gfx::ScrollOffset(20, 20));
float page_scale_delta = 1.f;
host_impl_->ScrollBegin(gfx::Point(10, 10), InputHandler::GESTURE);
host_impl_->PinchGestureBegin();
host_impl_->PinchGestureUpdate(page_scale_delta, gfx::Point(10, 10));
host_impl_->PinchGestureUpdate(page_scale_delta, gfx::Point(20, 20));
host_impl_->PinchGestureEnd();
host_impl_->ScrollEnd();
scoped_ptr<ScrollAndScaleSet> scroll_info =
host_impl_->ProcessScrollDeltas();
EXPECT_EQ(scroll_info->page_scale_delta, page_scale_delta);
EXPECT_TRUE(scroll_info->scrolls.empty());
}
// Two-finger panning should work with interleaved scroll events
{
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, min_page_scale,
max_page_scale);
scroll_layer->SetScrollDelta(gfx::Vector2d());
scroll_layer->PullDeltaForMainThread();
scroll_layer->PushScrollOffsetFromMainThread(gfx::ScrollOffset(20, 20));
float page_scale_delta = 1.f;
host_impl_->ScrollBegin(gfx::Point(10, 10), InputHandler::GESTURE);
host_impl_->PinchGestureBegin();
host_impl_->PinchGestureUpdate(page_scale_delta, gfx::Point(10, 10));
host_impl_->ScrollBy(gfx::Point(10, 10), gfx::Vector2d(-10, -10));
host_impl_->PinchGestureUpdate(page_scale_delta, gfx::Point(20, 20));
host_impl_->PinchGestureEnd();
host_impl_->ScrollEnd();
scoped_ptr<ScrollAndScaleSet> scroll_info =
host_impl_->ProcessScrollDeltas();
EXPECT_EQ(scroll_info->page_scale_delta, page_scale_delta);
EXPECT_TRUE(ScrollInfoContains(*scroll_info, scroll_layer->id(),
gfx::Vector2d(-10, -10)));
}
// Two-finger panning should work when starting fully zoomed out.
{
host_impl_->active_tree()->PushPageScaleFromMainThread(0.5f, 0.5f, 4.f);
scroll_layer->SetScrollDelta(gfx::Vector2d());
scroll_layer->PullDeltaForMainThread();
scroll_layer->PushScrollOffsetFromMainThread(gfx::ScrollOffset(0, 0));
host_impl_->ScrollBegin(gfx::Point(0, 0), InputHandler::GESTURE);
host_impl_->PinchGestureBegin();
host_impl_->PinchGestureUpdate(2.f, gfx::Point(0, 0));
host_impl_->PinchGestureUpdate(1.f, gfx::Point(0, 0));
host_impl_->ScrollBy(gfx::Point(0, 0), gfx::Vector2d(10, 10));
host_impl_->PinchGestureUpdate(1.f, gfx::Point(10, 10));
host_impl_->PinchGestureEnd();
host_impl_->ScrollEnd();
scoped_ptr<ScrollAndScaleSet> scroll_info =
host_impl_->ProcessScrollDeltas();
EXPECT_EQ(scroll_info->page_scale_delta, 2.f);
EXPECT_TRUE(ScrollInfoContains(*scroll_info, scroll_layer->id(),
gfx::Vector2d(20, 20)));
}
}
TEST_F(LayerTreeHostImplTest, PageScaleAnimation) {
SetupScrollAndContentsLayers(gfx::Size(100, 100));
host_impl_->SetViewportSize(gfx::Size(50, 50));
DrawFrame();
LayerImpl* scroll_layer = host_impl_->InnerViewportScrollLayer();
DCHECK(scroll_layer);
float min_page_scale = 0.5f;
float max_page_scale = 4.f;
base::TimeTicks start_time = base::TimeTicks() +
base::TimeDelta::FromSeconds(1);
base::TimeDelta duration = base::TimeDelta::FromMilliseconds(100);
base::TimeTicks halfway_through_animation = start_time + duration / 2;
base::TimeTicks end_time = start_time + duration;
BeginFrameArgs begin_frame_args =
CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE);
// Non-anchor zoom-in
{
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, min_page_scale,
max_page_scale);
scroll_layer->PushScrollOffsetFromMainThread(gfx::ScrollOffset(50, 50));
did_request_redraw_ = false;
did_request_animate_ = false;
host_impl_->active_tree()->SetPendingPageScaleAnimation(
scoped_ptr<PendingPageScaleAnimation>(new PendingPageScaleAnimation(
gfx::Vector2d(),
false,
2.f,
duration)));
host_impl_->ActivateSyncTree();
EXPECT_FALSE(did_request_redraw_);
EXPECT_TRUE(did_request_animate_);
did_request_redraw_ = false;
did_request_animate_ = false;
begin_frame_args.frame_time = start_time;
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
EXPECT_TRUE(did_request_redraw_);
EXPECT_TRUE(did_request_animate_);
host_impl_->DidFinishImplFrame();
did_request_redraw_ = false;
did_request_animate_ = false;
begin_frame_args.frame_time = halfway_through_animation;
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
EXPECT_TRUE(did_request_redraw_);
EXPECT_TRUE(did_request_animate_);
host_impl_->DidFinishImplFrame();
did_request_redraw_ = false;
did_request_animate_ = false;
did_request_commit_ = false;
begin_frame_args.frame_time = end_time;
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
EXPECT_TRUE(did_request_commit_);
EXPECT_FALSE(did_request_animate_);
host_impl_->DidFinishImplFrame();
scoped_ptr<ScrollAndScaleSet> scroll_info =
host_impl_->ProcessScrollDeltas();
EXPECT_EQ(scroll_info->page_scale_delta, 2);
EXPECT_TRUE(ScrollInfoContains(*scroll_info, scroll_layer->id(),
gfx::Vector2d(-50, -50)));
}
start_time += base::TimeDelta::FromSeconds(10);
halfway_through_animation += base::TimeDelta::FromSeconds(10);
end_time += base::TimeDelta::FromSeconds(10);
// Anchor zoom-out
{
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, min_page_scale,
max_page_scale);
scroll_layer->PushScrollOffsetFromMainThread(gfx::ScrollOffset(50, 50));
did_request_redraw_ = false;
did_request_animate_ = false;
host_impl_->active_tree()->SetPendingPageScaleAnimation(
scoped_ptr<PendingPageScaleAnimation> (new PendingPageScaleAnimation(
gfx::Vector2d(25, 25),
true,
min_page_scale,
duration)));
host_impl_->ActivateSyncTree();
EXPECT_FALSE(did_request_redraw_);
EXPECT_TRUE(did_request_animate_);
did_request_redraw_ = false;
did_request_animate_ = false;
begin_frame_args.frame_time = start_time;
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
EXPECT_TRUE(did_request_redraw_);
EXPECT_TRUE(did_request_animate_);
host_impl_->DidFinishImplFrame();
did_request_redraw_ = false;
did_request_commit_ = false;
did_request_animate_ = false;
begin_frame_args.frame_time = end_time;
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
EXPECT_TRUE(did_request_redraw_);
EXPECT_FALSE(did_request_animate_);
EXPECT_TRUE(did_request_commit_);
host_impl_->DidFinishImplFrame();
scoped_ptr<ScrollAndScaleSet> scroll_info =
host_impl_->ProcessScrollDeltas();
EXPECT_EQ(scroll_info->page_scale_delta, min_page_scale);
// Pushed to (0,0) via clamping against contents layer size.
EXPECT_TRUE(ScrollInfoContains(*scroll_info, scroll_layer->id(),
gfx::Vector2d(-50, -50)));
}
}
TEST_F(LayerTreeHostImplTest, PageScaleAnimationNoOp) {
SetupScrollAndContentsLayers(gfx::Size(100, 100));
host_impl_->SetViewportSize(gfx::Size(50, 50));
DrawFrame();
LayerImpl* scroll_layer = host_impl_->InnerViewportScrollLayer();
DCHECK(scroll_layer);
float min_page_scale = 0.5f;
float max_page_scale = 4.f;
base::TimeTicks start_time = base::TimeTicks() +
base::TimeDelta::FromSeconds(1);
base::TimeDelta duration = base::TimeDelta::FromMilliseconds(100);
base::TimeTicks halfway_through_animation = start_time + duration / 2;
base::TimeTicks end_time = start_time + duration;
BeginFrameArgs begin_frame_args =
CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE);
// Anchor zoom with unchanged page scale should not change scroll or scale.
{
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, min_page_scale,
max_page_scale);
scroll_layer->PushScrollOffsetFromMainThread(gfx::ScrollOffset(50, 50));
host_impl_->active_tree()->SetPendingPageScaleAnimation(
scoped_ptr<PendingPageScaleAnimation>(new PendingPageScaleAnimation(
gfx::Vector2d(),
true,
1.f,
duration)));
host_impl_->ActivateSyncTree();
begin_frame_args.frame_time = start_time;
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
host_impl_->DidFinishImplFrame();
begin_frame_args.frame_time = halfway_through_animation;
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
EXPECT_TRUE(did_request_redraw_);
host_impl_->DidFinishImplFrame();
begin_frame_args.frame_time = end_time;
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
EXPECT_TRUE(did_request_commit_);
host_impl_->DidFinishImplFrame();
scoped_ptr<ScrollAndScaleSet> scroll_info =
host_impl_->ProcessScrollDeltas();
EXPECT_EQ(scroll_info->page_scale_delta, 1);
ExpectNone(*scroll_info, scroll_layer->id());
}
}
TEST_F(LayerTreeHostImplTest, PageScaleAnimationTransferedOnSyncTreeActivate) {
host_impl_->CreatePendingTree();
host_impl_->pending_tree()->PushPageScaleFromMainThread(1.f, 1.f, 1.f);
CreateScrollAndContentsLayers(
host_impl_->pending_tree(),
gfx::Size(100, 100));
host_impl_->ActivateSyncTree();
DrawFrame();
LayerImpl* scroll_layer = host_impl_->InnerViewportScrollLayer();
DCHECK(scroll_layer);
float min_page_scale = 0.5f;
float max_page_scale = 4.f;
host_impl_->sync_tree()->PushPageScaleFromMainThread(1.f, min_page_scale,
max_page_scale);
host_impl_->ActivateSyncTree();
base::TimeTicks start_time = base::TimeTicks() +
base::TimeDelta::FromSeconds(1);
base::TimeDelta duration = base::TimeDelta::FromMilliseconds(100);
base::TimeTicks third_through_animation = start_time + duration / 3;
base::TimeTicks halfway_through_animation = start_time + duration / 2;
base::TimeTicks end_time = start_time + duration;
float target_scale = 2.f;
BeginFrameArgs begin_frame_args =
CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE);
scroll_layer->PushScrollOffsetFromMainThread(gfx::ScrollOffset(50, 50));
// Make sure TakePageScaleAnimation works properly.
host_impl_->sync_tree()->SetPendingPageScaleAnimation(
scoped_ptr<PendingPageScaleAnimation>(new PendingPageScaleAnimation(
gfx::Vector2d(),
false,
target_scale,
duration)));
scoped_ptr<PendingPageScaleAnimation> psa =
host_impl_->sync_tree()->TakePendingPageScaleAnimation();
EXPECT_EQ(target_scale, psa->scale);
EXPECT_EQ(duration, psa->duration);
EXPECT_EQ(nullptr, host_impl_->sync_tree()->TakePendingPageScaleAnimation());
// Recreate the PSA. Nothing should happen here since the tree containing the
// PSA hasn't been activated yet.
did_request_redraw_ = false;
did_request_animate_ = false;
host_impl_->sync_tree()->SetPendingPageScaleAnimation(
scoped_ptr<PendingPageScaleAnimation>(new PendingPageScaleAnimation(
gfx::Vector2d(),
false,
target_scale,
duration)));
begin_frame_args.frame_time = halfway_through_animation;
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
EXPECT_FALSE(did_request_animate_);
EXPECT_FALSE(did_request_redraw_);
host_impl_->DidFinishImplFrame();
// Activate the sync tree. This should cause the animation to become enabled.
// It should also clear the pointer on the sync tree.
host_impl_->ActivateSyncTree();
EXPECT_EQ(nullptr,
host_impl_->sync_tree()->TakePendingPageScaleAnimation().get());
EXPECT_FALSE(did_request_redraw_);
EXPECT_TRUE(did_request_animate_);
start_time += base::TimeDelta::FromSeconds(10);
third_through_animation += base::TimeDelta::FromSeconds(10);
halfway_through_animation += base::TimeDelta::FromSeconds(10);
end_time += base::TimeDelta::FromSeconds(10);
// From here on, make sure the animation runs as normal.
did_request_redraw_ = false;
did_request_animate_ = false;
begin_frame_args.frame_time = start_time;
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
EXPECT_TRUE(did_request_redraw_);
EXPECT_TRUE(did_request_animate_);
host_impl_->DidFinishImplFrame();
did_request_redraw_ = false;
did_request_animate_ = false;
begin_frame_args.frame_time = third_through_animation;
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
EXPECT_TRUE(did_request_redraw_);
EXPECT_TRUE(did_request_animate_);
host_impl_->DidFinishImplFrame();
// Another activation shouldn't have any effect on the animation.
host_impl_->ActivateSyncTree();
did_request_redraw_ = false;
did_request_animate_ = false;
begin_frame_args.frame_time = halfway_through_animation;
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
EXPECT_TRUE(did_request_redraw_);
EXPECT_TRUE(did_request_animate_);
host_impl_->DidFinishImplFrame();
did_request_redraw_ = false;
did_request_animate_ = false;
did_request_commit_ = false;
begin_frame_args.frame_time = end_time;
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
EXPECT_TRUE(did_request_commit_);
EXPECT_FALSE(did_request_animate_);
host_impl_->DidFinishImplFrame();
scoped_ptr<ScrollAndScaleSet> scroll_info =
host_impl_->ProcessScrollDeltas();
EXPECT_EQ(scroll_info->page_scale_delta, target_scale);
EXPECT_TRUE(ScrollInfoContains(*scroll_info, scroll_layer->id(),
gfx::Vector2d(-50, -50)));
}
TEST_F(LayerTreeHostImplTest, PageScaleAnimationCompletedNotification) {
SetupScrollAndContentsLayers(gfx::Size(100, 100));
host_impl_->SetViewportSize(gfx::Size(50, 50));
DrawFrame();
LayerImpl* scroll_layer = host_impl_->InnerViewportScrollLayer();
DCHECK(scroll_layer);
base::TimeTicks start_time =
base::TimeTicks() + base::TimeDelta::FromSeconds(1);
base::TimeDelta duration = base::TimeDelta::FromMilliseconds(100);
base::TimeTicks halfway_through_animation = start_time + duration / 2;
base::TimeTicks end_time = start_time + duration;
BeginFrameArgs begin_frame_args =
CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE);
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, 0.5f, 4.f);
scroll_layer->PushScrollOffsetFromMainThread(gfx::ScrollOffset(50, 50));
did_complete_page_scale_animation_ = false;
host_impl_->active_tree()->SetPendingPageScaleAnimation(
scoped_ptr<PendingPageScaleAnimation>(new PendingPageScaleAnimation(
gfx::Vector2d(), false, 2.f, duration)));
host_impl_->ActivateSyncTree();
begin_frame_args.frame_time = start_time;
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
EXPECT_FALSE(did_complete_page_scale_animation_);
host_impl_->DidFinishImplFrame();
begin_frame_args.frame_time = halfway_through_animation;
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
EXPECT_FALSE(did_complete_page_scale_animation_);
host_impl_->DidFinishImplFrame();
begin_frame_args.frame_time = end_time;
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
EXPECT_TRUE(did_complete_page_scale_animation_);
host_impl_->DidFinishImplFrame();
}
class LayerTreeHostImplOverridePhysicalTime : public LayerTreeHostImpl {
public:
LayerTreeHostImplOverridePhysicalTime(
const LayerTreeSettings& settings,
LayerTreeHostImplClient* client,
Proxy* proxy,
SharedBitmapManager* manager,
TaskGraphRunner* task_graph_runner,
RenderingStatsInstrumentation* rendering_stats_instrumentation)
: LayerTreeHostImpl(settings,
client,
proxy,
rendering_stats_instrumentation,
manager,
nullptr,
task_graph_runner,
0) {}
BeginFrameArgs CurrentBeginFrameArgs() const override {
return CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE,
fake_current_physical_time_);
}
void SetCurrentPhysicalTimeTicksForTest(base::TimeTicks fake_now) {
fake_current_physical_time_ = fake_now;
}
private:
base::TimeTicks fake_current_physical_time_;
};
class LayerTreeHostImplTestScrollbarAnimation : public LayerTreeHostImplTest {
protected:
void SetupLayers(LayerTreeSettings settings) {
gfx::Size content_size(100, 100);
LayerTreeHostImplOverridePhysicalTime* host_impl_override_time =
new LayerTreeHostImplOverridePhysicalTime(
settings, this, &proxy_, &shared_bitmap_manager_,
&task_graph_runner_, &stats_instrumentation_);
host_impl_ = make_scoped_ptr(host_impl_override_time);
host_impl_->InitializeRenderer(CreateOutputSurface());
SetupScrollAndContentsLayers(content_size);
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, 1.f, 4.f);
host_impl_->SetViewportSize(
gfx::Size(content_size.width() / 2, content_size.height() / 2));
scoped_ptr<SolidColorScrollbarLayerImpl> scrollbar =
SolidColorScrollbarLayerImpl::Create(host_impl_->active_tree(), 400,
VERTICAL, 10, 0, false, true);
EXPECT_FLOAT_EQ(0.f, scrollbar->opacity());
LayerImpl* scroll = host_impl_->InnerViewportScrollLayer();
LayerImpl* root = scroll->parent()->parent();
scrollbar->SetScrollLayerAndClipLayerByIds(scroll->id(), root->id());
root->AddChild(scrollbar.Pass());
host_impl_->active_tree()->DidBecomeActive();
DrawFrame();
}
void RunTest(LayerTreeSettings::ScrollbarAnimator animator) {
LayerTreeSettings settings;
settings.scrollbar_animator = animator;
settings.scrollbar_fade_delay_ms = 20;
settings.scrollbar_fade_duration_ms = 20;
SetupLayers(settings);
base::TimeTicks fake_now = base::TimeTicks::Now();
EXPECT_FALSE(did_request_animate_);
EXPECT_FALSE(did_request_redraw_);
EXPECT_EQ(base::TimeDelta(), requested_animation_delay_);
EXPECT_TRUE(animation_task_.Equals(base::Closure()));
// If no scroll happened during a scroll gesture, it should have no effect.
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL);
host_impl_->ScrollEnd();
EXPECT_FALSE(did_request_animate_);
EXPECT_FALSE(did_request_redraw_);
EXPECT_EQ(base::TimeDelta(), requested_animation_delay_);
EXPECT_TRUE(animation_task_.Equals(base::Closure()));
// After a scroll, a scrollbar animation should be scheduled about 20ms from
// now.
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL);
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2dF(0, 5));
EXPECT_FALSE(did_request_animate_);
EXPECT_TRUE(did_request_redraw_);
did_request_redraw_ = false;
EXPECT_EQ(base::TimeDelta(), requested_animation_delay_);
EXPECT_TRUE(animation_task_.Equals(base::Closure()));
host_impl_->ScrollEnd();
EXPECT_FALSE(did_request_animate_);
EXPECT_FALSE(did_request_redraw_);
EXPECT_EQ(base::TimeDelta::FromMilliseconds(20),
requested_animation_delay_);
EXPECT_FALSE(animation_task_.Equals(base::Closure()));
fake_now += requested_animation_delay_;
requested_animation_delay_ = base::TimeDelta();
animation_task_.Run();
animation_task_ = base::Closure();
EXPECT_TRUE(did_request_animate_);
did_request_animate_ = false;
EXPECT_FALSE(did_request_redraw_);
// After the scrollbar animation begins, we should start getting redraws.
BeginFrameArgs begin_frame_args =
CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE, fake_now);
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
EXPECT_TRUE(did_request_animate_);
did_request_animate_ = false;
EXPECT_TRUE(did_request_redraw_);
did_request_redraw_ = false;
EXPECT_EQ(base::TimeDelta(), requested_animation_delay_);
EXPECT_TRUE(animation_task_.Equals(base::Closure()));
host_impl_->DidFinishImplFrame();
// Setting the scroll offset outside a scroll should also cause the
// scrollbar to appear and to schedule a scrollbar animation.
host_impl_->InnerViewportScrollLayer()->PushScrollOffsetFromMainThread(
gfx::ScrollOffset(5, 5));
EXPECT_FALSE(did_request_animate_);
EXPECT_FALSE(did_request_redraw_);
EXPECT_EQ(base::TimeDelta::FromMilliseconds(20),
requested_animation_delay_);
EXPECT_FALSE(animation_task_.Equals(base::Closure()));
requested_animation_delay_ = base::TimeDelta();
animation_task_ = base::Closure();
// Scrollbar animation is not triggered unnecessarily.
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL);
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2dF(5, 0));
EXPECT_FALSE(did_request_animate_);
EXPECT_TRUE(did_request_redraw_);
did_request_redraw_ = false;
EXPECT_EQ(base::TimeDelta(), requested_animation_delay_);
EXPECT_TRUE(animation_task_.Equals(base::Closure()));
host_impl_->ScrollEnd();
EXPECT_FALSE(did_request_animate_);
EXPECT_FALSE(did_request_redraw_);
EXPECT_EQ(base::TimeDelta(), requested_animation_delay_);
EXPECT_TRUE(animation_task_.Equals(base::Closure()));
// Changing page scale triggers scrollbar animation.
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, 1.f, 4.f);
host_impl_->active_tree()->SetPageScaleOnActiveTree(1.1f);
EXPECT_FALSE(did_request_animate_);
EXPECT_FALSE(did_request_redraw_);
EXPECT_EQ(base::TimeDelta::FromMilliseconds(20),
requested_animation_delay_);
EXPECT_FALSE(animation_task_.Equals(base::Closure()));
requested_animation_delay_ = base::TimeDelta();
animation_task_ = base::Closure();
}
};
TEST_F(LayerTreeHostImplTestScrollbarAnimation, LinearFade) {
RunTest(LayerTreeSettings::LINEAR_FADE);
}
TEST_F(LayerTreeHostImplTestScrollbarAnimation, Thinning) {
RunTest(LayerTreeSettings::THINNING);
}
void LayerTreeHostImplTest::SetupMouseMoveAtWithDeviceScale(
float device_scale_factor) {
LayerTreeSettings settings;
settings.scrollbar_fade_delay_ms = 500;
settings.scrollbar_fade_duration_ms = 300;
settings.scrollbar_animator = LayerTreeSettings::THINNING;
gfx::Size viewport_size(300, 200);
gfx::Size device_viewport_size = gfx::ToFlooredSize(
gfx::ScaleSize(viewport_size, device_scale_factor));
gfx::Size content_size(1000, 1000);
CreateHostImpl(settings, CreateOutputSurface());
host_impl_->SetDeviceScaleFactor(device_scale_factor);
host_impl_->SetViewportSize(device_viewport_size);
scoped_ptr<LayerImpl> root =
LayerImpl::Create(host_impl_->active_tree(), 1);
root->SetBounds(viewport_size);
root->SetHasRenderSurface(true);
scoped_ptr<LayerImpl> scroll =
LayerImpl::Create(host_impl_->active_tree(), 2);
scroll->SetScrollClipLayer(root->id());
scroll->PushScrollOffsetFromMainThread(gfx::ScrollOffset());
scroll->SetBounds(content_size);
scroll->SetIsContainerForFixedPositionLayers(true);
scoped_ptr<LayerImpl> contents =
LayerImpl::Create(host_impl_->active_tree(), 3);
contents->SetDrawsContent(true);
contents->SetBounds(content_size);
// The scrollbar is on the right side.
scoped_ptr<PaintedScrollbarLayerImpl> scrollbar =
PaintedScrollbarLayerImpl::Create(host_impl_->active_tree(), 5, VERTICAL);
scrollbar->SetDrawsContent(true);
scrollbar->SetBounds(gfx::Size(15, viewport_size.height()));
scrollbar->SetPosition(gfx::Point(285, 0));
scroll->AddChild(contents.Pass());
root->AddChild(scroll.Pass());
scrollbar->SetScrollLayerAndClipLayerByIds(2, 1);
root->AddChild(scrollbar.Pass());
host_impl_->active_tree()->SetRootLayer(root.Pass());
host_impl_->active_tree()->SetViewportLayersFromIds(Layer::INVALID_ID, 1, 2,
Layer::INVALID_ID);
host_impl_->active_tree()->DidBecomeActive();
DrawFrame();
LayerImpl* root_scroll =
host_impl_->active_tree()->InnerViewportScrollLayer();
ASSERT_TRUE(root_scroll->scrollbar_animation_controller());
ScrollbarAnimationControllerThinning* scrollbar_animation_controller =
static_cast<ScrollbarAnimationControllerThinning*>(
root_scroll->scrollbar_animation_controller());
scrollbar_animation_controller->set_mouse_move_distance_for_test(100.f);
host_impl_->MouseMoveAt(gfx::Point(1, 1));
EXPECT_FALSE(scrollbar_animation_controller->mouse_is_near_scrollbar());
host_impl_->MouseMoveAt(gfx::Point(200, 50));
EXPECT_TRUE(scrollbar_animation_controller->mouse_is_near_scrollbar());
host_impl_->MouseMoveAt(gfx::Point(184, 100));
EXPECT_FALSE(scrollbar_animation_controller->mouse_is_near_scrollbar());
scrollbar_animation_controller->set_mouse_move_distance_for_test(102.f);
host_impl_->MouseMoveAt(gfx::Point(184, 100));
EXPECT_TRUE(scrollbar_animation_controller->mouse_is_near_scrollbar());
did_request_redraw_ = false;
EXPECT_EQ(0, host_impl_->scroll_layer_id_when_mouse_over_scrollbar());
host_impl_->MouseMoveAt(gfx::Point(290, 100));
EXPECT_EQ(2, host_impl_->scroll_layer_id_when_mouse_over_scrollbar());
host_impl_->MouseMoveAt(gfx::Point(290, 120));
EXPECT_EQ(2, host_impl_->scroll_layer_id_when_mouse_over_scrollbar());
host_impl_->MouseMoveAt(gfx::Point(150, 120));
EXPECT_EQ(0, host_impl_->scroll_layer_id_when_mouse_over_scrollbar());
}
TEST_F(LayerTreeHostImplTest, MouseMoveAtWithDeviceScaleOf1) {
SetupMouseMoveAtWithDeviceScale(1.f);
}
TEST_F(LayerTreeHostImplTest, MouseMoveAtWithDeviceScaleOf2) {
SetupMouseMoveAtWithDeviceScale(2.f);
}
TEST_F(LayerTreeHostImplTest, CompositorFrameMetadata) {
SetupScrollAndContentsLayers(gfx::Size(100, 100));
host_impl_->SetViewportSize(gfx::Size(50, 50));
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, 0.5f, 4.f);
DrawFrame();
{
CompositorFrameMetadata metadata =
host_impl_->MakeCompositorFrameMetadata();
EXPECT_EQ(gfx::Vector2dF(), metadata.root_scroll_offset);
EXPECT_EQ(1.f, metadata.page_scale_factor);
EXPECT_EQ(gfx::SizeF(50.f, 50.f), metadata.scrollable_viewport_size);
EXPECT_EQ(gfx::SizeF(100.f, 100.f), metadata.root_layer_size);
EXPECT_EQ(0.5f, metadata.min_page_scale_factor);
EXPECT_EQ(4.f, metadata.max_page_scale_factor);
EXPECT_FALSE(metadata.root_overflow_x_hidden);
EXPECT_FALSE(metadata.root_overflow_y_hidden);
}
// Scrolling should update metadata immediately.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, 10));
{
CompositorFrameMetadata metadata =
host_impl_->MakeCompositorFrameMetadata();
EXPECT_EQ(gfx::Vector2dF(0.f, 10.f), metadata.root_scroll_offset);
}
host_impl_->ScrollEnd();
{
CompositorFrameMetadata metadata =
host_impl_->MakeCompositorFrameMetadata();
EXPECT_EQ(gfx::Vector2dF(0.f, 10.f), metadata.root_scroll_offset);
}
// Root "overflow: hidden" properties should be reflected on the outer
// viewport scroll layer.
{
host_impl_->active_tree()
->OuterViewportScrollLayer()
->set_user_scrollable_horizontal(false);
CompositorFrameMetadata metadata =
host_impl_->MakeCompositorFrameMetadata();
EXPECT_TRUE(metadata.root_overflow_x_hidden);
EXPECT_FALSE(metadata.root_overflow_y_hidden);
host_impl_->active_tree()
->OuterViewportScrollLayer()
->set_user_scrollable_vertical(false);
metadata = host_impl_->MakeCompositorFrameMetadata();
EXPECT_TRUE(metadata.root_overflow_x_hidden);
EXPECT_TRUE(metadata.root_overflow_y_hidden);
}
// Re-enable scrollability and verify that overflows are no longer hidden.
{
host_impl_->active_tree()
->OuterViewportScrollLayer()
->set_user_scrollable_horizontal(true);
host_impl_->active_tree()
->OuterViewportScrollLayer()
->set_user_scrollable_vertical(true);
CompositorFrameMetadata metadata =
host_impl_->MakeCompositorFrameMetadata();
EXPECT_FALSE(metadata.root_overflow_x_hidden);
EXPECT_FALSE(metadata.root_overflow_y_hidden);
}
// Root "overflow: hidden" properties should also be reflected on the
// inner viewport scroll layer.
{
host_impl_->active_tree()
->InnerViewportScrollLayer()
->set_user_scrollable_horizontal(false);
CompositorFrameMetadata metadata =
host_impl_->MakeCompositorFrameMetadata();
EXPECT_TRUE(metadata.root_overflow_x_hidden);
EXPECT_FALSE(metadata.root_overflow_y_hidden);
host_impl_->active_tree()
->InnerViewportScrollLayer()
->set_user_scrollable_vertical(false);
metadata = host_impl_->MakeCompositorFrameMetadata();
EXPECT_TRUE(metadata.root_overflow_x_hidden);
EXPECT_TRUE(metadata.root_overflow_y_hidden);
}
// Page scale should update metadata correctly (shrinking only the viewport).
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE);
host_impl_->PinchGestureBegin();
host_impl_->PinchGestureUpdate(2.f, gfx::Point());
host_impl_->PinchGestureEnd();
host_impl_->ScrollEnd();
{
CompositorFrameMetadata metadata =
host_impl_->MakeCompositorFrameMetadata();
EXPECT_EQ(gfx::Vector2dF(0.f, 10.f), metadata.root_scroll_offset);
EXPECT_EQ(2.f, metadata.page_scale_factor);
EXPECT_EQ(gfx::SizeF(25.f, 25.f), metadata.scrollable_viewport_size);
EXPECT_EQ(gfx::SizeF(100.f, 100.f), metadata.root_layer_size);
EXPECT_EQ(0.5f, metadata.min_page_scale_factor);
EXPECT_EQ(4.f, metadata.max_page_scale_factor);
}
// Likewise if set from the main thread.
host_impl_->ProcessScrollDeltas();
host_impl_->active_tree()->PushPageScaleFromMainThread(4.f, 0.5f, 4.f);
host_impl_->active_tree()->SetPageScaleOnActiveTree(4.f);
{
CompositorFrameMetadata metadata =
host_impl_->MakeCompositorFrameMetadata();
EXPECT_EQ(gfx::Vector2dF(0.f, 10.f), metadata.root_scroll_offset);
EXPECT_EQ(4.f, metadata.page_scale_factor);
EXPECT_EQ(gfx::SizeF(12.5f, 12.5f), metadata.scrollable_viewport_size);
EXPECT_EQ(gfx::SizeF(100.f, 100.f), metadata.root_layer_size);
EXPECT_EQ(0.5f, metadata.min_page_scale_factor);
EXPECT_EQ(4.f, metadata.max_page_scale_factor);
}
}
class DidDrawCheckLayer : public LayerImpl {
public:
static scoped_ptr<LayerImpl> Create(LayerTreeImpl* tree_impl, int id) {
return make_scoped_ptr(new DidDrawCheckLayer(tree_impl, id));
}
bool WillDraw(DrawMode draw_mode, ResourceProvider* provider) override {
will_draw_called_ = true;
if (will_draw_returns_false_)
return false;
return LayerImpl::WillDraw(draw_mode, provider);
}
void AppendQuads(RenderPass* render_pass,
AppendQuadsData* append_quads_data) override {
append_quads_called_ = true;
LayerImpl::AppendQuads(render_pass, append_quads_data);
}
void DidDraw(ResourceProvider* provider) override {
did_draw_called_ = true;
LayerImpl::DidDraw(provider);
}
bool will_draw_called() const { return will_draw_called_; }
bool append_quads_called() const { return append_quads_called_; }
bool did_draw_called() const { return did_draw_called_; }
void set_will_draw_returns_false() { will_draw_returns_false_ = true; }
void ClearDidDrawCheck() {
will_draw_called_ = false;
append_quads_called_ = false;
did_draw_called_ = false;
}
static void IgnoreResult(scoped_ptr<CopyOutputResult> result) {}
void AddCopyRequest() {
ScopedPtrVector<CopyOutputRequest> requests;
requests.push_back(
CopyOutputRequest::CreateRequest(base::Bind(&IgnoreResult)));
SetHasRenderSurface(true);
PassCopyRequests(&requests);
}
protected:
DidDrawCheckLayer(LayerTreeImpl* tree_impl, int id)
: LayerImpl(tree_impl, id),
will_draw_returns_false_(false),
will_draw_called_(false),
append_quads_called_(false),
did_draw_called_(false) {
SetBounds(gfx::Size(10, 10));
SetDrawsContent(true);
draw_properties().visible_layer_rect = gfx::Rect(0, 0, 10, 10);
}
private:
bool will_draw_returns_false_;
bool will_draw_called_;
bool append_quads_called_;
bool did_draw_called_;
};
TEST_F(LayerTreeHostImplTest, WillDrawReturningFalseDoesNotCall) {
// The root layer is always drawn, so run this test on a child layer that
// will be masked out by the root layer's bounds.
host_impl_->active_tree()->SetRootLayer(
DidDrawCheckLayer::Create(host_impl_->active_tree(), 1));
DidDrawCheckLayer* root = static_cast<DidDrawCheckLayer*>(
host_impl_->active_tree()->root_layer());
root->AddChild(DidDrawCheckLayer::Create(host_impl_->active_tree(), 2));
root->SetHasRenderSurface(true);
DidDrawCheckLayer* layer =
static_cast<DidDrawCheckLayer*>(root->children()[0]);
{
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
EXPECT_TRUE(layer->will_draw_called());
EXPECT_TRUE(layer->append_quads_called());
EXPECT_TRUE(layer->did_draw_called());
}
host_impl_->SetViewportDamage(gfx::Rect(10, 10));
{
LayerTreeHostImpl::FrameData frame;
layer->set_will_draw_returns_false();
layer->ClearDidDrawCheck();
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
EXPECT_TRUE(layer->will_draw_called());
EXPECT_FALSE(layer->append_quads_called());
EXPECT_FALSE(layer->did_draw_called());
}
}
TEST_F(LayerTreeHostImplTest, DidDrawNotCalledOnHiddenLayer) {
// The root layer is always drawn, so run this test on a child layer that
// will be masked out by the root layer's bounds.
host_impl_->active_tree()->SetRootLayer(
DidDrawCheckLayer::Create(host_impl_->active_tree(), 1));
DidDrawCheckLayer* root = static_cast<DidDrawCheckLayer*>(
host_impl_->active_tree()->root_layer());
root->SetMasksToBounds(true);
root->SetHasRenderSurface(true);
root->AddChild(DidDrawCheckLayer::Create(host_impl_->active_tree(), 2));
DidDrawCheckLayer* layer =
static_cast<DidDrawCheckLayer*>(root->children()[0]);
// Ensure visible_layer_rect for layer is empty.
layer->SetPosition(gfx::PointF(100.f, 100.f));
layer->SetBounds(gfx::Size(10, 10));
LayerTreeHostImpl::FrameData frame;
EXPECT_FALSE(layer->will_draw_called());
EXPECT_FALSE(layer->did_draw_called());
host_impl_->active_tree()->BuildPropertyTreesForTesting();
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
EXPECT_FALSE(layer->will_draw_called());
EXPECT_FALSE(layer->did_draw_called());
EXPECT_TRUE(layer->visible_layer_rect().IsEmpty());
// Ensure visible_layer_rect for layer is not empty
layer->SetPosition(gfx::PointF());
EXPECT_FALSE(layer->will_draw_called());
EXPECT_FALSE(layer->did_draw_called());
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
EXPECT_TRUE(layer->will_draw_called());
EXPECT_TRUE(layer->did_draw_called());
EXPECT_FALSE(layer->visible_layer_rect().IsEmpty());
}
TEST_F(LayerTreeHostImplTest, WillDrawNotCalledOnOccludedLayer) {
gfx::Size big_size(1000, 1000);
host_impl_->SetViewportSize(big_size);
host_impl_->active_tree()->SetRootLayer(
DidDrawCheckLayer::Create(host_impl_->active_tree(), 1));
DidDrawCheckLayer* root =
static_cast<DidDrawCheckLayer*>(host_impl_->active_tree()->root_layer());
root->AddChild(DidDrawCheckLayer::Create(host_impl_->active_tree(), 2));
DidDrawCheckLayer* occluded_layer =
static_cast<DidDrawCheckLayer*>(root->children()[0]);
root->AddChild(DidDrawCheckLayer::Create(host_impl_->active_tree(), 3));
root->SetHasRenderSurface(true);
DidDrawCheckLayer* top_layer =
static_cast<DidDrawCheckLayer*>(root->children()[1]);
// This layer covers the occluded_layer above. Make this layer large so it can
// occlude.
top_layer->SetBounds(big_size);
top_layer->SetContentsOpaque(true);
LayerTreeHostImpl::FrameData frame;
EXPECT_FALSE(occluded_layer->will_draw_called());
EXPECT_FALSE(occluded_layer->did_draw_called());
EXPECT_FALSE(top_layer->will_draw_called());
EXPECT_FALSE(top_layer->did_draw_called());
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
EXPECT_FALSE(occluded_layer->will_draw_called());
EXPECT_FALSE(occluded_layer->did_draw_called());
EXPECT_TRUE(top_layer->will_draw_called());
EXPECT_TRUE(top_layer->did_draw_called());
}
TEST_F(LayerTreeHostImplTest, DidDrawCalledOnAllLayers) {
host_impl_->active_tree()->SetRootLayer(
DidDrawCheckLayer::Create(host_impl_->active_tree(), 1));
DidDrawCheckLayer* root =
static_cast<DidDrawCheckLayer*>(host_impl_->active_tree()->root_layer());
root->AddChild(DidDrawCheckLayer::Create(host_impl_->active_tree(), 2));
root->SetHasRenderSurface(true);
DidDrawCheckLayer* layer1 =
static_cast<DidDrawCheckLayer*>(root->children()[0]);
layer1->AddChild(DidDrawCheckLayer::Create(host_impl_->active_tree(), 3));
DidDrawCheckLayer* layer2 =
static_cast<DidDrawCheckLayer*>(layer1->children()[0]);
layer1->SetHasRenderSurface(true);
layer1->SetShouldFlattenTransform(true);
EXPECT_FALSE(root->did_draw_called());
EXPECT_FALSE(layer1->did_draw_called());
EXPECT_FALSE(layer2->did_draw_called());
LayerTreeHostImpl::FrameData frame;
FakeLayerTreeHostImpl::RecursiveUpdateNumChildren(
host_impl_->active_tree()->root_layer());
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
EXPECT_TRUE(root->did_draw_called());
EXPECT_TRUE(layer1->did_draw_called());
EXPECT_TRUE(layer2->did_draw_called());
EXPECT_NE(root->render_surface(), layer1->render_surface());
EXPECT_TRUE(layer1->render_surface());
}
class MissingTextureAnimatingLayer : public DidDrawCheckLayer {
public:
static scoped_ptr<LayerImpl> Create(LayerTreeImpl* tree_impl,
int id,
bool tile_missing,
bool had_incomplete_tile,
bool animating,
ResourceProvider* resource_provider) {
return make_scoped_ptr(new MissingTextureAnimatingLayer(tree_impl,
id,
tile_missing,
had_incomplete_tile,
animating,
resource_provider));
}
void AppendQuads(RenderPass* render_pass,
AppendQuadsData* append_quads_data) override {
LayerImpl::AppendQuads(render_pass, append_quads_data);
if (had_incomplete_tile_)
append_quads_data->num_incomplete_tiles++;
if (tile_missing_)
append_quads_data->num_missing_tiles++;
}
private:
MissingTextureAnimatingLayer(LayerTreeImpl* tree_impl,
int id,
bool tile_missing,
bool had_incomplete_tile,
bool animating,
ResourceProvider* resource_provider)
: DidDrawCheckLayer(tree_impl, id),
tile_missing_(tile_missing),
had_incomplete_tile_(had_incomplete_tile) {
if (animating)
AddAnimatedTransformToLayer(this, 10.0, 3, 0);
}
bool tile_missing_;
bool had_incomplete_tile_;
};
struct PrepareToDrawSuccessTestCase {
struct State {
bool has_missing_tile = false;
bool has_incomplete_tile = false;
bool is_animating = false;
bool has_copy_request = false;
};
bool high_res_required = false;
State layer_before;
State layer_between;
State layer_after;
DrawResult expected_result;
explicit PrepareToDrawSuccessTestCase(DrawResult result)
: expected_result(result) {}
};
TEST_F(LayerTreeHostImplTest, PrepareToDrawSucceedsAndFails) {
std::vector<PrepareToDrawSuccessTestCase> cases;
// 0. Default case.
cases.push_back(PrepareToDrawSuccessTestCase(DRAW_SUCCESS));
// 1. Animated layer first.
cases.push_back(PrepareToDrawSuccessTestCase(DRAW_SUCCESS));
cases.back().layer_before.is_animating = true;
// 2. Animated layer between.
cases.push_back(PrepareToDrawSuccessTestCase(DRAW_SUCCESS));
cases.back().layer_between.is_animating = true;
// 3. Animated layer last.
cases.push_back(PrepareToDrawSuccessTestCase(DRAW_SUCCESS));
cases.back().layer_after.is_animating = true;
// 4. Missing tile first.
cases.push_back(PrepareToDrawSuccessTestCase(DRAW_SUCCESS));
cases.back().layer_before.has_missing_tile = true;
// 5. Missing tile between.
cases.push_back(PrepareToDrawSuccessTestCase(DRAW_SUCCESS));
cases.back().layer_between.has_missing_tile = true;
// 6. Missing tile last.
cases.push_back(PrepareToDrawSuccessTestCase(DRAW_SUCCESS));
cases.back().layer_after.has_missing_tile = true;
// 7. Incomplete tile first.
cases.push_back(PrepareToDrawSuccessTestCase(DRAW_SUCCESS));
cases.back().layer_before.has_incomplete_tile = true;
// 8. Incomplete tile between.
cases.push_back(PrepareToDrawSuccessTestCase(DRAW_SUCCESS));
cases.back().layer_between.has_incomplete_tile = true;
// 9. Incomplete tile last.
cases.push_back(PrepareToDrawSuccessTestCase(DRAW_SUCCESS));
cases.back().layer_after.has_incomplete_tile = true;
// 10. Animation with missing tile.
cases.push_back(
PrepareToDrawSuccessTestCase(DRAW_ABORTED_CHECKERBOARD_ANIMATIONS));
cases.back().layer_between.has_missing_tile = true;
cases.back().layer_between.is_animating = true;
// 11. Animation with incomplete tile.
cases.push_back(PrepareToDrawSuccessTestCase(DRAW_SUCCESS));
cases.back().layer_between.has_incomplete_tile = true;
cases.back().layer_between.is_animating = true;
// 12. High res required.
cases.push_back(PrepareToDrawSuccessTestCase(DRAW_SUCCESS));
cases.back().high_res_required = true;
// 13. High res required with incomplete tile.
cases.push_back(
PrepareToDrawSuccessTestCase(DRAW_ABORTED_MISSING_HIGH_RES_CONTENT));
cases.back().high_res_required = true;
cases.back().layer_between.has_incomplete_tile = true;
// 14. High res required with missing tile.
cases.push_back(
PrepareToDrawSuccessTestCase(DRAW_ABORTED_MISSING_HIGH_RES_CONTENT));
cases.back().high_res_required = true;
cases.back().layer_between.has_missing_tile = true;
// 15. High res required is higher priority than animating missing tiles.
cases.push_back(
PrepareToDrawSuccessTestCase(DRAW_ABORTED_MISSING_HIGH_RES_CONTENT));
cases.back().high_res_required = true;
cases.back().layer_between.has_missing_tile = true;
cases.back().layer_after.has_missing_tile = true;
cases.back().layer_after.is_animating = true;
// 16. High res required is higher priority than animating missing tiles.
cases.push_back(
PrepareToDrawSuccessTestCase(DRAW_ABORTED_MISSING_HIGH_RES_CONTENT));
cases.back().high_res_required = true;
cases.back().layer_between.has_missing_tile = true;
cases.back().layer_before.has_missing_tile = true;
cases.back().layer_before.is_animating = true;
host_impl_->active_tree()->SetRootLayer(
DidDrawCheckLayer::Create(host_impl_->active_tree(), 1));
DidDrawCheckLayer* root =
static_cast<DidDrawCheckLayer*>(host_impl_->active_tree()->root_layer());
root->SetHasRenderSurface(true);
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
host_impl_->SwapBuffers(frame);
for (size_t i = 0; i < cases.size(); ++i) {
const auto& testcase = cases[i];
std::vector<LayerImpl*> to_remove;
for (auto* child : root->children())
to_remove.push_back(child);
for (auto* child : to_remove)
root->RemoveChild(child);
std::ostringstream scope;
scope << "Test case: " << i;
SCOPED_TRACE(scope.str());
root->AddChild(MissingTextureAnimatingLayer::Create(
host_impl_->active_tree(), 2, testcase.layer_before.has_missing_tile,
testcase.layer_before.has_incomplete_tile,
testcase.layer_before.is_animating, host_impl_->resource_provider()));
DidDrawCheckLayer* before =
static_cast<DidDrawCheckLayer*>(root->children().back());
if (testcase.layer_before.has_copy_request)
before->AddCopyRequest();
root->AddChild(MissingTextureAnimatingLayer::Create(
host_impl_->active_tree(), 3, testcase.layer_between.has_missing_tile,
testcase.layer_between.has_incomplete_tile,
testcase.layer_between.is_animating, host_impl_->resource_provider()));
DidDrawCheckLayer* between =
static_cast<DidDrawCheckLayer*>(root->children().back());
if (testcase.layer_between.has_copy_request)
between->AddCopyRequest();
root->AddChild(MissingTextureAnimatingLayer::Create(
host_impl_->active_tree(), 4, testcase.layer_after.has_missing_tile,
testcase.layer_after.has_incomplete_tile,
testcase.layer_after.is_animating, host_impl_->resource_provider()));
DidDrawCheckLayer* after =
static_cast<DidDrawCheckLayer*>(root->children().back());
if (testcase.layer_after.has_copy_request)
after->AddCopyRequest();
if (testcase.high_res_required)
host_impl_->SetRequiresHighResToDraw();
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(testcase.expected_result, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
host_impl_->SwapBuffers(frame);
}
}
TEST_F(LayerTreeHostImplTest,
PrepareToDrawWhenDrawAndSwapFullViewportEveryFrame) {
CreateHostImpl(DefaultSettings(),
FakeOutputSurface::CreateAlwaysDrawAndSwap3d());
EXPECT_TRUE(host_impl_->output_surface()
->capabilities()
.draw_and_swap_full_viewport_every_frame);
std::vector<PrepareToDrawSuccessTestCase> cases;
// 0. Default case.
cases.push_back(PrepareToDrawSuccessTestCase(DRAW_SUCCESS));
// 1. Animation with missing tile.
cases.push_back(PrepareToDrawSuccessTestCase(DRAW_SUCCESS));
cases.back().layer_between.has_missing_tile = true;
cases.back().layer_between.is_animating = true;
// 2. High res required with incomplete tile.
cases.push_back(PrepareToDrawSuccessTestCase(DRAW_SUCCESS));
cases.back().high_res_required = true;
cases.back().layer_between.has_incomplete_tile = true;
// 3. High res required with missing tile.
cases.push_back(PrepareToDrawSuccessTestCase(DRAW_SUCCESS));
cases.back().high_res_required = true;
cases.back().layer_between.has_missing_tile = true;
host_impl_->active_tree()->SetRootLayer(
DidDrawCheckLayer::Create(host_impl_->active_tree(), 1));
DidDrawCheckLayer* root =
static_cast<DidDrawCheckLayer*>(host_impl_->active_tree()->root_layer());
root->SetHasRenderSurface(true);
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
host_impl_->SwapBuffers(frame);
for (size_t i = 0; i < cases.size(); ++i) {
const auto& testcase = cases[i];
std::vector<LayerImpl*> to_remove;
for (auto* child : root->children())
to_remove.push_back(child);
for (auto* child : to_remove)
root->RemoveChild(child);
std::ostringstream scope;
scope << "Test case: " << i;
SCOPED_TRACE(scope.str());
root->AddChild(MissingTextureAnimatingLayer::Create(
host_impl_->active_tree(), 2, testcase.layer_before.has_missing_tile,
testcase.layer_before.has_incomplete_tile,
testcase.layer_before.is_animating, host_impl_->resource_provider()));
DidDrawCheckLayer* before =
static_cast<DidDrawCheckLayer*>(root->children().back());
if (testcase.layer_before.has_copy_request)
before->AddCopyRequest();
root->AddChild(MissingTextureAnimatingLayer::Create(
host_impl_->active_tree(), 3, testcase.layer_between.has_missing_tile,
testcase.layer_between.has_incomplete_tile,
testcase.layer_between.is_animating, host_impl_->resource_provider()));
DidDrawCheckLayer* between =
static_cast<DidDrawCheckLayer*>(root->children().back());
if (testcase.layer_between.has_copy_request)
between->AddCopyRequest();
root->AddChild(MissingTextureAnimatingLayer::Create(
host_impl_->active_tree(), 4, testcase.layer_after.has_missing_tile,
testcase.layer_after.has_incomplete_tile,
testcase.layer_after.is_animating, host_impl_->resource_provider()));
DidDrawCheckLayer* after =
static_cast<DidDrawCheckLayer*>(root->children().back());
if (testcase.layer_after.has_copy_request)
after->AddCopyRequest();
if (testcase.high_res_required)
host_impl_->SetRequiresHighResToDraw();
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(testcase.expected_result, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
host_impl_->SwapBuffers(frame);
}
}
TEST_F(LayerTreeHostImplTest, ScrollRootIgnored) {
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl_->active_tree(), 1);
root->SetScrollClipLayer(Layer::INVALID_ID);
root->SetHasRenderSurface(true);
host_impl_->active_tree()->SetRootLayer(root.Pass());
DrawFrame();
// Scroll event is ignored because layer is not scrollable.
EXPECT_EQ(InputHandler::SCROLL_IGNORED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
EXPECT_FALSE(did_request_redraw_);
EXPECT_FALSE(did_request_commit_);
}
TEST_F(LayerTreeHostImplTest, ClampingAfterActivation) {
host_impl_->CreatePendingTree();
host_impl_->pending_tree()->PushPageScaleFromMainThread(1.f, 1.f, 1.f);
CreateScrollAndContentsLayers(host_impl_->pending_tree(),
gfx::Size(100, 100));
host_impl_->ActivateSyncTree();
host_impl_->CreatePendingTree();
const gfx::ScrollOffset pending_scroll = gfx::ScrollOffset(-100, -100);
LayerImpl* active_outer_layer =
host_impl_->active_tree()->OuterViewportScrollLayer();
LayerImpl* pending_outer_layer =
host_impl_->pending_tree()->OuterViewportScrollLayer();
pending_outer_layer->PushScrollOffsetFromMainThread(pending_scroll);
host_impl_->ActivateSyncTree();
// Scrolloffsets on the active tree will be clamped after activation.
EXPECT_EQ(active_outer_layer->CurrentScrollOffset(), gfx::ScrollOffset(0, 0));
}
class LayerTreeHostImplTopControlsTest : public LayerTreeHostImplTest {
public:
LayerTreeHostImplTopControlsTest()
// Make the clip size the same as the layer (content) size so the layer is
// non-scrollable.
: layer_size_(10, 10),
clip_size_(layer_size_),
top_controls_height_(50) {
viewport_size_ = gfx::Size(clip_size_.width(),
clip_size_.height() + top_controls_height_);
}
bool CreateHostImpl(const LayerTreeSettings& settings,
scoped_ptr<OutputSurface> output_surface) override {
bool init =
LayerTreeHostImplTest::CreateHostImpl(settings, output_surface.Pass());
if (init) {
host_impl_->active_tree()->set_top_controls_height(top_controls_height_);
host_impl_->active_tree()->SetCurrentTopControlsShownRatio(1.f);
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, 1.f, 1.f);
}
return init;
}
void SetupTopControlsAndScrollLayerWithVirtualViewport(
const gfx::Size& inner_viewport_size,
const gfx::Size& outer_viewport_size,
const gfx::Size& scroll_layer_size) {
CreateHostImpl(settings_, CreateOutputSurface());
host_impl_->sync_tree()->set_top_controls_shrink_blink_size(true);
host_impl_->sync_tree()->set_top_controls_height(top_controls_height_);
host_impl_->DidChangeTopControlsPosition();
scoped_ptr<LayerImpl> root =
LayerImpl::Create(host_impl_->active_tree(), 1);
scoped_ptr<LayerImpl> root_clip =
LayerImpl::Create(host_impl_->active_tree(), 2);
scoped_ptr<LayerImpl> page_scale =
LayerImpl::Create(host_impl_->active_tree(), 3);
scoped_ptr<LayerImpl> outer_scroll =
LayerImpl::Create(host_impl_->active_tree(), 4);
scoped_ptr<LayerImpl> outer_clip =
LayerImpl::Create(host_impl_->active_tree(), 5);
root_clip->SetBounds(inner_viewport_size);
root->SetScrollClipLayer(root_clip->id());
root->SetBounds(outer_viewport_size);
root->SetPosition(gfx::PointF());
root->SetDrawsContent(false);
root->SetIsContainerForFixedPositionLayers(true);
root_clip->SetHasRenderSurface(true);
outer_clip->SetBounds(outer_viewport_size);
outer_scroll->SetScrollClipLayer(outer_clip->id());
outer_scroll->SetBounds(scroll_layer_size);
outer_scroll->SetPosition(gfx::PointF());
outer_scroll->SetDrawsContent(false);
outer_scroll->SetIsContainerForFixedPositionLayers(true);
int inner_viewport_scroll_layer_id = root->id();
int outer_viewport_scroll_layer_id = outer_scroll->id();
int page_scale_layer_id = page_scale->id();
outer_clip->AddChild(outer_scroll.Pass());
root->AddChild(outer_clip.Pass());
page_scale->AddChild(root.Pass());
root_clip->AddChild(page_scale.Pass());
host_impl_->active_tree()->SetRootLayer(root_clip.Pass());
host_impl_->active_tree()->SetViewportLayersFromIds(
Layer::INVALID_ID, page_scale_layer_id, inner_viewport_scroll_layer_id,
outer_viewport_scroll_layer_id);
host_impl_->SetViewportSize(inner_viewport_size);
LayerImpl* root_clip_ptr = host_impl_->active_tree()->root_layer();
EXPECT_EQ(inner_viewport_size, root_clip_ptr->bounds());
}
protected:
gfx::Size layer_size_;
gfx::Size clip_size_;
gfx::Size viewport_size_;
float top_controls_height_;
LayerTreeSettings settings_;
}; // class LayerTreeHostImplTopControlsTest
// Tests that, on a page with content the same size as the viewport, hiding
// the top controls also increases the ScrollableSize (i.e. the content size).
// Since the viewport got larger, the effective scrollable "content" also did.
// This ensures, for one thing, that the overscroll glow is shown in the right
// place.
TEST_F(LayerTreeHostImplTopControlsTest,
HidingTopControlsExpandsScrollableSize) {
SetupTopControlsAndScrollLayerWithVirtualViewport(
gfx::Size(50, 50), gfx::Size(50, 50), gfx::Size(50, 50));
LayerTreeImpl* active_tree = host_impl_->active_tree();
// Create a content layer beneath the outer viewport scroll layer.
int id = host_impl_->OuterViewportScrollLayer()->id();
host_impl_->OuterViewportScrollLayer()->AddChild(
LayerImpl::Create(host_impl_->active_tree(), id + 2));
LayerImpl* content = active_tree->OuterViewportScrollLayer()->children()[0];
content->SetBounds(gfx::Size(50, 50));
DrawFrame();
LayerImpl* inner_container = active_tree->InnerViewportContainerLayer();
LayerImpl* outer_container = active_tree->OuterViewportContainerLayer();
// The top controls should start off showing so the viewport should be shrunk.
ASSERT_EQ(gfx::Size(50, 50), inner_container->bounds());
ASSERT_EQ(gfx::Size(50, 50), outer_container->bounds());
EXPECT_EQ(gfx::SizeF(50, 50), active_tree->ScrollableSize());
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
host_impl_->top_controls_manager()->ScrollBegin();
// Hide the top controls by a bit, the scrollable size should increase but the
// actual content bounds shouldn't.
{
host_impl_->top_controls_manager()->ScrollBy(gfx::Vector2dF(0.f, 25.f));
ASSERT_EQ(gfx::Size(50, 75), inner_container->bounds());
ASSERT_EQ(gfx::Size(50, 75), outer_container->bounds());
EXPECT_EQ(gfx::SizeF(50, 75), active_tree->ScrollableSize());
EXPECT_EQ(gfx::SizeF(50, 50), content->BoundsForScrolling());
}
// Fully hide the top controls.
{
host_impl_->top_controls_manager()->ScrollBy(gfx::Vector2dF(0.f, 25.f));
ASSERT_EQ(gfx::Size(50, 100), inner_container->bounds());
ASSERT_EQ(gfx::Size(50, 100), outer_container->bounds());
EXPECT_EQ(gfx::SizeF(50, 100), active_tree->ScrollableSize());
EXPECT_EQ(gfx::SizeF(50, 50), content->BoundsForScrolling());
}
// Scrolling additionally shouldn't have any effect.
{
host_impl_->top_controls_manager()->ScrollBy(gfx::Vector2dF(0.f, 25.f));
ASSERT_EQ(gfx::Size(50, 100), inner_container->bounds());
ASSERT_EQ(gfx::Size(50, 100), outer_container->bounds());
EXPECT_EQ(gfx::SizeF(50, 100), active_tree->ScrollableSize());
EXPECT_EQ(gfx::SizeF(50, 50), content->BoundsForScrolling());
}
host_impl_->top_controls_manager()->ScrollEnd();
host_impl_->ScrollEnd();
}
TEST_F(LayerTreeHostImplTopControlsTest, ScrollTopControlsByFractionalAmount) {
SetupTopControlsAndScrollLayerWithVirtualViewport(
gfx::Size(10, 10), gfx::Size(10, 10), gfx::Size(10, 10));
DrawFrame();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
// Make the test scroll delta a fractional amount, to verify that the
// fixed container size delta is (1) non-zero, and (2) fractional, and
// (3) matches the movement of the top controls.
gfx::Vector2dF top_controls_scroll_delta(0.f, 5.25f);
host_impl_->top_controls_manager()->ScrollBegin();
host_impl_->top_controls_manager()->ScrollBy(top_controls_scroll_delta);
host_impl_->top_controls_manager()->ScrollEnd();
LayerImpl* inner_viewport_scroll_layer =
host_impl_->active_tree()->InnerViewportScrollLayer();
DCHECK(inner_viewport_scroll_layer);
host_impl_->ScrollEnd();
EXPECT_FLOAT_EQ(top_controls_scroll_delta.y(),
inner_viewport_scroll_layer->FixedContainerSizeDelta().y());
}
// In this test, the outer viewport is initially unscrollable. We test that a
// scroll initiated on the inner viewport, causing the top controls to show and
// thus making the outer viewport scrollable, still scrolls the outer viewport.
TEST_F(LayerTreeHostImplTopControlsTest,
TopControlsOuterViewportBecomesScrollable) {
SetupTopControlsAndScrollLayerWithVirtualViewport(
gfx::Size(10, 50), gfx::Size(10, 50), gfx::Size(10, 100));
DrawFrame();
LayerImpl* inner_scroll =
host_impl_->active_tree()->InnerViewportScrollLayer();
LayerImpl* inner_container =
host_impl_->active_tree()->InnerViewportContainerLayer();
LayerImpl* outer_scroll =
host_impl_->active_tree()->OuterViewportScrollLayer();
LayerImpl* outer_container =
host_impl_->active_tree()->OuterViewportContainerLayer();
// Need SetDrawsContent so ScrollBegin's hit test finds an actual layer.
outer_scroll->SetDrawsContent(true);
host_impl_->active_tree()->PushPageScaleFromMainThread(2.f, 1.f, 2.f);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2dF(0.f, 50.f));
// The entire scroll delta should have been used to hide the top controls.
// The viewport layers should be resized back to their full sizes.
EXPECT_EQ(0.f, host_impl_->active_tree()->CurrentTopControlsShownRatio());
EXPECT_EQ(0.f, inner_scroll->CurrentScrollOffset().y());
EXPECT_EQ(100.f, inner_container->BoundsForScrolling().height());
EXPECT_EQ(100.f, outer_container->BoundsForScrolling().height());
// The inner viewport should be scrollable by 50px * page_scale.
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2dF(0.f, 100.f));
EXPECT_EQ(50.f, inner_scroll->CurrentScrollOffset().y());
EXPECT_EQ(0.f, outer_scroll->CurrentScrollOffset().y());
EXPECT_EQ(gfx::ScrollOffset(), outer_scroll->MaxScrollOffset());
host_impl_->ScrollEnd();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
EXPECT_EQ(host_impl_->CurrentlyScrollingLayer(), inner_scroll);
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2dF(0.f, -50.f));
// The entire scroll delta should have been used to show the top controls.
// The outer viewport should be resized to accomodate and scrolled to the
// bottom of the document to keep the viewport in place.
EXPECT_EQ(1.f, host_impl_->active_tree()->CurrentTopControlsShownRatio());
EXPECT_EQ(50.f, outer_container->BoundsForScrolling().height());
EXPECT_EQ(50.f, inner_container->BoundsForScrolling().height());
EXPECT_EQ(25.f, outer_scroll->CurrentScrollOffset().y());
EXPECT_EQ(25.f, inner_scroll->CurrentScrollOffset().y());
// Now when we continue scrolling, make sure the outer viewport gets scrolled
// since it wasn't scrollable when the scroll began.
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2dF(0.f, -20.f));
EXPECT_EQ(15.f, outer_scroll->CurrentScrollOffset().y());
EXPECT_EQ(25.f, inner_scroll->CurrentScrollOffset().y());
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2dF(0.f, -30.f));
EXPECT_EQ(0.f, outer_scroll->CurrentScrollOffset().y());
EXPECT_EQ(25.f, inner_scroll->CurrentScrollOffset().y());
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2dF(0.f, -50.f));
host_impl_->ScrollEnd();
EXPECT_EQ(0.f, outer_scroll->CurrentScrollOffset().y());
EXPECT_EQ(0.f, inner_scroll->CurrentScrollOffset().y());
}
// Test that the fixed position container delta is appropriately adjusted
// by the top controls showing/hiding and page scale doesn't affect it.
TEST_F(LayerTreeHostImplTopControlsTest, FixedContainerDelta) {
SetupTopControlsAndScrollLayerWithVirtualViewport(
gfx::Size(100, 100), gfx::Size(100, 100), gfx::Size(100, 100));
DrawFrame();
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, 1.f, 2.f);
float page_scale = 1.5f;
LayerImpl* outer_viewport_scroll_layer =
host_impl_->active_tree()->OuterViewportScrollLayer();
// Zoom in, since the fixed container is the outer viewport, the delta should
// not be scaled.
host_impl_->active_tree()->PushPageScaleFromMainThread(page_scale, 1.f, 2.f);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
// Scroll down, the top controls hiding should expand the viewport size so
// the delta should be equal to the scroll distance.
gfx::Vector2dF top_controls_scroll_delta(0.f, 20.f);
host_impl_->top_controls_manager()->ScrollBegin();
host_impl_->top_controls_manager()->ScrollBy(top_controls_scroll_delta);
EXPECT_FLOAT_EQ(top_controls_height_ - top_controls_scroll_delta.y(),
host_impl_->top_controls_manager()->ContentTopOffset());
EXPECT_FLOAT_EQ(top_controls_scroll_delta.y(),
outer_viewport_scroll_layer->FixedContainerSizeDelta().y());
host_impl_->ScrollEnd();
// Scroll past the maximum extent. The delta shouldn't be greater than the
// top controls height.
host_impl_->top_controls_manager()->ScrollBegin();
host_impl_->top_controls_manager()->ScrollBy(top_controls_scroll_delta);
host_impl_->top_controls_manager()->ScrollBy(top_controls_scroll_delta);
host_impl_->top_controls_manager()->ScrollBy(top_controls_scroll_delta);
EXPECT_EQ(0.f, host_impl_->top_controls_manager()->ContentTopOffset());
EXPECT_VECTOR_EQ(gfx::Vector2dF(0, top_controls_height_),
outer_viewport_scroll_layer->FixedContainerSizeDelta());
host_impl_->ScrollEnd();
// Scroll in the direction to make the top controls show.
host_impl_->top_controls_manager()->ScrollBegin();
host_impl_->top_controls_manager()->ScrollBy(-top_controls_scroll_delta);
EXPECT_EQ(top_controls_scroll_delta.y(),
host_impl_->top_controls_manager()->ContentTopOffset());
EXPECT_VECTOR_EQ(
gfx::Vector2dF(0, top_controls_height_ - top_controls_scroll_delta.y()),
outer_viewport_scroll_layer->FixedContainerSizeDelta());
host_impl_->top_controls_manager()->ScrollEnd();
}
// Test that if only the top controls are scrolled, we shouldn't request a
// commit.
TEST_F(LayerTreeHostImplTopControlsTest, TopControlsDontTriggerCommit) {
SetupTopControlsAndScrollLayerWithVirtualViewport(
gfx::Size(100, 50), gfx::Size(100, 100), gfx::Size(100, 100));
DrawFrame();
// Show top controls
EXPECT_EQ(1.f, host_impl_->active_tree()->CurrentTopControlsShownRatio());
// Scroll 25px to hide top controls
gfx::Vector2dF scroll_delta(0.f, 25.f);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
EXPECT_FALSE(did_request_commit_);
}
// Test that if a scrollable sublayer doesn't consume the scroll,
// top controls should hide when scrolling down.
TEST_F(LayerTreeHostImplTopControlsTest, TopControlsScrollableSublayer) {
gfx::Size sub_content_size(100, 400);
gfx::Size sub_content_layer_size(100, 300);
SetupTopControlsAndScrollLayerWithVirtualViewport(
gfx::Size(100, 50), gfx::Size(100, 100), gfx::Size(100, 100));
DrawFrame();
// Show top controls
EXPECT_EQ(1.f, host_impl_->active_tree()->CurrentTopControlsShownRatio());
LayerImpl* outer_viewport_scroll_layer =
host_impl_->active_tree()->OuterViewportScrollLayer();
int id = outer_viewport_scroll_layer->id();
scoped_ptr<LayerImpl> child =
LayerImpl::Create(host_impl_->active_tree(), id + 2);
scoped_ptr<LayerImpl> child_clip =
LayerImpl::Create(host_impl_->active_tree(), id + 3);
child_clip->SetBounds(sub_content_layer_size);
child->SetScrollClipLayer(child_clip->id());
child->SetBounds(sub_content_size);
child->SetPosition(gfx::PointF());
child->SetDrawsContent(true);
child->SetIsContainerForFixedPositionLayers(true);
// scroll child to limit
child->SetScrollDelta(gfx::Vector2dF(0, 100.f));
child_clip->AddChild(child.Pass());
outer_viewport_scroll_layer->AddChild(child_clip.Pass());
// Scroll 25px to hide top controls
gfx::Vector2dF scroll_delta(0.f, 25.f);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
host_impl_->ScrollEnd();
// Top controls should be hidden
EXPECT_EQ(scroll_delta.y(),
top_controls_height_ -
host_impl_->top_controls_manager()->ContentTopOffset());
}
// Ensure setting the top controls position explicitly using the setters on the
// TreeImpl correctly affects the top controls manager and viewport bounds.
TEST_F(LayerTreeHostImplTopControlsTest, PositionTopControlsExplicitly) {
CreateHostImpl(settings_, CreateOutputSurface());
SetupTopControlsAndScrollLayerWithVirtualViewport(
layer_size_, layer_size_, layer_size_);
DrawFrame();
host_impl_->active_tree()->SetCurrentTopControlsShownRatio(0.f);
host_impl_->active_tree()->top_controls_shown_ratio()->PushFromMainThread(
30.f / top_controls_height_);
host_impl_->active_tree()->top_controls_shown_ratio()->PushPendingToActive();
EXPECT_FLOAT_EQ(30.f, host_impl_->top_controls_manager()->ContentTopOffset());
EXPECT_FLOAT_EQ(-20.f,
host_impl_->top_controls_manager()->ControlsTopOffset());
host_impl_->active_tree()->SetCurrentTopControlsShownRatio(0.f);
EXPECT_FLOAT_EQ(0.f, host_impl_->top_controls_manager()->ContentTopOffset());
EXPECT_FLOAT_EQ(-50.f,
host_impl_->top_controls_manager()->ControlsTopOffset());
host_impl_->DidChangeTopControlsPosition();
// Now that top controls have moved, expect the clip to resize.
LayerImpl* inner_clip_ptr =
host_impl_->InnerViewportScrollLayer()->parent()->parent();
EXPECT_EQ(viewport_size_, inner_clip_ptr->bounds());
}
// Test that the top_controls delta and sent delta are appropriately
// applied on sync tree activation. The total top controls offset shouldn't
// change after the activation.
TEST_F(LayerTreeHostImplTopControlsTest, ApplyDeltaOnTreeActivation) {
CreateHostImpl(settings_, CreateOutputSurface());
SetupTopControlsAndScrollLayerWithVirtualViewport(
layer_size_, layer_size_, layer_size_);
DrawFrame();
host_impl_->active_tree()->top_controls_shown_ratio()->PushFromMainThread(
20.f / top_controls_height_);
host_impl_->active_tree()->top_controls_shown_ratio()->PushPendingToActive();
host_impl_->active_tree()->SetCurrentTopControlsShownRatio(
15.f / top_controls_height_);
host_impl_->active_tree()
->top_controls_shown_ratio()
->PullDeltaForMainThread();
host_impl_->active_tree()->SetCurrentTopControlsShownRatio(0.f);
host_impl_->sync_tree()->PushTopControlsFromMainThread(15.f /
top_controls_height_);
host_impl_->DidChangeTopControlsPosition();
LayerImpl* inner_clip_ptr =
host_impl_->InnerViewportScrollLayer()->parent()->parent();
EXPECT_EQ(viewport_size_, inner_clip_ptr->bounds());
EXPECT_EQ(0.f, host_impl_->top_controls_manager()->ContentTopOffset());
host_impl_->ActivateSyncTree();
inner_clip_ptr = host_impl_->InnerViewportScrollLayer()->parent()->parent();
EXPECT_EQ(0.f, host_impl_->top_controls_manager()->ContentTopOffset());
EXPECT_EQ(viewport_size_, inner_clip_ptr->bounds());
EXPECT_FLOAT_EQ(
-15.f, host_impl_->active_tree()->top_controls_shown_ratio()->Delta() *
top_controls_height_);
EXPECT_FLOAT_EQ(
15.f,
host_impl_->active_tree()->top_controls_shown_ratio()->ActiveBase() *
top_controls_height_);
}
// Test that changing the top controls layout height is correctly applied to
// the inner viewport container bounds. That is, the top controls layout
// height is the amount that the inner viewport container was shrunk outside
// the compositor to accommodate the top controls.
TEST_F(LayerTreeHostImplTopControlsTest, TopControlsLayoutHeightChanged) {
CreateHostImpl(settings_, CreateOutputSurface());
SetupTopControlsAndScrollLayerWithVirtualViewport(
layer_size_, layer_size_, layer_size_);
DrawFrame();
host_impl_->sync_tree()->PushTopControlsFromMainThread(1.f);
host_impl_->sync_tree()->set_top_controls_shrink_blink_size(true);
host_impl_->active_tree()->top_controls_shown_ratio()->PushFromMainThread(
1.f);
host_impl_->active_tree()->top_controls_shown_ratio()->PushPendingToActive();
host_impl_->active_tree()->SetCurrentTopControlsShownRatio(0.f);
host_impl_->DidChangeTopControlsPosition();
LayerImpl* inner_clip_ptr =
host_impl_->InnerViewportScrollLayer()->parent()->parent();
EXPECT_EQ(viewport_size_, inner_clip_ptr->bounds());
EXPECT_EQ(0.f, host_impl_->top_controls_manager()->ContentTopOffset());
host_impl_->sync_tree()->root_layer()->SetBounds(
gfx::Size(inner_clip_ptr->bounds().width(),
inner_clip_ptr->bounds().height() - 50.f));
host_impl_->ActivateSyncTree();
inner_clip_ptr =
host_impl_->InnerViewportScrollLayer()->parent()->parent();
EXPECT_EQ(0.f, host_impl_->top_controls_manager()->ContentTopOffset());
// The total bounds should remain unchanged since the bounds delta should
// account for the difference between the layout height and the current
// top controls offset.
EXPECT_EQ(viewport_size_, inner_clip_ptr->bounds());
EXPECT_VECTOR_EQ(gfx::Vector2dF(0.f, 50.f), inner_clip_ptr->bounds_delta());
host_impl_->active_tree()->SetCurrentTopControlsShownRatio(1.f);
host_impl_->DidChangeTopControlsPosition();
EXPECT_EQ(1.f, host_impl_->top_controls_manager()->TopControlsShownRatio());
EXPECT_EQ(50.f, host_impl_->top_controls_manager()->TopControlsHeight());
EXPECT_EQ(50.f, host_impl_->top_controls_manager()->ContentTopOffset());
EXPECT_VECTOR_EQ(gfx::Vector2dF(0.f, 0.f), inner_clip_ptr->bounds_delta());
EXPECT_EQ(gfx::Size(viewport_size_.width(), viewport_size_.height() - 50.f),
inner_clip_ptr->bounds());
}
// Test that showing/hiding the top controls when the viewport is fully scrolled
// doesn't incorrectly change the viewport offset due to clamping from changing
// viewport bounds.
TEST_F(LayerTreeHostImplTopControlsTest, TopControlsViewportOffsetClamping) {
SetupTopControlsAndScrollLayerWithVirtualViewport(
gfx::Size(100, 100), gfx::Size(200, 200), gfx::Size(200, 400));
DrawFrame();
EXPECT_EQ(1.f, host_impl_->active_tree()->CurrentTopControlsShownRatio());
LayerImpl* outer_scroll = host_impl_->OuterViewportScrollLayer();
LayerImpl* inner_scroll = host_impl_->InnerViewportScrollLayer();
// Scroll the viewports to max scroll offset.
outer_scroll->SetScrollDelta(gfx::Vector2dF(0, 200.f));
inner_scroll->SetScrollDelta(gfx::Vector2dF(100, 100.f));
gfx::ScrollOffset viewport_offset =
host_impl_->active_tree()->TotalScrollOffset();
EXPECT_EQ(host_impl_->active_tree()->TotalMaxScrollOffset(), viewport_offset);
// Hide the top controls by 25px.
gfx::Vector2dF scroll_delta(0.f, 25.f);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
// scrolling down at the max extents no longer hides the top controls
EXPECT_EQ(1.f, host_impl_->active_tree()->CurrentTopControlsShownRatio());
// forcefully hide the top controls by 25px
host_impl_->top_controls_manager()->ScrollBy(scroll_delta);
host_impl_->ScrollEnd();
EXPECT_FLOAT_EQ(scroll_delta.y(),
top_controls_height_ -
host_impl_->top_controls_manager()->ContentTopOffset());
inner_scroll->ClampScrollToMaxScrollOffset();
outer_scroll->ClampScrollToMaxScrollOffset();
// We should still be fully scrolled.
EXPECT_EQ(host_impl_->active_tree()->TotalMaxScrollOffset(),
host_impl_->active_tree()->TotalScrollOffset());
viewport_offset = host_impl_->active_tree()->TotalScrollOffset();
// Bring the top controls down by 25px.
scroll_delta = gfx::Vector2dF(0.f, -25.f);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
host_impl_->ScrollEnd();
// The viewport offset shouldn't have changed.
EXPECT_EQ(viewport_offset,
host_impl_->active_tree()->TotalScrollOffset());
// Scroll the viewports to max scroll offset.
outer_scroll->SetScrollDelta(gfx::Vector2dF(0, 200.f));
inner_scroll->SetScrollDelta(gfx::Vector2dF(100, 100.f));
EXPECT_EQ(host_impl_->active_tree()->TotalMaxScrollOffset(),
host_impl_->active_tree()->TotalScrollOffset());
}
// Test that the top controls coming in and out maintains the same aspect ratio
// between the inner and outer viewports.
TEST_F(LayerTreeHostImplTopControlsTest, TopControlsAspectRatio) {
SetupTopControlsAndScrollLayerWithVirtualViewport(
gfx::Size(100, 100), gfx::Size(200, 200), gfx::Size(200, 400));
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, 0.5f, 2.f);
DrawFrame();
EXPECT_FLOAT_EQ(top_controls_height_,
host_impl_->top_controls_manager()->ContentTopOffset());
gfx::Vector2dF scroll_delta(0.f, 25.f);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
host_impl_->ScrollEnd();
EXPECT_FLOAT_EQ(scroll_delta.y(),
top_controls_height_ -
host_impl_->top_controls_manager()->ContentTopOffset());
// Top controls were hidden by 25px so the inner viewport should have expanded
// by that much.
LayerImpl* outer_container =
host_impl_->active_tree()->OuterViewportContainerLayer();
LayerImpl* inner_container =
host_impl_->active_tree()->InnerViewportContainerLayer();
EXPECT_EQ(gfx::Size(100, 100+25), inner_container->BoundsForScrolling());
// Outer viewport should match inner's aspect ratio. The bounds are ceiled.
float aspect_ratio = inner_container->BoundsForScrolling().width() /
inner_container->BoundsForScrolling().height();
gfx::Size expected = gfx::ToCeiledSize(gfx::SizeF(200, 200 / aspect_ratio));
EXPECT_EQ(expected, outer_container->BoundsForScrolling());
EXPECT_EQ(expected,
host_impl_->InnerViewportScrollLayer()->BoundsForScrolling());
}
// Test that scrolling the outer viewport affects the top controls.
TEST_F(LayerTreeHostImplTopControlsTest, TopControlsScrollOuterViewport) {
SetupTopControlsAndScrollLayerWithVirtualViewport(
gfx::Size(100, 100), gfx::Size(200, 200), gfx::Size(200, 400));
DrawFrame();
EXPECT_EQ(top_controls_height_,
host_impl_->top_controls_manager()->ContentTopOffset());
// Send a gesture scroll that will scroll the outer viewport, make sure the
// top controls get scrolled.
gfx::Vector2dF scroll_delta(0.f, 15.f);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
EXPECT_EQ(host_impl_->OuterViewportScrollLayer(),
host_impl_->CurrentlyScrollingLayer());
host_impl_->ScrollEnd();
EXPECT_FLOAT_EQ(scroll_delta.y(),
top_controls_height_ -
host_impl_->top_controls_manager()->ContentTopOffset());
scroll_delta = gfx::Vector2dF(0.f, 50.f);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
EXPECT_EQ(0, host_impl_->top_controls_manager()->ContentTopOffset());
EXPECT_EQ(host_impl_->OuterViewportScrollLayer(),
host_impl_->CurrentlyScrollingLayer());
host_impl_->ScrollEnd();
// Position the viewports such that the inner viewport will be scrolled.
gfx::Vector2dF inner_viewport_offset(0.f, 25.f);
host_impl_->OuterViewportScrollLayer()->SetScrollDelta(gfx::Vector2dF());
host_impl_->InnerViewportScrollLayer()->SetScrollDelta(inner_viewport_offset);
scroll_delta = gfx::Vector2dF(0.f, -65.f);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
EXPECT_EQ(top_controls_height_,
host_impl_->top_controls_manager()->ContentTopOffset());
EXPECT_FLOAT_EQ(
inner_viewport_offset.y() + (scroll_delta.y() + top_controls_height_),
host_impl_->InnerViewportScrollLayer()->ScrollDelta().y());
host_impl_->ScrollEnd();
}
TEST_F(LayerTreeHostImplTopControlsTest,
ScrollNonScrollableRootWithTopControls) {
CreateHostImpl(settings_, CreateOutputSurface());
SetupTopControlsAndScrollLayerWithVirtualViewport(
layer_size_, layer_size_, layer_size_);
DrawFrame();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
host_impl_->top_controls_manager()->ScrollBegin();
host_impl_->top_controls_manager()->ScrollBy(gfx::Vector2dF(0.f, 50.f));
host_impl_->top_controls_manager()->ScrollEnd();
EXPECT_EQ(0.f, host_impl_->top_controls_manager()->ContentTopOffset());
// Now that top controls have moved, expect the clip to resize.
LayerImpl* inner_clip_ptr =
host_impl_->InnerViewportScrollLayer()->parent()->parent();
EXPECT_EQ(viewport_size_, inner_clip_ptr->bounds());
host_impl_->ScrollEnd();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
float scroll_increment_y = -25.f;
host_impl_->top_controls_manager()->ScrollBegin();
host_impl_->top_controls_manager()->ScrollBy(
gfx::Vector2dF(0.f, scroll_increment_y));
EXPECT_FLOAT_EQ(-scroll_increment_y,
host_impl_->top_controls_manager()->ContentTopOffset());
// Now that top controls have moved, expect the clip to resize.
EXPECT_EQ(gfx::Size(viewport_size_.width(),
viewport_size_.height() + scroll_increment_y),
inner_clip_ptr->bounds());
host_impl_->top_controls_manager()->ScrollBy(
gfx::Vector2dF(0.f, scroll_increment_y));
host_impl_->top_controls_manager()->ScrollEnd();
EXPECT_FLOAT_EQ(-2 * scroll_increment_y,
host_impl_->top_controls_manager()->ContentTopOffset());
// Now that top controls have moved, expect the clip to resize.
EXPECT_EQ(clip_size_, inner_clip_ptr->bounds());
host_impl_->ScrollEnd();
// Verify the layer is once-again non-scrollable.
EXPECT_EQ(
gfx::ScrollOffset(),
host_impl_->active_tree()->InnerViewportScrollLayer()->MaxScrollOffset());
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
}
TEST_F(LayerTreeHostImplTest, ScrollNonCompositedRoot) {
// Test the configuration where a non-composited root layer is embedded in a
// scrollable outer layer.
gfx::Size surface_size(10, 10);
gfx::Size contents_size(20, 20);
scoped_ptr<LayerImpl> content_layer =
LayerImpl::Create(host_impl_->active_tree(), 1);
content_layer->SetDrawsContent(true);
content_layer->SetPosition(gfx::PointF());
content_layer->SetBounds(contents_size);
scoped_ptr<LayerImpl> scroll_clip_layer =
LayerImpl::Create(host_impl_->active_tree(), 3);
scroll_clip_layer->SetBounds(surface_size);
scoped_ptr<LayerImpl> scroll_layer =
LayerImpl::Create(host_impl_->active_tree(), 2);
scroll_layer->SetScrollClipLayer(3);
scroll_layer->SetBounds(contents_size);
scroll_layer->SetPosition(gfx::PointF());
scroll_layer->AddChild(content_layer.Pass());
scroll_clip_layer->AddChild(scroll_layer.Pass());
scroll_clip_layer->SetHasRenderSurface(true);
host_impl_->active_tree()->SetRootLayer(scroll_clip_layer.Pass());
host_impl_->SetViewportSize(surface_size);
DrawFrame();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(5, 5), InputHandler::WHEEL));
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, 10));
host_impl_->ScrollEnd();
EXPECT_TRUE(did_request_redraw_);
EXPECT_TRUE(did_request_commit_);
}
TEST_F(LayerTreeHostImplTest, ScrollChildCallsCommitAndRedraw) {
gfx::Size surface_size(10, 10);
gfx::Size contents_size(20, 20);
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl_->active_tree(), 1);
root->SetBounds(surface_size);
root->AddChild(CreateScrollableLayer(2, contents_size, root.get()));
root->SetHasRenderSurface(true);
host_impl_->active_tree()->SetRootLayer(root.Pass());
host_impl_->SetViewportSize(surface_size);
DrawFrame();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(5, 5), InputHandler::WHEEL));
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, 10));
host_impl_->ScrollEnd();
EXPECT_TRUE(did_request_redraw_);
EXPECT_TRUE(did_request_commit_);
}
TEST_F(LayerTreeHostImplTest, ScrollMissesChild) {
gfx::Size surface_size(10, 10);
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl_->active_tree(), 1);
root->AddChild(CreateScrollableLayer(2, surface_size, root.get()));
root->SetHasRenderSurface(true);
host_impl_->active_tree()->SetRootLayer(root.Pass());
host_impl_->SetViewportSize(surface_size);
DrawFrame();
// Scroll event is ignored because the input coordinate is outside the layer
// boundaries.
EXPECT_EQ(InputHandler::SCROLL_IGNORED,
host_impl_->ScrollBegin(gfx::Point(15, 5), InputHandler::WHEEL));
EXPECT_FALSE(did_request_redraw_);
EXPECT_FALSE(did_request_commit_);
}
TEST_F(LayerTreeHostImplTest, ScrollMissesBackfacingChild) {
gfx::Size surface_size(10, 10);
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl_->active_tree(), 1);
root->SetHasRenderSurface(true);
scoped_ptr<LayerImpl> child =
CreateScrollableLayer(2, surface_size, root.get());
host_impl_->SetViewportSize(surface_size);
gfx::Transform matrix;
matrix.RotateAboutXAxis(180.0);
child->SetTransform(matrix);
child->SetDoubleSided(false);
root->AddChild(child.Pass());
host_impl_->active_tree()->SetRootLayer(root.Pass());
DrawFrame();
// Scroll event is ignored because the scrollable layer is not facing the
// viewer and there is nothing scrollable behind it.
EXPECT_EQ(InputHandler::SCROLL_IGNORED,
host_impl_->ScrollBegin(gfx::Point(5, 5), InputHandler::WHEEL));
EXPECT_FALSE(did_request_redraw_);
EXPECT_FALSE(did_request_commit_);
}
TEST_F(LayerTreeHostImplTest, ScrollBlockedByContentLayer) {
gfx::Size surface_size(10, 10);
scoped_ptr<LayerImpl> clip_layer =
LayerImpl::Create(host_impl_->active_tree(), 3);
scoped_ptr<LayerImpl> content_layer =
CreateScrollableLayer(1, surface_size, clip_layer.get());
content_layer->SetShouldScrollOnMainThread(true);
content_layer->SetScrollClipLayer(Layer::INVALID_ID);
// Note: we can use the same clip layer for both since both calls to
// CreateScrollableLayer() use the same surface size.
scoped_ptr<LayerImpl> scroll_layer =
CreateScrollableLayer(2, surface_size, clip_layer.get());
scroll_layer->AddChild(content_layer.Pass());
clip_layer->AddChild(scroll_layer.Pass());
clip_layer->SetHasRenderSurface(true);
host_impl_->active_tree()->SetRootLayer(clip_layer.Pass());
host_impl_->SetViewportSize(surface_size);
DrawFrame();
// Scrolling fails because the content layer is asking to be scrolled on the
// main thread.
EXPECT_EQ(InputHandler::SCROLL_ON_MAIN_THREAD,
host_impl_->ScrollBegin(gfx::Point(5, 5), InputHandler::WHEEL));
}
TEST_F(LayerTreeHostImplTest, ScrollRootAndChangePageScaleOnMainThread) {
gfx::Size viewport_size(10, 10);
float page_scale = 2.f;
SetupScrollAndContentsLayers(viewport_size);
// Setup the layers so that the outer viewport is scrollable.
host_impl_->active_tree()->InnerViewportScrollLayer()->parent()->SetBounds(
viewport_size);
host_impl_->active_tree()->OuterViewportScrollLayer()->SetBounds(
gfx::Size(20, 20));
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, 1.f, 2.f);
DrawFrame();
LayerImpl* root_scroll =
host_impl_->active_tree()->OuterViewportScrollLayer();
EXPECT_EQ(viewport_size, root_scroll->scroll_clip_layer()->bounds());
gfx::Vector2d scroll_delta(0, 10);
gfx::Vector2d expected_scroll_delta = scroll_delta;
gfx::ScrollOffset expected_max_scroll = root_scroll->MaxScrollOffset();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(5, 5), InputHandler::WHEEL));
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
host_impl_->ScrollEnd();
// Set new page scale from main thread.
host_impl_->active_tree()->PushPageScaleFromMainThread(page_scale, 1.f, 2.f);
scoped_ptr<ScrollAndScaleSet> scroll_info = host_impl_->ProcessScrollDeltas();
EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), root_scroll->id(),
expected_scroll_delta));
// The scroll range should also have been updated.
EXPECT_EQ(expected_max_scroll, root_scroll->MaxScrollOffset());
// The page scale delta remains constant because the impl thread did not
// scale.
EXPECT_EQ(1.f, host_impl_->active_tree()->page_scale_delta());
}
TEST_F(LayerTreeHostImplTest, ScrollRootAndChangePageScaleOnImplThread) {
gfx::Size viewport_size(10, 10);
float page_scale = 2.f;
SetupScrollAndContentsLayers(viewport_size);
// Setup the layers so that the outer viewport is scrollable.
host_impl_->active_tree()->InnerViewportScrollLayer()->parent()->SetBounds(
viewport_size);
host_impl_->active_tree()->OuterViewportScrollLayer()->SetBounds(
gfx::Size(20, 20));
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, 1.f, 2.f);
DrawFrame();
LayerImpl* root_scroll =
host_impl_->active_tree()->OuterViewportScrollLayer();
EXPECT_EQ(viewport_size, root_scroll->scroll_clip_layer()->bounds());
gfx::Vector2d scroll_delta(0, 10);
gfx::Vector2d expected_scroll_delta = scroll_delta;
gfx::ScrollOffset expected_max_scroll = root_scroll->MaxScrollOffset();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(5, 5), InputHandler::WHEEL));
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
host_impl_->ScrollEnd();
// Set new page scale on impl thread by pinching.
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE);
host_impl_->PinchGestureBegin();
host_impl_->PinchGestureUpdate(page_scale, gfx::Point());
host_impl_->PinchGestureEnd();
host_impl_->ScrollEnd();
DrawOneFrame();
// The scroll delta is not scaled because the main thread did not scale.
scoped_ptr<ScrollAndScaleSet> scroll_info = host_impl_->ProcessScrollDeltas();
EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), root_scroll->id(),
expected_scroll_delta));
// The scroll range should also have been updated.
EXPECT_EQ(expected_max_scroll, root_scroll->MaxScrollOffset());
// The page scale delta should match the new scale on the impl side.
EXPECT_EQ(page_scale, host_impl_->active_tree()->current_page_scale_factor());
}
TEST_F(LayerTreeHostImplTest, PageScaleDeltaAppliedToRootScrollLayerOnly) {
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, 1.f, 2.f);
gfx::Size surface_size(10, 10);
float default_page_scale = 1.f;
gfx::Transform default_page_scale_matrix;
default_page_scale_matrix.Scale(default_page_scale, default_page_scale);
float new_page_scale = 2.f;
gfx::Transform new_page_scale_matrix;
new_page_scale_matrix.Scale(new_page_scale, new_page_scale);
// Create a normal scrollable root layer and another scrollable child layer.
LayerImpl* scroll = SetupScrollAndContentsLayers(surface_size);
LayerImpl* root = host_impl_->active_tree()->root_layer();
LayerImpl* child = scroll->children()[0];
scoped_ptr<LayerImpl> scrollable_child_clip =
LayerImpl::Create(host_impl_->active_tree(), 6);
scoped_ptr<LayerImpl> scrollable_child =
CreateScrollableLayer(7, surface_size, scrollable_child_clip.get());
scrollable_child_clip->AddChild(scrollable_child.Pass());
child->AddChild(scrollable_child_clip.Pass());
LayerImpl* grand_child = child->children()[0];
// Set new page scale on impl thread by pinching.
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE);
host_impl_->PinchGestureBegin();
host_impl_->PinchGestureUpdate(new_page_scale, gfx::Point());
host_impl_->PinchGestureEnd();
host_impl_->ScrollEnd();
DrawOneFrame();
// Make sure all the layers are drawn with the page scale delta applied, i.e.,
// the page scale delta on the root layer is applied hierarchically.
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
EXPECT_EQ(1.f, root->draw_transform().matrix().getDouble(0, 0));
EXPECT_EQ(1.f, root->draw_transform().matrix().getDouble(1, 1));
EXPECT_EQ(new_page_scale, scroll->draw_transform().matrix().getDouble(0, 0));
EXPECT_EQ(new_page_scale, scroll->draw_transform().matrix().getDouble(1, 1));
EXPECT_EQ(new_page_scale, child->draw_transform().matrix().getDouble(0, 0));
EXPECT_EQ(new_page_scale, child->draw_transform().matrix().getDouble(1, 1));
EXPECT_EQ(new_page_scale,
grand_child->draw_transform().matrix().getDouble(0, 0));
EXPECT_EQ(new_page_scale,
grand_child->draw_transform().matrix().getDouble(1, 1));
}
TEST_F(LayerTreeHostImplTest, ScrollChildAndChangePageScaleOnMainThread) {
gfx::Size surface_size(30, 30);
SetupScrollAndContentsLayers(surface_size);
LayerImpl* outer_scroll = host_impl_->OuterViewportScrollLayer();
// Make the outer scroll layer scrollable.
outer_scroll->SetBounds(gfx::Size(50, 50));
DrawFrame();
gfx::Vector2d scroll_delta(0, 10);
gfx::Vector2d expected_scroll_delta(scroll_delta);
gfx::ScrollOffset expected_max_scroll(outer_scroll->MaxScrollOffset());
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(5, 5), InputHandler::WHEEL));
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
host_impl_->ScrollEnd();
float page_scale = 2.f;
host_impl_->active_tree()->PushPageScaleFromMainThread(page_scale, 1.f,
page_scale);
DrawOneFrame();
scoped_ptr<ScrollAndScaleSet> scroll_info = host_impl_->ProcessScrollDeltas();
EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), outer_scroll->id(),
expected_scroll_delta));
// The scroll range should not have changed.
EXPECT_EQ(outer_scroll->MaxScrollOffset(), expected_max_scroll);
// The page scale delta remains constant because the impl thread did not
// scale.
EXPECT_EQ(1.f, host_impl_->active_tree()->page_scale_delta());
}
TEST_F(LayerTreeHostImplTest, ScrollChildBeyondLimit) {
// Scroll a child layer beyond its maximum scroll range and make sure the
// parent layer is scrolled on the axis on which the child was unable to
// scroll.
gfx::Size surface_size(10, 10);
gfx::Size content_size(20, 20);
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl_->active_tree(), 1);
root->SetBounds(surface_size);
root->SetHasRenderSurface(true);
scoped_ptr<LayerImpl> grand_child =
CreateScrollableLayer(3, content_size, root.get());
scoped_ptr<LayerImpl> child =
CreateScrollableLayer(2, content_size, root.get());
LayerImpl* grand_child_layer = grand_child.get();
child->AddChild(grand_child.Pass());
LayerImpl* child_layer = child.get();
root->AddChild(child.Pass());
host_impl_->active_tree()->SetRootLayer(root.Pass());
host_impl_->active_tree()->DidBecomeActive();
host_impl_->SetViewportSize(surface_size);
grand_child_layer->PushScrollOffsetFromMainThread(gfx::ScrollOffset(0, 5));
child_layer->PushScrollOffsetFromMainThread(gfx::ScrollOffset(3, 0));
DrawFrame();
{
gfx::Vector2d scroll_delta(-8, -7);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
host_impl_->ScrollEnd();
scoped_ptr<ScrollAndScaleSet> scroll_info =
host_impl_->ProcessScrollDeltas();
// The grand child should have scrolled up to its limit.
LayerImpl* child = host_impl_->active_tree()->root_layer()->children()[0];
LayerImpl* grand_child = child->children()[0];
EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), grand_child->id(),
gfx::Vector2d(0, -5)));
// The child should have only scrolled on the other axis.
EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), child->id(),
gfx::Vector2d(-3, 0)));
}
}
TEST_F(LayerTreeHostImplTest, ScrollWithoutBubbling) {
// Scroll a child layer beyond its maximum scroll range and make sure the
// the scroll doesn't bubble up to the parent layer.
gfx::Size surface_size(20, 20);
gfx::Size viewport_size(10, 10);
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl_->active_tree(), 1);
root->SetHasRenderSurface(true);
scoped_ptr<LayerImpl> root_scrolling =
CreateScrollableLayer(2, surface_size, root.get());
root_scrolling->SetIsContainerForFixedPositionLayers(true);
scoped_ptr<LayerImpl> grand_child =
CreateScrollableLayer(4, surface_size, root.get());
scoped_ptr<LayerImpl> child =
CreateScrollableLayer(3, surface_size, root.get());
LayerImpl* grand_child_layer = grand_child.get();
child->AddChild(grand_child.Pass());
LayerImpl* child_layer = child.get();
root_scrolling->AddChild(child.Pass());
root->AddChild(root_scrolling.Pass());
EXPECT_EQ(viewport_size, root->bounds());
host_impl_->active_tree()->SetRootLayer(root.Pass());
host_impl_->active_tree()->SetViewportLayersFromIds(Layer::INVALID_ID, 1, 2,
Layer::INVALID_ID);
host_impl_->active_tree()->DidBecomeActive();
host_impl_->SetViewportSize(viewport_size);
grand_child_layer->PushScrollOffsetFromMainThread(gfx::ScrollOffset(0, 2));
child_layer->PushScrollOffsetFromMainThread(gfx::ScrollOffset(0, 3));
DrawFrame();
{
gfx::Vector2d scroll_delta(0, -10);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(),
InputHandler::NON_BUBBLING_GESTURE));
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
host_impl_->ScrollEnd();
scoped_ptr<ScrollAndScaleSet> scroll_info =
host_impl_->ProcessScrollDeltas();
// The grand child should have scrolled up to its limit.
LayerImpl* child =
host_impl_->active_tree()->root_layer()->children()[0]->children()[0];
LayerImpl* grand_child = child->children()[0];
EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), grand_child->id(),
gfx::Vector2d(0, -2)));
// The child should not have scrolled.
ExpectNone(*scroll_info.get(), child->id());
// The next time we scroll we should only scroll the parent.
scroll_delta = gfx::Vector2d(0, -3);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(5, 5),
InputHandler::NON_BUBBLING_GESTURE));
EXPECT_EQ(host_impl_->CurrentlyScrollingLayer(), grand_child);
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
EXPECT_EQ(host_impl_->CurrentlyScrollingLayer(), child);
host_impl_->ScrollEnd();
scroll_info = host_impl_->ProcessScrollDeltas();
// The child should have scrolled up to its limit.
EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), child->id(),
gfx::Vector2d(0, -3)));
// The grand child should not have scrolled.
EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), grand_child->id(),
gfx::Vector2d(0, -2)));
// After scrolling the parent, another scroll on the opposite direction
// should still scroll the child.
scroll_delta = gfx::Vector2d(0, 7);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(5, 5),
InputHandler::NON_BUBBLING_GESTURE));
EXPECT_EQ(host_impl_->CurrentlyScrollingLayer(), grand_child);
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
EXPECT_EQ(host_impl_->CurrentlyScrollingLayer(), grand_child);
host_impl_->ScrollEnd();
scroll_info = host_impl_->ProcessScrollDeltas();
// The grand child should have scrolled.
EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), grand_child->id(),
gfx::Vector2d(0, 5)));
// The child should not have scrolled.
EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), child->id(),
gfx::Vector2d(0, -3)));
// Scrolling should be adjusted from viewport space.
host_impl_->active_tree()->PushPageScaleFromMainThread(2.f, 2.f, 2.f);
host_impl_->active_tree()->SetPageScaleOnActiveTree(2.f);
scroll_delta = gfx::Vector2d(0, -2);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(1, 1),
InputHandler::NON_BUBBLING_GESTURE));
EXPECT_EQ(grand_child, host_impl_->CurrentlyScrollingLayer());
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
host_impl_->ScrollEnd();
scroll_info = host_impl_->ProcessScrollDeltas();
// Should have scrolled by half the amount in layer space (5 - 2/2)
EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), grand_child->id(),
gfx::Vector2d(0, 4)));
}
}
TEST_F(LayerTreeHostImplTest, ScrollEventBubbling) {
// When we try to scroll a non-scrollable child layer, the scroll delta
// should be applied to one of its ancestors if possible.
gfx::Size surface_size(10, 10);
gfx::Size content_size(20, 20);
scoped_ptr<LayerImpl> root_clip =
LayerImpl::Create(host_impl_->active_tree(), 3);
root_clip->SetHasRenderSurface(true);
scoped_ptr<LayerImpl> root =
CreateScrollableLayer(1, content_size, root_clip.get());
// Make 'root' the clip layer for child: since they have the same sizes the
// child will have zero max_scroll_offset and scrolls will bubble.
scoped_ptr<LayerImpl> child =
CreateScrollableLayer(2, content_size, root.get());
child->SetIsContainerForFixedPositionLayers(true);
root->SetBounds(content_size);
int root_scroll_id = root->id();
root->AddChild(child.Pass());
root_clip->AddChild(root.Pass());
host_impl_->SetViewportSize(surface_size);
host_impl_->active_tree()->SetRootLayer(root_clip.Pass());
host_impl_->active_tree()->SetViewportLayersFromIds(Layer::INVALID_ID, 3, 2,
Layer::INVALID_ID);
host_impl_->active_tree()->DidBecomeActive();
DrawFrame();
{
gfx::Vector2d scroll_delta(0, 4);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(5, 5), InputHandler::WHEEL));
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
host_impl_->ScrollEnd();
scoped_ptr<ScrollAndScaleSet> scroll_info =
host_impl_->ProcessScrollDeltas();
// Only the root scroll should have scrolled.
ASSERT_EQ(scroll_info->scrolls.size(), 1u);
EXPECT_TRUE(
ScrollInfoContains(*scroll_info.get(), root_scroll_id, scroll_delta));
}
}
TEST_F(LayerTreeHostImplTest, ScrollBeforeRedraw) {
gfx::Size surface_size(10, 10);
scoped_ptr<LayerImpl> root_clip =
LayerImpl::Create(host_impl_->active_tree(), 1);
scoped_ptr<LayerImpl> root_scroll =
CreateScrollableLayer(2, surface_size, root_clip.get());
root_scroll->SetIsContainerForFixedPositionLayers(true);
root_clip->SetHasRenderSurface(true);
root_clip->AddChild(root_scroll.Pass());
host_impl_->active_tree()->SetRootLayer(root_clip.Pass());
host_impl_->active_tree()->SetViewportLayersFromIds(Layer::INVALID_ID, 1, 2,
Layer::INVALID_ID);
host_impl_->active_tree()->DidBecomeActive();
host_impl_->SetViewportSize(surface_size);
// Draw one frame and then immediately rebuild the layer tree to mimic a tree
// synchronization.
DrawFrame();
host_impl_->active_tree()->DetachLayerTree();
scoped_ptr<LayerImpl> root_clip2 =
LayerImpl::Create(host_impl_->active_tree(), 3);
scoped_ptr<LayerImpl> root_scroll2 =
CreateScrollableLayer(4, surface_size, root_clip2.get());
root_scroll2->SetIsContainerForFixedPositionLayers(true);
root_clip2->AddChild(root_scroll2.Pass());
root_clip2->SetHasRenderSurface(true);
host_impl_->active_tree()->SetRootLayer(root_clip2.Pass());
host_impl_->active_tree()->SetViewportLayersFromIds(Layer::INVALID_ID, 3, 4,
Layer::INVALID_ID);
host_impl_->active_tree()->DidBecomeActive();
// Scrolling should still work even though we did not draw yet.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(5, 5), InputHandler::WHEEL));
}
TEST_F(LayerTreeHostImplTest, ScrollAxisAlignedRotatedLayer) {
LayerImpl* scroll_layer = SetupScrollAndContentsLayers(gfx::Size(100, 100));
// Rotate the root layer 90 degrees counter-clockwise about its center.
gfx::Transform rotate_transform;
rotate_transform.Rotate(-90.0);
host_impl_->active_tree()->root_layer()->SetTransform(rotate_transform);
gfx::Size surface_size(50, 50);
host_impl_->SetViewportSize(surface_size);
DrawFrame();
// Scroll to the right in screen coordinates with a gesture.
gfx::Vector2d gesture_scroll_delta(10, 0);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
host_impl_->ScrollBy(gfx::Point(), gesture_scroll_delta);
host_impl_->ScrollEnd();
// The layer should have scrolled down in its local coordinates.
scoped_ptr<ScrollAndScaleSet> scroll_info = host_impl_->ProcessScrollDeltas();
EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), scroll_layer->id(),
gfx::Vector2d(0, gesture_scroll_delta.x())));
// Reset and scroll down with the wheel.
scroll_layer->SetScrollDelta(gfx::Vector2dF());
gfx::Vector2d wheel_scroll_delta(0, 10);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
host_impl_->ScrollBy(gfx::Point(), wheel_scroll_delta);
host_impl_->ScrollEnd();
// The layer should have scrolled down in its local coordinates.
scroll_info = host_impl_->ProcessScrollDeltas();
EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), scroll_layer->id(),
wheel_scroll_delta));
}
TEST_F(LayerTreeHostImplTest, ScrollNonAxisAlignedRotatedLayer) {
LayerImpl* scroll_layer = SetupScrollAndContentsLayers(gfx::Size(100, 100));
int child_clip_layer_id = 6;
int child_layer_id = 7;
float child_layer_angle = -20.f;
// Create a child layer that is rotated to a non-axis-aligned angle.
scoped_ptr<LayerImpl> clip_layer =
LayerImpl::Create(host_impl_->active_tree(), child_clip_layer_id);
scoped_ptr<LayerImpl> child = CreateScrollableLayer(
child_layer_id, scroll_layer->bounds(), clip_layer.get());
gfx::Transform rotate_transform;
rotate_transform.Translate(-50.0, -50.0);
rotate_transform.Rotate(child_layer_angle);
rotate_transform.Translate(50.0, 50.0);
clip_layer->SetTransform(rotate_transform);
// Only allow vertical scrolling.
clip_layer->SetBounds(
gfx::Size(child->bounds().width(), child->bounds().height() / 2));
// The rotation depends on the layer's transform origin, and the child layer
// is a different size than the clip, so make sure the clip layer's origin
// lines up over the child.
clip_layer->SetTransformOrigin(gfx::Point3F(
clip_layer->bounds().width() * 0.5f, clip_layer->bounds().height(), 0.f));
LayerImpl* child_ptr = child.get();
clip_layer->AddChild(child.Pass());
scroll_layer->AddChild(clip_layer.Pass());
gfx::Size surface_size(50, 50);
host_impl_->SetViewportSize(surface_size);
DrawFrame();
{
// Scroll down in screen coordinates with a gesture.
gfx::Vector2d gesture_scroll_delta(0, 10);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(1, 1), InputHandler::GESTURE));
host_impl_->ScrollBy(gfx::Point(), gesture_scroll_delta);
host_impl_->ScrollEnd();
// The child layer should have scrolled down in its local coordinates an
// amount proportional to the angle between it and the input scroll delta.
gfx::Vector2d expected_scroll_delta(
0, gesture_scroll_delta.y() *
std::cos(MathUtil::Deg2Rad(child_layer_angle)));
scoped_ptr<ScrollAndScaleSet> scroll_info =
host_impl_->ProcessScrollDeltas();
EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), child_layer_id,
expected_scroll_delta));
// The root scroll layer should not have scrolled, because the input delta
// was close to the layer's axis of movement.
EXPECT_EQ(scroll_info->scrolls.size(), 1u);
}
{
// Now reset and scroll the same amount horizontally.
child_ptr->SetScrollDelta(gfx::Vector2dF());
gfx::Vector2d gesture_scroll_delta(10, 0);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(1, 1), InputHandler::GESTURE));
host_impl_->ScrollBy(gfx::Point(), gesture_scroll_delta);
host_impl_->ScrollEnd();
// The child layer should have scrolled down in its local coordinates an
// amount proportional to the angle between it and the input scroll delta.
gfx::Vector2d expected_scroll_delta(
0, -gesture_scroll_delta.x() *
std::sin(MathUtil::Deg2Rad(child_layer_angle)));
scoped_ptr<ScrollAndScaleSet> scroll_info =
host_impl_->ProcessScrollDeltas();
EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), child_layer_id,
expected_scroll_delta));
// The root scroll layer should have scrolled more, since the input scroll
// delta was mostly orthogonal to the child layer's vertical scroll axis.
gfx::Vector2d expected_root_scroll_delta(
gesture_scroll_delta.x() *
std::pow(std::cos(MathUtil::Deg2Rad(child_layer_angle)), 2),
0);
EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), scroll_layer->id(),
expected_root_scroll_delta));
}
}
TEST_F(LayerTreeHostImplTest, ScrollPerspectiveTransformedLayer) {
// When scrolling an element with perspective, the distance scrolled
// depends on the point at which the scroll begins.
LayerImpl* scroll_layer = SetupScrollAndContentsLayers(gfx::Size(100, 100));
int child_clip_layer_id = 6;
int child_layer_id = 7;
// Create a child layer that is rotated on its x axis, with perspective.
scoped_ptr<LayerImpl> clip_layer =
LayerImpl::Create(host_impl_->active_tree(), child_clip_layer_id);
scoped_ptr<LayerImpl> child = CreateScrollableLayer(
child_layer_id, scroll_layer->bounds(), clip_layer.get());
LayerImpl* child_ptr = child.get();
gfx::Transform perspective_transform;
perspective_transform.Translate(-50.0, -50.0);
perspective_transform.ApplyPerspectiveDepth(20);
perspective_transform.RotateAboutXAxis(45);
perspective_transform.Translate(50.0, 50.0);
clip_layer->SetTransform(perspective_transform);
clip_layer->SetBounds(gfx::Size(child_ptr->bounds().width() / 2,
child_ptr->bounds().height() / 2));
// The transform depends on the layer's transform origin, and the child layer
// is a different size than the clip, so make sure the clip layer's origin
// lines up over the child.
clip_layer->SetTransformOrigin(gfx::Point3F(
clip_layer->bounds().width(), clip_layer->bounds().height(), 0.f));
clip_layer->AddChild(child.Pass());
scroll_layer->AddChild(clip_layer.Pass());
gfx::Size surface_size(50, 50);
host_impl_->SetViewportSize(surface_size);
scoped_ptr<ScrollAndScaleSet> scroll_info;
gfx::Vector2d gesture_scroll_deltas[4];
gesture_scroll_deltas[0] = gfx::Vector2d(4, 10);
gesture_scroll_deltas[1] = gfx::Vector2d(4, 10);
gesture_scroll_deltas[2] = gfx::Vector2d(10, 0);
gesture_scroll_deltas[3] = gfx::Vector2d(10, 0);
gfx::Vector2d expected_scroll_deltas[4];
// Perspective affects the vertical delta by a different
// amount depending on the vertical position of the |viewport_point|.
expected_scroll_deltas[0] = gfx::Vector2d(2, 8);
expected_scroll_deltas[1] = gfx::Vector2d(1, 4);
// Deltas which start with the same vertical position of the
// |viewport_point| are subject to identical perspective effects.
expected_scroll_deltas[2] = gfx::Vector2d(4, 0);
expected_scroll_deltas[3] = gfx::Vector2d(4, 0);
gfx::Point viewport_point(1, 1);
// Scroll in screen coordinates with a gesture. Each scroll starts
// where the previous scroll ended, but the scroll position is reset
// for each scroll.
for (int i = 0; i < 4; ++i) {
child_ptr->SetScrollDelta(gfx::Vector2dF());
DrawFrame();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(viewport_point, InputHandler::GESTURE));
host_impl_->ScrollBy(viewport_point, gesture_scroll_deltas[i]);
viewport_point += gesture_scroll_deltas[i];
host_impl_->ScrollEnd();
scroll_info = host_impl_->ProcessScrollDeltas();
EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), child_layer_id,
expected_scroll_deltas[i]));
// The root scroll layer should not have scrolled, because the input delta
// was close to the layer's axis of movement.
EXPECT_EQ(scroll_info->scrolls.size(), 1u);
}
}
TEST_F(LayerTreeHostImplTest, ScrollScaledLayer) {
LayerImpl* scroll_layer =
SetupScrollAndContentsLayers(gfx::Size(100, 100));
// Scale the layer to twice its normal size.
int scale = 2;
gfx::Transform scale_transform;
scale_transform.Scale(scale, scale);
scroll_layer->SetTransform(scale_transform);
gfx::Size surface_size(50, 50);
host_impl_->SetViewportSize(surface_size);
DrawFrame();
// Scroll down in screen coordinates with a gesture.
gfx::Vector2d scroll_delta(0, 10);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
host_impl_->ScrollEnd();
// The layer should have scrolled down in its local coordinates, but half the
// amount.
scoped_ptr<ScrollAndScaleSet> scroll_info = host_impl_->ProcessScrollDeltas();
EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), scroll_layer->id(),
gfx::Vector2d(0, scroll_delta.y() / scale)));
// Reset and scroll down with the wheel.
scroll_layer->SetScrollDelta(gfx::Vector2dF());
gfx::Vector2d wheel_scroll_delta(0, 10);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
host_impl_->ScrollBy(gfx::Point(), wheel_scroll_delta);
host_impl_->ScrollEnd();
// It should apply the scale factor to the scroll delta for the wheel event.
scroll_info = host_impl_->ProcessScrollDeltas();
EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), scroll_layer->id(),
wheel_scroll_delta));
}
TEST_F(LayerTreeHostImplTest, ScrollViewportRounding) {
int width = 332;
int height = 20;
int scale = 3;
SetupScrollAndContentsLayers(gfx::Size(width, height));
host_impl_->active_tree()->InnerViewportContainerLayer()->SetBounds(
gfx::Size(width * scale - 1, height * scale));
host_impl_->SetDeviceScaleFactor(scale);
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, 0.5f, 4.f);
LayerImpl* inner_viewport_scroll_layer =
host_impl_->active_tree()->InnerViewportScrollLayer();
EXPECT_EQ(gfx::ScrollOffset(0, 0),
inner_viewport_scroll_layer->MaxScrollOffset());
}
class TestScrollOffsetDelegate : public LayerScrollOffsetDelegate {
public:
TestScrollOffsetDelegate()
: page_scale_factor_(0.f),
min_page_scale_factor_(-1.f),
max_page_scale_factor_(-1.f) {}
~TestScrollOffsetDelegate() override {}
gfx::ScrollOffset GetTotalScrollOffset() override {
return getter_return_value_;
}
void UpdateRootLayerState(const gfx::ScrollOffset& total_scroll_offset,
const gfx::ScrollOffset& max_scroll_offset,
const gfx::SizeF& scrollable_size,
float page_scale_factor,
float min_page_scale_factor,
float max_page_scale_factor) override {
DCHECK(total_scroll_offset.x() <= max_scroll_offset.x());
DCHECK(total_scroll_offset.y() <= max_scroll_offset.y());
last_set_scroll_offset_ = total_scroll_offset;
max_scroll_offset_ = max_scroll_offset;
scrollable_size_ = scrollable_size;
page_scale_factor_ = page_scale_factor;
min_page_scale_factor_ = min_page_scale_factor;
max_page_scale_factor_ = max_page_scale_factor;
set_getter_return_value(last_set_scroll_offset_);
}
gfx::ScrollOffset last_set_scroll_offset() {
return last_set_scroll_offset_;
}
void set_getter_return_value(const gfx::ScrollOffset& value) {
getter_return_value_ = value;
}
gfx::ScrollOffset max_scroll_offset() const {
return max_scroll_offset_;
}
gfx::SizeF scrollable_size() const {
return scrollable_size_;
}
float page_scale_factor() const {
return page_scale_factor_;
}
float min_page_scale_factor() const {
return min_page_scale_factor_;
}
float max_page_scale_factor() const {
return max_page_scale_factor_;
}
private:
gfx::ScrollOffset last_set_scroll_offset_;
gfx::ScrollOffset getter_return_value_;
gfx::ScrollOffset max_scroll_offset_;
gfx::SizeF scrollable_size_;
float page_scale_factor_;
float min_page_scale_factor_;
float max_page_scale_factor_;
};
TEST_F(LayerTreeHostImplTest, RootLayerScrollOffsetDelegation) {
TestScrollOffsetDelegate scroll_delegate;
host_impl_->SetViewportSize(gfx::Size(10, 20));
LayerImpl* scroll_layer = SetupScrollAndContentsLayers(gfx::Size(100, 100));
LayerImpl* clip_layer = scroll_layer->parent()->parent();
clip_layer->SetBounds(gfx::Size(10, 20));
// Setting the delegate results in the current scroll offset being set.
gfx::Vector2dF initial_scroll_delta(10.f, 10.f);
scroll_layer->PushScrollOffsetFromMainThread(gfx::ScrollOffset());
scroll_layer->SetScrollDelta(initial_scroll_delta);
host_impl_->SetRootLayerScrollOffsetDelegate(&scroll_delegate);
EXPECT_EQ(initial_scroll_delta.ToString(),
scroll_delegate.last_set_scroll_offset().ToString());
// Setting the delegate results in the scrollable_size, max_scroll_offset,
// page_scale_factor and {min|max}_page_scale_factor being set.
EXPECT_EQ(gfx::SizeF(100, 100), scroll_delegate.scrollable_size());
EXPECT_EQ(gfx::ScrollOffset(90, 80), scroll_delegate.max_scroll_offset());
EXPECT_EQ(1.f, scroll_delegate.page_scale_factor());
EXPECT_EQ(1.f, scroll_delegate.min_page_scale_factor());
EXPECT_EQ(1.f, scroll_delegate.max_page_scale_factor());
// Updating page scale immediately updates the delegate.
host_impl_->active_tree()->PushPageScaleFromMainThread(2.f, 0.5f, 4.f);
EXPECT_EQ(2.f, scroll_delegate.page_scale_factor());
EXPECT_EQ(0.5f, scroll_delegate.min_page_scale_factor());
EXPECT_EQ(4.f, scroll_delegate.max_page_scale_factor());
host_impl_->active_tree()->SetPageScaleOnActiveTree(2.f * 1.5f);
EXPECT_EQ(3.f, scroll_delegate.page_scale_factor());
EXPECT_EQ(0.5f, scroll_delegate.min_page_scale_factor());
EXPECT_EQ(4.f, scroll_delegate.max_page_scale_factor());
host_impl_->active_tree()->SetPageScaleOnActiveTree(2.f);
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, 0.5f, 4.f);
EXPECT_EQ(1.f, scroll_delegate.page_scale_factor());
EXPECT_EQ(0.5f, scroll_delegate.min_page_scale_factor());
EXPECT_EQ(4.f, scroll_delegate.max_page_scale_factor());
// The pinch gesture doesn't put the delegate into a state where the scroll
// offset is outside of the scroll range. (this is verified by DCHECKs in the
// delegate).
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE);
host_impl_->PinchGestureBegin();
host_impl_->PinchGestureUpdate(2.f, gfx::Point());
host_impl_->PinchGestureUpdate(.5f, gfx::Point());
host_impl_->PinchGestureEnd();
host_impl_->ScrollEnd();
// Scrolling should be relative to the offset as given by the delegate.
gfx::Vector2dF scroll_delta(0.f, 10.f);
gfx::ScrollOffset current_offset(7.f, 8.f);
scroll_delegate.set_getter_return_value(current_offset);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
host_impl_->OnRootLayerDelegatedScrollOffsetChanged(current_offset);
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
EXPECT_EQ(ScrollOffsetWithDelta(current_offset, scroll_delta),
scroll_delegate.last_set_scroll_offset());
current_offset = gfx::ScrollOffset(42.f, 41.f);
scroll_delegate.set_getter_return_value(current_offset);
host_impl_->OnRootLayerDelegatedScrollOffsetChanged(current_offset);
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
EXPECT_EQ(current_offset + gfx::ScrollOffset(scroll_delta),
scroll_delegate.last_set_scroll_offset());
host_impl_->ScrollEnd();
scroll_delegate.set_getter_return_value(gfx::ScrollOffset());
host_impl_->OnRootLayerDelegatedScrollOffsetChanged(gfx::ScrollOffset());
// Forces a full tree synchronization and ensures that the scroll delegate
// sees the correct size of the new tree.
gfx::Size new_size(42, 24);
host_impl_->CreatePendingTree();
host_impl_->pending_tree()->PushPageScaleFromMainThread(1.f, 1.f, 1.f);
CreateScrollAndContentsLayers(host_impl_->pending_tree(), new_size);
host_impl_->ActivateSyncTree();
EXPECT_EQ(new_size, scroll_delegate.scrollable_size());
// Un-setting the delegate should propagate the delegate's current offset to
// the root scrollable layer.
current_offset = gfx::ScrollOffset(13.f, 12.f);
scroll_delegate.set_getter_return_value(current_offset);
host_impl_->OnRootLayerDelegatedScrollOffsetChanged(current_offset);
host_impl_->SetRootLayerScrollOffsetDelegate(NULL);
EXPECT_EQ(current_offset.ToString(),
scroll_layer->CurrentScrollOffset().ToString());
}
void CheckLayerScrollDelta(LayerImpl* layer, gfx::Vector2dF scroll_delta) {
const gfx::Transform target_space_transform =
layer->draw_properties().target_space_transform;
EXPECT_TRUE(target_space_transform.IsScaleOrTranslation());
gfx::Point translated_point;
target_space_transform.TransformPoint(&translated_point);
gfx::Point expected_point = gfx::Point() - ToRoundedVector2d(scroll_delta);
EXPECT_EQ(expected_point.ToString(), translated_point.ToString());
}
TEST_F(LayerTreeHostImplTest,
ExternalRootLayerScrollOffsetDelegationReflectedInNextDraw) {
TestScrollOffsetDelegate scroll_delegate;
host_impl_->SetViewportSize(gfx::Size(10, 20));
LayerImpl* scroll_layer = SetupScrollAndContentsLayers(gfx::Size(100, 100));
LayerImpl* clip_layer = scroll_layer->parent()->parent();
clip_layer->SetBounds(gfx::Size(10, 20));
host_impl_->SetRootLayerScrollOffsetDelegate(&scroll_delegate);
// Draw first frame to clear any pending draws and check scroll.
DrawFrame();
CheckLayerScrollDelta(scroll_layer, gfx::Vector2dF(0.f, 0.f));
EXPECT_FALSE(host_impl_->active_tree()->needs_update_draw_properties());
// Set external scroll delta on delegate and notify LayerTreeHost.
gfx::ScrollOffset scroll_offset(10.f, 10.f);
scroll_delegate.set_getter_return_value(scroll_offset);
host_impl_->OnRootLayerDelegatedScrollOffsetChanged(scroll_offset);
// Check scroll delta reflected in layer.
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
EXPECT_FALSE(frame.has_no_damage);
CheckLayerScrollDelta(scroll_layer, ScrollOffsetToVector2dF(scroll_offset));
host_impl_->SetRootLayerScrollOffsetDelegate(NULL);
}
TEST_F(LayerTreeHostImplTest, OverscrollRoot) {
InputHandlerScrollResult scroll_result;
SetupScrollAndContentsLayers(gfx::Size(100, 100));
host_impl_->SetViewportSize(gfx::Size(50, 50));
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, 0.5f, 4.f);
DrawFrame();
EXPECT_EQ(gfx::Vector2dF(), host_impl_->accumulated_root_overscroll());
// In-bounds scrolling does not affect overscroll.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
scroll_result = host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, 10));
EXPECT_TRUE(scroll_result.did_scroll);
EXPECT_FALSE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF(), scroll_result.unused_scroll_delta);
EXPECT_EQ(gfx::Vector2dF(), host_impl_->accumulated_root_overscroll());
// Overscroll events are reflected immediately.
scroll_result = host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, 50));
EXPECT_TRUE(scroll_result.did_scroll);
EXPECT_TRUE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF(0, 10), scroll_result.unused_scroll_delta);
EXPECT_EQ(gfx::Vector2dF(0, 10), host_impl_->accumulated_root_overscroll());
EXPECT_EQ(scroll_result.accumulated_root_overscroll,
host_impl_->accumulated_root_overscroll());
// In-bounds scrolling resets accumulated overscroll for the scrolled axes.
scroll_result = host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, -50));
EXPECT_TRUE(scroll_result.did_scroll);
EXPECT_FALSE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF(), scroll_result.unused_scroll_delta);
EXPECT_EQ(gfx::Vector2dF(0, 0), host_impl_->accumulated_root_overscroll());
EXPECT_EQ(scroll_result.accumulated_root_overscroll,
host_impl_->accumulated_root_overscroll());
scroll_result = host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, -10));
EXPECT_FALSE(scroll_result.did_scroll);
EXPECT_TRUE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF(0, -10), scroll_result.unused_scroll_delta);
EXPECT_EQ(gfx::Vector2dF(0, -10), host_impl_->accumulated_root_overscroll());
EXPECT_EQ(scroll_result.accumulated_root_overscroll,
host_impl_->accumulated_root_overscroll());
scroll_result = host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(10, 0));
EXPECT_TRUE(scroll_result.did_scroll);
EXPECT_FALSE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF(0, 0), scroll_result.unused_scroll_delta);
EXPECT_EQ(gfx::Vector2dF(0, -10), host_impl_->accumulated_root_overscroll());
EXPECT_EQ(scroll_result.accumulated_root_overscroll,
host_impl_->accumulated_root_overscroll());
scroll_result = host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(-15, 0));
EXPECT_TRUE(scroll_result.did_scroll);
EXPECT_TRUE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF(-5, 0), scroll_result.unused_scroll_delta);
EXPECT_EQ(gfx::Vector2dF(-5, -10), host_impl_->accumulated_root_overscroll());
EXPECT_EQ(scroll_result.accumulated_root_overscroll,
host_impl_->accumulated_root_overscroll());
scroll_result = host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, 60));
EXPECT_TRUE(scroll_result.did_scroll);
EXPECT_TRUE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF(0, 10), scroll_result.unused_scroll_delta);
EXPECT_EQ(gfx::Vector2dF(-5, 10), host_impl_->accumulated_root_overscroll());
EXPECT_EQ(scroll_result.accumulated_root_overscroll,
host_impl_->accumulated_root_overscroll());
scroll_result = host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(10, -60));
EXPECT_TRUE(scroll_result.did_scroll);
EXPECT_TRUE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF(0, -10), scroll_result.unused_scroll_delta);
EXPECT_EQ(gfx::Vector2dF(0, -10), host_impl_->accumulated_root_overscroll());
EXPECT_EQ(scroll_result.accumulated_root_overscroll,
host_impl_->accumulated_root_overscroll());
// Overscroll accumulates within the scope of ScrollBegin/ScrollEnd as long
// as no scroll occurs.
scroll_result = host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, -20));
EXPECT_FALSE(scroll_result.did_scroll);
EXPECT_TRUE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF(0, -20), scroll_result.unused_scroll_delta);
EXPECT_EQ(gfx::Vector2dF(0, -30), host_impl_->accumulated_root_overscroll());
EXPECT_EQ(scroll_result.accumulated_root_overscroll,
host_impl_->accumulated_root_overscroll());
scroll_result = host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, -20));
EXPECT_FALSE(scroll_result.did_scroll);
EXPECT_TRUE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF(0, -20), scroll_result.unused_scroll_delta);
EXPECT_EQ(gfx::Vector2dF(0, -50), host_impl_->accumulated_root_overscroll());
EXPECT_EQ(scroll_result.accumulated_root_overscroll,
host_impl_->accumulated_root_overscroll());
// Overscroll resets on valid scroll.
scroll_result = host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, 10));
EXPECT_TRUE(scroll_result.did_scroll);
EXPECT_FALSE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF(0, 0), scroll_result.unused_scroll_delta);
EXPECT_EQ(gfx::Vector2dF(0, 0), host_impl_->accumulated_root_overscroll());
EXPECT_EQ(scroll_result.accumulated_root_overscroll,
host_impl_->accumulated_root_overscroll());
scroll_result = host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, -20));
EXPECT_TRUE(scroll_result.did_scroll);
EXPECT_TRUE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF(0, -10), scroll_result.unused_scroll_delta);
EXPECT_EQ(gfx::Vector2dF(0, -10), host_impl_->accumulated_root_overscroll());
EXPECT_EQ(scroll_result.accumulated_root_overscroll,
host_impl_->accumulated_root_overscroll());
host_impl_->ScrollEnd();
}
TEST_F(LayerTreeHostImplTest, OverscrollChildWithoutBubbling) {
// Scroll child layers beyond their maximum scroll range and make sure root
// overscroll does not accumulate.
InputHandlerScrollResult scroll_result;
gfx::Size surface_size(10, 10);
scoped_ptr<LayerImpl> root_clip =
LayerImpl::Create(host_impl_->active_tree(), 4);
root_clip->SetHasRenderSurface(true);
scoped_ptr<LayerImpl> root =
CreateScrollableLayer(1, surface_size, root_clip.get());
scoped_ptr<LayerImpl> grand_child =
CreateScrollableLayer(3, surface_size, root_clip.get());
scoped_ptr<LayerImpl> child =
CreateScrollableLayer(2, surface_size, root_clip.get());
LayerImpl* grand_child_layer = grand_child.get();
child->AddChild(grand_child.Pass());
LayerImpl* child_layer = child.get();
root->AddChild(child.Pass());
root_clip->AddChild(root.Pass());
child_layer->PushScrollOffsetFromMainThread(gfx::ScrollOffset(0, 3));
grand_child_layer->PushScrollOffsetFromMainThread(gfx::ScrollOffset(0, 2));
host_impl_->active_tree()->SetRootLayer(root_clip.Pass());
host_impl_->active_tree()->DidBecomeActive();
host_impl_->SetViewportSize(surface_size);
DrawFrame();
{
gfx::Vector2d scroll_delta(0, -10);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(),
InputHandler::NON_BUBBLING_GESTURE));
scroll_result = host_impl_->ScrollBy(gfx::Point(), scroll_delta);
EXPECT_TRUE(scroll_result.did_scroll);
EXPECT_FALSE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF(), host_impl_->accumulated_root_overscroll());
host_impl_->ScrollEnd();
// The next time we scroll we should only scroll the parent, but overscroll
// should still not reach the root layer.
scroll_delta = gfx::Vector2d(0, -30);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(5, 5),
InputHandler::NON_BUBBLING_GESTURE));
EXPECT_EQ(host_impl_->CurrentlyScrollingLayer(), grand_child_layer);
EXPECT_EQ(gfx::Vector2dF(), host_impl_->accumulated_root_overscroll());
scroll_result = host_impl_->ScrollBy(gfx::Point(), scroll_delta);
EXPECT_TRUE(scroll_result.did_scroll);
EXPECT_FALSE(scroll_result.did_overscroll_root);
EXPECT_EQ(host_impl_->CurrentlyScrollingLayer(), child_layer);
EXPECT_EQ(gfx::Vector2dF(), host_impl_->accumulated_root_overscroll());
host_impl_->ScrollEnd();
// After scrolling the parent, another scroll on the opposite direction
// should scroll the child.
scroll_delta = gfx::Vector2d(0, 70);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(5, 5),
InputHandler::NON_BUBBLING_GESTURE));
EXPECT_EQ(host_impl_->CurrentlyScrollingLayer(), grand_child_layer);
scroll_result = host_impl_->ScrollBy(gfx::Point(), scroll_delta);
EXPECT_TRUE(scroll_result.did_scroll);
EXPECT_FALSE(scroll_result.did_overscroll_root);
EXPECT_EQ(host_impl_->CurrentlyScrollingLayer(), grand_child_layer);
EXPECT_EQ(gfx::Vector2dF(), host_impl_->accumulated_root_overscroll());
host_impl_->ScrollEnd();
}
}
TEST_F(LayerTreeHostImplTest, OverscrollChildEventBubbling) {
// When we try to scroll a non-scrollable child layer, the scroll delta
// should be applied to one of its ancestors if possible. Overscroll should
// be reflected only when it has bubbled up to the root scrolling layer.
InputHandlerScrollResult scroll_result;
SetupScrollAndContentsLayers(gfx::Size(20, 20));
DrawFrame();
{
gfx::Vector2d scroll_delta(0, 8);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(5, 5), InputHandler::WHEEL));
scroll_result = host_impl_->ScrollBy(gfx::Point(), scroll_delta);
EXPECT_TRUE(scroll_result.did_scroll);
EXPECT_FALSE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF(), host_impl_->accumulated_root_overscroll());
scroll_result = host_impl_->ScrollBy(gfx::Point(), scroll_delta);
EXPECT_TRUE(scroll_result.did_scroll);
EXPECT_TRUE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF(0, 6), host_impl_->accumulated_root_overscroll());
scroll_result = host_impl_->ScrollBy(gfx::Point(), scroll_delta);
EXPECT_FALSE(scroll_result.did_scroll);
EXPECT_TRUE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF(0, 14), host_impl_->accumulated_root_overscroll());
host_impl_->ScrollEnd();
}
}
TEST_F(LayerTreeHostImplTest, OverscrollAlways) {
InputHandlerScrollResult scroll_result;
LayerTreeSettings settings;
CreateHostImpl(settings, CreateOutputSurface());
LayerImpl* scroll_layer = SetupScrollAndContentsLayers(gfx::Size(50, 50));
LayerImpl* clip_layer = scroll_layer->parent()->parent();
clip_layer->SetBounds(gfx::Size(50, 50));
host_impl_->SetViewportSize(gfx::Size(50, 50));
host_impl_->active_tree()->PushPageScaleFromMainThread(1.f, 0.5f, 4.f);
DrawFrame();
EXPECT_EQ(gfx::Vector2dF(), host_impl_->accumulated_root_overscroll());
// Even though the layer can't scroll the overscroll still happens.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
scroll_result = host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, 10));
EXPECT_FALSE(scroll_result.did_scroll);
EXPECT_TRUE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF(0, 10), host_impl_->accumulated_root_overscroll());
}
TEST_F(LayerTreeHostImplTest, NoOverscrollWhenNotAtEdge) {
InputHandlerScrollResult scroll_result;
SetupScrollAndContentsLayers(gfx::Size(200, 200));
DrawFrame();
{
// Edge glow effect should be applicable only upon reaching Edges
// of the content. unnecessary glow effect calls shouldn't be
// called while scrolling up without reaching the edge of the content.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(0, 0), InputHandler::WHEEL));
scroll_result = host_impl_->ScrollBy(gfx::Point(), gfx::Vector2dF(0, 100));
EXPECT_TRUE(scroll_result.did_scroll);
EXPECT_FALSE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF().ToString(),
host_impl_->accumulated_root_overscroll().ToString());
scroll_result =
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2dF(0, -2.30f));
EXPECT_TRUE(scroll_result.did_scroll);
EXPECT_FALSE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF().ToString(),
host_impl_->accumulated_root_overscroll().ToString());
host_impl_->ScrollEnd();
// unusedrootDelta should be subtracted from applied delta so that
// unwanted glow effect calls are not called.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(0, 0),
InputHandler::NON_BUBBLING_GESTURE));
EXPECT_EQ(InputHandler::SCROLL_STARTED, host_impl_->FlingScrollBegin());
scroll_result = host_impl_->ScrollBy(gfx::Point(), gfx::Vector2dF(0, 20));
EXPECT_TRUE(scroll_result.did_scroll);
EXPECT_TRUE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF(0.000000f, 17.699997f).ToString(),
host_impl_->accumulated_root_overscroll().ToString());
scroll_result =
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2dF(0.02f, -0.01f));
EXPECT_FALSE(scroll_result.did_scroll);
EXPECT_FALSE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF(0.000000f, 17.699997f).ToString(),
host_impl_->accumulated_root_overscroll().ToString());
host_impl_->ScrollEnd();
// TestCase to check kEpsilon, which prevents minute values to trigger
// gloweffect without reaching edge.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(0, 0), InputHandler::WHEEL));
scroll_result =
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2dF(-0.12f, 0.1f));
EXPECT_FALSE(scroll_result.did_scroll);
EXPECT_FALSE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF().ToString(),
host_impl_->accumulated_root_overscroll().ToString());
host_impl_->ScrollEnd();
}
}
class BlendStateCheckLayer : public LayerImpl {
public:
static scoped_ptr<LayerImpl> Create(LayerTreeImpl* tree_impl,
int id,
ResourceProvider* resource_provider) {
return make_scoped_ptr(
new BlendStateCheckLayer(tree_impl, id, resource_provider));
}
void AppendQuads(RenderPass* render_pass,
AppendQuadsData* append_quads_data) override {
quads_appended_ = true;
gfx::Rect opaque_rect;
if (contents_opaque())
opaque_rect = quad_rect_;
else
opaque_rect = opaque_content_rect_;
gfx::Rect visible_quad_rect = quad_rect_;
SharedQuadState* shared_quad_state =
render_pass->CreateAndAppendSharedQuadState();
PopulateSharedQuadState(shared_quad_state);
TileDrawQuad* test_blending_draw_quad =
render_pass->CreateAndAppendDrawQuad<TileDrawQuad>();
test_blending_draw_quad->SetNew(shared_quad_state,
quad_rect_,
opaque_rect,
visible_quad_rect,
resource_id_,
gfx::RectF(0.f, 0.f, 1.f, 1.f),
gfx::Size(1, 1),
false,
false);
test_blending_draw_quad->visible_rect = quad_visible_rect_;
EXPECT_EQ(blend_, test_blending_draw_quad->ShouldDrawWithBlending());
EXPECT_EQ(has_render_surface_, !!render_surface());
}
void SetExpectation(bool blend, bool has_render_surface) {
blend_ = blend;
has_render_surface_ = has_render_surface;
quads_appended_ = false;
}
bool quads_appended() const { return quads_appended_; }
void SetQuadRect(const gfx::Rect& rect) { quad_rect_ = rect; }
void SetQuadVisibleRect(const gfx::Rect& rect) { quad_visible_rect_ = rect; }
void SetOpaqueContentRect(const gfx::Rect& rect) {
opaque_content_rect_ = rect;
}
private:
BlendStateCheckLayer(LayerTreeImpl* tree_impl,
int id,
ResourceProvider* resource_provider)
: LayerImpl(tree_impl, id),
blend_(false),
has_render_surface_(false),
quads_appended_(false),
quad_rect_(5, 5, 5, 5),
quad_visible_rect_(5, 5, 5, 5),
resource_id_(resource_provider->CreateResource(
gfx::Size(1, 1),
GL_CLAMP_TO_EDGE,
ResourceProvider::TEXTURE_HINT_IMMUTABLE,
RGBA_8888)) {
resource_provider->AllocateForTesting(resource_id_);
SetBounds(gfx::Size(10, 10));
SetDrawsContent(true);
}
bool blend_;
bool has_render_surface_;
bool quads_appended_;
gfx::Rect quad_rect_;
gfx::Rect opaque_content_rect_;
gfx::Rect quad_visible_rect_;
ResourceId resource_id_;
};
TEST_F(LayerTreeHostImplTest, BlendingOffWhenDrawingOpaqueLayers) {
{
scoped_ptr<LayerImpl> root =
LayerImpl::Create(host_impl_->active_tree(), 1);
root->SetBounds(gfx::Size(10, 10));
root->SetDrawsContent(false);
root->SetHasRenderSurface(true);
host_impl_->active_tree()->SetRootLayer(root.Pass());
}
LayerImpl* root = host_impl_->active_tree()->root_layer();
root->AddChild(
BlendStateCheckLayer::Create(host_impl_->active_tree(),
2,
host_impl_->resource_provider()));
BlendStateCheckLayer* layer1 =
static_cast<BlendStateCheckLayer*>(root->children()[0]);
layer1->SetPosition(gfx::PointF(2.f, 2.f));
LayerTreeHostImpl::FrameData frame;
// Opaque layer, drawn without blending.
layer1->SetContentsOpaque(true);
layer1->SetExpectation(false, false);
layer1->SetUpdateRect(gfx::Rect(layer1->bounds()));
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
EXPECT_TRUE(layer1->quads_appended());
host_impl_->DidDrawAllLayers(frame);
// Layer with translucent content and painting, so drawn with blending.
layer1->SetContentsOpaque(false);
layer1->SetExpectation(true, false);
layer1->SetUpdateRect(gfx::Rect(layer1->bounds()));
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
EXPECT_TRUE(layer1->quads_appended());
host_impl_->DidDrawAllLayers(frame);
// Layer with translucent opacity, drawn with blending.
layer1->SetContentsOpaque(true);
layer1->SetOpacity(0.5f);
layer1->SetExpectation(true, false);
layer1->SetUpdateRect(gfx::Rect(layer1->bounds()));
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
EXPECT_TRUE(layer1->quads_appended());
host_impl_->DidDrawAllLayers(frame);
// Layer with translucent opacity and painting, drawn with blending.
layer1->SetContentsOpaque(true);
layer1->SetOpacity(0.5f);
layer1->SetExpectation(true, false);
layer1->SetUpdateRect(gfx::Rect(layer1->bounds()));
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
EXPECT_TRUE(layer1->quads_appended());
host_impl_->DidDrawAllLayers(frame);
layer1->AddChild(
BlendStateCheckLayer::Create(host_impl_->active_tree(),
3,
host_impl_->resource_provider()));
BlendStateCheckLayer* layer2 =
static_cast<BlendStateCheckLayer*>(layer1->children()[0]);
layer2->SetPosition(gfx::PointF(4.f, 4.f));
// 2 opaque layers, drawn without blending.
layer1->SetContentsOpaque(true);
layer1->SetOpacity(1.f);
layer1->SetExpectation(false, false);
layer1->SetUpdateRect(gfx::Rect(layer1->bounds()));
layer2->SetContentsOpaque(true);
layer2->SetOpacity(1.f);
layer2->SetExpectation(false, false);
layer2->SetUpdateRect(gfx::Rect(layer1->bounds()));
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
EXPECT_TRUE(layer1->quads_appended());
EXPECT_TRUE(layer2->quads_appended());
host_impl_->DidDrawAllLayers(frame);
// Parent layer with translucent content, drawn with blending.
// Child layer with opaque content, drawn without blending.
layer1->SetContentsOpaque(false);
layer1->SetExpectation(true, false);
layer1->SetUpdateRect(gfx::Rect(layer1->bounds()));
layer2->SetExpectation(false, false);
layer2->SetUpdateRect(gfx::Rect(layer1->bounds()));
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
EXPECT_TRUE(layer1->quads_appended());
EXPECT_TRUE(layer2->quads_appended());
host_impl_->DidDrawAllLayers(frame);
// Parent layer with translucent content but opaque painting, drawn without
// blending.
// Child layer with opaque content, drawn without blending.
layer1->SetContentsOpaque(true);
layer1->SetExpectation(false, false);
layer1->SetUpdateRect(gfx::Rect(layer1->bounds()));
layer2->SetExpectation(false, false);
layer2->SetUpdateRect(gfx::Rect(layer1->bounds()));
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
EXPECT_TRUE(layer1->quads_appended());
EXPECT_TRUE(layer2->quads_appended());
host_impl_->DidDrawAllLayers(frame);
// Parent layer with translucent opacity and opaque content. Since it has a
// drawing child, it's drawn to a render surface which carries the opacity,
// so it's itself drawn without blending.
// Child layer with opaque content, drawn without blending (parent surface
// carries the inherited opacity).
layer1->SetContentsOpaque(true);
layer1->SetOpacity(0.5f);
layer1->SetHasRenderSurface(true);
layer1->SetExpectation(false, true);
layer1->SetUpdateRect(gfx::Rect(layer1->bounds()));
layer2->SetExpectation(false, false);
layer2->SetUpdateRect(gfx::Rect(layer1->bounds()));
FakeLayerTreeHostImpl::RecursiveUpdateNumChildren(
host_impl_->active_tree()->root_layer());
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
EXPECT_TRUE(layer1->quads_appended());
EXPECT_TRUE(layer2->quads_appended());
host_impl_->DidDrawAllLayers(frame);
layer1->SetHasRenderSurface(false);
// Draw again, but with child non-opaque, to make sure
// layer1 not culled.
layer1->SetContentsOpaque(true);
layer1->SetOpacity(1.f);
layer1->SetExpectation(false, false);
layer1->SetUpdateRect(gfx::Rect(layer1->bounds()));
layer2->SetContentsOpaque(true);
layer2->SetOpacity(0.5f);
layer2->SetExpectation(true, false);
layer2->SetUpdateRect(gfx::Rect(layer1->bounds()));
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
EXPECT_TRUE(layer1->quads_appended());
EXPECT_TRUE(layer2->quads_appended());
host_impl_->DidDrawAllLayers(frame);
// A second way of making the child non-opaque.
layer1->SetContentsOpaque(true);
layer1->SetOpacity(1.f);
layer1->SetExpectation(false, false);
layer1->SetUpdateRect(gfx::Rect(layer1->bounds()));
layer2->SetContentsOpaque(false);
layer2->SetOpacity(1.f);
layer2->SetExpectation(true, false);
layer2->SetUpdateRect(gfx::Rect(layer1->bounds()));
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
EXPECT_TRUE(layer1->quads_appended());
EXPECT_TRUE(layer2->quads_appended());
host_impl_->DidDrawAllLayers(frame);
// And when the layer says its not opaque but is painted opaque, it is not
// blended.
layer1->SetContentsOpaque(true);
layer1->SetOpacity(1.f);
layer1->SetExpectation(false, false);
layer1->SetUpdateRect(gfx::Rect(layer1->bounds()));
layer2->SetContentsOpaque(true);
layer2->SetOpacity(1.f);
layer2->SetExpectation(false, false);
layer2->SetUpdateRect(gfx::Rect(layer1->bounds()));
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
EXPECT_TRUE(layer1->quads_appended());
EXPECT_TRUE(layer2->quads_appended());
host_impl_->DidDrawAllLayers(frame);
// Layer with partially opaque contents, drawn with blending.
layer1->SetContentsOpaque(false);
layer1->SetQuadRect(gfx::Rect(5, 5, 5, 5));
layer1->SetQuadVisibleRect(gfx::Rect(5, 5, 5, 5));
layer1->SetOpaqueContentRect(gfx::Rect(5, 5, 2, 5));
layer1->SetExpectation(true, false);
layer1->SetUpdateRect(gfx::Rect(layer1->bounds()));
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
EXPECT_TRUE(layer1->quads_appended());
host_impl_->DidDrawAllLayers(frame);
// Layer with partially opaque contents partially culled, drawn with blending.
layer1->SetContentsOpaque(false);
layer1->SetQuadRect(gfx::Rect(5, 5, 5, 5));
layer1->SetQuadVisibleRect(gfx::Rect(5, 5, 5, 2));
layer1->SetOpaqueContentRect(gfx::Rect(5, 5, 2, 5));
layer1->SetExpectation(true, false);
layer1->SetUpdateRect(gfx::Rect(layer1->bounds()));
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
EXPECT_TRUE(layer1->quads_appended());
host_impl_->DidDrawAllLayers(frame);
// Layer with partially opaque contents culled, drawn with blending.
layer1->SetContentsOpaque(false);
layer1->SetQuadRect(gfx::Rect(5, 5, 5, 5));
layer1->SetQuadVisibleRect(gfx::Rect(7, 5, 3, 5));
layer1->SetOpaqueContentRect(gfx::Rect(5, 5, 2, 5));
layer1->SetExpectation(true, false);
layer1->SetUpdateRect(gfx::Rect(layer1->bounds()));
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
EXPECT_TRUE(layer1->quads_appended());
host_impl_->DidDrawAllLayers(frame);
// Layer with partially opaque contents and translucent contents culled, drawn
// without blending.
layer1->SetContentsOpaque(false);
layer1->SetQuadRect(gfx::Rect(5, 5, 5, 5));
layer1->SetQuadVisibleRect(gfx::Rect(5, 5, 2, 5));
layer1->SetOpaqueContentRect(gfx::Rect(5, 5, 2, 5));
layer1->SetExpectation(false, false);
layer1->SetUpdateRect(gfx::Rect(layer1->bounds()));
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
EXPECT_TRUE(layer1->quads_appended());
host_impl_->DidDrawAllLayers(frame);
}
class LayerTreeHostImplViewportCoveredTest : public LayerTreeHostImplTest {
protected:
LayerTreeHostImplViewportCoveredTest() :
gutter_quad_material_(DrawQuad::SOLID_COLOR),
child_(NULL),
did_activate_pending_tree_(false) {}
scoped_ptr<OutputSurface> CreateFakeOutputSurface(bool always_draw) {
if (always_draw) {
return FakeOutputSurface::CreateAlwaysDrawAndSwap3d();
}
return FakeOutputSurface::Create3d();
}
void SetupActiveTreeLayers() {
host_impl_->active_tree()->set_background_color(SK_ColorGRAY);
host_impl_->active_tree()->SetRootLayer(
LayerImpl::Create(host_impl_->active_tree(), 1));
host_impl_->active_tree()->root_layer()->SetHasRenderSurface(true);
host_impl_->active_tree()->root_layer()->AddChild(
BlendStateCheckLayer::Create(host_impl_->active_tree(),
2,
host_impl_->resource_provider()));
child_ = static_cast<BlendStateCheckLayer*>(
host_impl_->active_tree()->root_layer()->children()[0]);
child_->SetExpectation(false, false);
child_->SetContentsOpaque(true);
}
// Expect no gutter rects.
void TestLayerCoversFullViewport() {
gfx::Rect layer_rect(viewport_size_);
child_->SetPosition(layer_rect.origin());
child_->SetBounds(layer_rect.size());
child_->SetQuadRect(gfx::Rect(layer_rect.size()));
child_->SetQuadVisibleRect(gfx::Rect(layer_rect.size()));
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
ASSERT_EQ(1u, frame.render_passes.size());
EXPECT_EQ(0u, CountGutterQuads(frame.render_passes[0]->quad_list));
EXPECT_EQ(1u, frame.render_passes[0]->quad_list.size());
ValidateTextureDrawQuads(frame.render_passes[0]->quad_list);
VerifyQuadsExactlyCoverViewport(frame.render_passes[0]->quad_list);
host_impl_->DidDrawAllLayers(frame);
}
// Expect fullscreen gutter rect.
void TestEmptyLayer() {
gfx::Rect layer_rect(0, 0, 0, 0);
child_->SetPosition(layer_rect.origin());
child_->SetBounds(layer_rect.size());
child_->SetQuadRect(gfx::Rect(layer_rect.size()));
child_->SetQuadVisibleRect(gfx::Rect(layer_rect.size()));
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
ASSERT_EQ(1u, frame.render_passes.size());
EXPECT_EQ(1u, CountGutterQuads(frame.render_passes[0]->quad_list));
EXPECT_EQ(1u, frame.render_passes[0]->quad_list.size());
ValidateTextureDrawQuads(frame.render_passes[0]->quad_list);
VerifyQuadsExactlyCoverViewport(frame.render_passes[0]->quad_list);
host_impl_->DidDrawAllLayers(frame);
}
// Expect four surrounding gutter rects.
void TestLayerInMiddleOfViewport() {
gfx::Rect layer_rect(500, 500, 200, 200);
child_->SetPosition(layer_rect.origin());
child_->SetBounds(layer_rect.size());
child_->SetQuadRect(gfx::Rect(layer_rect.size()));
child_->SetQuadVisibleRect(gfx::Rect(layer_rect.size()));
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
ASSERT_EQ(1u, frame.render_passes.size());
EXPECT_EQ(4u, CountGutterQuads(frame.render_passes[0]->quad_list));
EXPECT_EQ(5u, frame.render_passes[0]->quad_list.size());
ValidateTextureDrawQuads(frame.render_passes[0]->quad_list);
VerifyQuadsExactlyCoverViewport(frame.render_passes[0]->quad_list);
host_impl_->DidDrawAllLayers(frame);
}
// Expect no gutter rects.
void TestLayerIsLargerThanViewport() {
gfx::Rect layer_rect(viewport_size_.width() + 10,
viewport_size_.height() + 10);
child_->SetPosition(layer_rect.origin());
child_->SetBounds(layer_rect.size());
child_->SetQuadRect(gfx::Rect(layer_rect.size()));
child_->SetQuadVisibleRect(gfx::Rect(layer_rect.size()));
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
ASSERT_EQ(1u, frame.render_passes.size());
EXPECT_EQ(0u, CountGutterQuads(frame.render_passes[0]->quad_list));
EXPECT_EQ(1u, frame.render_passes[0]->quad_list.size());
ValidateTextureDrawQuads(frame.render_passes[0]->quad_list);
host_impl_->DidDrawAllLayers(frame);
}
void DidActivateSyncTree() override { did_activate_pending_tree_ = true; }
void set_gutter_quad_material(DrawQuad::Material material) {
gutter_quad_material_ = material;
}
void set_gutter_texture_size(const gfx::Size& gutter_texture_size) {
gutter_texture_size_ = gutter_texture_size;
}
protected:
size_t CountGutterQuads(const QuadList& quad_list) {
size_t num_gutter_quads = 0;
for (const auto& quad : quad_list) {
num_gutter_quads += (quad->material == gutter_quad_material_) ? 1 : 0;
}
return num_gutter_quads;
}
void VerifyQuadsExactlyCoverViewport(const QuadList& quad_list) {
LayerTestCommon::VerifyQuadsExactlyCoverRect(
quad_list, gfx::Rect(DipSizeToPixelSize(viewport_size_)));
}
// Make sure that the texture coordinates match their expectations.
void ValidateTextureDrawQuads(const QuadList& quad_list) {
for (const auto& quad : quad_list) {
if (quad->material != DrawQuad::TEXTURE_CONTENT)
continue;
const TextureDrawQuad* texture_quad = TextureDrawQuad::MaterialCast(quad);
gfx::SizeF gutter_texture_size_pixels = gfx::ScaleSize(
gutter_texture_size_, host_impl_->device_scale_factor());
EXPECT_EQ(texture_quad->uv_top_left.x(),
texture_quad->rect.x() / gutter_texture_size_pixels.width());
EXPECT_EQ(texture_quad->uv_top_left.y(),
texture_quad->rect.y() / gutter_texture_size_pixels.height());
EXPECT_EQ(
texture_quad->uv_bottom_right.x(),
texture_quad->rect.right() / gutter_texture_size_pixels.width());
EXPECT_EQ(
texture_quad->uv_bottom_right.y(),
texture_quad->rect.bottom() / gutter_texture_size_pixels.height());
}
}
gfx::Size DipSizeToPixelSize(const gfx::Size& size) {
return gfx::ToRoundedSize(
gfx::ScaleSize(size, host_impl_->device_scale_factor()));
}
DrawQuad::Material gutter_quad_material_;
gfx::Size gutter_texture_size_;
gfx::Size viewport_size_;
BlendStateCheckLayer* child_;
bool did_activate_pending_tree_;
};
TEST_F(LayerTreeHostImplViewportCoveredTest, ViewportCovered) {
viewport_size_ = gfx::Size(1000, 1000);
bool always_draw = false;
CreateHostImpl(DefaultSettings(), CreateFakeOutputSurface(always_draw));
host_impl_->SetViewportSize(DipSizeToPixelSize(viewport_size_));
SetupActiveTreeLayers();
TestLayerCoversFullViewport();
TestEmptyLayer();
TestLayerInMiddleOfViewport();
TestLayerIsLargerThanViewport();
}
TEST_F(LayerTreeHostImplViewportCoveredTest, ViewportCoveredScaled) {
viewport_size_ = gfx::Size(1000, 1000);
bool always_draw = false;
CreateHostImpl(DefaultSettings(), CreateFakeOutputSurface(always_draw));
host_impl_->SetDeviceScaleFactor(2.f);
host_impl_->SetViewportSize(DipSizeToPixelSize(viewport_size_));
SetupActiveTreeLayers();
TestLayerCoversFullViewport();
TestEmptyLayer();
TestLayerInMiddleOfViewport();
TestLayerIsLargerThanViewport();
}
TEST_F(LayerTreeHostImplViewportCoveredTest, ActiveTreeGrowViewportInvalid) {
viewport_size_ = gfx::Size(1000, 1000);
bool always_draw = true;
CreateHostImpl(DefaultSettings(), CreateFakeOutputSurface(always_draw));
// Pending tree to force active_tree size invalid. Not used otherwise.
host_impl_->CreatePendingTree();
host_impl_->SetViewportSize(DipSizeToPixelSize(viewport_size_));
EXPECT_TRUE(host_impl_->active_tree()->ViewportSizeInvalid());
SetupActiveTreeLayers();
TestEmptyLayer();
TestLayerInMiddleOfViewport();
TestLayerIsLargerThanViewport();
}
TEST_F(LayerTreeHostImplViewportCoveredTest, ActiveTreeShrinkViewportInvalid) {
viewport_size_ = gfx::Size(1000, 1000);
bool always_draw = true;
CreateHostImpl(DefaultSettings(), CreateFakeOutputSurface(always_draw));
// Set larger viewport and activate it to active tree.
host_impl_->CreatePendingTree();
gfx::Size larger_viewport(viewport_size_.width() + 100,
viewport_size_.height() + 100);
host_impl_->SetViewportSize(DipSizeToPixelSize(larger_viewport));
EXPECT_TRUE(host_impl_->active_tree()->ViewportSizeInvalid());
host_impl_->ActivateSyncTree();
EXPECT_TRUE(did_activate_pending_tree_);
EXPECT_FALSE(host_impl_->active_tree()->ViewportSizeInvalid());
// Shrink pending tree viewport without activating.
host_impl_->CreatePendingTree();
host_impl_->SetViewportSize(DipSizeToPixelSize(viewport_size_));
EXPECT_TRUE(host_impl_->active_tree()->ViewportSizeInvalid());
SetupActiveTreeLayers();
TestEmptyLayer();
TestLayerInMiddleOfViewport();
TestLayerIsLargerThanViewport();
}
class FakeDrawableLayerImpl: public LayerImpl {
public:
static scoped_ptr<LayerImpl> Create(LayerTreeImpl* tree_impl, int id) {
return make_scoped_ptr(new FakeDrawableLayerImpl(tree_impl, id));
}
protected:
FakeDrawableLayerImpl(LayerTreeImpl* tree_impl, int id)
: LayerImpl(tree_impl, id) {}
};
// Only reshape when we know we are going to draw. Otherwise, the reshape
// can leave the window at the wrong size if we never draw and the proper
// viewport size is never set.
TEST_F(LayerTreeHostImplTest, ReshapeNotCalledUntilDraw) {
scoped_refptr<TestContextProvider> provider(TestContextProvider::Create());
scoped_ptr<OutputSurface> output_surface(
FakeOutputSurface::Create3d(provider));
CreateHostImpl(DefaultSettings(), output_surface.Pass());
scoped_ptr<LayerImpl> root =
FakeDrawableLayerImpl::Create(host_impl_->active_tree(), 1);
root->SetBounds(gfx::Size(10, 10));
root->SetDrawsContent(true);
root->SetHasRenderSurface(true);
host_impl_->active_tree()->SetRootLayer(root.Pass());
EXPECT_FALSE(provider->TestContext3d()->reshape_called());
provider->TestContext3d()->clear_reshape_called();
LayerTreeHostImpl::FrameData frame;
host_impl_->SetViewportSize(gfx::Size(10, 10));
host_impl_->SetDeviceScaleFactor(1.f);
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
EXPECT_TRUE(provider->TestContext3d()->reshape_called());
EXPECT_EQ(provider->TestContext3d()->width(), 10);
EXPECT_EQ(provider->TestContext3d()->height(), 10);
EXPECT_EQ(provider->TestContext3d()->scale_factor(), 1.f);
host_impl_->DidDrawAllLayers(frame);
provider->TestContext3d()->clear_reshape_called();
host_impl_->SetViewportSize(gfx::Size(20, 30));
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
EXPECT_TRUE(provider->TestContext3d()->reshape_called());
EXPECT_EQ(provider->TestContext3d()->width(), 20);
EXPECT_EQ(provider->TestContext3d()->height(), 30);
EXPECT_EQ(provider->TestContext3d()->scale_factor(), 1.f);
host_impl_->DidDrawAllLayers(frame);
provider->TestContext3d()->clear_reshape_called();
host_impl_->SetDeviceScaleFactor(2.f);
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
EXPECT_TRUE(provider->TestContext3d()->reshape_called());
EXPECT_EQ(provider->TestContext3d()->width(), 20);
EXPECT_EQ(provider->TestContext3d()->height(), 30);
EXPECT_EQ(provider->TestContext3d()->scale_factor(), 2.f);
host_impl_->DidDrawAllLayers(frame);
provider->TestContext3d()->clear_reshape_called();
}
// Make sure damage tracking propagates all the way to the graphics context,
// where it should request to swap only the sub-buffer that is damaged.
TEST_F(LayerTreeHostImplTest, PartialSwapReceivesDamageRect) {
scoped_refptr<TestContextProvider> context_provider(
TestContextProvider::Create());
context_provider->BindToCurrentThread();
context_provider->TestContext3d()->set_have_post_sub_buffer(true);
scoped_ptr<FakeOutputSurface> output_surface(
FakeOutputSurface::Create3d(context_provider));
FakeOutputSurface* fake_output_surface = output_surface.get();
// This test creates its own LayerTreeHostImpl, so
// that we can force partial swap enabled.
LayerTreeSettings settings;
settings.renderer_settings.partial_swap_enabled = true;
scoped_ptr<LayerTreeHostImpl> layer_tree_host_impl =
LayerTreeHostImpl::Create(
settings, this, &proxy_, &stats_instrumentation_,
&shared_bitmap_manager_, NULL, &task_graph_runner_, 0);
layer_tree_host_impl->InitializeRenderer(output_surface.Pass());
layer_tree_host_impl->WillBeginImplFrame(
CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE));
layer_tree_host_impl->SetViewportSize(gfx::Size(500, 500));
scoped_ptr<LayerImpl> root =
FakeDrawableLayerImpl::Create(layer_tree_host_impl->active_tree(), 1);
root->SetHasRenderSurface(true);
scoped_ptr<LayerImpl> child =
FakeDrawableLayerImpl::Create(layer_tree_host_impl->active_tree(), 2);
child->SetPosition(gfx::PointF(12.f, 13.f));
child->SetBounds(gfx::Size(14, 15));
child->SetDrawsContent(true);
root->SetBounds(gfx::Size(500, 500));
root->SetDrawsContent(true);
root->AddChild(child.Pass());
layer_tree_host_impl->active_tree()->SetRootLayer(root.Pass());
LayerTreeHostImpl::FrameData frame;
// First frame, the entire screen should get swapped.
EXPECT_EQ(DRAW_SUCCESS, layer_tree_host_impl->PrepareToDraw(&frame));
layer_tree_host_impl->DrawLayers(&frame);
layer_tree_host_impl->DidDrawAllLayers(frame);
layer_tree_host_impl->SwapBuffers(frame);
gfx::Rect expected_swap_rect(0, 0, 500, 500);
EXPECT_EQ(expected_swap_rect.ToString(),
fake_output_surface->last_swap_rect().ToString());
// Second frame, only the damaged area should get swapped. Damage should be
// the union of old and new child rects.
// expected damage rect: gfx::Rect(26, 28);
// expected swap rect: vertically flipped, with origin at bottom left corner.
layer_tree_host_impl->active_tree()->root_layer()->children()[0]->SetPosition(
gfx::PointF());
EXPECT_EQ(DRAW_SUCCESS, layer_tree_host_impl->PrepareToDraw(&frame));
layer_tree_host_impl->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
layer_tree_host_impl->SwapBuffers(frame);
// Make sure that partial swap is constrained to the viewport dimensions
// expected damage rect: gfx::Rect(500, 500);
// expected swap rect: flipped damage rect, but also clamped to viewport
expected_swap_rect = gfx::Rect(0, 500-28, 26, 28);
EXPECT_EQ(expected_swap_rect.ToString(),
fake_output_surface->last_swap_rect().ToString());
layer_tree_host_impl->SetViewportSize(gfx::Size(10, 10));
// This will damage everything.
layer_tree_host_impl->active_tree()->root_layer()->SetBackgroundColor(
SK_ColorBLACK);
EXPECT_EQ(DRAW_SUCCESS, layer_tree_host_impl->PrepareToDraw(&frame));
layer_tree_host_impl->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
layer_tree_host_impl->SwapBuffers(frame);
expected_swap_rect = gfx::Rect(0, 0, 10, 10);
EXPECT_EQ(expected_swap_rect.ToString(),
fake_output_surface->last_swap_rect().ToString());
}
TEST_F(LayerTreeHostImplTest, RootLayerDoesntCreateExtraSurface) {
scoped_ptr<LayerImpl> root =
FakeDrawableLayerImpl::Create(host_impl_->active_tree(), 1);
scoped_ptr<LayerImpl> child =
FakeDrawableLayerImpl::Create(host_impl_->active_tree(), 2);
child->SetBounds(gfx::Size(10, 10));
child->SetDrawsContent(true);
root->SetBounds(gfx::Size(10, 10));
root->SetDrawsContent(true);
root->SetHasRenderSurface(true);
root->AddChild(child.Pass());
host_impl_->active_tree()->SetRootLayer(root.Pass());
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
EXPECT_EQ(1u, frame.render_surface_layer_list->size());
EXPECT_EQ(1u, frame.render_passes.size());
host_impl_->DidDrawAllLayers(frame);
}
class FakeLayerWithQuads : public LayerImpl {
public:
static scoped_ptr<LayerImpl> Create(LayerTreeImpl* tree_impl, int id) {
return make_scoped_ptr(new FakeLayerWithQuads(tree_impl, id));
}
void AppendQuads(RenderPass* render_pass,
AppendQuadsData* append_quads_data) override {
SharedQuadState* shared_quad_state =
render_pass->CreateAndAppendSharedQuadState();
PopulateSharedQuadState(shared_quad_state);
SkColor gray = SkColorSetRGB(100, 100, 100);
gfx::Rect quad_rect(bounds());
gfx::Rect visible_quad_rect(quad_rect);
SolidColorDrawQuad* my_quad =
render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
my_quad->SetNew(
shared_quad_state, quad_rect, visible_quad_rect, gray, false);
}
private:
FakeLayerWithQuads(LayerTreeImpl* tree_impl, int id)
: LayerImpl(tree_impl, id) {}
};
class MockContext : public TestWebGraphicsContext3D {
public:
MOCK_METHOD1(useProgram, void(GLuint program));
MOCK_METHOD5(uniform4f, void(GLint location,
GLfloat x,
GLfloat y,
GLfloat z,
GLfloat w));
MOCK_METHOD4(uniformMatrix4fv, void(GLint location,
GLsizei count,
GLboolean transpose,
const GLfloat* value));
MOCK_METHOD4(drawElements, void(GLenum mode,
GLsizei count,
GLenum type,
GLintptr offset));
MOCK_METHOD1(enable, void(GLenum cap));
MOCK_METHOD1(disable, void(GLenum cap));
MOCK_METHOD4(scissor, void(GLint x,
GLint y,
GLsizei width,
GLsizei height));
};
class MockContextHarness {
private:
MockContext* context_;
public:
explicit MockContextHarness(MockContext* context)
: context_(context) {
context_->set_have_post_sub_buffer(true);
// Catch "uninteresting" calls
EXPECT_CALL(*context_, useProgram(_))
.Times(0);
EXPECT_CALL(*context_, drawElements(_, _, _, _))
.Times(0);
// These are not asserted
EXPECT_CALL(*context_, uniformMatrix4fv(_, _, _, _))
.WillRepeatedly(Return());
EXPECT_CALL(*context_, uniform4f(_, _, _, _, _))
.WillRepeatedly(Return());
// Any un-sanctioned calls to enable() are OK
EXPECT_CALL(*context_, enable(_))
.WillRepeatedly(Return());
// Any un-sanctioned calls to disable() are OK
EXPECT_CALL(*context_, disable(_))
.WillRepeatedly(Return());
}
void MustDrawSolidQuad() {
EXPECT_CALL(*context_, drawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0))
.WillOnce(Return())
.RetiresOnSaturation();
EXPECT_CALL(*context_, useProgram(_))
.WillOnce(Return())
.RetiresOnSaturation();
}
void MustSetScissor(int x, int y, int width, int height) {
EXPECT_CALL(*context_, enable(GL_SCISSOR_TEST))
.WillRepeatedly(Return());
EXPECT_CALL(*context_, scissor(x, y, width, height))
.Times(AtLeast(1))
.WillRepeatedly(Return());
}
void MustSetNoScissor() {
EXPECT_CALL(*context_, disable(GL_SCISSOR_TEST))
.WillRepeatedly(Return());
EXPECT_CALL(*context_, enable(GL_SCISSOR_TEST))
.Times(0);
EXPECT_CALL(*context_, scissor(_, _, _, _))
.Times(0);
}
};
TEST_F(LayerTreeHostImplTest, NoPartialSwap) {
scoped_ptr<MockContext> mock_context_owned(new MockContext);
MockContext* mock_context = mock_context_owned.get();
MockContextHarness harness(mock_context);
// Run test case
LayerTreeSettings settings = DefaultSettings();
settings.renderer_settings.partial_swap_enabled = false;
CreateHostImpl(settings,
FakeOutputSurface::Create3d(mock_context_owned.Pass()));
SetupRootLayerImpl(FakeLayerWithQuads::Create(host_impl_->active_tree(), 1));
// Without partial swap, and no clipping, no scissor is set.
harness.MustDrawSolidQuad();
harness.MustSetNoScissor();
{
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
}
Mock::VerifyAndClearExpectations(&mock_context);
// Without partial swap, but a layer does clip its subtree, one scissor is
// set.
host_impl_->active_tree()->root_layer()->SetMasksToBounds(true);
harness.MustDrawSolidQuad();
harness.MustSetScissor(0, 0, 10, 10);
{
LayerTreeHostImpl::FrameData frame;
host_impl_->active_tree()->BuildPropertyTreesForTesting();
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
}
Mock::VerifyAndClearExpectations(&mock_context);
}
TEST_F(LayerTreeHostImplTest, PartialSwap) {
scoped_ptr<MockContext> context_owned(new MockContext);
MockContext* mock_context = context_owned.get();
MockContextHarness harness(mock_context);
LayerTreeSettings settings = DefaultSettings();
settings.renderer_settings.partial_swap_enabled = true;
CreateHostImpl(settings, FakeOutputSurface::Create3d(context_owned.Pass()));
SetupRootLayerImpl(FakeLayerWithQuads::Create(host_impl_->active_tree(), 1));
// The first frame is not a partially-swapped one. No scissor should be set.
harness.MustSetNoScissor();
harness.MustDrawSolidQuad();
{
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
}
Mock::VerifyAndClearExpectations(&mock_context);
// Damage a portion of the frame.
host_impl_->active_tree()->root_layer()->SetUpdateRect(
gfx::Rect(0, 0, 2, 3));
// The second frame will be partially-swapped (the y coordinates are flipped).
harness.MustSetScissor(0, 7, 2, 3);
harness.MustDrawSolidQuad();
{
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
}
Mock::VerifyAndClearExpectations(&mock_context);
}
static scoped_ptr<LayerTreeHostImpl> SetupLayersForOpacity(
bool partial_swap,
LayerTreeHostImplClient* client,
Proxy* proxy,
SharedBitmapManager* manager,
TaskGraphRunner* task_graph_runner,
RenderingStatsInstrumentation* stats_instrumentation) {
scoped_refptr<TestContextProvider> provider(TestContextProvider::Create());
scoped_ptr<OutputSurface> output_surface(
FakeOutputSurface::Create3d(provider));
provider->BindToCurrentThread();
provider->TestContext3d()->set_have_post_sub_buffer(true);
LayerTreeSettings settings;
settings.renderer_settings.partial_swap_enabled = partial_swap;
scoped_ptr<LayerTreeHostImpl> my_host_impl =
LayerTreeHostImpl::Create(settings, client, proxy, stats_instrumentation,
manager, nullptr, task_graph_runner, 0);
my_host_impl->InitializeRenderer(output_surface.Pass());
my_host_impl->WillBeginImplFrame(
CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE));
my_host_impl->SetViewportSize(gfx::Size(100, 100));
/*
Layers are created as follows:
+--------------------+
| 1 |
| +-----------+ |
| | 2 | |
| | +-------------------+
| | | 3 |
| | +-------------------+
| | | |
| +-----------+ |
| |
| |
+--------------------+
Layers 1, 2 have render surfaces
*/
scoped_ptr<LayerImpl> root =
LayerImpl::Create(my_host_impl->active_tree(), 1);
scoped_ptr<LayerImpl> child =
LayerImpl::Create(my_host_impl->active_tree(), 2);
scoped_ptr<LayerImpl> grand_child =
FakeLayerWithQuads::Create(my_host_impl->active_tree(), 3);
gfx::Rect root_rect(0, 0, 100, 100);
gfx::Rect child_rect(10, 10, 50, 50);
gfx::Rect grand_child_rect(5, 5, 150, 150);
root->SetHasRenderSurface(true);
root->SetPosition(root_rect.origin());
root->SetBounds(root_rect.size());
root->draw_properties().visible_layer_rect = root_rect;
root->SetDrawsContent(false);
root->render_surface()->SetContentRect(gfx::Rect(root_rect.size()));
child->SetPosition(gfx::PointF(child_rect.x(), child_rect.y()));
child->SetOpacity(0.5f);
child->SetBounds(gfx::Size(child_rect.width(), child_rect.height()));
child->draw_properties().visible_layer_rect = child_rect;
child->SetDrawsContent(false);
child->SetHasRenderSurface(true);
grand_child->SetPosition(grand_child_rect.origin());
grand_child->SetBounds(grand_child_rect.size());
grand_child->draw_properties().visible_layer_rect = grand_child_rect;
grand_child->SetDrawsContent(true);
child->AddChild(grand_child.Pass());
root->AddChild(child.Pass());
my_host_impl->active_tree()->SetRootLayer(root.Pass());
return my_host_impl.Pass();
}
TEST_F(LayerTreeHostImplTest, ContributingLayerEmptyScissorPartialSwap) {
TestSharedBitmapManager shared_bitmap_manager;
TestTaskGraphRunner task_graph_runner;
scoped_ptr<LayerTreeHostImpl> my_host_impl =
SetupLayersForOpacity(true, this, &proxy_, &shared_bitmap_manager,
&task_graph_runner, &stats_instrumentation_);
{
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, my_host_impl->PrepareToDraw(&frame));
// Verify all quads have been computed
ASSERT_EQ(2U, frame.render_passes.size());
ASSERT_EQ(1U, frame.render_passes[0]->quad_list.size());
ASSERT_EQ(1U, frame.render_passes[1]->quad_list.size());
EXPECT_EQ(DrawQuad::SOLID_COLOR,
frame.render_passes[0]->quad_list.front()->material);
EXPECT_EQ(DrawQuad::RENDER_PASS,
frame.render_passes[1]->quad_list.front()->material);
my_host_impl->DrawLayers(&frame);
my_host_impl->DidDrawAllLayers(frame);
}
}
TEST_F(LayerTreeHostImplTest, ContributingLayerEmptyScissorNoPartialSwap) {
TestSharedBitmapManager shared_bitmap_manager;
TestTaskGraphRunner task_graph_runner;
scoped_ptr<LayerTreeHostImpl> my_host_impl =
SetupLayersForOpacity(false, this, &proxy_, &shared_bitmap_manager,
&task_graph_runner, &stats_instrumentation_);
{
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, my_host_impl->PrepareToDraw(&frame));
// Verify all quads have been computed
ASSERT_EQ(2U, frame.render_passes.size());
ASSERT_EQ(1U, frame.render_passes[0]->quad_list.size());
ASSERT_EQ(1U, frame.render_passes[1]->quad_list.size());
EXPECT_EQ(DrawQuad::SOLID_COLOR,
frame.render_passes[0]->quad_list.front()->material);
EXPECT_EQ(DrawQuad::RENDER_PASS,
frame.render_passes[1]->quad_list.front()->material);
my_host_impl->DrawLayers(&frame);
my_host_impl->DidDrawAllLayers(frame);
}
}
TEST_F(LayerTreeHostImplTest, LayersFreeTextures) {
scoped_ptr<TestWebGraphicsContext3D> context =
TestWebGraphicsContext3D::Create();
TestWebGraphicsContext3D* context3d = context.get();
scoped_ptr<OutputSurface> output_surface(
FakeOutputSurface::Create3d(context.Pass()));
CreateHostImpl(DefaultSettings(), output_surface.Pass());
scoped_ptr<LayerImpl> root_layer =
LayerImpl::Create(host_impl_->active_tree(), 1);
root_layer->SetBounds(gfx::Size(10, 10));
root_layer->SetHasRenderSurface(true);
scoped_refptr<VideoFrame> softwareFrame =
media::VideoFrame::CreateColorFrame(
gfx::Size(4, 4), 0x80, 0x80, 0x80, base::TimeDelta());
FakeVideoFrameProvider provider;
provider.set_frame(softwareFrame);
scoped_ptr<VideoLayerImpl> video_layer = VideoLayerImpl::Create(
host_impl_->active_tree(), 4, &provider, media::VIDEO_ROTATION_0);
video_layer->SetBounds(gfx::Size(10, 10));
video_layer->SetDrawsContent(true);
root_layer->AddChild(video_layer.Pass());
scoped_ptr<IOSurfaceLayerImpl> io_surface_layer =
IOSurfaceLayerImpl::Create(host_impl_->active_tree(), 5);
io_surface_layer->SetBounds(gfx::Size(10, 10));
io_surface_layer->SetDrawsContent(true);
io_surface_layer->SetIOSurfaceProperties(1, gfx::Size(10, 10));
root_layer->AddChild(io_surface_layer.Pass());
host_impl_->active_tree()->SetRootLayer(root_layer.Pass());
EXPECT_EQ(0u, context3d->NumTextures());
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
host_impl_->SwapBuffers(frame);
EXPECT_GT(context3d->NumTextures(), 0u);
// Kill the layer tree.
host_impl_->active_tree()->SetRootLayer(
LayerImpl::Create(host_impl_->active_tree(), 100));
// There should be no textures left in use after.
EXPECT_EQ(0u, context3d->NumTextures());
}
class MockDrawQuadsToFillScreenContext : public TestWebGraphicsContext3D {
public:
MOCK_METHOD1(useProgram, void(GLuint program));
MOCK_METHOD4(drawElements, void(GLenum mode,
GLsizei count,
GLenum type,
GLintptr offset));
};
TEST_F(LayerTreeHostImplTest, HasTransparentBackground) {
scoped_ptr<MockDrawQuadsToFillScreenContext> mock_context_owned(
new MockDrawQuadsToFillScreenContext);
MockDrawQuadsToFillScreenContext* mock_context = mock_context_owned.get();
// Run test case
LayerTreeSettings settings = DefaultSettings();
settings.renderer_settings.partial_swap_enabled = false;
CreateHostImpl(settings,
FakeOutputSurface::Create3d(mock_context_owned.Pass()));
SetupRootLayerImpl(LayerImpl::Create(host_impl_->active_tree(), 1));
host_impl_->active_tree()->set_background_color(SK_ColorWHITE);
// Verify one quad is drawn when transparent background set is not set.
host_impl_->active_tree()->set_has_transparent_background(false);
EXPECT_CALL(*mock_context, useProgram(_))
.Times(1);
EXPECT_CALL(*mock_context, drawElements(_, _, _, _))
.Times(1);
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
Mock::VerifyAndClearExpectations(&mock_context);
// Verify no quads are drawn when transparent background is set.
host_impl_->active_tree()->set_has_transparent_background(true);
host_impl_->SetFullRootLayerDamage();
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
Mock::VerifyAndClearExpectations(&mock_context);
}
class LayerTreeHostImplTestWithDelegatingRenderer
: public LayerTreeHostImplTest {
protected:
scoped_ptr<OutputSurface> CreateOutputSurface() override {
return FakeOutputSurface::CreateDelegating3d();
}
void DrawFrameAndTestDamage(const gfx::Rect& expected_damage) {
bool expect_to_draw = !expected_damage.IsEmpty();
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
if (!expect_to_draw) {
// With no damage, we don't draw, and no quads are created.
ASSERT_EQ(0u, frame.render_passes.size());
} else {
ASSERT_EQ(1u, frame.render_passes.size());
// Verify the damage rect for the root render pass.
const RenderPass* root_render_pass = frame.render_passes.back();
EXPECT_EQ(expected_damage, root_render_pass->damage_rect);
// Verify the root and child layers' quads are generated and not being
// culled.
ASSERT_EQ(2u, root_render_pass->quad_list.size());
LayerImpl* child = host_impl_->active_tree()->root_layer()->children()[0];
gfx::Rect expected_child_visible_rect(child->bounds());
EXPECT_EQ(expected_child_visible_rect,
root_render_pass->quad_list.front()->visible_rect);
LayerImpl* root = host_impl_->active_tree()->root_layer();
gfx::Rect expected_root_visible_rect(root->bounds());
EXPECT_EQ(expected_root_visible_rect,
root_render_pass->quad_list.ElementAt(1)->visible_rect);
}
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
EXPECT_EQ(expect_to_draw, host_impl_->SwapBuffers(frame));
}
};
TEST_F(LayerTreeHostImplTestWithDelegatingRenderer, FrameIncludesDamageRect) {
scoped_ptr<SolidColorLayerImpl> root =
SolidColorLayerImpl::Create(host_impl_->active_tree(), 1);
root->SetPosition(gfx::PointF());
root->SetBounds(gfx::Size(10, 10));
root->SetDrawsContent(true);
root->SetHasRenderSurface(true);
// Child layer is in the bottom right corner.
scoped_ptr<SolidColorLayerImpl> child =
SolidColorLayerImpl::Create(host_impl_->active_tree(), 2);
child->SetPosition(gfx::PointF(9.f, 9.f));
child->SetBounds(gfx::Size(1, 1));
child->SetDrawsContent(true);
root->AddChild(child.Pass());
host_impl_->active_tree()->SetRootLayer(root.Pass());
// Draw a frame. In the first frame, the entire viewport should be damaged.
gfx::Rect full_frame_damage(host_impl_->DrawViewportSize());
DrawFrameAndTestDamage(full_frame_damage);
// The second frame has damage that doesn't touch the child layer. Its quads
// should still be generated.
gfx::Rect small_damage = gfx::Rect(0, 0, 1, 1);
host_impl_->active_tree()->root_layer()->SetUpdateRect(small_damage);
DrawFrameAndTestDamage(small_damage);
// The third frame should have no damage, so no quads should be generated.
gfx::Rect no_damage;
DrawFrameAndTestDamage(no_damage);
}
// TODO(reveman): Remove this test and the ability to prevent on demand raster
// when delegating renderer supports PictureDrawQuads. crbug.com/342121
TEST_F(LayerTreeHostImplTestWithDelegatingRenderer, PreventRasterizeOnDemand) {
LayerTreeSettings settings;
CreateHostImpl(settings, CreateOutputSurface());
EXPECT_FALSE(host_impl_->GetRendererCapabilities().allow_rasterize_on_demand);
}
class FakeMaskLayerImpl : public LayerImpl {
public:
static scoped_ptr<FakeMaskLayerImpl> Create(LayerTreeImpl* tree_impl,
int id) {
return make_scoped_ptr(new FakeMaskLayerImpl(tree_impl, id));
}
void GetContentsResourceId(ResourceId* resource_id,
gfx::Size* resource_size) const override {
*resource_id = 0;
}
private:
FakeMaskLayerImpl(LayerTreeImpl* tree_impl, int id)
: LayerImpl(tree_impl, id) {}
};
class GLRendererWithSetupQuadForAntialiasing : public GLRenderer {
public:
using GLRenderer::ShouldAntialiasQuad;
};
TEST_F(LayerTreeHostImplTest, FarAwayQuadsDontNeedAA) {
// Due to precision issues (especially on Android), sometimes far
// away quads can end up thinking they need AA.
float device_scale_factor = 4.f / 3.f;
host_impl_->SetDeviceScaleFactor(device_scale_factor);
gfx::Size root_size(2000, 1000);
gfx::Size device_viewport_size =
gfx::ToCeiledSize(gfx::ScaleSize(root_size, device_scale_factor));
host_impl_->SetViewportSize(device_viewport_size);
host_impl_->CreatePendingTree();
host_impl_->pending_tree()->PushPageScaleFromMainThread(1.f, 1.f / 16.f,
16.f);
scoped_ptr<LayerImpl> scoped_root =
LayerImpl::Create(host_impl_->pending_tree(), 1);
LayerImpl* root = scoped_root.get();
root->SetHasRenderSurface(true);
host_impl_->pending_tree()->SetRootLayer(scoped_root.Pass());
scoped_ptr<LayerImpl> scoped_scrolling_layer =
LayerImpl::Create(host_impl_->pending_tree(), 2);
LayerImpl* scrolling_layer = scoped_scrolling_layer.get();
root->AddChild(scoped_scrolling_layer.Pass());
gfx::Size content_layer_bounds(100000, 100);
gfx::Size pile_tile_size(3000, 3000);
scoped_refptr<FakePicturePileImpl> pile(FakePicturePileImpl::CreateFilledPile(
pile_tile_size, content_layer_bounds));
scoped_ptr<FakePictureLayerImpl> scoped_content_layer =
FakePictureLayerImpl::CreateWithRasterSource(host_impl_->pending_tree(),
3, pile);
LayerImpl* content_layer = scoped_content_layer.get();
scrolling_layer->AddChild(scoped_content_layer.Pass());
content_layer->SetBounds(content_layer_bounds);
content_layer->SetDrawsContent(true);
root->SetBounds(root_size);
gfx::ScrollOffset scroll_offset(100000, 0);
scrolling_layer->SetScrollClipLayer(root->id());
scrolling_layer->PushScrollOffsetFromMainThread(scroll_offset);
host_impl_->ActivateSyncTree();
bool update_lcd_text = false;
host_impl_->active_tree()->UpdateDrawProperties(update_lcd_text);
ASSERT_EQ(1u, host_impl_->active_tree()->RenderSurfaceLayerList().size());
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
ASSERT_EQ(1u, frame.render_passes.size());
ASSERT_LE(1u, frame.render_passes[0]->quad_list.size());
const DrawQuad* quad = frame.render_passes[0]->quad_list.front();
bool clipped = false, force_aa = false;
gfx::QuadF device_layer_quad = MathUtil::MapQuad(
quad->shared_quad_state->quad_to_target_transform,
gfx::QuadF(gfx::RectF(quad->shared_quad_state->visible_quad_layer_rect)),
&clipped);
EXPECT_FALSE(clipped);
bool antialiased =
GLRendererWithSetupQuadForAntialiasing::ShouldAntialiasQuad(
device_layer_quad, clipped, force_aa);
EXPECT_FALSE(antialiased);
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
}
class CompositorFrameMetadataTest : public LayerTreeHostImplTest {
public:
CompositorFrameMetadataTest()
: swap_buffers_complete_(0) {}
void DidSwapBuffersCompleteOnImplThread() override {
swap_buffers_complete_++;
}
int swap_buffers_complete_;
};
TEST_F(CompositorFrameMetadataTest, CompositorFrameAckCountsAsSwapComplete) {
SetupRootLayerImpl(FakeLayerWithQuads::Create(host_impl_->active_tree(), 1));
{
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
}
CompositorFrameAck ack;
host_impl_->ReclaimResources(&ack);
host_impl_->DidSwapBuffersComplete();
EXPECT_EQ(swap_buffers_complete_, 1);
}
class CountingSoftwareDevice : public SoftwareOutputDevice {
public:
CountingSoftwareDevice() : frames_began_(0), frames_ended_(0) {}
SkCanvas* BeginPaint(const gfx::Rect& damage_rect) override {
++frames_began_;
return SoftwareOutputDevice::BeginPaint(damage_rect);
}
void EndPaint() override {
SoftwareOutputDevice::EndPaint();
++frames_ended_;
}
int frames_began_, frames_ended_;
};
TEST_F(LayerTreeHostImplTest, ForcedDrawToSoftwareDeviceBasicRender) {
// No main thread evictions in resourceless software mode.
set_reduce_memory_result(false);
CountingSoftwareDevice* software_device = new CountingSoftwareDevice();
EXPECT_TRUE(CreateHostImpl(
DefaultSettings(),
FakeOutputSurface::CreateSoftware(make_scoped_ptr(software_device))));
host_impl_->SetViewportSize(gfx::Size(50, 50));
SetupScrollAndContentsLayers(gfx::Size(100, 100));
const gfx::Transform external_transform;
const gfx::Rect external_viewport;
const gfx::Rect external_clip;
const bool resourceless_software_draw = true;
host_impl_->SetExternalDrawConstraints(external_transform,
external_viewport,
external_clip,
external_viewport,
external_transform,
resourceless_software_draw);
EXPECT_EQ(0, software_device->frames_began_);
EXPECT_EQ(0, software_device->frames_ended_);
DrawFrame();
EXPECT_EQ(1, software_device->frames_began_);
EXPECT_EQ(1, software_device->frames_ended_);
// Call another API method that is likely to hit nullptr in this mode.
scoped_refptr<base::trace_event::TracedValue> state =
make_scoped_refptr(new base::trace_event::TracedValue());
host_impl_->ActivationStateAsValueInto(state.get());
}
TEST_F(LayerTreeHostImplTest,
ForcedDrawToSoftwareDeviceSkipsUnsupportedLayers) {
set_reduce_memory_result(false);
EXPECT_TRUE(CreateHostImpl(DefaultSettings(),
FakeOutputSurface::CreateSoftware(
make_scoped_ptr(new CountingSoftwareDevice))));
const gfx::Transform external_transform;
const gfx::Rect external_viewport;
const gfx::Rect external_clip;
const bool resourceless_software_draw = true;
host_impl_->SetExternalDrawConstraints(external_transform,
external_viewport,
external_clip,
external_viewport,
external_transform,
resourceless_software_draw);
// SolidColorLayerImpl will be drawn.
scoped_ptr<SolidColorLayerImpl> root_layer =
SolidColorLayerImpl::Create(host_impl_->active_tree(), 1);
// VideoLayerImpl will not be drawn.
FakeVideoFrameProvider provider;
scoped_ptr<VideoLayerImpl> video_layer = VideoLayerImpl::Create(
host_impl_->active_tree(), 2, &provider, media::VIDEO_ROTATION_0);
video_layer->SetBounds(gfx::Size(10, 10));
video_layer->SetDrawsContent(true);
root_layer->AddChild(video_layer.Pass());
SetupRootLayerImpl(root_layer.Pass());
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
EXPECT_EQ(1u, frame.will_draw_layers.size());
EXPECT_EQ(host_impl_->active_tree()->root_layer(), frame.will_draw_layers[0]);
}
// Checks that we have a non-0 default allocation if we pass a context that
// doesn't support memory management extensions.
TEST_F(LayerTreeHostImplTest, DefaultMemoryAllocation) {
LayerTreeSettings settings;
host_impl_ = LayerTreeHostImpl::Create(
settings, this, &proxy_, &stats_instrumentation_, &shared_bitmap_manager_,
&gpu_memory_buffer_manager_, &task_graph_runner_, 0);
scoped_ptr<OutputSurface> output_surface(
FakeOutputSurface::Create3d(TestWebGraphicsContext3D::Create()));
host_impl_->InitializeRenderer(output_surface.Pass());
EXPECT_LT(0ul, host_impl_->memory_allocation_limit_bytes());
}
TEST_F(LayerTreeHostImplTest, RequireHighResWhenVisible) {
ASSERT_TRUE(host_impl_->active_tree());
// RequiresHighResToDraw is set when new output surface is used.
EXPECT_TRUE(host_impl_->RequiresHighResToDraw());
host_impl_->ResetRequiresHighResToDraw();
host_impl_->SetVisible(false);
EXPECT_FALSE(host_impl_->RequiresHighResToDraw());
host_impl_->SetVisible(true);
EXPECT_TRUE(host_impl_->RequiresHighResToDraw());
host_impl_->SetVisible(false);
EXPECT_TRUE(host_impl_->RequiresHighResToDraw());
host_impl_->ResetRequiresHighResToDraw();
EXPECT_FALSE(host_impl_->RequiresHighResToDraw());
host_impl_->SetVisible(true);
EXPECT_TRUE(host_impl_->RequiresHighResToDraw());
}
TEST_F(LayerTreeHostImplTest, RequireHighResAfterGpuRasterizationToggles) {
ASSERT_TRUE(host_impl_->active_tree());
EXPECT_FALSE(host_impl_->use_gpu_rasterization());
// RequiresHighResToDraw is set when new output surface is used.
EXPECT_TRUE(host_impl_->RequiresHighResToDraw());
host_impl_->ResetRequiresHighResToDraw();
host_impl_->SetContentIsSuitableForGpuRasterization(true);
host_impl_->SetHasGpuRasterizationTrigger(false);
host_impl_->UpdateTreeResourcesForGpuRasterizationIfNeeded();
EXPECT_FALSE(host_impl_->RequiresHighResToDraw());
host_impl_->SetHasGpuRasterizationTrigger(true);
host_impl_->UpdateTreeResourcesForGpuRasterizationIfNeeded();
EXPECT_TRUE(host_impl_->RequiresHighResToDraw());
host_impl_->SetHasGpuRasterizationTrigger(false);
host_impl_->UpdateTreeResourcesForGpuRasterizationIfNeeded();
EXPECT_TRUE(host_impl_->RequiresHighResToDraw());
host_impl_->ResetRequiresHighResToDraw();
EXPECT_FALSE(host_impl_->RequiresHighResToDraw());
host_impl_->SetHasGpuRasterizationTrigger(true);
host_impl_->UpdateTreeResourcesForGpuRasterizationIfNeeded();
EXPECT_TRUE(host_impl_->RequiresHighResToDraw());
}
class LayerTreeHostImplTestPrepareTiles : public LayerTreeHostImplTest {
public:
void SetUp() override {
fake_host_impl_ =
new FakeLayerTreeHostImpl(LayerTreeSettings(), &proxy_,
&shared_bitmap_manager_, &task_graph_runner_);
host_impl_.reset(fake_host_impl_);
host_impl_->InitializeRenderer(CreateOutputSurface());
host_impl_->SetViewportSize(gfx::Size(10, 10));
}
FakeLayerTreeHostImpl* fake_host_impl_;
};
TEST_F(LayerTreeHostImplTestPrepareTiles, PrepareTilesWhenInvisible) {
fake_host_impl_->DidModifyTilePriorities();
EXPECT_TRUE(fake_host_impl_->prepare_tiles_needed());
fake_host_impl_->SetVisible(false);
EXPECT_FALSE(fake_host_impl_->prepare_tiles_needed());
}
TEST_F(LayerTreeHostImplTest, UIResourceManagement) {
scoped_ptr<TestWebGraphicsContext3D> context =
TestWebGraphicsContext3D::Create();
TestWebGraphicsContext3D* context3d = context.get();
scoped_ptr<FakeOutputSurface> output_surface = FakeOutputSurface::Create3d();
CreateHostImpl(DefaultSettings(), output_surface.Pass());
EXPECT_EQ(0u, context3d->NumTextures());
UIResourceId ui_resource_id = 1;
bool is_opaque = false;
UIResourceBitmap bitmap(gfx::Size(1, 1), is_opaque);
host_impl_->CreateUIResource(ui_resource_id, bitmap);
EXPECT_EQ(1u, context3d->NumTextures());
ResourceId id1 = host_impl_->ResourceIdForUIResource(ui_resource_id);
EXPECT_NE(0u, id1);
// Multiple requests with the same id is allowed. The previous texture is
// deleted.
host_impl_->CreateUIResource(ui_resource_id, bitmap);
EXPECT_EQ(1u, context3d->NumTextures());
ResourceId id2 = host_impl_->ResourceIdForUIResource(ui_resource_id);
EXPECT_NE(0u, id2);
EXPECT_NE(id1, id2);
// Deleting invalid UIResourceId is allowed and does not change state.
host_impl_->DeleteUIResource(-1);
EXPECT_EQ(1u, context3d->NumTextures());
// Should return zero for invalid UIResourceId. Number of textures should
// not change.
EXPECT_EQ(0u, host_impl_->ResourceIdForUIResource(-1));
EXPECT_EQ(1u, context3d->NumTextures());
host_impl_->DeleteUIResource(ui_resource_id);
EXPECT_EQ(0u, host_impl_->ResourceIdForUIResource(ui_resource_id));
EXPECT_EQ(0u, context3d->NumTextures());
// Should not change state for multiple deletion on one UIResourceId
host_impl_->DeleteUIResource(ui_resource_id);
EXPECT_EQ(0u, context3d->NumTextures());
}
TEST_F(LayerTreeHostImplTest, CreateETC1UIResource) {
scoped_ptr<TestWebGraphicsContext3D> context =
TestWebGraphicsContext3D::Create();
TestWebGraphicsContext3D* context3d = context.get();
CreateHostImpl(DefaultSettings(), FakeOutputSurface::Create3d());
EXPECT_EQ(0u, context3d->NumTextures());
gfx::Size size(4, 4);
// SkImageInfo has no support for ETC1. The |info| below contains the right
// total pixel size for the bitmap but not the right height and width. The
// correct width/height are passed directly to UIResourceBitmap.
SkImageInfo info =
SkImageInfo::Make(4, 2, kAlpha_8_SkColorType, kPremul_SkAlphaType);
skia::RefPtr<SkPixelRef> pixel_ref =
skia::AdoptRef(SkMallocPixelRef::NewAllocate(info, 0, 0));
pixel_ref->setImmutable();
UIResourceBitmap bitmap(pixel_ref, size);
UIResourceId ui_resource_id = 1;
host_impl_->CreateUIResource(ui_resource_id, bitmap);
EXPECT_EQ(1u, context3d->NumTextures());
ResourceId id1 = host_impl_->ResourceIdForUIResource(ui_resource_id);
EXPECT_NE(0u, id1);
}
void ShutdownReleasesContext_Callback(scoped_ptr<CopyOutputResult> result) {
}
TEST_F(LayerTreeHostImplTest, ShutdownReleasesContext) {
scoped_refptr<TestContextProvider> context_provider =
TestContextProvider::Create();
CreateHostImpl(DefaultSettings(),
FakeOutputSurface::Create3d(context_provider));
SetupRootLayerImpl(LayerImpl::Create(host_impl_->active_tree(), 1));
ScopedPtrVector<CopyOutputRequest> requests;
requests.push_back(CopyOutputRequest::CreateRequest(
base::Bind(&ShutdownReleasesContext_Callback)));
host_impl_->active_tree()->root_layer()->PassCopyRequests(&requests);
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
// The CopyOutputResult's callback has a ref on the ContextProvider and a
// texture in a texture mailbox.
EXPECT_FALSE(context_provider->HasOneRef());
EXPECT_EQ(1u, context_provider->TestContext3d()->NumTextures());
host_impl_ = nullptr;
// The CopyOutputResult's callback was cancelled, the CopyOutputResult
// released, and the texture deleted.
EXPECT_TRUE(context_provider->HasOneRef());
EXPECT_EQ(0u, context_provider->TestContext3d()->NumTextures());
}
TEST_F(LayerTreeHostImplTest, TouchFlingShouldNotBubble) {
// When flinging via touch, only the child should scroll (we should not
// bubble).
gfx::Size surface_size(10, 10);
gfx::Size content_size(20, 20);
scoped_ptr<LayerImpl> root_clip =
LayerImpl::Create(host_impl_->active_tree(), 3);
root_clip->SetHasRenderSurface(true);
scoped_ptr<LayerImpl> root =
CreateScrollableLayer(1, content_size, root_clip.get());
root->SetIsContainerForFixedPositionLayers(true);
scoped_ptr<LayerImpl> child =
CreateScrollableLayer(2, content_size, root_clip.get());
root->AddChild(child.Pass());
int root_id = root->id();
root_clip->AddChild(root.Pass());
host_impl_->SetViewportSize(surface_size);
host_impl_->active_tree()->SetRootLayer(root_clip.Pass());
host_impl_->active_tree()->SetViewportLayersFromIds(Layer::INVALID_ID, 3, 1,
Layer::INVALID_ID);
host_impl_->active_tree()->DidBecomeActive();
DrawFrame();
{
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
EXPECT_EQ(InputHandler::SCROLL_STARTED, host_impl_->FlingScrollBegin());
gfx::Vector2d scroll_delta(0, 100);
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
host_impl_->ScrollEnd();
scoped_ptr<ScrollAndScaleSet> scroll_info =
host_impl_->ProcessScrollDeltas();
// Only the child should have scrolled.
ASSERT_EQ(1u, scroll_info->scrolls.size());
ExpectNone(*scroll_info.get(), root_id);
}
}
TEST_F(LayerTreeHostImplTest, TouchFlingShouldLockToFirstScrolledLayer) {
// Scroll a child layer beyond its maximum scroll range and make sure the
// the scroll doesn't bubble up to the parent layer.
gfx::Size surface_size(10, 10);
scoped_ptr<LayerImpl> root = LayerImpl::Create(host_impl_->active_tree(), 1);
root->SetHasRenderSurface(true);
scoped_ptr<LayerImpl> root_scrolling =
CreateScrollableLayer(2, surface_size, root.get());
scoped_ptr<LayerImpl> grand_child =
CreateScrollableLayer(4, surface_size, root.get());
grand_child->PushScrollOffsetFromMainThread(gfx::ScrollOffset(0, 2));
scoped_ptr<LayerImpl> child =
CreateScrollableLayer(3, surface_size, root.get());
child->PushScrollOffsetFromMainThread(gfx::ScrollOffset(0, 4));
child->AddChild(grand_child.Pass());
root_scrolling->AddChild(child.Pass());
root->AddChild(root_scrolling.Pass());
host_impl_->active_tree()->SetRootLayer(root.Pass());
host_impl_->active_tree()->DidBecomeActive();
host_impl_->SetViewportSize(surface_size);
DrawFrame();
{
scoped_ptr<ScrollAndScaleSet> scroll_info;
LayerImpl* child =
host_impl_->active_tree()->root_layer()->children()[0]->children()[0];
LayerImpl* grand_child = child->children()[0];
gfx::Vector2d scroll_delta(0, -2);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
EXPECT_TRUE(host_impl_->ScrollBy(gfx::Point(), scroll_delta).did_scroll);
// The grand child should have scrolled up to its limit.
scroll_info = host_impl_->ProcessScrollDeltas();
ASSERT_EQ(1u, scroll_info->scrolls.size());
EXPECT_TRUE(
ScrollInfoContains(*scroll_info, grand_child->id(), scroll_delta));
EXPECT_EQ(host_impl_->CurrentlyScrollingLayer(), grand_child);
// The child should have received the bubbled delta, but the locked
// scrolling layer should remain set as the grand child.
EXPECT_TRUE(host_impl_->ScrollBy(gfx::Point(), scroll_delta).did_scroll);
scroll_info = host_impl_->ProcessScrollDeltas();
ASSERT_EQ(2u, scroll_info->scrolls.size());
EXPECT_TRUE(
ScrollInfoContains(*scroll_info, grand_child->id(), scroll_delta));
EXPECT_TRUE(ScrollInfoContains(*scroll_info, child->id(), scroll_delta));
EXPECT_EQ(host_impl_->CurrentlyScrollingLayer(), grand_child);
// The first |ScrollBy| after the fling should re-lock the scrolling
// layer to the first layer that scrolled, which is the child.
EXPECT_EQ(InputHandler::SCROLL_STARTED, host_impl_->FlingScrollBegin());
EXPECT_TRUE(host_impl_->ScrollBy(gfx::Point(), scroll_delta).did_scroll);
EXPECT_EQ(host_impl_->CurrentlyScrollingLayer(), child);
// The child should have scrolled up to its limit.
scroll_info = host_impl_->ProcessScrollDeltas();
ASSERT_EQ(2u, scroll_info->scrolls.size());
EXPECT_TRUE(
ScrollInfoContains(*scroll_info, grand_child->id(), scroll_delta));
EXPECT_TRUE(ScrollInfoContains(*scroll_info, child->id(),
scroll_delta + scroll_delta));
// As the locked layer is at it's limit, no further scrolling can occur.
EXPECT_FALSE(host_impl_->ScrollBy(gfx::Point(), scroll_delta).did_scroll);
EXPECT_EQ(host_impl_->CurrentlyScrollingLayer(), child);
host_impl_->ScrollEnd();
}
}
TEST_F(LayerTreeHostImplTest, WheelFlingShouldBubble) {
// When flinging via wheel, the root should eventually scroll (we should
// bubble).
gfx::Size surface_size(10, 10);
gfx::Size content_size(20, 20);
scoped_ptr<LayerImpl> root_clip =
LayerImpl::Create(host_impl_->active_tree(), 3);
root_clip->SetHasRenderSurface(true);
scoped_ptr<LayerImpl> root_scroll =
CreateScrollableLayer(1, content_size, root_clip.get());
int root_scroll_id = root_scroll->id();
scoped_ptr<LayerImpl> child =
CreateScrollableLayer(2, content_size, root_clip.get());
root_scroll->AddChild(child.Pass());
root_clip->AddChild(root_scroll.Pass());
host_impl_->SetViewportSize(surface_size);
host_impl_->active_tree()->SetRootLayer(root_clip.Pass());
host_impl_->active_tree()->DidBecomeActive();
DrawFrame();
{
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
EXPECT_EQ(InputHandler::SCROLL_STARTED, host_impl_->FlingScrollBegin());
gfx::Vector2d scroll_delta(0, 100);
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
host_impl_->ScrollEnd();
scoped_ptr<ScrollAndScaleSet> scroll_info =
host_impl_->ProcessScrollDeltas();
// The root should have scrolled.
ASSERT_EQ(2u, scroll_info->scrolls.size());
EXPECT_TRUE(ScrollInfoContains(*scroll_info.get(), root_scroll_id,
gfx::Vector2d(0, 10)));
}
}
TEST_F(LayerTreeHostImplTest, ScrollUnknownNotOnAncestorChain) {
// If we ray cast a scroller that is not on the first layer's ancestor chain,
// we should return SCROLL_UNKNOWN.
gfx::Size content_size(100, 100);
SetupScrollAndContentsLayers(content_size);
int scroll_layer_id = 2;
LayerImpl* scroll_layer =
host_impl_->active_tree()->LayerById(scroll_layer_id);
scroll_layer->SetDrawsContent(true);
int page_scale_layer_id = 5;
LayerImpl* page_scale_layer =
host_impl_->active_tree()->LayerById(page_scale_layer_id);
int occluder_layer_id = 6;
scoped_ptr<LayerImpl> occluder_layer =
LayerImpl::Create(host_impl_->active_tree(), occluder_layer_id);
occluder_layer->SetDrawsContent(true);
occluder_layer->SetBounds(content_size);
occluder_layer->SetPosition(gfx::PointF());
// The parent of the occluder is *above* the scroller.
page_scale_layer->AddChild(occluder_layer.Pass());
DrawFrame();
EXPECT_EQ(InputHandler::SCROLL_UNKNOWN,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
}
TEST_F(LayerTreeHostImplTest, ScrollUnknownScrollAncestorMismatch) {
// If we ray cast a scroller this is on the first layer's ancestor chain, but
// is not the first scroller we encounter when walking up from the layer, we
// should also return SCROLL_UNKNOWN.
gfx::Size content_size(100, 100);
SetupScrollAndContentsLayers(content_size);
int scroll_layer_id = 2;
LayerImpl* scroll_layer =
host_impl_->active_tree()->LayerById(scroll_layer_id);
scroll_layer->SetDrawsContent(true);
int occluder_layer_id = 6;
scoped_ptr<LayerImpl> occluder_layer =
LayerImpl::Create(host_impl_->active_tree(), occluder_layer_id);
occluder_layer->SetDrawsContent(true);
occluder_layer->SetBounds(content_size);
occluder_layer->SetPosition(gfx::PointF(-10.f, -10.f));
int child_scroll_clip_layer_id = 7;
scoped_ptr<LayerImpl> child_scroll_clip =
LayerImpl::Create(host_impl_->active_tree(), child_scroll_clip_layer_id);
int child_scroll_layer_id = 8;
scoped_ptr<LayerImpl> child_scroll = CreateScrollableLayer(
child_scroll_layer_id, content_size, child_scroll_clip.get());
child_scroll->SetPosition(gfx::PointF(10.f, 10.f));
child_scroll->AddChild(occluder_layer.Pass());
scroll_layer->AddChild(child_scroll.Pass());
DrawFrame();
EXPECT_EQ(InputHandler::SCROLL_UNKNOWN,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
}
TEST_F(LayerTreeHostImplTest, NotScrollInvisibleScroller) {
gfx::Size content_size(100, 100);
SetupScrollAndContentsLayers(content_size);
LayerImpl* root = host_impl_->active_tree()->LayerById(1);
int scroll_layer_id = 2;
LayerImpl* scroll_layer =
host_impl_->active_tree()->LayerById(scroll_layer_id);
int child_scroll_layer_id = 7;
scoped_ptr<LayerImpl> child_scroll =
CreateScrollableLayer(child_scroll_layer_id, content_size, root);
child_scroll->SetDrawsContent(false);
scroll_layer->AddChild(child_scroll.Pass());
DrawFrame();
// We should not have scrolled |child_scroll| even though we technically "hit"
// it. The reason for this is that if the scrolling the scroll would not move
// any layer that is a drawn RSLL member, then we can ignore the hit.
//
// Why SCROLL_STARTED? In this case, it's because we've bubbled out and
// started scrolling the inner viewport.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
EXPECT_EQ(2, host_impl_->CurrentlyScrollingLayer()->id());
}
TEST_F(LayerTreeHostImplTest, ScrollInvisibleScrollerWithVisibleDescendent) {
gfx::Size content_size(100, 100);
SetupScrollAndContentsLayers(content_size);
LayerImpl* root = host_impl_->active_tree()->LayerById(1);
LayerImpl* root_scroll_layer = host_impl_->active_tree()->LayerById(2);
scoped_ptr<LayerImpl> invisible_scroll_layer =
CreateScrollableLayer(7, content_size, root);
invisible_scroll_layer->SetDrawsContent(false);
scoped_ptr<LayerImpl> child_layer =
LayerImpl::Create(host_impl_->active_tree(), 8);
child_layer->SetDrawsContent(false);
scoped_ptr<LayerImpl> grand_child_layer =
LayerImpl::Create(host_impl_->active_tree(), 9);
grand_child_layer->SetDrawsContent(true);
grand_child_layer->SetBounds(content_size);
// Move the grand child so it's not hit by our test point.
grand_child_layer->SetPosition(gfx::PointF(10.f, 10.f));
child_layer->AddChild(grand_child_layer.Pass());
invisible_scroll_layer->AddChild(child_layer.Pass());
root_scroll_layer->AddChild(invisible_scroll_layer.Pass());
DrawFrame();
// We should have scrolled |invisible_scroll_layer| as it was hit and it has
// a descendant which is a drawn RSLL member.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
EXPECT_EQ(7, host_impl_->CurrentlyScrollingLayer()->id());
}
TEST_F(LayerTreeHostImplTest, ScrollInvisibleScrollerWithVisibleScrollChild) {
// This test case is very similar to the one above with one key difference:
// the invisible scroller has a scroll child that is indeed draw contents.
// If we attempt to initiate a gesture scroll off of the visible scroll child
// we should still start the scroll child.
gfx::Size content_size(100, 100);
SetupScrollAndContentsLayers(content_size);
LayerImpl* root = host_impl_->active_tree()->LayerById(1);
int scroll_layer_id = 2;
LayerImpl* scroll_layer =
host_impl_->active_tree()->LayerById(scroll_layer_id);
int scroll_child_id = 6;
scoped_ptr<LayerImpl> scroll_child =
LayerImpl::Create(host_impl_->active_tree(), scroll_child_id);
scroll_child->SetDrawsContent(true);
scroll_child->SetBounds(content_size);
// Move the scroll child so it's not hit by our test point.
scroll_child->SetPosition(gfx::PointF(10.f, 10.f));
int invisible_scroll_layer_id = 7;
scoped_ptr<LayerImpl> invisible_scroll =
CreateScrollableLayer(invisible_scroll_layer_id, content_size, root);
invisible_scroll->SetDrawsContent(false);
int container_id = 8;
scoped_ptr<LayerImpl> container =
LayerImpl::Create(host_impl_->active_tree(), container_id);
scoped_ptr<std::set<LayerImpl*>> scroll_children(new std::set<LayerImpl*>);
scroll_children->insert(scroll_child.get());
invisible_scroll->SetScrollChildren(scroll_children.release());
scroll_child->SetScrollParent(invisible_scroll.get());
container->AddChild(invisible_scroll.Pass());
container->AddChild(scroll_child.Pass());
scroll_layer->AddChild(container.Pass());
DrawFrame();
// We should have scrolled |child_scroll| even though it is invisible.
// The reason for this is that if the scrolling the scroll would move a layer
// that is a drawn RSLL member, then we should accept this hit.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
EXPECT_EQ(7, host_impl_->CurrentlyScrollingLayer()->id());
}
// Make sure LatencyInfo carried by LatencyInfoSwapPromise are passed
// to CompositorFrameMetadata after SwapBuffers();
TEST_F(LayerTreeHostImplTest, LatencyInfoPassedToCompositorFrameMetadata) {
scoped_ptr<SolidColorLayerImpl> root =
SolidColorLayerImpl::Create(host_impl_->active_tree(), 1);
root->SetPosition(gfx::PointF());
root->SetBounds(gfx::Size(10, 10));
root->SetDrawsContent(true);
root->SetHasRenderSurface(true);
host_impl_->active_tree()->SetRootLayer(root.Pass());
FakeOutputSurface* fake_output_surface =
static_cast<FakeOutputSurface*>(host_impl_->output_surface());
const std::vector<ui::LatencyInfo>& metadata_latency_before =
fake_output_surface->last_sent_frame().metadata.latency_info;
EXPECT_TRUE(metadata_latency_before.empty());
ui::LatencyInfo latency_info;
latency_info.AddLatencyNumber(
ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT, 0, 0);
scoped_ptr<SwapPromise> swap_promise(
new LatencyInfoSwapPromise(latency_info));
host_impl_->active_tree()->QueuePinnedSwapPromise(swap_promise.Pass());
host_impl_->SetNeedsRedraw();
gfx::Rect full_frame_damage(host_impl_->DrawViewportSize());
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
EXPECT_TRUE(host_impl_->SwapBuffers(frame));
const std::vector<ui::LatencyInfo>& metadata_latency_after =
fake_output_surface->last_sent_frame().metadata.latency_info;
EXPECT_EQ(1u, metadata_latency_after.size());
EXPECT_TRUE(metadata_latency_after[0].FindLatency(
ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT, 0, NULL));
}
TEST_F(LayerTreeHostImplTest, SelectionBoundsPassedToCompositorFrameMetadata) {
int root_layer_id = 1;
scoped_ptr<SolidColorLayerImpl> root =
SolidColorLayerImpl::Create(host_impl_->active_tree(), root_layer_id);
root->SetPosition(gfx::PointF());
root->SetBounds(gfx::Size(10, 10));
root->SetDrawsContent(true);
root->SetHasRenderSurface(true);
host_impl_->active_tree()->SetRootLayer(root.Pass());
// Ensure the default frame selection bounds are empty.
FakeOutputSurface* fake_output_surface =
static_cast<FakeOutputSurface*>(host_impl_->output_surface());
const ViewportSelection& selection_before =
fake_output_surface->last_sent_frame().metadata.selection;
EXPECT_EQ(ViewportSelectionBound(), selection_before.start);
EXPECT_EQ(ViewportSelectionBound(), selection_before.end);
// Plumb the layer-local selection bounds.
gfx::PointF selection_top(5, 0);
gfx::PointF selection_bottom(5, 5);
LayerSelection selection;
selection.start.type = SELECTION_BOUND_CENTER;
selection.start.layer_id = root_layer_id;
selection.start.edge_bottom = selection_bottom;
selection.start.edge_top = selection_top;
selection.end = selection.start;
host_impl_->active_tree()->RegisterSelection(selection);
// Trigger a draw-swap sequence.
host_impl_->SetNeedsRedraw();
gfx::Rect full_frame_damage(host_impl_->DrawViewportSize());
LayerTreeHostImpl::FrameData frame;
EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
host_impl_->DrawLayers(&frame);
host_impl_->DidDrawAllLayers(frame);
EXPECT_TRUE(host_impl_->SwapBuffers(frame));
// Ensure the selection bounds have propagated to the frame metadata.
const ViewportSelection& selection_after =
fake_output_surface->last_sent_frame().metadata.selection;
EXPECT_EQ(selection.start.type, selection_after.start.type);
EXPECT_EQ(selection.end.type, selection_after.end.type);
EXPECT_EQ(selection_bottom, selection_after.start.edge_bottom);
EXPECT_EQ(selection_top, selection_after.start.edge_top);
EXPECT_TRUE(selection_after.start.visible);
EXPECT_TRUE(selection_after.start.visible);
}
class SimpleSwapPromiseMonitor : public SwapPromiseMonitor {
public:
SimpleSwapPromiseMonitor(LayerTreeHost* layer_tree_host,
LayerTreeHostImpl* layer_tree_host_impl,
int* set_needs_commit_count,
int* set_needs_redraw_count,
int* forward_to_main_count)
: SwapPromiseMonitor(layer_tree_host, layer_tree_host_impl),
set_needs_commit_count_(set_needs_commit_count),
set_needs_redraw_count_(set_needs_redraw_count),
forward_to_main_count_(forward_to_main_count) {}
~SimpleSwapPromiseMonitor() override {}
void OnSetNeedsCommitOnMain() override { (*set_needs_commit_count_)++; }
void OnSetNeedsRedrawOnImpl() override { (*set_needs_redraw_count_)++; }
void OnForwardScrollUpdateToMainThreadOnImpl() override {
(*forward_to_main_count_)++;
}
private:
int* set_needs_commit_count_;
int* set_needs_redraw_count_;
int* forward_to_main_count_;
};
TEST_F(LayerTreeHostImplTest, SimpleSwapPromiseMonitor) {
int set_needs_commit_count = 0;
int set_needs_redraw_count = 0;
int forward_to_main_count = 0;
{
scoped_ptr<SimpleSwapPromiseMonitor> swap_promise_monitor(
new SimpleSwapPromiseMonitor(NULL,
host_impl_.get(),
&set_needs_commit_count,
&set_needs_redraw_count,
&forward_to_main_count));
host_impl_->SetNeedsRedraw();
EXPECT_EQ(0, set_needs_commit_count);
EXPECT_EQ(1, set_needs_redraw_count);
EXPECT_EQ(0, forward_to_main_count);
}
// Now the monitor is destroyed, SetNeedsRedraw() is no longer being
// monitored.
host_impl_->SetNeedsRedraw();
EXPECT_EQ(0, set_needs_commit_count);
EXPECT_EQ(1, set_needs_redraw_count);
EXPECT_EQ(0, forward_to_main_count);
{
scoped_ptr<SimpleSwapPromiseMonitor> swap_promise_monitor(
new SimpleSwapPromiseMonitor(NULL,
host_impl_.get(),
&set_needs_commit_count,
&set_needs_redraw_count,
&forward_to_main_count));
host_impl_->SetNeedsRedrawRect(gfx::Rect(10, 10));
EXPECT_EQ(0, set_needs_commit_count);
EXPECT_EQ(2, set_needs_redraw_count);
EXPECT_EQ(0, forward_to_main_count);
}
{
scoped_ptr<SimpleSwapPromiseMonitor> swap_promise_monitor(
new SimpleSwapPromiseMonitor(NULL,
host_impl_.get(),
&set_needs_commit_count,
&set_needs_redraw_count,
&forward_to_main_count));
// Empty damage rect won't signal the monitor.
host_impl_->SetNeedsRedrawRect(gfx::Rect());
EXPECT_EQ(0, set_needs_commit_count);
EXPECT_EQ(2, set_needs_redraw_count);
EXPECT_EQ(0, forward_to_main_count);
}
{
set_needs_commit_count = 0;
set_needs_redraw_count = 0;
forward_to_main_count = 0;
scoped_ptr<SimpleSwapPromiseMonitor> swap_promise_monitor(
new SimpleSwapPromiseMonitor(NULL,
host_impl_.get(),
&set_needs_commit_count,
&set_needs_redraw_count,
&forward_to_main_count));
LayerImpl* scroll_layer = SetupScrollAndContentsLayers(gfx::Size(100, 100));
// Scrolling normally should not trigger any forwarding.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
EXPECT_TRUE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, 10)).did_scroll);
host_impl_->ScrollEnd();
EXPECT_EQ(0, set_needs_commit_count);
EXPECT_EQ(1, set_needs_redraw_count);
EXPECT_EQ(0, forward_to_main_count);
// Scrolling with a scroll handler should defer the swap to the main
// thread.
scroll_layer->SetHaveScrollEventHandlers(true);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
EXPECT_TRUE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, 10)).did_scroll);
host_impl_->ScrollEnd();
EXPECT_EQ(0, set_needs_commit_count);
EXPECT_EQ(2, set_needs_redraw_count);
EXPECT_EQ(1, forward_to_main_count);
}
}
class LayerTreeHostImplWithTopControlsTest : public LayerTreeHostImplTest {
public:
void SetUp() override {
LayerTreeSettings settings = DefaultSettings();
CreateHostImpl(settings, CreateOutputSurface());
host_impl_->active_tree()->set_top_controls_height(top_controls_height_);
host_impl_->sync_tree()->set_top_controls_height(top_controls_height_);
host_impl_->active_tree()->SetCurrentTopControlsShownRatio(1.f);
}
protected:
static const int top_controls_height_;
};
const int LayerTreeHostImplWithTopControlsTest::top_controls_height_ = 50;
TEST_F(LayerTreeHostImplWithTopControlsTest, NoIdleAnimations) {
SetupScrollAndContentsLayers(gfx::Size(100, 100))
->PushScrollOffsetFromMainThread(gfx::ScrollOffset(0, 10));
BeginFrameArgs begin_frame_args =
CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE);
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
EXPECT_FALSE(did_request_redraw_);
host_impl_->DidFinishImplFrame();
}
TEST_F(LayerTreeHostImplWithTopControlsTest, TopControlsHeightIsCommitted) {
SetupScrollAndContentsLayers(gfx::Size(100, 100));
EXPECT_FALSE(did_request_redraw_);
host_impl_->CreatePendingTree();
host_impl_->sync_tree()->set_top_controls_height(100);
host_impl_->ActivateSyncTree();
EXPECT_EQ(100, host_impl_->top_controls_manager()->TopControlsHeight());
}
TEST_F(LayerTreeHostImplWithTopControlsTest,
TopControlsStayFullyVisibleOnHeightChange) {
SetupScrollAndContentsLayers(gfx::Size(100, 100));
EXPECT_EQ(0.f, host_impl_->top_controls_manager()->ControlsTopOffset());
host_impl_->CreatePendingTree();
host_impl_->sync_tree()->set_top_controls_height(0);
host_impl_->ActivateSyncTree();
EXPECT_EQ(0.f, host_impl_->top_controls_manager()->ControlsTopOffset());
host_impl_->CreatePendingTree();
host_impl_->sync_tree()->set_top_controls_height(50);
host_impl_->ActivateSyncTree();
EXPECT_EQ(0.f, host_impl_->top_controls_manager()->ControlsTopOffset());
}
TEST_F(LayerTreeHostImplWithTopControlsTest, TopControlsAnimationScheduling) {
SetupScrollAndContentsLayers(gfx::Size(100, 100))
->PushScrollOffsetFromMainThread(gfx::ScrollOffset(0, 10));
host_impl_->DidChangeTopControlsPosition();
EXPECT_TRUE(did_request_animate_);
EXPECT_TRUE(did_request_redraw_);
}
TEST_F(LayerTreeHostImplWithTopControlsTest, ScrollHandledByTopControls) {
InputHandlerScrollResult result;
LayerImpl* scroll_layer = SetupScrollAndContentsLayers(gfx::Size(100, 200));
host_impl_->SetViewportSize(gfx::Size(100, 100));
host_impl_->top_controls_manager()->UpdateTopControlsState(
BOTH, SHOWN, false);
DrawFrame();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
EXPECT_EQ(0, host_impl_->top_controls_manager()->ControlsTopOffset());
EXPECT_EQ(gfx::Vector2dF().ToString(),
scroll_layer->CurrentScrollOffset().ToString());
// Scroll just the top controls and verify that the scroll succeeds.
const float residue = 10;
float offset = top_controls_height_ - residue;
result = host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, offset));
EXPECT_EQ(result.unused_scroll_delta, gfx::Vector2d(0, 0));
EXPECT_TRUE(result.did_scroll);
EXPECT_FLOAT_EQ(-offset,
host_impl_->top_controls_manager()->ControlsTopOffset());
EXPECT_EQ(gfx::Vector2dF().ToString(),
scroll_layer->CurrentScrollOffset().ToString());
// Scroll across the boundary
const float content_scroll = 20;
offset = residue + content_scroll;
result = host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, offset));
EXPECT_TRUE(result.did_scroll);
EXPECT_EQ(result.unused_scroll_delta, gfx::Vector2d(0, 0));
EXPECT_EQ(-top_controls_height_,
host_impl_->top_controls_manager()->ControlsTopOffset());
EXPECT_EQ(gfx::Vector2dF(0, content_scroll).ToString(),
scroll_layer->CurrentScrollOffset().ToString());
// Now scroll back to the top of the content
offset = -content_scroll;
result = host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, offset));
EXPECT_TRUE(result.did_scroll);
EXPECT_EQ(result.unused_scroll_delta, gfx::Vector2d(0, 0));
EXPECT_EQ(-top_controls_height_,
host_impl_->top_controls_manager()->ControlsTopOffset());
EXPECT_EQ(gfx::Vector2dF().ToString(),
scroll_layer->CurrentScrollOffset().ToString());
// And scroll the top controls completely into view
offset = -top_controls_height_;
result = host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, offset));
EXPECT_TRUE(result.did_scroll);
EXPECT_EQ(result.unused_scroll_delta, gfx::Vector2d(0, 0));
EXPECT_EQ(0, host_impl_->top_controls_manager()->ControlsTopOffset());
EXPECT_EQ(gfx::Vector2dF().ToString(),
scroll_layer->CurrentScrollOffset().ToString());
// And attempt to scroll past the end
result = host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, offset));
EXPECT_FALSE(result.did_scroll);
EXPECT_EQ(result.unused_scroll_delta, gfx::Vector2d(0, -50));
EXPECT_EQ(0, host_impl_->top_controls_manager()->ControlsTopOffset());
EXPECT_EQ(gfx::Vector2dF().ToString(),
scroll_layer->CurrentScrollOffset().ToString());
host_impl_->ScrollEnd();
}
TEST_F(LayerTreeHostImplWithTopControlsTest, WheelUnhandledByTopControls) {
SetupScrollAndContentsLayers(gfx::Size(100, 200));
host_impl_->SetViewportSize(gfx::Size(50, 100));
host_impl_->active_tree()->set_top_controls_shrink_blink_size(true);
host_impl_->top_controls_manager()->UpdateTopControlsState(BOTH, SHOWN,
false);
DrawFrame();
LayerImpl* viewport_layer = host_impl_->InnerViewportScrollLayer();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
EXPECT_EQ(0, host_impl_->top_controls_manager()->ControlsTopOffset());
EXPECT_VECTOR_EQ(gfx::Vector2dF(), viewport_layer->CurrentScrollOffset());
// Wheel scrolls should not affect the top controls, and should pass
// directly through to the viewport.
const float delta = top_controls_height_;
EXPECT_TRUE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, delta)).did_scroll);
EXPECT_FLOAT_EQ(0, host_impl_->top_controls_manager()->ControlsTopOffset());
EXPECT_VECTOR_EQ(gfx::Vector2dF(0, delta),
viewport_layer->CurrentScrollOffset());
EXPECT_TRUE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, delta)).did_scroll);
EXPECT_FLOAT_EQ(0, host_impl_->top_controls_manager()->ControlsTopOffset());
EXPECT_VECTOR_EQ(gfx::Vector2dF(0, delta * 2),
viewport_layer->CurrentScrollOffset());
}
TEST_F(LayerTreeHostImplWithTopControlsTest, TopControlsAnimationAtOrigin) {
LayerImpl* scroll_layer = SetupScrollAndContentsLayers(gfx::Size(100, 200));
host_impl_->SetViewportSize(gfx::Size(100, 200));
host_impl_->top_controls_manager()->UpdateTopControlsState(
BOTH, SHOWN, false);
DrawFrame();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
EXPECT_EQ(0, host_impl_->top_controls_manager()->ControlsTopOffset());
EXPECT_EQ(gfx::Vector2dF().ToString(),
scroll_layer->CurrentScrollOffset().ToString());
// Scroll the top controls partially.
const float residue = 35;
float offset = top_controls_height_ - residue;
EXPECT_TRUE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, offset)).did_scroll);
EXPECT_FLOAT_EQ(-offset,
host_impl_->top_controls_manager()->ControlsTopOffset());
EXPECT_EQ(gfx::Vector2dF().ToString(),
scroll_layer->CurrentScrollOffset().ToString());
did_request_redraw_ = false;
did_request_animate_ = false;
did_request_commit_ = false;
// End the scroll while the controls are still offset from their limit.
host_impl_->ScrollEnd();
ASSERT_TRUE(host_impl_->top_controls_manager()->animation());
EXPECT_TRUE(did_request_animate_);
EXPECT_TRUE(did_request_redraw_);
EXPECT_FALSE(did_request_commit_);
// The top controls should properly animate until finished, despite the scroll
// offset being at the origin.
BeginFrameArgs begin_frame_args = CreateBeginFrameArgsForTesting(
BEGINFRAME_FROM_HERE, base::TimeTicks::Now());
while (did_request_animate_) {
did_request_redraw_ = false;
did_request_animate_ = false;
did_request_commit_ = false;
float old_offset =
host_impl_->top_controls_manager()->ControlsTopOffset();
begin_frame_args.frame_time += base::TimeDelta::FromMilliseconds(5);
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
EXPECT_EQ(gfx::Vector2dF().ToString(),
scroll_layer->CurrentScrollOffset().ToString());
float new_offset =
host_impl_->top_controls_manager()->ControlsTopOffset();
// No commit is needed as the controls are animating the content offset,
// not the scroll offset.
EXPECT_FALSE(did_request_commit_);
if (new_offset != old_offset)
EXPECT_TRUE(did_request_redraw_);
if (new_offset != 0) {
EXPECT_TRUE(host_impl_->top_controls_manager()->animation());
EXPECT_TRUE(did_request_animate_);
}
host_impl_->DidFinishImplFrame();
}
EXPECT_FALSE(host_impl_->top_controls_manager()->animation());
}
TEST_F(LayerTreeHostImplWithTopControlsTest, TopControlsAnimationAfterScroll) {
LayerImpl* scroll_layer = SetupScrollAndContentsLayers(gfx::Size(100, 200));
host_impl_->SetViewportSize(gfx::Size(100, 100));
host_impl_->top_controls_manager()->UpdateTopControlsState(
BOTH, SHOWN, false);
float initial_scroll_offset = 50;
scroll_layer->PushScrollOffsetFromMainThread(
gfx::ScrollOffset(0, initial_scroll_offset));
DrawFrame();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
EXPECT_EQ(0, host_impl_->top_controls_manager()->ControlsTopOffset());
EXPECT_EQ(gfx::Vector2dF(0, initial_scroll_offset).ToString(),
scroll_layer->CurrentScrollOffset().ToString());
// Scroll the top controls partially.
const float residue = 15;
float offset = top_controls_height_ - residue;
EXPECT_TRUE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, offset)).did_scroll);
EXPECT_FLOAT_EQ(-offset,
host_impl_->top_controls_manager()->ControlsTopOffset());
EXPECT_EQ(gfx::Vector2dF(0, initial_scroll_offset).ToString(),
scroll_layer->CurrentScrollOffset().ToString());
did_request_redraw_ = false;
did_request_animate_ = false;
did_request_commit_ = false;
// End the scroll while the controls are still offset from the limit.
host_impl_->ScrollEnd();
ASSERT_TRUE(host_impl_->top_controls_manager()->animation());
EXPECT_TRUE(did_request_animate_);
EXPECT_TRUE(did_request_redraw_);
EXPECT_FALSE(did_request_commit_);
// Animate the top controls to the limit.
BeginFrameArgs begin_frame_args = CreateBeginFrameArgsForTesting(
BEGINFRAME_FROM_HERE, base::TimeTicks::Now());
while (did_request_animate_) {
did_request_redraw_ = false;
did_request_animate_ = false;
did_request_commit_ = false;
float old_offset =
host_impl_->top_controls_manager()->ControlsTopOffset();
begin_frame_args.frame_time += base::TimeDelta::FromMilliseconds(5);
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
float new_offset =
host_impl_->top_controls_manager()->ControlsTopOffset();
if (new_offset != old_offset) {
EXPECT_TRUE(did_request_redraw_);
EXPECT_TRUE(did_request_commit_);
}
host_impl_->DidFinishImplFrame();
}
EXPECT_FALSE(host_impl_->top_controls_manager()->animation());
EXPECT_EQ(-top_controls_height_,
host_impl_->top_controls_manager()->ControlsTopOffset());
}
TEST_F(LayerTreeHostImplWithTopControlsTest,
TopControlsAnimationAfterMainThreadFlingStopped) {
LayerImpl* scroll_layer = SetupScrollAndContentsLayers(gfx::Size(100, 200));
host_impl_->SetViewportSize(gfx::Size(100, 100));
host_impl_->top_controls_manager()->UpdateTopControlsState(BOTH, SHOWN,
false);
float initial_scroll_offset = 50;
scroll_layer->PushScrollOffsetFromMainThread(
gfx::ScrollOffset(0, initial_scroll_offset));
DrawFrame();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
EXPECT_EQ(0, host_impl_->top_controls_manager()->ControlsTopOffset());
EXPECT_EQ(gfx::Vector2dF(0, initial_scroll_offset).ToString(),
scroll_layer->CurrentScrollOffset().ToString());
// Scroll the top controls partially.
const float residue = 15;
float offset = top_controls_height_ - residue;
EXPECT_TRUE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, offset)).did_scroll);
EXPECT_FLOAT_EQ(-offset,
host_impl_->top_controls_manager()->ControlsTopOffset());
EXPECT_EQ(gfx::Vector2dF(0, initial_scroll_offset).ToString(),
scroll_layer->CurrentScrollOffset().ToString());
did_request_redraw_ = false;
did_request_animate_ = false;
did_request_commit_ = false;
// End the fling while the controls are still offset from the limit.
host_impl_->MainThreadHasStoppedFlinging();
ASSERT_TRUE(host_impl_->top_controls_manager()->animation());
EXPECT_TRUE(did_request_animate_);
EXPECT_TRUE(did_request_redraw_);
EXPECT_FALSE(did_request_commit_);
// Animate the top controls to the limit.
BeginFrameArgs begin_frame_args = CreateBeginFrameArgsForTesting(
BEGINFRAME_FROM_HERE, base::TimeTicks::Now());
while (did_request_animate_) {
did_request_redraw_ = false;
did_request_animate_ = false;
did_request_commit_ = false;
float old_offset = host_impl_->top_controls_manager()->ControlsTopOffset();
begin_frame_args.frame_time += base::TimeDelta::FromMilliseconds(5);
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
float new_offset = host_impl_->top_controls_manager()->ControlsTopOffset();
if (new_offset != old_offset) {
EXPECT_TRUE(did_request_redraw_);
EXPECT_TRUE(did_request_commit_);
}
host_impl_->DidFinishImplFrame();
}
EXPECT_FALSE(host_impl_->top_controls_manager()->animation());
EXPECT_EQ(-top_controls_height_,
host_impl_->top_controls_manager()->ControlsTopOffset());
}
TEST_F(LayerTreeHostImplWithTopControlsTest,
TopControlsScrollDeltaInOverScroll) {
// Verifies that the overscroll delta should not have accumulated in
// the top controls if we do a hide and show without releasing finger.
LayerImpl* scroll_layer = SetupScrollAndContentsLayers(gfx::Size(100, 200));
host_impl_->SetViewportSize(gfx::Size(100, 100));
host_impl_->top_controls_manager()->UpdateTopControlsState(BOTH, SHOWN,
false);
DrawFrame();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
EXPECT_EQ(0, host_impl_->top_controls_manager()->ControlsTopOffset());
float offset = 50;
EXPECT_TRUE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, offset)).did_scroll);
EXPECT_EQ(-offset, host_impl_->top_controls_manager()->ControlsTopOffset());
EXPECT_EQ(gfx::Vector2dF().ToString(),
scroll_layer->CurrentScrollOffset().ToString());
EXPECT_TRUE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, offset)).did_scroll);
EXPECT_EQ(gfx::Vector2dF(0, offset).ToString(),
scroll_layer->CurrentScrollOffset().ToString());
EXPECT_TRUE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, offset)).did_scroll);
// Should have fully scrolled
EXPECT_EQ(gfx::Vector2dF(0, scroll_layer->MaxScrollOffset().y()).ToString(),
scroll_layer->CurrentScrollOffset().ToString());
float overscrollamount = 10;
// Overscroll the content
EXPECT_FALSE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, overscrollamount))
.did_scroll);
EXPECT_EQ(gfx::Vector2dF(0, 2 * offset).ToString(),
scroll_layer->CurrentScrollOffset().ToString());
EXPECT_EQ(gfx::Vector2dF(0, overscrollamount).ToString(),
host_impl_->accumulated_root_overscroll().ToString());
EXPECT_TRUE(host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, -2 * offset))
.did_scroll);
EXPECT_EQ(gfx::Vector2dF(0, 0).ToString(),
scroll_layer->CurrentScrollOffset().ToString());
EXPECT_EQ(-offset, host_impl_->top_controls_manager()->ControlsTopOffset());
EXPECT_TRUE(
host_impl_->ScrollBy(gfx::Point(), gfx::Vector2d(0, -offset)).did_scroll);
EXPECT_EQ(gfx::Vector2dF(0, 0).ToString(),
scroll_layer->CurrentScrollOffset().ToString());
// Top controls should be fully visible
EXPECT_EQ(0, host_impl_->top_controls_manager()->ControlsTopOffset());
host_impl_->ScrollEnd();
}
class LayerTreeHostImplVirtualViewportTest : public LayerTreeHostImplTest {
public:
void SetupVirtualViewportLayers(const gfx::Size& content_size,
const gfx::Size& outer_viewport,
const gfx::Size& inner_viewport) {
LayerTreeImpl* layer_tree_impl = host_impl_->active_tree();
const int kOuterViewportClipLayerId = 6;
const int kOuterViewportScrollLayerId = 7;
const int kInnerViewportScrollLayerId = 2;
const int kInnerViewportClipLayerId = 4;
const int kPageScaleLayerId = 5;
scoped_ptr<LayerImpl> inner_scroll =
LayerImpl::Create(layer_tree_impl, kInnerViewportScrollLayerId);
inner_scroll->SetIsContainerForFixedPositionLayers(true);
inner_scroll->PushScrollOffsetFromMainThread(gfx::ScrollOffset());
scoped_ptr<LayerImpl> inner_clip =
LayerImpl::Create(layer_tree_impl, kInnerViewportClipLayerId);
inner_clip->SetBounds(inner_viewport);
scoped_ptr<LayerImpl> page_scale =
LayerImpl::Create(layer_tree_impl, kPageScaleLayerId);
inner_scroll->SetScrollClipLayer(inner_clip->id());
inner_scroll->SetBounds(outer_viewport);
inner_scroll->SetPosition(gfx::PointF());
scoped_ptr<LayerImpl> outer_clip =
LayerImpl::Create(layer_tree_impl, kOuterViewportClipLayerId);
outer_clip->SetBounds(outer_viewport);
outer_clip->SetIsContainerForFixedPositionLayers(true);
scoped_ptr<LayerImpl> outer_scroll =
LayerImpl::Create(layer_tree_impl, kOuterViewportScrollLayerId);
outer_scroll->SetScrollClipLayer(outer_clip->id());
outer_scroll->PushScrollOffsetFromMainThread(gfx::ScrollOffset());
outer_scroll->SetBounds(content_size);
outer_scroll->SetPosition(gfx::PointF());
scoped_ptr<LayerImpl> contents =
LayerImpl::Create(layer_tree_impl, 8);
contents->SetDrawsContent(true);
contents->SetBounds(content_size);
contents->SetPosition(gfx::PointF());
outer_scroll->AddChild(contents.Pass());
outer_clip->AddChild(outer_scroll.Pass());
inner_scroll->AddChild(outer_clip.Pass());
page_scale->AddChild(inner_scroll.Pass());
inner_clip->AddChild(page_scale.Pass());
inner_clip->SetHasRenderSurface(true);
layer_tree_impl->SetRootLayer(inner_clip.Pass());
layer_tree_impl->SetViewportLayersFromIds(
Layer::INVALID_ID, kPageScaleLayerId, kInnerViewportScrollLayerId,
kOuterViewportScrollLayerId);
host_impl_->active_tree()->DidBecomeActive();
}
};
TEST_F(LayerTreeHostImplVirtualViewportTest, ScrollBothInnerAndOuterLayer) {
gfx::Size content_size = gfx::Size(100, 160);
gfx::Size outer_viewport = gfx::Size(50, 80);
gfx::Size inner_viewport = gfx::Size(25, 40);
SetupVirtualViewportLayers(content_size, outer_viewport, inner_viewport);
TestScrollOffsetDelegate scroll_delegate;
host_impl_->SetRootLayerScrollOffsetDelegate(&scroll_delegate);
LayerImpl* outer_scroll = host_impl_->OuterViewportScrollLayer();
LayerImpl* inner_scroll = host_impl_->InnerViewportScrollLayer();
DrawFrame();
{
gfx::ScrollOffset inner_expected;
gfx::ScrollOffset outer_expected;
EXPECT_EQ(inner_expected, inner_scroll->CurrentScrollOffset());
EXPECT_EQ(outer_expected, outer_scroll->CurrentScrollOffset());
gfx::ScrollOffset current_offset(70.f, 100.f);
scroll_delegate.set_getter_return_value(current_offset);
host_impl_->OnRootLayerDelegatedScrollOffsetChanged(current_offset);
EXPECT_EQ(gfx::ScrollOffset(25.f, 40.f), inner_scroll->MaxScrollOffset());
EXPECT_EQ(gfx::ScrollOffset(50.f, 80.f), outer_scroll->MaxScrollOffset());
// Outer viewport scrolls first. Then the rest is applied to the inner
// viewport.
EXPECT_EQ(gfx::ScrollOffset(20.f, 20.f),
inner_scroll->CurrentScrollOffset());
EXPECT_EQ(gfx::ScrollOffset(50.f, 80.f),
outer_scroll->CurrentScrollOffset());
}
}
TEST_F(LayerTreeHostImplVirtualViewportTest, FlingScrollBubblesToInner) {
gfx::Size content_size = gfx::Size(100, 160);
gfx::Size outer_viewport = gfx::Size(50, 80);
gfx::Size inner_viewport = gfx::Size(25, 40);
SetupVirtualViewportLayers(content_size, outer_viewport, inner_viewport);
LayerImpl* outer_scroll = host_impl_->OuterViewportScrollLayer();
LayerImpl* inner_scroll = host_impl_->InnerViewportScrollLayer();
DrawFrame();
{
gfx::Vector2dF inner_expected;
gfx::Vector2dF outer_expected;
EXPECT_VECTOR_EQ(inner_expected, inner_scroll->CurrentScrollOffset());
EXPECT_VECTOR_EQ(outer_expected, outer_scroll->CurrentScrollOffset());
// Make sure the fling goes to the outer viewport first
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
EXPECT_EQ(outer_scroll, host_impl_->CurrentlyScrollingLayer());
EXPECT_EQ(InputHandler::SCROLL_STARTED, host_impl_->FlingScrollBegin());
EXPECT_EQ(outer_scroll, host_impl_->CurrentlyScrollingLayer());
gfx::Vector2d scroll_delta(inner_viewport.width(), inner_viewport.height());
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
outer_expected += gfx::Vector2dF(scroll_delta.x(), scroll_delta.y());
EXPECT_EQ(host_impl_->CurrentlyScrollingLayer(), outer_scroll);
host_impl_->ScrollEnd();
EXPECT_EQ(nullptr, host_impl_->CurrentlyScrollingLayer());
EXPECT_VECTOR_EQ(inner_expected, inner_scroll->CurrentScrollOffset());
EXPECT_VECTOR_EQ(outer_expected, outer_scroll->CurrentScrollOffset());
// Fling past the outer viewport boundry, make sure inner viewport scrolls.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
EXPECT_EQ(outer_scroll, host_impl_->CurrentlyScrollingLayer());
EXPECT_EQ(InputHandler::SCROLL_STARTED, host_impl_->FlingScrollBegin());
EXPECT_EQ(outer_scroll, host_impl_->CurrentlyScrollingLayer());
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
outer_expected += gfx::Vector2dF(scroll_delta.x(), scroll_delta.y());
EXPECT_EQ(outer_scroll, host_impl_->CurrentlyScrollingLayer());
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
inner_expected += gfx::Vector2dF(scroll_delta.x(), scroll_delta.y());
EXPECT_EQ(outer_scroll, host_impl_->CurrentlyScrollingLayer());
host_impl_->ScrollEnd();
EXPECT_EQ(nullptr, host_impl_->CurrentlyScrollingLayer());
EXPECT_VECTOR_EQ(inner_expected, inner_scroll->CurrentScrollOffset());
EXPECT_VECTOR_EQ(outer_expected, outer_scroll->CurrentScrollOffset());
}
}
TEST_F(LayerTreeHostImplVirtualViewportTest,
DiagonalScrollBubblesPerfectlyToInner) {
gfx::Size content_size = gfx::Size(100, 160);
gfx::Size outer_viewport = gfx::Size(50, 80);
gfx::Size inner_viewport = gfx::Size(25, 40);
SetupVirtualViewportLayers(content_size, outer_viewport, inner_viewport);
LayerImpl* outer_scroll = host_impl_->OuterViewportScrollLayer();
LayerImpl* inner_scroll = host_impl_->InnerViewportScrollLayer();
DrawFrame();
{
gfx::Vector2dF inner_expected;
gfx::Vector2dF outer_expected;
EXPECT_VECTOR_EQ(inner_expected, inner_scroll->CurrentScrollOffset());
EXPECT_VECTOR_EQ(outer_expected, outer_scroll->CurrentScrollOffset());
// Make sure the scroll goes to the outer viewport first.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
EXPECT_EQ(InputHandler::SCROLL_STARTED, host_impl_->FlingScrollBegin());
EXPECT_TRUE(host_impl_->IsCurrentlyScrollingLayerAt(gfx::Point(),
InputHandler::GESTURE));
// Scroll near the edge of the outer viewport.
gfx::Vector2d scroll_delta(inner_viewport.width(), inner_viewport.height());
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
outer_expected += scroll_delta;
EXPECT_TRUE(host_impl_->IsCurrentlyScrollingLayerAt(gfx::Point(),
InputHandler::GESTURE));
EXPECT_VECTOR_EQ(inner_expected, inner_scroll->CurrentScrollOffset());
EXPECT_VECTOR_EQ(outer_expected, outer_scroll->CurrentScrollOffset());
// Now diagonal scroll across the outer viewport boundary in a single event.
// The entirety of the scroll should be consumed, as bubbling between inner
// and outer viewport layers is perfect.
host_impl_->ScrollBy(gfx::Point(), gfx::ScaleVector2d(scroll_delta, 2));
EXPECT_TRUE(host_impl_->IsCurrentlyScrollingLayerAt(gfx::Point(),
InputHandler::GESTURE));
outer_expected += scroll_delta;
inner_expected += scroll_delta;
host_impl_->ScrollEnd();
EXPECT_FALSE(host_impl_->IsCurrentlyScrollingLayerAt(
gfx::Point(), InputHandler::GESTURE));
EXPECT_VECTOR_EQ(inner_expected, inner_scroll->CurrentScrollOffset());
EXPECT_VECTOR_EQ(outer_expected, outer_scroll->CurrentScrollOffset());
}
}
TEST_F(LayerTreeHostImplVirtualViewportTest,
TouchFlingCanLockToViewportLayerAfterBubbling) {
gfx::Size content_size = gfx::Size(100, 160);
gfx::Size outer_viewport = gfx::Size(50, 80);
gfx::Size inner_viewport = gfx::Size(25, 40);
SetupVirtualViewportLayers(content_size, outer_viewport, inner_viewport);
LayerImpl* outer_scroll = host_impl_->OuterViewportScrollLayer();
LayerImpl* inner_scroll = host_impl_->InnerViewportScrollLayer();
scoped_ptr<LayerImpl> child =
CreateScrollableLayer(10, outer_viewport, outer_scroll);
LayerImpl* child_scroll = child.get();
outer_scroll->children()[0]->AddChild(child.Pass());
DrawFrame();
{
scoped_ptr<ScrollAndScaleSet> scroll_info;
gfx::Vector2d scroll_delta(0, inner_viewport.height());
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
EXPECT_TRUE(host_impl_->ScrollBy(gfx::Point(), scroll_delta).did_scroll);
EXPECT_TRUE(host_impl_->IsCurrentlyScrollingLayerAt(gfx::Point(),
InputHandler::GESTURE));
// The child should have scrolled up to its limit.
scroll_info = host_impl_->ProcessScrollDeltas();
ASSERT_EQ(1u, scroll_info->scrolls.size());
EXPECT_TRUE(
ScrollInfoContains(*scroll_info, child_scroll->id(), scroll_delta));
EXPECT_EQ(host_impl_->CurrentlyScrollingLayer(), child_scroll);
// The first |ScrollBy| after the fling should re-lock the scrolling
// layer to the first layer that scrolled, the inner viewport scroll layer.
EXPECT_EQ(InputHandler::SCROLL_STARTED, host_impl_->FlingScrollBegin());
EXPECT_TRUE(host_impl_->ScrollBy(gfx::Point(), scroll_delta).did_scroll);
EXPECT_EQ(host_impl_->CurrentlyScrollingLayer(), inner_scroll);
EXPECT_TRUE(host_impl_->IsCurrentlyScrollingLayerAt(gfx::Point(),
InputHandler::GESTURE));
// The inner viewport should have scrolled up to its limit.
scroll_info = host_impl_->ProcessScrollDeltas();
ASSERT_EQ(2u, scroll_info->scrolls.size());
EXPECT_TRUE(
ScrollInfoContains(*scroll_info, child_scroll->id(), scroll_delta));
EXPECT_TRUE(
ScrollInfoContains(*scroll_info, inner_scroll->id(), scroll_delta));
// As the locked layer is at its limit, no further scrolling can occur.
EXPECT_FALSE(host_impl_->ScrollBy(gfx::Point(), scroll_delta).did_scroll);
EXPECT_EQ(host_impl_->CurrentlyScrollingLayer(), inner_scroll);
host_impl_->ScrollEnd();
EXPECT_FALSE(host_impl_->IsCurrentlyScrollingLayerAt(
gfx::Point(), InputHandler::GESTURE));
}
}
TEST_F(LayerTreeHostImplVirtualViewportTest,
ScrollBeginEventThatTargetsViewportLayerSkipsHitTest) {
gfx::Size content_size = gfx::Size(100, 160);
gfx::Size outer_viewport = gfx::Size(50, 80);
gfx::Size inner_viewport = gfx::Size(25, 40);
SetupVirtualViewportLayers(content_size, outer_viewport, inner_viewport);
LayerImpl* outer_scroll = host_impl_->OuterViewportScrollLayer();
LayerImpl* inner_scroll = host_impl_->InnerViewportScrollLayer();
scoped_ptr<LayerImpl> child =
CreateScrollableLayer(10, outer_viewport, outer_scroll);
LayerImpl* child_scroll = child.get();
outer_scroll->children()[0]->AddChild(child.Pass());
DrawFrame();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->RootScrollBegin(InputHandler::GESTURE));
EXPECT_EQ(host_impl_->CurrentlyScrollingLayer(), inner_scroll);
host_impl_->ScrollEnd();
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
EXPECT_EQ(host_impl_->CurrentlyScrollingLayer(), child_scroll);
host_impl_->ScrollEnd();
}
TEST_F(LayerTreeHostImplVirtualViewportTest,
NoOverscrollWhenInnerViewportCantScroll) {
InputHandlerScrollResult scroll_result;
gfx::Size content_size = gfx::Size(100, 160);
gfx::Size outer_viewport = gfx::Size(50, 80);
gfx::Size inner_viewport = gfx::Size(25, 40);
SetupVirtualViewportLayers(content_size, outer_viewport, inner_viewport);
DrawFrame();
// Make inner viewport unscrollable.
LayerImpl* inner_scroll = host_impl_->InnerViewportScrollLayer();
inner_scroll->set_user_scrollable_horizontal(false);
inner_scroll->set_user_scrollable_vertical(false);
// Ensure inner viewport doesn't react to scrolls (test it's unscrollable).
EXPECT_VECTOR_EQ(gfx::Vector2dF(), inner_scroll->CurrentScrollOffset());
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE));
scroll_result = host_impl_->ScrollBy(gfx::Point(), gfx::Vector2dF(0, 100));
EXPECT_VECTOR_EQ(gfx::Vector2dF(), inner_scroll->CurrentScrollOffset());
// When inner viewport is unscrollable, a fling gives zero overscroll.
EXPECT_FALSE(scroll_result.did_overscroll_root);
EXPECT_EQ(gfx::Vector2dF(), host_impl_->accumulated_root_overscroll());
}
class LayerTreeHostImplWithImplicitLimitsTest : public LayerTreeHostImplTest {
public:
void SetUp() override {
LayerTreeSettings settings = DefaultSettings();
settings.max_memory_for_prepaint_percentage = 50;
CreateHostImpl(settings, CreateOutputSurface());
}
};
TEST_F(LayerTreeHostImplWithImplicitLimitsTest, ImplicitMemoryLimits) {
// Set up a memory policy and percentages which could cause
// 32-bit integer overflows.
ManagedMemoryPolicy mem_policy(300 * 1024 * 1024); // 300MB
// Verify implicit limits are calculated correctly with no overflows
host_impl_->SetMemoryPolicy(mem_policy);
EXPECT_EQ(host_impl_->global_tile_state().hard_memory_limit_in_bytes,
300u * 1024u * 1024u);
EXPECT_EQ(host_impl_->global_tile_state().soft_memory_limit_in_bytes,
150u * 1024u * 1024u);
}
TEST_F(LayerTreeHostImplTest, ExternalTransformReflectedInNextDraw) {
const gfx::Size layer_size(100, 100);
gfx::Transform external_transform;
const gfx::Rect external_viewport(layer_size);
const gfx::Rect external_clip(layer_size);
const bool resourceless_software_draw = false;
LayerImpl* layer = SetupScrollAndContentsLayers(layer_size);
host_impl_->SetExternalDrawConstraints(external_transform,
external_viewport,
external_clip,
external_viewport,
external_transform,
resourceless_software_draw);
DrawFrame();
EXPECT_TRANSFORMATION_MATRIX_EQ(
external_transform, layer->draw_properties().target_space_transform);
external_transform.Translate(20, 20);
host_impl_->SetExternalDrawConstraints(external_transform,
external_viewport,
external_clip,
external_viewport,
external_transform,
resourceless_software_draw);
DrawFrame();
EXPECT_TRANSFORMATION_MATRIX_EQ(
external_transform, layer->draw_properties().target_space_transform);
}
TEST_F(LayerTreeHostImplTest, ScrollAnimated) {
SetupScrollAndContentsLayers(gfx::Size(100, 200));
DrawFrame();
base::TimeTicks start_time =
base::TimeTicks() + base::TimeDelta::FromMilliseconds(100);
BeginFrameArgs begin_frame_args =
CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollAnimated(gfx::Point(), gfx::Vector2d(0, 50)));
LayerImpl* scrolling_layer = host_impl_->CurrentlyScrollingLayer();
begin_frame_args.frame_time = start_time;
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
host_impl_->UpdateAnimationState(true);
EXPECT_EQ(gfx::ScrollOffset(), scrolling_layer->CurrentScrollOffset());
host_impl_->DidFinishImplFrame();
begin_frame_args.frame_time =
start_time + base::TimeDelta::FromMilliseconds(50);
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
host_impl_->UpdateAnimationState(true);
float y = scrolling_layer->CurrentScrollOffset().y();
EXPECT_TRUE(y > 1 && y < 49);
// Update target.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollAnimated(gfx::Point(), gfx::Vector2d(0, 50)));
host_impl_->DidFinishImplFrame();
begin_frame_args.frame_time =
start_time + base::TimeDelta::FromMilliseconds(200);
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
host_impl_->UpdateAnimationState(true);
y = scrolling_layer->CurrentScrollOffset().y();
EXPECT_TRUE(y > 50 && y < 100);
EXPECT_EQ(scrolling_layer, host_impl_->CurrentlyScrollingLayer());
host_impl_->DidFinishImplFrame();
begin_frame_args.frame_time =
start_time + base::TimeDelta::FromMilliseconds(250);
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
host_impl_->UpdateAnimationState(true);
EXPECT_VECTOR_EQ(gfx::ScrollOffset(0, 100),
scrolling_layer->CurrentScrollOffset());
EXPECT_EQ(NULL, host_impl_->CurrentlyScrollingLayer());
host_impl_->DidFinishImplFrame();
}
// Evolved from LayerTreeHostImplTest.ScrollAnimated.
TEST_F(LayerTreeHostImplTimelinesTest, ScrollAnimated) {
SetupScrollAndContentsLayers(gfx::Size(100, 200));
DrawFrame();
base::TimeTicks start_time =
base::TimeTicks() + base::TimeDelta::FromMilliseconds(100);
BeginFrameArgs begin_frame_args =
CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollAnimated(gfx::Point(), gfx::Vector2d(0, 50)));
LayerImpl* scrolling_layer = host_impl_->CurrentlyScrollingLayer();
begin_frame_args.frame_time = start_time;
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
host_impl_->UpdateAnimationState(true);
EXPECT_EQ(gfx::ScrollOffset(), scrolling_layer->CurrentScrollOffset());
host_impl_->DidFinishImplFrame();
begin_frame_args.frame_time =
start_time + base::TimeDelta::FromMilliseconds(50);
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
host_impl_->UpdateAnimationState(true);
float y = scrolling_layer->CurrentScrollOffset().y();
EXPECT_TRUE(y > 1 && y < 49);
// Update target.
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollAnimated(gfx::Point(), gfx::Vector2d(0, 50)));
host_impl_->DidFinishImplFrame();
begin_frame_args.frame_time =
start_time + base::TimeDelta::FromMilliseconds(200);
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
host_impl_->UpdateAnimationState(true);
y = scrolling_layer->CurrentScrollOffset().y();
EXPECT_TRUE(y > 50 && y < 100);
EXPECT_EQ(scrolling_layer, host_impl_->CurrentlyScrollingLayer());
host_impl_->DidFinishImplFrame();
begin_frame_args.frame_time =
start_time + base::TimeDelta::FromMilliseconds(250);
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->Animate();
host_impl_->UpdateAnimationState(true);
EXPECT_VECTOR_EQ(gfx::ScrollOffset(0, 100),
scrolling_layer->CurrentScrollOffset());
EXPECT_EQ(NULL, host_impl_->CurrentlyScrollingLayer());
host_impl_->DidFinishImplFrame();
}
TEST_F(LayerTreeHostImplTest, InvalidLayerNotAddedToRasterQueue) {
host_impl_->CreatePendingTree();
Region empty_invalidation;
scoped_refptr<RasterSource> pile_with_tiles(
FakePicturePileImpl::CreateFilledPileWithDefaultTileSize(
gfx::Size(10, 10)));
scoped_ptr<FakePictureLayerImpl> layer =
FakePictureLayerImpl::Create(host_impl_->pending_tree(), 11);
layer->SetBounds(gfx::Size(10, 10));
layer->set_gpu_raster_max_texture_size(host_impl_->device_viewport_size());
layer->SetDrawsContent(true);
layer->tilings()->AddTiling(1.0f, pile_with_tiles);
layer->UpdateRasterSource(pile_with_tiles, &empty_invalidation, nullptr);
layer->tilings()->tiling_at(0)->set_resolution(
TileResolution::HIGH_RESOLUTION);
layer->tilings()->tiling_at(0)->CreateAllTilesForTesting();
layer->tilings()->tiling_at(0)->ComputeTilePriorityRects(
gfx::Rect(gfx::Size(10, 10)), 1.f, 1.0, Occlusion());
host_impl_->pending_tree()->SetRootLayer(layer.Pass());
FakePictureLayerImpl* root_layer = static_cast<FakePictureLayerImpl*>(
host_impl_->pending_tree()->root_layer());
root_layer->set_has_valid_tile_priorities(true);
scoped_ptr<RasterTilePriorityQueue> non_empty_raster_priority_queue_all =
host_impl_->BuildRasterQueue(TreePriority::SAME_PRIORITY_FOR_BOTH_TREES,
RasterTilePriorityQueue::Type::ALL);
EXPECT_FALSE(non_empty_raster_priority_queue_all->IsEmpty());
root_layer->set_has_valid_tile_priorities(false);
scoped_ptr<RasterTilePriorityQueue> empty_raster_priority_queue_all =
host_impl_->BuildRasterQueue(TreePriority::SAME_PRIORITY_FOR_BOTH_TREES,
RasterTilePriorityQueue::Type::ALL);
EXPECT_TRUE(empty_raster_priority_queue_all->IsEmpty());
}
TEST_F(LayerTreeHostImplTest, DidBecomeActive) {
host_impl_->CreatePendingTree();
host_impl_->ActivateSyncTree();
host_impl_->CreatePendingTree();
LayerTreeImpl* pending_tree = host_impl_->pending_tree();
scoped_ptr<FakePictureLayerImpl> pending_layer =
FakePictureLayerImpl::Create(pending_tree, 10);
FakePictureLayerImpl* raw_pending_layer = pending_layer.get();
pending_tree->SetRootLayer(pending_layer.Pass());
ASSERT_EQ(raw_pending_layer, pending_tree->root_layer());
EXPECT_EQ(0u, raw_pending_layer->did_become_active_call_count());
pending_tree->DidBecomeActive();
EXPECT_EQ(1u, raw_pending_layer->did_become_active_call_count());
scoped_ptr<FakePictureLayerImpl> mask_layer =
FakePictureLayerImpl::Create(pending_tree, 11);
FakePictureLayerImpl* raw_mask_layer = mask_layer.get();
raw_pending_layer->SetMaskLayer(mask_layer.Pass());
ASSERT_EQ(raw_mask_layer, raw_pending_layer->mask_layer());
EXPECT_EQ(1u, raw_pending_layer->did_become_active_call_count());
EXPECT_EQ(0u, raw_mask_layer->did_become_active_call_count());
pending_tree->DidBecomeActive();
EXPECT_EQ(2u, raw_pending_layer->did_become_active_call_count());
EXPECT_EQ(1u, raw_mask_layer->did_become_active_call_count());
scoped_ptr<FakePictureLayerImpl> replica_layer =
FakePictureLayerImpl::Create(pending_tree, 12);
scoped_ptr<FakePictureLayerImpl> replica_mask_layer =
FakePictureLayerImpl::Create(pending_tree, 13);
FakePictureLayerImpl* raw_replica_mask_layer = replica_mask_layer.get();
replica_layer->SetMaskLayer(replica_mask_layer.Pass());
raw_pending_layer->SetReplicaLayer(replica_layer.Pass());
ASSERT_EQ(raw_replica_mask_layer,
raw_pending_layer->replica_layer()->mask_layer());
EXPECT_EQ(2u, raw_pending_layer->did_become_active_call_count());
EXPECT_EQ(1u, raw_mask_layer->did_become_active_call_count());
EXPECT_EQ(0u, raw_replica_mask_layer->did_become_active_call_count());
pending_tree->DidBecomeActive();
EXPECT_EQ(3u, raw_pending_layer->did_become_active_call_count());
EXPECT_EQ(2u, raw_mask_layer->did_become_active_call_count());
EXPECT_EQ(1u, raw_replica_mask_layer->did_become_active_call_count());
}
TEST_F(LayerTreeHostImplTest, WheelScrollWithPageScaleFactorOnInnerLayer) {
LayerImpl* scroll_layer = SetupScrollAndContentsLayers(gfx::Size(100, 100));
host_impl_->SetViewportSize(gfx::Size(50, 50));
DrawFrame();
EXPECT_EQ(scroll_layer, host_impl_->InnerViewportScrollLayer());
float min_page_scale = 1.f, max_page_scale = 4.f;
float page_scale_factor = 1.f;
// The scroll deltas should have the page scale factor applied.
{
host_impl_->active_tree()->PushPageScaleFromMainThread(
page_scale_factor, min_page_scale, max_page_scale);
host_impl_->active_tree()->SetPageScaleOnActiveTree(page_scale_factor);
scroll_layer->SetScrollDelta(gfx::Vector2d());
float page_scale_delta = 2.f;
host_impl_->ScrollBegin(gfx::Point(), InputHandler::GESTURE);
host_impl_->PinchGestureBegin();
host_impl_->PinchGestureUpdate(page_scale_delta, gfx::Point());
host_impl_->PinchGestureEnd();
host_impl_->ScrollEnd();
gfx::Vector2dF scroll_delta(0, 5);
EXPECT_EQ(InputHandler::SCROLL_STARTED,
host_impl_->ScrollBegin(gfx::Point(), InputHandler::WHEEL));
EXPECT_VECTOR_EQ(gfx::Vector2dF(), scroll_layer->CurrentScrollOffset());
host_impl_->ScrollBy(gfx::Point(), scroll_delta);
host_impl_->ScrollEnd();
EXPECT_VECTOR_EQ(gfx::Vector2dF(0, 2.5),
scroll_layer->CurrentScrollOffset());
}
}
class LayerTreeHostImplCountingLostSurfaces : public LayerTreeHostImplTest {
public:
LayerTreeHostImplCountingLostSurfaces() : num_lost_surfaces_(0) {}
void DidLoseOutputSurfaceOnImplThread() override { num_lost_surfaces_++; }
protected:
int num_lost_surfaces_;
};
TEST_F(LayerTreeHostImplCountingLostSurfaces, TwiceLostSurface) {
// Really we just need at least one client notification each time
// we go from having a valid output surface to not having a valid output
// surface.
EXPECT_EQ(0, num_lost_surfaces_);
host_impl_->DidLoseOutputSurface();
EXPECT_EQ(1, num_lost_surfaces_);
host_impl_->DidLoseOutputSurface();
EXPECT_LE(1, num_lost_surfaces_);
}
TEST_F(LayerTreeHostImplTest, RemoveUnreferencedRenderPass) {
LayerTreeHostImpl::FrameData frame;
frame.render_passes.push_back(RenderPass::Create());
RenderPass* pass3 = frame.render_passes.back();
frame.render_passes.push_back(RenderPass::Create());
RenderPass* pass2 = frame.render_passes.back();
frame.render_passes.push_back(RenderPass::Create());
RenderPass* pass1 = frame.render_passes.back();
pass1->SetNew(RenderPassId(1, 0), gfx::Rect(), gfx::Rect(), gfx::Transform());
pass2->SetNew(RenderPassId(2, 0), gfx::Rect(), gfx::Rect(), gfx::Transform());
pass3->SetNew(RenderPassId(3, 0), gfx::Rect(), gfx::Rect(), gfx::Transform());
frame.render_passes_by_id[pass1->id] = pass1;
frame.render_passes_by_id[pass2->id] = pass2;
frame.render_passes_by_id[pass3->id] = pass3;
// Add a quad to each pass so they aren't empty.
SolidColorDrawQuad* color_quad;
color_quad = pass1->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
color_quad->material = DrawQuad::SOLID_COLOR;
color_quad = pass2->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
color_quad->material = DrawQuad::SOLID_COLOR;
color_quad = pass3->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
color_quad->material = DrawQuad::SOLID_COLOR;
// pass3 is referenced by pass2.
RenderPassDrawQuad* rpdq =
pass2->CreateAndAppendDrawQuad<RenderPassDrawQuad>();
rpdq->material = DrawQuad::RENDER_PASS;
rpdq->render_pass_id = pass3->id;
// But pass2 is not referenced by pass1. So pass2 and pass3 should be culled.
FakeLayerTreeHostImpl::RemoveRenderPasses(&frame);
EXPECT_EQ(1u, frame.render_passes_by_id.size());
EXPECT_TRUE(frame.render_passes_by_id[RenderPassId(1, 0)]);
EXPECT_FALSE(frame.render_passes_by_id[RenderPassId(2, 0)]);
EXPECT_FALSE(frame.render_passes_by_id[RenderPassId(3, 0)]);
EXPECT_EQ(1u, frame.render_passes.size());
EXPECT_EQ(RenderPassId(1, 0), frame.render_passes[0]->id);
}
TEST_F(LayerTreeHostImplTest, RemoveEmptyRenderPass) {
LayerTreeHostImpl::FrameData frame;
frame.render_passes.push_back(RenderPass::Create());
RenderPass* pass3 = frame.render_passes.back();
frame.render_passes.push_back(RenderPass::Create());
RenderPass* pass2 = frame.render_passes.back();
frame.render_passes.push_back(RenderPass::Create());
RenderPass* pass1 = frame.render_passes.back();
pass1->SetNew(RenderPassId(1, 0), gfx::Rect(), gfx::Rect(), gfx::Transform());
pass2->SetNew(RenderPassId(2, 0), gfx::Rect(), gfx::Rect(), gfx::Transform());
pass3->SetNew(RenderPassId(3, 0), gfx::Rect(), gfx::Rect(), gfx::Transform());
frame.render_passes_by_id[pass1->id] = pass1;
frame.render_passes_by_id[pass2->id] = pass2;
frame.render_passes_by_id[pass3->id] = pass3;
// pass1 is not empty, but pass2 and pass3 are.
SolidColorDrawQuad* color_quad;
color_quad = pass1->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
color_quad->material = DrawQuad::SOLID_COLOR;
// pass3 is referenced by pass2.
RenderPassDrawQuad* rpdq =
pass2->CreateAndAppendDrawQuad<RenderPassDrawQuad>();
rpdq->material = DrawQuad::RENDER_PASS;
rpdq->render_pass_id = pass3->id;
// pass2 is referenced by pass1.
rpdq = pass1->CreateAndAppendDrawQuad<RenderPassDrawQuad>();
rpdq->material = DrawQuad::RENDER_PASS;
rpdq->render_pass_id = pass2->id;
// Since pass3 is empty it should be removed. Then pass2 is empty too, and
// should be removed.
FakeLayerTreeHostImpl::RemoveRenderPasses(&frame);
EXPECT_EQ(1u, frame.render_passes_by_id.size());
EXPECT_TRUE(frame.render_passes_by_id[RenderPassId(1, 0)]);
EXPECT_FALSE(frame.render_passes_by_id[RenderPassId(2, 0)]);
EXPECT_FALSE(frame.render_passes_by_id[RenderPassId(3, 0)]);
EXPECT_EQ(1u, frame.render_passes.size());
EXPECT_EQ(RenderPassId(1, 0), frame.render_passes[0]->id);
// The RenderPassDrawQuad should be removed from pass1.
EXPECT_EQ(1u, pass1->quad_list.size());
EXPECT_EQ(DrawQuad::SOLID_COLOR, pass1->quad_list.ElementAt(0)->material);
}
TEST_F(LayerTreeHostImplTest, DoNotRemoveEmptyRootRenderPass) {
LayerTreeHostImpl::FrameData frame;
frame.render_passes.push_back(RenderPass::Create());
RenderPass* pass3 = frame.render_passes.back();
frame.render_passes.push_back(RenderPass::Create());
RenderPass* pass2 = frame.render_passes.back();
frame.render_passes.push_back(RenderPass::Create());
RenderPass* pass1 = frame.render_passes.back();
pass1->SetNew(RenderPassId(1, 0), gfx::Rect(), gfx::Rect(), gfx::Transform());
pass2->SetNew(RenderPassId(2, 0), gfx::Rect(), gfx::Rect(), gfx::Transform());
pass3->SetNew(RenderPassId(3, 0), gfx::Rect(), gfx::Rect(), gfx::Transform());
frame.render_passes_by_id[pass1->id] = pass1;
frame.render_passes_by_id[pass2->id] = pass2;
frame.render_passes_by_id[pass3->id] = pass3;
// pass3 is referenced by pass2.
RenderPassDrawQuad* rpdq =
pass2->CreateAndAppendDrawQuad<RenderPassDrawQuad>();
rpdq->material = DrawQuad::RENDER_PASS;
rpdq->render_pass_id = pass3->id;
// pass2 is referenced by pass1.
rpdq = pass1->CreateAndAppendDrawQuad<RenderPassDrawQuad>();
rpdq->material = DrawQuad::RENDER_PASS;
rpdq->render_pass_id = pass2->id;
// Since pass3 is empty it should be removed. Then pass2 is empty too, and
// should be removed. Then pass1 is empty too, but it's the root so it should
// not be removed.
FakeLayerTreeHostImpl::RemoveRenderPasses(&frame);
EXPECT_EQ(1u, frame.render_passes_by_id.size());
EXPECT_TRUE(frame.render_passes_by_id[RenderPassId(1, 0)]);
EXPECT_FALSE(frame.render_passes_by_id[RenderPassId(2, 0)]);
EXPECT_FALSE(frame.render_passes_by_id[RenderPassId(3, 0)]);
EXPECT_EQ(1u, frame.render_passes.size());
EXPECT_EQ(RenderPassId(1, 0), frame.render_passes[0]->id);
// The RenderPassDrawQuad should be removed from pass1.
EXPECT_EQ(0u, pass1->quad_list.size());
}
class FakeVideoFrameController : public VideoFrameController {
public:
void OnBeginFrame(const BeginFrameArgs& args) override {
begin_frame_args_ = args;
did_draw_frame_ = false;
}
void DidDrawFrame() override { did_draw_frame_ = true; }
const BeginFrameArgs& begin_frame_args() const { return begin_frame_args_; }
bool did_draw_frame() const { return did_draw_frame_; }
private:
BeginFrameArgs begin_frame_args_;
bool did_draw_frame_ = false;
};
TEST_F(LayerTreeHostImplTest, AddVideoFrameControllerInsideFrame) {
BeginFrameArgs begin_frame_args =
CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE);
FakeVideoFrameController controller;
host_impl_->WillBeginImplFrame(begin_frame_args);
EXPECT_FALSE(controller.begin_frame_args().IsValid());
host_impl_->AddVideoFrameController(&controller);
EXPECT_TRUE(controller.begin_frame_args().IsValid());
host_impl_->DidFinishImplFrame();
EXPECT_FALSE(controller.did_draw_frame());
LayerTreeHostImpl::FrameData frame;
host_impl_->DidDrawAllLayers(frame);
EXPECT_TRUE(controller.did_draw_frame());
controller.OnBeginFrame(begin_frame_args);
EXPECT_FALSE(controller.did_draw_frame());
host_impl_->RemoveVideoFrameController(&controller);
host_impl_->DidDrawAllLayers(frame);
EXPECT_FALSE(controller.did_draw_frame());
}
TEST_F(LayerTreeHostImplTest, AddVideoFrameControllerOutsideFrame) {
BeginFrameArgs begin_frame_args =
CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE);
FakeVideoFrameController controller;
host_impl_->WillBeginImplFrame(begin_frame_args);
host_impl_->DidFinishImplFrame();
EXPECT_FALSE(controller.begin_frame_args().IsValid());
host_impl_->AddVideoFrameController(&controller);
EXPECT_FALSE(controller.begin_frame_args().IsValid());
begin_frame_args = CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE);
EXPECT_FALSE(controller.begin_frame_args().IsValid());
host_impl_->WillBeginImplFrame(begin_frame_args);
EXPECT_TRUE(controller.begin_frame_args().IsValid());
EXPECT_FALSE(controller.did_draw_frame());
LayerTreeHostImpl::FrameData frame;
host_impl_->DidDrawAllLayers(frame);
EXPECT_TRUE(controller.did_draw_frame());
controller.OnBeginFrame(begin_frame_args);
EXPECT_FALSE(controller.did_draw_frame());
host_impl_->RemoveVideoFrameController(&controller);
host_impl_->DidDrawAllLayers(frame);
EXPECT_FALSE(controller.did_draw_frame());
}
TEST_F(LayerTreeHostImplTest, GpuRasterizationStatusModes) {
EXPECT_FALSE(host_impl_->use_gpu_rasterization());
host_impl_->SetHasGpuRasterizationTrigger(true);
host_impl_->SetContentIsSuitableForGpuRasterization(true);
EXPECT_EQ(GpuRasterizationStatus::ON, host_impl_->gpu_rasterization_status());
EXPECT_TRUE(host_impl_->use_gpu_rasterization());
host_impl_->SetHasGpuRasterizationTrigger(false);
host_impl_->SetContentIsSuitableForGpuRasterization(true);
EXPECT_EQ(GpuRasterizationStatus::OFF_VIEWPORT,
host_impl_->gpu_rasterization_status());
EXPECT_FALSE(host_impl_->use_gpu_rasterization());
host_impl_->SetHasGpuRasterizationTrigger(true);
host_impl_->SetContentIsSuitableForGpuRasterization(false);
EXPECT_EQ(GpuRasterizationStatus::OFF_CONTENT,
host_impl_->gpu_rasterization_status());
EXPECT_FALSE(host_impl_->use_gpu_rasterization());
EXPECT_FALSE(host_impl_->use_msaa());
scoped_ptr<TestWebGraphicsContext3D> context_with_msaa =
TestWebGraphicsContext3D::Create();
context_with_msaa->SetMaxSamples(8);
LayerTreeSettings msaaSettings = GpuRasterizationEnabledSettings();
msaaSettings.gpu_rasterization_msaa_sample_count = 4;
EXPECT_TRUE(CreateHostImpl(
msaaSettings, FakeOutputSurface::Create3d(context_with_msaa.Pass())));
host_impl_->SetHasGpuRasterizationTrigger(true);
host_impl_->SetContentIsSuitableForGpuRasterization(false);
EXPECT_EQ(GpuRasterizationStatus::MSAA_CONTENT,
host_impl_->gpu_rasterization_status());
EXPECT_TRUE(host_impl_->use_gpu_rasterization());
EXPECT_TRUE(host_impl_->use_msaa());
LayerTreeSettings settings = DefaultSettings();
settings.gpu_rasterization_enabled = false;
EXPECT_TRUE(CreateHostImpl(settings, FakeOutputSurface::Create3d()));
host_impl_->SetHasGpuRasterizationTrigger(true);
host_impl_->SetContentIsSuitableForGpuRasterization(true);
EXPECT_EQ(GpuRasterizationStatus::OFF_DEVICE,
host_impl_->gpu_rasterization_status());
EXPECT_FALSE(host_impl_->use_gpu_rasterization());
settings.gpu_rasterization_forced = true;
EXPECT_TRUE(CreateHostImpl(settings, FakeOutputSurface::Create3d()));
host_impl_->SetHasGpuRasterizationTrigger(false);
host_impl_->SetContentIsSuitableForGpuRasterization(false);
EXPECT_EQ(GpuRasterizationStatus::ON_FORCED,
host_impl_->gpu_rasterization_status());
EXPECT_TRUE(host_impl_->use_gpu_rasterization());
}
// A mock output surface which lets us detect calls to ForceReclaimResources.
class MockReclaimResourcesOutputSurface : public FakeOutputSurface {
public:
static scoped_ptr<MockReclaimResourcesOutputSurface> Create3d() {
return make_scoped_ptr(new MockReclaimResourcesOutputSurface(
TestContextProvider::Create(), TestContextProvider::Create(), false));
}
MOCK_METHOD0(ForceReclaimResources, void());
protected:
MockReclaimResourcesOutputSurface(
scoped_refptr<ContextProvider> context_provider,
scoped_refptr<ContextProvider> worker_context_provider,
bool delegated_rendering)
: FakeOutputSurface(context_provider,
worker_context_provider,
delegated_rendering) {}
};
// Display::Draw (and the planned Display Scheduler) currently rely on resources
// being reclaimed to block drawing between BeginCommit / Swap. This test
// ensures that BeginCommit triggers ForceReclaimResources. See
// crbug.com/489515.
TEST_F(LayerTreeHostImplTest, BeginCommitReclaimsResources) {
scoped_ptr<MockReclaimResourcesOutputSurface> output_surface(
MockReclaimResourcesOutputSurface::Create3d());
// Hold an unowned pointer to the output surface to use for mock expectations.
MockReclaimResourcesOutputSurface* mock_output_surface = output_surface.get();
CreateHostImpl(DefaultSettings(), output_surface.Pass());
EXPECT_CALL(*mock_output_surface, ForceReclaimResources()).Times(1);
host_impl_->BeginCommit();
}
} // namespace
} // namespace cc
|
Chilledheart/chromium
|
cc/trees/layer_tree_host_impl_unittest.cc
|
C++
|
bsd-3-clause
| 343,926 |
///
/// \file PWGCF/FEMTOSCOPY/AliFemto/AliFemtoEventReaderAOD.h
/// \author Adam Kisiel <[email protected]>
///
/// \class AliFemtoEventReaderAOD
/// \brief The reader class for Alice AOD files
/// Reads in AOD information and converts it into internal AliFemtoEvent
///
#ifndef ALIFEMTOEVENTREADERAOD_H
#define ALIFEMTOEVENTREADERAOD_H
#include "AliFemtoEventReader.h"
#include "AliFemtoEnumeration.h"
#include <string>
#include "TTree.h"
#include "TChain.h"
#include "TBits.h"
#include "THnSparse.h"
#include "AliAODEvent.h"
//#include "AliPWG2AODTrack.h"
#include "AliAODMCParticle.h"
#include "AliFemtoV0.h"
#include "AliFemtoXi.h"
#include "AliAODpidUtil.h"
#include "AliAODHeader.h"
#include "AliAnalysisUtils.h"
#include "AliEventCuts.h"
class AliFemtoEvent;
class AliFemtoTrack;
class AliFemtoEventReaderAOD : public AliFemtoEventReader {
public:
enum EventMult {kCentrality = 0, kGlobalCount = 1, kReference = 2,
kTPCOnlyRef = 3, kVZERO = 4, kCentralityTRK = 5,
kCentralityZNA = 6, kCentralityCL1 = 7, kCentralityCND = 9,
kCentralityV0A = 10, kCentralityV0C = 11, kCentralityZNC = 12,
kCentralityCL0 = 13, kCentralityFMD = 14, kCentralityTKL = 15,
kCentralityNPA = 16
};
typedef enum EventMult EstEventMult;
AliFemtoEventReaderAOD();
AliFemtoEventReaderAOD(const AliFemtoEventReaderAOD &aReader);
virtual ~AliFemtoEventReaderAOD();
AliFemtoEventReaderAOD &operator=(const AliFemtoEventReaderAOD &aReader);
virtual AliFemtoEvent *ReturnHbtEvent();
AliFemtoString Report();
void SetInputFile(const char *inputfile);
void SetFilterBit(UInt_t ibit);
void SetFilterMask(int ibit);
UInt_t GetTrackFilter() const {
return fFilterBit | fFilterMask;
}
void SetReadMC(unsigned char a);
bool GetReadMC() const {
return fReadMC;
}
void SetReadV0(unsigned char a);
bool GetReadV0() const {
return fReadV0;
}
void SetReadCascade(unsigned char a);
bool GetReadCascade() const {
return fReadCascade;
}
void SetCentralityPreSelection(double min, double max);
std::pair<double, double> GetCentralityPreSelection() const {
return std::make_pair(fCentRange[0], fCentRange[1]);
}
void SetNoCentrality(bool anocent);
void SetAODpidUtil(AliAODpidUtil *aAODpidUtil);
void SetAODheader(AliAODHeader *aAODheader);
void SetMagneticFieldSign(int s);
void SetEPVZERO(Bool_t);
void GetGlobalPositionAtGlobalRadiiThroughTPC(AliAODTrack *track, Float_t bfield, Float_t globalPositionsAtRadii[9][3]);
void SetUseMultiplicity(EstEventMult aType);
EstEventMult GetUseMultiplicity() const {
return fEstEventMult;
}
void SetpA2013(Bool_t pa2013); ///< set vertex configuration for pA (2013): IsVertexSelected2013pA
void SetUseMVPlpSelection(Bool_t mvplp);
void SetUseOutOfBunchPlpSelection(Bool_t outOfBunchPlp);
void SetIsPileUpEvent(Bool_t ispileup);
void SetCascadePileUpRemoval(Bool_t cascadePileUpRemoval);
void SetV0PileUpRemoval(Bool_t v0PileUpRemoval);
void SetTrackPileUpRemoval(Bool_t trackPileUpRemoval);
void SetMinVtxContr(Int_t contr = 1) {
fMinVtxContr = contr;
}
void SetMinPlpContribMV(Int_t minPlpContribMV) {
fMinPlpContribMV = minPlpContribMV;
}
void SetMinPlpContribSPD(Int_t minPlpContribSPD) {
fMinPlpContribSPD = minPlpContribSPD;
}
void SetDCAglobalTrack(Int_t dcagt);
Int_t GetDCAglobalTrack() const {
return fDCAglobalTrack;
}
bool RejectEventCentFlat(float MagField, float CentPercent);
void SetCentralityFlattening(Bool_t flat);
bool GetCentralityFlattening() const {
return fFlatCent;
}
void SetShiftPosition(Double_t rad);
void SetPrimaryVertexCorrectionTPCPoints(bool correctTpcPoints);
bool GetPrimaryVertexCorrectionTPCPoints() const {
return fPrimaryVertexCorrectionTPCPoints;
}
void SetShiftedPositions(const AliAODTrack *track ,const Float_t bfield, Float_t posShifted[3], const Double_t radius=1.25);
void SetUseAliEventCuts(Bool_t useAliEventCuts);
void SetReadFullMCData(Bool_t should_read=true);
bool GetReadFullMCData() const;
void Set1DCorrectionsPions(TH1D *h1);
void Set1DCorrectionsKaons(TH1D *h1);
void Set1DCorrectionsProtons(TH1D *h1);
void Set1DCorrectionsPionsMinus(TH1D *h1);
void Set1DCorrectionsKaonsMinus(TH1D *h1);
void Set1DCorrectionsProtonsMinus(TH1D *h1);
void Set1DCorrectionsDeuterons(TH1D *h1);
void Set1DCorrectionsTritons(TH1D *h1);
void Set1DCorrectionsHe3s(TH1D *h1);
void Set1DCorrectionsAlphas(TH1D *h1);
void Set1DCorrectionsDeuteronsMinus(TH1D *h1);
void Set1DCorrectionsTritonsMinus(TH1D *h1);
void Set1DCorrectionsHe3sMinus(TH1D *h1);
void Set1DCorrectionsAlphasMinus(TH1D *h1);
void Set1DCorrectionsAll(TH1D *h1);
void Set1DCorrectionsLambdas(TH1D *h1);
void Set1DCorrectionsLambdasMinus(TH1D *h1);
void Set1DCorrectionsXiPlus(TH1D *h1);
void Set1DCorrectionsXiMinus(TH1D *h1);
void Set4DCorrectionsPions(THnSparse *h1);
void Set4DCorrectionsKaons(THnSparse *h1);
void Set4DCorrectionsProtons(THnSparse *h1);
void Set4DCorrectionsPionsMinus(THnSparse *h1);
void Set4DCorrectionsKaonsMinus(THnSparse *h1);
void Set4DCorrectionsProtonsMinus(THnSparse *h1);
void Set4DCorrectionsAll(THnSparse *h1);
void Set4DCorrectionsLambdas(THnSparse *h1);
void Set4DCorrectionsLambdasMinus(THnSparse *h1);
//Special MC analysis for pi,K,p,e slected by PDG code -->
void SetPionAnalysis(Bool_t aSetPionAna);
void SetKaonAnalysis(Bool_t aSetKaonAna);
void SetProtonAnalysis(Bool_t aSetProtonAna);
void SetElectronAnalysis(Bool_t aSetElectronAna);
void SetDeuteronAnalysis(Bool_t aSetDeuteronAna);
void SetTritonAnalysis(Bool_t aSetTritonAna);
void SetHe3Analysis(Bool_t aSetHe3Ana);
void SetAlphaAnalysis(Bool_t aSetAlphaAna);
//Special MC analysis for pi,K,p,e slected by PDG code <--
protected:
virtual AliFemtoEvent *CopyAODtoFemtoEvent();
virtual AliFemtoTrack *CopyAODtoFemtoTrack(AliAODTrack *tAodTrack
// AliPWG2AODTrack *tPWG2AODTrack
);
virtual AliFemtoV0 *CopyAODtoFemtoV0(AliAODv0 *tAODv0);
virtual AliFemtoXi *CopyAODtoFemtoXi(AliAODcascade *tAODxi);
virtual void CopyPIDtoFemtoTrack(AliAODTrack *tAodTrack, AliFemtoTrack *tFemtoTrack);
int fNumberofEvent; ///< number of Events in AOD file
int fCurEvent; ///< number of current event
AliAODEvent *fEvent; ///< AOD event
TBits fAllTrue; ///< Bit set with all true bits
TBits fAllFalse; ///< Bit set with all false bits
UInt_t fFilterBit; ///< Bitmap bit for AOD filters
UInt_t fFilterMask;
// TClonesArray* fPWG2AODTracks; // Link to PWG2 specific AOD information (if it exists)
unsigned char fReadMC; ///< Attempt to read the MC information from the AOD
unsigned char fReadV0; ///< Read V0 information from the AOD and put it into V0Collection
unsigned char fReadCascade; ///< Read Cascade information from the AOD and put it into V0Collection
unsigned char fUsePreCent; ///< Use centrality pre-selection to speed up analysis
EstEventMult fEstEventMult; ///< Type of the event multiplicity estimator
double fCentRange[2]; ///< Centrality pre-selection range
AliAODpidUtil *fAODpidUtil;
AliAODHeader *fAODheader;
AliAnalysisUtils *fAnaUtils;
AliEventCuts *fEventCuts;
Bool_t fUseAliEventCuts;
/// Read generated particle info of "low quality" MC tracks
/// (i.e. tracks with negative labels)
Bool_t fReadFullMCData;
private:
AliAODMCParticle *GetParticleWithLabel(TClonesArray *mcP, Int_t aLabel);
string fInputFile; ///< name of input file with AOD filenames
TChain *fTree; ///< AOD tree
TFile *fAodFile; ///< AOD file
int fMagFieldSign; ///< Magnetic field sign
Bool_t fisEPVZ; ///< to get event plane angle from VZERO
Bool_t fpA2013; ///< analysis on pA 2013 data
Bool_t fisPileUp; ///< pile up rejection on?
Bool_t fCascadePileUpRemoval;//pile-up removal for cascades (its+tof hits for pos, neg and bac tracks)
Bool_t fV0PileUpRemoval;//pile-up removal for V0s
Bool_t fTrackPileUpRemoval;//pile-up removal for tracks (its+tof hits of tracks)
Bool_t fMVPlp; ///< multi-vertex pileup rejection?
Bool_t fOutOfBunchPlp; ///out-of-bunch pileup rejection
Int_t fMinVtxContr; ///< no of contributors for pA 2013 data
Int_t fMinPlpContribMV; ///< no of contributors for multivertex pile-up rejection
Int_t fMinPlpContribSPD; ///< no of contributors for SPD pile-up rejection
Int_t fDCAglobalTrack; ///< to get DCA from global tracks instead of TPC-only
Bool_t fFlatCent; ///< Boolean determining if the user should flatten the centrality
Bool_t fPrimaryVertexCorrectionTPCPoints; ///< Boolean determining if the reader should shift all TPC points to be relative to event vertex
Double_t fShiftPosition; ///< radius at which the spatial position of the track in the shifted coordinate system is calculated
TH1D *f1DcorrectionsPions; ///<file with corrections, pT dependant
TH1D *f1DcorrectionsKaons; ///<file with corrections, pT dependant
TH1D *f1DcorrectionsProtons; ///<file with corrections, pT dependant
TH1D *f1DcorrectionsPionsMinus; ///<file with corrections, pT dependant
TH1D *f1DcorrectionsKaonsMinus; ///<file with corrections, pT dependant
TH1D *f1DcorrectionsProtonsMinus; ///<file with corrections, pT dependant
//
TH1D *f1DcorrectionsDeuterons; ///<file with corrections, pT dependant
TH1D *f1DcorrectionsTritons; ///<file with corrections, pT dependant
TH1D *f1DcorrectionsHe3s; ///<file with corrections, pT dependant
TH1D *f1DcorrectionsAlphas; ///<file with corrections, pT dependant
TH1D *f1DcorrectionsDeuteronsMinus; ///<file with corrections, pT dependant
TH1D *f1DcorrectionsTritonsMinus; ///<file with corrections, pT dependant
TH1D *f1DcorrectionsHe3sMinus; ///<file with corrections, pT dependant
TH1D *f1DcorrectionsAlphasMinus; ///<file with corrections, pT dependant
//
TH1D *f1DcorrectionsAll; ///<file with corrections, pT dependant
TH1D *f1DcorrectionsLambdas; ///<file with corrections, pT dependant
TH1D *f1DcorrectionsLambdasMinus; ///<file with corrections, pT dependant
TH1D *f1DcorrectionsXiPlus; ///<file with corrections, pT dependant
TH1D *f1DcorrectionsXiMinus; ///<file with corrections, pT dependant
THnSparse *f4DcorrectionsPions; ///<file with corrections, pT dependant
THnSparse *f4DcorrectionsKaons; ///<file with corrections, pT dependant
THnSparse *f4DcorrectionsProtons; ///<file with corrections, pT dependant
THnSparse *f4DcorrectionsPionsMinus; ///<file with corrections, pT dependant
THnSparse *f4DcorrectionsKaonsMinus; ///<file with corrections, pT dependant
THnSparse *f4DcorrectionsProtonsMinus; ///<file with corrections, pT dependant
THnSparse *f4DcorrectionsAll; ///<file with corrections, pT dependant
THnSparse *f4DcorrectionsLambdas; ///<file with corrections, pT dependant
THnSparse *f4DcorrectionsLambdasMinus; ///<file with corrections, pT dependant
//Special MC analysis for pi,K,p,e slected by PDG code -->
Bool_t fIsKaonAnalysis; // switch for Kaon analysis
Bool_t fIsProtonAnalysis; // switch for Proton analysis
Bool_t fIsPionAnalysis; // switch for Pion analysis
Bool_t fIsElectronAnalysis; // e+e- are taken (for gamma cut tuning)
//Special MC analysis for pi,K,p,e slected by PDG code <--
//
Bool_t fIsDeuteronAnalysis;
Bool_t fIsTritonAnalysis;
Bool_t fIsHe3Analysis;
Bool_t fIsAlphaAnalysis;
//
#ifdef __ROOT__
/// \cond CLASSIMP
ClassDef(AliFemtoEventReaderAOD, 13);
/// \endcond
#endif
};
inline void AliFemtoEventReaderAOD::SetReadFullMCData(bool read)
{ fReadFullMCData = read; }
inline bool AliFemtoEventReaderAOD::GetReadFullMCData() const
{ return fReadFullMCData; }
#endif
|
amatyja/AliPhysics
|
PWGCF/FEMTOSCOPY/AliFemto/AliFemtoEventReaderAOD.h
|
C
|
bsd-3-clause
| 12,155 |
<?php
namespace Universal\Container;
/*
* This file is part of the {{ }} package.
*
* (c) Yo-An Lin <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
class FooObjectBuilder
{
public $i = 1;
public function __invoke()
{
return 'foo' . $this->i++;
}
}
use Universal\Container\ObjectContainer;
class ObjectContainerTest extends \PHPUnit\Framework\TestCase
{
public function testSingletonBuilder()
{
$container = new ObjectContainer;
$container->std = function() {
return new \stdClass;
};
$this->assertInstanceOf('stdClass', $container->std);
$this->assertSame( $container->std , $container->std );
}
public function testFactoryBuilder()
{
$container = new ObjectContainer;
$container->factory('std',function($args) {
return $args;
});
$a = $container->getObject('std',[1]);
$this->assertEquals(1,$a);
$b = $container->getObject('std',[2]);
$this->assertEquals(2,$b);
}
public function testCallableObject()
{
$container = new ObjectContainer;
$container->factory('foo', new FooObjectBuilder);
$foo = $container->getObject('foo');
$this->assertEquals('foo1',$foo);
$this->assertEquals('foo2',$container->foo);
$this->assertEquals('foo3',$container->foo);
}
}
|
c9s/Universal
|
src/Container/ObjectContainerTest.php
|
PHP
|
bsd-3-clause
| 1,515 |
/*
* Copyright (c) 2016, Zolertia - http://www.zolertia.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
/*---------------------------------------------------------------------------*/
/**
* \addtogroup remote-power-mgmt-revb-test
* @{
*
* Test the RE-Mote's power management features, shutdown mode and battery
* management.
*
* @{
*
* \author
* Aitor Mejias <[email protected]>
* Antonio Lignan <[email protected]>
*/
/*---------------------------------------------------------------------------*/
#include "contiki.h"
#include "cpu.h"
#include "sys/process.h"
#include "dev/leds.h"
#include "dev/sys-ctrl.h"
#include "lib/list.h"
#include "power-mgmt.h"
#include "rtcc.h"
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
/*---------------------------------------------------------------------------*/
static struct etimer et;
/*---------------------------------------------------------------------------*/
/* RE-Mote revision B, low-power PIC version */
#define PM_EXPECTED_VERSION 0x20
/*---------------------------------------------------------------------------*/
#ifndef DATE
#define DATE "Unknown"
#endif
/*---------------------------------------------------------------------------*/
#define TEST_LEDS_FAIL leds_off(LEDS_ALL); \
leds_on(LEDS_RED); \
PROCESS_EXIT();
/*---------------------------------------------------------------------------*/
#define TEST_ALARM_SECOND 15
/*---------------------------------------------------------------------------*/
PROCESS(test_remote_pm, "RE-Mote rev.B Power Management Test");
AUTOSTART_PROCESSES(&test_remote_pm);
/*---------------------------------------------------------------------------*/
static uint8_t rtc_buffer[sizeof(simple_td_map)];
static simple_td_map *simple_td = (simple_td_map *)rtc_buffer;
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(test_remote_pm, ev, data)
{
static uint8_t aux;
static uint16_t voltage;
static uint32_t cycles;
static char *next;
PROCESS_BEGIN();
aux = 0;
cycles = 0;
/* Initialize the power management block and signal the low-power PIC */
if(pm_enable() != PM_SUCCESS) {
printf("PM: Failed to initialize\n");
TEST_LEDS_FAIL;
}
printf("PM: enabled!\n");
/* Retrieve the firmware version and check expected */
if((pm_get_fw_ver(&aux) == PM_ERROR) ||
(aux != PM_EXPECTED_VERSION)) {
printf("PM: unexpected version 0x%02X\n", aux);
TEST_LEDS_FAIL;
}
printf("PM: firmware version 0x%02X OK\n", aux);
/* Read the battery voltage level */
if(pm_get_voltage(&voltage) != PM_SUCCESS) {
printf("PM: error retrieving voltage\n");
TEST_LEDS_FAIL;
}
printf("PM: Voltage (raw) = %u\n", voltage);
/* Note: if running the following test while the RE-Mote is powered over USB
* will show the command execution, but it will not put the board in shutdown
* mode. If powering the RE-Mote with an external battery the shutdown mode
* will operate as intended, and the RE-Mote will restart and run the tests
* from the start after waking-up off the shutdown mode.
*
* The first test shows how to use the "soft" shutdown mode, being the low
* power PIC the one counting cycles and restarting the system off shutdown
* mode.
*
* Each restart cycle is tracked by the low-power PIC, we can use this value
* to determine how many times we have entered shutdown mode, thus choosing
* a specific configuration or behaviour. For the next examples we are going
* to trigger a "soft" mode each even number, and "hard" if odd.
*/
cycles = pm_get_num_cycles();
printf("PM: cycle number %lu\n", cycles);
if((cycles % 2) == 0) {
/* Set the timeout */
if(pm_set_timeout(PM_SOFT_SHTDN_5_7_SEC) != PM_SUCCESS) {
printf("PM: error setting timeout for soft shutdown mode\n");
TEST_LEDS_FAIL;
}
printf("PM: Soft shutdown, timeout set to %lu\n", pm_get_timeout());
leds_off(LEDS_ALL);
leds_on(LEDS_PURPLE);
/* Wait just enough to be able to check the LED result */
etimer_set(&et, CLOCK_SECOND * 3);
PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));
/* Enter soft shut*/
if(pm_shutdown_now(PM_SOFT_SLEEP_CONFIG) == PM_SUCCESS) {
printf("PM: Good night!\n");
} else {
printf("PM: error shutting down the system!\n");
TEST_LEDS_FAIL;
}
/* Exit and wait the next cycle */
PROCESS_EXIT();
}
/* Configure the RTCC to schedule a "hard" restart of the shutdown mode,
* waking up from a RTCC interrupt to the low-power PIC
*/
printf("PM: System date: %s\n", DATE);
if(strcmp("Unknown", DATE) == 0) {
printf("PM: could not retrieve date from system\n");
TEST_LEDS_FAIL;
}
/* Configure RTC and return structure with all parameters */
rtcc_init();
/* Configure the RTC with the current values */
simple_td->weekdays = (uint8_t)strtol(DATE, &next, 10);
simple_td->day = (uint8_t)strtol(next, &next, 10);
simple_td->months = (uint8_t)strtol(next, &next, 10);
simple_td->years = (uint8_t)strtol(next, &next, 10);
simple_td->hours = (uint8_t)strtol(next, &next, 10);
simple_td->minutes = (uint8_t)strtol(next, &next, 10);
simple_td->seconds = (uint8_t)strtol(next, NULL, 10);
simple_td->miliseconds = 0;
simple_td->mode = RTCC_24H_MODE;
simple_td->century = RTCC_CENTURY_20XX;
if(rtcc_set_time_date(simple_td) == AB08_ERROR) {
printf("PM: Time and date configuration failed\n");
TEST_LEDS_FAIL;
} else {
if(rtcc_get_time_date(simple_td) == AB08_ERROR) {
printf("PM: Couldn't read time and date\n");
TEST_LEDS_FAIL;
}
}
printf("PM: Configured time: ");
rtcc_print(RTCC_PRINT_DATE_DEC);
/* Configure the RTCC to trigger an alarm tick */
printf("\nPM: Setting an alarm to tick in %u seconds\n", TEST_ALARM_SECOND);
if(rtcc_date_increment_seconds(simple_td, TEST_ALARM_SECOND) == AB08_ERROR) {
printf("PM: could not increment the next alarm date\n");
TEST_LEDS_FAIL;
}
/* Set the timeout to zero to avoid the PIC being awake while waiting for the
* RTCC system to kick-in
*/
if(pm_set_timeout(0x00) != PM_SUCCESS) {
printf("PM: couldn't clear the shutdown period\n");
TEST_LEDS_FAIL;
}
/* We use the RTCC_REPEAT_DAY as we want the RTCC to match the given date */
if(rtcc_set_alarm_time_date(simple_td, RTCC_ALARM_ON, RTCC_REPEAT_DAY,
RTCC_TRIGGER_INT2) == AB08_ERROR) {
printf("PM: couldn't set the alarm\n");
TEST_LEDS_FAIL;
}
printf("PM: Alarm set to match: ");
rtcc_print(RTCC_PRINT_ALARM_DEC);
leds_off(LEDS_ALL);
leds_on(LEDS_BLUE);
etimer_set(&et, CLOCK_SECOND * 3);
PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));
if(pm_shutdown_now(PM_HARD_SLEEP_CONFIG) == PM_SUCCESS) {
printf("PM: good night!\n");
} else {
printf("PM: error shutting down the system!\n");
TEST_LEDS_FAIL;
}
PROCESS_END();
}
/*---------------------------------------------------------------------------*/
/**
* @}
* @}
*/
|
miarcompanies/sdn-wise-contiki
|
contiki/examples/zolertia/zoul/rev-b/test-power-mgmt.c
|
C
|
bsd-3-clause
| 8,670 |
#include <sys/klog.h>
#include <sys/libkern.h>
#include <sys/ktest.h>
#include <sys/malloc.h>
#include <sys/taskqueue.h>
static unsigned counter;
static void func(void *arg) {
int n = *(int *)arg;
/* Access to counter is intentionally not synchronized. */
counter += n;
}
static int test_taskqueue(void) {
taskqueue_t tq;
int N[] = {1, 2, 3};
task_t task0 = TASK_INIT(func, &N[0]);
task_t task1 = TASK_INIT(func, &N[1]);
task_t task2 = TASK_INIT(func, &N[2]);
counter = 0;
taskqueue_init(&tq);
taskqueue_add(&tq, &task0);
taskqueue_add(&tq, &task1);
taskqueue_add(&tq, &task2);
taskqueue_run(&tq);
assert(counter == 1 + 2 + 3);
taskqueue_destroy(&tq);
return KTEST_SUCCESS;
}
KTEST_ADD(taskqueue, test_taskqueue, 0);
|
cahirwpz/mimiker
|
sys/tests/taskqueue.c
|
C
|
bsd-3-clause
| 763 |
{% extends "base.html" %}
{% block content %}
<h3>Contact Information</h3>
<p>Thank you for contacting us.</p>
<p>We will attempt to get back to you within 48 hours</p>
{% endblock content %}
|
HEG-Arc/Appagoo
|
appagoo/templates/thankyou.html
|
HTML
|
bsd-3-clause
| 208 |
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkCanvas.h"
#include "SkClipOp.h"
#include "SkClipOpPriv.h"
#include "SkClipStack.h"
#include "SkImageInfo.h"
#include "SkMatrix.h"
#include "SkPath.h"
#include "SkPoint.h"
#include "SkRRect.h"
#include "SkRandom.h"
#include "SkRect.h"
#include "SkRefCnt.h"
#include "SkRegion.h"
#include "SkScalar.h"
#include "SkSize.h"
#include "SkString.h"
#include "SkSurface.h"
#include "SkTemplates.h"
#include "SkTypes.h"
#include "Test.h"
#include "GrCaps.h"
#include "GrClip.h"
#include "GrClipStackClip.h"
#include "GrConfig.h"
#include "GrContext.h"
#include "GrContextFactory.h"
#include "GrContextPriv.h"
#include "GrReducedClip.h"
#include "GrResourceCache.h"
#include "GrResourceKey.h"
#include "GrSurfaceProxyPriv.h"
#include "GrTexture.h"
#include "GrTextureProxy.h"
typedef GrReducedClip::ElementList ElementList;
typedef GrReducedClip::InitialState InitialState;
#include <cstring>
#include <new>
static void test_assign_and_comparison(skiatest::Reporter* reporter) {
SkClipStack s;
bool doAA = false;
REPORTER_ASSERT(reporter, 0 == s.getSaveCount());
// Build up a clip stack with a path, an empty clip, and a rect.
s.save();
REPORTER_ASSERT(reporter, 1 == s.getSaveCount());
SkPath p;
p.moveTo(5, 6);
p.lineTo(7, 8);
p.lineTo(5, 9);
p.close();
s.clipPath(p, SkMatrix::I(), kIntersect_SkClipOp, doAA);
s.save();
REPORTER_ASSERT(reporter, 2 == s.getSaveCount());
SkRect r = SkRect::MakeLTRB(1, 2, 3, 4);
s.clipRect(r, SkMatrix::I(), kIntersect_SkClipOp, doAA);
r = SkRect::MakeLTRB(10, 11, 12, 13);
s.clipRect(r, SkMatrix::I(), kIntersect_SkClipOp, doAA);
s.save();
REPORTER_ASSERT(reporter, 3 == s.getSaveCount());
r = SkRect::MakeLTRB(14, 15, 16, 17);
s.clipRect(r, SkMatrix::I(), kUnion_SkClipOp, doAA);
// Test that assignment works.
SkClipStack copy = s;
REPORTER_ASSERT(reporter, s == copy);
// Test that different save levels triggers not equal.
s.restore();
REPORTER_ASSERT(reporter, 2 == s.getSaveCount());
REPORTER_ASSERT(reporter, s != copy);
// Test that an equal, but not copied version is equal.
s.save();
REPORTER_ASSERT(reporter, 3 == s.getSaveCount());
r = SkRect::MakeLTRB(14, 15, 16, 17);
s.clipRect(r, SkMatrix::I(), kUnion_SkClipOp, doAA);
REPORTER_ASSERT(reporter, s == copy);
// Test that a different op on one level triggers not equal.
s.restore();
REPORTER_ASSERT(reporter, 2 == s.getSaveCount());
s.save();
REPORTER_ASSERT(reporter, 3 == s.getSaveCount());
r = SkRect::MakeLTRB(14, 15, 16, 17);
s.clipRect(r, SkMatrix::I(), kIntersect_SkClipOp, doAA);
REPORTER_ASSERT(reporter, s != copy);
// Test that version constructed with rect-path rather than a rect is still considered equal.
s.restore();
s.save();
SkPath rp;
rp.addRect(r);
s.clipPath(rp, SkMatrix::I(), kUnion_SkClipOp, doAA);
REPORTER_ASSERT(reporter, s == copy);
// Test that different rects triggers not equal.
s.restore();
REPORTER_ASSERT(reporter, 2 == s.getSaveCount());
s.save();
REPORTER_ASSERT(reporter, 3 == s.getSaveCount());
r = SkRect::MakeLTRB(24, 25, 26, 27);
s.clipRect(r, SkMatrix::I(), kUnion_SkClipOp, doAA);
REPORTER_ASSERT(reporter, s != copy);
// Sanity check
s.restore();
REPORTER_ASSERT(reporter, 2 == s.getSaveCount());
copy.restore();
REPORTER_ASSERT(reporter, 2 == copy.getSaveCount());
REPORTER_ASSERT(reporter, s == copy);
s.restore();
REPORTER_ASSERT(reporter, 1 == s.getSaveCount());
copy.restore();
REPORTER_ASSERT(reporter, 1 == copy.getSaveCount());
REPORTER_ASSERT(reporter, s == copy);
// Test that different paths triggers not equal.
s.restore();
REPORTER_ASSERT(reporter, 0 == s.getSaveCount());
s.save();
REPORTER_ASSERT(reporter, 1 == s.getSaveCount());
p.addRect(r);
s.clipPath(p, SkMatrix::I(), kIntersect_SkClipOp, doAA);
REPORTER_ASSERT(reporter, s != copy);
}
static void assert_count(skiatest::Reporter* reporter, const SkClipStack& stack,
int count) {
SkClipStack::B2TIter iter(stack);
int counter = 0;
while (iter.next()) {
counter += 1;
}
REPORTER_ASSERT(reporter, count == counter);
}
// Exercise the SkClipStack's bottom to top and bidirectional iterators
// (including the skipToTopmost functionality)
static void test_iterators(skiatest::Reporter* reporter) {
SkClipStack stack;
static const SkRect gRects[] = {
{ 0, 0, 40, 40 },
{ 60, 0, 100, 40 },
{ 0, 60, 40, 100 },
{ 60, 60, 100, 100 }
};
for (size_t i = 0; i < SK_ARRAY_COUNT(gRects); i++) {
// the union op will prevent these from being fused together
stack.clipRect(gRects[i], SkMatrix::I(), kUnion_SkClipOp, false);
}
assert_count(reporter, stack, 4);
// bottom to top iteration
{
const SkClipStack::Element* element = nullptr;
SkClipStack::B2TIter iter(stack);
int i;
for (i = 0, element = iter.next(); element; ++i, element = iter.next()) {
REPORTER_ASSERT(reporter, SkClipStack::Element::DeviceSpaceType::kRect ==
element->getDeviceSpaceType());
REPORTER_ASSERT(reporter, element->getDeviceSpaceRect() == gRects[i]);
}
SkASSERT(i == 4);
}
// top to bottom iteration
{
const SkClipStack::Element* element = nullptr;
SkClipStack::Iter iter(stack, SkClipStack::Iter::kTop_IterStart);
int i;
for (i = 3, element = iter.prev(); element; --i, element = iter.prev()) {
REPORTER_ASSERT(reporter, SkClipStack::Element::DeviceSpaceType::kRect ==
element->getDeviceSpaceType());
REPORTER_ASSERT(reporter, element->getDeviceSpaceRect() == gRects[i]);
}
SkASSERT(i == -1);
}
// skipToTopmost
{
const SkClipStack::Element* element = nullptr;
SkClipStack::Iter iter(stack, SkClipStack::Iter::kBottom_IterStart);
element = iter.skipToTopmost(kUnion_SkClipOp);
REPORTER_ASSERT(reporter, SkClipStack::Element::DeviceSpaceType::kRect ==
element->getDeviceSpaceType());
REPORTER_ASSERT(reporter, element->getDeviceSpaceRect() == gRects[3]);
}
}
// Exercise the SkClipStack's getConservativeBounds computation
static void test_bounds(skiatest::Reporter* reporter,
SkClipStack::Element::DeviceSpaceType primType) {
static const int gNumCases = 20;
static const SkRect gAnswerRectsBW[gNumCases] = {
// A op B
{ 40, 40, 50, 50 },
{ 10, 10, 50, 50 },
{ 10, 10, 80, 80 },
{ 10, 10, 80, 80 },
{ 40, 40, 80, 80 },
// invA op B
{ 40, 40, 80, 80 },
{ 0, 0, 100, 100 },
{ 0, 0, 100, 100 },
{ 0, 0, 100, 100 },
{ 40, 40, 50, 50 },
// A op invB
{ 10, 10, 50, 50 },
{ 40, 40, 50, 50 },
{ 0, 0, 100, 100 },
{ 0, 0, 100, 100 },
{ 0, 0, 100, 100 },
// invA op invB
{ 0, 0, 100, 100 },
{ 40, 40, 80, 80 },
{ 0, 0, 100, 100 },
{ 10, 10, 80, 80 },
{ 10, 10, 50, 50 },
};
static const SkClipOp gOps[] = {
kIntersect_SkClipOp,
kDifference_SkClipOp,
kUnion_SkClipOp,
kXOR_SkClipOp,
kReverseDifference_SkClipOp
};
SkRect rectA, rectB;
rectA.iset(10, 10, 50, 50);
rectB.iset(40, 40, 80, 80);
SkRRect rrectA, rrectB;
rrectA.setOval(rectA);
rrectB.setRectXY(rectB, SkIntToScalar(1), SkIntToScalar(2));
SkPath pathA, pathB;
pathA.addRoundRect(rectA, SkIntToScalar(5), SkIntToScalar(5));
pathB.addRoundRect(rectB, SkIntToScalar(5), SkIntToScalar(5));
SkClipStack stack;
SkRect devClipBound;
bool isIntersectionOfRects = false;
int testCase = 0;
int numBitTests = SkClipStack::Element::DeviceSpaceType::kPath == primType ? 4 : 1;
for (int invBits = 0; invBits < numBitTests; ++invBits) {
for (size_t op = 0; op < SK_ARRAY_COUNT(gOps); ++op) {
stack.save();
bool doInvA = SkToBool(invBits & 1);
bool doInvB = SkToBool(invBits & 2);
pathA.setFillType(doInvA ? SkPath::kInverseEvenOdd_FillType :
SkPath::kEvenOdd_FillType);
pathB.setFillType(doInvB ? SkPath::kInverseEvenOdd_FillType :
SkPath::kEvenOdd_FillType);
switch (primType) {
case SkClipStack::Element::DeviceSpaceType::kEmpty:
SkDEBUGFAIL("Don't call this with kEmpty.");
break;
case SkClipStack::Element::DeviceSpaceType::kRect:
stack.clipRect(rectA, SkMatrix::I(), kIntersect_SkClipOp, false);
stack.clipRect(rectB, SkMatrix::I(), gOps[op], false);
break;
case SkClipStack::Element::DeviceSpaceType::kRRect:
stack.clipRRect(rrectA, SkMatrix::I(), kIntersect_SkClipOp, false);
stack.clipRRect(rrectB, SkMatrix::I(), gOps[op], false);
break;
case SkClipStack::Element::DeviceSpaceType::kPath:
stack.clipPath(pathA, SkMatrix::I(), kIntersect_SkClipOp, false);
stack.clipPath(pathB, SkMatrix::I(), gOps[op], false);
break;
}
REPORTER_ASSERT(reporter, !stack.isWideOpen());
REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID != stack.getTopmostGenID());
stack.getConservativeBounds(0, 0, 100, 100, &devClipBound,
&isIntersectionOfRects);
if (SkClipStack::Element::DeviceSpaceType::kRect == primType) {
REPORTER_ASSERT(reporter, isIntersectionOfRects ==
(gOps[op] == kIntersect_SkClipOp));
} else {
REPORTER_ASSERT(reporter, !isIntersectionOfRects);
}
SkASSERT(testCase < gNumCases);
REPORTER_ASSERT(reporter, devClipBound == gAnswerRectsBW[testCase]);
++testCase;
stack.restore();
}
}
}
// Test out 'isWideOpen' entry point
static void test_isWideOpen(skiatest::Reporter* reporter) {
{
// Empty stack is wide open. Wide open stack means that gen id is wide open.
SkClipStack stack;
REPORTER_ASSERT(reporter, stack.isWideOpen());
REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID());
}
SkRect rectA, rectB;
rectA.iset(10, 10, 40, 40);
rectB.iset(50, 50, 80, 80);
// Stack should initially be wide open
{
SkClipStack stack;
REPORTER_ASSERT(reporter, stack.isWideOpen());
REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID());
}
// Test out case where the user specifies a union that includes everything
{
SkClipStack stack;
SkPath clipA, clipB;
clipA.addRoundRect(rectA, SkIntToScalar(5), SkIntToScalar(5));
clipA.setFillType(SkPath::kInverseEvenOdd_FillType);
clipB.addRoundRect(rectB, SkIntToScalar(5), SkIntToScalar(5));
clipB.setFillType(SkPath::kInverseEvenOdd_FillType);
stack.clipPath(clipA, SkMatrix::I(), kReplace_SkClipOp, false);
stack.clipPath(clipB, SkMatrix::I(), kUnion_SkClipOp, false);
REPORTER_ASSERT(reporter, stack.isWideOpen());
REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID());
}
// Test out union w/ a wide open clip
{
SkClipStack stack;
stack.clipRect(rectA, SkMatrix::I(), kUnion_SkClipOp, false);
REPORTER_ASSERT(reporter, stack.isWideOpen());
REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID());
}
// Test out empty difference from a wide open clip
{
SkClipStack stack;
SkRect emptyRect;
emptyRect.setEmpty();
stack.clipRect(emptyRect, SkMatrix::I(), kDifference_SkClipOp, false);
REPORTER_ASSERT(reporter, stack.isWideOpen());
REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID());
}
// Test out return to wide open
{
SkClipStack stack;
stack.save();
stack.clipRect(rectA, SkMatrix::I(), kReplace_SkClipOp, false);
REPORTER_ASSERT(reporter, !stack.isWideOpen());
REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID != stack.getTopmostGenID());
stack.restore();
REPORTER_ASSERT(reporter, stack.isWideOpen());
REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID());
}
}
static int count(const SkClipStack& stack) {
SkClipStack::Iter iter(stack, SkClipStack::Iter::kTop_IterStart);
const SkClipStack::Element* element = nullptr;
int count = 0;
for (element = iter.prev(); element; element = iter.prev(), ++count) {
}
return count;
}
static void test_rect_inverse_fill(skiatest::Reporter* reporter) {
// non-intersecting rectangles
SkRect rect = SkRect::MakeLTRB(0, 0, 10, 10);
SkPath path;
path.addRect(rect);
path.toggleInverseFillType();
SkClipStack stack;
stack.clipPath(path, SkMatrix::I(), kIntersect_SkClipOp, false);
SkRect bounds;
SkClipStack::BoundsType boundsType;
stack.getBounds(&bounds, &boundsType);
REPORTER_ASSERT(reporter, SkClipStack::kInsideOut_BoundsType == boundsType);
REPORTER_ASSERT(reporter, bounds == rect);
}
static void test_rect_replace(skiatest::Reporter* reporter) {
SkRect rect = SkRect::MakeWH(100, 100);
SkRect rect2 = SkRect::MakeXYWH(50, 50, 100, 100);
SkRect bound;
SkClipStack::BoundsType type;
bool isIntersectionOfRects;
// Adding a new rect with the replace operator should not increase
// the stack depth. BW replacing BW.
{
SkClipStack stack;
REPORTER_ASSERT(reporter, 0 == count(stack));
stack.clipRect(rect, SkMatrix::I(), kReplace_SkClipOp, false);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.clipRect(rect, SkMatrix::I(), kReplace_SkClipOp, false);
REPORTER_ASSERT(reporter, 1 == count(stack));
}
// Adding a new rect with the replace operator should not increase
// the stack depth. AA replacing AA.
{
SkClipStack stack;
REPORTER_ASSERT(reporter, 0 == count(stack));
stack.clipRect(rect, SkMatrix::I(), kReplace_SkClipOp, true);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.clipRect(rect, SkMatrix::I(), kReplace_SkClipOp, true);
REPORTER_ASSERT(reporter, 1 == count(stack));
}
// Adding a new rect with the replace operator should not increase
// the stack depth. BW replacing AA replacing BW.
{
SkClipStack stack;
REPORTER_ASSERT(reporter, 0 == count(stack));
stack.clipRect(rect, SkMatrix::I(), kReplace_SkClipOp, false);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.clipRect(rect, SkMatrix::I(), kReplace_SkClipOp, true);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.clipRect(rect, SkMatrix::I(), kReplace_SkClipOp, false);
REPORTER_ASSERT(reporter, 1 == count(stack));
}
// Make sure replace clip rects don't collapse too much.
{
SkClipStack stack;
stack.clipRect(rect, SkMatrix::I(), kReplace_SkClipOp, false);
stack.clipRect(rect2, SkMatrix::I(), kIntersect_SkClipOp, false);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.save();
stack.clipRect(rect, SkMatrix::I(), kReplace_SkClipOp, false);
REPORTER_ASSERT(reporter, 2 == count(stack));
stack.getBounds(&bound, &type, &isIntersectionOfRects);
REPORTER_ASSERT(reporter, bound == rect);
stack.restore();
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.save();
stack.clipRect(rect, SkMatrix::I(), kReplace_SkClipOp, false);
stack.clipRect(rect, SkMatrix::I(), kReplace_SkClipOp, false);
REPORTER_ASSERT(reporter, 2 == count(stack));
stack.restore();
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.save();
stack.clipRect(rect, SkMatrix::I(), kReplace_SkClipOp, false);
stack.clipRect(rect2, SkMatrix::I(), kIntersect_SkClipOp, false);
stack.clipRect(rect, SkMatrix::I(), kReplace_SkClipOp, false);
REPORTER_ASSERT(reporter, 2 == count(stack));
stack.restore();
REPORTER_ASSERT(reporter, 1 == count(stack));
}
}
// Simplified path-based version of test_rect_replace.
static void test_path_replace(skiatest::Reporter* reporter) {
SkRect rect = SkRect::MakeWH(100, 100);
SkPath path;
path.addCircle(50, 50, 50);
// Replace operation doesn't grow the stack.
{
SkClipStack stack;
REPORTER_ASSERT(reporter, 0 == count(stack));
stack.clipPath(path, SkMatrix::I(), kReplace_SkClipOp, false);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.clipPath(path, SkMatrix::I(), kReplace_SkClipOp, false);
REPORTER_ASSERT(reporter, 1 == count(stack));
}
// Replacing rect with path.
{
SkClipStack stack;
stack.clipRect(rect, SkMatrix::I(), kReplace_SkClipOp, true);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.clipPath(path, SkMatrix::I(), kReplace_SkClipOp, true);
REPORTER_ASSERT(reporter, 1 == count(stack));
}
}
// Test out SkClipStack's merging of rect clips. In particular exercise
// merging of aa vs. bw rects.
static void test_rect_merging(skiatest::Reporter* reporter) {
SkRect overlapLeft = SkRect::MakeLTRB(10, 10, 50, 50);
SkRect overlapRight = SkRect::MakeLTRB(40, 40, 80, 80);
SkRect nestedParent = SkRect::MakeLTRB(10, 10, 90, 90);
SkRect nestedChild = SkRect::MakeLTRB(40, 40, 60, 60);
SkRect bound;
SkClipStack::BoundsType type;
bool isIntersectionOfRects;
// all bw overlapping - should merge
{
SkClipStack stack;
stack.clipRect(overlapLeft, SkMatrix::I(), kReplace_SkClipOp, false);
stack.clipRect(overlapRight, SkMatrix::I(), kIntersect_SkClipOp, false);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.getBounds(&bound, &type, &isIntersectionOfRects);
REPORTER_ASSERT(reporter, isIntersectionOfRects);
}
// all aa overlapping - should merge
{
SkClipStack stack;
stack.clipRect(overlapLeft, SkMatrix::I(), kReplace_SkClipOp, true);
stack.clipRect(overlapRight, SkMatrix::I(), kIntersect_SkClipOp, true);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.getBounds(&bound, &type, &isIntersectionOfRects);
REPORTER_ASSERT(reporter, isIntersectionOfRects);
}
// mixed overlapping - should _not_ merge
{
SkClipStack stack;
stack.clipRect(overlapLeft, SkMatrix::I(), kReplace_SkClipOp, true);
stack.clipRect(overlapRight, SkMatrix::I(), kIntersect_SkClipOp, false);
REPORTER_ASSERT(reporter, 2 == count(stack));
stack.getBounds(&bound, &type, &isIntersectionOfRects);
REPORTER_ASSERT(reporter, !isIntersectionOfRects);
}
// mixed nested (bw inside aa) - should merge
{
SkClipStack stack;
stack.clipRect(nestedParent, SkMatrix::I(), kReplace_SkClipOp, true);
stack.clipRect(nestedChild, SkMatrix::I(), kIntersect_SkClipOp, false);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.getBounds(&bound, &type, &isIntersectionOfRects);
REPORTER_ASSERT(reporter, isIntersectionOfRects);
}
// mixed nested (aa inside bw) - should merge
{
SkClipStack stack;
stack.clipRect(nestedParent, SkMatrix::I(), kReplace_SkClipOp, false);
stack.clipRect(nestedChild, SkMatrix::I(), kIntersect_SkClipOp, true);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.getBounds(&bound, &type, &isIntersectionOfRects);
REPORTER_ASSERT(reporter, isIntersectionOfRects);
}
// reverse nested (aa inside bw) - should _not_ merge
{
SkClipStack stack;
stack.clipRect(nestedChild, SkMatrix::I(), kReplace_SkClipOp, false);
stack.clipRect(nestedParent, SkMatrix::I(), kIntersect_SkClipOp, true);
REPORTER_ASSERT(reporter, 2 == count(stack));
stack.getBounds(&bound, &type, &isIntersectionOfRects);
REPORTER_ASSERT(reporter, !isIntersectionOfRects);
}
}
static void test_quickContains(skiatest::Reporter* reporter) {
SkRect testRect = SkRect::MakeLTRB(10, 10, 40, 40);
SkRect insideRect = SkRect::MakeLTRB(20, 20, 30, 30);
SkRect intersectingRect = SkRect::MakeLTRB(25, 25, 50, 50);
SkRect outsideRect = SkRect::MakeLTRB(0, 0, 50, 50);
SkRect nonIntersectingRect = SkRect::MakeLTRB(100, 100, 110, 110);
SkPath insideCircle;
insideCircle.addCircle(25, 25, 5);
SkPath intersectingCircle;
intersectingCircle.addCircle(25, 40, 10);
SkPath outsideCircle;
outsideCircle.addCircle(25, 25, 50);
SkPath nonIntersectingCircle;
nonIntersectingCircle.addCircle(100, 100, 5);
{
SkClipStack stack;
stack.clipRect(outsideRect, SkMatrix::I(), kDifference_SkClipOp, false);
// return false because quickContains currently does not care for kDifference_SkClipOp
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
// Replace Op tests
{
SkClipStack stack;
stack.clipRect(outsideRect, SkMatrix::I(), kReplace_SkClipOp, false);
REPORTER_ASSERT(reporter, true == stack.quickContains(testRect));
}
{
SkClipStack stack;
stack.clipRect(insideRect, SkMatrix::I(), kIntersect_SkClipOp, false);
stack.save(); // To prevent in-place substitution by replace OP
stack.clipRect(outsideRect, SkMatrix::I(), kReplace_SkClipOp, false);
REPORTER_ASSERT(reporter, true == stack.quickContains(testRect));
stack.restore();
}
{
SkClipStack stack;
stack.clipRect(outsideRect, SkMatrix::I(), kIntersect_SkClipOp, false);
stack.save(); // To prevent in-place substitution by replace OP
stack.clipRect(insideRect, SkMatrix::I(), kReplace_SkClipOp, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
stack.restore();
}
// Verify proper traversal of multi-element clip
{
SkClipStack stack;
stack.clipRect(insideRect, SkMatrix::I(), kIntersect_SkClipOp, false);
// Use a path for second clip to prevent in-place intersection
stack.clipPath(outsideCircle, SkMatrix::I(), kIntersect_SkClipOp, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
// Intersect Op tests with rectangles
{
SkClipStack stack;
stack.clipRect(outsideRect, SkMatrix::I(), kIntersect_SkClipOp, false);
REPORTER_ASSERT(reporter, true == stack.quickContains(testRect));
}
{
SkClipStack stack;
stack.clipRect(insideRect, SkMatrix::I(), kIntersect_SkClipOp, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
{
SkClipStack stack;
stack.clipRect(intersectingRect, SkMatrix::I(), kIntersect_SkClipOp, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
{
SkClipStack stack;
stack.clipRect(nonIntersectingRect, SkMatrix::I(), kIntersect_SkClipOp, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
// Intersect Op tests with circle paths
{
SkClipStack stack;
stack.clipPath(outsideCircle, SkMatrix::I(), kIntersect_SkClipOp, false);
REPORTER_ASSERT(reporter, true == stack.quickContains(testRect));
}
{
SkClipStack stack;
stack.clipPath(insideCircle, SkMatrix::I(), kIntersect_SkClipOp, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
{
SkClipStack stack;
stack.clipPath(intersectingCircle, SkMatrix::I(), kIntersect_SkClipOp, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
{
SkClipStack stack;
stack.clipPath(nonIntersectingCircle, SkMatrix::I(), kIntersect_SkClipOp, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
// Intersect Op tests with inverse filled rectangles
{
SkClipStack stack;
SkPath path;
path.addRect(outsideRect);
path.toggleInverseFillType();
stack.clipPath(path, SkMatrix::I(), kIntersect_SkClipOp, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
{
SkClipStack stack;
SkPath path;
path.addRect(insideRect);
path.toggleInverseFillType();
stack.clipPath(path, SkMatrix::I(), kIntersect_SkClipOp, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
{
SkClipStack stack;
SkPath path;
path.addRect(intersectingRect);
path.toggleInverseFillType();
stack.clipPath(path, SkMatrix::I(), kIntersect_SkClipOp, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
{
SkClipStack stack;
SkPath path;
path.addRect(nonIntersectingRect);
path.toggleInverseFillType();
stack.clipPath(path, SkMatrix::I(), kIntersect_SkClipOp, false);
REPORTER_ASSERT(reporter, true == stack.quickContains(testRect));
}
// Intersect Op tests with inverse filled circles
{
SkClipStack stack;
SkPath path = outsideCircle;
path.toggleInverseFillType();
stack.clipPath(path, SkMatrix::I(), kIntersect_SkClipOp, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
{
SkClipStack stack;
SkPath path = insideCircle;
path.toggleInverseFillType();
stack.clipPath(path, SkMatrix::I(), kIntersect_SkClipOp, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
{
SkClipStack stack;
SkPath path = intersectingCircle;
path.toggleInverseFillType();
stack.clipPath(path, SkMatrix::I(), kIntersect_SkClipOp, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
{
SkClipStack stack;
SkPath path = nonIntersectingCircle;
path.toggleInverseFillType();
stack.clipPath(path, SkMatrix::I(), kIntersect_SkClipOp, false);
REPORTER_ASSERT(reporter, true == stack.quickContains(testRect));
}
}
static void set_region_to_stack(const SkClipStack& stack, const SkIRect& bounds, SkRegion* region) {
region->setRect(bounds);
SkClipStack::Iter iter(stack, SkClipStack::Iter::kBottom_IterStart);
while (const SkClipStack::Element *element = iter.next()) {
SkRegion elemRegion;
SkRegion boundsRgn(bounds);
SkPath path;
switch (element->getDeviceSpaceType()) {
case SkClipStack::Element::DeviceSpaceType::kEmpty:
elemRegion.setEmpty();
break;
default:
element->asDeviceSpacePath(&path);
elemRegion.setPath(path, boundsRgn);
break;
}
region->op(elemRegion, (SkRegion::Op)element->getOp());
}
}
static void test_invfill_diff_bug(skiatest::Reporter* reporter) {
SkClipStack stack;
stack.clipRect({10, 10, 20, 20}, SkMatrix::I(), kIntersect_SkClipOp, false);
SkPath path;
path.addRect({30, 10, 40, 20});
path.setFillType(SkPath::kInverseWinding_FillType);
stack.clipPath(path, SkMatrix::I(), kDifference_SkClipOp, false);
REPORTER_ASSERT(reporter, SkClipStack::kEmptyGenID == stack.getTopmostGenID());
SkRect stackBounds;
SkClipStack::BoundsType stackBoundsType;
stack.getBounds(&stackBounds, &stackBoundsType);
REPORTER_ASSERT(reporter, stackBounds.isEmpty());
REPORTER_ASSERT(reporter, SkClipStack::kNormal_BoundsType == stackBoundsType);
SkRegion region;
set_region_to_stack(stack, {0, 0, 50, 30}, ®ion);
REPORTER_ASSERT(reporter, region.isEmpty());
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Functions that add a shape to the clip stack. The shape is computed from a rectangle.
// AA is always disabled since the clip stack reducer can cause changes in aa rasterization of the
// stack. A fractional edge repeated in different elements may be rasterized fewer times using the
// reduced stack.
typedef void (*AddElementFunc) (const SkRect& rect,
bool invert,
SkClipOp op,
SkClipStack* stack,
bool doAA);
static void add_round_rect(const SkRect& rect, bool invert, SkClipOp op, SkClipStack* stack,
bool doAA) {
SkScalar rx = rect.width() / 10;
SkScalar ry = rect.height() / 20;
if (invert) {
SkPath path;
path.addRoundRect(rect, rx, ry);
path.setFillType(SkPath::kInverseWinding_FillType);
stack->clipPath(path, SkMatrix::I(), op, doAA);
} else {
SkRRect rrect;
rrect.setRectXY(rect, rx, ry);
stack->clipRRect(rrect, SkMatrix::I(), op, doAA);
}
};
static void add_rect(const SkRect& rect, bool invert, SkClipOp op, SkClipStack* stack,
bool doAA) {
if (invert) {
SkPath path;
path.addRect(rect);
path.setFillType(SkPath::kInverseWinding_FillType);
stack->clipPath(path, SkMatrix::I(), op, doAA);
} else {
stack->clipRect(rect, SkMatrix::I(), op, doAA);
}
};
static void add_oval(const SkRect& rect, bool invert, SkClipOp op, SkClipStack* stack,
bool doAA) {
SkPath path;
path.addOval(rect);
if (invert) {
path.setFillType(SkPath::kInverseWinding_FillType);
}
stack->clipPath(path, SkMatrix::I(), op, doAA);
};
static void add_elem_to_stack(const SkClipStack::Element& element, SkClipStack* stack) {
switch (element.getDeviceSpaceType()) {
case SkClipStack::Element::DeviceSpaceType::kRect:
stack->clipRect(element.getDeviceSpaceRect(), SkMatrix::I(), element.getOp(),
element.isAA());
break;
case SkClipStack::Element::DeviceSpaceType::kRRect:
stack->clipRRect(element.getDeviceSpaceRRect(), SkMatrix::I(), element.getOp(),
element.isAA());
break;
case SkClipStack::Element::DeviceSpaceType::kPath:
stack->clipPath(element.getDeviceSpacePath(), SkMatrix::I(), element.getOp(),
element.isAA());
break;
case SkClipStack::Element::DeviceSpaceType::kEmpty:
SkDEBUGFAIL("Why did the reducer produce an explicit empty.");
stack->clipEmpty();
break;
}
}
static void test_reduced_clip_stack(skiatest::Reporter* reporter) {
// We construct random clip stacks, reduce them, and then rasterize both versions to verify that
// they are equal.
// All the clip elements will be contained within these bounds.
static const SkIRect kIBounds = SkIRect::MakeWH(100, 100);
static const SkRect kBounds = SkRect::Make(kIBounds);
enum {
kNumTests = 250,
kMinElemsPerTest = 1,
kMaxElemsPerTest = 50,
};
// min/max size of a clip element as a fraction of kBounds.
static const SkScalar kMinElemSizeFrac = SK_Scalar1 / 5;
static const SkScalar kMaxElemSizeFrac = SK_Scalar1;
static const SkClipOp kOps[] = {
kDifference_SkClipOp,
kIntersect_SkClipOp,
kUnion_SkClipOp,
kXOR_SkClipOp,
kReverseDifference_SkClipOp,
kReplace_SkClipOp,
};
// Replace operations short-circuit the optimizer. We want to make sure that we test this code
// path a little bit but we don't want it to prevent us from testing many longer traversals in
// the optimizer.
static const int kReplaceDiv = 4 * kMaxElemsPerTest;
// We want to test inverse fills. However, they are quite rare in practice so don't over do it.
static const SkScalar kFractionInverted = SK_Scalar1 / kMaxElemsPerTest;
static const SkScalar kFractionAntialiased = 0.25;
static const AddElementFunc kElementFuncs[] = {
add_rect,
add_round_rect,
add_oval,
};
SkRandom r;
for (int i = 0; i < kNumTests; ++i) {
SkString testCase;
testCase.printf("Iteration %d", i);
// Randomly generate a clip stack.
SkClipStack stack;
int numElems = r.nextRangeU(kMinElemsPerTest, kMaxElemsPerTest);
bool doAA = r.nextBiasedBool(kFractionAntialiased);
for (int e = 0; e < numElems; ++e) {
SkClipOp op = kOps[r.nextULessThan(SK_ARRAY_COUNT(kOps))];
if (op == kReplace_SkClipOp) {
if (r.nextU() % kReplaceDiv) {
--e;
continue;
}
}
// saves can change the clip stack behavior when an element is added.
bool doSave = r.nextBool();
SkSize size = SkSize::Make(
kBounds.width() * r.nextRangeScalar(kMinElemSizeFrac, kMaxElemSizeFrac),
kBounds.height() * r.nextRangeScalar(kMinElemSizeFrac, kMaxElemSizeFrac));
SkPoint xy = {r.nextRangeScalar(kBounds.fLeft, kBounds.fRight - size.fWidth),
r.nextRangeScalar(kBounds.fTop, kBounds.fBottom - size.fHeight)};
SkRect rect;
if (doAA) {
rect.setXYWH(xy.fX, xy.fY, size.fWidth, size.fHeight);
if (GrClip::IsPixelAligned(rect)) {
// Don't create an element that may accidentally become not antialiased.
rect.outset(0.5f, 0.5f);
}
SkASSERT(!GrClip::IsPixelAligned(rect));
} else {
rect.setXYWH(SkScalarFloorToScalar(xy.fX),
SkScalarFloorToScalar(xy.fY),
SkScalarCeilToScalar(size.fWidth),
SkScalarCeilToScalar(size.fHeight));
}
bool invert = r.nextBiasedBool(kFractionInverted);
kElementFuncs[r.nextULessThan(SK_ARRAY_COUNT(kElementFuncs))](rect, invert, op, &stack,
doAA);
if (doSave) {
stack.save();
}
}
auto context = GrContext::MakeMock(nullptr);
const GrCaps* caps = context->priv().caps();
// Zero the memory we will new the GrReducedClip into. This ensures the elements gen ID
// will be kInvalidGenID if left uninitialized.
SkAlignedSTStorage<1, GrReducedClip> storage;
memset(storage.get(), 0, sizeof(GrReducedClip));
GR_STATIC_ASSERT(0 == SkClipStack::kInvalidGenID);
// Get the reduced version of the stack.
SkRect queryBounds = kBounds;
queryBounds.outset(kBounds.width() / 2, kBounds.height() / 2);
const GrReducedClip* reduced = new (storage.get()) GrReducedClip(stack, queryBounds, caps);
REPORTER_ASSERT(reporter,
reduced->maskElements().isEmpty() ||
SkClipStack::kInvalidGenID != reduced->maskGenID(),
testCase.c_str());
if (!reduced->maskElements().isEmpty()) {
REPORTER_ASSERT(reporter, reduced->hasScissor(), testCase.c_str());
SkRect stackBounds;
SkClipStack::BoundsType stackBoundsType;
stack.getBounds(&stackBounds, &stackBoundsType);
REPORTER_ASSERT(reporter, reduced->maskRequiresAA() == doAA, testCase.c_str());
}
// Build a new clip stack based on the reduced clip elements
SkClipStack reducedStack;
if (GrReducedClip::InitialState::kAllOut == reduced->initialState()) {
// whether the result is bounded or not, the whole plane should start outside the clip.
reducedStack.clipEmpty();
}
for (ElementList::Iter iter(reduced->maskElements()); iter.get(); iter.next()) {
add_elem_to_stack(*iter.get(), &reducedStack);
}
SkIRect scissor = reduced->hasScissor() ? reduced->scissor() : kIBounds;
// GrReducedClipStack assumes that the final result is clipped to the returned bounds
reducedStack.clipDevRect(scissor, kIntersect_SkClipOp);
stack.clipDevRect(scissor, kIntersect_SkClipOp);
// convert both the original stack and reduced stack to SkRegions and see if they're equal
SkRegion region;
set_region_to_stack(stack, scissor, ®ion);
SkRegion reducedRegion;
set_region_to_stack(reducedStack, scissor, &reducedRegion);
REPORTER_ASSERT(reporter, region == reducedRegion, testCase.c_str());
reduced->~GrReducedClip();
}
}
#ifdef SK_BUILD_FOR_WIN
#define SUPPRESS_VISIBILITY_WARNING
#else
#define SUPPRESS_VISIBILITY_WARNING __attribute__((visibility("hidden")))
#endif
static void test_reduced_clip_stack_genid(skiatest::Reporter* reporter) {
{
SkClipStack stack;
stack.clipRect(SkRect::MakeXYWH(0, 0, 100, 100), SkMatrix::I(), kReplace_SkClipOp,
true);
stack.clipRect(SkRect::MakeXYWH(0, 0, SkScalar(50.3), SkScalar(50.3)), SkMatrix::I(),
kReplace_SkClipOp, true);
SkRect bounds = SkRect::MakeXYWH(0, 0, 100, 100);
auto context = GrContext::MakeMock(nullptr);
const GrCaps* caps = context->priv().caps();
SkAlignedSTStorage<1, GrReducedClip> storage;
memset(storage.get(), 0, sizeof(GrReducedClip));
GR_STATIC_ASSERT(0 == SkClipStack::kInvalidGenID);
const GrReducedClip* reduced = new (storage.get()) GrReducedClip(stack, bounds, caps);
REPORTER_ASSERT(reporter, reduced->maskElements().count() == 1);
// Clips will be cached based on the generation id. Make sure the gen id is valid.
REPORTER_ASSERT(reporter, SkClipStack::kInvalidGenID != reduced->maskGenID());
reduced->~GrReducedClip();
}
{
SkClipStack stack;
// Create a clip with following 25.3, 25.3 boxes which are 25 apart:
// A B
// C D
stack.clipRect(SkRect::MakeXYWH(0, 0, SkScalar(25.3), SkScalar(25.3)), SkMatrix::I(),
kReplace_SkClipOp, true);
uint32_t genIDA = stack.getTopmostGenID();
stack.clipRect(SkRect::MakeXYWH(50, 0, SkScalar(25.3), SkScalar(25.3)), SkMatrix::I(),
kUnion_SkClipOp, true);
uint32_t genIDB = stack.getTopmostGenID();
stack.clipRect(SkRect::MakeXYWH(0, 50, SkScalar(25.3), SkScalar(25.3)), SkMatrix::I(),
kUnion_SkClipOp, true);
uint32_t genIDC = stack.getTopmostGenID();
stack.clipRect(SkRect::MakeXYWH(50, 50, SkScalar(25.3), SkScalar(25.3)), SkMatrix::I(),
kUnion_SkClipOp, true);
uint32_t genIDD = stack.getTopmostGenID();
#define IXYWH SkIRect::MakeXYWH
#define XYWH SkRect::MakeXYWH
SkIRect stackBounds = IXYWH(0, 0, 76, 76);
// The base test is to test each rect in two ways:
// 1) The box dimensions. (Should reduce to "all in", no elements).
// 2) A bit over the box dimensions.
// In the case 2, test that the generation id is what is expected.
// The rects are of fractional size so that case 2 never gets optimized to an empty element
// list.
// Not passing in tighter bounds is tested for consistency.
static const struct SUPPRESS_VISIBILITY_WARNING {
SkRect testBounds;
int reducedClipCount;
uint32_t reducedGenID;
InitialState initialState;
SkIRect clipIRect;
// parameter.
} testCases[] = {
// Rect A.
{ XYWH(0, 0, 25, 25), 0, SkClipStack::kInvalidGenID, GrReducedClip::InitialState::kAllIn, IXYWH(0, 0, 25, 25) },
{ XYWH(0.1f, 0.1f, 25.1f, 25.1f), 0, SkClipStack::kInvalidGenID, GrReducedClip::InitialState::kAllIn, IXYWH(0, 0, 26, 26) },
{ XYWH(0, 0, 27, 27), 1, genIDA, GrReducedClip::InitialState::kAllOut, IXYWH(0, 0, 26, 26)},
// Rect B.
{ XYWH(50, 0, 25, 25), 0, SkClipStack::kInvalidGenID, GrReducedClip::InitialState::kAllIn, IXYWH(50, 0, 25, 25) },
{ XYWH(50, 0, 25.3f, 25.3f), 0, SkClipStack::kInvalidGenID, GrReducedClip::InitialState::kAllIn, IXYWH(50, 0, 26, 26) },
{ XYWH(50, 0, 27, 27), 1, genIDB, GrReducedClip::InitialState::kAllOut, IXYWH(50, 0, 26, 27) },
// Rect C.
{ XYWH(0, 50, 25, 25), 0, SkClipStack::kInvalidGenID, GrReducedClip::InitialState::kAllIn, IXYWH(0, 50, 25, 25) },
{ XYWH(0.2f, 50.1f, 25.1f, 25.2f), 0, SkClipStack::kInvalidGenID, GrReducedClip::InitialState::kAllIn, IXYWH(0, 50, 26, 26) },
{ XYWH(0, 50, 27, 27), 1, genIDC, GrReducedClip::InitialState::kAllOut, IXYWH(0, 50, 27, 26) },
// Rect D.
{ XYWH(50, 50, 25, 25), 0, SkClipStack::kInvalidGenID, GrReducedClip::InitialState::kAllIn, IXYWH(50, 50, 25, 25)},
{ XYWH(50.3f, 50.3f, 25, 25), 0, SkClipStack::kInvalidGenID, GrReducedClip::InitialState::kAllIn, IXYWH(50, 50, 26, 26)},
{ XYWH(50, 50, 27, 27), 1, genIDD, GrReducedClip::InitialState::kAllOut, IXYWH(50, 50, 26, 26)},
// Other tests:
{ XYWH(0, 0, 100, 100), 4, genIDD, GrReducedClip::InitialState::kAllOut, stackBounds },
// Rect in the middle, touches none.
{ XYWH(26, 26, 24, 24), 0, SkClipStack::kInvalidGenID, GrReducedClip::InitialState::kAllOut, IXYWH(26, 26, 24, 24) },
// Rect in the middle, touches all the rects. GenID is the last rect.
{ XYWH(24, 24, 27, 27), 4, genIDD, GrReducedClip::InitialState::kAllOut, IXYWH(24, 24, 27, 27) },
};
#undef XYWH
#undef IXYWH
auto context = GrContext::MakeMock(nullptr);
const GrCaps* caps = context->priv().caps();
for (size_t i = 0; i < SK_ARRAY_COUNT(testCases); ++i) {
const GrReducedClip reduced(stack, testCases[i].testBounds, caps);
REPORTER_ASSERT(reporter, reduced.maskElements().count() ==
testCases[i].reducedClipCount);
SkASSERT(reduced.maskElements().count() == testCases[i].reducedClipCount);
if (reduced.maskElements().count()) {
REPORTER_ASSERT(reporter, reduced.maskGenID() == testCases[i].reducedGenID);
SkASSERT(reduced.maskGenID() == testCases[i].reducedGenID);
}
REPORTER_ASSERT(reporter, reduced.initialState() == testCases[i].initialState);
SkASSERT(reduced.initialState() == testCases[i].initialState);
REPORTER_ASSERT(reporter, reduced.hasScissor());
SkASSERT(reduced.hasScissor());
REPORTER_ASSERT(reporter, reduced.scissor() == testCases[i].clipIRect);
SkASSERT(reduced.scissor() == testCases[i].clipIRect);
}
}
}
static void test_reduced_clip_stack_no_aa_crash(skiatest::Reporter* reporter) {
SkClipStack stack;
stack.clipDevRect(SkIRect::MakeXYWH(0, 0, 100, 100), kReplace_SkClipOp);
stack.clipDevRect(SkIRect::MakeXYWH(0, 0, 50, 50), kReplace_SkClipOp);
SkRect bounds = SkRect::MakeXYWH(0, 0, 100, 100);
auto context = GrContext::MakeMock(nullptr);
const GrCaps* caps = context->priv().caps();
// At the time, this would crash.
const GrReducedClip reduced(stack, bounds, caps);
REPORTER_ASSERT(reporter, reduced.maskElements().isEmpty());
}
enum class ClipMethod {
kSkipDraw,
kIgnoreClip,
kScissor,
kAAElements
};
static void test_aa_query(skiatest::Reporter* reporter, const SkString& testName,
const SkClipStack& stack, const SkMatrix& queryXform,
const SkRect& preXformQuery, ClipMethod expectedMethod,
int numExpectedElems = 0) {
auto context = GrContext::MakeMock(nullptr);
const GrCaps* caps = context->priv().caps();
SkRect queryBounds;
queryXform.mapRect(&queryBounds, preXformQuery);
const GrReducedClip reduced(stack, queryBounds, caps);
SkClipStack::BoundsType stackBoundsType;
SkRect stackBounds;
stack.getBounds(&stackBounds, &stackBoundsType);
switch (expectedMethod) {
case ClipMethod::kSkipDraw:
SkASSERT(0 == numExpectedElems);
REPORTER_ASSERT(reporter, reduced.maskElements().isEmpty(), testName.c_str());
REPORTER_ASSERT(reporter,
GrReducedClip::InitialState::kAllOut == reduced.initialState(),
testName.c_str());
return;
case ClipMethod::kIgnoreClip:
SkASSERT(0 == numExpectedElems);
REPORTER_ASSERT(
reporter,
!reduced.hasScissor() || GrClip::IsInsideClip(reduced.scissor(), queryBounds),
testName.c_str());
REPORTER_ASSERT(reporter, reduced.maskElements().isEmpty(), testName.c_str());
REPORTER_ASSERT(reporter,
GrReducedClip::InitialState::kAllIn == reduced.initialState(),
testName.c_str());
return;
case ClipMethod::kScissor: {
SkASSERT(SkClipStack::kNormal_BoundsType == stackBoundsType);
SkASSERT(0 == numExpectedElems);
SkIRect expectedScissor;
stackBounds.round(&expectedScissor);
REPORTER_ASSERT(reporter, reduced.maskElements().isEmpty(), testName.c_str());
REPORTER_ASSERT(reporter, reduced.hasScissor(), testName.c_str());
REPORTER_ASSERT(reporter, expectedScissor == reduced.scissor(), testName.c_str());
REPORTER_ASSERT(reporter,
GrReducedClip::InitialState::kAllIn == reduced.initialState(),
testName.c_str());
return;
}
case ClipMethod::kAAElements: {
SkIRect expectedClipIBounds = GrClip::GetPixelIBounds(queryBounds);
if (SkClipStack::kNormal_BoundsType == stackBoundsType) {
SkAssertResult(expectedClipIBounds.intersect(GrClip::GetPixelIBounds(stackBounds)));
}
REPORTER_ASSERT(reporter, numExpectedElems == reduced.maskElements().count(),
testName.c_str());
REPORTER_ASSERT(reporter, reduced.hasScissor(), testName.c_str());
REPORTER_ASSERT(reporter, expectedClipIBounds == reduced.scissor(), testName.c_str());
REPORTER_ASSERT(reporter,
reduced.maskElements().isEmpty() || reduced.maskRequiresAA(),
testName.c_str());
break;
}
}
}
static void test_reduced_clip_stack_aa(skiatest::Reporter* reporter) {
constexpr SkScalar IL = 2, IT = 1, IR = 6, IB = 7; // Pixel aligned rect.
constexpr SkScalar L = 2.2f, T = 1.7f, R = 5.8f, B = 7.3f; // Generic rect.
constexpr SkScalar l = 3.3f, t = 2.8f, r = 4.7f, b = 6.2f; // Small rect contained in R.
SkRect alignedRect = {IL, IT, IR, IB};
SkRect rect = {L, T, R, B};
SkRect innerRect = {l, t, r, b};
SkMatrix m;
m.setIdentity();
constexpr SkScalar kMinScale = 2.0001f;
constexpr SkScalar kMaxScale = 3;
constexpr int kNumIters = 8;
SkString name;
SkRandom rand;
for (int i = 0; i < kNumIters; ++i) {
// Pixel-aligned rect (iior=true).
name.printf("Pixel-aligned rect test, iter %i", i);
SkClipStack stack;
stack.clipRect(alignedRect, SkMatrix::I(), kIntersect_SkClipOp, true);
test_aa_query(reporter, name, stack, m, {IL, IT, IR, IB}, ClipMethod::kIgnoreClip);
test_aa_query(reporter, name, stack, m, {IL, IT-1, IR, IT}, ClipMethod::kSkipDraw);
test_aa_query(reporter, name, stack, m, {IL, IT-2, IR, IB}, ClipMethod::kScissor);
// Rect (iior=true).
name.printf("Rect test, iter %i", i);
stack.reset();
stack.clipRect(rect, SkMatrix::I(), kIntersect_SkClipOp, true);
test_aa_query(reporter, name, stack, m, {L, T, R, B}, ClipMethod::kIgnoreClip);
test_aa_query(reporter, name, stack, m, {L-.1f, T, L, B}, ClipMethod::kSkipDraw);
test_aa_query(reporter, name, stack, m, {L-.1f, T, L+.1f, B}, ClipMethod::kAAElements, 1);
// Difference rect (iior=false, inside-out bounds).
name.printf("Difference rect test, iter %i", i);
stack.reset();
stack.clipRect(rect, SkMatrix::I(), kDifference_SkClipOp, true);
test_aa_query(reporter, name, stack, m, {L, T, R, B}, ClipMethod::kSkipDraw);
test_aa_query(reporter, name, stack, m, {L, T-.1f, R, T}, ClipMethod::kIgnoreClip);
test_aa_query(reporter, name, stack, m, {L, T-.1f, R, T+.1f}, ClipMethod::kAAElements, 1);
// Complex clip (iior=false, normal bounds).
name.printf("Complex clip test, iter %i", i);
stack.reset();
stack.clipRect(rect, SkMatrix::I(), kIntersect_SkClipOp, true);
stack.clipRect(innerRect, SkMatrix::I(), kXOR_SkClipOp, true);
test_aa_query(reporter, name, stack, m, {l, t, r, b}, ClipMethod::kSkipDraw);
test_aa_query(reporter, name, stack, m, {r-.1f, t, R, b}, ClipMethod::kAAElements, 1);
test_aa_query(reporter, name, stack, m, {r-.1f, t, R+.1f, b}, ClipMethod::kAAElements, 2);
test_aa_query(reporter, name, stack, m, {r, t, R+.1f, b}, ClipMethod::kAAElements, 1);
test_aa_query(reporter, name, stack, m, {r, t, R, b}, ClipMethod::kIgnoreClip);
test_aa_query(reporter, name, stack, m, {R, T, R+.1f, B}, ClipMethod::kSkipDraw);
// Complex clip where outer rect is pixel aligned (iior=false, normal bounds).
name.printf("Aligned Complex clip test, iter %i", i);
stack.reset();
stack.clipRect(alignedRect, SkMatrix::I(), kIntersect_SkClipOp, true);
stack.clipRect(innerRect, SkMatrix::I(), kXOR_SkClipOp, true);
test_aa_query(reporter, name, stack, m, {l, t, r, b}, ClipMethod::kSkipDraw);
test_aa_query(reporter, name, stack, m, {l, b-.1f, r, IB}, ClipMethod::kAAElements, 1);
test_aa_query(reporter, name, stack, m, {l, b-.1f, r, IB+.1f}, ClipMethod::kAAElements, 1);
test_aa_query(reporter, name, stack, m, {l, b, r, IB+.1f}, ClipMethod::kAAElements, 0);
test_aa_query(reporter, name, stack, m, {l, b, r, IB}, ClipMethod::kIgnoreClip);
test_aa_query(reporter, name, stack, m, {IL, IB, IR, IB+.1f}, ClipMethod::kSkipDraw);
// Apply random transforms and try again. This ensures the clip stack reduction is hardened
// against FP rounding error.
SkScalar sx = rand.nextRangeScalar(kMinScale, kMaxScale);
sx = SkScalarFloorToScalar(sx * alignedRect.width()) / alignedRect.width();
SkScalar sy = rand.nextRangeScalar(kMinScale, kMaxScale);
sy = SkScalarFloorToScalar(sy * alignedRect.height()) / alignedRect.height();
SkScalar tx = SkScalarRoundToScalar(sx * alignedRect.x()) - sx * alignedRect.x();
SkScalar ty = SkScalarRoundToScalar(sy * alignedRect.y()) - sy * alignedRect.y();
SkMatrix xform = SkMatrix::MakeScale(sx, sy);
xform.postTranslate(tx, ty);
xform.mapRect(&alignedRect);
xform.mapRect(&rect);
xform.mapRect(&innerRect);
m.postConcat(xform);
}
}
static void test_tiny_query_bounds_assertion_bug(skiatest::Reporter* reporter) {
// https://bugs.chromium.org/p/skia/issues/detail?id=5990
const SkRect clipBounds = SkRect::MakeXYWH(1.5f, 100, 1000, 1000);
SkClipStack rectStack;
rectStack.clipRect(clipBounds, SkMatrix::I(), kIntersect_SkClipOp, true);
SkPath clipPath;
clipPath.moveTo(clipBounds.left(), clipBounds.top());
clipPath.quadTo(clipBounds.right(), clipBounds.top(),
clipBounds.right(), clipBounds.bottom());
clipPath.quadTo(clipBounds.left(), clipBounds.bottom(),
clipBounds.left(), clipBounds.top());
SkClipStack pathStack;
pathStack.clipPath(clipPath, SkMatrix::I(), kIntersect_SkClipOp, true);
auto context = GrContext::MakeMock(nullptr);
const GrCaps* caps = context->priv().caps();
for (const SkClipStack& stack : {rectStack, pathStack}) {
for (SkRect queryBounds : {SkRect::MakeXYWH(53, 60, GrClip::kBoundsTolerance, 1000),
SkRect::MakeXYWH(53, 60, GrClip::kBoundsTolerance/2, 1000),
SkRect::MakeXYWH(53, 160, 1000, GrClip::kBoundsTolerance),
SkRect::MakeXYWH(53, 160, 1000, GrClip::kBoundsTolerance/2)}) {
const GrReducedClip reduced(stack, queryBounds, caps);
REPORTER_ASSERT(reporter, !reduced.hasScissor());
REPORTER_ASSERT(reporter, reduced.maskElements().isEmpty());
REPORTER_ASSERT(reporter,
GrReducedClip::InitialState::kAllOut == reduced.initialState());
}
}
}
DEF_TEST(ClipStack, reporter) {
SkClipStack stack;
REPORTER_ASSERT(reporter, 0 == stack.getSaveCount());
assert_count(reporter, stack, 0);
static const SkIRect gRects[] = {
{ 0, 0, 100, 100 },
{ 25, 25, 125, 125 },
{ 0, 0, 1000, 1000 },
{ 0, 0, 75, 75 }
};
for (size_t i = 0; i < SK_ARRAY_COUNT(gRects); i++) {
stack.clipDevRect(gRects[i], kIntersect_SkClipOp);
}
// all of the above rects should have been intersected, leaving only 1 rect
SkClipStack::B2TIter iter(stack);
const SkClipStack::Element* element = iter.next();
SkRect answer;
answer.iset(25, 25, 75, 75);
REPORTER_ASSERT(reporter, element);
REPORTER_ASSERT(reporter,
SkClipStack::Element::DeviceSpaceType::kRect == element->getDeviceSpaceType());
REPORTER_ASSERT(reporter, kIntersect_SkClipOp == element->getOp());
REPORTER_ASSERT(reporter, element->getDeviceSpaceRect() == answer);
// now check that we only had one in our iterator
REPORTER_ASSERT(reporter, !iter.next());
stack.reset();
REPORTER_ASSERT(reporter, 0 == stack.getSaveCount());
assert_count(reporter, stack, 0);
test_assign_and_comparison(reporter);
test_iterators(reporter);
test_bounds(reporter, SkClipStack::Element::DeviceSpaceType::kRect);
test_bounds(reporter, SkClipStack::Element::DeviceSpaceType::kRRect);
test_bounds(reporter, SkClipStack::Element::DeviceSpaceType::kPath);
test_isWideOpen(reporter);
test_rect_merging(reporter);
test_rect_replace(reporter);
test_rect_inverse_fill(reporter);
test_path_replace(reporter);
test_quickContains(reporter);
test_invfill_diff_bug(reporter);
test_reduced_clip_stack(reporter);
test_reduced_clip_stack_genid(reporter);
test_reduced_clip_stack_no_aa_crash(reporter);
test_reduced_clip_stack_aa(reporter);
test_tiny_query_bounds_assertion_bug(reporter);
}
//////////////////////////////////////////////////////////////////////////////
sk_sp<GrTextureProxy> GrClipStackClip::testingOnly_createClipMask(GrContext* context) const {
const GrReducedClip reducedClip(*fStack, SkRect::MakeWH(512, 512), 0);
return this->createSoftwareClipMask(context, reducedClip, nullptr);
}
// Verify that clip masks are freed up when the clip state that generated them goes away.
DEF_GPUTEST_FOR_ALL_CONTEXTS(ClipMaskCache, reporter, ctxInfo) {
// This test uses resource key tags which only function in debug builds.
#ifdef SK_DEBUG
GrContext* context = ctxInfo.grContext();
SkClipStack stack;
SkPath path;
path.addCircle(10, 10, 8);
path.addCircle(15, 15, 8);
path.setFillType(SkPath::kEvenOdd_FillType);
static const char* kTag = GrClipStackClip::kMaskTestTag;
GrResourceCache* cache = context->priv().getResourceCache();
static constexpr int kN = 5;
for (int i = 0; i < kN; ++i) {
SkMatrix m;
m.setTranslate(0.5, 0.5);
stack.save();
stack.clipPath(path, m, SkClipOp::kIntersect, true);
sk_sp<GrTextureProxy> mask = GrClipStackClip(&stack).testingOnly_createClipMask(context);
mask->instantiate(context->priv().resourceProvider());
GrTexture* tex = mask->peekTexture();
REPORTER_ASSERT(reporter, 0 == strcmp(tex->getUniqueKey().tag(), kTag));
// Make sure mask isn't pinned in cache.
mask.reset(nullptr);
context->flush();
REPORTER_ASSERT(reporter, i + 1 == cache->countUniqueKeysWithTag(kTag));
}
for (int i = 0; i < kN; ++i) {
stack.restore();
cache->purgeAsNeeded();
REPORTER_ASSERT(reporter, kN - (i + 1) == cache->countUniqueKeysWithTag(kTag));
}
#endif
}
DEF_GPUTEST_FOR_ALL_CONTEXTS(canvas_private_clipRgn, reporter, ctxInfo) {
GrContext* context = ctxInfo.grContext();
const int w = 10;
const int h = 10;
SkImageInfo info = SkImageInfo::Make(w, h, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
sk_sp<SkSurface> surf = SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, info);
SkCanvas* canvas = surf->getCanvas();
SkRegion rgn;
canvas->temporary_internal_getRgnClip(&rgn);
REPORTER_ASSERT(reporter, rgn.isRect());
REPORTER_ASSERT(reporter, rgn.getBounds() == SkIRect::MakeWH(w, h));
canvas->save();
canvas->clipRect(SkRect::MakeWH(5, 5), kDifference_SkClipOp);
canvas->temporary_internal_getRgnClip(&rgn);
REPORTER_ASSERT(reporter, rgn.isComplex());
REPORTER_ASSERT(reporter, rgn.getBounds() == SkIRect::MakeWH(w, h));
canvas->restore();
canvas->save();
canvas->clipRRect(SkRRect::MakeOval(SkRect::MakeLTRB(3, 3, 7, 7)));
canvas->temporary_internal_getRgnClip(&rgn);
REPORTER_ASSERT(reporter, rgn.isComplex());
REPORTER_ASSERT(reporter, rgn.getBounds() == SkIRect::MakeLTRB(3, 3, 7, 7));
canvas->restore();
}
|
rubenvb/skia
|
tests/ClipStackTest.cpp
|
C++
|
bsd-3-clause
| 59,257 |
import { NonIdealState, Spinner } from "@blueprintjs/core";
import React, { Component } from "react";
import { Col, Row } from "react-bootstrap";
import { FormattedMessage } from "react-intl";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import ExportRegionPanel from "./ExportRegionPanel";
import FilterForm from "./FilterForm";
import MapListView from "./MapListView";
import Paginator from "./Paginator";
import { getExportRegions } from "../actions/hdx";
class ExportRegionList extends Component {
render() {
const { loading, regions } = this.props;
if (regions == null || Object.keys(regions).length === 0) {
return null;
}
return (
<div>
{loading &&
<NonIdealState
action={
<strong>
<FormattedMessage id="ui.loading" defaultMessage="Loading..." />
</strong>
}
visual={<Spinner />}
/>}
{loading ||
Object.entries(regions).map(([id, region], i) => {
return (
<Row key={i}>
<ExportRegionPanel region={region} />
</Row>
);
})}
</div>
);
}
}
export class HDXExportRegionList extends Component {
state = {
filters: {}
};
componentWillMount() {
const { getExportRegions } = this.props;
getExportRegions();
}
search = ({ search, ...values }) => {
const { getExportRegions } = this.props;
const { filters } = this.state;
const newFilters = {
...filters,
...values,
search
};
this.setState({
filters: newFilters
});
return getExportRegions(newFilters);
};
render() {
const {
hdx,
hdx: { fetching, selectedExportRegion },
getExportRegions
} = this.props;
const { filters } = this.state;
const regionGeoms = {
features: hdx.items.map(x => x.simplified_geom),
type: "FeatureCollection"
};
return (
<Row style={{ height: "100%" }}>
<Col xs={6} style={{ height: "100%", overflowY: "scroll" }}>
<div style={{ padding: "20px" }}>
<h2 style={{ display: "inline" }}>HDX Export Regions</h2>
<Link
to="/hdx/new"
style={{ float: "right" }}
className="btn btn-primary"
>
Create New Export Region
</Link>
</div>
<div style={{ padding: "20px" }}>
<FilterForm hideAll={true} showFrequency type="Export Regions" onSubmit={this.search} />
<hr />
<Paginator
collection={hdx}
getPage={getExportRegions.bind(null, filters)}
/>
<ExportRegionList regions={hdx.items} loading={fetching} />
<Paginator
collection={hdx}
getPage={getExportRegions.bind(null, filters)}
/>
</div>
</Col>
<Col xs={6} style={{ height: "100%" }}>
<MapListView
features={regionGeoms}
selectedFeatureId={selectedExportRegion}
/>
</Col>
</Row>
);
}
}
const mapStateToProps = state => {
return {
hdx: state.hdx
};
};
export default connect(mapStateToProps, { getExportRegions })(
HDXExportRegionList
);
|
hotosm/osm-export-tool2
|
ui/app/components/HDXExportRegionList.js
|
JavaScript
|
bsd-3-clause
| 3,363 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_20) on Sun Jan 08 17:53:05 CET 2012 -->
<TITLE>
Uses of Package org.puremvc.java.core (PureMVC API Documentation)
</TITLE>
<META NAME="date" CONTENT="2012-01-08">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package org.puremvc.java.core (PureMVC API Documentation)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/puremvc/java/core/package-use.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Package<br>org.puremvc.java.core</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../org/puremvc/java/core/package-summary.html">org.puremvc.java.core</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.puremvc.java.core"><B>org.puremvc.java.core</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.puremvc.java.patterns.facade"><B>org.puremvc.java.patterns.facade</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="org.puremvc.java.core"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Classes in <A HREF="../../../../org/puremvc/java/core/package-summary.html">org.puremvc.java.core</A> used by <A HREF="../../../../org/puremvc/java/core/package-summary.html">org.puremvc.java.core</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../org/puremvc/java/core/class-use/Controller.html#org.puremvc.java.core"><B>Controller</B></A></B>
<BR>
A Singleton <code>IController</code> implementation.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../org/puremvc/java/core/class-use/Model.html#org.puremvc.java.core"><B>Model</B></A></B>
<BR>
A Singleton <code>IModel</code> implementation.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../org/puremvc/java/core/class-use/View.html#org.puremvc.java.core"><B>View</B></A></B>
<BR>
A Singleton <code>IView</code> implementation.</TD>
</TR>
</TABLE>
<P>
<A NAME="org.puremvc.java.patterns.facade"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Classes in <A HREF="../../../../org/puremvc/java/core/package-summary.html">org.puremvc.java.core</A> used by <A HREF="../../../../org/puremvc/java/patterns/facade/package-summary.html">org.puremvc.java.patterns.facade</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../org/puremvc/java/core/class-use/Controller.html#org.puremvc.java.patterns.facade"><B>Controller</B></A></B>
<BR>
A Singleton <code>IController</code> implementation.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../org/puremvc/java/core/class-use/Model.html#org.puremvc.java.patterns.facade"><B>Model</B></A></B>
<BR>
A Singleton <code>IModel</code> implementation.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../org/puremvc/java/core/class-use/View.html#org.puremvc.java.patterns.facade"><B>View</B></A></B>
<BR>
A Singleton <code>IView</code> implementation.</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/puremvc/java/core/package-use.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
|
azureplus/puremvc-java-standard-framework
|
doc/org/puremvc/java/core/package-use.html
|
HTML
|
bsd-3-clause
| 9,086 |
/*
Copyright (c) 2012-2014 The SSDB Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
*/
#ifndef NET_LINK_ADDR_H_
#define NET_LINK_ADDR_H_
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
struct LinkAddr
{
bool ipv4;
short family;
socklen_t addrlen;
LinkAddr(bool is_ipv4);
LinkAddr(const char *ip, int port);
void parse(const char *ip, int port);
unsigned short port(){
return ipv4? ntohs(addr4.sin_port) : ntohs(addr6.sin6_port);
}
struct sockaddr* addr(){
return ipv4? (struct sockaddr *)&addr4 : (struct sockaddr *)&addr6;
}
void* sin_addr(){
return ipv4? (void*)&addr4.sin_addr : (void*)&addr6.sin6_addr;
}
private:
struct sockaddr_in addr4;
struct sockaddr_in6 addr6;
LinkAddr(){};
void is_ipv4(bool yn);
};
#endif
|
ideawu/ssdb
|
src/net/link_addr.h
|
C
|
bsd-3-clause
| 874 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>onMouseMove property - ElementList class - polymer_app_layout library - Dart API</title>
<!-- required because all the links are pseudo-absolute -->
<base href="../..">
<link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="static-assets/prettify.css">
<link rel="stylesheet" href="static-assets/css/bootstrap.min.css">
<link rel="stylesheet" href="static-assets/styles.css">
<meta name="description" content="API docs for the onMouseMove property from the ElementList class, for the Dart programming language.">
<link rel="icon" href="static-assets/favicon.png">
<!-- Do not remove placeholder -->
<!-- Header Placeholder -->
</head>
<body>
<div id="overlay-under-drawer"></div>
<header class="container-fluid" id="title">
<nav class="navbar navbar-fixed-top">
<div class="container">
<button id="sidenav-left-toggle" type="button"> </button>
<ol class="breadcrumbs gt-separated hidden-xs">
<li><a href="index.html">polymer_app_layout_template</a></li>
<li><a href="polymer_app_layout/polymer_app_layout-library.html">polymer_app_layout</a></li>
<li><a href="polymer_app_layout/ElementList-class.html">ElementList</a></li>
<li class="self-crumb">onMouseMove</li>
</ol>
<div class="self-name">onMouseMove</div>
</div>
</nav>
<div class="container masthead">
<ol class="breadcrumbs gt-separated visible-xs">
<li><a href="index.html">polymer_app_layout_template</a></li>
<li><a href="polymer_app_layout/polymer_app_layout-library.html">polymer_app_layout</a></li>
<li><a href="polymer_app_layout/ElementList-class.html">ElementList</a></li>
<li class="self-crumb">onMouseMove</li>
</ol>
<div class="title-description">
<h1 class="title">
<div class="kind">property</div> onMouseMove
</h1>
<!-- p class="subtitle">
Stream of <code class="prettyprint lang-dart">mousemove</code> events handled by this <code class="prettyprint lang-dart">Element</code>.
</p -->
</div>
<ul class="subnav">
</ul>
</div>
</header>
<div class="container body">
<div class="col-xs-6 col-sm-3 sidebar sidebar-offcanvas-left">
<h5><a href="index.html">polymer_app_layout_template</a></h5>
<h5><a href="polymer_app_layout/polymer_app_layout-library.html">polymer_app_layout</a></h5>
<h5><a href="polymer_app_layout/ElementList-class.html">ElementList</a></h5>
<ol>
<li class="section-title"><a href="polymer_app_layout/ElementList-class.html#instance-properties">Properties</a></li>
<li><a href="polymer_app_layout/ElementList/borderEdge.html">borderEdge</a>
</li>
<li><a href="polymer_app_layout/ElementList/classes.html">classes</a>
</li>
<li><a href="polymer_app_layout/ElementList/contentEdge.html">contentEdge</a>
</li>
<li>first
</li>
<li>isEmpty
</li>
<li>isNotEmpty
</li>
<li>iterator
</li>
<li>last
</li>
<li>length
</li>
<li><a href="polymer_app_layout/ElementList/marginEdge.html">marginEdge</a>
</li>
<li><a href="polymer_app_layout/ElementList/onAbort.html">onAbort</a>
</li>
<li><a href="polymer_app_layout/ElementList/onBeforeCopy.html">onBeforeCopy</a>
</li>
<li><a href="polymer_app_layout/ElementList/onBeforeCut.html">onBeforeCut</a>
</li>
<li><a href="polymer_app_layout/ElementList/onBeforePaste.html">onBeforePaste</a>
</li>
<li><a href="polymer_app_layout/ElementList/onBlur.html">onBlur</a>
</li>
<li><a href="polymer_app_layout/ElementList/onCanPlay.html">onCanPlay</a>
</li>
<li><a href="polymer_app_layout/ElementList/onCanPlayThrough.html">onCanPlayThrough</a>
</li>
<li><a href="polymer_app_layout/ElementList/onChange.html">onChange</a>
</li>
<li><a href="polymer_app_layout/ElementList/onClick.html">onClick</a>
</li>
<li><a href="polymer_app_layout/ElementList/onContextMenu.html">onContextMenu</a>
</li>
<li><a href="polymer_app_layout/ElementList/onCopy.html">onCopy</a>
</li>
<li><a href="polymer_app_layout/ElementList/onCut.html">onCut</a>
</li>
<li><a href="polymer_app_layout/ElementList/onDoubleClick.html">onDoubleClick</a>
</li>
<li><a href="polymer_app_layout/ElementList/onDrag.html">onDrag</a>
</li>
<li><a href="polymer_app_layout/ElementList/onDragEnd.html">onDragEnd</a>
</li>
<li><a href="polymer_app_layout/ElementList/onDragEnter.html">onDragEnter</a>
</li>
<li><a href="polymer_app_layout/ElementList/onDragLeave.html">onDragLeave</a>
</li>
<li><a href="polymer_app_layout/ElementList/onDragOver.html">onDragOver</a>
</li>
<li><a href="polymer_app_layout/ElementList/onDragStart.html">onDragStart</a>
</li>
<li><a href="polymer_app_layout/ElementList/onDrop.html">onDrop</a>
</li>
<li><a href="polymer_app_layout/ElementList/onDurationChange.html">onDurationChange</a>
</li>
<li><a href="polymer_app_layout/ElementList/onEmptied.html">onEmptied</a>
</li>
<li><a href="polymer_app_layout/ElementList/onEnded.html">onEnded</a>
</li>
<li><a href="polymer_app_layout/ElementList/onError.html">onError</a>
</li>
<li><a href="polymer_app_layout/ElementList/onFocus.html">onFocus</a>
</li>
<li><a href="polymer_app_layout/ElementList/onFullscreenChange.html">onFullscreenChange</a>
</li>
<li><a href="polymer_app_layout/ElementList/onFullscreenError.html">onFullscreenError</a>
</li>
<li><a href="polymer_app_layout/ElementList/onInput.html">onInput</a>
</li>
<li><a href="polymer_app_layout/ElementList/onInvalid.html">onInvalid</a>
</li>
<li><a href="polymer_app_layout/ElementList/onKeyDown.html">onKeyDown</a>
</li>
<li><a href="polymer_app_layout/ElementList/onKeyPress.html">onKeyPress</a>
</li>
<li><a href="polymer_app_layout/ElementList/onKeyUp.html">onKeyUp</a>
</li>
<li><a href="polymer_app_layout/ElementList/onLoad.html">onLoad</a>
</li>
<li><a href="polymer_app_layout/ElementList/onLoadedData.html">onLoadedData</a>
</li>
<li><a href="polymer_app_layout/ElementList/onLoadedMetadata.html">onLoadedMetadata</a>
</li>
<li><a href="polymer_app_layout/ElementList/onMouseDown.html">onMouseDown</a>
</li>
<li><a href="polymer_app_layout/ElementList/onMouseEnter.html">onMouseEnter</a>
</li>
<li><a href="polymer_app_layout/ElementList/onMouseLeave.html">onMouseLeave</a>
</li>
<li><a href="polymer_app_layout/ElementList/onMouseMove.html">onMouseMove</a>
</li>
<li><a href="polymer_app_layout/ElementList/onMouseOut.html">onMouseOut</a>
</li>
<li><a href="polymer_app_layout/ElementList/onMouseOver.html">onMouseOver</a>
</li>
<li><a href="polymer_app_layout/ElementList/onMouseUp.html">onMouseUp</a>
</li>
<li><a href="polymer_app_layout/ElementList/onMouseWheel.html">onMouseWheel</a>
</li>
<li><a href="polymer_app_layout/ElementList/onPaste.html">onPaste</a>
</li>
<li><a href="polymer_app_layout/ElementList/onPause.html">onPause</a>
</li>
<li><a href="polymer_app_layout/ElementList/onPlay.html">onPlay</a>
</li>
<li><a href="polymer_app_layout/ElementList/onPlaying.html">onPlaying</a>
</li>
<li><a href="polymer_app_layout/ElementList/onRateChange.html">onRateChange</a>
</li>
<li><a href="polymer_app_layout/ElementList/onReset.html">onReset</a>
</li>
<li><a href="polymer_app_layout/ElementList/onResize.html">onResize</a>
</li>
<li><a href="polymer_app_layout/ElementList/onScroll.html">onScroll</a>
</li>
<li><a href="polymer_app_layout/ElementList/onSearch.html">onSearch</a>
</li>
<li><a href="polymer_app_layout/ElementList/onSeeked.html">onSeeked</a>
</li>
<li><a href="polymer_app_layout/ElementList/onSeeking.html">onSeeking</a>
</li>
<li><a href="polymer_app_layout/ElementList/onSelect.html">onSelect</a>
</li>
<li><a href="polymer_app_layout/ElementList/onSelectStart.html">onSelectStart</a>
</li>
<li><a href="polymer_app_layout/ElementList/onStalled.html">onStalled</a>
</li>
<li><a href="polymer_app_layout/ElementList/onSubmit.html">onSubmit</a>
</li>
<li><a href="polymer_app_layout/ElementList/onSuspend.html">onSuspend</a>
</li>
<li><a href="polymer_app_layout/ElementList/onTimeUpdate.html">onTimeUpdate</a>
</li>
<li><a href="polymer_app_layout/ElementList/onTouchCancel.html">onTouchCancel</a>
</li>
<li><a href="polymer_app_layout/ElementList/onTouchEnd.html">onTouchEnd</a>
</li>
<li><a href="polymer_app_layout/ElementList/onTouchEnter.html">onTouchEnter</a>
</li>
<li><a href="polymer_app_layout/ElementList/onTouchLeave.html">onTouchLeave</a>
</li>
<li><a href="polymer_app_layout/ElementList/onTouchMove.html">onTouchMove</a>
</li>
<li><a href="polymer_app_layout/ElementList/onTouchStart.html">onTouchStart</a>
</li>
<li><a href="polymer_app_layout/ElementList/onTransitionEnd.html">onTransitionEnd</a>
</li>
<li><a href="polymer_app_layout/ElementList/onVolumeChange.html">onVolumeChange</a>
</li>
<li><a href="polymer_app_layout/ElementList/onWaiting.html">onWaiting</a>
</li>
<li><a href="polymer_app_layout/ElementList/paddingEdge.html">paddingEdge</a>
</li>
<li>reversed
</li>
<li>single
</li>
<li><a href="polymer_app_layout/ElementList/style.html">style</a>
</li>
<li class="section-title"><a href="polymer_app_layout/ElementList-class.html#constructors">Constructors</a></li>
<li><a href="polymer_app_layout/ElementList/ElementList.html">ElementList</a></li>
<li class="section-title"><a href="polymer_app_layout/ElementList-class.html#operators">Operators</a></li>
<li>operator []
</li>
<li>operator []=
</li>
<li class="section-title"><a href="polymer_app_layout/ElementList-class.html#methods">Methods</a></li>
<li>add
</li>
<li>addAll
</li>
<li>any
</li>
<li>asMap
</li>
<li>clear
</li>
<li>contains
</li>
<li>elementAt
</li>
<li>every
</li>
<li>expand
</li>
<li>fillRange
</li>
<li>firstWhere
</li>
<li>fold
</li>
<li>forEach
</li>
<li>getRange
</li>
<li>indexOf
</li>
<li>insert
</li>
<li>insertAll
</li>
<li>join
</li>
<li>lastIndexOf
</li>
<li>lastWhere
</li>
<li>map
</li>
<li>reduce
</li>
<li>remove
</li>
<li>removeAt
</li>
<li>removeLast
</li>
<li>removeRange
</li>
<li>removeWhere
</li>
<li>replaceRange
</li>
<li>retainWhere
</li>
<li>setAll
</li>
<li>setRange
</li>
<li>shuffle
</li>
<li>singleWhere
</li>
<li>skip
</li>
<li>skipWhile
</li>
<li>sort
</li>
<li>sublist
</li>
<li>take
</li>
<li>takeWhile
</li>
<li>toList
</li>
<li>toSet
</li>
<li>toString
</li>
<li>where
</li>
</ol>
</div><!--/.sidebar-offcanvas-->
<div class="col-xs-12 col-sm-9 col-md-6 main-content">
<section class="multi-line-signature">
<span class="returntype"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a><<a href="dart-html/MouseEvent-class.html">MouseEvent</a>></span>
<span class="name ">onMouseMove</span>
<div class="readable-writable">
read-only
</div>
</section>
<section class="desc markdown">
<p>Stream of <code class="prettyprint lang-dart">mousemove</code> events handled by this <code class="prettyprint lang-dart">Element</code>.</p>
</section>
</div> <!-- /.main-content -->
</div> <!-- container -->
<footer>
<div class="container-fluid">
<div class="container">
<p class="text-center">
<span class="no-break">
polymer_app_layout_template 0.1.0 api docs
</span>
•
<span class="copyright no-break">
<a href="https://www.dartlang.org">
<img src="static-assets/favicon.png" alt="Dart" title="Dart"width="16" height="16">
</a>
</span>
•
<span class="copyright no-break">
<a href="http://creativecommons.org/licenses/by-sa/4.0/">cc license</a>
</span>
</p>
</div>
</div>
</footer>
<script src="static-assets/prettify.js"></script>
<script src="static-assets/script.js"></script>
<!-- Do not remove placeholder -->
<!-- Footer Placeholder -->
</body>
</html>
|
lejard-h/polymer_app_layout_templates
|
doc/api/polymer_app_layout/ElementList/onMouseMove.html
|
HTML
|
bsd-3-clause
| 13,086 |
/*L
* Copyright Washington University in St. Louis
* Copyright SemanticBits
* Copyright Persistent Systems
* Copyright Krishagni
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/catissue-core/LICENSE.txt for details.
*/
package edu.wustl.catissuecore.action;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.catissuecore.actionForm.SpecimenArrayForm;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.common.action.CommonAddEditAction;
import edu.wustl.common.actionForm.AbstractActionForm;
import edu.wustl.common.util.MapDataParser;
import edu.wustl.common.util.logger.Logger;
/**
* <p>
* This class initializes the fields of SpecimenArrayAddEditAction.java.
* </p>
*
* @author Ashwin Gupta
* @version 1.1
*/
public class SpecimenArrayAddEditAction extends CatissueAddEditAction
{
/**
* logger.
*/
private transient final Logger logger = Logger
.getCommonLogger(SpecimenArrayAddEditAction.class);
/**
* Overrides the executeSecureAction method of SecureAction class.
* @param mapping
* object of ActionMapping
* @param form
* object of ActionForm
* @param request
* object of HttpServletRequest
* @param response
* object of HttpServletResponse
* @throws IOException : IOException
* @throws ServletException : ServletException
* @return ActionForward : ActionForward
*/
@Override
public ActionForward executeSecureAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
final Map arrayContentMap = (Map) request.getSession().getAttribute(
Constants.SPECIMEN_ARRAY_CONTENT_KEY);
if (arrayContentMap != null)
{
try
{
final MapDataParser mapDataParser = new MapDataParser(
"edu.wustl.catissuecore.domain");
final Collection specimenArrayContentList = mapDataParser
.generateData(arrayContentMap);
final AbstractActionForm abstractForm = (AbstractActionForm) form;
if (abstractForm instanceof SpecimenArrayForm)
{
final SpecimenArrayForm specimenArrayForm = (SpecimenArrayForm) abstractForm;
specimenArrayForm.setSpecArrayContentCollection(specimenArrayContentList);
}
/*
* AbstractDomainObject abstractDomain =
* abstractDomainObjectFactory
* .getDomainObject(abstractForm.getFormId(), abstractForm); if
* (abstractDomain instanceof SpecimenArray) { SpecimenArray
* specimenArray = (SpecimenArray) abstractDomain;
* specimenArray.
* setSpecimenArrayContentCollection(specimenArrayContentList);
* }
*/
}
catch (final Exception exception)
{
this.logger.error(exception.getMessage(), exception);
}
}
return super.executeSecureAction(mapping, form, request, response);
}
}
|
NCIP/catissue-core
|
software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/SpecimenArrayAddEditAction.java
|
Java
|
bsd-3-clause
| 3,268 |
auth-mongo-mngr
===============
Package implement a [kidstuff/auth manager](https://github.com/kidstuff/auth/wiki/Getting-started) with MongoDB.
### Install
`
go get github.com/kidstuff/auth-mongo-mngr
`
### Setup
This manager require developer to build some indexes by calling [mgoauth.Setup](http://godoc.org/github.com/kidstuff/auth-mongo-mngr#Setup) in a setup script or by running these command in mongodb shell:
```javascript
db.mgoauth_user.ensureIndex( { Email: 1 }, { unique: true } )
db.mgoauth_user.ensureIndex( { LastActivity: 1 } )
db.mgoauth_user.ensureIndex( { Groups.Id: 1 } )
db.mgoauth_login.ensureIndex( { UserId: 1 } )
db.mgoauth_login.ensureIndex( { ExpiredOn: 1 }, { expireAfterSeconds: 60 } )
db.mgoauth_group.ensureIndex( { Name: 1 }, { unique: true } )
````
### Usage
```go
import (
"github.com/kidstuff/auth-mongo-mngr"
"labix.org/v2/mgo"
)
func main() {
// connect to database
session, err := mgo.Dial(MONGODB_URL)
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
db := session.DB(DB_NAME)
// config kidstuff/auth API to work with auth-mongo-mngr
mgoauth.Initial(db)
}
```
|
kidstuff/auth-mongo-mngr
|
README.md
|
Markdown
|
bsd-3-clause
| 1,165 |
/*L
* Copyright SAIC
* Copyright SAIC-Frederick
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/camod/LICENSE.txt for details.
*/
/**
* @author pandyas
*
* $Id: CellLineForm.java,v 1.10 2006-04-17 19:09:19 pandyas Exp $
*
* $Log: not supported by cvs2svn $
* Revision 1.9 2005/10/20 20:27:27 pandyas
* added javadocs
*
*
*/
package gov.nih.nci.camod.webapp.form;
import java.io.Serializable;
public class CellLineForm extends BaseForm implements Serializable, CellLineData {
private static final long serialVersionUID = 3257355453799404851L;
/**
* Default empty constructor
* @author rajputs
*/
public CellLineForm() {}
protected String cellLineName;
protected String experiment;
protected String results;
protected String comments;
protected String organ;
protected String organTissueName;
protected String organTissueCode;
/**
* @return Returns the cellLineName.
*/
public String getCellLineName() {
return cellLineName;
}
/**
* @param cellLineName The cellLineName to set.
*/
public void setCellLineName(String cellLineName) {
this.cellLineName = cellLineName;
}
/**
* @return Returns the experiment.
*/
public String getExperiment() {
return experiment;
}
/**
* @param experiment The experiment to set.
*/
public void setExperiment(String experiment) {
this.experiment = experiment;
}
/**
* @return Returns the results.
*/
public String getResults() {
return results;
}
/**
* @param results The results to set.
*/
public void setResults(String results) {
this.results = results;
}
/**
* @return Returns the comments.
*/
public String getComments() {
return comments;
}
/**
* @param comments The comments to set.
*/
public void setComments(String comments) {
this.comments = comments;
}
/**
* @return Returns the organ.
*/
public String getOrgan() {
return organ;
}
/**
* @param organ The organ to set.
*/
public void setOrgan( String organ ) {
this.organ = organ;
}
/**
* @return Returns the organTissueName.
*/
public String getOrganTissueName() {
return organTissueName;
}
/**
* @param organTissueName The organTissueName to set.
*/
public void setOrganTissueName( String organTissueName ) {
this.organTissueName = organTissueName;
}
/**
* @return Returns the organTissueCode (concept code).
*/
public String getOrganTissueCode() {
return organTissueCode;
}
/**
* @param organTissueCode The organTissueCode (concept code) to set .
*/
public void setOrganTissueCode( String organTissueCode ) {
this.organTissueCode = organTissueCode;
}
}
|
NCIP/camod
|
software/camod/src/gov/nih/nci/camod/webapp/form/CellLineForm.java
|
Java
|
bsd-3-clause
| 2,681 |
/*
* front
* author: ronglin
* create date: 2012.02.15
*/
.vs-visualstyle-front {
position:fixed;
display:block;
right:50px;
top:50px;
left:auto;
bottom:auto;
padding:5px;
border:1px solid #555;
background-color:#ddd;
z-index:9999;
}
.vs-visualstyle-front .btnAble{
display:block;
width:36px;
height:36px;
cursor:pointer;
background-color:#ddd;
background-repeat:no-repeat;
background-image:url(modules/images/visualstyle_front_turnon.gif);
}
|
Epitomy/CMS
|
Kooboo.CMS/Kooboo.CMS.ModuleArea/Areas/Sites/Scripts/visualStyle/front.css
|
CSS
|
bsd-3-clause
| 521 |
<?php
namespace app\controllers;
use app\models\rbac\AuthAdminuser;
//use yii\widgets\DetailView;
//use yii\widgets\ListView;
use yii\data\ActiveDataProvider;
//use yii\grid\GridView;
use yii\rbac\Item;
use app\models\rbac\Rbac;
class AdminuserController extends BaseController {
public function actionIndex() {
$query = AuthAdminuser::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 20,
],
]);
// 增加过滤条件来调整查询对象
//$query->andWhere(['in','status', [0, 1]]);
//$query->orderBy(['is_admin'=>SORT_DESC]);
return $this->render('index', ['dataProvider' => $dataProvider]);
}
public function actionAdd() {
$model = new AuthAdminuser();
$adminInfo = \Yii::$app->session->get('_ADMININFO');
if (!\Yii::$app->request->isPost) {
$model->status = 1;
$model->is_admin = 0;
return $this->render('add', ['model' => $model, 'row' => $model]);
}
// 表单字段验证
$model->load(\Yii::$app->request->post(), 'AuthAdminuser');
if (!$model->validate()) {
$error = array_values($model->FirstErrors)[0];
return $this->render('/site/error', ['name' => 'Error', 'message' => $error]);
}
$model->createtime = time();
$model->save(false);
return "<script>alert('完成');history.back()</script>";
}
public function actionUpdate() {
$model = new AuthAdminuser();
$id = \Yii::$app->request->get('id', 1);
if (!\Yii::$app->request->isPost) {
$row = $model->find()->where(['id' => $id])->one();
$model->status = $row->status;
$model->is_admin = $row->is_admin;
return $this->render('add', ['model' => $model, 'row' => $row]);
}
// 表单字段验证
$query = $model->findOne($id);
$query->load(\Yii::$app->request->post());
$query->_oldUniqueId = $query->userlogin;
$query->validate();
if ($query->getErrors()) {
$error = array_values($query->FirstErrors)[0];
return $this->render('/site/error', ['name' => 'Error', 'message' => $error]);
}
// 如果不更新密码
if (!$query->isUpdatePassword) {
unset($query->password);
}
$query->save(false);
return "<script>alert('完成');history.back()</script>";
}
public function actionDelete() {
$model = new AuthAdminuser();
$id = \Yii::$app->request->get('id', 1);
// 表单字段验证
$query = $model->findOne($id);
$query->delete();
return "<script>alert('完成');history.back()</script>";
}
/**
* 赋予 角色/权限 给用户
*/
public function actionAssign() {
$role = new Item();
$rbac = new Rbac();
if (!\Yii::$app->request->isPost) {
$userId = \Yii::$app->request->get('id', 0);
$list = $rbac->getRoles();
$roles = $rbac->getRolesByUser($userId);
$roles_keys = array_keys($roles);
return $this->renderAjax('assign', ['list' => $list, 'roles' => $roles_keys, 'id' => $userId]);
}
$userId = \Yii::$app->request->post('id', 0);
$names = \Yii::$app->request->post('childs', []);
if (!is_array($names) && count($names) < 1) {
$error = '请选择';
return $this->render('/site/error', ['name' => 'Error', 'message' => $error]);
}
// 先移除该用户所有角色
$rbac->revokeAll($userId);
foreach ($names as $name) {
$role->name = $name;
$rbac->assign($role, $userId);
}
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ['code'=>10000,'msg'=>'成功'];
}
}
|
xiaohaoyong/AcarAdmin
|
controllers/AdminuserController.php
|
PHP
|
bsd-3-clause
| 4,018 |
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package types
import (
"bytes"
"fmt"
"go/ast"
"go/token"
"github.com/godoctor/godoctor/internal/golang.org/x/tools/go/exact"
)
// TODO(gri) Document factory, accessor methods, and fields. General clean-up.
// An Object describes a named language entity such as a package,
// constant, type, variable, function (incl. methods), or label.
// All objects implement the Object interface.
//
type Object interface {
Parent() *Scope // scope in which this object is declared
Pos() token.Pos // position of object identifier in declaration
Pkg() *Package // nil for objects in the Universe scope and labels
Name() string // package local object name
Type() Type // object type
Exported() bool // reports whether the name starts with a capital letter
Id() string // object id (see Id below)
// String returns a human-readable string of the object.
String() string
// order reflects a package-level object's source order: if object
// a is before object b in the source, then a.order() < b.order().
// order returns a value > 0 for package-level objects; it returns
// 0 for all other objects (including objects in file scopes).
order() uint32
// setOrder sets the order number of the object. It must be > 0.
setOrder(uint32)
// setParent sets the parent scope of the object.
setParent(*Scope)
// sameId reports whether obj.Id() and Id(pkg, name) are the same.
sameId(pkg *Package, name string) bool
}
// Id returns name if it is exported, otherwise it
// returns the name qualified with the package path.
func Id(pkg *Package, name string) string {
if ast.IsExported(name) {
return name
}
// unexported names need the package path for differentiation
// (if there's no package, make sure we don't start with '.'
// as that may change the order of methods between a setup
// inside a package and outside a package - which breaks some
// tests)
path := "_"
// TODO(gri): shouldn't !ast.IsExported(name) => pkg != nil be an precondition?
// if pkg == nil {
// panic("nil package in lookup of unexported name")
// }
if pkg != nil {
path = pkg.path
if path == "" {
path = "_"
}
}
return path + "." + name
}
// An object implements the common parts of an Object.
type object struct {
parent *Scope
pos token.Pos
pkg *Package
name string
typ Type
order_ uint32
}
func (obj *object) Parent() *Scope { return obj.parent }
func (obj *object) Pos() token.Pos { return obj.pos }
func (obj *object) Pkg() *Package { return obj.pkg }
func (obj *object) Name() string { return obj.name }
func (obj *object) Type() Type { return obj.typ }
func (obj *object) Exported() bool { return ast.IsExported(obj.name) }
func (obj *object) Id() string { return Id(obj.pkg, obj.name) }
func (obj *object) String() string { panic("abstract") }
func (obj *object) order() uint32 { return obj.order_ }
func (obj *object) setOrder(order uint32) { assert(order > 0); obj.order_ = order }
func (obj *object) setParent(parent *Scope) { obj.parent = parent }
func (obj *object) sameId(pkg *Package, name string) bool {
// spec:
// "Two identifiers are different if they are spelled differently,
// or if they appear in different packages and are not exported.
// Otherwise, they are the same."
if name != obj.name {
return false
}
// obj.Name == name
if obj.Exported() {
return true
}
// not exported, so packages must be the same (pkg == nil for
// fields in Universe scope; this can only happen for types
// introduced via Eval)
if pkg == nil || obj.pkg == nil {
return pkg == obj.pkg
}
// pkg != nil && obj.pkg != nil
return pkg.path == obj.pkg.path
}
// A PkgName represents an imported Go package.
type PkgName struct {
object
imported *Package
used bool // set if the package was used
}
func NewPkgName(pos token.Pos, pkg *Package, name string, imported *Package) *PkgName {
return &PkgName{object{nil, pos, pkg, name, Typ[Invalid], 0}, imported, false}
}
// Imported returns the package that was imported.
// It is distinct from Pkg(), which is the package containing the import statement.
func (obj *PkgName) Imported() *Package { return obj.imported }
// A Const represents a declared constant.
type Const struct {
object
val exact.Value
visited bool // for initialization cycle detection
}
func NewConst(pos token.Pos, pkg *Package, name string, typ Type, val exact.Value) *Const {
return &Const{object{nil, pos, pkg, name, typ, 0}, val, false}
}
func (obj *Const) Val() exact.Value { return obj.val }
// A TypeName represents a declared type.
type TypeName struct {
object
}
func NewTypeName(pos token.Pos, pkg *Package, name string, typ Type) *TypeName {
return &TypeName{object{nil, pos, pkg, name, typ, 0}}
}
// A Variable represents a declared variable (including function parameters and results, and struct fields).
type Var struct {
object
anonymous bool // if set, the variable is an anonymous struct field, and name is the type name
visited bool // for initialization cycle detection
isField bool // var is struct field
used bool // set if the variable was used
}
func NewVar(pos token.Pos, pkg *Package, name string, typ Type) *Var {
return &Var{object: object{nil, pos, pkg, name, typ, 0}}
}
func NewParam(pos token.Pos, pkg *Package, name string, typ Type) *Var {
return &Var{object: object{nil, pos, pkg, name, typ, 0}, used: true} // parameters are always 'used'
}
func NewField(pos token.Pos, pkg *Package, name string, typ Type, anonymous bool) *Var {
return &Var{object: object{nil, pos, pkg, name, typ, 0}, anonymous: anonymous, isField: true}
}
func (obj *Var) Anonymous() bool { return obj.anonymous }
func (obj *Var) IsField() bool { return obj.isField }
// A Func represents a declared function, concrete method, or abstract
// (interface) method. Its Type() is always a *Signature.
// An abstract method may belong to many interfaces due to embedding.
type Func struct {
object
}
func NewFunc(pos token.Pos, pkg *Package, name string, sig *Signature) *Func {
// don't store a nil signature
var typ Type
if sig != nil {
typ = sig
}
return &Func{object{nil, pos, pkg, name, typ, 0}}
}
// FullName returns the package- or receiver-type-qualified name of
// function or method obj.
func (obj *Func) FullName() string {
var buf bytes.Buffer
writeFuncName(&buf, nil, obj)
return buf.String()
}
func (obj *Func) Scope() *Scope {
return obj.typ.(*Signature).scope
}
// A Label represents a declared label.
type Label struct {
object
used bool // set if the label was used
}
func NewLabel(pos token.Pos, pkg *Package, name string) *Label {
return &Label{object{pos: pos, pkg: pkg, name: name, typ: Typ[Invalid]}, false}
}
// A Builtin represents a built-in function.
// Builtins don't have a valid type.
type Builtin struct {
object
id builtinId
}
func newBuiltin(id builtinId) *Builtin {
return &Builtin{object{name: predeclaredFuncs[id].name, typ: Typ[Invalid]}, id}
}
// Nil represents the predeclared value nil.
type Nil struct {
object
}
func writeObject(buf *bytes.Buffer, this *Package, obj Object) {
typ := obj.Type()
switch obj := obj.(type) {
case *PkgName:
fmt.Fprintf(buf, "package %s", obj.Name())
if path := obj.imported.path; path != "" && path != obj.name {
fmt.Fprintf(buf, " (%q)", path)
}
return
case *Const:
buf.WriteString("const")
case *TypeName:
buf.WriteString("type")
typ = typ.Underlying()
case *Var:
if obj.isField {
buf.WriteString("field")
} else {
buf.WriteString("var")
}
case *Func:
buf.WriteString("func ")
writeFuncName(buf, this, obj)
if typ != nil {
WriteSignature(buf, this, typ.(*Signature))
}
return
case *Label:
buf.WriteString("label")
typ = nil
case *Builtin:
buf.WriteString("builtin")
typ = nil
case *Nil:
buf.WriteString("nil")
return
default:
panic(fmt.Sprintf("writeObject(%T)", obj))
}
buf.WriteByte(' ')
// For package-level objects, package-qualify the name,
// except for intra-package references (this != nil).
if pkg := obj.Pkg(); pkg != nil && this != pkg && pkg.scope.Lookup(obj.Name()) == obj {
buf.WriteString(pkg.path)
buf.WriteByte('.')
}
buf.WriteString(obj.Name())
if typ != nil {
buf.WriteByte(' ')
WriteType(buf, this, typ)
}
}
// ObjectString returns the string form of obj.
// Object and type names are printed package-qualified
// only if they do not belong to this package.
//
func ObjectString(this *Package, obj Object) string {
var buf bytes.Buffer
writeObject(&buf, this, obj)
return buf.String()
}
func (obj *PkgName) String() string { return ObjectString(nil, obj) }
func (obj *Const) String() string { return ObjectString(nil, obj) }
func (obj *TypeName) String() string { return ObjectString(nil, obj) }
func (obj *Var) String() string { return ObjectString(nil, obj) }
func (obj *Func) String() string { return ObjectString(nil, obj) }
func (obj *Label) String() string { return ObjectString(nil, obj) }
func (obj *Builtin) String() string { return ObjectString(nil, obj) }
func (obj *Nil) String() string { return ObjectString(nil, obj) }
func writeFuncName(buf *bytes.Buffer, this *Package, f *Func) {
if f.typ != nil {
sig := f.typ.(*Signature)
if recv := sig.Recv(); recv != nil {
buf.WriteByte('(')
if _, ok := recv.Type().(*Interface); ok {
// gcimporter creates abstract methods of
// named interfaces using the interface type
// (not the named type) as the receiver.
// Don't print it in full.
buf.WriteString("interface")
} else {
WriteType(buf, this, recv.Type())
}
buf.WriteByte(')')
buf.WriteByte('.')
} else if f.pkg != nil && f.pkg != this {
buf.WriteString(f.pkg.path)
buf.WriteByte('.')
}
}
buf.WriteString(f.name)
}
|
steffimariya/godoctor
|
internal/golang.org/x/tools/go/types/object.go
|
GO
|
bsd-3-clause
| 9,939 |
from django.http import JsonResponse
from django.template.loader import render_to_string
from django.utils.text import slugify
from couchdbkit.exceptions import DocTypeError, ResourceNotFound
from dimagi.ext.couchdbkit import Document
from soil import FileDownload
from corehq import toggles
from corehq.apps.app_manager.views.utils import get_langs, report_build_time
from corehq.apps.domain.decorators import api_auth
from corehq.apps.domain.models import Domain
from corehq.apps.hqmedia.tasks import create_files_for_ccz
from corehq.util.view_utils import absolute_reverse, json_error
from ..dbaccessors import (
get_build_doc_by_version,
get_current_app,
get_latest_build_doc,
get_latest_released_app_doc,
wrap_app,
)
@json_error
@api_auth
def list_apps(request, domain):
def app_to_json(app):
return {
'name': app.name,
'version': app.version,
'app_id': app.get_id,
'download_url': absolute_reverse('direct_ccz', args=[domain],
params={'app_id': app.get_id})
}
applications = Domain.get_by_name(domain).applications()
return JsonResponse({
'status': 'success',
'applications': list(map(app_to_json, applications)),
})
@json_error
def direct_ccz(request, domain):
"""
You must specify an app_id, and you may specify either 'version' or 'latest'
latest can be one of:
release: Latest starred version
build: Latest version regardless of star
save: Latest saved version of the application (even without a build)
If 'version' and 'latest' aren't specified it will default to latest save
You may also set 'include_multimedia=true' if you need multimedia.
"""
def error(msg, code=400):
return JsonResponse({'status': 'error', 'message': msg}, status_code=code)
def get_app(app_id, version, latest):
if version:
return get_build_doc_by_version(domain, app_id, version)
elif latest == 'build':
return get_latest_build_doc(domain, app_id)
elif latest == 'release':
return get_latest_released_app_doc(domain, app_id)
else:
# either latest=='save' or they didn't specify
return get_current_app(domain, app_id)
app_id = request.GET.get('app_id', None)
version = request.GET.get('version', None)
latest = request.GET.get('latest', None)
include_multimedia = request.GET.get('include_multimedia', 'false').lower() == 'true'
visit_scheduler_enabled = toggles.VISIT_SCHEDULER.enabled_for_request(request)
# Make sure URL params make sense
if not app_id:
return error("You must specify `app_id` in your GET parameters")
if version and latest:
return error("You can't specify both 'version' and 'latest'")
if latest not in (None, 'release', 'build', 'save',):
return error("latest must be either 'release', 'build', or 'save'")
if version:
try:
version = int(version)
except ValueError:
return error("'version' must be an integer")
try:
app = get_app(app_id, version, latest)
if not app:
raise ResourceNotFound()
app = app if isinstance(app, Document) else wrap_app(app)
except (ResourceNotFound, DocTypeError):
return error("Application not found", code=404)
lang, langs = get_langs(request, app)
with report_build_time(domain, app._id, 'live_preview'):
return get_direct_ccz(domain, app, langs, version, include_multimedia, visit_scheduler_enabled)
def get_direct_ccz(domain, app, langs, version=None, include_multimedia=False, visit_scheduler_enabled=False):
if not app.copy_of:
errors = app.validate_app()
else:
errors = None
if errors:
error_html = render_to_string("app_manager/partials/build_errors.html", {
'app': app,
'build_errors': errors,
'domain': domain,
'langs': langs,
'visit_scheduler_enabled': visit_scheduler_enabled,
})
return JsonResponse(
{'error_html': error_html},
status_code=400,
)
app.set_media_versions()
download = FileDownload('application-{}-{}'.format(app.get_id, version))
try:
create_files_for_ccz(
build=app,
build_profile_id=None,
include_multimedia_files=include_multimedia,
download_id=download.download_id,
compress_zip=True,
filename='{}.ccz'.format(slugify(app.name)),
)
except Exception as e:
return JsonResponse({'status': 'error', 'message': str(e)}, status_code=400)
return FileDownload.get(download.download_id).toHttpResponse()
|
dimagi/commcare-hq
|
corehq/apps/app_manager/views/cli.py
|
Python
|
bsd-3-clause
| 4,829 |
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model app\models\Goodgroup */
$this->title = 'Create Goodgroup';
$this->params['breadcrumbs'][] = ['label' => 'Goodgroups', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="goodgroup-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
|
Prostovic/avvita
|
views/goodgroup/create.php
|
PHP
|
bsd-3-clause
| 424 |
package edu.stanford.math.plex4.bottleneck;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import edu.stanford.math.plex4.homology.barcodes.Interval;
import edu.stanford.math.primitivelib.utility.Infinity;
public class BottleneckDistance {
public static List<Interval<Double>> truncate(List<Interval<Double>> A, double minimumValue, double maximumValue) {
List<Interval<Double>> result = new ArrayList<Interval<Double>>();
double start, end;
for (Interval<Double> interval: A) {
if (interval.isLeftInfinite()) {
start = minimumValue;
} else {
start = Math.max(minimumValue, interval.getStart());
}
if (interval.isRightInfinite()) {
end = maximumValue;
} else {
end = Math.min(maximumValue, interval.getEnd());
}
result.add(Interval.makeFiniteRightOpenInterval(start, end));
}
return result;
}
public static List<Interval<Double>> filterLargest(List<Interval<Double>> A, int N) {
if (A.size() <= N) {
return A;
}
double[] diagonalDistances = new double[A.size()];
for (int i = 0; i < A.size(); i++) {
Interval<Double> interval = A.get(i);
diagonalDistances[i] = BottleneckDistance.distanceToDiagonal(interval);
}
Arrays.sort(diagonalDistances);
double minimumDiagonalDistance = diagonalDistances[diagonalDistances.length - N];
List<Interval<Double>> result = new ArrayList<Interval<Double>>();
for (int i = 0; i < A.size(); i++) {
Interval<Double> interval = A.get(i);
double distance = BottleneckDistance.distanceToDiagonal(interval);
if (distance >= minimumDiagonalDistance) {
result.add(interval);
}
}
return result;
}
public static double computeBottleneckDistance(double[][] A, double[][] B) {
List<Interval<Double>> intA = new ArrayList<Interval<Double>>();
List<Interval<Double>> intB = new ArrayList<Interval<Double>>();
for(double[] element : A) {
intA.add(Interval.makeFiniteClosedInterval(element[0], element[1]));
}
for(double[] element : B) {
intB.add(Interval.makeFiniteClosedInterval(element[0], element[1]));
}
return computeBottleneckDistance(intA, intB);
}
public static double computeBottleneckDistance(List<Interval<Double>> A, List<Interval<Double>> B) {
int a = A.size();
int b = B.size();
int n = a + b;
WeightedBipartiteGraph graph = new WeightedBipartiteGraph(n);
double distance = 0;
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
distance = BottleneckDistance.distance(A.get(i), B.get(j));
graph.addEdge(i, j, distance);
}
}
for (int i = 0; i < a; i++) {
distance = BottleneckDistance.distanceToDiagonal(A.get(i));
graph.addEdge(i, b + i, distance);
}
for (int j = 0; j < b; j++) {
distance = BottleneckDistance.distanceToDiagonal(B.get(j));
graph.addEdge(a + j, j, distance);
}
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
graph.addEdge(a + j, b + i, 0);
}
}
double bottleneckDistance = graph.computePerfectMatchingThreshold();
return bottleneckDistance;
}
static double distanceToDiagonal(Interval<Double> A) {
if (!A.isLeftInfinite() && !A.isRightInfinite()) {
return 0.5 * Math.abs(A.getEnd() - A.getStart());
}
return Infinity.Double.getPositiveInfinity();
}
static double distance(Interval<Double> A, Interval<Double> B) {
if (!A.isLeftInfinite() && !B.isRightInfinite() && !A.isRightInfinite() && !B.isRightInfinite()) {
double startDifference = Math.abs(A.getStart() - B.getStart());
double endDifference = Math.abs(A.getEnd() - B.getEnd());
return Math.max(startDifference, endDifference);
}
if (A.isLeftInfinite() && B.isLeftInfinite() && !A.isRightInfinite() && !B.isRightInfinite()) {
return Math.abs(A.getEnd() - B.getEnd());
}
if (!A.isLeftInfinite() && !B.isLeftInfinite() && A.isRightInfinite() && B.isRightInfinite()) {
return Math.abs(A.getStart() - B.getStart());
}
return Infinity.Double.getPositiveInfinity();
}
}
|
appliedtopology/javaplex
|
src/java/edu/stanford/math/plex4/bottleneck/BottleneckDistance.java
|
Java
|
bsd-3-clause
| 4,085 |
CFLAGS = -Wall -std=c99 -O2
DEPS=main.o heap.o
PRGM=test
MAIN: $(DEPS)
$(CC) $(DEPS) -o $(PRGM)
clean:
rm *.o $(PRGM)
|
armon/c-minheap-array
|
Makefile
|
Makefile
|
bsd-3-clause
| 124 |
/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2012, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#ifndef KERNEL_H_
#define KERNEL_H_
#include <pcl/pcl_base.h>
#include <pcl/point_types.h>
namespace pcl
{
namespace pcl_2d
{
template<typename PointT>
class Kernel
{
public:
enum KERNEL_ENUM
{
SOBEL,
PREWITT,
ROBERTS,
LOG,
DERIVATIVE_CENTRAL_X,
DERIVATIVE_FORWARD_X,
DERIVATIVE_BACKWARD_X,
DERIVATIVE_CENTRAL_Y,
DERIVATIVE_FORWARD_Y,
DERIVATIVE_BACKWARD_Y,
GAUSSIAN
};
int kernel_size_;
float sigma_;
KERNEL_ENUM kernel_type_;
Kernel () :
kernel_size_ (3),
sigma_ (1.0),
kernel_type_ (GAUSSIAN)
{
}
void fetchKernel (PointCloud<PointT> &kernel);
void gaussianKernel (PointCloud<PointT> &kernel);
void loGKernel (PointCloud<PointT> &kernel);
void sobelKernel (PointCloud<PointT> &Kernel);
void prewittKernel (PointCloud<PointT> &Kernel);
void robertsKernel (PointCloud<PointT> &kernel);
void derivativeXCentralKernel (PointCloud<PointT> &kernel);
void derivativeYCentralKernel (PointCloud<PointT> &kernel);
};
}
}
#endif /* KERNEL_H_ */
|
patmarion/PCL
|
2d/include/pcl/2d/kernel.h
|
C
|
bsd-3-clause
| 2,996 |
/*
* node.c
*
* Created on: Mar 7, 2011
* Author: posixninja
*
* Copyright (c) 2011 Joshua Hill. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "node.h"
#include "node_list.h"
#include "node_iterator.h"
void node_destroy(node_t* node) {
if(!node) return;
if (node->children && node->children->count > 0) {
node_t* ch;
while ((ch = node->children->begin)) {
node_list_remove(node->children, ch);
node_destroy(ch);
}
}
node_list_destroy(node->children);
node->children = NULL;
free(node);
}
node_t* node_create(node_t* parent, void* data) {
int error = 0;
node_t* node = (node_t*) malloc(sizeof(node_t));
if(node == NULL) {
return NULL;
}
memset(node, '\0', sizeof(node_t));
node->data = data;
node->depth = 0;
node->next = NULL;
node->prev = NULL;
node->count = 0;
node->isLeaf = TRUE;
node->isRoot = TRUE;
node->parent = NULL;
node->children = node_list_create(node);
// Pass NULL to create a root node
if(parent != NULL) {
// This is a child node so attach it to it's parent
error = node_attach(parent, node);
if(error < 0) {
// Unable to attach nodes
printf("ERROR: %d \"Unable to attach nodes\"\n", error);
node_destroy(node);
return NULL;
}
}
return node;
}
int node_attach(node_t* parent, node_t* child) {
if (!parent || !child) return -1;
child->isLeaf = TRUE;
child->isRoot = FALSE;
child->parent = parent;
child->depth = parent->depth + 1;
if(parent->isLeaf == TRUE) {
parent->isLeaf = FALSE;
}
int res = node_list_add(parent->children, child);
if (res == 0) {
parent->count++;
}
return res;
}
int node_detach(node_t* parent, node_t* child) {
if (!parent || !child) return 0;
if (node_list_remove(parent->children, child) == 0) {
parent->count--;
}
return 0;
}
int node_insert(node_t* parent, unsigned int index, node_t* child)
{
if (!parent || !child) return -1;
child->isLeaf = TRUE;
child->isRoot = FALSE;
child->parent = parent;
child->depth = parent->depth + 1;
if(parent->isLeaf == TRUE) {
parent->isLeaf = FALSE;
}
int res = node_list_insert(parent->children, index, child);
if (res == 0) {
parent->count++;
}
return res;
}
void node_debug(node_t* node) {
unsigned int i = 0;
node_t* current = NULL;
node_iterator_t* iter = NULL;
for(i = 0; i < node->depth; i++) {
printf("\t");
}
if(node->isRoot) {
printf("ROOT\n");
}
if(node->isLeaf && !node->isRoot) {
printf("LEAF\n");
} else {
if(!node->isRoot) {
printf("NODE\n");
}
iter = node_iterator_create(node->children);
for(current = iter->begin; current != NULL; current = iter->next(iter)) {
node_debug(current);
}
}
}
unsigned int node_n_children(struct node_t* node)
{
if (!node) return 0;
return node->count;
}
node_t* node_nth_child(struct node_t* node, unsigned int n)
{
if (!node || !node->children || !node->children->begin) return NULL;
int index = 0;
int found = 0;
node_t *ch;
for (ch = node_first_child(node); ch; ch = node_next_sibling(ch)) {
if (index++ == n) {
found = 1;
break;
}
}
if (!found) {
return NULL;
}
return ch;
}
node_t* node_first_child(struct node_t* node)
{
if (!node || !node->children) return NULL;
return node->children->begin;
}
node_t* node_prev_sibling(struct node_t* node)
{
if (!node) return NULL;
return node->prev;
}
node_t* node_next_sibling(struct node_t* node)
{
if (!node) return NULL;
return node->next;
}
int node_child_position(struct node_t* parent, node_t* child)
{
if (!parent || !parent->children || !parent->children->begin || !child) return -1;
int index = 0;
int found = 0;
node_t *ch;
for (ch = node_first_child(parent); ch; ch = node_next_sibling(ch)) {
if (ch == child) {
found = 1;
break;
}
index++;
}
if (!found) {
return -1;
}
return index;
}
node_t* node_copy_deep(node_t* node, copy_func_t copy_func)
{
if (!node) return NULL;
void *data = NULL;
if (copy_func) {
data = copy_func(node->data);
}
node_t* copy = node_create(NULL, data);
node_t* ch;
for (ch = node_first_child(node); ch; ch = node_next_sibling(ch)) {
node_t* cc = node_copy_deep(ch, copy_func);
node_attach(copy, cc);
}
return copy;
}
|
azerg/NppBplistPlugin
|
src/NppBplistPlugin/dependencies/libimobiledevice/libcnary/node.c
|
C
|
bsd-3-clause
| 4,943 |
<!DOCTYPE html><html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
<meta charset="utf-8">
<title>Zend AMF API Documentation » \Zend_Loader_Autoloader</title>
<meta name="author" content="Mike van Riel">
<meta name="description" content="">
<link href="../css/template.css" rel="stylesheet" media="all">
<script src="../js/jquery-1.7.1.min.js" type="text/javascript"></script><script src="../js/jquery-ui-1.8.2.custom.min.js" type="text/javascript"></script><script src="../js/jquery.mousewheel.min.js" type="text/javascript"></script><script src="../js/bootstrap.js" type="text/javascript"></script><script src="../js/template.js" type="text/javascript"></script><script src="../js/prettify/prettify.min.js" type="text/javascript"></script><link rel="shortcut icon" href="../img/favicon.ico">
<link rel="apple-touch-icon" href="../img/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72" href="../img/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="../img/apple-touch-icon-114x114.png">
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner"><div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></a><a class="brand" href="../index.html">Zend AMF API Documentation</a><div class="nav-collapse"><ul class="nav">
<li class="dropdown">
<a href="#api" class="dropdown-toggle" data-toggle="dropdown">
API Documentation <b class="caret"></b></a><ul class="dropdown-menu">
<li><a>Packages</a></li>
<li><a href="../packages/Zend.html"><i class="icon-folder-open"></i> Zend</a></li>
<li><a href="../packages/Zend_Amf.html"><i class="icon-folder-open"></i> Zend_Amf</a></li>
<li><a href="../packages/Zend_Auth.html"><i class="icon-folder-open"></i> Zend_Auth</a></li>
<li><a href="../packages/Zend_Date.html"><i class="icon-folder-open"></i> Zend_Date</a></li>
<li><a href="../packages/Zend_Loader.html"><i class="icon-folder-open"></i> Zend_Loader</a></li>
<li><a href="../packages/Zend_Server.html"><i class="icon-folder-open"></i> Zend_Server</a></li>
<li><a href="../packages/Zend_Session.html"><i class="icon-folder-open"></i> Zend_Session</a></li>
<li><a href="../packages/Zend_Version.html"><i class="icon-folder-open"></i> Zend_Version</a></li>
</ul>
</li>
<li class="dropdown" id="reports-menu">
<a href="#reports" class="dropdown-toggle" data-toggle="dropdown">
Reports <b class="caret"></b></a><ul class="dropdown-menu">
<li><a href="../errors.html"><i class="icon-remove-sign"></i> Errors
<span class="label label-info">77</span></a></li>
<li><a href="../markers.html"><i class="icon-map-marker"></i> Markers
<ul></ul></a></li>
<li><a href="../deprecated.html"><i class="icon-stop"></i> Deprecated elements
<span class="label label-info">5</span></a></li>
</ul>
</li>
</ul></div>
</div></div>
<div class="go_to_top"><a href="#___" style="color: inherit">Back to top <i class="icon-upload icon-white"></i></a></div>
</div>
<div id="___" class="container">
<noscript><div class="alert alert-warning">
Javascript is disabled; several features are only available
if Javascript is enabled.
</div></noscript>
<div class="row">
<div class="span4">
<div xmlns:php="http://php.net/xsl" class="btn-toolbar">
<div class="btn-group visibility" data-toggle="buttons-checkbox">
<button class="btn public active" title="Show public elements">Public</button><button class="btn protected" title="Show protected elements">Protected</button><button class="btn private" title="Show private elements">Private</button><button class="btn inherited active" title="Show inherited elements">Inherited</button>
</div>
<div class="btn-group view pull-right" data-toggle="buttons-radio">
<button class="btn details" title="Show descriptions and method names"><i class="icon-list"></i></button><button class="btn simple" title="Show only method names"><i class="icon-align-justify"></i></button>
</div>
</div>
<ul xmlns:php="http://php.net/xsl" class="side-nav nav nav-list">
<li class="nav-header">
<i title="Methods" class="icon-custom icon-method"></i> Methods
<ul>
<li class="method public "><a href="#method_autoload" title="autoload() :: Autoload a class"><span class="description">Autoload a class</span><pre>autoload()</pre></a></li>
<li class="method public "><a href="#method_getAutoloaders" title="getAutoloaders() :: Get attached autoloader implementations"><span class="description">Get attached autoloader implementations</span><pre>getAutoloaders()</pre></a></li>
<li class="method public "><a href="#method_getClassAutoloaders" title="getClassAutoloaders() :: Get autoloaders to use when matching class"><span class="description">Get autoloaders to use when matching class</span><pre>getClassAutoloaders()</pre></a></li>
<li class="method public "><a href="#method_getDefaultAutoloader" title="getDefaultAutoloader() :: Retrieve the default autoloader callback"><span class="description">Retrieve the default autoloader callback</span><pre>getDefaultAutoloader()</pre></a></li>
<li class="method public "><a href="#method_getInstance" title="getInstance() :: Retrieve singleton instance"><span class="description">Retrieve singleton instance</span><pre>getInstance()</pre></a></li>
<li class="method public "><a href="#method_getNamespaceAutoloaders" title="getNamespaceAutoloaders() :: Return all autoloaders for a given namespace"><span class="description">Return all autoloaders for a given namespace</span><pre>getNamespaceAutoloaders()</pre></a></li>
<li class="method public "><a href="#method_getRegisteredNamespaces" title="getRegisteredNamespaces() :: Get a list of registered autoload namespaces"><span class="description">Get a list of registered autoload namespaces</span><pre>getRegisteredNamespaces()</pre></a></li>
<li class="method public "><a href="#method_getZfPath" title="getZfPath() :: "><span class="description">getZfPath()
</span><pre>getZfPath()</pre></a></li>
<li class="method public "><a href="#method_isFallbackAutoloader" title="isFallbackAutoloader() :: Is this instance acting as a fallback autoloader?"><span class="description">Is this instance acting as a fallback autoloader?</span><pre>isFallbackAutoloader()</pre></a></li>
<li class="method public "><a href="#method_pushAutoloader" title="pushAutoloader() :: Append an autoloader to the autoloader stack"><span class="description">Append an autoloader to the autoloader stack</span><pre>pushAutoloader()</pre></a></li>
<li class="method public "><a href="#method_registerNamespace" title="registerNamespace() :: Register a namespace to autoload"><span class="description">Register a namespace to autoload</span><pre>registerNamespace()</pre></a></li>
<li class="method public "><a href="#method_removeAutoloader" title="removeAutoloader() :: Remove an autoloader from the autoloader stack"><span class="description">Remove an autoloader from the autoloader stack</span><pre>removeAutoloader()</pre></a></li>
<li class="method public "><a href="#method_resetInstance" title="resetInstance() :: Reset the singleton instance"><span class="description">Reset the singleton instance</span><pre>resetInstance()</pre></a></li>
<li class="method public "><a href="#method_setAutoloaders" title="setAutoloaders() :: Set several autoloader callbacks at once"><span class="description">Set several autoloader callbacks at once</span><pre>setAutoloaders()</pre></a></li>
<li class="method public "><a href="#method_setDefaultAutoloader" title="setDefaultAutoloader() :: Set the default autoloader implementation"><span class="description">Set the default autoloader implementation</span><pre>setDefaultAutoloader()</pre></a></li>
<li class="method public "><a href="#method_setFallbackAutoloader" title="setFallbackAutoloader() :: Indicate whether or not this autoloader should be a fallback autoloader"><span class="description">Indicate whether or not this autoloader should be a fallback autoloader</span><pre>setFallbackAutoloader()</pre></a></li>
<li class="method public "><a href="#method_setZfPath" title="setZfPath() :: "><span class="description">setZfPath()
</span><pre>setZfPath()</pre></a></li>
<li class="method public "><a href="#method_suppressNotFoundWarnings" title='suppressNotFoundWarnings() :: Get or set the value of the "suppress not found warnings" flag'><span class="description">Get or set the value of the "suppress not found warnings" flag</span><pre>suppressNotFoundWarnings()</pre></a></li>
<li class="method public "><a href="#method_unregisterNamespace" title="unregisterNamespace() :: Unload a registered autoload namespace"><span class="description">Unload a registered autoload namespace</span><pre>unregisterNamespace()</pre></a></li>
<li class="method public "><a href="#method_unshiftAutoloader" title="unshiftAutoloader() :: Add an autoloader to the beginning of the stack"><span class="description">Add an autoloader to the beginning of the stack</span><pre>unshiftAutoloader()</pre></a></li>
</ul>
</li>
<li class="nav-header protected">» Protected
<ul>
<li class="method protected "><a href="#method___construct" title="__construct() :: Constructor"><span class="description">Constructor</span><pre>__construct()</pre></a></li>
<li class="method protected "><a href="#method__autoload" title="_autoload() :: Internal autoloader implementation"><span class="description">Internal autoloader implementation</span><pre>_autoload()</pre></a></li>
<li class="method protected "><a href="#method__getAvailableVersions" title="_getAvailableVersions() :: Get available versions for the version type requested"><span class="description">Get available versions for the version type requested</span><pre>_getAvailableVersions()</pre></a></li>
<li class="method protected "><a href="#method__getVersionPath" title="_getVersionPath() :: Retrieve the filesystem path for the requested ZF version"><span class="description">Retrieve the filesystem path for the requested ZF version</span><pre>_getVersionPath()</pre></a></li>
<li class="method protected "><a href="#method__getVersionType" title="_getVersionType() :: Retrieve the ZF version type"><span class="description">Retrieve the ZF version type</span><pre>_getVersionType()</pre></a></li>
<li class="method protected "><a href="#method__setNamespaceAutoloaders" title="_setNamespaceAutoloaders() :: Set autoloaders for a specific namespace"><span class="description">Set autoloaders for a specific namespace</span><pre>_setNamespaceAutoloaders()</pre></a></li>
</ul>
</li>
<li class="nav-header">
<i title="Properties" class="icon-custom icon-property"></i> Properties
<ul></ul>
</li>
<li class="nav-header protected">» Protected
<ul>
<li class="property protected "><a href="#property__autoloaders" title="$_autoloaders() :: "><span class="description">Concrete autoloader callback implementations</span><pre>$_autoloaders</pre></a></li>
<li class="property protected "><a href="#property__defaultAutoloader" title="$_defaultAutoloader() :: "><span class="description">Default autoloader callback</span><pre>$_defaultAutoloader</pre></a></li>
<li class="property protected "><a href="#property__fallbackAutoloader" title="$_fallbackAutoloader() :: "><span class="description">Whether or not to act as a fallback autoloader</span><pre>$_fallbackAutoloader</pre></a></li>
<li class="property protected "><a href="#property__instance" title="$_instance() :: "><span class="description">Singleton instance</span><pre>$_instance</pre></a></li>
<li class="property protected "><a href="#property__internalAutoloader" title="$_internalAutoloader() :: "><span class="description">Callback for internal autoloader implementation</span><pre>$_internalAutoloader</pre></a></li>
<li class="property protected "><a href="#property__namespaceAutoloaders" title="$_namespaceAutoloaders() :: "><span class="description">Namespace-specific autoloaders</span><pre>$_namespaceAutoloaders</pre></a></li>
<li class="property protected "><a href="#property__namespaces" title="$_namespaces() :: "><span class="description">Supported namespaces 'Zend' and 'ZendX' by default.</span><pre>$_namespaces</pre></a></li>
<li class="property protected "><a href="#property__suppressNotFoundWarnings" title="$_suppressNotFoundWarnings() :: "><span class="description">Whether or not to suppress file not found warnings</span><pre>$_suppressNotFoundWarnings</pre></a></li>
<li class="property protected "><a href="#property__zfPath" title="$_zfPath() :: "><span class="description"></span><pre>$_zfPath</pre></a></li>
</ul>
</li>
</ul>
</div>
<div class="span8">
<a xmlns:php="http://php.net/xsl" id="\Zend_Loader_Autoloader"></a><ul xmlns:php="http://php.net/xsl" class="breadcrumb">
<li>
<a href="../index.html"><i title="Classes" class="icon-custom icon-class"></i></a><span class="divider">\</span>
</li>
<li class="active">
<span class="divider">\</span><a href="../classes/Zend_Loader_Autoloader.html">Zend_Loader_Autoloader</a>
</li>
</ul>
<div xmlns:php="http://php.net/xsl" class="element class">
<p class="short_description">Autoloader stack and namespace autoloader</p>
<div class="details">
<div class="long_description"></div>
<table class="table table-bordered">
<tr>
<th>uses</th>
<td><a href="Zend_Loader_Autoloader"></a></td>
</tr>
<tr>
<th>package</th>
<td><a href="../packages/Zend_Loader.Autoloader.html">Zend_Loader</a></td>
</tr>
<tr>
<th>subpackage</th>
<td>Autoloader</td>
</tr>
<tr>
<th>copyright</th>
<td>Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)</td>
</tr>
<tr>
<th>license</th>
<td><a href="http://framework.zend.com/license/new-bsd">New BSD License</a></td>
</tr>
</table>
<h3>
<i title="Methods" class="icon-custom icon-method"></i> Methods</h3>
<a id="method_autoload"></a><div class="element clickable method public method_autoload " data-toggle="collapse" data-target=".method_autoload .collapse" title="public">
<h2>Autoload a class</h2>
<pre>autoload(string $class) : boolean</pre>
<div class="labels"><span class="label">Static</span></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$class</h4>
<code>string</code>
</div>
<h3>Returns</h3>
<div class="subelement response"><code>boolean</code></div>
</div></div>
</div>
<a id="method_getAutoloaders"></a><div class="element clickable method public method_getAutoloaders " data-toggle="collapse" data-target=".method_getAutoloaders .collapse" title="public">
<h2>Get attached autoloader implementations</h2>
<pre>getAutoloaders() : array</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Returns</h3>
<div class="subelement response"><code>array</code></div>
</div></div>
</div>
<a id="method_getClassAutoloaders"></a><div class="element clickable method public method_getClassAutoloaders " data-toggle="collapse" data-target=".method_getClassAutoloaders .collapse" title="public">
<h2>Get autoloaders to use when matching class</h2>
<pre>getClassAutoloaders(string $class) : array</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"><p>Determines if the class matches a registered namespace, and, if so,
returns only the autoloaders for that namespace. Otherwise, it returns
all non-namespaced autoloaders.</p></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$class</h4>
<code>string</code>
</div>
<h3>Returns</h3>
<div class="subelement response">
<code>array</code>Array of autoloaders to use</div>
</div></div>
</div>
<a id="method_getDefaultAutoloader"></a><div class="element clickable method public method_getDefaultAutoloader " data-toggle="collapse" data-target=".method_getDefaultAutoloader .collapse" title="public">
<h2>Retrieve the default autoloader callback</h2>
<pre>getDefaultAutoloader() : string | array</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Returns</h3>
<div class="subelement response">
<code>string</code><code>array</code>PHP Callback</div>
</div></div>
</div>
<a id="method_getInstance"></a><div class="element clickable method public method_getInstance " data-toggle="collapse" data-target=".method_getInstance .collapse" title="public">
<h2>Retrieve singleton instance</h2>
<pre>getInstance() : \Zend_Loader_Autoloader</pre>
<div class="labels"><span class="label">Static</span></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Returns</h3>
<div class="subelement response"><code>\Zend_Loader_Autoloader</code></div>
</div></div>
</div>
<a id="method_getNamespaceAutoloaders"></a><div class="element clickable method public method_getNamespaceAutoloaders " data-toggle="collapse" data-target=".method_getNamespaceAutoloaders .collapse" title="public">
<h2>Return all autoloaders for a given namespace</h2>
<pre>getNamespaceAutoloaders(string $namespace) : array</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$namespace</h4>
<code>string</code>
</div>
<h3>Returns</h3>
<div class="subelement response"><code>array</code></div>
</div></div>
</div>
<a id="method_getRegisteredNamespaces"></a><div class="element clickable method public method_getRegisteredNamespaces " data-toggle="collapse" data-target=".method_getRegisteredNamespaces .collapse" title="public">
<h2>Get a list of registered autoload namespaces</h2>
<pre>getRegisteredNamespaces() : array</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Returns</h3>
<div class="subelement response"><code>array</code></div>
</div></div>
</div>
<a id="method_getZfPath"></a><div class="element clickable method public method_getZfPath " data-toggle="collapse" data-target=".method_getZfPath .collapse" title="public">
<h2>getZfPath()
</h2>
<pre>getZfPath() </pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div>
</div>
<a id="method_isFallbackAutoloader"></a><div class="element clickable method public method_isFallbackAutoloader " data-toggle="collapse" data-target=".method_isFallbackAutoloader .collapse" title="public">
<h2>Is this instance acting as a fallback autoloader?</h2>
<pre>isFallbackAutoloader() : boolean</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Returns</h3>
<div class="subelement response"><code>boolean</code></div>
</div></div>
</div>
<a id="method_pushAutoloader"></a><div class="element clickable method public method_pushAutoloader " data-toggle="collapse" data-target=".method_pushAutoloader .collapse" title="public">
<h2>Append an autoloader to the autoloader stack</h2>
<pre>pushAutoloader(object|array|string $callback, string|array $namespace<code> = ''</code>) : \Zend_Loader_Autoloader</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$callback</h4>
<code>object</code><code>array</code><code>string</code><p>PHP callback or Zend_Loader_Autoloader_Interface implementation</p></div>
<div class="subelement argument">
<h4>$namespace</h4>
<code>string</code><code>array</code><p>Specific namespace(s) under which to register callback</p></div>
<h3>Returns</h3>
<div class="subelement response"><code>\Zend_Loader_Autoloader</code></div>
</div></div>
</div>
<a id="method_registerNamespace"></a><div class="element clickable method public method_registerNamespace " data-toggle="collapse" data-target=".method_registerNamespace .collapse" title="public">
<h2>Register a namespace to autoload</h2>
<pre>registerNamespace(string|array $namespace) : \Zend_Loader_Autoloader</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$namespace</h4>
<code>string</code><code>array</code>
</div>
<h3>Returns</h3>
<div class="subelement response"><code>\Zend_Loader_Autoloader</code></div>
</div></div>
</div>
<a id="method_removeAutoloader"></a><div class="element clickable method public method_removeAutoloader " data-toggle="collapse" data-target=".method_removeAutoloader .collapse" title="public">
<h2>Remove an autoloader from the autoloader stack</h2>
<pre>removeAutoloader(object|array|string $callback, null|string|array $namespace<code> = null</code>) : \Zend_Loader_Autoloader</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$callback</h4>
<code>object</code><code>array</code><code>string</code><p>PHP callback or Zend_Loader_Autoloader_Interface implementation</p></div>
<div class="subelement argument">
<h4>$namespace</h4>
<code>null</code><code>string</code><code>array</code><p>Specific namespace(s) from which to remove autoloader</p></div>
<h3>Returns</h3>
<div class="subelement response"><code>\Zend_Loader_Autoloader</code></div>
</div></div>
</div>
<a id="method_resetInstance"></a><div class="element clickable method public method_resetInstance " data-toggle="collapse" data-target=".method_resetInstance .collapse" title="public">
<h2>Reset the singleton instance</h2>
<pre>resetInstance() : void</pre>
<div class="labels"><span class="label">Static</span></div>
<div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div>
</div>
<a id="method_setAutoloaders"></a><div class="element clickable method public method_setAutoloaders " data-toggle="collapse" data-target=".method_setAutoloaders .collapse" title="public">
<h2>Set several autoloader callbacks at once</h2>
<pre>setAutoloaders(array $autoloaders) : \Zend_Loader_Autoloader</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$autoloaders</h4>
<code>array</code><p>Array of PHP callbacks (or Zend_Loader_Autoloader_Interface implementations) to act as autoloaders</p></div>
<h3>Returns</h3>
<div class="subelement response"><code>\Zend_Loader_Autoloader</code></div>
</div></div>
</div>
<a id="method_setDefaultAutoloader"></a><div class="element clickable method public method_setDefaultAutoloader " data-toggle="collapse" data-target=".method_setDefaultAutoloader .collapse" title="public">
<h2>Set the default autoloader implementation</h2>
<pre>setDefaultAutoloader(string|array $callback) : void</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$callback</h4>
<code>string</code><code>array</code><p>PHP callback</p></div>
</div></div>
</div>
<a id="method_setFallbackAutoloader"></a><div class="element clickable method public method_setFallbackAutoloader " data-toggle="collapse" data-target=".method_setFallbackAutoloader .collapse" title="public">
<h2>Indicate whether or not this autoloader should be a fallback autoloader</h2>
<pre>setFallbackAutoloader(boolean $flag) : \Zend_Loader_Autoloader</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$flag</h4>
<code>boolean</code>
</div>
<h3>Returns</h3>
<div class="subelement response"><code>\Zend_Loader_Autoloader</code></div>
</div></div>
</div>
<a id="method_setZfPath"></a><div class="element clickable method public method_setZfPath " data-toggle="collapse" data-target=".method_setZfPath .collapse" title="public">
<h2>setZfPath()
</h2>
<pre>setZfPath($spec, $version<code> = 'latest'</code>) </pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Parameters</h3>
<div class="subelement argument"><h4>$spec</h4></div>
<div class="subelement argument"><h4>$version</h4></div>
</div></div>
</div>
<a id="method_suppressNotFoundWarnings"></a><div class="element clickable method public method_suppressNotFoundWarnings " data-toggle="collapse" data-target=".method_suppressNotFoundWarnings .collapse" title="public">
<h2>Get or set the value of the "suppress not found warnings" flag</h2>
<pre>suppressNotFoundWarnings(null|boolean $flag<code> = null</code>) : boolean | \Zend_Loader_Autoloader</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$flag</h4>
<code>null</code><code>boolean</code>
</div>
<h3>Returns</h3>
<div class="subelement response">
<code>boolean</code><code>\Zend_Loader_Autoloader</code>Returns boolean if no argument is passed, object instance otherwise</div>
</div></div>
</div>
<a id="method_unregisterNamespace"></a><div class="element clickable method public method_unregisterNamespace " data-toggle="collapse" data-target=".method_unregisterNamespace .collapse" title="public">
<h2>Unload a registered autoload namespace</h2>
<pre>unregisterNamespace(string|array $namespace) : \Zend_Loader_Autoloader</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$namespace</h4>
<code>string</code><code>array</code>
</div>
<h3>Returns</h3>
<div class="subelement response"><code>\Zend_Loader_Autoloader</code></div>
</div></div>
</div>
<a id="method_unshiftAutoloader"></a><div class="element clickable method public method_unshiftAutoloader " data-toggle="collapse" data-target=".method_unshiftAutoloader .collapse" title="public">
<h2>Add an autoloader to the beginning of the stack</h2>
<pre>unshiftAutoloader(object|array|string $callback, string|array $namespace<code> = ''</code>) : \Zend_Loader_Autoloader</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$callback</h4>
<code>object</code><code>array</code><code>string</code><p>PHP callback or Zend_Loader_Autoloader_Interface implementation</p></div>
<div class="subelement argument">
<h4>$namespace</h4>
<code>string</code><code>array</code><p>Specific namespace(s) under which to register callback</p></div>
<h3>Returns</h3>
<div class="subelement response"><code>\Zend_Loader_Autoloader</code></div>
</div></div>
</div>
<a id="method___construct"></a><div class="element clickable method protected method___construct " data-toggle="collapse" data-target=".method___construct .collapse" title="protected">
<h2>Constructor</h2>
<pre>__construct() : void</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description"><div class="long_description"><p>Registers instance with spl_autoload stack</p></div></div></div>
</div>
<a id="method__autoload"></a><div class="element clickable method protected method__autoload " data-toggle="collapse" data-target=".method__autoload .collapse" title="protected">
<h2>Internal autoloader implementation</h2>
<pre>_autoload(string $class) : boolean</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$class</h4>
<code>string</code>
</div>
<h3>Returns</h3>
<div class="subelement response"><code>boolean</code></div>
</div></div>
</div>
<a id="method__getAvailableVersions"></a><div class="element clickable method protected method__getAvailableVersions " data-toggle="collapse" data-target=".method__getAvailableVersions .collapse" title="protected">
<h2>Get available versions for the version type requested</h2>
<pre>_getAvailableVersions(string $path, string $version) : array</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$path</h4>
<code>string</code>
</div>
<div class="subelement argument">
<h4>$version</h4>
<code>string</code>
</div>
<h3>Returns</h3>
<div class="subelement response"><code>array</code></div>
</div></div>
</div>
<a id="method__getVersionPath"></a><div class="element clickable method protected method__getVersionPath " data-toggle="collapse" data-target=".method__getVersionPath .collapse" title="protected">
<h2>Retrieve the filesystem path for the requested ZF version</h2>
<pre>_getVersionPath(string $path, string $version) : void</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$path</h4>
<code>string</code>
</div>
<div class="subelement argument">
<h4>$version</h4>
<code>string</code>
</div>
</div></div>
</div>
<a id="method__getVersionType"></a><div class="element clickable method protected method__getVersionType " data-toggle="collapse" data-target=".method__getVersionType .collapse" title="protected">
<h2>Retrieve the ZF version type</h2>
<pre>_getVersionType(string $version) : string</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$version</h4>
<code>string</code>
</div>
<h3>Exceptions</h3>
<table class="table table-bordered"><tr>
<th><code>\Zend_Loader_Exception</code></th>
<td>if version string contains too many dots</td>
</tr></table>
<h3>Returns</h3>
<div class="subelement response">
<code>string</code>"latest", "major", "minor", or "specific"</div>
</div></div>
</div>
<a id="method__setNamespaceAutoloaders"></a><div class="element clickable method protected method__setNamespaceAutoloaders " data-toggle="collapse" data-target=".method__setNamespaceAutoloaders .collapse" title="protected">
<h2>Set autoloaders for a specific namespace</h2>
<pre>_setNamespaceAutoloaders(array $autoloaders, string $namespace<code> = ''</code>) : \Zend_Loader_Autoloader</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$autoloaders</h4>
<code>array</code>
</div>
<div class="subelement argument">
<h4>$namespace</h4>
<code>string</code>
</div>
<h3>Returns</h3>
<div class="subelement response"><code>\Zend_Loader_Autoloader</code></div>
</div></div>
</div>
<h3>
<i title="Properties" class="icon-custom icon-property"></i> Properties</h3>
<a id="property__autoloaders"> </a><div class="element clickable property protected property__autoloaders" data-toggle="collapse" data-target=".property__autoloaders .collapse" title="protected">
<h2>Concrete autoloader callback implementations</h2>
<pre>$_autoloaders : array</pre>
<div class="row collapse"><div class="detail-description">
<h3>Default</h3>
<div class="subelement argument"><code>array()</code></div>
</div></div>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div>
</div>
<a id="property__defaultAutoloader"> </a><div class="element clickable property protected property__defaultAutoloader" data-toggle="collapse" data-target=".property__defaultAutoloader .collapse" title="protected">
<h2>Default autoloader callback</h2>
<pre>$_defaultAutoloader : array</pre>
<div class="row collapse"><div class="detail-description">
<h3>Default</h3>
<div class="subelement argument"><code>array('Zend_Loader', 'loadClass')</code></div>
</div></div>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div>
</div>
<a id="property__fallbackAutoloader"> </a><div class="element clickable property protected property__fallbackAutoloader" data-toggle="collapse" data-target=".property__fallbackAutoloader .collapse" title="protected">
<h2>Whether or not to act as a fallback autoloader</h2>
<pre>$_fallbackAutoloader : boolean</pre>
<div class="row collapse"><div class="detail-description">
<h3>Default</h3>
<div class="subelement argument"><code>false</code></div>
</div></div>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div>
</div>
<a id="property__instance"> </a><div class="element clickable property protected property__instance" data-toggle="collapse" data-target=".property__instance .collapse" title="protected">
<h2>Singleton instance</h2>
<pre>$_instance : \Zend_Loader_Autoloader</pre>
<div class="row collapse"><div class="detail-description">
<h3>Default</h3>
<div class="subelement argument"></div>
</div></div>
<div class="labels"><span class="label">Static</span></div>
<div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div>
</div>
<a id="property__internalAutoloader"> </a><div class="element clickable property protected property__internalAutoloader" data-toggle="collapse" data-target=".property__internalAutoloader .collapse" title="protected">
<h2>Callback for internal autoloader implementation</h2>
<pre>$_internalAutoloader : array</pre>
<div class="row collapse"><div class="detail-description">
<h3>Default</h3>
<div class="subelement argument"></div>
</div></div>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div>
</div>
<a id="property__namespaceAutoloaders"> </a><div class="element clickable property protected property__namespaceAutoloaders" data-toggle="collapse" data-target=".property__namespaceAutoloaders .collapse" title="protected">
<h2>Namespace-specific autoloaders</h2>
<pre>$_namespaceAutoloaders : array</pre>
<div class="row collapse"><div class="detail-description">
<h3>Default</h3>
<div class="subelement argument"><code>array()</code></div>
</div></div>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div>
</div>
<a id="property__namespaces"> </a><div class="element clickable property protected property__namespaces" data-toggle="collapse" data-target=".property__namespaces .collapse" title="protected">
<h2>Supported namespaces 'Zend' and 'ZendX' by default.</h2>
<pre>$_namespaces : array</pre>
<div class="row collapse"><div class="detail-description">
<h3>Default</h3>
<div class="subelement argument"><code>array('Zend_' => true, 'ZendX_' => true)</code></div>
</div></div>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div>
</div>
<a id="property__suppressNotFoundWarnings"> </a><div class="element clickable property protected property__suppressNotFoundWarnings" data-toggle="collapse" data-target=".property__suppressNotFoundWarnings .collapse" title="protected">
<h2>Whether or not to suppress file not found warnings</h2>
<pre>$_suppressNotFoundWarnings : boolean</pre>
<div class="row collapse"><div class="detail-description">
<h3>Default</h3>
<div class="subelement argument"><code>false</code></div>
</div></div>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div>
</div>
<a id="property__zfPath"> </a><div class="element clickable property protected property__zfPath" data-toggle="collapse" data-target=".property__zfPath .collapse" title="protected">
<h2>$_zfPath</h2>
<pre>$_zfPath : null | string</pre>
<div class="row collapse"><div class="detail-description">
<h3>Default</h3>
<div class="subelement argument"></div>
</div></div>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div>
</div>
</div>
</div>
</div>
</div>
<div class="row"><footer class="span12">
Template is built using <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap 2</a> and icons provided by <a href="http://glyphicons.com/">Glyphicons</a>.<br>
Documentation is powered by <a href="http://www.phpdoc.org/">phpDocumentor 2.8.5</a> and<br>
generated on 2015-11-23T12:38:53-06:00.<br></footer></div>
</div>
</body>
</html>
|
Notan/awery_zend_amf
|
documentation/api/core/classes/Zend_Loader_Autoloader.html
|
HTML
|
bsd-3-clause
| 37,412 |
# Copyright (c) 2003-2005 Maxim Sobolev. All rights reserved.
# Copyright (c) 2006-2007 Sippy Software, Inc. All rights reserved.
#
# This file is part of SIPPY, a free RFC3261 SIP stack and B2BUA.
#
# SIPPY is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# For a license to use the SIPPY software under conditions
# other than those described here, or to purchase support for this
# software, please contact Sippy Software, Inc. by e-mail at the
# following addresses: [email protected].
#
# SIPPY 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
from random import random
from hashlib import md5
from time import time
from .SipConf import SipConf
from .SipGenericHF import SipGenericHF
class SipCallId(SipGenericHF):
hf_names = ('call-id', 'i')
body = None
def __init__(self, body = None):
SipGenericHF.__init__(self, body)
self.parsed = True
if body == None:
self.body = md5(str((random() * 1000000000) + time())).hexdigest() + '@' + str(SipConf.my_address)
def __add__(self, other):
return SipCallId(self.body + str(other))
def genCallId(self):
self.body = md5(str((random() * 1000000000) + time())).hexdigest() + '@' + str(SipConf.my_address)
def getCanName(self, name, compact = False):
if compact:
return 'i'
return 'Call-ID'
|
hgascon/pulsar
|
pulsar/core/sippy/SipCallId.py
|
Python
|
bsd-3-clause
| 1,919 |
/*-
* Copyright (c) 2001 Atsushi Onoe
* Copyright (c) 2002, 2003 Sam Leffler, Errno Consulting
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* $FreeBSD: src/sys/net80211/ieee80211_ioctl.h,v 1.4 2003/10/17 23:15:30 sam Exp $
*/
#ifndef _NET80211_IEEE80211_IOCTL_H_
#define _NET80211_IEEE80211_IOCTL_H_
/*
* IEEE 802.11 ioctls.
*/
struct ieee80211_stats {
u_int32_t is_rx_badversion; /* rx frame with bad version */
u_int32_t is_rx_tooshort; /* rx frame too short */
u_int32_t is_rx_wrongbss; /* rx from wrong bssid */
u_int32_t is_rx_dup; /* rx discard 'cuz dup */
u_int32_t is_rx_wrongdir; /* rx w/ wrong direction */
u_int32_t is_rx_mcastecho; /* rx discard 'cuz mcast echo */
u_int32_t is_rx_notassoc; /* rx discard 'cuz sta !assoc */
u_int32_t is_rx_nowep; /* rx w/ wep but wep !config */
u_int32_t is_rx_wepfail; /* rx wep processing failed */
u_int32_t is_rx_decap; /* rx decapsulation failed */
u_int32_t is_rx_mgtdiscard; /* rx discard mgt frames */
u_int32_t is_rx_ctl; /* rx discard ctrl frames */
u_int32_t is_rx_rstoobig; /* rx rate set truncated */
u_int32_t is_rx_elem_missing; /* rx required element missing*/
u_int32_t is_rx_elem_toobig; /* rx element too big */
u_int32_t is_rx_elem_toosmall; /* rx element too small */
u_int32_t is_rx_elem_unknown; /* rx element unknown */
u_int32_t is_rx_badchan; /* rx frame w/ invalid chan */
u_int32_t is_rx_chanmismatch; /* rx frame chan mismatch */
u_int32_t is_rx_nodealloc; /* rx frame dropped */
u_int32_t is_rx_ssidmismatch; /* rx frame ssid mismatch */
u_int32_t is_rx_auth_unsupported; /* rx w/ unsupported auth alg */
u_int32_t is_rx_auth_fail; /* rx sta auth failure */
u_int32_t is_rx_assoc_bss; /* rx assoc from wrong bssid */
u_int32_t is_rx_assoc_notauth; /* rx assoc w/o auth */
u_int32_t is_rx_assoc_capmismatch;/* rx assoc w/ cap mismatch */
u_int32_t is_rx_assoc_norate; /* rx assoc w/ no rate match */
u_int32_t is_rx_deauth; /* rx deauthentication */
u_int32_t is_rx_disassoc; /* rx disassociation */
u_int32_t is_rx_badsubtype; /* rx frame w/ unknown subtype*/
u_int32_t is_rx_nombuf; /* rx failed for lack of mbuf */
u_int32_t is_rx_decryptcrc; /* rx decrypt failed on crc */
u_int32_t is_rx_ahdemo_mgt; /* rx discard ahdemo mgt frame*/
u_int32_t is_rx_bad_auth; /* rx bad auth request */
u_int32_t is_tx_nombuf; /* tx failed for lack of mbuf */
u_int32_t is_tx_nonode; /* tx failed for no node */
u_int32_t is_tx_unknownmgt; /* tx of unknown mgt frame */
u_int32_t is_scan_active; /* active scans started */
u_int32_t is_scan_passive; /* passive scans started */
u_int32_t is_node_timeout; /* nodes timed out inactivity */
u_int32_t is_crypto_nomem; /* no memory for crypto ctx */
};
#ifdef __FreeBSD__
/*
* FreeBSD-style ioctls.
*/
/* the first member must be matched with struct ifreq */
struct ieee80211req {
char i_name[IFNAMSIZ]; /* if_name, e.g. "wi0" */
u_int16_t i_type; /* req type */
int16_t i_val; /* Index or simple value */
int16_t i_len; /* Index or simple value */
void *i_data; /* Extra data */
};
#define SIOCS80211 _IOW('i', 234, struct ieee80211req)
#define SIOCG80211 _IOWR('i', 235, struct ieee80211req)
#define IEEE80211_IOC_SSID 1
#define IEEE80211_IOC_NUMSSIDS 2
#define IEEE80211_IOC_WEP 3
#define IEEE80211_WEP_NOSUP -1
#define IEEE80211_WEP_OFF 0
#define IEEE80211_WEP_ON 1
#define IEEE80211_WEP_MIXED 2
#define IEEE80211_IOC_WEPKEY 4
#define IEEE80211_IOC_NUMWEPKEYS 5
#define IEEE80211_IOC_WEPTXKEY 6
#define IEEE80211_IOC_AUTHMODE 7
#define IEEE80211_IOC_STATIONNAME 8
#define IEEE80211_IOC_CHANNEL 9
#define IEEE80211_IOC_POWERSAVE 10
#define IEEE80211_POWERSAVE_NOSUP -1
#define IEEE80211_POWERSAVE_OFF 0
#define IEEE80211_POWERSAVE_CAM 1
#define IEEE80211_POWERSAVE_PSP 2
#define IEEE80211_POWERSAVE_PSP_CAM 3
#define IEEE80211_POWERSAVE_ON IEEE80211_POWERSAVE_CAM
#define IEEE80211_IOC_POWERSAVESLEEP 11
#define IEEE80211_IOC_RTSTHRESHOLD 12
#ifndef IEEE80211_CHAN_ANY
#define IEEE80211_CHAN_ANY 0xffff /* token for ``any channel'' */
#endif
#define SIOCG80211STATS _IOWR('i', 236, struct ifreq)
#endif /* __FreeBSD__ */
#endif /* _NET80211_IEEE80211_IOCTL_H_ */
|
MarginC/kame
|
freebsd5/sys/net80211/ieee80211_ioctl.h
|
C
|
bsd-3-clause
| 5,750 |
// Copyright 2019 Google LLC.
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#include "fiddle/examples.h"
// HASH=37ffe2817d720f99e6c252332ce70460
REG_FIDDLE(IPoint_equal_operator, 256, 256, true, 0) {
void draw(SkCanvas* canvas) {
SkIPoint test[] = { {0, -0}, {-1, -2}, {SK_MaxS32, -1}, {SK_NaN32, -1} };
for (const SkIPoint& pt : test) {
SkDebugf("pt: %d, %d %c= pt\n", pt.fX, pt.fY, pt == pt ? '=' : '!');
}
}
} // END FIDDLE
|
rubenvb/skia
|
docs/examples/IPoint_equal_operator.cpp
|
C++
|
bsd-3-clause
| 505 |
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan, Robert Haschke */
#pragma once
#include <moveit/move_group/move_group_capability.h>
#include <moveit_msgs/QueryPlannerInterfaces.h>
#include <moveit_msgs/GetPlannerParams.h>
#include <moveit_msgs/SetPlannerParams.h>
namespace move_group
{
class MoveGroupQueryPlannersService : public MoveGroupCapability
{
public:
MoveGroupQueryPlannersService();
void initialize() override;
private:
bool queryInterface(moveit_msgs::QueryPlannerInterfaces::Request& req,
moveit_msgs::QueryPlannerInterfaces::Response& res);
bool getParams(moveit_msgs::GetPlannerParams::Request& req, moveit_msgs::GetPlannerParams::Response& res);
bool setParams(moveit_msgs::SetPlannerParams::Request& req, moveit_msgs::SetPlannerParams::Response& res);
ros::ServiceServer query_service_;
ros::ServiceServer get_service_;
ros::ServiceServer set_service_;
};
} // namespace move_group
|
ros-planning/moveit
|
moveit_ros/move_group/src/default_capabilities/query_planners_service_capability.h
|
C
|
bsd-3-clause
| 2,720 |
/*================================================================================
Copyright (c) 2013 Steve Jin. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
@SuppressWarnings("all")
public class ExtensionFaultTypeInfo extends DynamicData {
public String faultID;
public String getFaultID() {
return this.faultID;
}
public void setFaultID(String faultID) {
this.faultID=faultID;
}
}
|
paksv/vijava
|
src/com/vmware/vim25/ExtensionFaultTypeInfo.java
|
Java
|
bsd-3-clause
| 1,985 |
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Doozr - Configuration - Hierarchy - Kernel - System.
*
* System.php - The "system" node representation for providing autocompletion for configuration values.
*
* PHP versions 5.5
*
* LICENSE:
* Doozr - The lightweight PHP-Framework for high-performance websites
*
* Copyright (c) 2005 - 2016, Benjamin Carl - All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - All advertising materials mentioning features or use of this software
* must display the following acknowledgment: This product includes software
* developed by Benjamin Carl and other contributors.
* - Neither the name Benjamin Carl nor the names of other contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Please feel free to contact us via e-mail: [email protected]
*
* @category Doozr
*
* @author Benjamin Carl <[email protected]>
* @copyright 2005 - 2016 Benjamin Carl
* @license http://www.opensource.org/licenses/bsd-license.php The BSD License
*
* @version Git: $Id$
*
* @link http://clickalicious.github.com/Doozr/
*/
/**
* Doozr - Configuration - Hierarchy - Kernel - System.
*
* The "system" node representation for providing autocompletion for configuration values.
*
* @category Doozr
*
* @author Benjamin Carl <[email protected]>
* @copyright 2005 - 2016 Benjamin Carl
* @license http://www.opensource.org/licenses/bsd-license.php The BSD License
*
* @version Git: $Id$
*
* @link http://clickalicious.github.com/Doozr/
*/
class Doozr_Configuration_Hierarchy_Kernel_System
{
/**
* Configuration of php.ini keys and values.
*
* @var Doozr_Configuration_Hierarchy_Kernel_System_Php
*/
public $php;
}
|
clickalicious/DoozR
|
src/Doozr/Configuration/Hierarchy/Kernel/System.php
|
PHP
|
bsd-3-clause
| 3,152 |
/*
* vqec_config_parser.h - Implements parsing of VQE-C system configuration
* files.
*
* Copyright (c) 2007-2009 by Cisco Systems, Inc.
* All rights reserved.
*/
#include "queue_plus.h"
#include "vam_types.h"
/**
* Enumeration of setting types.
*/
typedef enum vqec_config_setting_type_ {
VQEC_CONFIG_SETTING_TYPE_INVALID = 0,
VQEC_CONFIG_SETTING_TYPE_STRING,
VQEC_CONFIG_SETTING_TYPE_BOOLEAN,
VQEC_CONFIG_SETTING_TYPE_INT,
VQEC_CONFIG_SETTING_TYPE_LIST,
VQEC_CONFIG_SETTING_TYPE_GROUP,
} vqec_config_setting_type_t;
#define VQEC_CONFIG_MAX_NAME_LEN 100
/**
* Declaration for structure to be used with list element.
*/
struct vqec_config_setting_;
/**
* Structure which contains all of a particular setting's data.
*/
typedef struct vqec_config_setting_ {
/**
* The type of setting which this is.
*/
vqec_config_setting_type_t type;
/**
* The name of this particular setting.
*/
char *name;
/**
* The following value fields are stored as a union to conserve memory.
*/
union {
/**
* The string value of this setting.
*/
char *value_string;
/**
* The boolean value of this setting.
*/
boolean value_boolean;
/**
* The integer (signed) value of this setting.
*/
int value_int;
};
/**
* Queue object for setting list.
*/
VQE_TAILQ_ENTRY(vqec_config_setting_) list_qobj;
/**
* Head for setting sublist.
*/
VQE_TAILQ_HEAD(setting_sublist_head, vqec_config_setting_) subsetting_head;
} vqec_config_setting_t;
#define VQEC_CONFIG_ERROR_STRLEN 80
/**
* Structure which contains all data within a particular configuration.
*/
typedef struct vqec_config_ {
/**
* Head for setting list.
*/
vqec_config_setting_t root;
/**
* Textual information which may help indicate a problem in parsing a
* particular configuration file.
*/
char error_text[VQEC_CONFIG_ERROR_STRLEN];
/**
* Line number at which a problem occurred while parsing a particular
* configuration file.
*/
int error_line;
} vqec_config_t;
/**
* Initialize the configuration parser.
*
* @param[in] cfg Instance of configuration parser.
* @return Returns TRUE if the parser was initialized successfully; FALSE
* otherwise.
*/
boolean vqec_config_init(vqec_config_t *cfg);
/**
* Read a configuration file and parse its parameters and values.
*
* @param[in] cfg Instance of configuration parser.
* @param[in] filepath Path to the file to be read and parsed.
* @return Returns TRUE if the file was read and parsed successfully; FALSE
* otherwise. If FALSE is returned, the "error_text" and
* "error_line" fields of cfg may contain information helpful in
* determining what the problem was.
*/
boolean vqec_config_read_file(vqec_config_t *cfg,
const char *filepath);
/**
* Read a buffer containing configuration information and parse its parameters
* and values.
*
* @param[in] cfg Instance of configuration parser.
* @param[in] buffer Pointer to the buffer to be parsed.
* @return Returns TRUE if the buffer was read and parsed successfully; FALSE
* otherwise. If FALSE is returned, the "error_text" and
* "error_line" fields of cfg may contain information helpful in
* determining what the problem was.
*/
boolean vqec_config_read_buffer(vqec_config_t *cfg,
const char *buffer);
/**
* Look up a configuration setting by its parameter name.
*
* @param[in] cfg Instance of configuration parser.
* @param[in] name Name of the parameter which should be looked up.
* @return If a setting is found that matches the given parameter name, then
* a pointer to that setting is returned. Otherwise, NULL is
* returned.
*/
vqec_config_setting_t *vqec_config_lookup(vqec_config_t *cfg,
char *name);
/**
* Determine the type of a particular setting.
*
* @param[in] setting Setting to have its type determined.
* @return Returns the type of the setting.
*/
vqec_config_setting_type_t
vqec_config_setting_type(vqec_config_setting_t *setting);
/**
* Determine the length (number of elements) of a particular group or list
* format configuration setting. If the given setting is not a group or list
* type, then 0 will be returned.
*
* @param[in] setting Setting to have its length determined.
* @return Returns the number of elements in the group or list.
*/
int vqec_config_setting_length(vqec_config_setting_t *setting);
/**
* Retrieve an element of a list by its index. If the given setting is not a
* list type, then NULL will be returned.
*
* @param[in] setting List from which the element shall be retrieved.
* @param[in] index Index of the requested element within the list.
* @return Returns a pointer to the requested element if it exists. If the
* requested element does not exist, NULL is returned.
*/
vqec_config_setting_t *
vqec_config_setting_get_elem(vqec_config_setting_t *setting,
int index);
/**
* Retrieve a member of a group by its name. If the given setting is not a
* group type, then NULL will be returned.
*
* @param[in] setting Group from which the member shall be retrieved.
* @param[in] name Name of the requested member within the group.
* @return Returns a pointer to the member with the given name if it exists.
* If no member with the given name exists, NULL is returned.
*/
vqec_config_setting_t *
vqec_config_setting_get_member(vqec_config_setting_t *setting,
char *name);
/**
* Retrieve the value of a string setting. If the given setting is not a
* string type, then NULL will be returned.
*
* @param[in] setting Setting to have its value retrieved.
* @return Returns a pointer to the string value of the setting.
*/
char *vqec_config_setting_get_string(vqec_config_setting_t *setting);
/**
* Retrieve the value of a boolean setting. If the given setting is not a
* boolean type, then FALSE will be returned.
*
* @param[in] setting Setting to have its value retrieved.
* @return Returns TRUE or FALSE in accordance with the value of the setting.
*/
boolean vqec_config_setting_get_bool(vqec_config_setting_t *setting);
/**
* Retrieve the value of a signed integer setting. If the given setting is not
* an integer type, then 0 will be returned.
*
* @param[in] setting Setting to have its value retrieved.
* @return Returns the signed integer value of the setting.
*/
int vqec_config_setting_get_int(vqec_config_setting_t *setting);
/**
* Destroy all information stored in a configuration parser instance.
*
* @param[in] cfg Instance of configuration parser.
* @return Returns TRUE if the parser was destroyed successfully; FALSE
* otherwise.
*/
boolean vqec_config_destroy(vqec_config_t *cfg);
|
wmanley/cisco-vqe-client
|
eva/vqec_config_parser.h
|
C
|
bsd-3-clause
| 7,094 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><html><head><style>TABLE {
BORDER-TOP: 0px; BORDER-RIGHT: 0px; WIDTH: 98%; BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; cellSpacing: 4; cellPadding: 0
}
TD {
VERTICAL-ALIGN: top
}
</style><meta content="text/html; charset=utf-8" http-equiv="Content-Type"></meta><link rel="stylesheet" type="text/css" href="v8help://service_book/service_style"></link><meta name="GENERATOR" content="MSHTML 9.00.8112.16421"></meta></head><body>В данной панели осуществляется контроль состояния программы, резервное копирование и восстановление, обновление версии, оптимизация быстродействия.<br><br><table><tbody><a name="СтандартныеПодсистемы.БазоваяФункциональность">
<tr><td>
<li><a href="DataProcessor.ЖурналРегистрации/Help">Журнал регистрации</a></li></td>
<td>Просмотр событий и действий, которые происходили в регламентных заданиях или в процессе работы пользователей в программе.</td></tr></a><a name="СтандартныеПодсистемы.ЗавершениеРаботыПользователей">
<tr><td>
<li><a href="DataProcessor.АктивныеПользователи/Help">Активные пользователи</a></li></td>
<td>Список пользователей, которые сейчас работают в программе.</td></tr><tr><td>
<li><a href="DataProcessor.БлокировкаРаботыПользователей/Help">Блокировка работы пользователей</a></li></td>
<td>Установка и снятие запрета работы пользователей с программой. При установке запрета завершается работа всех активных пользователей (включая текущего).</td></tr></a><a name="СтандартныеПодсистемы.УдалениеПомеченныхОбъектов">
<tr><td>
<li><a href="DataProcessor.УдалениеПомеченныхОбъектов/Help">Удаление помеченных объектов</a></li></td>
<td>Окончательное удаление тех объектов программы, которым ранее была присвоена пометка на удаление.</td></tr></a></tbody></table><h3>Отчеты и обработки</h3>
<table><tbody><tr><td>
<li><strong>Отчеты администратора</strong></li></td>
<td><a name="СтандартныеПодсистемы.АнализЖурналаРегистрации">
<p><a href="Report.АнализЖурналаРегистрации/Help">Отчеты по журналу регистрации</a>. </p></a>
<p>Отчеты для администрирования программы.</p></td></tr><a name="СтандартныеПодсистемы.ДополнительныеОтчетыИОбработки">
<tr><td>
<li><strong>Дополнительные </strong><strong> отчеты по администрированию</strong></li></td>
<td>Команды <a href="Catalog.ДополнительныеОтчетыИОбработки/Help">дополнительных отчетов</a>, подключенных к программе.</td></tr><tr><td>
<li><strong>Дополнительные </strong><strong>обработки по администрированию</strong></li></td>
<td>Команды <a href="Catalog.ДополнительныеОтчетыИОбработки/Help">дополнительных обработок</a>, подключенных к программе.</td></tr></a></tbody></table><h3>Регламентные операции</h3>
<table><tbody><a name="СтандартныеПодсистемы.РегламентныеЗадания">
<tr><td>
<li><a href="DataProcessor.РегламентныеИФоновыеЗадания/Help">Регламентные и фоновые задания</a></li></td>
<td>Настройка, выполнение и отслеживание состояний регламентных и фоновых заданий. Регламентные задания автоматически выполняют регламентные операции по расписанию.</td></tr></a>
<tr><td>
<li><strong>Разблокировать работу с внешними ресурсами</strong></li></td>
<td>С помощью кнопки можно снять блокировку регламентных заданий по работе с внешними ресурсами. Она автоматически устанавливается, если изменилось местоположение ИБ в связи с копированием или восстановлением из резервной копии.</td></tr><tr><td><a name="СтандартныеПодсистемы.УправлениеИтогамиИАгрегатами">
<li><a href="DataProcessor.УправлениеИтогамиИАгрегатами/Help">Управление итогами и агрегатами</a></li></a></td>
<td>Управление итогами регистров накопления и бухгалтерии и агрегатами оборотных регистров. Правильная настройка итогов и агрегатов может повысить производительность программы.</td></tr><a name="СтандартныеПодсистемы.ПолнотекстовыйПоиск">
<tr><td>
<li><a href="DataProcessor.ПанельАдминистрированияБСП.Form.УправлениеПолнотекстовымПоискомИИзвлечениемТекстов/Help">Полнотекстовый поиск данных</a></li></td>
<td>Включите флажок, после этого становится доступной команда:</td></tr><tr><td>
<li><strong>Настроить</strong></li></td>
<td>Настройка полнотекстового поиска и поддержка индекса полнотекстового поиска в актуальном состоянии.</td></tr><tr><td><a name="СтандартныеПодсистемы.ДатыЗапретаИзменения">
<li><a href="InformationRegister.ДатыЗапретаИзменения/Help">Даты запрета изменения</a></li></a></td>
<td>Включите флажок, для того чтобы использовать даты запрета изменения данных программы. <a name="СтандартныеПодсистемы.СинхронизацияДанных">
<p>См. также: <strong>Даты запрета загрузки данных</strong> в разделе <a href="DataProcessor.ПанельАдминистрированияБСП.Form.НастройкиСинхронизацииДанных/Help">Синхронизация данных</a>. После этого становится активной команда:</p></a></td></tr></a>
<tr><td>
<li><strong>Настроить</strong></li></td>
<td>Переход к установке запрета редактирования данных программы до определенной даты (данных прошлых периодов).</td></tr><tr><td>
<li><strong>Автоматически удалять помеченные объекты по расписанию</strong></li></td>
<td>Включите флажок, для того чтобы настроить расписание автоматического удаления помеченных объектов.</td></tr><tr><td>
<li><a href="v8help://mngbase/jobschedule.lf">Настроить расписание</a></li></td>
<td>После включения флажка команда становится доступной. Настройте расписание автоматического удаления объектов.</td></tr></tbody></table><a name="СтандартныеПодсистемы.РезервноеКопированиеИБ">
<h3>Резервное копирование и восстановление</h3></a>
<table><a name="СтандартныеПодсистемы.РезервноеКопированиеИБ">
<tbody><tr><td colspan="2">
<p>С целью уменьшения риска потери данных необходимо регулярно выполнять резервное копирование программы.<br>Частота создания резервных копий зависит от интенсивности ввода новых данных.</p></td></tr><tr><td>
<li><a href="DataProcessor.РезервноеКопированиеИБ.Form.РезервноеКопированиеДанных/Help">Создание резервной копии</a></li></td>
<td>Выполнение резервного копирования программы: прямо сейчас, через некоторое время или при завершении работы.</td></tr><tr><td>
<li><a href="DataProcessor.НастройкаРезервногоКопированияИБ/Help">Настройка резервного копирования</a></li></td>
<td>Настройка автоматического резервного копирования по расписанию, или отключение контроля резервного копирования, если оно выполняется сторонними средствами.</td></tr><tr><td>
<li><a href="DataProcessor.РезервноеКопированиеИБ.Form.ВосстановлениеДанныхИзРезервнойКопии/Help">Восстановление из резервной копии</a></li></td>
<td>Восстановление программы из резервной копии.</td></tr></tbody></a></table><a name="СтандартныеПодсистемы.ВерсионированиеОбъектов">
<h3>История изменений</h3>
<p>Программа позволяет вести историю изменения списков, просматривать любую версию объекта или сравнивать любые версии объекта между собой.</p></a>
<table><a name="СтандартныеПодсистемы.ВерсионированиеОбъектов">
<tbody><tr><td>
<li><strong>Хранить историю изменений</strong></li></td>
<td>Включите флажок для ведения истории изменения объектов программы. После этого становится доступной команда:</td></tr><tr><td>
<li><a href="InformationRegister.НастройкиВерсионированияОбъектов/Help">Настройки хранения</a></li></td>
<td>Настройка хранения и очистка версий документов и справочников.</td></tr></tbody></a></table><a name="СтандартныеПодсистемы.ОценкаПроизводительности">
<h3>Оценка производительности</h3>
<p>В программе предусмотрены встроенные средства для сбора и анализа данных о производительности ее работы по APDEX. В подразделе можно настроить параметры:</p></a>
<table><tbody><tr><td>
<li><strong>Оценка производительности</strong></li></td>
<td>Флажок замеров интегральной производительности программы по методике APDEX.</td></tr><tr><td>
<li><a href="DataProcessor.ОценкаПроизводительности.Form.АвтоматическийЭкспортЗамеровПроизводительности/Help">Настройки оценки производительности</a></li></td>
<td>Настройки параметров оценки производительности.</td></tr><tr><td>
<li><a href="DataProcessor.ОценкаПроизводительности/Help">Показатели производительности</a></li></td>
<td>Просмотр и оценка результатов замеров производительности.</td></tr><tr><td>
<li><a href="DataProcessor.ОценкаПроизводительности.Form.ЭкспортЗамеровПроизводительности/Help">Экспорт замеров производительности</a></li></td>
<td>Экспорт замеров производительности за произвольный период.</td></tr></tbody></table><br><a name="СтандартныеПодсистемы.АдресныйКлассификатор">
<h3>Адресный классификатор</h3></a>
<table><tbody><tr><td colspan="2">Выберите с помощью переключателя способ работы с адресными сведениями:</td></tr><tr><td>
<li><strong>Использовать веб-сервис 1С для ввода и проверки адресов</strong></li></td>
<td>
<p>Включите возможность использовать веб-сервис, предоставленный фирмой 1С. Требуется постоянное подключение к Интернету.</p></td></tr><tr><td>
<li><strong>Загружать классификатор в программу</strong></li></td>
<td>
<p>Использовать данные, загружаемые с сайта 1С или из папки на диске. Возможна работа без подключения к Интернету</p></td></tr><tr><td colspan="2">Для использования возможностей адресного классификатора предусмотрены команды:</td></tr><tr><td>
<li><a href="CommonForm.ПодключениеИнтернетПоддержки/Help">Подключить интернет-поддержку</a></li></td>
<td>Для использования веб-сервиса 1С и загрузки обновлений адресного классификатора необходимо выполнить подключение к интернет-поддержке пользователей.</td></tr><tr><td>
<li><a href="InformationRegister.АдресныеОбъекты.Form.ЗагрузкаАдресногоКлассификатора/Help">Загрузить классификатор</a></li></td>
<td>Загрузка адресного классификатора с сайта 1С или из папки на диске.</td></tr><tr><td>
<li><a href="InformationRegister.АдресныеОбъекты.Form.ОчисткаАдресногоКлассификатора/Help">Очистить адресные сведения</a></li></td>
<td>Удаление загруженных адресных сведений по выбранным, неиспользуемым регионам для уменьшения размера базы.</td></tr></tbody></table><h3>Другие классификаторы</h3>
<table><tbody><a name="СтандартныеПодсистемы.Банки">
<tr><td>
<li><a href="Catalog.КлассификаторБанковРФ/Help">Загрузить классификатор банков</a></li></td>
<td>Загрузка и обновление классификатора банков РФ из сети Интернет или диска 1С:ИТС.</td></tr></a><a name="СтандартныеПодсистемы.Валюты">
<tr><td>
<li><a href="DataProcessor.ЗагрузкаКурсовВалют/Help">Загрузить курсы валют</a></li></td>
<td>Загрузка курсов валют из сети Интернет.</td></tr></a></tbody></table><a name="СтандартныеПодсистемы.ЗащитаПерсональныхДанных">
<h3>Защита персональных данных</h3></a>
<table><a name="СтандартныеПодсистемы.ЗащитаПерсональныхДанных">
<tbody><tr><td>
<li><a href="CommonForm.НастройкиРегистрацииСобытийДоступаКПерсональнымДанным/Help">Настройки регистрации событий доступа к персональным данным</a></li></td>
<td>Настройки регистрации событий доступа в соответствии с требованиями Федерального закона от 27.07.2006 N152-ФЗ "О персональных данных"</td></tr><tr><td>
<li><a href="DataProcessor.ЗащитаПерсональныхДанных/Help">Защита персональных данных</a></li></td>
<td>Просмотр обращений к персональным данным выбранных объектов программы.</td></tr></tbody></a></table><h3>Корректировка данных</h3>
<table><tbody><a name="СтандартныеПодсистемы.ГрупповоеИзменениеОбъектов">
<tr><td>
<li><a href="DataProcessor.ГрупповоеИзменениеРеквизитов/Help">Групповое изменение реквизитов</a></li></td>
<td>Изменение реквизитов и табличных частей в выбранных элементах</td></tr></a><a name="СтандартныеПодсистемы.ПоискИУдалениеДублей">
<tr><td>
<li><a href="DataProcessor.ПоискИУдалениеДублей/Help">Поиск и удаление дублей</a></li></td>
<td>Поиск похожих элементов по заданным условиям сравнения.</td></tr></a></tbody></table><h3>Работа с контрагентами</h3>
<p>Для подготовки корректных данных и сокращения количества ошибок в программе предусмотрена автоматическая проверка контрагентов.</p>
<p></p>
<table width="100%"><tbody><tr><td>
<li><strong>Автоматически проверять контрагентов по ЕГРН</strong></li></td>
<td>Включите флажок для автоматической проверки регистрации контрагентов в ЕГРН (Едином государственном реестре налогоплательщиков). Проверка проводится с помощью регламентного задания.</td></tr><tr><td>
<li><strong>Подробнее о сервисе</strong></li></td>
<td>Нажмите ссылку, для того чтобы получить информацию о работе с сервисом.</td></tr><tr><td>
<li><strong>Проверить доступ к веб-сервису</strong></li></td>
<td>Нажмите кнопку для проверки доступа к веб-сервису ФНС.</td></tr></tbody></table><h3>Результаты обновления программы</h3>
<p>В подразделе производится установка обновлений программы, также можно просмотреть информацию о предыдущих обновлениях.</p>
<p></p>
<table><tbody><a name="СтандартныеПодсистемы.ОбновлениеКонфигурации">
<tr><td>
<li><a href="DataProcessor.УстановкаОбновлений/Help">Установка обновлений</a></li></td>
<td>Переход к установке обновлений программы.</td>
<p></p></tr></a><a name="СтандартныеПодсистемы.ОбновлениеВерсииИБ">
<tr><td>
<li><a href="CommonForm.ОписаниеИзмененийПрограммы/Help">Описание изменений программы</a></li></td>
<td>Просмотр списка изменений в установленной версии программы и рекомендаций по обновлению программы.</td></tr><tr><td>
<li><a href="DataProcessor.РезультатыОбновленияПрограммы.Form.ИндикацияХодаОтложенногоОбновленияИБ/Help">Результаты обновления и дополнительная обработка данных</a></li></td>
<td>Сведения о ходе обновления версии программы, отложенное выполнение дополнительных процедур обработки данных</td></tr><tr><td><a name="СтандартныеПодсистемы.БазоваяФункциональность">
<li><strong>Детализировать ход обновления в журнале регистрации</strong></li></a></td>
<td>При включенном флажке в <a href="DataProcessor.ЖурналРегистрации/Help">журнал регистрации</a> записываются выполняемые обработчики обновления с указанием времени выполнения.</td></tr></a></tbody></table><h3>Центр мониторинга</h3>
<p>В подразделе представлены настройки сбора, анализа и хранения технологической информации, обезличенной статистики использования конфигурации. Отчеты об использовании программы, автоматически переданные разработчикам, помогут им определить, над чем следует поработать в первую очередь. Собранные сведения являются обезличенными и содержат только статистические показатели. Подготовка и отправка отчетов не замедлит работу программы.</p>
<p>С помощью переключателя выберите: </p>
<p></p>
<table width="100%"><tbody><tr><td>
<li><strong>Разрешить автоматическую отправку сведений об использовании программы в фирму "1С"</strong></li></td>
<td>выбрано по умолчанию, рекомендуется.</td></tr><tr><td>
<li><strong>Разрешить отправку сведений стороннему разработчику</strong></li></td>
<td>в этом случае необходимо заполнить <strong>Адрес сервиса</strong>.</td></tr><tr><td>
<li><strong>Запретить отправку сведений</strong></li></td>
<td>не рекомендуется, т.к. статистика необходима разработчикам для анализа работы программы, при этом передача статистики не замедляет ее работу.</td></tr></tbody></table><h3>См. также: </h3>
<ul><li><a href="DataProcessor.ПанельАдминистрированияБСП/Help">Настройки программы</a>.</li></ul></body></html>
|
oleynikova/final_task
|
src/cf/DataProcessors/ПанельАдминистрированияБСП/Forms/ПоддержкаИОбслуживание/Ext/Help/ru.html
|
HTML
|
bsd-3-clause
| 23,914 |
// Copyright (c) 2013, Cornell University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of WTF nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifndef wtf_admin_admin_h_
#define wtf_admin_admin_h_
// STL
#include <map>
#include <list>
// BusyBee
#include <busybee_st.h>
// WTF
#include "include/wtf/admin.h"
#include "common/coordinator_link.h"
#include "common/mapper.h"
#include "admin/coord_rpc.h"
#include "admin/multi_yieldable.h"
#include "admin/pending.h"
namespace wtf __attribute__ ((visibility("hidden")))
{
class admin
{
public:
admin(const char* coordinator, uint16_t port);
~admin() throw ();
public:
// introspect the config
int64_t dump_config(enum wtf_admin_returncode* status,
const char** config);
// cluster
int64_t read_only(int ro,
enum wtf_admin_returncode* status);
// manage servers
int64_t server_register(uint64_t token, const char* address,
enum wtf_admin_returncode* status);
int64_t server_online(uint64_t token, enum wtf_admin_returncode* status);
int64_t server_offline(uint64_t token, enum wtf_admin_returncode* status);
int64_t server_forget(uint64_t token, enum wtf_admin_returncode* status);
int64_t server_kill(uint64_t token, enum wtf_admin_returncode* status);
// looping/polling
int64_t loop(int timeout, wtf_admin_returncode* status);
// error handling
const char* error_message();
const char* error_location();
void set_error_message(const char* msg);
// translate returncodes
void interpret_rpc_request_failure(replicant_returncode rstatus,
wtf_admin_returncode* status);
void interpret_rpc_loop_failure(replicant_returncode rstatus,
wtf_admin_returncode* status);
void interpret_rpc_response_failure(replicant_returncode rstatus,
wtf_admin_returncode* status,
e::error* err);
private:
struct pending_server_pair
{
pending_server_pair()
: si(), op() {}
pending_server_pair(const server_id& s,
const e::intrusive_ptr<pending>& o)
: si(s), op(o) {}
~pending_server_pair() throw () {}
server_id si;
e::intrusive_ptr<pending> op;
};
typedef std::map<uint64_t, pending_server_pair> pending_map_t;
typedef std::map<int64_t, e::intrusive_ptr<coord_rpc> > coord_rpc_map_t;
typedef std::map<int64_t, e::intrusive_ptr<multi_yieldable> > multi_yieldable_map_t;
typedef std::list<pending_server_pair> pending_queue_t;
private:
bool maintain_coord_connection(wtf_admin_returncode* status);
bool send(wtf_network_msgtype mt,
server_id id,
uint64_t nonce,
std::auto_ptr<e::buffer> msg,
e::intrusive_ptr<pending> op,
wtf_admin_returncode* status);
void handle_disruption(const server_id& si);
private:
coordinator_link m_coord;
e::garbage_collector m_gc;
e::garbage_collector::thread_state m_gc_ts;
mapper m_busybee_mapper;
busybee_st m_busybee;
int64_t m_next_admin_id;
uint64_t m_next_server_nonce;
bool m_handle_coord_ops;
coord_rpc_map_t m_coord_ops;
pending_map_t m_server_ops;
multi_yieldable_map_t m_multi_ops;
pending_queue_t m_failed;
std::list<e::intrusive_ptr<yieldable> > m_yieldable;
e::intrusive_ptr<yieldable> m_yielding;
e::intrusive_ptr<yieldable> m_yielded;
e::error m_last_error;
};
}
#endif // wtf_admin_admin_h_
|
seanogden/wtf
|
admin/admin.h
|
C
|
bsd-3-clause
| 5,384 |
# go run
在《Go并发编程实战》的第二章中,我介绍了Go源码文件的分类。Go源码文件包括:命令源码文件、库源码文件和测试源码文件。其中,命令源码文件总应该属于`main`代码包,且在其中有无参数声明、无结果声明的main函数。单个命令源码文件可以被单独编译,也可以被单独安装(可能需要设置环境变量GOBIN)。当然,命令源码文件也可以被单独运行。我们想要运行命令源码文件就需要使用命令`go run`。
`go run`命令可以编译并运行命令源码文件。由于它其中包含了编译动作,因此它也可以接受所有可用于`go build`命令的标记。除了标记之外,`go run`命令只接受Go源码文件作为参数,而不接受代码包。与`go build`命令和`go install`命令一样,`go run`命令也不允许多个命令源码文件作为参数,即使它们在同一个代码包中也是如此。而原因也是一致的,多个命令源码文件会都有main函数声明。
如果命令源码文件可以接受参数,那么在使用`go run`命令运行它的时候就可以把它的参数放在它的文件名后面,像这样:
```bash
hc@ubt:~/golang/goc2p/src/helper/ds$ go run showds.go -p ~/golang/goc2p
```
在上面的示例中,我们使用`go run`命令运行命令源码文件showds.go。这个命令源码文件可以接受一个名称为“p”的参数。我们用“-p”这种形式表示“p”是一个参数名而不是参数值。它与源码文件名之间需要用空格隔开。参数值会放在参数名的后面,两者成对出现。它们之间也要用空格隔开。如果有第二个参数,那么第二个参数的参数名与第一个参数的参数值之间也要有一个空格。以此类推。
`go run`命令只能接受一个命令源码文件以及若干个库源码文件(必须同属于`main`包)作为文件参数,且不能接受测试源码文件。它在执行时会检查源码文件的类型。如果参数中有多个或者没有命令源码文件,那么`go run`命令就只会打印错误提示信息并退出,而不会继续执行。
在通过参数检查后,`go run`命令会将编译参数中的命令源码文件,并把编译后的可执行文件存放到临时工作目录中。
**编译和运行过程**
为了更直观的体现出`go run`命令中的操作步骤,我们在执行命令时加入标记`-n`,用于打印相关命令而不实际执行。现在让我们来模拟运行goc2p项目中的代码包helper/ds的命令源码文件showds.go。示例如下:
```bash
hc@ubt:~/golang/goc2p/src/helper/ds$ go run -n showds.go
#
# command-line-arguments
#
mkdir -p $WORK/command-line-arguments/_obj/
mkdir -p $WORK/command-line-arguments/_obj/exe/
cd /home/hc/golang/goc2p/src/helper/ds
/usr/local/go1.5/pkg/tool/linux_amd64/compile -o $WORK/command-line-arguments.a -trimpath $WORK -p main -complete -buildid df49387da030ad0d3bebef3f046d4013f8cb08d3 -D _/home/hc/golang/goc2p/src/helper/ds -I $WORK -pack ./showds.go
cd .
/usr/local/go1.5/pkg/tool/linux_amd64/link -o $WORK/command-line-arguments/_obj/exe/showds -L $WORK -w -extld=clang -buildmode=exe -buildid=df49387da030ad0d3bebef3f046d4013f8cb08d3 $WORK/command-line-arguments.a
$WORK/command-line-arguments/_obj/exe/showds
```
在上面的示例中并没有显示针对命令源码文件showds.go的依赖包进行编译和运行的相关打印信息。这是因为该源码文件的所有依赖包已经在之前被编译过了。
现在,我们来逐行解释这些被打印出来的信息。
以前缀“#”开始的是注释信息。我们看到信息中有三行注释信息,并在中间行出现了内容“command-line-arguments”。我们在讲`go build`命令的时候说过,编译命令在分析参数的时候如果发现第一个参数是Go源码文件而不是代码包时,会在内部生成一个名为“command-line-arguments”的虚拟代码包。所以这里的注释信息就是要告诉我们下面的几行信息是关于虚拟代码包“command-line-arguments”的。
打印信息中的“$WORK”表示临时工作目录的绝对路径。为了存放对虚拟代码包“command-line-arguments”的编译结果,命令在临时工作目录中创建了名为command-line-arguments的子目录,并在其下又创建了_obj子目录和_obj/exe子目录。
然后,命令程序使用Go语言工具目录`compile`命令对命令源码文件showds.go进行了编译,并把结果文件存放到了$WORK目录下,名为command-line-arguments.a。其中,`compile`是Go语言自带的编程工具。
在编译成功之后,命令程序使用链接命令`link`生成最终的可执行文件,并将其存于$WORK/command-line-arguments/_obj/exe/目录中。打印信息中的最后一行表示,命令运行了生成的可执行文件。
通过对这些打印出来的命令的解读,我们了解了临时工作目录的用途以和内容。
在上面的示例中,我们只是让`go run`命令打印出运行命令源码文件showds.go过程中需要执行的命令,而没有真正运行它。如果我们想真正运行命令源码文件showds.go并且想知道临时工作目录的位置,就需要去掉标记`-n`并且加上标记`-work`。当然,如果依然想看到过程中执行的命令,可以加上标记`-x`。如果读者已经看过之前我们对`go build`命令的介绍,就应该知道标记`-x`与标记`-n`一样会打印出过程执行的命令,但不同的这些命令会被真正的执行。调整这些标记之后的命令就像这样:
```bash
hc@ubt:~/golang/goc2p/src/helper/ds$ go run -x -work showds.go
```
当命令真正执行后,临时工作目录中就会出现实实在在的内容了,像这样:
```bash
/tmp/go-build604555989:
command-line-arguments/
_obj/
exe/
showds
command-line-arguments.a
```
由于上述命令中包含了`-work`标记,所以我们可以从其输出中找到实际的工作目录(这里是/tmp/go-build604555989)。有意思的是,我们恰恰可以通过运行命令源码文件showds.go来查看这个临时工作目录的目录树:
```bash
hc@ubt:~/golang/goc2p/src/helper/ds$ go run showds.go -p /tmp/go-build604555989
```
读者可以自己试一试。
我们在前面介绍过,命令源码文件如果可以接受参数,则可以在执行`go run`命令运行这个命令源码文件时把参数名和参数值成对的追加在后面。实际上,如果在命令后追加参数,那么在最后执行生成的可执行文件的时候也会追加一致的参数。例如,如果这样执行命令:
```bash
hc@ubt:~/golang/goc2p/src/helper/ds$ go run -n showds.go -p ~/golang/goc2p
```
那么带`-x`或`-n`标记的命令程序打印的最后一个命令就是:
```bash
$WORK/command-line-arguments/_obj/exe/showds -p /home/hc/golang/goc2p
```
可见,`go run`命令会把追加到命令源码文件后面的参数原封不动的传给对应的可执行文件。
以上简要展示了一个命令源码文件从编译到运行的全过程。请记住,`go run`命令包含了两个动作:编译命令源码文件和运行对应的可执行文件。
|
hyper-carrot/go_command_tutorial
|
0.6.md
|
Markdown
|
bsd-3-clause
| 7,264 |
Copyright (c) 2011, Motorola Mobility, Inc
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
- Neither the name of Motorola Mobility nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
kriskowal/joey
|
LICENSE.md
|
Markdown
|
bsd-3-clause
| 1,515 |
/*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#pragma once
#include <boost/date_time/local_time/local_time_types.hpp>
#include "bistro/bistro/cron/CrontabItem.h"
#include "bistro/bistro/cron/CrontabSelector.h"
#include "bistro/bistro/cron/utils/date_time.h"
// Add stateful Cron support for more robustness, see README for a design.
namespace folly {
class dynamic;
}
namespace boost { namespace posix_time {
class ptime;
}}
namespace facebook { namespace bistro { namespace detail_cron {
class MatchComputeState; // Declared in CPP file
class StandardCrontabItem : public CrontabItem {
public:
// The positions we use to search through local time labels. We use
// human-readable values here, so some are 0-based and some are 1-based.
// This is nice since it matches the boost::date_time constructors.
enum class Position {
YEAR, // 1970..?
MONTH, // 1..12
DAY_OF_MONTH, // 1..28-31; day of week is computed
HOUR, // 0..23
MINUTE, // 0..59
MAX
};
StandardCrontabItem(
const folly::dynamic&, boost::local_time::time_zone_ptr
);
/**
* Even though we currently only support 1-minute resolution, you must not
* assume that the output will be aligned on the minute (it usually will
* be, except for "DST skip" cases).
*
* After finding the first local time label that matches this item's
* selectors, it may turn out that it maps to 0, 1, or 2 UTC timestamps as
* a consequence of DST clock forwards or rewinds (for details, see
* timezoneLocalPTimeToUTCTimestamps() docs). We use the item's
* configured heuristic to deal with this (see comments about the field
* "dst_fixes" below).
*/
folly::Optional<time_t> findFirstMatch(time_t time_since_utc_epoch)
const final;
bool isTimezoneDependent() override { return true; }
std::string getPrintable() const override; // For testing only, see base class
private:
// Here are the allowed values that can occur in the "dst_fixes" list,
// grouped by policy. You must specify exactly one entry for each policy,
//
// Forward (DST sets the clock ahead, skipping a range of local times):
// "unskip": [good for rare events]
// All matches in the skipped range are mapped to a single match in
// the instant before the skip.
// "skip": [good for frequent events]
// Cron matches in the skipped range of local times are ignored.
//
// Rewind (DST sets the clock back, making some local times ambiguous):
// "repeat_use_only_early": [good for rare events]
// For local time matches that are ambiguous, match only the times
// before the clock is rewound.
// "repeat_use_only_late": [good for rare events]
// For local time matches that are ambiguous, match only the times
// after the clock is rewound.
// "repeat_use_both": [good for frequent events]
// For local time matches that are ambiguous, match both times
// (before and after the clock is rewound).
const static short kDSTPolicyForward = 0x1;
const static short kDSTPolicyRewind = 0x2;
const static short kRequiredDSTPolicies = 0x3;
// These correspond to the actual actions the code has to take.
const static short kDSTForwardDoUnskip = 0x1; // "skip" sets no bits
// "repeat_use_both" sets both of the following bits
const static short kDSTRewindUseEarly = 0x2;
const static short kDSTRewindUseLate = 0x4;
void parseDstFixes(const folly::dynamic&);
folly::Optional<time_t> findFirstMatchImpl(time_t time_since_utc_epoch)
const;
folly::Optional<UTCTimestampsForLocalTime> findUTCTimestampsForFirstMatch(
time_t, boost::posix_time::ptime* match_pt
) const;
void findMatchingPositions(MatchComputeState *s, int64_t carry_steps)
const;
void findMatchingPositionsImpl(MatchComputeState *s, int64_t carry_steps)
const;
void findMatchingDayOfWeek(MatchComputeState *s, int64_t carry_steps) const;
int dstFixes_;
CrontabSelector selectors_[(int)Position::MAX];
folly::Optional<CrontabSelector> maybeDayOfWeekSel_;
};
}}}
|
linearregression/bistro
|
bistro/cron/StandardCrontabItem.h
|
C
|
bsd-3-clause
| 4,336 |
/**
* Copyright (c) 2011, University of Konstanz, Distributed Systems Group All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met: * Redistributions of source code must retain the
* above copyright notice, this list of conditions and the following disclaimer. * Redistributions
* in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Konstanz nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.sirix.service.xml.xpath.comparators;
import static org.sirix.service.xml.xpath.XPathAxis.XPATH_10_COMP;
import java.util.ArrayList;
import java.util.List;
import org.sirix.api.Axis;
import org.sirix.api.xml.XmlNodeReadOnlyTrx;
import org.sirix.exception.SirixXPathException;
import org.sirix.service.xml.xpath.AtomicValue;
import org.sirix.service.xml.xpath.functions.Function;
import org.sirix.service.xml.xpath.types.Type;
/**
* <p>
* General comparisons are existentially quantified comparisons that may be applied to operand
* sequences of any length.
* </p>
*/
public class GeneralComp extends AbstractComparator {
/**
* Constructor. Initializes the internal state.
*
* @param rtx Exclusive (immutable) trx to iterate with.
* @param mOperand1 First value of the comparison
* @param mOperand2 Second value of the comparison
* @param mCom comparison kind
*/
public GeneralComp(final XmlNodeReadOnlyTrx rtx, final Axis mOperand1, final Axis mOperand2,
final CompKind mCom) {
super(rtx, mOperand1, mOperand2, mCom);
}
/**
* {@inheritDoc}
*/
@Override
protected boolean compare(final AtomicValue[] mOperand1, final AtomicValue[] mOperand2)
throws SirixXPathException {
assert mOperand1.length >= 1 && mOperand2.length >= 1;
for (AtomicValue op1 : mOperand1) {
for (AtomicValue op2 : mOperand2) {
String value1 = new String(op1.getRawValue());
String value2 = new String(op2.getRawValue());
if (getCompKind().compare(value1, value2, getType(op1.getTypeKey(), op2.getTypeKey()))) {
return true;
}
}
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
protected AtomicValue[] atomize(final Axis mOperand) {
final XmlNodeReadOnlyTrx rtx = asXdmNodeReadTrx();
final List<AtomicValue> op = new ArrayList<AtomicValue>();
AtomicValue atomized;
// cast to double, if compatible with XPath 1.0 and <, >, >=, <=
final boolean convert =
!(!XPATH_10_COMP || getCompKind() == CompKind.EQ || getCompKind() == CompKind.EQ);
boolean first = true;
do {
if (first) {
first = false;
} else {
mOperand.next();
}
if (convert) { // cast to double
Function.fnnumber(rtx);
}
atomized = new AtomicValue(rtx.getValue().getBytes(), rtx.getTypeKey());
op.add(atomized);
} while (mOperand.hasNext());
return op.toArray(new AtomicValue[op.size()]);
}
/**
* {@inheritDoc}
*/
@Override
protected Type getType(final int mKey1, final int mKey2) throws SirixXPathException {
final Type mType1 = Type.getType(mKey1).getPrimitiveBaseType();
final Type mType2 = Type.getType(mKey2).getPrimitiveBaseType();
if (XPATH_10_COMP) {
if (mType1.isNumericType() || mType2.isNumericType()) {
return Type.DOUBLE;
}
if (mType1 == Type.STRING || mType2 == Type.STRING
|| (mType1 == Type.UNTYPED_ATOMIC && mType2 == Type.UNTYPED_ATOMIC)) {
return Type.STRING;
}
if (mType1 == Type.UNTYPED_ATOMIC || mType2 == Type.UNTYPED_ATOMIC) {
return Type.UNTYPED_ATOMIC;
}
} else {
if (mType1 == Type.UNTYPED_ATOMIC) {
switch (mType2) {
case UNTYPED_ATOMIC:
case STRING:
return Type.STRING;
case INTEGER:
case DECIMAL:
case FLOAT:
case DOUBLE:
return Type.DOUBLE;
default:
return mType2;
}
}
if (mType2 == Type.UNTYPED_ATOMIC) {
switch (mType1) {
case UNTYPED_ATOMIC:
case STRING:
return Type.STRING;
case INTEGER:
case DECIMAL:
case FLOAT:
case DOUBLE:
return Type.DOUBLE;
default:
return mType1;
}
}
}
return Type.getLeastCommonType(mType1, mType2);
}
// protected void hook(final AtomicValue[] operand1, final AtomicValue[]
// operand2) {
//
// if (operand1.length == 1
// && operand1[0].getTypeKey() == getTransaction()
// .keyForName("xs:boolean")) {
// operand2 = new AtomicValue[1];
// getOperand2().reset(startKey);
// operand2[0] = new AtomicValue(Function.ebv(getOperand1()));
// } else {
// if (operand2.length == 1
// && operand2[0].getTypeKey() == getTransaction().keyForName(
// "xs:boolean")) {
// operand1 = new AtomicValue[1];
// getOperand1().reset(startKey);
// operand1[0] = new AtomicValue(Function.ebv(getOperand2()));
// }
// }
// }
}
|
sirixdb/sirix
|
bundles/sirix-core/src/main/java/org/sirix/service/xml/xpath/comparators/GeneralComp.java
|
Java
|
bsd-3-clause
| 6,166 |
#pragma once
#define NET_DEFAULT_PORT 7871
class CConn
{
//protected:
public:
CSocket* _sock;
CSocketFile* _file;
CArchive* _arIn;
CArchive* _arOut;
bool _connected;
static HANDLE _creationMutex;
public:
CString _name;
int _port;
public:
CConn() : _sock(0), _file(0), _arIn(0), _arOut(0), _connected(false), _name(""), _port(NET_DEFAULT_PORT)
{
if (_creationMutex == 0)
_creationMutex = CreateMutex(NULL, FALSE, NULL);
}
~CConn()
{
disconnect();
}
void dealloc()
{
if (_arIn) delete _arIn; _arIn = 0;
if (_arOut) delete _arOut; _arOut = 0;
if (_file) delete _file; _file = 0;
if (_sock) delete _sock; _sock = 0;
}
void cancel();
bool connect() { return connect(_name, _port); }
bool connect(const CString name, int port = NET_DEFAULT_PORT) ;
void disconnect();
bool isConnected() const { return _connected; }
bool listen(int port = NET_DEFAULT_PORT);
bool accept(CConn& conn);
bool flush();
bool readn(void* buf, int bytes);
bool sendn(const void* buf, int bytes);
int readv(void* buf, int maxBytes);
bool sendv(const void* buf, int bytes);
bool readString(CString& str);
bool sendString(const char* str);
bool sendBool(bool v) { return sendn(&v, sizeof(bool )); }
bool sendChar(char v) { return sendn(&v, sizeof(char )); }
bool sendInt(int v) { return sendn(&v, sizeof(int )); }
bool sendFloat(float v) { return sendn(&v, sizeof(float )); }
bool sendDouble(double v) { return sendn(&v, sizeof(double)); }
bool readBool(bool* p) { return readn(p, sizeof(bool )); }
bool readChar(char* p) { return readn(p, sizeof(char )); }
bool readInt(int* p) { return readn(p, sizeof(int )); }
bool readFloat(float* p) { return readn(p, sizeof(float )); }
bool readDouble(double* p) { return readn(p, sizeof(double)); }
};
bool closeProcessByName(const char* name);
BOOL CALLBACK enumCloseProc(HWND hwnd, LPARAM lParam);
|
karlgluck/fabathome
|
FabInterpreter - 4.26.2010 - Revision 22/projects/FabStudio v0/Fab@Home Studio/conn.h
|
C
|
bsd-3-clause
| 1,956 |
/*L
* Copyright Ekagra Software Technologies Ltd.
* Copyright SAIC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cacore-sdk-pre411/LICENSE.txt for details.
*/
package gov.nih.nci.system.dao.impl.orm;
import gov.nih.nci.common.net.Request;
import gov.nih.nci.common.net.Response;
import gov.nih.nci.common.util.CQL2HQL;
import gov.nih.nci.common.util.Constant;
import gov.nih.nci.common.util.HQLCriteria;
import gov.nih.nci.common.util.HibernateQueryWrapper;
import gov.nih.nci.common.util.NestedCriteria;
import gov.nih.nci.common.util.NestedCriteria2HQL;
import gov.nih.nci.common.util.ObjectFactory;
import gov.nih.nci.system.dao.DAO;
import gov.nih.nci.system.dao.DAOException;
import gov.nih.nci.system.query.cql.CQLQuery;
import gov.nih.nci.system.servicelocator.ServiceLocator;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.JDBCException;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
/**
* <!-- LICENSE_TEXT_START -->
* Copyright 2001-2004 SAIC. Copyright 2001-2003 SAIC. This software was developed in conjunction with the National Cancer Institute,
* and so to the extent government employees are co-authors, any rights in such works shall be subject to Title 17 of the United States Code, section 105.
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer of Article 3, below. Redistributions
* in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
* 2. The end-user documentation included with the redistribution, if any, must include the following acknowledgment:
* "This product includes software developed by the SAIC and the National Cancer Institute."
* If no such end-user documentation is to be included, this acknowledgment shall appear in the software itself,
* wherever such third-party acknowledgments normally appear.
* 3. The names "The National Cancer Institute", "NCI" and "SAIC" must not be used to endorse or promote products derived from this software.
* 4. This license does not authorize the incorporation of this software into any third party proprietary programs. This license does not authorize
* the recipient to use any trademarks owned by either NCI or SAIC-Frederick.
* 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE,
* SAIC, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* <!-- LICENSE_TEXT_END -->
*/
/**
* ORMDAOImpl converts a request to a hibernate query that returns results from a data source
* @author caBIO Team
* @version 1.0
*/
public class ORMDAOImpl implements DAO
{
private static Logger log = Logger.getLogger(ORMDAOImpl.class.getName());
public SessionFactory sf;
int recordsPerQuery;
int maxRecordsPerQuery;
/**
* Default Constructor
*/
public ORMDAOImpl()
{
loadProperties();
}
/**
* Return the resultset of the query embedded in an object of gov.nih.nci.common.net.Response
* @param request - a gov.nih.nci.common.net.Request object passed from client
* @return an object of gov.nih.nci.common.net.Response that contains the query resultset
* @throws DAOException
*/
public Response query(Request request) throws DAOException
{
List rs = null;
int counter = 0;
ORMConnection ormConn = ORMConnection.getInstance();
org.hibernate.Session session = null;
Criteria hCriteria = null;
Integer rowCount = null;
Query query = null;
String entityName = request.getDomainObjectName();
ServiceLocator serviceLocator = null;
try{
serviceLocator = (ServiceLocator)ObjectFactory.getObject("ServiceLocator");
counter = serviceLocator.getORMCounter(entityName);
session = ORMConnection.openSession(entityName);
}
catch(Exception e)
{
log.error("Could not retrieve proper datasource \n " + e.getMessage());
throw new DAOException("Could not retrieve proper datasource " + e);
}
Object obj = request.getRequest();
Integer firstRow = request.getFirstRow();
log.debug("Integer firstRow = " + firstRow);
Integer resultsPerQuery = request.getRecordsCount();
log.debug("Integer resultsPerQuery = " + resultsPerQuery);
Boolean isCount = request.getIsCount();
log.debug("boolean isCount = " + isCount.booleanValue());
try
{
if (obj instanceof DetachedCriteria)
{
hCriteria = ((org.hibernate.criterion.DetachedCriteria)request.getRequest()).getExecutableCriteria(session);
log.info("Detached Criteria Query :"+hCriteria.toString());
if (hCriteria != null)
{
if(isCount != null && isCount.booleanValue())
{
rowCount = (Integer)hCriteria.setProjection(Projections.rowCount()).uniqueResult();
log.debug("DetachedCriteria ORMDAOImpl ===== count = " + rowCount);
hCriteria.setResultTransformer( Criteria.ROOT_ENTITY );
hCriteria.setProjection( null );
}
else if((isCount != null && !isCount.booleanValue()) || isCount == null)
{
if(firstRow != null)
hCriteria.setFirstResult(firstRow.intValue());
if(resultsPerQuery != null)
{
if(resultsPerQuery.intValue() > maxRecordsPerQuery)
{
String msg = "Illegal Value for RecordsPerQuery: recordsPerQuery cannot be greater than maxRecordsPerQuery. RecordsPerQuery = " +
recordsPerQuery + " maxRecordsPerQuery = " + maxRecordsPerQuery;
log.error(msg);
throw new Exception(msg);
}
else
{
hCriteria.setMaxResults(resultsPerQuery.intValue());
}
}
else
{
hCriteria.setMaxResults(recordsPerQuery);
}
// Set resultSet = new HashSet(hCriteria.list());
// rs = new ArrayList((Collection)resultSet);
rs = hCriteria.list();
}
}
}
else if (obj instanceof NestedCriteria)
{
log.debug("ORMDAOImpl.query: it is a NestedCriteria Object ....");
NestedCriteria2HQL converter = new NestedCriteria2HQL((NestedCriteria)obj, ormConn.getConfiguration(counter), session);
query = converter.translate();
log.info("HQL Query :"+query.getQueryString());
if (query != null)
{
if(isCount != null && isCount.booleanValue())
{
log.debug("ORMDAOImpl. isCount .... .... | converter.getCountQuery() = " + converter.getCountQuery().getQueryString());
rowCount = (Integer)converter.getCountQuery().uniqueResult();
log.debug("ORMDAOImpl HQL ===== count = " + rowCount);
}
else if((isCount != null && !isCount.booleanValue()) || isCount == null)
{
if(firstRow != null)
{
log.debug("Setting First Row to " + firstRow);
query.setFirstResult(firstRow.intValue());
}
if(resultsPerQuery != null)
{
if(resultsPerQuery.intValue() > maxRecordsPerQuery)
{
String msg = "Illegal Value for RecordsPerQuery: recordsPerQuery cannot be greater than maxRecordsPerQuery. RecordsPerQuery = " + recordsPerQuery + " maxRecordsPerQuery = " + maxRecordsPerQuery ;
log.error(msg);
throw new Exception(msg);
}
else
{
log.debug("Setting Max Results to " + resultsPerQuery.intValue());
query.setMaxResults(resultsPerQuery.intValue());
}
}
else
{
log.debug("Setting Max Results to " + recordsPerQuery);
query.setMaxResults(recordsPerQuery);
}
rs = query.list();
}
}
}
else if (obj instanceof HQLCriteria)
{
Query hqlQuery = session.createQuery(((HQLCriteria)obj).getHqlString());
log.info("HQL Criteria Query :"+hqlQuery.getQueryString());
if(isCount != null && isCount.booleanValue())
{
rowCount = new Integer(hqlQuery.list().size());
}
else if((isCount != null && !isCount.booleanValue()) || isCount == null)
{
if(firstRow != null)
{
hqlQuery.setFirstResult(firstRow.intValue());
}
if(resultsPerQuery != null)
{
if(resultsPerQuery.intValue() > maxRecordsPerQuery)
{
String msg = "Illegal Value for RecordsPerQuery: recordsPerQuery cannot be greater than maxRecordsPerQuery. RecordsPerQuery = " + recordsPerQuery + " maxRecordsPerQuery = " + maxRecordsPerQuery ;
log.error(msg);
throw new Exception(msg);
}
else
{
hqlQuery.setMaxResults(resultsPerQuery.intValue());
}
}
else
{
hqlQuery.setMaxResults(recordsPerQuery);
}
rs = hqlQuery.list();
}
}
else if (obj instanceof CQLQuery)
{
HibernateQueryWrapper queryWrapper = CQL2HQL.translate((CQLQuery)obj, false,request.getCaseSensitivity().booleanValue());
String hql = queryWrapper.getHql();
List params = queryWrapper.getParameters();
log.info("CQL Query :"+hql);
Query hqlQuery = session.createQuery(hql);
for(int i = 0; i<params.size();i++)
hqlQuery.setParameter(i,params.get(i) );
if(isCount != null && isCount.booleanValue())
{
rowCount = new Integer(hqlQuery.list().size());
}
else if((isCount != null && !isCount.booleanValue()) || isCount == null)
{
if(firstRow != null)
{
hqlQuery.setFirstResult(firstRow.intValue());
}
if(resultsPerQuery != null)
{
if(resultsPerQuery.intValue() > maxRecordsPerQuery)
{
String msg = "Illegal Value for RecordsPerQuery: recordsPerQuery cannot be greater than maxRecordsPerQuery. RecordsPerQuery = " + recordsPerQuery + " maxRecordsPerQuery = " + maxRecordsPerQuery ;
log.error(msg);
throw new Exception(msg);
}
else
{
hqlQuery.setMaxResults(resultsPerQuery.intValue());
}
}
else
{
hqlQuery.setMaxResults(recordsPerQuery);
}
rs = hqlQuery.list();
}
}
}
catch (JDBCException ex)
{
log.error("JDBC Exception in ORMDAOImpl ", ex);
throw new DAOException("JDBC Exception in ORMDAOImpl ", ex);
}
catch(org.hibernate.HibernateException hbmEx)
{
log.error(hbmEx.getMessage());
throw new DAOException("Hibernate problem ", hbmEx);
}
catch(Exception e)
{
log.error("Exception ", e);
throw new DAOException("Exception in the ORMDAOImpl ", e);
}
finally
{
try
{
session.clear();
session.close();
}
catch (Exception eSession)
{
log.error("Could not close the session - "+ eSession.getMessage());
throw new DAOException("Could not close the session " + eSession);
}
}
Response rsp = new Response();
if(isCount != null && isCount.booleanValue())
rsp.setRowCount(rowCount);
else
rsp.setResponse(rs);
return rsp;
}
private void loadProperties(){
try{
Properties _properties = new Properties();
_properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("CORESystem.properties"));
String resultsPerQuery = _properties.getProperty("RECORDSPERQUERY");
String maxResultsPerQuery = _properties.getProperty("MAXRECORDSPERQUERY");
if(resultsPerQuery != null)
{
recordsPerQuery = new Integer(resultsPerQuery).intValue();
}
else
{
recordsPerQuery = Constant.MAX_RESULT_COUNT_PER_QUERY;
}
if(maxResultsPerQuery != null)
{
maxRecordsPerQuery = new Integer(maxResultsPerQuery).intValue();
}
}catch(IOException e)
{
log.error("IOException ", e);
}
catch(Exception ex){
log.error("Exception ", ex);
}
}
}
|
NCIP/cacore-sdk-pre411
|
src/gov/nih/nci/system/dao/impl/orm/ORMDAOImpl.java
|
Java
|
bsd-3-clause
| 13,122 |
{% extends "base.html" %}
{% block content %}
<p>Your account has been created and an email sent with information on how to activate it has been sent to you</p>
{% endblock %}
|
wraithan/archcode
|
templates/registration/registration_complete.html
|
HTML
|
bsd-3-clause
| 177 |
// MFEM Example 2
//
// Compile with: make ex2
//
// Sample runs: ex2 -m ../data/beam-tri.mesh
// ex2 -m ../data/beam-quad.mesh
// ex2 -m ../data/beam-tet.mesh
// ex2 -m ../data/beam-hex.mesh
// ex2 -m ../data/beam-wedge.mesh
// ex2 -m ../data/beam-quad.mesh -o 3 -sc
// ex2 -m ../data/beam-quad-nurbs.mesh
// ex2 -m ../data/beam-hex-nurbs.mesh
//
// Description: This example code solves a simple linear elasticity problem
// describing a multi-material cantilever beam.
//
// Specifically, we approximate the weak form of -div(sigma(u))=0
// where sigma(u)=lambda*div(u)*I+mu*(grad*u+u*grad) is the stress
// tensor corresponding to displacement field u, and lambda and mu
// are the material Lame constants. The boundary conditions are
// u=0 on the fixed part of the boundary with attribute 1, and
// sigma(u).n=f on the remainder with f being a constant pull down
// vector on boundary elements with attribute 2, and zero
// otherwise. The geometry of the domain is assumed to be as
// follows:
//
// +----------+----------+
// boundary --->| material | material |<--- boundary
// attribute 1 | 1 | 2 | attribute 2
// (fixed) +----------+----------+ (pull down)
//
// The example demonstrates the use of high-order and NURBS vector
// finite element spaces with the linear elasticity bilinear form,
// meshes with curved elements, and the definition of piece-wise
// constant and vector coefficient objects. Static condensation is
// also illustrated.
//
// We recommend viewing Example 1 before viewing this example.
#include "mfem.hpp"
#include <fstream>
#include <iostream>
using namespace std;
using namespace mfem;
int main(int argc, char *argv[])
{
// 1. Parse command-line options.
const char *mesh_file = "../data/beam-tri.mesh";
int order = 1;
bool static_cond = false;
bool visualization = 1;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&order, "-o", "--order",
"Finite element order (polynomial degree).");
args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
"--no-static-condensation", "Enable static condensation.");
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.Parse();
if (!args.Good())
{
args.PrintUsage(cout);
return 1;
}
args.PrintOptions(cout);
// 2. Read the mesh from the given mesh file. We can handle triangular,
// quadrilateral, tetrahedral or hexahedral elements with the same code.
Mesh *mesh = new Mesh(mesh_file, 1, 1);
int dim = mesh->Dimension();
if (mesh->attributes.Max() < 2 || mesh->bdr_attributes.Max() < 2)
{
cerr << "\nInput mesh should have at least two materials and "
<< "two boundary attributes! (See schematic in ex2.cpp)\n"
<< endl;
return 3;
}
// 3. Select the order of the finite element discretization space. For NURBS
// meshes, we increase the order by degree elevation.
if (mesh->NURBSext)
{
mesh->DegreeElevate(order, order);
}
// 4. Refine the mesh to increase the resolution. In this example we do
// 'ref_levels' of uniform refinement. We choose 'ref_levels' to be the
// largest number that gives a final mesh with no more than 5,000
// elements.
{
int ref_levels =
(int)floor(log(5000./mesh->GetNE())/log(2.)/dim);
for (int l = 0; l < ref_levels; l++)
{
mesh->UniformRefinement();
}
}
// 5. Define a finite element space on the mesh. Here we use vector finite
// elements, i.e. dim copies of a scalar finite element space. The vector
// dimension is specified by the last argument of the FiniteElementSpace
// constructor. For NURBS meshes, we use the (degree elevated) NURBS space
// associated with the mesh nodes.
FiniteElementCollection *fec;
FiniteElementSpace *fespace;
if (mesh->NURBSext)
{
fec = NULL;
fespace = mesh->GetNodes()->FESpace();
}
else
{
fec = new H1_FECollection(order, dim);
fespace = new FiniteElementSpace(mesh, fec, dim);
}
cout << "Number of finite element unknowns: " << fespace->GetTrueVSize()
<< endl << "Assembling: " << flush;
// 6. Determine the list of true (i.e. conforming) essential boundary dofs.
// In this example, the boundary conditions are defined by marking only
// boundary attribute 1 from the mesh as essential and converting it to a
// list of true dofs.
Array<int> ess_tdof_list, ess_bdr(mesh->bdr_attributes.Max());
ess_bdr = 0;
ess_bdr[0] = 1;
fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
// 7. Set up the linear form b(.) which corresponds to the right-hand side of
// the FEM linear system. In this case, b_i equals the boundary integral
// of f*phi_i where f represents a "pull down" force on the Neumann part
// of the boundary and phi_i are the basis functions in the finite element
// fespace. The force is defined by the VectorArrayCoefficient object f,
// which is a vector of Coefficient objects. The fact that f is non-zero
// on boundary attribute 2 is indicated by the use of piece-wise constants
// coefficient for its last component.
VectorArrayCoefficient f(dim);
for (int i = 0; i < dim-1; i++)
{
f.Set(i, new ConstantCoefficient(0.0));
}
{
Vector pull_force(mesh->bdr_attributes.Max());
pull_force = 0.0;
pull_force(1) = -1.0e-2;
f.Set(dim-1, new PWConstCoefficient(pull_force));
}
LinearForm *b = new LinearForm(fespace);
b->AddBoundaryIntegrator(new VectorBoundaryLFIntegrator(f));
cout << "r.h.s. ... " << flush;
b->Assemble();
// 8. Define the solution vector x as a finite element grid function
// corresponding to fespace. Initialize x with initial guess of zero,
// which satisfies the boundary conditions.
GridFunction x(fespace);
x = 0.0;
// 9. Set up the bilinear form a(.,.) on the finite element space
// corresponding to the linear elasticity integrator with piece-wise
// constants coefficient lambda and mu.
Vector lambda(mesh->attributes.Max());
lambda = 1.0;
lambda(0) = lambda(1)*50;
PWConstCoefficient lambda_func(lambda);
Vector mu(mesh->attributes.Max());
mu = 1.0;
mu(0) = mu(1)*50;
PWConstCoefficient mu_func(mu);
BilinearForm *a = new BilinearForm(fespace);
a->AddDomainIntegrator(new ElasticityIntegrator(lambda_func,mu_func));
// 10. Assemble the bilinear form and the corresponding linear system,
// applying any necessary transformations such as: eliminating boundary
// conditions, applying conforming constraints for non-conforming AMR,
// static condensation, etc.
cout << "matrix ... " << flush;
if (static_cond) { a->EnableStaticCondensation(); }
a->Assemble();
SparseMatrix A;
Vector B, X;
a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);
cout << "done." << endl;
cout << "Size of linear system: " << A.Height() << endl;
#ifndef MFEM_USE_SUITESPARSE
// 11. Define a simple symmetric Gauss-Seidel preconditioner and use it to
// solve the system Ax=b with PCG.
GSSmoother M(A);
PCG(A, M, B, X, 1, 500, 1e-8, 0.0);
#else
// 11. If MFEM was compiled with SuiteSparse, use UMFPACK to solve the system.
UMFPackSolver umf_solver;
umf_solver.Control[UMFPACK_ORDERING] = UMFPACK_ORDERING_METIS;
umf_solver.SetOperator(A);
umf_solver.Mult(B, X);
#endif
// 12. Recover the solution as a finite element grid function.
a->RecoverFEMSolution(X, *b, x);
// 13. For non-NURBS meshes, make the mesh curved based on the finite element
// space. This means that we define the mesh elements through a fespace
// based transformation of the reference element. This allows us to save
// the displaced mesh as a curved mesh when using high-order finite
// element displacement field. We assume that the initial mesh (read from
// the file) is not higher order curved mesh compared to the chosen FE
// space.
if (!mesh->NURBSext)
{
mesh->SetNodalFESpace(fespace);
}
// 14. Save the displaced mesh and the inverted solution (which gives the
// backward displacements to the original grid). This output can be
// viewed later using GLVis: "glvis -m displaced.mesh -g sol.gf".
{
GridFunction *nodes = mesh->GetNodes();
*nodes += x;
x *= -1;
ofstream mesh_ofs("displaced.mesh");
mesh_ofs.precision(8);
mesh->Print(mesh_ofs);
ofstream sol_ofs("sol.gf");
sol_ofs.precision(8);
x.Save(sol_ofs);
}
// 15. Send the above data by socket to a GLVis server. Use the "n" and "b"
// keys in GLVis to visualize the displacements.
if (visualization)
{
char vishost[] = "localhost";
int visport = 19916;
socketstream sol_sock(vishost, visport);
sol_sock.precision(8);
sol_sock << "solution\n" << *mesh << x << flush;
}
// 16. Free the used memory.
delete a;
delete b;
if (fec)
{
delete fespace;
delete fec;
}
delete mesh;
return 0;
}
|
mfem/mfem
|
examples/ex2.cpp
|
C++
|
bsd-3-clause
| 9,845 |
#include <Python.h>
#include <structmember.h>
#include <DK/DK.h>
#include "DCObject.h"
struct DCLight
{
PyObject_HEAD
DKLight light;
};
static PyObject* DCLightNew(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
DCLight* self = (DCLight*)type->tp_alloc(type, 0);
if (self)
{
new (&self->light) DKLight();
return (PyObject*)self;
}
return NULL;
}
static int DCLightInit(DCLight *self, PyObject *args, PyObject *kwds)
{
int type;
DKVector3 pos;
DKColor color;
if (!PyArg_ParseTuple(args, "iO&O&", &type,
&DCVector3Converter, &pos,
&DCColorConverter, &color))
return NULL;
if (type <= 0 || type > 2)
{
PyErr_SetString(PyExc_ValueError, "first argument is invalid.");
return NULL;
}
self->light.SetType((DKLight::LightType)type);
self->light.position = pos;
self->light.color = color;
return 0;
}
static void DCLightDealloc(DCLight* self)
{
self->light.~DKLight();
Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject* DCLightAttenuation(DCLight* self, PyObject* args)
{
DKVector3 pos;
if (!PyArg_ParseTuple(args, "O&", &DCVector3Converter, &pos))
return NULL;
float f = self->light.Attenuation(pos);
return PyFloat_FromDouble(f);
}
static PyMethodDef methods[] = {
{ "attenuation", (PyCFunction)&DCLightAttenuation, METH_VARARGS },
{ NULL, NULL, NULL, NULL } /* Sentinel */
};
static PyObject* DCLightType(DCLight* self, void*)
{
int t = self->light.Type();
return PyLong_FromLong(t);
}
static int DCLightSetType(DCLight* self, PyObject* value, void*)
{
DCOBJECT_ATTRIBUTE_NOT_DELETABLE(value);
long type = PyLong_AsLong(value);
if (PyErr_Occurred())
{
PyErr_Clear();
PyErr_SetString(PyExc_TypeError, "attribute must be integer.");
return -1;
}
if (type <= 0 || type > 2)
{
PyErr_SetString(PyExc_ValueError, "attribute value is invalid.");
return -1;
}
self->light.SetType((DKLight::LightType)type);
return 0;
}
static PyObject* DCLightPosition(DCLight* self, void*)
{
const DKVector3& p = self->light.position;
return Py_BuildValue("fff", p.x, p.y, p.z);
}
static int DCLightSetPosition(DCLight* self, PyObject* value, void*)
{
DCOBJECT_ATTRIBUTE_NOT_DELETABLE(value);
DKVector3 pos;
if (DCVector3Converter(value, &pos))
{
self->light.position = pos;
return 0;
}
PyErr_Clear();
PyErr_SetString(PyExc_TypeError, "attribute must be Vector3 object.");
return -1;
}
static PyObject* DCLightColor(DCLight* self, void*)
{
const DKColor& c = self->light.color;
return Py_BuildValue("ffff", c.r, c.g, c.b, c.a);
}
static int DCLightSetColor(DCLight* self, PyObject* value, void*)
{
DCOBJECT_ATTRIBUTE_NOT_DELETABLE(value);
DKColor c;
if (DCColorConverter(value, &c))
{
self->light.color = c;
return 0;
}
PyErr_Clear();
PyErr_SetString(PyExc_TypeError, "attribute must be Color object.");
return -1;
}
static PyObject* DCLightConstAttenuation(DCLight* self, void*)
{
return PyFloat_FromDouble(self->light.constAttenuation);
}
static int DCLightSetConstAttenuation(DCLight* self, PyObject* value, void*)
{
DCOBJECT_ATTRIBUTE_NOT_DELETABLE(value);
double v = PyFloat_AsDouble(value);
if (PyErr_Occurred())
{
PyErr_Clear();
PyErr_SetString(PyExc_TypeError, "attribute must be Flaot.");
return -1;
}
self->light.constAttenuation = v;
return 0;
}
static PyObject* DCLightLinearAttenuation(DCLight* self, void*)
{
return PyFloat_FromDouble(self->light.linearAttenuation);
}
static int DCLightSetLinearAttenuation(DCLight* self, PyObject* value, void*)
{
DCOBJECT_ATTRIBUTE_NOT_DELETABLE(value);
double v = PyFloat_AsDouble(value);
if (PyErr_Occurred())
{
PyErr_Clear();
PyErr_SetString(PyExc_TypeError, "attribute must be Flaot.");
return -1;
}
self->light.linearAttenuation = v;
return 0;
}
static PyObject* DCLightQuadraticAttenuation(DCLight* self, void*)
{
return PyFloat_FromDouble(self->light.quadraticAttenuation);
}
static int DCLightSetQuadraticAttenuation(DCLight* self, PyObject* value, void*)
{
DCOBJECT_ATTRIBUTE_NOT_DELETABLE(value);
double v = PyFloat_AsDouble(value);
if (PyErr_Occurred())
{
PyErr_Clear();
PyErr_SetString(PyExc_TypeError, "attribute must be Flaot.");
return -1;
}
self->light.quadraticAttenuation = v;
return 0;
}
static PyGetSetDef getsets[] = {
{ "type", (getter)&DCLightType, (setter)&DCLightSetType, 0, 0 },
{ "position", (getter)&DCLightPosition, (setter)&DCLightSetPosition, 0, 0 },
{ "color", (getter)&DCLightColor, (setter)&DCLightSetColor, 0, 0 },
{ "constAttenuation", (getter)&DCLightConstAttenuation, (setter)&DCLightSetConstAttenuation, 0, 0 },
{ "linearAttenuation", (getter)&DCLightLinearAttenuation, (setter)&DCLightSetLinearAttenuation, 0, 0 },
{ "quadraticAttenuation", (getter)&DCLightQuadraticAttenuation, (setter)&DCLightSetQuadraticAttenuation, 0, 0 },
{ NULL } /* Sentinel */
};
static PyTypeObject objectType = {
PyVarObject_HEAD_INIT(NULL, 0)
PYDK_MODULE_NAME ".Light", /* tp_name */
sizeof(DCLight), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)&DCLightDealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
methods, /* tp_methods */
0, /* tp_members */
getsets, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)&DCLightInit, /* tp_init */
0, /* tp_alloc */
&DCLightNew, /* tp_new */
};
PyTypeObject* DCLightTypeObject(void)
{
return &objectType;
}
PyObject* DCLightFromObject(DKLight* light)
{
if (light)
{
PyObject* args = PyTuple_New(0);
PyObject* kwds = PyDict_New();
PyObject* tp = (PyObject*)DCObjectDefaultClass(&objectType);
DCLight* self = (DCLight*)PyObject_Call(tp, args, kwds);
if (self)
{
DKASSERT_DEBUG(PyObject_TypeCheck(self, DCLightTypeObject()));
self->light = *light;
}
Py_XDECREF(tp);
Py_XDECREF(args);
Py_XDECREF(kwds);
return (PyObject*)self;
}
Py_RETURN_NONE;
}
DKLight* DCLightToObject(PyObject* obj)
{
if (obj && PyObject_TypeCheck(obj, &objectType))
{
return &((DCLight*)obj)->light;
}
return NULL;
}
|
DKGL/DKGL
|
PyDK/src/DCLight.cpp
|
C++
|
bsd-3-clause
| 6,839 |
<?php
// mPDF 2.5
// BIG 5
$cw = array(
32 => 250, 33 => 250, 34 => 408, 35 => 668, 36 => 490, 37 => 875, 38 => 698, 39 => 250, 40 => 240, 41 => 240,
42 => 417, 43 => 667, 44 => 250, 45 => 313, 46 => 250, 47 => 520, 48 => 500, 49 => 500, 50 => 500, 51 => 500,
52 => 500, 53 => 500, 54 => 500, 55 => 500, 56 => 500, 57 => 500, 58 => 250, 59 => 250, 60 => 667, 61 => 667,
62 => 667, 63 => 396, 64 => 921, 65 => 677, 66 => 615, 67 => 719, 68 => 760, 69 => 625, 70 => 552, 71 => 771,
72 => 802, 73 => 354, 74 => 354, 75 => 781, 76 => 604, 77 => 927, 78 => 750, 79 => 823, 80 => 563, 81 => 823,
82 => 729, 83 => 542, 84 => 698, 85 => 771, 86 => 729, 87 => 948, 88 => 771, 89 => 677, 90 => 635, 91 => 344,
92 => 520, 93 => 344, 94 => 469, 95 => 500, 96 => 250, 97 => 469, 98 => 521, 99 => 427, 100 => 521, 101 => 438,
102 => 271, 103 => 469, 104 => 531, 105 => 250, 106 => 250, 107 => 458, 108 => 240, 109 => 802, 110 => 531, 111 => 500,
112 => 521, 113 => 521, 114 => 365, 115 => 333, 116 => 292, 117 => 521, 118 => 458, 119 => 677, 120 => 479, 121 => 458,
122 => 427, 123 => 480, 124 => 496, 125 => 480, 126 => 667,
17601 => 500,
);
$this->Big5_widths=$cw;
// GB
$cw = array(
32 => 207, 33 => 270, 34 => 342, 35 => 467, 36 => 462, 37 => 797, 38 => 710, 39 => 239, 40 => 374, 41 => 374,
42 => 423, 43 => 605, 44 => 238, 45 => 375, 46 => 238, 47 => 334, 48 => 462, 49 => 462, 50 => 462, 51 => 462,
52 => 462, 53 => 462, 54 => 462, 55 => 462, 56 => 462, 57 => 462, 58 => 238, 59 => 238, 60 => 605, 61 => 605,
62 => 605, 63 => 344, 64 => 748, 65 => 684, 66 => 560, 67 => 695, 68 => 739, 69 => 563, 70 => 511, 71 => 729,
72 => 793, 73 => 318, 74 => 312, 75 => 666, 76 => 526, 77 => 896, 78 => 758, 79 => 772, 80 => 544, 81 => 772,
82 => 628, 83 => 465, 84 => 607, 85 => 753, 86 => 711, 87 => 972, 88 => 647, 89 => 620, 90 => 607, 91 => 374,
92 => 333, 93 => 374, 94 => 606, 95 => 500, 96 => 239, 97 => 417, 98 => 503, 99 => 427, 100 => 529, 101 => 415,
102 => 264, 103 => 444, 104 => 518, 105 => 241, 106 => 230, 107 => 495, 108 => 228, 109 => 793, 110 => 527, 111 => 524,
112 => 524, 113 => 504, 114 => 338, 115 => 336, 116 => 277, 117 => 517, 118 => 450, 119 => 652, 120 => 466, 121 => 452,
122 => 407, 123 => 370, 124 => 258, 125 => 370, 126 => 605,
);
$this->GB_widths=$cw;
// Japanese
$cw = array(
32 => 278, 33 => 299, 34 => 353, 35 => 614, 36 => 614, 37 => 721, 38 => 735, 39 => 216, 40 => 323, 41 => 323,
42 => 449, 43 => 529, 44 => 219, 45 => 306, 46 => 219, 47 => 453, 48 => 614, 49 => 614, 50 => 614, 51 => 614,
52 => 614, 53 => 614, 54 => 614, 55 => 614, 56 => 614, 57 => 614, 58 => 219, 59 => 219, 60 => 529, 61 => 529,
62 => 529, 63 => 486, 64 => 744, 65 => 646, 66 => 604, 67 => 617, 68 => 681, 69 => 567, 70 => 537, 71 => 647,
72 => 738, 73 => 320, 74 => 433, 75 => 637, 76 => 566, 77 => 904, 78 => 710, 79 => 716, 80 => 605, 81 => 716,
82 => 623, 83 => 517, 84 => 601, 85 => 690, 86 => 668, 87 => 990, 88 => 681, 89 => 634, 90 => 578, 91 => 316,
92 => 614, 93 => 316, 94 => 529, 95 => 500, 96 => 387, 97 => 509, 98 => 566, 99 => 478, 100 => 565, 101 => 503,
102 => 337, 103 => 549, 104 => 580, 105 => 275, 106 => 266, 107 => 544, 108 => 276, 109 => 854, 110 => 579, 111 => 550,
112 => 578, 113 => 566, 114 => 410, 115 => 444, 116 => 340, 117 => 575, 118 => 512, 119 => 760, 120 => 503, 121 => 529,
122 => 453, 123 => 326, 124 => 380, 125 => 326, 126 => 387, 127 => 216, 128 => 453, 129 => 216, 130 => 380, 131 => 529,
132 => 299, 133 => 614, 134 => 614, 135 => 265, 136 => 614, 137 => 475, 138 => 614, 139 => 353, 140 => 451, 141 => 291,
142 => 291, 143 => 588, 144 => 589, 145 => 500, 146 => 476, 147 => 476, 148 => 219, 149 => 494, 150 => 452, 151 => 216,
152 => 353, 153 => 353, 154 => 451, 156 => 1075, 157 => 486, 158 => 387, 159 => 387, 160 => 387, 161 => 387,
162 => 387, 163 => 387, 164 => 387, 165 => 387, 166 => 387, 167 => 387, 168 => 387, 170 => 880, 171 => 448,
172 => 566, 173 => 716, 174 => 903, 175 => 460, 176 => 805, 177 => 275, 178 => 276, 179 => 550, 180 => 886, 181 => 582,
182 => 529, 183 => 738, 184 => 529, 185 => 738, 186 => 357, 187 => 529, 188 => 406, 189 => 406, 190 => 575, 191 => 406,
192 => 934, 193 => 934, 194 => 934, 195 => 646, 196 => 646, 197 => 646, 198 => 646, 199 => 646, 200 => 646, 201 => 617,
202 => 567, 203 => 567, 204 => 567, 205 => 567, 206 => 320, 207 => 320, 208 => 320, 209 => 320, 210 => 681, 211 => 710,
212 => 716, 213 => 716, 214 => 716, 215 => 716, 216 => 716, 217 => 529, 218 => 690, 219 => 690, 220 => 690, 221 => 690,
222 => 634, 223 => 605, 224 => 509, 225 => 509, 226 => 509, 227 => 509, 228 => 509, 229 => 509, 230 => 478, 231 => 503,
232 => 503, 233 => 503, 234 => 503, 235 => 275, 236 => 275, 237 => 275, 238 => 275, 239 => 550, 240 => 579, 241 => 550,
242 => 550, 243 => 550, 244 => 550, 245 => 550, 246 => 529, 247 => 575, 248 => 575, 249 => 575, 250 => 575, 251 => 529,
252 => 578, 253 => 529, 254 => 517, 255 => 634, 256 => 578, 257 => 445, 258 => 444, 259 => 842, 260 => 453, 261 => 614,
);
$_cr = array(
array(231, 632, 500), // half-width
array(8718, 8718, 500),
array(9738, 9757, 250), // quarter-width
array(9758, 9778, 333), // third-width
array(12063, 12087, 500),
);
foreach($_cr as $_r) {
for($i = $_r[0]; $i <= $_r[1]; $i++) {
$cw[$i+31] = $_r[2];
}
}
$this->SJIS_widths=$cw;
// Korean
$cw = array(
32 => 333, 33 => 416, 34 => 416, 35 => 833, 36 => 625, 37 => 916, 38 => 833, 39 => 250, 40 => 500, 41 => 500,
42 => 500, 43 => 833, 44 => 291, 45 => 450, 46 => 291, 47 => 375, 48 => 625, 49 => 625, 50 => 625, 51 => 625,
52 => 625, 53 => 625, 54 => 625, 55 => 625, 56 => 625, 57 => 625, 58 => 333, 59 => 333, 60 => 833, 61 => 833,
62 => 916, 63 => 500, 64 => 1000, 65 => 791, 66 => 708, 67 => 708, 68 => 750, 69 => 708, 70 => 666, 71 => 750,
72 => 791, 73 => 375, 74 => 500, 75 => 791, 76 => 666, 77 => 916, 78 => 791, 79 => 750, 80 => 666, 81 => 750,
82 => 708, 83 => 666, 84 => 791, 85 => 791, 86 => 750, 87 => 1000, 88 => 708, 89 => 708, 90 => 666, 91 => 500,
92 => 375, 93 => 500, 94 => 500, 95 => 500, 96 => 333, 97 => 541, 98 => 583, 99 => 541, 100 => 583, 101 => 583,
102 => 375, 103 => 583, 104 => 583, 105 => 291, 106 => 333, 107 => 583, 108 => 291, 109 => 875, 110 => 583, 111 => 583,
112 => 583, 113 => 583, 114 => 458, 115 => 541, 116 => 375, 117 => 583, 118 => 583, 119 => 833, 120 => 625, 121 => 625,
122 => 500, 123 => 583, 124 => 583, 125 => 583, 126 => 750,
);
$_cr = array(
array(8094, 8190, 500)
);
foreach($_cr as $_r) {
for($i = $_r[0]; $i <= $_r[1]; $i++) {
$cw[$i+31] = $_r[2];
}
}
$this->UHC_widths=$cw;
?>
|
troikaitsulutions/templeadvisor
|
common/pdftest/mpdf/includes/CJKdata.php
|
PHP
|
bsd-3-clause
| 6,591 |
<?php
namespace Vivo\Service;
use Zend\Db\Adapter\Adapter as ZendDbAdapter;
use Doctrine\ORM\EntityManager;
use PDO;
/**
* DbProvider
* Provides various types of db access objects for a configured db source
*/
class DbProvider implements DbProviderInterface
{
/**
* Db source name
* @var string
*/
protected $dbSource;
/**
* Db Service Manager
* @var DbServiceManagerInterface
*/
protected $dbServiceManager;
/**
* Constructor
* @param \Vivo\Service\DbServiceManagerInterface $dbServiceManager
* @param string $dbSource
* @throws Exception\DbSourceDoesNotExistException
*/
public function __construct(DbServiceManagerInterface $dbServiceManager, $dbSource)
{
$this->dbServiceManager = $dbServiceManager;
$this->dbSource = $dbSource;
//Check that the specified db source exists
if (!$this->dbServiceManager->hasDbService($dbSource)) {
throw new Exception\DbSourceDoesNotExistException(
sprintf("%s: Db source '%s' does not exist", __METHOD__, $dbSource));
}
}
/**
* Returns PDO object
* @return PDO
*/
public function getPdo()
{
return $this->dbServiceManager->getPdo($this->dbSource);
}
/**
* Returns Zend DB Adapter
* @return ZendDbAdapter
*/
public function getZendDbAdapter()
{
return $this->dbServiceManager->getZendDbAdapter($this->dbSource);
}
/**
* Returns Doctrine Entity Manager
* @return EntityManager
*/
public function getDoctrineEntityManager()
{
return $this->dbServiceManager->getDoctrineEntityManager($this->dbSource);
}
}
|
kormik/vp
|
module/Vivo/src/Vivo/Service/DbProvider.php
|
PHP
|
bsd-3-clause
| 1,730 |
<script src="../turi/js/recview.js"></script>
# Distributed Machine Learning
*Note: The distributed machine learning API has been through significant changes in 2.0 and is not backwards compatible*
In the previous chapter we showed how to run jobs in a Turi Distributed cluster.
While, Job (or Map Job) give you the benefit of executing arbitrary python code in cluster in a map reduce fashion,
it does not support distributing the training of machine learning models.
For a set of GraphLab Create toolkits we have enabled distributed model training in a hadoop cluster.
We call this _Distributed Machine Learning_ or _DML_. In this section, we will demonstrate how to run distributed machine learning tasks.
The toolkits currently supported to run in a distributed execution environment are:
* [Linear regression](https://turi.com/learn/userguide/supervised-learning/linear-regression.html)
* [Logistic classifier](https://turi.com/learn/userguide/supervised-learning/logistic-regression.html)
* [SVM classifier](https://turi.com/learn/userguide/supervised-learning/svm.html)
* [Boosted trees classifier](https://turi.com/learn/userguide/supervised-learning/boosted_trees_classifier.html)
* [Boosted trees regression](https://turi.com/learn/userguide/supervised-learning/boosted_trees_regression.html)
* [Random forest classifier](https://turi.com/learn/userguide/supervised-learning/random_forest_classifier.html)
* [Random forest regression](https://turi.com/learn/userguide/supervised-learning/random_forest_regression.html)
* [Pagerank](https://turi.com/products/create/docs/generated/graphlab.pagerank.create.html)
* [Label propagation](https://turi.com/products/create/docs/generated/graphlab.label_propagation.create.html)
Let us look at an example which trains a boosted trees classifier model:
```python
import graphlab as gl
# Load data
dataset = 'https://static.turi.com/datasets/xgboost/mushroom.csv'
sf = gl.SFrame(dataset)
# Train model
model = gl.boosted_trees_classifier.create(sf, target='label', max_iterations=12)
```
#### Hadoop
For distributed machine learning on Hadoop, you will need a cluster object based on a Turi Distributed installation in your Hadoop cluster:
```python
>>> c = gl.deploy.hadoop_cluster.create('my-first-hadoop-cluster',
'hdfs://path-to-turi-distributed-installation',
num_containers=4,
container_size=4096,
num_vcores=4)
>>> c.hdfs_tmp_dir = hdfs:///tmp
>>> print c
Hadoop Cluster:
Name: : my-cluster
Cluster path : hdfs://path-to-turi-distributed-installation
Number of Containers: : 4
Container Size (in mb) : 4096
Container num of vcores : 4
Port range : 9100 - 9200
Node temp directory : /tmp
HDFS temp directory : hdfs:///tmp
Additional packages : None
```
For more information about how to set up a cluster in Hadoop see the chapter on [clusters](pipeline-ec2-hadoop.md).
The following cluster parameters are critical for successfully running distributed model training:
- `container_size` : Memory limit in MB for each worker. Workers which exceed the memory limit may get killed and result in job failure.
- `Node temp directory` : The local temporary directory to store cache and intermediate files. Make sure this directory has
enough disk space.
- `HDFS temp directory` : The hdfs temporary directory to store cache and intermediate files. Make sure this directory has
enough disk space and is writable by hadoop user `yarn`.
Once the cluster is created you can use it as an execution environment for a machine learning task:
```python
sf = gl.SFrame('hdfs://DATASET_PATH')
job = gl.distributed.boosted_trees_classifier.submit_training_job(env=c, dataset=sf, target='label')
```
The above code submits to the cluster a distributed boosted trees classifier training job which is automatically distributed
among the number of containers. The return object is a handle to the submitted job.
```python
>>> print job.get_state()
STATE.COMPLETED
```
```
>>> print job.get_progress()
PROGRESS: Number of workers: 4
PROGRESS: CPUs per worker : 4
PROGRESS: Memory limit: 3276.8MB
PROGRESS: Local cache file locations: /tmp
PROGRESS: HDFS access: yes
PROGRESS: HDFS cache file locations: hdfs:///tmp
PROGRESS: Max fileio cache capacity: 819.2MB
PROGRESS: Boosted trees classifier:
PROGRESS: --------------------------------------------------------
PROGRESS: Number of examples : 8124
PROGRESS: Number of classes : 2
PROGRESS: Number of feature columns : 22
PROGRESS: Number of unpacked features : 22
PROGRESS: +-----------+--------------+-------------------+-------------------+
PROGRESS: | Iteration | Elapsed Time | Training-accuracy | Training-log_loss |
PROGRESS: +-----------+--------------+-------------------+-------------------+
PROGRESS: | 1 | 0.124934 | 0.999631 | 0.438946 |
PROGRESS: | 2 | 0.245594 | 0.999631 | 0.298226 |
PROGRESS: | 3 | 0.355051 | 0.999631 | 0.209494 |
PROGRESS: | 4 | 0.489932 | 0.999631 | 0.150114 |
PROGRESS: | 5 | 0.605267 | 0.999631 | 0.109027 |
PROGRESS: Checkpointing to hdfs:///turi_distributed/jobs/dml_job_88a92020-e6d9-42d3-ade3-058e278dbf1e/checkpoints/model_checkpoint_5
PROGRESS: | 6 | 1.255561 | 0.999631 | 0.080002 |
PROGRESS: | 10 | 1.665121 | 0.999631 | 0.024130 |
PROGRESS: Checkpointing to hdfs:///turi_distributed/jobs/dml_job_88a92020-e6d9-42d3-ade3-058e278dbf1e/checkpoints/model_checkpoint_10
PROGRESS: +-----------+--------------+-------------------+-------------------+
```
```python
# wait for job to complete
import time
while job.get_state() != job.STATE.COMPLETED:
time.sleep(1)
print job.get_progress()
print job.get_state()
# check the final state
assert job.get_final_state() == job.FINAL_STATE.SUCCESS:
# fetch the trained model, this code will block until job.get_state() is COMPLETED.
model = job.get_results()
model.save('./bst_mushroom')
```
#### Data locality
Data locality is critical to efficient distributed model training with massive data.
In the example above, because the SFrame is constructed from HDFS source, there will be no copy
of data between HDFS and the local machine that submits the training job.
The model training process will be executed natively in the cluster by reading from HDFS.
On the other hand, if the SFrame is constructed locally, or read from S3, the SFrame will
be automatically copied into HDFS. Depending on the size of the data and network speed, this process
can take from minutes to hours. Hence, it is recommended to always save your training or validation SFrame
to HDFS before submitting the training job.
#### Model Checkpointing (Available for Boosted Trees and Random Forest models)
Jobs running in distributed environment like Yarn may be preempted when the load of the cluster is high. Therefore,
it is critical to have some recovery mechanism for models that could take very long time to train.
For training a Boosted Trees or Random Forest model, the API supports checkpointing the model
every K (default 5) iterations to a file system (local, HDFS or S3) location. In case of interruption,
you can resume the training procedure by pointing to the checkpointed model. This feature is enabled by default
for distributed boosted trees and random forest model. The training job automatically creates a checkpoint
every 5 iterations at the working directory.
```python
>>> print job.last_checkpoint()
hdfs://turi_distributed/jobs/dml_job_1324f729-250f-497c-9f28-4c06ff5daf71/checkpoints/model_checkpoint_10
```
```python
# Resume training from last checkpoint at iteration 10
job2 = gl.distributed.boosted_trees_classifier.submit_training_job(env=c, dataset=sf, target='label', max_iterations=12,
resume_from_checkpoint=job.last_checkpoint())
```
You can also specify the location and frequency of checkpointing by using the parameter `model_checkpoint_path` and
`model_checkpoint_interval` in `submit_training_job`. For example:
```python
# Change the default checkpoint frequency and location
job = gl.distributed.boosted_trees_classifier.submit_training_job(env=c, dataset=sf, target='label', max_iterations=12,
model_checkpoint_interval=10,
model_checkpoint_path='hdfs:///tmp/job1/model_checkpoints')
```
*Note: The training job is executed as hadoop user `yarn` in the cluster. When specifying model_checkpoint_path, please
make sure the directory is writable by hadoop user `yarn`.*
#### Debugging Job Failure
The final job state could be one of the followings: `FINAL_STATE.SUCCESS`, `FINAL_STATE.KILLED`, `FINAL_STATE.FAILURE`.
When the job does not complete successfully, the following sequence may be executed to debug the failure.
```python
>>> print job.get_final_state()
'FINAL_STATE.FAILURE'
>>> print job.summary()
Container list: ['container_e44_1467403925081_0044_01_000001', 'container_e44_1467403925081_0044_01_000002', 'container_e44_1467403925081_0044_01_000003', 'container_e44_1467403925081_0044_01_000004']
container_e44_1467403925081_0044_01_000001:
Application Master
container_e44_1467403925081_0044_01_000002:
Report not found in log.
container_e44_1467403925081_0044_01_000003:
Report not found in log.
container_e44_1467403925081_0044_01_000004:
Container terminated due to exceeding allocated physical memory. (-104)
```
```python
# Get the location of yarn logs, you can open the log file in your local editor.
>>> print job.get_log_file_path()
/tmp/tmpdcl2_V/tmp_log.stdout
```
|
dato-code/userguide
|
deployment/pipeline-dml.md
|
Markdown
|
bsd-3-clause
| 10,064 |
// Copyright 2016 EF CTX. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"time"
"github.com/kelseyhightower/envconfig"
"github.com/sirupsen/logrus"
)
const version = "0.1.3"
var printVersion bool
func init() {
flag.BoolVar(&printVersion, "v", false, "print version and exit")
flag.Parse()
}
type config struct {
BindAddress string `envconfig:"BIND_ADDRESS" default:":9000"`
HipacheAddress string `envconfig:"HIPACHE_ADDRESS" required:"true"`
LogLevel string `envconfig:"LOG_LEVEL" default:"debug"`
}
func (c config) logLevel() logrus.Level {
if level, err := logrus.ParseLevel(c.LogLevel); err == nil {
return level
}
return logrus.DebugLevel
}
func main() {
if printVersion {
fmt.Printf("hipache-healthcheck-proxy %s\n", version)
return
}
var c config
err := envconfig.Process("", &c)
if err != nil {
log.Fatal(err)
}
logger := logrus.New()
logger.Level = c.logLevel()
if _, err = url.Parse(c.HipacheAddress); err != nil {
logger.WithError(err).Fatal("failed to parse hipache address")
}
client := http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{Timeout: time.Second}).DialContext,
},
Timeout: 2 * time.Second,
}
logger.Debugf("starting on %s...", c.BindAddress)
err = http.ListenAndServe(c.BindAddress, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
req, err := http.NewRequest("GET", c.HipacheAddress, nil)
if err != nil {
logger.WithError(err).Error("failed to create request")
http.Error(w, "failed to process request", http.StatusInternalServerError)
return
}
req.Host = "__ping__"
resp, err := client.Do(req)
if err != nil {
logger.WithError(err).Error("failed to send request to hipache")
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
defer resp.Body.Close()
headers := make(map[string]string)
for h := range resp.Header {
w.Header().Set(h, resp.Header.Get(h))
headers[h] = resp.Header.Get(h)
}
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
logger.WithFields(logrus.Fields{
"statusCode": resp.StatusCode,
"ellapsedTime": time.Since(start).String(),
"headers": headers,
}).Debug("healthcheck completed")
}))
if err != nil {
log.Fatal(err)
}
}
|
ef-ctx/hipache-healthcheck-proxy
|
proxy.go
|
GO
|
bsd-3-clause
| 2,432 |
# -*- coding: utf-8 -*-
import os
ugettext = lambda s: s # dummy ugettext function, as django's docs say
DEBUG = True
TEMPLATE_DEBUG = DEBUG
THUMBNAIL_DEBUG = DEBUG
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__.decode('utf-8')))
ADMINS = (('Mirat Can Bayrak', '[email protected]'),)
SERVER_EMAIL = "[email protected]"
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(PROJECT_ROOT, 'sqlite3.db')}}
TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'tr'
SITE_ID = 1
USE_I18N = True
USE_L10N = False
STATIC_ROOT = os.path.join(PROJECT_ROOT, "static")
MEDIA_ROOT = os.path.join(PROJECT_ROOT, "media")
LOCALE_PATHS = (os.path.join(PROJECT_ROOT, "locale"),)
MEDIA_URL = "/media/"
STATIC_URL = "/static/"
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, "sitestatic/"),
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
'django.middleware.locale.LocaleMiddleware',
'seo_cascade.middleware.SEOMiddleware',
)
INTERNAL_IPS = ('127.0.0.1',)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages",
'django.core.context_processors.request',
)
ROOT_URLCONF = 'linkfloyd.urls'
TEMPLATE_DIRS = (
os.path.join(PROJECT_ROOT, "templates"),
)
INSTALLED_APPS = [
# contrib
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.flatpages',
'django.contrib.sitemaps',
# linkfloyd
'linkfloyd.links',
'linkfloyd.preferences',
'linkfloyd.channels',
'linkfloyd.comments',
'linkfloyd.summaries',
'linkfloyd.wiki',
'linkfloyd.notifications',
# 3th party
'sorl.thumbnail',
'qhonuskan_votes',
'registration',
'gravatar',
'seo_cascade',
'pipeline',
]
STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
PIPELINE_COMPILERS = (
'pipeline.compilers.less.LessCompiler',
)
PIPELINE_CSS = {
'bootstrap': {
'source_filenames': (
'css/style.less',
),
'output_filename': 'css/b.css',
'extra_context': {
'media': 'screen,projection',
},
},
}
PIPELINE_LESS_BINARY = "~/node_modules/less/bin/lessc"
# EMAIL
SEND_BROKEN_LINK_EMAILS = True
DEFAULT_FROM_EMAIL = "[email protected]"
# REGISTRATION
ACCOUNT_ACTIVATION_DAYS = 3
LOGIN_REDIRECT_URL = "/"
ABSOLUTE_URL_OVERRIDES = {
'auth.user': lambda user: "/links/from/%s/" % user.username,
}
# GRAVATAR
GRAVATAR_DEFAULT_IMAGE = "mm"
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
from local_settings import *
|
linkfloyd/linkfloyd
|
linkfloyd/settings.py
|
Python
|
bsd-3-clause
| 4,418 |
<!DOCTYPE html>
<html>
<head>
<title>Foreign Function Interface - Rubinius</title>
<meta content='text/html;charset=utf-8' http-equiv='content-type'>
<meta content='en' http-equiv='content-language'>
<meta content='Rubinius is an implementation of the Ruby programming language. The Rubinius bytecode virtual machine is written in C++. The bytecode compiler is written in pure Ruby. The vast majority of the core library is also written in Ruby, with some supporting primitives that interact with the VM directly.' name='description'>
<meta content='Less Than Three. <3. http://less.thanthree.com' name='author'>
<link href='/' rel='home'>
<link href='/' rel='start'>
<link href='/doc/en/systems/primitives' rel='prev' title='Primitives'>
<link href='/doc/en/systems/concurrency' rel='next' title='Concurrency'>
<!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js" type="text/javascript"></script><![endif]-->
<script src="/javascripts/jquery-1.3.2.js" type="text/javascript"></script>
<script src="/javascripts/paging_keys.js" type="text/javascript"></script>
<script src="/javascripts/application.js" type="text/javascript"></script>
<style>article, aside, dialog, figure, footer, header, hgroup, menu, nav, section { display: block; }</style>
<link href="/stylesheets/blueprint/screen.css" media="screen" rel="stylesheet" type="text/css" />
<link href="/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />
<link href="/stylesheets/blueprint/print.css" media="print" rel="stylesheet" type="text/css" />
<!--[if IE]><link href="/stylesheets/blueprint/ie.css" media="screen" rel="stylesheet" type="text/css" /><![endif]-->
<!--[if IE]><link href="/stylesheets/ie.css" media="screen" rel="stylesheet" type="text/css" /><![endif]-->
<link href="/stylesheets/pygments.css" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>
<div class='container'>
<div class='span-21 doc_menu'>
<header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a id="blog" href="/blog/">Blog</a></li>
<li><a id="documentation" href="/doc/en/">Documentation</a></li>
<li><a href="/projects/">Projects</a></li>
<li><a href="/roadmap/">Roadmap</a></li>
<li><a href="/releases/">Releases</a></li>
</ul>
</nav>
</header>
</div>
<div class='span-3 last'>
<div id='version'>
<a href="/releases/1.2.3">1.2.3</a>
</div>
</div>
</div>
<div class="container languages">
<nav>
<span class="label">Languages:</span>
<ul>
<li><a href="/doc/fr/systems/ffi/"
>de</a></li>
<li><a href="/doc/fr/systems/ffi/"
class="current"
>en</a></li>
<li><a href="/doc/fr/systems/ffi/"
>es</a></li>
<li><a href="/doc/fr/systems/ffi/"
>fr</a></li>
<li><a href="/doc/fr/systems/ffi/"
>ja</a></li>
<li><a href="/doc/fr/systems/ffi/"
>pl</a></li>
<li><a href="/doc/fr/systems/ffi/"
>pt-br</a></li>
<li><a href="/doc/fr/systems/ffi/"
>ru</a></li>
</ul>
</nav>
</div>
<div class="container doc_page_nav">
<span class="label">Previous:</span>
<a href="/doc/en/systems/primitives">Primitives</a>
<span class="label">Up:</span>
<a href="/doc/en/">Table of Contents</a>
<span class="label">Next:</span>
<a href="/doc/en/systems/concurrency">Concurrency</a>
</div>
<div class="container documentation">
<h2>Foreign Function Interface</h2>
<div class="review">
<p>This topic has missing or partial documentation. Please help us improve
it.</p>
<p>See <a href="/doc/en/how-to/write-documentation">
How-To - Write Documentation</a></p>
</div>
</div>
<div class="container doc_page_nav">
<span class="label">Previous:</span>
<a href="/doc/en/systems/primitives">Primitives</a>
<span class="label">Up:</span>
<a href="/doc/en/">Table of Contents</a>
<span class="label">Next:</span>
<a href="/doc/en/systems/concurrency">Concurrency</a>
</div>
<div class="container">
<div id="disqus_thread"></div>
<script type="text/javascript">
var disqus_shortname = 'rubinius';
var disqus_identifier = '/doc/fr/systems/ffi/';
var disqus_url = 'http://rubini.us/doc/fr/systems/ffi/';
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>
<footer>
<div class='container'>
<nav>
<ul>
<li><a href="http://twitter.com/rubinius">Follow Rubinius on Twitter</a></li>
<li><a href="http://github.com/rubinius/rubinius">Fork Rubinius on github</a></li>
<li><a href="http://engineyard.com">An Engine Yard project</a></li>
<li id='credit'>
Site design by
<a href="http://less.thanthree.com">Less Than Three</a>
</li>
</ul>
</nav>
</div>
</footer>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-12328521-1");
pageTracker._trackPageview();
} catch(err) {}</script>
</body>
</html>
|
mallibone/rubinius
|
web/_site/doc/fr/systems/ffi/index.html
|
HTML
|
bsd-3-clause
| 6,415 |
#include "CLIConfigParsing.h"
#include "mmcore/LuaAPI.h"
#include "mmcore/utility/log/DefaultTarget.h"
#include "mmcore/utility/log/Log.h"
#include "mmcore/CoreInstance.h"
#include "mmcore/MegaMolGraph.h"
#include "GlobalValueStore.h"
#include "RuntimeConfig.h"
#include "CUDA_Service.hpp"
#include "Command_Service.hpp"
#include "FrameStatistics_Service.hpp"
#include "FrontendServiceCollection.hpp"
#include "GUI_Service.hpp"
#include "ImagePresentation_Service.hpp"
#include "Lua_Service_Wrapper.hpp"
#include "OpenGL_GLFW_Service.hpp"
#include "Profiling_Service.hpp"
#include "ProjectLoader_Service.hpp"
#include "Remote_Service.hpp"
#include "Screenshot_Service.hpp"
#include "VR_Service.hpp"
static void log(std::string const& text) {
const std::string msg = "Main: " + text;
megamol::core::utility::log::Log::DefaultLog.WriteInfo(msg.c_str());
}
static void log_warning(std::string const& text) {
const std::string msg = "Main: " + text;
megamol::core::utility::log::Log::DefaultLog.WriteWarn(msg.c_str());
}
static void log_error(std::string const& text) {
const std::string msg = "Main: " + text;
megamol::core::utility::log::Log::DefaultLog.WriteError(msg.c_str());
}
int main(const int argc, const char** argv) {
megamol::core::LuaAPI lua_api;
auto [config, global_value_store] = megamol::frontend::handle_cli_and_config(argc, argv, lua_api);
const bool with_gl = !config.no_opengl;
// setup log
megamol::core::utility::log::Log::DefaultLog.SetLevel(config.echo_level);
megamol::core::utility::log::Log::DefaultLog.SetEchoLevel(config.echo_level);
megamol::core::utility::log::Log::DefaultLog.SetFileLevel(config.log_level);
megamol::core::utility::log::Log::DefaultLog.SetOfflineMessageBufferSize(100);
megamol::core::utility::log::Log::DefaultLog.SetMainTarget(
std::make_shared<megamol::core::utility::log::DefaultTarget>());
if (!config.log_file.empty())
megamol::core::utility::log::Log::DefaultLog.SetLogFileName(config.log_file.data(), false);
log(config.as_string());
log(global_value_store.as_string());
megamol::core::CoreInstance core;
core.SetConfigurationPaths_Frontend3000Compatibility(
config.application_directory, config.shader_directories, config.resource_directories);
core.Initialise(
false); // false means the core ignores some mmconsole legacy features, e.g. we don't collide on Lua host ports
megamol::frontend::OpenGL_GLFW_Service gl_service;
megamol::frontend::OpenGL_GLFW_Service::Config openglConfig;
openglConfig.windowTitlePrefix = "MegaMol";
if (config.opengl_context_version.has_value()) {
openglConfig.versionMajor = std::get<0>(config.opengl_context_version.value());
openglConfig.versionMinor = std::get<1>(config.opengl_context_version.value());
openglConfig.glContextCoreProfile = std::get<2>(config.opengl_context_version.value());
}
openglConfig.enableKHRDebug = config.opengl_khr_debug;
openglConfig.enableVsync = config.opengl_vsync;
// pass window size and position
if (config.window_size.has_value()) {
openglConfig.windowPlacement.size = true;
openglConfig.windowPlacement.w = config.window_size.value().first;
openglConfig.windowPlacement.h = config.window_size.value().second;
}
if (config.window_position.has_value()) {
openglConfig.windowPlacement.pos = true;
openglConfig.windowPlacement.x = config.window_position.value().first;
openglConfig.windowPlacement.y = config.window_position.value().second;
}
openglConfig.windowPlacement.mon = config.window_monitor;
using megamol::frontend_resources::RuntimeConfig;
openglConfig.windowPlacement.fullScreen = config.window_mode & RuntimeConfig::WindowMode::fullscreen;
openglConfig.windowPlacement.noDec = config.window_mode & RuntimeConfig::WindowMode::nodecoration;
openglConfig.windowPlacement.topMost = config.window_mode & RuntimeConfig::WindowMode::topmost;
openglConfig.windowPlacement.noCursor = config.window_mode & RuntimeConfig::WindowMode::nocursor;
gl_service.setPriority(2);
megamol::frontend::GUI_Service gui_service;
megamol::frontend::GUI_Service::Config guiConfig;
guiConfig.backend = (with_gl) ? (megamol::gui::GUIRenderBackend::OPEN_GL) : (megamol::gui::GUIRenderBackend::CPU);
guiConfig.core_instance = &core;
guiConfig.gui_show = config.gui_show;
guiConfig.gui_scale = config.gui_scale;
// priority must be higher than priority of gl_service (=1)
// service callbacks get called in order of priority of the service.
// postGraphRender() and close() are called in reverse order of priorities.
gui_service.setPriority(23);
megamol::frontend::Screenshot_Service screenshot_service;
megamol::frontend::Screenshot_Service::Config screenshotConfig;
screenshotConfig.show_privacy_note = config.screenshot_show_privacy_note;
screenshot_service.setPriority(30);
megamol::frontend::FrameStatistics_Service framestatistics_service;
megamol::frontend::FrameStatistics_Service::Config framestatisticsConfig;
// needs to execute before gl_service at frame start, after gl service at frame end
framestatistics_service.setPriority(1);
megamol::frontend::Lua_Service_Wrapper lua_service_wrapper;
megamol::frontend::Lua_Service_Wrapper::Config luaConfig;
luaConfig.lua_api_ptr = &lua_api;
luaConfig.host_address = config.lua_host_address;
luaConfig.retry_socket_port = config.lua_host_port_retry;
luaConfig.show_version_notification = config.show_version_note;
lua_service_wrapper.setPriority(0);
megamol::frontend::ProjectLoader_Service projectloader_service;
megamol::frontend::ProjectLoader_Service::Config projectloaderConfig;
projectloader_service.setPriority(1);
megamol::frontend::ImagePresentation_Service imagepresentation_service;
megamol::frontend::ImagePresentation_Service::Config imagepresentationConfig;
imagepresentationConfig.local_framebuffer_resolution = config.local_framebuffer_resolution;
// when there is no GL we should make sure the user defined some initial framebuffer size via CLI
if (!with_gl) {
if (!config.local_framebuffer_resolution.has_value()) {
if (!config.window_size.has_value()) {
log_error("Window and framebuffer size is not set. Abort.");
return 1;
}
imagepresentationConfig.local_framebuffer_resolution = config.window_size;
}
}
imagepresentationConfig.local_viewport_tile =
config.local_viewport_tile.has_value()
? std::make_optional(megamol::frontend::ImagePresentation_Service::Config::Tile{
config.local_viewport_tile.value().global_framebuffer_resolution,
config.local_viewport_tile.value().tile_start_pixel,
config.local_viewport_tile.value().tile_resolution})
: std::nullopt;
imagepresentation_service.setPriority(3);
megamol::frontend::VR_Service vr_service;
vr_service.setPriority(imagepresentation_service.getPriority() - 1);
megamol::frontend::VR_Service::Config vrConfig;
vrConfig.mode = megamol::frontend::VR_Service::Config::Mode(static_cast<int>(config.vr_mode));
const bool with_vr = vrConfig.mode != megamol::frontend::VR_Service::Config::Mode::Off;
megamol::frontend::Command_Service command_service;
// Should be applied after gui service to process only keyboard events not used by gui.
command_service.setPriority(24);
#ifdef PROFILING
megamol::frontend::Profiling_Service profiling_service;
megamol::frontend::Profiling_Service::Config profiling_config;
profiling_config.log_file = config.profiling_output_file;
#endif
#ifdef MM_CUDA_ENABLED
megamol::frontend::CUDA_Service cuda_service;
cuda_service.setPriority(24);
#endif
// clang-format off
// the main loop is organized around services that can 'do something' in different parts of the main loop.
// a service is something that implements the AbstractFrontendService interface from 'megamol\frontend_services\include'.
// a central mechanism that allows services to communicate with each other and with graph modules are _resources_.
// (see FrontendResource in 'megamol\frontend_resources\include').
// services may provide resources to the system and they may request resources they need themselves for functioning.
// think of a resource as a struct (or some type of your choice) that gets wrapped
// by a helper structure and gets a name attached to it. the fronend makes sure (at least
// attempts to) to hand each service the resources it requested, or else fail execution of megamol with an error message.
// resource assignment is done by the name of the resource, so this is a very loose interface based on trust.
// type safety of resources is ensured in the sense that extracting the wrong type from a FrontendResource will
// lead to an unhandled bad type cast exception, leading to the shutdown of megamol.
// clang-format on
bool run_megamol = true;
megamol::frontend::FrontendServiceCollection services;
if (with_gl) {
services.add(gl_service, &openglConfig);
}
services.add(gui_service, &guiConfig);
services.add(lua_service_wrapper, &luaConfig);
services.add(screenshot_service, &screenshotConfig);
services.add(framestatistics_service, &framestatisticsConfig);
services.add(projectloader_service, &projectloaderConfig);
services.add(imagepresentation_service, &imagepresentationConfig);
services.add(command_service, nullptr);
if (with_vr) {
services.add(vr_service, &vrConfig);
}
#ifdef PROFILING
services.add(profiling_service, &profiling_config);
#endif
#ifdef MM_CUDA_ENABLED
services.add(cuda_service, nullptr);
#endif
megamol::frontend::Remote_Service remote_service;
megamol::frontend::Remote_Service::Config remoteConfig;
if (auto remote_session_role = handle_remote_session_config(config, remoteConfig); !remote_session_role.empty()) {
openglConfig.windowTitlePrefix += remote_session_role;
remote_service.setPriority(
lua_service_wrapper.getPriority() - 1); // remote does stuff before everything else, even before lua
services.add(remote_service, &remoteConfig);
}
const bool init_ok = services.init(); // runs init(config_ptr) on all services with provided config sructs
if (!init_ok) {
log_error("Some frontend service could not be initialized successfully. Abort.");
services.close();
return 1;
}
const megamol::core::factories::ModuleDescriptionManager& moduleProvider = core.GetModuleDescriptionManager();
const megamol::core::factories::CallDescriptionManager& callProvider = core.GetCallDescriptionManager();
megamol::core::MegaMolGraph graph(core, moduleProvider, callProvider);
// Graph and Config are also a resources that may be accessed by services
services.getProvidedResources().push_back({"MegaMolGraph", graph});
services.getProvidedResources().push_back({"RuntimeConfig", config});
services.getProvidedResources().push_back({"GlobalValueStore", global_value_store});
// proof of concept: a resource that returns a list of names of available resources
// used by Lua Wrapper and LuaAPI to return list of available resources via remoteconsole
const std::function<std::vector<std::string>()> resource_lister = [&]() -> std::vector<std::string> {
std::vector<std::string> resources;
for (auto& resource : services.getProvidedResources()) {
resources.push_back(resource.getIdentifier());
}
resources.push_back("FrontendResourcesList");
return resources;
};
services.getProvidedResources().push_back({"FrontendResourcesList", resource_lister});
uint32_t frameID = 0;
const auto render_next_frame = [&]() -> bool {
// set global Frame Counter
core.SetFrameID(frameID++);
// services: receive inputs (GLFW poll events [keyboard, mouse, window], network, lua)
services.updateProvidedResources();
// aka simulation step
// services: digest new inputs via FrontendResources (GUI digest user inputs, lua digest inputs, network ?)
// e.g. graph updates, module and call creation via lua and GUI happen here
services.digestChangedRequestedResources();
// services tell us wheter we should shut down megamol
if (services.shouldShutdown())
return false;
// actual rendering
{
services.preGraphRender(); // e.g. start frame timer, clear render buffers
imagepresentation_service
.RenderNextFrame(); // executes graph views, those digest input events like keyboard/mouse, then render
services.postGraphRender(); // render GUI, glfw swap buffers, stop frame timer
}
imagepresentation_service
.PresentRenderedImages(); // draws rendering results to GLFW window, writes images to disk, sends images via network...
services.resetProvidedResources(); // clear buffers holding glfw keyboard+mouse input
return true;
};
// lua can issue rendering of frames, we provide a resource for this
const std::function<bool()> render_next_frame_func = [&]() -> bool { return render_next_frame(); };
services.getProvidedResources().push_back({"RenderNextFrame", render_next_frame_func});
// image presentation service needs to assign frontend resources to entry points
auto& frontend_resources = services.getProvidedResources();
services.getProvidedResources().push_back({"FrontendResources", frontend_resources});
// distribute registered resources among registered services.
const bool resources_ok = services.assignRequestedResources();
// for each service we call their resource callbacks here:
// std::vector<FrontendResource>& getProvidedResources()
// std::vector<std::string> getRequestedResourceNames()
// void setRequestedResources(std::vector<FrontendResource>& resources)
if (!resources_ok) {
log_error("Frontend could not assign requested service resources. Abort.");
run_megamol = false;
}
bool graph_resources_ok = graph.AddFrontendResources(frontend_resources);
if (!graph_resources_ok) {
log_error("Graph did not get resources he needs from frontend. Abort.");
run_megamol = false;
}
// load project files via lua
if (run_megamol && graph_resources_ok)
for (auto& file : config.project_files) {
if (!projectloader_service.load_file(file)) {
log_error("Project file \"" + file + "\" did not execute correctly");
run_megamol = false;
// if interactive, continue to run MegaMol
if (config.interactive) {
log_warning("Interactive mode: start MegaMol anyway");
run_megamol = true;
}
}
}
// execute Lua commands passed via CLI
if (graph_resources_ok)
if (!config.cli_execute_lua_commands.empty()) {
std::string lua_result;
bool cli_lua_ok = lua_api.RunString(config.cli_execute_lua_commands, lua_result);
if (!cli_lua_ok) {
run_megamol = false;
log_error("Error in CLI Lua command: " + lua_result);
}
}
while (run_megamol) {
run_megamol = render_next_frame();
}
graph.Clear();
// close glfw context, network connections, other system resources
services.close();
return 0;
}
|
UniStuttgart-VISUS/megamol
|
frontend/main/src/main.cpp
|
C++
|
bsd-3-clause
| 15,857 |
\documentclass[11pt,a4paper,roman]{moderncv} % Font sizes: 10, 11, or 12; paper sizes: a4paper, letterpaper, a5paper, legalpaper, executivepaper or landscape; font families: sans or roman
\moderncvstyle{casual} % CV theme - options include: 'casual' (default), 'classic', 'oldstyle' and 'banking'
\moderncvcolor{blue} % CV color - options include: 'blue' (default), 'orange', 'green', 'red', 'purple', 'grey' and 'black'
\usepackage{color}
\usepackage{lipsum} % Used for inserting dummy 'Lorem ipsum' text into the template
\usepackage[scale=0.75]{geometry} % Reduce document margins
%\setlength{\hintscolumnwidth}{3cm} % Uncomment to change the width of the dates column
%\setlength{\makecvtitlenamewidth}{10cm} % For the 'classic' style, uncomment to adjust the width of the space allocated to your name
%----------------------------------------------------------------------------------------
% NAME AND CONTACT INFORMATION SECTION
%----------------------------------------------------------------------------------------
\firstname{Alankar} % Your first name
\familyname{Kotwal} % Your last name
% All information in this block is optional, comment out any lines you don't need
\title{Detailed Resume}
\email{[email protected]}
\homepage{alankarkotwal.github.io}{alankarkotwal.github.io}
\mobile{+91-9969678123}
\extrainfo{\url{www.github.com/alankarkotwal}}
\photo[70pt][0.4pt]{pic.jpg}
\begin{document}
\makecvtitle
\section{Education}
\cventry{2012--Present}{Dual Degree, B. Tech and M.Tech in Electrical Engineering}{\newline Indian Institute of Technology}{Bombay}{\textit{CPI -- 8.9/10}}{Specialization: Communication and Signal Processing, Minor Degree: Computer Sciences and Engineering}
\cventry{2010--2012}{Intermediate Examination}{\newline Ratanbai Walbai Junior College of Science}{Mumbai}{\textit{Percentage -- 93.83}}{}
\cventry{2001--2010}{Matriculation}{\newline SVPT's Saraswati Vidyalaya}{Thane}{\textit{Percentage -- 95.27}}{}
\section{Achievements}
\cventry{2012}{\textbf{Gold Medal, International Olympiad on Astronomy and Astrophysics}}{\newline Brazil} {International Rank 4, Special Prize for Best Data Analysis}{}{}
\cventry{2011}{\textbf{Bronze Medal, International Earth Sciences Olympiad}}{\newline Italy} {Special Prize for Best Performance in Hydrosphere section}{}{}
\cventry{2012}{All India Rank 105}{IIT-JEE}{\newline among around 5,90,000 participants for entrance to the IITs}{}{}
\cventry{2009--2012}{Olympiad Orientation-cum-Selection Camps}{}{\newline Selected for the following camps, among the top 30 students in India (Astronomy: 2012 \& 2010, Earth Sciences: 2011, Junior Sciences: 2010 \& 2009)}{}{}
\cventry{2010}{Kishore Vaigyanik Protsahan Yojana Scholarship}{}{\newline Awarded by the Government of India to students interested in research}{}{}
\cventry{2008}{National Talent Search Examination Scholarship}{}{\newline Awarded by the Government of India to students interested in research}{}{}
\cventry{2011--2012}{Infosys Award for Olympiad Medallists}{}{}{}{}
\cventry{2013}{Inter-IIT Messier Marathon}{}{\newline Secured IIT Bombay the second position by putting on board 72 messier objects including the entire Virgo cluster of galaxies}{}{}
\cventry{2013}{Other competitions}{}{\newline Won the Innovation Cell recruitment contest for freshmen and the Astronomy Quiz conducted by the Astronomy Club, IITB in 2012 and BITS Goa in 2013}{}{}
%\newpage
\section{Experience: Astronomy and Astrophysics}
\cventry{2014}{Google Summer of Code}{\newline A New Pixel-Level Method for Determination of Photometric Redshifts}{\newline Prof. R. J. Brunner and M. C. Kind, Laboratory for Cosmological Data Mining}{University of Illinois at Urbana-Champaign}{
\begin{itemize}
\item{Developed the software package image-photo-z implementing this new method}
\item{Worked with SDSS photometry data and extracted pixel-level information for training machine learning algorithms: k-nearest neighbour algorithm and trees for photo-z}
\item{Worked on parallel programming and performance enhancement for this method}
\item{Validated the approach and got consistent predictions for redshifts in the testing set}
\end{itemize}
}
\cventry{2013}{National Initiative for Undergraduate Studies -- Astronomy}{\newline An X-Ray Study of Black Hole Candidate X Norma X-1}{\newline Prof. Manojendu Choudhury}{Center for Basic Sciences, University of Mumbai}{
\begin{itemize}
\item{Analysed statistically timing information from RXTE to detect quasi-periodic oscillations and find their possible relation to accretion disk thickening and synchrotron jets}
\item{Fitted the spectra obtained with a thermal and non-thermal power-law distribution to obtain essential system parameters and observed unusual oscillations in the inner radius}
\item{Working on finding a possible cause for these oscillations}
\end{itemize}
}
\cventry{2012}{National Initiative for Undergraduate Studies -- Astronomy}{\newline Estimation of Photometric Redshifts Using Machine Learning Techniques}{\newline Prof. Ninan Sajeeth Philip}{Inter University Center for Astronomy and Astrophysics, Pune}{
\begin{itemize}
\item{Estimated redshift data from colour index information obtained from SDSS data artificial neural networks}
\item{Worked on generation of training data from available data by redshifting spectra}
\end{itemize}
}
\cventry{2013-2014}{Resource Person}{\newline Indian National Astronomy Olympiad Programme}{}{\newline Homi Bhabha Center for Science Education}{
\begin{itemize}
\item{Selected twice as a Student Facilitator and a Resource Person for the Indian Astronomy Olympiad OCSC (Orientation-Cum-Selection Camp) for mentoring camp students, handling academic and organizational arrangements and aiding in evaluations}
\item{Involved in the selection and rigorous training of the 3 member Indian National team which won 3 Gold Medals at the International Astronomy Olympiad 2013 held in Lithuania}
\item{Involved in generating problems for the Indian National Astronomy Olympiad which is conducted as a part of selection of students for the camp}
\end{itemize}
}
\cventry{2014}{Gravitational Lens Identification}{}{\newline See the Computer Sciences section below}{}{}
\newpage
\section{Experience: Electrical Engineering and Computer Sciences}
\cventry{2014}{Google Summer of Code}{}{\newline See the Astronomy and Astrophysics section above}{}{}
\cventry{2013--Present}{Computer Vision, The IITB Mars Rover Team}{\newline A Student Initiative at IITB}{}{}{
\begin{itemize}
\item{Work in 2014:}
\begin{itemize}
\item{Exploring illumination-corrected stereo vision and shape from motion for autonomous navigation}
\item{Design and testing of a new algorithm for navigation and obstacle avoidance}
\item{Implementation of the rover software stack on ROS}
\end{itemize}
\item{Work in 2013:}
\begin{itemize}
\item{Programming manual controls and safety on-board}
\item{Hardware interfacing for peripherals on-board and debugging}
\end{itemize}
\end{itemize}
}
\cventry{2014}{The Arkaroola Mars Robot Challenge}{\newline A joint venture of the Mars Society Australia and Saber Astronautics}{}{}{
\begin{itemize}
\item{Tested the Mars Rover prototype developed by the IITB Rover Team in the harsh conditions of the Australian outback}
\item{Participated in a series of exercises in Mars operations research conducted by Saber Astronautics which included simulated extra-vehicular activities in simulated space-suits}
\item{Explored Arkaroola geology and studied its similarities to Martian geology}
\end{itemize}
\textbf{Featured in Clarke et al., "Field Robotics, Astrobiology and Mars Analogue Research on the Arkaroola Mars Robot Challenge Expedition", Australian Space Research Conference 2015}
}
\cventry{2014}{Gravitational Lens Identification Using Image Processing Techniques}{\newline A PCA-based Method for Identifying Lenses in Databases}{\newline Prof. A. Rajwade and S. Awate, Department of Computer Sciences}{\newline Indian Institute of Technology Bombay}{
\begin{itemize}
\item{Improvised on source-subtraction algorithms for lens subtraction}
\item{Implemented the algorithm in Matlab and got a good identification rate lenses}
\end{itemize}
}
\cventry{2014}{Microprocessor Design}{\newline Design, Implementation and Validation of Three Processors in Verilog}{\newline Prof. V. Singh, Department of Electrical Engineering}{\newline Indian Institute of Technology Bombay}{
\begin{itemize}
\item{Designed and simulated a pipelined processor with the Little Computer Architecture}
\item{Designed, implemented and tested a multi-cycle RISC processor using the LC-3b ISA}
\item{Designed a CISC processor with reduced 8085 architecture}
\end{itemize}
}
\cventry{2014}{Temperature Controller on a CPLD}{\newline A Peltier-Plate Based Fast-Response P-Controller for Temperature Control}{\newline Prof. J. Mukherjee, Department of Electrical Engineering}{\newline Indian Institute of Technology Bombay}{}
\newpage
\section{Research Interests}
\cventry{}{Astronomy and Astrophysics}{}{}{}{
\begin{itemize}
\item{Cosmology and the large-scale structure of the universe}
\item{Stellar populations, structure and evolution}
\item{Applications of computer vision to astronomy}
\item{Data mining and its applications for handling astronomical data}
\end{itemize}
}
\cventry{}{Electrical Engineering and Computer Sciences}{}{}{}{
\begin{itemize}
\item{Using computational Fourier Optics for imaging resolution improvement}
\item{3D shape reconstruction using computer vision techniques}
\item{Robot navigation using stereo vision and structure from motion}
\item{Efficient algorithms for robot navigation using geometry of visual field}
\item{Processor architecture}
\item{Hardware description and simulation}
\end{itemize}
}
\cventry{}{Things I'd like to do}{}{}{}{
\begin{itemize}
\item{Logic minimization}
\item{Operations research in relation to Mars missions}
\end{itemize}
}
\section{Relevant Skills}
\cventry{}{Languages}{}{}{}{C/C++, Python, Shell Scripting, Java, Matlab, SQL, HTML/CSS, PHP, \LaTeX}
\cventry{}{Science Software}{}{}{}{Python packages: NumPy, SciPy and Matplotlib, GNUPlot, Scikit-learn, Astropy, SExtractor, SDSS tools}
\cventry{}{Special Software}{}{}{}{ROS/Gazebo, OpenCV, The Point Cloud Library, SPICE Circuit Simulation, EAGLE PCB Design, SolidWorks CAD, AutoCAD, LabView, Django}
\cventry{}{Hardware}{}{}{}{Microprocessor Architectures: 8051, 8085, AVR and PIC, CPLDs and FPGAs, Embedded Platforms: Arduino, RaspberryPi, Beaglebone, and so on, standard digital logic families}
\section{Relevant Courses Undertaken}
\cventry{}{Physics and Mathematics}{}{}{}{The General Theory of Relativity, Quantum Mechanics I*, Statistical Physics*, Electromagnetic Waves, Electricity and Magnetism, Classical Mechanics, Differential Equations, Linear Algebra, Complex Analysis, Calculus}
\cventry{}{Computer Sciences}{}{}{}{Computer Vision, Algorithms for Medical Image Processing, Machine Learning, Convex Optimisation, Digital Image Processing, Design and Analysis of Algorithms, Data Structures and Algorithms, Discrete Mathematics}
\cventry{}{Electrical Engineering}{}{}{}{Digital Signal Processing, Controls, Probability and Random Processes, Digital Communication, Communication Systems, Microprocessors, Signals and Systems, Digital and Analog Systems, Electrical Machines and Power Electronics, Power Systems, Electronic Devices and Circuits, Network Theory}
\end{document}
|
aigeano/aigeano.github.io
|
resume/resume-astro.tex
|
TeX
|
bsd-3-clause
| 11,473 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Program.h: Defines the gl::Program class. Implements GL program objects
// and related functionality. [OpenGL ES 2.0.24] section 2.10.3 page 28.
#ifndef LIBGLESV2_PROGRAM_BINARY_H_
#define LIBGLESV2_PROGRAM_BINARY_H_
#define GL_APICALL
#include <gles2/gl2.h>
#include <gles2/gl2ext.h>
#include <d3dx9.h>
#include <d3dcompiler.h>
#include <string>
#include <vector>
#include "libGLESv2/Shader.h"
#include "libGLESv2/Context.h"
namespace gl
{
class FragmentShader;
class VertexShader;
// Helper struct representing a single shader uniform
struct Uniform
{
Uniform(GLenum type, const std::string &_name, unsigned int arraySize);
~Uniform();
bool isArray();
const GLenum type;
const std::string _name; // Decorated name
const std::string name; // Undecorated name
const unsigned int arraySize;
unsigned char *data;
bool dirty;
struct RegisterInfo
{
RegisterInfo()
{
float4Index = -1;
samplerIndex = -1;
boolIndex = -1;
registerCount = 0;
}
void set(const D3DXCONSTANT_DESC &constantDescription)
{
switch(constantDescription.RegisterSet)
{
case D3DXRS_BOOL: boolIndex = constantDescription.RegisterIndex; break;
case D3DXRS_FLOAT4: float4Index = constantDescription.RegisterIndex; break;
case D3DXRS_SAMPLER: samplerIndex = constantDescription.RegisterIndex; break;
default: UNREACHABLE();
}
ASSERT(registerCount == 0 || registerCount == (int)constantDescription.RegisterCount);
registerCount = constantDescription.RegisterCount;
}
int float4Index;
int samplerIndex;
int boolIndex;
int registerCount;
};
RegisterInfo ps;
RegisterInfo vs;
};
// Struct used for correlating uniforms/elements of uniform arrays to handles
struct UniformLocation
{
UniformLocation()
{
}
UniformLocation(const std::string &_name, unsigned int element, unsigned int index);
std::string name;
unsigned int element;
unsigned int index;
};
// This is the result of linking a program. It is the state that would be passed to ProgramBinary.
class ProgramBinary : public RefCountObject
{
public:
ProgramBinary();
~ProgramBinary();
IDirect3DPixelShader9 *getPixelShader();
IDirect3DVertexShader9 *getVertexShader();
GLuint getAttributeLocation(const char *name);
int getSemanticIndex(int attributeIndex);
GLint getSamplerMapping(SamplerType type, unsigned int samplerIndex);
TextureType getSamplerTextureType(SamplerType type, unsigned int samplerIndex);
GLint getUsedSamplerRange(SamplerType type);
GLint getUniformLocation(std::string name);
bool setUniform1fv(GLint location, GLsizei count, const GLfloat *v);
bool setUniform2fv(GLint location, GLsizei count, const GLfloat *v);
bool setUniform3fv(GLint location, GLsizei count, const GLfloat *v);
bool setUniform4fv(GLint location, GLsizei count, const GLfloat *v);
bool setUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *value);
bool setUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *value);
bool setUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *value);
bool setUniform1iv(GLint location, GLsizei count, const GLint *v);
bool setUniform2iv(GLint location, GLsizei count, const GLint *v);
bool setUniform3iv(GLint location, GLsizei count, const GLint *v);
bool setUniform4iv(GLint location, GLsizei count, const GLint *v);
bool getUniformfv(GLint location, GLsizei *bufSize, GLfloat *params);
bool getUniformiv(GLint location, GLsizei *bufSize, GLint *params);
GLint getDxDepthRangeLocation() const;
GLint getDxDepthLocation() const;
GLint getDxCoordLocation() const;
GLint getDxHalfPixelSizeLocation() const;
GLint getDxFrontCCWLocation() const;
GLint getDxPointsOrLinesLocation() const;
void dirtyAllUniforms();
void applyUniforms();
bool load(InfoLog &infoLog, const void *binary, GLsizei length);
bool save(void* binary, GLsizei bufSize, GLsizei *length);
GLint getLength();
bool link(InfoLog &infoLog, const AttributeBindings &attributeBindings, FragmentShader *fragmentShader, VertexShader *vertexShader);
void getAttachedShaders(GLsizei maxCount, GLsizei *count, GLuint *shaders);
void getActiveAttribute(GLuint index, GLsizei bufsize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
GLint getActiveAttributeCount();
GLint getActiveAttributeMaxLength();
void getActiveUniform(GLuint index, GLsizei bufsize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
GLint getActiveUniformCount();
GLint getActiveUniformMaxLength();
void validate(InfoLog &infoLog);
bool validateSamplers(InfoLog *infoLog);
bool isValidated() const;
unsigned int getSerial() const;
static std::string decorateAttribute(const std::string &name); // Prepend an underscore
static std::string undecorateUniform(const std::string &_name); // Remove leading underscore
private:
DISALLOW_COPY_AND_ASSIGN(ProgramBinary);
ID3D10Blob *compileToBinary(InfoLog &infoLog, const char *hlsl, const char *profile, ID3DXConstantTable **constantTable);
int packVaryings(InfoLog &infoLog, const Varying *packing[][4], FragmentShader *fragmentShader);
bool linkVaryings(InfoLog &infoLog, std::string& pixelHLSL, std::string& vertexHLSL, FragmentShader *fragmentShader, VertexShader *vertexShader);
bool linkAttributes(InfoLog &infoLog, const AttributeBindings &attributeBindings, FragmentShader *fragmentShader, VertexShader *vertexShader);
bool linkUniforms(InfoLog &infoLog, GLenum shader, ID3DXConstantTable *constantTable);
bool defineUniform(InfoLog &infoLog, GLenum shader, const D3DXHANDLE &constantHandle, const D3DXCONSTANT_DESC &constantDescription, std::string name = "");
bool defineUniform(GLenum shader, const D3DXCONSTANT_DESC &constantDescription, const std::string &name);
Uniform *createUniform(const D3DXCONSTANT_DESC &constantDescription, const std::string &name);
bool applyUniformnfv(Uniform *targetUniform, const GLfloat *v);
bool applyUniform1iv(Uniform *targetUniform, GLsizei count, const GLint *v);
bool applyUniform2iv(Uniform *targetUniform, GLsizei count, const GLint *v);
bool applyUniform3iv(Uniform *targetUniform, GLsizei count, const GLint *v);
bool applyUniform4iv(Uniform *targetUniform, GLsizei count, const GLint *v);
void applyUniformniv(Uniform *targetUniform, GLsizei count, const D3DXVECTOR4 *vector);
void applyUniformnbv(Uniform *targetUniform, GLsizei count, int width, const GLboolean *v);
IDirect3DDevice9 *mDevice;
IDirect3DPixelShader9 *mPixelExecutable;
IDirect3DVertexShader9 *mVertexExecutable;
// These are only used during linking.
ID3DXConstantTable *mConstantTablePS;
ID3DXConstantTable *mConstantTableVS;
Attribute mLinkedAttribute[MAX_VERTEX_ATTRIBS];
int mSemanticIndex[MAX_VERTEX_ATTRIBS];
struct Sampler
{
Sampler();
bool active;
GLint logicalTextureUnit;
TextureType textureType;
};
Sampler mSamplersPS[MAX_TEXTURE_IMAGE_UNITS];
Sampler mSamplersVS[MAX_VERTEX_TEXTURE_IMAGE_UNITS_VTF];
GLuint mUsedVertexSamplerRange;
GLuint mUsedPixelSamplerRange;
typedef std::vector<Uniform*> UniformArray;
UniformArray mUniforms;
typedef std::vector<UniformLocation> UniformIndex;
UniformIndex mUniformIndex;
GLint mDxDepthRangeLocation;
GLint mDxDepthLocation;
GLint mDxCoordLocation;
GLint mDxHalfPixelSizeLocation;
GLint mDxFrontCCWLocation;
GLint mDxPointsOrLinesLocation;
bool mValidated;
const unsigned int mSerial;
static unsigned int issueSerial();
static unsigned int mCurrentSerial;
};
}
#endif // LIBGLESV2_PROGRAM_BINARY_H_
|
adobe/angle.js
|
src/libGLESv2/ProgramBinary.h
|
C
|
bsd-3-clause
| 8,242 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Wild Dragon Energy Drink </title>
<link rel="shortcut icon" href="img/favicon.ico" type="image/x-icon" />
<link rel="apple-touch-icon" href="img/apple-touch-icon.png">
<meta name="robots" content="all, index, follow" />
<meta name="description" content="Wild Dragon, Wild Dragon Energy Drink, Wild, Dragon, Energy Drink, Energy Drink Vienna, Wild Dragon Tropic, Wild Dragon Vienna"/>
<meta name="keywords" content="Wild Dragon, Wild Dragon Energy Drink, Wild, Dragon, Energy Drink, Energy Drink Vienna, Wild Dragon Tropic, Wild Dragon Vienna" />
<meta name="keyword" content="Wild Dragon, Wild Dragon Energy Drink, Wild, Dragon, Energy Drink, Energy Drink Vienna, Wild Dragon Tropic, Wild Dragon Vienna">
<meta name="distribution" content="GLOBAL">
<meta name="revisit-after" CONTENT="7">
<meta name="page-type" CONTENT="Wild Dragon Energy Drink from Vienna / Austria">
<meta name="page-topic" CONTENT="Wild Dragon Energy Drink from Vienna / Austria">
<meta name="author" content="Wild Dragon GmbH" />
<meta name="organization" content="Wild Dragon GmbH" />
<meta name="copyright" content="Wild Dragon GmbH" />
<meta name="public" content="yes" />
<meta name="ABSTRACT" content="Wild Dragon Energy Drink from Vienna / Austria" />
<meta name="searchTitle" content="Wild Dragon Energy Drink from Vienna / Austria"/>
<meta name="searchPreview" content="Wild Dragon Energy Drink from Vienna / Austria"/>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800%7CShadows+Into+Light" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Love+Ya+Like+A+Sister" rel="stylesheet">
<link rel="stylesheet" href="vendor/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="vendor/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="vendor/animate/animate.min.css">
<link rel="stylesheet" href="vendor/simple-line-icons/css/simple-line-icons.min.css">
<link rel="stylesheet" href="vendor/owl.carousel/assets/owl.carousel.min.css">
<link rel="stylesheet" href="vendor/owl.carousel/assets/owl.theme.default.min.css">
<link rel="stylesheet" href="vendor/magnific-popup/magnific-popup.min.css">
<link rel="stylesheet" href="css/theme.css">
<link rel="stylesheet" href="css/theme-elements.css">
<link rel="stylesheet" href="vendor/rs-plugin/css/settings.css">
<link rel="stylesheet" href="vendor/rs-plugin/css/layers.css">
<link rel="stylesheet" href="vendor/rs-plugin/css/navigation.css">
<link rel="stylesheet" href="css/skin.css">
<link rel="stylesheet" href="css/custom.css">
<script src="vendor/modernizr/modernizr.min.js"></script>
</head>
<body>
<div class="body">
<header id="header" class="header-narrow header-semi-transparent header-transparent-sticky-deactive header-transparent-bottom-border" data-plugin-options="{'stickyEnabled': true, 'stickyEnableOnBoxed': true, 'stickyEnableOnMobile': true, 'stickyStartAt': 1, 'stickySetTop': '1'}">
<div class="header-body">
<div class="header-container container">
<div class="header-row">
<div class="header-column">
<div class="header-logo">
<a href="./">
<img alt="Wild Dragon Energy Drink" width="242" src="img/wild-dragon-logo.png">
</a>
</div>
</div>
<div class="header-column">
<div class="header-row">
<div class="header-nav header-nav-dark-dropdown">
<button class="btn header-btn-collapse-nav" data-toggle="collapse" data-target=".header-nav-main">
<i class="fa fa-bars"></i>
</button>
<div class="header-nav-main header-nav-main-square header-nav-main-effect-2 header-nav-main-sub-effect-1 collapse">
<nav>
<ul class="nav nav-pills" id="mainNav">
<li class="dropdown active">
<a class="dropdown-toggle" href="./">
Home
</a>
<ul class="dropdown-menu">
<li>
<a href="video">
Video
</a>
</li>
<li>
<a href="artist">
Artist
</a>
</li>
</ul>
</li>
<li class="dropdown">
<a class="dropdown-toggle" href="product">
Product
</a>
<ul class="dropdown-menu">
<li>
<a href="product">
Product
</a>
</li>
<li>
<a href="ingredients">
Ingredients
</a>
</li>
<li>
<a href="effects">
Effects
</a>
</li>
</ul>
</li>
<li class="dropdown">
<a class="dropdown-toggle" href="media.php">
Media
</a>
<ul class="dropdown-menu">
<li>
<a href="media.php#wallpapers">
Wallpapers
</a>
</li>
<li>
<a href="media.php#videos">
Videos
</a>
</li>
<li>
<a href="media.php#posters">
Posters
</a>
</li>
<li>
<a href="media.php#logos">
Logos
</a>
</li>
<li>
<a href="media.php#cans">
Cans
</a>
</li>
</ul>
</li>
<li class="">
<a class="" href="wild-territories">
Wild Territories
</a>
</li>
<li class="">
<a class="" href="awards">
Awards
</a>
</li>
<li class="">
<a class="" href="contact">
Contact
</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</header>
<div role="main" class="main">
<div class="slider-container rev_slider_wrapper" style="height: 760px;">
<div id="revolutionSlider" class="slider rev_slider" data-plugin-revolution-slider data-plugin-options="{'delay': 9000, 'gridwidth': 800, 'gridheight': 760}">
<ul>
<!-- <li data-transition="fade">
<div class="tp-caption tp-resizeme tp-videolayer"
data-frames='[{"delay": 0, "speed": 300, "from": "opacity: 0", "to": "opacity: 1"},
{"delay": "wait", "speed": 300, "to": "opacity: 0"}]'
data-type="video"
data-ytid="fd1cqIHXISY"
data-videowidth="100%"
data-videoheight="500%"
data-autoplay="off"
data-videocontrols="controls"
data-nextslideatend="true"
data-forcerewind="on"
data-videoloop="loopandnoslidestop"
data-videoattributes="version=3&enablejsapi=1&html5=1&hd=1&wmode=opaque&showinfo=0&rel=0&origin=http://www.wilddragon.at"
data-x="center"
data-y="center"
data-hoffset="0"
data-voffset="0"
data-basealign="slide">
<div>
</li>-->
<li data-transition="fade">
<img src="img/bg/1.jpg"
alt=""
data-bgposition="center center"
data-bgfit="cover"
data-bgrepeat="no-repeat"
class="rev-slidebg">
<div class="tp-caption top-label banfont"
data-x="left" data-hoffset="0"
data-y="center" data-voffset="-95"
data-start="500"
style="z-index: 5; font-size:44px;"
data-transform_in="y:[-300%];opacity:0;s:500;">Life is like music,</div>
<div class="tp-caption top-label banfont"
data-x="left" data-hoffset="110"
data-y="center" data-voffset="-45"
data-start="1500"
data-whitespace="nowrap"
data-transform_in="y:[100%];s:500;"
data-transform_out="opacity:0;s:500;"
style="z-index: 5; font-size:40px;">it must be composed by ear,</div>
<div class="tp-caption bottom-label banfont"
data-x="center" data-hoffset="0"
data-y="center" data-voffset="5"
data-start="2000"
style="z-index: 5; font-size:43px"
data-transform_in="y:[100%];opacity:0;s:500;">feeling and instinct, not by rule!</div>
</li>
<li data-transition="fade">
<img src="img/bg/2.jpg"
alt=""
data-bgposition="center center"
data-bgfit="cover"
data-bgrepeat="no-repeat"
class="rev-slidebg">
<div class="tp-caption top-label banfont"
data-x="left"
data-y="center" data-voffset="-45"
data-start="500"
style="z-index: 5; font-size:44px;"
data-transform_in="y:[100%];s:500;"
data-transform_out="opacity:0;s:500;">No chaos,</div>
<div class="tp-caption top-label banfont"
data-x="left" data-hoffset="110"
data-y="center" data-voffset="5"
data-start="1000"
style="z-index: 5; font-size:44px;"
data-transform_in="y:[100%];s:500;"
data-transform_out="opacity:0;s:500;">no creation</div>
</li>
<li data-transition="fade">
<img src="img/bg/3.jpg"
alt=""
data-bgposition="center center"
data-bgfit="cover"
data-bgrepeat="no-repeat"
class="rev-slidebg">
<div class="tp-caption top-label banfont"
data-x="left" data-hoffset="10"
data-y="center" data-voffset="-95"
data-start="500"
style="z-index: 5; font-size:44px; font-weight:bold;"
data-transform_in="y:[-300%];opacity:0;s:500;">Wer sagt:</div>
<div class="tp-caption top-label banfont"
data-x="left" data-hoffset="50"
data-y="center" data-voffset="-45"
data-start="1500"
data-whitespace="nowrap"
data-transform_in="y:[100%];s:500;"
data-transform_out="opacity:0;s:500;"
style="z-index: 5; font-size:34px;">hier herrscht Freiheit,</div>
<div class="tp-caption bottom-label banfont"
data-x="left" data-hoffset="18"
data-y="center" data-voffset="5"
data-start="2000"
style="z-index: 5; font-size:45px; font-weight:bold"
data-transform_in="y:[100%];opacity:0;s:500;">der lügt,</div>
<div class="tp-caption bottom-label banfont"
data-x="left" data-hoffset="70"
data-y="center" data-voffset="50"
data-start="2500"
style="z-index: 5; font-size:34px"
data-transform_in="y:[100%];opacity:0;s:500;">denn Freiheit herrscht nicht.</div>
</li>
<li data-transition="fade">
<img src="img/bg/4.jpg"
alt=""
data-bgposition="center center"
data-bgfit="cover"
data-bgrepeat="no-repeat"
class="rev-slidebg">
<div class="tp-caption top-label banfont"
data-x="left" data-hoffset="10"
data-y="center" data-voffset="-95"
data-start="500"
style="z-index: 5; font-size:44px; font-weight:bold;"
data-transform_in="y:[-300%];opacity:0;s:500;">Wild!</div>
<div class="tp-caption top-label banfont"
data-x="left" data-hoffset="50"
data-y="center" data-voffset="-45"
data-start="1500"
data-whitespace="nowrap"
data-transform_in="y:[100%];s:500;"
data-transform_out="opacity:0;s:500;"
style="z-index: 5; font-size:47px;">Frei!</div>
<div class="tp-caption bottom-label banfont"
data-x="left" data-hoffset="18"
data-y="center" data-voffset="5"
data-start="2000"
style="z-index: 5; font-size:45px; font-weight:bold"
data-transform_in="y:[100%];opacity:0;s:500;">Unzähmbar! </div>
</li>
<li data-transition="fade">
<img src="img/bg/5.jpg"
alt=""
data-bgposition="center center"
data-bgfit="cover"
data-bgrepeat="no-repeat"
class="rev-slidebg">
<div class="tp-caption top-label banfont"
data-x="left" data-hoffset="10"
data-y="center" data-voffset="-95"
data-start="500"
style="z-index: 5; font-size:44px; font-weight:bold;"
data-transform_in="y:[-300%];opacity:0;s:500;">To love oneself</div>
<div class="tp-caption top-label banfont"
data-x="left" data-hoffset="50"
data-y="center" data-voffset="-45"
data-start="1500"
data-whitespace="nowrap"
data-transform_in="y:[100%];s:500;"
data-transform_out="opacity:0;s:500;"
style="z-index: 5; font-size:47px;">is the beginning of a</div>
<div class="tp-caption bottom-label banfont"
data-x="left" data-hoffset="18"
data-y="center" data-voffset="5"
data-start="2000"
style="z-index: 5; font-size:45px; font-weight:bold"
data-transform_in="y:[100%];opacity:0;s:500;">lifelong romance </div>
</li>
<li data-transition="fade">
<img src="img/bg/6.jpg"
alt=""
data-bgposition="center center"
data-bgfit="cover"
data-bgrepeat="no-repeat"
class="rev-slidebg">
<div class="tp-caption top-label banfont"
data-x="left" data-hoffset="10"
data-y="center" data-voffset="-95"
data-start="500"
style="z-index: 5; font-size:44px; font-weight:bold;"
data-transform_in="y:[-300%];opacity:0;s:500;">Patterning your life</div>
<div class="tp-caption top-label banfont"
data-x="left" data-hoffset="50"
data-y="center" data-voffset="-45"
data-start="1500"
data-whitespace="nowrap"
data-transform_in="y:[100%];s:500;"
data-transform_out="opacity:0;s:500;"
style="z-index: 5; font-size:47px;">around other's opinions</div>
<div class="tp-caption bottom-label banfont"
data-x="left" data-hoffset="18"
data-y="center" data-voffset="5"
data-start="2000"
style="z-index: 5; font-size:45px; font-weight:bold"
data-transform_in="y:[100%];opacity:0;s:500;">is nothing more than slavery</div>
</li>
<li data-transition="fade">
<img src="img/bg/7.jpg"
alt=""
data-bgposition="center center"
data-bgfit="cover"
data-bgrepeat="no-repeat"
class="rev-slidebg">
<div class="tp-caption top-label banfont"
data-x="left" data-hoffset="10"
data-y="center" data-voffset="-95"
data-start="500"
style="z-index: 5; font-size:44px; font-weight:bold;"
data-transform_in="y:[-300%];opacity:0;s:500;">We believe in</div>
<div class="tp-caption top-label banfont"
data-x="left" data-hoffset="50"
data-y="center" data-voffset="-45"
data-start="1500"
data-whitespace="nowrap"
data-transform_in="y:[100%];s:500;"
data-transform_out="opacity:0;s:500;"
style="z-index: 5; font-size:47px;">life before death</div>
</li>
</ul>
</div>
</div>
<div class="home-intro home-intro-primary" id="home-intro">
<div class="container">
<div class="row">
<div class="col-md-12">
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-8">
<div>
<p>Wild Dragon has launched a new global marketing campaign under the slogan "be wild". The campaign, created by New York`s famous nightlife photographer blogger extraordinaire Merlin Bronques, was rolled out in several countries in September 2008. The striking images show downtown New York`s hip, cool and "wild" nightlife with its real and restless people, pushing the limits of their barefaced enthusiasm.</p>
<p>The campaign is aimed at Wild Dragon's typical consumers: young, free and hip individuals with the courage to swim against the stream; and allows the brand to communicate everything it stands for.</p>
<p>The creator of the campaign, Merlin Bronques has attracted thousands of eyeballs from around the globe to his site www.lastnightsparty.com and has recently shot images for several prestigious fashion brands.</p>
</div>
</div>
</div>
</div>
<footer id="footer">
<div class="container">
<div class="row">
<div class="col-md-4">
<div class="contact-details">
<h4>Office Vienna</h4>
<ul class="contact">
<li><p><i class="fa fa-map-marker"></i> Laxenburger Straße 365/A8, A-1230 Vienna</p></li>
<li><p><i class="fa fa-phone"></i> <strong>Phone:</strong> (+43 1) 616 43 60 - 34</p></li>
<li><p><i class="fa fa-envelope"></i> <strong>Email:</strong> <a href="mailto:info@wilddragon.at">info@wilddragon.at</a></p></li>
</ul>
</div>
</div>
<div class="col-md-4">
<div class="contact-details">
<h4>Office Berlin</h4>
<ul class="contact">
<li><p><i class="fa fa-map-marker"></i> Großbeerenstraße 2-10, D-12107 Berlin</p></li>
<li><p><i class="fa fa-phone"></i> <strong>Phone:</strong> (+49 1) 72 351 26 99</p></li>
<li><p><i class="fa fa-envelope"></i> <strong>Email:</strong> <a href="mailto:berlin@wilddragon.at">berlin@wilddragon.at</a></p></li>
</ul>
</div>
</div>
<div class="col-md-4">
<h4>Follow Us</h4>
<ul class="social-icons">
<li class="social-icons-facebook"><a href="http://www.facebook.com/wilddragoncom/" target="_blank" title="Wild Dragon Energy Drink on Facebook"><i class="fa fa-facebook"></i></a></li>
<li class="social-icons-twitter"><a href="http://www.twitter.com/wilddragoncom/" target="_blank" title="Wild Dragon Energy Drink on Twitter"><i class="fa fa-twitter"></i></a></li>
<li class="social-icons-instagram"><a href="https://www.instagram.com/wilddragoncom/" target="_blank" title="Wild Dragon Energy Drink on Instagram"><i class="fa fa-instagram"></i></a></li>
<li class="social-icons-youtube"><a href="https://www.youtube.com/user/wilddragoncom/" target="_blank" title="Wild Dragon Energy Drink on YouTube"><i class="fa fa-youtube"></i></a></li>
<li class="social-icons-google-plus"><a href="https://plus.google.com/+wilddragoncom/" target="_blank" title="Wild Dragon Energy Drink on Google+"><i class="fa fa-google-plus"></i></a></li>
</ul>
</div>
</div>
</div>
<div class="footer-copyright">
<div class="container">
<div class="row">
<div class="col-md-1">
<a href="index.html" class="logo">
<img alt="Porto Website Template" class="img-responsive" src="img/wild-dragon-logo-footer.png">
</a>
</div>
<div class="col-md-4">
<p>© Copyright 2017. All Rights Reserved.</p>
</div>
<div class="col-md-5 pull-right">
<nav id="sub-menu">
<ul>
<li class="active"><a href="./">Home</a></li>
<li><a href="product">Product</a></li>
<li><a href="media.php">Media</a></li>
<li><a href="wild-territories">Wild Territories</a></li>
<li><a href="awards">Awards</a></li>
<li><a href="contact">Contact</a></li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</footer>
</div>
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/jquery.appear/jquery.appear.min.js"></script>
<script src="vendor/jquery.easing/jquery.easing.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="vendor/common/common.min.js"></script>
<script src="vendor/jquery.validation/jquery.validation.min.js"></script>
<script src="vendor/jquery.gmap/jquery.gmap.min.js"></script>
<script src="vendor/jquery.lazyload/jquery.lazyload.min.js"></script>
<script src="vendor/isotope/jquery.isotope.min.js"></script>
<script src="vendor/owl.carousel/owl.carousel.min.js"></script>
<script src="js/theme.js"></script>
<script src="vendor/rs-plugin/js/jquery.themepunch.tools.min.js"></script>
<script src="vendor/rs-plugin/js/jquery.themepunch.revolution.min.js"></script>
<script src="js/custom.js"></script>
<script src="js/theme.init.js"></script>
</body>
</html>
|
todor-dk/HTML-Renderer
|
Source/Testing/HtmlRenderer.ExperimentalApp/Data/Files/bild/F0700B0B73305D4D46178A9E7DB3781D.html
|
HTML
|
bsd-3-clause
| 22,189 |
<?php
/**
* Jazz Library/Framework
*
* LICENSE
* This library is being released under the terms of the New BSD License. A
* copy of the license is packaged with the software (LICENSE.txt). If no
* copy is found, a copy of the license template can be found at:
* http://www.opensource.org/licenses/bsd-license.php
*
* @package Jazz
* @subpackage Finder
* @author Michael Luster <[email protected]>
* @copyright Copyright (c) NYCLagniappe.com - All Rights Reserved
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
* @link https://github.com/nyclagniappe/phpjazz
*/
namespace Jazz\Application\Finder\Prepare;
require_once ('Jazz/Application/Finder/APrepare.php');
/**
* Helper Preparation Finder Class
*
* @package Jazz
* @subpackage Finder
* @author Michael Luster <[email protected]>
* @copyright Copyright (c) NYCLagniappe.com - All Rights Reserved
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
* @link https://github.com/nyclagniappe/phpjazz
*/
class Helper extends \Jazz\Application\Finder\APrepare {
/**
* Initialization method
*/
protected function init() {
$this->setNamespace('Helper');
}
/** ACTION METHODS **/
/**
* Setup the Application Paths
* @param \Jazz\Application\ISettings $settings
* @param \Jazz\Loader\IEngine $engine
*/
public function setupApplication(\Jazz\Application\ISettings $settings
, \Jazz\Loader\IEngine $engine) {
$engine->setIsClass(true);
$engine->setReturnClassName(true);
$prepend = $this->getNamespace() . $settings->getSeparator();
$path = $this->formatApplicationPath($settings);
if (file_exists($path)) {
$ns = $this->formatApplicationNamespace($settings);
$engine->appendPath(
new \Jazz\Loader\Path($path, $ns, null, null, 'php', $settings->getSeparator()));
}
$path = $this->formatLibraryPath($settings);
if (file_exists($path)) {
$ns = $this->formatLibraryNamespace($settings);
$engine->appendPath(
new \Jazz\Loader\Path($path, $ns, null, null, 'php', $settings->getSeparator()));
}
$path = dirname(dirname(dirname(dirname(__FILE__))));
$ns = '\Jazz\\';
$engine->appendPath(
new \Jazz\Loader\Path($path, $ns, $prepend, null, 'php', $settings->getSeparator()));
}
/**
* Setup the Component Paths
* @param \Jazz\Application\ISettings $settings
* @param \Jazz\Loader\IEngine $engine
* @param string $name
*/
public function setupComponent(\Jazz\Application\ISettings $settings
, \Jazz\Loader\IEngine $engine
, $name) {
$engine->setIsClass(true);
$engine->setReturnClassName(true);
$prepend = $this->getNamespace() . $settings->getSeparator();
$path = $this->formatComponentPath($settings, $name);
if (file_exists($path)) {
$ns = $this->formatComponentNamespace($settings, $name);
$engine->appendPath(
new \Jazz\Loader\Path($path, $ns, null, null, 'php', $settings->getSeparator()));
}
$path = $this->formatLibraryPath($settings);
if (file_exists($path)) {
$ns = $this->formatLibraryNamespace($settings);
$engine->appendPath(
new \Jazz\Loader\Path($path, $ns, null, null, 'php', $settings->getSeparator()));
}
$path = dirname(dirname(dirname(dirname(__FILE__))));
$ns = '\Jazz\\';
$engine->appendPath(
new \Jazz\Loader\Path($path, $ns, $prepend, null, 'php', $settings->getSeparator()));
}
}
|
ibayou/phpjazz
|
archive/Jazz/Application/Finder/Prepare/Helper.php
|
PHP
|
bsd-3-clause
| 3,826 |
/*
Copyright (C) 2016 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file qle/instruments/currencyswap.hpp
\brief Interest rate swap with extended interface
\ingroup instruments
*/
#ifndef quantext_currencyswap_hpp
#define quantext_currencyswap_hpp
#include <ql/instruments/swap.hpp>
#include <ql/time/daycounter.hpp>
#include <ql/time/schedule.hpp>
#include <ql/cashflows/cashflows.hpp>
#include <ql/indexes/iborindex.hpp>
#include <ql/currency.hpp>
#include <ql/currencies/europe.hpp>
#include <ql/money.hpp>
using namespace QuantLib;
namespace QuantExt {
//! %Currency Interest Rate Swap
/*!
This instrument generalizes the QuantLib Swap instrument in that
it allows multiple legs with different currencies (one per leg)
\ingroup instruments
*/
class CurrencySwap : public Instrument {
public:
class arguments;
class results;
class engine;
//! \name Constructors
//@{
/*! Multi leg constructor. */
CurrencySwap(const std::vector<Leg>& legs, const std::vector<bool>& payer, const std::vector<Currency>& currency);
//@}
//! \name Instrument interface
//@{
bool isExpired() const;
void setupArguments(PricingEngine::arguments*) const;
void fetchResults(const PricingEngine::results*) const;
//@}
//! \name Additional interface
//@{
Date startDate() const;
Date maturityDate() const;
Real legBPS(Size j) const {
QL_REQUIRE(j < legs_.size(), "leg# " << j << " doesn't exist!");
calculate();
return legBPS_[j];
}
Real legNPV(Size j) const {
QL_REQUIRE(j < legs_.size(), "leg #" << j << " doesn't exist!");
calculate();
return legNPV_[j];
}
Real inCcyLegBPS(Size j) const {
QL_REQUIRE(j < legs_.size(), "leg# " << j << " doesn't exist!");
calculate();
return inCcyLegBPS_[j];
}
Real inCcyLegNPV(Size j) const {
QL_REQUIRE(j < legs_.size(), "leg #" << j << " doesn't exist!");
calculate();
return inCcyLegNPV_[j];
}
DiscountFactor startDiscounts(Size j) const {
QL_REQUIRE(j < legs_.size(), "leg #" << j << " doesn't exist!");
calculate();
return startDiscounts_[j];
}
DiscountFactor endDiscounts(Size j) const {
QL_REQUIRE(j < legs_.size(), "leg #" << j << " doesn't exist!");
calculate();
return endDiscounts_[j];
}
DiscountFactor npvDateDiscount() const {
calculate();
return npvDateDiscount_;
}
const Leg& leg(Size j) const {
QL_REQUIRE(j < legs_.size(), "leg #" << j << " doesn't exist!");
return legs_[j];
}
const Currency& legCurrency(Size j) const {
QL_REQUIRE(j < legs_.size(), "leg #" << j << " doesn't exist!");
return currency_[j];
}
std::vector<Leg> legs() { return legs_; }
std::vector<Currency> currencies() { return currency_; }
boost::shared_ptr<PricingEngine> engine() { return engine_; }
//@}
protected:
//! \name Constructors
//@{
/*! This constructor can be used by derived classes that will
build their legs themselves.
*/
CurrencySwap(Size legs);
//! \name Instrument interface
//@{
void setupExpired() const;
//@}
// data members
std::vector<Leg> legs_;
std::vector<Real> payer_;
std::vector<Currency> currency_;
mutable std::vector<Real> legNPV_, inCcyLegNPV_;
mutable std::vector<Real> legBPS_, inCcyLegBPS_;
mutable std::vector<DiscountFactor> startDiscounts_, endDiscounts_;
mutable DiscountFactor npvDateDiscount_;
};
class CurrencySwap::arguments : public virtual PricingEngine::arguments {
public:
std::vector<Leg> legs;
std::vector<Real> payer;
std::vector<Currency> currency;
void validate() const;
};
class CurrencySwap::results : public Instrument::results {
public:
std::vector<Real> legNPV, inCcyLegNPV;
std::vector<Real> legBPS, inCcyLegBPS;
std::vector<DiscountFactor> startDiscounts, endDiscounts;
DiscountFactor npvDateDiscount;
void reset();
};
class CurrencySwap::engine : public GenericEngine<CurrencySwap::arguments, CurrencySwap::results> {};
//! Vanilla cross currency interest rate swap
/*! Specialised CurrencySwap: Two currencies, fixed vs. floating,
constant notionals, rate and spread.
\ingroup instruments{
*/
class VanillaCrossCurrencySwap : public CurrencySwap {
public:
VanillaCrossCurrencySwap(bool payFixed, Currency fixedCcy, Real fixedNominal, const Schedule& fixedSchedule,
Rate fixedRate, const DayCounter& fixedDayCount, Currency floatCcy, Real floatNominal,
const Schedule& floatSchedule, const boost::shared_ptr<IborIndex>& iborIndex,
Rate floatSpread, boost::optional<BusinessDayConvention> paymentConvention = boost::none);
};
//! Cross currency swap
/*! Specialised CurrencySwap: Two currencies, variable notionals,
rates and spreads; flavours fix/float, fix/fix, float/float
\ingroup instruments
*/
class CrossCurrencySwap : public CurrencySwap {
public:
// fixed/floating
CrossCurrencySwap(bool payFixed, Currency fixedCcy, std::vector<Real> fixedNominals, const Schedule& fixedSchedule,
std::vector<Rate> fixedRates, const DayCounter& fixedDayCount, Currency floatCcy,
std::vector<Real> floatNominals, const Schedule& floatSchedule,
const boost::shared_ptr<IborIndex>& iborIndex, std::vector<Rate> floatSpreads,
boost::optional<BusinessDayConvention> paymentConvention = boost::none);
// fixed/fixed
CrossCurrencySwap(bool pay1, Currency ccy1, std::vector<Real> nominals1, const Schedule& schedule1,
std::vector<Rate> fixedRates1, const DayCounter& fixedDayCount1, Currency ccy2,
std::vector<Real> nominals2, const Schedule& schedule2, std::vector<Rate> fixedRates2,
const DayCounter& fixedDayCount2,
boost::optional<BusinessDayConvention> paymentConvention = boost::none);
// floating/floating
CrossCurrencySwap(bool pay1, Currency ccy1, std::vector<Real> nominals1, const Schedule& schedule1,
const boost::shared_ptr<IborIndex>& iborIndex1, std::vector<Rate> spreads1, Currency ccy2,
std::vector<Real> nominals2, const Schedule& schedule2,
const boost::shared_ptr<IborIndex>& iborIndex2, std::vector<Rate> spreads2,
boost::optional<BusinessDayConvention> paymentConvention = boost::none);
};
}
#endif
|
ChinaQuants/Engine
|
QuantExt/qle/instruments/currencyswap.hpp
|
C++
|
bsd-3-clause
| 7,353 |
package edu.brown.cs.systems.tracing.aspects;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.junit.Test;
import edu.brown.cs.systems.tracing.aspects.Annotations.BaggageInheritanceDisabled;
import edu.brown.cs.systems.tracing.aspects.RunnablesCallablesThreads.InstrumentedExecution;
import junit.framework.TestCase;
/** Tests to see whether wrapper classes are correctly created */
public class TestInstrumentedClassesPublic extends TestCase {
public static class TestCallable<T> implements Callable<T> {
public T call() {
return null;
}
}
public static class TestCallable2<T> extends TestCallable<T> {
}
public static class TestCallable3<T> extends TestCallable<T> {
public T call() {
return null;
}
}
@BaggageInheritanceDisabled
public static class TestNonTraceCallable<T> implements Callable<T> {
public T call(){
return null;
}
}
public static class TestNonTraceCallable2<T> extends TestNonTraceCallable<T> {
}
public static class TestNonTraceCallable3<T> extends TestNonTraceCallable<T> {
public T call() {
return null;
}
}
public static class TestRunnable implements Runnable {
public void run() {
}
}
public static class TestRunnable2 extends TestRunnable {
}
public static class TestThread extends Thread {
}
public static class TestThread2 extends TestThread {
}
@BaggageInheritanceDisabled
public static class TestNonTraceRunnable implements Runnable {
public void run() {
}
}
public static class TestNonTraceRunnable2 extends TestNonTraceRunnable{}
@BaggageInheritanceDisabled
public static class TestNonTraceRunnable3 extends TestNonTraceRunnable{}
@Test
public void testRunnables() {
Runnable r1 = new Runnable() {
public void run() {
}
};
Runnable r2 = new TestRunnable();
Runnable r3 = new TestRunnable2();
Runnable r4 = new TestNonTraceRunnable();
Runnable r5 = new TestNonTraceRunnable2();
Runnable r6 = new TestNonTraceRunnable3();
Thread t1 = new Thread() {
};
Thread t2 = new TestThread();
Thread t3 = new TestThread2();
Thread t4 = new Thread(r1);
Thread t5 = new Thread(r2);
Thread t6 = new Thread(r3);
Thread t7 = new Thread(t1);
Thread t8 = new Thread(t2);
Thread t9 = new Thread(t3);
assertTrue(r1 instanceof InstrumentedExecution);
assertTrue(r2 instanceof InstrumentedExecution);
assertTrue(r3 instanceof InstrumentedExecution);
assertTrue(t1 instanceof InstrumentedExecution);
assertTrue(t2 instanceof InstrumentedExecution);
assertTrue(t3 instanceof InstrumentedExecution);
assertFalse(r4 instanceof InstrumentedExecution);
assertFalse(r5 instanceof InstrumentedExecution);
assertFalse(r6 instanceof InstrumentedExecution);
assertTrue(t4 instanceof InstrumentedExecution);
assertTrue(t5 instanceof InstrumentedExecution);
assertTrue(t6 instanceof InstrumentedExecution);
assertTrue(t7 instanceof InstrumentedExecution);
assertTrue(t8 instanceof InstrumentedExecution);
assertTrue(t9 instanceof InstrumentedExecution);
assertTrue(t4 instanceof WrappedThread);
assertTrue(t5 instanceof WrappedThread);
assertTrue(t6 instanceof WrappedThread);
assertTrue(t7 instanceof WrappedThread);
assertTrue(t8 instanceof WrappedThread);
assertTrue(t9 instanceof WrappedThread);
assertTrue(TracingplaneAspectUtils.getRunnable(t4) instanceof InstrumentedExecution);
assertTrue(TracingplaneAspectUtils.getRunnable(t5) instanceof InstrumentedExecution);
assertTrue(TracingplaneAspectUtils.getRunnable(t6) instanceof InstrumentedExecution);
assertTrue(TracingplaneAspectUtils.getRunnable(t7) instanceof InstrumentedExecution);
assertTrue(TracingplaneAspectUtils.getRunnable(t8) instanceof InstrumentedExecution);
assertTrue(TracingplaneAspectUtils.getRunnable(t9) instanceof InstrumentedExecution);
Callable<Object> c1 = new TestCallable<>();
Callable<Object> c2 = new TestCallable2<>();
Callable<Object> c3 = new TestCallable3<>();
Callable<Object> c4 = new TestNonTraceCallable<>();
Callable<Object> c5 = new TestNonTraceCallable2<>();
Callable<Object> c6 = new TestNonTraceCallable3<>();
assertTrue(c1 instanceof InstrumentedExecution);
assertTrue(c2 instanceof InstrumentedExecution);
assertTrue(c3 instanceof InstrumentedExecution);
assertFalse(c4 instanceof InstrumentedExecution);
assertFalse(c5 instanceof InstrumentedExecution);
assertFalse(c6 instanceof InstrumentedExecution);
ExecutorService s = Executors.newFixedThreadPool(1);
Future<Object> f1 = s.submit(c1);
Future<Object> f2 = s.submit(c2);
Future<Object> f3 = s.submit(c3);
Future<Object> f4 = s.submit(c4);
Future<Object> f5 = s.submit(c5);
Future<Object> f6 = s.submit(c6);
Future<?> f7 = s.submit(r1);
Future<?> f8 = s.submit(r2);
Future<?> f9 = s.submit(r3);
Future<?> f10 = s.submit(r4);
Future<?> f11 = s.submit(r5);
Future<?> f12 = s.submit(r6);
assertTrue(f1 instanceof WrappedFuture);
assertTrue(f2 instanceof WrappedFuture);
assertTrue(f3 instanceof WrappedFuture);
assertFalse(f4 instanceof WrappedFuture);
assertFalse(f5 instanceof WrappedFuture);
assertFalse(f6 instanceof WrappedFuture);
assertTrue(f7 instanceof WrappedFuture);
assertTrue(f8 instanceof WrappedFuture);
assertTrue(f9 instanceof WrappedFuture);
assertFalse(f10 instanceof WrappedFuture);
assertFalse(f11 instanceof WrappedFuture);
assertFalse(f12 instanceof WrappedFuture);
}
}
|
brownsys/tracing-framework
|
tracingplane/aspects/src/test/aspect/edu/brown/cs/systems/tracing/aspects/TestInstrumentedClassesPublic.java
|
Java
|
bsd-3-clause
| 6,273 |
/*
Copyright (c) 2013, Taiga Nomi
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <cstddef>
/**
* define if you want to use intel TBB library
*/
//#define CNN_USE_TBB
/**
* define to enable avx vectorization
*/
//#define CNN_USE_AVX
/**
* define to enable sse2 vectorization
*/
//#define CNN_USE_SSE
/**
* define to enable OMP parallelization
*/
//#define CNN_USE_OMP
/**
* define to use exceptions
*/
#define CNN_USE_EXCEPTIONS
/**
* comment out if you want tiny-dnn to be quiet
*/
#define CNN_USE_STDOUT
/**
* number of task in batch-gradient-descent.
* @todo automatic optimization
*/
#ifdef CNN_USE_OMP
#define CNN_TASK_SIZE 100
#else
#define CNN_TASK_SIZE 8
#endif
#if !defined(_MSC_VER) || (_MSC_VER >= 1900) // default generation of move constructor is unsupported in VS2013
#define CNN_USE_DEFAULT_MOVE_CONSTRUCTORS
#endif
#if !defined(_MSC_VER)
#define CNN_USE_GEMMLOWP // gemmlowp doesn't support MSVC
#endif
#if defined _WIN32
#define CNN_WINDOWS
#endif
namespace tiny_dnn {
/**
* calculation data type
* you can change it to float, or user defined class (fixed point,etc)
**/
typedef float float_t;
/**
* size of layer, model, data etc.
* change to smaller type if memory footprint is severe
**/
typedef std::size_t cnn_size_t;
}
|
zhangqianhui/tiny-cnn
|
tiny_dnn/config.h
|
C
|
bsd-3-clause
| 2,785 |
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\apidoc\commands;
use phpDocumentor\Reflection\FileReflector;
use TokenReflection\ReflectionFile;
use yii\apidoc\templates\BaseRenderer;
use yii\console\Controller;
use yii\helpers\ArrayHelper;
use yii\helpers\Console;
use yii\helpers\FileHelper;
use yii\apidoc\components\OfflineRenderer;
use yii\apidoc\models\Context;
use Yii;
/**
* Command to render API Documentation files
*
* @author Carsten Brandt <[email protected]>
* @since 2.0
*/
class RenderController extends Controller
{
public $template = 'bootstrap';
public $guide;
/**
* Renders API documentation files
* @param array $sourceDirs
* @param string $targetDir
* @return int
*/
public function actionIndex(array $sourceDirs, $targetDir)
{
$targetDir = rtrim(Yii::getAlias($targetDir), '\\/');
if (is_dir($targetDir) && !$this->confirm('TargetDirectory already exists. Overwrite?')) {
return 2;
}
if (!is_dir($targetDir)) {
mkdir($targetDir);
}
$renderer = $this->findRenderer();
if ($renderer === false) {
return 1;
}
$renderer->targetDir = $targetDir;
if ($this->guide !== null && $renderer->hasProperty('guideUrl')) {
$renderer->guideUrl = './';
$renderer->markDownFiles = $this->findMarkdownFiles($this->guide, ['README.md']);
}
$this->stdout('Searching files to process... ');
$files = [];
foreach($sourceDirs as $source) {
foreach($this->findFiles($source) as $fileName) {
$files[$fileName] = $fileName;
}
}
$this->stdout('done.' . PHP_EOL, Console::FG_GREEN);
if (empty($files)) {
$this->stderr('Error: No php files found to process.' . PHP_EOL);
return 1;
}
$context = new Context();
$cacheFile = $targetDir . '/cache/' . md5(serialize($files)) . '.tmp';
if (file_exists($cacheFile)) {
$this->stdout('Loading processed data from cache... ');
$context = unserialize(file_get_contents($cacheFile));
$this->stdout('done.' . PHP_EOL, Console::FG_GREEN);
$this->stdout('Checking for updated files... ');
foreach($context->files as $file => $sha) {
if (sha1_file($file) === $sha) {
unset($files[$file]);
}
}
$this->stdout('done.' . PHP_EOL, Console::FG_GREEN);
}
$fileCount = count($files);
$this->stdout($fileCount . ' file' . ($fileCount == 1 ? '' : 's') . ' to update.' . PHP_EOL);
Console::startProgress(0, $fileCount, 'Processing files... ', false);
$done = 0;
foreach($files as $file) {
$context->addFile($file);
Console::updateProgress(++$done, $fileCount);
}
Console::endProgress(true);
$this->stdout('done.' . PHP_EOL, Console::FG_GREEN);
// save processed data to cache
if (!is_dir(dirname($cacheFile))) {
mkdir(dirname($cacheFile));
}
file_put_contents($cacheFile, serialize($context));
$this->stdout('Updating cross references and backlinks... ');
$context->updateReferences();
$this->stdout('done.' . PHP_EOL, Console::FG_GREEN);
// render models
$renderer->renderApi($context, $this);
ArrayHelper::multisort($context->errors, 'file');
print_r($context->errors);
// render guide if specified
if ($this->guide !== null) {
$renderer->renderMarkdownFiles($this);
$this->stdout('Publishing images...');
FileHelper::copyDirectory(rtrim($this->guide, '/\\') . '/images', $targetDir . '/images');
$this->stdout('done.' . PHP_EOL, Console::FG_GREEN);
}
}
/**
* @return BaseRenderer
*/
protected function findRenderer()
{
$rendererClass = 'yii\\apidoc\\templates\\' . $this->template . '\\Renderer';
if (!class_exists($rendererClass)) {
$this->stderr('Renderer not found.' . PHP_EOL);
return false;
}
return new $rendererClass();
}
protected function findFiles($path, $except = ['vendor/', 'tests/'])
{
$path = FileHelper::normalizePath($path);
$options = [
'filter' => function ($path) {
if (is_file($path)) {
$file = basename($path);
if ($file[0] < 'A' || $file[0] > 'Z') {
return false;
}
}
return null;
},
'only' => ['*.php'],
'except' => $except,
];
return FileHelper::findFiles($path, $options);
}
protected function findMarkdownFiles($path, $except = [])
{
$path = FileHelper::normalizePath($path);
$options = [
'only' => ['*.md'],
'except' => $except,
];
return FileHelper::findFiles($path, $options);
}
/**
* @inheritdoc
*/
public function globalOptions()
{
return array_merge(parent::globalOptions(), ['template', 'guide']);
}
}
|
yourcodehere/yii2
|
extensions/apidoc/commands/RenderController.php
|
PHP
|
bsd-3-clause
| 4,589 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__wchar_t_file_w32_spawnlp_62b.cpp
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-62b.tmpl.cpp
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: file Read input from a file
* GoodSource: Fixed string
* Sinks: w32_spawnlp
* BadSink : execute command with wspawnlp
* Flow Variant: 62 Data flow: data flows using a C++ reference from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT L"cmd.exe"
#define COMMAND_ARG1 L"/c"
#define COMMAND_ARG2 L"dir "
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH L"/bin/sh"
#define COMMAND_INT L"sh"
#define COMMAND_ARG1 L"-c"
#define COMMAND_ARG2 L"ls "
#define COMMAND_ARG3 data
#endif
#ifdef _WIN32
#define FILENAME "C:\\temp\\file.txt"
#else
#define FILENAME "/tmp/file.txt"
#endif
namespace CWE78_OS_Command_Injection__wchar_t_file_w32_spawnlp_62
{
#ifndef OMITBAD
void badSource(wchar_t * &data)
{
{
/* Read input from a file */
size_t dataLen = wcslen(data);
FILE * pFile;
/* if there is room in data, attempt to read the input from a file */
if (100-dataLen > 1)
{
pFile = fopen(FILENAME, "r");
if (pFile != NULL)
{
/* POTENTIAL FLAW: Read data from a file */
if (fgetws(data+dataLen, (int)(100-dataLen), pFile) == NULL)
{
printLine("fgetws() failed");
/* Restore NUL terminator if fgetws fails */
data[dataLen] = L'\0';
}
fclose(pFile);
}
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
void goodG2BSource(wchar_t * &data)
{
/* FIX: Append a fixed string to data (not user / external input) */
wcscat(data, L"*.*");
}
#endif /* OMITGOOD */
} /* close namespace */
|
JianpingZeng/xcc
|
xcc/test/juliet/testcases/CWE78_OS_Command_Injection/s08/CWE78_OS_Command_Injection__wchar_t_file_w32_spawnlp_62b.cpp
|
C++
|
bsd-3-clause
| 2,248 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__char_environment_w32_spawnv_63a.c
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-63a.tmpl.c
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: environment Read input from an environment variable
* GoodSource: Fixed string
* Sinks: w32_spawnv
* BadSink : execute command with spawnv
* Flow Variant: 63 Data flow: pointer to data passed from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT "cmd.exe"
#define COMMAND_ARG1 "/c"
#define COMMAND_ARG2 "dir "
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH "/bin/sh"
#define COMMAND_INT "sh"
#define COMMAND_ARG1 "-c"
#define COMMAND_ARG2 "ls "
#define COMMAND_ARG3 data
#endif
#define ENV_VARIABLE "ADD"
#ifdef _WIN32
#define GETENV getenv
#else
#define GETENV getenv
#endif
#include <process.h>
#ifndef OMITBAD
/* bad function declaration */
void CWE78_OS_Command_Injection__char_environment_w32_spawnv_63b_badSink(char * * dataPtr);
void CWE78_OS_Command_Injection__char_environment_w32_spawnv_63_bad()
{
char * data;
char dataBuffer[100] = COMMAND_ARG2;
data = dataBuffer;
{
/* Append input from an environment variable to data */
size_t dataLen = strlen(data);
char * environment = GETENV(ENV_VARIABLE);
/* If there is data in the environment variable */
if (environment != NULL)
{
/* POTENTIAL FLAW: Read data from an environment variable */
strncat(data+dataLen, environment, 100-dataLen-1);
}
}
CWE78_OS_Command_Injection__char_environment_w32_spawnv_63b_badSink(&data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void CWE78_OS_Command_Injection__char_environment_w32_spawnv_63b_goodG2BSink(char * * data);
static void goodG2B()
{
char * data;
char dataBuffer[100] = COMMAND_ARG2;
data = dataBuffer;
/* FIX: Append a fixed string to data (not user / external input) */
strcat(data, "*.*");
CWE78_OS_Command_Injection__char_environment_w32_spawnv_63b_goodG2BSink(&data);
}
void CWE78_OS_Command_Injection__char_environment_w32_spawnv_63_good()
{
goodG2B();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE78_OS_Command_Injection__char_environment_w32_spawnv_63_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE78_OS_Command_Injection__char_environment_w32_spawnv_63_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
JianpingZeng/xcc
|
xcc/test/juliet/testcases/CWE78_OS_Command_Injection/s03/CWE78_OS_Command_Injection__char_environment_w32_spawnv_63a.c
|
C
|
bsd-3-clause
| 3,371 |
/*
* Copyright (c) 2009-2020 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package jme3test.batching;
import com.jme3.app.SimpleApplication;
import com.jme3.bounding.BoundingBox;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.scene.BatchNode;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.debug.WireFrustum;
import com.jme3.scene.shape.Box;
import com.jme3.system.NanoTimer;
import com.jme3.util.TangentBinormalGenerator;
/**
* A test to demonstrate the usage and functionality of the {@link BatchNode}
* @author Nehon
*/
public class TestBatchNode extends SimpleApplication {
private BatchNode batch;
private WireFrustum frustum;
private final Vector3f[] points;
private Geometry cube2;
private float time = 0;
private DirectionalLight dl;
private boolean done = false;
public static void main(String[] args) {
TestBatchNode app = new TestBatchNode();
app.start();
}
public TestBatchNode() {
points = new Vector3f[8];
for (int i = 0; i < points.length; i++) {
points[i] = new Vector3f();
}
}
@Override
public void simpleInitApp() {
timer = new NanoTimer();
batch = new BatchNode("theBatchNode");
/*
* A cube with a color "bleeding" through transparent texture. Uses
* Texture from jme3-test-data library!
*/
Box boxshape4 = new Box(1f, 1f, 1f);
Geometry cube = new Geometry("cube1", boxshape4);
Material mat = assetManager.loadMaterial("Textures/Terrain/Pond/Pond.j3m");
cube.setMaterial(mat);
//Material mat = new Material(assetManager, "Common/MatDefs/Light/Lighting.j3md");
//mat.setColor("Diffuse", ColorRGBA.Blue);
//mat.setBoolean("UseMaterialColors", true);
/*
* A cube with a color "bleeding" through transparent texture. Uses
* Texture from jme3-test-data library!
*/
Box box = new Box(1f, 1f, 1f);
cube2 = new Geometry("cube2", box);
cube2.setMaterial(mat);
TangentBinormalGenerator.generate(cube);
TangentBinormalGenerator.generate(cube2);
batch.attachChild(cube);
// batch.attachChild(cube2);
// batch.setMaterial(mat);
batch.batch();
rootNode.attachChild(batch);
cube.setLocalTranslation(3, 0, 0);
cube2.setLocalTranslation(0, 20, 0);
updateBoundingPoints(points);
frustum = new WireFrustum(points);
Geometry frustumMdl = new Geometry("f", frustum);
frustumMdl.setCullHint(Spatial.CullHint.Never);
frustumMdl.setMaterial(new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"));
frustumMdl.getMaterial().getAdditionalRenderState().setWireframe(true);
frustumMdl.getMaterial().setColor("Color", ColorRGBA.Red);
rootNode.attachChild(frustumMdl);
dl = new DirectionalLight();
dl.setColor(ColorRGBA.White.mult(2));
dl.setDirection(new Vector3f(1, -1, -1));
rootNode.addLight(dl);
flyCam.setMoveSpeed(10);
}
@Override
public void simpleUpdate(float tpf) {
if (!done) {
done = true;
batch.attachChild(cube2);
batch.batch();
}
updateBoundingPoints(points);
frustum.update(points);
time += tpf;
dl.setDirection(cam.getDirection());
cube2.setLocalTranslation(FastMath.sin(-time) * 3, FastMath.cos(time) * 3, 0);
cube2.setLocalRotation(new Quaternion().fromAngleAxis(time, Vector3f.UNIT_Z));
cube2.setLocalScale(Math.max(FastMath.sin(time), 0.5f));
// batch.setLocalRotation(new Quaternion().fromAngleAxis(time, Vector3f.UNIT_Z));
}
public void updateBoundingPoints(Vector3f[] points) {
BoundingBox bb = (BoundingBox) batch.getWorldBound();
float xe = bb.getXExtent();
float ye = bb.getYExtent();
float ze = bb.getZExtent();
float x = bb.getCenter().x;
float y = bb.getCenter().y;
float z = bb.getCenter().z;
points[0].set(new Vector3f(x - xe, y - ye, z - ze));
points[1].set(new Vector3f(x - xe, y + ye, z - ze));
points[2].set(new Vector3f(x + xe, y + ye, z - ze));
points[3].set(new Vector3f(x + xe, y - ye, z - ze));
points[4].set(new Vector3f(x + xe, y - ye, z + ze));
points[5].set(new Vector3f(x - xe, y - ye, z + ze));
points[6].set(new Vector3f(x - xe, y + ye, z + ze));
points[7].set(new Vector3f(x + xe, y + ye, z + ze));
}
}
|
zzuegg/jmonkeyengine
|
jme3-examples/src/main/java/jme3test/batching/TestBatchNode.java
|
Java
|
bsd-3-clause
| 6,315 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html>
<head>
<title>LOG-DESIRE-TO-ADD-A-LINK</title>
</head>
<body>
<h3><i>I add to the log when an individual prefers to add a link.</i> </h3>
<font size="2" color="gray">Begin micro-behaviour</font>
<p><b>LOG-DESIRE-TO-ADD-A-LINK</b></p>
<font size="2" color="gray">Begin NetLogo code:</font>
<pre>when [my-desire-to-link = true and is-object? my-other-player]
[output-print (word "Individual " who " desired to add a link to " [who] of my-other-player " at time " round time)
output-print (word "His utility of the network with this addition is " utility-of-network (list my-other-player) []
" which is greater than the utility of his network with no changes " utility-of-network [] [])]
</pre>
<font size="2" color="gray">End NetLogo code</font>
<h2>Variants</h2>
<p>You can change the text of the message. </p>
<h2>Related Micro-behaviours</h2>
<p>This behaviour relies upon
<a title="POSSIBLE-INFECTION" href="SIMPLE-ADD-LINK-DECISION.html">
SIMPLE-ADD-LINK-DECISION</a> to determine the value of <i>my-desire-to-link</i>.
<a href="LOG-DESIRE-TO-REMOVE-A-LINK.html">LOG-DESIRE-TO-REMOVE-A-LINK</a>
logs decisions to remove links.</p>
<h2>How this works</h2>
<p>This checks if I've set a variable indicating I prefer to add a link and then adds a message to the log.</p>
<h2>History</h2>
<p>This was implemented by Ken Kahn. </p>
</body>
</html>
|
ToonTalk/behaviour-composer
|
BC/Static Web Pages/Resources/Composer/en/MB.2/LOG-DESIRE-TO-ADD-A-LINK.html
|
HTML
|
bsd-3-clause
| 1,563 |
<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Zend Framework API Documentation</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta><link rel="stylesheet" href="css/black-tie/jquery-ui-1.8.2.custom.css" type="text/css"></link><link rel="stylesheet" href="css/jquery.treeview.css" type="text/css"></link><link rel="stylesheet" href="css/theme.css" type="text/css"></link><script type="text/javascript" src="js/jquery-1.4.2.min.js"></script><script type="text/javascript" src="js/jquery-ui-1.8.2.custom.min.js"></script><script type="text/javascript" src="js/jquery.cookie.js"></script><script type="text/javascript" src="js/jquery.treeview.js"></script><script type="text/javascript">
$(document).ready(function() {
$(".filetree").treeview({
collapsed: true,
persist: "cookie"
});
$("#accordion").accordion({
collapsible: true,
autoHeight: false,
fillSpace: true
});
$(".tabs").tabs();
});
</script></head><body><div xmlns="" class="content">
<div class="sub-page-main-header-api-documentation"><h2>API Documentation</h2></div>
<div class="dotted-line"></div>
</div>
<div xmlns="" id="content">
<script type="text/javascript" src="js/menu.js"></script><script>
$(document).ready(function() {
$('a.gripper').click(function() {
$(this).nextAll('div.code-tabs').slideToggle();
$(this).children('img').toggle();
return false;
});
$('div.code-tabs').hide();
$('a.gripper').show();
$('div.file-nav').show();
});
</script><h1 class="file">OpenId/Provider.php</h1>
<div class="file-nav"><ul id="file-nav">
<li><a href="#top">Global</a></li>
<li>
<a href="#classes"><img src="images/icons/class.png" height="14">
Classes
</a><ul><li><a href="#%5CZend_OpenId_Provider">\Zend_OpenId_Provider</a></li></ul>
</li>
</ul></div>
<a name="top"></a><div id="file-description">
<p class="short-description">Zend Framework</p>
<div class="long-description"><p>LICENSE</p>
<p>This source file is subject to the new BSD license that is bundled
with this package in the file LICENSE.txt.
It is also available through the world-wide-web at this URL:
http://framework.zend.com/license/new-bsd
If you did not receive a copy of the license and are unable to
obtain it through the world-wide-web, please send an email
to [email protected] so we can send you a copy immediately.</p>
</div>
</div>
<dl class="file-info">
<dt>category</dt>
<dd>Zend
</dd>
<dt>copyright</dt>
<dd>Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
</dd>
<dt>license</dt>
<dd>
<a href="http://framework.zend.com/license/new-bsd">New BSD License</a>
</dd>
<dt>package</dt>
<dd>Zend_OpenId
</dd>
<dt>subpackage</dt>
<dd>Zend_OpenId_Provider
</dd>
<dt>version</dt>
<dd>$Id: Provider.php 23775 2011-03-01 17:25:24Z ralph $
</dd>
</dl>
<a name="classes"></a><a id="\Zend_OpenId_Provider"></a><h2 class="class">\Zend_OpenId_Provider<div class="to-top"><a href="#top">jump to top</a></div>
</h2>
<div class="class">
<p class="short-description">OpenID provider (server) implementation</p>
<div class="long-description">
</div>
<dl class="class-info">
<dt>category</dt>
<dd>Zend
</dd>
<dt>copyright</dt>
<dd>Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
</dd>
<dt>license</dt>
<dd>
<a href="http://framework.zend.com/license/new-bsd">New BSD License</a>
</dd>
<dt>package</dt>
<dd>Zend_OpenId
</dd>
<dt>subpackage</dt>
<dd>Zend_OpenId_Provider
</dd>
</dl>
<h3>Properties</h3>
<div>
<a id="\Zend_OpenId_Provider::$_loginUrl"></a><div class="property">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/property.png" alt="Property"><img src="images/icons/visibility_private.png" style="margin-right: 5px" alt="private">string
<span class="highlight">$_loginUrl</span>= ''
</code><div class="description">
<p class="short-description">URL to peform interactive user login</p></div>
<div class="code-tabs">
<div class="long-description">
</div>
<strong>Details</strong><dl class="property-info">
<dt>Type</dt>
<dd>string</dd>
</dl>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::$_opEndpoint"></a><div class="property">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/property.png" alt="Property"><img src="images/icons/visibility_private.png" style="margin-right: 5px" alt="private">string
<span class="highlight">$_opEndpoint</span>= ''
</code><div class="description">
<p class="short-description">The OP Endpoint URL</p></div>
<div class="code-tabs">
<div class="long-description">
</div>
<strong>Details</strong><dl class="property-info">
<dt>Type</dt>
<dd>string</dd>
</dl>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::$_sessionTtl"></a><div class="property">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/property.png" alt="Property"><img src="images/icons/visibility_private.png" style="margin-right: 5px" alt="private">integer
<span class="highlight">$_sessionTtl</span>= ''
</code><div class="description">
<p class="short-description">Time to live of association session in secconds</p></div>
<div class="code-tabs">
<div class="long-description">
</div>
<strong>Details</strong><dl class="property-info">
<dt>Type</dt>
<dd>integer</dd>
</dl>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::$_storage"></a><div class="property">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/property.png" alt="Property"><img src="images/icons/visibility_private.png" style="margin-right: 5px" alt="private">\Zend_OpenId_Provider_Storage
<span class="highlight">$_storage</span>= ''
</code><div class="description">
<p class="short-description">Reference to an implementation of storage object</p></div>
<div class="code-tabs">
<div class="long-description">
</div>
<strong>Details</strong><dl class="property-info">
<dt>Type</dt>
<dd><a href="db_OpenId_Provider_Storage.html#%5CZend_OpenId_Provider_Storage">\Zend_OpenId_Provider_Storage</a></dd>
</dl>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::$_trustUrl"></a><div class="property">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/property.png" alt="Property"><img src="images/icons/visibility_private.png" style="margin-right: 5px" alt="private">string
<span class="highlight">$_trustUrl</span>= ''
</code><div class="description">
<p class="short-description">URL to peform interactive validation of consumer by user</p></div>
<div class="code-tabs">
<div class="long-description">
</div>
<strong>Details</strong><dl class="property-info">
<dt>Type</dt>
<dd>string</dd>
</dl>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::$_user"></a><div class="property">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/property.png" alt="Property"><img src="images/icons/visibility_private.png" style="margin-right: 5px" alt="private">\Zend_OpenId_Provider_User
<span class="highlight">$_user</span>= ''
</code><div class="description">
<p class="short-description">Reference to an implementation of user object</p></div>
<div class="code-tabs">
<div class="long-description">
</div>
<strong>Details</strong><dl class="property-info">
<dt>Type</dt>
<dd><a href="db_OpenId_Provider_User.html#%5CZend_OpenId_Provider_User">\Zend_OpenId_Provider_User</a></dd>
</dl>
</div>
<div class="clear"></div>
</div>
</div>
<h3>Methods</h3>
<div>
<a id="\Zend_OpenId_Provider::__construct()"></a><div class="method">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">__construct</span><span class="nb-faded-text">(
string $loginUrl
=
null, string $trustUrl
=
null, <a href="db_OpenId_Provider_User.html#%5CZend_OpenId_Provider_User">\Zend_OpenId_Provider_User</a> $user
=
null, <a href="db_OpenId_Provider_Storage.html#%5CZend_OpenId_Provider_Storage">\Zend_OpenId_Provider_Storage</a> $storage
=
null, integer $sessionTtl
=
3600
)
</span>
:
void</code><div class="description"><p class="short_description">Constructs a Zend_OpenId_Provider object with given parameters.</p></div>
<div class="code-tabs">
<div class="long-description">
</div>
<strong>Parameters</strong><table class="argument-info">
<thead><tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<th>$loginUrl</th>
<td>string</td>
<td><em><p>is an URL that provides login screen for end-user (by default it is the same URL with additional GET variable openid.action=login)</p>
</em></td>
</tr>
<tr>
<th>$trustUrl</th>
<td>string</td>
<td><em><p>is an URL that shows a question if end-user trust to given consumer (by default it is the same URL with additional GET variable openid.action=trust)</p>
</em></td>
</tr>
<tr>
<th>$user</th>
<td><a href="db_OpenId_Provider_User.html#%5CZend_OpenId_Provider_User">\Zend_OpenId_Provider_User</a></td>
<td><em><p>is an object for communication with User-Agent and store information about logged-in user (it is a Zend_OpenId_Provider_User_Session object by default)</p>
</em></td>
</tr>
<tr>
<th>$storage</th>
<td><a href="db_OpenId_Provider_Storage.html#%5CZend_OpenId_Provider_Storage">\Zend_OpenId_Provider_Storage</a></td>
<td><em><p>is an object for keeping persistent database (it is a Zend_OpenId_Provider_Storage_File object by default)</p>
</em></td>
</tr>
<tr>
<th>$sessionTtl</th>
<td>integer</td>
<td><em><p>is a default time to live for association session in seconds (1 hour by default). Consumer must reestablish association after that time.</p>
</em></td>
</tr>
</table>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::_associate()"></a><div class="method">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">_associate</span><span class="nb-faded-text">(
float $version, array $params
)
</span>
:
array</code><div class="description"><p class="short_description">Processes association request from OpenID consumerm generates secret
shared key and send it back using Diffie-Hellman encruption.</p></div>
<div class="code-tabs">
<div class="long-description"><p>Returns array of variables to push back to consumer.</p>
</div>
<strong>Parameters</strong><table class="argument-info">
<thead><tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<th>$version</th>
<td>float</td>
<td><em>OpenID version</em></td>
</tr>
<tr>
<th>$params</th>
<td>array</td>
<td><em>GET or POST request variables</em></td>
</tr>
</table>
<strong>Returns</strong><table class="argument-info">
<thead><tr>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<td>array</td>
<td></td>
</tr>
</table>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::_checkAuthentication()"></a><div class="method">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">_checkAuthentication</span><span class="nb-faded-text">(
float $version, array $params
)
</span>
:
array</code><div class="description"><p class="short_description">Performs authentication validation for dumb consumers
Returns array of variables to push back to consumer.</p></div>
<div class="code-tabs">
<div class="long-description"><p>It MUST contain 'is_valid' variable with value 'true' or 'false'.</p>
</div>
<strong>Parameters</strong><table class="argument-info">
<thead><tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<th>$version</th>
<td>float</td>
<td><em>OpenID version</em></td>
</tr>
<tr>
<th>$params</th>
<td>array</td>
<td><em>GET or POST request variables</em></td>
</tr>
</table>
<strong>Returns</strong><table class="argument-info">
<thead><tr>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<td>array</td>
<td></td>
</tr>
</table>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::_checkId()"></a><div class="method">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">_checkId</span><span class="nb-faded-text">(
float $version, array $params, bool $immediate, mixed $extensions
=
null, <a href="db_Controller_Response_Abstract.html#%5CZend_Controller_Response_Abstract">\Zend_Controller_Response_Abstract</a> $response
=
null
)
</span>
:
array</code><div class="description"><p class="short_description">Performs authentication (or authentication check).</p></div>
<div class="code-tabs">
<div class="long-description">
</div>
<strong>Parameters</strong><table class="argument-info">
<thead><tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<th>$version</th>
<td>float</td>
<td><em>OpenID version</em></td>
</tr>
<tr>
<th>$params</th>
<td>array</td>
<td><em>GET or POST request variables</em></td>
</tr>
<tr>
<th>$immediate</th>
<td>bool</td>
<td><em>enables or disables interaction with user</em></td>
</tr>
<tr>
<th>$extensions</th>
<td>mixed</td>
<td><em>extension object or array of extensions objects</em></td>
</tr>
<tr>
<th>$response</th>
<td><a href="db_Controller_Response_Abstract.html#%5CZend_Controller_Response_Abstract">\Zend_Controller_Response_Abstract</a></td>
<td><em></em></td>
</tr>
</table>
<strong>Returns</strong><table class="argument-info">
<thead><tr>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<td>array</td>
<td></td>
</tr>
</table>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::_genSecret()"></a><div class="method">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">_genSecret</span><span class="nb-faded-text">(
string $func
)
</span>
:
mixed</code><div class="description"><p class="short_description">Generates a secret key for given hash function, returns RAW key or false
if function is not supported</p></div>
<div class="code-tabs">
<div class="long-description">
</div>
<strong>Parameters</strong><table class="argument-info">
<thead><tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<th>$func</th>
<td>string</td>
<td><em><p>hash function (sha1 or sha256)</p>
</em></td>
</tr>
</table>
<strong>Returns</strong><table class="argument-info">
<thead><tr>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<td>mixed</td>
<td></td>
</tr>
</table>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::_respond()"></a><div class="method">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">_respond</span><span class="nb-faded-text">(
float $version, array $ret, array $params, mixed $extensions
=
null
)
</span>
:
array</code><div class="description"><p class="short_description">Perepares information to send back to consumer's authentication request
and signs it using shared secret.</p></div>
<div class="code-tabs">
<div class="long-description">
</div>
<strong>Parameters</strong><table class="argument-info">
<thead><tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<th>$version</th>
<td>float</td>
<td><em>OpenID protcol version</em></td>
</tr>
<tr>
<th>$ret</th>
<td>array</td>
<td><em>arguments to be send back to consumer</em></td>
</tr>
<tr>
<th>$params</th>
<td>array</td>
<td><em>GET or POST request variables</em></td>
</tr>
<tr>
<th>$extensions</th>
<td>mixed</td>
<td><em>extension object or array of extensions objects</em></td>
</tr>
</table>
<strong>Returns</strong><table class="argument-info">
<thead><tr>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<td>array</td>
<td></td>
</tr>
</table>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::_secureStringCompare()"></a><div class="method">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">_secureStringCompare</span><span class="nb-faded-text">(
string $a, string $b
)
</span>
:
bool</code><div class="description"><p class="short_description">Securely compare two strings for equality while avoided C level memcmp()
optimisations capable of leaking timing information useful to an attacker
attempting to iteratively guess the unknown string (e.g. password) being
compared against.</p></div>
<div class="code-tabs">
<div class="long-description">
</div>
<strong>Parameters</strong><table class="argument-info">
<thead><tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<th>$a</th>
<td>string</td>
<td><em></em></td>
</tr>
<tr>
<th>$b</th>
<td>string</td>
<td><em></em></td>
</tr>
</table>
<strong>Returns</strong><table class="argument-info">
<thead><tr>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<td>bool</td>
<td></td>
</tr>
</table>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::allowSite()"></a><div class="method">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">allowSite</span><span class="nb-faded-text">(
string $root, mixed $extensions
=
null
)
</span>
:
bool</code><div class="description"><p class="short_description">Allows consumer with given root URL to authenticate current logged
in user. Returns true on success and false on error.</p></div>
<div class="code-tabs">
<div class="long-description">
</div>
<strong>Parameters</strong><table class="argument-info">
<thead><tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<th>$root</th>
<td>string</td>
<td><em>root URL</em></td>
</tr>
<tr>
<th>$extensions</th>
<td>mixed</td>
<td><em>extension object or array of extensions objects</em></td>
</tr>
</table>
<strong>Returns</strong><table class="argument-info">
<thead><tr>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<td>bool</td>
<td></td>
</tr>
</table>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::delSite()"></a><div class="method">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">delSite</span><span class="nb-faded-text">(
string $root
)
</span>
:
bool</code><div class="description"><p class="short_description">Delete consumer with given root URL from known sites of current logged
in user. Next time this consumer will try to authenticate the user,
Provider will ask user's confirmation.</p></div>
<div class="code-tabs">
<div class="long-description"><p>Returns true on success and false on error.</p>
</div>
<strong>Parameters</strong><table class="argument-info">
<thead><tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<th>$root</th>
<td>string</td>
<td><em>root URL</em></td>
</tr>
</table>
<strong>Returns</strong><table class="argument-info">
<thead><tr>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<td>bool</td>
<td></td>
</tr>
</table>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::denySite()"></a><div class="method">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">denySite</span><span class="nb-faded-text">(
string $root
)
</span>
:
bool</code><div class="description"><p class="short_description">Prohibit consumer with given root URL to authenticate current logged
in user. Returns true on success and false on error.</p></div>
<div class="code-tabs">
<div class="long-description">
</div>
<strong>Parameters</strong><table class="argument-info">
<thead><tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<th>$root</th>
<td>string</td>
<td><em>root URL</em></td>
</tr>
</table>
<strong>Returns</strong><table class="argument-info">
<thead><tr>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<td>bool</td>
<td></td>
</tr>
</table>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::getLoggedInUser()"></a><div class="method">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getLoggedInUser</span><span class="nb-faded-text">(
)
</span>
:
mixed</code><div class="description"><p class="short_description">Returns identity URL of current logged in user or false</p></div>
<div class="code-tabs">
<div class="long-description">
</div>
<strong>Returns</strong><table class="argument-info">
<thead><tr>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<td>mixed</td>
<td></td>
</tr>
</table>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::getSiteRoot()"></a><div class="method">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getSiteRoot</span><span class="nb-faded-text">(
array $params
)
</span>
:
mixed</code><div class="description"><p class="short_description">Retrieve consumer's root URL from request query.</p></div>
<div class="code-tabs">
<div class="long-description"><p>Returns URL or false in case of failure</p>
</div>
<strong>Parameters</strong><table class="argument-info">
<thead><tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<th>$params</th>
<td>array</td>
<td><em>query arguments</em></td>
</tr>
</table>
<strong>Returns</strong><table class="argument-info">
<thead><tr>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<td>mixed</td>
<td></td>
</tr>
</table>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::getTrustedSites()"></a><div class="method">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getTrustedSites</span><span class="nb-faded-text">(
)
</span>
:
mixed</code><div class="description"><p class="short_description">Returns list of known consumers for current logged in user or false
if he is not logged in.</p></div>
<div class="code-tabs">
<div class="long-description">
</div>
<strong>Returns</strong><table class="argument-info">
<thead><tr>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<td>mixed</td>
<td></td>
</tr>
</table>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::handle()"></a><div class="method">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">handle</span><span class="nb-faded-text">(
array $params
=
null, mixed $extensions
=
null, <a href="db_Controller_Response_Abstract.html#%5CZend_Controller_Response_Abstract">\Zend_Controller_Response_Abstract</a> $response
=
null
)
</span>
:
mixed</code><div class="description"><p class="short_description">Handles HTTP request from consumer</p></div>
<div class="code-tabs">
<div class="long-description">
</div>
<strong>Parameters</strong><table class="argument-info">
<thead><tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<th>$params</th>
<td>array</td>
<td><em><p>GET or POST variables. If this parameter is omited or set to null, then $_GET or $_POST superglobal variable is used according to REQUEST_METHOD.</p>
</em></td>
</tr>
<tr>
<th>$extensions</th>
<td>mixed</td>
<td><em>extension object or array of extensions objects</em></td>
</tr>
<tr>
<th>$response</th>
<td><a href="db_Controller_Response_Abstract.html#%5CZend_Controller_Response_Abstract">\Zend_Controller_Response_Abstract</a></td>
<td><em>an optional response object to perform HTTP or HTML form redirection</em></td>
</tr>
</table>
<strong>Returns</strong><table class="argument-info">
<thead><tr>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<td>mixed</td>
<td></td>
</tr>
</table>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::hasUser()"></a><div class="method">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">hasUser</span><span class="nb-faded-text">(
string $id
)
</span>
:
bool</code><div class="description"><p class="short_description">Returns true if user with given $id exists and false otherwise</p></div>
<div class="code-tabs">
<div class="long-description">
</div>
<strong>Parameters</strong><table class="argument-info">
<thead><tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<th>$id</th>
<td>string</td>
<td><em>user identity URL</em></td>
</tr>
</table>
<strong>Returns</strong><table class="argument-info">
<thead><tr>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<td>bool</td>
<td></td>
</tr>
</table>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::login()"></a><div class="method">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">login</span><span class="nb-faded-text">(
string $id, string $password
)
</span>
:
bool</code><div class="description"><p class="short_description">Performs login of user with given $id and $password
Returns true in case of success and false otherwise</p></div>
<div class="code-tabs">
<div class="long-description">
</div>
<strong>Parameters</strong><table class="argument-info">
<thead><tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<th>$id</th>
<td>string</td>
<td><em>user identity URL</em></td>
</tr>
<tr>
<th>$password</th>
<td>string</td>
<td><em>user password</em></td>
</tr>
</table>
<strong>Returns</strong><table class="argument-info">
<thead><tr>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<td>bool</td>
<td></td>
</tr>
</table>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::logout()"></a><div class="method">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">logout</span><span class="nb-faded-text">(
)
</span>
:
void</code><div class="description"><p class="short_description">Performs logout. Clears information about logged in user.</p></div>
<div class="code-tabs"><div class="long-description">
</div></div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::register()"></a><div class="method">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">register</span><span class="nb-faded-text">(
string $id, string $password
)
</span>
:
bool</code><div class="description"><p class="short_description">Registers a new user with given $id and $password
Returns true in case of success and false if user with given $id already
exists</p></div>
<div class="code-tabs">
<div class="long-description">
</div>
<strong>Parameters</strong><table class="argument-info">
<thead><tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<th>$id</th>
<td>string</td>
<td><em>user identity URL</em></td>
</tr>
<tr>
<th>$password</th>
<td>string</td>
<td><em>encoded user password</em></td>
</tr>
</table>
<strong>Returns</strong><table class="argument-info">
<thead><tr>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<td>bool</td>
<td></td>
</tr>
</table>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::respondToConsumer()"></a><div class="method">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">respondToConsumer</span><span class="nb-faded-text">(
array $params, mixed $extensions
=
null, <a href="db_Controller_Response_Abstract.html#%5CZend_Controller_Response_Abstract">\Zend_Controller_Response_Abstract</a> $response
=
null
)
</span>
:
bool</code><div class="description"><p class="short_description">Perepares information to send back to consumer's authentication request,
signs it using shared secret and send back through HTTP redirection</p></div>
<div class="code-tabs">
<div class="long-description">
</div>
<strong>Parameters</strong><table class="argument-info">
<thead><tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<th>$params</th>
<td>array</td>
<td><em>GET or POST request variables</em></td>
</tr>
<tr>
<th>$extensions</th>
<td>mixed</td>
<td><em>extension object or array of extensions objects</em></td>
</tr>
<tr>
<th>$response</th>
<td><a href="db_Controller_Response_Abstract.html#%5CZend_Controller_Response_Abstract">\Zend_Controller_Response_Abstract</a></td>
<td><em>an optional response object to perform HTTP or HTML form redirection</em></td>
</tr>
</table>
<strong>Returns</strong><table class="argument-info">
<thead><tr>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<td>bool</td>
<td></td>
</tr>
</table>
</div>
<div class="clear"></div>
</div>
<a id="\Zend_OpenId_Provider::setOpEndpoint()"></a><div class="method">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setOpEndpoint</span><span class="nb-faded-text">(
string $url
)
</span>
:
null</code><div class="description"><p class="short_description">Sets the OP Endpoint URL</p></div>
<div class="code-tabs">
<div class="long-description">
</div>
<strong>Parameters</strong><table class="argument-info">
<thead><tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<th>$url</th>
<td>string</td>
<td><em>the OP Endpoint URL</em></td>
</tr>
</table>
<strong>Returns</strong><table class="argument-info">
<thead><tr>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<td>null</td>
<td></td>
</tr>
</table>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</div>
<small xmlns="" class="footer">Documentation was generated by <a href="http://docblox-project.org">DocBlox 0.13.3</a>.
</small></body></html>
|
wukchung/Home-development
|
documentation/api/core/db_OpenId_Provider.html
|
HTML
|
bsd-3-clause
| 35,567 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ZendTest\Form\View\Helper\Captcha;
use DirectoryIterator;
use Zend\Captcha\Image as ImageCaptcha;
use Zend\Form\Element\Captcha as CaptchaElement;
use Zend\Form\View\Helper\Captcha\Image as ImageCaptchaHelper;
use ZendTest\Form\View\Helper\CommonTestCase;
class ImageTest extends CommonTestCase
{
protected $tmpDir;
protected $testDir;
public function setUp()
{
if (! extension_loaded('gd')) {
$this->markTestSkipped('The GD extension is not available.');
return;
}
if (! function_exists("imagepng")) {
$this->markTestSkipped("Image CAPTCHA requires PNG support");
}
if (! function_exists("imageftbbox")) {
$this->markTestSkipped("Image CAPTCHA requires FT fonts support");
}
if (! class_exists(ImageCaptcha::class)) {
$this->markTestSkipped(
'zend-captcha-related tests are skipped until the component '
. 'is forwards-compatible with zend-servicemanager v3'
);
}
$this->testDir = $this->getTmpDir() . '/ZF_test_images';
if (! is_dir($this->testDir)) {
@mkdir($this->testDir);
}
$this->helper = new ImageCaptchaHelper();
$this->captcha = new ImageCaptcha([
'imgDir' => $this->testDir,
'font' => __DIR__. '/_files/Vera.ttf',
]);
parent::setUp();
}
/**
* Tears down the fixture, for example, close a network connection.
* This method is called after a test is executed.
*
* @return void
*/
public function tearDown()
{
// remove captcha images
if (! isset($this->testDir)) {
parent::tearDown();
return;
}
foreach (new DirectoryIterator($this->testDir) as $file) {
if (! $file->isDot() && ! $file->isDir()) {
unlink($file->getPathname());
}
}
parent::tearDown();
}
/**
* Determine system TMP directory
*
* @return string
* @throws Zend_File_Transfer_Exception if unable to determine directory
*/
protected function getTmpDir()
{
if (null === $this->tmpDir) {
$this->tmpDir = sys_get_temp_dir();
}
return $this->tmpDir;
}
public function getElement()
{
$element = new CaptchaElement('foo');
$element->setCaptcha($this->captcha);
return $element;
}
public function testMissingCaptchaAttributeThrowsDomainException()
{
$element = new CaptchaElement('foo');
$this->setExpectedException('Zend\Form\Exception\DomainException');
$this->helper->render($element);
}
public function testRendersHiddenInputForId()
{
$element = $this->getElement();
$markup = $this->helper->render($element);
$this->assertRegExp('#(name="' . $element->getName() . '\&\#x5B\;id\&\#x5D\;").*?(type="hidden")#', $markup);
$this->assertRegExp(
'#(name="' . $element->getName() . '\&\#x5B\;id\&\#x5D\;").*?(value="' . $this->captcha->getId() . '")#',
$markup
);
}
public function testRendersTextInputForInput()
{
$element = $this->getElement();
$markup = $this->helper->render($element);
$this->assertRegExp('#(name="' . $element->getName() . '\&\#x5B\;input\&\#x5D\;").*?(type="text")#', $markup);
}
public function testRendersImageTagPriorToInputByDefault()
{
$element = $this->getElement();
$markup = $this->helper->render($element);
$this->assertRegexp('#<img[^>]+><input#', $markup);
}
public function testCanRenderImageTagFollowingInput()
{
$this->helper->setCaptchaPosition('prepend');
$element = $this->getElement();
$markup = $this->helper->render($element);
$this->assertRegexp('#<input[^>]+><img#', $markup);
}
}
|
akrabat/zend-form
|
test/View/Helper/Captcha/ImageTest.php
|
PHP
|
bsd-3-clause
| 4,318 |
#!/usr/bin/env perl
use strict;
use warnings;
use Carp;
use FindBin;
use lib ("$FindBin::RealBin/../../PerlLib");
use Fasta_reader;
use Nuc_translator;
use Getopt::Long qw(:config no_ignore_case bundling pass_through);
use Cwd;
my $usage = <<__EOUSAGE__;
##################################################################
#
# Required:
#
# --transcripts <string> file containing target transcripts in fasta format
#
# Optional:
#
# --read_length <int> default: 76
#
# --frag_length <int> default: 300
#
# --out_prefix <string> default: 'reads'
#
# --depth_of_cov <int> default: 100 (100x targeted base coverage)
#
# --SS_lib_type <string> RF or FR
#
#################################################################
__EOUSAGE__
;
my $require_proper_pairs_flag = 0;
my $transcripts;
my $read_length = 76;
my $spacing = 1;
my $frag_length = 300;
my $help_flag;
my $out_prefix = "reads";
my $depth_of_cov = 100;
my $SS_lib_type = "";
&GetOptions ( 'h' => \$help_flag,
'transcripts=s' => \$transcripts,
'read_length=i' => \$read_length,
'frag_length=i' => \$frag_length,
'out_prefix=s' => \$out_prefix,
'depth_of_cov=i' => \$depth_of_cov,
'SS_lib_type=s' => \$SS_lib_type,
);
if (@ARGV) {
die "Error, dont understand params: @ARGV";
}
if ($help_flag) {
die $usage;
}
unless ($transcripts) {
die $usage;
}
unless ($out_prefix =~ /^\//) {
$out_prefix = cwd() . "/$out_prefix";
}
main: {
my $number_reads = &estimate_total_read_count($transcripts, $depth_of_cov, $read_length);
my $cmd = "wgsim-trans -N $number_reads -1 $read_length -2 $read_length "
. " -d $frag_length "
. " -r 0 "
. " -e 0 "
;
my $token = "wgsim_R${read_length}_F${frag_length}_D${depth_of_cov}";
if ($SS_lib_type) {
$token .= "_${SS_lib_type}";
if ($SS_lib_type eq 'FR') {
$cmd .= " -Z 1 ";
}
elsif ($SS_lib_type eq 'RF') {
$cmd .= " -Z 2 ";
}
else {
die "Error, don't recognize SS_lib_type: [$SS_lib_type] ";
}
}
my $left_prefix = "$out_prefix.$token.left";
my $right_prefix = "$out_prefix.$token.right";
$cmd .= " $transcripts $left_prefix.fq $right_prefix.fq";
&process_cmd($cmd);
# convert to fasta format
&process_cmd("$FindBin::Bin/../support_scripts/fastQ_to_fastA.pl -I $left_prefix.fq > $left_prefix.fa");
&process_cmd("$FindBin::Bin/../support_scripts/fastQ_to_fastA.pl -I $right_prefix.fq > $right_prefix.fa");
unlink("$left_prefix.fq", "$right_prefix.fq");
open(my $ofh, ">$out_prefix.$token.info") or die "Error, cannot write to file: $out_prefix.$token.info";
print $ofh join("\t", $transcripts, "$left_prefix.fa", "$right_prefix.fa");
close $ofh;
exit(0);
}
####
sub estimate_total_read_count {
my ($transcripts_fasta_file, $depth_of_cov, $read_length) = @_;
my $sum_seq_length = 0;
my $fasta_reader = new Fasta_reader($transcripts);
while (my $seq_obj = $fasta_reader->next()) {
my $sequence = $seq_obj->get_sequence();
$sum_seq_length += length($sequence);
}
# DOC = num_reads * read_length * 2 / seq_length
# so,
# num_reads = DOC * seq_length / 2 / read_length
my $num_reads = $depth_of_cov * $sum_seq_length / 2 / $read_length;
$num_reads = int($num_reads + 0.5);
return($num_reads);
}
####
sub process_cmd {
my ($cmd) = @_;
print STDERR "CMD: $cmd\n";
my $ret = system($cmd);
if ($ret) {
die "Error, cmd: $cmd died with ret $ret";
}
return;
}
|
g1o/trinityrnaseq
|
util/misc/simulate_illuminaPE_from_transcripts.wgsim.pl
|
Perl
|
bsd-3-clause
| 3,786 |
from semver import Version
class SemVerWithVPrefix(Version):
"""
A subclass of Version which allows a "v" prefix
"""
@classmethod
def parse(cls, version: str) -> "SemVerWithVPrefix":
"""
Parse version string to a Version instance.
:param version: version string with "v" or "V" prefix
:raises ValueError: when version does not start with "v" or "V"
:return: a new instance
"""
if not version[0] in ("v", "V"):
raise ValueError(
"{v!r}: not a valid semantic version tag. Must start with 'v' or 'V'".format(
v=version
)
)
return super().parse(version[1:])
def __str__(self) -> str:
# Reconstruct the tag
return "v" + super().__str__()
|
k-bx/python-semver
|
docs/semverwithvprefix.py
|
Python
|
bsd-3-clause
| 818 |
/* Definitions of target machine for GNU compiler, for HPs running
HPUX using the 64bit runtime model.
Copyright (C) 1999, 2000, 2001, 2002, 2004, 2005 Free Software Foundation,
Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GCC 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING. If not, write to
the Free Software Foundation, 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA. */
/* We can debug dynamically linked executables on hpux11; we also
want dereferencing of a NULL pointer to cause a SEGV. Do not move
the "+Accept TypeMismatch" switch. We check for it in collect2
to determine which init/fini is needed. */
#undef LINK_SPEC
#if ((TARGET_DEFAULT | TARGET_CPU_DEFAULT) & MASK_GNU_LD)
#define LINK_SPEC \
"%{!shared:%{p:-L/lib/pa20_64/libp -L/usr/lib/pa20_64/libp %{!static:\
%nWarning: consider linking with `-static' as system libraries with\n\
%n profiling support are only provided in archive format}}}\
%{!shared:%{pg:-L/lib/pa20_64/libp -L/usr/lib/pa20_64/libp %{!static:\
%nWarning: consider linking with `-static' as system libraries with\n\
%n profiling support are only provided in archive format}}}\
%{mhp-ld:+Accept TypeMismatch -z} -E %{mlinker-opt:-O}\
%{!shared:-u main %{!nostdlib:%{!nodefaultlibs:-u __cxa_finalize}}}\
%{static:-a archive} %{shared:%{mhp-ld:-b}%{!mhp-ld:-shared}}"
#else
#define LINK_SPEC \
"%{!shared:%{p:-L/lib/pa20_64/libp -L/usr/lib/pa20_64/libp %{!static:\
%nWarning: consider linking with `-static' as system libraries with\n\
%n profiling support are only provided in archive format}}}\
%{!shared:%{pg:-L/lib/pa20_64/libp -L/usr/lib/pa20_64/libp %{!static:\
%nWarning: consider linking with `-static' as system libraries with\n\
%n profiling support are only provided in archive format}}}\
%{!mgnu-ld:+Accept TypeMismatch -z} -E %{mlinker-opt:-O}\
%{!shared:-u main %{!nostdlib:%{!nodefaultlibs:-u __cxa_finalize}}}\
%{static:-a archive} %{shared:%{mgnu-ld:-shared}%{!mgnu-ld:-b}}"
#endif
/* Profiling support is only provided in libc.a. However, libprof and
libgprof are only available in shared form on HP-UX 11.00. We use
the shared form if we are using the GNU linker or an archive form
isn't available. We also usually need to link with libdld and it's
only available in shared form. */
#undef LIB_SPEC
#if ((TARGET_DEFAULT | TARGET_CPU_DEFAULT) & MASK_GNU_LD)
#define LIB_SPEC \
"%{!shared:\
%{!p:%{!pg: %{static|mt|pthread:-lpthread} -lc\
%{static:%{!nolibdld:-a shared -ldld -a archive -lc}}}}\
%{p:%{!pg:%{static:%{!mhp-ld:-a shared}%{mhp-ld:-a archive_shared}}\
-lprof %{static:-a archive} %{static|mt|pthread:-lpthread} -lc\
%{static:%{!nolibdld:-a shared -ldld -a archive -lc}}}}\
%{pg:%{static:%{!mhp-ld:-a shared}%{mhp-ld:-a archive_shared}}\
-lgprof %{static:-a archive} %{static|mt|pthread:-lpthread} -lc\
%{static:%{!nolibdld:-a shared -ldld -a archive -lc}}}}"
#else
#define LIB_SPEC \
"%{!shared:\
%{!p:%{!pg: %{static|mt|pthread:-lpthread} -lc\
%{static:%{!nolibdld:-a shared -ldld -a archive -lc}}}}\
%{p:%{!pg:%{static:%{mgnu-ld:-a shared}%{!mgnu-ld:-a archive_shared}}\
-lprof %{static:-a archive} %{static|mt|pthread:-lpthread} -lc\
%{static:%{!nolibdld:-a shared -ldld -a archive -lc}}}}\
%{pg:%{static:%{mgnu-ld:-a shared}%{!mgnu-ld:-a archive_shared}}\
-lgprof %{static:-a archive} %{static|mt|pthread:-lpthread} -lc\
%{static:%{!nolibdld:-a shared -ldld -a archive -lc}}}}"
#endif
/* The libgcc_stub.a and milli.a libraries need to come last. */
#undef LINK_GCC_C_SEQUENCE_SPEC
#define LINK_GCC_C_SEQUENCE_SPEC "\
%G %L %G %{!nostdlib:%{!nodefaultlibs:%{!shared:-lgcc_stub}\
/usr/lib/pa20_64/milli.a}}"
/* Under hpux11, the normal location of the `ld' and `as' programs is the
/usr/ccs/bin directory. */
#ifndef CROSS_COMPILE
#undef MD_EXEC_PREFIX
#define MD_EXEC_PREFIX "/usr/ccs/bin"
#endif
/* Default prefixes. */
#undef STANDARD_STARTFILE_PREFIX_1
#define STANDARD_STARTFILE_PREFIX_1 "/lib/pa20_64/"
#undef STANDARD_STARTFILE_PREFIX_2
#define STANDARD_STARTFILE_PREFIX_2 "/usr/lib/pa20_64/"
/* Under hpux11 the normal location of the various pa20_64 *crt*.o files
is the /usr/ccs/lib/pa20_64 directory. Some files may also be in the
/opt/langtools/lib/pa20_64 directory. */
#ifndef CROSS_COMPILE
#undef MD_STARTFILE_PREFIX
#define MD_STARTFILE_PREFIX "/usr/ccs/lib/pa20_64/"
#endif
#ifndef CROSS_COMPILE
#undef MD_STARTFILE_PREFIX_1
#define MD_STARTFILE_PREFIX_1 "/opt/langtools/lib/pa20_64/"
#endif
/* This macro specifies the biggest alignment supported by the object
file format of this machine.
The .align directive in the HP assembler allows alignments up to
4096 bytes. However, the maximum alignment of a global common symbol
is 16 bytes using HP ld. Unfortunately, this macro doesn't provide
a method to check for common symbols. */
#undef MAX_OFILE_ALIGNMENT
#define MAX_OFILE_ALIGNMENT 32768
/* Due to limitations in the target structure, it isn't currently possible
to dynamically switch between the GNU and HP assemblers. */
#undef TARGET_GAS
/* Configure selects the standard ELFOS defines for use with GAS. */
#ifdef USING_ELFOS_H
/* We are using GAS. */
#define TARGET_GAS 1
#undef TARGET_ASM_FILE_START
#define TARGET_ASM_FILE_START pa_hpux64_gas_file_start
/* This is how we output a null terminated string. */
#undef STRING_ASM_OP
#define STRING_ASM_OP "\t.stringz\t"
#define TEXT_SECTION_ASM_OP "\t.text"
#define DATA_SECTION_ASM_OP "\t.data"
#define BSS_SECTION_ASM_OP "\t.section\t.bss"
#define JCR_SECTION_NAME ".jcr"
#define HP_INIT_ARRAY_SECTION_ASM_OP "\t.section\t.init"
#define GNU_INIT_ARRAY_SECTION_ASM_OP "\t.section\t.init_array"
#define HP_FINI_ARRAY_SECTION_ASM_OP "\t.section\t.fini"
#define GNU_FINI_ARRAY_SECTION_ASM_OP "\t.section\t.fini_array"
/* We need to override the following two macros defined in elfos.h since
the .comm directive has a different syntax and it can't be used for
local common symbols. */
#undef ASM_OUTPUT_ALIGNED_COMMON
#define ASM_OUTPUT_ALIGNED_COMMON(FILE, NAME, SIZE, ALIGN) \
pa_asm_output_aligned_common (FILE, NAME, SIZE, ALIGN)
#undef ASM_OUTPUT_ALIGNED_LOCAL
#define ASM_OUTPUT_ALIGNED_LOCAL(FILE, NAME, SIZE, ALIGN) \
pa_asm_output_aligned_local (FILE, NAME, SIZE, ALIGN)
/* The define in pa.h doesn't work with the alias attribute. The
default is ok with the following define for GLOBAL_ASM_OP. */
#undef TARGET_ASM_GLOBALIZE_LABEL
/* This is how we globalize a label. */
#define GLOBAL_ASM_OP "\t.globl\t"
/* Hacked version from defaults.h that uses assemble_name_raw
instead of assemble_name. A symbol in a type directive that
isn't otherwise referenced doesn't cause the symbol to be
placed in the symbol table of the assembled object. */
#undef ASM_OUTPUT_TYPE_DIRECTIVE
#define ASM_OUTPUT_TYPE_DIRECTIVE(STREAM, NAME, TYPE) \
do { \
fputs (TYPE_ASM_OP, STREAM); \
assemble_name_raw (STREAM, NAME); \
fputs (", ", STREAM); \
fprintf (STREAM, TYPE_OPERAND_FMT, TYPE); \
putc ('\n', STREAM); \
} while (0)
/* Hacked version from elfos.h that doesn't output a label. */
#undef ASM_DECLARE_FUNCTION_NAME
#define ASM_DECLARE_FUNCTION_NAME(FILE, NAME, DECL) \
do { \
ASM_OUTPUT_TYPE_DIRECTIVE (FILE, NAME, "function"); \
ASM_DECLARE_RESULT (FILE, DECL_RESULT (DECL)); \
} while (0)
/* The type of external references must be set correctly for the
dynamic loader to work correctly. This is equivalent to the
HP assembler's .IMPORT directive but relates more directly to
ELF object file types. */
#define ASM_OUTPUT_EXTERNAL(FILE, DECL, NAME) \
pa_hpux_asm_output_external ((FILE), (DECL), (NAME))
#define ASM_OUTPUT_EXTERNAL_REAL(FILE, DECL, NAME) \
do { \
if (FUNCTION_NAME_P (NAME)) \
ASM_OUTPUT_TYPE_DIRECTIVE (FILE, NAME, "function"); \
else \
ASM_OUTPUT_TYPE_DIRECTIVE (FILE, NAME, "object"); \
} while (0)
/* We need set the type for external libcalls. Also note that not all
libcall names are passed to targetm.encode_section_info (e.g., __main).
Thus, we also have to do the section encoding if it hasn't been done
already. */
#undef ASM_OUTPUT_EXTERNAL_LIBCALL
#define ASM_OUTPUT_EXTERNAL_LIBCALL(FILE, FUN) \
do { \
if (!FUNCTION_NAME_P (XSTR (FUN, 0))) \
hppa_encode_label (FUN); \
ASM_OUTPUT_TYPE_DIRECTIVE (FILE, XSTR (FUN, 0), "function"); \
} while (0)
/* We need to use the HP style for internal labels. */
#undef ASM_GENERATE_INTERNAL_LABEL
#define ASM_GENERATE_INTERNAL_LABEL(LABEL, PREFIX, NUM) \
sprintf (LABEL, "*%c$%s%04ld", (PREFIX)[0], (PREFIX) + 1, (long)(NUM))
#else /* USING_ELFOS_H */
/* We are not using GAS. */
#define TARGET_GAS 0
/* HPUX 11 has the "new" HP assembler. It's still lousy, but it's a whole
lot better than the assembler shipped with older versions of hpux.
However, it doesn't support weak symbols and is a bad fit with ELF. */
#undef NEW_HP_ASSEMBLER
#define NEW_HP_ASSEMBLER 1
/* It looks like DWARF2 will be the easiest debug format to handle on this
platform. */
#define DWARF2_DEBUGGING_INFO 1
#define PREFERRED_DEBUGGING_TYPE DWARF2_DEBUG
/* This target uses the ELF object file format. */
#define OBJECT_FORMAT_ELF
#undef TARGET_ASM_FILE_START
#define TARGET_ASM_FILE_START pa_hpux64_hpas_file_start
#undef TEXT_SECTION_ASM_OP
#define TEXT_SECTION_ASM_OP "\t.SUBSPA $CODE$\n"
#undef READONLY_DATA_SECTION_ASM_OP
#define READONLY_DATA_SECTION_ASM_OP "\t.SUBSPA $LIT$\n"
#undef DATA_SECTION_ASM_OP
#define DATA_SECTION_ASM_OP "\t.SUBSPA $DATA$\n"
#undef BSS_SECTION_ASM_OP
#define BSS_SECTION_ASM_OP "\t.SUBSPA $BSS$\n"
/* We provide explicit defines for CTORS_SECTION_ASM_OP and
DTORS_SECTION_ASM_OP since we don't yet have support for
named sections with the HP assembler. */
#undef CTORS_SECTION_ASM_OP
#define CTORS_SECTION_ASM_OP "\t.SUBSPA \\.ctors,QUAD=1,ALIGN=8,ACCESS=31"
#undef DTORS_SECTION_ASM_OP
#define DTORS_SECTION_ASM_OP "\t.SUBSPA \\.dtors,QUAD=1,ALIGN=8,ACCESS=31"
#define HP_INIT_ARRAY_SECTION_ASM_OP \
"\t.SUBSPA \\.init,QUAD=1,ALIGN=8,ACCESS=31"
#define GNU_INIT_ARRAY_SECTION_ASM_OP \
"\t.SUBSPA \\.init_array,QUAD=1,ALIGN=8,ACCESS=31"
#define HP_FINI_ARRAY_SECTION_ASM_OP \
"\t.SUBSPA \\.fini,QUAD=1,ALIGN=8,ACCESS=31"
#define GNU_FINI_ARRAY_SECTION_ASM_OP \
"\t.SUBSPA \\.fini_array,QUAD=1,ALIGN=8,ACCESS=31"
#endif /* USING_ELFOS_H */
/* The following defines, used to run constructors and destructors with
the SOM linker under HP-UX 11, are not needed. */
#undef HAS_INIT_SECTION
#undef LD_INIT_SWITCH
#undef LD_FINI_SWITCH
/* The following STARTFILE_SPEC and ENDFILE_SPEC defines provide the
magic needed to run initializers and finalizers. */
#undef STARTFILE_SPEC
#if TARGET_HPUX_11_11
#define STARTFILE_SPEC \
"%{!shared: %{!symbolic: crt0%O%s} %{munix=95:unix95.o%s} \
%{!munix=93:%{!munix=95:unix98%O%s}}} %{static:crtbeginT%O%s} \
%{!static:%{!shared:crtbegin%O%s} %{shared:crtbeginS%O%s}}"
#else
#define STARTFILE_SPEC \
"%{!shared: %{!symbolic: crt0%O%s} %{munix=95:unix95%O%s}} \
%{static:crtbeginT%O%s} %{!static:%{!shared:crtbegin%O%s} \
%{shared:crtbeginS%O%s}}"
#endif
#undef ENDFILE_SPEC
#define ENDFILE_SPEC "%{!shared:crtend%O%s} %{shared:crtendS%O%s}"
/* Since HP uses the .init and .fini sections for array initializers
and finalizers, we need different defines for INIT_SECTION_ASM_OP
and FINI_SECTION_ASM_OP. With the implementation adopted below,
the sections are not actually used. However, we still must provide
defines to select the proper code path. */
#undef INIT_SECTION_ASM_OP
#define INIT_SECTION_ASM_OP
#undef FINI_SECTION_ASM_OP
#define FINI_SECTION_ASM_OP
/* We are using array initializers and don't want calls in the INIT
and FINI sections. */
#undef CRT_CALL_STATIC_FUNCTION
#define CRT_CALL_STATIC_FUNCTION(SECTION_OP, FUNC)
/* The init_priority attribute is not supported with HP ld. This could be
supported if collect2 was used with LD_INIT_SWITCH. Unfortunately, this
approach doesn't work with GNU ld since HP-UX doesn't support DT_INIT,
and therefore the -init and -fini GNU ld switches. */
#undef SUPPORTS_INIT_PRIORITY
#define SUPPORTS_INIT_PRIORITY (TARGET_GNU_LD ? 1 : 0)
/* We use DTOR_LIST_BEGIN to carry a bunch of hacks to allow us to use
the init and fini array sections with both the HP and GNU linkers.
The linkers setup the required dynamic entries in the dynamic segment
and the dynamic linker does the calls. This approach avoids using
collect2.
The first hack is to implement __do_global_ctors_aux in crtbegin as
it needs to be the first entry in the init array so that it is called
last. HP got the order of the init array backwards. The DT_INIT_ARRAY
is supposed to be executed in the same order as the addresses appear in
the array. DT_FINI_ARRAY is supposed to be executed in the opposite
order.
The second hack is a set of plabels to implement the effect of
CRT_CALL_STATIC_FUNCTION. HP-UX 11 only supports DI_INIT_ARRAY and
DT_FINI_ARRAY and they put the arrays in .init and .fini, rather than
in .init_array and .fini_array. The standard defines for .init and
.fini have the execute flag set. So, the assembler has to be hacked
to munge the standard flags for these sections to make them agree
with what the HP linker expects. With the GNU linker, we need to
used the .init_array and .fini_array sections. So, we set up for
both just in case. Once we have built the table, the linker does
the rest of the work.
The order is significant. Placing __do_global_ctors_aux first in
the list, results in it being called last. User specified initializers,
either using the linker +init command or a plabel, run before the
initializers specified here. */
/* We need to add frame_dummy to the initializer list if EH_FRAME_SECTION_NAME
or JCR_SECTION_NAME is defined. */
#if defined(EH_FRAME_SECTION_NAME) || defined(JCR_SECTION_NAME)
#define PA_INIT_FRAME_DUMMY_ASM_OP ".dword P%frame_dummy"
#else
#define PA_INIT_FRAME_DUMMY_ASM_OP ""
#endif
/* The following hack sets up the .init, .init_array, .fini and
.fini_array sections. */
#define PA_CRTBEGIN_HACK \
asm (TEXT_SECTION_ASM_OP); \
static void __attribute__((used)) \
__do_global_ctors_aux (void) \
{ \
func_ptr *p = __CTOR_LIST__; \
while (*(p + 1)) \
p++; \
for (; *p != (func_ptr) -1; p--) \
(*p) (); \
} \
\
asm (HP_INIT_ARRAY_SECTION_ASM_OP); \
asm (".align 8"); \
asm (".dword P%__do_global_ctors_aux"); \
asm (PA_INIT_FRAME_DUMMY_ASM_OP); \
asm (GNU_INIT_ARRAY_SECTION_ASM_OP); \
asm (".align 8"); \
asm (".dword P%__do_global_ctors_aux"); \
asm (PA_INIT_FRAME_DUMMY_ASM_OP); \
asm (HP_FINI_ARRAY_SECTION_ASM_OP); \
asm (".align 8"); \
asm (".dword P%__do_global_dtors_aux"); \
asm (GNU_FINI_ARRAY_SECTION_ASM_OP); \
asm (".align 8"); \
asm (".dword P%__do_global_dtors_aux")
/* The following two variants of DTOR_LIST_BEGIN are identical to those
in crtstuff.c except for the addition of the above crtbegin hack. */
#ifdef DTORS_SECTION_ASM_OP
#define DTOR_LIST_BEGIN \
asm (DTORS_SECTION_ASM_OP); \
STATIC func_ptr __DTOR_LIST__[1] \
__attribute__ ((aligned(sizeof(func_ptr)))) \
= { (func_ptr) (-1) }; \
PA_CRTBEGIN_HACK
#else
#define DTOR_LIST_BEGIN \
STATIC func_ptr __DTOR_LIST__[1] \
__attribute__ ((section(".dtors"), aligned(sizeof(func_ptr)))) \
= { (func_ptr) (-1) }; \
PA_CRTBEGIN_HACK
#endif
/* If using HP ld do not call pxdb. Use size as a program that does nothing
and returns 0. /bin/true cannot be used because it is a script without
an interpreter. */
#define INIT_ENVIRONMENT "LD_PXDB=/usr/ccs/bin/size"
/* The HPUX dynamic linker objects to undefined weak symbols, so do
not use them in gthr-posix.h. */
#define GTHREAD_USE_WEAK 0
/* We don't want undefined weak references to __register_frame_info,
__deregister_frame_info, _Jv_RegisterClasses and __cxa_finalize
introduced by crtbegin.o. The GNU linker only resolves weak
references if they appear in a shared library. Thus, it would be
impossible to create a static executable if the symbols were weak.
So, the best solution seems to be to make the symbols strong and
provide an archive library of empty stub functions. */
#define TARGET_ATTRIBUTE_WEAK
|
avaitla/Haskell-to-C---Bridge
|
gccxml/GCC/gcc/config/pa/pa64-hpux.h
|
C
|
bsd-3-clause
| 19,299 |
<?php $this->title = 'Статистика обращений'; ?>
<div class="container">
<h2 class="title_reg">Статистика обращений</h2>
<div class="alert alert-info" role="alert">В данный момент статистика пуста!</div>
<!-- <div class="demo">-->
<!-- <input class="hide" id="hd-1" type="checkbox">-->
<!-- <label for="hd-1">МВД России<span class="badge badge-info">24</span></label>-->
<!-- <div>-->
<!-- <table class="my-table">-->
<!-- <tr>-->
<!-- <td>Выдача, замена паспортов гражданина Российской Федерации, удостоверяющих личность гражданина Российской Федерации на территории Российской Федерации</td>-->
<!-- <td><span class="badge badge-static">8</span></td>-->
<!-- </tr>-->
<!-- <tr>-->
<!-- <td>Осуществление миграционного учета иностранных граждан и лиц без гражданства в Российской Федерации (в части приема уведомления о прибытии иностранного гражданина или лица без гражданства в место пребывания и проставления отметки о приеме уведомления)</td>-->
<!-- <td><span class="badge badge-static">2</span></td>-->
<!-- </tr>-->
<!-- <tr>-->
<!-- <td>Регистрационный учет граждан Российской Федерации по месту пребывания и по месту жительства в пределах Российской Федерации (в части приема и выдачи документов о регистрации и снятии граждан Российской Федерации с регистрационного учета по месту пребывания и по месту жительства в пределах Российской Федерации)</td>-->
<!-- <td><span class="badge badge-static">14</span></td>-->
<!-- </tr>-->
<!-- </table>-->
<!-- </div>-->
<!-- <input class="hide" id="hd-2" type="checkbox">-->
<!-- <label for="hd-2">Акционерное общество "Федеральная корпорация по развитию малого и среднего предпринимательства"<span class="badge badge-info">17</span></label>-->
<!-- <div>-->
<!-- <table class="my-table">-->
<!-- <tr>-->
<!-- <td>Услуга по подбору по заданным параметрам информации о недвижимом имуществе, включенном в перечни государственного и муниципального имущества, предусмотренные частью 4 статьи 18 Федерального закона от 24.07.2007 № 209-ФЗ, и свободном от прав третьих лиц</td>-->
<!-- <td><span class="badge badge-static">4</span></td>-->
<!-- </tr>-->
<!-- <tr>-->
<!-- <td>Услуга по предоставлению информации о формах и условиях финансовой поддержки субъектов МСП по заданным параметрам</td>-->
<!-- <td><span class="badge badge-static">2</span></td>-->
<!-- </tr>-->
<!-- <tr>-->
<!-- <td>Услуга по предоставлению по заданным параметрам информации об организации участия субъектов МСП в закупках товаров, работ, услуг, в том числе инновационной продукции, высокотехнологичной продукции, конкретных заказчиков, определенных Правительством РФ в соответствии с Федеральным законом от 18.07.2011 № 223-ФЗ «О закупках товаров, работ, услуг отдельными видами юридических лиц</td>-->
<!-- <td><span class="badge badge-static">1</span></td>-->
<!-- </tr>-->
<!-- <tr>-->
<!-- <td>Выдача разрешений на ввод в эксплуатацию объектов капитального строительства, возведенных на территориях двух и более муниципальных образований (муниципальных районов, городских округов), и реконструкцию объектов капитального строительства, расположенных на территориях двух и более муниципальных образований (муниципальных районов, городских округов)</td>-->
<!-- <td><span class="badge badge-static">4</span></td>-->
<!-- </tr>-->
<!-- <tr>-->
<!-- <td>Выдача разрешений на строительство объектов капитального строительства, планируемых на территориях двух и более муниципальных образований (муниципальных районов, городских округов), и реконструкцию объектов капитального строительства, расположенных на территориях двух и более муниципальных образований (муниципальных районов, городских округов)</td>-->
<!-- <td><span class="badge badge-static">6</span></td>-->
<!-- </tr>-->
<!-- </table>-->
<!-- </div>-->
<!-- </div>-->
</div>
|
Beginner95/mfc
|
modules/admin/views/journal/static.php
|
PHP
|
bsd-3-clause
| 6,406 |
package org.swistowski.vaulthelper.filters;
import org.swistowski.vaulthelper.models.Item;
import java.util.HashMap;
import java.util.LinkedHashMap;
/**
* Created by damian on 22.10.15.
*/
public abstract class BaseFilter {
abstract protected int[] getLabels();
abstract public boolean filter(Item item);
abstract public int getMenuLabel();
protected HashMap<Integer, Boolean> mFilters;
public BaseFilter(){
}
public HashMap<Integer, Boolean> getFilters(){
if(mFilters==null){
mFilters=new LinkedHashMap<>();
for(int label: getLabels()){
mFilters.put(label, Boolean.FALSE);
}
}
return mFilters;
}
}
|
DestinyVaultHelper/dvh
|
app/src/main/java/org/swistowski/vaulthelper/filters/BaseFilter.java
|
Java
|
bsd-3-clause
| 716 |
it("should check ng-options",function(){expect(element(by.binding("{selected_color:myColor}")).getText()).toMatch("red"),element.all(by.model("myColor")).first().click(),element.all(by.css('select[ng-model="myColor"] option')).first().click(),expect(element(by.binding("{selected_color:myColor}")).getText()).toMatch("black"),element(by.css('.nullable select[ng-model="myColor"]')).click(),element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click(),expect(element(by.binding("{selected_color:myColor}")).getText()).toMatch("null")});
//# sourceMappingURL=..\..\..\..\debug\angular\docs\examples\example-example48\protractor.min.map
|
infrabel/docs-gnap
|
node_modules/gnap-theme-gnap-angular/js/angular/docs/examples/example-example48/protractor.min.js
|
JavaScript
|
bsd-3-clause
| 655 |
<?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\grid\GridView;
/**
* @var yii\web\View $this
* @var yii\data\ActiveDataProvider $dataProvider
* @var app\models\search\WeighingSearch $searchModel
*/
$this->title = Yii::t('app', 'Weighings');
$this->params['breadcrumbs'][] = $this->title;
if (isset($actionColumnTemplates))
{
$actionColumnTemplate = implode(' ', $actionColumnTemplates);
$actionColumnTemplateString = $actionColumnTemplate;
}
else
{
Yii::$app->view->params['pageButtons'] = Html::a('<span class="glyphicon glyphicon-plus"></span> '.'New',
['create'], ['class' => 'btn btn-success']);
$actionColumnTemplateString = "{view} {update} {delete}";
}
?>
<div class="giiant-crud weighing-index">
<?php
\yii\widgets\Pjax::begin([
'id' => 'pjax-main',
'enableReplaceState' => false,
'linkSelector' => '#pjax-main ul.pagination a, th a',
'clientOptions' => ['pjax:success' => 'function(){alert("yo")}'],
])
?>
<h1>
<?= Yii::t('app', 'Weighings') ?>
<small>
List
</small>
</h1>
<div class="clearfix crud-navigation">
<div class="pull-left">
<?=
Html::a('<span class="glyphicon glyphicon-plus"></span> '.'New', ['create'], ['class' => 'btn btn-success'])
?>
</div>
<div class="pull-right">
<?=
\yii\bootstrap\ButtonDropdown::widget(
[
'id' => 'giiant-relations',
'encodeLabel' => false,
'label' => '<span class="glyphicon glyphicon-paperclip"></span> '.'Relations',
'dropdown' => [
'options' => [
'class' => 'dropdown-menu-right'
],
'encodeLabels' => false,
'items' => []
],
'options' => [
'class' => 'btn-default'
]
]
);
?> </div>
</div>
<hr />
<div class="table-responsive">
<?=
GridView::widget([
'layout' => '{summary}{pager}{items}{pager}',
'dataProvider' => $dataProvider,
'pager' => [
'class' => yii\widgets\LinkPager::className(),
'firstPageLabel' => 'First',
'lastPageLabel' => 'Last',
],
'filterModel' => $searchModel,
'tableOptions' => ['class' => 'table table-striped table-bordered table-hover'],
'headerRowOptions' => ['class' => 'x'],
'columns' => [
'job_order',
'container_number',
'grossmass',
//'gatein_grossmass',
//'gateout_grossmass',
'stack_datetime',
/* 'gatein_tracknumber', */
/* 'gateout_tracknumber', */
//'emkl_id',
'container_id',
[
'class' => 'yii\grid\ActionColumn',
'options' => [],
'template' => $actionColumnTemplateString,
'urlCreator' => function($action, $model, $key, $index)
{
// using the column name as key, not mapping to 'id' like the standard generator
$params = is_array($key) ? $key : [$model->primaryKey()[0] => (string) $key];
$params[0] = \Yii::$app->controller->id ? \Yii::$app->controller->id.'/'.$action : $action;
return Url::toRoute($params);
},
'contentOptions' => ['nowrap' => 'nowrap']
],
],
]);
?>
</div>
</div>
<?php \yii\widgets\Pjax::end() ?>
|
fredyns/shippingweight
|
views/weighing/index.php
|
PHP
|
bsd-3-clause
| 4,065 |
/*
* Copyright (c) 2001 Ian Dowse. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD: src/sys/ufs/ufs/ufs_dirhash.c,v 1.13 2002/06/30 02:49:39 iedowse Exp $
*/
/*
* This implements a hash-based lookup scheme for UFS directories.
*/
#include "opt_ufs.h"
#ifdef UFS_DIRHASH
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/lock.h>
#include <sys/mutex.h>
#include <sys/malloc.h>
#include <sys/fnv_hash.h>
#include <sys/proc.h>
#include <sys/bio.h>
#include <sys/buf.h>
#include <sys/vnode.h>
#include <sys/mount.h>
#include <sys/sysctl.h>
#include <vm/uma.h>
#include <ufs/ufs/quota.h>
#include <ufs/ufs/inode.h>
#include <ufs/ufs/dir.h>
#include <ufs/ufs/dirhash.h>
#include <ufs/ufs/extattr.h>
#include <ufs/ufs/ufsmount.h>
#include <ufs/ufs/ufs_extern.h>
#define WRAPINCR(val, limit) (((val) + 1 == (limit)) ? 0 : ((val) + 1))
#define WRAPDECR(val, limit) (((val) == 0) ? ((limit) - 1) : ((val) - 1))
#define OFSFMT(vp) ((vp)->v_mount->mnt_maxsymlinklen <= 0)
#define BLKFREE2IDX(n) ((n) > DH_NFSTATS ? DH_NFSTATS : (n))
static MALLOC_DEFINE(M_DIRHASH, "UFS dirhash", "UFS directory hash tables");
SYSCTL_NODE(_vfs, OID_AUTO, ufs, CTLFLAG_RD, 0, "UFS filesystem");
static int ufs_mindirhashsize = DIRBLKSIZ * 5;
SYSCTL_INT(_vfs_ufs, OID_AUTO, dirhash_minsize, CTLFLAG_RW,
&ufs_mindirhashsize,
0, "minimum directory size in bytes for which to use hashed lookup");
static int ufs_dirhashmaxmem = 2 * 1024 * 1024;
SYSCTL_INT(_vfs_ufs, OID_AUTO, dirhash_maxmem, CTLFLAG_RW, &ufs_dirhashmaxmem,
0, "maximum allowed dirhash memory usage");
static int ufs_dirhashmem;
SYSCTL_INT(_vfs_ufs, OID_AUTO, dirhash_mem, CTLFLAG_RD, &ufs_dirhashmem,
0, "current dirhash memory usage");
static int ufs_dirhashcheck = 0;
SYSCTL_INT(_vfs_ufs, OID_AUTO, dirhash_docheck, CTLFLAG_RW, &ufs_dirhashcheck,
0, "enable extra sanity tests");
static int ufsdirhash_hash(struct dirhash *dh, char *name, int namelen);
static void ufsdirhash_adjfree(struct dirhash *dh, doff_t offset, int diff);
static void ufsdirhash_delslot(struct dirhash *dh, int slot);
static int ufsdirhash_findslot(struct dirhash *dh, char *name, int namelen,
doff_t offset);
static doff_t ufsdirhash_getprev(struct direct *dp, doff_t offset);
static int ufsdirhash_recycle(int wanted);
static uma_zone_t ufsdirhash_zone;
/* Dirhash list; recently-used entries are near the tail. */
static TAILQ_HEAD(, dirhash) ufsdirhash_list;
/* Protects: ufsdirhash_list, `dh_list' field, ufs_dirhashmem. */
static struct mtx ufsdirhash_mtx;
/*
* Locking order:
* ufsdirhash_mtx
* dh_mtx
*
* The dh_mtx mutex should be aquired either via the inode lock, or via
* ufsdirhash_mtx. Only the owner of the inode may free the associated
* dirhash, but anything can steal its memory and set dh_hash to NULL.
*/
/*
* Attempt to build up a hash table for the directory contents in
* inode 'ip'. Returns 0 on success, or -1 of the operation failed.
*/
int
ufsdirhash_build(struct inode *ip)
{
struct dirhash *dh;
struct buf *bp = NULL;
struct direct *ep;
struct vnode *vp;
doff_t bmask, pos;
int dirblocks, i, j, memreqd, nblocks, narrays, nslots, slot;
/* Check if we can/should use dirhash. */
if (ip->i_dirhash == NULL) {
if (ip->i_size < ufs_mindirhashsize || OFSFMT(ip->i_vnode))
return (-1);
} else {
/* Hash exists, but sysctls could have changed. */
if (ip->i_size < ufs_mindirhashsize ||
ufs_dirhashmem > ufs_dirhashmaxmem) {
ufsdirhash_free(ip);
return (-1);
}
/* Check if hash exists and is intact (note: unlocked read). */
if (ip->i_dirhash->dh_hash != NULL)
return (0);
/* Free the old, recycled hash and build a new one. */
ufsdirhash_free(ip);
}
/* Don't hash removed directories. */
if (ip->i_effnlink == 0)
return (-1);
vp = ip->i_vnode;
/* Allocate 50% more entries than this dir size could ever need. */
KASSERT(ip->i_size >= DIRBLKSIZ, ("ufsdirhash_build size"));
nslots = ip->i_size / DIRECTSIZ(1);
nslots = (nslots * 3 + 1) / 2;
narrays = howmany(nslots, DH_NBLKOFF);
nslots = narrays * DH_NBLKOFF;
dirblocks = howmany(ip->i_size, DIRBLKSIZ);
nblocks = (dirblocks * 3 + 1) / 2;
memreqd = sizeof(*dh) + narrays * sizeof(*dh->dh_hash) +
narrays * DH_NBLKOFF * sizeof(**dh->dh_hash) +
nblocks * sizeof(*dh->dh_blkfree);
mtx_lock(&ufsdirhash_mtx);
if (memreqd + ufs_dirhashmem > ufs_dirhashmaxmem) {
mtx_unlock(&ufsdirhash_mtx);
if (memreqd > ufs_dirhashmaxmem / 2)
return (-1);
/* Try to free some space. */
if (ufsdirhash_recycle(memreqd) != 0)
return (-1);
/* Enough was freed, and ufsdirhash_mtx has been locked. */
}
ufs_dirhashmem += memreqd;
mtx_unlock(&ufsdirhash_mtx);
/*
* Use non-blocking mallocs so that we will revert to a linear
* lookup on failure rather than potentially blocking forever.
*/
MALLOC(dh, struct dirhash *, sizeof *dh, M_DIRHASH, M_NOWAIT | M_ZERO);
if (dh == NULL)
return (-1);
MALLOC(dh->dh_hash, doff_t **, narrays * sizeof(dh->dh_hash[0]),
M_DIRHASH, M_NOWAIT | M_ZERO);
MALLOC(dh->dh_blkfree, u_int8_t *, nblocks * sizeof(dh->dh_blkfree[0]),
M_DIRHASH, M_NOWAIT);
if (dh->dh_hash == NULL || dh->dh_blkfree == NULL)
goto fail;
for (i = 0; i < narrays; i++) {
if ((dh->dh_hash[i] = uma_zalloc(ufsdirhash_zone,
M_WAITOK)) == NULL)
goto fail;
for (j = 0; j < DH_NBLKOFF; j++)
dh->dh_hash[i][j] = DIRHASH_EMPTY;
}
/* Initialise the hash table and block statistics. */
mtx_init(&dh->dh_mtx, "dirhash", NULL, MTX_DEF);
dh->dh_narrays = narrays;
dh->dh_hlen = nslots;
dh->dh_nblk = nblocks;
dh->dh_dirblks = dirblocks;
for (i = 0; i < dirblocks; i++)
dh->dh_blkfree[i] = DIRBLKSIZ / DIRALIGN;
for (i = 0; i < DH_NFSTATS; i++)
dh->dh_firstfree[i] = -1;
dh->dh_firstfree[DH_NFSTATS] = 0;
dh->dh_seqopt = 0;
dh->dh_seqoff = 0;
dh->dh_score = DH_SCOREINIT;
ip->i_dirhash = dh;
bmask = VFSTOUFS(vp->v_mount)->um_mountp->mnt_stat.f_iosize - 1;
pos = 0;
while (pos < ip->i_size) {
/* If necessary, get the next directory block. */
if ((pos & bmask) == 0) {
if (bp != NULL)
brelse(bp);
if (UFS_BLKATOFF(vp, (off_t)pos, NULL, &bp) != 0)
goto fail;
}
/* Add this entry to the hash. */
ep = (struct direct *)((char *)bp->b_data + (pos & bmask));
if (ep->d_reclen == 0 || ep->d_reclen >
DIRBLKSIZ - (pos & (DIRBLKSIZ - 1))) {
/* Corrupted directory. */
brelse(bp);
goto fail;
}
if (ep->d_ino != 0) {
/* Add the entry (simplified ufsdirhash_add). */
slot = ufsdirhash_hash(dh, ep->d_name, ep->d_namlen);
while (DH_ENTRY(dh, slot) != DIRHASH_EMPTY)
slot = WRAPINCR(slot, dh->dh_hlen);
dh->dh_hused++;
DH_ENTRY(dh, slot) = pos;
ufsdirhash_adjfree(dh, pos, -DIRSIZ(0, ep));
}
pos += ep->d_reclen;
}
if (bp != NULL)
brelse(bp);
mtx_lock(&ufsdirhash_mtx);
TAILQ_INSERT_TAIL(&ufsdirhash_list, dh, dh_list);
dh->dh_onlist = 1;
mtx_unlock(&ufsdirhash_mtx);
return (0);
fail:
if (dh->dh_hash != NULL) {
for (i = 0; i < narrays; i++)
if (dh->dh_hash[i] != NULL)
uma_zfree(ufsdirhash_zone, dh->dh_hash[i]);
FREE(dh->dh_hash, M_DIRHASH);
}
if (dh->dh_blkfree != NULL)
FREE(dh->dh_blkfree, M_DIRHASH);
FREE(dh, M_DIRHASH);
ip->i_dirhash = NULL;
mtx_lock(&ufsdirhash_mtx);
ufs_dirhashmem -= memreqd;
mtx_unlock(&ufsdirhash_mtx);
return (-1);
}
/*
* Free any hash table associated with inode 'ip'.
*/
void
ufsdirhash_free(struct inode *ip)
{
struct dirhash *dh;
int i, mem;
if ((dh = ip->i_dirhash) == NULL)
return;
mtx_lock(&ufsdirhash_mtx);
mtx_lock(&dh->dh_mtx);
if (dh->dh_onlist)
TAILQ_REMOVE(&ufsdirhash_list, dh, dh_list);
mtx_unlock(&dh->dh_mtx);
mtx_unlock(&ufsdirhash_mtx);
/* The dirhash pointed to by 'dh' is exclusively ours now. */
mem = sizeof(*dh);
if (dh->dh_hash != NULL) {
for (i = 0; i < dh->dh_narrays; i++)
uma_zfree(ufsdirhash_zone, dh->dh_hash[i]);
FREE(dh->dh_hash, M_DIRHASH);
FREE(dh->dh_blkfree, M_DIRHASH);
mem += dh->dh_narrays * sizeof(*dh->dh_hash) +
dh->dh_narrays * DH_NBLKOFF * sizeof(**dh->dh_hash) +
dh->dh_nblk * sizeof(*dh->dh_blkfree);
}
mtx_destroy(&dh->dh_mtx);
FREE(dh, M_DIRHASH);
ip->i_dirhash = NULL;
mtx_lock(&ufsdirhash_mtx);
ufs_dirhashmem -= mem;
mtx_unlock(&ufsdirhash_mtx);
}
/*
* Find the offset of the specified name within the given inode.
* Returns 0 on success, ENOENT if the entry does not exist, or
* EJUSTRETURN if the caller should revert to a linear search.
*
* If successful, the directory offset is stored in *offp, and a
* pointer to a struct buf containing the entry is stored in *bpp. If
* prevoffp is non-NULL, the offset of the previous entry within
* the DIRBLKSIZ-sized block is stored in *prevoffp (if the entry
* is the first in a block, the start of the block is used).
*/
int
ufsdirhash_lookup(struct inode *ip, char *name, int namelen, doff_t *offp,
struct buf **bpp, doff_t *prevoffp)
{
struct dirhash *dh, *dh_next;
struct direct *dp;
struct vnode *vp;
struct buf *bp;
doff_t blkoff, bmask, offset, prevoff;
int i, slot;
if ((dh = ip->i_dirhash) == NULL)
return (EJUSTRETURN);
/*
* Move this dirhash towards the end of the list if it has a
* score higher than the next entry, and aquire the dh_mtx.
* Optimise the case where it's already the last by performing
* an unlocked read of the TAILQ_NEXT pointer.
*
* In both cases, end up holding just dh_mtx.
*/
if (TAILQ_NEXT(dh, dh_list) != NULL) {
mtx_lock(&ufsdirhash_mtx);
mtx_lock(&dh->dh_mtx);
/*
* If the new score will be greater than that of the next
* entry, then move this entry past it. With both mutexes
* held, dh_next won't go away, but its dh_score could
* change; that's not important since it is just a hint.
*/
if (dh->dh_hash != NULL &&
(dh_next = TAILQ_NEXT(dh, dh_list)) != NULL &&
dh->dh_score >= dh_next->dh_score) {
KASSERT(dh->dh_onlist, ("dirhash: not on list"));
TAILQ_REMOVE(&ufsdirhash_list, dh, dh_list);
TAILQ_INSERT_AFTER(&ufsdirhash_list, dh_next, dh,
dh_list);
}
mtx_unlock(&ufsdirhash_mtx);
} else {
/* Already the last, though that could change as we wait. */
mtx_lock(&dh->dh_mtx);
}
if (dh->dh_hash == NULL) {
mtx_unlock(&dh->dh_mtx);
ufsdirhash_free(ip);
return (EJUSTRETURN);
}
/* Update the score. */
if (dh->dh_score < DH_SCOREMAX)
dh->dh_score++;
vp = ip->i_vnode;
bmask = VFSTOUFS(vp->v_mount)->um_mountp->mnt_stat.f_iosize - 1;
blkoff = -1;
bp = NULL;
restart:
slot = ufsdirhash_hash(dh, name, namelen);
if (dh->dh_seqopt) {
/*
* Sequential access optimisation. dh_seqoff contains the
* offset of the directory entry immediately following
* the last entry that was looked up. Check if this offset
* appears in the hash chain for the name we are looking for.
*/
for (i = slot; (offset = DH_ENTRY(dh, i)) != DIRHASH_EMPTY;
i = WRAPINCR(i, dh->dh_hlen))
if (offset == dh->dh_seqoff)
break;
if (offset == dh->dh_seqoff) {
/*
* We found an entry with the expected offset. This
* is probably the entry we want, but if not, the
* code below will turn off seqoff and retry.
*/
slot = i;
} else
dh->dh_seqopt = 0;
}
for (; (offset = DH_ENTRY(dh, slot)) != DIRHASH_EMPTY;
slot = WRAPINCR(slot, dh->dh_hlen)) {
if (offset == DIRHASH_DEL)
continue;
mtx_unlock(&dh->dh_mtx);
if (offset < 0 || offset >= ip->i_size)
panic("ufsdirhash_lookup: bad offset in hash array");
if ((offset & ~bmask) != blkoff) {
if (bp != NULL)
brelse(bp);
blkoff = offset & ~bmask;
if (UFS_BLKATOFF(vp, (off_t)blkoff, NULL, &bp) != 0)
return (EJUSTRETURN);
}
dp = (struct direct *)(bp->b_data + (offset & bmask));
if (dp->d_reclen == 0 || dp->d_reclen >
DIRBLKSIZ - (offset & (DIRBLKSIZ - 1))) {
/* Corrupted directory. */
brelse(bp);
return (EJUSTRETURN);
}
if (dp->d_namlen == namelen &&
bcmp(dp->d_name, name, namelen) == 0) {
/* Found. Get the prev offset if needed. */
if (prevoffp != NULL) {
if (offset & (DIRBLKSIZ - 1)) {
prevoff = ufsdirhash_getprev(dp,
offset);
if (prevoff == -1) {
brelse(bp);
return (EJUSTRETURN);
}
} else
prevoff = offset;
*prevoffp = prevoff;
}
/* Check for sequential access, and update offset. */
if (dh->dh_seqopt == 0 && dh->dh_seqoff == offset)
dh->dh_seqopt = 1;
dh->dh_seqoff = offset + DIRSIZ(0, dp);
*bpp = bp;
*offp = offset;
return (0);
}
mtx_lock(&dh->dh_mtx);
if (dh->dh_hash == NULL) {
mtx_unlock(&dh->dh_mtx);
if (bp != NULL)
brelse(bp);
ufsdirhash_free(ip);
return (EJUSTRETURN);
}
/*
* When the name doesn't match in the seqopt case, go back
* and search normally.
*/
if (dh->dh_seqopt) {
dh->dh_seqopt = 0;
goto restart;
}
}
mtx_unlock(&dh->dh_mtx);
if (bp != NULL)
brelse(bp);
return (ENOENT);
}
/*
* Find a directory block with room for 'slotneeded' bytes. Returns
* the offset of the directory entry that begins the free space.
* This will either be the offset of an existing entry that has free
* space at the end, or the offset of an entry with d_ino == 0 at
* the start of a DIRBLKSIZ block.
*
* To use the space, the caller may need to compact existing entries in
* the directory. The total number of bytes in all of the entries involved
* in the compaction is stored in *slotsize. In other words, all of
* the entries that must be compacted are exactly contained in the
* region beginning at the returned offset and spanning *slotsize bytes.
*
* Returns -1 if no space was found, indicating that the directory
* must be extended.
*/
doff_t
ufsdirhash_findfree(struct inode *ip, int slotneeded, int *slotsize)
{
struct direct *dp;
struct dirhash *dh;
struct buf *bp;
doff_t pos, slotstart;
int dirblock, error, freebytes, i;
if ((dh = ip->i_dirhash) == NULL)
return (-1);
mtx_lock(&dh->dh_mtx);
if (dh->dh_hash == NULL) {
mtx_unlock(&dh->dh_mtx);
ufsdirhash_free(ip);
return (-1);
}
/* Find a directory block with the desired free space. */
dirblock = -1;
for (i = howmany(slotneeded, DIRALIGN); i <= DH_NFSTATS; i++)
if ((dirblock = dh->dh_firstfree[i]) != -1)
break;
if (dirblock == -1) {
mtx_unlock(&dh->dh_mtx);
return (-1);
}
KASSERT(dirblock < dh->dh_nblk &&
dh->dh_blkfree[dirblock] >= howmany(slotneeded, DIRALIGN),
("ufsdirhash_findfree: bad stats"));
mtx_unlock(&dh->dh_mtx);
pos = dirblock * DIRBLKSIZ;
error = UFS_BLKATOFF(ip->i_vnode, (off_t)pos, (char **)&dp, &bp);
if (error)
return (-1);
/* Find the first entry with free space. */
for (i = 0; i < DIRBLKSIZ; ) {
if (dp->d_reclen == 0) {
brelse(bp);
return (-1);
}
if (dp->d_ino == 0 || dp->d_reclen > DIRSIZ(0, dp))
break;
i += dp->d_reclen;
dp = (struct direct *)((char *)dp + dp->d_reclen);
}
if (i > DIRBLKSIZ) {
brelse(bp);
return (-1);
}
slotstart = pos + i;
/* Find the range of entries needed to get enough space */
freebytes = 0;
while (i < DIRBLKSIZ && freebytes < slotneeded) {
freebytes += dp->d_reclen;
if (dp->d_ino != 0)
freebytes -= DIRSIZ(0, dp);
if (dp->d_reclen == 0) {
brelse(bp);
return (-1);
}
i += dp->d_reclen;
dp = (struct direct *)((char *)dp + dp->d_reclen);
}
if (i > DIRBLKSIZ) {
brelse(bp);
return (-1);
}
if (freebytes < slotneeded)
panic("ufsdirhash_findfree: free mismatch");
brelse(bp);
*slotsize = pos + i - slotstart;
return (slotstart);
}
/*
* Return the start of the unused space at the end of a directory, or
* -1 if there are no trailing unused blocks.
*/
doff_t
ufsdirhash_enduseful(struct inode *ip)
{
struct dirhash *dh;
int i;
if ((dh = ip->i_dirhash) == NULL)
return (-1);
mtx_lock(&dh->dh_mtx);
if (dh->dh_hash == NULL) {
mtx_unlock(&dh->dh_mtx);
ufsdirhash_free(ip);
return (-1);
}
if (dh->dh_blkfree[dh->dh_dirblks - 1] != DIRBLKSIZ / DIRALIGN) {
mtx_unlock(&dh->dh_mtx);
return (-1);
}
for (i = dh->dh_dirblks - 1; i >= 0; i--)
if (dh->dh_blkfree[i] != DIRBLKSIZ / DIRALIGN)
break;
mtx_unlock(&dh->dh_mtx);
return ((doff_t)(i + 1) * DIRBLKSIZ);
}
/*
* Insert information into the hash about a new directory entry. dirp
* points to a struct direct containing the entry, and offset specifies
* the offset of this entry.
*/
void
ufsdirhash_add(struct inode *ip, struct direct *dirp, doff_t offset)
{
struct dirhash *dh;
int slot;
if ((dh = ip->i_dirhash) == NULL)
return;
mtx_lock(&dh->dh_mtx);
if (dh->dh_hash == NULL) {
mtx_unlock(&dh->dh_mtx);
ufsdirhash_free(ip);
return;
}
KASSERT(offset < dh->dh_dirblks * DIRBLKSIZ,
("ufsdirhash_add: bad offset"));
/*
* Normal hash usage is < 66%. If the usage gets too high then
* remove the hash entirely and let it be rebuilt later.
*/
if (dh->dh_hused >= (dh->dh_hlen * 3) / 4) {
mtx_unlock(&dh->dh_mtx);
ufsdirhash_free(ip);
return;
}
/* Find a free hash slot (empty or deleted), and add the entry. */
slot = ufsdirhash_hash(dh, dirp->d_name, dirp->d_namlen);
while (DH_ENTRY(dh, slot) >= 0)
slot = WRAPINCR(slot, dh->dh_hlen);
if (DH_ENTRY(dh, slot) == DIRHASH_EMPTY)
dh->dh_hused++;
DH_ENTRY(dh, slot) = offset;
/* Update the per-block summary info. */
ufsdirhash_adjfree(dh, offset, -DIRSIZ(0, dirp));
mtx_unlock(&dh->dh_mtx);
}
/*
* Remove the specified directory entry from the hash. The entry to remove
* is defined by the name in `dirp', which must exist at the specified
* `offset' within the directory.
*/
void
ufsdirhash_remove(struct inode *ip, struct direct *dirp, doff_t offset)
{
struct dirhash *dh;
int slot;
if ((dh = ip->i_dirhash) == NULL)
return;
mtx_lock(&dh->dh_mtx);
if (dh->dh_hash == NULL) {
mtx_unlock(&dh->dh_mtx);
ufsdirhash_free(ip);
return;
}
KASSERT(offset < dh->dh_dirblks * DIRBLKSIZ,
("ufsdirhash_remove: bad offset"));
/* Find the entry */
slot = ufsdirhash_findslot(dh, dirp->d_name, dirp->d_namlen, offset);
/* Remove the hash entry. */
ufsdirhash_delslot(dh, slot);
/* Update the per-block summary info. */
ufsdirhash_adjfree(dh, offset, DIRSIZ(0, dirp));
mtx_unlock(&dh->dh_mtx);
}
/*
* Change the offset associated with a directory entry in the hash. Used
* when compacting directory blocks.
*/
void
ufsdirhash_move(struct inode *ip, struct direct *dirp, doff_t oldoff,
doff_t newoff)
{
struct dirhash *dh;
int slot;
if ((dh = ip->i_dirhash) == NULL)
return;
mtx_lock(&dh->dh_mtx);
if (dh->dh_hash == NULL) {
mtx_unlock(&dh->dh_mtx);
ufsdirhash_free(ip);
return;
}
KASSERT(oldoff < dh->dh_dirblks * DIRBLKSIZ &&
newoff < dh->dh_dirblks * DIRBLKSIZ,
("ufsdirhash_move: bad offset"));
/* Find the entry, and update the offset. */
slot = ufsdirhash_findslot(dh, dirp->d_name, dirp->d_namlen, oldoff);
DH_ENTRY(dh, slot) = newoff;
mtx_unlock(&dh->dh_mtx);
}
/*
* Inform dirhash that the directory has grown by one block that
* begins at offset (i.e. the new length is offset + DIRBLKSIZ).
*/
void
ufsdirhash_newblk(struct inode *ip, doff_t offset)
{
struct dirhash *dh;
int block;
if ((dh = ip->i_dirhash) == NULL)
return;
mtx_lock(&dh->dh_mtx);
if (dh->dh_hash == NULL) {
mtx_unlock(&dh->dh_mtx);
ufsdirhash_free(ip);
return;
}
KASSERT(offset == dh->dh_dirblks * DIRBLKSIZ,
("ufsdirhash_newblk: bad offset"));
block = offset / DIRBLKSIZ;
if (block >= dh->dh_nblk) {
/* Out of space; must rebuild. */
mtx_unlock(&dh->dh_mtx);
ufsdirhash_free(ip);
return;
}
dh->dh_dirblks = block + 1;
/* Account for the new free block. */
dh->dh_blkfree[block] = DIRBLKSIZ / DIRALIGN;
if (dh->dh_firstfree[DH_NFSTATS] == -1)
dh->dh_firstfree[DH_NFSTATS] = block;
mtx_unlock(&dh->dh_mtx);
}
/*
* Inform dirhash that the directory is being truncated.
*/
void
ufsdirhash_dirtrunc(struct inode *ip, doff_t offset)
{
struct dirhash *dh;
int block, i;
if ((dh = ip->i_dirhash) == NULL)
return;
mtx_lock(&dh->dh_mtx);
if (dh->dh_hash == NULL) {
mtx_unlock(&dh->dh_mtx);
ufsdirhash_free(ip);
return;
}
KASSERT(offset <= dh->dh_dirblks * DIRBLKSIZ,
("ufsdirhash_dirtrunc: bad offset"));
block = howmany(offset, DIRBLKSIZ);
/*
* If the directory shrinks to less than 1/8 of dh_nblk blocks
* (about 20% of its original size due to the 50% extra added in
* ufsdirhash_build) then free it, and let the caller rebuild
* if necessary.
*/
if (block < dh->dh_nblk / 8 && dh->dh_narrays > 1) {
mtx_unlock(&dh->dh_mtx);
ufsdirhash_free(ip);
return;
}
/*
* Remove any `first free' information pertaining to the
* truncated blocks. All blocks we're removing should be
* completely unused.
*/
if (dh->dh_firstfree[DH_NFSTATS] >= block)
dh->dh_firstfree[DH_NFSTATS] = -1;
for (i = block; i < dh->dh_dirblks; i++)
if (dh->dh_blkfree[i] != DIRBLKSIZ / DIRALIGN)
panic("ufsdirhash_dirtrunc: blocks in use");
for (i = 0; i < DH_NFSTATS; i++)
if (dh->dh_firstfree[i] >= block)
panic("ufsdirhash_dirtrunc: first free corrupt");
dh->dh_dirblks = block;
mtx_unlock(&dh->dh_mtx);
}
/*
* Debugging function to check that the dirhash information about
* a directory block matches its actual contents. Panics if a mismatch
* is detected.
*
* On entry, `buf' should point to the start of an in-core
* DIRBLKSIZ-sized directory block, and `offset' should contain the
* offset from the start of the directory of that block.
*/
void
ufsdirhash_checkblock(struct inode *ip, char *buf, doff_t offset)
{
struct dirhash *dh;
struct direct *dp;
int block, ffslot, i, nfree;
if (!ufs_dirhashcheck)
return;
if ((dh = ip->i_dirhash) == NULL)
return;
mtx_lock(&dh->dh_mtx);
if (dh->dh_hash == NULL) {
mtx_unlock(&dh->dh_mtx);
ufsdirhash_free(ip);
return;
}
block = offset / DIRBLKSIZ;
if ((offset & (DIRBLKSIZ - 1)) != 0 || block >= dh->dh_dirblks)
panic("ufsdirhash_checkblock: bad offset");
nfree = 0;
for (i = 0; i < DIRBLKSIZ; i += dp->d_reclen) {
dp = (struct direct *)(buf + i);
if (dp->d_reclen == 0 || i + dp->d_reclen > DIRBLKSIZ)
panic("ufsdirhash_checkblock: bad dir");
if (dp->d_ino == 0) {
#if 0
/*
* XXX entries with d_ino == 0 should only occur
* at the start of a DIRBLKSIZ block. However the
* ufs code is tolerant of such entries at other
* offsets, and fsck does not fix them.
*/
if (i != 0)
panic("ufsdirhash_checkblock: bad dir inode");
#endif
nfree += dp->d_reclen;
continue;
}
/* Check that the entry exists (will panic if it doesn't). */
ufsdirhash_findslot(dh, dp->d_name, dp->d_namlen, offset + i);
nfree += dp->d_reclen - DIRSIZ(0, dp);
}
if (i != DIRBLKSIZ)
panic("ufsdirhash_checkblock: bad dir end");
if (dh->dh_blkfree[block] * DIRALIGN != nfree)
panic("ufsdirhash_checkblock: bad free count");
ffslot = BLKFREE2IDX(nfree / DIRALIGN);
for (i = 0; i <= DH_NFSTATS; i++)
if (dh->dh_firstfree[i] == block && i != ffslot)
panic("ufsdirhash_checkblock: bad first-free");
if (dh->dh_firstfree[ffslot] == -1)
panic("ufsdirhash_checkblock: missing first-free entry");
mtx_unlock(&dh->dh_mtx);
}
/*
* Hash the specified filename into a dirhash slot.
*/
static int
ufsdirhash_hash(struct dirhash *dh, char *name, int namelen)
{
u_int32_t hash;
/*
* We hash the name and then some ofther bit of data which is
* invarient over the dirhash's lifetime. Otherwise names
* differing only in the last byte are placed close to one
* another in the table, which is bad for linear probing.
*/
hash = fnv_32_buf(name, namelen, FNV1_32_INIT);
hash = fnv_32_buf(dh, sizeof(dh), hash);
return (hash % dh->dh_hlen);
}
/*
* Adjust the number of free bytes in the block containing `offset'
* by the value specified by `diff'.
*
* The caller must ensure we have exclusive access to `dh'; normally
* that means that dh_mtx should be held, but this is also called
* from ufsdirhash_build() where exclusive access can be assumed.
*/
static void
ufsdirhash_adjfree(struct dirhash *dh, doff_t offset, int diff)
{
int block, i, nfidx, ofidx;
/* Update the per-block summary info. */
block = offset / DIRBLKSIZ;
KASSERT(block < dh->dh_nblk && block < dh->dh_dirblks,
("dirhash bad offset"));
ofidx = BLKFREE2IDX(dh->dh_blkfree[block]);
dh->dh_blkfree[block] = (int)dh->dh_blkfree[block] + (diff / DIRALIGN);
nfidx = BLKFREE2IDX(dh->dh_blkfree[block]);
/* Update the `first free' list if necessary. */
if (ofidx != nfidx) {
/* If removing, scan forward for the next block. */
if (dh->dh_firstfree[ofidx] == block) {
for (i = block + 1; i < dh->dh_dirblks; i++)
if (BLKFREE2IDX(dh->dh_blkfree[i]) == ofidx)
break;
dh->dh_firstfree[ofidx] = (i < dh->dh_dirblks) ? i : -1;
}
/* Make this the new `first free' if necessary */
if (dh->dh_firstfree[nfidx] > block ||
dh->dh_firstfree[nfidx] == -1)
dh->dh_firstfree[nfidx] = block;
}
}
/*
* Find the specified name which should have the specified offset.
* Returns a slot number, and panics on failure.
*
* `dh' must be locked on entry and remains so on return.
*/
static int
ufsdirhash_findslot(struct dirhash *dh, char *name, int namelen, doff_t offset)
{
int slot;
mtx_assert(&dh->dh_mtx, MA_OWNED);
/* Find the entry. */
KASSERT(dh->dh_hused < dh->dh_hlen, ("dirhash find full"));
slot = ufsdirhash_hash(dh, name, namelen);
while (DH_ENTRY(dh, slot) != offset &&
DH_ENTRY(dh, slot) != DIRHASH_EMPTY)
slot = WRAPINCR(slot, dh->dh_hlen);
if (DH_ENTRY(dh, slot) != offset)
panic("ufsdirhash_findslot: '%.*s' not found", namelen, name);
return (slot);
}
/*
* Remove the entry corresponding to the specified slot from the hash array.
*
* `dh' must be locked on entry and remains so on return.
*/
static void
ufsdirhash_delslot(struct dirhash *dh, int slot)
{
int i;
mtx_assert(&dh->dh_mtx, MA_OWNED);
/* Mark the entry as deleted. */
DH_ENTRY(dh, slot) = DIRHASH_DEL;
/* If this is the end of a chain of DIRHASH_DEL slots, remove them. */
for (i = slot; DH_ENTRY(dh, i) == DIRHASH_DEL; )
i = WRAPINCR(i, dh->dh_hlen);
if (DH_ENTRY(dh, i) == DIRHASH_EMPTY) {
i = WRAPDECR(i, dh->dh_hlen);
while (DH_ENTRY(dh, i) == DIRHASH_DEL) {
DH_ENTRY(dh, i) = DIRHASH_EMPTY;
dh->dh_hused--;
i = WRAPDECR(i, dh->dh_hlen);
}
KASSERT(dh->dh_hused >= 0, ("ufsdirhash_delslot neg hlen"));
}
}
/*
* Given a directory entry and its offset, find the offset of the
* previous entry in the same DIRBLKSIZ-sized block. Returns an
* offset, or -1 if there is no previous entry in the block or some
* other problem occurred.
*/
static doff_t
ufsdirhash_getprev(struct direct *dirp, doff_t offset)
{
struct direct *dp;
char *blkbuf;
doff_t blkoff, prevoff;
int entrypos, i;
blkoff = offset & ~(DIRBLKSIZ - 1); /* offset of start of block */
entrypos = offset & (DIRBLKSIZ - 1); /* entry relative to block */
blkbuf = (char *)dirp - entrypos;
prevoff = blkoff;
/* If `offset' is the start of a block, there is no previous entry. */
if (entrypos == 0)
return (-1);
/* Scan from the start of the block until we get to the entry. */
for (i = 0; i < entrypos; i += dp->d_reclen) {
dp = (struct direct *)(blkbuf + i);
if (dp->d_reclen == 0 || i + dp->d_reclen > entrypos)
return (-1); /* Corrupted directory. */
prevoff = blkoff + i;
}
return (prevoff);
}
/*
* Try to free up `wanted' bytes by stealing memory from existing
* dirhashes. Returns zero with ufsdirhash_mtx locked if successful.
*/
static int
ufsdirhash_recycle(int wanted)
{
struct dirhash *dh;
doff_t **hash;
u_int8_t *blkfree;
int i, mem, narrays;
mtx_lock(&ufsdirhash_mtx);
while (wanted + ufs_dirhashmem > ufs_dirhashmaxmem) {
/* Find a dirhash, and lock it. */
if ((dh = TAILQ_FIRST(&ufsdirhash_list)) == NULL) {
mtx_unlock(&ufsdirhash_mtx);
return (-1);
}
mtx_lock(&dh->dh_mtx);
KASSERT(dh->dh_hash != NULL, ("dirhash: NULL hash on list"));
/* Decrement the score; only recycle if it becomes zero. */
if (--dh->dh_score > 0) {
mtx_unlock(&dh->dh_mtx);
mtx_unlock(&ufsdirhash_mtx);
return (-1);
}
/* Remove it from the list and detach its memory. */
TAILQ_REMOVE(&ufsdirhash_list, dh, dh_list);
dh->dh_onlist = 0;
hash = dh->dh_hash;
dh->dh_hash = NULL;
blkfree = dh->dh_blkfree;
dh->dh_blkfree = NULL;
narrays = dh->dh_narrays;
mem = narrays * sizeof(*dh->dh_hash) +
narrays * DH_NBLKOFF * sizeof(**dh->dh_hash) +
dh->dh_nblk * sizeof(*dh->dh_blkfree);
/* Unlock everything, free the detached memory. */
mtx_unlock(&dh->dh_mtx);
mtx_unlock(&ufsdirhash_mtx);
for (i = 0; i < narrays; i++)
uma_zfree(ufsdirhash_zone, hash[i]);
FREE(hash, M_DIRHASH);
FREE(blkfree, M_DIRHASH);
/* Account for the returned memory, and repeat if necessary. */
mtx_lock(&ufsdirhash_mtx);
ufs_dirhashmem -= mem;
}
/* Success; return with ufsdirhash_mtx locked. */
return (0);
}
void
ufsdirhash_init()
{
ufsdirhash_zone = uma_zcreate("DIRHASH", DH_NBLKOFF * sizeof(doff_t),
NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
mtx_init(&ufsdirhash_mtx, "dirhash list", NULL, MTX_DEF);
TAILQ_INIT(&ufsdirhash_list);
}
void
ufsdirhash_uninit()
{
KASSERT(TAILQ_EMPTY(&ufsdirhash_list), ("ufsdirhash_uninit"));
uma_zdestroy(ufsdirhash_zone);
mtx_destroy(&ufsdirhash_mtx);
}
#endif /* UFS_DIRHASH */
|
MarginC/kame
|
freebsd5/sys/ufs/ufs/ufs_dirhash.c
|
C
|
bsd-3-clause
| 30,589 |
/*
* Copyright (c) 2000 Paycounter, Inc.
* Author: Alfred Perlstein <[email protected]>, <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD: src/sys/netinet/accf_http.c,v 1.13 2002/06/18 07:42:02 tanimura Exp $
*/
#define ACCEPT_FILTER_MOD
#include <sys/param.h>
#include <sys/kernel.h>
#include <sys/mbuf.h>
#include <sys/signalvar.h>
#include <sys/sysctl.h>
#include <sys/socketvar.h>
/* check for GET/HEAD */
static void sohashttpget(struct socket *so, void *arg, int waitflag);
/* check for HTTP/1.0 or HTTP/1.1 */
static void soparsehttpvers(struct socket *so, void *arg, int waitflag);
/* check for end of HTTP/1.x request */
static void soishttpconnected(struct socket *so, void *arg, int waitflag);
/* strcmp on an mbuf chain */
static int mbufstrcmp(struct mbuf *m, struct mbuf *npkt, int offset, char *cmp);
/* strncmp on an mbuf chain */
static int mbufstrncmp(struct mbuf *m, struct mbuf *npkt, int offset,
int max, char *cmp);
/* socketbuffer is full */
static int sbfull(struct sockbuf *sb);
static struct accept_filter accf_http_filter = {
"httpready",
sohashttpget,
NULL,
NULL
};
static moduledata_t accf_http_mod = {
"accf_http",
accept_filt_generic_mod_event,
&accf_http_filter
};
DECLARE_MODULE(accf_http, accf_http_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
static int parse_http_version = 1;
SYSCTL_NODE(_net_inet_accf, OID_AUTO, http, CTLFLAG_RW, 0,
"HTTP accept filter");
SYSCTL_INT(_net_inet_accf_http, OID_AUTO, parsehttpversion, CTLFLAG_RW,
&parse_http_version, 1,
"Parse http version so that non 1.x requests work");
#ifdef ACCF_HTTP_DEBUG
#define DPRINT(fmt, args...) \
do { \
printf("%s:%d: " fmt "\n", __func__, __LINE__, ##args); \
} while (0)
#else
#define DPRINT(fmt, args...)
#endif
static int
sbfull(struct sockbuf *sb)
{
DPRINT("sbfull, cc(%ld) >= hiwat(%ld): %d, "
"mbcnt(%ld) >= mbmax(%ld): %d",
sb->sb_cc, sb->sb_hiwat, sb->sb_cc >= sb->sb_hiwat,
sb->sb_mbcnt, sb->sb_mbmax, sb->sb_mbcnt >= sb->sb_mbmax);
return (sb->sb_cc >= sb->sb_hiwat || sb->sb_mbcnt >= sb->sb_mbmax);
}
/*
* start at mbuf m, (must provide npkt if exists)
* starting at offset in m compare characters in mbuf chain for 'cmp'
*/
static int
mbufstrcmp(struct mbuf *m, struct mbuf *npkt, int offset, char *cmp)
{
struct mbuf *n;
for (; m != NULL; m = n) {
n = npkt;
if (npkt)
npkt = npkt->m_nextpkt;
for (; m; m = m->m_next) {
for (; offset < m->m_len; offset++, cmp++) {
if (*cmp == '\0')
return (1);
else if (*cmp != *(mtod(m, char *) + offset))
return (0);
}
if (*cmp == '\0')
return (1);
offset = 0;
}
}
return (0);
}
/*
* start at mbuf m, (must provide npkt if exists)
* starting at offset in m compare characters in mbuf chain for 'cmp'
* stop at 'max' characters
*/
static int
mbufstrncmp(struct mbuf *m, struct mbuf *npkt, int offset, int max, char *cmp)
{
struct mbuf *n;
for (; m != NULL; m = n) {
n = npkt;
if (npkt)
npkt = npkt->m_nextpkt;
for (; m; m = m->m_next) {
for (; offset < m->m_len; offset++, cmp++, max--) {
if (max == 0 || *cmp == '\0')
return (1);
else if (*cmp != *(mtod(m, char *) + offset))
return (0);
}
if (max == 0 || *cmp == '\0')
return (1);
offset = 0;
}
}
return (0);
}
#define STRSETUP(sptr, slen, str) \
do { \
sptr = str; \
slen = sizeof(str) - 1; \
} while(0)
static void
sohashttpget(struct socket *so, void *arg, int waitflag)
{
if ((so->so_state & SS_CANTRCVMORE) == 0 && !sbfull(&so->so_rcv)) {
struct mbuf *m;
char *cmp;
int cmplen, cc;
m = so->so_rcv.sb_mb;
cc = so->so_rcv.sb_cc - 1;
if (cc < 1)
return;
switch (*mtod(m, char *)) {
case 'G':
STRSETUP(cmp, cmplen, "ET ");
break;
case 'H':
STRSETUP(cmp, cmplen, "EAD ");
break;
default:
goto fallout;
}
if (cc < cmplen) {
if (mbufstrncmp(m, m->m_nextpkt, 1, cc, cmp) == 1) {
DPRINT("short cc (%d) but mbufstrncmp ok", cc);
return;
} else {
DPRINT("short cc (%d) mbufstrncmp failed", cc);
goto fallout;
}
}
if (mbufstrcmp(m, m->m_nextpkt, 1, cmp) == 1) {
DPRINT("mbufstrcmp ok");
if (parse_http_version == 0)
soishttpconnected(so, arg, waitflag);
else
soparsehttpvers(so, arg, waitflag);
return;
}
DPRINT("mbufstrcmp bad");
}
fallout:
DPRINT("fallout");
so->so_upcall = NULL;
so->so_rcv.sb_flags &= ~SB_UPCALL;
soisconnected(so);
return;
}
static void
soparsehttpvers(struct socket *so, void *arg, int waitflag)
{
struct mbuf *m, *n;
int i, cc, spaces, inspaces;
if ((so->so_state & SS_CANTRCVMORE) != 0 || sbfull(&so->so_rcv))
goto fallout;
m = so->so_rcv.sb_mb;
cc = so->so_rcv.sb_cc;
inspaces = spaces = 0;
for (m = so->so_rcv.sb_mb; m; m = n) {
n = m->m_nextpkt;
for (; m; m = m->m_next) {
for (i = 0; i < m->m_len; i++, cc--) {
switch (*(mtod(m, char *) + i)) {
case ' ':
/* tabs? '\t' */
if (!inspaces) {
spaces++;
inspaces = 1;
}
break;
case '\r':
case '\n':
DPRINT("newline");
goto fallout;
default:
if (spaces != 2) {
inspaces = 0;
break;
}
/*
* if we don't have enough characters
* left (cc < sizeof("HTTP/1.0") - 1)
* then see if the remaining ones
* are a request we can parse.
*/
if (cc < sizeof("HTTP/1.0") - 1) {
if (mbufstrncmp(m, n, i, cc,
"HTTP/1.") == 1) {
DPRINT("ok");
goto readmore;
} else {
DPRINT("bad");
goto fallout;
}
} else if (
mbufstrcmp(m, n, i, "HTTP/1.0") ||
mbufstrcmp(m, n, i, "HTTP/1.1")) {
DPRINT("ok");
soishttpconnected(so,
arg, waitflag);
return;
} else {
DPRINT("bad");
goto fallout;
}
}
}
}
}
readmore:
DPRINT("readmore");
/*
* if we hit here we haven't hit something
* we don't understand or a newline, so try again
*/
so->so_upcall = soparsehttpvers;
so->so_rcv.sb_flags |= SB_UPCALL;
return;
fallout:
DPRINT("fallout");
so->so_upcall = NULL;
so->so_rcv.sb_flags &= ~SB_UPCALL;
soisconnected(so);
return;
}
#define NCHRS 3
static void
soishttpconnected(struct socket *so, void *arg, int waitflag)
{
char a, b, c;
struct mbuf *m, *n;
int ccleft, copied;
DPRINT("start");
if ((so->so_state & SS_CANTRCVMORE) != 0 || sbfull(&so->so_rcv))
goto gotit;
/*
* Walk the socketbuffer and copy the last NCHRS (3) into a, b, and c
* copied - how much we've copied so far
* ccleft - how many bytes remaining in the socketbuffer
* just loop over the mbufs subtracting from 'ccleft' until we only
* have NCHRS left
*/
copied = 0;
ccleft = so->so_rcv.sb_cc;
if (ccleft < NCHRS)
goto readmore;
a = b = c = '\0';
for (m = so->so_rcv.sb_mb; m; m = n) {
n = m->m_nextpkt;
for (; m; m = m->m_next) {
ccleft -= m->m_len;
if (ccleft <= NCHRS) {
char *src;
int tocopy;
tocopy = (NCHRS - ccleft) - copied;
src = mtod(m, char *) + (m->m_len - tocopy);
while (tocopy--) {
switch (copied++) {
case 0:
a = *src++;
break;
case 1:
b = *src++;
break;
case 2:
c = *src++;
break;
}
}
}
}
}
if (c == '\n' && (b == '\n' || (b == '\r' && a == '\n'))) {
/* we have all request headers */
goto gotit;
}
readmore:
so->so_upcall = soishttpconnected;
so->so_rcv.sb_flags |= SB_UPCALL;
return;
gotit:
so->so_upcall = NULL;
so->so_rcv.sb_flags &= ~SB_UPCALL;
soisconnected(so);
return;
}
|
MarginC/kame
|
freebsd5/sys/netinet/accf_http.c
|
C
|
bsd-3-clause
| 8,834 |
{% extends "base.html" %}
{% block title %}{{ block.super }} - API | Share and store code or command snippets.{% endblock %}
{% block body_styles %} id="userpage"{% endblock %}
{% block logo %}
<a href="/"><img id="logo" src="/media/images/logo-api.png" alt="Snipt API" title="Snipt API" /></a>
{% endblock %}
{% block content %}
{% if request.user.is_authenticated %}
{% include 'userpage-header.html' %}
{% endif %}
<div id="userpage-content" class="api clearfix">
<h1>The Snipt API</h1>
<p style="margin-top: 0;">Note: API development is still in-progress. Follow the API updates on <a href="http://feedback.snipt.net/pages/8117-general/suggestions/86197-api-for-snipt-app-developers?ref=title">UserVoice</a> and <a href="http://twitter.com/lionburger">Twitter</a>.</p>
<p style="font-size: 12px; font-style: italic;">The format of this API doc was inspired by the cleverly manufactured <a href="http://baconfile.com/api/">Baconfile API</a> crafted by the very talented <a href="http://www.wilsonminer.com/">Wilson Miner</a>.</p>
<a name="tags" id="tags"></a>
<h2>Tags</h2>
<script type="text/javascript" src="http://snipt.net/embed/fb34d5c7f1d900a00405aae84173096d"></script>
<dl>
<dt>Formats:</dt>
<dd>json, xml, yaml, pickle</dd>
<dt>Sample:</dt>
<dd><a href="http://snipt.net/api/tags.json">http://snipt.net/api/tags.json</a></dd>
</dl>
<a name="tag" id="tag"></a>
<h2>Tag</h2>
<script type="text/javascript" src="http://snipt.net/embed/138a79969e2c6b82e9b563f01fa150fb"></script>
<dl>
<dt>Formats:</dt>
<dd>json, xml, yaml, pickle</dd>
<dt>Sample:</dt>
<dd><a href="http://snipt.net/api/tags/1.json">http://snipt.net/api/tags/1.json</a></dd>
</dl>
<a name="user" id="user"></a>
<h2>User</h2>
<script type="text/javascript" src="http://snipt.net/embed/735315a787af892cc6bf6721c7d8c1f0"></script>
<dl>
<dt>Formats:</dt>
<dd>json, xml, yaml, pickle</dd>
<dt>Sample:</dt>
<dd><a href="http://snipt.net/api/users/nick.json">http://snipt.net/api/users/nick.json</a></dd>
</dl>
<a name="snipt" id="snipt"></a>
<h2>Snipt</h2>
<script type="text/javascript" src="http://snipt.net/embed/5963a0e3419671fe3b4dcb710e466861"></script>
<dl>
<dt>Formats:</dt>
<dd>json, xml, yaml, pickle</dd>
<dt>Optional:</dt>
<dd>style - you can specify a <a href="http://pygments.org/docs/styles">Pygments theme</a> here, otherwise it will fall back to 'default'. Available styles: 'manni', 'perldoc', 'borland', 'colorful', 'default', 'murphy', 'vs', 'trac', 'tango', 'fruity', 'autumn', 'bw', 'emacs', 'pastie', 'friendly', 'native'.</dd>
<dt>Sample:</dt>
<dd><a href="http://snipt.net/api/snipts/13.json?style=native">http://snipt.net/api/snipts/13.json?style=native</a></dd>
</dl>
</div>
{% endblock %}
|
nicksergeant/snipt-old
|
api/templates/api/home.html
|
HTML
|
bsd-3-clause
| 3,118 |
from sqlpharmacy.core import Database
from sqlalchemy import Column, String, Text
__metaclass__ = Database.DefaultMeta
class User:
name = Column(String(30))
@Database.many_to_one(User, ref_name = 'author', backref_name = 'articles_authored')
@Database.many_to_one(User, ref_name = 'editor', backref_name = 'articles_edited')
class Article:
title = Column(String(80))
content = Column(Text)
Database.register()
if __name__ == '__main__':
db = Database('sqlite://')
db.create_tables()
author = User(name = 'Tyler Long')
editor = User(name = 'Peter Lau')
article = Article(author = author, editor = editor, title = 'sqlpharmacy is super quick and easy',
content = 'sqlpharmacy is super quick and easy. Believe it or not.')
db.session.add_then_commit(article)
article = db.session.query(Article).get(1)
print('Article:', article.title)
print('Author:', article.author.name)
print('Editor:', article.editor.name)
|
tek/sqlpharmacy
|
sqlpharmacy/examples/multiple_many_to_one.py
|
Python
|
bsd-3-clause
| 974 |
class Admin::ShopOrdersController < Admin::BaseController
def index
return @shop_orders if @shop_orders.present?
pagination_options = {
:per_page => Spree::Config[:admin_products_per_page],
:page => params[:page]}
@search = Operates::Order.search(params[:search])
@shop_orders = @search.paginate(pagination_options)
end
def show
@shop_order = Operates::Order.find(params[:id])
end
def edit
@shop_order = Operates::Order.find(params[:id])
end
def update
@shop_order = Operates::Order.find(params[:id])
@shop_order.update_attributes(params[:operates_order])
end
def new
@shop_order = Operates::Order.new
end
def create
@shop_order = Operates::Order.new(params[:shop_order])
@shop_order.save
redirect_to :action => 'show', :id => @shop_order
end
end
|
solo123/spree-shopweb
|
app/controllers/admin/shop_orders_controller.rb
|
Ruby
|
bsd-3-clause
| 935 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.