code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
//
// Triple Play - utilities for use in PlayN-based games
// Copyright (c) 2011-2014, Three Rings Design, Inc. - All rights reserved.
// http://github.com/threerings/tripleplay/blob/master/LICENSE
package tripleplay.platform;
import cli.MonoTouch.CoreAnimation.CAShapeLayer;
import cli.MonoTouch.CoreGraphics.CGPath;
import cli.MonoTouch.UIKit.UIEvent;
import cli.MonoTouch.UIKit.UIView;
import cli.System.Drawing.PointF;
import cli.System.Drawing.RectangleF;
import pythagoras.f.IRectangle;
public class IOSUIOverlay extends UIView
{
public IOSUIOverlay (RectangleF bounds) {
super(bounds);
set_MultipleTouchEnabled(true);
}
@Override public boolean PointInside (PointF pointF, UIEvent uiEvent) {
// if it's masked, we don't want it
if (_hidden != null && _hidden.Contains(pointF)) return false;
// only accept the touch if it is hitting one of our native widgets
UIView[] subs = get_Subviews();
if (subs == null) return false;
for (UIView view : subs)
if (view.PointInside(ConvertPointToView(pointF, view), uiEvent))
return true;
return false;
}
public void setHiddenArea (IRectangle area) {
_hidden = area == null ? null : new RectangleF(area.x(), area.y(),
area.width(), area.height());
if (_hidden == null) {
get_Layer().set_Mask(null);
return;
}
RectangleF bounds = get_Bounds();
CAShapeLayer maskLayer = new CAShapeLayer();
// draw four rectangles surrounding the area we want to hide, and create a mask out of it.
CGPath path = new CGPath();
// top
path.AddRect(new RectangleF(0, 0, bounds.get_Width(), _hidden.get_Top()));
// bottom
path.AddRect(new RectangleF(0, _hidden.get_Bottom(), bounds.get_Width(),
bounds.get_Bottom() - _hidden.get_Bottom()));
// left
path.AddRect(new RectangleF(0, _hidden.get_Top(), _hidden.get_Left(), _hidden.get_Height()));
// right
path.AddRect(new RectangleF(_hidden.get_Right(), _hidden.get_Top(), bounds.get_Right()
- _hidden.get_Right(), _hidden.get_Height()));
maskLayer.set_Path(path);
get_Layer().set_Mask(maskLayer);
}
protected RectangleF _hidden;
}
| tomfisher/tripleplay | ios/src/main/java/tripleplay/platform/IOSUIOverlay.java | Java | bsd-3-clause | 2,336 |
<?php
namespace backend\modules\admin\controllers;
use yii\web\Controller;
/**
* Default controller for the `admin` module
*/
class DefaultController extends Controller {
/**
* Renders the index view for the module
* @return string
*/
public function actionIndex() {
return $this->redirect('admin-posts/index');
}
}
| jithinazryah/emperror | backend/modules/admin/controllers/DefaultController.php | PHP | bsd-3-clause | 390 |
/*L
* Copyright RTI International
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/webgenome/LICENSE.txt for details.
*/
package org.rti.webgenome.client;
/**
* Generates <code>ExperimentDTO</code> objects for testing.
* @author dhall
*
*/
public class ExperimentDTOGenerator {
/** Bioassay data transfer object generator. */
private final BioAssayDTOGenerator bioAssayDTOGenerator;
/** Number of bioassays per experiment. */
private final int numBioAssays;
/**
* Constructor.
* @param gap Gap between generated reporters.
* @param numBioAssays Number of bioassays generated per experiment.
*/
public ExperimentDTOGenerator(final long gap, final int numBioAssays) {
this.bioAssayDTOGenerator = new BioAssayDTOGenerator(gap);
this.numBioAssays = numBioAssays;
}
/**
* Generate new experiment data transfer object.
* @param experimentId Experiment ID.
* @param constraints Constraints.
* @return Experiment data transfer object
*/
public final ExperimentDTO newExperimentDTO(
final String experimentId,
final BioAssayDataConstraints[] constraints) {
BioAssayDTO[] bioAssayDtos = new BioAssayDTO[this.numBioAssays];
for (int i = 0; i < this.numBioAssays; i++) {
bioAssayDtos[i] =
this.bioAssayDTOGenerator.newBioAssayDTO(constraints);
}
return new DefExperimentDTOImpl(experimentId, bioAssayDtos);
}
}
| NCIP/webgenome | tags/WEBGENOME_R3.2_6MAR2009_BUILD1/java/core/src/org/rti/webgenome/client/ExperimentDTOGenerator.java | Java | bsd-3-clause | 1,419 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.10.24 at 02:08:27 PM BST
//
package com.oracle.xmlns.apps.cdm.foundation.parties.locationservice.applicationmodule.types;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import com.oracle.xmlns.apps.cdm.foundation.parties.locationservice.Location;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="location" type="{http://xmlns.oracle.com/apps/cdm/foundation/parties/locationService/}Location"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"location"
})
@XmlRootElement(name = "updateLocation")
public class UpdateLocation {
@XmlElement(required = true)
protected Location location;
/**
* Gets the value of the location property.
*
* @return
* possible object is
* {@link Location }
*
*/
public Location getLocation() {
return location;
}
/**
* Sets the value of the location property.
*
* @param value
* allowed object is
* {@link Location }
*
*/
public void setLocation(Location value) {
this.location = value;
}
}
| dushmis/Oracle-Cloud | PaaS_SaaS_Accelerator_RESTFulFacade/XJC_Beans/src/com/oracle/xmlns/apps/cdm/foundation/parties/locationservice/applicationmodule/types/UpdateLocation.java | Java | bsd-3-clause | 2,082 |
"""django-cms-redirects"""
VERSION = (1, 0, 6)
__version__ = "1.0.6"
| vovanbo/djangocms-redirects | cms_redirects/__init__.py | Python | bsd-3-clause | 69 |
// Copyright 2014 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/task_manager/guest_information.h"
#include "base/strings/string16.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/favicon/favicon_tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/task_manager/renderer_resource.h"
#include "chrome/browser/task_manager/resource_provider.h"
#include "chrome/browser/task_manager/task_manager.h"
#include "chrome/browser/task_manager/task_manager_util.h"
#include "chrome/grit/generated_resources.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_iterator.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/web_contents.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
using content::RenderProcessHost;
using content::RenderViewHost;
using content::RenderWidgetHost;
using content::WebContents;
using extensions::Extension;
namespace task_manager {
class GuestResource : public RendererResource {
public:
explicit GuestResource(content::RenderViewHost* render_view_host);
virtual ~GuestResource();
// Resource methods:
virtual Type GetType() const OVERRIDE;
virtual base::string16 GetTitle() const OVERRIDE;
virtual gfx::ImageSkia GetIcon() const OVERRIDE;
virtual content::WebContents* GetWebContents() const OVERRIDE;
private:
DISALLOW_COPY_AND_ASSIGN(GuestResource);
};
GuestResource::GuestResource(RenderViewHost* render_view_host)
: RendererResource(
render_view_host->GetSiteInstance()->GetProcess()->GetHandle(),
render_view_host) {
}
GuestResource::~GuestResource() {
}
Resource::Type GuestResource::GetType() const {
return GUEST;
}
base::string16 GuestResource::GetTitle() const {
WebContents* web_contents = GetWebContents();
const int message_id = IDS_TASK_MANAGER_WEBVIEW_TAG_PREFIX;
if (web_contents) {
base::string16 title = util::GetTitleFromWebContents(web_contents);
return l10n_util::GetStringFUTF16(message_id, title);
}
return l10n_util::GetStringFUTF16(message_id, base::string16());
}
gfx::ImageSkia GuestResource::GetIcon() const {
WebContents* web_contents = GetWebContents();
if (web_contents && FaviconTabHelper::FromWebContents(web_contents)) {
return FaviconTabHelper::FromWebContents(web_contents)->
GetFavicon().AsImageSkia();
}
return gfx::ImageSkia();
}
WebContents* GuestResource::GetWebContents() const {
return WebContents::FromRenderViewHost(render_view_host());
}
////////////////////////////////////////////////////////////////////////////////
// GuestInformation class
////////////////////////////////////////////////////////////////////////////////
GuestInformation::GuestInformation() {}
GuestInformation::~GuestInformation() {}
bool GuestInformation::CheckOwnership(WebContents* web_contents) {
// Guest WebContentses are created and owned internally by the content layer.
return web_contents->IsSubframe();
}
void GuestInformation::GetAll(const NewWebContentsCallback& callback) {
scoped_ptr<content::RenderWidgetHostIterator> widgets(
content::RenderWidgetHost::GetRenderWidgetHosts());
while (content::RenderWidgetHost* widget = widgets->GetNextHost()) {
if (widget->IsRenderView()) {
content::RenderViewHost* rvh = content::RenderViewHost::From(widget);
WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
if (web_contents && web_contents->IsSubframe())
callback.Run(web_contents);
}
}
}
scoped_ptr<RendererResource> GuestInformation::MakeResource(
WebContents* web_contents) {
return scoped_ptr<RendererResource>(
new GuestResource(web_contents->GetRenderViewHost()));
}
} // namespace task_manager
| 7kbird/chrome | chrome/browser/task_manager/guest_information.cc | C++ | bsd-3-clause | 4,136 |
#!/usr/bin/env python
import gtk
import Editor
def main(filenames=[]):
"""
start the editor, with a new empty document
or load all *filenames* as tabs
returns the tab object
"""
Editor.register_stock_icons()
editor = Editor.EditorWindow()
tabs = map(editor.load_document, filenames)
if len(filenames) == 0:
editor.welcome()
return tabs
def run():
"""
handle all initialisation and start main() and gtk.main()
"""
try: # this works only on linux
from ctypes import cdll
libc = cdll.LoadLibrary("libc.so.6")
libc.prctl(15, 'odMLEditor', 0, 0, 0)
except:
pass
from optparse import OptionParser
parser = OptionParser()
(options, args) = parser.parse_args()
main(filenames=args)
gtk.main()
if __name__=="__main__":
run()
| carloscanova/python-odml | odml/gui/__main__.py | Python | bsd-3-clause | 845 |
#include "density.h"
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstddef>
#include <cstdio>
#include <iostream>
#include "blas_interface.h"
#include "compress.h"
void distribute_matrix(const int mat_dim,
const int block_length,
const bool use_gradient,
const bool use_tau,
const double prefactors[],
const double u[],
double fmat[],
const int k_aoc_num,
const int k_aoc_index[],
const double k_aoc[],
const int l_aoc_num,
const int l_aoc_index[],
const double l_aoc[])
{
// here we compute F(k, l) += AO_k(k, b) u(b) AO_l(l, b)
// in two steps
// step 1: W(k, b) = AO_k(k, b) u(b)
// step 2: F(k, l) += W(k, b) AO_l(l, b)^T
if (k_aoc_num == 0)
return;
if (l_aoc_num == 0)
return;
double *W = new double[k_aoc_num * block_length];
std::fill(&W[0], &W[block_length * k_aoc_num], 0.0);
int kc, lc, iboff;
int num_slices;
(use_gradient) ? (num_slices = 4) : (num_slices = 1);
for (int islice = 0; islice < num_slices; islice++)
{
if (std::abs(prefactors[islice]) > 0.0)
{
for (int k = 0; k < k_aoc_num; k++)
{
iboff = k * block_length;
for (int ib = 0; ib < block_length; ib++)
{
W[iboff + ib] +=
prefactors[islice] * u[islice * block_length + ib] *
k_aoc[islice * block_length * mat_dim + iboff + ib];
}
}
}
}
double *F = new double[k_aoc_num * l_aoc_num];
// we compute F(k, l) += W(k, b) AO_l(l, b)^T
// we transpose W instead of AO_l because we call fortran blas
char ta = 't';
char tb = 'n';
int im = l_aoc_num;
int in = k_aoc_num;
int ik = block_length;
int lda = ik;
int ldb = ik;
int ldc = im;
double alpha = 1.0;
double beta = 0.0;
wrap_dgemm(ta,
tb,
im,
in,
ik,
alpha,
l_aoc,
lda,
W,
ldb,
beta,
F,
ldc);
if (use_tau)
{
if (std::abs(prefactors[4]) > 0.0)
{
for (int ixyz = 0; ixyz < 3; ixyz++)
{
for (int k = 0; k < k_aoc_num; k++)
{
iboff = k * block_length;
for (int ib = 0; ib < block_length; ib++)
{
W[iboff + ib] =
u[4 * block_length + ib] *
k_aoc[(ixyz + 1) * block_length * mat_dim + iboff +
ib];
}
}
alpha = prefactors[4];
beta = 1.0;
wrap_dgemm(ta,
tb,
im,
in,
ik,
alpha,
W,
lda,
&l_aoc[(ixyz + 1) * block_length * mat_dim],
ldb,
beta,
F,
ldc);
}
}
}
delete[] W;
W = NULL;
// FIXME easier route possible if k and l match
for (int k = 0; k < k_aoc_num; k++)
{
kc = k_aoc_index[k];
for (int l = 0; l < l_aoc_num; l++)
{
lc = l_aoc_index[l];
fmat[kc * mat_dim + lc] += F[k * l_aoc_num + l];
}
}
delete[] F;
F = NULL;
}
void get_density(const int mat_dim,
const int block_length,
const bool use_gradient,
const bool use_tau,
const double prefactors[],
double density[],
const double dmat[],
const bool dmat_is_symmetric,
const bool kl_match,
const int k_aoc_num,
const int k_aoc_index[],
const double k_aoc[],
const int l_aoc_num,
const int l_aoc_index[],
const double l_aoc[])
{
// here we compute n(b) = AO_k(k, b) D(k, l) AO_l(l, b)
// in two steps
// step 1: X(k, b) = D(k, l) AO_l(l, b)
// step 2: n(b) = AO_k(k, b) X(k, b)
if (k_aoc_num == 0)
return;
if (l_aoc_num == 0)
return;
int kc, lc, iboff;
double *D = new double[k_aoc_num * l_aoc_num];
double *X = new double[k_aoc_num * block_length];
// compress dmat
if (kl_match)
{
if (dmat_is_symmetric)
{
for (int k = 0; k < k_aoc_num; k++)
{
kc = k_aoc_index[k];
for (int l = 0; l <= k; l++)
{
lc = l_aoc_index[l];
D[k * l_aoc_num + l] = 2.0 * dmat[kc * mat_dim + lc];
}
}
}
else
{
for (int k = 0; k < k_aoc_num; k++)
{
kc = k_aoc_index[k];
for (int l = 0; l < l_aoc_num; l++)
{
lc = l_aoc_index[l];
D[k * l_aoc_num + l] = 2.0 * dmat[kc * mat_dim + lc];
}
}
}
}
else
{
if (dmat_is_symmetric)
{
for (int k = 0; k < k_aoc_num; k++)
{
kc = k_aoc_index[k];
for (int l = 0; l < l_aoc_num; l++)
{
lc = l_aoc_index[l];
D[k * l_aoc_num + l] = 2.0 * dmat[kc * mat_dim + lc];
}
}
}
else
{
for (int k = 0; k < k_aoc_num; k++)
{
kc = k_aoc_index[k];
for (int l = 0; l < l_aoc_num; l++)
{
lc = l_aoc_index[l];
D[k * l_aoc_num + l] =
dmat[kc * mat_dim + lc] + dmat[lc * mat_dim + kc];
}
}
}
}
// form xmat
if (dmat_is_symmetric)
{
char si = 'r';
char up = 'u';
int im = block_length;
int in = k_aoc_num;
int lda = in;
int ldb = im;
int ldc = im;
double alpha = 1.0;
double beta = 0.0;
wrap_dsymm(
si, up, im, in, alpha, D, lda, l_aoc, ldb, beta, X, ldc);
}
else
{
char ta = 'n';
char tb = 'n';
int im = block_length;
int in = k_aoc_num;
int ik = l_aoc_num;
int lda = im;
int ldb = ik;
int ldc = im;
double alpha = 1.0;
double beta = 0.0;
wrap_dgemm(ta,
tb,
im,
in,
ik,
alpha,
l_aoc,
lda,
D,
ldb,
beta,
X,
ldc);
}
int num_slices;
(use_gradient) ? (num_slices = 4) : (num_slices = 1);
// it is not ok to zero out here since geometric
// derivatives are accumulated from several contributions
// std::fill(&density[0], &density[num_slices * block_length], 0.0);
// assemble density and possibly gradient
for (int islice = 0; islice < num_slices; islice++)
{
if (std::abs(prefactors[islice]) > 0.0)
{
for (int k = 0; k < k_aoc_num; k++)
{
iboff = k * block_length;
for (int ib = 0; ib < block_length; ib++)
{
density[islice * block_length + ib] +=
prefactors[islice] * X[iboff + ib] *
k_aoc[islice * block_length * mat_dim + iboff + ib];
}
}
}
}
if (use_tau)
{
if (std::abs(prefactors[4]) > 0.0)
{
for (int ixyz = 0; ixyz < 3; ixyz++)
{
if (dmat_is_symmetric)
{
char si = 'r';
char up = 'u';
int im = block_length;
int in = k_aoc_num;
int lda = in;
int ldb = im;
int ldc = im;
double alpha = 1.0;
double beta = 0.0;
wrap_dsymm(si,
up,
im,
in,
alpha,
D,
lda,
&l_aoc[(ixyz + 1) * block_length * mat_dim],
ldb,
beta,
X,
ldc);
}
else
{
char ta = 'n';
char tb = 'n';
int im = block_length;
int in = k_aoc_num;
int ik = l_aoc_num;
int lda = im;
int ldb = ik;
int ldc = im;
double alpha = 1.0;
double beta = 0.0;
wrap_dgemm(ta,
tb,
im,
in,
ik,
alpha,
&l_aoc[(ixyz + 1) * block_length * mat_dim],
lda,
D,
ldb,
beta,
X,
ldc);
}
for (int k = 0; k < k_aoc_num; k++)
{
iboff = k * block_length;
for (int ib = 0; ib < block_length; ib++)
{
density[4 * block_length + ib] +=
prefactors[4] * X[iboff + ib] *
k_aoc[(ixyz + 1) * block_length * mat_dim + iboff +
ib];
}
}
}
}
}
delete[] D;
D = NULL;
delete[] X;
X = NULL;
}
void get_dens_geo_derv(const int mat_dim,
const int num_aos,
const int block_length,
const int buffer_len,
const double ao[],
const int ao_centers[],
const bool use_gradient,
const bool use_tau,
const std::vector<int> &coor,
std::function<int(int, int, int)> get_geo_offset,
double density[],
const double mat[])
{
/*
1st a,0
2nd ab,0 a,b
/ \ / \
/ \ / \
3rd abc,0 ab,c ac,b a,bc
/ \ / \ / \ / \
4th abcd,0 abc,d abd,c ab,cd acd,b ac,bd ad,bc a,bcd
*/
for (unsigned int i = 0; i < coor.size(); i++)
{
if (coor[i] == 0)
return;
}
// there is a factor 2 because center-a
// differentiation can be left or right
double f = 2.0 * pow(-1.0, (int)coor.size());
std::vector<int> k_coor;
std::vector<int> l_coor;
switch (coor.size())
{
// FIXME implement shortcuts
case 1:
k_coor.push_back(coor[0]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
break;
case 2:
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
l_coor.push_back(coor[1]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
break;
case 3:
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
k_coor.push_back(coor[2]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
l_coor.push_back(coor[2]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
l_coor.push_back(coor[1]);
l_coor.push_back(coor[2]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[2]);
l_coor.push_back(coor[1]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
break;
case 4:
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
k_coor.push_back(coor[2]);
k_coor.push_back(coor[3]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
k_coor.push_back(coor[2]);
l_coor.push_back(coor[3]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
l_coor.push_back(coor[2]);
l_coor.push_back(coor[3]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
l_coor.push_back(coor[1]);
l_coor.push_back(coor[2]);
l_coor.push_back(coor[3]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
k_coor.push_back(coor[3]);
l_coor.push_back(coor[2]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[2]);
k_coor.push_back(coor[3]);
l_coor.push_back(coor[1]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[2]);
l_coor.push_back(coor[1]);
l_coor.push_back(coor[3]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[3]);
l_coor.push_back(coor[1]);
l_coor.push_back(coor[2]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
break;
default:
std::cout << "ERROR: get_dens_geo_derv coor.size() too high\n";
exit(1);
break;
}
}
void get_mat_geo_derv(const int mat_dim,
const int num_aos,
const int block_length,
const int buffer_len,
const double ao[],
const int ao_centers[],
const bool use_gradient,
const bool use_tau,
const std::vector<int> &coor,
std::function<int(int, int, int)> get_geo_offset,
const double density[],
double mat[])
{
/*
1st a,0
2nd ab,0 a,b
/ \ / \
/ \ / \
3rd abc,0 ab,c ac,b a,bc
/ \ / \ / \ / \
4th abcd,0 abc,d abd,c ab,cd acd,b ac,bd ad,bc a,bcd
*/
for (unsigned int i = 0; i < coor.size(); i++)
{
if (coor[i] == 0)
return;
}
// there is a factor 2 because center-a
// differentiation can be left or right
double f = 2.0 * pow(-1.0, (int)coor.size());
std::vector<int> k_coor;
std::vector<int> l_coor;
switch (coor.size())
{
// FIXME implement shortcuts
case 1:
k_coor.push_back(coor[0]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
break;
case 2:
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
l_coor.push_back(coor[1]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
break;
case 3:
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
k_coor.push_back(coor[2]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
l_coor.push_back(coor[2]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
l_coor.push_back(coor[1]);
l_coor.push_back(coor[2]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[2]);
l_coor.push_back(coor[1]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
break;
case 4:
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
k_coor.push_back(coor[2]);
k_coor.push_back(coor[3]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
k_coor.push_back(coor[2]);
l_coor.push_back(coor[3]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
l_coor.push_back(coor[2]);
l_coor.push_back(coor[3]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
l_coor.push_back(coor[1]);
l_coor.push_back(coor[2]);
l_coor.push_back(coor[3]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
k_coor.push_back(coor[3]);
l_coor.push_back(coor[2]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[2]);
k_coor.push_back(coor[3]);
l_coor.push_back(coor[1]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[2]);
l_coor.push_back(coor[1]);
l_coor.push_back(coor[3]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[3]);
l_coor.push_back(coor[1]);
l_coor.push_back(coor[2]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
break;
default:
std::cout << "ERROR: get_dens_geo_derv coor.size() too high\n";
exit(1);
break;
}
}
void diff_u_wrt_center_tuple(const int mat_dim,
const int num_aos,
const int block_length,
const int buffer_len,
const double ao[],
const int ao_centers[],
const bool use_gradient,
const bool use_tau,
const double f,
std::function<int(int, int, int)> get_geo_offset,
const std::vector<int> &k_coor,
const std::vector<int> &l_coor,
double u[],
const double M[])
{
double *k_ao_compressed = new double[buffer_len];
int *k_ao_compressed_index = new int[buffer_len];
int k_ao_compressed_num;
double *l_ao_compressed = new double[buffer_len];
int *l_ao_compressed_index = new int[buffer_len];
int l_ao_compressed_num;
int slice_offsets[4];
compute_slice_offsets(get_geo_offset, k_coor, slice_offsets);
compress(use_gradient,
block_length,
k_ao_compressed_num,
k_ao_compressed_index,
k_ao_compressed,
num_aos,
ao,
ao_centers,
k_coor,
slice_offsets);
compute_slice_offsets(get_geo_offset, l_coor, slice_offsets);
compress(use_gradient,
block_length,
l_ao_compressed_num,
l_ao_compressed_index,
l_ao_compressed,
num_aos,
ao,
ao_centers,
l_coor,
slice_offsets);
double prefactors[5] = {f, f, f, f, 0.5 * f};
// evaluate density dervs
get_density(mat_dim,
block_length,
use_gradient,
use_tau,
prefactors,
u,
M,
false,
false,
k_ao_compressed_num,
k_ao_compressed_index,
k_ao_compressed,
l_ao_compressed_num,
l_ao_compressed_index,
l_ao_compressed);
if (use_gradient)
{
prefactors[0] = 0.0;
get_density(mat_dim,
block_length,
use_gradient,
false,
prefactors,
u,
M,
false,
false,
l_ao_compressed_num,
l_ao_compressed_index,
l_ao_compressed,
k_ao_compressed_num,
k_ao_compressed_index,
k_ao_compressed);
}
delete[] k_ao_compressed;
delete[] k_ao_compressed_index;
delete[] l_ao_compressed;
delete[] l_ao_compressed_index;
}
void diff_M_wrt_center_tuple(const int mat_dim,
const int num_aos,
const int block_length,
const int buffer_len,
const double ao[],
const int ao_centers[],
const bool use_gradient,
const bool use_tau,
const double f,
std::function<int(int, int, int)> get_geo_offset,
const std::vector<int> &k_coor,
const std::vector<int> &l_coor,
const double u[],
double M[])
{
double *k_ao_compressed = new double[buffer_len];
int *k_ao_compressed_index = new int[buffer_len];
int k_ao_compressed_num;
double *l_ao_compressed = new double[buffer_len];
int *l_ao_compressed_index = new int[buffer_len];
int l_ao_compressed_num;
int slice_offsets[4];
compute_slice_offsets(get_geo_offset, k_coor, slice_offsets);
compress(use_gradient,
block_length,
k_ao_compressed_num,
k_ao_compressed_index,
k_ao_compressed,
num_aos,
ao,
ao_centers,
k_coor,
slice_offsets);
compute_slice_offsets(get_geo_offset, l_coor, slice_offsets);
compress(use_gradient,
block_length,
l_ao_compressed_num,
l_ao_compressed_index,
l_ao_compressed,
num_aos,
ao,
ao_centers,
l_coor,
slice_offsets);
double prefactors[5] = {f, f, f, f, 0.5 * f};
// distribute over XC potential derivative matrix
distribute_matrix(mat_dim,
block_length,
use_gradient,
use_tau,
prefactors,
u,
M,
k_ao_compressed_num,
k_ao_compressed_index,
k_ao_compressed,
l_ao_compressed_num,
l_ao_compressed_index,
l_ao_compressed);
if (use_gradient)
{
prefactors[0] = 0.0;
distribute_matrix(mat_dim,
block_length,
use_gradient,
false,
prefactors,
u,
M,
l_ao_compressed_num,
l_ao_compressed_index,
l_ao_compressed,
k_ao_compressed_num,
k_ao_compressed_index,
k_ao_compressed);
}
delete[] k_ao_compressed;
delete[] k_ao_compressed_index;
delete[] l_ao_compressed;
delete[] l_ao_compressed_index;
}
void compute_slice_offsets(std::function<int(int, int, int)> get_geo_offset,
const std::vector<int> &coor,
int off[])
{
int kp[3] = {0, 0, 0};
for (size_t j = 0; j < coor.size(); j++)
{
kp[(coor[j] - 1) % 3]++;
}
off[0] = get_geo_offset(kp[0], kp[1], kp[2]);
off[1] = get_geo_offset(kp[0] + 1, kp[1], kp[2]);
off[2] = get_geo_offset(kp[0], kp[1] + 1, kp[2]);
off[3] = get_geo_offset(kp[0], kp[1], kp[2] + 1);
}
| bast/xcint | src/density/density.cpp | C++ | bsd-3-clause | 42,641 |
// Copyright 2015 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 "flutter/lib/ui/window/window.h"
#include "flutter/lib/ui/compositing/scene.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "flutter/lib/ui/window/platform_message_response_dart.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_args.h"
#include "third_party/tonic/dart_library_natives.h"
#include "third_party/tonic/dart_microtask_queue.h"
#include "third_party/tonic/logging/dart_invoke.h"
#include "third_party/tonic/typed_data/dart_byte_data.h"
using tonic::DartInvokeField;
using tonic::DartState;
using tonic::StdStringToDart;
using tonic::ToDart;
namespace blink {
namespace {
void DefaultRouteName(Dart_NativeArguments args) {
std::string routeName =
UIDartState::Current()->window()->client()->DefaultRouteName();
Dart_SetReturnValue(args, StdStringToDart(routeName));
}
void ScheduleFrame(Dart_NativeArguments args) {
UIDartState::Current()->window()->client()->ScheduleFrame();
}
void Render(Dart_NativeArguments args) {
Dart_Handle exception = nullptr;
Scene* scene =
tonic::DartConverter<Scene*>::FromArguments(args, 1, exception);
if (exception) {
Dart_ThrowException(exception);
return;
}
UIDartState::Current()->window()->client()->Render(scene);
}
void UpdateSemantics(Dart_NativeArguments args) {
Dart_Handle exception = nullptr;
SemanticsUpdate* update =
tonic::DartConverter<SemanticsUpdate*>::FromArguments(args, 1, exception);
if (exception) {
Dart_ThrowException(exception);
return;
}
UIDartState::Current()->window()->client()->UpdateSemantics(update);
}
void SetIsolateDebugName(Dart_NativeArguments args) {
Dart_Handle exception = nullptr;
const std::string name =
tonic::DartConverter<std::string>::FromArguments(args, 1, exception);
if (exception) {
Dart_ThrowException(exception);
return;
}
UIDartState::Current()->window()->client()->SetIsolateDebugName(name);
}
Dart_Handle SendPlatformMessage(Dart_Handle window,
const std::string& name,
Dart_Handle callback,
const tonic::DartByteData& data) {
UIDartState* dart_state = UIDartState::Current();
if (!dart_state->window()) {
// Must release the TypedData buffer before allocating other Dart objects.
data.Release();
return ToDart("Platform messages can only be sent from the main isolate");
}
fml::RefPtr<PlatformMessageResponse> response;
if (!Dart_IsNull(callback)) {
response = fml::MakeRefCounted<PlatformMessageResponseDart>(
tonic::DartPersistentValue(dart_state, callback),
dart_state->GetTaskRunners().GetUITaskRunner());
}
if (Dart_IsNull(data.dart_handle())) {
dart_state->window()->client()->HandlePlatformMessage(
fml::MakeRefCounted<PlatformMessage>(name, response));
} else {
const uint8_t* buffer = static_cast<const uint8_t*>(data.data());
dart_state->window()->client()->HandlePlatformMessage(
fml::MakeRefCounted<PlatformMessage>(
name, std::vector<uint8_t>(buffer, buffer + data.length_in_bytes()),
response));
}
return Dart_Null();
}
void _SendPlatformMessage(Dart_NativeArguments args) {
tonic::DartCallStatic(&SendPlatformMessage, args);
}
void RespondToPlatformMessage(Dart_Handle window,
int response_id,
const tonic::DartByteData& data) {
if (Dart_IsNull(data.dart_handle())) {
UIDartState::Current()->window()->CompletePlatformMessageEmptyResponse(
response_id);
} else {
// TODO(engine): Avoid this copy.
const uint8_t* buffer = static_cast<const uint8_t*>(data.data());
UIDartState::Current()->window()->CompletePlatformMessageResponse(
response_id,
std::vector<uint8_t>(buffer, buffer + data.length_in_bytes()));
}
}
void _RespondToPlatformMessage(Dart_NativeArguments args) {
tonic::DartCallStatic(&RespondToPlatformMessage, args);
}
} // namespace
Dart_Handle ToByteData(const std::vector<uint8_t>& buffer) {
Dart_Handle data_handle =
Dart_NewTypedData(Dart_TypedData_kByteData, buffer.size());
if (Dart_IsError(data_handle))
return data_handle;
Dart_TypedData_Type type;
void* data = nullptr;
intptr_t num_bytes = 0;
FML_CHECK(!Dart_IsError(
Dart_TypedDataAcquireData(data_handle, &type, &data, &num_bytes)));
memcpy(data, buffer.data(), num_bytes);
Dart_TypedDataReleaseData(data_handle);
return data_handle;
}
WindowClient::~WindowClient() {}
Window::Window(WindowClient* client) : client_(client) {}
Window::~Window() {}
void Window::DidCreateIsolate() {
library_.Set(DartState::Current(), Dart_LookupLibrary(ToDart("dart:ui")));
}
void Window::UpdateWindowMetrics(const ViewportMetrics& metrics) {
viewport_metrics_ = metrics;
std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
if (!dart_state)
return;
tonic::DartState::Scope scope(dart_state);
DartInvokeField(library_.value(), "_updateWindowMetrics",
{
ToDart(metrics.device_pixel_ratio),
ToDart(metrics.physical_width),
ToDart(metrics.physical_height),
ToDart(metrics.physical_padding_top),
ToDart(metrics.physical_padding_right),
ToDart(metrics.physical_padding_bottom),
ToDart(metrics.physical_padding_left),
ToDart(metrics.physical_view_inset_top),
ToDart(metrics.physical_view_inset_right),
ToDart(metrics.physical_view_inset_bottom),
ToDart(metrics.physical_view_inset_left),
});
}
void Window::UpdateLocales(const std::vector<std::string>& locales) {
std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
if (!dart_state)
return;
tonic::DartState::Scope scope(dart_state);
DartInvokeField(library_.value(), "_updateLocales",
{
tonic::ToDart<std::vector<std::string>>(locales),
});
}
void Window::UpdateUserSettingsData(const std::string& data) {
std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
if (!dart_state)
return;
tonic::DartState::Scope scope(dart_state);
DartInvokeField(library_.value(), "_updateUserSettingsData",
{
StdStringToDart(data),
});
}
void Window::UpdateSemanticsEnabled(bool enabled) {
std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
if (!dart_state)
return;
tonic::DartState::Scope scope(dart_state);
DartInvokeField(library_.value(), "_updateSemanticsEnabled",
{ToDart(enabled)});
}
void Window::UpdateAccessibilityFeatures(int32_t values) {
std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
if (!dart_state)
return;
tonic::DartState::Scope scope(dart_state);
DartInvokeField(library_.value(), "_updateAccessibilityFeatures",
{ToDart(values)});
}
void Window::DispatchPlatformMessage(fml::RefPtr<PlatformMessage> message) {
std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
if (!dart_state)
return;
tonic::DartState::Scope scope(dart_state);
Dart_Handle data_handle =
(message->hasData()) ? ToByteData(message->data()) : Dart_Null();
if (Dart_IsError(data_handle))
return;
int response_id = 0;
if (auto response = message->response()) {
response_id = next_response_id_++;
pending_responses_[response_id] = response;
}
DartInvokeField(
library_.value(), "_dispatchPlatformMessage",
{ToDart(message->channel()), data_handle, ToDart(response_id)});
}
void Window::DispatchPointerDataPacket(const PointerDataPacket& packet) {
std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
if (!dart_state)
return;
tonic::DartState::Scope scope(dart_state);
Dart_Handle data_handle = ToByteData(packet.data());
if (Dart_IsError(data_handle))
return;
DartInvokeField(library_.value(), "_dispatchPointerDataPacket",
{data_handle});
}
void Window::DispatchSemanticsAction(int32_t id,
SemanticsAction action,
std::vector<uint8_t> args) {
std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
if (!dart_state)
return;
tonic::DartState::Scope scope(dart_state);
Dart_Handle args_handle = (args.empty()) ? Dart_Null() : ToByteData(args);
if (Dart_IsError(args_handle))
return;
DartInvokeField(
library_.value(), "_dispatchSemanticsAction",
{ToDart(id), ToDart(static_cast<int32_t>(action)), args_handle});
}
void Window::BeginFrame(fml::TimePoint frameTime) {
std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
if (!dart_state)
return;
tonic::DartState::Scope scope(dart_state);
int64_t microseconds = (frameTime - fml::TimePoint()).ToMicroseconds();
DartInvokeField(library_.value(), "_beginFrame",
{
Dart_NewInteger(microseconds),
});
UIDartState::Current()->FlushMicrotasksNow();
DartInvokeField(library_.value(), "_drawFrame", {});
}
void Window::CompletePlatformMessageEmptyResponse(int response_id) {
if (!response_id)
return;
auto it = pending_responses_.find(response_id);
if (it == pending_responses_.end())
return;
auto response = std::move(it->second);
pending_responses_.erase(it);
response->CompleteEmpty();
}
void Window::CompletePlatformMessageResponse(int response_id,
std::vector<uint8_t> data) {
if (!response_id)
return;
auto it = pending_responses_.find(response_id);
if (it == pending_responses_.end())
return;
auto response = std::move(it->second);
pending_responses_.erase(it);
response->Complete(std::make_unique<fml::DataMapping>(std::move(data)));
}
void Window::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register({
{"Window_defaultRouteName", DefaultRouteName, 1, true},
{"Window_scheduleFrame", ScheduleFrame, 1, true},
{"Window_sendPlatformMessage", _SendPlatformMessage, 4, true},
{"Window_respondToPlatformMessage", _RespondToPlatformMessage, 3, true},
{"Window_render", Render, 2, true},
{"Window_updateSemantics", UpdateSemantics, 2, true},
{"Window_setIsolateDebugName", SetIsolateDebugName, 2, true},
});
}
} // namespace blink
| krisgiesing/sky_engine | lib/ui/window/window.cc | C++ | bsd-3-clause | 10,895 |
<?php
/*
CalendarServer example
This server features CalDAV support
*/
// settings
date_default_timezone_set('Canada/Eastern');
// If you want to run the SabreDAV server in a custom location (using mod_rewrite for instance)
// You can override the baseUri here.
// $baseUri = '/';
/* Database */
$pdo = new PDO('sqlite:data/db.sqlite');
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
//Mapping PHP errors to exceptions
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
// Files we need
require_once 'vendor/autoload.php';
// Backends
$authBackend = new Sabre\DAV\Auth\Backend\PDO($pdo);
$calendarBackend = new Sabre\CalDAV\Backend\PDO($pdo);
$principalBackend = new Sabre\DAVACL\PrincipalBackend\PDO($pdo);
// Directory structure
$tree = [
new Sabre\CalDAV\Principal\Collection($principalBackend),
new Sabre\CalDAV\CalendarRootNode($principalBackend, $calendarBackend),
];
$server = new Sabre\DAV\Server($tree);
if (isset($baseUri))
$server->setBaseUri($baseUri);
/* Server Plugins */
$authPlugin = new Sabre\DAV\Auth\Plugin($authBackend,'SabreDAV');
$server->addPlugin($authPlugin);
$aclPlugin = new Sabre\DAVACL\Plugin();
$server->addPlugin($aclPlugin);
/* CalDAV support */
$caldavPlugin = new Sabre\CalDAV\Plugin();
$server->addPlugin($caldavPlugin);
/* Calendar subscription support */
$server->addPlugin(
new Sabre\CalDAV\Subscription\Plugin()
);
// Support for html frontend
$browser = new Sabre\DAV\Browser\Plugin();
$server->addPlugin($browser);
// And off we go!
$server->exec();
| DeepDiver1975/sabre-dav | examples/calendarserver.php | PHP | bsd-3-clause | 1,682 |
<?php
/**
* Logo helper
*/
class Zend_View_Helper_Logo extends Zend_View_Helper_Abstract {
public $view;
public function setView(Zend_View_Interface $view) {
$this->view = $view;
}
public function logo($data = array()) {
$isp = Shineisp_Registry::get('ISP');
if (! empty ( $isp->logo )) {
if (file_exists ( PUBLIC_PATH . "/documents/isp/" . $isp->logo )) {
$this->view->file = "/documents/isp/" . $isp->logo;
}
}
$this->view->logotitle = $isp->company;
$this->view->slogan = $isp->slogan;
return $this->view->render ( 'partials/logo.phtml' );
}
} | tanerkuc/shineisp | application/modules/default/views/helpers/Logo.php | PHP | bsd-3-clause | 588 |
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace Centro\Model\Data;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
use Zend\Validator\NotEmpty;
class Item
{
public $id;
public $titulo;
public $enlace;
public $descripcion;
public $fecha_publicacion;
public $canal_id;
protected $inputFilter;
public function exchangeArray($data)
{
$this->id = (!empty($data['id'])) ? $data['id'] : null;
$this->titulo = (!empty($data['titulo'])) ? $data['titulo'] : null;
$this->enlace = (!empty($data['enlace'])) ? $data['enlace'] : null;
$this->descripcion = (!empty($data['descripcion'])) ? $data['descripcion'] : null;
$this->fecha_publicacion = (!empty($data['fecha_publicacion'])) ? $data['fecha_publicacion'] : null;
$this->canal_id = (!empty($data['canal_id'])) ? $data['canal_id'] : null;
}
public function getArrayCopy() {
return get_object_vars($this);
}
public function setInputFilter(InputFilterInterface $inputFilter) {
throw new \Exception("Not used");
}
public function getInputFilter() {
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
));
$inputFilter->add(array(
'name' => 'canal_id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
));
$inputFilter->add(array(
'name' => 'titulo',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'NotEmpty',
'options' => array(
'setMessages' => array(
NotEmpty::IS_EMPTY => 'Campo obligatorio',
),
),
'break_chain_on_failure' => true,
),
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 200,
'setMessages' => array(
'stringLengthTooLong' => 'La cadena ingresada es mayor al limite permitido',
),
),
'break_chain_on_failure' => true,
),
),
));
$inputFilter->add(array(
'name' => 'enlace',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'NotEmpty',
'options' => array(
'setMessages' => array(
NotEmpty::IS_EMPTY => 'Campo obligatorio',
),
),
'break_chain_on_failure' => true,
),
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 200,
'setMessages' => array(
'stringLengthTooLong' => 'Cadena de caracteres mayor al limite permitido',
),
),
'break_chain_on_failure' => true,
),
array(
'name' => 'Regex',
'options' => array(
'pattern' => '#(http://|https://).+#',
'message' => 'Formato del url ingresada no valido',
),
'break_chain_on_failure' => true,
),
),
));
$inputFilter->add(array(
'name' => 'descripcion',
'required' => false,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 500,
'setMessages' => array(
'stringLengthTooLong' => 'Cadena de caracteres mayor al limite permitido',
),
),
'break_chain_on_failure' => true,
),
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
} | tavoot/cysdusac | module/Centro/src/Centro/Model/Data/Item.php | PHP | bsd-3-clause | 5,949 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_char_snprintf_53d.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806.label.xml
Template File: sources-sink-53d.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Initialize data as a large string
* GoodSource: Initialize data as a small string
* Sink: snprintf
* BadSink : Copy data to string using snprintf
* Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define SNPRINTF _snprintf
#else
#define SNPRINTF snprintf
#endif
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_char_snprintf_53
{
/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */
#ifndef OMITBAD
void badSink_d(char * data)
{
{
char dest[50] = "";
/* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */
SNPRINTF(dest, strlen(data), "%s", data);
printLine(data);
delete [] data;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink_d(char * data)
{
{
char dest[50] = "";
/* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */
SNPRINTF(dest, strlen(data), "%s", data);
printLine(data);
delete [] data;
}
}
#endif /* OMITGOOD */
} /* close namespace */
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s04/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_char_snprintf_53d.cpp | C++ | bsd-3-clause | 1,666 |
# Merge stimuli information from spike2 mat file into Kwik file
import h5py as h5
import tables
import os
import numpy as np
import argparse
import glob
try: import simplejson as json
except ImportError: import json
from klusta_pipeline.dataio import load_recordings, save_info, load_digmark, load_stim_info
from klusta_pipeline.utils import get_import_list, validate_merge, realign
def get_args():
parser = argparse.ArgumentParser(description='Compile Spike2 epoch .mat files into KlustaKwik KWD file.')
parser.add_argument('path', default = './', nargs='?',
help='directory containing all of the mat files to compile')
parser.add_argument('dest', default = './', nargs='?',
help='destination directory for kwd and other files')
return parser.parse_args()
def get_rec_samples(kwd_file,index):
with h5.File(kwd_file, 'r') as kwd:
return kwd['/recordings/{}/data'.format(index)].shape[0]
def merge_recording_info(klu_path,mat_path):
batch = klu_path.split('__')[-1]
with open(os.path.join(klu_path,batch+'_info.json')) as f:
info = json.load(f)
assert 'recordings' not in info
import_list = get_import_list(mat_path,info['exports'])
for item in import_list:
assert os.path.exists(item), item
mat_data = validate_merge(import_list,info['omit'])
fs = info['params']['fs']
chans = set(mat_data[0]['chans'])
for d2 in mat_data[1:]:
chans = chans.intersection(d2['chans'])
chans = list(chans)
for i,m in zip(info['exports'],mat_data):
i['chans'] = chans
rec_list = []
for import_file in import_list:
recordings = load_recordings(import_file,chans)
for r in recordings:
rec = realign(r,chans,fs,'spline')
del rec['data']
rec_list.append(rec)
info['recordings'] = [{k:v for k,v in rec.items() if k is not 'data'} for rec in rec_list]
save_info(klu_path,info)
return info
def merge(spike2mat_folder, kwik_folder):
info_json = glob.glob(os.path.join(kwik_folder,'*_info.json'))[0]
with open(info_json, 'r') as f:
info = json.load(f)
kwik_data_file = os.path.join(kwik_folder,info['name']+'.kwik')
kwd_raw_file = os.path.join(kwik_folder,info['name']+'.raw.kwd')\
with tables.open_file(kwik_data_file, 'r+') as kkfile:
digmark_timesamples = []
digmark_recording = []
digmark_codes = []
stimulus_timesamples = []
stimulus_recording = []
stimulus_codes = []
stimulus_names = []
spike_recording_obj = kkfile.get_node('/channel_groups/0/spikes','recording')
spike_time_samples_obj = kkfile.get_node('/channel_groups/0/spikes','time_samples')
spike_recording = spike_recording_obj.read()
spike_time_samples = spike_time_samples_obj.read()
try:
assert 'recordings' in info
except AssertionError:
info = merge_recording_info(kwik_folder,spike2mat_folder)
order = np.sort([str(ii) for ii in range(len(info['recordings']))])
print order
print len(spike_recording)
is_done = np.zeros(spike_recording.shape,np.bool_)
for rr,rid_str in enumerate(order):
# rr: index of for-loop
# rid: recording id
# rid_str: string form of recording id
rid = int(rid_str)
rec = info['recordings'][rid]
n_samps = get_rec_samples(kwd_raw_file,rid)
#is_done = np.vectorize(lambda x: x not in done)
todo = ~is_done & (spike_time_samples >= n_samps)
print "rec {}: {} spikes done".format(rid,is_done.sum())
print "setting {} spikes to next cluster".format(todo.sum())
if todo.sum()>0:
spike_recording[todo] = int(order[rr+1])
spike_time_samples[todo] -= n_samps
is_done = is_done | ~todo
print is_done.sum()
t0 = rec['start_time']
fs = rec['fs']
dur = float(n_samps) / fs
s2mat = os.path.split(rec['file_origin'])[-1]
s2mat = os.path.join(spike2mat_folder, s2mat)
codes, times = load_digmark(s2mat)
rec_mask = (times >= t0) * (times < (t0+dur))
codes = codes[rec_mask]
times = times[rec_mask] - t0
time_samples = (times * fs).round().astype(np.uint64)
recording = rid * np.ones(codes.shape,np.uint16)
digmark_timesamples.append(time_samples)
digmark_recording.append(recording)
digmark_codes.append(codes)
codes, times, names = load_stim_info(s2mat)
rec_mask = (times >= t0) * (times < (t0+dur))
codes = codes[rec_mask]
names = names[rec_mask]
times = times[rec_mask] - t0
time_samples = (times * fs).round().astype(np.uint64)
recording = rid * np.ones(codes.shape,np.uint16)
stimulus_timesamples.append(time_samples)
stimulus_recording.append(recording)
stimulus_codes.append(codes)
stimulus_names.append(names)
digmark_timesamples = np.concatenate(digmark_timesamples)
digmark_recording = np.concatenate(digmark_recording)
digmark_codes = np.concatenate(digmark_codes)
stimulus_timesamples = np.concatenate(stimulus_timesamples)
stimulus_recording = np.concatenate(stimulus_recording)
stimulus_codes = np.concatenate(stimulus_codes)
stimulus_names = np.concatenate(stimulus_names)
print digmark_timesamples.dtype
print digmark_recording.dtype
print digmark_codes.dtype
print stimulus_timesamples.dtype
print stimulus_recording.dtype
print stimulus_codes.dtype
print stimulus_names.dtype
kkfile.create_group("/", "event_types", "event_types")
kkfile.create_group("/event_types", "DigMark")
kkfile.create_earray("/event_types/DigMark", 'time_samples', obj=digmark_timesamples)
kkfile.create_earray("/event_types/DigMark", 'recording', obj=digmark_recording)
kkfile.create_earray("/event_types/DigMark", 'codes', obj=digmark_codes)
kkfile.create_group("/event_types", "Stimulus")
kkfile.create_earray("/event_types/Stimulus", 'time_samples', obj=stimulus_timesamples)
kkfile.create_earray("/event_types/Stimulus", 'recording', obj=stimulus_recording)
kkfile.create_earray("/event_types/Stimulus", 'codes', obj=stimulus_codes)
kkfile.create_earray("/event_types/Stimulus", 'text', obj=stimulus_names)
spike_recording_obj[:] = spike_recording
spike_time_samples_obj[:] = spike_time_samples
def main():
args = get_args()
spike2mat_folder = os.path.abspath(args.path)
kwik_folder = os.path.abspath(args.dest)
merge(spike2mat_folder, kwik_folder)
if __name__ == '__main__':
main()
| gentnerlab/klusta-pipeline | klusta_pipeline/merge_stim_kwik.py | Python | bsd-3-clause | 7,008 |
#include "studiopaletteviewer.h"
#include "palettesscanpopup.h"
#include "toonz/studiopalettecmd.h"
#include "toonzqt/menubarcommand.h"
#include "floatingpanelcommand.h"
#include "toonzqt/gutil.h"
#include "toonz/tpalettehandle.h"
#include "toonz/txshlevelhandle.h"
#include "toonzqt/paletteviewer.h"
#include "toonzutil.h"
#include "tconvert.h"
#include "toonz/txshsimplelevel.h"
#include <QHeaderView>
#include <QContextMenuEvent>
#include <QMenu>
#include <QUrl>
#include <QPainter>
#include <QVBoxLayout>
#include <QToolBar>
#include <QSplitter>
#include "toonz/tscenehandle.h"
#include "toonz/toonzscene.h"
#include "toonz/sceneproperties.h"
using namespace std;
using namespace PaletteViewerGUI;
//=============================================================================
namespace
{
//-----------------------------------------------------------------------------
/*! Return true if path is in folder \b rootPath of \b StudioPalette.
*/
bool isInStudioPaletteFolder(TFilePath path, TFilePath rootPath)
{
if (path.getType() != "tpl")
return false;
StudioPalette *studioPlt = StudioPalette::instance();
std::vector<TFilePath> childrenPath;
studioPlt->getChildren(childrenPath, rootPath);
int i;
for (i = 0; i < (int)childrenPath.size(); i++) {
if (path == childrenPath[i])
return true;
else if (isInStudioPaletteFolder(path, childrenPath[i]))
return true;
}
return false;
}
//-----------------------------------------------------------------------------
/*! Return true if path is in a \b StudioPalette folder.
*/
bool isInStudioPalette(TFilePath path)
{
if (path.getType() != "tpl")
return false;
StudioPalette *studioPlt = StudioPalette::instance();
if (isInStudioPaletteFolder(path, studioPlt->getLevelPalettesRoot()))
return true;
if (isInStudioPaletteFolder(path, studioPlt->getCleanupPalettesRoot()))
return true;
if (isInStudioPaletteFolder(path, TFilePath("C:\\Toonz 6.0 stuff\\projects\\Project Palettes"))) //DAFARE studioPlt->getProjectPalettesRoot(); Per ora lo fisso))
return true;
return false;
}
//-----------------------------------------------------------------------------
} //namespace
//-----------------------------------------------------------------------------
//=============================================================================
/*! \class StudioPaletteTreeViewer
\brief The StudioPaletteTreeViewer class provides an object to view and manage
palettes files.
Inherits \b QTreeWidget and \b StudioPalette::Listener.
This object provides interface for class \b StudioPalette.
StudioPaletteTreeViewer is a \b QTreeWidget with three root item related to
level palette folder, cleanup palette folder and current project palette folder,
the three root folder of \b StudioPalette.
*/
/*! \fn void StudioPaletteTreeViewer::onStudioPaletteTreeChange()
Overriden from StudioPalette::Listener.
\fn void StudioPaletteTreeViewer::onStudioPaletteMove(const TFilePath &dstPath, const TFilePath &srcPath)
Overriden from StudioPalette::Listener.
\fn void StudioPaletteTreeViewer::onStudioPaletteChange(const TFilePath &palette)
Overriden from StudioPalette::Listener.
*/
StudioPaletteTreeViewer::StudioPaletteTreeViewer(QWidget *parent,
TPaletteHandle *studioPaletteHandle,
TPaletteHandle *levelPaletteHandle)
: QTreeWidget(parent), m_dropItem(0), m_stdPltHandle(studioPaletteHandle), m_levelPltHandle(levelPaletteHandle), m_sceneHandle(0), m_levelHandle(0)
{
header()->close();
setIconSize(QSize(20, 20));
//Da sistemare le icone dei tre folder principali
static QPixmap PaletteIconPxmp(":Resources/icon.png");
QList<QTreeWidgetItem *> paletteItems;
StudioPalette *studioPlt = StudioPalette::instance();
//static QPixmap PaletteLevelIconPxmp(":Resources/studio_plt_toonz.png");
TFilePath levelPltPath = studioPlt->getLevelPalettesRoot();
paletteItems.append(createRootItem(levelPltPath, PaletteIconPxmp));
//static QPixmap PaletteCleanupIconPxmp(":Resources/studio_plt_cleanup.png");
TFilePath cleanupPltPath = studioPlt->getCleanupPalettesRoot();
paletteItems.append(createRootItem(cleanupPltPath, PaletteIconPxmp));
//DAFARE
//Oss.: se il folder non c'e' non fa nulla, non si aprono neanche i menu' da tasto destro!
//static QPixmap PaletteProjectIconPxmp(":Resources/studio_plt_project.png");
TFilePath projectPltPath = TFilePath("C:\\Toonz 6.0 stuff\\projects\\Project Palettes"); //studioPlt->getProjectPalettesRoot(); Per ora lo fisso
paletteItems.append(createRootItem(projectPltPath, PaletteIconPxmp));
insertTopLevelItems(0, paletteItems);
connect(this, SIGNAL(itemChanged(QTreeWidgetItem *, int)),
this, SLOT(onItemChanged(QTreeWidgetItem *, int)));
connect(this, SIGNAL(itemExpanded(QTreeWidgetItem *)),
this, SLOT(onItemExpanded(QTreeWidgetItem *)));
connect(this, SIGNAL(itemCollapsed(QTreeWidgetItem *)),
this, SLOT(onItemCollapsed(QTreeWidgetItem *)));
connect(this, SIGNAL(itemSelectionChanged()),
this, SLOT(onItemSelectionChanged()));
m_palettesScanPopup = new PalettesScanPopup();
setAcceptDrops(true);
}
//-----------------------------------------------------------------------------
StudioPaletteTreeViewer::~StudioPaletteTreeViewer()
{
}
//-----------------------------------------------------------------------------
void StudioPaletteTreeViewer::setLevelPaletteHandle(TPaletteHandle *paletteHandle)
{
m_levelPltHandle = paletteHandle;
}
//-----------------------------------------------------------------------------
void StudioPaletteTreeViewer::setStdPaletteHandle(TPaletteHandle *stdPltHandle)
{
m_stdPltHandle = stdPltHandle;
}
//-----------------------------------------------------------------------------
void StudioPaletteTreeViewer::setSceneHandle(TSceneHandle *sceneHandle)
{
m_sceneHandle = sceneHandle;
}
//-----------------------------------------------------------------------------
void StudioPaletteTreeViewer::setLevelHandle(TXshLevelHandle *levelHandle)
{
m_levelHandle = levelHandle;
}
//-----------------------------------------------------------------------------
/*! Create root item related to path \b path.
*/
QTreeWidgetItem *StudioPaletteTreeViewer::createRootItem(TFilePath path, const QPixmap pix)
{
QString rootName = QString(path.getName().c_str());
QTreeWidgetItem *rootItem = new QTreeWidgetItem((QTreeWidget *)0, QStringList(rootName));
rootItem->setIcon(0, pix);
rootItem->setData(1, Qt::UserRole, toQString(path));
refreshItem(rootItem);
return rootItem;
}
//-----------------------------------------------------------------------------
/*! Return true if \b item is a root item; false otherwis.
*/
bool StudioPaletteTreeViewer::isRootItem(QTreeWidgetItem *item)
{
assert(item);
TFilePath path = getFolderPath(item);
//DAFARE
//Oss.: se il folder non c'e' non fa nulla, non si aprono neanche i menu' da tasto destro!
//static QPixmap PaletteProjectIconPxmp(":Resources/studio_plt_project.png");
TFilePath projectPltPath = TFilePath("C:\\Toonz 6.0 stuff\\projects\\Project Palettes"); //studioPlt->getProjectPalettesRoot(); Per ora lo fisso
StudioPalette *stdPalette = StudioPalette::instance();
if (path == stdPalette->getCleanupPalettesRoot() ||
path == stdPalette->getLevelPalettesRoot() ||
path == projectPltPath)
return true;
return false;
}
//-----------------------------------------------------------------------------
/*! Create a new item related to path \b path.
*/
QTreeWidgetItem *StudioPaletteTreeViewer::createItem(const TFilePath path)
{
static QPixmap PaletteIconPxmp(":Resources/icon.png");
static QPixmap FolderIconPxmp(":Resources/newfolder_over.png");
StudioPalette *studioPlt = StudioPalette::instance();
QString itemName = QString(path.getName().c_str());
QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidget *)0, QStringList(itemName));
if (studioPlt->isPalette(path))
item->setIcon(0, PaletteIconPxmp);
else if (studioPlt->isFolder(path))
item->setIcon(0, FolderIconPxmp);
item->setData(1, Qt::UserRole, toQString(path));
item->setFlags(item->flags() | Qt::ItemIsEditable);
return item;
}
//-----------------------------------------------------------------------------
/*! Return path related to item \b item if \b item exist, otherwise return an
empty path \b TFilePath.
*/
TFilePath StudioPaletteTreeViewer::getFolderPath(QTreeWidgetItem *item)
{
TFilePath path = (item) ? TFilePath(item->data(1, Qt::UserRole).toString().toStdWString())
: TFilePath();
return path;
}
//-----------------------------------------------------------------------------
/*! Return current item path.
*/
TFilePath StudioPaletteTreeViewer::getCurrentFolderPath()
{
return getFolderPath(currentItem());
}
//-----------------------------------------------------------------------------
/*! Return item identified by \b path; if it doesn't exist return 0.
*/
QTreeWidgetItem *StudioPaletteTreeViewer::getItem(const TFilePath path)
{
QList<QTreeWidgetItem *> oldItems = findItems(QString(""), Qt::MatchContains, 0);
if (oldItems.isEmpty())
return 0;
int i;
for (i = 0; i < (int)oldItems.size(); i++) {
TFilePath oldItemPath(oldItems[i]->data(1, Qt::UserRole).toString().toStdWString());
if (oldItemPath == path)
return oldItems[i];
else {
QTreeWidgetItem *item = getFolderItem(oldItems[i], path);
if (item)
return item;
}
}
return 0;
}
//-----------------------------------------------------------------------------
/*! Return item child of \b parent identified by \b path; if it doesn't exist return 0.
*/
QTreeWidgetItem *StudioPaletteTreeViewer::getFolderItem(QTreeWidgetItem *parent, const TFilePath path)
{
int childrenCount = parent->childCount();
int i;
for (i = 0; i < childrenCount; i++) {
QTreeWidgetItem *item = parent->child(i);
if (getFolderPath(item) == path)
return item;
else {
item = getFolderItem(item, path);
if (item)
return item;
}
}
return 0;
}
//-----------------------------------------------------------------------------
/*! Refresh all item of three root item in tree and preserve current item.
*/
void StudioPaletteTreeViewer::refresh()
{
StudioPalette *studioPlt = StudioPalette::instance();
TFilePath levelPltPath = studioPlt->getLevelPalettesRoot();
refreshItem(getItem(levelPltPath));
TFilePath cleanupPltPath = studioPlt->getCleanupPalettesRoot();
refreshItem(getItem(cleanupPltPath));
//DAFARE
TFilePath projectPltPath = TFilePath("C:\\Toonz 6.0 stuff\\projects\\Project Palettes"); //studioPlt->getProjectPalettesRoot(); Per ora lo fisso
refreshItem(getItem(projectPltPath));
}
//-----------------------------------------------------------------------------
/*! Refresh item \b item and its children; take path concerning \b item and
compare \b StudioPalette folder in path with folder in item.
If are not equal add or remove child to current \b item. Recall itself
for each item child.
*/
void StudioPaletteTreeViewer::refreshItem(QTreeWidgetItem *item)
{
TFilePath folderPath = getFolderPath(item);
assert(folderPath != TFilePath());
std::vector<TFilePath> childrenPath;
StudioPalette::instance()->getChildren(childrenPath, folderPath);
int currentChildCount = item->childCount();
std::vector<QTreeWidgetItem *> currentChildren;
int i;
for (i = 0; i < currentChildCount; i++)
currentChildren.push_back(item->child(i));
int childrenPathCount = childrenPath.size();
int itemIndex = 0;
int pathIndex = 0;
while (itemIndex < currentChildCount || pathIndex < childrenPathCount) {
TFilePath path = (pathIndex < childrenPathCount) ? childrenPath[pathIndex] : TFilePath();
QTreeWidgetItem *currentItem = (itemIndex < currentChildCount) ? currentChildren[itemIndex] : 0;
TFilePath currentItemPath = getFolderPath(currentItem);
if (path == currentItemPath) {
itemIndex++;
pathIndex++;
refreshItem(currentItem);
} else if ((!path.isEmpty() && path < currentItemPath) ||
currentItemPath.isEmpty()) {
currentItem = createItem(path);
item->insertChild(pathIndex, currentItem);
refreshItem(currentItem);
pathIndex++;
} else {
assert(currentItemPath < path || path.isEmpty());
assert(currentItem);
item->removeChild(currentItem);
itemIndex++;
}
}
}
//-----------------------------------------------------------------------------
/*! If item \b item name changed update name item related path name in \b StudioPalette.
*/
void StudioPaletteTreeViewer::onItemChanged(QTreeWidgetItem *item, int column)
{
if (item != currentItem())
return;
string name = item->text(column).toStdString();
TFilePath oldPath = getCurrentFolderPath();
if (oldPath.isEmpty() || name.empty() || oldPath.getName() == name)
return;
TFilePath newPath(oldPath.getParentDir() + TFilePath(name + oldPath.getDottedType()));
try {
StudioPaletteCmd::movePalette(newPath, oldPath);
} catch (TException &e) {
error("Can't rename palette: " + QString(toString(e.getMessage()).c_str()));
} catch (...) {
error("Can't rename palette");
}
setCurrentItem(getItem(newPath));
}
//-----------------------------------------------------------------------------
/*! If item \b item is expanded change item icon.
*/
void StudioPaletteTreeViewer::onItemExpanded(QTreeWidgetItem *item)
{
if (!item || isRootItem(item))
return;
static QPixmap FolderIconExpandedPxmp(":Resources/folder_open.png");
item->setIcon(0, FolderIconExpandedPxmp);
}
//-----------------------------------------------------------------------------
/*! If item \b item is collapsed change item icon.
*/
void StudioPaletteTreeViewer::onItemCollapsed(QTreeWidgetItem *item)
{
if (!item || isRootItem(item))
return;
static QPixmap FolderIconPxmp(":Resources/newfolder_over.png");
item->setIcon(0, FolderIconPxmp);
}
//-----------------------------------------------------------------------------
/*! If current item is a palette set current studioPalette to it.
*/
void StudioPaletteTreeViewer::onItemSelectionChanged()
{
TFilePath path = getCurrentFolderPath();
if (!m_stdPltHandle || path.getType() != "tpl")
return;
if (m_stdPltHandle->getPalette() && m_stdPltHandle->getPalette()->getDirtyFlag()) {
QString question;
question = "Current Studio Palette has been modified.\n"
"Do you want to save your changes?";
int ret = MsgBox(0, question, QObject::tr("Save"), QObject::tr("Don't Save"), QObject::tr("Cancel"), 0);
TPaletteP oldPalette = m_stdPltHandle->getPalette();
TFilePath oldPath = StudioPalette::instance()->getPalettePath(oldPalette->getGlobalName());
if (ret == 3) {
setCurrentItem(getItem(oldPath));
return;
}
if (ret == 1)
StudioPalette::instance()->save(oldPath, oldPalette.getPointer());
oldPalette->setDirtyFlag(false);
}
m_stdPltHandle->setPalette(StudioPalette::instance()->getPalette(path, true));
m_stdPltHandle->notifyPaletteSwitched();
}
//-----------------------------------------------------------------------------
/*! Create a new \b StudioPalette palette in current item path.
*/
void StudioPaletteTreeViewer::addNewPlt()
{
if (!currentItem()) {
error("Error: No folder selected.");
return;
}
TFilePath newPath;
try {
newPath = StudioPaletteCmd::createPalette(getCurrentFolderPath(), "", 0);
} catch (TException &e) {
error("Can't create palette: " + QString(toString(e.getMessage()).c_str()));
} catch (...) {
error("Can't create palette");
}
setCurrentItem(getItem(newPath));
}
//-----------------------------------------------------------------------------
/*! Create a new \b StudioPalette folder in current item path.
*/
void StudioPaletteTreeViewer::addNewFolder()
{
if (!currentItem()) {
error("Error: No folder selected.");
return;
}
TFilePath newPath;
try {
newPath = StudioPaletteCmd::addFolder(getCurrentFolderPath());
} catch (TException &e) {
error("Can't create palette folder: " + QString(toString(e.getMessage()).c_str()));
} catch (...) {
error("Can't create palette folder");
}
setCurrentItem(getItem(newPath));
}
//-----------------------------------------------------------------------------
/*! Delete current item path from \b StudioPalette. If item is a not empty
folder send a question to know if must delete item or not.
*/
void StudioPaletteTreeViewer::deleteItem()
{
if (!currentItem()) {
error("Nothing to delete");
return;
}
QTreeWidgetItem *parent = currentItem()->parent();
if (!parent)
return;
if (currentItem()->childCount() > 0) {
QString question;
question = tr("This folder is not empty. Delete anyway?");
int ret = MsgBox(0, question, QObject::tr("Yes"), QObject::tr("No"));
if (ret == 0 || ret == 2)
return;
}
TFilePath path = getCurrentFolderPath();
StudioPalette *studioPlt = StudioPalette::instance();
if (studioPlt->isFolder(path)) {
try {
StudioPaletteCmd::deleteFolder(path);
} catch (TException &e) {
error("Can't delete palette: " + QString(toString(e.getMessage()).c_str()));
} catch (...) {
error("Can't delete palette");
}
} else {
assert(studioPlt->isPalette(path));
try {
StudioPaletteCmd::deletePalette(path);
} catch (TException &e) {
error("Can't delete palette: " + QString(toString(e.getMessage()).c_str()));
} catch (...) {
error("Can't delete palette");
}
}
}
//-----------------------------------------------------------------------------
/*! Open a \b PalettesScanPopup.
*/
void StudioPaletteTreeViewer::searchForPlt()
{
m_palettesScanPopup->setCurrentFolder(getCurrentFolderPath());
int ret = m_palettesScanPopup->exec();
if (ret == QDialog::Accepted)
refresh();
}
//-----------------------------------------------------------------------------
/*! Recall \b StudioPaletteCmd::loadIntoCleanupPalette.
*/
void StudioPaletteTreeViewer::loadInCurrentCleanupPlt()
{
StudioPaletteCmd::loadIntoCleanupPalette(m_levelPltHandle, m_sceneHandle, getCurrentFolderPath());
}
//-----------------------------------------------------------------------------
/*! Recall \b StudioPaletteCmd::replaceWithCleanupPalette.
*/
void StudioPaletteTreeViewer::replaceCurrentCleanupPlt()
{
StudioPaletteCmd::replaceWithCleanupPalette(m_levelPltHandle, m_stdPltHandle,
m_sceneHandle, getCurrentFolderPath());
}
//-----------------------------------------------------------------------------
/*! Recall \b StudioPaletteCmd::loadIntoCurrentPalette.
*/
void StudioPaletteTreeViewer::loadInCurrentPlt()
{
StudioPaletteCmd::loadIntoCurrentPalette(m_levelPltHandle, m_sceneHandle,
getCurrentFolderPath());
}
//-----------------------------------------------------------------------------
/*! Recall \b StudioPaletteCmd::replaceWithCurrentPalette.
*/
void StudioPaletteTreeViewer::replaceCurrentPlt()
{
StudioPaletteCmd::replaceWithCurrentPalette(m_levelPltHandle, m_stdPltHandle,
m_sceneHandle, getCurrentFolderPath());
}
//-----------------------------------------------------------------------------
/*! Recall \b StudioPaletteCmd::mergeIntoCurrentPalette.
*/
void StudioPaletteTreeViewer::mergeToCurrentPlt()
{
StudioPaletteCmd::mergeIntoCurrentPalette(m_levelPltHandle, m_sceneHandle,
getCurrentFolderPath());
}
//-----------------------------------------------------------------------------
void StudioPaletteTreeViewer::paintEvent(QPaintEvent *event)
{
QTreeWidget::paintEvent(event);
QPainter p(viewport());
if (m_dropItem) {
QRect rect = visualItemRect(m_dropItem).adjusted(0, 0, -5, 0);
p.setPen(Qt::red);
p.drawRect(rect);
}
}
//-----------------------------------------------------------------------------
/*! Open a context menu considering current item data role \b Qt::UserRole.
*/
void StudioPaletteTreeViewer::contextMenuEvent(QContextMenuEvent *event)
{
TFilePath path = getCurrentFolderPath();
StudioPalette *studioPlt = StudioPalette::instance();
// Verify if click position is in a row containing an item.
QRect rect = visualItemRect(currentItem());
if (!QRect(0, rect.y(), width(), rect.height()).contains(event->pos()))
return;
bool isLevelFolder = (studioPlt->isFolder(path) && !studioPlt->isCleanupFolder(path));
QMenu menu(this);
if (isLevelFolder) {
createMenuAction(menu, tr("New Palette"), "addNewPlt()");
createMenuAction(menu, tr("New Folder"), "addNewFolder()");
} else if (studioPlt->isCleanupFolder(path)) {
createMenuAction(menu, tr("New Cleanup Palette"), "addNewPlt()");
createMenuAction(menu, tr("New Folder"), "addNewFolder()");
}
if (studioPlt->isFolder(path) &&
studioPlt->getLevelPalettesRoot() != path &&
studioPlt->getCleanupPalettesRoot() != path &&
TFilePath("C:\\Toonz 6.0 stuff\\projects\\Project Palettes") != path) //DAFARE studioPlt->getProjectPalettesRoot(); Per ora lo fisso)
{
menu.addSeparator();
createMenuAction(menu, tr("Delete Folder"), "deleteItem()");
} else if (studioPlt->isPalette(path)) {
if (studioPlt->isCleanupPalette(path)) {
createMenuAction(menu, tr("Load into Current Cleaunp Palette"), "loadInCurrentCleanupPlt()");
createMenuAction(menu, tr("Replace with Current Cleaunp Palette"), "replaceCurrentCleanupPlt()");
menu.addSeparator();
} else if (m_stdPltHandle->getPalette()) {
createMenuAction(menu, tr("Load into Current Palette"), "loadInCurrentPlt()");
createMenuAction(menu, tr("Merge to Current Palette"), "mergeToCurrentPlt()");
createMenuAction(menu, tr("Replace with Current Palette"), "replaceCurrentPlt()");
menu.addSeparator();
}
createMenuAction(menu, tr("Delete Palette"), "deleteItem()");
menu.addSeparator();
menu.addAction(CommandManager::instance()->getAction("MI_LoadColorModelInStdPlt"));
}
if (isLevelFolder) {
menu.addSeparator();
createMenuAction(menu, tr("Search for Palettes"), "searchForPlt()");
}
menu.exec(event->globalPos());
}
//-----------------------------------------------------------------------------
/*! Add an action to menu \b menu; the action has text \b name and its
\b triggered() signal is connetted with \b slot.
*/
void StudioPaletteTreeViewer::createMenuAction(QMenu &menu, QString name, const char *slot)
{
QAction *act = menu.addAction(name);
string slotName(slot);
slotName = string("1") + slotName;
connect(act, SIGNAL(triggered()), slotName.c_str());
}
//-----------------------------------------------------------------------------
/*! If button left is pressed start drag and drop.
*/
void StudioPaletteTreeViewer::mouseMoveEvent(QMouseEvent *event)
{
// If left button is not pressed return; is not drag event.
if (!(event->buttons() & Qt::LeftButton))
return;
startDragDrop();
}
//-----------------------------------------------------------------------------
/*! If path related to current item exist and is a palette execute drag.
*/
void StudioPaletteTreeViewer::startDragDrop()
{
TFilePath path = getCurrentFolderPath();
if (!path.isEmpty() &&
(path.getType() == "tpl" || path.getType() == "pli" ||
path.getType() == "tlv" || path.getType() == "tnz")) {
QDrag *drag = new QDrag(this);
QMimeData *mimeData = new QMimeData;
QList<QUrl> urls;
urls.append(pathToUrl(path));
mimeData->setUrls(urls);
drag->setMimeData(mimeData);
Qt::DropAction dropAction = drag->exec(Qt::CopyAction | Qt::MoveAction);
}
viewport()->update();
}
//-----------------------------------------------------------------------------
/*! Verify drag enter data, if it has an url and it's path is a palette or data
is a PaletteData accept drag event.
*/
void StudioPaletteTreeViewer::dragEnterEvent(QDragEnterEvent *event)
{
const QMimeData *mimeData = event->mimeData();
const PaletteData *paletteData = dynamic_cast<const PaletteData *>(mimeData);
if (mimeData->hasUrls()) {
if (mimeData->urls().size() != 1)
return;
QUrl url = mimeData->urls()[0];
TFilePath path(url.toLocalFile().toStdWString());
if (path.isEmpty() ||
(path.getType() != "tpl" && path.getType() != "pli" &&
path.getType() != "tlv" && path.getType() != "tnz"))
return;
event->acceptProposedAction();
} else if (paletteData && !paletteData->hasStyleIndeces())
event->acceptProposedAction();
viewport()->update();
}
//-----------------------------------------------------------------------------
/*! Find item folder nearest to current position.
*/
void StudioPaletteTreeViewer::dragMoveEvent(QDragMoveEvent *event)
{
QTreeWidgetItem *item = itemAt(event->pos());
TFilePath newPath = getFolderPath(item);
if (newPath.getType() == "tpl") {
m_dropItem = 0;
event->ignore();
} else {
m_dropItem = item;
event->acceptProposedAction();
}
viewport()->update();
}
//-----------------------------------------------------------------------------
/*! Execute drop event. If dropped palette is in studio palette folder move
palette, otherwise copy palette in current folder.
*/
void StudioPaletteTreeViewer::dropEvent(QDropEvent *event)
{
TFilePath path;
const QMimeData *mimeData = event->mimeData();
if (!mimeData->hasUrls())
return;
if (mimeData->urls().size() != 1)
return;
QUrl url = mimeData->urls()[0];
path = TFilePath(url.toLocalFile().toStdWString());
event->setDropAction(Qt::CopyAction);
event->accept();
TFilePath newPath = getFolderPath(m_dropItem);
StudioPalette *studioPlt = StudioPalette::instance();
if (path == newPath || path.getParentDir() == newPath)
return;
if (isInStudioPalette(path)) {
newPath += TFilePath(path.getName() + path.getDottedType());
try {
StudioPaletteCmd::movePalette(newPath, path);
} catch (TException &e) {
error("Can't rename palette: " + QString(toString(e.getMessage()).c_str()));
} catch (...) {
error("Can't rename palette");
}
} else {
TPalette *palette = studioPlt->getPalette(path);
//Se non trova palette sto importando: - la palette del livello corrente o - la cleanupPalette!
if (!palette) {
if (path.getType() == "pli" || path.getType() == "tlv") {
TXshLevel *level = m_levelHandle->getLevel();
assert(level && level->getSimpleLevel());
palette = level->getSimpleLevel()->getPalette();
path = level->getPath();
} else if (path.getType() == "tnz") {
palette = m_sceneHandle->getScene()->getProperties()->getCleanupPalette();
path = TFilePath();
}
}
try {
StudioPaletteCmd::createPalette(newPath, path.getName(), palette);
} catch (TException &e) {
error("Can't create palette: " + QString(toString(e.getMessage()).c_str()));
} catch (...) {
error("Can't create palette");
}
}
m_dropItem = 0;
}
//-----------------------------------------------------------------------------
/*! Set dropItem to 0 and update the tree.
*/
void StudioPaletteTreeViewer::dragLeaveEvent(QDragLeaveEvent *event)
{
m_dropItem = 0;
update();
}
//-----------------------------------------------------------------------------
/*! Receive widget hide events. Remove this listener from \b StudioPalette.
*/
void StudioPaletteTreeViewer::hideEvent(QHideEvent *event)
{
StudioPalette::instance()->removeListener(this);
}
//-----------------------------------------------------------------------------
/*! Receive widget show events. Add this listener to \b StudioPalette and
refresh tree.
*/
void StudioPaletteTreeViewer::showEvent(QShowEvent *event)
{
StudioPalette::instance()->addListener(this);
refresh();
}
//=============================================================================
/*! \class StudioPaletteViewer
\brief The StudioPaletteViewer class provides an object to view and manage
studio palettes.
Inherits \b QFrame.
This object is composed of a splitter \b QSplitter that contain a vertical
layout and a \b PaletteViewer. Vertical layout contain a \b StudioPaletteTreeViewer
and a toolbar, this object allows to manage the palettes in studio palette folders.
\b PaletteViewer is set to fixed view type: \b PaletteViewerGUI::STUDIO_PALETTE
allows to show and modify current studio palette selected in tree.
*/
StudioPaletteViewer::StudioPaletteViewer(QWidget *parent,
TPaletteHandle *studioPaletteHandle,
TPaletteHandle *levelPaletteHandle,
TSceneHandle *sceneHandle,
TXshLevelHandle *levelHandle,
TFrameHandle *frameHandle)
: QFrame(parent)
{
setObjectName("studiopalette");
setFrameStyle(QFrame::StyledPanel);
setAcceptDrops(true);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setMargin(0);
QSplitter *splitter = new QSplitter(this);
splitter->setOrientation(Qt::Vertical);
//First Splitter Widget
QWidget *treeWidget = new QWidget(this);
QVBoxLayout *treeVLayout = new QVBoxLayout(treeWidget);
treeVLayout->setMargin(0);
treeVLayout->setSpacing(0);
StudioPaletteTreeViewer *studioPltTreeViewer = new StudioPaletteTreeViewer(treeWidget,
studioPaletteHandle,
levelPaletteHandle);
studioPltTreeViewer->setSceneHandle(sceneHandle);
studioPltTreeViewer->setLevelHandle(levelHandle);
treeVLayout->addWidget(studioPltTreeViewer);
//Create toolbar. It is an horizontal layout with three internal toolbar.
QWidget *treeToolbarWidget = new QWidget(this);
treeToolbarWidget->setFixedHeight(22);
QHBoxLayout *treeToolbarLayout = new QHBoxLayout(treeToolbarWidget);
treeToolbarLayout->setMargin(0);
treeToolbarLayout->setSpacing(0);
QToolBar *newToolbar = new QToolBar(treeToolbarWidget);
//New folder action
QIcon newFolderIcon = createQIconPNG("newfolder");
QAction *addFolder = new QAction(newFolderIcon, tr("&New Folder"), newToolbar);
connect(addFolder, SIGNAL(triggered()), studioPltTreeViewer, SLOT(addNewFolder()));
newToolbar->addAction(addFolder);
//New palette action
QIcon newPaletteIcon = createQIconPNG("newpalette");
QAction *addPalette = new QAction(newPaletteIcon, tr("&New Palette"), newToolbar);
connect(addPalette, SIGNAL(triggered()), studioPltTreeViewer, SLOT(addNewPlt()));
newToolbar->addAction(addPalette);
newToolbar->addSeparator();
QToolBar *spacingToolBar = new QToolBar(treeToolbarWidget);
spacingToolBar->setMinimumHeight(22);
QToolBar *deleteToolbar = new QToolBar(treeToolbarWidget);
//Delete folder and palette action
QIcon deleteFolderIcon = createQIconPNG("delete");
QAction *deleteFolder = new QAction(deleteFolderIcon, tr("&Delete"), deleteToolbar);
connect(deleteFolder, SIGNAL(triggered()), studioPltTreeViewer, SLOT(deleteItem()));
deleteToolbar->addSeparator();
deleteToolbar->addAction(deleteFolder);
treeToolbarLayout->addWidget(newToolbar, 0, Qt::AlignLeft);
treeToolbarLayout->addWidget(spacingToolBar, 1);
treeToolbarLayout->addWidget(deleteToolbar, 0, Qt::AlignRight);
treeToolbarWidget->setLayout(treeToolbarLayout);
treeVLayout->addWidget(treeToolbarWidget);
treeWidget->setLayout(treeVLayout);
//Second Splitter Widget
PaletteViewer *studioPltViewer = new PaletteViewer(this, PaletteViewerGUI::STUDIO_PALETTE);
studioPltViewer->setPaletteHandle(studioPaletteHandle);
studioPltViewer->setFrameHandle(frameHandle);
studioPltViewer->setLevelHandle(levelHandle);
studioPltViewer->setSceneHandle(sceneHandle);
splitter->addWidget(treeWidget);
splitter->addWidget(studioPltViewer);
layout->addWidget(splitter);
setLayout(layout);
}
//-----------------------------------------------------------------------------
StudioPaletteViewer::~StudioPaletteViewer()
{
}
//=============================================================================
OpenFloatingPanel openStudioPaletteCommand("MI_OpenStudioPalette",
"StudioPalette",
"Studio Palette");
| JosefMeixner/opentoonz | toonz/sources/toonz/studiopaletteviewer.cpp | C++ | bsd-3-clause | 31,411 |
"""
Module for abstract serializer/unserializer base classes.
"""
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from django.db import models
from django.utils.encoding import smart_str, smart_unicode
class SerializationError(Exception):
"""Something bad happened during serialization."""
pass
class DeserializationError(Exception):
"""Something bad happened during deserialization."""
pass
class Serializer(object):
"""
Abstract serializer base class.
"""
# Indicates if the implemented serializer is only available for
# internal Django use.
internal_use_only = False
def serialize(self, queryset, **options):
"""
Serialize a queryset.
"""
self.options = options
self.stream = options.get("stream", StringIO())
self.selected_fields = options.get("fields")
self.start_serialization()
for obj in queryset:
self.start_object(obj)
for field in obj._meta.local_fields:
if field.serialize:
if field.rel is None:
if self.selected_fields is None or field.attname in self.selected_fields:
self.handle_field(obj, field)
else:
if self.selected_fields is None or field.attname[:-3] in self.selected_fields:
self.handle_fk_field(obj, field)
for field in obj._meta.many_to_many:
if field.serialize:
if self.selected_fields is None or field.attname in self.selected_fields:
self.handle_m2m_field(obj, field)
self.end_object(obj)
self.end_serialization()
return self.getvalue()
def get_string_value(self, obj, field):
"""
Convert a field's value to a string.
"""
if isinstance(field, models.DateTimeField):
value = getattr(obj, field.name).strftime("%Y-%m-%d %H:%M:%S")
else:
value = field.flatten_data(follow=None, obj=obj).get(field.name, "")
return smart_unicode(value)
def start_serialization(self):
"""
Called when serializing of the queryset starts.
"""
raise NotImplementedError
def end_serialization(self):
"""
Called when serializing of the queryset ends.
"""
pass
def start_object(self, obj):
"""
Called when serializing of an object starts.
"""
raise NotImplementedError
def end_object(self, obj):
"""
Called when serializing of an object ends.
"""
pass
def handle_field(self, obj, field):
"""
Called to handle each individual (non-relational) field on an object.
"""
raise NotImplementedError
def handle_fk_field(self, obj, field):
"""
Called to handle a ForeignKey field.
"""
raise NotImplementedError
def handle_m2m_field(self, obj, field):
"""
Called to handle a ManyToManyField.
"""
raise NotImplementedError
def getvalue(self):
"""
Return the fully serialized queryset (or None if the output stream is
not seekable).
"""
if callable(getattr(self.stream, 'getvalue', None)):
return self.stream.getvalue()
class Deserializer(object):
"""
Abstract base deserializer class.
"""
def __init__(self, stream_or_string, **options):
"""
Init this serializer given a stream or a string
"""
self.options = options
if isinstance(stream_or_string, basestring):
self.stream = StringIO(stream_or_string)
else:
self.stream = stream_or_string
# hack to make sure that the models have all been loaded before
# deserialization starts (otherwise subclass calls to get_model()
# and friends might fail...)
models.get_apps()
def __iter__(self):
return self
def next(self):
"""Iteration iterface -- return the next item in the stream"""
raise NotImplementedError
class DeserializedObject(object):
"""
A deserialized model.
Basically a container for holding the pre-saved deserialized data along
with the many-to-many data saved with the object.
Call ``save()`` to save the object (with the many-to-many data) to the
database; call ``save(save_m2m=False)`` to save just the object fields
(and not touch the many-to-many stuff.)
"""
def __init__(self, obj, m2m_data=None):
self.object = obj
self.m2m_data = m2m_data
def __repr__(self):
return "<DeserializedObject: %s>" % smart_str(self.object)
def save(self, save_m2m=True):
# Call save on the Model baseclass directly. This bypasses any
# model-defined save. The save is also forced to be raw.
# This ensures that the data that is deserialized is literally
# what came from the file, not post-processed by pre_save/save
# methods.
models.Model.save_base(self.object, raw=True)
if self.m2m_data and save_m2m:
for accessor_name, object_list in self.m2m_data.items():
setattr(self.object, accessor_name, object_list)
# prevent a second (possibly accidental) call to save() from saving
# the m2m data twice.
self.m2m_data = None
| diofeher/django-nfa | django/core/serializers/base.py | Python | bsd-3-clause | 5,533 |
<?php
namespace Rcm\Factory;
use Rcm\Service\ResponseHandler;
use Zend\Mvc\ResponseSender\HttpResponseSender;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
/**
* Service Factory for the Container Manager
*
* Factory for the Container Manager.
*
* @category Reliv
* @package Rcm
* @author Westin Shafer <wshafer@relivinc.com>
* @copyright 2012 Reliv International
* @license License.txt New BSD License
* @version Release: 1.0
* @link https://github.com/reliv
*
*/
class ResponseHandlerFactory implements FactoryInterface
{
/**
* Creates Service
*
* @param ServiceLocatorInterface $serviceLocator Zend Service Locator
*
* @return ResponseHandler
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
/** @var \Rcm\Entity\Site $currentSite */
$currentSite = $serviceLocator->get('Rcm\Service\CurrentSite');
/** @var \RcmUser\Service\RcmUserService $rcmUserService */
$rcmUserService = $serviceLocator->get('RcmUser\Service\RcmUserService');
/** @var \Zend\Stdlib\Request $request */
$request = $serviceLocator->get('request');
$responseSender = new HttpResponseSender();
return new ResponseHandler(
$request,
$currentSite,
$responseSender,
$rcmUserService
);
}
}
| innaDa/Rcm | src/Factory/ResponseHandlerFactory.php | PHP | bsd-3-clause | 1,430 |
/*
* Copyright (c) 2013 - 2016 Stefan Muller Arisona, Simon Schubiger
* Copyright (c) 2013 - 2016 FHNW & ETH Zurich
* All rights reserved.
*
* Contributions by: Filip Schramka, Samuel von Stachelski
*
* 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 FHNW / ETH Zurich 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 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 ch.fhnw.util;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
public final class ClassUtilities {
public static final Class<Object> CLS_Object = Object.class;
public static final Class<Object[]> CLS_ObjectA = Object[].class;
public static final Object[] EMPTY_ObjectA = new Object[0];
public static final Class<?> CLS_void = void.class;
public static final Class<?> CLS_Class = Class.class;
public static final Class<?>[] EMPTY_ClassA = new Class[0];
public static final Class<?> CLS_boolean = boolean.class;
public static final Class<boolean[]> CLS_booleanA = boolean[].class;
public static final Class<Boolean> CLS_Boolean = Boolean.class;
public static final boolean[] EMPTY_booleanA = new boolean[0];
public static final Class<?> CLS_byte = byte.class;
public static final Class<byte[]> CLS_byteA = byte[].class;
public static final byte[] EMPTY_byteA = new byte[0];
public static final Class<Byte> CLS_Byte = Byte.class;
public static final Class<?> CLS_char = char.class;
public static final Class<char[]> CLS_charA = char[].class;
public static final char[] EMPTY_charA = new char[0];
public static final Class<Character> CLS_Character = Character.class;
public static final Class<?> CLS_short = short.class;
public static final Class<short[]> CLS_shortA = short[].class;
public static final Class<Short> CLS_Short = Short.class;
public static final Class<?> CLS_int = int.class;
public static final Class<int[]> CLS_intA = int[].class;
public static final int[] EMPTY_intA = new int[0];
public static final Class<Integer> CLS_Integer = Integer.class;
public static final Class<?> CLS_long = long.class;
public static final Class<long[]> CLS_longA = long[].class;
public static final long[] EMPTY_longA = new long[0];
public static final Class<Long> CLS_Long = Long.class;
public static final Class<?> CLS_float = float.class;
public static final Class<float[]> CLS_floatA = float[].class;
public static final float[] EMPTY_floatA = new float[0];
public static final Class<Float> CLS_Float = Float.class;
public static final Class<?> CLS_double = double.class;
public static final double[] EMPTY_doubleA = new double[0];
public static final Class<double[]> CLS_doubleA = double[].class;
public static final Class<Double> CLS_Double = Double.class;
public static final Class<String> CLS_String = String.class;
public static final Class<String[]> CLS_StringA = String[].class;
public static final String EMPTY_String = "";
public static final String[] EMPTY_StringA = new String[0];
public static final Class<BitSet> CLS_BitSet = BitSet.class;
public static final Class<UUID> CLS_UUID = UUID.class;
public static final UUID[] EMPTY_UUIDA = new UUID[0];
public static final Class<File> CLS_File = File.class;
public static final File[] EMPTY_FileA = new File[0];
@SuppressWarnings("rawtypes")
public static final Class<Enum> CLS_Enum = Enum.class;
@SuppressWarnings("rawtypes")
public static final Class<Map> CLS_Map = Map.class;
@SuppressWarnings("rawtypes")
public static final Class<List> CLS_List = List.class;
@SuppressWarnings("rawtypes")
public static final Class<HashMap> CLS_HashMap = HashMap.class;
@SuppressWarnings("rawtypes")
public static final Class<IdentityHashMap> CLS_IdentityHashMap = IdentityHashMap.class;
@SuppressWarnings("rawtypes")
public static final Class<ArrayList> CLS_ArrayList = ArrayList.class;
static final Hashtable<Class<?>, byte[]> cls2md5 = new Hashtable<>();
static final Hashtable<String, Class<?>> clsMap = new Hashtable<>();
static final Set<Class<?>> IS_INTEGRAL = new IdentityHashSet<>();
static final Set<Class<?>> IS_FLOAT = new IdentityHashSet<>();
static final Set<Class<?>> IS_PRIMITIVE = new IdentityHashSet<>();
static final Set<Class<?>> IS_WRAPPER = new IdentityHashSet<>();
static final Map<Class<?>, HashMap<String, Field>> fieldMap = new IdentityHashMap<>();
static final Map<Class<?>, Field[]> cls2fields = new IdentityHashMap<>();
static final Map<Class<?>, Method[]> cls2methods = new IdentityHashMap<>();
static final Map<Class<?>, Map<Class<?>, Field[]>> clsAnnotation2fields = new IdentityHashMap<>();
static final Map<Class<?>, Map<Class<?>, Method[]>> clsAnnotation2methods = new IdentityHashMap<>();
static final Map<Class<?>, Class<?>> inner2outer = new IdentityHashMap<>();
static {
clsMap.put("boolean", CLS_boolean);
clsMap.put("byte", CLS_byte);
clsMap.put("char", CLS_char);
clsMap.put("short", CLS_short);
clsMap.put("int", CLS_int);
clsMap.put("long", CLS_long);
clsMap.put("float", CLS_float);
clsMap.put("double", CLS_double);
IS_INTEGRAL.add(CLS_byte);
IS_INTEGRAL.add(CLS_Byte);
IS_INTEGRAL.add(CLS_char);
IS_INTEGRAL.add(CLS_Character);
IS_INTEGRAL.add(CLS_short);
IS_INTEGRAL.add(CLS_Short);
IS_INTEGRAL.add(CLS_int);
IS_INTEGRAL.add(CLS_Integer);
IS_INTEGRAL.add(CLS_long);
IS_INTEGRAL.add(CLS_Long);
IS_FLOAT.add(CLS_float);
IS_FLOAT.add(CLS_Float);
IS_FLOAT.add(CLS_double);
IS_FLOAT.add(CLS_Double);
IS_PRIMITIVE.add(CLS_boolean);
IS_PRIMITIVE.add(CLS_void);
IS_PRIMITIVE.add(CLS_byte);
IS_PRIMITIVE.add(CLS_char);
IS_PRIMITIVE.add(CLS_short);
IS_PRIMITIVE.add(CLS_int);
IS_PRIMITIVE.add(CLS_long);
IS_PRIMITIVE.add(CLS_float);
IS_PRIMITIVE.add(CLS_double);
IS_WRAPPER.add(CLS_Boolean);
IS_WRAPPER.add(CLS_Byte);
IS_WRAPPER.add(CLS_Character);
IS_WRAPPER.add(CLS_Short);
IS_WRAPPER.add(CLS_Integer);
IS_WRAPPER.add(CLS_Long);
IS_WRAPPER.add(CLS_Float);
IS_WRAPPER.add(CLS_Double);
}
public static byte[] getMD5(Class<?> cls) throws NoSuchAlgorithmException, IOException {
byte[] result = cls2md5.get(cls);
if(result == null) {
MessageDigest md = MessageDigest.getInstance("MD5");
String name = cls.getName();
name = name.substring(name.lastIndexOf('.') + 1) + ".class";
try (InputStream in = cls.getResourceAsStream(name)) {
byte[] buffer = new byte[8192];
while(true) {
int r = in.read(buffer);
if(r == -1) break;
md.update(buffer, 0, r);
}
}
result = md.digest();
cls2md5.put(cls, result);
}
return result;
}
public static Class<?> toPrimitiveType(Class<?> type) {
if(type == Boolean.class)
return Boolean.TYPE;
else if(type == Byte.class)
return Byte.TYPE;
else if(type == Short.class)
return Short.TYPE;
else if(type == Integer.class)
return Integer.TYPE;
else if(type == Long.class)
return Long.TYPE;
else if(type == Float.class)
return Float.TYPE;
else if(type == Double.class)
return Double.TYPE;
else
return type;
}
public static Class<?> forName(String name) throws ClassNotFoundException {
Class<?> result = clsMap.get(name);
return result == null ? getGlobalClassloader().loadClass(name) : result;
}
public static Class<?>[] getGenericTypes(Type genericType) throws ClassNotFoundException {
String[] gtypes = genericType.toString().split("[<>]");
Class<?>[] result = new Class<?>[gtypes.length - 1];
for(int i = 0; i < result.length; i++) {
String cls = gtypes[i + 1];
int dimension = TextUtilities.count(cls, '[');
if(dimension == 0)
result[i] = forName(cls);
else {
cls = cls.substring(0, cls.indexOf('['));
int[] dims = new int[dimension];
result[i] = Array.newInstance(forName(cls), dims).getClass();
}
}
return result;
}
public static boolean isBoolean(Class<?> cls) {
return CLS_boolean == cls || CLS_Boolean == cls;
}
public static boolean isIntegral(Class<?> cls) {
return IS_INTEGRAL.contains(cls);
}
public static boolean isFloat(Class<?> cls) {
return IS_FLOAT.contains(cls);
}
public static boolean isPrimitiveOrWrapper(Class<?> cls) {
return IS_PRIMITIVE.contains(cls) || IS_WRAPPER.contains(cls);
}
public static Class<?> getComponentType(Class<?> type) {
if(type.isArray()) return getComponentType(type.getComponentType());
return type;
}
public static Field[] getAllFields(Class<?> type) {
Field[] result = cls2fields.get(type);
if(result == null) {
Collection<Field> fields = getAllFields(type, new ArrayList<>());
result = fields.toArray(new Field[fields.size()]);
cls2fields.put(type, result);
AccessibleObject.setAccessible(result, true);
}
return result;
}
private static Collection<Field> getAllFields(Class<?> type, List<Field> result) {
if(type == CLS_Object) return result;
try {
Collections.addAll(result, type.getDeclaredFields());
} catch(Throwable t) {
t.printStackTrace();
}
return getAllFields(type.getSuperclass(), result);
}
public static Method[] getAllMethods(Class<?> type) {
Method[] result = cls2methods.get(type);
if(result == null) {
Collection<Method> methods = getAllMethods(type, new ArrayList<>());
result = methods.toArray(new Method[methods.size()]);
cls2methods.put(type, result);
AccessibleObject.setAccessible(result, true);
}
return result;
}
public static Method getMethod(String type, String method, Class<?> ... argTypes) throws ClassNotFoundException {
return getMethod(getGlobalClassloader().loadClass(type), method, argTypes);
}
public static Method getMethod(Class<?> type, String method, Class<?> ... argTypes) {
for(Method m : getAllMethods(type)) {
if(m.getName().equals(method) && Arrays.equals(m.getParameterTypes(), argTypes))
return m;
}
throw new NoSuchMethodError(method + TextUtilities.toString("(", ",", ")", argTypes));
}
private static Collection<Method> getAllMethods(Class<?> type, List<Method> result) {
if(type == CLS_Object) return result;
Collections.addAll(result, type.getDeclaredMethods());
return getAllMethods(type.getSuperclass(), result);
}
public static String getCurrentMethodName() {
return Thread.currentThread().getStackTrace()[2].getMethodName();
}
public static String getCallerMethodName() {
return Thread.currentThread().getStackTrace()[3].getMethodName();
}
public static String getCallerClassName() {
return Thread.currentThread().getStackTrace()[3].getClassName();
}
public static String getCallerClassAndMethodName(int n) {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
if (n + 4 >= elements.length)
return "none";
return elements[n + 3].getClassName() + "." + elements[n + 3].getMethodName();
}
public static Field getField(Class<?> type, String field) {
HashMap<String, Field> fields = fieldMap.get(type);
if(fields == null) {
fields = new HashMap<>();
Field[] fieldsa = getAllFields(type);
for(int i = fieldsa.length; --i >= 0;)
fields.put(fieldsa[i].getName(), fieldsa[i]);
fieldMap.put(type, fields);
}
Field result = fields.get(field);
if(result == null)
throw new NoSuchFieldError(type.getName() + "." + field);
return result;
}
public static Field[] getAllAnotatedFields(Class<?> cls, Class<? extends Annotation> annotationCls) {
Map<Class<?>, Field[]> annotation2field = clsAnnotation2fields.get(cls);
if(annotation2field == null) {
annotation2field = new IdentityHashMap<>();
clsAnnotation2fields.put(cls, annotation2field);
}
Field[] result = annotation2field.get(annotationCls);
if(result == null) {
List<Field> fields = new LinkedList<>();
for(Field field : getAllFields(cls)) {
if(field.getAnnotation(annotationCls) != null)
fields.add(field);
}
result = fields.toArray(new Field[fields.size()]);
annotation2field.put(annotationCls, result);
}
return result;
}
public static Method[] getAllAnnotatedMethods(Class<?> cls, Class<? extends Annotation> annotationCls) {
Map<Class<?>, Method[]> annotation2method = clsAnnotation2methods.get(cls);
if(annotation2method == null) {
annotation2method = new IdentityHashMap<>();
clsAnnotation2methods.put(cls, annotation2method);
}
Method[] result = annotation2method.get(annotationCls);
if(result == null) {
List<Method> methods = new LinkedList<>();
for(Method method : getAllMethods(cls)) {
if(method.getAnnotation(annotationCls) != null)
methods.add(method);
}
result = methods.toArray(new Method[methods.size()]);
annotation2method.put(annotationCls, result);
}
return result;
}
private static final Map<Method, Class<?>[]> method2paramTypes = new IdentityHashMap<>();
public synchronized static Class<?>[] getParameterTypes(Method m) {
Class<?>[] result = method2paramTypes.get(m);
if(result == null) {
result = m.getParameterTypes();
method2paramTypes.put(m, result);
}
return result;
}
public synchronized static ClassLoader getGlobalClassloader() {
return ClassUtilities.class.getClassLoader();
}
public static Class<?>[] getTypeHierarchy(Class<?> cls) {
ArrayList<Class<?>> result = getTypeHierarchy(cls, new ArrayList<>());
return result.toArray(new Class<?>[result.size()]);
}
private static ArrayList<Class<?>> getTypeHierarchy(Class<?> cls, ArrayList<Class<?>> result) {
result.add(cls);
if(cls == CLS_Object)
return result;
return getTypeHierarchy(cls.getSuperclass(), result);
}
@SuppressWarnings("unchecked")
public static <T> Class<T> forNameOrNull(String cls) {
try {
return (Class<T>) forName(cls);
} catch (Throwable t) {
return null;
}
}
/**
* Returns the class of the specified object, or {@code null} if {@code object} is null.
* This method is also useful for fetching the class of an object known only by its bound
* type. As of Java 6, the usual pattern:
*
* <blockquote><pre>
* Number n = 0;
* Class<? extends Number> c = n.getClass();
* </pre></blockquote>
*
* doesn't seem to work if {@link Number} is replaced by a parametirez type {@code T}.
*
* @param <T> The type of the given object.
* @param object The object for which to get the class, or {@code null}.
* @return The class of the given object, or {@code null} if the given object was null.
*/
@SuppressWarnings("unchecked")
public static <T> Class<? extends T> getClass(final T object) {
return (object != null) ? (Class<? extends T>) object.getClass() : null;
}
public static int getDimension(Class<?> cls) {
return cls.getComponentType() == null ? 0 : 1 + getDimension(cls.getComponentType());
}
private static final AtomicLong ID_COUNTER = new AtomicLong();
public static long createObjectID() {
return ID_COUNTER.addAndGet(1);
}
public static int identityHashCode(Object x) {
if(x instanceof IObjectID)
return (int) ((IObjectID) x).getObjectID();
else if(x instanceof String || x instanceof Number || x instanceof UUID)
return x.hashCode();
return System.identityHashCode(x);
}
/**
* Value representing null keys inside tables.
*/
private static final Object NULL_KEY = new IObjectID() {
@Override
public long getObjectID() {
return 0;
}
};
/**
* Use NULL_KEY for key if it is null.
*/
public static Object maskNull(Object key) {
return (key == null ? NULL_KEY : key);
}
/**
* Returns internal representation of null key back to caller as null.
*/
public static Object unmaskNull(Object key) {
return (key == NULL_KEY ? null : key);
}
@SuppressWarnings("unchecked")
public static <T> T newInstance(String cls, Class<?>[] types, Object ... args) {
try {
return (T) getGlobalClassloader().loadClass(cls).getConstructor(types).newInstance(args);
} catch(Throwable t) {
t.printStackTrace();
}
return null;
}
public static <T> T newInstance(Class<? extends T> cls, Class<?>[] types, Object ... args) {
try {
return cls.getConstructor(types).newInstance(args);
} catch(Throwable t) {
t.printStackTrace();
}
return null;
}
public static Class<?> getEnclosingClass(Class<?> cls) {
Class<?> result = inner2outer.get(cls);
if(result == null) {
result = cls.getEnclosingClass();
inner2outer.put(cls, result);
}
return result;
}
}
| arisona/ether | ether-core/src/main/java/ch/fhnw/util/ClassUtilities.java | Java | bsd-3-clause | 19,598 |
from django.urls import include, path, register_converter
from django.urls.converters import StringConverter
from django.contrib import admin
from django.contrib.auth import logout
from django.views.generic import RedirectView, TemplateView
from pontoon.teams.views import team
class LocaleConverter(StringConverter):
regex = r"[A-Za-z0-9\-\@\.]+"
register_converter(LocaleConverter, "locale")
pontoon_js_view = TemplateView.as_view(
template_name="js/pontoon.js", content_type="text/javascript"
)
permission_denied_view = TemplateView.as_view(template_name="403.html")
page_not_found_view = TemplateView.as_view(template_name="404.html")
server_error_view = TemplateView.as_view(template_name="500.html")
urlpatterns = [
# Accounts
path("accounts/", include("pontoon.allauth_urls")),
# Admin
path("admin/", include("pontoon.administration.urls")),
# Django admin: Disable the login form
path("a/login/", permission_denied_view),
# Django admin
path("a/", admin.site.urls),
# Logout
path("signout/", logout, {"next_page": "/"}, name="signout"),
# Error pages
path("403/", permission_denied_view),
path("404/", page_not_found_view),
path("500/", server_error_view),
# Robots.txt
path(
"robots.txt",
TemplateView.as_view(template_name="robots.txt", content_type="text/plain"),
),
# contribute.json
path(
"contribute.json",
TemplateView.as_view(
template_name="contribute.json", content_type="text/plain"
),
),
# Favicon
path(
"favicon.ico",
RedirectView.as_view(url="/static/img/favicon.ico", permanent=True),
),
# Include script
path("pontoon.js", pontoon_js_view),
path("static/js/pontoon.js", pontoon_js_view),
# Include URL configurations from installed apps
path("terminology/", include("pontoon.terminology.urls")),
path("translations/", include("pontoon.translations.urls")),
path("", include("pontoon.teams.urls")),
path("", include("pontoon.tour.urls")),
path("", include("pontoon.tags.urls")),
path("", include("pontoon.sync.urls")),
path("", include("pontoon.projects.urls")),
path("", include("pontoon.machinery.urls")),
path("", include("pontoon.contributors.urls")),
path("", include("pontoon.localizations.urls")),
path("", include("pontoon.base.urls")),
path("", include("pontoon.translate.urls")),
path("", include("pontoon.batch.urls")),
path("", include("pontoon.api.urls")),
path("", include("pontoon.homepage.urls")),
path("", include("pontoon.in_context.urls")),
path("", include("pontoon.uxactionlog.urls")),
# Team page: Must be at the end
path("<locale:locale>/", team, name="pontoon.teams.team"),
]
| mathjazz/pontoon | pontoon/urls.py | Python | bsd-3-clause | 2,791 |
// clang-format off
CppKeySet { 10,
keyNew (PREFIX "primes", KEY_META, "array", "#3", KEY_END),
keyNew (PREFIX "primes/#0", KEY_VALUE, "two", KEY_END),
keyNew (PREFIX "primes/#1", KEY_VALUE, "three", KEY_END),
keyNew (PREFIX "primes/#2", KEY_VALUE, "five", KEY_END),
keyNew (PREFIX "primes/#3", KEY_VALUE, "seven", KEY_END),
KS_END }
| BernhardDenner/libelektra | src/plugins/yanlr/yanlr/map-list-plain_scalars.hpp | C++ | bsd-3-clause | 365 |
<?php
/**
* author : forecho <caizhenghai@gmail.com>
* createTime : 15/4/19 下午3:20
* description:
*/
namespace common\services;
use common\models\Post;
use common\models\PostComment;
use common\models\User;
use common\models\UserInfo;
use DevGroup\TagDependencyHelper\NamingHelper;
use frontend\modules\topic\models\Topic;
use frontend\modules\user\models\UserMeta;
use yii\caching\TagDependency;
class UserService
{
/**
* 获取通知条数
* @return mixed
*/
public static function findNotifyCount()
{
$user = \Yii::$app->getUser()->getIdentity();
return $user ? $user->notification_count : null;
}
/**
* 清除通知数
* @return mixed
*/
public static function clearNotifyCount()
{
return User::updateAll(['notification_count' => '0'], ['id' => \Yii::$app->user->id]);
}
/**
* 赞话题(如果已经赞,则取消赞)
* @param User $user
* @param Topic $topic
* @param $action 动作
* @return array
*/
public static function TopicActionA(User $user, Topic $topic, $action)
{
return self::toggleType($user, $topic, $action);
}
/**
* 用户对话题其他动作
* @param User $user
* @param Post $model
* @param $action fa
* @return array
*/
public static function TopicActionB(User $user, Post $model, $action)
{
$data = [
'target_id' => $model->id,
'target_type' => $model->type,
'user_id' => $user->id,
'value' => '1',
];
if (!UserMeta::deleteOne($data + ['type' => $action])) { // 删除数据有行数则代表有数据,无行数则添加数据
$userMeta = new UserMeta();
$userMeta->setAttributes($data + ['type' => $action]);
$result = $userMeta->save();
if ($result) {
$model->updateCounters([$action . '_count' => 1]);
if ($action == 'thanks') {
UserInfo::updateAllCounters([$action . '_count' => 1], ['user_id' => $model->user_id]);
}
}
return [$result, $userMeta];
}
$model->updateCounters([$action . '_count' => -1]);
if ($action == 'thanks') {
UserInfo::updateAllCounters([$action . '_count' => -1], ['user_id' => $model->user_id]);
}
return [true, null];
}
/**
* 对评论点赞
* @param User $user
* @param PostComment $comment
* @param $action
* @return array
*/
public static function CommentAction(User $user, PostComment $comment, $action)
{
$data = [
'target_id' => $comment->id,
'target_type' => $comment::TYPE,
'user_id' => $user->id,
'value' => '1',
];
if (!UserMeta::deleteOne($data + ['type' => $action])) { // 删除数据有行数则代表有数据,无行数则添加数据
$userMeta = new UserMeta();
$userMeta->setAttributes($data + ['type' => $action]);
$result = $userMeta->save();
if ($result) {
$comment->updateCounters([$action . '_count' => 1]);
// 更新个人总统计
UserInfo::updateAllCounters([$action . '_count' => 1], ['user_id' => $comment->user_id]);
}
return [$result, $userMeta];
}
$comment->updateCounters([$action . '_count' => -1]);
// 更新个人总统计
UserInfo::updateAllCounters([$action . '_count' => -1], ['user_id' => $comment->user_id]);
return [true, null];
}
/**
* 喝倒彩或者赞
* @param User $user
* @param Post $model
* @param $action 动作
* @return array
*/
protected static function toggleType(User $user, Post $model, $action)
{
$data = [
'target_id' => $model->id,
'target_type' => $model->type,
'user_id' => $user->id,
'value' => '1',
];
if (!UserMeta::deleteOne($data + ['type' => $action])) { // 删除数据有行数则代表有数据,无行数则添加数据
$userMeta = new UserMeta();
$userMeta->setAttributes($data + ['type' => $action]);
$result = $userMeta->save();
if ($result) { // 如果是新增数据, 删除掉Hate的同类型数据
$attributeName = ($action == 'like' ? 'hate' : 'like');
$attributes = [$action . '_count' => 1];
if (UserMeta::deleteOne($data + ['type' => $attributeName])) { // 如果有删除hate数据, hate_count也要-1
$attributes[$attributeName . '_count'] = -1;
}
//更新版块统计
$model->updateCounters($attributes);
// 更新个人总统计
UserInfo::updateAllCounters($attributes, ['user_id' => $model->user_id]);
}
return [$result, $userMeta];
}
$model->updateCounters([$action . '_count' => -1]);
UserInfo::updateAllCounters([$action . '_count' => -1], ['user_id' => $model->user_id]);
return [true, null];
}
/**
* 查找活跃用户
* @param int $limit
* @return array|\yii\db\ActiveRecord[]
*/
public static function findActiveUser($limit = 12)
{
$cacheKey = md5(__METHOD__ . $limit);
if (false === $items = \Yii::$app->cache->get($cacheKey)) {
$items = User::find()
->joinWith(['merit', 'userInfo'])
->where([User::tableName() . '.status' => 10])
->orderBy(['merit' => SORT_DESC, '(like_count+thanks_count)' => SORT_DESC])
->limit($limit)
->all();
//一天缓存
\Yii::$app->cache->set($cacheKey, $items, 86400,
new TagDependency([
'tags' => [NamingHelper::getCommonTag(User::className())]
])
);
}
return $items;
}
} | upliu/getyii | common/services/UserService.php | PHP | bsd-3-clause | 6,118 |
/**
* Copyright (c) 2013-present, 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.
*
* @providesModule TouchEventUtils
*/
const TouchEventUtils = {
/**
* Utility function for common case of extracting out the primary touch from a
* touch event.
* - `touchEnd` events usually do not have the `touches` property.
* http://stackoverflow.com/questions/3666929/
* mobile-sarai-touchend-event-not-firing-when-last-touch-is-removed
*
* @param {Event} nativeEvent Native event that may or may not be a touch.
* @return {TouchesObject?} an object with pageX and pageY or null.
*/
extractSingleTouch: function(nativeEvent) {
const touches = nativeEvent.touches;
const changedTouches = nativeEvent.changedTouches;
const hasTouches = touches && touches.length > 0;
const hasChangedTouches = changedTouches && changedTouches.length > 0;
return !hasTouches && hasChangedTouches ? changedTouches[0] :
hasTouches ? touches[0] :
nativeEvent;
}
};
module.exports = TouchEventUtils;
| chicoxyzzy/fbjs | packages/fbjs/src/core/TouchEventUtils.js | JavaScript | bsd-3-clause | 1,271 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE134_Uncontrolled_Format_String__char_console_printf_72a.cpp
Label Definition File: CWE134_Uncontrolled_Format_String.label.xml
Template File: sources-sinks-72a.tmpl.cpp
*/
/*
* @description
* CWE: 134 Uncontrolled Format String
* BadSource: console Read input from the console
* GoodSource: Copy a fixed string into data
* Sinks: printf
* GoodSink: printf with "%s" as the first argument and data as the second
* BadSink : printf with only data as an argument
* Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <vector>
#ifndef _WIN32
#include <wchar.h>
#endif
using namespace std;
namespace CWE134_Uncontrolled_Format_String__char_console_printf_72
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(vector<char *> dataVector);
void bad()
{
char * data;
vector<char *> dataVector;
char dataBuffer[100] = "";
data = dataBuffer;
{
/* Read input from the console */
size_t dataLen = strlen(data);
/* if there is room in data, read into it from the console */
if (100-dataLen > 1)
{
/* POTENTIAL FLAW: Read data from the console */
if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL)
{
/* The next few lines remove the carriage return from the string that is
* inserted by fgets() */
dataLen = strlen(data);
if (dataLen > 0 && data[dataLen-1] == '\n')
{
data[dataLen-1] = '\0';
}
}
else
{
printLine("fgets() failed");
/* Restore NUL terminator if fgets fails */
data[dataLen] = '\0';
}
}
}
/* Put data in a vector */
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
badSink(dataVector);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(vector<char *> dataVector);
static void goodG2B()
{
char * data;
vector<char *> dataVector;
char dataBuffer[100] = "";
data = dataBuffer;
/* FIX: Use a fixed string that does not contain a format specifier */
strcpy(data, "fixedstringtest");
/* Put data in a vector */
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
goodG2BSink(dataVector);
}
/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink(vector<char *> dataVector);
static void goodB2G()
{
char * data;
vector<char *> dataVector;
char dataBuffer[100] = "";
data = dataBuffer;
{
/* Read input from the console */
size_t dataLen = strlen(data);
/* if there is room in data, read into it from the console */
if (100-dataLen > 1)
{
/* POTENTIAL FLAW: Read data from the console */
if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL)
{
/* The next few lines remove the carriage return from the string that is
* inserted by fgets() */
dataLen = strlen(data);
if (dataLen > 0 && data[dataLen-1] == '\n')
{
data[dataLen-1] = '\0';
}
}
else
{
printLine("fgets() failed");
/* Restore NUL terminator if fgets fails */
data[dataLen] = '\0';
}
}
}
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
goodB2GSink(dataVector);
}
void good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
} /* close namespace */
/* 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
using namespace CWE134_Uncontrolled_Format_String__char_console_printf_72; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE134_Uncontrolled_Format_String/s01/CWE134_Uncontrolled_Format_String__char_console_printf_72a.cpp | C++ | bsd-3-clause | 5,028 |
<?php
/**
* Payment object representing a cheque payment.
*
* @package payment
*/
class ChequePayment extends Payment {
/**
* Process the Cheque payment method
*/
function processPayment($data, $form) {
$this->Status = 'Pending';
$this->Message = '<p class="warningMessage">' . _t('ChequePayment.MESSAGE', 'Payment accepted via Cheque. Please note : products will not be shipped until payment has been received.') . '</p>';
$this->write();
return new Payment_Success();
}
function getPaymentFormFields() {
return new FieldSet(
// retrieve cheque content from the ChequeContent() method on this class
new LiteralField("Chequeblurb", '<div id="Cheque" class="typography">' . $this->ChequeContent() . '</div>'),
new HiddenField("Cheque", "Cheque", 0)
);
}
function getPaymentFormRequirements() {
return null;
}
/**
* Returns the Cheque content from the CheckoutPage
*/
function ChequeContent() {
if(class_exists('CheckoutPage')) {
return DataObject::get_one('CheckoutPage')->ChequeMessage;
}
}
}
| bartoszrychlicki/MainBrain.pl | payment/code/ChequePayment/ChequePayment.php | PHP | bsd-3-clause | 1,059 |
from django.conf.urls.defaults import *
from corehq.apps.adm.dispatcher import ADMAdminInterfaceDispatcher, ADMSectionDispatcher
from corehq.apps.adm.views import ADMAdminCRUDFormView
adm_admin_interface_urls = patterns('corehq.apps.adm.views',
url(r'^$', 'default_adm_admin', name="default_adm_admin_interface"),
url(r'^form/(?P<form_type>[\w_]+)/(?P<action>[(update)|(new)|(delete)]+)/((?P<item_id>[\w_]+)/)?$',
ADMAdminCRUDFormView.as_view(), name="adm_item_form"),
ADMAdminInterfaceDispatcher.url_pattern(),
)
urlpatterns = patterns('corehq.apps.adm.views',
url(r'^$', 'default_adm_report', name="default_adm_report"),
ADMSectionDispatcher.url_pattern(),
)
| gmimano/commcaretest | corehq/apps/adm/urls.py | Python | bsd-3-clause | 691 |
// Copyright 2020 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "util/file/output_stream_file_writer.h"
#include "base/logging.h"
#include "util/stream/output_stream_interface.h"
namespace crashpad {
OutputStreamFileWriter::OutputStreamFileWriter(
std::unique_ptr<OutputStreamInterface> output_stream)
: output_stream_(std::move(output_stream)),
flush_needed_(false),
flushed_(false) {}
OutputStreamFileWriter::~OutputStreamFileWriter() {
DCHECK(!flush_needed_);
}
bool OutputStreamFileWriter::Write(const void* data, size_t size) {
DCHECK(!flushed_);
flush_needed_ =
output_stream_->Write(static_cast<const uint8_t*>(data), size);
return flush_needed_;
}
bool OutputStreamFileWriter::WriteIoVec(std::vector<WritableIoVec>* iovecs) {
DCHECK(!flushed_);
flush_needed_ = true;
if (iovecs->empty()) {
LOG(ERROR) << "no iovecs";
flush_needed_ = false;
return false;
}
for (const WritableIoVec& iov : *iovecs) {
if (!output_stream_->Write(static_cast<const uint8_t*>(iov.iov_base),
iov.iov_len)) {
flush_needed_ = false;
return false;
}
}
return true;
}
FileOffset OutputStreamFileWriter::Seek(FileOffset offset, int whence) {
NOTREACHED();
return -1;
}
bool OutputStreamFileWriter::Flush() {
flush_needed_ = false;
flushed_ = true;
return output_stream_->Flush();
}
} // namespace crashpad
| youtube/cobalt | third_party/crashpad/util/file/output_stream_file_writer.cc | C++ | bsd-3-clause | 1,982 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE36_Absolute_Path_Traversal__char_connect_socket_ofstream_73a.cpp
Label Definition File: CWE36_Absolute_Path_Traversal.label.xml
Template File: sources-sink-73a.tmpl.cpp
*/
/*
* @description
* CWE: 36 Absolute Path Traversal
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Full path and file name
* Sinks: ofstream
* BadSink : Open the file named in data using ofstream::open()
* Flow Variant: 73 Data flow: data passed in a list from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <list>
#ifndef _WIN32
#include <wchar.h>
#endif
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
using namespace std;
namespace CWE36_Absolute_Path_Traversal__char_connect_socket_ofstream_73
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(list<char *> dataList);
void bad()
{
char * data;
list<char *> dataList;
char dataBuffer[FILENAME_MAX] = "";
data = dataBuffer;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
char *replace;
SOCKET connectSocket = INVALID_SOCKET;
size_t dataLen = strlen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
/* Abort on error or the connection was closed */
recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (FILENAME_MAX - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(char)] = '\0';
/* Eliminate CRLF */
replace = strchr(data, '\r');
if (replace)
{
*replace = '\0';
}
replace = strchr(data, '\n');
if (replace)
{
*replace = '\0';
}
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
/* Put data in a list */
dataList.push_back(data);
dataList.push_back(data);
dataList.push_back(data);
badSink(dataList);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declarations */
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(list<char *> dataList);
static void goodG2B()
{
char * data;
list<char *> dataList;
char dataBuffer[FILENAME_MAX] = "";
data = dataBuffer;
#ifdef _WIN32
/* FIX: Use a fixed, full path and file name */
strcat(data, "c:\\temp\\file.txt");
#else
/* FIX: Use a fixed, full path and file name */
strcat(data, "/tmp/file.txt");
#endif
/* Put data in a list */
dataList.push_back(data);
dataList.push_back(data);
dataList.push_back(data);
goodG2BSink(dataList);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* 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
using namespace CWE36_Absolute_Path_Traversal__char_connect_socket_ofstream_73; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE36_Absolute_Path_Traversal/s01/CWE36_Absolute_Path_Traversal__char_connect_socket_ofstream_73a.cpp | C++ | bsd-3-clause | 5,444 |
/*
* Copyright (C) 2010-2012 The Async HBase Authors. All rights reserved.
* This file is part of Async HBase.
*
* 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 StumbleUpon 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.
*/
package org.hbase.async;
import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import org.hbase.async.generated.ClientPB.MutateRequest;
import org.hbase.async.generated.ClientPB.MutateResponse;
import org.hbase.async.generated.ClientPB.MutationProto;
import org.jboss.netty.buffer.ChannelBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
/**
* Atomically increments several column values in HBase.
*
* <h1>A note on passing {@code byte} arrays in argument</h1>
* None of the method that receive a {@code byte[]} in argument will copy it.
* For more info, please refer to the documentation of {@link HBaseRpc}.
* <h1>A note on passing {@code String}s in argument</h1>
* All strings are assumed to use the platform's default charset.
*/
public final class MultiColumnAtomicIncrementRequest extends HBaseRpc
implements HBaseRpc.HasTable, HBaseRpc.HasKey,
HBaseRpc.HasFamily, HBaseRpc.HasQualifiers, HBaseRpc.IsEdit {
private static byte[][] toByteArrays(String[] strArray) {
byte[][] converted = new byte[strArray.length][];
for(int i = 0; i < strArray.length; i++) {
converted[i] = strArray[i].getBytes();
}
return converted;
}
private static final byte[] INCREMENT_COLUMN_VALUE = new byte[] {
'i', 'n', 'c', 'r', 'e', 'm', 'e', 'n', 't',
'C', 'o', 'l', 'u', 'm', 'n',
'V', 'a', 'l', 'u', 'e'
};
private static final Joiner AMOUNT_JOINER = Joiner.on(",");
private final byte[] family;
private final byte[][] qualifiers;
private long[] amounts;
private boolean durable = true;
/**
* Constructor.
* <strong>These byte arrays will NOT be copied.</strong>
* @param table The non-empty name of the table to use.
* @param key The row key of the value to increment.
* @param family The column family of the value to increment.
* @param qualifiers The column qualifier of the value to increment.
* @param amounts Amount by which to increment the value in HBase.
* If negative, the value in HBase will be decremented.
*/
public MultiColumnAtomicIncrementRequest(final byte[] table,
final byte[] key,
final byte[] family,
final byte[][] qualifiers,
final long[] amounts) {
super(table, key);
KeyValue.checkFamily(family);
this.family = family;
if (qualifiers == null || qualifiers.length == 0) {
throw new IllegalArgumentException("qualifiers must be provided for MultiColumnAtomicIncrementRequest");
}
for (byte[] qualifier : qualifiers) {
KeyValue.checkQualifier(qualifier);
}
this.qualifiers = qualifiers;
if (amounts != null) {
if (amounts.length == 0) {
throw new IllegalArgumentException("amounts must be provided for MultiColumnAtomicIncrementRequest");
}
if (qualifiers.length != amounts.length) {
throw new IllegalArgumentException("Number of amounts must be equal to the number of qualifiers provided for MultiColumnAtomicIncrementRequest");
}
this.amounts = amounts;
} else {
this.amounts = new long[qualifiers.length];
Arrays.fill(this.amounts, 1L);
}
}
/**
* Constructor. This is equivalent to:
* {@link #MultiColumnAtomicIncrementRequest(byte[], byte[], byte[], byte[][], long[])
* MultiColumnAtomicIncrementRequest}{@code (table, key, family, qualifiers, new long[] {1, ..})}
* <p>
* <strong>These byte arrays will NOT be copied.</strong>
* @param table The non-empty name of the table to use.
* @param key The row key of the value to increment.
* @param family The column family of the value to increment.
* @param qualifiers The column qualifier of the value to increment.
*/
public MultiColumnAtomicIncrementRequest(final byte[] table,
final byte[] key,
final byte[] family,
final byte[][] qualifiers) {
this(table, key, family, qualifiers, null);
}
/**
* Constructor.
* All strings are assumed to use the platform's default charset.
* @param table The non-empty name of the table to use.
* @param key The row key of the value to increment.
* @param family The column family of the value to increment.
* @param qualifiers The column qualifier of the value to increment.
* @param amounts Amount by which to increment the value in HBase.
* If negative, the value in HBase will be decremented.
*/
public MultiColumnAtomicIncrementRequest(final String table,
final String key,
final String family,
final String[] qualifiers,
final long[] amounts) {
this(table.getBytes(), key.getBytes(), family.getBytes(),
toByteArrays(qualifiers), amounts);
}
/**
* Constructor. This is equivalent to:
* All strings are assumed to use the platform's default charset.
* {@link #MultiColumnAtomicIncrementRequest(String, String, String, String[], long[])
* MultiColumnAtomicIncrementRequest}{@code (table, key, family, qualifiers, new long[]{ 1, ..})}
* @param table The non-empty name of the table to use.
* @param key The row key of the value to increment.
* @param family The column family of the value to increment.
* @param qualifiers The column qualifier of the value to increment.
*/
public MultiColumnAtomicIncrementRequest(final String table,
final String key,
final String family,
final String[] qualifiers) {
this(table.getBytes(), key.getBytes(), family.getBytes(),
toByteArrays(qualifiers), null);
}
/**
* Returns the amount by which the value is going to be incremented.
*/
public long[] getAmounts() {
return amounts;
}
/**
* Changes the amounts by which the values are going to be incremented.
* @param amounts The new amounts. If negative, the value will be decremented.
*/
public void setAmounts(final long[] amounts) {
this.amounts = amounts;
}
@Override
byte[] method(final byte server_version) {
return (server_version >= RegionClient.SERVER_VERSION_095_OR_ABOVE
? MUTATE
: INCREMENT_COLUMN_VALUE);
}
@Override
public byte[] table() {
return table;
}
@Override
public byte[] key() {
return key;
}
@Override
public byte[] family() {
return family;
}
@Override
public byte[][] qualifiers() {
return qualifiers;
}
public String toString() {
return super.toStringWithQualifiers("MultiColumnAtomicIncrementRequest",
family, qualifiers, null, ", amounts=" + AMOUNT_JOINER.join(Arrays.asList(amounts)));
}
// ---------------------- //
// Package private stuff. //
// ---------------------- //
/**
* Changes whether or not this atomic increment should use the WAL.
* @param durable {@code true} to use the WAL, {@code false} otherwise.
*/
void setDurable(final boolean durable) {
this.durable = durable;
}
private int predictSerializedSize() {
int size = 0;
size += 4; // int: Number of parameters.
size += 1; // byte: Type of the 1st parameter.
size += 3; // vint: region name length (3 bytes => max length = 32768).
size += region.name().length; // The region name.
size += 1; // byte: Type of the 2nd parameter.
size += 3; // vint: row key length (3 bytes => max length = 32768).
size += key.length; // The row key.
size += 1; // byte: Type of the 3rd parameter.
size += 1; // vint: Family length (guaranteed on 1 byte).
size += family.length; // The family.
size += 1; // byte: Type of the 4th parameter.
size += 3; // vint: Qualifier length.
for(byte[] qualifier : qualifiers) {
size += qualifier.length; // The qualifier.
}
size += 1; // byte: Type of the 5th parameter.
size += 8 * amounts.length; // long: Amount.
size += 1; // byte: Type of the 6th parameter.
size += 1; // bool: Whether or not to write to the WAL.
return size;
}
/** Serializes this request. */
ChannelBuffer serialize(final byte server_version) {
if (server_version < RegionClient.SERVER_VERSION_095_OR_ABOVE) {
throw new UnsupportedOperationException(server_version + " is not supported by " + this.getClass().getName());
}
MutationProto.Builder incr = MutationProto.newBuilder()
.setRow(Bytes.wrap(key))
.setMutateType(MutationProto.MutationType.INCREMENT);
for (int i = 0; i < qualifiers.length; i++) {
final MutationProto.ColumnValue.QualifierValue qualifier =
MutationProto.ColumnValue.QualifierValue.newBuilder()
.setQualifier(Bytes.wrap(this.qualifiers[i]))
.setValue(Bytes.wrap(Bytes.fromLong(this.amounts[i])))
.build();
final MutationProto.ColumnValue column =
MutationProto.ColumnValue.newBuilder()
.setFamily(Bytes.wrap(family))
.addQualifierValue(qualifier)
.build();
incr.addColumnValue(column);
}
if (!durable) {
incr.setDurability(MutationProto.Durability.SKIP_WAL);
}
final MutateRequest req = MutateRequest.newBuilder()
.setRegion(region.toProtobuf())
.setMutation(incr.build())
.build();
return toChannelBuffer(MUTATE, req);
}
@Override
Object deserialize(final ChannelBuffer buf, int cell_size) {
final MutateResponse resp = readProtobuf(buf, MutateResponse.PARSER);
// An increment must always produce a result, so we shouldn't need to
// check whether the `result' field is set here.
final ArrayList<KeyValue> kvs = GetRequest.convertResult(resp.getResult(),
buf, cell_size);
Map<byte[], Long> updatedValues = Maps.newHashMap();
for (KeyValue kv : kvs) {
updatedValues.put(kv.qualifier(), Bytes.getLong(kv.value()));
}
return updatedValues;
}
}
| manolama/asynchbase | src/MultiColumnAtomicIncrementRequest.java | Java | bsd-3-clause | 11,947 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE197_Numeric_Truncation_Error__int_connect_socket_to_short_74a.cpp
Label Definition File: CWE197_Numeric_Truncation_Error__int.label.xml
Template File: sources-sink-74a.tmpl.cpp
*/
/*
* @description
* CWE: 197 Numeric Truncation Error
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Less than CHAR_MAX
* Sinks: to_short
* BadSink : Convert data to a short
* Flow Variant: 74 Data flow: data passed in a map from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <map>
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)
using namespace std;
namespace CWE197_Numeric_Truncation_Error__int_connect_socket_to_short_74
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(map<int, int> dataMap);
void bad()
{
int data;
map<int, int> dataMap;
/* Initialize data */
data = -1;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
SOCKET connectSocket = INVALID_SOCKET;
char inputBuffer[CHAR_ARRAY_SIZE];
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* NUL-terminate the string */
inputBuffer[recvResult] = '\0';
/* Convert to int */
data = atoi(inputBuffer);
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
/* Put data in a map */
dataMap[0] = data;
dataMap[1] = data;
dataMap[2] = data;
badSink(dataMap);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declarations */
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(map<int, int> dataMap);
static void goodG2B()
{
int data;
map<int, int> dataMap;
/* Initialize data */
data = -1;
/* FIX: Use a positive integer less than CHAR_MAX*/
data = CHAR_MAX-5;
/* Put data in a map */
dataMap[0] = data;
dataMap[1] = data;
dataMap[2] = data;
goodG2BSink(dataMap);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* 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
using namespace CWE197_Numeric_Truncation_Error__int_connect_socket_to_short_74; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE197_Numeric_Truncation_Error/s01/CWE197_Numeric_Truncation_Error__int_connect_socket_to_short_74a.cpp | C++ | bsd-3-clause | 4,835 |
<?php
namespace ZF\Apigility\Doctrine\Server\Query\Provider;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use Zend\Paginator\Adapter\AdapterInterface;
use Zend\ServiceManager\AbstractPluginManager;
use ZF\Rest\ResourceEvent;
interface QueryProviderInterface extends ObjectManagerAwareInterface
{
/**
* @param string $entityClass
* @param array $parameters
*
* @return mixed This will return an ORM or ODM Query\Builder
*/
public function createQuery(ResourceEvent $event, $entityClass, $parameters);
/**
* This function is not necessary for any but fetch-all queries
* In order to provide a single QueryProvider service this is
* included in this interface.
*
* @param $queryBuilder
*
* @return AdapterInterface
*/
public function getPaginatedQuery($queryBuilder);
/**
* This function is not necessary for any but fetch-all queries
* In order to provide a single QueryProvider service this is
* included in this interface.
*
* @param $entityClass
*
* @return int
*/
public function getCollectionTotal($entityClass);
}
| alunys/ApigilityAngularTest | vendor/zfcampus/zf-apigility-doctrine/src/Server/Query/Provider/QueryProviderInterface.php | PHP | bsd-3-clause | 1,172 |
#include <cloudcv.hpp>
#include <framework/marshal/marshal.hpp>
#include <framework/marshal/node_object_builder.hpp>
#include <framework/Job.hpp>
#include <framework/NanCheck.hpp>
#include <framework/Logger.h>
#include "framework/ImageSource.hpp"
#include "CameraCalibrationAlgorithm.hpp"
using namespace v8;
using namespace node;
namespace cloudcv
{
class DetectPatternTask : public Job
{
public:
DetectPatternTask(ImageSourcePtr imageSource, cv::Size patternSize, PatternType type, NanCallback * callback)
: Job(callback)
, m_imageSource(imageSource)
, m_algorithm(patternSize, type)
{
TRACE_FUNCTION;
}
virtual ~DetectPatternTask()
{
TRACE_FUNCTION;
}
protected:
void ExecuteNativeCode()
{
TRACE_FUNCTION;
cv::Mat frame = m_imageSource->getImage(cv::IMREAD_GRAYSCALE);
if (frame.empty())
{
SetErrorMessage("Cannot decode input image");
return;
}
try
{
m_patternfound = m_algorithm.detectCorners(frame, m_corners2d);
}
catch (...)
{
SetErrorMessage("Internal exception");
}
}
virtual Local<Value> CreateCallbackResult()
{
TRACE_FUNCTION;
NanEscapableScope();
Local<Object> res = NanNew<Object>(); //(Object::New());
NodeObject resultWrapper(res);
resultWrapper["patternFound"] = m_patternfound;
if (m_patternfound)
{
resultWrapper["corners"] = m_corners2d;
}
return NanEscapeScope(res);
}
private:
ImageSourcePtr m_imageSource;
CameraCalibrationAlgorithm m_algorithm;
CameraCalibrationAlgorithm::VectorOf2DPoints m_corners2d;
bool m_patternfound;
bool m_returnImage;
};
class ComputeIntrinsicParametersTask : public Job
{
public:
typedef CameraCalibrationAlgorithm::VectorOfVectorOf3DPoints VectorOfVectorOf3DPoints;
typedef CameraCalibrationAlgorithm::VectorOfVectorOf2DPoints VectorOfVectorOf2DPoints;
typedef CameraCalibrationAlgorithm::VectorOfMat VectorOfMat;
ComputeIntrinsicParametersTask(
const std::vector<std::string>& files,
cv::Size boardSize,
PatternType type,
NanCallback * callback
)
: Job(callback)
, m_algorithm(boardSize, type)
, m_imageFiles(files)
{
}
ComputeIntrinsicParametersTask(
const VectorOfVectorOf2DPoints& v,
cv::Size imageSize,
cv::Size boardSize,
PatternType type,
NanCallback * callback
)
: Job(callback)
, m_algorithm(boardSize, type)
, m_imageSize(imageSize)
, m_gridCorners(v)
{
}
protected:
virtual void ExecuteNativeCode()
{
TRACE_FUNCTION;
if (!m_imageFiles.empty())
{
m_gridCorners.resize(m_imageFiles.size());
for (size_t i = 0; i < m_imageFiles.size(); i++)
{
cv::Mat image = CreateImageSource(m_imageFiles[i])->getImage(cv::IMREAD_GRAYSCALE);
if (image.empty())
{
SetErrorMessage(std::string("Cannot read image at index ") + lexical_cast(i) + ": " + m_imageFiles[i]);
return;
}
if (!m_algorithm.detectCorners(image, m_gridCorners[i]))
{
SetErrorMessage(std::string("Cannot detect calibration pattern on image at index ") + lexical_cast(i));
return;
}
m_imageSize = image.size();
}
}
if (!m_gridCorners.empty())
{
m_calibrationSuccess = m_algorithm.calibrateCamera(m_gridCorners, m_imageSize, m_cameraMatrix, m_distCoeffs);
LOG_TRACE_MESSAGE("m_calibrationSuccess = " << m_calibrationSuccess);
}
else
{
SetErrorMessage("Neither image files nor grid corners were passed");
return;
}
}
virtual Local<Value> CreateCallbackResult()
{
TRACE_FUNCTION;
NanEscapableScope();
Local<Object> res = NanNew<Object>(); //Local(Object::New());
NodeObject resultWrapper(res);
if (m_calibrationSuccess)
{
resultWrapper["intrinsic"] = m_cameraMatrix;
resultWrapper["distCoeffs"] = m_distCoeffs;
}
resultWrapper["calibrationSuccess"] = m_calibrationSuccess;
return NanEscapeScope(res);
}
private:
CameraCalibrationAlgorithm m_algorithm;
std::vector<std::string> m_imageFiles;
cv::Size m_imageSize;
VectorOfVectorOf2DPoints m_gridCorners;
cv::Mat m_cameraMatrix;
cv::Mat m_distCoeffs;
bool m_calibrationSuccess;
};
NAN_METHOD(calibrationPatternDetect)
{
TRACE_FUNCTION;
NanEscapableScope();
Local<Object> imageBuffer;
std::string imagePath;
Local<Function> callback;
cv::Size patternSize;
PatternType pattern;
std::string error;
LOG_TRACE_MESSAGE("Begin parsing arguments");
if (NanCheck(args)
.Error(&error)
.ArgumentsCount(4)
.Argument(0).IsBuffer().Bind(imageBuffer)
.Argument(1).Bind(patternSize)
.Argument(2).StringEnum<PatternType>({
{ "CHESSBOARD", PatternType::CHESSBOARD },
{ "CIRCLES_GRID", PatternType::CIRCLES_GRID },
{ "ACIRCLES_GRID", PatternType::ACIRCLES_GRID } }).Bind(pattern)
.Argument(3).IsFunction().Bind(callback))
{
LOG_TRACE_MESSAGE("Parsed function arguments");
NanCallback *nanCallback = new NanCallback(callback);
NanAsyncQueueWorker(new DetectPatternTask(
CreateImageSource(imageBuffer),
patternSize,
pattern,
nanCallback));
}
else if (NanCheck(args)
.Error(&error)
.ArgumentsCount(4)
.Argument(0).IsString().Bind(imagePath)
.Argument(1).Bind(patternSize)
.Argument(2).StringEnum<PatternType>({
{ "CHESSBOARD", PatternType::CHESSBOARD },
{ "CIRCLES_GRID", PatternType::CIRCLES_GRID },
{ "ACIRCLES_GRID", PatternType::ACIRCLES_GRID } }).Bind(pattern)
.Argument(3).IsFunction().Bind(callback))
{
LOG_TRACE_MESSAGE("Parsed function arguments");
NanCallback *nanCallback = new NanCallback(callback);
NanAsyncQueueWorker(new DetectPatternTask(
CreateImageSource(imagePath),
patternSize,
pattern,
nanCallback));
}
else if (!error.empty())
{
LOG_TRACE_MESSAGE(error);
NanThrowTypeError(error.c_str());
}
NanReturnUndefined();
}
NAN_METHOD(calibrateCamera)
{
TRACE_FUNCTION;
NanEscapableScope();
std::vector<std::string> imageFiles;
std::vector< std::vector<cv::Point2f> > imageCorners;
Local<Function> callback;
cv::Size patternSize;
cv::Size imageSize;
PatternType pattern;
std::string error;
if (NanCheck(args)
.Error(&error)
.ArgumentsCount(4)
.Argument(0).IsArray().Bind(imageFiles)
.Argument(1).Bind(patternSize)
.Argument(2).StringEnum<PatternType>({
{ "CHESSBOARD", PatternType::CHESSBOARD },
{ "CIRCLES_GRID", PatternType::CIRCLES_GRID },
{ "ACIRCLES_GRID", PatternType::ACIRCLES_GRID } }).Bind(pattern)
.Argument(3).IsFunction().Bind(callback))
{
LOG_TRACE_MESSAGE("Image files count: " << imageFiles.size());
NanCallback *nanCallback = new NanCallback(callback);
NanAsyncQueueWorker(new ComputeIntrinsicParametersTask(imageFiles, patternSize, pattern, nanCallback));
} else if (NanCheck(args)
.Error(&error)
.ArgumentsCount(6)
.Argument(0).IsArray().Bind(imageCorners)
.Argument(1).Bind(imageSize)
.Argument(2).Bind(patternSize)
.Argument(3).StringEnum<PatternType>({
{ "CHESSBOARD", PatternType::CHESSBOARD },
{ "CIRCLES_GRID", PatternType::CIRCLES_GRID },
{ "ACIRCLES_GRID", PatternType::ACIRCLES_GRID } }).Bind(pattern)
.Argument(4).IsFunction().Bind(callback))
{
NanCallback *nanCallback = new NanCallback(callback);
NanAsyncQueueWorker(new ComputeIntrinsicParametersTask(imageCorners, imageSize, patternSize, pattern, nanCallback));
}
else if (!error.empty())
{
NanThrowTypeError(error.c_str());
}
NanReturnUndefined();
}
}
| MalcolmD/CloudCVPlusDetection | src/modules/cameraCalibration/CameraCalibrationBinding.cpp | C++ | bsd-3-clause | 10,211 |
/*
* $Id$
*/
/*
Copyright (c) 2000-2002 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.mbf;
import java.util.*;
import java.security.*;
import java.io.*;
import org.lockss.util.*;
import org.lockss.plugin.*;
import org.lockss.daemon.*;
import org.lockss.protocol.*;
/**
* @author David S. H. Rosenthal
* @version 1.0
*/
public class MockMemoryBoundFunctionVote extends MemoryBoundFunctionVote {
private byte[][] mockHashes;
private int[][] mockProofs;
private boolean[] mockVerifies;
private int stepLimit;
/**
* No-argument constructor for use with Class.newInstance().
*/
public MockMemoryBoundFunctionVote() {
mockHashes = null;
mockProofs = null;
mockVerifies = null;
stepLimit = 0;
}
/**
* Public constructor for an object that will compute a vote
* using hashing and memory bound functions.
* It accepts as input a nonce and a CachedUrlSet. It divides the
* content into i blocks of length <= 2**(i+1) and for each computes
* the MBF proof and the hash. The first proof depends on the nonce
* the AU name and the first bytes of the AU. Subsequent proofs
* depend on the preceeding hash and proof. The effort sizer e
* is constant for all rounds. The path length l is set equal to
* the block size for that round.
* @param nVal a byte array containing the nonce
* @param eVal the effort sizer (# of low-order zeros in destination)
* @param cusVal the CachedUrlSet containing the content to be voted on
* @param pollID the byte array ID for the poll
* @param voterID the PeerIdentity of the voter
*
*/
protected void setupGeneration(MemoryBoundFunctionFactory fact,
byte[] nVal,
int eVal,
CachedUrlSet cusVal,
byte[] pollID,
PeerIdentity voterID)
throws MemoryBoundFunctionException {
super.setupGeneration(fact, nVal, eVal, cusVal, pollID, voterID);
setup(nVal, eVal, cusVal);
}
/**
* Public constructor for an object that will verify a vote
* using hashing and memory bound functions. It accepts as
* input a nonce, a cachedUrlSet, and arrays of proofs
* and hashes.
* @param nVal a byte array containing the nonce
* @param eVal the effort sizer (# of low-order zeros in destination)
* @param cusVal the CachedUrlSet containing the content to be voted on
* @param sVals the starting points chosen by the prover for each block
* @param hashes the hashes of each block
* @param pollID the byte array ID for the poll
* @param voterID the PeerIdentity of the voter
*
*/
public void setupVerification(MemoryBoundFunctionFactory fact,
byte[] nVal,
int eVal,
CachedUrlSet cusVal,
int sVals[][],
byte[][] hashes,
byte[] pollID,
PeerIdentity voterID)
throws MemoryBoundFunctionException {
super.setupVerification(fact, nVal, eVal, cusVal, sVals, hashes,
pollID, voterID);
setup(nVal, eVal, cusVal);
}
private void setup(byte[] nVal, int eVal, CachedUrlSet cusVal) throws
MemoryBoundFunctionException {
finished = false;
}
/**
* Do "n" steps of the underlying hash or effort proof generation
* @param n number of steps to move.
* @return true if there is more work to do
*
*/
public boolean computeSteps(int n) throws MemoryBoundFunctionException {
stepLimit -= n;
if (stepLimit <= 0) {
logger.info("MockMemoryBoundFunctionVote: valid " + valid +
" agreeing " + agreeing);
finished = true;
}
return (!finished);
}
protected void setStepCount(int steps) {
stepLimit = steps;
}
protected void setHashes(byte[][] hshs) {
mockHashes = hshs;
for (int i = 0; i <mockHashes.length; i++)
saveHash(i, mockHashes[i]);
}
protected void setProofs(int[][] prfs) {
mockProofs = prfs;
for (int i = 0; i < mockProofs.length; i++)
saveProof(i , mockProofs[i]);
}
protected void setValid(boolean val) {
valid = val;
}
protected void setAgreeing(boolean val) {
agreeing = val;
}
protected void setFinished(boolean val) {
finished = val;
}
}
| lockss/lockss-daemon | test/src/org/lockss/mbf/MockMemoryBoundFunctionVote.java | Java | bsd-3-clause | 5,392 |
(function ($) {
'use strict';
var dw, dh, rw, rh, lx, ly;
var defaults = {
// The text to display within the notice box while loading the zoom image.
loadingNotice: 'Loading image',
// The text to display within the notice box if an error occurs when loading the zoom image.
errorNotice: 'The image could not be loaded',
// The time (in milliseconds) to display the error notice.
errorDuration: 2500,
// Attribute to retrieve the zoom image URL from.
linkAttribute: 'href',
// Prevent clicks on the zoom image link.
preventClicks: true,
// Callback function to execute before the flyout is displayed.
beforeShow: $.noop,
// Callback function to execute before the flyout is removed.
beforeHide: $.noop,
// Callback function to execute when the flyout is displayed.
onShow: $.noop,
// Callback function to execute when the flyout is removed.
onHide: $.noop,
// Callback function to execute when the cursor is moved while over the image.
onMove: $.noop
};
/**
* EasyZoom
* @constructor
* @param {Object} target
* @param {Object} options (Optional)
*/
function EasyZoom(target, options) {
this.$target = $(target);
this.opts = $.extend({}, defaults, options, this.$target.data());
this.isOpen === undefined && this._init();
}
/**
* Init
* @private
*/
EasyZoom.prototype._init = function() {
this.$link = this.$target.find('a');
this.$image = this.$target.find('img');
this.$flyout = $('<div class="easyzoom-flyout" />');
this.$notice = $('<div class="easyzoom-notice" />');
this.$target.on({
'mousemove.easyzoom touchmove.easyzoom': $.proxy(this._onMove, this),
'mouseleave.easyzoom touchend.easyzoom': $.proxy(this._onLeave, this),
'mouseenter.easyzoom touchstart.easyzoom': $.proxy(this._onEnter, this)
});
this.opts.preventClicks && this.$target.on('click.easyzoom', function(e) {
e.preventDefault();
});
};
/**
* Show
* @param {MouseEvent|TouchEvent} e
* @param {Boolean} testMouseOver (Optional)
*/
EasyZoom.prototype.show = function(e, testMouseOver) {
var w1, h1, w2, h2;
var self = this;
if (this.opts.beforeShow.call(this) === false) return;
if (!this.isReady) {
return this._loadImage(this.$link.attr(this.opts.linkAttribute), function() {
if (self.isMouseOver || !testMouseOver) {
self.show(e);
}
});
}
this.$target.append(this.$flyout);
w1 = this.$target.width();
h1 = this.$target.height();
w2 = this.$flyout.width();
h2 = this.$flyout.height();
dw = this.$zoom.width() - w2;
dh = this.$zoom.height() - h2;
// For the case where the zoom image is actually smaller than
// the flyout.
if (dw < 0) dw = 0;
if (dh < 0) dh = 0;
rw = dw / w1;
rh = dh / h1;
this.isOpen = true;
this.opts.onShow.call(this);
e && this._move(e);
};
/**
* On enter
* @private
* @param {Event} e
*/
EasyZoom.prototype._onEnter = function(e) {
var touches = e.originalEvent.touches;
this.isMouseOver = true;
if (!touches || touches.length == 1) {
e.preventDefault();
this.show(e, true);
}
};
/**
* On move
* @private
* @param {Event} e
*/
EasyZoom.prototype._onMove = function(e) {
if (!this.isOpen) return;
e.preventDefault();
this._move(e);
};
/**
* On leave
* @private
*/
EasyZoom.prototype._onLeave = function() {
this.isMouseOver = false;
this.isOpen && this.hide();
};
/**
* On load
* @private
* @param {Event} e
*/
EasyZoom.prototype._onLoad = function(e) {
// IE may fire a load event even on error so test the image dimensions
if (!e.currentTarget.width) return;
this.isReady = true;
this.$notice.detach();
this.$flyout.html(this.$zoom);
this.$target.removeClass('is-loading').addClass('is-ready');
e.data.call && e.data();
};
/**
* On error
* @private
*/
EasyZoom.prototype._onError = function() {
var self = this;
this.$notice.text(this.opts.errorNotice);
this.$target.removeClass('is-loading').addClass('is-error');
this.detachNotice = setTimeout(function() {
self.$notice.detach();
self.detachNotice = null;
}, this.opts.errorDuration);
};
/**
* Load image
* @private
* @param {String} href
* @param {Function} callback
*/
EasyZoom.prototype._loadImage = function(href, callback) {
var zoom = new Image;
this.$target
.addClass('is-loading')
.append(this.$notice.text(this.opts.loadingNotice));
this.$zoom = $(zoom)
.on('error', $.proxy(this._onError, this))
.on('load', callback, $.proxy(this._onLoad, this));
zoom.style.position = 'absolute';
zoom.src = href;
};
/**
* Move
* @private
* @param {Event} e
*/
EasyZoom.prototype._move = function(e) {
if (e.type.indexOf('touch') === 0) {
var touchlist = e.touches || e.originalEvent.touches;
lx = touchlist[0].pageX;
ly = touchlist[0].pageY;
} else {
lx = e.pageX || lx;
ly = e.pageY || ly;
}
var offset = this.$target.offset();
var pt = ly - offset.top;
var pl = lx - offset.left;
var xt = Math.ceil(pt * rh);
var xl = Math.ceil(pl * rw);
// Close if outside
if (xl < 0 || xt < 0 || xl > dw || xt > dh) {
this.hide();
} else {
var top = xt * -1;
var left = xl * -1;
this.$zoom.css({
top: top,
left: left
});
this.opts.onMove.call(this, top, left);
}
};
/**
* Hide
*/
EasyZoom.prototype.hide = function() {
if (!this.isOpen) return;
if (this.opts.beforeHide.call(this) === false) return;
this.$flyout.detach();
this.isOpen = false;
this.opts.onHide.call(this);
};
/**
* Swap
* @param {String} standardSrc
* @param {String} zoomHref
* @param {String|Array} srcset (Optional)
*/
EasyZoom.prototype.swap = function(standardSrc, zoomHref, srcset) {
this.hide();
this.isReady = false;
this.detachNotice && clearTimeout(this.detachNotice);
this.$notice.parent().length && this.$notice.detach();
this.$target.removeClass('is-loading is-ready is-error');
this.$image.attr({
src: standardSrc,
srcset: $.isArray(srcset) ? srcset.join() : srcset
});
this.$link.attr(this.opts.linkAttribute, zoomHref);
};
/**
* Teardown
*/
EasyZoom.prototype.teardown = function() {
this.hide();
this.$target
.off('.easyzoom')
.removeClass('is-loading is-ready is-error');
this.detachNotice && clearTimeout(this.detachNotice);
delete this.$link;
delete this.$zoom;
delete this.$image;
delete this.$notice;
delete this.$flyout;
delete this.isOpen;
delete this.isReady;
};
// jQuery plugin wrapper
$.fn.easyZoom = function(options) {
return this.each(function() {
var api = $.data(this, 'easyZoom');
if (!api) {
$.data(this, 'easyZoom', new EasyZoom(this, options));
} else if (api.isOpen === undefined) {
api._init();
}
});
};
// AMD and CommonJS module compatibility
if (typeof define === 'function' && define.amd){
define(function() {
return EasyZoom;
});
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = EasyZoom;
}
})(jQuery);
| 201528013359030/basic_pai | views/js/easyzoom.js | JavaScript | bsd-3-clause | 8,461 |
# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# Adapted from portage/getbinpkg.py -- Portage binary-package helper functions
# Copyright 2003-2004 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
"""Helpers dealing with binpkg Packages index files"""
import collections
import cStringIO
import operator
import os
import tempfile
import time
import urllib2
from chromite.lib import cros_build_lib
from chromite.lib import gs
from chromite.lib import parallel
TWO_WEEKS = 60 * 60 * 24 * 7 * 2
HTTP_FORBIDDEN_CODES = (401, 403)
HTTP_NOT_FOUND_CODES = (404, 410)
_Package = collections.namedtuple('_Package', ['mtime', 'uri'])
class PackageIndex(object):
"""A parser for the Portage Packages index file.
The Portage Packages index file serves to keep track of what packages are
included in a tree. It contains the following sections:
1) The header. The header tracks general key/value pairs that don't apply
to any specific package. E.g., it tracks the base URL of the packages
file, and the number of packages included in the file. The header is
terminated by a blank line.
2) The body. The body is a list of packages. Each package contains a list
of key/value pairs. Packages are either terminated by a blank line or
by the end of the file. Every package has a CPV entry, which serves as
a unique identifier for the package.
"""
def __init__(self):
"""Constructor."""
# The header tracks general key/value pairs that don't apply to any
# specific package. E.g., it tracks the base URL of the packages.
self.header = {}
# A list of packages (stored as a list of dictionaries).
self.packages = []
# Whether or not the PackageIndex has been modified since the last time it
# was written.
self.modified = False
def _PopulateDuplicateDB(self, db, expires):
"""Populate db with SHA1 -> URL mapping for packages.
Args:
db: Dictionary to populate with SHA1 -> URL mapping for packages.
expires: The time at which prebuilts expire from the binhost.
"""
uri = gs.CanonicalizeURL(self.header['URI'])
for pkg in self.packages:
cpv, sha1, mtime = pkg['CPV'], pkg.get('SHA1'), pkg.get('MTIME')
oldpkg = db.get(sha1, _Package(0, None))
if sha1 and mtime and int(mtime) > max(expires, oldpkg.mtime):
path = pkg.get('PATH', cpv + '.tbz2')
db[sha1] = _Package(int(mtime), '%s/%s' % (uri.rstrip('/'), path))
def _ReadPkgIndex(self, pkgfile):
"""Read a list of key/value pairs from the Packages file into a dictionary.
Both header entries and package entries are lists of key/value pairs, so
they can both be read by this function. Entries can be terminated by empty
lines or by the end of the file.
This function will read lines from the specified file until it encounters
the a blank line or the end of the file.
Keys and values in the Packages file are separated by a colon and a space.
Keys may contain capital letters, numbers, and underscores, but may not
contain colons. Values may contain any character except a newline. In
particular, it is normal for values to contain colons.
Lines that have content, and do not contain a valid key/value pair, are
ignored. This is for compatibility with the Portage package parser, and
to allow for future extensions to the Packages file format.
All entries must contain at least one key/value pair. If the end of the
fils is reached, an empty dictionary is returned.
Args:
pkgfile: A python file object.
Returns:
The dictionary of key-value pairs that was read from the file.
"""
d = {}
for line in pkgfile:
line = line.rstrip('\n')
if not line:
assert d, 'Packages entry must contain at least one key/value pair'
break
line = line.split(': ', 1)
if len(line) == 2:
k, v = line
d[k] = v
return d
def _WritePkgIndex(self, pkgfile, entry):
"""Write header entry or package entry to packages file.
The keys and values will be separated by a colon and a space. The entry
will be terminated by a blank line.
Args:
pkgfile: A python file object.
entry: A dictionary of the key/value pairs to write.
"""
lines = ['%s: %s' % (k, v) for k, v in sorted(entry.items()) if v]
pkgfile.write('%s\n\n' % '\n'.join(lines))
def _ReadHeader(self, pkgfile):
"""Read header of packages file.
Args:
pkgfile: A python file object.
"""
assert not self.header, 'Should only read header once.'
self.header = self._ReadPkgIndex(pkgfile)
def _ReadBody(self, pkgfile):
"""Read body of packages file.
Before calling this function, you must first read the header (using
_ReadHeader).
Args:
pkgfile: A python file object.
"""
assert self.header, 'Should read header first.'
assert not self.packages, 'Should only read body once.'
# Read all of the sections in the body by looping until we reach the end
# of the file.
while True:
d = self._ReadPkgIndex(pkgfile)
if not d:
break
if 'CPV' in d:
self.packages.append(d)
def Read(self, pkgfile):
"""Read the entire packages file.
Args:
pkgfile: A python file object.
"""
self._ReadHeader(pkgfile)
self._ReadBody(pkgfile)
def RemoveFilteredPackages(self, filter_fn):
"""Remove packages which match filter_fn.
Args:
filter_fn: A function which operates on packages. If it returns True,
the package should be removed.
"""
filtered = [p for p in self.packages if not filter_fn(p)]
if filtered != self.packages:
self.modified = True
self.packages = filtered
def ResolveDuplicateUploads(self, pkgindexes):
"""Point packages at files that have already been uploaded.
For each package in our index, check if there is an existing package that
has already been uploaded to the same base URI, and that is no older than
two weeks. If so, point that package at the existing file, so that we don't
have to upload the file.
Args:
pkgindexes: A list of PackageIndex objects containing info about packages
that have already been uploaded.
Returns:
A list of the packages that still need to be uploaded.
"""
db = {}
now = int(time.time())
expires = now - TWO_WEEKS
base_uri = gs.CanonicalizeURL(self.header['URI'])
for pkgindex in pkgindexes:
if gs.CanonicalizeURL(pkgindex.header['URI']) == base_uri:
# pylint: disable=W0212
pkgindex._PopulateDuplicateDB(db, expires)
uploads = []
base_uri = self.header['URI']
for pkg in self.packages:
sha1 = pkg.get('SHA1')
dup = db.get(sha1)
if sha1 and dup and dup.uri.startswith(base_uri):
pkg['PATH'] = dup.uri[len(base_uri):].lstrip('/')
pkg['MTIME'] = str(dup.mtime)
else:
pkg['MTIME'] = str(now)
uploads.append(pkg)
return uploads
def SetUploadLocation(self, base_uri, path_prefix):
"""Set upload location to base_uri + path_prefix.
Args:
base_uri: Base URI for all packages in the file. We set
self.header['URI'] to this value, so all packages must live under
this directory.
path_prefix: Path prefix to use for all current packages in the file.
This will be added to the beginning of the path for every package.
"""
self.header['URI'] = base_uri
for pkg in self.packages:
path = pkg['CPV'] + '.tbz2'
pkg['PATH'] = '%s/%s' % (path_prefix.rstrip('/'), path)
def Write(self, pkgfile):
"""Write a packages file to disk.
If 'modified' flag is set, the TIMESTAMP and PACKAGES fields in the header
will be updated before writing to disk.
Args:
pkgfile: A python file object.
"""
if self.modified:
self.header['TIMESTAMP'] = str(long(time.time()))
self.header['PACKAGES'] = str(len(self.packages))
self.modified = False
self._WritePkgIndex(pkgfile, self.header)
for metadata in sorted(self.packages, key=operator.itemgetter('CPV')):
self._WritePkgIndex(pkgfile, metadata)
def WriteToNamedTemporaryFile(self):
"""Write pkgindex to a temporary file.
Args:
pkgindex: The PackageIndex object.
Returns:
A temporary file containing the packages from pkgindex.
"""
f = tempfile.NamedTemporaryFile(prefix='chromite.binpkg.pkgidx.')
self.Write(f)
f.flush()
f.seek(0)
return f
def _RetryUrlOpen(url, tries=3):
"""Open the specified url, retrying if we run into temporary errors.
We retry for both network errors and 5xx Server Errors. We do not retry
for HTTP errors with a non-5xx code.
Args:
url: The specified url.
tries: The number of times to try.
Returns:
The result of urllib2.urlopen(url).
"""
for i in range(tries):
try:
return urllib2.urlopen(url)
except urllib2.HTTPError as e:
if i + 1 >= tries or e.code < 500:
e.msg += ('\nwhile processing %s' % url)
raise
else:
print 'Cannot GET %s: %s' % (url, str(e))
except urllib2.URLError as e:
if i + 1 >= tries:
raise
else:
print 'Cannot GET %s: %s' % (url, str(e))
print 'Sleeping for 10 seconds before retrying...'
time.sleep(10)
def GrabRemotePackageIndex(binhost_url):
"""Grab the latest binary package database from the specified URL.
Args:
binhost_url: Base URL of remote packages (PORTAGE_BINHOST).
Returns:
A PackageIndex object, if the Packages file can be retrieved. If the
packages file cannot be retrieved, then None is returned.
"""
url = '%s/Packages' % binhost_url.rstrip('/')
pkgindex = PackageIndex()
if binhost_url.startswith('http'):
try:
f = _RetryUrlOpen(url)
except urllib2.HTTPError as e:
if e.code in HTTP_FORBIDDEN_CODES:
cros_build_lib.PrintBuildbotStepWarnings()
cros_build_lib.Error('Cannot GET %s: %s' % (url, str(e)))
return None
# Not found errors are normal if old prebuilts were cleaned out.
if e.code in HTTP_NOT_FOUND_CODES:
return None
raise
elif binhost_url.startswith('gs://'):
try:
gs_context = gs.GSContext()
output = gs_context.Cat(url).output
except (cros_build_lib.RunCommandError, gs.GSNoSuchKey) as e:
cros_build_lib.PrintBuildbotStepWarnings()
cros_build_lib.Error('Cannot GET %s: %s' % (url, str(e)))
return None
f = cStringIO.StringIO(output)
else:
return None
pkgindex.Read(f)
pkgindex.header.setdefault('URI', binhost_url)
f.close()
return pkgindex
def GrabLocalPackageIndex(package_path):
"""Read a local packages file from disk into a PackageIndex() object.
Args:
package_path: Directory containing Packages file.
Returns:
A PackageIndex object.
"""
packages_file = file(os.path.join(package_path, 'Packages'))
pkgindex = PackageIndex()
pkgindex.Read(packages_file)
packages_file.close()
return pkgindex
def _DownloadURLs(urls, dest_dir):
"""Copy URLs into the specified |dest_dir|.
Args:
urls: List of URLs to fetch.
dest_dir: Destination directory.
"""
gs_ctx = gs.GSContext()
cmd = ['cp'] + urls + [dest_dir]
gs_ctx.DoCommand(cmd, parallel=len(urls) > 1)
def FetchTarballs(binhost_urls, pkgdir):
"""Prefetch the specified |binhost_urls| to the specified |pkgdir|.
This function fetches the tarballs from the specified list of binhost
URLs to disk. It does not populate the Packages file -- we leave that
to Portage.
Args:
binhost_urls: List of binhost URLs to fetch.
pkgdir: Location to store the fetched packages.
"""
categories = {}
for binhost_url in binhost_urls:
pkgindex = GrabRemotePackageIndex(binhost_url)
base_uri = pkgindex.header['URI']
for pkg in pkgindex.packages:
cpv = pkg['CPV']
path = pkg.get('PATH', '%s.tbz2' % cpv)
uri = '/'.join([base_uri, path])
category = cpv.partition('/')[0]
fetches = categories.setdefault(category, {})
fetches[cpv] = uri
with parallel.BackgroundTaskRunner(_DownloadURLs) as queue:
for category, urls in categories.iteritems():
category_dir = os.path.join(pkgdir, category)
if not os.path.exists(category_dir):
os.makedirs(category_dir)
queue.put((urls.values(), category_dir))
| bpsinc-native/src_third_party_chromite | lib/binpkg.py | Python | bsd-3-clause | 12,642 |
// Copyright 2015 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 "config.h"
#include "modules/permissions/PermissionsCallback.h"
#include "bindings/core/v8/ScriptPromiseResolver.h"
#include "modules/permissions/PermissionStatus.h"
namespace blink {
PermissionsCallback::PermissionsCallback(ScriptPromiseResolver* resolver, PassOwnPtr<Vector<WebPermissionType>> internalPermissions, PassOwnPtr<Vector<int>> callerIndexToInternalIndex)
: m_resolver(resolver),
m_internalPermissions(internalPermissions),
m_callerIndexToInternalIndex(callerIndexToInternalIndex)
{
ASSERT(m_resolver);
}
void PermissionsCallback::onSuccess(WebPassOwnPtr<WebVector<WebPermissionStatus>> permissionStatus)
{
if (!m_resolver->executionContext() || m_resolver->executionContext()->activeDOMObjectsAreStopped())
return;
OwnPtr<WebVector<WebPermissionStatus>> statusPtr = permissionStatus.release();
HeapVector<Member<PermissionStatus>> result(m_callerIndexToInternalIndex->size());
// Create the response vector by finding the status for each index by
// using the caller to internal index mapping and looking up the status
// using the internal index obtained.
for (size_t i = 0; i < m_callerIndexToInternalIndex->size(); ++i) {
int internalIndex = m_callerIndexToInternalIndex->operator[](i);
result[i] = PermissionStatus::createAndListen(m_resolver->executionContext(), statusPtr->operator[](internalIndex), m_internalPermissions->operator[](internalIndex));
}
m_resolver->resolve(result);
}
void PermissionsCallback::onError()
{
if (!m_resolver->executionContext() || m_resolver->executionContext()->activeDOMObjectsAreStopped())
return;
m_resolver->reject();
}
} // namespace blink
| Workday/OpenFrame | third_party/WebKit/Source/modules/permissions/PermissionsCallback.cpp | C++ | bsd-3-clause | 1,871 |
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\DI;
use Nette;
/**
* Definition used by ContainerBuilder.
*/
class ServiceDefinition extends Nette\Object
{
/** @var string|NULL class or interface name */
private $class;
/** @var Statement|NULL */
private $factory;
/** @var Statement[] */
private $setup = array();
/** @var array */
public $parameters = array();
/** @var array */
private $tags = array();
/** @var bool */
private $autowired = TRUE;
/** @var bool */
private $dynamic = FALSE;
/** @var string|NULL interface name */
private $implement;
/** @var string|NULL create | get */
private $implementType;
/**
* @return self
*/
public function setClass($class, array $args = array())
{
$this->class = ltrim($class, '\\');
if ($args) {
$this->setFactory($class, $args);
}
return $this;
}
/**
* @return string|NULL
*/
public function getClass()
{
return $this->class;
}
/**
* @return self
*/
public function setFactory($factory, array $args = array())
{
$this->factory = $factory instanceof Statement ? $factory : new Statement($factory, $args);
return $this;
}
/**
* @return Statement|NULL
*/
public function getFactory()
{
return $this->factory;
}
/**
* @return string|array|ServiceDefinition|NULL
*/
public function getEntity()
{
return $this->factory ? $this->factory->getEntity() : NULL;
}
/**
* @return self
*/
public function setArguments(array $args = array())
{
if (!$this->factory) {
$this->factory = new Statement($this->class);
}
$this->factory->arguments = $args;
return $this;
}
/**
* @param Statement[]
* @return self
*/
public function setSetup(array $setup)
{
foreach ($setup as $v) {
if (!$v instanceof Statement) {
throw new Nette\InvalidArgumentException('Argument must be Nette\DI\Statement[].');
}
}
$this->setup = $setup;
return $this;
}
/**
* @return Statement[]
*/
public function getSetup()
{
return $this->setup;
}
/**
* @return self
*/
public function addSetup($entity, array $args = array())
{
$this->setup[] = $entity instanceof Statement ? $entity : new Statement($entity, $args);
return $this;
}
/**
* @return self
*/
public function setParameters(array $params)
{
$this->parameters = $params;
return $this;
}
/**
* @return array
*/
public function getParameters()
{
return $this->parameters;
}
/**
* @return self
*/
public function setTags(array $tags)
{
$this->tags = $tags;
return $this;
}
/**
* @return array
*/
public function getTags()
{
return $this->tags;
}
/**
* @return self
*/
public function addTag($tag, $attr = TRUE)
{
$this->tags[$tag] = $attr;
return $this;
}
/**
* @return mixed
*/
public function getTag($tag)
{
return isset($this->tags[$tag]) ? $this->tags[$tag] : NULL;
}
/**
* @param bool
* @return self
*/
public function setAutowired($state = TRUE)
{
$this->autowired = (bool) $state;
return $this;
}
/**
* @return bool
*/
public function isAutowired()
{
return $this->autowired;
}
/**
* @param bool
* @return self
*/
public function setDynamic($state = TRUE)
{
$this->dynamic = (bool) $state;
return $this;
}
/**
* @return bool
*/
public function isDynamic()
{
return $this->dynamic;
}
/**
* @param string
* @return self
*/
public function setImplement($interface)
{
$this->implement = ltrim($interface, '\\');
return $this;
}
/**
* @return string|NULL
*/
public function getImplement()
{
return $this->implement;
}
/**
* @param string
* @return self
*/
public function setImplementType($type)
{
if (!in_array($type, array('get', 'create'), TRUE)) {
throw new Nette\InvalidArgumentException('Argument must be get|create.');
}
$this->implementType = $type;
return $this;
}
/**
* @return string|NULL
*/
public function getImplementType()
{
return $this->implementType;
}
/** @deprecated */
public function setShared($on)
{
trigger_error(__METHOD__ . '() is deprecated.', E_USER_DEPRECATED);
$this->autowired = $on ? $this->autowired : FALSE;
return $this;
}
/** @deprecated */
public function isShared()
{
trigger_error(__METHOD__ . '() is deprecated.', E_USER_DEPRECATED);
}
/** @return self */
public function setInject($state = TRUE)
{
//trigger_error(__METHOD__ . '() is deprecated.', E_USER_DEPRECATED);
return $this->addTag(Extensions\InjectExtension::TAG_INJECT, $state);
}
/** @return bool|NULL */
public function getInject()
{
//trigger_error(__METHOD__ . '() is deprecated.', E_USER_DEPRECATED);
return $this->getTag(Extensions\InjectExtension::TAG_INJECT);
}
}
| kivi8/ars-poetica | vendor/nette/di/src/DI/ServiceDefinition.php | PHP | bsd-3-clause | 4,863 |
#!/usr/bin/env python
from setuptools import *
setup(
name='dataflow',
version='0.1.1',
description='a dataflow library for python',
author='Tim Cuthbertson',
author_email='tim3d.junk+dataflow@gmail.com',
url='http://github.com/gfxmonk/py-dataflow/tree',
packages=find_packages(exclude=["test"]),
long_description=open('readme.rst').read(),
classifiers=[
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries :: Python Modules",
],
keywords='dataflow concurrent concurrency',
license='BSD',
install_requires=[
'setuptools',
],
)
| gfxmonk/py-dataflow | setup.py | Python | bsd-3-clause | 694 |
#ifndef NT2_INCLUDE_FUNCTIONS_SCALAR_STORE_HPP_INCLUDED
#define NT2_INCLUDE_FUNCTIONS_SCALAR_STORE_HPP_INCLUDED
#include <nt2/memory/include/functions/scalar/store.hpp>
#endif
| hainm/pythran | third_party/nt2/include/functions/scalar/store.hpp | C++ | bsd-3-clause | 178 |
using System;
using System.Collections;
namespace Platform.Xml.Serialization
{
/// <summary>
/// Maintains state required to perform serialization.
/// </summary>
public sealed class SerializationContext
{
private readonly IList stack = new ArrayList();
public SerializationParameters Parameters { get; }
public SerializerOptions SerializerOptions { get; set; }
public SerializationContext(SerializerOptions options, SerializationParameters parameters)
{
this.Parameters = parameters;
SerializerOptions = options;
}
/// <summary>
/// Checks if see if an object should be serialized.
/// </summary>
/// <remarks>
/// <p>
/// An object shouldn't be serialized if it has already been serialized.
/// This method automatically checks if the object has been serialized
/// by examining the serialization stack. This stack is maintained by
/// the SerializationStart and SerializationEnd methods.
/// </p>
/// <p>
/// You should call SerializationStart and SerializationEnd when you start
/// and finish serializing an object.
/// </p>
/// </remarks>
/// <param name="obj"></param>
/// <returns></returns>
public bool ShouldSerialize(object obj, SerializationMemberInfo memberInfo)
{
IXmlSerializationShouldSerializeProvider shouldSerialize;
if (obj == null && !memberInfo.SerializeIfNull)
{
return false;
}
if ((shouldSerialize = obj as IXmlSerializationShouldSerializeProvider) != null)
{
if (!shouldSerialize.ShouldSerialize(this.SerializerOptions, this.Parameters))
{
return false;
}
}
for (var i = 0; i < stack.Count; i++)
{
if (stack[i] == obj)
{
return false;
}
}
return true;
}
private readonly Stack serializationMemberInfoStack = new Stack();
public void PushCurrentMemberInfo(SerializationMemberInfo memberInfo)
{
serializationMemberInfoStack.Push(memberInfo);
}
public void PopCurrentMemberInfo()
{
serializationMemberInfoStack.Pop();
}
public SerializationMemberInfo GetCurrentMemberInfo()
{
return (SerializationMemberInfo)serializationMemberInfoStack.Peek();
}
public void DeserializationStart(object obj)
{
var listener = obj as IXmlDeserializationStartListener;
listener?.XmlDeserializationStart(this.Parameters);
}
public void DeserializationEnd(object obj)
{
var listener = obj as IXmlDeserializationEndListener;
listener?.XmlDeserializationEnd(this.Parameters);
}
/// <summary>
/// Prepares an object for serialization/
/// </summary>
/// <remarks>
/// The object is pushed onto the serialization stack.
/// This prevents the object from being serialized in cycles.
/// </remarks>
/// <param name="obj"></param>
public void SerializationStart(object obj)
{
stack.Add(obj);
var listener = obj as IXmlSerializationStartListener;
listener?.XmlSerializationStart(this.Parameters);
}
/// <summary>
/// Call when an object has been serialized.
/// </summary>
/// <remarks>
/// The object is popped off the serialization stack.
/// </remarks>
/// <param name="obj"></param>
public void SerializationEnd(object obj)
{
if (stack[stack.Count - 1] != obj)
{
stack.RemoveAt(stack.Count - 1);
throw new InvalidOperationException("Push/Pop misalignment.");
}
stack.RemoveAt(stack.Count - 1);
var listener = obj as IXmlSerializationEndListener;
listener?.XmlSerializationEnd(this.Parameters);
}
}
}
| mwillebrands/Platform | src/Platform.Xml.Serialization/SerializationContext.cs | C# | bsd-3-clause | 3,632 |
using System;
using System.Net;
namespace LumiSoft.Net.Dns.Client
{
/// <summary>
/// A record class.
/// </summary>
[Serializable]
public class DNS_rr_A : DNS_rr_base
{
private IPAddress m_IP = null;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="ip">IP address.</param>
/// <param name="ttl">TTL value.</param>
public DNS_rr_A(IPAddress ip,int ttl) : base(QTYPE.A,ttl)
{
m_IP = ip;
}
#region static method Parse
/// <summary>
/// Parses resource record from reply data.
/// </summary>
/// <param name="reply">DNS server reply data.</param>
/// <param name="offset">Current offset in reply data.</param>
/// <param name="rdLength">Resource record data length.</param>
/// <param name="ttl">Time to live in seconds.</param>
public static DNS_rr_A Parse(byte[] reply,ref int offset,int rdLength,int ttl)
{
// IPv4 = byte byte byte byte
byte[] ip = new byte[rdLength];
Array.Copy(reply,offset,ip,0,rdLength);
offset += rdLength;
return new DNS_rr_A(new IPAddress(ip),ttl);
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets host IP address.
/// </summary>
public IPAddress IP
{
get{ return m_IP; }
}
#endregion
}
}
| Klaudit/inbox2_desktop | ThirdParty/Src/Lumisoft.Net/DNS/Client/DNS_rr_A.cs | C# | bsd-3-clause | 1,419 |
package ch.hevs.aislab.magpie.event;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
import alice.tuprolog.Term;
import ch.hevs.aislab.magpie.environment.Services;
public class LogicTupleEvent extends MagpieEvent {
private String logicRepresentation;
public LogicTupleEvent(Term term) {
this.type = Services.LOGIC_TUPLE;
this.logicRepresentation = term.toString();
}
public LogicTupleEvent(long timestamp, String logicEvent) {
this(logicEvent);
this.setTimestamp(timestamp);
}
public LogicTupleEvent(String logicEvent) {
this.type = Services.LOGIC_TUPLE;
// This checks if the Term is correct
Term term = Term.createTerm(logicEvent);
this.logicRepresentation = term.toString();
}
/**
* Creates a logic tuple with format: name(arg1,arg2,...,argN), and assigns the timestamp to the
* event
* @param timestamp
* @param name
* @param args
*/
public LogicTupleEvent(long timestamp, String name, String ... args) {
this(name, args);
this.setTimestamp(timestamp);
}
/**
* Creates a logic tuple with format: name(arg1,arg2,...,argN), and assigns the current timestamp
* to the event
* @param name
* @param args
*/
public LogicTupleEvent(String name, String ... args) {
this.type = Services.LOGIC_TUPLE;
String tuple = name + "(";
for (String arg : args) {
tuple = tuple + arg + ",";
}
// Remove the last comma and close the parenthesis
tuple = tuple.substring(0, tuple.length() - 1);
tuple = tuple + ")";
this.logicRepresentation = tuple;
}
/**
* It returns the tuple representation of the event
*
* @return
*/
public String toTuple(){
return logicRepresentation;
}
public String getName() {
int end = logicRepresentation.indexOf("(");
return logicRepresentation.substring(0,end);
}
public List<String> getArguments() {
List<String> arguments = new ArrayList<>();
int elements = StringUtils.countMatches(logicRepresentation, ",");
if (elements == 0) {
arguments.add(getSubstring("(", ")"));
} else if (elements == 1) {
arguments.add(getSubstring("(", ","));
arguments.add(getSubstring(",", ")"));
} else if (elements > 1) {
arguments.add(getSubstring("(", ","));
String restString = getSubstring(",", ")");
String[] restArray = StringUtils.split(restString, ",");
for (String aRestArray : restArray) {
arguments.add(aRestArray);
}
}
return arguments;
}
private String getSubstring(String start, String end) {
int first = StringUtils.indexOf(logicRepresentation, start);
int second = StringUtils.indexOf(logicRepresentation, end);
return StringUtils.substring(logicRepresentation, first + 1, second);
}
}
| aislab-hevs/magpie | MAGPIE/library/src/main/java/ch/hevs/aislab/magpie/event/LogicTupleEvent.java | Java | bsd-3-clause | 3,019 |
/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** 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 ETH Zurich 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.
**
***********************************************************************************************************************/
#include "test_nodes/PositionExtension.h"
namespace TestNodes {
DEFINE_EXTENSION(PositionExtension)
REGISTER_EXTENSION_ATTRIBUTE(PositionExtension, x, Integer, false, false, true)
REGISTER_EXTENSION_ATTRIBUTE(PositionExtension, y, Integer, false, false, true)
}
| patrick-luethi/Envision | ModelBase/src/test_nodes/PositionExtension.cpp | C++ | bsd-3-clause | 2,073 |
/*
* Copyright (c) 2009-2015, United States Government, as represented by the Secretary of Health and Human Services.
* 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 United States Government 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 UNITED STATES GOVERNMENT 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.
*/
/*
Copyright (c) 2010, NHIN Direct Project
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 The NHIN Direct Project (nhindirect.org) 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.
*/
package gov.hhs.fha.nhinc.directconfig.service.jaxws;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name = "disassociatePolicyGroupFromDomains", namespace = "http://nhind.org/config")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "disassociatePolicyGroupFromDomains", namespace = "http://nhind.org/config")
public class DisassociatePolicyGroupFromDomains {
@XmlElement(name = "policyGroupId", namespace = "")
private long policyGroupId;
/**
*
* @return
* returns long
*/
public long getPolicyGroupId() {
return this.policyGroupId;
}
/**
*
* @param policyGroupId
* the value for the policyGroupId property
*/
public void setPolicyGroupId(long policyGroupId) {
this.policyGroupId = policyGroupId;
}
}
| beiyuxinke/CONNECT | Product/Production/Adapters/General/CONNECTDirectConfig/src/main/java/gov/hhs/fha/nhinc/directconfig/service/jaxws/DisassociatePolicyGroupFromDomains.java | Java | bsd-3-clause | 4,210 |
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// Stroke generator
//
//----------------------------------------------------------------------------
#include <math.h>
#include "agg_vcgen_stroke.h"
#include "agg_shorten_path.h"
namespace agg24
{
//------------------------------------------------------------------------
vcgen_stroke::vcgen_stroke() :
m_stroker(),
m_src_vertices(),
m_out_vertices(),
m_shorten(0.0),
m_closed(0),
m_status(initial),
m_src_vertex(0),
m_out_vertex(0)
{
}
//------------------------------------------------------------------------
void vcgen_stroke::remove_all()
{
m_src_vertices.remove_all();
m_closed = 0;
m_status = initial;
}
//------------------------------------------------------------------------
void vcgen_stroke::add_vertex(double x, double y, unsigned cmd)
{
m_status = initial;
if(is_move_to(cmd))
{
m_src_vertices.modify_last(vertex_dist(x, y));
}
else
{
if(is_vertex(cmd))
{
m_src_vertices.add(vertex_dist(x, y));
}
else
{
m_closed = get_close_flag(cmd);
}
}
}
//------------------------------------------------------------------------
void vcgen_stroke::rewind(unsigned)
{
if(m_status == initial)
{
m_src_vertices.close(m_closed != 0);
shorten_path(m_src_vertices, m_shorten, m_closed);
if(m_src_vertices.size() < 3) m_closed = 0;
}
m_status = ready;
m_src_vertex = 0;
m_out_vertex = 0;
}
//------------------------------------------------------------------------
unsigned vcgen_stroke::vertex(double* x, double* y)
{
unsigned cmd = path_cmd_line_to;
while(!is_stop(cmd))
{
switch(m_status)
{
case initial:
rewind(0);
case ready:
if(m_src_vertices.size() < 2 + unsigned(m_closed != 0))
{
cmd = path_cmd_stop;
break;
}
m_status = m_closed ? outline1 : cap1;
cmd = path_cmd_move_to;
m_src_vertex = 0;
m_out_vertex = 0;
break;
case cap1:
m_stroker.calc_cap(m_out_vertices,
m_src_vertices[0],
m_src_vertices[1],
m_src_vertices[0].dist);
m_src_vertex = 1;
m_prev_status = outline1;
m_status = out_vertices;
m_out_vertex = 0;
break;
case cap2:
m_stroker.calc_cap(m_out_vertices,
m_src_vertices[m_src_vertices.size() - 1],
m_src_vertices[m_src_vertices.size() - 2],
m_src_vertices[m_src_vertices.size() - 2].dist);
m_prev_status = outline2;
m_status = out_vertices;
m_out_vertex = 0;
break;
case outline1:
if(m_closed)
{
if(m_src_vertex >= m_src_vertices.size())
{
m_prev_status = close_first;
m_status = end_poly1;
break;
}
}
else
{
if(m_src_vertex >= m_src_vertices.size() - 1)
{
m_status = cap2;
break;
}
}
m_stroker.calc_join(m_out_vertices,
m_src_vertices.prev(m_src_vertex),
m_src_vertices.curr(m_src_vertex),
m_src_vertices.next(m_src_vertex),
m_src_vertices.prev(m_src_vertex).dist,
m_src_vertices.curr(m_src_vertex).dist);
++m_src_vertex;
m_prev_status = m_status;
m_status = out_vertices;
m_out_vertex = 0;
break;
case close_first:
m_status = outline2;
cmd = path_cmd_move_to;
case outline2:
if(m_src_vertex <= unsigned(m_closed == 0))
{
m_status = end_poly2;
m_prev_status = stop;
break;
}
--m_src_vertex;
m_stroker.calc_join(m_out_vertices,
m_src_vertices.next(m_src_vertex),
m_src_vertices.curr(m_src_vertex),
m_src_vertices.prev(m_src_vertex),
m_src_vertices.curr(m_src_vertex).dist,
m_src_vertices.prev(m_src_vertex).dist);
m_prev_status = m_status;
m_status = out_vertices;
m_out_vertex = 0;
break;
case out_vertices:
if(m_out_vertex >= m_out_vertices.size())
{
m_status = m_prev_status;
}
else
{
const point_d& c = m_out_vertices[m_out_vertex++];
*x = c.x;
*y = c.y;
return cmd;
}
break;
case end_poly1:
m_status = m_prev_status;
return path_cmd_end_poly | path_flags_close | path_flags_ccw;
case end_poly2:
m_status = m_prev_status;
return path_cmd_end_poly | path_flags_close | path_flags_cw;
case stop:
cmd = path_cmd_stop;
break;
}
}
return cmd;
}
}
| tommy-u/enable | kiva/agg/agg-24/src/agg_vcgen_stroke.cpp | C++ | bsd-3-clause | 7,176 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Orchard.Themes;
using Orchard.UI.Admin;
using Orchard.Data;
using ESchool.Models;
using Orchard.ContentManagement;
using Orchard;
using Orchard.Localization;
using Orchard.DisplayManagement;
using Orchard.UI.Notify;
using Orchard.Core.Feeds;
namespace ESchool.Controllers
{
[Themed]
public class CourseController : Controller
{
private readonly IContentManager contentManager;
dynamic Shape { get; set; }
public CourseController(IContentManager contentManager, IShapeFactory shapeFactory)
{
this.contentManager = contentManager;
Shape = shapeFactory;
}
public ActionResult List(int idYear)
{
var list = Shape.List();
list.AddRange(contentManager.Query<CoursePart, CourseRecord>(VersionOptions.Published).Where(x => x.Year.Id == idYear).OrderBy(x => x.Name).List().Select(b =>
{
var courseDisplay = contentManager.BuildDisplay(b);
return courseDisplay;
}));
var year = contentManager.Get<YearPart>(idYear);
dynamic viewModel = Shape.ViewModel().ContentItems(list).Year(year);
return View((object)viewModel);
}
}
} | prakasha/Orchard1.4 | Modules/ESchool/Controllers/Frontend/CourseController.cs | C# | bsd-3-clause | 1,352 |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
using Mosa.Compiler.Framework;
namespace Mosa.Platform.x86.Instructions
{
/// <summary>
/// Intermediate representation of the arithmetic shift right instruction.
/// </summary>
public sealed class Sar : X86Instruction
{
#region Data Members
private static readonly OpCode C = new OpCode(new byte[] { 0xC1 }, 7);
private static readonly OpCode C1 = new OpCode(new byte[] { 0xD1 }, 7);
private static readonly OpCode RM = new OpCode(new byte[] { 0xD3 }, 7);
#endregion Data Members
#region Construction
/// <summary>
/// Initializes a new instance of <see cref="Shr"/>.
/// </summary>
public Sar() :
base(1, 2)
{
}
#endregion Construction
#region Methods
/// <summary>
/// Emits the specified platform instruction.
/// </summary>
/// <param name="node">The node.</param>
/// <param name="emitter">The emitter.</param>
protected override void Emit(InstructionNode node, MachineCodeEmitter emitter)
{
if (node.Operand2.IsConstant)
{
if (node.Operand2.IsConstantOne)
{
emitter.Emit(C1, node.Result, null);
}
else
{
emitter.Emit(C, node.Result, node.Operand2);
}
}
else
{
emitter.Emit(RM, node.Operand1, null);
}
}
/// <summary>
/// Allows visitor based dispatch for this instruction object.
/// </summary>
/// <param name="visitor">The visitor object.</param>
/// <param name="context">The context.</param>
public override void Visit(IX86Visitor visitor, Context context)
{
visitor.Sar(context);
}
#endregion Methods
}
}
| modulexcite/MOSA-Project | Source/Mosa.Platform.x86/Instructions/Sar.cs | C# | bsd-3-clause | 1,628 |
<?php
namespace test\g;
class e { } | theosyspe/levent_01 | vendor/ZF2/bin/test/g/e.php | PHP | bsd-3-clause | 35 |
/*
* Copyright (c) 2016, The OpenThread Authors.
* 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 copyright holder 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.
*/
/**
* @file
* This file implements IPv6 networking.
*/
#include "ip6.hpp"
#include "backbone_router/bbr_leader.hpp"
#include "backbone_router/bbr_local.hpp"
#include "backbone_router/ndproxy_table.hpp"
#include "common/code_utils.hpp"
#include "common/debug.hpp"
#include "common/instance.hpp"
#include "common/locator_getters.hpp"
#include "common/log.hpp"
#include "common/message.hpp"
#include "common/random.hpp"
#include "net/checksum.hpp"
#include "net/icmp6.hpp"
#include "net/ip6_address.hpp"
#include "net/ip6_filter.hpp"
#include "net/netif.hpp"
#include "net/udp6.hpp"
#include "openthread/ip6.h"
#include "thread/mle.hpp"
using IcmpType = ot::Ip6::Icmp::Header::Type;
static const IcmpType sForwardICMPTypes[] = {
IcmpType::kTypeDstUnreach, IcmpType::kTypePacketToBig, IcmpType::kTypeTimeExceeded,
IcmpType::kTypeParameterProblem, IcmpType::kTypeEchoRequest, IcmpType::kTypeEchoReply,
};
namespace ot {
namespace Ip6 {
RegisterLogModule("Ip6");
Ip6::Ip6(Instance &aInstance)
: InstanceLocator(aInstance)
, mForwardingEnabled(false)
, mIsReceiveIp6FilterEnabled(false)
, mReceiveIp6DatagramCallback(nullptr)
, mReceiveIp6DatagramCallbackContext(nullptr)
, mSendQueueTask(aInstance, Ip6::HandleSendQueue)
, mIcmp(aInstance)
, mUdp(aInstance)
, mMpl(aInstance)
#if OPENTHREAD_CONFIG_TCP_ENABLE
, mTcp(aInstance)
#endif
{
}
Message *Ip6::NewMessage(uint16_t aReserved, const Message::Settings &aSettings)
{
return Get<MessagePool>().Allocate(
Message::kTypeIp6, sizeof(Header) + sizeof(HopByHopHeader) + sizeof(OptionMpl) + aReserved, aSettings);
}
Message *Ip6::NewMessage(const uint8_t *aData, uint16_t aDataLength, const Message::Settings &aSettings)
{
Message *message = Get<MessagePool>().Allocate(Message::kTypeIp6, /* aReserveHeader */ 0, aSettings);
VerifyOrExit(message != nullptr);
if (message->AppendBytes(aData, aDataLength) != kErrorNone)
{
message->Free();
message = nullptr;
}
exit:
return message;
}
Message *Ip6::NewMessage(const uint8_t *aData, uint16_t aDataLength)
{
Message * message = nullptr;
Message::Priority priority;
SuccessOrExit(GetDatagramPriority(aData, aDataLength, priority));
message = NewMessage(aData, aDataLength, Message::Settings(Message::kWithLinkSecurity, priority));
exit:
return message;
}
Message::Priority Ip6::DscpToPriority(uint8_t aDscp)
{
Message::Priority priority;
uint8_t cs = aDscp & kDscpCsMask;
switch (cs)
{
case kDscpCs1:
case kDscpCs2:
priority = Message::kPriorityLow;
break;
case kDscpCs0:
case kDscpCs3:
priority = Message::kPriorityNormal;
break;
case kDscpCs4:
case kDscpCs5:
case kDscpCs6:
case kDscpCs7:
priority = Message::kPriorityHigh;
break;
default:
priority = Message::kPriorityNormal;
break;
}
return priority;
}
uint8_t Ip6::PriorityToDscp(Message::Priority aPriority)
{
uint8_t dscp = kDscpCs0;
switch (aPriority)
{
case Message::kPriorityLow:
dscp = kDscpCs1;
break;
case Message::kPriorityNormal:
case Message::kPriorityNet:
dscp = kDscpCs0;
break;
case Message::kPriorityHigh:
dscp = kDscpCs4;
break;
}
return dscp;
}
Error Ip6::GetDatagramPriority(const uint8_t *aData, uint16_t aDataLen, Message::Priority &aPriority)
{
Error error = kErrorNone;
const Header *header;
VerifyOrExit((aData != nullptr) && (aDataLen >= sizeof(Header)), error = kErrorInvalidArgs);
header = reinterpret_cast<const Header *>(aData);
VerifyOrExit(header->IsValid(), error = kErrorParse);
VerifyOrExit(sizeof(Header) + header->GetPayloadLength() == aDataLen, error = kErrorParse);
aPriority = DscpToPriority(header->GetDscp());
exit:
return error;
}
void Ip6::SetReceiveDatagramCallback(otIp6ReceiveCallback aCallback, void *aCallbackContext)
{
mReceiveIp6DatagramCallback = aCallback;
mReceiveIp6DatagramCallbackContext = aCallbackContext;
}
Error Ip6::AddMplOption(Message &aMessage, Header &aHeader)
{
Error error = kErrorNone;
HopByHopHeader hbhHeader;
OptionMpl mplOption;
OptionPadN padOption;
hbhHeader.SetNextHeader(aHeader.GetNextHeader());
hbhHeader.SetLength(0);
mMpl.InitOption(mplOption, aHeader.GetSource());
// Mpl option may require two bytes padding.
if ((mplOption.GetTotalLength() + sizeof(hbhHeader)) % 8)
{
padOption.Init(2);
SuccessOrExit(error = aMessage.PrependBytes(&padOption, padOption.GetTotalLength()));
}
SuccessOrExit(error = aMessage.PrependBytes(&mplOption, mplOption.GetTotalLength()));
SuccessOrExit(error = aMessage.Prepend(hbhHeader));
aHeader.SetPayloadLength(aHeader.GetPayloadLength() + sizeof(hbhHeader) + sizeof(mplOption));
aHeader.SetNextHeader(kProtoHopOpts);
exit:
return error;
}
Error Ip6::AddTunneledMplOption(Message &aMessage, Header &aHeader, MessageInfo &aMessageInfo)
{
Error error = kErrorNone;
Header tunnelHeader;
const Netif::UnicastAddress *source;
MessageInfo messageInfo(aMessageInfo);
// Use IP-in-IP encapsulation (RFC2473) and ALL_MPL_FORWARDERS address.
messageInfo.GetPeerAddr().SetToRealmLocalAllMplForwarders();
tunnelHeader.Init();
tunnelHeader.SetHopLimit(static_cast<uint8_t>(kDefaultHopLimit));
tunnelHeader.SetPayloadLength(aHeader.GetPayloadLength() + sizeof(tunnelHeader));
tunnelHeader.SetDestination(messageInfo.GetPeerAddr());
tunnelHeader.SetNextHeader(kProtoIp6);
VerifyOrExit((source = SelectSourceAddress(messageInfo)) != nullptr, error = kErrorInvalidSourceAddress);
tunnelHeader.SetSource(source->GetAddress());
SuccessOrExit(error = AddMplOption(aMessage, tunnelHeader));
SuccessOrExit(error = aMessage.Prepend(tunnelHeader));
exit:
return error;
}
Error Ip6::InsertMplOption(Message &aMessage, Header &aHeader, MessageInfo &aMessageInfo)
{
Error error = kErrorNone;
VerifyOrExit(aHeader.GetDestination().IsMulticast() &&
aHeader.GetDestination().GetScope() >= Address::kRealmLocalScope);
if (aHeader.GetDestination().IsRealmLocalMulticast())
{
aMessage.RemoveHeader(sizeof(aHeader));
if (aHeader.GetNextHeader() == kProtoHopOpts)
{
HopByHopHeader hbh;
uint16_t hbhLength = 0;
OptionMpl mplOption;
// read existing hop-by-hop option header
SuccessOrExit(error = aMessage.Read(0, hbh));
hbhLength = (hbh.GetLength() + 1) * 8;
VerifyOrExit(hbhLength <= aHeader.GetPayloadLength(), error = kErrorParse);
// increase existing hop-by-hop option header length by 8 bytes
hbh.SetLength(hbh.GetLength() + 1);
aMessage.Write(0, hbh);
// make space for MPL Option + padding by shifting hop-by-hop option header
SuccessOrExit(error = aMessage.PrependBytes(nullptr, 8));
aMessage.CopyTo(8, 0, hbhLength, aMessage);
// insert MPL Option
mMpl.InitOption(mplOption, aHeader.GetSource());
aMessage.WriteBytes(hbhLength, &mplOption, mplOption.GetTotalLength());
// insert Pad Option (if needed)
if (mplOption.GetTotalLength() % 8)
{
OptionPadN padOption;
padOption.Init(8 - (mplOption.GetTotalLength() % 8));
aMessage.WriteBytes(hbhLength + mplOption.GetTotalLength(), &padOption, padOption.GetTotalLength());
}
// increase IPv6 Payload Length
aHeader.SetPayloadLength(aHeader.GetPayloadLength() + 8);
}
else
{
SuccessOrExit(error = AddMplOption(aMessage, aHeader));
}
SuccessOrExit(error = aMessage.Prepend(aHeader));
}
else
{
#if OPENTHREAD_FTD
if (aHeader.GetDestination().IsMulticastLargerThanRealmLocal() &&
Get<ChildTable>().HasSleepyChildWithAddress(aHeader.GetDestination()))
{
Message *messageCopy = nullptr;
if ((messageCopy = aMessage.Clone()) != nullptr)
{
IgnoreError(HandleDatagram(*messageCopy, nullptr, nullptr, /* aFromHost */ true));
LogInfo("Message copy for indirect transmission to sleepy children");
}
else
{
LogWarn("No enough buffer for message copy for indirect transmission to sleepy children");
}
}
#endif
SuccessOrExit(error = AddTunneledMplOption(aMessage, aHeader, aMessageInfo));
}
exit:
return error;
}
Error Ip6::RemoveMplOption(Message &aMessage)
{
Error error = kErrorNone;
Header ip6Header;
HopByHopHeader hbh;
uint16_t offset;
uint16_t endOffset;
uint16_t mplOffset = 0;
uint8_t mplLength = 0;
bool remove = false;
offset = 0;
IgnoreError(aMessage.Read(offset, ip6Header));
offset += sizeof(ip6Header);
VerifyOrExit(ip6Header.GetNextHeader() == kProtoHopOpts);
IgnoreError(aMessage.Read(offset, hbh));
endOffset = offset + (hbh.GetLength() + 1) * 8;
VerifyOrExit(aMessage.GetLength() >= endOffset, error = kErrorParse);
offset += sizeof(hbh);
while (offset < endOffset)
{
OptionHeader option;
IgnoreError(aMessage.Read(offset, option));
switch (option.GetType())
{
case OptionMpl::kType:
// if multiple MPL options exist, discard packet
VerifyOrExit(mplOffset == 0, error = kErrorParse);
mplOffset = offset;
mplLength = option.GetLength();
VerifyOrExit(mplLength <= sizeof(OptionMpl) - sizeof(OptionHeader), error = kErrorParse);
if (mplOffset == sizeof(ip6Header) + sizeof(hbh) && hbh.GetLength() == 0)
{
// first and only IPv6 Option, remove IPv6 HBH Option header
remove = true;
}
else if (mplOffset + 8 == endOffset)
{
// last IPv6 Option, remove last 8 bytes
remove = true;
}
offset += sizeof(option) + option.GetLength();
break;
case OptionPad1::kType:
offset += sizeof(OptionPad1);
break;
case OptionPadN::kType:
offset += sizeof(option) + option.GetLength();
break;
default:
// encountered another option, now just replace MPL Option with PadN
remove = false;
offset += sizeof(option) + option.GetLength();
break;
}
}
// verify that IPv6 Options header is properly formed
VerifyOrExit(offset == endOffset, error = kErrorParse);
if (remove)
{
// last IPv6 Option, shrink HBH Option header
uint8_t buf[8];
offset = endOffset - sizeof(buf);
while (offset >= sizeof(buf))
{
IgnoreError(aMessage.Read(offset - sizeof(buf), buf));
aMessage.Write(offset, buf);
offset -= sizeof(buf);
}
aMessage.RemoveHeader(sizeof(buf));
if (mplOffset == sizeof(ip6Header) + sizeof(hbh))
{
// remove entire HBH header
ip6Header.SetNextHeader(hbh.GetNextHeader());
}
else
{
// update HBH header length
hbh.SetLength(hbh.GetLength() - 1);
aMessage.Write(sizeof(ip6Header), hbh);
}
ip6Header.SetPayloadLength(ip6Header.GetPayloadLength() - sizeof(buf));
aMessage.Write(0, ip6Header);
}
else if (mplOffset != 0)
{
// replace MPL Option with PadN Option
OptionPadN padOption;
padOption.Init(sizeof(OptionHeader) + mplLength);
aMessage.WriteBytes(mplOffset, &padOption, padOption.GetTotalLength());
}
exit:
return error;
}
void Ip6::EnqueueDatagram(Message &aMessage)
{
mSendQueue.Enqueue(aMessage);
mSendQueueTask.Post();
}
Error Ip6::SendDatagram(Message &aMessage, MessageInfo &aMessageInfo, uint8_t aIpProto)
{
Error error = kErrorNone;
Header header;
uint16_t payloadLength = aMessage.GetLength();
header.Init();
header.SetDscp(PriorityToDscp(aMessage.GetPriority()));
header.SetEcn(aMessageInfo.mEcn);
header.SetPayloadLength(payloadLength);
header.SetNextHeader(aIpProto);
if (aMessageInfo.GetHopLimit() != 0 || aMessageInfo.ShouldAllowZeroHopLimit())
{
header.SetHopLimit(aMessageInfo.GetHopLimit());
}
else
{
header.SetHopLimit(static_cast<uint8_t>(kDefaultHopLimit));
}
if (aMessageInfo.GetSockAddr().IsUnspecified() || aMessageInfo.GetSockAddr().IsMulticast())
{
const Netif::UnicastAddress *source = SelectSourceAddress(aMessageInfo);
VerifyOrExit(source != nullptr, error = kErrorInvalidSourceAddress);
header.SetSource(source->GetAddress());
}
else
{
header.SetSource(aMessageInfo.GetSockAddr());
}
header.SetDestination(aMessageInfo.GetPeerAddr());
if (aMessageInfo.GetPeerAddr().IsRealmLocalMulticast())
{
SuccessOrExit(error = AddMplOption(aMessage, header));
}
SuccessOrExit(error = aMessage.Prepend(header));
Checksum::UpdateMessageChecksum(aMessage, header.GetSource(), header.GetDestination(), aIpProto);
if (aMessageInfo.GetPeerAddr().IsMulticastLargerThanRealmLocal())
{
#if OPENTHREAD_FTD
if (Get<ChildTable>().HasSleepyChildWithAddress(header.GetDestination()))
{
Message *messageCopy = aMessage.Clone();
if (messageCopy != nullptr)
{
LogInfo("Message copy for indirect transmission to sleepy children");
EnqueueDatagram(*messageCopy);
}
else
{
LogWarn("No enough buffer for message copy for indirect transmission to sleepy children");
}
}
#endif
SuccessOrExit(error = AddTunneledMplOption(aMessage, header, aMessageInfo));
}
aMessage.SetMulticastLoop(aMessageInfo.GetMulticastLoop());
if (aMessage.GetLength() > kMaxDatagramLength)
{
error = FragmentDatagram(aMessage, aIpProto);
}
else
{
EnqueueDatagram(aMessage);
}
exit:
return error;
}
void Ip6::HandleSendQueue(Tasklet &aTasklet)
{
aTasklet.Get<Ip6>().HandleSendQueue();
}
void Ip6::HandleSendQueue(void)
{
Message *message;
while ((message = mSendQueue.GetHead()) != nullptr)
{
mSendQueue.Dequeue(*message);
IgnoreError(HandleDatagram(*message, nullptr, nullptr, /* aFromHost */ false));
}
}
Error Ip6::HandleOptions(Message &aMessage, Header &aHeader, bool aIsOutbound, bool &aReceive)
{
Error error = kErrorNone;
HopByHopHeader hbhHeader;
OptionHeader optionHeader;
uint16_t endOffset;
SuccessOrExit(error = aMessage.Read(aMessage.GetOffset(), hbhHeader));
endOffset = aMessage.GetOffset() + (hbhHeader.GetLength() + 1) * 8;
VerifyOrExit(endOffset <= aMessage.GetLength(), error = kErrorParse);
aMessage.MoveOffset(sizeof(optionHeader));
while (aMessage.GetOffset() < endOffset)
{
SuccessOrExit(error = aMessage.Read(aMessage.GetOffset(), optionHeader));
if (optionHeader.GetType() == OptionPad1::kType)
{
aMessage.MoveOffset(sizeof(OptionPad1));
continue;
}
VerifyOrExit(aMessage.GetOffset() + sizeof(optionHeader) + optionHeader.GetLength() <= endOffset,
error = kErrorParse);
switch (optionHeader.GetType())
{
case OptionMpl::kType:
SuccessOrExit(error = mMpl.ProcessOption(aMessage, aHeader.GetSource(), aIsOutbound, aReceive));
break;
default:
switch (optionHeader.GetAction())
{
case OptionHeader::kActionSkip:
break;
case OptionHeader::kActionDiscard:
ExitNow(error = kErrorDrop);
case OptionHeader::kActionForceIcmp:
// TODO: send icmp error
ExitNow(error = kErrorDrop);
case OptionHeader::kActionIcmp:
// TODO: send icmp error
ExitNow(error = kErrorDrop);
}
break;
}
aMessage.MoveOffset(sizeof(optionHeader) + optionHeader.GetLength());
}
exit:
return error;
}
#if OPENTHREAD_CONFIG_IP6_FRAGMENTATION_ENABLE
Error Ip6::FragmentDatagram(Message &aMessage, uint8_t aIpProto)
{
Error error = kErrorNone;
Header header;
FragmentHeader fragmentHeader;
Message * fragment = nullptr;
uint16_t fragmentCnt = 0;
uint16_t payloadFragment = 0;
uint16_t offset = 0;
uint16_t maxPayloadFragment =
FragmentHeader::MakeDivisibleByEight(kMinimalMtu - aMessage.GetOffset() - sizeof(fragmentHeader));
uint16_t payloadLeft = aMessage.GetLength() - aMessage.GetOffset();
SuccessOrExit(error = aMessage.Read(0, header));
header.SetNextHeader(kProtoFragment);
fragmentHeader.Init();
fragmentHeader.SetIdentification(Random::NonCrypto::GetUint32());
fragmentHeader.SetNextHeader(aIpProto);
fragmentHeader.SetMoreFlag();
while (payloadLeft != 0)
{
if (payloadLeft < maxPayloadFragment)
{
fragmentHeader.ClearMoreFlag();
payloadFragment = payloadLeft;
payloadLeft = 0;
LogDebg("Last Fragment");
}
else
{
payloadLeft -= maxPayloadFragment;
payloadFragment = maxPayloadFragment;
}
offset = fragmentCnt * FragmentHeader::BytesToFragmentOffset(maxPayloadFragment);
fragmentHeader.SetOffset(offset);
VerifyOrExit((fragment = NewMessage(0)) != nullptr, error = kErrorNoBufs);
SuccessOrExit(error = fragment->SetLength(aMessage.GetOffset() + sizeof(fragmentHeader) + payloadFragment));
header.SetPayloadLength(payloadFragment + sizeof(fragmentHeader));
fragment->Write(0, header);
fragment->SetOffset(aMessage.GetOffset());
fragment->Write(aMessage.GetOffset(), fragmentHeader);
VerifyOrExit(aMessage.CopyTo(aMessage.GetOffset() + FragmentHeader::FragmentOffsetToBytes(offset),
aMessage.GetOffset() + sizeof(fragmentHeader), payloadFragment,
*fragment) == static_cast<int>(payloadFragment),
error = kErrorNoBufs);
EnqueueDatagram(*fragment);
fragmentCnt++;
fragment = nullptr;
LogInfo("Fragment %d with %d bytes sent", fragmentCnt, payloadFragment);
}
aMessage.Free();
exit:
if (error == kErrorNoBufs)
{
LogWarn("No buffer for Ip6 fragmentation");
}
FreeMessageOnError(fragment, error);
return error;
}
Error Ip6::HandleFragment(Message &aMessage, Netif *aNetif, MessageInfo &aMessageInfo, bool aFromHost)
{
Error error = kErrorNone;
Header header, headerBuffer;
FragmentHeader fragmentHeader;
Message * message = nullptr;
uint16_t offset = 0;
uint16_t payloadFragment = 0;
int assertValue = 0;
bool isFragmented = true;
OT_UNUSED_VARIABLE(assertValue);
SuccessOrExit(error = aMessage.Read(0, header));
SuccessOrExit(error = aMessage.Read(aMessage.GetOffset(), fragmentHeader));
if (fragmentHeader.GetOffset() == 0 && !fragmentHeader.IsMoreFlagSet())
{
isFragmented = false;
aMessage.MoveOffset(sizeof(fragmentHeader));
ExitNow();
}
for (message = mReassemblyList.GetHead(); message; message = message->GetNext())
{
SuccessOrExit(error = message->Read(0, headerBuffer));
if (message->GetDatagramTag() == fragmentHeader.GetIdentification() &&
headerBuffer.GetSource() == header.GetSource() && headerBuffer.GetDestination() == header.GetDestination())
{
break;
}
}
offset = FragmentHeader::FragmentOffsetToBytes(fragmentHeader.GetOffset());
payloadFragment = aMessage.GetLength() - aMessage.GetOffset() - sizeof(fragmentHeader);
LogInfo("Fragment with id %d received > %d bytes, offset %d", fragmentHeader.GetIdentification(), payloadFragment,
offset);
if (offset + payloadFragment + aMessage.GetOffset() > kMaxAssembledDatagramLength)
{
LogWarn("Packet too large for fragment buffer");
ExitNow(error = kErrorNoBufs);
}
if (message == nullptr)
{
LogDebg("start reassembly");
VerifyOrExit((message = NewMessage(0)) != nullptr, error = kErrorNoBufs);
mReassemblyList.Enqueue(*message);
SuccessOrExit(error = message->SetLength(aMessage.GetOffset()));
message->SetTimeout(kIp6ReassemblyTimeout);
message->SetOffset(0);
message->SetDatagramTag(fragmentHeader.GetIdentification());
// copying the non-fragmentable header to the fragmentation buffer
assertValue = aMessage.CopyTo(0, 0, aMessage.GetOffset(), *message);
OT_ASSERT(assertValue == aMessage.GetOffset());
Get<TimeTicker>().RegisterReceiver(TimeTicker::kIp6FragmentReassembler);
}
// increase message buffer if necessary
if (message->GetLength() < offset + payloadFragment + aMessage.GetOffset())
{
SuccessOrExit(error = message->SetLength(offset + payloadFragment + aMessage.GetOffset()));
}
// copy the fragment payload into the message buffer
assertValue = aMessage.CopyTo(aMessage.GetOffset() + sizeof(fragmentHeader), aMessage.GetOffset() + offset,
payloadFragment, *message);
OT_ASSERT(assertValue == static_cast<int>(payloadFragment));
// check if it is the last frame
if (!fragmentHeader.IsMoreFlagSet())
{
// use the offset value for the whole ip message length
message->SetOffset(aMessage.GetOffset() + offset + payloadFragment);
// creates the header for the reassembled ipv6 package
SuccessOrExit(error = aMessage.Read(0, header));
header.SetPayloadLength(message->GetLength() - sizeof(header));
header.SetNextHeader(fragmentHeader.GetNextHeader());
message->Write(0, header);
LogDebg("Reassembly complete.");
mReassemblyList.Dequeue(*message);
IgnoreError(HandleDatagram(*message, aNetif, aMessageInfo.mLinkInfo, aFromHost));
}
exit:
if (error != kErrorDrop && error != kErrorNone && isFragmented)
{
if (message != nullptr)
{
mReassemblyList.DequeueAndFree(*message);
}
LogWarn("Reassembly failed: %s", ErrorToString(error));
}
if (isFragmented)
{
// drop all fragments, the payload is stored in the fragment buffer
error = kErrorDrop;
}
return error;
}
void Ip6::CleanupFragmentationBuffer(void)
{
mReassemblyList.DequeueAndFreeAll();
}
void Ip6::HandleTimeTick(void)
{
UpdateReassemblyList();
if (mReassemblyList.GetHead() == nullptr)
{
Get<TimeTicker>().UnregisterReceiver(TimeTicker::kIp6FragmentReassembler);
}
}
void Ip6::UpdateReassemblyList(void)
{
Message *next;
for (Message *message = mReassemblyList.GetHead(); message; message = next)
{
next = message->GetNext();
if (message->GetTimeout() > 0)
{
message->DecrementTimeout();
}
else
{
LogNote("Reassembly timeout.");
SendIcmpError(*message, Icmp::Header::kTypeTimeExceeded, Icmp::Header::kCodeFragmReasTimeEx);
mReassemblyList.DequeueAndFree(*message);
}
}
}
void Ip6::SendIcmpError(Message &aMessage, Icmp::Header::Type aIcmpType, Icmp::Header::Code aIcmpCode)
{
Error error = kErrorNone;
Header header;
MessageInfo messageInfo;
SuccessOrExit(error = aMessage.Read(0, header));
messageInfo.SetPeerAddr(header.GetSource());
messageInfo.SetSockAddr(header.GetDestination());
messageInfo.SetHopLimit(header.GetHopLimit());
messageInfo.SetLinkInfo(nullptr);
error = mIcmp.SendError(aIcmpType, aIcmpCode, messageInfo, aMessage);
exit:
if (error != kErrorNone)
{
LogWarn("Failed to send ICMP error: %s", ErrorToString(error));
}
}
#else
Error Ip6::FragmentDatagram(Message &aMessage, uint8_t aIpProto)
{
OT_UNUSED_VARIABLE(aIpProto);
EnqueueDatagram(aMessage);
return kErrorNone;
}
Error Ip6::HandleFragment(Message &aMessage, Netif *aNetif, MessageInfo &aMessageInfo, bool aFromHost)
{
OT_UNUSED_VARIABLE(aNetif);
OT_UNUSED_VARIABLE(aMessageInfo);
OT_UNUSED_VARIABLE(aFromHost);
Error error = kErrorNone;
FragmentHeader fragmentHeader;
SuccessOrExit(error = aMessage.Read(aMessage.GetOffset(), fragmentHeader));
VerifyOrExit(fragmentHeader.GetOffset() == 0 && !fragmentHeader.IsMoreFlagSet(), error = kErrorDrop);
aMessage.MoveOffset(sizeof(fragmentHeader));
exit:
return error;
}
#endif // OPENTHREAD_CONFIG_IP6_FRAGMENTATION_ENABLE
Error Ip6::HandleExtensionHeaders(Message & aMessage,
Netif * aNetif,
MessageInfo &aMessageInfo,
Header & aHeader,
uint8_t & aNextHeader,
bool aIsOutbound,
bool aFromHost,
bool & aReceive)
{
Error error = kErrorNone;
ExtensionHeader extHeader;
while (aReceive || aNextHeader == kProtoHopOpts)
{
SuccessOrExit(error = aMessage.Read(aMessage.GetOffset(), extHeader));
switch (aNextHeader)
{
case kProtoHopOpts:
SuccessOrExit(error = HandleOptions(aMessage, aHeader, aIsOutbound, aReceive));
break;
case kProtoFragment:
#if !OPENTHREAD_CONFIG_IP6_FRAGMENTATION_ENABLE
IgnoreError(ProcessReceiveCallback(aMessage, aMessageInfo, aNextHeader, aFromHost,
/* aAllowReceiveFilter */ false, Message::kCopyToUse));
#endif
SuccessOrExit(error = HandleFragment(aMessage, aNetif, aMessageInfo, aFromHost));
break;
case kProtoDstOpts:
SuccessOrExit(error = HandleOptions(aMessage, aHeader, aIsOutbound, aReceive));
break;
case kProtoIp6:
ExitNow();
case kProtoRouting:
case kProtoNone:
ExitNow(error = kErrorDrop);
default:
ExitNow();
}
aNextHeader = static_cast<uint8_t>(extHeader.GetNextHeader());
}
exit:
return error;
}
Error Ip6::HandlePayload(Header & aIp6Header,
Message & aMessage,
MessageInfo & aMessageInfo,
uint8_t aIpProto,
Message::Ownership aMessageOwnership)
{
#if !OPENTHREAD_CONFIG_TCP_ENABLE
OT_UNUSED_VARIABLE(aIp6Header);
#endif
Error error = kErrorNone;
Message *message = (aMessageOwnership == Message::kTakeCustody) ? &aMessage : nullptr;
VerifyOrExit(aIpProto == kProtoTcp || aIpProto == kProtoUdp || aIpProto == kProtoIcmp6);
if (aMessageOwnership == Message::kCopyToUse)
{
VerifyOrExit((message = aMessage.Clone()) != nullptr, error = kErrorNoBufs);
}
switch (aIpProto)
{
#if OPENTHREAD_CONFIG_TCP_ENABLE
case kProtoTcp:
error = mTcp.HandleMessage(aIp6Header, *message, aMessageInfo);
if (error == kErrorDrop)
{
LogNote("Error TCP Checksum");
}
break;
#endif
case kProtoUdp:
error = mUdp.HandleMessage(*message, aMessageInfo);
if (error == kErrorDrop)
{
LogNote("Error UDP Checksum");
}
break;
case kProtoIcmp6:
error = mIcmp.HandleMessage(*message, aMessageInfo);
break;
default:
break;
}
exit:
if (error != kErrorNone)
{
LogNote("Failed to handle payload: %s", ErrorToString(error));
}
FreeMessage(message);
return error;
}
Error Ip6::ProcessReceiveCallback(Message & aMessage,
const MessageInfo &aMessageInfo,
uint8_t aIpProto,
bool aFromHost,
bool aAllowReceiveFilter,
Message::Ownership aMessageOwnership)
{
Error error = kErrorNone;
Message *message = &aMessage;
VerifyOrExit(!aFromHost, error = kErrorNoRoute);
VerifyOrExit(mReceiveIp6DatagramCallback != nullptr, error = kErrorNoRoute);
// Do not forward reassembled IPv6 packets.
VerifyOrExit(aMessage.GetLength() <= kMinimalMtu, error = kErrorDrop);
if (mIsReceiveIp6FilterEnabled && aAllowReceiveFilter)
{
#if !OPENTHREAD_CONFIG_PLATFORM_NETIF_ENABLE
// do not pass messages sent to an RLOC/ALOC, except Service Locator
bool isLocator = Get<Mle::Mle>().IsMeshLocalAddress(aMessageInfo.GetSockAddr()) &&
aMessageInfo.GetSockAddr().GetIid().IsLocator();
VerifyOrExit(!isLocator || aMessageInfo.GetSockAddr().GetIid().IsAnycastServiceLocator(),
error = kErrorNoRoute);
#endif
switch (aIpProto)
{
case kProtoIcmp6:
if (mIcmp.ShouldHandleEchoRequest(aMessageInfo))
{
Icmp::Header icmp;
IgnoreError(aMessage.Read(aMessage.GetOffset(), icmp));
// do not pass ICMP Echo Request messages
VerifyOrExit(icmp.GetType() != Icmp::Header::kTypeEchoRequest, error = kErrorDrop);
}
break;
case kProtoUdp:
{
Udp::Header udp;
IgnoreError(aMessage.Read(aMessage.GetOffset(), udp));
VerifyOrExit(Get<Udp>().ShouldUsePlatformUdp(udp.GetDestinationPort()) &&
!Get<Udp>().IsPortInUse(udp.GetDestinationPort()),
error = kErrorNoRoute);
break;
}
default:
break;
}
}
switch (aMessageOwnership)
{
case Message::kTakeCustody:
break;
case Message::kCopyToUse:
message = aMessage.Clone();
if (message == nullptr)
{
LogWarn("No buff to clone msg (len: %d) to pass to host", aMessage.GetLength());
ExitNow(error = kErrorNoBufs);
}
break;
}
IgnoreError(RemoveMplOption(*message));
mReceiveIp6DatagramCallback(message, mReceiveIp6DatagramCallbackContext);
exit:
if ((error != kErrorNone) && (aMessageOwnership == Message::kTakeCustody))
{
aMessage.Free();
}
return error;
}
Error Ip6::SendRaw(Message &aMessage, bool aFromHost)
{
Error error = kErrorNone;
Header header;
MessageInfo messageInfo;
bool freed = false;
SuccessOrExit(error = header.Init(aMessage));
VerifyOrExit(!header.GetSource().IsMulticast(), error = kErrorInvalidSourceAddress);
messageInfo.SetPeerAddr(header.GetSource());
messageInfo.SetSockAddr(header.GetDestination());
messageInfo.SetHopLimit(header.GetHopLimit());
if (header.GetDestination().IsMulticast())
{
SuccessOrExit(error = InsertMplOption(aMessage, header, messageInfo));
}
error = HandleDatagram(aMessage, nullptr, nullptr, aFromHost);
freed = true;
exit:
if (!freed)
{
aMessage.Free();
}
return error;
}
Error Ip6::HandleDatagram(Message &aMessage, Netif *aNetif, const void *aLinkMessageInfo, bool aFromHost)
{
Error error;
MessageInfo messageInfo;
Header header;
bool receive;
bool forwardThread;
bool forwardHost;
bool shouldFreeMessage;
uint8_t nextHeader;
start:
receive = false;
forwardThread = false;
forwardHost = false;
shouldFreeMessage = true;
SuccessOrExit(error = header.Init(aMessage));
messageInfo.Clear();
messageInfo.SetPeerAddr(header.GetSource());
messageInfo.SetSockAddr(header.GetDestination());
messageInfo.SetHopLimit(header.GetHopLimit());
messageInfo.SetLinkInfo(aLinkMessageInfo);
// determine destination of packet
if (header.GetDestination().IsMulticast())
{
Netif *netif;
if (aNetif != nullptr)
{
#if OPENTHREAD_FTD
if (header.GetDestination().IsMulticastLargerThanRealmLocal() &&
Get<ChildTable>().HasSleepyChildWithAddress(header.GetDestination()))
{
forwardThread = true;
}
#endif
netif = aNetif;
}
else
{
forwardThread = true;
netif = &Get<ThreadNetif>();
}
forwardHost = header.GetDestination().IsMulticastLargerThanRealmLocal();
if ((aNetif != nullptr || aMessage.GetMulticastLoop()) && netif->IsMulticastSubscribed(header.GetDestination()))
{
receive = true;
}
else if (netif->IsMulticastPromiscuousEnabled())
{
forwardHost = true;
}
}
else
{
// unicast
if (Get<ThreadNetif>().HasUnicastAddress(header.GetDestination()))
{
receive = true;
}
else if (!header.GetDestination().IsLinkLocal())
{
forwardThread = true;
}
else if (aNetif == nullptr)
{
forwardThread = true;
}
if (forwardThread && !ShouldForwardToThread(messageInfo, aFromHost))
{
forwardThread = false;
forwardHost = true;
}
}
aMessage.SetOffset(sizeof(header));
// process IPv6 Extension Headers
nextHeader = static_cast<uint8_t>(header.GetNextHeader());
SuccessOrExit(error = HandleExtensionHeaders(aMessage, aNetif, messageInfo, header, nextHeader, aNetif == nullptr,
aFromHost, receive));
// process IPv6 Payload
if (receive)
{
if (nextHeader == kProtoIp6)
{
// Remove encapsulating header and start over.
aMessage.RemoveHeader(aMessage.GetOffset());
Get<MeshForwarder>().LogMessage(MeshForwarder::kMessageReceive, aMessage, nullptr, kErrorNone);
goto start;
}
error = ProcessReceiveCallback(aMessage, messageInfo, nextHeader, aFromHost,
/* aAllowReceiveFilter */ !forwardHost, Message::kCopyToUse);
if ((error == kErrorNone || error == kErrorNoRoute) && forwardHost)
{
forwardHost = false;
}
error = HandlePayload(header, aMessage, messageInfo, nextHeader,
(forwardThread || forwardHost ? Message::kCopyToUse : Message::kTakeCustody));
shouldFreeMessage = forwardThread || forwardHost;
}
if (forwardHost)
{
// try passing to host
error = ProcessReceiveCallback(aMessage, messageInfo, nextHeader, aFromHost, /* aAllowReceiveFilter */ false,
forwardThread ? Message::kCopyToUse : Message::kTakeCustody);
shouldFreeMessage = forwardThread;
}
if (forwardThread)
{
uint8_t hopLimit;
if (aNetif != nullptr)
{
VerifyOrExit(mForwardingEnabled);
header.SetHopLimit(header.GetHopLimit() - 1);
}
VerifyOrExit(header.GetHopLimit() > 0, error = kErrorDrop);
hopLimit = header.GetHopLimit();
aMessage.Write(Header::kHopLimitFieldOffset, hopLimit);
if (nextHeader == kProtoIcmp6)
{
uint8_t icmpType;
bool isAllowedType = false;
SuccessOrExit(error = aMessage.Read(aMessage.GetOffset(), icmpType));
for (IcmpType type : sForwardICMPTypes)
{
if (icmpType == type)
{
isAllowedType = true;
break;
}
}
VerifyOrExit(isAllowedType, error = kErrorDrop);
}
#if !OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE
if (aFromHost && (nextHeader == kProtoUdp))
{
uint16_t destPort;
SuccessOrExit(error = aMessage.Read(aMessage.GetOffset() + Udp::Header::kDestPortFieldOffset, destPort));
destPort = HostSwap16(destPort);
if (nextHeader == kProtoUdp)
{
VerifyOrExit(Get<Udp>().ShouldUsePlatformUdp(destPort), error = kErrorDrop);
}
}
#endif
#if OPENTHREAD_CONFIG_MULTI_RADIO
// Since the message will be forwarded, we clear the radio
// type on the message to allow the radio type for tx to be
// selected later (based on the radios supported by the next
// hop).
aMessage.ClearRadioType();
#endif
// `SendMessage()` takes custody of message in the success case
SuccessOrExit(error = Get<ThreadNetif>().SendMessage(aMessage));
shouldFreeMessage = false;
}
exit:
if (shouldFreeMessage)
{
aMessage.Free();
}
return error;
}
bool Ip6::ShouldForwardToThread(const MessageInfo &aMessageInfo, bool aFromHost) const
{
OT_UNUSED_VARIABLE(aFromHost);
bool rval = false;
if (aMessageInfo.GetSockAddr().IsMulticast())
{
// multicast
ExitNow(rval = true);
}
else if (aMessageInfo.GetSockAddr().IsLinkLocal())
{
// on-link link-local address
ExitNow(rval = true);
}
else if (IsOnLink(aMessageInfo.GetSockAddr()))
{
// on-link global address
#if OPENTHREAD_FTD && OPENTHREAD_CONFIG_BACKBONE_ROUTER_DUA_NDPROXYING_ENABLE
ExitNow(rval = (aFromHost ||
!Get<BackboneRouter::Manager>().ShouldForwardDuaToBackbone(aMessageInfo.GetSockAddr())));
#else
ExitNow(rval = true);
#endif
}
else if (Get<ThreadNetif>().RouteLookup(aMessageInfo.GetPeerAddr(), aMessageInfo.GetSockAddr(), nullptr) ==
kErrorNone)
{
// route
ExitNow(rval = true);
}
else
{
ExitNow(rval = false);
}
exit:
return rval;
}
const Netif::UnicastAddress *Ip6::SelectSourceAddress(MessageInfo &aMessageInfo)
{
Address * destination = &aMessageInfo.GetPeerAddr();
uint8_t destinationScope = destination->GetScope();
const bool destinationIsRoutingLocator = Get<Mle::Mle>().IsRoutingLocator(*destination);
const Netif::UnicastAddress *rvalAddr = nullptr;
uint8_t rvalPrefixMatched = 0;
for (const Netif::UnicastAddress &addr : Get<ThreadNetif>().GetUnicastAddresses())
{
const Address *candidateAddr = &addr.GetAddress();
uint8_t candidatePrefixMatched;
uint8_t overrideScope;
if (Get<Mle::Mle>().IsAnycastLocator(*candidateAddr))
{
// Don't use anycast address as source address.
continue;
}
candidatePrefixMatched = destination->PrefixMatch(*candidateAddr);
if (candidatePrefixMatched >= addr.mPrefixLength)
{
candidatePrefixMatched = addr.mPrefixLength;
overrideScope = addr.GetScope();
}
else
{
overrideScope = destinationScope;
}
if (rvalAddr == nullptr)
{
// Rule 0: Prefer any address
rvalAddr = &addr;
rvalPrefixMatched = candidatePrefixMatched;
}
else if (*candidateAddr == *destination)
{
// Rule 1: Prefer same address
rvalAddr = &addr;
ExitNow();
}
else if (addr.GetScope() < rvalAddr->GetScope())
{
// Rule 2: Prefer appropriate scope
if (addr.GetScope() >= overrideScope)
{
rvalAddr = &addr;
rvalPrefixMatched = candidatePrefixMatched;
}
else
{
continue;
}
}
else if (addr.GetScope() > rvalAddr->GetScope())
{
if (rvalAddr->GetScope() < overrideScope)
{
rvalAddr = &addr;
rvalPrefixMatched = candidatePrefixMatched;
}
else
{
continue;
}
}
else if (addr.mPreferred && !rvalAddr->mPreferred)
{
// Rule 3: Avoid deprecated addresses
rvalAddr = &addr;
rvalPrefixMatched = candidatePrefixMatched;
}
else if (candidatePrefixMatched > rvalPrefixMatched)
{
// Rule 6: Prefer matching label
// Rule 7: Prefer public address
// Rule 8: Use longest prefix matching
rvalAddr = &addr;
rvalPrefixMatched = candidatePrefixMatched;
}
else if ((candidatePrefixMatched == rvalPrefixMatched) &&
(destinationIsRoutingLocator == Get<Mle::Mle>().IsRoutingLocator(*candidateAddr)))
{
// Additional rule: Prefer RLOC source for RLOC destination, EID source for anything else
rvalAddr = &addr;
rvalPrefixMatched = candidatePrefixMatched;
}
else
{
continue;
}
// infer destination scope based on prefix match
if (rvalPrefixMatched >= rvalAddr->mPrefixLength)
{
destinationScope = rvalAddr->GetScope();
}
}
exit:
return rvalAddr;
}
bool Ip6::IsOnLink(const Address &aAddress) const
{
bool rval = false;
if (Get<ThreadNetif>().IsOnMesh(aAddress))
{
ExitNow(rval = true);
}
for (const Netif::UnicastAddress &cur : Get<ThreadNetif>().GetUnicastAddresses())
{
if (cur.GetAddress().PrefixMatch(aAddress) >= cur.mPrefixLength)
{
ExitNow(rval = true);
}
}
exit:
return rval;
}
// LCOV_EXCL_START
const char *Ip6::IpProtoToString(uint8_t aIpProto)
{
static constexpr Stringify::Entry kIpProtoTable[] = {
{kProtoHopOpts, "HopOpts"}, {kProtoTcp, "TCP"}, {kProtoUdp, "UDP"},
{kProtoIp6, "IP6"}, {kProtoRouting, "Routing"}, {kProtoFragment, "Frag"},
{kProtoIcmp6, "ICMP6"}, {kProtoNone, "None"}, {kProtoDstOpts, "DstOpts"},
};
static_assert(Stringify::IsSorted(kIpProtoTable), "kIpProtoTable is not sorted");
return Stringify::Lookup(aIpProto, kIpProtoTable, "Unknown");
}
// LCOV_EXCL_STOP
} // namespace Ip6
} // namespace ot
| openthread/openthread | src/core/net/ip6.cpp | C++ | bsd-3-clause | 45,337 |
// Copyright 2014 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 "components/omnibox/browser/autocomplete_match.h"
#include <algorithm>
#include "base/check_op.h"
#include "base/cxx17_backports.h"
#include "base/debug/crash_logging.h"
#include "base/feature_list.h"
#include "base/i18n/case_conversion.h"
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "base/notreached.h"
#include "base/ranges/algorithm.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "base/trace_event/memory_usage_estimator.h"
#include "base/trace_event/trace_event.h"
#include "components/omnibox/browser/actions/omnibox_action.h"
#include "components/omnibox/browser/autocomplete_provider.h"
#include "components/omnibox/browser/document_provider.h"
#include "components/omnibox/browser/omnibox_field_trial.h"
#include "components/omnibox/common/omnibox_features.h"
#include "components/search_engines/search_engine_utils.h"
#include "components/search_engines/template_url_service.h"
#include "inline_autocompletion_util.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "ui/gfx/vector_icon_types.h"
#include "url/third_party/mozilla/url_parse.h"
#if (!defined(OS_ANDROID) || BUILDFLAG(ENABLE_VR)) && !defined(OS_IOS)
#include "components/omnibox/browser/suggestion_answer.h"
#include "components/omnibox/browser/vector_icons.h" // nogncheck
#include "components/vector_icons/vector_icons.h" // nogncheck
#endif
namespace {
bool IsTrivialClassification(const ACMatchClassifications& classifications) {
return classifications.empty() ||
((classifications.size() == 1) &&
(classifications.back().style == ACMatchClassification::NONE));
}
// Returns true if one of the |terms_prefixed_by_http_or_https| matches the
// beginning of the URL (sans scheme). (Recall that
// |terms_prefixed_by_http_or_https|, for the input "http://a b" will be
// ["a"].) This suggests that the user wants a particular URL with a scheme
// in mind, hence the caller should not consider another URL like this one
// but with a different scheme to be a duplicate.
bool WordMatchesURLContent(
const std::vector<std::u16string>& terms_prefixed_by_http_or_https,
const GURL& url) {
size_t prefix_length =
url.scheme().length() + strlen(url::kStandardSchemeSeparator);
DCHECK_GE(url.spec().length(), prefix_length);
const std::u16string& formatted_url = url_formatter::FormatUrl(
url, url_formatter::kFormatUrlOmitNothing, net::UnescapeRule::NORMAL,
nullptr, nullptr, &prefix_length);
if (prefix_length == std::u16string::npos)
return false;
const std::u16string& formatted_url_without_scheme =
formatted_url.substr(prefix_length);
for (const auto& term : terms_prefixed_by_http_or_https) {
if (base::StartsWith(formatted_url_without_scheme, term,
base::CompareCase::SENSITIVE))
return true;
}
return false;
}
// Check if title or non-prefix rich autocompletion is possible. I.e.:
// 1) Enabled for all providers OR for the shortcut provider if the suggestion
// is from the shortcut provider.
// 2) The input is longer than the threshold.
// 3) Enabled for inputs containing spaces OR the input contains no spaces.
bool RichAutocompletionApplicable(bool enabled_all_providers,
bool enabled_shortcut_provider,
size_t min_char,
bool no_inputs_with_spaces,
bool shortcut_provider,
const std::u16string& input_text) {
return (enabled_all_providers ||
(shortcut_provider && enabled_shortcut_provider)) &&
input_text.size() >= min_char &&
(!no_inputs_with_spaces ||
base::ranges::none_of(input_text, &base::IsAsciiWhitespace<char>));
}
} // namespace
SplitAutocompletion::SplitAutocompletion(std::u16string display_text,
std::vector<gfx::Range> selections)
: display_text(display_text), selections(selections) {}
SplitAutocompletion::SplitAutocompletion() = default;
SplitAutocompletion::SplitAutocompletion(const SplitAutocompletion& copy) =
default;
SplitAutocompletion::SplitAutocompletion(SplitAutocompletion&& other) noexcept =
default;
SplitAutocompletion& SplitAutocompletion::operator=(
const SplitAutocompletion&) = default;
SplitAutocompletion& SplitAutocompletion::operator=(
SplitAutocompletion&&) noexcept = default;
SplitAutocompletion::~SplitAutocompletion() = default;
bool SplitAutocompletion::Empty() const {
return selections.empty();
}
void SplitAutocompletion::Clear() {
selections.clear();
}
// AutocompleteMatch ----------------------------------------------------------
// static
const char* const AutocompleteMatch::kDocumentTypeStrings[]{
"none", "drive_docs", "drive_forms", "drive_sheets", "drive_slides",
"drive_image", "drive_pdf", "drive_video", "drive_folder", "drive_other"};
static_assert(
base::size(AutocompleteMatch::kDocumentTypeStrings) ==
static_cast<int>(AutocompleteMatch::DocumentType::DOCUMENT_TYPE_SIZE),
"Sizes of AutocompleteMatch::kDocumentTypeStrings and "
"AutocompleteMatch::DocumentType don't match.");
// static
const char* AutocompleteMatch::DocumentTypeString(DocumentType type) {
return kDocumentTypeStrings[static_cast<int>(type)];
}
// static
bool AutocompleteMatch::DocumentTypeFromInteger(int value,
DocumentType* result) {
DCHECK(result);
// The resulting value may still be invalid after the static_cast.
DocumentType document_type = static_cast<DocumentType>(value);
if (document_type >= DocumentType::NONE &&
document_type < DocumentType::DOCUMENT_TYPE_SIZE) {
*result = document_type;
return true;
}
return false;
}
// static
const char16_t AutocompleteMatch::kInvalidChars[] = {
'\n', '\r', '\t',
0x2028, // Line separator
0x2029, // Paragraph separator
0};
// static
const char16_t AutocompleteMatch::kEllipsis[] = u"... ";
AutocompleteMatch::AutocompleteMatch()
: transition(ui::PAGE_TRANSITION_GENERATED) {}
AutocompleteMatch::AutocompleteMatch(AutocompleteProvider* provider,
int relevance,
bool deletable,
Type type)
: provider(provider),
relevance(relevance),
deletable(deletable),
transition(ui::PAGE_TRANSITION_TYPED),
type(type) {}
AutocompleteMatch::AutocompleteMatch(const AutocompleteMatch& match)
: provider(match.provider),
relevance(match.relevance),
typed_count(match.typed_count),
deletable(match.deletable),
fill_into_edit(match.fill_into_edit),
additional_text(match.additional_text),
inline_autocompletion(match.inline_autocompletion),
rich_autocompletion_triggered(match.rich_autocompletion_triggered),
prefix_autocompletion(match.prefix_autocompletion),
split_autocompletion(match.split_autocompletion),
allowed_to_be_default_match(match.allowed_to_be_default_match),
destination_url(match.destination_url),
stripped_destination_url(match.stripped_destination_url),
image_dominant_color(match.image_dominant_color),
image_url(match.image_url),
document_type(match.document_type),
tail_suggest_common_prefix(match.tail_suggest_common_prefix),
contents(match.contents),
contents_class(match.contents_class),
description(match.description),
description_class(match.description_class),
description_for_shortcuts(match.description_for_shortcuts),
description_class_for_shortcuts(match.description_class_for_shortcuts),
suggestion_group_id(match.suggestion_group_id),
swap_contents_and_description(match.swap_contents_and_description),
answer(match.answer),
transition(match.transition),
type(match.type),
has_tab_match(match.has_tab_match),
subtypes(match.subtypes),
associated_keyword(match.associated_keyword
? new AutocompleteMatch(*match.associated_keyword)
: nullptr),
keyword(match.keyword),
from_keyword(match.from_keyword),
action(match.action),
from_previous(match.from_previous),
search_terms_args(
match.search_terms_args
? new TemplateURLRef::SearchTermsArgs(*match.search_terms_args)
: nullptr),
post_content(match.post_content
? new TemplateURLRef::PostContent(*match.post_content)
: nullptr),
additional_info(match.additional_info),
duplicate_matches(match.duplicate_matches),
query_tiles(match.query_tiles),
navsuggest_tiles(match.navsuggest_tiles) {}
AutocompleteMatch::AutocompleteMatch(AutocompleteMatch&& match) noexcept {
*this = std::move(match);
}
AutocompleteMatch& AutocompleteMatch::operator=(
AutocompleteMatch&& match) noexcept {
provider = std::move(match.provider);
relevance = std::move(match.relevance);
typed_count = std::move(match.typed_count);
deletable = std::move(match.deletable);
fill_into_edit = std::move(match.fill_into_edit);
additional_text = std::move(match.additional_text);
inline_autocompletion = std::move(match.inline_autocompletion);
rich_autocompletion_triggered =
std::move(match.rich_autocompletion_triggered);
prefix_autocompletion = std::move(match.prefix_autocompletion);
split_autocompletion = std::move(match.split_autocompletion);
allowed_to_be_default_match = std::move(match.allowed_to_be_default_match);
destination_url = std::move(match.destination_url);
stripped_destination_url = std::move(match.stripped_destination_url);
image_dominant_color = std::move(match.image_dominant_color);
image_url = std::move(match.image_url);
document_type = std::move(match.document_type);
tail_suggest_common_prefix = std::move(match.tail_suggest_common_prefix);
contents = std::move(match.contents);
contents_class = std::move(match.contents_class);
description = std::move(match.description);
description_class = std::move(match.description_class);
description_for_shortcuts = std::move(match.description_for_shortcuts);
description_class_for_shortcuts =
std::move(match.description_class_for_shortcuts);
suggestion_group_id = std::move(match.suggestion_group_id);
swap_contents_and_description =
std::move(match.swap_contents_and_description);
answer = std::move(match.answer);
transition = std::move(match.transition);
type = std::move(match.type);
has_tab_match = std::move(match.has_tab_match);
subtypes = std::move(match.subtypes);
associated_keyword = std::move(match.associated_keyword);
keyword = std::move(match.keyword);
from_keyword = std::move(match.from_keyword);
action = std::move(match.action);
from_previous = std::move(match.from_previous);
search_terms_args = std::move(match.search_terms_args);
post_content = std::move(match.post_content);
additional_info = std::move(match.additional_info);
duplicate_matches = std::move(match.duplicate_matches);
query_tiles = std::move(match.query_tiles);
navsuggest_tiles = std::move(match.navsuggest_tiles);
#if defined(OS_ANDROID)
DestroyJavaObject();
std::swap(java_match_, match.java_match_);
std::swap(matching_java_tab_, match.matching_java_tab_);
UpdateJavaObjectNativeRef();
#endif
return *this;
}
AutocompleteMatch::~AutocompleteMatch() {
#if defined(OS_ANDROID)
DestroyJavaObject();
#endif
}
AutocompleteMatch& AutocompleteMatch::operator=(
const AutocompleteMatch& match) {
if (this == &match)
return *this;
provider = match.provider;
relevance = match.relevance;
typed_count = match.typed_count;
deletable = match.deletable;
fill_into_edit = match.fill_into_edit;
additional_text = match.additional_text;
inline_autocompletion = match.inline_autocompletion;
rich_autocompletion_triggered = match.rich_autocompletion_triggered;
prefix_autocompletion = match.prefix_autocompletion;
split_autocompletion = match.split_autocompletion;
allowed_to_be_default_match = match.allowed_to_be_default_match;
destination_url = match.destination_url;
stripped_destination_url = match.stripped_destination_url;
image_dominant_color = match.image_dominant_color;
image_url = match.image_url;
document_type = match.document_type;
tail_suggest_common_prefix = match.tail_suggest_common_prefix;
contents = match.contents;
contents_class = match.contents_class;
description = match.description;
description_class = match.description_class;
description_for_shortcuts = match.description_for_shortcuts;
description_class_for_shortcuts = match.description_class_for_shortcuts;
suggestion_group_id = match.suggestion_group_id;
swap_contents_and_description = match.swap_contents_and_description;
answer = match.answer;
transition = match.transition;
type = match.type;
has_tab_match = match.has_tab_match;
subtypes = match.subtypes;
associated_keyword.reset(
match.associated_keyword
? new AutocompleteMatch(*match.associated_keyword)
: nullptr);
keyword = match.keyword;
from_keyword = match.from_keyword;
action = match.action;
from_previous = match.from_previous;
search_terms_args.reset(
match.search_terms_args
? new TemplateURLRef::SearchTermsArgs(*match.search_terms_args)
: nullptr);
post_content.reset(match.post_content
? new TemplateURLRef::PostContent(*match.post_content)
: nullptr);
additional_info = match.additional_info;
duplicate_matches = match.duplicate_matches;
query_tiles = match.query_tiles;
navsuggest_tiles = match.navsuggest_tiles;
#if defined(OS_ANDROID)
// In case the target element previously held a java object, release it.
// This happens, when in an expression "match1 = match2;" match1 already
// is initialized and linked to a Java object: we rewrite the contents of the
// match1 object and it would be desired to either update its corresponding
// Java element, or drop it and construct it lazily the next time it is
// needed.
// Note that because Java<>C++ AutocompleteMatch relation is 1:1, we do not
// want to copy the object here.
DestroyJavaObject();
#endif
return *this;
}
#if (!defined(OS_ANDROID) || BUILDFLAG(ENABLE_VR)) && !defined(OS_IOS)
// static
const gfx::VectorIcon& AutocompleteMatch::AnswerTypeToAnswerIcon(int type) {
switch (static_cast<SuggestionAnswer::AnswerType>(type)) {
case SuggestionAnswer::ANSWER_TYPE_CURRENCY:
return omnibox::kAnswerCurrencyIcon;
case SuggestionAnswer::ANSWER_TYPE_DICTIONARY:
return omnibox::kAnswerDictionaryIcon;
case SuggestionAnswer::ANSWER_TYPE_FINANCE:
return omnibox::kAnswerFinanceIcon;
case SuggestionAnswer::ANSWER_TYPE_SUNRISE:
return omnibox::kAnswerSunriseIcon;
case SuggestionAnswer::ANSWER_TYPE_TRANSLATION:
return omnibox::kAnswerTranslationIcon;
case SuggestionAnswer::ANSWER_TYPE_WHEN_IS:
return omnibox::kAnswerWhenIsIcon;
default:
return omnibox::kAnswerDefaultIcon;
}
}
const gfx::VectorIcon& AutocompleteMatch::GetVectorIcon(
bool is_bookmark) const {
// TODO(https://crbug.com/1024114): Remove crash logging once fixed.
SCOPED_CRASH_KEY_NUMBER("AutocompleteMatch", "type", type);
SCOPED_CRASH_KEY_NUMBER("AutocompleteMatch", "provider_type",
provider ? provider->type() : -1);
if (is_bookmark)
return omnibox::kBookmarkIcon;
if (answer.has_value())
return AnswerTypeToAnswerIcon(answer->type());
switch (type) {
case Type::URL_WHAT_YOU_TYPED:
case Type::HISTORY_URL:
case Type::HISTORY_TITLE:
case Type::HISTORY_BODY:
case Type::HISTORY_KEYWORD:
case Type::NAVSUGGEST:
case Type::BOOKMARK_TITLE:
case Type::NAVSUGGEST_PERSONALIZED:
case Type::CLIPBOARD_URL:
case Type::PHYSICAL_WEB_DEPRECATED:
case Type::PHYSICAL_WEB_OVERFLOW_DEPRECATED:
case Type::TAB_SEARCH_DEPRECATED:
case Type::TILE_NAVSUGGEST:
return omnibox::kPageIcon;
case Type::SEARCH_SUGGEST: {
if (subtypes.contains(/*SUBTYPE_TRENDS=*/143))
return omnibox::kTrendingUpIcon;
return vector_icons::kSearchIcon;
}
case Type::SEARCH_WHAT_YOU_TYPED:
case Type::SEARCH_SUGGEST_ENTITY:
case Type::SEARCH_SUGGEST_PROFILE:
case Type::SEARCH_OTHER_ENGINE:
case Type::CONTACT_DEPRECATED:
case Type::VOICE_SUGGEST:
case Type::PEDAL_DEPRECATED:
case Type::CLIPBOARD_TEXT:
case Type::CLIPBOARD_IMAGE:
case Type::TILE_SUGGESTION:
return vector_icons::kSearchIcon;
case Type::SEARCH_HISTORY:
case Type::SEARCH_SUGGEST_PERSONALIZED: {
DCHECK(IsSearchHistoryType(type));
return omnibox::kClockIcon;
}
case Type::EXTENSION_APP_DEPRECATED:
return omnibox::kExtensionAppIcon;
case Type::CALCULATOR:
return omnibox::kCalculatorIcon;
case Type::SEARCH_SUGGEST_TAIL:
return omnibox::kBlankIcon;
case Type::DOCUMENT_SUGGESTION:
switch (document_type) {
case DocumentType::DRIVE_DOCS:
return omnibox::kDriveDocsIcon;
case DocumentType::DRIVE_FORMS:
return omnibox::kDriveFormsIcon;
case DocumentType::DRIVE_SHEETS:
return omnibox::kDriveSheetsIcon;
case DocumentType::DRIVE_SLIDES:
return omnibox::kDriveSlidesIcon;
case DocumentType::DRIVE_IMAGE:
return omnibox::kDriveImageIcon;
case DocumentType::DRIVE_PDF:
return omnibox::kDrivePdfIcon;
case DocumentType::DRIVE_VIDEO:
return omnibox::kDriveVideoIcon;
case DocumentType::DRIVE_FOLDER:
return omnibox::kDriveFolderIcon;
case DocumentType::DRIVE_OTHER:
return omnibox::kDriveLogoIcon;
default:
return omnibox::kPageIcon;
}
case Type::NUM_TYPES:
// TODO(https://crbug.com/1024114): Replace with NOTREACHED() once fixed.
CHECK(false);
return vector_icons::kErrorIcon;
}
// TODO(https://crbug.com/1024114): Replace with NOTREACHED() once fixed.
CHECK(false);
return vector_icons::kErrorIcon;
}
#endif
// static
bool AutocompleteMatch::MoreRelevant(const AutocompleteMatch& match1,
const AutocompleteMatch& match2) {
// For equal-relevance matches, we sort alphabetically, so that providers
// who return multiple elements at the same priority get a "stable" sort
// across multiple updates.
return (match1.relevance == match2.relevance)
? (match1.contents < match2.contents)
: (match1.relevance > match2.relevance);
}
// static
bool AutocompleteMatch::BetterDuplicate(const AutocompleteMatch& match1,
const AutocompleteMatch& match2) {
// Prefer the Entity Match over the non-entity match, if they have the same
// |fill_into_edit| value.
if (match1.type == AutocompleteMatchType::SEARCH_SUGGEST_ENTITY &&
match2.type != AutocompleteMatchType::SEARCH_SUGGEST_ENTITY &&
match1.fill_into_edit == match2.fill_into_edit) {
return true;
}
if (match1.type != AutocompleteMatchType::SEARCH_SUGGEST_ENTITY &&
match2.type == AutocompleteMatchType::SEARCH_SUGGEST_ENTITY &&
match1.fill_into_edit == match2.fill_into_edit) {
return false;
}
// Prefer matches allowed to be the default match.
if (match1.allowed_to_be_default_match && !match2.allowed_to_be_default_match)
return true;
if (!match1.allowed_to_be_default_match && match2.allowed_to_be_default_match)
return false;
// Prefer URL autocompleted default matches if the appropriate param is true.
if (OmniboxFieldTrial::kRichAutocompletionAutocompletePreferUrlsOverPrefixes
.Get()) {
if (match1.additional_text.empty() && !match2.additional_text.empty())
return true;
if (!match1.additional_text.empty() && match2.additional_text.empty())
return false;
}
// Prefer live document suggestions. We check provider type instead of match
// type in order to distinguish live suggestions from the document provider
// from stale suggestions from the shortcuts providers, because the latter
// omits changing metadata such as last access date.
if (match1.provider->type() == AutocompleteProvider::TYPE_DOCUMENT &&
match2.provider->type() != AutocompleteProvider::TYPE_DOCUMENT) {
return true;
}
if (match1.provider->type() != AutocompleteProvider::TYPE_DOCUMENT &&
match2.provider->type() == AutocompleteProvider::TYPE_DOCUMENT) {
return false;
}
// By default, simply prefer the more relevant match.
return MoreRelevant(match1, match2);
}
// static
bool AutocompleteMatch::BetterDuplicateByIterator(
const std::vector<AutocompleteMatch>::const_iterator it1,
const std::vector<AutocompleteMatch>::const_iterator it2) {
return BetterDuplicate(*it1, *it2);
}
// static
void AutocompleteMatch::ClassifyMatchInString(
const std::u16string& find_text,
const std::u16string& text,
int style,
ACMatchClassifications* classification) {
ClassifyLocationInString(text.find(find_text), find_text.length(),
text.length(), style, classification);
}
// static
void AutocompleteMatch::ClassifyLocationInString(
size_t match_location,
size_t match_length,
size_t overall_length,
int style,
ACMatchClassifications* classification) {
classification->clear();
// Don't classify anything about an empty string
// (AutocompleteMatch::Validate() checks this).
if (overall_length == 0)
return;
// Mark pre-match portion of string (if any).
if (match_location != 0) {
classification->push_back(ACMatchClassification(0, style));
}
// Mark matching portion of string.
if (match_location == std::u16string::npos) {
// No match, above classification will suffice for whole string.
return;
}
// Classifying an empty match makes no sense and will lead to validation
// errors later.
DCHECK_GT(match_length, 0U);
classification->push_back(ACMatchClassification(match_location,
(style | ACMatchClassification::MATCH) & ~ACMatchClassification::DIM));
// Mark post-match portion of string (if any).
const size_t after_match(match_location + match_length);
if (after_match < overall_length) {
classification->push_back(ACMatchClassification(after_match, style));
}
}
// static
AutocompleteMatch::ACMatchClassifications
AutocompleteMatch::MergeClassifications(
const ACMatchClassifications& classifications1,
const ACMatchClassifications& classifications2) {
// We must return the empty vector only if both inputs are truly empty.
// The result of merging an empty vector with a single (0, NONE)
// classification is the latter one-entry vector.
if (IsTrivialClassification(classifications1))
return classifications2.empty() ? classifications1 : classifications2;
if (IsTrivialClassification(classifications2))
return classifications1;
ACMatchClassifications output;
for (auto i = classifications1.begin(), j = classifications2.begin();
i != classifications1.end();) {
AutocompleteMatch::AddLastClassificationIfNecessary(&output,
std::max(i->offset, j->offset), i->style | j->style);
const size_t next_i_offset = (i + 1) == classifications1.end() ?
static_cast<size_t>(-1) : (i + 1)->offset;
const size_t next_j_offset = (j + 1) == classifications2.end() ?
static_cast<size_t>(-1) : (j + 1)->offset;
if (next_i_offset >= next_j_offset)
++j;
if (next_j_offset >= next_i_offset)
++i;
}
return output;
}
// static
std::string AutocompleteMatch::ClassificationsToString(
const ACMatchClassifications& classifications) {
std::string serialized_classifications;
for (size_t i = 0; i < classifications.size(); ++i) {
if (i)
serialized_classifications += ',';
serialized_classifications +=
base::NumberToString(classifications[i].offset) + ',' +
base::NumberToString(classifications[i].style);
}
return serialized_classifications;
}
// static
ACMatchClassifications AutocompleteMatch::ClassificationsFromString(
const std::string& serialized_classifications) {
ACMatchClassifications classifications;
std::vector<base::StringPiece> tokens = base::SplitStringPiece(
serialized_classifications, ",", base::KEEP_WHITESPACE,
base::SPLIT_WANT_NONEMPTY);
DCHECK(!(tokens.size() & 1)); // The number of tokens should be even.
for (size_t i = 0; i < tokens.size(); i += 2) {
int classification_offset = 0;
int classification_style = ACMatchClassification::NONE;
if (!base::StringToInt(tokens[i], &classification_offset) ||
!base::StringToInt(tokens[i + 1], &classification_style)) {
NOTREACHED();
return classifications;
}
classifications.push_back(ACMatchClassification(classification_offset,
classification_style));
}
return classifications;
}
// static
void AutocompleteMatch::AddLastClassificationIfNecessary(
ACMatchClassifications* classifications,
size_t offset,
int style) {
DCHECK(classifications);
if (classifications->empty() || classifications->back().style != style) {
DCHECK(classifications->empty() ||
(offset > classifications->back().offset));
classifications->push_back(ACMatchClassification(offset, style));
}
}
// static
bool AutocompleteMatch::HasMatchStyle(
const ACMatchClassifications& classifications) {
for (const auto& it : classifications) {
if (it.style & AutocompleteMatch::ACMatchClassification::MATCH)
return true;
}
return false;
}
// static
std::u16string AutocompleteMatch::SanitizeString(const std::u16string& text) {
// NOTE: This logic is mirrored by |sanitizeString()| in
// omnibox_custom_bindings.js.
std::u16string result;
base::TrimWhitespace(text, base::TRIM_LEADING, &result);
base::RemoveChars(result, kInvalidChars, &result);
return result;
}
// static
bool AutocompleteMatch::IsSearchType(Type type) {
return type == AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED ||
type == AutocompleteMatchType::SEARCH_HISTORY ||
type == AutocompleteMatchType::SEARCH_SUGGEST ||
type == AutocompleteMatchType::SEARCH_OTHER_ENGINE ||
type == AutocompleteMatchType::CALCULATOR ||
type == AutocompleteMatchType::VOICE_SUGGEST ||
IsSpecializedSearchType(type);
}
// static
bool AutocompleteMatch::IsSpecializedSearchType(Type type) {
return type == AutocompleteMatchType::SEARCH_SUGGEST_ENTITY ||
type == AutocompleteMatchType::SEARCH_SUGGEST_TAIL ||
type == AutocompleteMatchType::SEARCH_SUGGEST_PERSONALIZED ||
type == AutocompleteMatchType::TILE_SUGGESTION ||
type == AutocompleteMatchType::SEARCH_SUGGEST_PROFILE;
}
// static
bool AutocompleteMatch::IsSearchHistoryType(Type type) {
return type == AutocompleteMatchType::SEARCH_HISTORY ||
type == AutocompleteMatchType::SEARCH_SUGGEST_PERSONALIZED;
}
// static
bool AutocompleteMatch::IsActionCompatibleType(Type type) {
// Note: There is a PEDAL type, but it is deprecated because Pedals always
// attach to matches of other types instead of creating dedicated matches.
return type != AutocompleteMatchType::SEARCH_SUGGEST_ENTITY;
}
// static
bool AutocompleteMatch::ShouldBeSkippedForGroupBySearchVsUrl(Type type) {
return type == AutocompleteMatchType::CLIPBOARD_URL ||
type == AutocompleteMatchType::CLIPBOARD_TEXT ||
type == AutocompleteMatchType::CLIPBOARD_IMAGE ||
type == AutocompleteMatchType::TILE_NAVSUGGEST ||
type == AutocompleteMatchType::TILE_SUGGESTION;
}
// static
TemplateURL* AutocompleteMatch::GetTemplateURLWithKeyword(
TemplateURLService* template_url_service,
const std::u16string& keyword,
const std::string& host) {
return const_cast<TemplateURL*>(GetTemplateURLWithKeyword(
static_cast<const TemplateURLService*>(template_url_service), keyword,
host));
}
// static
const TemplateURL* AutocompleteMatch::GetTemplateURLWithKeyword(
const TemplateURLService* template_url_service,
const std::u16string& keyword,
const std::string& host) {
if (template_url_service == nullptr)
return nullptr;
const TemplateURL* template_url =
keyword.empty() ? nullptr
: template_url_service->GetTemplateURLForKeyword(keyword);
return (template_url || host.empty()) ?
template_url : template_url_service->GetTemplateURLForHost(host);
}
// static
GURL AutocompleteMatch::GURLToStrippedGURL(
const GURL& url,
const AutocompleteInput& input,
const TemplateURLService* template_url_service,
const std::u16string& keyword) {
if (!url.is_valid())
return url;
// Special-case canonicalizing Docs URLs. This logic is self-contained and
// will not participate in the TemplateURL canonicalization.
GURL docs_url = DocumentProvider::GetURLForDeduping(url);
if (docs_url.is_valid())
return docs_url;
GURL stripped_destination_url = url;
// If the destination URL looks like it was generated from a TemplateURL,
// remove all substitutions other than the search terms. This allows us
// to eliminate cases like past search URLs from history that differ only
// by some obscure query param from each other or from the search/keyword
// provider matches.
const TemplateURL* template_url = GetTemplateURLWithKeyword(
template_url_service, keyword, stripped_destination_url.host());
if (template_url != nullptr &&
template_url->SupportsReplacement(
template_url_service->search_terms_data())) {
std::u16string search_terms;
if (template_url->ExtractSearchTermsFromURL(
stripped_destination_url,
template_url_service->search_terms_data(),
&search_terms)) {
stripped_destination_url =
GURL(template_url->url_ref().ReplaceSearchTerms(
TemplateURLRef::SearchTermsArgs(search_terms),
template_url_service->search_terms_data()));
}
}
// |replacements| keeps all the substitutions we're going to make to
// from {destination_url} to {stripped_destination_url}. |need_replacement|
// is a helper variable that helps us keep track of whether we need
// to apply the replacement.
bool needs_replacement = false;
GURL::Replacements replacements;
// Remove the www. prefix from the host.
static const char prefix[] = "www.";
static const size_t prefix_len = base::size(prefix) - 1;
std::string host = stripped_destination_url.host();
if (host.compare(0, prefix_len, prefix) == 0 && host.length() > prefix_len) {
replacements.SetHostStr(base::StringPiece(host).substr(prefix_len));
needs_replacement = true;
}
// Replace https protocol with http, as long as the user didn't explicitly
// specify one of the two.
if (stripped_destination_url.SchemeIs(url::kHttpsScheme) &&
(input.terms_prefixed_by_http_or_https().empty() ||
!WordMatchesURLContent(
input.terms_prefixed_by_http_or_https(), url))) {
replacements.SetScheme(url::kHttpScheme,
url::Component(0, strlen(url::kHttpScheme)));
needs_replacement = true;
}
if (!input.parts().ref.is_nonempty() && url.has_ref()) {
replacements.ClearRef();
needs_replacement = true;
}
if (needs_replacement)
stripped_destination_url = stripped_destination_url.ReplaceComponents(
replacements);
return stripped_destination_url;
}
// static
void AutocompleteMatch::GetMatchComponents(
const GURL& url,
const std::vector<MatchPosition>& match_positions,
bool* match_in_scheme,
bool* match_in_subdomain) {
DCHECK(match_in_scheme);
DCHECK(match_in_subdomain);
size_t domain_length =
net::registry_controlled_domains::GetDomainAndRegistry(
url, net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES)
.size();
const url::Parsed& parsed = url.parsed_for_possibly_invalid_spec();
size_t host_pos = parsed.CountCharactersBefore(url::Parsed::HOST, false);
bool has_subdomain =
domain_length > 0 && domain_length < url.host_piece().length();
// Subtract an extra character from the domain start to exclude the '.'
// delimiter between subdomain and domain.
size_t subdomain_end =
has_subdomain ? host_pos + url.host_piece().length() - domain_length - 1
: std::string::npos;
for (auto& position : match_positions) {
// Only flag |match_in_scheme| if the match starts at the very beginning.
if (position.first == 0 && parsed.scheme.is_nonempty())
*match_in_scheme = true;
// Subdomain matches must begin before the domain, and end somewhere within
// the host or later.
if (has_subdomain && position.first < subdomain_end &&
position.second > host_pos && parsed.host.is_nonempty()) {
*match_in_subdomain = true;
}
}
}
// static
url_formatter::FormatUrlTypes AutocompleteMatch::GetFormatTypes(
bool preserve_scheme,
bool preserve_subdomain) {
auto format_types = url_formatter::kFormatUrlOmitDefaults;
if (preserve_scheme) {
format_types &= ~url_formatter::kFormatUrlOmitHTTP;
} else {
format_types |= url_formatter::kFormatUrlOmitHTTPS;
}
if (!preserve_subdomain) {
format_types |= url_formatter::kFormatUrlOmitTrivialSubdomains;
}
return format_types;
}
// static
void AutocompleteMatch::LogSearchEngineUsed(
const AutocompleteMatch& match,
TemplateURLService* template_url_service) {
DCHECK(template_url_service);
TemplateURL* template_url = match.GetTemplateURL(template_url_service, false);
if (template_url) {
SearchEngineType search_engine_type =
match.destination_url.is_valid()
? SearchEngineUtils::GetEngineType(match.destination_url)
: SEARCH_ENGINE_OTHER;
UMA_HISTOGRAM_ENUMERATION("Omnibox.SearchEngineType", search_engine_type,
SEARCH_ENGINE_MAX);
}
}
void AutocompleteMatch::ComputeStrippedDestinationURL(
const AutocompleteInput& input,
TemplateURLService* template_url_service) {
// Other than document suggestions, computing |stripped_destination_url| will
// have the same result during a match's lifecycle, so it's safe to skip
// re-computing it if it's already computed. Document suggestions'
// |stripped_url|s are pre-computed by the document provider, and overwriting
// them here would prevent potential deduping.
if (stripped_destination_url.is_empty()) {
stripped_destination_url = GURLToStrippedGURL(
destination_url, input, template_url_service, keyword);
}
}
void AutocompleteMatch::GetKeywordUIState(
TemplateURLService* template_url_service,
std::u16string* keyword_out,
bool* is_keyword_hint) const {
*is_keyword_hint = associated_keyword != nullptr;
keyword_out->assign(
*is_keyword_hint
? associated_keyword->keyword
: GetSubstitutingExplicitlyInvokedKeyword(template_url_service));
}
std::u16string AutocompleteMatch::GetSubstitutingExplicitlyInvokedKeyword(
TemplateURLService* template_url_service) const {
if (!ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_KEYWORD) ||
template_url_service == nullptr) {
return std::u16string();
}
const TemplateURL* t_url = GetTemplateURL(template_url_service, false);
return (t_url &&
t_url->SupportsReplacement(template_url_service->search_terms_data()))
? keyword
: std::u16string();
}
TemplateURL* AutocompleteMatch::GetTemplateURL(
TemplateURLService* template_url_service,
bool allow_fallback_to_destination_host) const {
return GetTemplateURLWithKeyword(
template_url_service, keyword,
allow_fallback_to_destination_host ?
destination_url.host() : std::string());
}
GURL AutocompleteMatch::ImageUrl() const {
return answer ? answer->image_url() : image_url;
}
void AutocompleteMatch::RecordAdditionalInfo(const std::string& property,
const std::string& value) {
DCHECK(!property.empty());
additional_info[property] = value;
}
void AutocompleteMatch::RecordAdditionalInfo(const std::string& property,
const std::u16string& value) {
RecordAdditionalInfo(property, base::UTF16ToUTF8(value));
}
void AutocompleteMatch::RecordAdditionalInfo(const std::string& property,
int value) {
RecordAdditionalInfo(property, base::NumberToString(value));
}
void AutocompleteMatch::RecordAdditionalInfo(const std::string& property,
base::Time value) {
RecordAdditionalInfo(
property, base::StringPrintf("%d hours ago",
(base::Time::Now() - value).InHours()));
}
std::string AutocompleteMatch::GetAdditionalInfo(
const std::string& property) const {
auto i(additional_info.find(property));
return (i == additional_info.end()) ? std::string() : i->second;
}
metrics::OmniboxEventProto::Suggestion::ResultType
AutocompleteMatch::AsOmniboxEventResultType() const {
using metrics::OmniboxEventProto;
switch (type) {
case AutocompleteMatchType::URL_WHAT_YOU_TYPED:
return OmniboxEventProto::Suggestion::URL_WHAT_YOU_TYPED;
case AutocompleteMatchType::HISTORY_URL:
return OmniboxEventProto::Suggestion::HISTORY_URL;
case AutocompleteMatchType::HISTORY_TITLE:
return OmniboxEventProto::Suggestion::HISTORY_TITLE;
case AutocompleteMatchType::HISTORY_BODY:
return OmniboxEventProto::Suggestion::HISTORY_BODY;
case AutocompleteMatchType::HISTORY_KEYWORD:
return OmniboxEventProto::Suggestion::HISTORY_KEYWORD;
case AutocompleteMatchType::NAVSUGGEST:
return OmniboxEventProto::Suggestion::NAVSUGGEST;
case AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED:
return OmniboxEventProto::Suggestion::SEARCH_WHAT_YOU_TYPED;
case AutocompleteMatchType::SEARCH_HISTORY:
return OmniboxEventProto::Suggestion::SEARCH_HISTORY;
case AutocompleteMatchType::SEARCH_SUGGEST:
return OmniboxEventProto::Suggestion::SEARCH_SUGGEST;
case AutocompleteMatchType::SEARCH_SUGGEST_ENTITY:
return OmniboxEventProto::Suggestion::SEARCH_SUGGEST_ENTITY;
case AutocompleteMatchType::SEARCH_SUGGEST_TAIL:
return OmniboxEventProto::Suggestion::SEARCH_SUGGEST_TAIL;
case AutocompleteMatchType::SEARCH_SUGGEST_PERSONALIZED:
return OmniboxEventProto::Suggestion::SEARCH_SUGGEST_PERSONALIZED;
case AutocompleteMatchType::SEARCH_SUGGEST_PROFILE:
return OmniboxEventProto::Suggestion::SEARCH_SUGGEST_PROFILE;
case AutocompleteMatchType::CALCULATOR:
return OmniboxEventProto::Suggestion::CALCULATOR;
case AutocompleteMatchType::SEARCH_OTHER_ENGINE:
return OmniboxEventProto::Suggestion::SEARCH_OTHER_ENGINE;
case AutocompleteMatchType::EXTENSION_APP_DEPRECATED:
return OmniboxEventProto::Suggestion::EXTENSION_APP;
case AutocompleteMatchType::BOOKMARK_TITLE:
return OmniboxEventProto::Suggestion::BOOKMARK_TITLE;
case AutocompleteMatchType::NAVSUGGEST_PERSONALIZED:
return OmniboxEventProto::Suggestion::NAVSUGGEST_PERSONALIZED;
case AutocompleteMatchType::CLIPBOARD_URL:
return OmniboxEventProto::Suggestion::CLIPBOARD_URL;
case AutocompleteMatchType::DOCUMENT_SUGGESTION:
return OmniboxEventProto::Suggestion::DOCUMENT;
case AutocompleteMatchType::CLIPBOARD_TEXT:
return OmniboxEventProto::Suggestion::CLIPBOARD_TEXT;
case AutocompleteMatchType::CLIPBOARD_IMAGE:
return OmniboxEventProto::Suggestion::CLIPBOARD_IMAGE;
case AutocompleteMatchType::TILE_SUGGESTION:
return OmniboxEventProto::Suggestion::TILE_SUGGESTION;
case AutocompleteMatchType::TILE_NAVSUGGEST:
return OmniboxEventProto::Suggestion::NAVSUGGEST;
case AutocompleteMatchType::VOICE_SUGGEST:
// VOICE_SUGGEST matches are only used in Java and are not logged,
// so we should never reach this case.
case AutocompleteMatchType::CONTACT_DEPRECATED:
case AutocompleteMatchType::PHYSICAL_WEB_DEPRECATED:
case AutocompleteMatchType::PHYSICAL_WEB_OVERFLOW_DEPRECATED:
case AutocompleteMatchType::TAB_SEARCH_DEPRECATED:
case AutocompleteMatchType::PEDAL_DEPRECATED:
case AutocompleteMatchType::NUM_TYPES:
break;
}
NOTREACHED();
return OmniboxEventProto::Suggestion::UNKNOWN_RESULT_TYPE;
}
bool AutocompleteMatch::IsVerbatimType() const {
const bool is_keyword_verbatim_match =
(type == AutocompleteMatchType::SEARCH_OTHER_ENGINE &&
provider != nullptr &&
provider->type() == AutocompleteProvider::TYPE_SEARCH);
return type == AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED ||
type == AutocompleteMatchType::URL_WHAT_YOU_TYPED ||
is_keyword_verbatim_match;
}
bool AutocompleteMatch::IsSearchProviderSearchSuggestion() const {
const bool from_search_provider =
(provider && provider->type() == AutocompleteProvider::TYPE_SEARCH);
return from_search_provider &&
type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED;
}
bool AutocompleteMatch::IsOnDeviceSearchSuggestion() const {
const bool from_on_device_provider =
(provider &&
provider->type() == AutocompleteProvider::TYPE_ON_DEVICE_HEAD);
return from_on_device_provider && subtypes.contains(271);
}
bool AutocompleteMatch::IsTrivialAutocompletion() const {
return type == AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED ||
type == AutocompleteMatchType::URL_WHAT_YOU_TYPED ||
type == AutocompleteMatchType::SEARCH_OTHER_ENGINE;
}
bool AutocompleteMatch::SupportsDeletion() const {
return deletable ||
std::any_of(duplicate_matches.begin(), duplicate_matches.end(),
[](const auto& m) { return m.deletable; });
}
AutocompleteMatch
AutocompleteMatch::GetMatchWithContentsAndDescriptionPossiblySwapped() const {
AutocompleteMatch copy(*this);
if (copy.swap_contents_and_description) {
std::swap(copy.contents, copy.description);
std::swap(copy.contents_class, copy.description_class);
copy.description_for_shortcuts.clear();
copy.description_class_for_shortcuts.clear();
// Clear bit to prevent accidentally performing the swap again.
copy.swap_contents_and_description = false;
}
return copy;
}
void AutocompleteMatch::SetAllowedToBeDefault(const AutocompleteInput& input) {
if (IsEmptyAutocompletion())
allowed_to_be_default_match = true;
else if (input.prevent_inline_autocomplete())
allowed_to_be_default_match = false;
else if (input.text().empty() ||
!base::IsUnicodeWhitespace(input.text().back()))
allowed_to_be_default_match = true;
else {
// If we've reached here, the input ends in trailing whitespace. If the
// trailing whitespace prefixes |inline_autocompletion|, then allow the
// match to be default and remove the whitespace from
// |inline_autocompletion|.
size_t last_non_whitespace_pos =
input.text().find_last_not_of(base::kWhitespaceUTF16);
DCHECK_NE(last_non_whitespace_pos, std::string::npos);
auto whitespace_suffix = input.text().substr(last_non_whitespace_pos + 1);
if (base::StartsWith(inline_autocompletion, whitespace_suffix,
base::CompareCase::SENSITIVE)) {
inline_autocompletion =
inline_autocompletion.substr(whitespace_suffix.size());
allowed_to_be_default_match = true;
} else
allowed_to_be_default_match = false;
}
}
void AutocompleteMatch::InlineTailPrefix(const std::u16string& common_prefix) {
// Prevent re-addition of prefix.
if (type == AutocompleteMatchType::SEARCH_SUGGEST_TAIL &&
tail_suggest_common_prefix.empty()) {
tail_suggest_common_prefix = common_prefix;
// Insert an ellipsis before uncommon part.
const std::u16string ellipsis = kEllipsis;
contents = ellipsis + contents;
// If the first class is not already NONE, prepend a NONE class for the new
// ellipsis.
if (contents_class.empty() ||
(contents_class[0].offset == 0 &&
contents_class[0].style != ACMatchClassification::NONE)) {
contents_class.insert(contents_class.begin(),
{0, ACMatchClassification::NONE});
}
// Shift existing styles.
for (size_t i = 1; i < contents_class.size(); ++i)
contents_class[i].offset += ellipsis.size();
}
}
size_t AutocompleteMatch::EstimateMemoryUsage() const {
size_t res = 0;
res += base::trace_event::EstimateMemoryUsage(fill_into_edit);
res += base::trace_event::EstimateMemoryUsage(additional_text);
res += base::trace_event::EstimateMemoryUsage(inline_autocompletion);
res += base::trace_event::EstimateMemoryUsage(prefix_autocompletion);
res += base::trace_event::EstimateMemoryUsage(destination_url);
res += base::trace_event::EstimateMemoryUsage(stripped_destination_url);
res += base::trace_event::EstimateMemoryUsage(image_dominant_color);
res += base::trace_event::EstimateMemoryUsage(image_url);
res += base::trace_event::EstimateMemoryUsage(tail_suggest_common_prefix);
res += base::trace_event::EstimateMemoryUsage(contents);
res += base::trace_event::EstimateMemoryUsage(contents_class);
res += base::trace_event::EstimateMemoryUsage(description);
res += base::trace_event::EstimateMemoryUsage(description_class);
res += base::trace_event::EstimateMemoryUsage(description_for_shortcuts);
res +=
base::trace_event::EstimateMemoryUsage(description_class_for_shortcuts);
if (answer)
res += base::trace_event::EstimateMemoryUsage(answer.value());
else
res += sizeof(SuggestionAnswer);
res += base::trace_event::EstimateMemoryUsage(associated_keyword);
res += base::trace_event::EstimateMemoryUsage(keyword);
res += base::trace_event::EstimateMemoryUsage(search_terms_args);
res += base::trace_event::EstimateMemoryUsage(post_content);
res += base::trace_event::EstimateMemoryUsage(additional_info);
res += base::trace_event::EstimateMemoryUsage(duplicate_matches);
return res;
}
void AutocompleteMatch::UpgradeMatchWithPropertiesFrom(
AutocompleteMatch& duplicate_match) {
// For Entity Matches, absorb the duplicate match's |allowed_to_be_default|
// and |inline_autocompletion| properties.
if (type == AutocompleteMatchType::SEARCH_SUGGEST_ENTITY &&
fill_into_edit == duplicate_match.fill_into_edit &&
duplicate_match.allowed_to_be_default_match) {
allowed_to_be_default_match = true;
if (IsEmptyAutocompletion()) {
inline_autocompletion = duplicate_match.inline_autocompletion;
prefix_autocompletion = duplicate_match.prefix_autocompletion;
split_autocompletion = duplicate_match.split_autocompletion;
}
}
// For Search Suggest and Search What-You-Typed matches, absorb any
// Search History type.
if ((type == AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED ||
type == AutocompleteMatchType::SEARCH_SUGGEST) &&
fill_into_edit == duplicate_match.fill_into_edit &&
IsSearchHistoryType(duplicate_match.type)) {
type = duplicate_match.type;
}
// And always absorb the higher relevance score of duplicates.
if (duplicate_match.relevance > relevance) {
RecordAdditionalInfo(kACMatchPropertyScoreBoostedFrom, relevance);
relevance = duplicate_match.relevance;
}
// Take the |action|, if any, so that it will be presented instead of buried.
if (!action && duplicate_match.action &&
AutocompleteMatch::IsActionCompatibleType(type)) {
action = duplicate_match.action;
duplicate_match.action = nullptr;
}
// Copy |rich_autocompletion_triggered| for counterfactual logging. Only copy
// true values since a rich autocompleted would have
// |allowed_to_be_default_match| true and would be preferred to a non rich
// autocompleted duplicate in non-counterfactual variations.
if (duplicate_match.rich_autocompletion_triggered)
rich_autocompletion_triggered = true;
}
bool AutocompleteMatch::TryRichAutocompletion(
const std::u16string& primary_text,
const std::u16string& secondary_text,
const AutocompleteInput& input,
bool shortcut_provider) {
if (!OmniboxFieldTrial::IsRichAutocompletionEnabled())
return false;
bool counterfactual =
OmniboxFieldTrial::kRichAutocompletionCounterfactual.Get();
if (input.prevent_inline_autocomplete())
return false;
const std::u16string primary_text_lower{base::i18n::ToLower(primary_text)};
const std::u16string secondary_text_lower{
base::i18n::ToLower(secondary_text)};
const std::u16string input_text_lower{base::i18n::ToLower(input.text())};
// Try matching the prefix of |primary_text|.
if (base::StartsWith(primary_text_lower, input_text_lower,
base::CompareCase::SENSITIVE)) {
if (counterfactual)
return false;
// This case intentionally doesn't set |rich_autocompletion_triggered| to
// true since presumably non-rich autocompletion should also be able to
// handle this case.
inline_autocompletion = primary_text.substr(input_text_lower.length());
allowed_to_be_default_match = true;
RecordAdditionalInfo("autocompletion", "primary & prefix");
return true;
}
const bool can_autocomplete_titles = RichAutocompletionApplicable(
OmniboxFieldTrial::kRichAutocompletionAutocompleteTitles.Get(),
OmniboxFieldTrial::kRichAutocompletionAutocompleteTitlesShortcutProvider
.Get(),
OmniboxFieldTrial::kRichAutocompletionAutocompleteTitlesMinChar.Get(),
OmniboxFieldTrial::kRichAutocompletionAutocompleteTitlesNoInputsWithSpaces
.Get(),
shortcut_provider, input.text());
const bool can_autocomplete_non_prefix = RichAutocompletionApplicable(
OmniboxFieldTrial::kRichAutocompletionAutocompleteNonPrefixAll.Get(),
OmniboxFieldTrial::
kRichAutocompletionAutocompleteNonPrefixShortcutProvider.Get(),
OmniboxFieldTrial::kRichAutocompletionAutocompleteNonPrefixMinChar.Get(),
OmniboxFieldTrial::
kRichAutocompletionAutocompleteNonPrefixNoInputsWithSpaces.Get(),
shortcut_provider, input.text());
// All else equal, prefer matching primary over secondary texts and prefixes
// over non-prefixes. |prefer_primary_non_prefix_over_secondary_prefix|
// determines whether to prefer matching primary text non-prefixes or
// secondary text prefixes.
bool prefer_primary_non_prefix_over_secondary_prefix =
OmniboxFieldTrial::kRichAutocompletionAutocompletePreferUrlsOverPrefixes
.Get();
size_t find_index;
// A helper to avoid duplicate code. Depending on the
// |prefer_primary_non_prefix_over_secondary_prefix|, this may be invoked
// either before or after trying prefix secondary autocompletion.
auto NonPrefixPrimaryHelper = [&]() {
rich_autocompletion_triggered = true;
if (counterfactual)
return false;
inline_autocompletion =
primary_text.substr(find_index + input_text_lower.length());
prefix_autocompletion = primary_text.substr(0, find_index);
allowed_to_be_default_match = true;
RecordAdditionalInfo("autocompletion", "primary & non-prefix");
return true;
};
// Try matching a non-prefix of |primary_text| if
// |prefer_primary_non_prefix_over_secondary_prefix| is true; otherwise, we'll
// try this only after tying to match the prefix of |secondary_text|.
if (prefer_primary_non_prefix_over_secondary_prefix &&
can_autocomplete_non_prefix &&
(find_index = FindAtWordbreak(primary_text_lower, input_text_lower)) !=
std::u16string::npos) {
return NonPrefixPrimaryHelper();
}
// Try matching the prefix of |secondary_text|.
if (can_autocomplete_titles &&
base::StartsWith(secondary_text_lower, input_text_lower,
base::CompareCase::SENSITIVE)) {
rich_autocompletion_triggered = true;
if (counterfactual)
return false;
additional_text = primary_text;
inline_autocompletion = secondary_text.substr(input_text_lower.length());
allowed_to_be_default_match = true;
RecordAdditionalInfo("autocompletion", "secondary & prefix");
return true;
}
// Try matching a non-prefix of |primary_text|. If
// |prefer_primary_non_prefix_over_secondary_prefix| is false; otherwise, this
// was already tried above.
if (!prefer_primary_non_prefix_over_secondary_prefix &&
can_autocomplete_non_prefix &&
(find_index = FindAtWordbreak(primary_text_lower, input_text_lower)) !=
std::u16string::npos) {
return NonPrefixPrimaryHelper();
}
// Try matching a non-prefix of |secondary_text|.
if (can_autocomplete_non_prefix && can_autocomplete_titles &&
(find_index = FindAtWordbreak(secondary_text_lower, input_text_lower)) !=
std::u16string::npos) {
rich_autocompletion_triggered = true;
if (counterfactual)
return false;
additional_text = primary_text;
inline_autocompletion =
secondary_text.substr(find_index + input_text_lower.length());
prefix_autocompletion = secondary_text.substr(0, find_index);
allowed_to_be_default_match = true;
RecordAdditionalInfo("autocompletion", "secondary & non-prefix");
return true;
}
const bool can_autocomplete_split_url =
OmniboxFieldTrial::kRichAutocompletionSplitUrlCompletion.Get() &&
input.text().size() >=
static_cast<size_t>(
OmniboxFieldTrial::kRichAutocompletionSplitCompletionMinChar
.Get());
// Try split matching (see comments for |split_autocompletion|) with
// |primary_text|.
std::vector<std::pair<size_t, size_t>> input_words;
if (can_autocomplete_split_url &&
!(input_words = FindWordsSequentiallyAtWordbreak(primary_text_lower,
input_text_lower))
.empty()) {
rich_autocompletion_triggered = true;
if (counterfactual)
return false;
split_autocompletion = SplitAutocompletion(
primary_text_lower,
TermMatchesToSelections(primary_text_lower.length(), input_words));
allowed_to_be_default_match = true;
RecordAdditionalInfo("autocompletion", "primary & split");
return true;
}
// Try split matching (see comments for |split_autocompletion|) with
// |secondary_text|.
const bool can_autocomplete_split_title =
OmniboxFieldTrial::kRichAutocompletionSplitTitleCompletion.Get() &&
input.text().size() >=
static_cast<size_t>(
OmniboxFieldTrial::kRichAutocompletionSplitCompletionMinChar
.Get());
if (can_autocomplete_split_title &&
!(input_words = FindWordsSequentiallyAtWordbreak(secondary_text_lower,
input_text_lower))
.empty()) {
rich_autocompletion_triggered = true;
if (counterfactual)
return false;
additional_text = primary_text;
split_autocompletion = SplitAutocompletion(
secondary_text_lower,
TermMatchesToSelections(secondary_text_lower.length(), input_words));
allowed_to_be_default_match = true;
RecordAdditionalInfo("autocompletion", "secondary & split");
return true;
}
return false;
}
bool AutocompleteMatch::IsEmptyAutocompletion() const {
return inline_autocompletion.empty() && prefix_autocompletion.empty() &&
split_autocompletion.Empty();
}
void AutocompleteMatch::WriteIntoTrace(perfetto::TracedValue context) const {
perfetto::TracedDictionary dict = std::move(context).WriteDictionary();
dict.Add("fill_into_edit", fill_into_edit);
dict.Add("additional_text", additional_text);
dict.Add("destination_url", destination_url);
dict.Add("keyword", keyword);
}
#if DCHECK_IS_ON()
void AutocompleteMatch::Validate() const {
std::string provider_name = provider ? provider->GetName() : "None";
ValidateClassifications(contents, contents_class, provider_name);
ValidateClassifications(description, description_class, provider_name);
ValidateClassifications(description_for_shortcuts,
description_class_for_shortcuts, provider_name);
}
#endif // DCHECK_IS_ON()
// static
void AutocompleteMatch::ValidateClassifications(
const std::u16string& text,
const ACMatchClassifications& classifications,
const std::string& provider_name) {
if (text.empty()) {
DCHECK(classifications.empty());
return;
}
// The classifications should always cover the whole string.
DCHECK(!classifications.empty()) << "No classification for \"" << text << '"';
DCHECK_EQ(0U, classifications[0].offset)
<< "Classification misses beginning for \"" << text << '"';
if (classifications.size() == 1)
return;
// The classifications should always be sorted.
size_t last_offset = classifications[0].offset;
for (auto i(classifications.begin() + 1); i != classifications.end(); ++i) {
DCHECK_GT(i->offset, last_offset)
<< " Classification for \"" << text << "\" with offset of " << i->offset
<< " is unsorted in relation to last offset of " << last_offset
<< ". Provider: " << provider_name << ".";
DCHECK_LT(i->offset, text.length())
<< " Classification of [" << i->offset << "," << text.length()
<< "] is out of bounds for \"" << text << "\". Provider: "
<< provider_name << ".";
last_offset = i->offset;
}
}
| nwjs/chromium.src | components/omnibox/browser/autocomplete_match.cc | C++ | bsd-3-clause | 58,314 |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest ; pytest
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
# External imports
# Bokeh imports
from bokeh.command.bootstrap import main
# Module under test
import bokeh.command.subcommands.secret as scsecret
#-----------------------------------------------------------------------------
# Setup
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
def test_create():
import argparse
from bokeh.command.subcommand import Subcommand
obj = scsecret.Secret(parser=argparse.ArgumentParser())
assert isinstance(obj, Subcommand)
def test_name():
assert scsecret.Secret.name == "secret"
def test_help():
assert scsecret.Secret.help == "Create a Bokeh secret key for use with Bokeh server"
def test_args():
assert scsecret.Secret.args == (
)
def test_run(capsys):
main(["bokeh", "secret"])
out, err = capsys.readouterr()
assert err == ""
assert len(out) == 45
assert out[-1] == '\n'
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
| stonebig/bokeh | bokeh/command/subcommands/tests/test_secret.py | Python | bsd-3-clause | 2,391 |
/**
* @file IdealSolidSolnPhase.cpp Implementation file for an ideal solid
* solution model with incompressible thermodynamics (see \ref
* thermoprops and \link Cantera::IdealSolidSolnPhase
* IdealSolidSolnPhase\endlink).
*/
/*
* Copyright 2006 Sandia Corporation. Under the terms of Contract
* DE-AC04-94AL85000, with Sandia Corporation, the U.S. Government
* retains certain rights in this software.
*/
#include "cantera/thermo/IdealSolidSolnPhase.h"
#include "cantera/thermo/ThermoFactory.h"
#include "cantera/base/stringUtils.h"
#include "cantera/base/ctml.h"
#include "cantera/base/utilities.h"
using namespace std;
namespace Cantera
{
IdealSolidSolnPhase::IdealSolidSolnPhase(int formGC) :
m_formGC(formGC),
m_Pref(OneAtm),
m_Pcurrent(OneAtm)
{
if (formGC < 0 || formGC > 2) {
throw CanteraError(" IdealSolidSolnPhase Constructor",
" Illegal value of formGC");
}
}
IdealSolidSolnPhase::IdealSolidSolnPhase(const std::string& inputFile,
const std::string& id_, int formGC) :
m_formGC(formGC),
m_Pref(OneAtm),
m_Pcurrent(OneAtm)
{
if (formGC < 0 || formGC > 2) {
throw CanteraError(" IdealSolidSolnPhase Constructor",
" Illegal value of formGC");
}
initThermoFile(inputFile, id_);
}
IdealSolidSolnPhase::IdealSolidSolnPhase(XML_Node& root, const std::string& id_,
int formGC) :
m_formGC(formGC),
m_Pref(OneAtm),
m_Pcurrent(OneAtm)
{
if (formGC < 0 || formGC > 2) {
throw CanteraError(" IdealSolidSolnPhase Constructor",
" Illegal value of formGC");
}
importPhase(root, this);
}
IdealSolidSolnPhase::IdealSolidSolnPhase(const IdealSolidSolnPhase& b)
{
*this = b;
}
IdealSolidSolnPhase& IdealSolidSolnPhase::operator=(const IdealSolidSolnPhase& b)
{
if (this != &b) {
ThermoPhase::operator=(b);
m_formGC = b.m_formGC;
m_Pref = b.m_Pref;
m_Pcurrent = b.m_Pcurrent;
m_speciesMolarVolume = b.m_speciesMolarVolume;
m_h0_RT = b.m_h0_RT;
m_cp0_R = b.m_cp0_R;
m_g0_RT = b.m_g0_RT;
m_s0_R = b.m_s0_R;
m_expg0_RT = b.m_expg0_RT;
m_pe = b.m_pe;
m_pp = b.m_pp;
}
return *this;
}
ThermoPhase* IdealSolidSolnPhase::duplMyselfAsThermoPhase() const
{
return new IdealSolidSolnPhase(*this);
}
int IdealSolidSolnPhase::eosType() const
{
integer res;
switch (m_formGC) {
case 0:
res = cIdealSolidSolnPhase0;
break;
case 1:
res = cIdealSolidSolnPhase1;
break;
case 2:
res = cIdealSolidSolnPhase2;
break;
default:
throw CanteraError("eosType", "Unknown type");
break;
}
return res;
}
/********************************************************************
* Molar Thermodynamic Properties of the Solution
********************************************************************/
doublereal IdealSolidSolnPhase::enthalpy_mole() const
{
doublereal htp = GasConstant * temperature() * mean_X(enthalpy_RT_ref());
return htp + (pressure() - m_Pref)/molarDensity();
}
doublereal IdealSolidSolnPhase::entropy_mole() const
{
return GasConstant * (mean_X(entropy_R_ref()) - sum_xlogx());
}
doublereal IdealSolidSolnPhase::gibbs_mole() const
{
return GasConstant * temperature() * (mean_X(gibbs_RT_ref()) + sum_xlogx());
}
doublereal IdealSolidSolnPhase::cp_mole() const
{
return GasConstant * mean_X(cp_R_ref());
}
/********************************************************************
* Mechanical Equation of State
********************************************************************/
void IdealSolidSolnPhase::calcDensity()
{
/*
* Calculate the molarVolume of the solution (m**3 kmol-1)
*/
const doublereal* const dtmp = moleFractdivMMW();
double invDens = dot(m_speciesMolarVolume.begin(),
m_speciesMolarVolume.end(), dtmp);
/*
* Set the density in the parent State object directly,
* by calling the Phase::setDensity() function.
*/
Phase::setDensity(1.0/invDens);
}
void IdealSolidSolnPhase::setDensity(const doublereal rho)
{
/*
* Unless the input density is exactly equal to the density
* calculated and stored in the State object, we throw an
* exception. This is because the density is NOT an
* independent variable.
*/
if (rho != density()) {
throw CanteraError("IdealSolidSolnPhase::setDensity",
"Density is not an independent variable");
}
}
void IdealSolidSolnPhase::setPressure(doublereal p)
{
m_Pcurrent = p;
calcDensity();
}
void IdealSolidSolnPhase::setMolarDensity(const doublereal n)
{
throw CanteraError("IdealSolidSolnPhase::setMolarDensity",
"Density is not an independent variable");
}
void IdealSolidSolnPhase::setMoleFractions(const doublereal* const x)
{
Phase::setMoleFractions(x);
calcDensity();
}
void IdealSolidSolnPhase::setMoleFractions_NoNorm(const doublereal* const x)
{
Phase::setMoleFractions(x);
calcDensity();
}
void IdealSolidSolnPhase::setMassFractions(const doublereal* const y)
{
Phase::setMassFractions(y);
calcDensity();
}
void IdealSolidSolnPhase::setMassFractions_NoNorm(const doublereal* const y)
{
Phase::setMassFractions_NoNorm(y);
calcDensity();
}
void IdealSolidSolnPhase::setConcentrations(const doublereal* const c)
{
Phase::setConcentrations(c);
calcDensity();
}
/********************************************************************
* Chemical Potentials and Activities
********************************************************************/
void IdealSolidSolnPhase::getActivityConcentrations(doublereal* c) const
{
const doublereal* const dtmp = moleFractdivMMW();
const double mmw = meanMolecularWeight();
switch (m_formGC) {
case 0:
for (size_t k = 0; k < m_kk; k++) {
c[k] = dtmp[k] * mmw;
}
break;
case 1:
for (size_t k = 0; k < m_kk; k++) {
c[k] = dtmp[k] * mmw / m_speciesMolarVolume[k];
}
break;
case 2:
double atmp = mmw / m_speciesMolarVolume[m_kk-1];
for (size_t k = 0; k < m_kk; k++) {
c[k] = dtmp[k] * atmp;
}
break;
}
}
doublereal IdealSolidSolnPhase::standardConcentration(size_t k) const
{
switch (m_formGC) {
case 0:
return 1.0;
case 1:
return 1.0 / m_speciesMolarVolume[k];
case 2:
return 1.0/m_speciesMolarVolume[m_kk-1];
}
return 0.0;
}
doublereal IdealSolidSolnPhase::referenceConcentration(int k) const
{
switch (m_formGC) {
case 0:
return 1.0;
case 1:
return 1.0 / m_speciesMolarVolume[k];
case 2:
return 1.0 / m_speciesMolarVolume[m_kk-1];
}
return 0.0;
}
doublereal IdealSolidSolnPhase::logStandardConc(size_t k) const
{
_updateThermo();
double res;
switch (m_formGC) {
case 0:
res = 0.0;
break;
case 1:
res = log(1.0/m_speciesMolarVolume[k]);
break;
case 2:
res = log(1.0/m_speciesMolarVolume[m_kk-1]);
break;
default:
throw CanteraError("eosType", "Unknown type");
break;
}
return res;
}
void IdealSolidSolnPhase::getActivityCoefficients(doublereal* ac) const
{
for (size_t k = 0; k < m_kk; k++) {
ac[k] = 1.0;
}
}
void IdealSolidSolnPhase::getChemPotentials(doublereal* mu) const
{
doublereal delta_p = m_Pcurrent - m_Pref;
const vector_fp& g_RT = gibbs_RT_ref();
for (size_t k = 0; k < m_kk; k++) {
double xx = std::max(SmallNumber, moleFraction(k));
mu[k] = RT() * (g_RT[k] + log(xx))
+ delta_p * m_speciesMolarVolume[k];
}
}
void IdealSolidSolnPhase::getChemPotentials_RT(doublereal* mu) const
{
doublereal delta_pdRT = (m_Pcurrent - m_Pref) / (temperature() * GasConstant);
const vector_fp& g_RT = gibbs_RT_ref();
for (size_t k = 0; k < m_kk; k++) {
double xx = std::max(SmallNumber, moleFraction(k));
mu[k] = (g_RT[k] + log(xx))
+ delta_pdRT * m_speciesMolarVolume[k];
}
}
/********************************************************************
* Partial Molar Properties
********************************************************************/
void IdealSolidSolnPhase::getPartialMolarEnthalpies(doublereal* hbar) const
{
const vector_fp& _h = enthalpy_RT_ref();
scale(_h.begin(), _h.end(), hbar, GasConstant * temperature());
}
void IdealSolidSolnPhase::getPartialMolarEntropies(doublereal* sbar) const
{
const vector_fp& _s = entropy_R_ref();
for (size_t k = 0; k < m_kk; k++) {
double xx = std::max(SmallNumber, moleFraction(k));
sbar[k] = GasConstant * (_s[k] - log(xx));
}
}
void IdealSolidSolnPhase::getPartialMolarCp(doublereal* cpbar) const
{
getCp_R(cpbar);
for (size_t k = 0; k < m_kk; k++) {
cpbar[k] *= GasConstant;
}
}
void IdealSolidSolnPhase::getPartialMolarVolumes(doublereal* vbar) const
{
getStandardVolumes(vbar);
}
/*****************************************************************
* Properties of the Standard State of the Species in the Solution
*****************************************************************/
void IdealSolidSolnPhase::getPureGibbs(doublereal* gpure) const
{
const vector_fp& gibbsrt = gibbs_RT_ref();
const doublereal* const gk = DATA_PTR(gibbsrt);
doublereal delta_p = (m_Pcurrent - m_Pref);
for (size_t k = 0; k < m_kk; k++) {
gpure[k] = RT() * gk[k] + delta_p * m_speciesMolarVolume[k];
}
}
void IdealSolidSolnPhase::getGibbs_RT(doublereal* grt) const
{
const vector_fp& gibbsrt = gibbs_RT_ref();
const doublereal* const gk = DATA_PTR(gibbsrt);
doublereal delta_prt = (m_Pcurrent - m_Pref)/ RT();
for (size_t k = 0; k < m_kk; k++) {
grt[k] = gk[k] + delta_prt * m_speciesMolarVolume[k];
}
}
void IdealSolidSolnPhase::getEnthalpy_RT(doublereal* hrt) const
{
const vector_fp& _h = enthalpy_RT_ref();
doublereal delta_prt = (m_Pcurrent - m_Pref) / RT();
for (size_t k = 0; k < m_kk; k++) {
hrt[k] = _h[k] + delta_prt * m_speciesMolarVolume[k];
}
}
void IdealSolidSolnPhase::getEntropy_R(doublereal* sr) const
{
const vector_fp& _s = entropy_R_ref();
copy(_s.begin(), _s.end(), sr);
}
void IdealSolidSolnPhase::getIntEnergy_RT(doublereal* urt) const
{
const vector_fp& _h = enthalpy_RT_ref();
doublereal prefrt = m_Pref / (GasConstant * temperature());
for (size_t k = 0; k < m_kk; k++) {
urt[k] = _h[k] - prefrt * m_speciesMolarVolume[k];
}
}
void IdealSolidSolnPhase::getCp_R(doublereal* cpr) const
{
const vector_fp& _cpr = cp_R_ref();
copy(_cpr.begin(), _cpr.end(), cpr);
}
void IdealSolidSolnPhase::getStandardVolumes(doublereal* vol) const
{
copy(m_speciesMolarVolume.begin(), m_speciesMolarVolume.end(), vol);
}
/*********************************************************************
* Thermodynamic Values for the Species Reference States
*********************************************************************/
void IdealSolidSolnPhase::getEnthalpy_RT_ref(doublereal* hrt) const
{
_updateThermo();
for (size_t k = 0; k != m_kk; k++) {
hrt[k] = m_h0_RT[k];
}
}
void IdealSolidSolnPhase::getGibbs_RT_ref(doublereal* grt) const
{
_updateThermo();
for (size_t k = 0; k != m_kk; k++) {
grt[k] = m_g0_RT[k];
}
}
void IdealSolidSolnPhase::getGibbs_ref(doublereal* g) const
{
_updateThermo();
double tmp = GasConstant * temperature();
for (size_t k = 0; k != m_kk; k++) {
g[k] = tmp * m_g0_RT[k];
}
}
void IdealSolidSolnPhase::getIntEnergy_RT_ref(doublereal* urt) const
{
const vector_fp& _h = enthalpy_RT_ref();
doublereal prefrt = m_Pref / (GasConstant * temperature());
for (size_t k = 0; k < m_kk; k++) {
urt[k] = _h[k] - prefrt * m_speciesMolarVolume[k];
}
}
void IdealSolidSolnPhase::getEntropy_R_ref(doublereal* er) const
{
_updateThermo();
for (size_t k = 0; k != m_kk; k++) {
er[k] = m_s0_R[k];
}
}
void IdealSolidSolnPhase::getCp_R_ref(doublereal* cpr) const
{
_updateThermo();
for (size_t k = 0; k != m_kk; k++) {
cpr[k] = m_cp0_R[k];
}
}
const vector_fp& IdealSolidSolnPhase::enthalpy_RT_ref() const
{
_updateThermo();
return m_h0_RT;
}
const vector_fp& IdealSolidSolnPhase::entropy_R_ref() const
{
_updateThermo();
return m_s0_R;
}
/*********************************************************************
* Utility Functions
*********************************************************************/
void IdealSolidSolnPhase::initThermoXML(XML_Node& phaseNode, const std::string& id_)
{
if (id_.size() > 0 && phaseNode.id() != id_) {
throw CanteraError("IdealSolidSolnPhase::initThermoXML",
"phasenode and Id are incompatible");
}
/*
* Check on the thermo field. Must have:
* <thermo model="IdealSolidSolution" />
*/
if (phaseNode.hasChild("thermo")) {
XML_Node& thNode = phaseNode.child("thermo");
string mString = thNode.attrib("model");
if (lowercase(mString) != "idealsolidsolution") {
throw CanteraError("IdealSolidSolnPhase::initThermoXML",
"Unknown thermo model: " + mString);
}
} else {
throw CanteraError("IdealSolidSolnPhase::initThermoXML",
"Unspecified thermo model");
}
/*
* Form of the standard concentrations. Must have one of:
*
* <standardConc model="unity" />
* <standardConc model="molar_volume" />
* <standardConc model="solvent_volume" />
*/
if (phaseNode.hasChild("standardConc")) {
XML_Node& scNode = phaseNode.child("standardConc");
string formStringa = scNode.attrib("model");
string formString = lowercase(formStringa);
if (formString == "unity") {
m_formGC = 0;
} else if (formString == "molar_volume") {
m_formGC = 1;
} else if (formString == "solvent_volume") {
m_formGC = 2;
} else {
throw CanteraError("IdealSolidSolnPhase::initThermoXML",
"Unknown standardConc model: " + formStringa);
}
} else {
throw CanteraError("IdealSolidSolnPhase::initThermoXML",
"Unspecified standardConc model");
}
/*
* Initialize all of the lengths now that we know how many species
* there are in the phase.
*/
initLengths();
/*
* Now go get the molar volumes
*/
XML_Node& speciesList = phaseNode.child("speciesArray");
XML_Node* speciesDB = get_XML_NameID("speciesData", speciesList["datasrc"],
&phaseNode.root());
for (size_t k = 0; k < m_kk; k++) {
XML_Node* s = speciesDB->findByAttr("name", speciesName(k));
XML_Node* ss = s->findByName("standardState");
m_speciesMolarVolume[k] = getFloat(*ss, "molarVolume", "toSI");
}
/*
* Call the base initThermo, which handles setting the initial
* state.
*/
ThermoPhase::initThermoXML(phaseNode, id_);
}
void IdealSolidSolnPhase::initLengths()
{
/*
* Obtain the reference pressure by calling the ThermoPhase
* function refPressure, which in turn calls the
* species thermo reference pressure function of the
* same name.
*/
m_Pref = refPressure();
m_h0_RT.resize(m_kk);
m_g0_RT.resize(m_kk);
m_expg0_RT.resize(m_kk);
m_cp0_R.resize(m_kk);
m_s0_R.resize(m_kk);
m_pe.resize(m_kk, 0.0);
m_pp.resize(m_kk);
m_speciesMolarVolume.resize(m_kk);
}
void IdealSolidSolnPhase::setToEquilState(const doublereal* lambda_RT)
{
const vector_fp& grt = gibbs_RT_ref();
// set the pressure and composition to be consistent with
// the temperature,
doublereal pres = 0.0;
for (size_t k = 0; k < m_kk; k++) {
m_pp[k] = -grt[k];
for (size_t m = 0; m < nElements(); m++) {
m_pp[k] += nAtoms(k,m)*lambda_RT[m];
}
m_pp[k] = m_Pref * exp(m_pp[k]);
pres += m_pp[k];
}
setState_PX(pres, &m_pp[0]);
}
double IdealSolidSolnPhase::speciesMolarVolume(int k) const
{
return m_speciesMolarVolume[k];
}
void IdealSolidSolnPhase::getSpeciesMolarVolumes(doublereal* smv) const
{
copy(m_speciesMolarVolume.begin(), m_speciesMolarVolume.end(), smv);
}
void IdealSolidSolnPhase::_updateThermo() const
{
doublereal tnow = temperature();
if (m_tlast != tnow) {
/*
* Update the thermodynamic functions of the reference state.
*/
m_spthermo->update(tnow, DATA_PTR(m_cp0_R), DATA_PTR(m_h0_RT),
DATA_PTR(m_s0_R));
m_tlast = tnow;
doublereal rrt = 1.0 / (GasConstant * tnow);
for (size_t k = 0; k < m_kk; k++) {
double deltaE = rrt * m_pe[k];
m_h0_RT[k] += deltaE;
m_g0_RT[k] = m_h0_RT[k] - m_s0_R[k];
}
m_tlast = tnow;
}
}
} // end namespace Cantera
| Heathckliff/cantera | src/thermo/IdealSolidSolnPhase.cpp | C++ | bsd-3-clause | 17,406 |
/*
Copyright (c) 2012-2013, Arvid Norberg
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 author 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.
*/
#include "libtorrent/torrent_peer.hpp"
#include "libtorrent/assert.hpp"
#include "libtorrent/string_util.hpp"
#include "libtorrent/peer_connection.hpp"
#include "libtorrent/crc32c.hpp"
#include "libtorrent/ip_voter.hpp"
namespace libtorrent
{
void apply_mask(boost::uint8_t* b, boost::uint8_t const* mask, int size)
{
for (int i = 0; i < size; ++i)
{
*b &= *mask;
++b;
++mask;
}
}
// 1. if the IP addresses are identical, hash the ports in 16 bit network-order
// binary representation, ordered lowest first.
// 2. if the IPs are in the same /24, hash the IPs ordered, lowest first.
// 3. if the IPs are in the ame /16, mask the IPs by 0xffffff55, hash them
// ordered, lowest first.
// 4. if IPs are not in the same /16, mask the IPs by 0xffff5555, hash them
// ordered, lowest first.
//
// * for IPv6 peers, just use the first 64 bits and widen the masks.
// like this: 0xffff5555 -> 0xffffffff55555555
// the lower 64 bits are always unmasked
//
// * for IPv6 addresses, compare /32 and /48 instead of /16 and /24
//
// * the two IP addresses that are used to calculate the rank must
// always be of the same address family
//
// * all IP addresses are in network byte order when hashed
boost::uint32_t peer_priority(tcp::endpoint e1, tcp::endpoint e2)
{
TORRENT_ASSERT(e1.address().is_v4() == e2.address().is_v4());
using std::swap;
boost::uint32_t ret;
if (e1.address() == e2.address())
{
if (e1.port() > e2.port())
swap(e1, e2);
boost::uint32_t p;
reinterpret_cast<boost::uint16_t*>(&p)[0] = htons(e1.port());
reinterpret_cast<boost::uint16_t*>(&p)[1] = htons(e2.port());
ret = crc32c_32(p);
}
#if TORRENT_USE_IPV6
else if (e1.address().is_v6())
{
const static boost::uint8_t v6mask[][8] = {
{ 0xff, 0xff, 0xff, 0xff, 0x55, 0x55, 0x55, 0x55 },
{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x55, 0x55 },
{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }
};
if (e1 > e2) swap(e1, e2);
address_v6::bytes_type b1 = e1.address().to_v6().to_bytes();
address_v6::bytes_type b2 = e2.address().to_v6().to_bytes();
int mask = memcmp(&b1[0], &b2[0], 4) ? 0
: memcmp(&b1[0], &b2[0], 6) ? 1 : 2;
apply_mask(&b1[0], v6mask[mask], 8);
apply_mask(&b2[0], v6mask[mask], 8);
boost::uint64_t addrbuf[4];
memcpy(&addrbuf[0], &b1[0], 16);
memcpy(&addrbuf[2], &b2[0], 16);
ret = crc32c(addrbuf, 4);
}
#endif
else
{
const static boost::uint8_t v4mask[][4] = {
{ 0xff, 0xff, 0x55, 0x55 },
{ 0xff, 0xff, 0xff, 0x55 },
{ 0xff, 0xff, 0xff, 0xff }
};
if (e1 > e2) swap(e1, e2);
address_v4::bytes_type b1 = e1.address().to_v4().to_bytes();
address_v4::bytes_type b2 = e2.address().to_v4().to_bytes();
int mask = memcmp(&b1[0], &b2[0], 2) ? 0
: memcmp(&b1[0], &b2[0], 3) ? 1 : 2;
apply_mask(&b1[0], v4mask[mask], 4);
apply_mask(&b2[0], v4mask[mask], 4);
boost::uint64_t addrbuf;
memcpy(&addrbuf, &b1[0], 4);
memcpy(reinterpret_cast<char*>(&addrbuf) + 4, &b2[0], 4);
ret = crc32c(&addrbuf, 1);
}
return ret;
}
torrent_peer::torrent_peer(boost::uint16_t port, bool conn, int src)
: prev_amount_upload(0)
, prev_amount_download(0)
, connection(0)
, peer_rank(0)
, last_optimistically_unchoked(0)
, last_connected(0)
, port(port)
, hashfails(0)
, failcount(0)
, connectable(conn)
, optimistically_unchoked(false)
, seed(false)
, fast_reconnects(0)
, trust_points(0)
, source(src)
#if !defined(TORRENT_DISABLE_ENCRYPTION) && !defined(TORRENT_DISABLE_EXTENSIONS)
// assume no support in order to
// prefer opening non-encrypyed
// connections. If it fails, we'll
// retry with encryption
, pe_support(false)
#endif
#if TORRENT_USE_IPV6
, is_v6_addr(false)
#endif
#if TORRENT_USE_I2P
, is_i2p_addr(false)
#endif
, on_parole(false)
, banned(false)
, supports_utp(true) // assume peers support utp
, confirmed_supports_utp(false)
, supports_holepunch(false)
, web_seed(false)
#if TORRENT_USE_ASSERTS
, in_use(false)
#endif
{
TORRENT_ASSERT((src & 0xff) == src);
}
boost::uint32_t torrent_peer::rank(external_ip const& external, int external_port) const
{
//TODO: how do we deal with our external address changing?
if (peer_rank == 0)
peer_rank = peer_priority(
tcp::endpoint(external.external_address(this->address()), external_port)
, tcp::endpoint(this->address(), this->port));
return peer_rank;
}
boost::uint64_t torrent_peer::total_download() const
{
if (connection != 0)
{
TORRENT_ASSERT(prev_amount_download == 0);
return connection->statistics().total_payload_download();
}
else
{
return boost::uint64_t(prev_amount_download) << 10;
}
}
boost::uint64_t torrent_peer::total_upload() const
{
if (connection != 0)
{
TORRENT_ASSERT(prev_amount_upload == 0);
return connection->statistics().total_payload_upload();
}
else
{
return boost::uint64_t(prev_amount_upload) << 10;
}
}
ipv4_peer::ipv4_peer(
tcp::endpoint const& ep, bool c, int src
)
: torrent_peer(ep.port(), c, src)
, addr(ep.address().to_v4())
{
#if TORRENT_USE_IPV6
is_v6_addr = false;
#endif
#if TORRENT_USE_I2P
is_i2p_addr = false;
#endif
}
#if TORRENT_USE_I2P
i2p_peer::i2p_peer(char const* dest, bool connectable, int src)
: torrent_peer(0, connectable, src), destination(allocate_string_copy(dest))
{
#if TORRENT_USE_IPV6
is_v6_addr = false;
#endif
is_i2p_addr = true;
}
i2p_peer::~i2p_peer()
{ free(destination); }
#endif // TORRENT_USE_I2P
#if TORRENT_USE_IPV6
ipv6_peer::ipv6_peer(
tcp::endpoint const& ep, bool c, int src
)
: torrent_peer(ep.port(), c, src)
, addr(ep.address().to_v6().to_bytes())
{
is_v6_addr = true;
#if TORRENT_USE_I2P
is_i2p_addr = false;
#endif
}
#endif // TORRENT_USE_IPV6
#if TORRENT_USE_I2P
char const* torrent_peer::dest() const
{
if (is_i2p_addr)
return static_cast<i2p_peer const*>(this)->destination;
return "";
}
#endif
libtorrent::address torrent_peer::address() const
{
#if TORRENT_USE_IPV6
if (is_v6_addr)
return libtorrent::address_v6(
static_cast<ipv6_peer const*>(this)->addr);
else
#endif
#if TORRENT_USE_I2P
if (is_i2p_addr) return libtorrent::address();
else
#endif
return static_cast<ipv4_peer const*>(this)->addr;
}
}
| mirror/libtorrent | src/torrent_peer.cpp | C++ | bsd-3-clause | 7,842 |
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// This package is generated by client-gen with arguments: --clientset-name=release_1_5 --input=[api/v1,apps/v1alpha1,authentication/v1beta1,authorization/v1beta1,autoscaling/v1,batch/v1,certificates/v1alpha1,extensions/v1beta1,policy/v1alpha1,rbac/v1alpha1,storage/v1beta1]
// This package has the automatically generated typed clients.
package v1
| jnewland/kops | vendor/k8s.io/kubernetes/staging/src/k8s.io/client-go/1.5/kubernetes/typed/core/v1/doc.go | GO | apache-2.0 | 921 |
'use strict';
describe('onDisconnect', function() {
var fireproof;
beforeEach(function() {
fireproof = new Fireproof(firebase);
});
describe('#set', function() {
it('promises to set the ref to the specified value on disconnect', function() {
return fireproof
.child('odSet')
.onDisconnect()
.set(true)
.then(function() {
Firebase.goOffline();
Firebase.goOnline();
return fireproof.child('odSet');
})
.then(function(snap) {
expect(snap.val()).to.equal(true);
});
});
});
describe('#remove', function() {
it('promises to remove the data at specified ref on disconnect', function() {
return fireproof
.child('odSet')
.onDisconnect()
.remove()
.then(function() {
Firebase.goOffline();
Firebase.goOnline();
return fireproof.child('odSet');
})
.then(function(snap) {
expect(snap.val()).to.equal(null);
});
});
});
describe('#setWithPriority', function() {
it('promises to set the ref to a value/priority on disconnect', function() {
return fireproof
.child('odSet')
.onDisconnect()
.setWithPriority(true, 5)
.then(function() {
Firebase.goOffline();
Firebase.goOnline();
return fireproof.child('odSet');
})
.then(function(snap) {
expect(snap.val()).to.equal(true);
expect(snap.getPriority()).to.equal(5);
});
});
});
describe('#update', function() {
it('promises to update the ref with the given values on disconnect', function() {
return fireproof
.child('odUpdate')
.set({ foo: 'bar', baz: 'quux' })
.then(function() {
return fireproof
.child('odUpdate')
.onDisconnect()
.update({ baz: 'bells', whistles: true });
})
.then(function() {
Firebase.goOffline();
Firebase.goOnline();
return fireproof.child('odUpdate');
})
.then(function(snap) {
expect(snap.val()).to.deep.equal({
foo: 'bar',
baz: 'bells',
whistles: true
});
});
});
});
describe('#cancel', function() {
it('promises to cancel all onDisconnect operations at the ref', function() {
return fireproof.child('odCancel')
.onDisconnect().set({ foo: 'bar '})
.then(function() {
return fireproof.child('odCancel')
.onDisconnect().cancel();
})
.then(function() {
Firebase.goOffline();
Firebase.goOnline();
return fireproof.child('odCancel');
})
.then(function(snap) {
expect(snap.val()).to.equal(null);
});
});
});
});
| airdrummingfool/fireproof | test/spec/lib/on-disconnect.js | JavaScript | isc | 2,784 |
using System.Linq.Expressions;
namespace AutoMapper.Mappers
{
using System.Linq;
using System.Reflection;
using Configuration;
public class ImplicitConversionOperatorMapper : IObjectMapExpression
{
public object Map(ResolutionContext context)
{
var implicitOperator = GetImplicitConversionOperator(context.Types);
return implicitOperator.Invoke(null, new[] {context.SourceValue});
}
public bool IsMatch(TypePair context)
{
var methodInfo = GetImplicitConversionOperator(context);
return methodInfo != null;
}
private static MethodInfo GetImplicitConversionOperator(TypePair context)
{
var destinationType = context.DestinationType;
if(destinationType.IsNullableType())
{
destinationType = destinationType.GetTypeOfNullable();
}
var sourceTypeMethod = context.SourceType
.GetDeclaredMethods()
.FirstOrDefault(mi => mi.IsPublic && mi.IsStatic && mi.Name == "op_Implicit" && mi.ReturnType == destinationType);
return sourceTypeMethod ?? destinationType.GetMethod("op_Implicit", new[] { context.SourceType });
}
public Expression MapExpression(Expression sourceExpression, Expression destExpression, Expression contextExpression)
{
var implicitOperator = GetImplicitConversionOperator(new TypePair(sourceExpression.Type, destExpression.Type));
return Expression.Call(null, implicitOperator, sourceExpression);
}
}
} | jbogard/AutoMapper | src/AutoMapper/Mappers/ImplicitConversionOperatorMapper.cs | C# | mit | 1,677 |
<?php
namespace ZEDx\Console\Commands\Module;
use File;
use Illuminate\Console\Command;
use Modules;
use ZEDx\Console\Commands\Module\Generators\FileAlreadyExistException;
use ZEDx\Console\Commands\Module\Generators\FileGenerator;
abstract class GeneratorCommand extends Command
{
/**
* The name of 'name' argument.
*
* @var string
*/
protected $argumentName = '';
/**
* Get template contents.
*
* @return string
*/
abstract protected function getTemplateContents();
/**
* Get the destination file path.
*
* @return string
*/
abstract protected function getDestinationFilePath();
/**
* Execute the console command.
*/
public function fire()
{
$path = str_replace('\\', '/', $this->getDestinationFilePath());
if (!File::isDirectory($dir = dirname($path))) {
File::makeDirectory($dir, 0777, true);
}
$contents = $this->getTemplateContents();
try {
with(new FileGenerator($path, $contents))->generate();
$this->info("Created : {$path}");
} catch (FileAlreadyExistException $e) {
$this->error("File : {$path} already exists.");
}
}
/**
* Get class name.
*
* @return string
*/
public function getClass()
{
return class_basename($this->argument($this->argumentName));
}
/**
* Get default namespace.
*
* @return string
*/
public function getDefaultNamespace()
{
return '';
}
/**
* Get class namespace.
*
* @param Module $module
*
* @return string
*/
public function getClassNamespace($module)
{
$extra = str_replace($this->getClass(), '', $this->argument($this->argumentName));
$extra = str_replace('/', '\\', $extra);
$namespace = Modules::config('namespace');
$namespace .= '\\'.$module->getStudlyName();
$namespace .= '\\'.$this->getDefaultNamespace();
$namespace .= '\\'.$extra;
return rtrim($namespace, '\\');
}
}
| zorx/core | src/Console/Commands/Module/GeneratorCommand.php | PHP | mit | 2,135 |
package de.danoeh.antennapod.preferences;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceScreen;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import de.danoeh.antennapod.BuildConfig;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.activity.AboutActivity;
import de.danoeh.antennapod.activity.DirectoryChooserActivity;
import de.danoeh.antennapod.activity.MainActivity;
import de.danoeh.antennapod.activity.PreferenceActivity;
import de.danoeh.antennapod.activity.PreferenceActivityGingerbread;
import de.danoeh.antennapod.asynctask.OpmlExportWorker;
import de.danoeh.antennapod.core.preferences.GpodnetPreferences;
import de.danoeh.antennapod.core.preferences.UserPreferences;
import de.danoeh.antennapod.core.util.flattr.FlattrUtils;
import de.danoeh.antennapod.dialog.AuthenticationDialog;
import de.danoeh.antennapod.dialog.AutoFlattrPreferenceDialog;
import de.danoeh.antennapod.dialog.GpodnetSetHostnameDialog;
import de.danoeh.antennapod.dialog.VariableSpeedDialog;
/**
* Sets up a preference UI that lets the user change user preferences.
*/
public class PreferenceController {
private static final String TAG = "PreferenceController";
public static final String PREF_FLATTR_SETTINGS = "prefFlattrSettings";
public static final String PREF_FLATTR_AUTH = "pref_flattr_authenticate";
public static final String PREF_FLATTR_REVOKE = "prefRevokeAccess";
public static final String PREF_AUTO_FLATTR_PREFS = "prefAutoFlattrPrefs";
public static final String PREF_OPML_EXPORT = "prefOpmlExport";
public static final String PREF_ABOUT = "prefAbout";
public static final String PREF_CHOOSE_DATA_DIR = "prefChooseDataDir";
public static final String AUTO_DL_PREF_SCREEN = "prefAutoDownloadSettings";
public static final String PREF_PLAYBACK_SPEED_LAUNCHER = "prefPlaybackSpeedLauncher";
public static final String PREF_GPODNET_LOGIN = "pref_gpodnet_authenticate";
public static final String PREF_GPODNET_SETLOGIN_INFORMATION = "pref_gpodnet_setlogin_information";
public static final String PREF_GPODNET_LOGOUT = "pref_gpodnet_logout";
public static final String PREF_GPODNET_HOSTNAME = "pref_gpodnet_hostname";
public static final String PREF_EXPANDED_NOTIFICATION = "prefExpandNotify";
private final PreferenceUI ui;
private CheckBoxPreference[] selectedNetworks;
public PreferenceController(PreferenceUI ui) {
this.ui = ui;
}
/**
* Returns the preference activity that should be used on this device.
*
* @return PreferenceActivity if the API level is greater than 10, PreferenceActivityGingerbread otherwise.
*/
public static Class getPreferenceActivity() {
if (Build.VERSION.SDK_INT > 10) {
return PreferenceActivity.class;
} else {
return PreferenceActivityGingerbread.class;
}
}
public void onCreate() {
final Activity activity = ui.getActivity();
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
// disable expanded notification option on unsupported android versions
ui.findPreference(PreferenceController.PREF_EXPANDED_NOTIFICATION).setEnabled(false);
ui.findPreference(PreferenceController.PREF_EXPANDED_NOTIFICATION).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
Toast toast = Toast.makeText(activity, R.string.pref_expand_notify_unsupport_toast, Toast.LENGTH_SHORT);
toast.show();
return true;
}
}
);
}
ui.findPreference(PreferenceController.PREF_FLATTR_REVOKE).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
FlattrUtils.revokeAccessToken(activity);
checkItemVisibility();
return true;
}
}
);
ui.findPreference(PreferenceController.PREF_ABOUT).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
activity.startActivity(new Intent(
activity, AboutActivity.class));
return true;
}
}
);
ui.findPreference(PreferenceController.PREF_OPML_EXPORT).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
new OpmlExportWorker(activity)
.executeAsync();
return true;
}
}
);
ui.findPreference(PreferenceController.PREF_CHOOSE_DATA_DIR).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
activity.startActivityForResult(
new Intent(activity,
DirectoryChooserActivity.class),
DirectoryChooserActivity.RESULT_CODE_DIR_SELECTED
);
return true;
}
}
);
ui.findPreference(UserPreferences.PREF_THEME)
.setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(
Preference preference, Object newValue) {
Intent i = new Intent(activity, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NEW_TASK);
activity.finish();
activity.startActivity(i);
return true;
}
}
);
ui.findPreference(UserPreferences.PREF_HIDDEN_DRAWER_ITEMS)
.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
showDrawerPreferencesDialog();
return true;
}
});
ui.findPreference(UserPreferences.PREF_UPDATE_INTERVAL)
.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
showUpdateIntervalTimePreferencesDialog();
return true;
}
});
ui.findPreference(UserPreferences.PREF_ENABLE_AUTODL)
.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (newValue instanceof Boolean) {
ui.findPreference(UserPreferences.PREF_ENABLE_AUTODL_WIFI_FILTER).setEnabled((Boolean) newValue);
setSelectedNetworksEnabled((Boolean) newValue && UserPreferences.isEnableAutodownloadWifiFilter());
ui.findPreference(UserPreferences.PREF_ENABLE_AUTODL_ON_BATTERY).setEnabled((Boolean) newValue);
}
return true;
}
});
ui.findPreference(UserPreferences.PREF_ENABLE_AUTODL_WIFI_FILTER)
.setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(
Preference preference, Object newValue) {
if (newValue instanceof Boolean) {
setSelectedNetworksEnabled((Boolean) newValue);
return true;
} else {
return false;
}
}
}
);
ui.findPreference(UserPreferences.PREF_PARALLEL_DOWNLOADS)
.setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
if (o instanceof String) {
try {
int value = Integer.valueOf((String) o);
if (1 <= value && value <= 50) {
setParallelDownloadsText(value);
return true;
}
} catch(NumberFormatException e) {
return false;
}
}
return false;
}
}
);
// validate and set correct value: number of downloads between 1 and 50 (inclusive)
final EditText ev = ((EditTextPreference)ui.findPreference(UserPreferences.PREF_PARALLEL_DOWNLOADS)).getEditText();
ev.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
if(s.length() > 0) {
try {
int value = Integer.valueOf(s.toString());
if (value <= 0) {
ev.setText("1");
} else if (value > 50) {
ev.setText("50");
}
} catch(NumberFormatException e) {
ev.setText("6");
}
ev.setSelection(ev.getText().length());
}
}
});
ui.findPreference(UserPreferences.PREF_EPISODE_CACHE_SIZE)
.setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
if (o instanceof String) {
setEpisodeCacheSizeText(UserPreferences.readEpisodeCacheSize((String) o));
}
return true;
}
}
);
ui.findPreference(PreferenceController.PREF_PLAYBACK_SPEED_LAUNCHER)
.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
VariableSpeedDialog.showDialog(activity);
return true;
}
});
ui.findPreference(PreferenceController.PREF_GPODNET_SETLOGIN_INFORMATION).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
AuthenticationDialog dialog = new AuthenticationDialog(activity,
R.string.pref_gpodnet_setlogin_information_title, false, false, GpodnetPreferences.getUsername(),
null) {
@Override
protected void onConfirmed(String username, String password, boolean saveUsernamePassword) {
GpodnetPreferences.setPassword(password);
}
};
dialog.show();
return true;
}
});
ui.findPreference(PreferenceController.PREF_GPODNET_LOGOUT).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
GpodnetPreferences.logout();
Toast toast = Toast.makeText(activity, R.string.pref_gpodnet_logout_toast, Toast.LENGTH_SHORT);
toast.show();
updateGpodnetPreferenceScreen();
return true;
}
});
ui.findPreference(PreferenceController.PREF_GPODNET_HOSTNAME).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
GpodnetSetHostnameDialog.createDialog(activity).setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
updateGpodnetPreferenceScreen();
}
});
return true;
}
});
ui.findPreference(PreferenceController.PREF_AUTO_FLATTR_PREFS).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
AutoFlattrPreferenceDialog.newAutoFlattrPreferenceDialog(activity,
new AutoFlattrPreferenceDialog.AutoFlattrPreferenceDialogInterface() {
@Override
public void onCancelled() {
}
@Override
public void onConfirmed(boolean autoFlattrEnabled, float autoFlattrValue) {
UserPreferences.setAutoFlattrSettings(autoFlattrEnabled, autoFlattrValue);
checkItemVisibility();
}
});
return true;
}
});
ui.findPreference(UserPreferences.PREF_IMAGE_CACHE_SIZE)
.setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
if (o instanceof String) {
int newValue = Integer.valueOf((String) o) * 1024 * 1024;
if(newValue != UserPreferences.getImageCacheSize()) {
AlertDialog.Builder dialog = new AlertDialog.Builder(ui.getActivity());
dialog.setTitle(android.R.string.dialog_alert_title);
dialog.setMessage(R.string.pref_restart_required);
dialog.setPositiveButton(android.R.string.ok, null);
dialog.show();
}
return true;
}
return false;
}
}
);
buildSmartMarkAsPlayedPreference();
buildAutodownloadSelectedNetworsPreference();
setSelectedNetworksEnabled(UserPreferences
.isEnableAutodownloadWifiFilter());
}
public void onResume() {
checkItemVisibility();
setParallelDownloadsText(UserPreferences.getParallelDownloads());
setEpisodeCacheSizeText(UserPreferences.getEpisodeCacheSize());
setDataFolderText();
updateGpodnetPreferenceScreen();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == DirectoryChooserActivity.RESULT_CODE_DIR_SELECTED) {
String dir = data
.getStringExtra(DirectoryChooserActivity.RESULT_SELECTED_DIR);
if (BuildConfig.DEBUG)
Log.d(TAG, "Setting data folder");
UserPreferences.setDataFolder(dir);
}
}
private void updateGpodnetPreferenceScreen() {
final boolean loggedIn = GpodnetPreferences.loggedIn();
ui.findPreference(PreferenceController.PREF_GPODNET_LOGIN).setEnabled(!loggedIn);
ui.findPreference(PreferenceController.PREF_GPODNET_SETLOGIN_INFORMATION).setEnabled(loggedIn);
ui.findPreference(PreferenceController.PREF_GPODNET_LOGOUT).setEnabled(loggedIn);
ui.findPreference(PreferenceController.PREF_GPODNET_HOSTNAME).setSummary(GpodnetPreferences.getHostname());
}
private String[] getUpdateIntervalEntries(final String[] values) {
final Resources res = ui.getActivity().getResources();
String[] entries = new String[values.length];
for (int x = 0; x < values.length; x++) {
Integer v = Integer.parseInt(values[x]);
switch (v) {
case 0:
entries[x] = res.getString(R.string.pref_update_interval_hours_manual);
break;
case 1:
entries[x] = v + " " + res.getString(R.string.pref_update_interval_hours_singular);
break;
default:
entries[x] = v + " " + res.getString(R.string.pref_update_interval_hours_plural);
break;
}
}
return entries;
}
private void buildSmartMarkAsPlayedPreference() {
final Resources res = ui.getActivity().getResources();
ListPreference pref = (ListPreference) ui.findPreference(UserPreferences.PREF_SMART_MARK_AS_PLAYED_SECS);
String[] values = res.getStringArray(
R.array.smart_mark_as_played_values);
String[] entries = new String[values.length];
for (int x = 0; x < values.length; x++) {
if(x == 0) {
entries[x] = res.getString(R.string.pref_smart_mark_as_played_disabled);
} else {
Integer v = Integer.parseInt(values[x]);
entries[x] = res.getQuantityString(R.plurals.time_seconds_quantified, v, v);
}
}
pref.setEntries(entries);
}
private void setSelectedNetworksEnabled(boolean b) {
if (selectedNetworks != null) {
for (Preference p : selectedNetworks) {
p.setEnabled(b);
}
}
}
@SuppressWarnings("deprecation")
private void checkItemVisibility() {
boolean hasFlattrToken = FlattrUtils.hasToken();
ui.findPreference(PreferenceController.PREF_FLATTR_SETTINGS).setEnabled(FlattrUtils.hasAPICredentials());
ui.findPreference(PreferenceController.PREF_FLATTR_AUTH).setEnabled(!hasFlattrToken);
ui.findPreference(PreferenceController.PREF_FLATTR_REVOKE).setEnabled(hasFlattrToken);
ui.findPreference(PreferenceController.PREF_AUTO_FLATTR_PREFS).setEnabled(hasFlattrToken);
ui.findPreference(UserPreferences.PREF_ENABLE_AUTODL_WIFI_FILTER)
.setEnabled(UserPreferences.isEnableAutodownload());
setSelectedNetworksEnabled(UserPreferences.isEnableAutodownload()
&& UserPreferences.isEnableAutodownloadWifiFilter());
ui.findPreference(UserPreferences.PREF_ENABLE_AUTODL_ON_BATTERY)
.setEnabled(UserPreferences.isEnableAutodownload());
if (Build.VERSION.SDK_INT >= 16) {
ui.findPreference(UserPreferences.PREF_SONIC).setEnabled(true);
} else {
Preference prefSonic = ui.findPreference(UserPreferences.PREF_SONIC);
prefSonic.setSummary("[Android 4.1+]\n" + prefSonic.getSummary());
}
}
private void setParallelDownloadsText(int downloads) {
final Resources res = ui.getActivity().getResources();
String s = Integer.toString(downloads)
+ res.getString(R.string.parallel_downloads_suffix);
ui.findPreference(UserPreferences.PREF_PARALLEL_DOWNLOADS).setSummary(s);
}
private void setEpisodeCacheSizeText(int cacheSize) {
final Resources res = ui.getActivity().getResources();
String s;
if (cacheSize == res.getInteger(
R.integer.episode_cache_size_unlimited)) {
s = res.getString(R.string.pref_episode_cache_unlimited);
} else {
s = Integer.toString(cacheSize)
+ res.getString(R.string.episodes_suffix);
}
ui.findPreference(UserPreferences.PREF_EPISODE_CACHE_SIZE).setSummary(s);
}
private void setDataFolderText() {
File f = UserPreferences.getDataFolder(ui.getActivity(), null);
if (f != null) {
ui.findPreference(PreferenceController.PREF_CHOOSE_DATA_DIR)
.setSummary(f.getAbsolutePath());
}
}
private void buildAutodownloadSelectedNetworsPreference() {
final Activity activity = ui.getActivity();
if (selectedNetworks != null) {
clearAutodownloadSelectedNetworsPreference();
}
// get configured networks
WifiManager wifiservice = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);
List<WifiConfiguration> networks = wifiservice.getConfiguredNetworks();
if (networks != null) {
selectedNetworks = new CheckBoxPreference[networks.size()];
List<String> prefValues = Arrays.asList(UserPreferences
.getAutodownloadSelectedNetworks());
PreferenceScreen prefScreen = (PreferenceScreen) ui.findPreference(PreferenceController.AUTO_DL_PREF_SCREEN);
Preference.OnPreferenceClickListener clickListener = new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
if (preference instanceof CheckBoxPreference) {
String key = preference.getKey();
ArrayList<String> prefValuesList = new ArrayList<String>(
Arrays.asList(UserPreferences
.getAutodownloadSelectedNetworks())
);
boolean newValue = ((CheckBoxPreference) preference)
.isChecked();
if (BuildConfig.DEBUG)
Log.d(TAG, "Selected network " + key
+ ". New state: " + newValue);
int index = prefValuesList.indexOf(key);
if (index >= 0 && newValue == false) {
// remove network
prefValuesList.remove(index);
} else if (index < 0 && newValue == true) {
prefValuesList.add(key);
}
UserPreferences.setAutodownloadSelectedNetworks(
prefValuesList.toArray(new String[prefValuesList.size()])
);
return true;
} else {
return false;
}
}
};
// create preference for each known network. attach listener and set
// value
for (int i = 0; i < networks.size(); i++) {
WifiConfiguration config = networks.get(i);
CheckBoxPreference pref = new CheckBoxPreference(activity);
String key = Integer.toString(config.networkId);
pref.setTitle(config.SSID);
pref.setKey(key);
pref.setOnPreferenceClickListener(clickListener);
pref.setPersistent(false);
pref.setChecked(prefValues.contains(key));
selectedNetworks[i] = pref;
prefScreen.addPreference(pref);
}
} else {
Log.e(TAG, "Couldn't get list of configure Wi-Fi networks");
}
}
private void clearAutodownloadSelectedNetworsPreference() {
if (selectedNetworks != null) {
PreferenceScreen prefScreen = (PreferenceScreen) ui.findPreference(PreferenceController.AUTO_DL_PREF_SCREEN);
for (int i = 0; i < selectedNetworks.length; i++) {
if (selectedNetworks[i] != null) {
prefScreen.removePreference(selectedNetworks[i]);
}
}
}
}
private void showDrawerPreferencesDialog() {
final Context context = ui.getActivity();
final List<String> hiddenDrawerItems = UserPreferences.getHiddenDrawerItems();
final String[] navTitles = context.getResources().getStringArray(R.array.nav_drawer_titles);
final String[] NAV_DRAWER_TAGS = MainActivity.NAV_DRAWER_TAGS;
boolean[] checked = new boolean[MainActivity.NAV_DRAWER_TAGS.length];
for(int i=0; i < NAV_DRAWER_TAGS.length; i++) {
String tag = NAV_DRAWER_TAGS[i];
if(!hiddenDrawerItems.contains(tag)) {
checked[i] = true;
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(R.string.drawer_preferences);
builder.setMultiChoiceItems(navTitles, checked, (dialog, which, isChecked) -> {
if (isChecked) {
hiddenDrawerItems.remove(NAV_DRAWER_TAGS[which]);
} else {
hiddenDrawerItems.add(NAV_DRAWER_TAGS[which]);
}
});
builder.setPositiveButton(R.string.confirm_label, new DialogInterface
.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
UserPreferences.setHiddenDrawerItems(context, hiddenDrawerItems);
}
});
builder.setNegativeButton(R.string.cancel_label, null);
builder.create().show();
}
private void showUpdateIntervalTimePreferencesDialog() {
final Context context = ui.getActivity();
MaterialDialog.Builder builder = new MaterialDialog.Builder(context);
builder.title(R.string.pref_autoUpdateIntervallOrTime_title);
builder.content(R.string.pref_autoUpdateIntervallOrTime_message);
builder.positiveText(R.string.pref_autoUpdateIntervallOrTime_Interval);
builder.negativeText(R.string.pref_autoUpdateIntervallOrTime_TimeOfDay);
builder.neutralText(R.string.pref_autoUpdateIntervallOrTime_Disable);
builder.callback(new MaterialDialog.ButtonCallback() {
@Override
public void onPositive(MaterialDialog dialog) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(context.getString(R.string.pref_autoUpdateIntervallOrTime_Interval));
final String[] values = context.getResources().getStringArray(R.array.update_intervall_values);
final String[] entries = getUpdateIntervalEntries(values);
builder.setSingleChoiceItems(entries, -1, (dialog1, which) -> {
int hours = Integer.valueOf(values[which]);
UserPreferences.setUpdateInterval(hours);
dialog1.dismiss();
});
builder.setNegativeButton(context.getString(R.string.cancel_label), null);
builder.show();
}
@Override
public void onNegative(MaterialDialog dialog) {
int hourOfDay = 7, minute = 0;
int[] updateTime = UserPreferences.getUpdateTimeOfDay();
if (updateTime.length == 2) {
hourOfDay = updateTime[0];
minute = updateTime[1];
}
TimePickerDialog timePickerDialog = new TimePickerDialog(context,
(view, selectedHourOfDay, selectedMinute) -> {
if (view.getTag() == null) { // onTimeSet() may get called twice!
view.setTag("TAGGED");
UserPreferences.setUpdateTimeOfDay(selectedHourOfDay, selectedMinute);
}
}, hourOfDay, minute, DateFormat.is24HourFormat(context));
timePickerDialog.setTitle(context.getString(R.string.pref_autoUpdateIntervallOrTime_TimeOfDay));
timePickerDialog.show();
}
@Override
public void onNeutral(MaterialDialog dialog) {
UserPreferences.setUpdateInterval(0);
}
});
builder.forceStacking(true);
builder.show();
}
public interface PreferenceUI {
/**
* Finds a preference based on its key.
*/
Preference findPreference(CharSequence key);
Activity getActivity();
}
}
| richq/AntennaPod | app/src/main/java/de/danoeh/antennapod/preferences/PreferenceController.java | Java | mit | 31,136 |
<?php
namespace TDN\DocumentBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use TDN\ImageBundle\Entity\Image;
/**
* TDN\DocumentBundle\Entity\Slider
*/
class Slider
{
/**
* @var string $pitch
*/
private $pitch;
/**
* @var integer $ordre
*/
private $ordre;
/**
* @var integer $statut
*/
private $statut;
/**
* @var \DateTime $datePublication
*/
private $datePublication;
/**
* @var integer $idSlide
*/
private $idSlide;
/**
* @var TDN\DocumentBundle\Entity\Document
*/
private $lnSource;
/**
* @var TDN\ImageBundle\Entity\Image
*/
private $lnCover;
/**
* Set pitch
*
* @param string $pitch
* @return Slider
*/
public function setPitch($pitch)
{
$this->pitch = $pitch;
return $this;
}
/**
* Get pitch
*
* @return string
*/
public function getPitch()
{
return $this->pitch;
}
/**
* Set ordre
*
* @param integer $ordre
* @return Slider
*/
public function setOrdre($ordre)
{
$this->ordre = $ordre;
return $this;
}
/**
* Get ordre
*
* @return integer
*/
public function getOrdre()
{
return $this->ordre;
}
/**
* Set statut
*
* @param integer $statut
* @return Slider
*/
public function setStatut($statut)
{
$this->statut = $statut;
return $this;
}
/**
* Get statut
*
* @return integer
*/
public function getStatut()
{
return $this->statut;
}
/**
* Set datePublication
*
* @param \DateTime $datePublication
* @return Slider
*/
public function setDatePublication($datePublication)
{
$this->datePublication = $datePublication;
return $this;
}
/**
* Get datePublication
*
* @return \DateTime
*/
public function getDatePublication()
{
return $this->datePublication;
}
/**
* Get idSlide
*
* @return integer
*/
public function getIdSlide()
{
return $this->idSlide;
}
/**
* Set lnSource
*
* @param TDN\DocumentBundle\Entity\Document $lnSource
* @return Slider
*/
public function setLnSource(\TDN\DocumentBundle\Entity\Document $lnSource = null)
{
$this->lnSource = $lnSource;
return $this;
}
/**
* Get lnSource
*
* @return TDN\DocumentBundle\Entity\Document
*/
public function getLnSource()
{
return $this->lnSource;
}
/**
* Set lnCover
*
* @param TDN\ImageBundle\Entity\Image $lnCover
* @return Slider
*/
public function setLnCover(\TDN\ImageBundle\Entity\Image $lnCover = null)
{
$this->lnCover = $lnCover;
return $this;
}
/**
* Get lnCover
*
* @return TDN\ImageBundle\Entity\Image
*/
public function getLnCover()
{
return $this->lnCover;
}
/**
* Construit un nouveau slide
*
* @return Slider
*/
public function setup ($imageOwner = NULL) {
// Création de l'illustration de l'article en une
$imageSlider = $this->getLnCover();
if ($imageSlider instanceof Image) {
$now = new \DateTime;
$dossier = '/public/'.$now->format('Y').'/'.$now->format('m').'/';
$imageSlider->init($dossier, $imageOwner, $imageOwner);
}
$this->setOrdre(0);
if ($this->getStatut() == 1) {
$this->setDatePublication(new \DateTime);
}
return $this;
}
/**
* Construit un nouveau slide
*
* @return Slider
*/
public function make ($_TDNDocument) {
$imageOwner = $_TDNDocument->getLnAuteur();
// Création de l'illustration de l'article en une
$imageSlider = $this->getLnCover();
if ($imageSlider instanceof Image) {
$now = new \DateTime;
$dossier = '/public/'.$now->format('Y').'/'.$now->format('m').'/';
$imageSlider->init($dossier, $imageOwner, $imageOwner);
}
$this->setLnSource($_TDNDocument)->setDatePublication($_TDNDocument->getDatePublication());
if (is_null($slider->getStatut())) {
$this->setStatut(0);
}
$this->setOrdre(0);
if ($this->getStatut() == 1) {
$this->setDatePublication(new \DateTime);
}
return $this;
}
} | HamzaBendidane/tdnold | src/TDN/DocumentBundle/Entity/backup 2/Slider.php | PHP | mit | 4,670 |
typedef int sampleInt;
class C {
void f();
};
void hoge() {
sampleInt a = 10;
C c;
c.f();
}
| jovial/nim-libclang | examples/tokenize/samples/sample2.cc | C++ | mit | 101 |
var Orbit = requireModule("orbit");
// Globalize loader properties for use by other Orbit packages
Orbit.__define__ = define;
Orbit.__requireModule__ = requireModule;
Orbit.__require__ = require;
Orbit.__requirejs__ = requirejs;
window.Orbit = Orbit;
| opsb/orbit-firebase | build-support/globalize-orbit.js | JavaScript | mit | 253 |
require 'test_helper'
describe 'Directives' do
describe '#directives' do
describe 'non value directives' do
it 'accepts public symbol' do
subject = Lotus::Action::Cache::Directives.new(:public)
subject.values.size.must_equal(1)
end
it 'accepts private symbol' do
subject = Lotus::Action::Cache::Directives.new(:private)
subject.values.size.must_equal(1)
end
it 'accepts no_cache symbol' do
subject = Lotus::Action::Cache::Directives.new(:no_cache)
subject.values.size.must_equal(1)
end
it 'accepts no_store symbol' do
subject = Lotus::Action::Cache::Directives.new(:no_store)
subject.values.size.must_equal(1)
end
it 'accepts no_transform symbol' do
subject = Lotus::Action::Cache::Directives.new(:no_transform)
subject.values.size.must_equal(1)
end
it 'accepts must_revalidate symbol' do
subject = Lotus::Action::Cache::Directives.new(:must_revalidate)
subject.values.size.must_equal(1)
end
it 'accepts proxy_revalidate symbol' do
subject = Lotus::Action::Cache::Directives.new(:proxy_revalidate)
subject.values.size.must_equal(1)
end
it 'does not accept weird symbol' do
subject = Lotus::Action::Cache::Directives.new(:weird)
subject.values.size.must_equal(0)
end
describe 'multiple symbols' do
it 'creates one directive for each valid symbol' do
subject = Lotus::Action::Cache::Directives.new(:private, :proxy_revalidate)
subject.values.size.must_equal(2)
end
end
describe 'private and public at the same time' do
it 'ignores public directive' do
subject = Lotus::Action::Cache::Directives.new(:private, :public)
subject.values.size.must_equal(1)
end
it 'creates one private directive' do
subject = Lotus::Action::Cache::Directives.new(:private, :public)
subject.values.first.name.must_equal(:private)
end
end
end
describe 'value directives' do
it 'accepts max_age symbol' do
subject = Lotus::Action::Cache::Directives.new(max_age: 600)
subject.values.size.must_equal(1)
end
it 'accepts s_maxage symbol' do
subject = Lotus::Action::Cache::Directives.new(s_maxage: 600)
subject.values.size.must_equal(1)
end
it 'accepts min_fresh symbol' do
subject = Lotus::Action::Cache::Directives.new(min_fresh: 600)
subject.values.size.must_equal(1)
end
it 'accepts max_stale symbol' do
subject = Lotus::Action::Cache::Directives.new(max_stale: 600)
subject.values.size.must_equal(1)
end
it 'does not accept weird symbol' do
subject = Lotus::Action::Cache::Directives.new(weird: 600)
subject.values.size.must_equal(0)
end
describe 'multiple symbols' do
it 'creates one directive for each valid symbol' do
subject = Lotus::Action::Cache::Directives.new(max_age: 600, max_stale: 600)
subject.values.size.must_equal(2)
end
end
end
describe 'value and non value directives' do
it 'creates one directive for each valid symbol' do
subject = Lotus::Action::Cache::Directives.new(:public, max_age: 600, max_stale: 600)
subject.values.size.must_equal(3)
end
end
end
end
describe 'ValueDirective' do
describe '#to_str' do
it 'returns as http cache format' do
subject = Lotus::Action::Cache::ValueDirective.new(:max_age, 600)
subject.to_str.must_equal('max-age=600')
end
end
end
describe 'NonValueDirective' do
describe '#to_str' do
it 'returns as http cache format' do
subject = Lotus::Action::Cache::NonValueDirective.new(:no_cache)
subject.to_str.must_equal('no-cache')
end
end
end
| weppos/hanami-controller | test/unit/cache/directives_test.rb | Ruby | mit | 3,932 |
<?php
$context = 'prod-hal-api-app';
require dirname(dirname(__DIR__)) . '/bootstrap/bootstrap.php';
| ryo88c/ChatWorkNotify | var/www/index.php | PHP | mit | 102 |
vti_encoding:SR|utf8-nl
vti_timelastmodified:TR|09 Feb 2017 03:34:58 -0000
vti_extenderversion:SR|6.0.2.8161
vti_backlinkinfo:VX|astro_site/mobile.html astro_site/mobile2.html
| akarys92/astro_site | vendor/scrollreveal/_vti_cnf/scrollreveal.min.js | JavaScript | mit | 176 |
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
//
// To add a suppression to this file, right-click the message in the
// Error List, point to "Suppress Message(s)", and click
// "In Project Suppression File".
// You do not need to add suppressions to this file manually.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes",
Scope = "namespace", Target = "AutoFixture.AutoFakeItEasy",
Justification = "This should be a separate assembly because it provides extensions to AutoFixture that are specific to the use of FakeItEasy.")]
| Pvlerick/AutoFixture | Src/AutoFakeItEasy/GlobalSuppressions.cs | C# | mit | 805 |
#include "Binding_pch.h"
using namespace gl;
namespace glbinding
{
Function<void, GLboolean> Binding::EdgeFlag("glEdgeFlag");
Function<void, GLsizei> Binding::EdgeFlagFormatNV("glEdgeFlagFormatNV");
Function<void, GLsizei, const void *> Binding::EdgeFlagPointer("glEdgeFlagPointer");
Function<void, GLsizei, GLsizei, const GLboolean *> Binding::EdgeFlagPointerEXT("glEdgeFlagPointerEXT");
Function<void, GLint, const GLboolean **, GLint> Binding::EdgeFlagPointerListIBM("glEdgeFlagPointerListIBM");
Function<void, const GLboolean *> Binding::EdgeFlagv("glEdgeFlagv");
Function<void, GLenum, GLeglImageOES, const GLint*> Binding::EGLImageTargetTexStorageEXT("glEGLImageTargetTexStorageEXT");
Function<void, GLuint, GLeglImageOES, const GLint*> Binding::EGLImageTargetTextureStorageEXT("glEGLImageTargetTextureStorageEXT");
Function<void, GLenum, const void *> Binding::ElementPointerAPPLE("glElementPointerAPPLE");
Function<void, GLenum, const void *> Binding::ElementPointerATI("glElementPointerATI");
Function<void, GLenum> Binding::Enable("glEnable");
Function<void, GLenum> Binding::EnableClientState("glEnableClientState");
Function<void, GLenum, GLuint> Binding::EnableClientStateiEXT("glEnableClientStateiEXT");
Function<void, GLenum, GLuint> Binding::EnableClientStateIndexedEXT("glEnableClientStateIndexedEXT");
Function<void, GLenum, GLuint> Binding::Enablei("glEnablei");
Function<void, GLenum, GLuint> Binding::EnableIndexedEXT("glEnableIndexedEXT");
Function<void, GLuint> Binding::EnableVariantClientStateEXT("glEnableVariantClientStateEXT");
Function<void, GLuint, GLuint> Binding::EnableVertexArrayAttrib("glEnableVertexArrayAttrib");
Function<void, GLuint, GLuint> Binding::EnableVertexArrayAttribEXT("glEnableVertexArrayAttribEXT");
Function<void, GLuint, GLenum> Binding::EnableVertexArrayEXT("glEnableVertexArrayEXT");
Function<void, GLuint, GLenum> Binding::EnableVertexAttribAPPLE("glEnableVertexAttribAPPLE");
Function<void, GLuint> Binding::EnableVertexAttribArray("glEnableVertexAttribArray");
Function<void, GLuint> Binding::EnableVertexAttribArrayARB("glEnableVertexAttribArrayARB");
Function<void> Binding::End("glEnd");
Function<void> Binding::EndConditionalRender("glEndConditionalRender");
Function<void> Binding::EndConditionalRenderNV("glEndConditionalRenderNV");
Function<void> Binding::EndConditionalRenderNVX("glEndConditionalRenderNVX");
Function<void> Binding::EndFragmentShaderATI("glEndFragmentShaderATI");
Function<void> Binding::EndList("glEndList");
Function<void> Binding::EndOcclusionQueryNV("glEndOcclusionQueryNV");
Function<void, GLuint> Binding::EndPerfMonitorAMD("glEndPerfMonitorAMD");
Function<void, GLuint> Binding::EndPerfQueryINTEL("glEndPerfQueryINTEL");
Function<void, GLenum> Binding::EndQuery("glEndQuery");
Function<void, GLenum> Binding::EndQueryARB("glEndQueryARB");
Function<void, GLenum, GLuint> Binding::EndQueryIndexed("glEndQueryIndexed");
Function<void> Binding::EndTransformFeedback("glEndTransformFeedback");
Function<void> Binding::EndTransformFeedbackEXT("glEndTransformFeedbackEXT");
Function<void> Binding::EndTransformFeedbackNV("glEndTransformFeedbackNV");
Function<void> Binding::EndVertexShaderEXT("glEndVertexShaderEXT");
Function<void, GLuint> Binding::EndVideoCaptureNV("glEndVideoCaptureNV");
Function<void, GLdouble> Binding::EvalCoord1d("glEvalCoord1d");
Function<void, const GLdouble *> Binding::EvalCoord1dv("glEvalCoord1dv");
Function<void, GLfloat> Binding::EvalCoord1f("glEvalCoord1f");
Function<void, const GLfloat *> Binding::EvalCoord1fv("glEvalCoord1fv");
Function<void, GLfixed> Binding::EvalCoord1xOES("glEvalCoord1xOES");
Function<void, const GLfixed *> Binding::EvalCoord1xvOES("glEvalCoord1xvOES");
Function<void, GLdouble, GLdouble> Binding::EvalCoord2d("glEvalCoord2d");
Function<void, const GLdouble *> Binding::EvalCoord2dv("glEvalCoord2dv");
Function<void, GLfloat, GLfloat> Binding::EvalCoord2f("glEvalCoord2f");
Function<void, const GLfloat *> Binding::EvalCoord2fv("glEvalCoord2fv");
Function<void, GLfixed, GLfixed> Binding::EvalCoord2xOES("glEvalCoord2xOES");
Function<void, const GLfixed *> Binding::EvalCoord2xvOES("glEvalCoord2xvOES");
Function<void, GLenum, GLenum> Binding::EvalMapsNV("glEvalMapsNV");
Function<void, GLenum, GLint, GLint> Binding::EvalMesh1("glEvalMesh1");
Function<void, GLenum, GLint, GLint, GLint, GLint> Binding::EvalMesh2("glEvalMesh2");
Function<void, GLint> Binding::EvalPoint1("glEvalPoint1");
Function<void, GLint, GLint> Binding::EvalPoint2("glEvalPoint2");
Function<void> Binding::EvaluateDepthValuesARB("glEvaluateDepthValuesARB");
Function<void, GLenum, GLuint, const GLfloat *> Binding::ExecuteProgramNV("glExecuteProgramNV");
Function<void, GLuint, GLuint, GLuint> Binding::ExtractComponentEXT("glExtractComponentEXT");
} // namespace glbinding | hpicgs/glbinding | source/glbinding/source/Binding_objects_e.cpp | C++ | mit | 4,797 |
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2011 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreTerrain.h"
#include "OgreTerrainQuadTreeNode.h"
#include "OgreStreamSerialiser.h"
#include "OgreMath.h"
#include "OgreImage.h"
#include "OgrePixelFormat.h"
#include "OgreSceneManager.h"
#include "OgreSceneNode.h"
#include "OgreException.h"
#include "OgreBitwise.h"
#include "OgreStringConverter.h"
#include "OgreViewport.h"
#include "OgreLogManager.h"
#include "OgreHardwarePixelBuffer.h"
#include "OgreTextureManager.h"
#include "OgreRoot.h"
#include "OgreRenderSystem.h"
#include "OgreRay.h"
#include "OgrePlane.h"
#include "OgreTerrainMaterialGeneratorA.h"
#include "OgreMaterialManager.h"
#include "OgreHardwareBufferManager.h"
#include "OgreDeflate.h"
#if OGRE_COMPILER == OGRE_COMPILER_MSVC
// we do lots of conversions here, casting them all is tedious & cluttered, we know what we're doing
# pragma warning (disable : 4244)
#endif
namespace Ogre
{
//---------------------------------------------------------------------
const uint32 Terrain::TERRAIN_CHUNK_ID = StreamSerialiser::makeIdentifier("TERR");
const uint16 Terrain::TERRAIN_CHUNK_VERSION = 1;
const uint32 Terrain::TERRAINLAYERDECLARATION_CHUNK_ID = StreamSerialiser::makeIdentifier("TDCL");
const uint16 Terrain::TERRAINLAYERDECLARATION_CHUNK_VERSION = 1;
const uint32 Terrain::TERRAINLAYERSAMPLER_CHUNK_ID = StreamSerialiser::makeIdentifier("TSAM");;
const uint16 Terrain::TERRAINLAYERSAMPLER_CHUNK_VERSION = 1;
const uint32 Terrain::TERRAINLAYERSAMPLERELEMENT_CHUNK_ID = StreamSerialiser::makeIdentifier("TSEL");;
const uint16 Terrain::TERRAINLAYERSAMPLERELEMENT_CHUNK_VERSION = 1;
const uint32 Terrain::TERRAINLAYERINSTANCE_CHUNK_ID = StreamSerialiser::makeIdentifier("TLIN");;
const uint16 Terrain::TERRAINLAYERINSTANCE_CHUNK_VERSION = 1;
const uint32 Terrain::TERRAINDERIVEDDATA_CHUNK_ID = StreamSerialiser::makeIdentifier("TDDA");;
const uint16 Terrain::TERRAINDERIVEDDATA_CHUNK_VERSION = 1;
// since 129^2 is the greatest power we can address in 16-bit index
const uint16 Terrain::TERRAIN_MAX_BATCH_SIZE = 129;
const uint16 Terrain::WORKQUEUE_DERIVED_DATA_REQUEST = 1;
const size_t Terrain::LOD_MORPH_CUSTOM_PARAM = 1001;
const uint8 Terrain::DERIVED_DATA_DELTAS = 1;
const uint8 Terrain::DERIVED_DATA_NORMALS = 2;
const uint8 Terrain::DERIVED_DATA_LIGHTMAP = 4;
// This MUST match the bitwise OR of all the types above with no extra bits!
const uint8 Terrain::DERIVED_DATA_ALL = 7;
//-----------------------------------------------------------------------
template<> TerrainGlobalOptions* Singleton<TerrainGlobalOptions>::msSingleton = 0;
TerrainGlobalOptions* TerrainGlobalOptions::getSingletonPtr(void)
{
return msSingleton;
}
TerrainGlobalOptions& TerrainGlobalOptions::getSingleton(void)
{
assert( msSingleton ); return ( *msSingleton );
}
//---------------------------------------------------------------------
TerrainGlobalOptions::TerrainGlobalOptions()
: mSkirtSize(30)
, mLightMapDir(Vector3(1, -1, 0).normalisedCopy())
, mCastsShadows(false)
, mMaxPixelError(3.0)
, mRenderQueueGroup(RENDER_QUEUE_MAIN)
, mVisibilityFlags(0xFFFFFFFF)
, mQueryFlags(0xFFFFFFFF)
, mUseRayBoxDistanceCalculation(false)
, mLayerBlendMapSize(1024)
, mDefaultLayerTextureWorldSize(10)
, mDefaultGlobalColourMapSize(1024)
, mLightmapSize(1024)
, mCompositeMapSize(1024)
, mCompositeMapAmbient(ColourValue::White)
, mCompositeMapDiffuse(ColourValue::White)
, mCompositeMapDistance(4000)
, mResourceGroup(ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME)
, mUseVertexCompressionWhenAvailable(true)
{
}
//---------------------------------------------------------------------
void TerrainGlobalOptions::setDefaultMaterialGenerator(TerrainMaterialGeneratorPtr gen)
{
mDefaultMaterialGenerator = gen;
}
//---------------------------------------------------------------------
TerrainMaterialGeneratorPtr TerrainGlobalOptions::getDefaultMaterialGenerator()
{
if (mDefaultMaterialGenerator.isNull())
{
// default
mDefaultMaterialGenerator.bind(OGRE_NEW TerrainMaterialGeneratorA());
}
return mDefaultMaterialGenerator;
}
//---------------------------------------------------------------------
//---------------------------------------------------------------------
NameGenerator Terrain::msBlendTextureGenerator = NameGenerator("TerrBlend");
//---------------------------------------------------------------------
Terrain::Terrain(SceneManager* sm)
: mSceneMgr(sm)
, mResourceGroup(StringUtil::BLANK)
, mIsLoaded(false)
, mModified(false)
, mHeightDataModified(false)
, mHeightData(0)
, mDeltaData(0)
, mPos(Vector3::ZERO)
, mQuadTree(0)
, mNumLodLevels(0)
, mNumLodLevelsPerLeafNode(0)
, mTreeDepth(0)
, mDirtyGeometryRect(0, 0, 0, 0)
, mDirtyDerivedDataRect(0, 0, 0, 0)
, mDirtyGeometryRectForNeighbours(0, 0, 0, 0)
, mDirtyLightmapFromNeighboursRect(0, 0, 0, 0)
, mDerivedDataUpdateInProgress(false)
, mDerivedUpdatePendingMask(0)
, mMaterialGenerationCount(0)
, mMaterialDirty(false)
, mMaterialParamsDirty(false)
, mGlobalColourMapSize(0)
, mGlobalColourMapEnabled(false)
, mCpuColourMapStorage(0)
, mCpuLightmapStorage(0)
, mCpuCompositeMapStorage(0)
, mCompositeMapDirtyRect(0, 0, 0, 0)
, mCompositeMapUpdateCountdown(0)
, mLastMillis(0)
, mCompositeMapDirtyRectLightmapUpdate(false)
, mLodMorphRequired(false)
, mNormalMapRequired(false)
, mLightMapRequired(false)
, mLightMapShadowsOnly(true)
, mCompositeMapRequired(false)
, mCpuTerrainNormalMap(0)
, mLastLODCamera(0)
, mLastLODFrame(0)
, mLastViewportHeight(0)
, mCustomGpuBufferAllocator(0)
{
mRootNode = sm->getRootSceneNode()->createChildSceneNode();
sm->addListener(this);
WorkQueue* wq = Root::getSingleton().getWorkQueue();
mWorkQueueChannel = wq->getChannel("Ogre/Terrain");
wq->addRequestHandler(mWorkQueueChannel, this);
wq->addResponseHandler(mWorkQueueChannel, this);
// generate a material name, it's important for the terrain material
// name to be consistent & unique no matter what generator is being used
// so use our own pointer as identifier, use FashHash rather than just casting
// the pointer to a long so we support 64-bit pointers
Terrain* pTerrain = this;
mMaterialName = "OgreTerrain/" + StringConverter::toString(FastHash((const char*)&pTerrain, sizeof(Terrain*)));
memset(mNeighbours, 0, sizeof(Terrain*) * NEIGHBOUR_COUNT);
}
//---------------------------------------------------------------------
Terrain::~Terrain()
{
mDerivedUpdatePendingMask = 0;
waitForDerivedProcesses();
WorkQueue* wq = Root::getSingleton().getWorkQueue();
wq->removeRequestHandler(mWorkQueueChannel, this);
wq->removeResponseHandler(mWorkQueueChannel, this);
freeTemporaryResources();
freeGPUResources();
freeCPUResources();
if (mSceneMgr)
{
mSceneMgr->destroySceneNode(mRootNode);
mSceneMgr->removeListener(this);
}
}
//---------------------------------------------------------------------
const AxisAlignedBox& Terrain::getAABB() const
{
if (!mQuadTree)
return AxisAlignedBox::BOX_NULL;
else
return mQuadTree->getAABB();
}
//---------------------------------------------------------------------
AxisAlignedBox Terrain::getWorldAABB() const
{
Matrix4 m = Matrix4::IDENTITY;
m.setTrans(getPosition());
AxisAlignedBox ret = getAABB();
ret.transformAffine(m);
return ret;
}
//---------------------------------------------------------------------
Real Terrain::getMinHeight() const
{
if (!mQuadTree)
return 0;
else
return mQuadTree->getMinHeight();
}
//---------------------------------------------------------------------
Real Terrain::getMaxHeight() const
{
if (!mQuadTree)
return 0;
else
return mQuadTree->getMaxHeight();
}
//---------------------------------------------------------------------
Real Terrain::getBoundingRadius() const
{
if (!mQuadTree)
return 0;
else
return mQuadTree->getBoundingRadius();
}
//---------------------------------------------------------------------
void Terrain::save(const String& filename)
{
DataStreamPtr stream = Root::getSingleton().createFileStream(filename, _getDerivedResourceGroup(), true);
// Compress
DataStreamPtr compressStream(OGRE_NEW DeflateStream(filename, stream));
StreamSerialiser ser(compressStream);
save(ser);
}
//---------------------------------------------------------------------
void Terrain::save(StreamSerialiser& stream)
{
// wait for any queued processes to finish
waitForDerivedProcesses();
if (mHeightDataModified)
{
// When modifying, for efficiency we only increase the max deltas at each LOD,
// we never reduce them (since that would require re-examining more samples)
// Since we now save this data in the file though, we need to make sure we've
// calculated the optimal
Rect rect;
rect.top = 0; rect.bottom = mSize;
rect.left = 0; rect.right = mSize;
calculateHeightDeltas(rect);
finaliseHeightDeltas(rect, false);
}
stream.writeChunkBegin(TERRAIN_CHUNK_ID, TERRAIN_CHUNK_VERSION);
uint8 align = (uint8)mAlign;
stream.write(&align);
stream.write(&mSize);
stream.write(&mWorldSize);
stream.write(&mMaxBatchSize);
stream.write(&mMinBatchSize);
stream.write(&mPos);
stream.write(mHeightData, mSize * mSize);
writeLayerDeclaration(mLayerDecl, stream);
// Layers
checkLayers(false);
uint8 numLayers = (uint8)mLayers.size();
writeLayerInstanceList(mLayers, stream);
// Packed layer blend data
if(!mCpuBlendMapStorage.empty())
{
// save from CPU data if it's there, it means GPU data was never created
stream.write(&mLayerBlendMapSize);
// load packed CPU data
int numBlendTex = getBlendTextureCount(numLayers);
for (int i = 0; i < numBlendTex; ++i)
{
PixelFormat fmt = getBlendTextureFormat(i, numLayers);
size_t channels = PixelUtil::getNumElemBytes(fmt);
size_t dataSz = channels * mLayerBlendMapSize * mLayerBlendMapSize;
uint8* pData = mCpuBlendMapStorage[i];
stream.write(pData, dataSz);
}
}
else
{
if (mLayerBlendMapSize != mLayerBlendMapSizeActual)
{
LogManager::getSingleton().stream() <<
"WARNING: blend maps were requested at a size larger than was supported "
"on this hardware, which means the quality has been degraded";
}
stream.write(&mLayerBlendMapSizeActual);
uint8* tmpData = (uint8*)OGRE_MALLOC(mLayerBlendMapSizeActual * mLayerBlendMapSizeActual * 4, MEMCATEGORY_GENERAL);
uint8 texIndex = 0;
for (TexturePtrList::iterator i = mBlendTextureList.begin(); i != mBlendTextureList.end(); ++i, ++texIndex)
{
// Must blit back in CPU format!
PixelFormat cpuFormat = getBlendTextureFormat(texIndex, getLayerCount());
PixelBox dst(mLayerBlendMapSizeActual, mLayerBlendMapSizeActual, 1, cpuFormat, tmpData);
(*i)->getBuffer()->blitToMemory(dst);
size_t dataSz = PixelUtil::getNumElemBytes((*i)->getFormat()) *
mLayerBlendMapSizeActual * mLayerBlendMapSizeActual;
stream.write(tmpData, dataSz);
}
OGRE_FREE(tmpData, MEMCATEGORY_GENERAL);
}
// other data
// normals
stream.writeChunkBegin(TERRAINDERIVEDDATA_CHUNK_ID, TERRAINDERIVEDDATA_CHUNK_VERSION);
String normalDataType("normalmap");
stream.write(&normalDataType);
stream.write(&mSize);
if (mCpuTerrainNormalMap)
{
// save from CPU data if it's there, it means GPU data was never created
stream.write((uint8*)mCpuTerrainNormalMap->data, mSize * mSize * 3);
}
else
{
uint8* tmpData = (uint8*)OGRE_MALLOC(mSize * mSize * 3, MEMCATEGORY_GENERAL);
PixelBox dst(mSize, mSize, 1, PF_BYTE_RGB, tmpData);
mTerrainNormalMap->getBuffer()->blitToMemory(dst);
stream.write(tmpData, mSize * mSize * 3);
OGRE_FREE(tmpData, MEMCATEGORY_GENERAL);
}
stream.writeChunkEnd(TERRAINDERIVEDDATA_CHUNK_ID);
// colourmap
if (mGlobalColourMapEnabled)
{
stream.writeChunkBegin(TERRAINDERIVEDDATA_CHUNK_ID, TERRAINDERIVEDDATA_CHUNK_VERSION);
String colourDataType("colourmap");
stream.write(&colourDataType);
stream.write(&mGlobalColourMapSize);
if (mCpuColourMapStorage)
{
// save from CPU data if it's there, it means GPU data was never created
stream.write(mCpuColourMapStorage, mGlobalColourMapSize * mGlobalColourMapSize * 3);
}
else
{
uint8* tmpData = (uint8*)OGRE_MALLOC(mGlobalColourMapSize * mGlobalColourMapSize * 3, MEMCATEGORY_GENERAL);
PixelBox dst(mGlobalColourMapSize, mGlobalColourMapSize, 1, PF_BYTE_RGB, tmpData);
mColourMap->getBuffer()->blitToMemory(dst);
stream.write(tmpData, mGlobalColourMapSize * mGlobalColourMapSize * 3);
OGRE_FREE(tmpData, MEMCATEGORY_GENERAL);
}
stream.writeChunkEnd(TERRAINDERIVEDDATA_CHUNK_ID);
}
// lightmap
if (mLightMapRequired)
{
stream.writeChunkBegin(TERRAINDERIVEDDATA_CHUNK_ID, TERRAINDERIVEDDATA_CHUNK_VERSION);
String lightmapDataType("lightmap");
stream.write(&lightmapDataType);
stream.write(&mLightmapSize);
if (mCpuLightmapStorage)
{
// save from CPU data if it's there, it means GPU data was never created
stream.write(mCpuLightmapStorage, mLightmapSize * mLightmapSize);
}
else
{
uint8* tmpData = (uint8*)OGRE_MALLOC(mLightmapSize * mLightmapSize, MEMCATEGORY_GENERAL);
PixelBox dst(mLightmapSize, mLightmapSize, 1, PF_L8, tmpData);
mLightmap->getBuffer()->blitToMemory(dst);
stream.write(tmpData, mLightmapSize * mLightmapSize);
OGRE_FREE(tmpData, MEMCATEGORY_GENERAL);
}
stream.writeChunkEnd(TERRAINDERIVEDDATA_CHUNK_ID);
}
// composite map
if (mCompositeMapRequired)
{
stream.writeChunkBegin(TERRAINDERIVEDDATA_CHUNK_ID, TERRAINDERIVEDDATA_CHUNK_VERSION);
String compositeMapDataType("compositemap");
stream.write(&compositeMapDataType);
stream.write(&mCompositeMapSize);
if (mCpuCompositeMapStorage)
{
// save from CPU data if it's there, it means GPU data was never created
stream.write(mCpuCompositeMapStorage, mCompositeMapSize * mCompositeMapSize * 4);
}
else
{
// composite map is 4 channel, 3x diffuse, 1x specular mask
uint8* tmpData = (uint8*)OGRE_MALLOC(mCompositeMapSize * mCompositeMapSize * 4, MEMCATEGORY_GENERAL);
PixelBox dst(mCompositeMapSize, mCompositeMapSize, 1, PF_BYTE_RGBA, tmpData);
mCompositeMap->getBuffer()->blitToMemory(dst);
stream.write(tmpData, mCompositeMapSize * mCompositeMapSize * 4);
OGRE_FREE(tmpData, MEMCATEGORY_GENERAL);
}
stream.writeChunkEnd(TERRAINDERIVEDDATA_CHUNK_ID);
}
// write deltas
stream.write(mDeltaData, mSize * mSize);
// write the quadtree
mQuadTree->save(stream);
stream.writeChunkEnd(TERRAIN_CHUNK_ID);
mModified = false;
mHeightDataModified = false;
}
//---------------------------------------------------------------------
void Terrain::writeLayerDeclaration(const TerrainLayerDeclaration& decl, StreamSerialiser& stream)
{
// Layer declaration
stream.writeChunkBegin(TERRAINLAYERDECLARATION_CHUNK_ID, TERRAINLAYERDECLARATION_CHUNK_VERSION);
// samplers
uint8 numSamplers = (uint8)decl.samplers.size();
stream.write(&numSamplers);
for (TerrainLayerSamplerList::const_iterator i = decl.samplers.begin();
i != decl.samplers.end(); ++i)
{
const TerrainLayerSampler& sampler = *i;
stream.writeChunkBegin(TERRAINLAYERSAMPLER_CHUNK_ID, TERRAINLAYERSAMPLER_CHUNK_VERSION);
stream.write(&sampler.alias);
uint8 pixFmt = (uint8)sampler.format;
stream.write(&pixFmt);
stream.writeChunkEnd(TERRAINLAYERSAMPLER_CHUNK_ID);
}
// elements
uint8 numElems = (uint8)decl.elements.size();
stream.write(&numElems);
for (TerrainLayerSamplerElementList::const_iterator i = decl.elements.begin();
i != decl.elements.end(); ++i)
{
const TerrainLayerSamplerElement& elem= *i;
stream.writeChunkBegin(TERRAINLAYERSAMPLERELEMENT_CHUNK_ID, TERRAINLAYERSAMPLERELEMENT_CHUNK_VERSION);
stream.write(&elem.source);
uint8 sem = (uint8)elem.semantic;
stream.write(&sem);
stream.write(&elem.elementStart);
stream.write(&elem.elementCount);
stream.writeChunkEnd(TERRAINLAYERSAMPLERELEMENT_CHUNK_ID);
}
stream.writeChunkEnd(TERRAINLAYERDECLARATION_CHUNK_ID);
}
//---------------------------------------------------------------------
bool Terrain::readLayerDeclaration(StreamSerialiser& stream, TerrainLayerDeclaration& targetdecl)
{
if (!stream.readChunkBegin(TERRAINLAYERDECLARATION_CHUNK_ID, TERRAINLAYERDECLARATION_CHUNK_VERSION))
return false;
// samplers
uint8 numSamplers;
stream.read(&numSamplers);
targetdecl.samplers.resize(numSamplers);
for (uint8 s = 0; s < numSamplers; ++s)
{
if (!stream.readChunkBegin(TERRAINLAYERSAMPLER_CHUNK_ID, TERRAINLAYERSAMPLER_CHUNK_VERSION))
return false;
stream.read(&(targetdecl.samplers[s].alias));
uint8 pixFmt;
stream.read(&pixFmt);
targetdecl.samplers[s].format = (PixelFormat)pixFmt;
stream.readChunkEnd(TERRAINLAYERSAMPLER_CHUNK_ID);
}
// elements
uint8 numElems;
stream.read(&numElems);
targetdecl.elements.resize(numElems);
for (uint8 e = 0; e < numElems; ++e)
{
if (!stream.readChunkBegin(TERRAINLAYERSAMPLERELEMENT_CHUNK_ID, TERRAINLAYERSAMPLERELEMENT_CHUNK_VERSION))
return false;
stream.read(&(targetdecl.elements[e].source));
uint8 sem;
stream.read(&sem);
targetdecl.elements[e].semantic = (TerrainLayerSamplerSemantic)sem;
stream.read(&(targetdecl.elements[e].elementStart));
stream.read(&(targetdecl.elements[e].elementCount));
stream.readChunkEnd(TERRAINLAYERSAMPLERELEMENT_CHUNK_ID);
}
stream.readChunkEnd(TERRAINLAYERDECLARATION_CHUNK_ID);
return true;
}
//---------------------------------------------------------------------
void Terrain::writeLayerInstanceList(const Terrain::LayerInstanceList& layers, StreamSerialiser& stream)
{
uint8 numLayers = (uint8)layers.size();
stream.write(&numLayers);
for (LayerInstanceList::const_iterator i = layers.begin(); i != layers.end(); ++i)
{
const LayerInstance& inst = *i;
stream.writeChunkBegin(TERRAINLAYERINSTANCE_CHUNK_ID, TERRAINLAYERINSTANCE_CHUNK_VERSION);
stream.write(&inst.worldSize);
for (StringVector::const_iterator t = inst.textureNames.begin();
t != inst.textureNames.end(); ++t)
{
stream.write(&(*t));
}
stream.writeChunkEnd(TERRAINLAYERINSTANCE_CHUNK_ID);
}
}
//---------------------------------------------------------------------
bool Terrain::readLayerInstanceList(StreamSerialiser& stream, size_t numSamplers, Terrain::LayerInstanceList& targetlayers)
{
uint8 numLayers;
stream.read(&numLayers);
targetlayers.resize(numLayers);
for (uint8 l = 0; l < numLayers; ++l)
{
if (!stream.readChunkBegin(TERRAINLAYERINSTANCE_CHUNK_ID, TERRAINLAYERINSTANCE_CHUNK_VERSION))
return false;
stream.read(&targetlayers[l].worldSize);
targetlayers[l].textureNames.resize(numSamplers);
for (size_t t = 0; t < numSamplers; ++t)
{
stream.read(&(targetlayers[l].textureNames[t]));
}
stream.readChunkEnd(TERRAINLAYERINSTANCE_CHUNK_ID);
}
return true;
}
//---------------------------------------------------------------------
const String& Terrain::_getDerivedResourceGroup() const
{
if (mResourceGroup.empty())
return TerrainGlobalOptions::getSingleton().getDefaultResourceGroup();
else
return mResourceGroup;
}
//---------------------------------------------------------------------
bool Terrain::prepare(const String& filename)
{
DataStreamPtr stream = Root::getSingleton().openFileStream(filename,
_getDerivedResourceGroup());
// uncompress
// Note DeflateStream automatically falls back on reading the underlying
// stream direct if it's not actually compressed so this will still work
// with uncompressed streams
DataStreamPtr uncompressStream(OGRE_NEW DeflateStream(filename, stream));
StreamSerialiser ser(uncompressStream);
return prepare(ser);
}
//---------------------------------------------------------------------
bool Terrain::prepare(StreamSerialiser& stream)
{
freeTemporaryResources();
freeCPUResources();
copyGlobalOptions();
if (!stream.readChunkBegin(TERRAIN_CHUNK_ID, TERRAIN_CHUNK_VERSION))
return false;
uint8 align;
stream.read(&align);
mAlign = (Alignment)align;
stream.read(&mSize);
stream.read(&mWorldSize);
stream.read(&mMaxBatchSize);
stream.read(&mMinBatchSize);
stream.read(&mPos);
mRootNode->setPosition(mPos);
updateBaseScale();
determineLodLevels();
size_t numVertices = mSize * mSize;
mHeightData = OGRE_ALLOC_T(float, numVertices, MEMCATEGORY_GEOMETRY);
stream.read(mHeightData, numVertices);
// Layer declaration
if (!readLayerDeclaration(stream, mLayerDecl))
return false;
checkDeclaration();
// Layers
if (!readLayerInstanceList(stream, mLayerDecl.samplers.size(), mLayers))
return false;
deriveUVMultipliers();
// Packed layer blend data
uint8 numLayers = (uint8)mLayers.size();
stream.read(&mLayerBlendMapSize);
mLayerBlendMapSizeActual = mLayerBlendMapSize; // for now, until we check
// load packed CPU data
int numBlendTex = getBlendTextureCount(numLayers);
for (int i = 0; i < numBlendTex; ++i)
{
PixelFormat fmt = getBlendTextureFormat(i, numLayers);
size_t channels = PixelUtil::getNumElemBytes(fmt);
size_t dataSz = channels * mLayerBlendMapSize * mLayerBlendMapSize;
uint8* pData = (uint8*)OGRE_MALLOC(dataSz, MEMCATEGORY_RESOURCE);
stream.read(pData, dataSz);
mCpuBlendMapStorage.push_back(pData);
}
// derived data
while (!stream.isEndOfChunk(TERRAIN_CHUNK_ID) &&
stream.peekNextChunkID() == TERRAINDERIVEDDATA_CHUNK_ID)
{
stream.readChunkBegin(TERRAINDERIVEDDATA_CHUNK_ID, TERRAINDERIVEDDATA_CHUNK_VERSION);
// name
String name;
stream.read(&name);
uint16 sz;
stream.read(&sz);
if (name == "normalmap")
{
mNormalMapRequired = true;
uint8* pData = static_cast<uint8*>(OGRE_MALLOC(sz * sz * 3, MEMCATEGORY_GENERAL));
mCpuTerrainNormalMap = OGRE_NEW PixelBox(sz, sz, 1, PF_BYTE_RGB, pData);
stream.read(pData, sz * sz * 3);
}
else if (name == "colourmap")
{
mGlobalColourMapEnabled = true;
mGlobalColourMapSize = sz;
mCpuColourMapStorage = static_cast<uint8*>(OGRE_MALLOC(sz * sz * 3, MEMCATEGORY_GENERAL));
stream.read(mCpuColourMapStorage, sz * sz * 3);
}
else if (name == "lightmap")
{
mLightMapRequired = true;
mLightmapSize = sz;
mCpuLightmapStorage = static_cast<uint8*>(OGRE_MALLOC(sz * sz, MEMCATEGORY_GENERAL));
stream.read(mCpuLightmapStorage, sz * sz);
}
else if (name == "compositemap")
{
mCompositeMapRequired = true;
mCompositeMapSize = sz;
mCpuCompositeMapStorage = static_cast<uint8*>(OGRE_MALLOC(sz * sz * 4, MEMCATEGORY_GENERAL));
stream.read(mCpuCompositeMapStorage, sz * sz * 4);
}
stream.readChunkEnd(TERRAINDERIVEDDATA_CHUNK_ID);
}
// Load delta data
mDeltaData = OGRE_ALLOC_T(float, numVertices, MEMCATEGORY_GEOMETRY);
stream.read(mDeltaData, numVertices);
// Create & load quadtree
mQuadTree = OGRE_NEW TerrainQuadTreeNode(this, 0, 0, 0, mSize, mNumLodLevels - 1, 0, 0);
mQuadTree->prepare(stream);
stream.readChunkEnd(TERRAIN_CHUNK_ID);
distributeVertexData();
mModified = false;
mHeightDataModified = false;
return true;
}
//---------------------------------------------------------------------
bool Terrain::prepare(const ImportData& importData)
{
freeTemporaryResources();
freeCPUResources();
copyGlobalOptions();
// validate
if (!(Bitwise::isPO2(importData.terrainSize - 1) && Bitwise::isPO2(importData.minBatchSize - 1)
&& Bitwise::isPO2(importData.maxBatchSize - 1)))
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"terrainSize, minBatchSize and maxBatchSize must all be 2^n + 1",
"Terrain::prepare");
}
if (importData.minBatchSize > importData.maxBatchSize)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"minBatchSize must be less than or equal to maxBatchSize",
"Terrain::prepare");
}
if (importData.maxBatchSize > TERRAIN_MAX_BATCH_SIZE)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"maxBatchSize must be no larger than " +
StringConverter::toString(TERRAIN_MAX_BATCH_SIZE),
"Terrain::prepare");
}
mAlign = importData.terrainAlign;
mSize = importData.terrainSize;
mWorldSize = importData.worldSize;
mLayerDecl = importData.layerDeclaration;
checkDeclaration();
mLayers = importData.layerList;
checkLayers(false);
deriveUVMultipliers();
mMaxBatchSize = importData.maxBatchSize;
mMinBatchSize = importData.minBatchSize;
setPosition(importData.pos);
updateBaseScale();
determineLodLevels();
size_t numVertices = mSize * mSize;
mHeightData = OGRE_ALLOC_T(float, numVertices, MEMCATEGORY_GEOMETRY);
if (importData.inputFloat)
{
if (Math::RealEqual(importData.inputBias, 0.0) && Math::RealEqual(importData.inputScale, 1.0))
{
// straight copy
memcpy(mHeightData, importData.inputFloat, sizeof(float) * numVertices);
}
else
{
// scale & bias
float* src = importData.inputFloat;
float* dst = mHeightData;
for (size_t i = 0; i < numVertices; ++i)
*dst++ = (*src++ * importData.inputScale) + importData.inputBias;
}
}
else if (importData.inputImage)
{
Image* img = importData.inputImage;
if (img->getWidth() != mSize || img->getHeight() != mSize)
img->resize(mSize, mSize);
// convert image data to floats
// Do this on a row-by-row basis, because we describe the terrain in
// a bottom-up fashion (ie ascending world coords), while Image is top-down
unsigned char* pSrcBase = img->getData();
for (size_t i = 0; i < mSize; ++i)
{
size_t srcy = mSize - i - 1;
unsigned char* pSrc = pSrcBase + srcy * img->getRowSpan();
float* pDst = mHeightData + i * mSize;
PixelUtil::bulkPixelConversion(pSrc, img->getFormat(),
pDst, PF_FLOAT32_R, mSize);
}
if (!Math::RealEqual(importData.inputBias, 0.0) || !Math::RealEqual(importData.inputScale, 1.0))
{
float* pAdj = mHeightData;
for (size_t i = 0; i < numVertices; ++i)
{
*pAdj = (*pAdj * importData.inputScale) + importData.inputBias;
++pAdj;
}
}
}
else
{
// start with flat terrain
if (importData.constantHeight == 0)
memset(mHeightData, 0, sizeof(float) * mSize * mSize);
else
{
float* pFloat = mHeightData;
for (long i = 0 ; i < mSize * mSize; ++i)
*pFloat++ = importData.constantHeight;
}
}
mDeltaData = OGRE_ALLOC_T(float, numVertices, MEMCATEGORY_GEOMETRY);
memset(mDeltaData, 0, sizeof(float) * numVertices);
mQuadTree = OGRE_NEW TerrainQuadTreeNode(this, 0, 0, 0, mSize, mNumLodLevels - 1, 0, 0);
mQuadTree->prepare();
// calculate entire terrain
Rect rect;
rect.top = 0; rect.bottom = mSize;
rect.left = 0; rect.right = mSize;
calculateHeightDeltas(rect);
finaliseHeightDeltas(rect, true);
distributeVertexData();
// Imported data is treated as modified because it's not saved
mModified = true;
mHeightDataModified = true;
return true;
}
//---------------------------------------------------------------------
void Terrain::copyGlobalOptions()
{
TerrainGlobalOptions& opts = TerrainGlobalOptions::getSingleton();
mSkirtSize = opts.getSkirtSize();
mRenderQueueGroup = opts.getRenderQueueGroup();
mVisibilityFlags = opts.getVisibilityFlags();
mQueryFlags = opts.getQueryFlags();
mLayerBlendMapSize = opts.getLayerBlendMapSize();
mLayerBlendMapSizeActual = mLayerBlendMapSize; // for now, until we check
mLightmapSize = opts.getLightMapSize();
mLightmapSizeActual = mLightmapSize; // for now, until we check
mCompositeMapSize = opts.getCompositeMapSize();
mCompositeMapSizeActual = mCompositeMapSize; // for now, until we check
}
//---------------------------------------------------------------------
void Terrain::determineLodLevels()
{
/* On a leaf-node basis, LOD can vary from maxBatch to minBatch in
number of vertices. After that, nodes will be gathered into parent
nodes with the same number of vertices, but they are combined with
3 of their siblings. In practice, the number of LOD levels overall
is:
LODlevels = log2(size - 1) - log2(minBatch - 1) + 1
TreeDepth = log2((size - 1) / (maxBatch - 1)) + 1
.. it's just that at the max LOD, the terrain is divided into
(size - 1) / (maxBatch - 1) tiles each of maxBatch vertices, and
at the lowest LOD the terrain is made up of one single tile of
minBatch vertices.
Example: size = 257, minBatch = 17, maxBatch = 33
LODlevels = log2(257 - 1) - log2(17 - 1) + 1 = 8 - 4 + 1 = 5
TreeDepth = log2((size - 1) / (maxBatch - 1)) + 1 = 4
LOD list - this assumes everything changes at once, which rarely happens of course
in fact except where groupings must occur, tiles can change independently
LOD 0: 257 vertices, 8 x 33 vertex tiles (tree depth 3)
LOD 1: 129 vertices, 8 x 17 vertex tiles (tree depth 3)
LOD 2: 65 vertices, 4 x 17 vertex tiles (tree depth 2)
LOD 3: 33 vertices, 2 x 17 vertex tiles (tree depth 1)
LOD 4: 17 vertices, 1 x 17 vertex tiles (tree depth 0)
Notice how we only have 2 sizes of index buffer to be concerned about,
17 vertices (per side) or 33. This makes buffer re-use much easier while
still giving the full range of LODs.
*/
mNumLodLevelsPerLeafNode = (uint16) (Math::Log2(mMaxBatchSize - 1.0f) - Math::Log2(mMinBatchSize - 1.0f) + 1.0f);
mNumLodLevels = (uint16) (Math::Log2(mSize - 1.0f) - Math::Log2(mMinBatchSize - 1.0f) + 1.0f);
//mTreeDepth = Math::Log2(mMaxBatchSize - 1) - Math::Log2(mMinBatchSize - 1) + 2;
mTreeDepth = mNumLodLevels - mNumLodLevelsPerLeafNode + 1;
LogManager::getSingleton().stream() << "Terrain created; size=" << mSize
<< " minBatch=" << mMinBatchSize << " maxBatch=" << mMaxBatchSize
<< " treeDepth=" << mTreeDepth << " lodLevels=" << mNumLodLevels
<< " leafLods=" << mNumLodLevelsPerLeafNode;
}
//---------------------------------------------------------------------
void Terrain::distributeVertexData()
{
/* Now we need to figure out how to distribute vertex data. We want to
use 16-bit indexes for compatibility, which means that the maximum patch
size that we can address (even sparsely for lower LODs) is 129x129
(the next one up, 257x257 is too big).
So we need to split the vertex data into chunks of 129. The number of
primary tiles this creates also indicates the point above which in
the node tree that we can no longer merge tiles at lower LODs without
using different vertex data. For example, using the 257x257 input example
above, the vertex data would have to be split in 2 (in each dimension)
in order to fit within the 129x129 range. This data could be shared by
all tree depths from 1 onwards, it's just that LODs 3-1 would sample
the 129x129 data sparsely. LOD 0 would sample all of the vertices.
LOD 4 however, the lowest LOD, could not work with the same vertex data
because it needs to cover the entire terrain. There are 2 choices here:
create another set of vertex data at 17x17 which is only used by LOD 4,
or make LOD 4 occur at tree depth 1 instead (ie still split up, and
rendered as 2x9 along each edge instead.
Since rendering very small batches is not desirable, and the vertex counts
are inherently not going to be large, creating a separate vertex set is
preferable. This will also be more efficient on the vertex cache with
distant terrains.
We probably need a larger example, because in this case only 1 level (LOD 0)
needs to use this separate vertex data. Higher detail terrains will need
it for multiple levels, here's a 2049x2049 example with 65 / 33 batch settings:
LODlevels = log2(2049 - 1) - log2(33 - 1) + 1 = 11 - 5 + 1 = 7
TreeDepth = log2((2049 - 1) / (65 - 1)) + 1 = 6
Number of vertex data splits at most detailed level:
(size - 1) / (TERRAIN_MAX_BATCH_SIZE - 1) = 2048 / 128 = 16
LOD 0: 2049 vertices, 32 x 65 vertex tiles (tree depth 5) vdata 0-15 [129x16]
LOD 1: 1025 vertices, 32 x 33 vertex tiles (tree depth 5) vdata 0-15 [129x16]
LOD 2: 513 vertices, 16 x 33 vertex tiles (tree depth 4) vdata 0-15 [129x16]
LOD 3: 257 vertices, 8 x 33 vertex tiles (tree depth 3) vdata 16-17 [129x2]
LOD 4: 129 vertices, 4 x 33 vertex tiles (tree depth 2) vdata 16-17 [129x2]
LOD 5: 65 vertices, 2 x 33 vertex tiles (tree depth 1) vdata 16-17 [129x2]
LOD 6: 33 vertices, 1 x 33 vertex tiles (tree depth 0) vdata 18 [33]
All the vertex counts are to be squared, they are just along one edge.
So as you can see, we need to have 3 levels of vertex data to satisy this
(admittedly quite extreme) case, and a total of 19 sets of vertex data.
The full detail geometry, which is 16(x16) sets of 129(x129), used by
LODs 0-2. LOD 3 can't use this set because it needs to group across them,
because it has only 8 tiles, so we make another set which satisfies this
at a maximum of 129 vertices per vertex data section. In this case LOD
3 needs 257(x257) total vertices so we still split into 2(x2) sets of 129.
This set is good up to and including LOD 5, but LOD 6 needs a single
contiguous set of vertices, so we make a 33x33 vertex set for it.
In terms of vertex data stored, this means that while our primary data is:
2049^2 = 4198401 vertices
our final stored vertex data is
(16 * 129)^2 + (2 * 129)^2 + 33^2 = 4327749 vertices
That equals a 3% premium, but it's both necessary and worth it for the
reduction in batch count resulting from the grouping. In addition, at
LODs 3 and 6 (or rather tree depth 3 and 0) there is the opportunity
to free up the vertex data used by more detailed LODs, which is
important when dealing with large terrains. For example, if we
freed the (GPU) vertex data for LOD 0-2 in the medium distance,
we would save 98% of the memory overhead for this terrain.
*/
LogManager& logMgr = LogManager::getSingleton();
logMgr.stream(LML_TRIVIAL) << "Terrain::distributeVertexData processing source "
"terrain size of " << mSize;
uint16 depth = mTreeDepth;
uint16 prevdepth = depth;
uint16 currresolution = mSize;
uint16 bakedresolution = mSize;
uint16 targetSplits = (bakedresolution - 1) / (TERRAIN_MAX_BATCH_SIZE - 1);
while(depth-- && targetSplits)
{
uint splits = 1 << depth;
if (splits == targetSplits)
{
logMgr.stream(LML_TRIVIAL) << " Assigning vertex data, resolution="
<< bakedresolution << " startDepth=" << depth << " endDepth=" << prevdepth
<< " splits=" << splits;
// vertex data goes at this level, at bakedresolution
// applies to all lower levels (except those with a closer vertex data)
// determine physical size (as opposed to resolution)
size_t sz = ((bakedresolution-1) / splits) + 1;
mQuadTree->assignVertexData(depth, prevdepth, bakedresolution, sz);
// next set to look for
bakedresolution = ((currresolution - 1) >> 1) + 1;
targetSplits = (bakedresolution - 1) / (TERRAIN_MAX_BATCH_SIZE - 1);
prevdepth = depth;
}
currresolution = ((currresolution - 1) >> 1) + 1;
}
// Always assign vertex data to the top of the tree
if (prevdepth > 0)
{
mQuadTree->assignVertexData(0, 1, bakedresolution, bakedresolution);
logMgr.stream(LML_TRIVIAL) << " Assigning vertex data, resolution: "
<< bakedresolution << " startDepth=0 endDepth=1 splits=1";
}
logMgr.stream(LML_TRIVIAL) << "Terrain::distributeVertexData finished";
}
//---------------------------------------------------------------------
void Terrain::load(const String& filename)
{
if (prepare(filename))
load();
else
OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
"Error while preparing " + filename + ", see log for details",
__FUNCTION__);
}
//---------------------------------------------------------------------
void Terrain::load(StreamSerialiser& stream)
{
if (prepare(stream))
load();
else
OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
"Error while preparing from stream, see log for details",
__FUNCTION__);
}
//---------------------------------------------------------------------
void Terrain::load()
{
if (mIsLoaded)
return;
if (mQuadTree)
mQuadTree->load();
checkLayers(true);
createOrDestroyGPUColourMap();
createOrDestroyGPUNormalMap();
createOrDestroyGPULightmap();
createOrDestroyGPUCompositeMap();
mMaterialGenerator->requestOptions(this);
mIsLoaded = true;
}
//---------------------------------------------------------------------
void Terrain::unload()
{
if (!mIsLoaded)
return;
if (mQuadTree)
mQuadTree->unload();
// free own buffers if used, but not custom
mDefaultGpuBufferAllocator.freeAllBuffers();
mIsLoaded = false;
mModified = false;
mHeightDataModified = false;
}
//---------------------------------------------------------------------
void Terrain::unprepare()
{
if (mQuadTree)
mQuadTree->unprepare();
}
//---------------------------------------------------------------------
float* Terrain::getHeightData() const
{
return mHeightData;
}
//---------------------------------------------------------------------
float* Terrain::getHeightData(long x, long y) const
{
assert (x >= 0 && x < mSize && y >= 0 && y < mSize);
return &mHeightData[y * mSize + x];
}
//---------------------------------------------------------------------
float Terrain::getHeightAtPoint(long x, long y) const
{
// clamp
x = std::min(x, (long)mSize - 1L);
x = std::max(x, 0L);
y = std::min(y, (long)mSize - 1L);
y = std::max(y, 0L);
return *getHeightData(x, y);
}
//---------------------------------------------------------------------
void Terrain::setHeightAtPoint(long x, long y, float h)
{
// clamp
x = std::min(x, (long)mSize - 1L);
x = std::max(x, 0L);
y = std::min(y, (long)mSize - 1L);
y = std::max(y, 0L);
*getHeightData(x, y) = h;
Rect rect;
rect.left = x;
rect.right = x+1;
rect.top = y;
rect.bottom = y+1;
dirtyRect(rect);
}
//---------------------------------------------------------------------
float Terrain::getHeightAtTerrainPosition(Real x, Real y)
{
// get left / bottom points (rounded down)
Real factor = (Real)mSize - 1.0f;
Real invFactor = 1.0f / factor;
long startX = static_cast<long>(x * factor);
long startY = static_cast<long>(y * factor);
long endX = startX + 1;
long endY = startY + 1;
// now get points in terrain space (effectively rounding them to boundaries)
// note that we do not clamp! We need a valid plane
Real startXTS = startX * invFactor;
Real startYTS = startY * invFactor;
Real endXTS = endX * invFactor;
Real endYTS = endY * invFactor;
// now clamp
endX = std::min(endX, (long)mSize-1);
endY = std::min(endY, (long)mSize-1);
// get parametric from start coord to next point
Real xParam = (x - startXTS) / invFactor;
Real yParam = (y - startYTS) / invFactor;
/* For even / odd tri strip rows, triangles are this shape:
even odd
3---2 3---2
| / | | \ |
0---1 0---1
*/
// Build all 4 positions in terrain space, using point-sampled height
Vector3 v0 (startXTS, startYTS, getHeightAtPoint(startX, startY));
Vector3 v1 (endXTS, startYTS, getHeightAtPoint(endX, startY));
Vector3 v2 (endXTS, endYTS, getHeightAtPoint(endX, endY));
Vector3 v3 (startXTS, endYTS, getHeightAtPoint(startX, endY));
// define this plane in terrain space
Plane plane;
if (startY % 2)
{
// odd row
bool secondTri = ((1.0 - yParam) > xParam);
if (secondTri)
plane.redefine(v0, v1, v3);
else
plane.redefine(v1, v2, v3);
}
else
{
// even row
bool secondTri = (yParam > xParam);
if (secondTri)
plane.redefine(v0, v2, v3);
else
plane.redefine(v0, v1, v2);
}
// Solve plane equation for z
return (-plane.normal.x * x
-plane.normal.y * y
- plane.d) / plane.normal.z;
}
//---------------------------------------------------------------------
float Terrain::getHeightAtWorldPosition(Real x, Real y, Real z)
{
Vector3 terrPos;
getTerrainPosition(x, y, z, &terrPos);
return getHeightAtTerrainPosition(terrPos.x, terrPos.y);
}
//---------------------------------------------------------------------
float Terrain::getHeightAtWorldPosition(const Vector3& pos)
{
return getHeightAtWorldPosition(pos.x, pos.y, pos.z);
}
//---------------------------------------------------------------------
const float* Terrain::getDeltaData()
{
return mDeltaData;
}
//---------------------------------------------------------------------
const float* Terrain::getDeltaData(long x, long y)
{
assert (x >= 0 && x < mSize && y >= 0 && y < mSize);
return &mDeltaData[y * mSize + x];
}
//---------------------------------------------------------------------
Vector3 Terrain::convertPosition(Space inSpace, const Vector3& inPos, Space outSpace) const
{
Vector3 ret;
convertPosition(inSpace, inPos, outSpace, ret);
return ret;
}
//---------------------------------------------------------------------
Vector3 Terrain::convertDirection(Space inSpace, const Vector3& inDir, Space outSpace) const
{
Vector3 ret;
convertDirection(inSpace, inDir, outSpace, ret);
return ret;
}
//---------------------------------------------------------------------
void Terrain::convertPosition(Space inSpace, const Vector3& inPos, Space outSpace, Vector3& outPos) const
{
convertSpace(inSpace, inPos, outSpace, outPos, true);
}
//---------------------------------------------------------------------
void Terrain::convertDirection(Space inSpace, const Vector3& inDir, Space outSpace, Vector3& outDir) const
{
convertSpace(inSpace, inDir, outSpace, outDir, false);
}
//---------------------------------------------------------------------
void Terrain::convertSpace(Space inSpace, const Vector3& inVec, Space outSpace, Vector3& outVec, bool translation) const
{
Space currSpace = inSpace;
outVec = inVec;
while (currSpace != outSpace)
{
switch(currSpace)
{
case WORLD_SPACE:
// In all cases, transition to local space
if (translation)
outVec -= mPos;
currSpace = LOCAL_SPACE;
break;
case LOCAL_SPACE:
switch(outSpace)
{
case WORLD_SPACE:
if (translation)
outVec += mPos;
currSpace = WORLD_SPACE;
break;
case POINT_SPACE:
case TERRAIN_SPACE:
// go via terrain space
outVec = convertWorldToTerrainAxes(outVec);
if (translation)
{
outVec.x -= mBase; outVec.y -= mBase;
outVec.x /= (mSize - 1) * mScale; outVec.y /= (mSize - 1) * mScale;
}
currSpace = TERRAIN_SPACE;
break;
case LOCAL_SPACE:
default:
break;
};
break;
case TERRAIN_SPACE:
switch(outSpace)
{
case WORLD_SPACE:
case LOCAL_SPACE:
// go via local space
if (translation)
{
outVec.x *= (mSize - 1) * mScale; outVec.y *= (mSize - 1) * mScale;
outVec.x += mBase; outVec.y += mBase;
}
outVec = convertTerrainToWorldAxes(outVec);
currSpace = LOCAL_SPACE;
break;
case POINT_SPACE:
if (translation)
{
outVec.x *= (mSize - 1); outVec.y *= (mSize - 1);
// rounding up/down
// this is why POINT_SPACE is the last on the list, because it loses data
outVec.x = static_cast<Real>(static_cast<int>(outVec.x + 0.5));
outVec.y = static_cast<Real>(static_cast<int>(outVec.y + 0.5));
}
currSpace = POINT_SPACE;
break;
case TERRAIN_SPACE:
default:
break;
};
break;
case POINT_SPACE:
// always go via terrain space
if (translation)
outVec.x /= (mSize - 1); outVec.y /= (mSize - 1);
currSpace = TERRAIN_SPACE;
break;
};
}
}
//---------------------------------------------------------------------
void Terrain::convertWorldToTerrainAxes(Alignment align, const Vector3& worldVec, Vector3* terrainVec)
{
switch (align)
{
case ALIGN_X_Z:
terrainVec->z = worldVec.y;
terrainVec->x = worldVec.x;
terrainVec->y = -worldVec.z;
break;
case ALIGN_Y_Z:
terrainVec->z = worldVec.x;
terrainVec->x = -worldVec.z;
terrainVec->y = worldVec.y;
break;
case ALIGN_X_Y:
*terrainVec = worldVec;
break;
};
}
//---------------------------------------------------------------------
void Terrain::convertTerrainToWorldAxes(Alignment align, const Vector3& terrainVec, Vector3* worldVec)
{
switch (align)
{
case ALIGN_X_Z:
worldVec->x = terrainVec.x;
worldVec->y = terrainVec.z;
worldVec->z = -terrainVec.y;
break;
case ALIGN_Y_Z:
worldVec->x = terrainVec.z;
worldVec->y = terrainVec.y;
worldVec->z = -terrainVec.x;
break;
case ALIGN_X_Y:
*worldVec = terrainVec;
break;
};
}
//---------------------------------------------------------------------
Vector3 Terrain::convertWorldToTerrainAxes(const Vector3& inVec) const
{
Vector3 ret;
convertWorldToTerrainAxes(mAlign, inVec, &ret);
return ret;
}
//---------------------------------------------------------------------
Vector3 Terrain::convertTerrainToWorldAxes(const Vector3& inVec) const
{
Vector3 ret;
convertTerrainToWorldAxes(mAlign, inVec, &ret);
return ret;
}
//---------------------------------------------------------------------
void Terrain::getPoint(long x, long y, Vector3* outpos)
{
getPointAlign(x, y, mAlign, outpos);
}
//---------------------------------------------------------------------
void Terrain::getPoint(long x, long y, float height, Vector3* outpos)
{
getPointAlign(x, y, height, mAlign, outpos);
}
//---------------------------------------------------------------------
void Terrain::getPointAlign(long x, long y, Alignment align, Vector3* outpos)
{
getPointAlign(x, y, *getHeightData(x, y), align, outpos);
}
//---------------------------------------------------------------------
void Terrain::getPointAlign(long x, long y, float height, Alignment align, Vector3* outpos)
{
switch(align)
{
case ALIGN_X_Z:
outpos->y = height;
outpos->x = x * mScale + mBase;
outpos->z = y * -mScale - mBase;
break;
case ALIGN_Y_Z:
outpos->x = height;
outpos->z = x * -mScale - mBase;
outpos->y = y * mScale + mBase;
break;
case ALIGN_X_Y:
outpos->z = height;
outpos->x = x * mScale + mBase;
outpos->y = y * mScale + mBase;
break;
};
}
//---------------------------------------------------------------------
void Terrain::getPointTransform(Matrix4* outXform) const
{
*outXform = Matrix4::ZERO;
switch(mAlign)
{
case ALIGN_X_Z:
//outpos->y = height (z)
(*outXform)[1][2] = 1.0f;
//outpos->x = x * mScale + mBase;
(*outXform)[0][0] = mScale;
(*outXform)[0][3] = mBase;
//outpos->z = y * -mScale - mBase;
(*outXform)[2][1] = -mScale;
(*outXform)[2][3] = -mBase;
break;
case ALIGN_Y_Z:
//outpos->x = height;
(*outXform)[0][2] = 1.0f;
//outpos->z = x * -mScale - mBase;
(*outXform)[2][0] = -mScale;
(*outXform)[2][3] = -mBase;
//outpos->y = y * mScale + mBase;
(*outXform)[1][1] = mScale;
(*outXform)[1][3] = mBase;
break;
case ALIGN_X_Y:
//outpos->z = height;
(*outXform)[2][2] = 1.0f; // strictly already the case, but..
//outpos->x = x * mScale + mBase;
(*outXform)[0][0] = mScale;
(*outXform)[0][3] = mBase;
//outpos->y = y * mScale + mBase;
(*outXform)[1][1] = mScale;
(*outXform)[1][3] = mBase;
break;
};
(*outXform)[3][3] = 1.0f;
}
//---------------------------------------------------------------------
void Terrain::getVector(const Vector3& inVec, Vector3* outVec)
{
getVectorAlign(inVec.x, inVec.y, inVec.z, mAlign, outVec);
}
//---------------------------------------------------------------------
void Terrain::getVector(Real x, Real y, Real z, Vector3* outVec)
{
getVectorAlign(x, y, z, mAlign, outVec);
}
//---------------------------------------------------------------------
void Terrain::getVectorAlign(const Vector3& inVec, Alignment align, Vector3* outVec)
{
getVectorAlign(inVec.x, inVec.y, inVec.z, align, outVec);
}
//---------------------------------------------------------------------
void Terrain::getVectorAlign(Real x, Real y, Real z, Alignment align, Vector3* outVec)
{
switch(align)
{
case ALIGN_X_Z:
outVec->y = z;
outVec->x = x;
outVec->z = -y;
break;
case ALIGN_Y_Z:
outVec->x = z;
outVec->y = y;
outVec->z = -x;
break;
case ALIGN_X_Y:
outVec->x = x;
outVec->y = y;
outVec->z = z;
break;
};
}
//---------------------------------------------------------------------
void Terrain::getPosition(const Vector3& TSpos, Vector3* outWSpos)
{
getPositionAlign(TSpos, mAlign, outWSpos);
}
//---------------------------------------------------------------------
void Terrain::getPosition(Real x, Real y, Real z, Vector3* outWSpos)
{
getPositionAlign(x, y, z, mAlign, outWSpos);
}
//---------------------------------------------------------------------
void Terrain::getTerrainPosition(const Vector3& WSpos, Vector3* outTSpos)
{
getTerrainPositionAlign(WSpos, mAlign, outTSpos);
}
//---------------------------------------------------------------------
void Terrain::getTerrainPosition(Real x, Real y, Real z, Vector3* outTSpos)
{
getTerrainPositionAlign(x, y, z, mAlign, outTSpos);
}
//---------------------------------------------------------------------
void Terrain::getPositionAlign(const Vector3& TSpos, Alignment align, Vector3* outWSpos)
{
getPositionAlign(TSpos.x, TSpos.y, TSpos.z, align, outWSpos);
}
//---------------------------------------------------------------------
void Terrain::getPositionAlign(Real x, Real y, Real z, Alignment align, Vector3* outWSpos)
{
switch(align)
{
case ALIGN_X_Z:
outWSpos->y = z;
outWSpos->x = x * (mSize - 1) * mScale + mBase;
outWSpos->z = y * (mSize - 1) * -mScale - mBase;
break;
case ALIGN_Y_Z:
outWSpos->x = z;
outWSpos->y = y * (mSize - 1) * mScale + mBase;
outWSpos->z = x * (mSize - 1) * -mScale - mBase;
break;
case ALIGN_X_Y:
outWSpos->z = z;
outWSpos->x = x * (mSize - 1) * mScale + mBase;
outWSpos->y = y * (mSize - 1) * mScale + mBase;
break;
};
}
//---------------------------------------------------------------------
void Terrain::getTerrainPositionAlign(const Vector3& WSpos, Alignment align, Vector3* outTSpos)
{
getTerrainPositionAlign(WSpos.x, WSpos.y, WSpos.z, align, outTSpos);
}
//---------------------------------------------------------------------
void Terrain::getTerrainPositionAlign(Real x, Real y, Real z, Alignment align, Vector3* outTSpos)
{
switch(align)
{
case ALIGN_X_Z:
outTSpos->x = (x - mBase - mPos.x) / ((mSize - 1) * mScale);
outTSpos->y = (z + mBase - mPos.z) / ((mSize - 1) * -mScale);
outTSpos->z = y;
break;
case ALIGN_Y_Z:
outTSpos->x = (z - mBase - mPos.z) / ((mSize - 1) * -mScale);
outTSpos->y = (y + mBase - mPos.y) / ((mSize - 1) * mScale);
outTSpos->z = x;
break;
case ALIGN_X_Y:
outTSpos->x = (x - mBase - mPos.x) / ((mSize - 1) * mScale);
outTSpos->y = (y - mBase - mPos.y) / ((mSize - 1) * mScale);
outTSpos->z = z;
break;
};
}
//---------------------------------------------------------------------
void Terrain::getTerrainVector(const Vector3& inVec, Vector3* outVec)
{
getTerrainVectorAlign(inVec.x, inVec.y, inVec.z, mAlign, outVec);
}
//---------------------------------------------------------------------
void Terrain::getTerrainVector(Real x, Real y, Real z, Vector3* outVec)
{
getTerrainVectorAlign(x, y, z, mAlign, outVec);
}
//---------------------------------------------------------------------
void Terrain::getTerrainVectorAlign(const Vector3& inVec, Alignment align, Vector3* outVec)
{
getTerrainVectorAlign(inVec.x, inVec.y, inVec.z, align, outVec);
}
//---------------------------------------------------------------------
void Terrain::getTerrainVectorAlign(Real x, Real y, Real z, Alignment align, Vector3* outVec)
{
switch(align)
{
case ALIGN_X_Z:
outVec->z = y;
outVec->x = x;
outVec->y = -z;
break;
case ALIGN_Y_Z:
outVec->z = x;
outVec->y = y;
outVec->x = -z;
break;
case ALIGN_X_Y:
outVec->x = x;
outVec->y = y;
outVec->z = z;
break;
};
}
//---------------------------------------------------------------------
Terrain::Alignment Terrain::getAlignment() const
{
return mAlign;
}
//---------------------------------------------------------------------
uint16 Terrain::getSize() const
{
return mSize;
}
//---------------------------------------------------------------------
uint16 Terrain::getMaxBatchSize() const
{
return mMaxBatchSize;
}
//---------------------------------------------------------------------
uint16 Terrain::getMinBatchSize() const
{
return mMinBatchSize;
}
//---------------------------------------------------------------------
Real Terrain::getWorldSize() const
{
return mWorldSize;
}
//---------------------------------------------------------------------
Real Terrain::getLayerWorldSize(uint8 index) const
{
if (index < mLayers.size())
{
return mLayers[index].worldSize;
}
else if (!mLayers.empty())
{
return mLayers[0].worldSize;
}
else
{
return TerrainGlobalOptions::getSingleton().getDefaultLayerTextureWorldSize();
}
}
//---------------------------------------------------------------------
void Terrain::setLayerWorldSize(uint8 index, Real size)
{
if (index < mLayers.size())
{
if (index >= mLayerUVMultiplier.size())
mLayerUVMultiplier.resize(index + 1);
mLayers[index].worldSize = size;
mLayerUVMultiplier[index] = mWorldSize / size;
mMaterialParamsDirty = true;
mModified = true;
}
}
//---------------------------------------------------------------------
Real Terrain::getLayerUVMultiplier(uint8 index) const
{
if (index < mLayerUVMultiplier.size())
{
return mLayerUVMultiplier[index];
}
else if (!mLayerUVMultiplier.empty())
{
return mLayerUVMultiplier[0];
}
else
{
// default to tile 100 times
return 100;
}
}
//---------------------------------------------------------------------
void Terrain::deriveUVMultipliers()
{
mLayerUVMultiplier.resize(mLayers.size());
for (size_t i = 0; i < mLayers.size(); ++i)
{
const LayerInstance& inst = mLayers[i];
mLayerUVMultiplier[i] = mWorldSize / inst.worldSize;
}
}
//---------------------------------------------------------------------
const String& Terrain::getLayerTextureName(uint8 layerIndex, uint8 samplerIndex) const
{
if (layerIndex < mLayers.size() && samplerIndex < mLayerDecl.samplers.size())
{
return mLayers[layerIndex].textureNames[samplerIndex];
}
else
{
return StringUtil::BLANK;
}
}
//---------------------------------------------------------------------
void Terrain::setLayerTextureName(uint8 layerIndex, uint8 samplerIndex, const String& textureName)
{
if (layerIndex < mLayers.size() && samplerIndex < mLayerDecl.samplers.size())
{
if (mLayers[layerIndex].textureNames[samplerIndex] != textureName)
{
mLayers[layerIndex].textureNames[samplerIndex] = textureName;
mMaterialDirty = true;
mMaterialParamsDirty = true;
mModified = true;
}
}
}
//---------------------------------------------------------------------
void Terrain::setPosition(const Vector3& pos)
{
if (pos != mPos)
{
mPos = pos;
mRootNode->setPosition(pos);
updateBaseScale();
mModified = true;
}
}
//---------------------------------------------------------------------
SceneNode* Terrain::_getRootSceneNode() const
{
return mRootNode;
}
//---------------------------------------------------------------------
void Terrain::updateBaseScale()
{
// centre the terrain on local origin
mBase = -mWorldSize * 0.5;
// scale determines what 1 unit on the grid becomes in world space
mScale = mWorldSize / (Real)(mSize-1);
}
//---------------------------------------------------------------------
void Terrain::dirty()
{
Rect rect;
rect.top = 0; rect.bottom = mSize;
rect.left = 0; rect.right = mSize;
dirtyRect(rect);
}
//---------------------------------------------------------------------
void Terrain::dirtyRect(const Rect& rect)
{
mDirtyGeometryRect.merge(rect);
mDirtyGeometryRectForNeighbours.merge(rect);
mDirtyDerivedDataRect.merge(rect);
mCompositeMapDirtyRect.merge(rect);
mModified = true;
mHeightDataModified = true;
}
//---------------------------------------------------------------------
void Terrain::_dirtyCompositeMapRect(const Rect& rect)
{
mCompositeMapDirtyRect.merge(rect);
mModified = true;
}
//---------------------------------------------------------------------
void Terrain::dirtyLightmapRect(const Rect& rect)
{
mDirtyDerivedDataRect.merge(rect);
mModified = true;
}
//---------------------------------------------------------------------
void Terrain::dirtyLightmap()
{
Rect rect;
rect.top = 0; rect.bottom = mSize;
rect.left = 0; rect.right = mSize;
dirtyLightmapRect(rect);
}
//---------------------------------------------------------------------
void Terrain::update(bool synchronous)
{
updateGeometry();
updateDerivedData(synchronous);
}
//---------------------------------------------------------------------
void Terrain::updateGeometry()
{
if (!mDirtyGeometryRect.isNull())
{
mQuadTree->updateVertexData(true, false, mDirtyGeometryRect, false);
mDirtyGeometryRect.setNull();
}
// propagate changes
notifyNeighbours();
}
//---------------------------------------------------------------------
void Terrain::updateDerivedData(bool synchronous, uint8 typeMask)
{
if (!mDirtyDerivedDataRect.isNull() || !mDirtyLightmapFromNeighboursRect.isNull())
{
mModified = true;
if (mDerivedDataUpdateInProgress)
{
// Don't launch many updates, instead wait for the other one
// to finish and issue another afterwards.
mDerivedUpdatePendingMask |= typeMask;
}
else
{
updateDerivedDataImpl(mDirtyDerivedDataRect, mDirtyLightmapFromNeighboursRect,
synchronous, typeMask);
mDirtyDerivedDataRect.setNull();
mDirtyLightmapFromNeighboursRect.setNull();
}
}
else
{
// Usually the composite map is updated after the other background
// data is updated (no point doing it beforehand), but if there's
// nothing to update, then we'll do it right now.
updateCompositeMap();
}
}
//---------------------------------------------------------------------
void Terrain::updateDerivedDataImpl(const Rect& rect, const Rect& lightmapExtraRect,
bool synchronous, uint8 typeMask)
{
mDerivedDataUpdateInProgress = true;
mDerivedUpdatePendingMask = 0;
DerivedDataRequest req;
req.terrain = this;
req.dirtyRect = rect;
req.lightmapExtraDirtyRect = lightmapExtraRect;
req.typeMask = typeMask;
if (!mNormalMapRequired)
req.typeMask = req.typeMask & ~DERIVED_DATA_NORMALS;
if (!mLightMapRequired)
req.typeMask = req.typeMask & ~DERIVED_DATA_LIGHTMAP;
Root::getSingleton().getWorkQueue()->addRequest(
mWorkQueueChannel, WORKQUEUE_DERIVED_DATA_REQUEST,
Any(req), 0, synchronous);
}
//---------------------------------------------------------------------
void Terrain::waitForDerivedProcesses()
{
while (mDerivedDataUpdateInProgress)
{
// we need to wait for this to finish
OGRE_THREAD_SLEEP(50);
Root::getSingleton().getWorkQueue()->processResponses();
}
}
//---------------------------------------------------------------------
void Terrain::freeCPUResources()
{
OGRE_FREE(mHeightData, MEMCATEGORY_GEOMETRY);
mHeightData = 0;
OGRE_FREE(mDeltaData, MEMCATEGORY_GEOMETRY);
mDeltaData = 0;
OGRE_DELETE mQuadTree;
mQuadTree = 0;
if (mCpuTerrainNormalMap)
{
OGRE_FREE(mCpuTerrainNormalMap->data, MEMCATEGORY_GENERAL);
OGRE_DELETE mCpuTerrainNormalMap;
mCpuTerrainNormalMap = 0;
}
OGRE_FREE(mCpuColourMapStorage, MEMCATEGORY_GENERAL);
mCpuColourMapStorage = 0;
OGRE_FREE(mCpuLightmapStorage, MEMCATEGORY_GENERAL);
mCpuLightmapStorage = 0;
OGRE_FREE(mCpuCompositeMapStorage, MEMCATEGORY_GENERAL);
mCpuCompositeMapStorage = 0;
}
//---------------------------------------------------------------------
void Terrain::freeGPUResources()
{
// remove textures
TextureManager* tmgr = TextureManager::getSingletonPtr();
if (tmgr)
{
for (TexturePtrList::iterator i = mBlendTextureList.begin(); i != mBlendTextureList.end(); ++i)
{
tmgr->remove((*i)->getHandle());
}
mBlendTextureList.clear();
}
if (!mTerrainNormalMap.isNull())
{
tmgr->remove(mTerrainNormalMap->getHandle());
mTerrainNormalMap.setNull();
}
if (!mColourMap.isNull())
{
tmgr->remove(mColourMap->getHandle());
mColourMap.setNull();
}
if (!mLightmap.isNull())
{
tmgr->remove(mLightmap->getHandle());
mLightmap.setNull();
}
if (!mCompositeMap.isNull())
{
tmgr->remove(mCompositeMap->getHandle());
mCompositeMap.setNull();
}
if (!mMaterial.isNull())
{
MaterialManager::getSingleton().remove(mMaterial->getHandle());
mMaterial.setNull();
}
if (!mCompositeMapMaterial.isNull())
{
MaterialManager::getSingleton().remove(mCompositeMapMaterial->getHandle());
mCompositeMapMaterial.setNull();
}
}
//---------------------------------------------------------------------
Rect Terrain::calculateHeightDeltas(const Rect& rect)
{
Rect clampedRect(rect);
clampedRect.left = std::max(0L, clampedRect.left);
clampedRect.top = std::max(0L, clampedRect.top);
clampedRect.right = std::min((long)mSize, clampedRect.right);
clampedRect.bottom = std::min((long)mSize, clampedRect.bottom);
Rect finalRect(clampedRect);
mQuadTree->preDeltaCalculation(clampedRect);
/// Iterate over target levels,
for (int targetLevel = 1; targetLevel < mNumLodLevels; ++targetLevel)
{
int sourceLevel = targetLevel - 1;
int step = 1 << targetLevel;
// The step of the next higher LOD
// int higherstep = step >> 1;
// need to widen the dirty rectangle since change will affect surrounding
// vertices at lower LOD
Rect widenedRect(rect);
widenedRect.left = std::max(0L, widenedRect.left - step);
widenedRect.top = std::max(0L, widenedRect.top - step);
widenedRect.right = std::min((long)mSize, widenedRect.right + step);
widenedRect.bottom = std::min((long)mSize, widenedRect.bottom + step);
// keep a merge of the widest
finalRect.merge(widenedRect);
// now round the rectangle at this level so that it starts & ends on
// the step boundaries
Rect lodRect(widenedRect);
lodRect.left -= lodRect.left % step;
lodRect.top -= lodRect.top % step;
if (lodRect.right % step)
lodRect.right += step - (lodRect.right % step);
if (lodRect.bottom % step)
lodRect.bottom += step - (lodRect.bottom % step);
for (int j = lodRect.top; j < lodRect.bottom - step; j += step )
{
for (int i = lodRect.left; i < lodRect.right - step; i += step )
{
// Form planes relating to the lower detail tris to be produced
// For even tri strip rows, they are this shape:
// 2---3
// | / |
// 0---1
// For odd tri strip rows, they are this shape:
// 2---3
// | \ |
// 0---1
Vector3 v0, v1, v2, v3;
getPointAlign(i, j, ALIGN_X_Y, &v0);
getPointAlign(i + step, j, ALIGN_X_Y, &v1);
getPointAlign(i, j + step, ALIGN_X_Y, &v2);
getPointAlign(i + step, j + step, ALIGN_X_Y, &v3);
Plane t1, t2;
bool backwardTri = false;
// Odd or even in terms of target level
if ((j / step) % 2 == 0)
{
t1.redefine(v0, v1, v3);
t2.redefine(v0, v3, v2);
}
else
{
t1.redefine(v1, v3, v2);
t2.redefine(v0, v1, v2);
backwardTri = true;
}
// include the bottommost row of vertices if this is the last row
int yubound = (j == (mSize - step)? step : step - 1);
for ( int y = 0; y <= yubound; y++ )
{
// include the rightmost col of vertices if this is the last col
int xubound = (i == (mSize - step)? step : step - 1);
for ( int x = 0; x <= xubound; x++ )
{
int fulldetailx = i + x;
int fulldetaily = j + y;
if ( fulldetailx % step == 0 &&
fulldetaily % step == 0 )
{
// Skip, this one is a vertex at this level
continue;
}
Real ypct = (Real)y / (Real)step;
Real xpct = (Real)x / (Real)step;
//interpolated height
Vector3 actualPos;
getPointAlign(fulldetailx, fulldetaily, ALIGN_X_Y, &actualPos);
Real interp_h;
// Determine which tri we're on
if ((xpct > ypct && !backwardTri) ||
(xpct > (1-ypct) && backwardTri))
{
// Solve for x/z
interp_h =
(-t1.normal.x * actualPos.x
- t1.normal.y * actualPos.y
- t1.d) / t1.normal.z;
}
else
{
// Second tri
interp_h =
(-t2.normal.x * actualPos.x
- t2.normal.y * actualPos.y
- t2.d) / t2.normal.z;
}
Real actual_h = actualPos.z;
Real delta = interp_h - actual_h;
// max(delta) is the worst case scenario at this LOD
// compared to the original heightmap
// tell the quadtree about this
mQuadTree->notifyDelta(fulldetailx, fulldetaily, sourceLevel, delta);
// If this vertex is being removed at this LOD,
// then save the height difference since that's the move
// it will need to make. Vertices to be removed at this LOD
// are halfway between the steps, but exclude those that
// would have been eliminated at earlier levels
int halfStep = step / 2;
if (
((fulldetailx % step) == halfStep && (fulldetaily % halfStep) == 0) ||
((fulldetaily % step) == halfStep && (fulldetailx % halfStep) == 0))
{
// Save height difference
mDeltaData[fulldetailx + (fulldetaily * mSize)] = delta;
}
}
}
} // i
} // j
} // targetLevel
mQuadTree->postDeltaCalculation(clampedRect);
return finalRect;
}
//---------------------------------------------------------------------
void Terrain::finaliseHeightDeltas(const Rect& rect, bool cpuData)
{
Rect clampedRect(rect);
clampedRect.left = std::max(0L, clampedRect.left);
clampedRect.top = std::max(0L, clampedRect.top);
clampedRect.right = std::min((long)mSize, clampedRect.right);
clampedRect.bottom = std::min((long)mSize, clampedRect.bottom);
// min/max information
mQuadTree->finaliseDeltaValues(clampedRect);
// delta vertex data
mQuadTree->updateVertexData(false, true, clampedRect, cpuData);
}
//---------------------------------------------------------------------
uint16 Terrain::getResolutionAtLod(uint16 lodLevel)
{
return ((mSize - 1) >> lodLevel) + 1;
}
//---------------------------------------------------------------------
void Terrain::preFindVisibleObjects(SceneManager* source,
SceneManager::IlluminationRenderStage irs, Viewport* v)
{
// Early-out
if (!mIsLoaded)
return;
// check deferred updates
unsigned long currMillis = Root::getSingleton().getTimer()->getMilliseconds();
unsigned long elapsedMillis = currMillis - mLastMillis;
if (mCompositeMapUpdateCountdown > 0 && elapsedMillis)
{
if (elapsedMillis > mCompositeMapUpdateCountdown)
mCompositeMapUpdateCountdown = 0;
else
mCompositeMapUpdateCountdown -= elapsedMillis;
if (!mCompositeMapUpdateCountdown)
updateCompositeMap();
}
mLastMillis = currMillis;
// only calculate LOD once per LOD camera, per frame, per viewport height
const Camera* lodCamera = v->getCamera()->getLodCamera();
unsigned long frameNum = Root::getSingleton().getNextFrameNumber();
int vpHeight = v->getActualHeight();
if (mLastLODCamera != lodCamera || frameNum != mLastLODFrame
|| mLastViewportHeight != vpHeight)
{
mLastLODCamera = lodCamera;
mLastLODFrame = frameNum;
mLastViewportHeight = vpHeight;
calculateCurrentLod(v);
}
}
//---------------------------------------------------------------------
void Terrain::sceneManagerDestroyed(SceneManager* source)
{
unload();
unprepare();
if (source == mSceneMgr)
mSceneMgr = 0;
}
//---------------------------------------------------------------------
void Terrain::calculateCurrentLod(Viewport* vp)
{
if (mQuadTree)
{
// calculate error terms
const Camera* cam = vp->getCamera()->getLodCamera();
// W. de Boer 2000 calculation
// A = vp_near / abs(vp_top)
// A = 1 / tan(fovy*0.5) (== 1 for fovy=45*2)
Real A = 1.0f / Math::Tan(cam->getFOVy() * 0.5f);
// T = 2 * maxPixelError / vertRes
Real maxPixelError = TerrainGlobalOptions::getSingleton().getMaxPixelError() * cam->_getLodBiasInverse();
Real T = 2.0f * maxPixelError / (Real)vp->getActualHeight();
// CFactor = A / T
Real cFactor = A / T;
mQuadTree->calculateCurrentLod(cam, cFactor);
}
}
//---------------------------------------------------------------------
std::pair<bool, Vector3> Terrain::rayIntersects(const Ray& ray,
bool cascadeToNeighbours /* = false */, Real distanceLimit /* = 0 */)
{
typedef std::pair<bool, Vector3> Result;
// first step: convert the ray to a local vertex space
// we assume terrain to be in the x-z plane, with the [0,0] vertex
// at origin and a plane distance of 1 between vertices.
// This makes calculations easier.
Vector3 rayOrigin = ray.getOrigin() - getPosition();
Vector3 rayDirection = ray.getDirection();
// change alignment
Vector3 tmp;
switch (getAlignment())
{
case ALIGN_X_Y:
std::swap(rayOrigin.y, rayOrigin.z);
std::swap(rayDirection.y, rayDirection.z);
break;
case ALIGN_Y_Z:
// x = z, z = y, y = -x
tmp.x = rayOrigin.z;
tmp.z = rayOrigin.y;
tmp.y = -rayOrigin.x;
rayOrigin = tmp;
tmp.x = rayDirection.z;
tmp.z = rayDirection.y;
tmp.y = -rayDirection.x;
rayDirection = tmp;
break;
case ALIGN_X_Z:
// already in X/Z but values increase in -Z
rayOrigin.z = -rayOrigin.z;
rayDirection.z = -rayDirection.z;
break;
}
// readjust coordinate origin
rayOrigin.x += mWorldSize/2;
rayOrigin.z += mWorldSize/2;
// scale down to vertex level
rayOrigin.x /= mScale;
rayOrigin.z /= mScale;
rayDirection.x /= mScale;
rayDirection.z /= mScale;
rayDirection.normalise();
Ray localRay (rayOrigin, rayDirection);
// test if the ray actually hits the terrain's bounds
Real maxHeight = getMaxHeight();
Real minHeight = getMinHeight();
AxisAlignedBox aabb (Vector3(0, minHeight, 0), Vector3(mSize, maxHeight, mSize));
std::pair<bool, Real> aabbTest = localRay.intersects(aabb);
if (!aabbTest.first)
{
if (cascadeToNeighbours)
{
Terrain* neighbour = raySelectNeighbour(ray, distanceLimit);
if (neighbour)
return neighbour->rayIntersects(ray, cascadeToNeighbours, distanceLimit);
}
return Result(false, Vector3());
}
// get intersection point and move inside
Vector3 cur = localRay.getPoint(aabbTest.second);
// now check every quad the ray touches
int quadX = std::min(std::max(static_cast<int>(cur.x), 0), (int)mSize-2);
int quadZ = std::min(std::max(static_cast<int>(cur.z), 0), (int)mSize-2);
int flipX = (rayDirection.x < 0 ? 0 : 1);
int flipZ = (rayDirection.z < 0 ? 0 : 1);
int xDir = (rayDirection.x < 0 ? -1 : 1);
int zDir = (rayDirection.z < 0 ? -1 : 1);
Result result(true, Vector3::ZERO);
Real dummyHighValue = (Real)mSize * 10000.0f;
while (cur.y >= (minHeight - 1e-3) && cur.y <= (maxHeight + 1e-3))
{
if (quadX < 0 || quadX >= (int)mSize-1 || quadZ < 0 || quadZ >= (int)mSize-1)
break;
result = checkQuadIntersection(quadX, quadZ, localRay);
if (result.first)
break;
// determine next quad to test
Real xDist = Math::RealEqual(rayDirection.x, 0.0) ? dummyHighValue :
(quadX - cur.x + flipX) / rayDirection.x;
Real zDist = Math::RealEqual(rayDirection.z, 0.0) ? dummyHighValue :
(quadZ - cur.z + flipZ) / rayDirection.z;
if (xDist < zDist)
{
quadX += xDir;
cur += rayDirection * xDist;
}
else
{
quadZ += zDir;
cur += rayDirection * zDist;
}
}
if (result.first)
{
// transform the point of intersection back to world space
result.second.x *= mScale;
result.second.z *= mScale;
result.second.x -= mWorldSize/2;
result.second.z -= mWorldSize/2;
switch (getAlignment())
{
case ALIGN_X_Y:
std::swap(result.second.y, result.second.z);
break;
case ALIGN_Y_Z:
// z = x, y = z, x = -y
tmp.x = -rayOrigin.y;
tmp.y = rayOrigin.z;
tmp.z = rayOrigin.x;
rayOrigin = tmp;
break;
case ALIGN_X_Z:
result.second.z = -result.second.z;
break;
}
result.second += getPosition();
}
else if (cascadeToNeighbours)
{
Terrain* neighbour = raySelectNeighbour(ray, distanceLimit);
if (neighbour)
result = neighbour->rayIntersects(ray, cascadeToNeighbours, distanceLimit);
}
return result;
}
//---------------------------------------------------------------------
std::pair<bool, Vector3> Terrain::checkQuadIntersection(int x, int z, const Ray& ray)
{
// build the two planes belonging to the quad's triangles
Vector3 v1 ((Real)x, *getHeightData(x,z), (Real)z);
Vector3 v2 ((Real)x+1, *getHeightData(x+1,z), (Real)z);
Vector3 v3 ((Real)x, *getHeightData(x,z+1), (Real)z+1);
Vector3 v4 ((Real)x+1, *getHeightData(x+1,z+1), (Real)z+1);
Plane p1, p2;
bool oddRow = false;
if (z % 2)
{
/* odd
3---4
| \ |
1---2
*/
p1.redefine(v2, v4, v3);
p2.redefine(v1, v2, v3);
oddRow = true;
}
else
{
/* even
3---4
| / |
1---2
*/
p1.redefine(v1, v2, v4);
p2.redefine(v1, v4, v3);
}
// Test for intersection with the two planes.
// Then test that the intersection points are actually
// still inside the triangle (with a small error margin)
// Also check which triangle it is in
std::pair<bool, Real> planeInt = ray.intersects(p1);
if (planeInt.first)
{
Vector3 where = ray.getPoint(planeInt.second);
Vector3 rel = where - v1;
if (rel.x >= -0.01 && rel.x <= 1.01 && rel.z >= -0.01 && rel.z <= 1.01 // quad bounds
&& ((rel.x >= rel.z && !oddRow) || (rel.x >= (1 - rel.z) && oddRow))) // triangle bounds
return std::pair<bool, Vector3>(true, where);
}
planeInt = ray.intersects(p2);
if (planeInt.first)
{
Vector3 where = ray.getPoint(planeInt.second);
Vector3 rel = where - v1;
if (rel.x >= -0.01 && rel.x <= 1.01 && rel.z >= -0.01 && rel.z <= 1.01 // quad bounds
&& ((rel.x <= rel.z && !oddRow) || (rel.x <= (1 - rel.z) && oddRow))) // triangle bounds
return std::pair<bool, Vector3>(true, where);
}
return std::pair<bool, Vector3>(false, Vector3());
}
//---------------------------------------------------------------------
const MaterialPtr& Terrain::getMaterial() const
{
if (mMaterial.isNull() ||
mMaterialGenerator->getChangeCount() != mMaterialGenerationCount ||
mMaterialDirty)
{
mMaterial = mMaterialGenerator->generate(this);
mMaterial->load();
if (mCompositeMapRequired)
{
mCompositeMapMaterial = mMaterialGenerator->generateForCompositeMap(this);
mCompositeMapMaterial->load();
}
mMaterialGenerationCount = mMaterialGenerator->getChangeCount();
mMaterialDirty = false;
}
if (mMaterialParamsDirty)
{
mMaterialGenerator->updateParams(mMaterial, this);
if(mCompositeMapRequired)
mMaterialGenerator->updateParamsForCompositeMap(mCompositeMapMaterial, this);
mMaterialParamsDirty = false;
}
return mMaterial;
}
//---------------------------------------------------------------------
const MaterialPtr& Terrain::getCompositeMapMaterial() const
{
// both materials updated together since they change at the same time
getMaterial();
return mCompositeMapMaterial;
}
//---------------------------------------------------------------------
void Terrain::checkLayers(bool includeGPUResources)
{
for (LayerInstanceList::iterator it = mLayers.begin(); it != mLayers.end(); ++it)
{
LayerInstance& layer = *it;
// If we're missing sampler entries compared to the declaration, initialise them
for (size_t i = layer.textureNames.size(); i < mLayerDecl.samplers.size(); ++i)
{
layer.textureNames.push_back(StringUtil::BLANK);
}
// if we have too many layers for the declaration, trim them
if (layer.textureNames.size() > mLayerDecl.samplers.size())
{
layer.textureNames.resize(mLayerDecl.samplers.size());
}
}
if (includeGPUResources)
{
createGPUBlendTextures();
createLayerBlendMaps();
}
}
//---------------------------------------------------------------------
void Terrain::checkDeclaration()
{
if (mMaterialGenerator.isNull())
{
mMaterialGenerator = TerrainGlobalOptions::getSingleton().getDefaultMaterialGenerator();
}
if (mLayerDecl.elements.empty())
{
// default the declaration
mLayerDecl = mMaterialGenerator->getLayerDeclaration();
}
}
//---------------------------------------------------------------------
void Terrain::replaceLayer(uint8 index, bool keepBlends, Real worldSize, const StringVector* textureNames)
{
if (getLayerCount() > 0)
{
if (index >= getLayerCount())
index = getLayerCount() - 1;
LayerInstanceList::iterator i = mLayers.begin();
std::advance(i, index);
if (textureNames)
{
(*i).textureNames = *textureNames;
}
// use utility method to update UV scaling
setLayerWorldSize(index, worldSize);
// Delete the blend map if its not the base
if ( !keepBlends && index > 0 )
{
if (mLayerBlendMapList[index-1])
{
delete mLayerBlendMapList[index-1];
mLayerBlendMapList[index-1] = 0;
}
// Reset the layer to black
std::pair<uint8,uint8> layerPair = getLayerBlendTextureIndex(index);
clearGPUBlendChannel( layerPair.first, layerPair.second );
}
mMaterialDirty = true;
mMaterialParamsDirty = true;
mModified = true;
}
}
//---------------------------------------------------------------------
void Terrain::addLayer(Real worldSize, const StringVector* textureNames)
{
addLayer(getLayerCount(), worldSize, textureNames);
}
//---------------------------------------------------------------------
void Terrain::addLayer(uint8 index, Real worldSize, const StringVector* textureNames)
{
if (!worldSize)
worldSize = TerrainGlobalOptions::getSingleton().getDefaultLayerTextureWorldSize();
uint8 blendIndex = std::max(index-1,0);
if (index >= getLayerCount())
{
mLayers.push_back(LayerInstance());
index = getLayerCount() - 1;
}
else
{
LayerInstanceList::iterator i = mLayers.begin();
std::advance(i, index);
mLayers.insert(i, LayerInstance());
RealVector::iterator uvi = mLayerUVMultiplier.begin();
std::advance(uvi, index);
mLayerUVMultiplier.insert(uvi, 0.0f);
TerrainLayerBlendMapList::iterator bi = mLayerBlendMapList.begin();
std::advance(bi, blendIndex);
mLayerBlendMapList.insert(bi, static_cast<TerrainLayerBlendMap*>(0));
}
if (textureNames)
{
LayerInstance& inst = mLayers[index];
inst.textureNames = *textureNames;
}
// use utility method to update UV scaling
setLayerWorldSize(index, worldSize);
checkLayers(true);
// Is this an insert into the middle of the layer list?
if (index < getLayerCount() - 1)
{
// Shift all GPU texture channels up one
shiftUpGPUBlendChannels(blendIndex);
// All blend maps above this layer index will need to be recreated since their buffers/channels have changed
deleteBlendMaps(index);
}
mMaterialDirty = true;
mMaterialParamsDirty = true;
mModified = true;
}
//---------------------------------------------------------------------
void Terrain::removeLayer(uint8 index)
{
if (index < mLayers.size())
{
uint8 blendIndex = std::max(index-1,0);
// Shift all GPU texture channels down one
shiftDownGPUBlendChannels(blendIndex);
LayerInstanceList::iterator i = mLayers.begin();
std::advance(i, index);
mLayers.erase(i);
RealVector::iterator uvi = mLayerUVMultiplier.begin();
std::advance(uvi, index);
mLayerUVMultiplier.erase(uvi);
if (mLayerBlendMapList.size() > 0)
{
// If they removed the base OR the first layer, we need to erase the first blend map
TerrainLayerBlendMapList::iterator bi = mLayerBlendMapList.begin();
std::advance(bi, blendIndex);
OGRE_DELETE *bi;
mLayerBlendMapList.erase(bi);
// Check to see if a GPU textures can be released
checkLayers(true);
// All blend maps for layers above the erased will need to be recreated since their buffers/channels have changed
deleteBlendMaps(blendIndex);
}
mMaterialDirty = true;
mMaterialParamsDirty = true;
mModified = true;
}
}
//---------------------------------------------------------------------
uint8 Terrain::getMaxLayers() const
{
return mMaterialGenerator->getMaxLayers(this);
}
//---------------------------------------------------------------------
TerrainLayerBlendMap* Terrain::getLayerBlendMap(uint8 layerIndex)
{
if (layerIndex == 0 || layerIndex-1 >= (uint8)mLayerBlendMapList.size())
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Invalid layer index", "Terrain::getLayerBlendMap");
uint8 idx = layerIndex - 1;
if (!mLayerBlendMapList[idx])
{
if (mBlendTextureList.size() < static_cast<size_t>(idx / 4))
checkLayers(true);
const TexturePtr& tex = mBlendTextureList[idx / 4];
mLayerBlendMapList[idx] = OGRE_NEW TerrainLayerBlendMap(this, layerIndex, tex->getBuffer().getPointer());
}
return mLayerBlendMapList[idx];
}
//---------------------------------------------------------------------
uint8 Terrain::getBlendTextureCount(uint8 numLayers) const
{
return ((numLayers - 1) / 4) + 1;
}
//---------------------------------------------------------------------
uint8 Terrain::getBlendTextureCount() const
{
return (uint8)mBlendTextureList.size();
}
//---------------------------------------------------------------------
PixelFormat Terrain::getBlendTextureFormat(uint8 textureIndex, uint8 numLayers)
{
/*
if (numLayers - 1 - (textureIndex * 4) > 3)
return PF_BYTE_RGBA;
else
return PF_BYTE_RGB;
*/
// Always create RGBA; no point trying to create RGB since all cards pad to 32-bit (XRGB)
// and it makes it harder to expand layer count dynamically if format has to change
return PF_BYTE_RGBA;
}
//---------------------------------------------------------------------
void Terrain::shiftUpGPUBlendChannels(uint8 index)
{
// checkLayers() has been called to make sure the blend textures have been created
assert( mBlendTextureList.size() == getBlendTextureCount(getLayerCount()) );
// Shift all blend channels > index UP one slot, possibly into the next texture
// Example: index = 2
// Before: [1 2 3 4] [5]
// After: [1 2 0 3] [4 5]
uint8 layerIndex = index + 1;
for (uint8 i=getLayerCount()-1; i > layerIndex; --i )
{
std::pair<uint8,uint8> destPair = getLayerBlendTextureIndex(i);
std::pair<uint8,uint8> srcPair = getLayerBlendTextureIndex(i - 1);
copyBlendTextureChannel( srcPair.first, srcPair.second, destPair.first, destPair.second );
}
// Reset the layer to black
std::pair<uint8,uint8> layerPair = getLayerBlendTextureIndex(layerIndex);
clearGPUBlendChannel( layerPair.first, layerPair.second );
}
//---------------------------------------------------------------------
void Terrain::shiftDownGPUBlendChannels(uint8 index)
{
// checkLayers() has been called to make sure the blend textures have been created
assert( mBlendTextureList.size() == getBlendTextureCount(getLayerCount()) );
// Shift all blend channels above layerIndex DOWN one slot, possibly into the previous texture
// Example: index = 2
// Before: [1 2 3 4] [5]
// After: [1 2 4 5] [0]
uint8 layerIndex = index + 1;
for (uint8 i=layerIndex; i < getLayerCount() - 1; ++i )
{
std::pair<uint8,uint8> destPair = getLayerBlendTextureIndex(i);
std::pair<uint8,uint8> srcPair = getLayerBlendTextureIndex(i + 1);
copyBlendTextureChannel( srcPair.first, srcPair.second, destPair.first, destPair.second );
}
// Reset the layer to black
if ( getLayerCount() > 1 )
{
std::pair<uint8,uint8> layerPair = getLayerBlendTextureIndex(getLayerCount() - 1);
clearGPUBlendChannel( layerPair.first, layerPair.second );
}
}
//---------------------------------------------------------------------
void Terrain::copyBlendTextureChannel(uint8 srcIndex, uint8 srcChannel, uint8 destIndex, uint8 destChannel )
{
HardwarePixelBufferSharedPtr srcBuffer = getLayerBlendTexture(srcIndex)->getBuffer();
HardwarePixelBufferSharedPtr destBuffer = getLayerBlendTexture(destIndex)->getBuffer();
unsigned char rgbaShift[4];
Image::Box box(0, 0, destBuffer->getWidth(), destBuffer->getHeight());
uint8* pDestBase = static_cast<uint8*>(destBuffer->lock(box, HardwareBuffer::HBL_NORMAL).data);
PixelUtil::getBitShifts(destBuffer->getFormat(), rgbaShift);
uint8* pDest = pDestBase + rgbaShift[destChannel] / 8;
size_t destInc = PixelUtil::getNumElemBytes(destBuffer->getFormat());
size_t srcInc;
uint8* pSrc;
if ( destBuffer == srcBuffer )
{
pSrc = pDestBase + rgbaShift[srcChannel] / 8;
srcInc = destInc;
}
else
{
pSrc = static_cast<uint8*>(srcBuffer->lock(box, HardwareBuffer::HBL_READ_ONLY).data);
PixelUtil::getBitShifts(srcBuffer->getFormat(), rgbaShift);
pSrc += rgbaShift[srcChannel] / 8;
srcInc = PixelUtil::getNumElemBytes(srcBuffer->getFormat());
}
for (size_t y = box.top; y < box.bottom; ++y)
{
for (size_t x = box.left; x < box.right; ++x)
{
*pDest = *pSrc;
pSrc += srcInc;
pDest += destInc;
}
}
destBuffer->unlock();
if ( destBuffer != srcBuffer )
srcBuffer->unlock();
}
//---------------------------------------------------------------------
void Terrain::clearGPUBlendChannel(uint8 index, uint channel)
{
HardwarePixelBufferSharedPtr buffer = getLayerBlendTexture(index)->getBuffer();
unsigned char rgbaShift[4];
Image::Box box(0, 0, buffer->getWidth(), buffer->getHeight());
uint8* pData = static_cast<uint8*>(buffer->lock(box, HardwareBuffer::HBL_NORMAL).data);
PixelUtil::getBitShifts(buffer->getFormat(), rgbaShift);
pData += rgbaShift[channel] / 8;
size_t inc = PixelUtil::getNumElemBytes(buffer->getFormat());
for (size_t y = box.top; y < box.bottom; ++y)
{
for (size_t x = box.left; x < box.right; ++x)
{
*pData = 0;
pData += inc;
}
}
buffer->unlock();
}
//---------------------------------------------------------------------
void Terrain::createGPUBlendTextures()
{
// Create enough RGBA/RGB textures to cope with blend layers
uint8 numTex = getBlendTextureCount(getLayerCount());
// delete extras
TextureManager* tmgr = TextureManager::getSingletonPtr();
if (!tmgr)
return;
while (mBlendTextureList.size() > numTex)
{
tmgr->remove(mBlendTextureList.back()->getHandle());
mBlendTextureList.pop_back();
}
uint8 currentTex = (uint8)mBlendTextureList.size();
mBlendTextureList.resize(numTex);
// create new textures
for (uint8 i = currentTex; i < numTex; ++i)
{
PixelFormat fmt = getBlendTextureFormat(i, getLayerCount());
// Use TU_STATIC because although we will update this, we won't do it every frame
// in normal circumstances, so we don't want TU_DYNAMIC. Also we will
// read it (if we've cleared local temp areas) so no WRITE_ONLY
mBlendTextureList[i] = TextureManager::getSingleton().createManual(
msBlendTextureGenerator.generate(), _getDerivedResourceGroup(),
TEX_TYPE_2D, mLayerBlendMapSize, mLayerBlendMapSize, 1, 0, fmt, TU_STATIC);
mLayerBlendMapSizeActual = mBlendTextureList[i]->getWidth();
if (mCpuBlendMapStorage.size() > i)
{
// Load blend data
PixelBox src(mLayerBlendMapSize, mLayerBlendMapSize, 1, fmt, mCpuBlendMapStorage[i]);
mBlendTextureList[i]->getBuffer()->blitFromMemory(src);
// release CPU copy, don't need it anymore
OGRE_FREE(mCpuBlendMapStorage[i], MEMCATEGORY_RESOURCE);
}
else
{
// initialise black
Box box(0, 0, mLayerBlendMapSize, mLayerBlendMapSize);
HardwarePixelBufferSharedPtr buf = mBlendTextureList[i]->getBuffer();
uint8* pInit = static_cast<uint8*>(buf->lock(box, HardwarePixelBuffer::HBL_DISCARD).data);
memset(pInit, 0, PixelUtil::getNumElemBytes(fmt) * mLayerBlendMapSize * mLayerBlendMapSize);
buf->unlock();
}
}
mCpuBlendMapStorage.clear();
}
//---------------------------------------------------------------------
void Terrain::createLayerBlendMaps()
{
// delete extra blend layers (affects GPU)
while (mLayerBlendMapList.size() > mLayers.size() - 1)
{
OGRE_DELETE mLayerBlendMapList.back();
mLayerBlendMapList.pop_back();
}
// resize up (initialises to 0, populate as necessary)
if ( mLayers.size() > 1 )
mLayerBlendMapList.resize(mLayers.size() - 1, 0);
}
//---------------------------------------------------------------------
void Terrain::createOrDestroyGPUNormalMap()
{
if (mNormalMapRequired && mTerrainNormalMap.isNull())
{
// create
mTerrainNormalMap = TextureManager::getSingleton().createManual(
mMaterialName + "/nm", _getDerivedResourceGroup(),
TEX_TYPE_2D, mSize, mSize, 1, 0, PF_BYTE_RGB, TU_STATIC);
// Upload loaded normal data if present
if (mCpuTerrainNormalMap)
{
mTerrainNormalMap->getBuffer()->blitFromMemory(*mCpuTerrainNormalMap);
OGRE_FREE(mCpuTerrainNormalMap->data, MEMCATEGORY_GENERAL);
OGRE_DELETE mCpuTerrainNormalMap;
mCpuTerrainNormalMap = 0;
}
}
else if (!mNormalMapRequired && !mTerrainNormalMap.isNull())
{
// destroy
TextureManager::getSingleton().remove(mTerrainNormalMap->getHandle());
mTerrainNormalMap.setNull();
}
}
//---------------------------------------------------------------------
void Terrain::freeTemporaryResources()
{
// CPU blend maps
for (BytePointerList::iterator i = mCpuBlendMapStorage.begin();
i != mCpuBlendMapStorage.end(); ++i)
{
OGRE_FREE(*i, MEMCATEGORY_RESOURCE);
}
mCpuBlendMapStorage.clear();
// Editable structures for blend layers (not needed at runtime, only blend textures are)
deleteBlendMaps(0);
}
//---------------------------------------------------------------------
void Terrain::deleteBlendMaps(uint8 lowIndex)
{
TerrainLayerBlendMapList::iterator i = mLayerBlendMapList.begin();
std::advance(i, lowIndex);
for (; i != mLayerBlendMapList.end(); ++i )
{
OGRE_DELETE *i;
*i = 0;
}
}
//---------------------------------------------------------------------
const TexturePtr& Terrain::getLayerBlendTexture(uint8 index)
{
assert(index < mBlendTextureList.size());
return mBlendTextureList[index];
}
//---------------------------------------------------------------------
std::pair<uint8,uint8> Terrain::getLayerBlendTextureIndex(uint8 layerIndex)
{
assert(layerIndex > 0 && layerIndex < mLayers.size());
uint8 idx = layerIndex - 1;
return std::pair<uint8, uint8>(idx / 4, idx % 4);
}
//---------------------------------------------------------------------
void Terrain::_setNormalMapRequired(bool normalMap)
{
if (normalMap != mNormalMapRequired)
{
mNormalMapRequired = normalMap;
// Check NPOT textures supported. We have to use NPOT textures to map
// texels to vertices directly!
if (!mNormalMapRequired && Root::getSingleton().getRenderSystem()
->getCapabilities()->hasCapability(RSC_NON_POWER_OF_2_TEXTURES))
{
mNormalMapRequired = false;
LogManager::getSingleton().stream(LML_CRITICAL) <<
"Terrain: Ignoring request for normal map generation since "
"non-power-of-two texture support is required.";
}
createOrDestroyGPUNormalMap();
// if we enabled, generate normal maps
if (mNormalMapRequired)
{
// update derived data for whole terrain, but just normals
mDirtyDerivedDataRect.left = mDirtyDerivedDataRect.top = 0;
mDirtyDerivedDataRect.right = mDirtyDerivedDataRect.bottom = mSize;
updateDerivedData(false, DERIVED_DATA_NORMALS);
}
}
}
//---------------------------------------------------------------------
void Terrain::_setLightMapRequired(bool lightMap, bool shadowsOnly)
{
if (lightMap != mLightMapRequired || shadowsOnly != mLightMapShadowsOnly)
{
mLightMapRequired = lightMap;
mLightMapShadowsOnly = shadowsOnly;
createOrDestroyGPULightmap();
// if we enabled, generate light maps
if (mLightMapRequired)
{
// update derived data for whole terrain, but just lightmap
mDirtyDerivedDataRect.left = mDirtyDerivedDataRect.top = 0;
mDirtyDerivedDataRect.right = mDirtyDerivedDataRect.bottom = mSize;
updateDerivedData(false, DERIVED_DATA_LIGHTMAP);
}
}
}
//---------------------------------------------------------------------
void Terrain::_setCompositeMapRequired(bool compositeMap)
{
if (compositeMap != mCompositeMapRequired)
{
mCompositeMapRequired = compositeMap;
createOrDestroyGPUCompositeMap();
// if we enabled, generate composite maps
if (mCompositeMapRequired)
{
mCompositeMapDirtyRect.left = mCompositeMapDirtyRect.top = 0;
mCompositeMapDirtyRect.right = mCompositeMapDirtyRect.bottom = mSize;
updateCompositeMap();
}
}
}
//---------------------------------------------------------------------
bool Terrain::_getUseVertexCompression() const
{
return mMaterialGenerator->isVertexCompressionSupported() &&
TerrainGlobalOptions::getSingleton().getUseVertexCompressionWhenAvailable();
}
//---------------------------------------------------------------------
bool Terrain::canHandleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ)
{
DerivedDataRequest ddr = any_cast<DerivedDataRequest>(req->getData());
// only deal with own requests
// we do this because if we delete a terrain we want any pending tasks to be discarded
if (ddr.terrain != this)
return false;
else
return RequestHandler::canHandleRequest(req, srcQ);
}
//---------------------------------------------------------------------
bool Terrain::canHandleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ)
{
DerivedDataRequest ddreq = any_cast<DerivedDataRequest>(res->getRequest()->getData());
// only deal with own requests
// we do this because if we delete a terrain we want any pending tasks to be discarded
if (ddreq.terrain != this)
return false;
else
return true;
}
//---------------------------------------------------------------------
WorkQueue::Response* Terrain::handleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ)
{
// Background thread (maybe)
DerivedDataRequest ddr = any_cast<DerivedDataRequest>(req->getData());
// only deal with own requests; we shouldn't ever get here though
if (ddr.terrain != this)
return 0;
DerivedDataResponse ddres;
ddres.remainingTypeMask = ddr.typeMask & DERIVED_DATA_ALL;
// Do only ONE type of task per background iteration, in order of priority
// this means we return faster, can abort faster and we repeat less redundant calcs
// we don't do this as separate requests, because we only want one background
// task per Terrain instance in flight at once
if (ddr.typeMask & DERIVED_DATA_DELTAS)
{
ddres.deltaUpdateRect = calculateHeightDeltas(ddr.dirtyRect);
ddres.remainingTypeMask &= ~ DERIVED_DATA_DELTAS;
}
else if (ddr.typeMask & DERIVED_DATA_NORMALS)
{
ddres.normalMapBox = calculateNormals(ddr.dirtyRect, ddres.normalUpdateRect);
ddres.remainingTypeMask &= ~ DERIVED_DATA_NORMALS;
}
else if (ddr.typeMask & DERIVED_DATA_LIGHTMAP)
{
ddres.lightMapBox = calculateLightmap(ddr.dirtyRect, ddr.lightmapExtraDirtyRect, ddres.lightmapUpdateRect);
ddres.remainingTypeMask &= ~ DERIVED_DATA_LIGHTMAP;
}
ddres.terrain = ddr.terrain;
WorkQueue::Response* response = OGRE_NEW WorkQueue::Response(req, true, Any(ddres));
return response;
}
//---------------------------------------------------------------------
void Terrain::handleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ)
{
// Main thread
DerivedDataResponse ddres = any_cast<DerivedDataResponse>(res->getData());
DerivedDataRequest ddreq = any_cast<DerivedDataRequest>(res->getRequest()->getData());
// only deal with own requests
if (ddreq.terrain != this)
return;
if ((ddreq.typeMask & DERIVED_DATA_DELTAS) &&
!(ddres.remainingTypeMask & DERIVED_DATA_DELTAS))
finaliseHeightDeltas(ddres.deltaUpdateRect, false);
if ((ddreq.typeMask & DERIVED_DATA_NORMALS) &&
!(ddres.remainingTypeMask & DERIVED_DATA_NORMALS))
{
finaliseNormals(ddres.normalUpdateRect, ddres.normalMapBox);
mCompositeMapDirtyRect.merge(ddreq.dirtyRect);
}
if ((ddreq.typeMask & DERIVED_DATA_LIGHTMAP) &&
!(ddres.remainingTypeMask & DERIVED_DATA_LIGHTMAP))
{
finaliseLightmap(ddres.lightmapUpdateRect, ddres.lightMapBox);
mCompositeMapDirtyRect.merge(ddreq.dirtyRect);
mCompositeMapDirtyRectLightmapUpdate = true;
}
mDerivedDataUpdateInProgress = false;
// Re-trigger another request if there are still things to do, or if
// we had a new request since this one
Rect newRect(0,0,0,0);
if (ddres.remainingTypeMask)
newRect.merge(ddreq.dirtyRect);
if (mDerivedUpdatePendingMask)
{
newRect.merge(mDirtyDerivedDataRect);
mDirtyDerivedDataRect.setNull();
}
Rect newLightmapExtraRect(0,0,0,0);
if (ddres.remainingTypeMask)
newLightmapExtraRect.merge(ddreq.lightmapExtraDirtyRect);
if (mDerivedUpdatePendingMask)
{
newLightmapExtraRect.merge(mDirtyLightmapFromNeighboursRect);
mDirtyLightmapFromNeighboursRect.setNull();
}
uint8 newMask = ddres.remainingTypeMask | mDerivedUpdatePendingMask;
if (newMask)
{
// trigger again
updateDerivedDataImpl(newRect, newLightmapExtraRect, false, newMask);
}
else
{
// we've finished all the background processes
// update the composite map if enabled
if (mCompositeMapRequired)
updateCompositeMap();
}
}
//---------------------------------------------------------------------
uint16 Terrain::getLODLevelWhenVertexEliminated(long x, long y)
{
// gets eliminated by either row or column first
return std::min(getLODLevelWhenVertexEliminated(x), getLODLevelWhenVertexEliminated(y));
}
//---------------------------------------------------------------------
uint16 Terrain::getLODLevelWhenVertexEliminated(long rowOrColulmn)
{
// LOD levels bisect the domain.
// start at the lowest detail
uint16 currentElim = (mSize - 1) / (mMinBatchSize - 1);
// start at a non-exitant LOD index, this applies to the min batch vertices
// which are never eliminated
uint16 currentLod = mNumLodLevels;
while (rowOrColulmn % currentElim)
{
// not on this boundary, look finer
currentElim = currentElim / 2;
--currentLod;
// This will always terminate since (anything % 1 == 0)
}
return currentLod;
}
//---------------------------------------------------------------------
PixelBox* Terrain::calculateNormals(const Rect &rect, Rect& finalRect)
{
// Widen the rectangle by 1 element in all directions since height
// changes affect neighbours normals
Rect widenedRect(
std::max(0L, rect.left - 1L),
std::max(0L, rect.top - 1L),
std::min((long)mSize, rect.right + 1L),
std::min((long)mSize, rect.bottom + 1L)
);
// allocate memory for RGB
uint8* pData = static_cast<uint8*>(
OGRE_MALLOC(widenedRect.width() * widenedRect.height() * 3, MEMCATEGORY_GENERAL));
PixelBox* pixbox = OGRE_NEW PixelBox(widenedRect.width(), widenedRect.height(), 1, PF_BYTE_RGB, pData);
// Evaluate normal like this
// 3---2---1
// | \ | / |
// 4---P---0
// | / | \ |
// 5---6---7
Plane plane;
for (long y = widenedRect.top; y < widenedRect.bottom; ++y)
{
for (long x = widenedRect.left; x < widenedRect.right; ++x)
{
Vector3 cumulativeNormal = Vector3::ZERO;
// Build points to sample
Vector3 centrePoint;
Vector3 adjacentPoints[8];
getPointFromSelfOrNeighbour(x , y, ¢rePoint);
getPointFromSelfOrNeighbour(x+1, y, &adjacentPoints[0]);
getPointFromSelfOrNeighbour(x+1, y+1, &adjacentPoints[1]);
getPointFromSelfOrNeighbour(x, y+1, &adjacentPoints[2]);
getPointFromSelfOrNeighbour(x-1, y+1, &adjacentPoints[3]);
getPointFromSelfOrNeighbour(x-1, y, &adjacentPoints[4]);
getPointFromSelfOrNeighbour(x-1, y-1, &adjacentPoints[5]);
getPointFromSelfOrNeighbour(x, y-1, &adjacentPoints[6]);
getPointFromSelfOrNeighbour(x+1, y-1, &adjacentPoints[7]);
for (int i = 0; i < 8; ++i)
{
plane.redefine(centrePoint, adjacentPoints[i], adjacentPoints[(i+1)%8]);
cumulativeNormal += plane.normal;
}
// normalise & store normal
cumulativeNormal.normalise();
// encode as RGB, object space
// invert the Y to deal with image space
long storeX = x - widenedRect.left;
long storeY = widenedRect.bottom - y - 1;
uint8* pStore = pData + ((storeY * widenedRect.width()) + storeX) * 3;
*pStore++ = static_cast<uint8>((cumulativeNormal.x + 1.0f) * 0.5f * 255.0f);
*pStore++ = static_cast<uint8>((cumulativeNormal.y + 1.0f) * 0.5f * 255.0f);
*pStore++ = static_cast<uint8>((cumulativeNormal.z + 1.0f) * 0.5f * 255.0f);
}
}
finalRect = widenedRect;
return pixbox;
}
//---------------------------------------------------------------------
void Terrain::finaliseNormals(const Ogre::Rect &rect, Ogre::PixelBox *normalsBox)
{
createOrDestroyGPUNormalMap();
// deal with race condition where nm has been disabled while we were working!
if (!mTerrainNormalMap.isNull())
{
// blit the normals into the texture
if (rect.left == 0 && rect.top == 0 && rect.bottom == mSize && rect.right == mSize)
{
mTerrainNormalMap->getBuffer()->blitFromMemory(*normalsBox);
}
else
{
// content of normalsBox is already inverted in Y, but rect is still
// in terrain space for dealing with sub-rect, so invert
Image::Box dstBox;
dstBox.left = rect.left;
dstBox.right = rect.right;
dstBox.top = mSize - rect.bottom;
dstBox.bottom = mSize - rect.top;
mTerrainNormalMap->getBuffer()->blitFromMemory(*normalsBox, dstBox);
}
}
// delete memory
OGRE_FREE(normalsBox->data, MEMCATEGORY_GENERAL);
OGRE_DELETE(normalsBox);
}
//---------------------------------------------------------------------
void Terrain::widenRectByVector(const Vector3& vec, const Rect& inRect, Rect& outRect)
{
widenRectByVector(vec, inRect, getMinHeight(), getMaxHeight(), outRect);
}
//---------------------------------------------------------------------
void Terrain::widenRectByVector(const Vector3& vec, const Rect& inRect,
Real minHeight, Real maxHeight, Rect& outRect)
{
outRect = inRect;
Plane p;
switch(getAlignment())
{
case ALIGN_X_Y:
p.redefine(Vector3::UNIT_Z, Vector3(0, 0, vec.z < 0.0 ? minHeight : maxHeight));
break;
case ALIGN_X_Z:
p.redefine(Vector3::UNIT_Y, Vector3(0, vec.y < 0.0 ? minHeight : maxHeight, 0));
break;
case ALIGN_Y_Z:
p.redefine(Vector3::UNIT_X, Vector3(vec.x < 0.0 ? minHeight : maxHeight, 0, 0));
break;
}
float verticalVal = vec.dotProduct(p.normal);
if (Math::RealEqual(verticalVal, 0.0))
return;
Vector3 corners[4];
Real startHeight = verticalVal < 0.0 ? maxHeight : minHeight;
getPoint(inRect.left, inRect.top, startHeight, &corners[0]);
getPoint(inRect.right-1, inRect.top, startHeight, &corners[1]);
getPoint(inRect.left, inRect.bottom-1, startHeight, &corners[2]);
getPoint(inRect.right-1, inRect.bottom-1, startHeight, &corners[3]);
for (int i = 0; i < 4; ++i)
{
Ray ray(corners[i] + mPos, vec);
std::pair<bool, Real> rayHit = ray.intersects(p);
if(rayHit.first)
{
Vector3 pt = ray.getPoint(rayHit.second);
// convert back to terrain point
Vector3 terrainHitPos;
getTerrainPosition(pt, &terrainHitPos);
// build rectangle which has rounded down & rounded up values
// remember right & bottom are exclusive
Rect mergeRect(
(long)(terrainHitPos.x * (mSize - 1)),
(long)(terrainHitPos.y * (mSize - 1)),
(long)(terrainHitPos.x * (float)(mSize - 1) + 0.5) + 1,
(long)(terrainHitPos.y * (float)(mSize - 1) + 0.5) + 1
);
outRect.merge(mergeRect);
}
}
}
//---------------------------------------------------------------------
PixelBox* Terrain::calculateLightmap(const Rect& rect, const Rect& extraTargetRect, Rect& outFinalRect)
{
// as well as calculating the lighting changes for the area that is
// dirty, we also need to calculate the effect on casting shadow on
// other areas. To do this, we project the dirt rect by the light direction
// onto the minimum height
const Vector3& lightVec = TerrainGlobalOptions::getSingleton().getLightMapDirection();
Ogre::Rect widenedRect;
widenRectByVector(lightVec, rect, widenedRect);
// merge in the extra area (e.g. from neighbours)
widenedRect.merge(extraTargetRect);
// widenedRect now contains terrain point space version of the area we
// need to calculate. However, we need to calculate in lightmap image space
float terrainToLightmapScale = (float)mLightmapSizeActual / (float)mSize;
widenedRect.left = (long)(widenedRect.left * terrainToLightmapScale);
widenedRect.right = (long)(widenedRect.right * terrainToLightmapScale);
widenedRect.top = (long)(widenedRect.top * terrainToLightmapScale);
widenedRect.bottom = (long)(widenedRect.bottom * terrainToLightmapScale);
// clamp
widenedRect.left = std::max(0L, widenedRect.left);
widenedRect.top = std::max(0L, widenedRect.top);
widenedRect.right = std::min((long)mLightmapSizeActual, widenedRect.right);
widenedRect.bottom = std::min((long)mLightmapSizeActual, widenedRect.bottom);
outFinalRect = widenedRect;
// allocate memory (L8)
uint8* pData = static_cast<uint8*>(
OGRE_MALLOC(widenedRect.width() * widenedRect.height(), MEMCATEGORY_GENERAL));
PixelBox* pixbox = OGRE_NEW PixelBox(widenedRect.width(), widenedRect.height(), 1, PF_L8, pData);
Real heightPad = (getMaxHeight() - getMinHeight()) * 1.0e-3f;
for (long y = widenedRect.top; y < widenedRect.bottom; ++y)
{
for (long x = widenedRect.left; x < widenedRect.right; ++x)
{
float litVal = 1.0f;
// convert to terrain space (not points, allow this to go between points)
float Tx = (float)x / (float)(mLightmapSizeActual-1);
float Ty = (float)y / (float)(mLightmapSizeActual-1);
// get world space point
// add a little height padding to stop shadowing self
Vector3 wpos = Vector3::ZERO;
getPosition(Tx, Ty, getHeightAtTerrainPosition(Tx, Ty) + heightPad, &wpos);
wpos += getPosition();
// build ray, cast backwards along light direction
Ray ray(wpos, -lightVec);
// Cascade into neighbours when casting, but don't travel further
// than world size
std::pair<bool, Vector3> rayHit = rayIntersects(ray, true, mWorldSize);
if (rayHit.first)
litVal = 0.0f;
// encode as L8
// invert the Y to deal with image space
long storeX = x - widenedRect.left;
long storeY = widenedRect.bottom - y - 1;
uint8* pStore = pData + ((storeY * widenedRect.width()) + storeX);
*pStore = (unsigned char)(litVal * 255.0);
}
}
return pixbox;
}
//---------------------------------------------------------------------
void Terrain::finaliseLightmap(const Rect& rect, PixelBox* lightmapBox)
{
createOrDestroyGPULightmap();
// deal with race condition where lm has been disabled while we were working!
if (!mLightmap.isNull())
{
// blit the normals into the texture
if (rect.left == 0 && rect.top == 0 && rect.bottom == mLightmapSizeActual && rect.right == mLightmapSizeActual)
{
mLightmap->getBuffer()->blitFromMemory(*lightmapBox);
}
else
{
// content of PixelBox is already inverted in Y, but rect is still
// in terrain space for dealing with sub-rect, so invert
Image::Box dstBox;
dstBox.left = rect.left;
dstBox.right = rect.right;
dstBox.top = mLightmapSizeActual - rect.bottom;
dstBox.bottom = mLightmapSizeActual - rect.top;
mLightmap->getBuffer()->blitFromMemory(*lightmapBox, dstBox);
}
}
// delete memory
OGRE_FREE(lightmapBox->data, MEMCATEGORY_GENERAL);
OGRE_DELETE(lightmapBox);
}
//---------------------------------------------------------------------
void Terrain::updateCompositeMap()
{
// All done in the render thread
if (mCompositeMapRequired && !mCompositeMapDirtyRect.isNull())
{
mModified = true;
createOrDestroyGPUCompositeMap();
if (mCompositeMapDirtyRectLightmapUpdate &&
(mCompositeMapDirtyRect.width() < mSize || mCompositeMapDirtyRect.height() < mSize))
{
// widen the dirty rectangle since lighting makes it wider
Rect widenedRect;
widenRectByVector(TerrainGlobalOptions::getSingleton().getLightMapDirection(), mCompositeMapDirtyRect, widenedRect);
// clamp
widenedRect.left = std::max(widenedRect.left, 0L);
widenedRect.top = std::max(widenedRect.top, 0L);
widenedRect.right = std::min(widenedRect.right, (long)mSize);
widenedRect.bottom = std::min(widenedRect.bottom, (long)mSize);
mMaterialGenerator->updateCompositeMap(this, widenedRect);
}
else
mMaterialGenerator->updateCompositeMap(this, mCompositeMapDirtyRect);
mCompositeMapDirtyRectLightmapUpdate = false;
mCompositeMapDirtyRect.setNull();
}
}
//---------------------------------------------------------------------
void Terrain::updateCompositeMapWithDelay(Real delay)
{
mCompositeMapUpdateCountdown = (long)(delay * 1000);
}
//---------------------------------------------------------------------
uint8 Terrain::getBlendTextureIndex(uint8 layerIndex) const
{
if (layerIndex == 0 || layerIndex-1 >= (uint8)mLayerBlendMapList.size())
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Invalid layer index", "Terrain::getBlendTextureIndex");
return (layerIndex - 1) % 4;
}
//---------------------------------------------------------------------
const String& Terrain::getBlendTextureName(uint8 textureIndex) const
{
if (textureIndex >= (uint8)mBlendTextureList.size())
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Invalid texture index", "Terrain::getBlendTextureName");
return mBlendTextureList[textureIndex]->getName();
}
//---------------------------------------------------------------------
void Terrain::setGlobalColourMapEnabled(bool enabled, uint16 sz)
{
if (!sz)
sz = TerrainGlobalOptions::getSingleton().getDefaultGlobalColourMapSize();
if (enabled != mGlobalColourMapEnabled ||
(enabled && mGlobalColourMapSize != sz))
{
mGlobalColourMapEnabled = enabled;
mGlobalColourMapSize = sz;
createOrDestroyGPUColourMap();
mMaterialDirty = true;
mMaterialParamsDirty = true;
mModified = true;
}
}
//---------------------------------------------------------------------
void Terrain::createOrDestroyGPUColourMap()
{
if (mGlobalColourMapEnabled && mColourMap.isNull())
{
// create
mColourMap = TextureManager::getSingleton().createManual(
mMaterialName + "/cm", _getDerivedResourceGroup(),
TEX_TYPE_2D, mGlobalColourMapSize, mGlobalColourMapSize, MIP_DEFAULT,
PF_BYTE_RGB, TU_STATIC);
if (mCpuColourMapStorage)
{
// Load cached data
PixelBox src(mGlobalColourMapSize, mGlobalColourMapSize, 1, PF_BYTE_RGB, mCpuColourMapStorage);
mColourMap->getBuffer()->blitFromMemory(src);
// release CPU copy, don't need it anymore
OGRE_FREE(mCpuColourMapStorage, MEMCATEGORY_RESOURCE);
mCpuColourMapStorage = 0;
}
}
else if (!mGlobalColourMapEnabled && !mColourMap.isNull())
{
// destroy
TextureManager::getSingleton().remove(mColourMap->getHandle());
mColourMap.setNull();
}
}
//---------------------------------------------------------------------
void Terrain::createOrDestroyGPULightmap()
{
if (mLightMapRequired && mLightmap.isNull())
{
// create
mLightmap = TextureManager::getSingleton().createManual(
mMaterialName + "/lm", _getDerivedResourceGroup(),
TEX_TYPE_2D, mLightmapSize, mLightmapSize, 0, PF_L8, TU_STATIC);
mLightmapSizeActual = mLightmap->getWidth();
if (mCpuLightmapStorage)
{
// Load cached data
PixelBox src(mLightmapSize, mLightmapSize, 1, PF_L8, mCpuLightmapStorage);
mLightmap->getBuffer()->blitFromMemory(src);
// release CPU copy, don't need it anymore
OGRE_FREE(mCpuLightmapStorage, MEMCATEGORY_RESOURCE);
mCpuLightmapStorage = 0;
}
else
{
// initialise to full-bright
Box box(0, 0, mLightmapSizeActual, mLightmapSizeActual);
HardwarePixelBufferSharedPtr buf = mLightmap->getBuffer();
uint8* pInit = static_cast<uint8*>(buf->lock(box, HardwarePixelBuffer::HBL_DISCARD).data);
memset(pInit, 255, mLightmapSizeActual * mLightmapSizeActual);
buf->unlock();
}
}
else if (!mLightMapRequired && !mLightmap.isNull())
{
// destroy
TextureManager::getSingleton().remove(mLightmap->getHandle());
mLightmap.setNull();
}
}
//---------------------------------------------------------------------
void Terrain::createOrDestroyGPUCompositeMap()
{
if (mCompositeMapRequired && mCompositeMap.isNull())
{
// create
mCompositeMap = TextureManager::getSingleton().createManual(
mMaterialName + "/comp", _getDerivedResourceGroup(),
TEX_TYPE_2D, mCompositeMapSize, mCompositeMapSize, 0, PF_BYTE_RGBA, TU_STATIC);
mCompositeMapSizeActual = mCompositeMap->getWidth();
if (mCpuCompositeMapStorage)
{
// Load cached data
PixelBox src(mCompositeMapSize, mCompositeMapSize, 1, PF_BYTE_RGBA, mCpuCompositeMapStorage);
mCompositeMap->getBuffer()->blitFromMemory(src);
// release CPU copy, don't need it anymore
OGRE_FREE(mCpuCompositeMapStorage, MEMCATEGORY_RESOURCE);
mCpuCompositeMapStorage = 0;
}
else
{
// initialise to black
Box box(0, 0, mCompositeMapSizeActual, mCompositeMapSizeActual);
HardwarePixelBufferSharedPtr buf = mCompositeMap->getBuffer();
uint8* pInit = static_cast<uint8*>(buf->lock(box, HardwarePixelBuffer::HBL_DISCARD).data);
memset(pInit, 0, mCompositeMapSizeActual * mCompositeMapSizeActual * 4);
buf->unlock();
}
}
else if (!mCompositeMapRequired && !mCompositeMap.isNull())
{
// destroy
TextureManager::getSingleton().remove(mCompositeMap->getHandle());
mCompositeMap.setNull();
}
}
//---------------------------------------------------------------------
Terrain* Terrain::getNeighbour(NeighbourIndex index)
{
return mNeighbours[index];
}
//---------------------------------------------------------------------
void Terrain::setNeighbour(NeighbourIndex index, Terrain* neighbour,
bool recalculate /*= false*/, bool notifyOther /* = true */)
{
if (mNeighbours[index] != neighbour)
{
assert(neighbour != this && "Can't set self as own neighbour!");
// detach existing
if (mNeighbours[index] && notifyOther)
mNeighbours[index]->setNeighbour(getOppositeNeighbour(index), 0, false, false);
mNeighbours[index] = neighbour;
if (neighbour && notifyOther)
mNeighbours[index]->setNeighbour(getOppositeNeighbour(index), this, recalculate, false);
if (recalculate)
{
// Recalculate, pass OUR edge rect
Rect edgerect;
getEdgeRect(index, 2, &edgerect);
neighbourModified(index, edgerect, edgerect);
}
}
}
//---------------------------------------------------------------------
Terrain::NeighbourIndex Terrain::getOppositeNeighbour(NeighbourIndex index)
{
int intindex = static_cast<int>(index);
intindex += NEIGHBOUR_COUNT / 2;
intindex = intindex % NEIGHBOUR_COUNT;
return static_cast<NeighbourIndex>(intindex);
}
//---------------------------------------------------------------------
Terrain::NeighbourIndex Terrain::getNeighbourIndex(long x, long y)
{
if (x < 0)
{
if (y < 0)
return NEIGHBOUR_SOUTHWEST;
else if (y > 0)
return NEIGHBOUR_NORTHWEST;
else
return NEIGHBOUR_WEST;
}
else if (x > 0)
{
if (y < 0)
return NEIGHBOUR_SOUTHEAST;
else if (y > 0)
return NEIGHBOUR_NORTHEAST;
else
return NEIGHBOUR_EAST;
}
if (y < 0)
{
if (x == 0)
return NEIGHBOUR_SOUTH;
}
else if (y > 0)
{
if (x == 0)
return NEIGHBOUR_NORTH;
}
return NEIGHBOUR_NORTH;
}
//---------------------------------------------------------------------
void Terrain::notifyNeighbours()
{
// There are 3 things that can need updating:
// Height at edge - match to neighbour (first one to update 'loses' to other since read-only)
// Normal at edge - use heights from across boundary too
// Shadows across edge
// The extent to which these can affect the current tile vary:
// Height at edge - only affected by a change at the adjoining edge / corner
// Normal at edge - only affected by a change to the 2 rows adjoining the edge / corner
// Shadows across edge - possible effect extends based on the projection of the
// neighbour AABB along the light direction (worst case scenario)
if (!mDirtyGeometryRectForNeighbours.isNull())
{
Rect dirtyRectForNeighbours(mDirtyGeometryRectForNeighbours);
mDirtyGeometryRectForNeighbours.setNull();
// calculate light update rectangle
const Vector3& lightVec = TerrainGlobalOptions::getSingleton().getLightMapDirection();
Rect lightmapRect;
widenRectByVector(lightVec, dirtyRectForNeighbours, getMinHeight(), getMaxHeight(), lightmapRect);
for (int i = 0; i < (int)NEIGHBOUR_COUNT; ++i)
{
NeighbourIndex ni = static_cast<NeighbourIndex>(i);
Terrain* neighbour = getNeighbour(ni);
if (!neighbour)
continue;
// Intersect the incoming rectangles with the edge regions related to this neighbour
Rect edgeRect;
getEdgeRect(ni, 2, &edgeRect);
Rect heightEdgeRect = edgeRect.intersect(dirtyRectForNeighbours);
Rect lightmapEdgeRect = edgeRect.intersect(lightmapRect);
if (!heightEdgeRect.isNull() || !lightmapRect.isNull())
{
// ok, we have something valid to pass on
Rect neighbourHeightEdgeRect, neighbourLightmapEdgeRect;
if (!heightEdgeRect.isNull())
getNeighbourEdgeRect(ni, heightEdgeRect, &neighbourHeightEdgeRect);
if (!lightmapRect.isNull())
getNeighbourEdgeRect(ni, lightmapEdgeRect, &neighbourLightmapEdgeRect);
neighbour->neighbourModified(getOppositeNeighbour(ni),
neighbourHeightEdgeRect, neighbourLightmapEdgeRect);
}
}
}
}
//---------------------------------------------------------------------
void Terrain::neighbourModified(NeighbourIndex index, const Rect& edgerect, const Rect& shadowrect)
{
// We can safely assume that we would not have been contacted if it wasn't
// important
const Terrain* neighbour = getNeighbour(index);
if (!neighbour)
return; // bogus request
bool updateGeom = false;
uint8 updateDerived = 0;
if (!edgerect.isNull())
{
// update edges; match heights first, then recalculate normals
// reduce to just single line / corner
Rect heightMatchRect;
getEdgeRect(index, 1, &heightMatchRect);
heightMatchRect = heightMatchRect.intersect(edgerect);
for (long y = heightMatchRect.top; y < heightMatchRect.bottom; ++y)
{
for (long x = heightMatchRect.left; x < heightMatchRect.right; ++x)
{
long nx, ny;
getNeighbourPoint(index, x, y, &nx, &ny);
float neighbourHeight = neighbour->getHeightAtPoint(nx, ny);
if (!Math::RealEqual(neighbourHeight, getHeightAtPoint(x, y), 1e-3f))
{
setHeightAtPoint(x, y, neighbourHeight);
if (!updateGeom)
{
updateGeom = true;
updateDerived |= DERIVED_DATA_ALL;
}
}
}
}
// if we didn't need to update heights, we still need to update normals
// because this was called only if neighbor changed
if (!updateGeom)
{
// ideally we would deal with normal dirty rect separately (as we do with
// lightmaps) because a dirty geom rectangle will actually grow by one
// element in each direction for normals recalculation. However for
// the sake of one row/column it's really not worth it.
mDirtyDerivedDataRect.merge(edgerect);
updateDerived |= DERIVED_DATA_NORMALS;
}
}
if (!shadowrect.isNull())
{
// update shadows
// here we need to widen the rect passed in based on the min/max height
// of the *neighbour*
const Vector3& lightVec = TerrainGlobalOptions::getSingleton().getLightMapDirection();
Rect widenedRect;
widenRectByVector(lightVec, shadowrect, neighbour->getMinHeight(), neighbour->getMaxHeight(), widenedRect);
// set the special-case lightmap dirty rectangle
mDirtyLightmapFromNeighboursRect.merge(widenedRect);
updateDerived |= DERIVED_DATA_LIGHTMAP;
}
if (updateGeom)
updateGeometry();
if (updateDerived)
updateDerivedData(false, updateDerived);
}
//---------------------------------------------------------------------
void Terrain::getEdgeRect(NeighbourIndex index, long range, Rect* outRect)
{
// We make the edge rectangle 2 rows / columns at the edge of the tile
// 2 because this copes with normal changes and potentially filtered
// shadows.
// all right / bottom values are exclusive
// terrain origin is bottom-left remember so north is highest value
// set left/right
switch(index)
{
case NEIGHBOUR_EAST:
case NEIGHBOUR_NORTHEAST:
case NEIGHBOUR_SOUTHEAST:
outRect->left = mSize - range;
outRect->right = mSize;
break;
case NEIGHBOUR_WEST:
case NEIGHBOUR_NORTHWEST:
case NEIGHBOUR_SOUTHWEST:
outRect->left = 0;
outRect->right = range;
break;
case NEIGHBOUR_NORTH:
case NEIGHBOUR_SOUTH:
outRect->left = 0;
outRect->right = mSize;
break;
case NEIGHBOUR_COUNT:
default:
break;
};
// set top / bottom
switch(index)
{
case NEIGHBOUR_NORTH:
case NEIGHBOUR_NORTHEAST:
case NEIGHBOUR_NORTHWEST:
outRect->top = mSize - range;
outRect->bottom = mSize;
break;
case NEIGHBOUR_SOUTH:
case NEIGHBOUR_SOUTHWEST:
case NEIGHBOUR_SOUTHEAST:
outRect->top = 0;
outRect->bottom = range;
break;
case NEIGHBOUR_EAST:
case NEIGHBOUR_WEST:
outRect->top = 0;
outRect->bottom = mSize;
break;
case NEIGHBOUR_COUNT:
default:
break;
};
}
//---------------------------------------------------------------------
void Terrain::getNeighbourEdgeRect(NeighbourIndex index, const Rect& inRect, Rect* outRect)
{
assert (mSize == getNeighbour(index)->getSize());
// Basically just reflect the rect
// remember index is neighbour relationship from OUR perspective so
// arrangement is backwards to getEdgeRect
// left/right
switch(index)
{
case NEIGHBOUR_EAST:
case NEIGHBOUR_NORTHEAST:
case NEIGHBOUR_SOUTHEAST:
case NEIGHBOUR_WEST:
case NEIGHBOUR_NORTHWEST:
case NEIGHBOUR_SOUTHWEST:
outRect->left = mSize - inRect.right;
outRect->right = mSize - inRect.left;
break;
default:
outRect->left = inRect.left;
outRect->right = inRect.right;
break;
};
// top / bottom
switch(index)
{
case NEIGHBOUR_NORTH:
case NEIGHBOUR_NORTHEAST:
case NEIGHBOUR_NORTHWEST:
case NEIGHBOUR_SOUTH:
case NEIGHBOUR_SOUTHWEST:
case NEIGHBOUR_SOUTHEAST:
outRect->top = mSize - inRect.bottom;
outRect->bottom = mSize - inRect.top;
break;
default:
outRect->top = inRect.top;
outRect->bottom = inRect.bottom;
break;
};
}
//---------------------------------------------------------------------
void Terrain::getNeighbourPoint(NeighbourIndex index, long x, long y, long *outx, long *outy)
{
// Get the index of the point we should be looking at on a neighbour
// in order to match up points
assert (mSize == getNeighbour(index)->getSize());
// left/right
switch(index)
{
case NEIGHBOUR_EAST:
case NEIGHBOUR_NORTHEAST:
case NEIGHBOUR_SOUTHEAST:
case NEIGHBOUR_WEST:
case NEIGHBOUR_NORTHWEST:
case NEIGHBOUR_SOUTHWEST:
*outx = mSize - x - 1;
break;
default:
*outx = x;
break;
};
// top / bottom
switch(index)
{
case NEIGHBOUR_NORTH:
case NEIGHBOUR_NORTHEAST:
case NEIGHBOUR_NORTHWEST:
case NEIGHBOUR_SOUTH:
case NEIGHBOUR_SOUTHWEST:
case NEIGHBOUR_SOUTHEAST:
*outy = mSize - y - 1;
break;
default:
*outy = y;
break;
};
}
//---------------------------------------------------------------------
void Terrain::getPointFromSelfOrNeighbour(long x, long y, Vector3* outpos)
{
if (x >= 0 && y >=0 && x < mSize && y < mSize)
getPoint(x, y, outpos);
else
{
long nx, ny;
NeighbourIndex ni = NEIGHBOUR_EAST;
getNeighbourPointOverflow(x, y, &ni, &nx, &ny);
Terrain* neighbour = getNeighbour(ni);
if (neighbour)
{
Vector3 neighbourPos = Vector3::ZERO;
neighbour->getPoint(nx, ny, &neighbourPos);
// adjust to make it relative to our position
*outpos = neighbourPos + neighbour->getPosition() - getPosition();
}
else
{
// use our getPoint() after all, just clamp
x = std::min(x, mSize - 1L);
y = std::min(y, mSize - 1L);
x = std::max(x, 0L);
y = std::max(y, 0L);
getPoint(x, y, outpos);
}
}
}
//---------------------------------------------------------------------
void Terrain::getNeighbourPointOverflow(long x, long y, NeighbourIndex *outindex, long *outx, long *outy)
{
if (x < 0)
{
*outx = x + mSize - 1;
if (y < 0)
*outindex = NEIGHBOUR_SOUTHWEST;
else if (y >= mSize)
*outindex = NEIGHBOUR_NORTHWEST;
else
*outindex = NEIGHBOUR_WEST;
}
else if (x >= mSize)
{
*outx = x - mSize + 1;
if (y < 0)
*outindex = NEIGHBOUR_SOUTHEAST;
else if (y >= mSize)
*outindex = NEIGHBOUR_NORTHEAST;
else
*outindex = NEIGHBOUR_EAST;
}
else
*outx = x;
if (y < 0)
{
*outy = y + mSize - 1;
if (x >= 0 && x < mSize)
*outindex = NEIGHBOUR_SOUTH;
}
else if (y >= mSize)
{
*outy = y - mSize + 1;
if (x >= 0 && x < mSize)
*outindex = NEIGHBOUR_NORTH;
}
else
*outy = y;
}
//---------------------------------------------------------------------
Terrain* Terrain::raySelectNeighbour(const Ray& ray, Real distanceLimit /* = 0 */)
{
Ray modifiedRay(ray.getOrigin(), ray.getDirection());
// Move back half a square - if we're on the edge of the AABB we might
// miss the intersection otherwise; it's ok for everywhere else since
// we want the far intersection anyway
modifiedRay.setOrigin(modifiedRay.getPoint(-mWorldSize/mSize * 0.5f));
// transform into terrain space
Vector3 tPos, tDir;
convertPosition(WORLD_SPACE, modifiedRay.getOrigin(), TERRAIN_SPACE, tPos);
convertDirection(WORLD_SPACE, modifiedRay.getDirection(), TERRAIN_SPACE, tDir);
// Discard rays with no lateral component
if (Math::RealEqual(tDir.x, 0.0f, 1e-4) && Math::RealEqual(tDir.y, 0.0f, 1e-4))
return 0;
Ray terrainRay(tPos, tDir);
// Intersect with boundary planes
// Only collide with the positive (exit) side of the plane, because we may be
// querying from a point outside ourselves if we've cascaded more than once
Real dist = std::numeric_limits<Real>::max();
std::pair<bool, Real> intersectResult;
if (tDir.x < 0.0f)
{
intersectResult = Math::intersects(terrainRay, Plane(Vector3::UNIT_X, Vector3::ZERO));
if (intersectResult.first && intersectResult.second < dist)
dist = intersectResult.second;
}
else if (tDir.x > 0.0f)
{
intersectResult = Math::intersects(terrainRay, Plane(Vector3::NEGATIVE_UNIT_X, Vector3(1,0,0)));
if (intersectResult.first && intersectResult.second < dist)
dist = intersectResult.second;
}
if (tDir.y < 0.0f)
{
intersectResult = Math::intersects(terrainRay, Plane(Vector3::UNIT_Y, Vector3::ZERO));
if (intersectResult.first && intersectResult.second < dist)
dist = intersectResult.second;
}
else if (tDir.y > 0.0f)
{
intersectResult = Math::intersects(terrainRay, Plane(Vector3::NEGATIVE_UNIT_Y, Vector3(0,1,0)));
if (intersectResult.first && intersectResult.second < dist)
dist = intersectResult.second;
}
// discard out of range
if (dist * mWorldSize > distanceLimit)
return 0;
Vector3 terrainIntersectPos = terrainRay.getPoint(dist);
Real x = terrainIntersectPos.x;
Real y = terrainIntersectPos.y;
Real dx = tDir.x;
Real dy = tDir.y;
// Never return diagonal directions, we will navigate those recursively anyway
if (Math::RealEqual(x, 1.0f, 1e-4f) && dx > 0)
return getNeighbour(NEIGHBOUR_EAST);
else if (Math::RealEqual(x, 0.0f, 1e-4f) && dx < 0)
return getNeighbour(NEIGHBOUR_WEST);
else if (Math::RealEqual(y, 1.0f, 1e-4f) && dy > 0)
return getNeighbour(NEIGHBOUR_NORTH);
else if (Math::RealEqual(y, 0.0f, 1e-4f) && dy < 0)
return getNeighbour(NEIGHBOUR_SOUTH);
return 0;
}
//---------------------------------------------------------------------
void Terrain::_dumpTextures(const String& prefix, const String& suffix)
{
if (!mTerrainNormalMap.isNull())
{
Image img;
mTerrainNormalMap->convertToImage(img);
img.save(prefix + "_normalmap" + suffix);
}
if (!mColourMap.isNull())
{
Image img;
mColourMap->convertToImage(img);
img.save(prefix + "_colourmap" + suffix);
}
if (!mLightmap.isNull())
{
Image img;
mLightmap->convertToImage(img);
img.save(prefix + "_lightmap" + suffix);
}
if (!mCompositeMap.isNull())
{
Image img;
mCompositeMap->convertToImage(img);
img.save(prefix + "_compositemap" + suffix);
}
int blendTexture = 0;
for (TexturePtrList::iterator i = mBlendTextureList.begin(); i != mBlendTextureList.end(); ++i, ++blendTexture)
{
if (!i->isNull())
{
Image img;
(*i)->convertToImage(img);
img.save(prefix + "_blendtexture" + StringConverter::toString(blendTexture) + suffix);
}
}
}
//---------------------------------------------------------------------
void Terrain::setGpuBufferAllocator(GpuBufferAllocator* alloc)
{
if (alloc != getGpuBufferAllocator())
{
if (isLoaded())
OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
"Cannot alter the allocator when loaded!", __FUNCTION__);
mCustomGpuBufferAllocator = alloc;
}
}
//---------------------------------------------------------------------
Terrain::GpuBufferAllocator* Terrain::getGpuBufferAllocator()
{
if (mCustomGpuBufferAllocator)
return mCustomGpuBufferAllocator;
else
return &mDefaultGpuBufferAllocator;
}
//---------------------------------------------------------------------
size_t Terrain::getPositionBufVertexSize() const
{
size_t sz = 0;
if (_getUseVertexCompression())
{
// short2 position
sz += sizeof(short) * 2;
// float1 height
sz += sizeof(float);
}
else
{
// float3 position
sz += sizeof(float) * 3;
// float2 uv
sz += sizeof(float) * 2;
}
return sz;
}
//---------------------------------------------------------------------
size_t Terrain::getDeltaBufVertexSize() const
{
// float2(delta, deltaLODthreshold)
return sizeof(float) * 2;
}
//---------------------------------------------------------------------
size_t Terrain::_getNumIndexesForBatchSize(uint16 batchSize)
{
size_t mainIndexesPerRow = batchSize * 2 + 1;
size_t numRows = batchSize - 1;
size_t mainIndexCount = mainIndexesPerRow * numRows;
// skirts share edges, so they take 1 less row per side than batchSize,
// but with 2 extra at the end (repeated) to finish the strip
// * 2 for the vertical line, * 4 for the sides, +2 to finish
size_t skirtIndexCount = (batchSize - 1) * 2 * 4 + 2;
return mainIndexCount + skirtIndexCount;
}
//---------------------------------------------------------------------
void Terrain::_populateIndexBuffer(uint16* pI, uint16 batchSize,
uint16 vdatasize, size_t vertexIncrement, uint16 xoffset, uint16 yoffset, uint16 numSkirtRowsCols,
uint16 skirtRowColSkip)
{
/* For even / odd tri strip rows, triangles are this shape:
6---7---8
| \ | \ |
3---4---5
| / | / |
0---1---2
Note how vertex rows count upwards. In order to match up the anti-clockwise
winding and this upward transitioning list, we need to start from the
right hand side. So we get (2,5,1,4,0,3) etc on even lines (right-left)
and (3,6,4,7,5,8) etc on odd lines (left-right). At the turn, we emit the end index
twice, this forms a degenerate triangle, which lets us turn without any artefacts.
So the full list in this simple case is (2,5,1,4,0,3,3,6,4,7,5,8)
Skirts are part of the same strip, so after finishing on 8, where sX is
the skirt vertex corresponding to main vertex X, we go
anticlockwise around the edge, (s8,7,s7,6,s6) to do the top skirt,
then (3,s3,0,s0),(1,s1,2,s2),(5,s5,8,s8) to finish the left, bottom, and
right skirts respectively.
*/
// to issue a complete row, it takes issuing the upper and lower row
// and one extra index, which is the degenerate triangle and also turning
// around the winding
size_t rowSize = vdatasize * vertexIncrement;
size_t numRows = batchSize - 1;
// Start on the right
uint16 currentVertex = (batchSize - 1) * vertexIncrement;
// but, our quad area might not start at 0 in this vertex data
// offsets are at main terrain resolution, remember
uint16 columnStart = xoffset;
uint16 rowStart = yoffset;
currentVertex += rowStart * vdatasize + columnStart;
bool rightToLeft = true;
for (uint16 r = 0; r < numRows; ++r)
{
for (uint16 c = 0; c < batchSize; ++c)
{
*pI++ = currentVertex;
*pI++ = currentVertex + rowSize;
// don't increment / decrement at a border, keep this vertex for next
// row as we 'snake' across the tile
if (c+1 < batchSize)
{
currentVertex = rightToLeft ?
currentVertex - vertexIncrement : currentVertex + vertexIncrement;
}
}
rightToLeft = !rightToLeft;
currentVertex += rowSize;
// issue one extra index to turn winding around
*pI++ = currentVertex;
}
// Skirts
for (uint16 s = 0; s < 4; ++s)
{
// edgeIncrement is the index offset from one original edge vertex to the next
// in this row or column. Columns skip based on a row size here
// skirtIncrement is the index offset from one skirt vertex to the next,
// because skirts are packed in rows/cols then there is no row multiplier for
// processing columns
int edgeIncrement = 0, skirtIncrement = 0;
switch(s)
{
case 0: // top
edgeIncrement = -static_cast<int>(vertexIncrement);
skirtIncrement = -static_cast<int>(vertexIncrement);
break;
case 1: // left
edgeIncrement = -static_cast<int>(rowSize);
skirtIncrement = -static_cast<int>(vertexIncrement);
break;
case 2: // bottom
edgeIncrement = static_cast<int>(vertexIncrement);
skirtIncrement = static_cast<int>(vertexIncrement);
break;
case 3: // right
edgeIncrement = static_cast<int>(rowSize);
skirtIncrement = static_cast<int>(vertexIncrement);
break;
}
// Skirts are stored in contiguous rows / columns (rows 0/2, cols 1/3)
uint16 skirtIndex = _calcSkirtVertexIndex(currentVertex, vdatasize,
(s % 2) != 0, numSkirtRowsCols, skirtRowColSkip);
for (uint16 c = 0; c < batchSize - 1; ++c)
{
*pI++ = currentVertex;
*pI++ = skirtIndex;
currentVertex += edgeIncrement;
skirtIndex += skirtIncrement;
}
if (s == 3)
{
// we issue an extra 2 indices to finish the skirt off
*pI++ = currentVertex;
*pI++ = skirtIndex;
currentVertex += edgeIncrement;
}
}
}
//---------------------------------------------------------------------
uint16 Terrain::_calcSkirtVertexIndex(uint16 mainIndex, uint16 vdatasize, bool isCol,
uint16 numSkirtRowsCols, uint16 skirtRowColSkip)
{
// row / col in main vertex resolution
uint16 row = mainIndex / vdatasize;
uint16 col = mainIndex % vdatasize;
// skrits are after main vertices, so skip them
uint16 base = vdatasize * vdatasize;
// The layout in vertex data is:
// 1. row skirts
// numSkirtRowsCols rows of resolution vertices each
// 2. column skirts
// numSkirtRowsCols cols of resolution vertices each
// No offsets used here, this is an index into the current vertex data,
// which is already relative
if (isCol)
{
uint16 skirtNum = col / skirtRowColSkip;
uint16 colbase = numSkirtRowsCols * vdatasize;
return base + colbase + vdatasize * skirtNum + row;
}
else
{
uint16 skirtNum = row / skirtRowColSkip;
return base + vdatasize * skirtNum + col;
}
}
//---------------------------------------------------------------------
void Terrain::setWorldSize(Real newWorldSize)
{
if(mWorldSize != newWorldSize)
{
waitForDerivedProcesses();
mWorldSize = newWorldSize;
updateBaseScale();
deriveUVMultipliers();
mMaterialParamsDirty = true;
if(mIsLoaded)
{
Rect dRect(0, 0, mSize, mSize);
dirtyRect(dRect);
update();
}
mModified = true;
}
}
//---------------------------------------------------------------------
void Terrain::setSize(uint16 newSize)
{
if(mSize != newSize)
{
waitForDerivedProcesses();
size_t numVertices = newSize * newSize;
PixelBox src(mSize, mSize, 1, Ogre::PF_FLOAT32_R, (void*)getHeightData());
float* tmpData = OGRE_ALLOC_T(float, numVertices, MEMCATEGORY_GENERAL);
PixelBox dst(newSize, newSize, 1, Ogre::PF_FLOAT32_R, tmpData);
Image::scale(src, dst, Image::FILTER_BILINEAR);
freeCPUResources();
mSize = newSize;
determineLodLevels();
updateBaseScale();
deriveUVMultipliers();
mMaterialParamsDirty = true;
mHeightData = tmpData;
mDeltaData = OGRE_ALLOC_T(float, numVertices, MEMCATEGORY_GEOMETRY);
memset(mDeltaData, 0, sizeof(float) * numVertices);
mQuadTree = OGRE_NEW TerrainQuadTreeNode(this, 0, 0, 0, mSize, mNumLodLevels - 1, 0, 0);
mQuadTree->prepare();
// calculate entire terrain
Rect rect;
rect.top = 0; rect.bottom = mSize;
rect.left = 0; rect.right = mSize;
calculateHeightDeltas(rect);
finaliseHeightDeltas(rect, true);
distributeVertexData();
if(mIsLoaded)
{
if (mQuadTree)
mQuadTree->load();
}
mModified = true;
}
}
//---------------------------------------------------------------------
//---------------------------------------------------------------------
Terrain::DefaultGpuBufferAllocator::DefaultGpuBufferAllocator()
{
}
//---------------------------------------------------------------------
Terrain::DefaultGpuBufferAllocator::~DefaultGpuBufferAllocator()
{
freeAllBuffers();
}
//---------------------------------------------------------------------
void Terrain::DefaultGpuBufferAllocator::allocateVertexBuffers(Terrain* forTerrain,
size_t numVertices, HardwareVertexBufferSharedPtr& destPos, HardwareVertexBufferSharedPtr& destDelta)
{
destPos = getVertexBuffer(mFreePosBufList, forTerrain->getPositionBufVertexSize(), numVertices);
destDelta = getVertexBuffer(mFreeDeltaBufList, forTerrain->getDeltaBufVertexSize(), numVertices);
}
//---------------------------------------------------------------------
HardwareVertexBufferSharedPtr Terrain::DefaultGpuBufferAllocator::getVertexBuffer(
VBufList& list, size_t vertexSize, size_t numVertices)
{
size_t sz = vertexSize * numVertices;
for (VBufList::iterator i = list.begin(); i != list.end(); ++i)
{
if ((*i)->getSizeInBytes() == sz)
{
HardwareVertexBufferSharedPtr ret = *i;
list.erase(i);
return ret;
}
}
// Didn't find one?
return HardwareBufferManager::getSingleton()
.createVertexBuffer(vertexSize, numVertices, HardwareBuffer::HBU_STATIC_WRITE_ONLY);
}
//---------------------------------------------------------------------
void Terrain::DefaultGpuBufferAllocator::freeVertexBuffers(
const HardwareVertexBufferSharedPtr& posbuf, const HardwareVertexBufferSharedPtr& deltabuf)
{
mFreePosBufList.push_back(posbuf);
mFreeDeltaBufList.push_back(deltabuf);
}
//---------------------------------------------------------------------
HardwareIndexBufferSharedPtr Terrain::DefaultGpuBufferAllocator::getSharedIndexBuffer(uint16 batchSize,
uint16 vdatasize, size_t vertexIncrement, uint16 xoffset, uint16 yoffset, uint16 numSkirtRowsCols,
uint16 skirtRowColSkip)
{
uint32 hsh = hashIndexBuffer(batchSize, vdatasize, vertexIncrement, xoffset, yoffset,
numSkirtRowsCols, skirtRowColSkip);
IBufMap::iterator i = mSharedIBufMap.find(hsh);
if (i == mSharedIBufMap.end())
{
// create new
size_t indexCount = Terrain::_getNumIndexesForBatchSize(batchSize);
HardwareIndexBufferSharedPtr ret = HardwareBufferManager::getSingleton()
.createIndexBuffer(HardwareIndexBuffer::IT_16BIT, indexCount,
HardwareBuffer::HBU_STATIC_WRITE_ONLY);
uint16* pI = static_cast<uint16*>(ret->lock(HardwareBuffer::HBL_DISCARD));
Terrain::_populateIndexBuffer(pI, batchSize, vdatasize, vertexIncrement, xoffset, yoffset, numSkirtRowsCols, skirtRowColSkip);
ret->unlock();
mSharedIBufMap[hsh] = ret;
return ret;
}
else
return i->second;
}
//---------------------------------------------------------------------
void Terrain::DefaultGpuBufferAllocator::freeAllBuffers()
{
mFreePosBufList.clear();
mFreeDeltaBufList.clear();
mSharedIBufMap.clear();
}
//---------------------------------------------------------------------
void Terrain::DefaultGpuBufferAllocator::warmStart(size_t numInstances, uint16 terrainSize, uint16 maxBatchSize,
uint16 mMinBatchSize)
{
// TODO
}
//---------------------------------------------------------------------
uint32 Terrain::DefaultGpuBufferAllocator::hashIndexBuffer(uint16 batchSize,
uint16 vdatasize, size_t vertexIncrement, uint16 xoffset, uint16 yoffset, uint16 numSkirtRowsCols,
uint16 skirtRowColSkip)
{
uint32 ret = 0;
ret = HashCombine(ret, batchSize);
ret = HashCombine(ret, vdatasize);
ret = HashCombine(ret, vertexIncrement);
ret = HashCombine(ret, xoffset);
ret = HashCombine(ret, yoffset);
ret = HashCombine(ret, numSkirtRowsCols);
ret = HashCombine(ret, skirtRowColSkip);
return ret;
}
}
| bhlzlx/ogre | Components/Terrain/src/OgreTerrain.cpp | C++ | mit | 145,401 |
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Resources;
namespace Microsoft.HockeyApp
{
public class LocalizedStrings
{
private static ResourceWrapper _localizedResources = null;
public static dynamic LocalizedResources {
get {
if (_localizedResources == null)
{
_localizedResources = new ResourceWrapper();
}
return _localizedResources;
}
}
}
public class ResourceWrapper : DynamicObject
{
private ResourceLoader _customResLoader;
internal ResourceLoader CustomResourceLoader
{
get { return _customResLoader; }
set { _customResLoader = value; }
}
private ResourceLoader _internalResLoader;
internal ResourceLoader InternalResourceLoader
{
get { return _internalResLoader; }
set { _internalResLoader = value; }
}
internal ResourceWrapper()
{
InternalResourceLoader = ResourceLoader.GetForViewIndependentUse(Tools.WebBrowserHelper.AssemblyNameWithoutExtension + "/Resources");
try
{ //try to load .resw if available in project!
CustomResourceLoader = ResourceLoader.GetForViewIndependentUse(Tools.WebBrowserHelper.AssemblyNameWithoutExtension);
}
catch (Exception) { }
}
public object this[string index]
{
get
{
string value = null;
if (_customResLoader != null)
{
value = _customResLoader.GetString(index);
}
if (String.IsNullOrEmpty(value))
{
value = _internalResLoader.GetString(index);
}
if (String.IsNullOrEmpty(value))
{
value = index + "_i18n";
}
return value;
}
}
//For dynamic use in code
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = this[binder.Name];
return result != null;
}
}
}
| dkackman/HockeySDK-Windows | Src/Kit.WP81/Universal/LocalizedStrings.cs | C# | mit | 2,406 |
<?php
/*
* WellCommerce Open-Source E-Commerce Platform
*
* This file is part of the WellCommerce package.
*
* (c) Adam Piotrowski <adam@wellcommerce.org>
*
* For the full copyright and license information,
* please view the LICENSE file that was distributed with this source code.
*/
namespace WellCommerce\Bundle\AppBundle\Controller\Admin;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use WellCommerce\Bundle\AppBundle\Entity\Client;
use WellCommerce\Bundle\CoreBundle\Controller\Admin\AbstractAdminController;
/**
* Class ClientController
*
* @author Adam Piotrowski <adam@wellcommerce.org>
*/
class ClientController extends AbstractAdminController
{
public function addAction(Request $request): Response
{
/** @var Client $resource */
$resource = $this->getManager()->initResource();
$form = $this->formBuilder->createForm($resource, [
'validation_groups' => ['client_admin_registration']
]);
if ($form->handleRequest()->isSubmitted()) {
if ($form->isValid()) {
$this->getManager()->createResource($resource);
$password = $form->getValue()['required_data']['clientDetails']['clientDetails.hashedPassword'];
$this->getMailerHelper()->sendEmail([
'recipient' => $resource->getContactDetails()->getEmail(),
'subject' => $this->getTranslatorHelper()->trans('client.email.heading.register'),
'template' => 'WellCommerceAppBundle:Email:register_admin.html.twig',
'parameters' => [
'client' => $resource,
'password' => $password,
],
'configuration' => $resource->getShop()->getMailerConfiguration(),
]);
}
return $this->createFormDefaultJsonResponse($form);
}
return $this->displayTemplate('add', [
'form' => $form,
]);
}
public function detailsAction(Client $client): Response
{
$data = $this->get('serializer')->serialize($client, 'json', ['group' => 'client']);
return new Response($data);
}
}
| diversantvlz/WellCommerce | src/WellCommerce/Bundle/AppBundle/Controller/Admin/ClientController.php | PHP | mit | 2,342 |
'use strict';
module.exports = function copyto(grunt) {
// Load task
grunt.loadNpmTasks('grunt-copy-to');
// Options
return {
build: {
files: [{
cwd: 'src',
src: ['**/*.json'],
dest: '.dist/'
},{
cwd: 'src',
src: ['public/css/**/*.less'],
dest: '.dist/'
}]
}
};
};
| samsel/Gander | tasks/copyto.js | JavaScript | mit | 436 |
/*
define(['iframeResizerContent'], function() {
describe('ParentIFrame methods: ', function() {
var id = 'parentIFrame';
var log = LOG;
it('Get ID of iFrame is same as iFrame', function() {
mockInitFromParent(id,log);
expect(window.parentIFrame.getId()).toBe(id);
closeChild();
});
it('call methods', function() {
var count = 0;
mockInitFromParent(id,false,function(msg){
switch(++count){
case 2:
expect(msg.split('#')[1]).toBe('foo');
break;
case 3:
expect(strEnd(msg,5)).toBe('reset');
break;
case 4:
expect(msg).toBe('foo');
break;
case 5:
expect(msg).toBe('foo');
break;
case 6:
expect(msg).toBe('foo');
break;
case 7:
expect(msg).toBe('foo');
break;
case 8:
expect(msg).toBe('foo');
break;
}
});
expect(window.parentIFrame.getId()).toBe(id);
window.parentIFrame.moveToAnchor('foo');
//window.parentIFrame.reset();
//setTimeout(closeChild,1);
});
});
});
*/ | tlan16/sushi-co | web/protected/controls/iframeResizer/doc/spec/parentIFrameMethodsSpec.js | JavaScript | mit | 1,024 |
package appeng.api.me.util;
/**
* Pretty much just a place holder right now
*
*/
public interface ICraftRequest {
}
| ExtraCells/ExtraCells1 | src/api/java/appeng/api/me/util/ICraftRequest.java | Java | mit | 121 |
<?php
namespace Lib\Services;
/**
* Internal utility component
*
* @depends service session
* @depends service profiler
*/
class Util extends \Base\Service
{
protected $messages = [];
protected $memory = [
'start' => 0,
'end' => 0 ];
protected $time = [
'start' => 0,
'end' => 0 ];
public function addMessage( $message, $type = SUCCESS )
{
if ( is_array( $message ) )
{
foreach ( $message as $m )
{
$this->messages[] = [ $type => $m ];
}
}
else
{
$this->messages[] = [ $type => $message ];
}
}
public function getMessages()
{
return $this->messages;
}
public function setFlash( $messages )
{
$session = $this->getService( 'session' );
$flash = $session->get( 'flash' );
if ( ! is_array( $flash ) )
{
$flash = [];
}
$flash = array_merge( $flash, $messages );
$session->set( 'flash', $flash );
}
public function getFlash()
{
$session = $this->getService( 'session' );
$flash = $session->get( 'flash' );
$session->remove( 'flash' );
return $flash;
}
public function clearMessages()
{
$this->messages = [];
}
public function startBenchmark()
{
$this->memory[ 'start' ] = memory_get_usage();
$this->time[ 'start' ] = microtime( TRUE );
}
public function stopBenchmark()
{
$this->memory[ 'end' ] = memory_get_usage();
$this->time[ 'end' ] = microtime( TRUE );
}
public function resetBenchmarks()
{
$this->memory = [
'start' => 0,
'end' => 0 ];
$this->time = [
'start' => 0,
'end' => 0 ];
}
public function getMemoryUsage()
{
return $this->memory[ 'end' ] - $this->memory[ 'start' ];
}
public function getPeakMemoryUsage()
{
return memory_get_peak_usage();
}
public function getExecutionTime()
{
return $this->time[ 'end' ] - $this->time[ 'start' ];
}
public function getQueryProfiles()
{
$profiler = $this->getService( 'profiler' );
$profiles = $profiler->getProfiles();
$return = [];
foreach ( (array) $profiles as $profile )
{
$return[] = [
'statement' => $profile->getSQLStatement(),
'start_time' => $profile->getInitialTime(),
'end_time' => $profile->getFinalTime(),
'elapsed_time' => $profile->getTotalElapsedSeconds() ];
}
return $return;
}
public function getDebugInfo()
{
return [
'session_id' => $this->getService( 'session' )->getId(),
'memory' => $this->getMemoryUsage(),
'memory_human' => human_bytes( $this->getMemoryUsage() ),
'peak_memory' => self::getPeakMemoryUsage(),
'peak_memory_human' => human_bytes( $this->getPeakMemoryUsage() ),
'time' => $this->getExecutionTime(),
'time_human' => round( $this->getExecutionTime() * 1000, 2 ) .' ms',
'query_profiles' => $this->getQueryProfiles() ];
}
} | iGusev/phalcon-boilerplate | app/library/Services/Util.php | PHP | mit | 3,314 |
require 'rubygems'
module YARD
module Templates::Helpers
# Helper methods for loading and managing markup types.
module MarkupHelper
class << self
# Clears the markup provider cache information. Mainly used for testing.
# @return [void]
def clear_markup_cache
self.markup_cache = {}
end
# @return [Hash{Symbol=>{(:provider,:class)=>Object}}] the cached markup providers
# @private
# @since 0.6.4
attr_accessor :markup_cache
end
MarkupHelper.clear_markup_cache
# The default list of markup providers for each markup type
MARKUP_PROVIDERS = {
:markdown => [
{:lib => :redcarpet, :const => 'RedcarpetCompat'},
{:lib => :rdiscount, :const => 'RDiscount'},
{:lib => :kramdown, :const => 'Kramdown::Document'},
{:lib => :bluecloth, :const => 'BlueCloth'},
{:lib => :maruku, :const => 'Maruku'},
{:lib => :'rpeg-markdown', :const => 'PEGMarkdown'},
{:lib => :rdoc, :const => 'YARD::Templates::Helpers::Markup::RDocMarkdown'},
],
:textile => [
{:lib => :redcloth, :const => 'RedCloth'},
],
:textile_strict => [
{:lib => :redcloth, :const => 'RedCloth'},
],
:rdoc => [
{:lib => nil, :const => 'YARD::Templates::Helpers::Markup::RDocMarkup'},
],
:asciidoc => [
{:lib => :asciidoctor, :const => 'Asciidoctor'}
],
:ruby => [],
:text => [],
:pre => [],
:html => [],
:none => [],
}
# Returns a list of extensions for various markup types. To register
# extensions for a type, add them to the array of extensions for the
# type.
# @since 0.6.0
MARKUP_EXTENSIONS = {
:html => ['htm', 'html', 'shtml'],
:text => ['txt'],
:textile => ['textile', 'txtile'],
:asciidoc => ['asciidoc'],
:markdown => ['markdown', 'md', 'mdown', 'mkd'],
:rdoc => ['rdoc'],
:ruby => ['rb', 'ru']
}
# Contains the Regexp object that matches the shebang line of extra
# files to detect the markup type.
MARKUP_FILE_SHEBANG = /\A#!(\S+)\s*$/
# Attempts to load the first valid markup provider in {MARKUP_PROVIDERS}.
# If a provider is specified, immediately try to load it.
#
# On success this sets `@markup_provider` and `@markup_class` to
# the provider name and library constant class/module respectively for
# the loaded provider.
#
# On failure this method will inform the user that no provider could be
# found and exit the program.
#
# @return [Boolean] whether the markup provider was successfully loaded.
def load_markup_provider(type = options.markup)
return true if MarkupHelper.markup_cache[type]
MarkupHelper.markup_cache[type] ||= {}
providers = MARKUP_PROVIDERS[type.to_sym]
return true if providers && providers.empty?
if providers && options.markup_provider
providers = providers.select {|p| p[:lib] == options.markup_provider }
end
if providers == nil || providers.empty?
log.error "Invalid markup type '#{type}' or markup provider " +
"(#{options.markup_provider}) is not registered."
return false
end
# Search for provider, return the library class name as const if found
providers.each do |provider|
begin require provider[:lib].to_s; rescue LoadError; next end if provider[:lib]
begin klass = eval("::" + provider[:const]); rescue NameError; next end
MarkupHelper.markup_cache[type][:provider] = provider[:lib] # Cache the provider
MarkupHelper.markup_cache[type][:class] = klass
return true
end
# Show error message telling user to install first potential provider
name, lib = *[providers.first[:const], providers.first[:lib] || type]
log.error "Missing '#{lib}' gem for #{type.to_s.capitalize} formatting. Install it with `gem install #{lib}`"
false
end
# Checks for a shebang or looks at the file extension to determine
# the markup type for the file contents. File extensions are registered
# for a markup type in {MARKUP_EXTENSIONS}.
#
# A shebang should be on the first line of a file and be in the form:
#
# #!markup_type
#
# Standard markup types are text, html, rdoc, markdown, textile
#
# @param [String] contents Unused. Was necessary prior to 0.7.0.
# Newer versions of YARD use {CodeObjects::ExtraFileObject#contents}
# @return [Symbol] the markup type recognized for the file
# @see MARKUP_EXTENSIONS
# @since 0.6.0
def markup_for_file(contents, filename)
if contents && contents =~ MARKUP_FILE_SHEBANG # Shebang support
return $1.to_sym
end
ext = (File.extname(filename)[1..-1] || '').downcase
MARKUP_EXTENSIONS.each do |type, exts|
return type if exts.include?(ext)
end
options.markup
end
# Strips any shebang lines on the file contents that pertain to
# markup or preprocessing data.
#
# @deprecated Use {CodeObjects::ExtraFileObject#contents} instead
# @return [String] the file contents minus any preprocessing tags
# @since 0.6.0
def markup_file_contents(contents)
contents =~ MARKUP_FILE_SHEBANG ? $' : contents
end
# Gets the markup provider class/module constant for a markup type
# Call {#load_markup_provider} before using this method.
#
# @param [Symbol] type the markup type (:rdoc, :markdown, etc.)
# @return [Class] the markup class
def markup_class(type = options.markup)
load_markup_provider(type)
MarkupHelper.markup_cache[type][:class]
end
# Gets the markup provider name for a markup type
# Call {#load_markup_provider} before using this method.
#
# @param [Symbol] type the markup type (:rdoc, :markdown, etc.)
# @return [Symbol] the markup provider name (usually the gem name of the library)
def markup_provider(type = options.markup)
MarkupHelper.markup_cache[type][:provider]
end
end
end
end
| sourcegraph/srclib-ruby | yard/lib/yard/templates/helpers/markup_helper.rb | Ruby | mit | 6,420 |
/**
* Copyright (c) 2015-2016 Angelo ZERR.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation
*/
package ts.eclipse.ide.jsdt.internal.ui;
import ts.eclipse.ide.jsdt.ui.PreferenceConstants;
/**
* Defines the constants used in the <code>org.eclipse.ui.themes</code>
* extension contributed by this plug-in.
*
*
*/
public interface ITypeScriptThemeConstants {
String ID_PREFIX = JSDTTypeScriptUIPlugin.PLUGIN_ID + "."; //$NON-NLS-1$
/**
* A theme constant that holds the color used to render JSX tag border
* constants.
*/
public final String EDITOR_TYPESCRIPT_DECORATOR_COLOR = ID_PREFIX
+ PreferenceConstants.EDITOR_TYPESCRIPT_DECORATOR_COLOR;
/**
* A theme constant that holds the color used to render JSX tag border
* constants.
*/
public final String EDITOR_JSX_TAG_BORDER_COLOR = ID_PREFIX + PreferenceConstants.EDITOR_JSX_TAG_BORDER_COLOR;
/**
* A theme constant that holds the color used to render JSX tag name
* constants.
*/
public final String EDITOR_JSX_TAG_NAME_COLOR = ID_PREFIX + PreferenceConstants.EDITOR_JSX_TAG_NAME_COLOR;
/**
* A theme constant that holds the color used to render JSX tag attribute
* name constants.
*/
public final String EDITOR_JSX_TAG_ATTRIBUTE_NAME_COLOR = ID_PREFIX
+ PreferenceConstants.EDITOR_JSX_TAG_ATTRIBUTE_NAME_COLOR;
/**
* A theme constant that holds the color used to render JSX tag attribute
* value constants.
*/
public final String EDITOR_JSX_TAG_ATTRIBUTE_VALUE_COLOR = ID_PREFIX
+ PreferenceConstants.EDITOR_JSX_TAG_ATTRIBUTE_VALUE_COLOR;
}
| angelozerr/typescript.java | eclipse/jsdt/ts.eclipse.ide.jsdt.ui/src/ts/eclipse/ide/jsdt/internal/ui/ITypeScriptThemeConstants.java | Java | mit | 1,914 |
import * as React from 'react';
import { BsPrefixComponent } from './helpers';
declare class ModalTitle<
As extends React.ReactType = 'div'
> extends BsPrefixComponent<As> {}
export default ModalTitle;
| glenjamin/react-bootstrap | types/components/ModalTitle.d.ts | TypeScript | mit | 207 |
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* The "deployments" collection of methods.
* Typical usage is:
* <code>
* $deploymentmanagerService = new Google_Service_DeploymentManager(...);
* $deployments = $deploymentmanagerService->deployments;
* </code>
*/
class Google_Service_DeploymentManager_Resource_Deployments extends Google_Service_Resource
{
/**
* Cancels and removes the preview currently associated with the deployment.
* (deployments.cancelPreview)
*
* @param string $project The project ID for this request.
* @param string $deployment The name of the deployment for this request.
* @param Google_Service_DeploymentManager_DeploymentsCancelPreviewRequest $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_DeploymentManager_Operation
*/
public function cancelPreview($project, $deployment, Google_Service_DeploymentManager_DeploymentsCancelPreviewRequest $postBody, $optParams = array())
{
$params = array('project' => $project, 'deployment' => $deployment, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('cancelPreview', array($params), "Google_Service_DeploymentManager_Operation");
}
/**
* Deletes a deployment and all of the resources in the deployment.
* (deployments.delete)
*
* @param string $project The project ID for this request.
* @param string $deployment The name of the deployment for this request.
* @param array $optParams Optional parameters.
*
* @opt_param string deletePolicy Sets the policy to use for deleting resources.
* @return Google_Service_DeploymentManager_Operation
*/
public function delete($project, $deployment, $optParams = array())
{
$params = array('project' => $project, 'deployment' => $deployment);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params), "Google_Service_DeploymentManager_Operation");
}
/**
* Gets information about a specific deployment. (deployments.get)
*
* @param string $project The project ID for this request.
* @param string $deployment The name of the deployment for this request.
* @param array $optParams Optional parameters.
* @return Google_Service_DeploymentManager_Deployment
*/
public function get($project, $deployment, $optParams = array())
{
$params = array('project' => $project, 'deployment' => $deployment);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_DeploymentManager_Deployment");
}
/**
* Gets the access control policy for a resource. May be empty if no such policy
* or resource exists. (deployments.getIamPolicy)
*
* @param string $project Project ID for this request.
* @param string $resource Name of the resource for this request.
* @param array $optParams Optional parameters.
* @return Google_Service_DeploymentManager_Policy
*/
public function getIamPolicy($project, $resource, $optParams = array())
{
$params = array('project' => $project, 'resource' => $resource);
$params = array_merge($params, $optParams);
return $this->call('getIamPolicy', array($params), "Google_Service_DeploymentManager_Policy");
}
/**
* Creates a deployment and all of the resources described by the deployment
* manifest. (deployments.insert)
*
* @param string $project The project ID for this request.
* @param Google_Service_DeploymentManager_Deployment $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string createPolicy Sets the policy to use for creating new
* resources.
* @opt_param bool preview If set to true, creates a deployment and creates
* "shell" resources but does not actually instantiate these resources. This
* allows you to preview what your deployment looks like. After previewing a
* deployment, you can deploy your resources by making a request with the
* update() method or you can use the cancelPreview() method to cancel the
* preview altogether. Note that the deployment will still exist after you
* cancel the preview and you must separately delete this deployment if you want
* to remove it.
* @return Google_Service_DeploymentManager_Operation
*/
public function insert($project, Google_Service_DeploymentManager_Deployment $postBody, $optParams = array())
{
$params = array('project' => $project, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('insert', array($params), "Google_Service_DeploymentManager_Operation");
}
/**
* Lists all deployments for a given project. (deployments.listDeployments)
*
* @param string $project The project ID for this request.
* @param array $optParams Optional parameters.
*
* @opt_param string filter A filter expression that filters resources listed in
* the response. The expression must specify the field name, a comparison
* operator, and the value that you want to use for filtering. The value must be
* a string, a number, or a boolean. The comparison operator must be either =,
* !=, >, or <.
*
* For example, if you are filtering Compute Engine instances, you can exclude
* instances named example-instance by specifying name != example-instance.
*
* You can also filter nested fields. For example, you could specify
* scheduling.automaticRestart = false to include instances only if they are not
* scheduled for automatic restarts. You can use filtering on nested fields to
* filter based on resource labels.
*
* To filter on multiple expressions, provide each separate expression within
* parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform =
* "Intel Skylake"). By default, each expression is an AND expression. However,
* you can include AND and OR expressions explicitly. For example, (cpuPlatform
* = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND
* (scheduling.automaticRestart = true).
* @opt_param string maxResults The maximum number of results per page that
* should be returned. If the number of available results is larger than
* maxResults, Compute Engine returns a nextPageToken that can be used to get
* the next page of results in subsequent list requests. Acceptable values are 0
* to 500, inclusive. (Default: 500)
* @opt_param string orderBy Sorts list results by a certain order. By default,
* results are returned in alphanumerical order based on the resource name.
*
* You can also sort results in descending order based on the creation timestamp
* using orderBy="creationTimestamp desc". This sorts results based on the
* creationTimestamp field in reverse chronological order (newest result first).
* Use this to sort resources like operations so that the newest operation is
* returned first.
*
* Currently, only sorting by name or creationTimestamp desc is supported.
* @opt_param string pageToken Specifies a page token to use. Set pageToken to
* the nextPageToken returned by a previous list request to get the next page of
* results.
* @return Google_Service_DeploymentManager_DeploymentsListResponse
*/
public function listDeployments($project, $optParams = array())
{
$params = array('project' => $project);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_DeploymentManager_DeploymentsListResponse");
}
/**
* Updates a deployment and all of the resources described by the deployment
* manifest. This method supports patch semantics. (deployments.patch)
*
* @param string $project The project ID for this request.
* @param string $deployment The name of the deployment for this request.
* @param Google_Service_DeploymentManager_Deployment $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string createPolicy Sets the policy to use for creating new
* resources.
* @opt_param string deletePolicy Sets the policy to use for deleting resources.
* @opt_param bool preview If set to true, updates the deployment and creates
* and updates the "shell" resources but does not actually alter or instantiate
* these resources. This allows you to preview what your deployment will look
* like. You can use this intent to preview how an update would affect your
* deployment. You must provide a target.config with a configuration if this is
* set to true. After previewing a deployment, you can deploy your resources by
* making a request with the update() or you can cancelPreview() to remove the
* preview altogether. Note that the deployment will still exist after you
* cancel the preview and you must separately delete this deployment if you want
* to remove it.
* @return Google_Service_DeploymentManager_Operation
*/
public function patch($project, $deployment, Google_Service_DeploymentManager_Deployment $postBody, $optParams = array())
{
$params = array('project' => $project, 'deployment' => $deployment, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('patch', array($params), "Google_Service_DeploymentManager_Operation");
}
/**
* Sets the access control policy on the specified resource. Replaces any
* existing policy. (deployments.setIamPolicy)
*
* @param string $project Project ID for this request.
* @param string $resource Name of the resource for this request.
* @param Google_Service_DeploymentManager_Policy $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_DeploymentManager_Policy
*/
public function setIamPolicy($project, $resource, Google_Service_DeploymentManager_Policy $postBody, $optParams = array())
{
$params = array('project' => $project, 'resource' => $resource, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('setIamPolicy', array($params), "Google_Service_DeploymentManager_Policy");
}
/**
* Stops an ongoing operation. This does not roll back any work that has already
* been completed, but prevents any new work from being started.
* (deployments.stop)
*
* @param string $project The project ID for this request.
* @param string $deployment The name of the deployment for this request.
* @param Google_Service_DeploymentManager_DeploymentsStopRequest $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_DeploymentManager_Operation
*/
public function stop($project, $deployment, Google_Service_DeploymentManager_DeploymentsStopRequest $postBody, $optParams = array())
{
$params = array('project' => $project, 'deployment' => $deployment, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('stop', array($params), "Google_Service_DeploymentManager_Operation");
}
/**
* Returns permissions that a caller has on the specified resource.
* (deployments.testIamPermissions)
*
* @param string $project Project ID for this request.
* @param string $resource Name of the resource for this request.
* @param Google_Service_DeploymentManager_TestPermissionsRequest $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_DeploymentManager_TestPermissionsResponse
*/
public function testIamPermissions($project, $resource, Google_Service_DeploymentManager_TestPermissionsRequest $postBody, $optParams = array())
{
$params = array('project' => $project, 'resource' => $resource, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('testIamPermissions', array($params), "Google_Service_DeploymentManager_TestPermissionsResponse");
}
/**
* Updates a deployment and all of the resources described by the deployment
* manifest. (deployments.update)
*
* @param string $project The project ID for this request.
* @param string $deployment The name of the deployment for this request.
* @param Google_Service_DeploymentManager_Deployment $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string createPolicy Sets the policy to use for creating new
* resources.
* @opt_param string deletePolicy Sets the policy to use for deleting resources.
* @opt_param bool preview If set to true, updates the deployment and creates
* and updates the "shell" resources but does not actually alter or instantiate
* these resources. This allows you to preview what your deployment will look
* like. You can use this intent to preview how an update would affect your
* deployment. You must provide a target.config with a configuration if this is
* set to true. After previewing a deployment, you can deploy your resources by
* making a request with the update() or you can cancelPreview() to remove the
* preview altogether. Note that the deployment will still exist after you
* cancel the preview and you must separately delete this deployment if you want
* to remove it.
* @return Google_Service_DeploymentManager_Operation
*/
public function update($project, $deployment, Google_Service_DeploymentManager_Deployment $postBody, $optParams = array())
{
$params = array('project' => $project, 'deployment' => $deployment, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('update', array($params), "Google_Service_DeploymentManager_Operation");
}
}
| githubmoros/myclinicsoft | vendor/google/apiclient-services/src/Google/Service/DeploymentManager/Resource/Deployments.php | PHP | mit | 14,180 |
import expect from 'expect';
import isFunction from '../../../src/validation/validators/isFunction';
describe('validators', () => {
describe('toFunction', () => {
it('should return infoObject if requested', () => {
expect(isFunction(null, true))
.toEqual({
type: 'Function',
required: false,
canBeEmpty: null,
converter: undefined,
unmanagedObject: false,
});
});
it('should validate a function correctly', () => {
expect(isFunction(() => {}))
.toBe(true);
});
it('should validate a function correctly when undefined', () => {
expect(isFunction(undefined))
.toBe(true);
});
it('should return error if value is not a function', () => {
expect(isFunction(1))
.toInclude('not a function');
});
it('should allow undefined and null', () => {
expect(isFunction(null))
.toBe(true);
expect(isFunction(undefined))
.toBe(true);
});
});
});
| vgno/roc-config | test/validation/validators/isFunction.js | JavaScript | mit | 1,209 |
using DomainModel.DTO;
using DomainModel.Enum;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Web.Http;
namespace PingerAPI.Controllers
{
public class TaskController : ApiController
{
[HttpPost]
public async Task<List<TaskDTO>> CheckTaskStatus(List<TaskDTO> list)
{
foreach (var item in list)
{
switch (item.TaskType)
{
case (int)TaskTypeEnum.WebSite:
await CheckWebsiteStatus(item);
break;
case (int)TaskTypeEnum.Server:
await CheckServerNDBStatus(item);
break;
case (int)TaskTypeEnum.Database:
await CheckServerNDBStatus(item);
break;
default:
break;
}
}
return list;
}
private async Task<bool> CheckWebsiteStatus(TaskDTO obj)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create((obj.Entity.IndexOf("://") == -1) ?
"http://" + obj.Entity : obj.Entity);
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
{
if (response.StatusCode == HttpStatusCode.OK)
{
if (obj.PreviousState != (int)TaskStatusEnum.Alive)
{
obj.UpdatedState = (int)TaskStatusEnum.Alive;
}
}
}
return true;
}
catch
{
}
if (obj.PreviousState != (int)TaskStatusEnum.Dead)
{
obj.UpdatedState = (int)TaskStatusEnum.Dead;
}
return true;
}
private async Task<bool> CheckServerNDBStatus(TaskDTO obj)
{
try
{
string[] list = obj.Entity.Split(':');
TcpClient client = new TcpClient();
await client.ConnectAsync(list[0], Convert.ToInt32(list[1]));
if (obj.PreviousState != (int)TaskStatusEnum.Alive)
{
obj.UpdatedState = (int)TaskStatusEnum.Alive;
}
return true;
}
catch
{
}
if (obj.PreviousState != (int)TaskStatusEnum.Dead)
{
obj.UpdatedState = (int)TaskStatusEnum.Dead;
}
return true;
}
}
} | Anvesh-Reddy/Pinger | PingerAPI/PingerAPI/Controllers/TaskController.cs | C# | mit | 2,814 |
/*!
* NETEYE Activity Indicator jQuery Plugin
*
* Copyright (c) 2010 NETEYE GmbH
* Licensed under the MIT license
*
* Author: Felix Gnass [fgnass at neteye dot de]
* Version: 1.0.0
*/
/**
* Plugin that renders a customisable activity indicator (spinner) using SVG or VML.
*/
(function($) {
$.fn.activity = function(opts) {
this.each(function() {
var $this = $(this);
var el = $this.data('activity');
if (el) {
clearInterval(el.data('interval'));
el.remove();
$this.removeData('activity');
}
if (opts !== false) {
opts = $.extend({color: $this.css('color')}, $.fn.activity.defaults, opts);
el = render($this, opts).css('position', 'absolute').prependTo(opts.outside ? 'body' : $this);
var h = $this.outerHeight() - el.height();
var w = $this.outerWidth() - el.width();
var margin = {
top: opts.valign == 'top' ? opts.padding : opts.valign == 'bottom' ? h - opts.padding : Math.floor(h / 2),
left: opts.align == 'left' ? opts.padding : opts.align == 'right' ? w - opts.padding : Math.floor(w / 2)
};
var offset = $this.offset();
if (opts.outside) {
el.css({top: offset.top + 'px', left: offset.left + 'px'});
}
else {
margin.top -= el.offset().top - offset.top;
margin.left -= el.offset().left - offset.left;
}
el.css({marginTop: margin.top + 'px', marginLeft: margin.left + 'px'});
animate(el, opts.segments, Math.round(10 / opts.speed) / 10);
$this.data('activity', el);
}
});
return this;
};
$.fn.activity.defaults = {
segments: 12,
space: 3,
length: 7,
width: 4,
speed: 1.2,
align: 'center',
valign: 'center',
padding: 4
};
$.fn.activity.getOpacity = function(opts, i) {
var steps = opts.steps || opts.segments-1;
var end = opts.opacity !== undefined ? opts.opacity : 1/steps;
return 1 - Math.min(i, steps) * (1 - end) / steps;
};
/**
* Default rendering strategy. If neither SVG nor VML is available, a div with class-name 'busy'
* is inserted, that can be styled with CSS to display an animated gif as fallback.
*/
var render = function() {
return $('<div>').addClass('busy');
};
/**
* The default animation strategy does nothing as we expect an animated gif as fallback.
*/
var animate = function() {
};
/**
* Utility function to create elements in the SVG namespace.
*/
function svg(tag, attr) {
var el = document.createElementNS("http://www.w3.org/2000/svg", tag || 'svg');
if (attr) {
$.each(attr, function(k, v) {
el.setAttributeNS(null, k, v);
});
}
return $(el);
}
if (document.createElementNS && document.createElementNS( "http://www.w3.org/2000/svg", "svg").createSVGRect) {
// =======================================================================================
// SVG Rendering
// =======================================================================================
/**
* Rendering strategy that creates a SVG tree.
*/
render = function(target, d) {
var innerRadius = d.width*2 + d.space;
var r = (innerRadius + d.length + Math.ceil(d.width / 2) + 1);
var el = svg().width(r*2).height(r*2);
var g = svg('g', {
'stroke-width': d.width,
'stroke-linecap': 'round',
stroke: d.color
}).appendTo(svg('g', {transform: 'translate('+ r +','+ r +')'}).appendTo(el));
for (var i = 0; i < d.segments; i++) {
g.append(svg('line', {
x1: 0,
y1: innerRadius,
x2: 0,
y2: innerRadius + d.length,
transform: 'rotate(' + (360 / d.segments * i) + ', 0, 0)',
opacity: $.fn.activity.getOpacity(d, i)
}));
}
return $('<div>').append(el).width(2*r).height(2*r);
};
// Check if Webkit CSS animations are available, as they work much better on the iPad
// than setTimeout() based animations.
if (document.createElement('div').style.WebkitAnimationName !== undefined) {
var animations = {};
/**
* Animation strategy that uses dynamically created CSS animation rules.
*/
animate = function(el, steps, duration) {
if (!animations[steps]) {
var name = 'spin' + steps;
var rule = '@-webkit-keyframes '+ name +' {';
for (var i=0; i < steps; i++) {
var p1 = Math.round(100000 / steps * i) / 1000;
var p2 = Math.round(100000 / steps * (i+1) - 1) / 1000;
var value = '% { -webkit-transform:rotate(' + Math.round(360 / steps * i) + 'deg); }\n';
rule += p1 + value + p2 + value;
}
rule += '100% { -webkit-transform:rotate(100deg); }\n}';
document.styleSheets[0].insertRule(rule,document.styleSheets[0].cssRules.length-1);
animations[steps] = name;
}
el.css('-webkit-animation', animations[steps] + ' ' + duration +'s linear infinite');
};
}
else {
/**
* Animation strategy that transforms a SVG element using setInterval().
*/
animate = function(el, steps, duration) {
var rotation = 0;
var g = el.find('g g').get(0);
el.data('interval', setInterval(function() {
g.setAttributeNS(null, 'transform', 'rotate(' + (++rotation % steps * (360 / steps)) + ')');
}, duration * 1000 / steps));
};
}
}
else {
// =======================================================================================
// VML Rendering
// =======================================================================================
var s = $('<shape>').css('behavior', 'url(#default#VML)').appendTo('body');
if (s.get(0).adj) {
// VML support detected. Insert CSS rules for group, shape and stroke.
var sheet = document.createStyleSheet();
$.each(['group', 'shape', 'stroke'], function() {
sheet.addRule(this, "behavior:url(#default#VML);");
});
/**
* Rendering strategy that creates a VML tree.
*/
render = function(target, d) {
var innerRadius = d.width*2 + d.space;
var r = (innerRadius + d.length + Math.ceil(d.width / 2) + 1);
var s = r*2;
var o = -Math.ceil(s/2);
var el = $('<group>', {coordsize: s + ' ' + s, coordorigin: o + ' ' + o}).css({top: o, left: o, width: s, height: s});
for (var i = 0; i < d.segments; i++) {
el.append($('<shape>', {path: 'm ' + innerRadius + ',0 l ' + (innerRadius + d.length) + ',0'}).css({
width: s,
height: s,
rotation: (360 / d.segments * i) + 'deg'
}).append($('<stroke>', {color: d.color, weight: d.width + 'px', endcap: 'round', opacity: $.fn.activity.getOpacity(d, i)})));
}
return $('<group>', {coordsize: s + ' ' + s}).css({width: s, height: s, overflow: 'hidden'}).append(el);
};
/**
* Animation strategy that modifies the VML rotation property using setInterval().
*/
animate = function(el, steps, duration) {
var rotation = 0;
var g = el.get(0);
el.data('interval', setInterval(function() {
g.style.rotation = ++rotation % steps * (360 / steps);
}, duration * 1000 / steps));
};
}
$(s).remove();
}
})(jQuery);
| MSylvia/feeds | Website/js/jquery.activity-indicator-1.0.1.js | JavaScript | mit | 6,993 |
/* jshint browser:true */
/* global define, google */
define(['underscore', 'backbone', 'oro/translator'],
function(_, Backbone, __) {
'use strict';
var $ = Backbone.$;
/**
* @export oro/mapservice/googlemaps
* @class oro.mapservice.Googlemaps
* @extends Backbone.View
*/
return Backbone.View.extend({
options: {
mapOptions: {
zoom: 17,
mapTypeControl: true,
panControl: false,
zoomControl: true
},
apiVersion: '3.exp',
sensor: false,
apiKey: null,
showWeather: true
},
mapLocationCache: {},
mapsLoadExecuted: false,
initialize: function() {
this.$mapContainer = $('<div class="map-visual"/>')
.appendTo(this.$el);
this.$unknownAddress = $('<div class="map-unknown">' + __('map.unknown.location') + '</div>')
.appendTo(this.$el);
this.mapLocationUnknown();
},
_initMapOptions: function() {
if (_.isUndefined(this.options.mapOptions.mapTypeControlOptions)) {
this.options.mapOptions.mapTypeControlOptions = {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
};
}
if (_.isUndefined(this.options.mapOptions.zoomControlOptions)) {
this.options.mapOptions.zoomControlOptions = {
style: google.maps.ZoomControlStyle.SMALL
};
}
if (_.isUndefined(this.options.mapOptions.mapTypeId)) {
this.options.mapOptions.mapTypeId = google.maps.MapTypeId.ROADMAP;
}
},
_initMap: function(location) {
this._initMapOptions();
this.map = new google.maps.Map(
this.$mapContainer[0],
_.extend({}, this.options.mapOptions, {center: location})
);
this.mapLocationMarker = new google.maps.Marker({
draggable: false,
map: this.map,
position: location
});
if (this.options.showWeather) {
var weatherLayer = new google.maps.weather.WeatherLayer();
weatherLayer.setMap(this.map);
var cloudLayer = new google.maps.weather.CloudLayer();
cloudLayer.setMap(this.map);
}
},
loadGoogleMaps: function() {
var googleMapsSettings = 'sensor=' + (this.options.sensor ? 'true' : 'false');
if (this.options.showWeather) {
googleMapsSettings += '&libraries=weather';
}
if (this.options.apiKey) {
googleMapsSettings += '&key=' + this.options.apiKey;
}
$.ajax({
url: window.location.protocol + "//www.google.com/jsapi",
dataType: "script",
cache: true,
success: _.bind(function() {
google.load('maps', this.options.apiVersion, {
other_params: googleMapsSettings,
callback: _.bind(this.onGoogleMapsInit, this)
});
}, this)
});
},
updateMap: function(address, label) {
// Load google maps js
if (!this.hasGoogleMaps() && !this.mapsLoadExecuted) {
this.mapsLoadExecuted = true;
this.requestedLocation = {
'address': address,
'label': label
};
this.loadGoogleMaps();
return;
}
if (this.mapLocationCache.hasOwnProperty(address)) {
this.updateMapLocation(this.mapLocationCache[address], label);
} else {
this.getGeocoder().geocode({'address': address}, _.bind(function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
this.mapLocationCache[address] = results[0].geometry.location;
//Move location marker and map center to new coordinates
this.updateMapLocation(results[0].geometry.location, label);
} else {
this.mapLocationUnknown();
}
}, this));
}
},
onGoogleMapsInit: function() {
if (!_.isUndefined(this.requestedLocation)) {
this.updateMap(this.requestedLocation.address, this.requestedLocation.label);
delete this.requestedLocation;
}
},
hasGoogleMaps: function() {
return !_.isUndefined(window.google) && google.hasOwnProperty('maps');
},
mapLocationUnknown: function() {
this.$mapContainer.hide();
this.$unknownAddress.show();
},
mapLocationKnown: function() {
this.$mapContainer.show();
this.$unknownAddress.hide();
},
updateMapLocation: function(location, label) {
this.mapLocationKnown();
if (location && (!this.location || location.toString() !== this.location.toString())) {
this._initMap(location);
this.map.setCenter(location);
this.mapLocationMarker.setPosition(location);
this.mapLocationMarker.setTitle(label);
this.location = location;
}
},
getGeocoder: function() {
if (_.isUndefined(this.geocoder)) {
this.geocoder = new google.maps.Geocoder();
}
return this.geocoder;
}
});
});
| minhnguyen-balance/oro_platform | web/bundles/oroaddress/js/mapservice/googlemaps.js | JavaScript | mit | 5,828 |
// Type definitions for temp 0.9
// Project: https://github.com/bruce/node-temp
// Definitions by: Daniel Rosenwasser <https://github.com/DanielRosenwasser>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import * as fs from "fs";
declare namespace temp {
interface OpenFile {
path: string;
fd: number;
}
interface Stats {
files: number;
dirs: number;
}
interface AffixOptions {
prefix?: string;
suffix?: string;
dir?: string;
}
let dir: string;
function track(value?: boolean): typeof temp;
function mkdir(affixes: string | AffixOptions | undefined, callback: (err: any, dirPath: string) => void): void;
function mkdir(affixes?: string | AffixOptions): Promise<string>;
function mkdirSync(affixes?: string | AffixOptions): string;
function open(affixes: string | AffixOptions | undefined, callback: (err: any, result: OpenFile) => void): void;
function open(affixes?: string | AffixOptions): Promise<OpenFile>;
function openSync(affixes?: string | AffixOptions): OpenFile;
function path(affixes?: string | AffixOptions, defaultPrefix?: string): string;
function cleanup(callback: (err: any, result: Stats) => void): void;
function cleanup(): Promise<Stats>;
function cleanupSync(): boolean | Stats;
function createWriteStream(affixes?: string | AffixOptions): fs.WriteStream;
}
export = temp;
| georgemarshall/DefinitelyTyped | types/temp/index.d.ts | TypeScript | mit | 1,426 |
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.okfn.pod;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
/**
* <p>A utility class which helps ease integration with Barcode Scanner via {@link Intent}s. This is a simple
* way to invoke barcode scanning and receive the result, without any need to integrate, modify, or learn the
* project's source code.</p>
*
* <h2>Initiating a barcode scan</h2>
*
* <p>To integrate, create an instance of {@code IntentIntegrator} and call {@link #initiateScan()} and wait
* for the result in your app.</p>
*
* <p>It does require that the Barcode Scanner (or work-alike) application is installed. The
* {@link #initiateScan()} method will prompt the user to download the application, if needed.</p>
*
* <p>There are a few steps to using this integration. First, your {@link Activity} must implement
* the method {@link Activity#onActivityResult(int, int, Intent)} and include a line of code like this:</p>
*
* <pre>{@code
* public void onActivityResult(int requestCode, int resultCode, Intent intent) {
* IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
* if (scanResult != null) {
* // handle scan result
* }
* // else continue with any other code you need in the method
* ...
* }
* }</pre>
*
* <p>This is where you will handle a scan result.</p>
*
* <p>Second, just call this in response to a user action somewhere to begin the scan process:</p>
*
* <pre>{@code
* IntentIntegrator integrator = new IntentIntegrator(yourActivity);
* integrator.initiateScan();
* }</pre>
*
* <p>Note that {@link #initiateScan()} returns an {@link AlertDialog} which is non-null if the
* user was prompted to download the application. This lets the calling app potentially manage the dialog.
* In particular, ideally, the app dismisses the dialog if it's still active in its {@link Activity#onPause()}
* method.</p>
*
* <p>You can use {@link #setTitle(String)} to customize the title of this download prompt dialog (or, use
* {@link #setTitleByID(int)} to set the title by string resource ID.) Likewise, the prompt message, and
* yes/no button labels can be changed.</p>
*
* <p>Finally, you can use {@link #addExtra(String, Object)} to add more parameters to the Intent used
* to invoke the scanner. This can be used to set additional options not directly exposed by this
* simplified API.</p>
*
* <p>By default, this will only allow applications that are known to respond to this intent correctly
* do so. The apps that are allowed to response can be set with {@link #setTargetApplications(List)}.
* For example, set to {@link #TARGET_BARCODE_SCANNER_ONLY} to only target the Barcode Scanner app itself.</p>
*
* <h2>Sharing text via barcode</h2>
*
* <p>To share text, encoded as a QR Code on-screen, similarly, see {@link #shareText(CharSequence)}.</p>
*
* <p>Some code, particularly download integration, was contributed from the Anobiit application.</p>
*
* <h2>Enabling experimental barcode formats</h2>
*
* <p>Some formats are not enabled by default even when scanning with {@link #ALL_CODE_TYPES}, such as
* PDF417. Use {@link #initiateScan(java.util.Collection)} with
* a collection containing the names of formats to scan for explicitly, like "PDF_417", to use such
* formats.</p>
*
* @author Sean Owen
* @author Fred Lin
* @author Isaac Potoczny-Jones
* @author Brad Drehmer
* @author gcstang
*/
public class IntentIntegrator {
public static final int REQUEST_CODE = 0x0000c0de; // Only use bottom 16 bits
private static final String TAG = IntentIntegrator.class.getSimpleName();
public static final String DEFAULT_TITLE = "Install Barcode Scanner?";
public static final String DEFAULT_MESSAGE =
"This application requires Barcode Scanner. Would you like to install it?";
public static final String DEFAULT_YES = "Yes";
public static final String DEFAULT_NO = "No";
// private static final String BS_PACKAGE = "com.google.zxing.client.android";
// private static final String BSPLUS_PACKAGE = "com.srowen.bs.android";
private static final String BS_PACKAGE = "com.google.zxing.client.android";
private static final String BSPLUS_PACKAGE = "com.google.zxing.client.android";
// supported barcode formats
public static final Collection<String> PRODUCT_CODE_TYPES = list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "RSS_14");
public static final Collection<String> ONE_D_CODE_TYPES =
list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "CODE_39", "CODE_93", "CODE_128",
"ITF", "RSS_14", "RSS_EXPANDED");
public static final Collection<String> QR_CODE_TYPES = Collections.singleton("QR_CODE");
public static final Collection<String> DATA_MATRIX_TYPES = Collections.singleton("DATA_MATRIX");
public static final Collection<String> ALL_CODE_TYPES = null;
public static final List<String> TARGET_BARCODE_SCANNER_ONLY = Collections.singletonList(BS_PACKAGE);
public static final List<String> TARGET_ALL_KNOWN = list(
BSPLUS_PACKAGE, // Barcode Scanner+
BSPLUS_PACKAGE + ".simple", // Barcode Scanner+ Simple
BS_PACKAGE // Barcode Scanner
// What else supports this intent?
);
private final Activity activity;
private String title;
private String message;
private String buttonYes;
private String buttonNo;
private List<String> targetApplications;
private final Map<String,Object> moreExtras;
public IntentIntegrator(Activity activity) {
this.activity = activity;
title = DEFAULT_TITLE;
message = DEFAULT_MESSAGE;
buttonYes = DEFAULT_YES;
buttonNo = DEFAULT_NO;
targetApplications = TARGET_ALL_KNOWN;
moreExtras = new HashMap<String,Object>(3);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setTitleByID(int titleID) {
title = activity.getString(titleID);
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void setMessageByID(int messageID) {
message = activity.getString(messageID);
}
public String getButtonYes() {
return buttonYes;
}
public void setButtonYes(String buttonYes) {
this.buttonYes = buttonYes;
}
public void setButtonYesByID(int buttonYesID) {
buttonYes = activity.getString(buttonYesID);
}
public String getButtonNo() {
return buttonNo;
}
public void setButtonNo(String buttonNo) {
this.buttonNo = buttonNo;
}
public void setButtonNoByID(int buttonNoID) {
buttonNo = activity.getString(buttonNoID);
}
public Collection<String> getTargetApplications() {
return targetApplications;
}
public final void setTargetApplications(List<String> targetApplications) {
if (targetApplications.isEmpty()) {
throw new IllegalArgumentException("No target applications");
}
this.targetApplications = targetApplications;
}
public void setSingleTargetApplication(String targetApplication) {
this.targetApplications = Collections.singletonList(targetApplication);
}
public Map<String,?> getMoreExtras() {
return moreExtras;
}
public final void addExtra(String key, Object value) {
moreExtras.put(key, value);
}
/**
* Initiates a scan for all known barcode types.
*/
public final AlertDialog initiateScan() {
return initiateScan(ALL_CODE_TYPES);
}
/**
* Initiates a scan only for a certain set of barcode types, given as strings corresponding
* to their names in ZXing's {@code BarcodeFormat} class like "UPC_A". You can supply constants
* like {@link #PRODUCT_CODE_TYPES} for example.
*
* @return the {@link AlertDialog} that was shown to the user prompting them to download the app
* if a prompt was needed, or null otherwise
*/
public final AlertDialog initiateScan(Collection<String> desiredBarcodeFormats) {
Intent intentScan = new Intent(BS_PACKAGE + ".SCAN");
intentScan.addCategory(Intent.CATEGORY_DEFAULT);
// check which types of codes to scan for
if (desiredBarcodeFormats != null) {
// set the desired barcode types
StringBuilder joinedByComma = new StringBuilder();
for (String format : desiredBarcodeFormats) {
if (joinedByComma.length() > 0) {
joinedByComma.append(',');
}
joinedByComma.append(format);
}
intentScan.putExtra("SCAN_FORMATS", joinedByComma.toString());
}
String targetAppPackage = findTargetAppPackage(intentScan);
if (targetAppPackage == null) {
return showDownloadDialog();
}
intentScan.setPackage(targetAppPackage);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
attachMoreExtras(intentScan);
startActivityForResult(intentScan, REQUEST_CODE);
return null;
}
/**
* Start an activity. This method is defined to allow different methods of activity starting for
* newer versions of Android and for compatibility library.
*
* @param intent Intent to start.
* @param code Request code for the activity
* @see android.app.Activity#startActivityForResult(Intent, int)
* @see android.app.Fragment#startActivityForResult(Intent, int)
*/
protected void startActivityForResult(Intent intent, int code) {
activity.startActivityForResult(intent, code);
}
private String findTargetAppPackage(Intent intent) {
PackageManager pm = activity.getPackageManager();
List<ResolveInfo> availableApps = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (availableApps != null) {
for (String targetApp : targetApplications) {
if (contains(availableApps, targetApp)) {
return targetApp;
}
}
}
return null;
}
private static boolean contains(Iterable<ResolveInfo> availableApps, String targetApp) {
for (ResolveInfo availableApp : availableApps) {
String packageName = availableApp.activityInfo.packageName;
if (targetApp.equals(packageName)) {
return true;
}
}
return false;
}
private AlertDialog showDownloadDialog() {
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity);
downloadDialog.setTitle(title);
downloadDialog.setMessage(message);
downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String packageName = targetApplications.get(0);
Uri uri = Uri.parse("market://details?id=" + packageName);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
activity.startActivity(intent);
} catch (ActivityNotFoundException anfe) {
// Hmm, market is not installed
Log.w(TAG, "Google Play is not installed; cannot install " + packageName);
}
}
});
downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {}
});
return downloadDialog.show();
}
/**
* <p>Call this from your {@link Activity}'s
* {@link Activity#onActivityResult(int, int, Intent)} method.</p>
*
* @return null if the event handled here was not related to this class, or
* else an {@link IntentResult} containing the result of the scan. If the user cancelled scanning,
* the fields will be null.
*/
public static IntentResult parseActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String formatName = intent.getStringExtra("SCAN_RESULT_FORMAT");
byte[] rawBytes = intent.getByteArrayExtra("SCAN_RESULT_BYTES");
int intentOrientation = intent.getIntExtra("SCAN_RESULT_ORIENTATION", Integer.MIN_VALUE);
Integer orientation = intentOrientation == Integer.MIN_VALUE ? null : intentOrientation;
String errorCorrectionLevel = intent.getStringExtra("SCAN_RESULT_ERROR_CORRECTION_LEVEL");
return new IntentResult(contents,
formatName,
rawBytes,
orientation,
errorCorrectionLevel);
}
return new IntentResult();
}
return null;
}
/**
* Defaults to type "TEXT_TYPE".
* @see #shareText(CharSequence, CharSequence)
*/
public final AlertDialog shareText(CharSequence text) {
return shareText(text, "TEXT_TYPE");
}
/**
* Shares the given text by encoding it as a barcode, such that another user can
* scan the text off the screen of the device.
*
* @param text the text string to encode as a barcode
* @param type type of data to encode. See {@code com.google.zxing.client.android.Contents.Type} constants.
* @return the {@link AlertDialog} that was shown to the user prompting them to download the app
* if a prompt was needed, or null otherwise
*/
public final AlertDialog shareText(CharSequence text, CharSequence type) {
Intent intent = new Intent();
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setAction(BS_PACKAGE + ".ENCODE");
intent.putExtra("ENCODE_TYPE", type);
intent.putExtra("ENCODE_DATA", text);
String targetAppPackage = findTargetAppPackage(intent);
if (targetAppPackage == null) {
return showDownloadDialog();
}
intent.setPackage(targetAppPackage);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
attachMoreExtras(intent);
activity.startActivity(intent);
return null;
}
private static List<String> list(String... values) {
return Collections.unmodifiableList(Arrays.asList(values));
}
private void attachMoreExtras(Intent intent) {
for (Map.Entry<String,Object> entry : moreExtras.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// Kind of hacky
if (value instanceof Integer) {
intent.putExtra(key, (Integer) value);
} else if (value instanceof Long) {
intent.putExtra(key, (Long) value);
} else if (value instanceof Boolean) {
intent.putExtra(key, (Boolean) value);
} else if (value instanceof Double) {
intent.putExtra(key, (Double) value);
} else if (value instanceof Float) {
intent.putExtra(key, (Float) value);
} else if (value instanceof Bundle) {
intent.putExtra(key, (Bundle) value);
} else {
intent.putExtra(key, value.toString());
}
}
}
}
| okfn/product-browser-android | src/org/okfn/pod/IntentIntegrator.java | Java | mit | 16,341 |
/* global Dubtrack */
const modal = require('../utils/modal.js');
var isActiveTab = true;
window.onfocus = function () {
isActiveTab = true;
};
window.onblur = function () {
isActiveTab = false;
};
var onDenyDismiss = function() {
modal.create({
title: 'Desktop Notifications',
content: "You have dismissed or chosen to deny the request to allow desktop notifications. Reset this choice by clearing your cache for the site."
});
};
export function notifyCheckPermission(cb){
var _cb = typeof cb === 'function' ? cb : function(){};
// first check if browser supports it
if (!("Notification" in window)) {
modal.create({
title: 'Desktop Notifications',
content: "Sorry this browser does not support desktop notifications. Please use the latest version of Chrome or FireFox"
});
return _cb(false);
}
// no request needed, good to go
if (Notification.permission === "granted") {
return _cb(true);
}
if (Notification.permission !== 'denied') {
Notification.requestPermission().then(function(result) {
if (result === 'denied' || result === 'default') {
onDenyDismiss();
_cb(false);
return;
}
_cb(true);
});
} else {
onDenyDismiss();
return _cb(false);
}
}
export function showNotification (opts){
var defaults = {
title : 'New Message',
content : '',
ignoreActiveTab : false,
callback : null,
wait : 5000
};
var options = Object.assign({}, defaults, opts);
// don't show a notification if tab is active
if (isActiveTab === true && !options.ignoreActiveTab) { return; }
var notificationOptions = {
body: options.content,
icon: "https://res.cloudinary.com/hhberclba/image/upload/c_lpad,h_100,w_100/v1400351432/dubtrack_new_logo_fvpxa6.png"
};
var n = new Notification(options.title, notificationOptions);
n.onclick = function() {
window.focus();
if (typeof options.callback === "function") { options.callback(); }
n.close();
};
setTimeout(n.close.bind(n), options.wait);
}
| coryshaw1/DubPlus | src/js/utils/notify.js | JavaScript | mit | 2,082 |
pageflow.VideoPlayer.bufferUnderrunWaiting = function(player) {
var originalPause = player.pause;
player.pause = function() {
cancelWaiting();
originalPause.apply(this, arguments);
};
function pauseAndPreloadOnUnderrun() {
if (bufferUnderrun()) {
pauseAndPreload();
}
}
function bufferUnderrun() {
return !player.isBufferedAhead(0.1, true) && !player.waitingOnUnderrun && !ignoringUnderruns();
}
function pauseAndPreload() {
pageflow.log('Buffer underrun');
player.trigger('bufferunderrun');
player.pause();
player.waitingOnUnderrun = true;
player.prebuffer({secondsToBuffer: 5, secondsToWait: 5}).then(function() {
// do nothing if user aborted waiting by clicking pause
if (player.waitingOnUnderrun) {
player.waitingOnUnderrun = false;
player.trigger('bufferunderruncontinue');
player.play();
}
});
}
function cancelWaiting() {
if (player.waitingOnUnderrun) {
player.ignoreUnderrunsUntil = new Date().getTime() + 5 * 1000;
player.waitingOnUnderrun = false;
player.trigger('bufferunderruncontinue');
}
}
function ignoringUnderruns() {
var r = player.ignoreUnderrunsUntil && new Date().getTime() < player.ignoreUnderrunsUntil;
if (r) {
pageflow.log('ignoring underrun');
}
return r;
}
function stopListeningForProgress() {
player.off('progress', pauseAndPreloadOnUnderrun);
}
if (pageflow.browser.has('buffer underrun waiting support')) {
player.on('play', function() {
player.on('progress', pauseAndPreloadOnUnderrun);
});
player.on('pause', stopListeningForProgress);
player.on('ended', stopListeningForProgress);
}
}; | tf/pageflow-dependabot-test | app/assets/javascripts/pageflow/video_player/buffer_underrun_waiting.js | JavaScript | mit | 1,736 |
using MonoGame.Extended.Sprites;
using Xunit;
namespace MonoGame.Extended.Entities.Tests
{
public class ComponentManagerTests
{
[Fact]
public void GetMapperForType()
{
var componentManager = new ComponentManager();
var transformMapper = componentManager.GetMapper<Transform2>();
var spriteMapper = componentManager.GetMapper<Sprite>();
Assert.IsType<ComponentMapper<Transform2>>(transformMapper);
Assert.IsType<ComponentMapper<Sprite>>(spriteMapper);
Assert.Equal(0, transformMapper.Id);
Assert.Equal(1, spriteMapper.Id);
Assert.Same(spriteMapper, componentManager.GetMapper<Sprite>());
}
[Fact]
public void GetComponentTypeId()
{
var componentManager = new ComponentManager();
Assert.Equal(0, componentManager.GetComponentTypeId(typeof(Transform2)));
Assert.Equal(1, componentManager.GetComponentTypeId(typeof(Sprite)));
Assert.Equal(0, componentManager.GetComponentTypeId(typeof(Transform2)));
}
//[Fact]
//public void GetCompositionIdentity()
//{
// var compositionBits = new BitArray(3)
// {
// [0] = true,
// [1] = false,
// [2] = true
// };
// var componentManager = new ComponentManager();
// var identity = componentManager.GetCompositionIdentity(compositionBits);
// Assert.Equal(0b101, identity);
//}
}
} | craftworkgames/MonoGame.Extended | src/cs/Tests/MonoGame.Extended.Entities.Tests/ComponentManagerTests.cs | C# | mit | 1,586 |
# User Instructions
#
# Write a function 'sub1' that, given a
# string, embeds that string in
# the string:
# "I think X is a perfectly normal thing to do in public."
# where X is replaced by the given
# string.
#
given_string = "I think %s is a perfectly normal thing to do in public."
def sub1(s):
return given_string.replace("%s", s)
def sub2(s):
return given_string % s
print sub1("running")
# => "I think running is a perfectly normal thing to do in public."
print sub1("sleeping")
# => "I think sleeping is a perfectly normal thing to do in public."
| KellyChan/python-examples | web/gae/python/b_words_replaced.py | Python | mit | 581 |
# Cookbook Name:: shared
# Recipe:: _hosts - run on base node - copies and sets permissions on host file
#
# Copyright (c) 2015 Charles T Betz, All Rights Reserved.
# Recipe for all nodes within Calavera
# from files directory
#ssh and network setup
# from files directory
file_map = {
"calaverahosts" => "/home/vagrant/calaverahosts", # there is now a recipe for managing hosts
}
# download each file and place it in right directory
file_map.each do | fileName, pathName |
cookbook_file fileName do
path pathName
mode 0755
#user "xx"
#group "xx"
action :create
end
end
# convert next 2 commands to the hostsfile cookbook?
execute 'configure host file' do
command 'cat /home/vagrant/calaverahosts >> /etc/hosts' # REALLY not idempotent. just put a touch x guard
end
execute 'remove host file' do
command 'rm /home/vagrant/calaverahosts'
end
| svrc-pivotal/Calavera | cookbooks/base/recipes/_hosts.rb | Ruby | mit | 881 |
define([
'extensions/collections/collection'
],
function (Collection) {
return Collection.extend({
initialize: function (models, options) {
if(options !== undefined){
options.flattenEverything = false;
}
return Collection.prototype.initialize.apply(this, arguments);
},
parse: function () {
var data = Collection.prototype.parse.apply(this, arguments);
var lines = this.options.axes.y;
var hasOther = _.findWhere(lines, { groupId: 'other' });
if (this.options.groupMapping) {
_.each(this.options.groupMapping, function (to, from) {
from = new RegExp(from + ':' + this.valueAttr);
_.each(data, function (model) {
var toAttr = to + ':' + this.valueAttr;
var sum = 0;
_.each(model, function (val, key) {
if (key.match(from)) {
if (val) {
sum += val;
}
delete model[key];
}
});
if (model[toAttr] === undefined) {
model[toAttr] = 0;
}
model[toAttr] += sum;
}, this);
}, this);
}
_.each(data, function (model) {
var total = null,
other = null;
_.each(model, function (val, key) {
var index = key.indexOf(this.valueAttr);
if (index > 1 && model[key]) {
// get the prefix value
var group = key.replace(':' + this.valueAttr, '');
var axis = _.findWhere(lines, { groupId: group });
if (axis || hasOther) {
total += model[key];
}
if (!axis) {
other += model[key];
delete model[key];
}
}
}, this);
model['other:' + this.valueAttr] = other;
model['total:' + this.valueAttr] = total;
_.each(lines, function (line) {
var prop = (line.key || line.groupId) + ':' + this.valueAttr;
var value = model[prop];
if (value === undefined) {
value = model[prop] = null;
}
if (model['total:' + this.valueAttr]) {
model[prop + ':percent'] = value / model['total:' + this.valueAttr];
} else {
model[prop + ':percent'] = null;
}
}, this);
}, this);
return data;
},
getYAxes: function () {
var axes = Collection.prototype.getYAxes.apply(this, arguments);
_.each(this.options.groupMapping, function (to, from) {
axes.push({ groupId: from });
});
return axes;
}
});
});
| alphagov/spotlight | app/common/collections/grouped_timeseries.js | JavaScript | mit | 2,654 |
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.command;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.spongepowered.api.command.CommandMessageFormatting.error;
import static org.spongepowered.api.util.SpongeApiTranslationHelper.t;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
import org.slf4j.Logger;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandCallable;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandManager;
import org.spongepowered.api.command.CommandMapping;
import org.spongepowered.api.command.CommandPermissionException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.InvocationCommandException;
import org.spongepowered.api.command.dispatcher.Disambiguator;
import org.spongepowered.api.command.dispatcher.SimpleDispatcher;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.NamedCause;
import org.spongepowered.api.event.command.SendCommandEvent;
import org.spongepowered.api.event.command.TabCompleteEvent;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.action.TextActions;
import org.spongepowered.api.text.serializer.TextSerializers;
import org.spongepowered.api.util.TextMessageException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import javax.annotation.Nullable;
import javax.inject.Inject;
/**
* A simple implementation of {@link CommandManager}.
* This service calls the appropriate events for a command.
*/
public class SpongeCommandManager implements CommandManager {
private final Logger log;
private final SimpleDispatcher dispatcher;
private final Multimap<PluginContainer, CommandMapping> owners = HashMultimap.create();
private final Object lock = new Object();
/**
* Construct a simple {@link CommandManager}.
*
* @param logger The logger to log error messages to
*/
@Inject
public SpongeCommandManager(Logger logger) {
this(logger, SimpleDispatcher.FIRST_DISAMBIGUATOR);
}
/**
* Construct a simple {@link CommandManager}.
*
* @param logger The logger to log error messages to
* @param disambiguator The function to resolve a single command when multiple options are available
*/
public SpongeCommandManager(Logger logger, Disambiguator disambiguator) {
this.log = logger;
this.dispatcher = new SimpleDispatcher(disambiguator);
}
@Override
public Optional<CommandMapping> register(Object plugin, CommandCallable callable, String... alias) {
return register(plugin, callable, Arrays.asList(alias));
}
@Override
public Optional<CommandMapping> register(Object plugin, CommandCallable callable, List<String> aliases) {
return register(plugin, callable, aliases, Function.identity());
}
@Override
public Optional<CommandMapping> register(Object plugin, CommandCallable callable, List<String> aliases,
Function<List<String>, List<String>> callback) {
checkNotNull(plugin, "plugin");
Optional<PluginContainer> containerOptional = Sponge.getGame().getPluginManager().fromInstance(plugin);
if (!containerOptional.isPresent()) {
throw new IllegalArgumentException(
"The provided plugin object does not have an associated plugin container "
+ "(in other words, is 'plugin' actually your plugin object?");
}
PluginContainer container = containerOptional.get();
synchronized (this.lock) {
// <namespace>:<alias> for all commands
List<String> aliasesWithPrefix = new ArrayList<>(aliases.size() * 3);
for (String alias : aliases) {
final Collection<CommandMapping> ownedCommands = this.owners.get(container);
for (CommandMapping mapping : this.dispatcher.getAll(alias)) {
if (ownedCommands.contains(mapping)) {
throw new IllegalArgumentException("A plugin may not register multiple commands for the same alias ('" + alias + "')!");
}
}
aliasesWithPrefix.add(alias);
// Alias commands with unqualified ID and qualified ID
String unqualifiedId = container.getUnqualifiedId();
aliasesWithPrefix.add(unqualifiedId + ':' + alias);
if (!container.getId().equals(unqualifiedId)) {
aliasesWithPrefix.add(container.getId() + ':' + alias);
}
}
Optional<CommandMapping> mapping = this.dispatcher.register(callable, aliasesWithPrefix, callback);
if (mapping.isPresent()) {
this.owners.put(container, mapping.get());
}
return mapping;
}
}
@Override
public Optional<CommandMapping> removeMapping(CommandMapping mapping) {
synchronized (this.lock) {
Optional<CommandMapping> removed = this.dispatcher.removeMapping(mapping);
if (removed.isPresent()) {
forgetMapping(removed.get());
}
return removed;
}
}
private void forgetMapping(CommandMapping mapping) {
Iterator<CommandMapping> it = this.owners.values().iterator();
while (it.hasNext()) {
if (it.next().equals(mapping)) {
it.remove();
break;
}
}
}
@Override
public Set<PluginContainer> getPluginContainers() {
synchronized (this.lock) {
return ImmutableSet.copyOf(this.owners.keySet());
}
}
@Override
public Set<CommandMapping> getCommands() {
return this.dispatcher.getCommands();
}
@Override
public Set<CommandMapping> getOwnedBy(Object instance) {
Optional<PluginContainer> container = Sponge.getGame().getPluginManager().fromInstance(instance);
if (!container.isPresent()) {
throw new IllegalArgumentException("The provided plugin object does not have an associated plugin container "
+ "(in other words, is 'plugin' actually your plugin object?)");
}
synchronized (this.lock) {
return ImmutableSet.copyOf(this.owners.get(container.get()));
}
}
@Override
public Set<String> getPrimaryAliases() {
return this.dispatcher.getPrimaryAliases();
}
@Override
public Set<String> getAliases() {
return this.dispatcher.getAliases();
}
@Override
public Optional<CommandMapping> get(String alias) {
return this.dispatcher.get(alias);
}
@Override
public Optional<? extends CommandMapping> get(String alias, @Nullable CommandSource source) {
return this.dispatcher.get(alias, source);
}
@Override
public Set<? extends CommandMapping> getAll(String alias) {
return this.dispatcher.getAll(alias);
}
@Override
public Multimap<String, CommandMapping> getAll() {
return this.dispatcher.getAll();
}
@Override
public boolean containsAlias(String alias) {
return this.dispatcher.containsAlias(alias);
}
@Override
public boolean containsMapping(CommandMapping mapping) {
return this.dispatcher.containsMapping(mapping);
}
@Override
public CommandResult process(CommandSource source, String commandLine) {
final String[] argSplit = commandLine.split(" ", 2);
final SendCommandEvent event = SpongeEventFactory.createSendCommandEvent(Cause.of(NamedCause.source(source)),
argSplit.length > 1 ? argSplit[1] : "", argSplit[0], CommandResult.empty());
Sponge.getGame().getEventManager().post(event);
if (event.isCancelled()) {
return event.getResult();
}
// Only the first part of argSplit is used at the moment, do the other in the future if needed.
argSplit[0] = event.getCommand();
commandLine = event.getCommand();
if (!event.getArguments().isEmpty()) {
commandLine = commandLine + ' ' + event.getArguments();
}
try {
try {
return this.dispatcher.process(source, commandLine);
} catch (InvocationCommandException ex) {
if (ex.getCause() != null) {
throw ex.getCause();
}
} catch (CommandPermissionException ex) {
Text text = ex.getText();
if (text != null) {
source.sendMessage(error(text));
}
} catch (CommandException ex) {
Text text = ex.getText();
if (text != null) {
source.sendMessage(error(text));
}
if (ex.shouldIncludeUsage()) {
final Optional<CommandMapping> mapping = this.dispatcher.get(argSplit[0], source);
if (mapping.isPresent()) {
source.sendMessage(error(t("Usage: /%s %s", argSplit[0], mapping.get().getCallable().getUsage(source))));
}
}
}
} catch (Throwable thr) {
Text.Builder excBuilder;
if (thr instanceof TextMessageException) {
Text text = ((TextMessageException) thr).getText();
excBuilder = text == null ? Text.builder("null") : Text.builder();
} else {
excBuilder = Text.builder(String.valueOf(thr.getMessage()));
}
if (source.hasPermission("sponge.debug.hover-stacktrace")) {
final StringWriter writer = new StringWriter();
thr.printStackTrace(new PrintWriter(writer));
excBuilder.onHover(TextActions.showText(Text.of(writer.toString()
.replace("\t", " ")
.replace("\r\n", "\n")
.replace("\r", "\n")))); // I mean I guess somebody could be running this on like OS 9?
}
source.sendMessage(error(t("Error occurred while executing command: %s", excBuilder.build())));
this.log.error(TextSerializers.PLAIN.serialize(t("Error occurred while executing command '%s' for source %s: %s", commandLine, source.toString(), String
.valueOf(thr.getMessage()))), thr);
}
return CommandResult.empty();
}
@Override
public List<String> getSuggestions(CommandSource src, String arguments) {
try {
final String[] argSplit = arguments.split(" ", 2);
List<String> suggestions = new ArrayList<>(this.dispatcher.getSuggestions(src, arguments));
final TabCompleteEvent.Command event = SpongeEventFactory.createTabCompleteEventCommand(Cause.source(src).build(),
ImmutableList.copyOf(suggestions), suggestions, argSplit.length > 1 ? argSplit[1] : "", argSplit[0], arguments);
Sponge.getGame().getEventManager().post(event);
if (event.isCancelled()) {
return ImmutableList.of();
} else {
return ImmutableList.copyOf(event.getTabCompletions());
}
} catch (CommandException e) {
src.sendMessage(error(t("Error getting suggestions: %s", e.getText())));
return Collections.emptyList();
}
}
@Override
public boolean testPermission(CommandSource source) {
return this.dispatcher.testPermission(source);
}
@Override
public Optional<Text> getShortDescription(CommandSource source) {
return this.dispatcher.getShortDescription(source);
}
@Override
public Optional<Text> getHelp(CommandSource source) {
return this.dispatcher.getHelp(source);
}
@Override
public Text getUsage(CommandSource source) {
return this.dispatcher.getUsage(source);
}
@Override
public int size() {
return this.dispatcher.size();
}
}
| ryantheleach/SpongeCommon | src/main/java/org/spongepowered/common/command/SpongeCommandManager.java | Java | mit | 13,967 |
from .downloader_base import DownloaderBase
from ... import logger
log = logger.get(__name__)
import traceback
import subprocess
import shutil
from ... import settings
class ExternalDownloader(DownloaderBase):
"""Abstract Base class for downloading through an external utility"""
program = None
args = []
@classmethod
def is_available(cls):
return not settings.is_windows() and shutil.which(cls.program)
def get(self, url):
try:
log.debug('%s downloader getting url %s', self.program, url)
call = [self.program] + self.args + [url]
result = subprocess.check_output(call)
except subprocess.CalledProcessError:
log.error('%s downloader failed.', self.program)
traceback.print_exc()
result = False
return result
| Colorsublime/Colorsublime-Plugin | colorsublime/http/downloaders/external.py | Python | mit | 843 |
/**
* \file register_loader_saver_odgi.cpp
* Defines IO for a PackedGraph from stream files.
*/
#include <arpa/inet.h>
#include <vg/io/registry.hpp>
#include "register_loader_saver_odgi.hpp"
#include "handle.hpp"
#include "bdsg/odgi.hpp"
namespace vg {
namespace io {
using namespace std;
using namespace vg::io;
void register_loader_saver_odgi() {
// Convert the ODGI SerializableHandleGraph magic number to a string
bdsg::ODGI empty;
// Make sure it is in network byte order
uint32_t new_magic_number = htonl(empty.get_magic_number());
// Load all 4 characters of it into a string
string new_magic((char*)&new_magic_number, 4);
Registry::register_bare_loader_saver_with_magic<bdsg::ODGI, MutablePathDeletableHandleGraph, MutablePathMutableHandleGraph, MutableHandleGraph, PathHandleGraph, HandleGraph>("ODGI", new_magic, [](istream& input) -> void* {
// Allocate an ODGI graph
bdsg::ODGI* odgi = new bdsg::ODGI();
// Load it
odgi->deserialize(input);
// Return it so the caller owns it.
return (void*) odgi;
}, [](const void* odgi_void, ostream& output) {
// Cast to ODGI and serialize to the stream.
assert(odgi_void != nullptr);
((bdsg::ODGI*) odgi_void)->serialize(output);
});
}
}
}
| ekg/vg | src/io/register_loader_saver_odgi.cpp | C++ | mit | 1,329 |
<?php
class __USE_STATIC_ACCESS__Filter
{
/***********************************************************************************/
/* FILTER LIBRARY */
/***********************************************************************************/
/* Yazar: Ozan UYKUN <ozanbote@windowslive.com> | <ozanbote@gmail.com>
/* Site: www.zntr.net
/* Lisans: The MIT License
/* Telif Hakkı: Copyright (c) 2012-2015, zntr.net
/*
/* Sınıf Adı: Filter
/* Versiyon: 1.4
/* Tanımlanma: Statik
/* Dahil Edilme: Gerektirmez
/* Erişim: Filter::, $this->Filter, zn::$use->Filter, uselib('Filter')
/* Not: Büyük-küçük harf duyarlılığı yoktur.
/***********************************************************************************/
/******************************************************************************************
* CALL *
*******************************************************************************************
| Genel Kullanım: Geçersiz fonksiyon girildiğinde çağrılması için. |
| |
******************************************************************************************/
public function __call($method = '', $param = '')
{
die(getErrorMessage('Error', 'undefinedFunction', "Filter::$method()"));
}
/******************************************************************************************
* WORD *
*******************************************************************************************
| Genel Kullanım: Metin içinde istenilmeyen kelimelerin izole edilmesi için kullanılır. |
| |
******************************************************************************************/
public function word($string = '', $badWords = '', $changeChar = '[badwords]')
{
if( ! isValue($string) )
{
return Error::set(lang('Error', 'valueParameter', 'string'));
}
if( ! is_array($badWords) )
{
if( empty($badWords) )
{
return $string;
}
return $string = Regex::replace($badWords, $changeChar, $string, 'xi');
}
$ch = '';
$i = 0;
if( ! empty($badWords) ) foreach( $badWords as $value )
{
if( ! is_array($changeChar) )
{
$ch = $changeChar;
}
else
{
if( isset($changeChar[$i]) )
{
$ch = $changeChar[$i];
$i++;
}
}
$string = Regex::replace($value, $ch, $string, 'xi');
}
return $string;
}
/******************************************************************************************
* DATA *
*******************************************************************************************
| Genel Kullanım: Filter::word() yöntemi ile aynı işlevi görür. |
| |
******************************************************************************************/
public function data($string = '', $badWords = '', $changeChar = '[badwords]')
{
return self::word($string, $badWords, $changeChar);
}
} | erdidoqan/znframework | System/Libraries/Helpers/Filter.php | PHP | mit | 3,266 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
namespace VirtualCollection.VirtualCollection
{
public class VirtualizingWrapPanel : VirtualizingPanel, IScrollInfo
{
private const double ScrollLineAmount = 16.0;
private Size _extentSize;
private Size _viewportSize;
private Point _offset;
private ItemsControl _itemsControl;
private readonly Dictionary<UIElement, Rect> _childLayouts = new Dictionary<UIElement, Rect>();
public static readonly DependencyProperty ItemWidthProperty =
DependencyProperty.Register(nameof(ItemWidth), typeof(double), typeof(VirtualizingWrapPanel), new PropertyMetadata(1.0, HandleItemDimensionChanged));
public static readonly DependencyProperty ItemHeightProperty =
DependencyProperty.Register(nameof(ItemHeight), typeof(double), typeof(VirtualizingWrapPanel), new PropertyMetadata(1.0, HandleItemDimensionChanged));
private static readonly DependencyProperty VirtualItemIndexProperty =
DependencyProperty.RegisterAttached("VirtualItemIndex", typeof(int), typeof(VirtualizingWrapPanel), new PropertyMetadata(-1));
private IRecyclingItemContainerGenerator _itemsGenerator;
private bool _isInMeasure;
private static int GetVirtualItemIndex(DependencyObject obj)
{
return (int)obj.GetValue(VirtualItemIndexProperty);
}
private static void SetVirtualItemIndex(DependencyObject obj, int value)
{
obj.SetValue(VirtualItemIndexProperty, value);
}
public double ItemHeight
{
get { return (double)GetValue(ItemHeightProperty); }
set { SetValue(ItemHeightProperty, value); }
}
public double ItemWidth
{
get { return (double)GetValue(ItemWidthProperty); }
set { SetValue(ItemWidthProperty, value); }
}
public VirtualizingWrapPanel()
{
if (!DesignerProperties.GetIsInDesignMode(this))
{
Dispatcher.BeginInvoke(new Action(Initialize));
}
}
private void Initialize()
{
_itemsControl = ItemsControl.GetItemsOwner(this);
_itemsGenerator = (IRecyclingItemContainerGenerator)ItemContainerGenerator;
InvalidateMeasure();
}
protected override void OnItemsChanged(object sender, ItemsChangedEventArgs args)
{
base.OnItemsChanged(sender, args);
InvalidateMeasure();
}
protected override Size MeasureOverride(Size availableSize)
{
if (_itemsControl == null)
{
return new Size(double.IsInfinity(availableSize.Width) ? 0 : availableSize.Width,
double.IsInfinity(availableSize.Height) ? 0 : availableSize.Height);
}
_isInMeasure = true;
_childLayouts.Clear();
var extentInfo = GetExtentInfo(availableSize, ItemHeight);
EnsureScrollOffsetIsWithinConstrains(extentInfo);
var layoutInfo = GetLayoutInfo(availableSize, ItemHeight, extentInfo);
RecycleItems(layoutInfo);
// Determine where the first item is in relation to previously realized items
var generatorStartPosition = _itemsGenerator.GeneratorPositionFromIndex(layoutInfo.FirstRealizedItemIndex);
var visualIndex = 0;
var currentX = layoutInfo.FirstRealizedItemLeft;
var currentY = layoutInfo.FirstRealizedLineTop;
using (_itemsGenerator.StartAt(generatorStartPosition, GeneratorDirection.Forward, true))
{
for (var itemIndex = layoutInfo.FirstRealizedItemIndex; itemIndex <= layoutInfo.LastRealizedItemIndex; itemIndex++, visualIndex++)
{
bool newlyRealized;
var child = (UIElement)_itemsGenerator.GenerateNext(out newlyRealized);
SetVirtualItemIndex(child, itemIndex);
if (newlyRealized)
{
InsertInternalChild(visualIndex, child);
}
else
{
// check if item needs to be moved into a new position in the Children collection
if (visualIndex < Children.Count)
{
if (Children[visualIndex] != child)
{
var childCurrentIndex = Children.IndexOf(child);
if (childCurrentIndex >= 0)
{
RemoveInternalChildRange(childCurrentIndex, 1);
}
InsertInternalChild(visualIndex, child);
}
}
else
{
// we know that the child can't already be in the children collection
// because we've been inserting children in correct visualIndex order,
// and this child has a visualIndex greater than the Children.Count
AddInternalChild(child);
}
}
// only prepare the item once it has been added to the visual tree
_itemsGenerator.PrepareItemContainer(child);
child.Measure(new Size(ItemWidth, ItemHeight));
_childLayouts.Add(child, new Rect(currentX, currentY, ItemWidth, ItemHeight));
if (currentX + ItemWidth * 2 >= availableSize.Width)
{
// wrap to a new line
currentY += ItemHeight;
currentX = 0;
}
else
{
currentX += ItemWidth;
}
}
}
RemoveRedundantChildren();
UpdateScrollInfo(availableSize, extentInfo);
var desiredSize = new Size(double.IsInfinity(availableSize.Width) ? 0 : availableSize.Width,
double.IsInfinity(availableSize.Height) ? 0 : availableSize.Height);
_isInMeasure = false;
return desiredSize;
}
private void EnsureScrollOffsetIsWithinConstrains(ExtentInfo extentInfo)
{
_offset.Y = Clamp(_offset.Y, 0, extentInfo.MaxVerticalOffset);
}
private void RecycleItems(ItemLayoutInfo layoutInfo)
{
foreach (var child in Children.OfType<UIElement>())
{
var virtualItemIndex = GetVirtualItemIndex(child);
if (virtualItemIndex < layoutInfo.FirstRealizedItemIndex || virtualItemIndex > layoutInfo.LastRealizedItemIndex)
{
var generatorPosition = _itemsGenerator.GeneratorPositionFromIndex(virtualItemIndex);
if (generatorPosition.Index >= 0)
{
_itemsGenerator.Recycle(generatorPosition, 1);
}
}
SetVirtualItemIndex(child, -1);
}
}
protected override Size ArrangeOverride(Size finalSize)
{
foreach (var child in Children.OfType<UIElement>())
{
child.Arrange(_childLayouts[child]);
}
return finalSize;
}
private void UpdateScrollInfo(Size availableSize, ExtentInfo extentInfo)
{
_viewportSize = availableSize;
_extentSize = new Size(availableSize.Width, extentInfo.ExtentHeight);
InvalidateScrollInfo();
}
private void RemoveRedundantChildren()
{
// iterate backwards through the child collection because we're going to be
// removing items from it
for (var i = Children.Count - 1; i >= 0; i--)
{
var child = Children[i];
// if the virtual item index is -1, this indicates
// it is a recycled item that hasn't been reused this time round
if (GetVirtualItemIndex(child) == -1)
{
RemoveInternalChildRange(i, 1);
}
}
}
private ItemLayoutInfo GetLayoutInfo(Size availableSize, double itemHeight, ExtentInfo extentInfo)
{
if (_itemsControl == null)
{
return new ItemLayoutInfo();
}
// we need to ensure that there is one realized item prior to the first visible item, and one after the last visible item,
// so that keyboard navigation works properly. For example, when focus is on the first visible item, and the user
// navigates up, the ListBox selects the previous item, and the scrolls that into view - and this triggers the loading of the rest of the items
// in that row
var firstVisibleLine = (int)Math.Floor(VerticalOffset / itemHeight);
var firstRealizedIndex = Math.Max(extentInfo.ItemsPerLine * firstVisibleLine - 1, 0);
var firstRealizedItemLeft = firstRealizedIndex % extentInfo.ItemsPerLine * ItemWidth - HorizontalOffset;
var firstRealizedItemTop = (firstRealizedIndex / extentInfo.ItemsPerLine) * itemHeight - VerticalOffset;
var firstCompleteLineTop = (firstVisibleLine == 0 ? firstRealizedItemTop : firstRealizedItemTop + ItemHeight);
var completeRealizedLines = (int)Math.Ceiling((availableSize.Height - firstCompleteLineTop) / itemHeight);
var lastRealizedIndex = Math.Min(firstRealizedIndex + completeRealizedLines * extentInfo.ItemsPerLine + 2, _itemsControl.Items.Count - 1);
return new ItemLayoutInfo
{
FirstRealizedItemIndex = firstRealizedIndex,
FirstRealizedItemLeft = firstRealizedItemLeft,
FirstRealizedLineTop = firstRealizedItemTop,
LastRealizedItemIndex = lastRealizedIndex,
};
}
private ExtentInfo GetExtentInfo(Size viewPortSize, double itemHeight)
{
if (_itemsControl == null)
{
return new ExtentInfo();
}
var itemsPerLine = Math.Max((int)Math.Floor(viewPortSize.Width / ItemWidth), 1);
var totalLines = (int)Math.Ceiling((double)_itemsControl.Items.Count / itemsPerLine);
var extentHeight = Math.Max(totalLines * ItemHeight, viewPortSize.Height);
return new ExtentInfo()
{
ItemsPerLine = itemsPerLine,
TotalLines = totalLines,
ExtentHeight = extentHeight,
MaxVerticalOffset = extentHeight - viewPortSize.Height,
};
}
public void LineUp()
{
SetVerticalOffset(VerticalOffset - ScrollLineAmount);
}
public void LineDown()
{
SetVerticalOffset(VerticalOffset + ScrollLineAmount);
}
public void LineLeft()
{
SetHorizontalOffset(HorizontalOffset + ScrollLineAmount);
}
public void LineRight()
{
SetHorizontalOffset(HorizontalOffset - ScrollLineAmount);
}
public void PageUp()
{
SetVerticalOffset(VerticalOffset - ViewportHeight);
}
public void PageDown()
{
SetVerticalOffset(VerticalOffset + ViewportHeight);
}
public void PageLeft()
{
SetHorizontalOffset(HorizontalOffset + ItemWidth);
}
public void PageRight()
{
SetHorizontalOffset(HorizontalOffset - ItemWidth);
}
public void MouseWheelUp()
{
SetVerticalOffset(VerticalOffset - ScrollLineAmount * SystemParameters.WheelScrollLines);
}
public void MouseWheelDown()
{
SetVerticalOffset(VerticalOffset + ScrollLineAmount * SystemParameters.WheelScrollLines);
}
public void MouseWheelLeft()
{
SetHorizontalOffset(HorizontalOffset - ScrollLineAmount * SystemParameters.WheelScrollLines);
}
public void MouseWheelRight()
{
SetHorizontalOffset(HorizontalOffset + ScrollLineAmount * SystemParameters.WheelScrollLines);
}
public void SetHorizontalOffset(double offset)
{
if (_isInMeasure)
{
return;
}
offset = Clamp(offset, 0, ExtentWidth - ViewportWidth);
_offset = new Point(offset, _offset.Y);
InvalidateScrollInfo();
InvalidateMeasure();
}
public void SetVerticalOffset(double offset)
{
if (_isInMeasure)
{
return;
}
offset = Clamp(offset, 0, ExtentHeight - ViewportHeight);
_offset = new Point(_offset.X, offset);
InvalidateScrollInfo();
InvalidateMeasure();
}
public Rect MakeVisible(Visual visual, Rect rectangle)
{
return new Rect();
}
public Rect MakeVisible(UIElement visual, Rect rectangle)
{
return new Rect();
}
public ItemLayoutInfo GetVisibleItemsRange()
{
return GetLayoutInfo(_viewportSize, ItemHeight, GetExtentInfo(_viewportSize, ItemHeight));
}
public bool CanVerticallyScroll
{
get;
set;
}
public bool CanHorizontallyScroll
{
get;
set;
}
public double ExtentWidth
{
get { return _extentSize.Width; }
}
public double ExtentHeight
{
get { return _extentSize.Height; }
}
public double ViewportWidth
{
get { return _viewportSize.Width; }
}
public double ViewportHeight
{
get { return _viewportSize.Height; }
}
public double HorizontalOffset
{
get { return _offset.X; }
}
public double VerticalOffset
{
get { return _offset.Y; }
}
public ScrollViewer ScrollOwner
{
get;
set;
}
private void InvalidateScrollInfo()
{
if (ScrollOwner != null)
{
ScrollOwner.InvalidateScrollInfo();
}
}
private static void HandleItemDimensionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var wrapPanel = (d as VirtualizingWrapPanel);
wrapPanel.InvalidateMeasure();
}
private double Clamp(double value, double min, double max)
{
return Math.Min(Math.Max(value, min), max);
}
internal class ExtentInfo
{
public int ItemsPerLine;
public int TotalLines;
public double ExtentHeight;
public double MaxVerticalOffset;
}
}
public class ItemLayoutInfo
{
public int FirstRealizedItemIndex;
public double FirstRealizedLineTop;
public double FirstRealizedItemLeft;
public int LastRealizedItemIndex;
}
}
| tipunch74/MaterialDesignInXamlToolkit | paket-files/samueldjack/VirtualCollection/VirtualCollection/VirtualCollection/VirtualizingWrapPanel.cs | C# | mit | 15,915 |
using Foundation;
using UIKit;
namespace XamarinSimulatedSensors.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to application events from iOS.
[Register ("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
// class-level declarations
public override UIWindow Window {
get;
set;
}
public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
{
// Override point for customization after application launch.
// If not required for your application you can safely delete this method
return true;
}
public override void OnResignActivation (UIApplication application)
{
// Invoked when the application is about to move from active to inactive state.
// This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message)
// or when the user quits the application and it begins the transition to the background state.
// Games should use this method to pause the game.
}
public override void DidEnterBackground (UIApplication application)
{
// Use this method to release shared resources, save user data, invalidate timers and store the application state.
// If your application supports background exection this method is called instead of WillTerminate when the user quits.
}
public override void WillEnterForeground (UIApplication application)
{
// Called as part of the transiton from background to active state.
// Here you can undo many of the changes made on entering the background.
}
public override void OnActivated (UIApplication application)
{
// Restart any tasks that were paused (or not yet started) while the application was inactive.
// If the application was previously in the background, optionally refresh the user interface.
}
public override void WillTerminate (UIApplication application)
{
// Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground.
}
}
}
| MSOpenTech/connectthedots | Devices/DirectlyConnectedDevices/XamarinSimulatedSensors/XamarinSimulatedSensors/XamarinSimulatedSensors.iOS/AppDelegate.cs | C# | mit | 2,158 |
package math.geometry;
interface Shape {
double calcArea();
} | joaopedronardari/COO-EACHUSP | Listas/Lista 1/4/src/math/geometry/Shape.java | Java | mit | 63 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Sys
{
[DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetPeerName")]
internal static extern unsafe Error GetPeerName(int socket, byte* socketAddress, int* socketAddressLen);
}
}
| josguil/corefx | src/Common/src/Interop/Unix/System.Native/Interop.GetPeerName.cs | C# | mit | 495 |
package com.ibanheiz.model;
public class Erdinger extends Cerveja {
@Override
public void info() {
System.out.println("Sou uma breja alemã boa e modinha");
}
}
| MarcosToledo/java-design-patterns | FactoryMethod/src/com/ibanheiz/model/Erdinger.java | Java | mit | 169 |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AllReady.Areas.Admin.Features.Itineraries;
using AllReady.Features.Notifications;
using AllReady.Models;
using MediatR;
using Microsoft.AspNetCore.Mvc.Rendering;
using Moq;
using Xunit;
namespace AllReady.UnitTest.Areas.Admin.Features.Itineraries
{
public class AddTeamMemberCommandHandlerAsyncTests : InMemoryContextTest
{
protected override void LoadTestData()
{
var htb = new Organization
{
Name = "Humanitarian Toolbox",
LogoUrl = "http://www.htbox.org/upload/home/ht-hero.png",
WebUrl = "http://www.htbox.org",
Campaigns = new List<Campaign>()
};
var firePrev = new Campaign
{
Name = "Neighborhood Fire Prevention Days",
ManagingOrganization = htb
};
htb.Campaigns.Add(firePrev);
var queenAnne = new Event
{
Id = 1,
Name = "Queen Anne Fire Prevention Day",
Campaign = firePrev,
CampaignId = firePrev.Id,
StartDateTime = new DateTime(2015, 7, 4, 10, 0, 0).ToUniversalTime(),
EndDateTime = new DateTime(2015, 12, 31, 15, 0, 0).ToUniversalTime(),
Location = new Location { Id = 1 },
RequiredSkills = new List<EventSkill>(),
EventType = EventType.Itinerary
};
var itinerary = new Itinerary
{
Event = queenAnne,
Name = "1st Itinerary",
Id = 1,
Date = new DateTime(2016, 07, 01)
};
Context.Organizations.Add(htb);
Context.Campaigns.Add(firePrev);
Context.Events.Add(queenAnne);
Context.Itineraries.Add(itinerary);
Context.SaveChanges();
}
[Fact]
public async Task AddTeamMemberCommandHandlerAsyncReturnsFalseWhenItineraryDoesNotExist()
{
var query = new AddTeamMemberCommand
{
ItineraryId = 0,
TaskSignupId = 1
};
var handler = new AddTeamMemberCommandHandlerAsync(Context, null);
var result = await handler.Handle(query);
Assert.Equal(false, result);
}
[Fact]
public async Task AddTeamMemberCommandHandlerAsyncReturnsTrueWhenItineraryExists()
{
var query = new AddTeamMemberCommand
{
ItineraryId = 1,
TaskSignupId = 1
};
var handler = new AddTeamMemberCommandHandlerAsync(Context, Mock.Of<IMediator>());
var result = await handler.Handle(query);
Assert.Equal(true, result);
}
[Fact]
public async Task AddTeamMemberCommandHandlerAsyncSendsPotentialItineraryTeamMemberQueryWithCorrectEventId()
{
var query = new AddTeamMemberCommand
{
ItineraryId = 1,
TaskSignupId = 1
};
var mockMediator = new Mock<IMediator>();
var handler = new AddTeamMemberCommandHandlerAsync(Context, mockMediator.Object);
await handler.Handle(query);
mockMediator.Verify(x => x.SendAsync(It.Is<PotentialItineraryTeamMembersQuery>(y => y.EventId == 1)), Times.Once);
}
[Fact(Skip = "RTM Broken Tests")]
public async Task AddTeamMemberCommandHandlerAsyncPublishesItineraryVolunteerListUpdatedWhenMatchedOnTaskSignupId()
{
var query = new AddTeamMemberCommand
{
ItineraryId = 1,
TaskSignupId = 1
};
var potentialTaskSignups = new List<SelectListItem>
{
new SelectListItem
{
Text = "user@domain.tld : Test TaskName",
Value = query.TaskSignupId.ToString()
}
};
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(x => x.SendAsync(It.IsAny<PotentialItineraryTeamMembersQuery>())).ReturnsAsync(potentialTaskSignups);
var handler = new AddTeamMemberCommandHandlerAsync(Context, mockMediator.Object);
await handler.Handle(query);
mockMediator.Verify(x => x.PublishAsync(It.Is<IntineraryVolunteerListUpdated>(y => y.TaskSignupId == query.TaskSignupId && y.ItineraryId == query.ItineraryId && y.UpdateType == UpdateType.VolunteerAssigned)), Times.Once);
}
}
} | mheggeseth/allReady | AllReadyApp/Web-App/AllReady.UnitTest/Areas/Admin/Features/Itineraries/AddTeamMemberCommandHandlerAsyncTests.cs | C# | mit | 4,697 |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
namespace Microsoft.HockeyApp.Tools
{
/// <summary>
/// xaml converter boolean to visibility
/// </summary>
public class BooleanToVisibilityConverter : IValueConverter
{
/// <summary>
/// Modifies the source data before passing it to the target for display in the UI.
/// </summary>
/// <param name="value">The source data being passed to the target.</param>
/// <param name="targetType">The type of the target property, as a type reference (System.Type for Microsoft .NET, a TypeName helper struct for Visual C++ component extensions (C++/CX)).</param>
/// <param name="parameter">An optional parameter to be used in the converter logic.</param>
/// <param name="language">The language of the conversion.</param>
/// <returns>
/// The value to be passed to the target dependency property.
/// </returns>
public object Convert(object value, Type targetType, object parameter, string language)
{
return ((bool)value) ? Visibility.Visible : Visibility.Collapsed;
}
/// <summary>
/// Modifies the target data before passing it to the source object. This method is called only in TwoWay bindings.
/// </summary>
/// <param name="value">The target data being passed to the source.</param>
/// <param name="targetType">The type of the target property, as a type reference (System.Type for Microsoft .NET, a TypeName helper struct for Visual C++ component extensions (C++/CX)).</param>
/// <param name="parameter">An optional parameter to be used in the converter logic.</param>
/// <param name="language">The language of the conversion.</param>
/// <returns>
/// The value to be passed to the source object.
/// </returns>
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return ((Visibility)value) == Visibility.Visible;
}
}
}
| bitstadium/HockeySDK-Windows | Src/Kit.WP81/Universal/Tools/BooleanToVisibilityConverter.cs | C# | mit | 2,258 |
import { isUndefined, isObject } from '../utils/isType';
$(() => {
// url for the api we will be querying
let url = '';
// key/value lookup for standards
const descriptions = {};
// cleaned up structure of the API results
const minTree = {};
// keeps track of how many waiting api-requests still need to run
let noWaiting = 0;
// prune the min_tree where there are no standards
// opporates on the principal that no two subjects have the same name
function removeUnused(name) {
const num = Object.keys(minTree).find((x) => minTree[x].name === name);
// if not top level standard
if (isUndefined(num)) {
// for each top level standard
Object.keys(minTree).forEach((knum) => {
const child = Object.keys(minTree[knum].children)
.find((x) => minTree[knum].children[x].name === name);
if (isObject(child)) {
delete minTree[knum].children[child];
$(`.rda_metadata .sub-subject select option[value="${name}"]`).remove();
}
});
} else {
delete minTree[num];
// remove min_tree[num] from top-level dropdowns
$(`.rda_metadata .subject select option[value="${name}"]`).remove();
}
}
function getDescription(id) {
$.ajax({
url: url + id.slice(4),
type: 'GET',
crossDomain: true,
dataType: 'json',
}).done((results) => {
descriptions[id] = {};
descriptions[id].title = results.title;
descriptions[id].description = results.description;
noWaiting -= 1;
});
}
// init descriptions lookup table based on passed ids
function initDescriptions(ids) {
ids.forEach((id) => {
if (!(id in descriptions)) {
noWaiting += 1;
getDescription(id);
}
});
}
// takes in a subset of the min_tree which has name and standards properties
// initializes the standards property to the result of an AJAX POST
function getStandards(name, num, child) {
// slice -4 from url to remove '/api/'
noWaiting += 1;
$.ajax({
url: `${url.slice(0, -4)}query/schemes`,
type: 'POST',
crossDomain: true,
data: `keyword=${name}`,
dataType: 'json',
}).done((result) => {
if (isUndefined(child)) {
minTree[num].standards = result.ids;
} else {
minTree[num].children[child].standards = result.ids;
}
if (result.ids.length < 1) {
removeUnused(name);
}
noWaiting -= 1;
initDescriptions(result.ids);
});
}
// clean up the data initially returned from the API
function cleanTree(apiTree) {
// iterate over api_tree
Object.keys(apiTree).forEach((num) => {
minTree[num] = {};
minTree[num].name = apiTree[num].name;
minTree[num].children = [];
if (apiTree[num].children !== undefined) {
Object.keys(apiTree[num].children).forEach((child) => {
minTree[num].children[child] = {};
minTree[num].children[child].name = apiTree[num].children[child].name;
minTree[num].children[child].standards = [];
getStandards(minTree[num].children[child].name, num, child);
});
}
// init a standards on top level
minTree[num].standards = [];
getStandards(minTree[num].name, num, undefined);
});
}
// create object for typeahead
function initTypeahead() {
const data = [];
const simpdat = [];
Object.keys(descriptions).forEach((id) => {
data.push({ value: descriptions[id].title, id });
simpdat.push(descriptions[id].title);
});
const typ = $('.standards-typeahead');
typ.typeahead({ source: simpdat });
}
function initStandards() {
// for each metadata question, init selected standards according to html
$('.rda_metadata').each(function () { // eslint-disable-line func-names
// list of selected standards
const selectedStandards = $(this).find('.selected_standards .list');
// form listing of standards
const formStandards = $(this).next('form').find('#standards');
// need to pull in the value from frm_stds
const standardsArray = JSON.parse(formStandards.val());
// init the data value
formStandards.data('standard', standardsArray);
Object.keys(standardsArray).forEach((key) => {
// add the standard to list
if (key === standardsArray[key]) {
selectedStandards.append(`<li class="${key}">${key}<button class="remove-standard"><i class="fas fa-times-circle"></i></button></li`);
} else {
selectedStandards.append(`<li class="${key}">${descriptions[key].title}<button class="remove-standard"><i class="fas fa-times-circle"></i></button></li>`);
}
});
});
}
function waitAndUpdate() {
if (noWaiting > 0) {
// if we are waiting on api responces, call this function in 1 seccond
setTimeout(waitAndUpdate, 1000);
} else {
// update all the dropdowns/ standards explore box (calling on subject
// will suffice since it will necisarily update sub-subject)
$('.rda_metadata .subject select').change();
initStandards();
initTypeahead();
}
}
// given a subject name, returns the portion of the min_tree applicable
function getSubject(subjectText) {
const num = Object.keys(minTree).find((x) => minTree[x].name === subjectText);
return minTree[num];
}
// given a subsubject name and an array of children, data, return the
// applicable child
function getSubSubject(subsubjectText, data) {
const child = Object.keys(data).find((x) => data[x].name === subsubjectText);
return data[child];
}
function updateSaveStatus(group) {
// update save/autosave status
group.next('form').find('fieldset input').change();
}
// change sub-subjects and standards based on selected subject
$('.rda_metadata').on('change', '.subject select', (e) => {
const target = $(e.currentTarget);
const group = target.closest('.rda_metadata');
const subSubject = group.find('.sub-subject select');
const subjectText = target.find(':selected').text();
// find subject in min_tree
const subject = getSubject(subjectText);
// check to see if this object has no children(and thus it's own standards)
if (subject.children.length === 0) {
// hide sub-subject since there's no data for it
subSubject.closest('div').hide();
// update the standards display selector
$('.rda_metadata .sub-subject select').change();
} else {
// show the sub-subject incase it was previously hidden
subSubject.closest('div').show();
// update the sub-subject display selector
subSubject.find('option').remove();
subject.children.forEach((child) => {
$('<option />', { value: child.name, text: child.name }).appendTo(subSubject);
});
// once we have updated the sub-standards, ensure the standards displayed
// get updated as well
$('.rda_metadata .sub-subject select').change();
}
});
// change standards based on selected sub-subject
$('.rda_metadata').on('change', '.sub-subject select', (e) => {
const target = $(e.currentTarget);
const group = target.closest('.rda_metadata');
const subject = group.find('.subject select');
const subSubject = group.find('.sub-subject select');
const subjectText = subject.find(':selected').text();
const subjectData = getSubject(subjectText);
const standards = group.find('.browse-standards-border');
let standardsData;
if (subjectData.children.length === 0) {
// update based on subject's standards
standardsData = subjectData.standards;
} else {
// update based on sub-subject's standards
const subsubjectText = subSubject.find(':selected').text();
standardsData = getSubSubject(subsubjectText, subjectData.children).standards;
}
// clear list of standards
standards.empty();
// update list of standards
Object.keys(standardsData).forEach((num) => {
const standard = descriptions[standardsData[num]];
standards.append(`<div style="background-color:#EAEAEA;border-radius:3px"><strong>${standard.title}</strong><div style="float:right"><button class="btn btn-primary select_standard" data-standard="${standardsData[num]}">Add Standard</button></br></div><p>${standard.description}</p></div>`);
});
});
// when 'Add Standard' button next to the search is clicked, we need to add
// this to the user's selected list of standards.
// update the data and val of hidden standards field in form
$('.rda_metadata').on('click', '.select_standard_typeahead', (e) => {
const target = $(e.currentTarget);
const group = target.closest('.rda_metadata');
const selected = group.find('ul.typeahead li.active');
const selectedStandards = group.find('.selected_standards .list');
// the title of the standard
const standardTitle = selected.data('value');
// need to find the standard
let standard;
Object.keys(descriptions).forEach((standardId) => {
if (descriptions[standardId].title === standardTitle) {
standard = standardId;
}
});
selectedStandards.append(`<li class="${standard}">${descriptions[standard].title}<button class="remove-standard"><i class="fas fa-times-circle"></i></button></li>`);
const formStandards = group.next('form').find('#standards');
// get the data for selected standards from the data attribute 'standard'
// of the hidden field #standards within the answer form
let frmStdsDat = formStandards.data('standard');
// need to init data object for first time
if (typeof frmStdsDat === 'undefined') {
frmStdsDat = {};
}
// init the key to standard id and value to standard.
// NOTE: is there any point in storing the title or description here?
// storing the title could make export easier as we wolnt need to query api
// but queries to the api would be 1 per-standard if we dont store these
frmStdsDat[standard] = descriptions[standard].title;
// update data value
formStandards.data('standard', frmStdsDat);
// update input value
formStandards.val(JSON.stringify(frmStdsDat));
updateSaveStatus(group);
});
// when a 'Add standard' button is clicked, we need to add this to the user's
// selected list of standards
// update the data and val of hidden standards field in form
$('.rda_metadata').on('click', '.select_standard', (e) => {
const target = $(e.currentTarget);
const group = target.closest('.rda_metadata');
const selectedStandards = group.find('.selected_standards .list');
// the identifier for the standard which was selected
const standard = target.data('standard');
// append the standard to the displayed list of selected standards
selectedStandards.append(`<li class="${standard}">${descriptions[standard].title}<button class="remove-standard"><i class="fas fa-times-circle"></i></button></li>`);
const formStandards = group.next('form').find('#standards');
// get the data for selected standards from the data attribute 'standard'
// of the hidden field #standards within the answer form
let frmStdsDat = formStandards.data('standard');
// need to init data object for first time
if (isUndefined(frmStdsDat)) {
frmStdsDat = {};
}
// init the key to standard id and value to standard.
frmStdsDat[standard] = descriptions[standard].title;
// update data value
formStandards.data('standard', frmStdsDat);
// update input value
formStandards.val(JSON.stringify(frmStdsDat));
updateSaveStatus(group);
});
// when a 'Remove Standard' button is clicked, we need to remove this from the
// user's selected list of standards. Additionally, we need to remove the
// standard from the data/val fields of standards in hidden form
$('.rda_metadata').on('click', '.remove-standard', (e) => {
const target = $(e.currentTarget);
const group = target.closest('.rda_metadata');
const listedStandard = target.closest('li');
const standardId = listedStandard.attr('class');
// remove the standard from the list
listedStandard.remove();
// update the data for the form
const formStandards = group.next('form').find('#standards');
const frmStdsDat = formStandards.data('standard');
delete frmStdsDat[standardId];
// update data value
formStandards.data('standard', frmStdsDat);
// update input value
formStandards.val(JSON.stringify(frmStdsDat));
updateSaveStatus(group);
});
// show the add custom standard div when standard not listed clicked
$('.rda_metadata').on('click', '.custom-standard', (e) => {
e.preventDefault();
const target = $(e.currentTarget);
const group = target.closest('.rda_metadata');
const addStandardDiv = $(group.find('.add-custom-standard'));
addStandardDiv.show();
});
// when this button is clicked, we add the typed standard to the list of
// selected standards
$('.rda_metadata').on('click', '.submit_custom_standard', (e) => {
e.preventDefault();
const target = $(e.currentTarget);
const group = target.closest('.rda_metadata');
const selectedStandards = group.find('.selected_standards .list');
const standardName = group.find('.custom-standard-name').val();
selectedStandards.append(`<li class="${standardName}">${standardName}<button class="remove-standard"><i class="fas fa-times-circle"></i></button></li>`);
const formStandards = group.next('form').find('#standards');
// get the data for selected standards from the data attribute 'standard'
// of the hidden field #standards within the answer form
let frmStdsDat = formStandards.data('standard');
// need to init data object for first time
if (typeof frmStdsDat === 'undefined') {
frmStdsDat = {};
}
// init the key to standard id and value to standard.
frmStdsDat[standardName] = standardName;
// update data value
formStandards.data('standard', frmStdsDat);
// update input value
formStandards.val(JSON.stringify(frmStdsDat));
updateSaveStatus(group);
});
function initMetadataQuestions() {
// find all elements with rda_metadata div
$('.rda_metadata').each((idx, el) => {
// $(this) is the element
const sub = $(el).find('.subject select');
// var sub_subject = $(this).find(".sub-subject select");
Object.keys(minTree).forEach((num) => {
$('<option />', { value: minTree[num].name, text: minTree[num].name }).appendTo(sub);
});
});
waitAndUpdate();// $(".rda_metadata .subject select").change();
}
// callback from url+subject-index
// define api_tree and call to initMetadataQuestions
function subjectCallback(data) {
// remove unused standards/substandards
cleanTree(data);
// initialize the dropdowns/selected standards for the page
initMetadataQuestions();
}
// callback from get request to rda_api_address
// define url and make a call to url+subject-index
function urlCallback(data) {
// init url
({ url } = data);
// get api_tree structure from api
$.ajax({
url: `${url}subject-index`,
type: 'GET',
crossDomain: true,
dataType: 'json',
}).done((result) => {
subjectCallback(result);
});
}
// get the url we will be using for the api
// only do this if page has an rda_metadata div
if ($('.rda_metadata').length) {
$.getJSON('/question_formats/rda_api_address', urlCallback);
}
// when the autosave or save action occurs, this clears out both the list of
// selected standards, and the selectors for new standards, as it re-renders
// the partial. This "autosave" event is triggered by that JS in order to
// allow us to know when the save has happened and re-init the question
$('.rda_metadata').on('autosave', (e) => {
e.preventDefault();
// re-initialize the metadata question
initMetadataQuestions();
});
});
| DigitalCurationCentre/roadmap | app/javascript/src/answers/rdaMetadata.js | JavaScript | mit | 16,053 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.