code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
/*
* (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands.
* See the copyright notice in the ACK home directory, in the file "Copyright".
*/
/* $Id$ */
#ifndef UTIL_OPT_TYPES_H
#define UTIL_OPT_TYPES_H
typedef char byte;
typedef char bool;
typedef struct line line_t;
typedef struct line *line_p;
typedef struct sym sym_t;
typedef struct sym *sym_p;
typedef struct num num_t;
typedef struct num *num_p;
typedef struct arg arg_t;
typedef struct arg *arg_p;
typedef struct argbytes argb_t;
typedef struct argbytes *argb_p;
typedef struct regs reg_t;
typedef struct regs *reg_p;
#ifdef LONGOFF
typedef long offset;
#else
typedef short offset;
#endif
#endif /* UTIL_OPT_TYPES_H */ | Godzil/ack | util/opt/types.h | C | bsd-3-clause | 701 |
<?php
namespace backend\helpers;
use backend\models\Order;
use backend\models\Call;
use backend\models\Review;
use yii\helpers\Html;
class AdminMenuStatus
{
public static function badges($modelName)
{
$count = 0;
switch ($modelName) {
case 'Order':
$count = Order::find()->where([
'status' => Order::STATUS_NEW
])->count();
break;
case 'Call':
$count = Call::find()->where([
'status' => Call::STATUS_NEW
])->count();
break;
case 'Review':
$count = Review::find()->where([
'status' => Review::STATUS_NEW
])->count();
break;
default:
$count = 0;
break;
}
$options = ['class' => 'label-danger label-as-badge'];
if ($count) {
return Html::tag('span', $count, $options);
}
$options = ['class' => 'label-info label-as-badge'];
return Html::tag('span', $count, $options);
}
} | Ravend6/php_yii2_ecommerce | backend/helpers/AdminMenuStatus.php | PHP | bsd-3-clause | 1,160 |
<?php
namespace Auth\Model;
use Zend\Db\TableGateway\TableGateway;
class UserTable
{
protected $tableGateway;
protected $_name = 'users';
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function getUser($id)
{
$id = (int) $id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
public function getUserByUsername($username)
{
$rowset = $this->tableGateway->select(array('username' => $username));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $username");
}
return $row;
}
public function saveUser(User $user,Array $data)
{
$now = new \DateTime();
if (empty($data['updated_at'])){
$data['updated_at'] = $now->format('Y-m-d H:i:s');
}
$id = (int) $user->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getUser($id)) {
$data['created_at'] = $now->format('Y-m-d H:i:s');
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('User id does not exist');
}
}
}
public function saveMyProfile(User $user)
{
$data = array(
'email' => $user->email,
'firstname' => $user->firstname,
'lastname' => $user->lastname,
);
if (!empty($user->id))
{
return $this->saveUser($user,$data);
}else {
throw new \Exception('User id is required');
}
}
} | Zbintiosul/zf2-tutorial | module/Auth/src/Auth/Model/UserTable.php | PHP | bsd-3-clause | 1,927 |
/*
-- MAGMA (version 2.1.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date August 2016
@author Hartwig Anzt
@generated from sparse-iter/src/zcustomic.cpp, normal z -> s, Tue Aug 30 09:38:58 2016
*/
#include "magmasparse_internal.h"
#define REAL
/**
Purpose
-------
Reads in an Incomplete Cholesky preconditioner.
Arguments
---------
@param[in]
A magma_s_matrix
input matrix A
@param[in]
b magma_s_matrix
input RHS b
@param[in,out]
precond magma_s_preconditioner*
preconditioner parameters
@param[in]
queue magma_queue_t
Queue to execute in.
@ingroup magmasparse_sgepr
********************************************************************/
extern "C"
magma_int_t
magma_scustomicsetup(
magma_s_matrix A,
magma_s_matrix b,
magma_s_preconditioner *precond,
magma_queue_t queue )
{
magma_int_t info = 0;
cusparseHandle_t cusparseHandle=NULL;
cusparseMatDescr_t descrL=NULL;
cusparseMatDescr_t descrU=NULL;
magma_s_matrix hA={Magma_CSR};
char preconditionermatrix[255];
snprintf( preconditionermatrix, sizeof(preconditionermatrix),
"/Users/hanzt0114cl306/work/matrices/ani/ani7_crop_ichol.mtx" );
CHECK( magma_s_csr_mtx( &hA, preconditionermatrix , queue) );
// for CUSPARSE
CHECK( magma_smtransfer( hA, &precond->M, Magma_CPU, Magma_DEV , queue ));
// copy the matrix to precond->L and (transposed) to precond->U
CHECK( magma_smtransfer(precond->M, &(precond->L), Magma_DEV, Magma_DEV, queue ));
CHECK( magma_smtranspose( precond->L, &(precond->U), queue ));
// extract the diagonal of L into precond->d
CHECK( magma_sjacobisetup_diagscal( precond->L, &precond->d, queue ));
CHECK( magma_svinit( &precond->work1, Magma_DEV, hA.num_rows, 1, MAGMA_S_ZERO, queue ));
// extract the diagonal of U into precond->d2
CHECK( magma_sjacobisetup_diagscal( precond->U, &precond->d2, queue ));
CHECK( magma_svinit( &precond->work2, Magma_DEV, hA.num_rows, 1, MAGMA_S_ZERO, queue ));
// CUSPARSE context //
CHECK_CUSPARSE( cusparseCreate( &cusparseHandle ));
CHECK_CUSPARSE( cusparseCreateMatDescr( &descrL ));
CHECK_CUSPARSE( cusparseSetMatType( descrL, CUSPARSE_MATRIX_TYPE_TRIANGULAR ));
CHECK_CUSPARSE( cusparseSetMatDiagType( descrL, CUSPARSE_DIAG_TYPE_NON_UNIT ));
CHECK_CUSPARSE( cusparseSetMatIndexBase( descrL, CUSPARSE_INDEX_BASE_ZERO ));
CHECK_CUSPARSE( cusparseSetMatFillMode( descrL, CUSPARSE_FILL_MODE_LOWER ));
CHECK_CUSPARSE( cusparseCreateSolveAnalysisInfo( &precond->cuinfoL ));
CHECK_CUSPARSE( cusparseScsrsv_analysis( cusparseHandle,
CUSPARSE_OPERATION_NON_TRANSPOSE, precond->M.num_rows,
precond->M.nnz, descrL,
precond->M.val, precond->M.row, precond->M.col, precond->cuinfoL ));
CHECK_CUSPARSE( cusparseCreateMatDescr( &descrU ));
CHECK_CUSPARSE( cusparseSetMatType( descrU, CUSPARSE_MATRIX_TYPE_TRIANGULAR ));
CHECK_CUSPARSE( cusparseSetMatDiagType( descrU, CUSPARSE_DIAG_TYPE_NON_UNIT ));
CHECK_CUSPARSE( cusparseSetMatIndexBase( descrU, CUSPARSE_INDEX_BASE_ZERO ));
CHECK_CUSPARSE( cusparseSetMatFillMode( descrU, CUSPARSE_FILL_MODE_LOWER ));
CHECK_CUSPARSE( cusparseCreateSolveAnalysisInfo( &precond->cuinfoU ));
CHECK_CUSPARSE( cusparseScsrsv_analysis( cusparseHandle,
CUSPARSE_OPERATION_TRANSPOSE, precond->M.num_rows,
precond->M.nnz, descrU,
precond->M.val, precond->M.row, precond->M.col, precond->cuinfoU ));
cleanup:
cusparseDestroy( cusparseHandle );
cusparseDestroyMatDescr( descrL );
cusparseDestroyMatDescr( descrU );
cusparseHandle=NULL;
descrL=NULL;
descrU=NULL;
magma_smfree( &hA, queue );
return info;
}
| maxhutch/magma | sparse-iter/src/scustomic.cpp | C++ | bsd-3-clause | 4,038 |
/**
* Css lint grunt task for CARTO.js
*
*/
module.exports = {
task: function() {
return {
dist: {
options: {
check: 'gzip'
}
},
themes: {
options: {
banner: '/* CartoDB.css minified version: <%= version %> */',
check: 'gzip'
},
files: {
'<%= dist %>/internal/themes/css/cartodb.css': ['<%= dist %>/internal/themes/css/cartodb.css']
}
}
}
}
}
| splashblot/cartodb.js | grunt/tasks/cssmin.js | JavaScript | bsd-3-clause | 475 |
package nodejs_test
import (
"log"
"net"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"syscall"
"testing"
"time"
"github.com/yookoala/gofast/example/nodejs"
)
func examplePath() string {
basePath, err := os.Getwd()
if err != nil {
panic(err)
}
return filepath.Join(basePath, "src", "index.js")
}
func exampleAssetPath() string {
basePath, err := os.Getwd()
if err != nil {
panic(err)
}
return filepath.Join(basePath, "assets")
}
func waitConn(socket string) <-chan net.Conn {
chanConn := make(chan net.Conn)
go func() {
log.Printf("wait for socket: %s", socket)
for {
if conn, err := net.Dial("unix", socket); err != nil {
time.Sleep(time.Millisecond * 2)
} else {
chanConn <- conn
break
}
}
}()
return chanConn
}
func TestHandler(t *testing.T) {
webapp := examplePath()
socket := filepath.Join(filepath.Dir(webapp), "test.sock")
// define webapp.py command
cmd := exec.Command("node", webapp)
cmd.Env = append(os.Environ(), "TEST_FCGI_SOCK="+socket)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// start the command and wait for its exit
done := make(chan error, 1)
go func() {
if err := cmd.Start(); err != nil {
done <- err
return
}
// wait if the command started successfully
log.Printf("started successfully")
log.Printf("process=%#v", cmd.Process)
done <- cmd.Wait()
log.Printf("wait ended")
}()
// wait until socket ready
conn := <-waitConn(socket)
conn.Close()
log.Printf("socket ready")
// start the proxy handler
h := nodejs.NewHandler(webapp, "unix", socket)
get := func(path string) (w *httptest.ResponseRecorder, err error) {
r, err := http.NewRequest("GET", path, nil)
if err != nil {
return
}
w = httptest.NewRecorder()
h.ServeHTTP(w, r)
return
}
testDone := make(chan bool)
go func() {
w, err := get("/")
if err != nil {
t.Errorf("unexpected error %v", err)
testDone <- false
return
}
if want, have := "hello index", w.Body.String(); want != have {
t.Errorf("expected %#v, got %#v", want, have)
testDone <- false
return
}
testDone <- true
}()
select {
case testSuccess := <-testDone:
if !testSuccess {
log.Printf("test failed")
}
case <-time.After(3 * time.Second):
log.Printf("test timeout")
case err := <-done:
if err != nil {
log.Printf("process done with error = %v", err)
} else {
log.Print("process done gracefully without error")
}
}
log.Printf("send SIGTERM")
if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {
log.Fatal("failed to kill: ", err)
}
log.Println("process killed")
os.Remove(socket)
}
func TestMuxHandler(t *testing.T) {
root := exampleAssetPath() // the "assets" folder
webapp := examplePath() // the "src/index.js" file path
socket := filepath.Join(filepath.Dir(webapp), "test2.sock")
// define webapp.py command
cmd := exec.Command("node", webapp)
cmd.Env = append(os.Environ(), "TEST_FCGI_SOCK="+socket)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// start the command and wait for its exit
done := make(chan error, 1)
go func() {
if err := cmd.Start(); err != nil {
done <- err
return
}
// wait if the command started successfully
log.Printf("started successfully")
log.Printf("process=%#v", cmd.Process)
done <- cmd.Wait()
log.Printf("wait ended")
}()
// wait until socket ready
conn := <-waitConn(socket)
conn.Close()
log.Printf("socket ready")
// start the proxy handler
h := nodejs.NewMuxHandler(
root,
webapp,
"unix", socket,
)
get := func(path string) (w *httptest.ResponseRecorder, err error) {
r, err := http.NewRequest("GET", path, nil)
if err != nil {
return
}
w = httptest.NewRecorder()
h.ServeHTTP(w, r)
return
}
testDone := make(chan bool)
go func() {
w, err := get("/responder/")
if err != nil {
t.Errorf("unexpected error %v", err)
testDone <- false
return
}
if want, have := "hello index", w.Body.String(); want != have {
t.Errorf("expected %#v, got %#v", want, have)
testDone <- false
return
}
w, err = get("/filter/content.txt")
if err != nil {
t.Errorf("unexpected error %v", err)
testDone <- false
return
}
if want, have := "ereh dlrow olleh", w.Body.String(); want != have {
t.Errorf("expected %#v, got %#v", want, have)
testDone <- false
return
}
testDone <- true
}()
select {
case testSuccess := <-testDone:
if !testSuccess {
log.Printf("test failed")
}
case <-time.After(3 * time.Second):
log.Printf("test timeout")
case err := <-done:
if err != nil {
log.Printf("process done with error = %v", err)
} else {
log.Print("process done gracefully without error")
}
}
log.Printf("send SIGTERM")
if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {
log.Fatal("failed to kill: ", err)
}
log.Println("process killed")
os.Remove(socket)
}
func TestMuxHandler_authorizer(t *testing.T) {
root := exampleAssetPath() // the "assets" folder
webapp := examplePath() // the "src/index.js" file path
socket := filepath.Join(filepath.Dir(webapp), "test3.sock")
// define webapp.py command
cmd := exec.Command("node", webapp)
cmd.Env = append(os.Environ(), "TEST_FCGI_SOCK="+socket)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// start the command and wait for its exit
done := make(chan error, 1)
go func() {
if err := cmd.Start(); err != nil {
done <- err
return
}
// wait if the command started successfully
log.Printf("started successfully")
log.Printf("process=%#v", cmd.Process)
done <- cmd.Wait()
log.Printf("wait ended")
}()
// wait until socket ready
conn := <-waitConn(socket)
conn.Close()
log.Printf("socket ready")
// start the proxy handler
h := nodejs.NewMuxHandler(
root,
webapp,
"unix", socket,
)
testDone := make(chan bool)
go func() {
path := "/authorized/responder/"
r, err := http.NewRequest("GET", path, nil)
if err != nil {
return
}
w := httptest.NewRecorder()
// try to access without proper authorization
h.ServeHTTP(w, r)
if err != nil {
t.Errorf("unexpected error %v", err)
testDone <- false
return
}
if want, have := "authorizer app: permission denied", w.Body.String(); want != have {
t.Errorf("expected %#v, got %#v", want, have)
testDone <- false
return
}
if want, have := http.StatusForbidden, w.Code; want != have {
t.Errorf("expected %#v, got %#v", want, have)
testDone <- false
return
}
// try to access with proper authorization
r, err = http.NewRequest("GET", path, nil)
if err != nil {
return
}
r.Header.Add("Authorization", "hello-auth")
w = httptest.NewRecorder()
h.ServeHTTP(w, r)
if err != nil {
t.Errorf("unexpected error %v", err)
testDone <- false
return
}
if want1, want2, have := "foo: bar!\nhello: howdy!\nhello index", "hello: howdy!\nfoo: bar!\nhello index", w.Body.String(); want1 != have && want2 != have {
t.Errorf("expected %#v or %#v, got %#v", want1, want2, have)
testDone <- false
return
}
testDone <- true
}()
select {
case testSuccess := <-testDone:
if !testSuccess {
log.Printf("test failed")
}
case <-time.After(3 * time.Second):
log.Printf("test timeout")
case err := <-done:
if err != nil {
log.Printf("process done with error = %v", err)
} else {
log.Print("process done gracefully without error")
}
}
log.Printf("send SIGTERM")
if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {
log.Fatal("failed to kill: ", err)
}
log.Println("process killed")
os.Remove(socket)
}
| yookoala/gofast | example/nodejs/nodejs_test.go | GO | bsd-3-clause | 7,583 |
package net.ripe.db.whois.api.whois;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.net.InetAddresses;
import net.ripe.db.whois.api.whois.domain.*;
import net.ripe.db.whois.common.DateTimeProvider;
import net.ripe.db.whois.common.dao.RpslObjectDao;
import net.ripe.db.whois.common.domain.CIString;
import net.ripe.db.whois.common.domain.ResponseObject;
import net.ripe.db.whois.common.rpsl.*;
import net.ripe.db.whois.common.source.SourceContext;
import net.ripe.db.whois.query.domain.*;
import net.ripe.db.whois.query.handler.QueryHandler;
import net.ripe.db.whois.query.query.Query;
import net.ripe.db.whois.query.query.QueryFlag;
import net.ripe.db.whois.update.domain.*;
import net.ripe.db.whois.update.handler.UpdateRequestHandler;
import net.ripe.db.whois.update.log.LoggerContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static net.ripe.db.whois.common.domain.CIString.ciString;
import static net.ripe.db.whois.query.query.QueryFlag.*;
@Component
@Path("/")
public class WhoisRestService {
private static final int STATUS_TOO_MANY_REQUESTS = 429;
private static final Pattern UPDATE_RESPONSE_ERRORS = Pattern.compile("(?m)^\\*\\*\\*Error:\\s*((.*)(\\n[ ]+.*)*)$");
private static final Joiner JOINER = Joiner.on(",");
private static final Splitter AMPERSAND = Splitter.on("&");
private static final Set<String> NOT_ALLOWED_SEARCH_QUERY_FLAGS = Sets.newHashSet(Iterables.concat(
TEMPLATE.getFlags(),
VERBOSE.getFlags(),
CLIENT.getFlags(),
NO_GROUPING.getFlags(),
SOURCES.getFlags(),
NO_TAG_INFO.getFlags(),
SHOW_TAG_INFO.getFlags(),
ALL_SOURCES.getFlags(),
LIST_SOURCES_OR_VERSION.getFlags(),
LIST_SOURCES.getFlags(),
DIFF_VERSIONS.getFlags(),
LIST_VERSIONS.getFlags(),
SHOW_VERSION.getFlags(),
PERSISTENT_CONNECTION.getFlags()
));
private final DateTimeProvider dateTimeProvider;
private final UpdateRequestHandler updateRequestHandler;
private final LoggerContext loggerContext;
private final RpslObjectDao rpslObjectDao;
private final SourceContext sourceContext;
private final QueryHandler queryHandler;
private final WhoisObjectMapper whoisObjectMapper;
@Autowired
public WhoisRestService(final DateTimeProvider dateTimeProvider, final UpdateRequestHandler updateRequestHandler, final LoggerContext loggerContext, final RpslObjectDao rpslObjectDao, final SourceContext sourceContext, final QueryHandler queryHandler, final WhoisObjectMapper whoisObjectMapper) {
this.dateTimeProvider = dateTimeProvider;
this.updateRequestHandler = updateRequestHandler;
this.loggerContext = loggerContext;
this.rpslObjectDao = rpslObjectDao;
this.sourceContext = sourceContext;
this.queryHandler = queryHandler;
this.whoisObjectMapper = whoisObjectMapper;
}
@DELETE
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Path("/{source}/{objectType}/{key:.*}")
public Response restDelete(
@Context final HttpServletRequest request,
@PathParam("source") final String source,
@PathParam("objectType") final String objectType,
@PathParam("key") final String key,
@QueryParam(value = "reason") @DefaultValue("--") final String reason,
@QueryParam(value = "password") final List<String> passwords) {
checkForMainSource(source);
final RpslObject originalObject = rpslObjectDao.getByKey(ObjectType.getByName(objectType), key);
performUpdate(
createOrigin(request),
createUpdate(originalObject, passwords, reason),
createContent(originalObject, passwords, reason),
Keyword.NONE);
return Response.status(Response.Status.OK).build();
}
@PUT
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Path("/{source}/{objectType}/{key:.*}")
public Response restUpdate(
final WhoisResources resource,
@Context final HttpServletRequest request,
@PathParam("source") final String source,
@PathParam("objectType") final String objectType,
@PathParam("key") final String key,
@QueryParam(value = "password") final List<String> passwords) {
checkForMainSource(source);
final RpslObject submittedObject = getSubmittedObject(resource);
validateSubmittedObject(submittedObject, objectType, key);
final RpslObject response = performUpdate(
createOrigin(request),
createUpdate(submittedObject, passwords, null),
createContent(submittedObject, passwords, null),
Keyword.NONE);
return Response.ok(createWhoisResources(request, response, false)).build();
}
@POST
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Path("/{source}/{objectType}")
public Response restCreate(
final WhoisResources resource,
@Context final HttpServletRequest request,
@PathParam("source") final String source,
@PathParam("objectType") final String objectType,
@QueryParam(value = "password") final List<String> passwords) {
checkForMainSource(source);
final RpslObject submittedObject = getSubmittedObject(resource);
final RpslObject response = performUpdate(
createOrigin(request),
createUpdate(submittedObject, passwords, null),
createContent(submittedObject, passwords, null),
Keyword.NEW);
return Response.ok(createWhoisResources(request, response, false)).build();
}
private void checkForMainSource(String source) {
if (!sourceContext.getCurrentSource().getName().toString().equalsIgnoreCase(source)) {
throw new IllegalArgumentException("Invalid source: " + source);
}
}
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Path("/{source}/{objectType}/{key:.*}")
public Response restGet(
@Context final HttpServletRequest request,
@PathParam("source") final String source,
@PathParam("objectType") final String objectType,
@PathParam("key") final String key) {
checkForInvalidSource(source);
final boolean noFilter = hasUnfilteredQueryParameter(request.getQueryString());
final Query query = Query.parse(String.format("%s %s %s %s %s %s %s %s %s %s",
QueryFlag.EXACT.getLongFlag(),
QueryFlag.NO_GROUPING.getLongFlag(),
QueryFlag.NO_REFERENCED.getLongFlag(),
QueryFlag.SOURCES.getLongFlag(),
source,
QueryFlag.SELECT_TYPES.getLongFlag(),
ObjectType.getByName(objectType).getName(),
QueryFlag.SHOW_TAG_INFO.getLongFlag(),
noFilter ? QueryFlag.NO_FILTERING.getLongFlag() : "",
key));
return handleQuery(query, key, request, null);
}
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Path("/{source}/{objectType}/{key:.*}/versions")
public Response restVersions(
@Context final HttpServletRequest request,
@PathParam("source") final String source,
@PathParam("objectType") final String objectType,
@PathParam("key") final String key) {
checkForMainSource(source);
final Query query = Query.parse(String.format("--list-versions %s", key));
return handleQuery(query, key, request, null);
}
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Path("/{source}/{objectType}/{key:.*}/versions/{version}")
public Response restVersion(
@Context final HttpServletRequest request,
@PathParam("source") final String source,
@PathParam("objectType") final String objectType,
@PathParam("key") final String key,
@PathParam("version") final Integer version) {
checkForMainSource(source);
final Query query = Query.parse(String.format("" +
"--show-version %s %s",
version,
key));
return handleQuery(query, key, request, null);
}
// TODO: [AH] refactor this looks-generic-but-is-not method
private Response handleQuery(final Query query, final String key, final HttpServletRequest request, @Nullable final Parameters parameters) {
final InetAddress remoteAddress = InetAddresses.forString(request.getRemoteAddr());
final int contextId = System.identityHashCode(Thread.currentThread());
if (query.isVersionList() || query.isObjectVersion()) {
return handleVersionQuery(query, key, remoteAddress, contextId);
}
return handleQueryAndStreamResponse(query, request, remoteAddress, contextId, parameters);
}
// TODO: [AH] refactor this spaghetti
private Response handleVersionQuery(final Query query, final String key, final InetAddress remoteAddress, final int contextId) {
final ApiResponseHandlerVersions apiResponseHandlerVersions = new ApiResponseHandlerVersions();
queryHandler.streamResults(query, remoteAddress, contextId, apiResponseHandlerVersions);
final VersionWithRpslResponseObject versionResponseObject = apiResponseHandlerVersions.getVersionWithRpslResponseObject();
final List<DeletedVersionResponseObject> deleted = apiResponseHandlerVersions.getDeletedObjects();
final List<VersionResponseObject> versions = apiResponseHandlerVersions.getVersionObjects();
if (versionResponseObject == null && versions.isEmpty()) {
if (deleted.isEmpty() || query.isObjectVersion()) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
}
final WhoisResources whoisResources = new WhoisResources();
if (versionResponseObject != null) {
final WhoisObject whoisObject = whoisObjectMapper.map(versionResponseObject.getRpslObject());
whoisObject.setVersion(versionResponseObject.getVersion());
whoisResources.setWhoisObjects(Collections.singletonList(whoisObject));
} else {
final String type = (versions.size() > 0) ? versions.get(0).getType().getName() : deleted.size() > 0 ? deleted.get(0).getType().getName() : null;
final WhoisVersions whoisVersions = new WhoisVersions(type, key, whoisObjectMapper.mapVersions(deleted, versions));
whoisResources.setVersions(whoisVersions);
}
return Response.ok(whoisResources).build();
}
private Response handleQueryAndStreamResponse(final Query query, final HttpServletRequest request, final InetAddress remoteAddress, final int contextId, @Nullable final Parameters parameters) {
final StreamingMarshal streamingMarshal = getStreamingMarshal(request);
return Response.ok(new StreamingOutput() {
private boolean found;
@Override
public void write(final OutputStream output) throws IOException {
// TODO [AK] Crude way to handle tags, but working
final Queue<RpslObject> rpslObjectQueue = new ArrayDeque<>(1);
final List<TagResponseObject> tagResponseObjects = Lists.newArrayList();
try {
queryHandler.streamResults(query, remoteAddress, contextId, new ApiResponseHandler() {
@Override
public void handle(final ResponseObject responseObject) {
if (responseObject instanceof TagResponseObject) {
tagResponseObjects.add((TagResponseObject) responseObject);
} else if (responseObject instanceof RpslObject) {
if (!found) {
startStreaming(output);
}
found = true;
streamObject(rpslObjectQueue.poll(), tagResponseObjects);
rpslObjectQueue.add((RpslObject) responseObject);
}
// TODO [AK] Handle related messages
}
});
streamObject(rpslObjectQueue.poll(), tagResponseObjects);
if (!found) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
} catch (QueryException e) {
if (e.getCompletionInfo() == QueryCompletionInfo.BLOCKED) {
throw new WebApplicationException(Response.status(STATUS_TOO_MANY_REQUESTS).build());
} else {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build());
}
}
streamingMarshal.close();
}
private void startStreaming(final OutputStream output) {
streamingMarshal.open(output, "whois-resources");
if (parameters != null) {
streamingMarshal.write("parameters", parameters);
}
streamingMarshal.start("objects");
}
private void streamObject(@Nullable final RpslObject rpslObject, final List<TagResponseObject> tagResponseObjects) {
if (rpslObject == null) {
return;
}
final WhoisObject whoisObject = whoisObjectMapper.map(rpslObject, tagResponseObjects);
if (streamingMarshal instanceof StreamingMarshalJson) {
streamingMarshal.write("object", Collections.singletonList(whoisObject));
} else {
streamingMarshal.write("object", whoisObject);
}
tagResponseObjects.clear();
}
}).build();
}
private StreamingMarshal getStreamingMarshal(final HttpServletRequest request) {
final String acceptHeader = request.getHeader(HttpHeaders.ACCEPT);
for (final String accept : Splitter.on(',').split(acceptHeader)) {
try {
final MediaType mediaType = MediaType.valueOf(accept);
final String subtype = mediaType.getSubtype().toLowerCase();
if (subtype.equals("json") || subtype.endsWith("+json")) {
return new StreamingMarshalJson();
} else if (subtype.equals("xml") || subtype.endsWith("+xml")) {
return new StreamingMarshalXml();
}
} catch (IllegalArgumentException ignored) {
}
}
return new StreamingMarshalXml();
}
private boolean hasUnfilteredQueryParameter(final String queryString) {
return !StringUtils.isBlank(queryString) &&
Iterables.contains(Iterables.transform(AMPERSAND.split(queryString), new Function<String, String>() {
@Override
public String apply(final String input) {
String result = input.toLowerCase();
if (result.contains("=")) {
return result.substring(0, result.indexOf("="));
}
return result;
}
}), "unfiltered");
}
/**
* The search interface resembles a standard Whois client query with the extra features of multi-registry client, multiple response styles that can be selected via content negotiation and with an extensible URL parameters schema.
*
* @param sources Mandatory. It's possible to specify multiple sources.
* @param queryString Mandatory.
* @param inverseAttributes If specified the query is an inverse lookup on the given attribute, if not specified the query is a direct lookup search.
* @param includeTags Only show RPSL objects with given tags. Can be multiple.
* @param excludeTags Only show RPSL objects that <i>do not</i> have given tags. Can be multiple.
* @param types If specified the results will be filtered by object-type, multiple type-filters can be specified.
* @param flags Optional query-flags. Use separate flags parameters for each option (see examples above)
* @return Returns the query result.
*/
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Path("/search")
public Response search(
@Context HttpServletRequest request,
@QueryParam("source") Set<String> sources,
@QueryParam("query-string") String queryString,
@QueryParam("inverse-attribute") Set<String> inverseAttributes,
@QueryParam("include-tag") Set<String> includeTags,
@QueryParam("exclude-tag") Set<String> excludeTags,
@QueryParam("type-filter") Set<String> types,
@QueryParam("flags") Set<String> flags) {
if (sources == null || sources.isEmpty()) {
sources = Collections.singleton(sourceContext.getCurrentSource().getName().toString());
} else {
checkForInvalidSources(sources);
}
final Set<String> separateFlags = splitInputFlags(flags);
checkForInvalidFlags(separateFlags);
final Query query = Query.parse(String.format("%s %s %s %s %s %s %s %s %s %s %s %s %s",
QueryFlag.SOURCES.getLongFlag(),
JOINER.join(sources),
QueryFlag.SHOW_TAG_INFO.getLongFlag(),
(types == null || types.isEmpty()) ? "" : QueryFlag.SELECT_TYPES.getLongFlag(),
JOINER.join(types),
(inverseAttributes == null || inverseAttributes.isEmpty()) ? "" : QueryFlag.INVERSE.getLongFlag(),
JOINER.join(inverseAttributes),
(includeTags == null || includeTags.isEmpty()) ? "" : QueryFlag.FILTER_TAG_INCLUDE.getLongFlag(),
JOINER.join(includeTags),
(excludeTags == null || excludeTags.isEmpty()) ? "" : QueryFlag.FILTER_TAG_EXCLUDE.getLongFlag(),
JOINER.join(excludeTags),
Joiner.on(" ").join(Iterables.transform(separateFlags, new Function<String, String>() {
@Override
public String apply(String input) {
return input.length() > 1 ? "--" + input : "-" + input;
}
})),
(queryString == null ? "" : queryString)));
final Parameters parameters = new Parameters();
parameters.setSources(sources);
parameters.setQueryStrings(queryString);
parameters.setInverseLookup(inverseAttributes);
parameters.setTypeFilters(types);
parameters.setFlags(separateFlags);
return handleQuery(query, queryString, request, parameters);
}
private void checkForInvalidSources(final Set<String> sources) {
for (final String source : sources) {
checkForInvalidSource(source);
}
}
private void checkForInvalidSource(final String source) {
if (!sourceContext.getAllSourceNames().contains(ciString(source))) {
throw new IllegalArgumentException(String.format("Invalid source '%s'", source));
}
}
private Set<String> splitInputFlags(final Set<String> inputFlags) {
final Set<String> separateFlags = Sets.newLinkedHashSet(); // reporting errors should happen in the same order
for (final String flagParameter : inputFlags) {
if (QueryFlag.getValidLongFlags().contains(flagParameter)) {
separateFlags.add(flagParameter);
} else {
final CharacterIterator charIterator = new StringCharacterIterator(flagParameter);
for (char flag = charIterator.first(); flag != CharacterIterator.DONE; flag = charIterator.next()) {
final String flagString = String.valueOf(flag);
if (!QueryFlag.getValidShortFlags().contains(flagString)) {
throw new IllegalArgumentException(String.format("Invalid option '%s'", flag));
}
separateFlags.add(flagString);
}
}
}
return separateFlags;
}
private void checkForInvalidFlags(final Set<String> flags) {
for (final String flag : flags) {
if (NOT_ALLOWED_SEARCH_QUERY_FLAGS.contains(flag)) {
throw new IllegalArgumentException(String.format("Disallowed option '%s'", flag));
}
}
}
private RpslObject performUpdate(final Origin origin, final Update update, final String content, final Keyword keyword) {
loggerContext.init(getRequestId(origin.getFrom()));
try {
final UpdateContext updateContext = new UpdateContext(loggerContext);
final boolean notificationsEnabled = true;
final UpdateRequest updateRequest = new UpdateRequest(
origin,
keyword,
content,
Lists.newArrayList(update),
notificationsEnabled);
final UpdateResponse response = updateRequestHandler.handle(updateRequest, updateContext);
if (updateContext.getStatus(update) == UpdateStatus.FAILED_AUTHENTICATION) {
throw new WebApplicationException(getResponse(new UpdateResponse(UpdateStatus.FAILED_AUTHENTICATION, response.getResponse())));
}
if (response.getStatus() != UpdateStatus.SUCCESS) {
throw new WebApplicationException(getResponse(response));
}
return update.getOperation() == Operation.DELETE ? null : rpslObjectDao.getById(updateContext.getUpdateInfo(update).getObjectId());
} finally {
loggerContext.remove();
}
}
private String createContent(final RpslObject rpslObject, final List<String> passwords, final String deleteReason) {
final StringBuilder builder = new StringBuilder();
builder.append(rpslObject.toString());
if (builder.charAt(builder.length() - 1) != '\n') {
builder.append('\n');
}
if (deleteReason != null) {
builder.append("delete: ");
builder.append(deleteReason);
builder.append("\n\n");
}
for (final String password : passwords) {
builder.append("password: ");
builder.append(password);
builder.append('\n');
}
return builder.toString();
}
private Update createUpdate(final RpslObject rpslObject, final List<String> passwords, final String deleteReason) {
return new Update(
createParagraph(rpslObject, passwords),
deleteReason != null ? Operation.DELETE : Operation.UNSPECIFIED,
deleteReason != null ? Lists.newArrayList(deleteReason) : null,
rpslObject);
}
private Paragraph createParagraph(final RpslObject rpslObject, final List<String> passwords) {
final Set<PasswordCredential> passwordCredentials = Sets.newHashSet();
for (String password : passwords) {
passwordCredentials.add(new PasswordCredential(password));
}
return new Paragraph(rpslObject.toString(), new Credentials(passwordCredentials));
}
private Origin createOrigin(final HttpServletRequest request) {
return new WhoisRestApi(dateTimeProvider, request.getRemoteAddr());
}
private WhoisResources createWhoisResources(final HttpServletRequest request, final RpslObject rpslObject, boolean filter) {
final WhoisResources whoisResources = new WhoisResources();
whoisResources.setWhoisObjects(Collections.singletonList(whoisObjectMapper.map(rpslObject, filter)));
whoisResources.setLink(new Link("locator", RestServiceHelper.getRequestURL(request)));
return whoisResources;
}
private RpslObject getSubmittedObject(final WhoisResources whoisResources) {
if (whoisResources.getWhoisObjects().isEmpty() || whoisResources.getWhoisObjects().size() > 1) {
throw new IllegalArgumentException("Expected a single RPSL object");
}
return whoisObjectMapper.map(whoisResources.getWhoisObjects().get(0));
}
private Response getResponse(final UpdateResponse updateResponse) {
int status;
switch (updateResponse.getStatus()) {
case FAILED: {
status = HttpServletResponse.SC_BAD_REQUEST;
final String errors = findAllErrors(updateResponse);
if (!errors.isEmpty()) {
if (errors.contains("Enforced new keyword specified, but the object already exists")) {
status = HttpServletResponse.SC_CONFLICT;
}
return Response.status(status).entity(errors).build();
}
break;
}
case EXCEPTION:
status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
break;
case FAILED_AUTHENTICATION:
status = HttpServletResponse.SC_UNAUTHORIZED;
final String errors = findAllErrors(updateResponse);
if (!errors.isEmpty()) {
return Response.status(status).entity(errors).build();
}
break;
default:
status = HttpServletResponse.SC_OK;
}
return Response.status(status).build();
}
private String getRequestId(final String remoteAddress) {
return String.format("rest_%s_%s", remoteAddress, System.nanoTime());
}
private String findAllErrors(final UpdateResponse updateResponse) {
final StringBuilder builder = new StringBuilder();
final Matcher matcher = UPDATE_RESPONSE_ERRORS.matcher(updateResponse.getResponse());
while (matcher.find()) {
builder.append(matcher.group(1).replaceAll("[\\n ]+", " "));
builder.append('\n');
}
return builder.toString();
}
private void validateSubmittedObject(final RpslObject object, final String objectType, final String key) {
if (!(object.getKey().equals(CIString.ciString(key)) &&
object.getType().getName().equalsIgnoreCase(objectType))) {
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
}
}
| APNIC-net/whois | whois-api/src/main/java/net/ripe/db/whois/api/whois/WhoisRestService.java | Java | bsd-3-clause | 27,939 |
package com.wixpress.petri.petri
import java.util
import java.util.UUID
import com.wixpress.petri.experiments.domain.{Experiment, ExperimentSpec}
/**
* @author Dalias
* @since 3/22/15
*/
trait PetriDeveloperApi {
def getFullUserState(userGuid: UUID): UserState
def migrateStartEndDates(): Unit
def addSpecNoValidation(spec :ExperimentSpec): Unit
def fetchExperimentsGoingToEndDueToDate(minutesEnded: Int): util.List[Experiment]
}
| wix/petri | petri-server-core/src/main/java/com/wixpress/petri/petri/PetriDeveloperApi.scala | Scala | bsd-3-clause | 449 |
FactoryGirl.define do
factory :dmi_order_ready_to_ship, parent: :order_ready_to_ship do
dmi_status 'processed'
dmi_order_number { (1..8).map { rand(10) }.join }
end
factory :shipped_dmi_order, parent: :shipped_order do
dmi_status 'processed'
dmi_order_number { (1..8).map { rand(10) }.join }
end
factory :dmi_order_with_pending_payments, parent: :completed_order_with_pending_payment do
dmi_status 'processed'
dmi_order_number { (1..8).map { rand(10) }.join }
end
factory :order_with_dmi_error, parent: :order_ready_to_ship do
dmi_status 'error'
dmi_order_number nil
end
factory :dmi_event, class: 'Spree::DmiEvent' do
event_type %w(info error success warning).sample
description 'Sample description'
end
end
| manmartinez/spree_dmi | lib/spree_dmi/factories.rb | Ruby | bsd-3-clause | 777 |
// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
// Original code is licensed as follows:
/*
* Copyright 2008 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.
*/
#include "xfa/fxbarcode/common/BC_CommonByteMatrix.h"
#include "xfa/fxbarcode/qrcode/BC_QRCoder.h"
#include "xfa/fxbarcode/qrcode/BC_QRCoderErrorCorrectionLevel.h"
#include "xfa/fxbarcode/qrcode/BC_QRCoderMaskUtil.h"
#include "xfa/fxbarcode/utils.h"
CBC_QRCoderMaskUtil::CBC_QRCoderMaskUtil() {}
CBC_QRCoderMaskUtil::~CBC_QRCoderMaskUtil() {}
int32_t CBC_QRCoderMaskUtil::ApplyMaskPenaltyRule1(
CBC_CommonByteMatrix* matrix) {
return ApplyMaskPenaltyRule1Internal(matrix, true) +
ApplyMaskPenaltyRule1Internal(matrix, false);
}
int32_t CBC_QRCoderMaskUtil::ApplyMaskPenaltyRule2(
CBC_CommonByteMatrix* matrix) {
int32_t penalty = 0;
uint8_t* array = matrix->GetArray();
int32_t width = matrix->GetWidth();
int32_t height = matrix->GetHeight();
for (int32_t y = 0; y < height - 1; y++) {
for (int32_t x = 0; x < width - 1; x++) {
int32_t value = array[y * width + x];
if (value == array[y * width + x + 1] &&
value == array[(y + 1) * width + x] &&
value == array[(y + 1) * width + x + 1]) {
penalty++;
}
}
}
return 3 * penalty;
}
int32_t CBC_QRCoderMaskUtil::ApplyMaskPenaltyRule3(
CBC_CommonByteMatrix* matrix) {
int32_t penalty = 0;
uint8_t* array = matrix->GetArray();
int32_t width = matrix->GetWidth();
int32_t height = matrix->GetHeight();
for (int32_t y = 0; y < height; ++y) {
for (int32_t x = 0; x < width; ++x) {
if (x == 0 &&
((y >= 0 && y <= 6) || (y >= height - 7 && y <= height - 1))) {
continue;
}
if (x == width - 7 && (y >= 0 && y <= 6)) {
continue;
}
if (y == 0 &&
((x >= 0 && x <= 6) || (x >= width - 7 && x <= width - 1))) {
continue;
}
if (y == height - 7 && (x >= 0 && x <= 6)) {
continue;
}
if (x + 6 < width && array[y * width + x] == 1 &&
array[y * width + x + 1] == 0 && array[y * width + x + 2] == 1 &&
array[y * width + x + 3] == 1 && array[y * width + x + 4] == 1 &&
array[y * width + x + 5] == 0 && array[y * width + x + 6] == 1 &&
((x + 10 < width && array[y * width + x + 7] == 0 &&
array[y * width + x + 8] == 0 && array[y * width + x + 9] == 0 &&
array[y * width + x + 10] == 0) ||
(x - 4 >= 0 && array[y * width + x - 1] == 0 &&
array[y * width + x - 2] == 0 && array[y * width + x - 3] == 0 &&
array[y * width + x - 4] == 0))) {
penalty += 40;
}
if (y + 6 < height && array[y * width + x] == 1 &&
array[(y + 1) * width + x] == 0 && array[(y + 2) * width + x] == 1 &&
array[(y + 3) * width + x] == 1 && array[(y + 4) * width + x] == 1 &&
array[(y + 5) * width + x] == 0 && array[(y + 6) * width + x] == 1 &&
((y + 10 < height && array[(y + 7) * width + x] == 0 &&
array[(y + 8) * width + x] == 0 &&
array[(y + 9) * width + x] == 0 &&
array[(y + 10) * width + x] == 0) ||
(y - 4 >= 0 && array[(y - 1) * width + x] == 0 &&
array[(y - 2) * width + x] == 0 &&
array[(y - 3) * width + x] == 0 &&
array[(y - 4) * width + x] == 0))) {
penalty += 40;
}
}
}
return penalty;
}
int32_t CBC_QRCoderMaskUtil::ApplyMaskPenaltyRule4(
CBC_CommonByteMatrix* matrix) {
int32_t numDarkCells = 0;
uint8_t* array = matrix->GetArray();
int32_t width = matrix->GetWidth();
int32_t height = matrix->GetHeight();
for (int32_t y = 0; y < height; ++y) {
for (int32_t x = 0; x < width; ++x) {
if (array[y * width + x] == 1) {
numDarkCells += 1;
}
}
}
int32_t numTotalCells = matrix->GetHeight() * matrix->GetWidth();
double darkRatio = (double)numDarkCells / numTotalCells;
return abs((int32_t)(darkRatio * 100 - 50) / 5) * 5 * 10;
}
bool CBC_QRCoderMaskUtil::GetDataMaskBit(int32_t maskPattern,
int32_t x,
int32_t y,
int32_t& e) {
if (!CBC_QRCoder::IsValidMaskPattern(maskPattern)) {
e = (BCExceptionInvalidateMaskPattern);
return false;
}
int32_t intermediate = 0, temp = 0;
switch (maskPattern) {
case 0:
intermediate = (y + x) & 0x1;
break;
case 1:
intermediate = y & 0x1;
break;
case 2:
intermediate = x % 3;
break;
case 3:
intermediate = (y + x) % 3;
break;
case 4:
intermediate = ((y >> 1) + (x / 3)) & 0x1;
break;
case 5:
temp = y * x;
intermediate = (temp & 0x1) + (temp % 3);
break;
case 6:
temp = y * x;
intermediate = (((temp & 0x1) + (temp % 3)) & 0x1);
break;
case 7:
temp = y * x;
intermediate = (((temp % 3) + ((y + x) & 0x1)) & 0x1);
break;
default: {
e = BCExceptionInvalidateMaskPattern;
return false;
}
}
return intermediate == 0;
}
int32_t CBC_QRCoderMaskUtil::ApplyMaskPenaltyRule1Internal(
CBC_CommonByteMatrix* matrix,
bool isHorizontal) {
int32_t penalty = 0;
int32_t numSameBitCells = 0;
int32_t prevBit = -1;
int32_t width = matrix->GetWidth();
int32_t height = matrix->GetHeight();
int32_t iLimit = isHorizontal ? height : width;
int32_t jLimit = isHorizontal ? width : height;
uint8_t* array = matrix->GetArray();
for (int32_t i = 0; i < iLimit; ++i) {
for (int32_t j = 0; j < jLimit; ++j) {
int32_t bit = isHorizontal ? array[i * width + j] : array[j * width + i];
if (bit == prevBit) {
numSameBitCells += 1;
if (numSameBitCells == 5) {
penalty += 3;
} else if (numSameBitCells > 5) {
penalty += 1;
}
} else {
numSameBitCells = 1;
prevBit = bit;
}
}
numSameBitCells = 0;
}
return penalty;
}
| DrAlexx/pdfium | xfa/fxbarcode/qrcode/BC_QRCoderMaskUtil.cpp | C++ | bsd-3-clause | 6,779 |
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font-family: Helvetica;
font-size: 10px;
}
.point {
fill: black;
}
rect, circle, line {
fill: none;
stroke: black;
stroke-width: 1;
}
</style>
<body>
<script src="../node_modules/d3/build/d3.js"></script>
<script src="../build/d3-gridding.js"></script>
<script src="utils/utils.js"></script>
<script src="utils/layouts.js"></script>
<script>
var width = 400,
height = 400;
var nb_set = 15;
var cell_width = 10;
var data = layouts[3].values;
var dataMarginal = d3.range(1000).map(d3.randomBates(10));
var x = d3.scaleLinear()
.rangeRound([0, width]);
var bins = d3.histogram()
.domain(x.domain())
.thresholds(x.ticks(25))
(dataMarginal);
// PERMUTATIONS
d3.range(10).map(function(a) {
d3.range(10).map(function(_, j) {
var f = {};
f.__width = 10; //cell_width;
f.__height = a + 10; //nb_set * cell_width;
f.index = j + "";
data.push(f);
});
});
var params = [{
"size": function() { return [width, height]; },
"offset": function(d) { return [0, 0]; },
"mode": "coordinate",
"valueX": "__x",
"valueY": "__y",
"valueWidth": "__width",
"valueHeight": "__height",
"padding": 2,
"level": 0
}, {
"size": function(d) { return [d.width, d.height]; },
"offset": function(d) { return [d.x, d.y]; },
"mode": "vertical",
"orient": "up",
"valueHeight": "__height",
"padding": 10,
"level": 1
}];
var svgSquares = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g");
function update() {
nested_data = generate_nesting_agg([
{groupBy: "", fn: function(d) { return d.length}, accessor: function(d) { return d; }},
{groupBy: "index", fn: function(d) { return Math.random();}},
// {groupBy: "index2", fn: function(d) { return d.length;}}
], "data");
draw(svgSquares, nested_data[0], params, 0, "0_");
d3.selectAll(".index").remove();
// Get all the rects and create groups?
// d3.selectAll(".square0_").remove();
}
update();
</script>
| romsson/d3-gridding | example/layout-benchmark.html | HTML | bsd-3-clause | 2,050 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/devtools/devtools_window.h"
#include <algorithm>
#include "base/command_line.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/lazy_instance.h"
#include "base/metrics/histogram.h"
#include "base/prefs/scoped_user_pref_update.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/chrome_page_zoom.h"
#include "chrome/browser/extensions/api/debugger/debugger_api.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_web_contents_observer.h"
#include "chrome/browser/file_select_helper.h"
#include "chrome/browser/infobars/confirm_infobar_delegate.h"
#include "chrome/browser/infobars/infobar.h"
#include "chrome/browser/prefs/pref_service_syncable.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/session_tab_helper.h"
#include "chrome/browser/themes/theme_properties.h"
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/browser/ui/browser_iterator.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/host_desktop.h"
#include "chrome/browser/ui/prefs/prefs_tab_helper.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/webui/devtools_ui.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/manifest_url_handler.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "components/user_prefs/pref_registry_syncable.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/devtools_client_host.h"
#include "content/public/browser/devtools_manager.h"
#include "content/public/browser/favicon_status.h"
#include "content/public/browser/load_notification_details.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_view.h"
#include "content/public/common/bindings_policy.h"
#include "content/public/common/content_client.h"
#include "content/public/common/page_transition_types.h"
#include "content/public/common/renderer_preferences.h"
#include "content/public/common/url_constants.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/extension_system.h"
#include "extensions/common/extension_set.h"
#include "grit/generated_resources.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "ui/base/l10n/l10n_util.h"
using base::DictionaryValue;
using content::BrowserThread;
using content::DevToolsAgentHost;
// DevToolsConfirmInfoBarDelegate ---------------------------------------------
class DevToolsConfirmInfoBarDelegate : public ConfirmInfoBarDelegate {
public:
// If |infobar_service| is NULL, runs |callback| with a single argument with
// value "false". Otherwise, creates a dev tools confirm infobar and delegate
// and adds the inofbar to |infobar_service|.
static void Create(InfoBarService* infobar_service,
const DevToolsWindow::InfoBarCallback& callback,
const base::string16& message);
private:
DevToolsConfirmInfoBarDelegate(
const DevToolsWindow::InfoBarCallback& callback,
const base::string16& message);
virtual ~DevToolsConfirmInfoBarDelegate();
virtual base::string16 GetMessageText() const OVERRIDE;
virtual base::string16 GetButtonLabel(InfoBarButton button) const OVERRIDE;
virtual bool Accept() OVERRIDE;
virtual bool Cancel() OVERRIDE;
DevToolsWindow::InfoBarCallback callback_;
const base::string16 message_;
DISALLOW_COPY_AND_ASSIGN(DevToolsConfirmInfoBarDelegate);
};
void DevToolsConfirmInfoBarDelegate::Create(
InfoBarService* infobar_service,
const DevToolsWindow::InfoBarCallback& callback,
const base::string16& message) {
if (!infobar_service) {
callback.Run(false);
return;
}
infobar_service->AddInfoBar(ConfirmInfoBarDelegate::CreateInfoBar(
scoped_ptr<ConfirmInfoBarDelegate>(
new DevToolsConfirmInfoBarDelegate(callback, message))));
}
DevToolsConfirmInfoBarDelegate::DevToolsConfirmInfoBarDelegate(
const DevToolsWindow::InfoBarCallback& callback,
const base::string16& message)
: ConfirmInfoBarDelegate(),
callback_(callback),
message_(message) {
}
DevToolsConfirmInfoBarDelegate::~DevToolsConfirmInfoBarDelegate() {
if (!callback_.is_null())
callback_.Run(false);
}
base::string16 DevToolsConfirmInfoBarDelegate::GetMessageText() const {
return message_;
}
base::string16 DevToolsConfirmInfoBarDelegate::GetButtonLabel(
InfoBarButton button) const {
return l10n_util::GetStringUTF16((button == BUTTON_OK) ?
IDS_DEV_TOOLS_CONFIRM_ALLOW_BUTTON : IDS_DEV_TOOLS_CONFIRM_DENY_BUTTON);
}
bool DevToolsConfirmInfoBarDelegate::Accept() {
callback_.Run(true);
callback_.Reset();
return true;
}
bool DevToolsConfirmInfoBarDelegate::Cancel() {
callback_.Run(false);
callback_.Reset();
return true;
}
// DevToolsWindow::InspectedWebContentsObserver -------------------------------
class DevToolsWindow::InspectedWebContentsObserver
: public content::WebContentsObserver {
public:
explicit InspectedWebContentsObserver(content::WebContents* web_contents);
virtual ~InspectedWebContentsObserver();
content::WebContents* web_contents() {
return WebContentsObserver::web_contents();
}
private:
DISALLOW_COPY_AND_ASSIGN(InspectedWebContentsObserver);
};
DevToolsWindow::InspectedWebContentsObserver::InspectedWebContentsObserver(
content::WebContents* web_contents)
: WebContentsObserver(web_contents) {
}
DevToolsWindow::InspectedWebContentsObserver::~InspectedWebContentsObserver() {
}
// DevToolsWindow::FrontendWebContentsObserver --------------------------------
class DevToolsWindow::FrontendWebContentsObserver
: public content::WebContentsObserver {
public:
explicit FrontendWebContentsObserver(DevToolsWindow* window);
virtual ~FrontendWebContentsObserver();
private:
// contents::WebContentsObserver:
virtual void AboutToNavigateRenderView(
content::RenderViewHost* render_view_host) OVERRIDE;
virtual void DocumentOnLoadCompletedInMainFrame(int32 page_id) OVERRIDE;
virtual void WebContentsDestroyed(content::WebContents*) OVERRIDE;
DevToolsWindow* devtools_window_;
DISALLOW_COPY_AND_ASSIGN(FrontendWebContentsObserver);
};
DevToolsWindow::FrontendWebContentsObserver::FrontendWebContentsObserver(
DevToolsWindow* devtools_window)
: WebContentsObserver(devtools_window->web_contents()),
devtools_window_(devtools_window) {
}
void DevToolsWindow::FrontendWebContentsObserver::WebContentsDestroyed(
content::WebContents* contents) {
delete devtools_window_;
}
DevToolsWindow::FrontendWebContentsObserver::~FrontendWebContentsObserver() {
}
void DevToolsWindow::FrontendWebContentsObserver::AboutToNavigateRenderView(
content::RenderViewHost* render_view_host) {
content::DevToolsClientHost::SetupDevToolsFrontendClient(render_view_host);
}
void DevToolsWindow::FrontendWebContentsObserver::
DocumentOnLoadCompletedInMainFrame(int32 page_id) {
devtools_window_->DocumentOnLoadCompletedInMainFrame();
}
// DevToolsWindow -------------------------------------------------------------
namespace {
typedef std::vector<DevToolsWindow*> DevToolsWindows;
base::LazyInstance<DevToolsWindows>::Leaky g_instances =
LAZY_INSTANCE_INITIALIZER;
static const char kFrontendHostId[] = "id";
static const char kFrontendHostMethod[] = "method";
static const char kFrontendHostParams[] = "params";
std::string SkColorToRGBAString(SkColor color) {
// We avoid StringPrintf because it will use locale specific formatters for
// the double (e.g. ',' instead of '.' in German).
return "rgba(" + base::IntToString(SkColorGetR(color)) + "," +
base::IntToString(SkColorGetG(color)) + "," +
base::IntToString(SkColorGetB(color)) + "," +
base::DoubleToString(SkColorGetA(color) / 255.0) + ")";
}
base::DictionaryValue* CreateFileSystemValue(
DevToolsFileHelper::FileSystem file_system) {
base::DictionaryValue* file_system_value = new base::DictionaryValue();
file_system_value->SetString("fileSystemName", file_system.file_system_name);
file_system_value->SetString("rootURL", file_system.root_url);
file_system_value->SetString("fileSystemPath", file_system.file_system_path);
return file_system_value;
}
} // namespace
const char DevToolsWindow::kDevToolsApp[] = "DevToolsApp";
DevToolsWindow::~DevToolsWindow() {
content::DevToolsManager::GetInstance()->ClientHostClosing(
frontend_host_.get());
UpdateBrowserToolbar();
DevToolsWindows* instances = g_instances.Pointer();
DevToolsWindows::iterator it(
std::find(instances->begin(), instances->end(), this));
DCHECK(it != instances->end());
instances->erase(it);
for (IndexingJobsMap::const_iterator jobs_it(indexing_jobs_.begin());
jobs_it != indexing_jobs_.end(); ++jobs_it) {
jobs_it->second->Stop();
}
indexing_jobs_.clear();
}
// static
std::string DevToolsWindow::GetDevToolsWindowPlacementPrefKey() {
return std::string(prefs::kBrowserWindowPlacement) + "_" +
std::string(kDevToolsApp);
}
// static
void DevToolsWindow::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
registry->RegisterDictionaryPref(
prefs::kDevToolsEditedFiles,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
registry->RegisterDictionaryPref(
prefs::kDevToolsFileSystemPaths,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
registry->RegisterStringPref(
prefs::kDevToolsAdbKey, std::string(),
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
registry->RegisterDictionaryPref(
GetDevToolsWindowPlacementPrefKey().c_str(),
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
registry->RegisterBooleanPref(
prefs::kDevToolsDiscoverUsbDevicesEnabled,
false,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
registry->RegisterBooleanPref(
prefs::kDevToolsPortForwardingEnabled,
false,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
registry->RegisterBooleanPref(
prefs::kDevToolsPortForwardingDefaultSet,
false,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
registry->RegisterDictionaryPref(
prefs::kDevToolsPortForwardingConfig,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
}
// static
DevToolsWindow* DevToolsWindow::GetDockedInstanceForInspectedTab(
content::WebContents* inspected_web_contents) {
DevToolsWindow* window = GetInstanceForInspectedRenderViewHost(
inspected_web_contents->GetRenderViewHost());
if (!window)
return NULL;
// Not yet loaded window is treated as docked, but we should not present it
// until we decided on docking.
bool is_docked_set = window->load_state_ == kLoadCompleted ||
window->load_state_ == kIsDockedSet;
return window->is_docked_ && is_docked_set ? window : NULL;
}
// static
DevToolsWindow* DevToolsWindow::GetInstanceForInspectedRenderViewHost(
content::RenderViewHost* inspected_rvh) {
if (!inspected_rvh || !DevToolsAgentHost::HasFor(inspected_rvh))
return NULL;
scoped_refptr<DevToolsAgentHost> agent(DevToolsAgentHost::GetOrCreateFor(
inspected_rvh));
return FindDevToolsWindow(agent.get());
}
// static
bool DevToolsWindow::IsDevToolsWindow(content::RenderViewHost* window_rvh) {
return AsDevToolsWindow(window_rvh) != NULL;
}
// static
DevToolsWindow* DevToolsWindow::OpenDevToolsWindowForWorker(
Profile* profile,
DevToolsAgentHost* worker_agent) {
DevToolsWindow* window = FindDevToolsWindow(worker_agent);
if (!window) {
window = DevToolsWindow::CreateDevToolsWindowForWorker(profile);
// Will disconnect the current client host if there is one.
content::DevToolsManager::GetInstance()->RegisterDevToolsClientHostFor(
worker_agent, window->frontend_host_.get());
}
window->ScheduleShow(DevToolsToggleAction::Show());
return window;
}
// static
DevToolsWindow* DevToolsWindow::CreateDevToolsWindowForWorker(
Profile* profile) {
content::RecordAction(base::UserMetricsAction("DevTools_InspectWorker"));
return Create(profile, GURL(), NULL, true, false, false);
}
// static
DevToolsWindow* DevToolsWindow::OpenDevToolsWindow(
content::RenderViewHost* inspected_rvh) {
return ToggleDevToolsWindow(
inspected_rvh, true, DevToolsToggleAction::Show());
}
// static
DevToolsWindow* DevToolsWindow::OpenDevToolsWindow(
content::RenderViewHost* inspected_rvh,
const DevToolsToggleAction& action) {
return ToggleDevToolsWindow(
inspected_rvh, true, action);
}
// static
DevToolsWindow* DevToolsWindow::OpenDevToolsWindowForTest(
content::RenderViewHost* inspected_rvh,
bool is_docked) {
DevToolsWindow* window = OpenDevToolsWindow(inspected_rvh);
window->SetIsDockedAndShowImmediatelyForTest(is_docked);
return window;
}
// static
DevToolsWindow* DevToolsWindow::OpenDevToolsWindowForTest(
Browser* browser,
bool is_docked) {
return OpenDevToolsWindowForTest(
browser->tab_strip_model()->GetActiveWebContents()->GetRenderViewHost(),
is_docked);
}
// static
DevToolsWindow* DevToolsWindow::ToggleDevToolsWindow(
Browser* browser,
const DevToolsToggleAction& action) {
if (action.type() == DevToolsToggleAction::kToggle &&
browser->is_devtools()) {
browser->tab_strip_model()->CloseAllTabs();
return NULL;
}
return ToggleDevToolsWindow(
browser->tab_strip_model()->GetActiveWebContents()->GetRenderViewHost(),
action.type() == DevToolsToggleAction::kInspect, action);
}
// static
void DevToolsWindow::OpenExternalFrontend(
Profile* profile,
const std::string& frontend_url,
content::DevToolsAgentHost* agent_host) {
DevToolsWindow* window = FindDevToolsWindow(agent_host);
if (!window) {
window = Create(profile, DevToolsUI::GetProxyURL(frontend_url), NULL,
false, true, false);
content::DevToolsManager::GetInstance()->RegisterDevToolsClientHostFor(
agent_host, window->frontend_host_.get());
}
window->ScheduleShow(DevToolsToggleAction::Show());
}
// static
DevToolsWindow* DevToolsWindow::ToggleDevToolsWindow(
content::RenderViewHost* inspected_rvh,
bool force_open,
const DevToolsToggleAction& action) {
scoped_refptr<DevToolsAgentHost> agent(
DevToolsAgentHost::GetOrCreateFor(inspected_rvh));
content::DevToolsManager* manager = content::DevToolsManager::GetInstance();
DevToolsWindow* window = FindDevToolsWindow(agent.get());
bool do_open = force_open;
if (!window) {
Profile* profile = Profile::FromBrowserContext(
inspected_rvh->GetProcess()->GetBrowserContext());
content::RecordAction(
base::UserMetricsAction("DevTools_InspectRenderer"));
window = Create(profile, GURL(), inspected_rvh, false, false, true);
manager->RegisterDevToolsClientHostFor(agent.get(),
window->frontend_host_.get());
do_open = true;
}
// Update toolbar to reflect DevTools changes.
window->UpdateBrowserToolbar();
// If window is docked and visible, we hide it on toggle. If window is
// undocked, we show (activate) it.
if (!window->is_docked_ || do_open)
window->ScheduleShow(action);
else
window->CloseWindow();
return window;
}
// static
void DevToolsWindow::InspectElement(content::RenderViewHost* inspected_rvh,
int x,
int y) {
scoped_refptr<DevToolsAgentHost> agent(
DevToolsAgentHost::GetOrCreateFor(inspected_rvh));
agent->InspectElement(x, y);
bool should_measure_time = FindDevToolsWindow(agent.get()) == NULL;
base::TimeTicks start_time = base::TimeTicks::Now();
// TODO(loislo): we should initiate DevTools window opening from within
// renderer. Otherwise, we still can hit a race condition here.
DevToolsWindow* window = OpenDevToolsWindow(inspected_rvh);
if (should_measure_time)
window->inspect_element_start_time_ = start_time;
}
void DevToolsWindow::InspectedContentsClosing() {
intercepted_page_beforeunload_ = false;
// This will prevent any activity after frontend is loaded.
action_on_load_ = DevToolsToggleAction::NoOp();
ignore_set_is_docked_ = true;
web_contents_->GetRenderViewHost()->ClosePage();
}
content::RenderViewHost* DevToolsWindow::GetRenderViewHost() {
return web_contents_->GetRenderViewHost();
}
const DevToolsContentsResizingStrategy&
DevToolsWindow::GetContentsResizingStrategy() const {
return contents_resizing_strategy_;
}
gfx::Size DevToolsWindow::GetMinimumSize() const {
const gfx::Size kMinDevToolsSize = gfx::Size(230, 100);
return kMinDevToolsSize;
}
void DevToolsWindow::ScheduleShow(const DevToolsToggleAction& action) {
if (load_state_ == kLoadCompleted) {
Show(action);
return;
}
// Action will be done only after load completed.
action_on_load_ = action;
if (!can_dock_) {
// No harm to show always-undocked window right away.
is_docked_ = false;
Show(DevToolsToggleAction::Show());
}
}
void DevToolsWindow::Show(const DevToolsToggleAction& action) {
if (action.type() == DevToolsToggleAction::kNoOp)
return;
if (is_docked_) {
DCHECK(can_dock_);
Browser* inspected_browser = NULL;
int inspected_tab_index = -1;
FindInspectedBrowserAndTabIndex(GetInspectedWebContents(),
&inspected_browser,
&inspected_tab_index);
DCHECK(inspected_browser);
DCHECK(inspected_tab_index != -1);
// Tell inspected browser to update splitter and switch to inspected panel.
BrowserWindow* inspected_window = inspected_browser->window();
web_contents_->SetDelegate(this);
TabStripModel* tab_strip_model = inspected_browser->tab_strip_model();
tab_strip_model->ActivateTabAt(inspected_tab_index, true);
inspected_window->UpdateDevTools();
web_contents_->GetView()->SetInitialFocus();
inspected_window->Show();
// On Aura, focusing once is not enough. Do it again.
// Note that focusing only here but not before isn't enough either. We just
// need to focus twice.
web_contents_->GetView()->SetInitialFocus();
PrefsTabHelper::CreateForWebContents(web_contents_);
GetRenderViewHost()->SyncRendererPrefs();
DoAction(action);
return;
}
// Avoid consecutive window switching if the devtools window has been opened
// and the Inspect Element shortcut is pressed in the inspected tab.
bool should_show_window =
!browser_ || (action.type() != DevToolsToggleAction::kInspect);
if (!browser_)
CreateDevToolsBrowser();
if (should_show_window) {
browser_->window()->Show();
web_contents_->GetView()->SetInitialFocus();
}
DoAction(action);
}
// static
bool DevToolsWindow::HandleBeforeUnload(content::WebContents* frontend_contents,
bool proceed, bool* proceed_to_fire_unload) {
DevToolsWindow* window = AsDevToolsWindow(
frontend_contents->GetRenderViewHost());
if (!window)
return false;
if (!window->intercepted_page_beforeunload_)
return false;
window->BeforeUnloadFired(frontend_contents, proceed,
proceed_to_fire_unload);
return true;
}
// static
bool DevToolsWindow::InterceptPageBeforeUnload(content::WebContents* contents) {
DevToolsWindow* window =
DevToolsWindow::GetInstanceForInspectedRenderViewHost(
contents->GetRenderViewHost());
if (!window || window->intercepted_page_beforeunload_)
return false;
// Not yet loaded frontend will not handle beforeunload.
if (window->load_state_ != kLoadCompleted)
return false;
window->intercepted_page_beforeunload_ = true;
// Handle case of devtools inspecting another devtools instance by passing
// the call up to the inspecting devtools instance.
if (!DevToolsWindow::InterceptPageBeforeUnload(window->web_contents())) {
window->web_contents()->GetRenderViewHost()->FirePageBeforeUnload(false);
}
return true;
}
// static
bool DevToolsWindow::NeedsToInterceptBeforeUnload(
content::WebContents* contents) {
DevToolsWindow* window =
DevToolsWindow::GetInstanceForInspectedRenderViewHost(
contents->GetRenderViewHost());
return window && !window->intercepted_page_beforeunload_;
}
// static
bool DevToolsWindow::HasFiredBeforeUnloadEventForDevToolsBrowser(
Browser* browser) {
DCHECK(browser->is_devtools());
// When FastUnloadController is used, devtools frontend will be detached
// from the browser window at this point which means we've already fired
// beforeunload.
if (browser->tab_strip_model()->empty())
return true;
content::WebContents* contents =
browser->tab_strip_model()->GetWebContentsAt(0);
DevToolsWindow* window = AsDevToolsWindow(contents->GetRenderViewHost());
if (!window)
return false;
return window->intercepted_page_beforeunload_;
}
// static
void DevToolsWindow::OnPageCloseCanceled(content::WebContents* contents) {
DevToolsWindow *window =
DevToolsWindow::GetInstanceForInspectedRenderViewHost(
contents->GetRenderViewHost());
if (!window)
return;
window->intercepted_page_beforeunload_ = false;
// Propagate to devtools opened on devtools if any.
DevToolsWindow::OnPageCloseCanceled(window->web_contents());
}
DevToolsWindow::DevToolsWindow(Profile* profile,
const GURL& url,
content::RenderViewHost* inspected_rvh,
bool can_dock)
: profile_(profile),
browser_(NULL),
is_docked_(true),
can_dock_(can_dock),
// This initialization allows external front-end to work without changes.
// We don't wait for docking call, but instead immediately show undocked.
// Passing "dockSide=undocked" parameter ensures proper UI.
load_state_(can_dock ? kNotLoaded : kIsDockedSet),
action_on_load_(DevToolsToggleAction::NoOp()),
ignore_set_is_docked_(false),
intercepted_page_beforeunload_(false),
weak_factory_(this) {
web_contents_ =
content::WebContents::Create(content::WebContents::CreateParams(profile));
frontend_contents_observer_.reset(new FrontendWebContentsObserver(this));
web_contents_->GetMutableRendererPrefs()->can_accept_load_drops = false;
// Set up delegate, so we get fully-functional window immediately.
// It will not appear in UI though until |load_state_ == kLoadCompleted|.
web_contents_->SetDelegate(this);
web_contents_->GetController().LoadURL(url, content::Referrer(),
content::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string());
frontend_host_.reset(content::DevToolsClientHost::CreateDevToolsFrontendHost(
web_contents_, this));
file_helper_.reset(new DevToolsFileHelper(web_contents_, profile));
file_system_indexer_ = new DevToolsFileSystemIndexer();
extensions::ExtensionWebContentsObserver::CreateForWebContents(web_contents_);
g_instances.Get().push_back(this);
// Wipe out page icon so that the default application icon is used.
content::NavigationEntry* entry =
web_contents_->GetController().GetActiveEntry();
entry->GetFavicon().image = gfx::Image();
entry->GetFavicon().valid = true;
// Register on-load actions.
registrar_.Add(
this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
content::Source<ThemeService>(
ThemeServiceFactory::GetForProfile(profile_)));
// There is no inspected_rvh in case of shared workers.
if (inspected_rvh)
inspected_contents_observer_.reset(new InspectedWebContentsObserver(
content::WebContents::FromRenderViewHost(inspected_rvh)));
embedder_message_dispatcher_.reset(
new DevToolsEmbedderMessageDispatcher(this));
}
// static
DevToolsWindow* DevToolsWindow::Create(
Profile* profile,
const GURL& frontend_url,
content::RenderViewHost* inspected_rvh,
bool shared_worker_frontend,
bool external_frontend,
bool can_dock) {
if (inspected_rvh) {
// Check for a place to dock.
Browser* browser = NULL;
int tab;
content::WebContents* inspected_web_contents =
content::WebContents::FromRenderViewHost(inspected_rvh);
if (!FindInspectedBrowserAndTabIndex(inspected_web_contents,
&browser, &tab) ||
browser->is_type_popup()) {
can_dock = false;
}
}
// Create WebContents with devtools.
GURL url(GetDevToolsURL(profile, frontend_url,
shared_worker_frontend,
external_frontend,
can_dock));
return new DevToolsWindow(profile, url, inspected_rvh, can_dock);
}
// static
GURL DevToolsWindow::GetDevToolsURL(Profile* profile,
const GURL& base_url,
bool shared_worker_frontend,
bool external_frontend,
bool can_dock) {
if (base_url.SchemeIs("data"))
return base_url;
std::string frontend_url(
base_url.is_empty() ? chrome::kChromeUIDevToolsURL : base_url.spec());
ThemeService* tp = ThemeServiceFactory::GetForProfile(profile);
DCHECK(tp);
std::string url_string(
frontend_url +
((frontend_url.find("?") == std::string::npos) ? "?" : "&") +
"dockSide=undocked" + // TODO(dgozman): remove this support in M38.
"&toolbarColor=" +
SkColorToRGBAString(tp->GetColor(ThemeProperties::COLOR_TOOLBAR)) +
"&textColor=" +
SkColorToRGBAString(tp->GetColor(ThemeProperties::COLOR_BOOKMARK_TEXT)));
if (shared_worker_frontend)
url_string += "&isSharedWorker=true";
if (external_frontend)
url_string += "&remoteFrontend=true";
if (can_dock)
url_string += "&can_dock=true";
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableDevToolsExperiments))
url_string += "&experiments=true";
url_string += "&updateAppcache";
return GURL(url_string);
}
// static
DevToolsWindow* DevToolsWindow::FindDevToolsWindow(
DevToolsAgentHost* agent_host) {
DevToolsWindows* instances = g_instances.Pointer();
content::DevToolsManager* manager = content::DevToolsManager::GetInstance();
for (DevToolsWindows::iterator it(instances->begin()); it != instances->end();
++it) {
if (manager->GetDevToolsAgentHostFor((*it)->frontend_host_.get()) ==
agent_host)
return *it;
}
return NULL;
}
// static
DevToolsWindow* DevToolsWindow::AsDevToolsWindow(
content::RenderViewHost* window_rvh) {
if (g_instances == NULL)
return NULL;
DevToolsWindows* instances = g_instances.Pointer();
for (DevToolsWindows::iterator it(instances->begin()); it != instances->end();
++it) {
if ((*it)->web_contents_->GetRenderViewHost() == window_rvh)
return *it;
}
return NULL;
}
void DevToolsWindow::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK_EQ(chrome::NOTIFICATION_BROWSER_THEME_CHANGED, type);
UpdateTheme();
}
content::WebContents* DevToolsWindow::OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) {
DCHECK(source == web_contents_);
if (!params.url.SchemeIs(content::kChromeDevToolsScheme)) {
content::WebContents* inspected_web_contents = GetInspectedWebContents();
return inspected_web_contents ?
inspected_web_contents->OpenURL(params) : NULL;
}
content::DevToolsManager* manager = content::DevToolsManager::GetInstance();
scoped_refptr<DevToolsAgentHost> agent_host(
manager->GetDevToolsAgentHostFor(frontend_host_.get()));
if (!agent_host.get())
return NULL;
manager->ClientHostClosing(frontend_host_.get());
manager->RegisterDevToolsClientHostFor(agent_host.get(),
frontend_host_.get());
content::NavigationController::LoadURLParams load_url_params(params.url);
web_contents_->GetController().LoadURLWithParams(load_url_params);
return web_contents_;
}
void DevToolsWindow::AddNewContents(content::WebContents* source,
content::WebContents* new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_pos,
bool user_gesture,
bool* was_blocked) {
content::WebContents* inspected_web_contents = GetInspectedWebContents();
if (inspected_web_contents) {
inspected_web_contents->GetDelegate()->AddNewContents(
source, new_contents, disposition, initial_pos, user_gesture,
was_blocked);
}
}
void DevToolsWindow::CloseContents(content::WebContents* source) {
CHECK(is_docked_);
// This will prevent any activity after frontend is loaded.
action_on_load_ = DevToolsToggleAction::NoOp();
ignore_set_is_docked_ = true;
// Update dev tools to reflect removed dev tools window.
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
inspected_window->UpdateDevTools();
// In case of docked web_contents_, we own it so delete here.
// Embedding DevTools window will be deleted as a result of
// WebContentsDestroyed callback.
delete web_contents_;
}
void DevToolsWindow::ContentsZoomChange(bool zoom_in) {
DCHECK(is_docked_);
chrome_page_zoom::Zoom(web_contents(),
zoom_in ? content::PAGE_ZOOM_IN : content::PAGE_ZOOM_OUT);
}
void DevToolsWindow::BeforeUnloadFired(content::WebContents* tab,
bool proceed,
bool* proceed_to_fire_unload) {
if (!intercepted_page_beforeunload_) {
// Docked devtools window closed directly.
if (proceed) {
content::DevToolsManager::GetInstance()->ClientHostClosing(
frontend_host_.get());
}
*proceed_to_fire_unload = proceed;
} else {
// Inspected page is attempting to close.
content::WebContents* inspected_web_contents = GetInspectedWebContents();
if (proceed) {
inspected_web_contents->GetRenderViewHost()->FirePageBeforeUnload(false);
} else {
bool should_proceed;
inspected_web_contents->GetDelegate()->BeforeUnloadFired(
inspected_web_contents, false, &should_proceed);
DCHECK(!should_proceed);
}
*proceed_to_fire_unload = false;
}
}
bool DevToolsWindow::PreHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event,
bool* is_keyboard_shortcut) {
if (is_docked_) {
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window) {
return inspected_window->PreHandleKeyboardEvent(event,
is_keyboard_shortcut);
}
}
return false;
}
void DevToolsWindow::HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (is_docked_) {
if (event.windowsKeyCode == 0x08) {
// Do not navigate back in history on Windows (http://crbug.com/74156).
return;
}
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
inspected_window->HandleKeyboardEvent(event);
}
}
content::JavaScriptDialogManager* DevToolsWindow::GetJavaScriptDialogManager() {
content::WebContents* inspected_web_contents = GetInspectedWebContents();
return (inspected_web_contents && inspected_web_contents->GetDelegate()) ?
inspected_web_contents->GetDelegate()->GetJavaScriptDialogManager() :
content::WebContentsDelegate::GetJavaScriptDialogManager();
}
content::ColorChooser* DevToolsWindow::OpenColorChooser(
content::WebContents* web_contents,
SkColor initial_color,
const std::vector<content::ColorSuggestion>& suggestions) {
return chrome::ShowColorChooser(web_contents, initial_color);
}
void DevToolsWindow::RunFileChooser(content::WebContents* web_contents,
const content::FileChooserParams& params) {
FileSelectHelper::RunFileChooser(web_contents, params);
}
void DevToolsWindow::WebContentsFocused(content::WebContents* contents) {
Browser* inspected_browser = NULL;
int inspected_tab_index = -1;
if (is_docked_ && FindInspectedBrowserAndTabIndex(GetInspectedWebContents(),
&inspected_browser,
&inspected_tab_index))
inspected_browser->window()->WebContentsFocused(contents);
}
bool DevToolsWindow::PreHandleGestureEvent(
content::WebContents* source,
const blink::WebGestureEvent& event) {
// Disable pinch zooming.
return event.type == blink::WebGestureEvent::GesturePinchBegin ||
event.type == blink::WebGestureEvent::GesturePinchUpdate ||
event.type == blink::WebGestureEvent::GesturePinchEnd;
}
void DevToolsWindow::DispatchOnEmbedder(const std::string& message) {
std::string method;
base::ListValue empty_params;
base::ListValue* params = &empty_params;
base::DictionaryValue* dict = NULL;
scoped_ptr<base::Value> parsed_message(base::JSONReader::Read(message));
if (!parsed_message ||
!parsed_message->GetAsDictionary(&dict) ||
!dict->GetString(kFrontendHostMethod, &method) ||
(dict->HasKey(kFrontendHostParams) &&
!dict->GetList(kFrontendHostParams, ¶ms))) {
LOG(ERROR) << "Invalid message was sent to embedder: " << message;
return;
}
int id = 0;
dict->GetInteger(kFrontendHostId, &id);
std::string error = embedder_message_dispatcher_->Dispatch(method, params);
if (id) {
scoped_ptr<base::Value> id_value(base::Value::CreateIntegerValue(id));
scoped_ptr<base::Value> error_value(base::Value::CreateStringValue(error));
CallClientFunction("InspectorFrontendAPI.embedderMessageAck",
id_value.get(), error_value.get(), NULL);
}
}
void DevToolsWindow::ActivateWindow() {
if (is_docked_ && GetInspectedBrowserWindow())
web_contents_->GetView()->Focus();
else if (!is_docked_ && !browser_->window()->IsActive())
browser_->window()->Activate();
}
void DevToolsWindow::ActivateContents(content::WebContents* contents) {
if (is_docked_) {
content::WebContents* inspected_tab = this->GetInspectedWebContents();
inspected_tab->GetDelegate()->ActivateContents(inspected_tab);
} else {
browser_->window()->Activate();
}
}
void DevToolsWindow::CloseWindow() {
DCHECK(is_docked_);
// This will prevent any activity after frontend is loaded.
action_on_load_ = DevToolsToggleAction::NoOp();
ignore_set_is_docked_ = true;
web_contents_->GetRenderViewHost()->FirePageBeforeUnload(false);
}
void DevToolsWindow::SetContentsInsets(
int top, int left, int bottom, int right) {
gfx::Insets insets(top, left, bottom, right);
SetContentsResizingStrategy(insets, contents_resizing_strategy_.min_size());
}
void DevToolsWindow::SetContentsResizingStrategy(
const gfx::Insets& insets, const gfx::Size& min_size) {
DevToolsContentsResizingStrategy strategy(insets, min_size);
if (contents_resizing_strategy_.Equals(strategy))
return;
contents_resizing_strategy_.CopyFrom(strategy);
if (is_docked_) {
// Update inspected window.
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
inspected_window->UpdateDevTools();
}
}
void DevToolsWindow::InspectElementCompleted() {
if (!inspect_element_start_time_.is_null()) {
UMA_HISTOGRAM_TIMES("DevTools.InspectElement",
base::TimeTicks::Now() - inspect_element_start_time_);
inspect_element_start_time_ = base::TimeTicks();
}
}
void DevToolsWindow::MoveWindow(int x, int y) {
if (!is_docked_) {
gfx::Rect bounds = browser_->window()->GetBounds();
bounds.Offset(x, y);
browser_->window()->SetBounds(bounds);
}
}
void DevToolsWindow::SetIsDockedAndShowImmediatelyForTest(bool is_docked) {
DCHECK(!is_docked || can_dock_);
if (load_state_ == kLoadCompleted) {
SetIsDocked(is_docked);
} else {
is_docked_ = is_docked;
// Load is completed when both kIsDockedSet and kOnLoadFired happened.
// Note that kIsDockedSet may be already set when can_dock_ is false.
load_state_ = load_state_ == kOnLoadFired ? kLoadCompleted : kIsDockedSet;
// Note that action_on_load_ will be performed after the load is actually
// completed. For now, just show the window.
Show(DevToolsToggleAction::Show());
if (load_state_ == kLoadCompleted)
LoadCompleted();
}
ignore_set_is_docked_ = true;
}
void DevToolsWindow::SetIsDocked(bool dock_requested) {
if (ignore_set_is_docked_)
return;
DCHECK(can_dock_ || !dock_requested);
if (!can_dock_)
dock_requested = false;
bool was_docked = is_docked_;
is_docked_ = dock_requested;
if (load_state_ != kLoadCompleted) {
// This is a first time call we waited for to initialize.
load_state_ = load_state_ == kOnLoadFired ? kLoadCompleted : kIsDockedSet;
if (load_state_ == kLoadCompleted)
LoadCompleted();
return;
}
if (dock_requested == was_docked)
return;
if (dock_requested && !was_docked) {
// Detach window from the external devtools browser. It will lead to
// the browser object's close and delete. Remove observer first.
TabStripModel* tab_strip_model = browser_->tab_strip_model();
tab_strip_model->DetachWebContentsAt(
tab_strip_model->GetIndexOfWebContents(web_contents_));
browser_ = NULL;
} else if (!dock_requested && was_docked) {
// Update inspected window to hide split and reset it.
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
inspected_window->UpdateDevTools();
}
Show(DevToolsToggleAction::Show());
}
void DevToolsWindow::OpenInNewTab(const std::string& url) {
content::OpenURLParams params(
GURL(url), content::Referrer(), NEW_FOREGROUND_TAB,
content::PAGE_TRANSITION_LINK, false);
content::WebContents* inspected_web_contents = GetInspectedWebContents();
if (inspected_web_contents) {
inspected_web_contents->OpenURL(params);
} else {
chrome::HostDesktopType host_desktop_type;
if (browser_) {
host_desktop_type = browser_->host_desktop_type();
} else {
// There should always be a browser when there are no inspected web
// contents.
NOTREACHED();
host_desktop_type = chrome::GetActiveDesktop();
}
const BrowserList* browser_list =
BrowserList::GetInstance(host_desktop_type);
for (BrowserList::const_iterator it = browser_list->begin();
it != browser_list->end(); ++it) {
if ((*it)->type() == Browser::TYPE_TABBED) {
(*it)->OpenURL(params);
break;
}
}
}
}
void DevToolsWindow::SaveToFile(const std::string& url,
const std::string& content,
bool save_as) {
file_helper_->Save(url, content, save_as,
base::Bind(&DevToolsWindow::FileSavedAs,
weak_factory_.GetWeakPtr(), url),
base::Bind(&DevToolsWindow::CanceledFileSaveAs,
weak_factory_.GetWeakPtr(), url));
}
void DevToolsWindow::AppendToFile(const std::string& url,
const std::string& content) {
file_helper_->Append(url, content,
base::Bind(&DevToolsWindow::AppendedTo,
weak_factory_.GetWeakPtr(), url));
}
void DevToolsWindow::RequestFileSystems() {
CHECK(web_contents_->GetURL().SchemeIs(content::kChromeDevToolsScheme));
file_helper_->RequestFileSystems(base::Bind(
&DevToolsWindow::FileSystemsLoaded, weak_factory_.GetWeakPtr()));
}
void DevToolsWindow::AddFileSystem() {
CHECK(web_contents_->GetURL().SchemeIs(content::kChromeDevToolsScheme));
file_helper_->AddFileSystem(
base::Bind(&DevToolsWindow::FileSystemAdded, weak_factory_.GetWeakPtr()),
base::Bind(&DevToolsWindow::ShowDevToolsConfirmInfoBar,
weak_factory_.GetWeakPtr()));
}
void DevToolsWindow::RemoveFileSystem(const std::string& file_system_path) {
CHECK(web_contents_->GetURL().SchemeIs(content::kChromeDevToolsScheme));
file_helper_->RemoveFileSystem(file_system_path);
base::StringValue file_system_path_value(file_system_path);
CallClientFunction("InspectorFrontendAPI.fileSystemRemoved",
&file_system_path_value, NULL, NULL);
}
void DevToolsWindow::UpgradeDraggedFileSystemPermissions(
const std::string& file_system_url) {
CHECK(web_contents_->GetURL().SchemeIs(content::kChromeDevToolsScheme));
file_helper_->UpgradeDraggedFileSystemPermissions(
file_system_url,
base::Bind(&DevToolsWindow::FileSystemAdded, weak_factory_.GetWeakPtr()),
base::Bind(&DevToolsWindow::ShowDevToolsConfirmInfoBar,
weak_factory_.GetWeakPtr()));
}
void DevToolsWindow::IndexPath(int request_id,
const std::string& file_system_path) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
CHECK(web_contents_->GetURL().SchemeIs(content::kChromeDevToolsScheme));
if (!file_helper_->IsFileSystemAdded(file_system_path)) {
IndexingDone(request_id, file_system_path);
return;
}
indexing_jobs_[request_id] =
scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>(
file_system_indexer_->IndexPath(
file_system_path,
Bind(&DevToolsWindow::IndexingTotalWorkCalculated,
weak_factory_.GetWeakPtr(),
request_id,
file_system_path),
Bind(&DevToolsWindow::IndexingWorked,
weak_factory_.GetWeakPtr(),
request_id,
file_system_path),
Bind(&DevToolsWindow::IndexingDone,
weak_factory_.GetWeakPtr(),
request_id,
file_system_path)));
}
void DevToolsWindow::StopIndexing(int request_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
IndexingJobsMap::iterator it = indexing_jobs_.find(request_id);
if (it == indexing_jobs_.end())
return;
it->second->Stop();
indexing_jobs_.erase(it);
}
void DevToolsWindow::SearchInPath(int request_id,
const std::string& file_system_path,
const std::string& query) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
CHECK(web_contents_->GetURL().SchemeIs(content::kChromeDevToolsScheme));
if (!file_helper_->IsFileSystemAdded(file_system_path)) {
SearchCompleted(request_id, file_system_path, std::vector<std::string>());
return;
}
file_system_indexer_->SearchInPath(file_system_path,
query,
Bind(&DevToolsWindow::SearchCompleted,
weak_factory_.GetWeakPtr(),
request_id,
file_system_path));
}
void DevToolsWindow::ZoomIn() {
chrome_page_zoom::Zoom(web_contents(), content::PAGE_ZOOM_IN);
}
void DevToolsWindow::ZoomOut() {
chrome_page_zoom::Zoom(web_contents(), content::PAGE_ZOOM_OUT);
}
void DevToolsWindow::ResetZoom() {
chrome_page_zoom::Zoom(web_contents(), content::PAGE_ZOOM_RESET);
}
void DevToolsWindow::FileSavedAs(const std::string& url) {
base::StringValue url_value(url);
CallClientFunction("InspectorFrontendAPI.savedURL", &url_value, NULL, NULL);
}
void DevToolsWindow::CanceledFileSaveAs(const std::string& url) {
base::StringValue url_value(url);
CallClientFunction("InspectorFrontendAPI.canceledSaveURL",
&url_value, NULL, NULL);
}
void DevToolsWindow::AppendedTo(const std::string& url) {
base::StringValue url_value(url);
CallClientFunction("InspectorFrontendAPI.appendedToURL", &url_value, NULL,
NULL);
}
void DevToolsWindow::FileSystemsLoaded(
const std::vector<DevToolsFileHelper::FileSystem>& file_systems) {
base::ListValue file_systems_value;
for (size_t i = 0; i < file_systems.size(); ++i)
file_systems_value.Append(CreateFileSystemValue(file_systems[i]));
CallClientFunction("InspectorFrontendAPI.fileSystemsLoaded",
&file_systems_value, NULL, NULL);
}
void DevToolsWindow::FileSystemAdded(
const DevToolsFileHelper::FileSystem& file_system) {
scoped_ptr<base::StringValue> error_string_value(
new base::StringValue(std::string()));
scoped_ptr<base::DictionaryValue> file_system_value;
if (!file_system.file_system_path.empty())
file_system_value.reset(CreateFileSystemValue(file_system));
CallClientFunction("InspectorFrontendAPI.fileSystemAdded",
error_string_value.get(), file_system_value.get(), NULL);
}
void DevToolsWindow::IndexingTotalWorkCalculated(
int request_id,
const std::string& file_system_path,
int total_work) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::FundamentalValue request_id_value(request_id);
base::StringValue file_system_path_value(file_system_path);
base::FundamentalValue total_work_value(total_work);
CallClientFunction("InspectorFrontendAPI.indexingTotalWorkCalculated",
&request_id_value, &file_system_path_value,
&total_work_value);
}
void DevToolsWindow::IndexingWorked(int request_id,
const std::string& file_system_path,
int worked) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::FundamentalValue request_id_value(request_id);
base::StringValue file_system_path_value(file_system_path);
base::FundamentalValue worked_value(worked);
CallClientFunction("InspectorFrontendAPI.indexingWorked", &request_id_value,
&file_system_path_value, &worked_value);
}
void DevToolsWindow::IndexingDone(int request_id,
const std::string& file_system_path) {
indexing_jobs_.erase(request_id);
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::FundamentalValue request_id_value(request_id);
base::StringValue file_system_path_value(file_system_path);
CallClientFunction("InspectorFrontendAPI.indexingDone", &request_id_value,
&file_system_path_value, NULL);
}
void DevToolsWindow::SearchCompleted(
int request_id,
const std::string& file_system_path,
const std::vector<std::string>& file_paths) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::ListValue file_paths_value;
for (std::vector<std::string>::const_iterator it(file_paths.begin());
it != file_paths.end(); ++it) {
file_paths_value.AppendString(*it);
}
base::FundamentalValue request_id_value(request_id);
base::StringValue file_system_path_value(file_system_path);
CallClientFunction("InspectorFrontendAPI.searchCompleted", &request_id_value,
&file_system_path_value, &file_paths_value);
}
void DevToolsWindow::ShowDevToolsConfirmInfoBar(
const base::string16& message,
const InfoBarCallback& callback) {
DevToolsConfirmInfoBarDelegate::Create(
is_docked_ ?
InfoBarService::FromWebContents(GetInspectedWebContents()) :
InfoBarService::FromWebContents(web_contents_),
callback, message);
}
void DevToolsWindow::CreateDevToolsBrowser() {
std::string wp_key = GetDevToolsWindowPlacementPrefKey();
PrefService* prefs = profile_->GetPrefs();
const base::DictionaryValue* wp_pref = prefs->GetDictionary(wp_key.c_str());
if (!wp_pref || wp_pref->empty()) {
DictionaryPrefUpdate update(prefs, wp_key.c_str());
base::DictionaryValue* defaults = update.Get();
defaults->SetInteger("left", 100);
defaults->SetInteger("top", 100);
defaults->SetInteger("right", 740);
defaults->SetInteger("bottom", 740);
defaults->SetBoolean("maximized", false);
defaults->SetBoolean("always_on_top", false);
}
browser_ = new Browser(Browser::CreateParams::CreateForDevTools(
profile_,
chrome::GetHostDesktopTypeForNativeView(
web_contents_->GetView()->GetNativeView())));
browser_->tab_strip_model()->AddWebContents(
web_contents_, -1, content::PAGE_TRANSITION_AUTO_TOPLEVEL,
TabStripModel::ADD_ACTIVE);
GetRenderViewHost()->SyncRendererPrefs();
}
// static
bool DevToolsWindow::FindInspectedBrowserAndTabIndex(
content::WebContents* inspected_web_contents, Browser** browser, int* tab) {
if (!inspected_web_contents)
return false;
for (chrome::BrowserIterator it; !it.done(); it.Next()) {
int tab_index = it->tab_strip_model()->GetIndexOfWebContents(
inspected_web_contents);
if (tab_index != TabStripModel::kNoTab) {
*browser = *it;
*tab = tab_index;
return true;
}
}
return false;
}
BrowserWindow* DevToolsWindow::GetInspectedBrowserWindow() {
Browser* browser = NULL;
int tab;
return FindInspectedBrowserAndTabIndex(GetInspectedWebContents(),
&browser, &tab) ?
browser->window() : NULL;
}
void DevToolsWindow::DoAction(const DevToolsToggleAction& action) {
switch (action.type()) {
case DevToolsToggleAction::kShowConsole:
CallClientFunction("InspectorFrontendAPI.showConsole", NULL, NULL, NULL);
break;
case DevToolsToggleAction::kInspect:
CallClientFunction("InspectorFrontendAPI.enterInspectElementMode", NULL,
NULL, NULL);
break;
case DevToolsToggleAction::kShow:
case DevToolsToggleAction::kToggle:
// Do nothing.
break;
case DevToolsToggleAction::kReveal: {
const DevToolsToggleAction::RevealParams* params =
action.params();
CHECK(params);
base::StringValue url_value(params->url);
base::FundamentalValue line_value(static_cast<int>(params->line_number));
base::FundamentalValue column_value(
static_cast<int>(params->column_number));
CallClientFunction("InspectorFrontendAPI.revealSourceLine",
&url_value,
&line_value,
&column_value);
break;
}
default:
NOTREACHED();
break;
}
}
void DevToolsWindow::UpdateTheme() {
ThemeService* tp = ThemeServiceFactory::GetForProfile(profile_);
DCHECK(tp);
std::string command("InspectorFrontendAPI.setToolbarColors(\"" +
SkColorToRGBAString(tp->GetColor(ThemeProperties::COLOR_TOOLBAR)) +
"\", \"" +
SkColorToRGBAString(tp->GetColor(ThemeProperties::COLOR_BOOKMARK_TEXT)) +
"\")");
web_contents_->GetRenderViewHost()->ExecuteJavascriptInWebFrame(
base::string16(), base::ASCIIToUTF16(command));
}
void DevToolsWindow::AddDevToolsExtensionsToClient() {
content::WebContents* inspected_web_contents = GetInspectedWebContents();
if (inspected_web_contents) {
SessionTabHelper* session_tab_helper =
SessionTabHelper::FromWebContents(inspected_web_contents);
if (session_tab_helper) {
base::FundamentalValue tabId(session_tab_helper->session_id().id());
CallClientFunction("WebInspector.setInspectedTabId", &tabId, NULL, NULL);
}
}
Profile* profile =
Profile::FromBrowserContext(web_contents_->GetBrowserContext());
const ExtensionService* extension_service = extensions::ExtensionSystem::Get(
profile->GetOriginalProfile())->extension_service();
if (!extension_service)
return;
const extensions::ExtensionSet* extensions = extension_service->extensions();
base::ListValue results;
for (extensions::ExtensionSet::const_iterator extension(extensions->begin());
extension != extensions->end(); ++extension) {
if (extensions::ManifestURL::GetDevToolsPage(extension->get()).is_empty())
continue;
base::DictionaryValue* extension_info = new base::DictionaryValue();
extension_info->Set(
"startPage",
new base::StringValue(
extensions::ManifestURL::GetDevToolsPage(extension->get()).spec()));
extension_info->Set("name", new base::StringValue((*extension)->name()));
extension_info->Set(
"exposeExperimentalAPIs",
new base::FundamentalValue((*extension)->HasAPIPermission(
extensions::APIPermission::kExperimental)));
results.Append(extension_info);
}
CallClientFunction("WebInspector.addExtensions", &results, NULL, NULL);
}
void DevToolsWindow::CallClientFunction(const std::string& function_name,
const base::Value* arg1,
const base::Value* arg2,
const base::Value* arg3) {
std::string params;
if (arg1) {
std::string json;
base::JSONWriter::Write(arg1, &json);
params.append(json);
if (arg2) {
base::JSONWriter::Write(arg2, &json);
params.append(", " + json);
if (arg3) {
base::JSONWriter::Write(arg3, &json);
params.append(", " + json);
}
}
}
base::string16 javascript =
base::ASCIIToUTF16(function_name + "(" + params + ");");
web_contents_->GetRenderViewHost()->ExecuteJavascriptInWebFrame(
base::string16(), javascript);
}
void DevToolsWindow::UpdateBrowserToolbar() {
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
inspected_window->UpdateToolbar(NULL);
}
content::WebContents* DevToolsWindow::GetInspectedWebContents() {
return inspected_contents_observer_ ?
inspected_contents_observer_->web_contents() : NULL;
}
void DevToolsWindow::DocumentOnLoadCompletedInMainFrame() {
// We could be in kLoadCompleted state already if frontend reloads itself.
if (load_state_ != kLoadCompleted) {
// Load is completed when both kIsDockedSet and kOnLoadFired happened.
// Here we set kOnLoadFired.
load_state_ = load_state_ == kIsDockedSet ? kLoadCompleted : kOnLoadFired;
}
if (load_state_ == kLoadCompleted)
LoadCompleted();
}
void DevToolsWindow::LoadCompleted() {
Show(action_on_load_);
action_on_load_ = DevToolsToggleAction::NoOp();
UpdateTheme();
AddDevToolsExtensionsToClient();
if (!load_completed_callback_.is_null()) {
load_completed_callback_.Run();
load_completed_callback_ = base::Closure();
}
}
void DevToolsWindow::SetLoadCompletedCallback(const base::Closure& closure) {
if (load_state_ == kLoadCompleted) {
if (!closure.is_null())
closure.Run();
return;
}
load_completed_callback_ = closure;
}
| ChromiumWebApps/chromium | chrome/browser/devtools/devtools_window.cc | C++ | bsd-3-clause | 56,093 |
/*================================================================================
Copyright (c) 2009 VMware, Inc. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
@author Steve Jin (sjin@vmware.com)
*/
public class LicenseServerUnavailableEvent extends LicenseEvent
{
public String licenseServer;
public String getLicenseServer()
{
return this.licenseServer;
}
public void setLicenseServer(String licenseServer)
{
this.licenseServer=licenseServer;
}
} | mikem2005/vijava | src/com/vmware/vim25/LicenseServerUnavailableEvent.java | Java | bsd-3-clause | 1,988 |
//
// KBPGPDecryptAppView.h
// Keybase
//
// Created by Gabriel on 4/27/15.
// Copyright (c) 2015 Gabriel Handford. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <Tikppa/Tikppa.h>
#import "KBRPC.h"
@interface KBPGPDecryptAppView : YOView
@property KBNavigationView *navigation;
@property (nonatomic) KBRPClient *client;
@end
| keybase/client | osx/KBKit/KBKit/UI/PGP/KBPGPDecryptAppView.h | C | bsd-3-clause | 354 |
// vim:filetype=java:ts=4
/*
Copyright (c) 2007
Conor McDermottroe. 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 author nor the names of any contributors to
the software 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
HOLDERS 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 junit.com.mcdermottroe.exemplar.input;
import com.mcdermottroe.exemplar.input.AbstractInputModule;
import junit.com.mcdermottroe.exemplar.AbstractClassTestCase;
/** Test class for {@link AbstractInputModule}.
@author Conor McDermottroe
@since 0.2
@param <T> The type of {@link AbstractInputModule} to test.
*/
public class AbstractInputModuleTest<T extends AbstractInputModule<T>>
extends AbstractClassTestCase<T>
{
}
| conormcd/exemplar | tests/junit/src/junit/com/mcdermottroe/exemplar/input/AbstractInputModuleTest.java | Java | bsd-3-clause | 2,000 |
/*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
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 Vodafone Group Services Ltd 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 "OldMapIdByName.h"
#include "MapGenUtil.h"
#include "OldGenericMapHeader.h"
#include "MapBits.h"
#include <fstream>
OldMapIdByName::OldMapIdByName( MC2String fileName ){
m_fileName = fileName;
}
OldMapIdByName::mapIdAndHdlByName_t&
OldMapIdByName::getWriteableMapIdByAndHdlName()
{
return m_mapIdAndHdlByName;
} // getWriteableMapIdByAndHdlName
bool
OldMapIdByName::initAndWriteFile(MC2String mapPath)
{
// Map mapping map id to map name and handled status.
// Setting all handled statuses to false.
m_mapIdAndHdlByName.clear();
uint32 mapID = 0;
bool cont = true;
while (cont) {
OldGenericMapHeader* curMap =
new OldGenericMapHeader( mapID, mapPath.c_str() );
if ( curMap->load() ){
pair< MC2String, pair<uint32, bool> > nameToIdAndHdl;
MC2String underviewName=curMap->getMapName();
nameToIdAndHdl.first = curMap->getMapName();
nameToIdAndHdl.second.first = mapID;
nameToIdAndHdl.second.second = false; // handled.
mc2log << info << "Read name of map: " << mapID
<< ":" << underviewName << endl;
m_mapIdAndHdlByName.insert( nameToIdAndHdl );
delete curMap;
curMap = NULL;
mapID = MapBits::nextMapID(mapID);
}
else if ( MapBits::isUnderviewMap(mapID) ){
// Continue with ovierview maps.
mapID = FIRST_OVERVIEWMAP_ID; // defined in config.h
}
else if ( ( MapBits::isOverviewMap(mapID) ) &&
(mapID < FIRST_SUPEROVERVIEWMAP_ID) ){
// Continue with country overivew maps.
mapID = FIRST_COUNTRYMAP_ID; // defined in config.h
}
else if ( MapBits::isCountryMap(mapID) ){
// Continue with super ovierview maps.
mapID = FIRST_SUPEROVERVIEWMAP_ID; // defined in config.h
}
else {
// Have read all underview, overivew, country overiview and super
// overviews.
cont = false;
}
}
mc2log << info << "OldMapIdByName::initAndWriteFile"
<< "Done reading underview map names. Saving list in file"
<< endl;
// Write
bool result = OldMapIdByName::writeFile();
return result;
} // initAndWriteFile
bool
OldMapIdByName::fileExists()
{
// Test to open file.
mc2dbg << "Test to open file:" << m_fileName << endl;
bool fileExists = MapGenUtil::fileExists(m_fileName);
if ( fileExists ){
mc2dbg << m_fileName << " exists." << endl;
}
else {
mc2dbg << m_fileName << " does not exist." << endl;
}
return fileExists;
} // fileExists
bool
OldMapIdByName::writeFile()
{
/* Structure of the file pointed at by m_fileName
* mapName mapID mapHdl
*
* mapName Name of underview map.
* mapID Map ID of underview map.
* mapHdl A string "TRUE" or "FALSE". Tells whether this map
* has been added to an overview map.
*/
ofstream file( m_fileName.c_str(), ios::out|ios::trunc );
if ( ! file ) {
mc2log << error << "OldMapIdByName::writeFile. Could not open "
<< m_fileName << endl;
return false;
}
mapIdAndHdlByName_t::const_iterator it = m_mapIdAndHdlByName.begin();
while ( it != m_mapIdAndHdlByName.end() ){
MC2String mapName = it->first;
uint32 mapID = it->second.first;
MC2String mapHdl = ( it->second.second ? "TRUE": "FALSE");
file << mapName << " " << mapID << " " << mapHdl << endl;
++it;
}
file.close();
return true;
} // writeFile
bool
OldMapIdByName::readFile()
{
// For documentation of the structure in this file, see definition of
// writeFile.
ifstream file( m_fileName.c_str(), ios::in );
if ( ! file ) {
mc2log << error << "OldMapIdByName::readFile. Could not open "
<< m_fileName << endl;
return false;
}
while ( ! file.eof() ) {
pair<MC2String, pair<uint32, bool> > nameToIdAndHdl;
MC2String mapHdlStr;
file >> nameToIdAndHdl.first; // map name
file >> nameToIdAndHdl.second.first; // map ID
file >> mapHdlStr; // map handled
if ( mapHdlStr.compare("TRUE") == 0 ){
nameToIdAndHdl.second.second = true;
}
else{
nameToIdAndHdl.second.second = false;
}
if ( ! file.eof() ){
mc2dbg << "OldMapIdByName::readFile. "
<< nameToIdAndHdl.first << ":"
<< nameToIdAndHdl.second.first << ":"
<< nameToIdAndHdl.second.second << endl;
m_mapIdAndHdlByName.insert(nameToIdAndHdl);
}
}
file.close();
// Check the read result.
if ( m_mapIdAndHdlByName.size() == 0 ){
mc2log << error << "OldMapIdByName::readFile. Found 0 underviews in "
<< m_fileName << endl;
return false;
}
return true;
} // readFile
bool
OldMapIdByName::cmpUndIDsWithMapFiles( MC2String mapPath,
uint32& highestID,
uint32& nextMapID )
{
// Check that all underview maps are present in the file.
highestID = 0;
OldMapIdByName::mapIdAndHdlByName_t::const_iterator it =
m_mapIdAndHdlByName.begin();
while ( it != m_mapIdAndHdlByName.end() ){
// Find highest underview ID
uint32 mapID = it->second.first;
if ( MapBits::isUnderviewMap(mapID) && ( mapID > highestID ) ){
highestID = it->second.first;
}
++it;
}
nextMapID = MapGenUtil::getNextUndMapID(mapPath);
if ( (highestID+1) != nextMapID ){
return false;
}
else {
return true;
}
} // cmpUndIDsWithMapFiles
bool
OldMapIdByName::overviewsContained()
{
bool result = false;
OldMapIdByName::mapIdAndHdlByName_t::const_iterator it =
m_mapIdAndHdlByName.begin();
while ( !result && ( it != m_mapIdAndHdlByName.end() ) ){
uint32 mapID = it->second.first;
if ( MapBits::isOverviewMap(mapID) ){
result = true;
}
++it;
}
return result;
} // overviewsContained
| wayfinder/Wayfinder-Server | Server/MapGen/src/OldMapIdByName.cpp | C++ | bsd-3-clause | 7,659 |
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2016, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#ifndef GAFFERSCENEUI_SHADERVIEW_H
#define GAFFERSCENEUI_SHADERVIEW_H
#include "GafferImageUI/ImageView.h"
#include "GafferSceneUI/TypeIds.h"
namespace Gaffer
{
IE_CORE_FORWARDDECLARE( Box )
} // namespace Gaffer
namespace GafferSceneUI
{
class ShaderView : public GafferImageUI::ImageView
{
public :
ShaderView( const std::string &name = defaultName<ShaderView>() );
virtual ~ShaderView();
IE_CORE_DECLARERUNTIMETYPEDEXTENSION( GafferSceneUI::ShaderView, ShaderViewTypeId, GafferImageUI::ImageView );
Gaffer::StringPlug *scenePlug();
const Gaffer::StringPlug *scenePlug() const;
// The prefix for the shader currently being viewed.
std::string shaderPrefix() const;
// The scene currently being used.
Gaffer::Node *scene();
const Gaffer::Node *scene() const;
typedef boost::signal<void ( ShaderView * )> SceneChangedSignal;
SceneChangedSignal &sceneChangedSignal();
virtual void setContext( Gaffer::ContextPtr context );
typedef boost::function<Gaffer::NodePtr ()> RendererCreator;
static void registerRenderer( const std::string &shaderPrefix, RendererCreator rendererCreator );
typedef boost::function<Gaffer::NodePtr ()> SceneCreator;
static void registerScene( const std::string &shaderPrefix, const std::string &name, SceneCreator sceneCreator );
static void registerScene( const std::string &shaderPrefix, const std::string &name, const std::string &referenceFileName );
static void registeredScenes( const std::string &shaderPrefix, std::vector<std::string> &names );
private :
typedef std::pair<std::string, std::string> PrefixAndName;
typedef std::map<PrefixAndName, Gaffer::NodePtr> Scenes;
void viewportVisibilityChanged();
void plugSet( Gaffer::Plug *plug );
void plugDirtied( Gaffer::Plug *plug );
void sceneRegistrationChanged( const PrefixAndName &prefixAndName );
void idleUpdate();
void updateRenderer();
void updateRendererContext();
void updateRendererState();
void updateScene();
void preRender();
bool m_framed;
Gaffer::BoxPtr m_imageConverter;
boost::signals::scoped_connection m_idleConnection;
Gaffer::NodePtr m_renderer;
std::string m_rendererShaderPrefix;
Scenes m_scenes;
Gaffer::NodePtr m_scene;
PrefixAndName m_scenePrefixAndName;
SceneChangedSignal m_sceneChangedSignal;
static ViewDescription<ShaderView> g_viewDescription;
};
IE_CORE_DECLAREPTR( ShaderView );
} // namespace GafferSceneUI
#endif // GAFFERSCENEUI_SHADERVIEW_H
| chippey/gaffer | include/GafferSceneUI/ShaderView.h | C | bsd-3-clause | 4,310 |
<?php
/**
* @var $cart \yz\shoppingcart\ShoppingCart
*/
use app\modules\store\models\StoreProduct;
use app\modules\store\models\StoreProductCartPosition;
use common\models\Currency;
use metalguardian\fileProcessor\helpers\FPM;
use yii\helpers\Url;
$cart = Yii::$app->cart;
$positions = $cart->getPositions();
$totalCost = $cart->getCost() . ' ' . Currency::getDefaultCurrencyCode();
?>
<div id="cart-page">
<div class="breadcrumb">
<a href="<?= Url::home() ?>"><?= \Yii::t('front', 'Home') ?></a> »
<a href="#"><?= \Yii::t('front', 'Cart') ?></a>
</div>
<h1><span class="h1-top"><?= \Yii::t('front', 'Cart') ?></span></h1>
<div class="cart-info">
<table>
<thead>
<tr>
<td class="image"><?= \Yii::t('front', 'Image') ?></td>
<td class="name"><?= \Yii::t('front', 'Product Name') ?></td>
<td class="model"><?= \Yii::t('front', 'Model') ?></td>
<td class="model"><?= \Yii::t('front', 'Size') ?></td>
<td class="quantity"><?= \Yii::t('front', 'Quantity') ?></td>
<td class="price"><?= \Yii::t('front', 'Unit Price') ?></td>
<td class="total"><?= \Yii::t('front', 'Total') ?></td>
</tr>
</thead>
<tbody>
<?php /** @var StoreProductCartPosition $item */
foreach ($positions as $item):
$product = $item->getProduct();
?>
<?php $productUrl = StoreProduct::getProductUrl(['alias' => $product->alias]) ?>
<tr>
<td class="image">
<a href="<?= $productUrl ?>">
<?= FPM::image($product->mainImage->file_id, 'product', 'mainPreview', [
'width' => 130,
'height' => 130
]) ?>
</a>
</td>
<td class="name">
<a href="<?= $productUrl ?>"><?= $product->label ?></a>
<div> </div>
</td>
<td class="model"><?= $product->sku ?></td>
<td class="model"><?= $item->getSize()->typeSize->getLabel() ?></td>
<td class="quantity">
<input class="cart-quantity" data-url="<?= StoreProductCartPosition::getCartUpdateUrl(['id' => $item->id]) ?>" type="text" name="quantity" value="<?= $item->getQuantity() ?>" size="1">
</td>
<td class="price"><?= $item->getPrice() ?> <?= Currency::getDefaultCurrencyCode() ?></td>
<td class="total"><?= $item->getCost() ?> <?= Currency::getDefaultCurrencyCode() ?>
<div class="reload">
<a class="ajax-link" href="<?= $item->getRemoveUrl(true) ?>" data-item="<?= $item->id ?>">
<img src="/image/del.png" alt="<?= \Yii::t('front', 'Remove') ?>" title="<?= \Yii::t('front', 'Remove') ?>">
</a>
</div>
</td>
</tr>
<tr>
<td colspan="6" class="emptyrow"></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<h2 class="cart-h2"><?= \Yii::t('front', 'What would you like to do next?') ?></h2>
<div class="cart-total">
<table id="total">
<tbody>
<tr>
<td class="right lastrow"><b><?= \Yii::t('front', 'Total:') ?></b></td>
<td class="right last lastrow"><?= $totalCost ?></td>
</tr>
</tbody>
</table>
</div>
<div class="buttons">
<div class="right"><a href="<?= StoreProductCartPosition::getCheckoutUrl() ?>" class="button"><?= \Yii::t('front', 'Checkout') ?></a></div>
<div class="center">
<a href="<?= Url::home() ?>" class="button"><?= \Yii::t('front', 'Continue Shopping') ?></a>
</div>
</div>
</div>
| tolik505/baby | frontend/themes/basic/modules/store/views/cart/cart.php | PHP | bsd-3-clause | 4,156 |
/*
* Copyright (C) 2011 Apple Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "third_party/blink/renderer/core/scroll/scrollbar_theme.h"
#include "base/optional.h"
#include "build/build_config.h"
#include "cc/input/scrollbar.h"
#include "third_party/blink/public/common/input/web_mouse_event.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_rect.h"
#include "third_party/blink/renderer/core/scroll/scrollbar.h"
#include "third_party/blink/renderer/core/scroll/scrollbar_theme_overlay_mock.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context_state_saver.h"
#include "third_party/blink/renderer/platform/graphics/paint/cull_rect.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_display_item.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_controller.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#if !defined(OS_MACOSX)
#include "third_party/blink/public/platform/web_theme_engine.h"
#endif
namespace blink {
void ScrollbarTheme::Paint(const Scrollbar& scrollbar,
GraphicsContext& graphics_context,
const IntPoint& paint_offset) {
PaintTrackButtonsTickmarks(graphics_context, scrollbar, paint_offset);
if (HasThumb(scrollbar)) {
IntRect thumb_rect = ThumbRect(scrollbar);
thumb_rect.MoveBy(paint_offset);
PaintThumbWithOpacity(graphics_context, scrollbar, thumb_rect);
}
}
ScrollbarPart ScrollbarTheme::HitTestRootFramePosition(
const Scrollbar& scrollbar,
const IntPoint& position_in_root_frame) {
if (!AllowsHitTest())
return kNoPart;
if (!scrollbar.Enabled())
return kNoPart;
IntPoint test_position =
scrollbar.ConvertFromRootFrame(position_in_root_frame);
test_position.Move(scrollbar.X(), scrollbar.Y());
return HitTest(scrollbar, test_position);
}
ScrollbarPart ScrollbarTheme::HitTest(const Scrollbar& scrollbar,
const IntPoint& test_position) {
if (!scrollbar.FrameRect().Contains(test_position))
return kNoPart;
IntRect track = TrackRect(scrollbar);
if (track.Contains(test_position)) {
IntRect before_thumb_rect;
IntRect thumb_rect;
IntRect after_thumb_rect;
SplitTrack(scrollbar, track, before_thumb_rect, thumb_rect,
after_thumb_rect);
if (thumb_rect.Contains(test_position))
return kThumbPart;
if (before_thumb_rect.Contains(test_position))
return kBackTrackPart;
if (after_thumb_rect.Contains(test_position))
return kForwardTrackPart;
return kTrackBGPart;
}
if (BackButtonRect(scrollbar).Contains(test_position))
return kBackButtonStartPart;
if (ForwardButtonRect(scrollbar).Contains(test_position))
return kForwardButtonEndPart;
return kScrollbarBGPart;
}
void ScrollbarTheme::PaintScrollCorner(
GraphicsContext& context,
const Scrollbar* vertical_scrollbar,
const DisplayItemClient& display_item_client,
const IntRect& corner_rect,
WebColorScheme color_scheme) {
if (corner_rect.IsEmpty())
return;
if (DrawingRecorder::UseCachedDrawingIfPossible(context, display_item_client,
DisplayItem::kScrollCorner))
return;
DrawingRecorder recorder(context, display_item_client,
DisplayItem::kScrollCorner);
#if defined(OS_MACOSX)
context.FillRect(corner_rect, Color::kWhite);
#else
Platform::Current()->ThemeEngine()->Paint(
context.Canvas(), WebThemeEngine::kPartScrollbarCorner,
WebThemeEngine::kStateNormal, WebRect(corner_rect), nullptr,
color_scheme);
#endif
}
void ScrollbarTheme::PaintTickmarks(GraphicsContext& context,
const Scrollbar& scrollbar,
const IntRect& rect) {
// Android paints tickmarks in the browser at FindResultBar.java.
#if !defined(OS_ANDROID)
if (scrollbar.Orientation() != kVerticalScrollbar)
return;
if (rect.Height() <= 0 || rect.Width() <= 0)
return;
Vector<IntRect> tickmarks = scrollbar.GetTickmarks();
if (!tickmarks.size())
return;
if (DrawingRecorder::UseCachedDrawingIfPossible(
context, scrollbar, DisplayItem::kScrollbarTickmarks))
return;
DrawingRecorder recorder(context, scrollbar,
DisplayItem::kScrollbarTickmarks);
GraphicsContextStateSaver state_saver(context);
context.SetShouldAntialias(false);
for (const IntRect& tickmark : tickmarks) {
// Calculate how far down (in %) the tick-mark should appear.
const float percent =
static_cast<float>(tickmark.Y()) / scrollbar.TotalSize();
// Calculate how far down (in pixels) the tick-mark should appear.
const int y_pos = rect.Y() + (rect.Height() * percent);
FloatRect tick_rect(rect.X(), y_pos, rect.Width(), 3);
context.FillRect(tick_rect, Color(0xCC, 0xAA, 0x00, 0xFF));
FloatRect tick_stroke(rect.X() + TickmarkBorderWidth(), y_pos + 1,
rect.Width() - 2 * TickmarkBorderWidth(), 1);
context.FillRect(tick_stroke, Color(0xFF, 0xDD, 0x00, 0xFF));
}
#endif
}
base::TimeDelta ScrollbarTheme::OverlayScrollbarFadeOutDelay() const {
// On Mac, fading is controlled by the painting code in ScrollAnimatorMac.
return base::TimeDelta();
}
base::TimeDelta ScrollbarTheme::OverlayScrollbarFadeOutDuration() const {
// On Mac, fading is controlled by the painting code in ScrollAnimatorMac.
return base::TimeDelta();
}
int ScrollbarTheme::ThumbPosition(const Scrollbar& scrollbar,
float scroll_position) {
if (scrollbar.Enabled()) {
float size = scrollbar.TotalSize() - scrollbar.VisibleSize();
// Avoid doing a floating point divide by zero and return 1 when
// usedTotalSize == visibleSize.
if (!size)
return 0;
float pos = std::max(0.0f, scroll_position) *
(TrackLength(scrollbar) - ThumbLength(scrollbar)) / size;
return (pos < 1 && pos > 0) ? 1 : base::saturated_cast<int>(pos);
}
return 0;
}
int ScrollbarTheme::ThumbLength(const Scrollbar& scrollbar) {
if (!scrollbar.Enabled())
return 0;
float overhang = fabsf(scrollbar.ElasticOverscroll());
float proportion = 0.0f;
float total_size = scrollbar.TotalSize();
if (total_size > 0.0f) {
proportion = (scrollbar.VisibleSize() - overhang) / total_size;
}
int track_len = TrackLength(scrollbar);
int length = round(proportion * track_len);
length = std::max(length, MinimumThumbLength(scrollbar));
if (length > track_len)
length = track_len; // Once the thumb is below the track length,
// it fills the track.
return length;
}
int ScrollbarTheme::TrackPosition(const Scrollbar& scrollbar) {
IntRect constrained_track_rect =
ConstrainTrackRectToTrackPieces(scrollbar, TrackRect(scrollbar));
return (scrollbar.Orientation() == kHorizontalScrollbar)
? constrained_track_rect.X() - scrollbar.X()
: constrained_track_rect.Y() - scrollbar.Y();
}
int ScrollbarTheme::TrackLength(const Scrollbar& scrollbar) {
IntRect constrained_track_rect =
ConstrainTrackRectToTrackPieces(scrollbar, TrackRect(scrollbar));
return (scrollbar.Orientation() == kHorizontalScrollbar)
? constrained_track_rect.Width()
: constrained_track_rect.Height();
}
IntRect ScrollbarTheme::ThumbRect(const Scrollbar& scrollbar) {
if (!HasThumb(scrollbar))
return IntRect();
IntRect track = TrackRect(scrollbar);
IntRect start_track_rect;
IntRect thumb_rect;
IntRect end_track_rect;
SplitTrack(scrollbar, track, start_track_rect, thumb_rect, end_track_rect);
return thumb_rect;
}
int ScrollbarTheme::ThumbThickness(const Scrollbar& scrollbar) {
IntRect track = TrackRect(scrollbar);
return scrollbar.Orientation() == kHorizontalScrollbar ? track.Height()
: track.Width();
}
void ScrollbarTheme::SplitTrack(const Scrollbar& scrollbar,
const IntRect& unconstrained_track_rect,
IntRect& before_thumb_rect,
IntRect& thumb_rect,
IntRect& after_thumb_rect) {
// This function won't even get called unless we're big enough to have some
// combination of these three rects where at least one of them is non-empty.
IntRect track_rect =
ConstrainTrackRectToTrackPieces(scrollbar, unconstrained_track_rect);
int thumb_pos = ThumbPosition(scrollbar);
if (scrollbar.Orientation() == kHorizontalScrollbar) {
thumb_rect = IntRect(track_rect.X() + thumb_pos, track_rect.Y(),
ThumbLength(scrollbar), scrollbar.Height());
before_thumb_rect =
IntRect(track_rect.X(), track_rect.Y(),
thumb_pos + thumb_rect.Width() / 2, track_rect.Height());
after_thumb_rect = IntRect(
track_rect.X() + before_thumb_rect.Width(), track_rect.Y(),
track_rect.MaxX() - before_thumb_rect.MaxX(), track_rect.Height());
} else {
thumb_rect = IntRect(track_rect.X(), track_rect.Y() + thumb_pos,
scrollbar.Width(), ThumbLength(scrollbar));
before_thumb_rect =
IntRect(track_rect.X(), track_rect.Y(), track_rect.Width(),
thumb_pos + thumb_rect.Height() / 2);
after_thumb_rect = IntRect(
track_rect.X(), track_rect.Y() + before_thumb_rect.Height(),
track_rect.Width(), track_rect.MaxY() - before_thumb_rect.MaxY());
}
}
base::TimeDelta ScrollbarTheme::InitialAutoscrollTimerDelay() {
return kInitialAutoscrollTimerDelay;
}
base::TimeDelta ScrollbarTheme::AutoscrollTimerDelay() {
return base::TimeDelta::FromSecondsD(1.f / kAutoscrollMultiplier);
}
ScrollbarTheme& ScrollbarTheme::GetTheme() {
if (MockScrollbarsEnabled()) {
// We only support mock overlay scrollbars.
DCHECK(OverlayScrollbarsEnabled());
DEFINE_STATIC_LOCAL(ScrollbarThemeOverlayMock, overlay_mock_theme, ());
return overlay_mock_theme;
}
return NativeTheme();
}
void ScrollbarTheme::PaintTrackAndButtons(GraphicsContext& context,
const Scrollbar& scrollbar,
const IntPoint& offset) {
// CustomScrollbarTheme must override this method.
DCHECK(!scrollbar.IsCustomScrollbar());
if (DrawingRecorder::UseCachedDrawingIfPossible(
context, scrollbar, DisplayItem::kScrollbarTrackAndButtons))
return;
DrawingRecorder recorder(context, scrollbar,
DisplayItem::kScrollbarTrackAndButtons);
if (HasButtons(scrollbar)) {
IntRect back_button_rect = BackButtonRect(scrollbar);
back_button_rect.MoveBy(offset);
PaintButton(context, scrollbar, back_button_rect, kBackButtonStartPart);
IntRect forward_button_rect = ForwardButtonRect(scrollbar);
forward_button_rect.MoveBy(offset);
PaintButton(context, scrollbar, forward_button_rect, kForwardButtonEndPart);
}
IntRect track_rect = TrackRect(scrollbar);
track_rect.MoveBy(offset);
PaintTrack(context, scrollbar, track_rect);
}
void ScrollbarTheme::PaintTrackButtonsTickmarks(GraphicsContext& context,
const Scrollbar& scrollbar,
const IntPoint& offset) {
PaintTrackAndButtons(context, scrollbar, offset);
if (scrollbar.HasTickmarks()) {
IntRect track_rect = TrackRect(scrollbar);
track_rect.MoveBy(offset);
PaintTickmarks(context, scrollbar, track_rect);
}
}
} // namespace blink
| endlessm/chromium-browser | third_party/blink/renderer/core/scroll/scrollbar_theme.cc | C++ | bsd-3-clause | 13,214 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<link rel="up" title="FatFs" href="../00index_e.html">
<link rel="alternate" hreflang="ja" title="Japanese" href="../ja/dread.html">
<link rel="stylesheet" href="../css_e.css" type="text/css" media="screen" title="ELM Default">
<title>FatFs - disk_read</title>
</head>
<body>
<div class="para func">
<h2>disk_read</h2>
<p>The disk_read function reads sector(s) from the disk drive.</p>
<pre>
DRESULT disk_read (
BYTE <em>Drive</em>, <span class="c">/* Physical drive number */</span>
BYTE* <em>Buffer</em>, <span class="c">/* Pointer to the read data buffer */</span>
DWORD <em>SectorNumber</em>, <span class="c">/* Start sector number */</span>
BYTE <em>SectorCount</em> <span class="c">/* Number of sectros to read */</span>
);
</pre>
</div>
<div class="para arg">
<h4>Parameters</h4>
<dl class="par">
<dt>Drive</dt>
<dd>Specifies the physical drive number.</dd>
<dt>Buffer</dt>
<dd>Pointer to the <em>byte array</em> to store the read data. The size of buffer must be in sector size * sector count.</dd>
<dt>SectorNumber</dt>
<dd>Specifies the start sector number in logical block address (LBA).</dd>
<dt>SectorCount</dt>
<dd>Specifies number of sectors to read. The value can be 1 to 128. Generally, a multiple sector transfer request must not be split into single sector transactions to the device, or you may not get good read performance.</dd>
</dl>
</div>
<div class="para ret">
<h4>Return Value</h4>
<dl class="ret">
<dt>RES_OK (0)</dt>
<dd>The function succeeded.</dd>
<dt>RES_ERROR</dt>
<dd>Any hard error occured during the read operation and could not recover it.</dd>
<dt>RES_PARERR</dt>
<dd>Invalid parameter.</dd>
<dt>RES_NOTRDY</dt>
<dd>The disk drive has not been initialized.</dd>
</dl>
</div>
<div class="para desc">
<h4>Description</h4>
<p>The specified memory address is not that always aligned to word boundary because the type of pointer is defined as BYTE. The misaligned read/write request can occure at <a href="appnote.html#fs1">direct transfer</a>. If the bus architecture, especially DMA controller, does not allow misaligned memory access, it should be solved in this function. There are some workarounds below to avoid this problem.</p>
<ul>
<li>In this function, convert word transfer to byte transfer. - Recommended.</li>
<li>On f_read(), avoid long read request that includes a whole of sector. - Direct transfer will never occure.</li>
<li>On f_read(), make sure that the lower two bits of start address is equal to the lower two bits of file read/write pointer. - Word aligned direct transfer is guaranteed.</li>
</ul>
</div>
<p class="foot"><a href="../00index_e.html">Return</a></p>
</body>
</html>
| rodb70/gendosfs | doc/en/dread.html | HTML | bsd-3-clause | 2,992 |
<?php
namespace app\modules\admin\controllers;
use yii\web\Controller;
use yii;
class TestController extends Controller
{
public $enableCsrfValidation = false;
//后台登录界面
public function actionIndex(){
return $this->renderPartial('index.html');
}
//登录
public function actionLogin(){
$r =Yii::$app->request;
$mod = new \app\models\RootDB();
$rst = $mod::find()->select(['id','pwd','power','user'])->where('user=:user',[':user'=>$r->post('user')])->one(); //查询用户
if(!$rst){
echo 0;
}
else if(md5($r->post('pwd')) == $rst->attributes['pwd']){//核对密码
$session = Yii::$app->session;
$session->set('user',$rst->attributes);
echo 1;
}else{
echo 0;
}
}
//退出登录
public function actionLogout(){
$session = Yii::$app->session;
$session->remove('user');
// return $this->redirect('admin/test/index');
return $this->redirect('./index.php?r=admin/test/index');
}
}
| uoi00/basic | modules/admin/controllers/TestController.php | PHP | bsd-3-clause | 1,092 |
<?php
namespace common\libraries\sdk\alipay\request;
/**
* ALIPAY API: alipay.trade.wap.pay request
*
* @author auto create
* @since 1.0, 2016-04-29 17:06:46
*/
class AlipayTradeWapPayRequest
{
/**
* 手机网站支付接口2.0
**/
private $bizContent;
private $apiParas = array();
private $terminalType;
private $terminalInfo;
private $prodCode;
private $apiVersion="1.0";
private $notifyUrl;
private $returnUrl;
private $needEncrypt=false;
public function setBizContent($bizContent)
{
$this->bizContent = $bizContent;
$this->apiParas["biz_content"] = $bizContent;
}
public function getBizContent()
{
return $this->bizContent;
}
public function getApiMethodName()
{
return "alipay.trade.create";
}
public function setNotifyUrl($notifyUrl)
{
$this->notifyUrl=$notifyUrl;
}
public function getNotifyUrl()
{
return $this->notifyUrl;
}
public function setReturnUrl($returnUrl)
{
$this->returnUrl=$returnUrl;
}
public function getReturnUrl()
{
return $this->returnUrl;
}
public function getApiParas()
{
return $this->apiParas;
}
public function getTerminalType()
{
return $this->terminalType;
}
public function setTerminalType($terminalType)
{
$this->terminalType = $terminalType;
}
public function getTerminalInfo()
{
return $this->terminalInfo;
}
public function setTerminalInfo($terminalInfo)
{
$this->terminalInfo = $terminalInfo;
}
public function getProdCode()
{
return $this->prodCode;
}
public function setProdCode($prodCode)
{
$this->prodCode = $prodCode;
}
public function setApiVersion($apiVersion)
{
$this->apiVersion=$apiVersion;
}
public function getApiVersion()
{
return $this->apiVersion;
}
public function setNeedEncrypt($needEncrypt)
{
$this->needEncrypt=$needEncrypt;
}
public function getNeedEncrypt()
{
return $this->needEncrypt;
}
}
| Youxiang11/wenheyou | common/libraries/sdk/alipay/request/AlipayTradeWapPayRequest.php | PHP | bsd-3-clause | 1,901 |
"""
Menu-driven login system
Contribution - Griatch 2011
This is an alternative login system for Evennia, using the
contrib.menusystem module. As opposed to the default system it doesn't
use emails for authentication and also don't auto-creates a Character
with the same name as the Player (instead assuming some sort of
character-creation to come next).
Install is simple:
To your settings file, add/edit the line:
CMDSET_UNLOGGEDIN = "contrib.menu_login.UnloggedInCmdSet"
That's it. Reload the server and try to log in to see it.
The initial login "graphic" is taken from strings in the module given
by settings.CONNECTION_SCREEN_MODULE. You will want to copy the
template file in game/gamesrc/conf/examples up one level and re-point
the settings file to this custom module. you can then edit the string
in that module (at least comment out the default string that mentions
commands that are not available) and add something more suitable for
the initial splash screen.
"""
import re
import traceback
from django.conf import settings
from ev import managers
from ev import utils, logger, create_player
from ev import Command, CmdSet
from ev import syscmdkeys
from src.server.models import ServerConfig
from contrib.menusystem import MenuNode, MenuTree
CMD_LOGINSTART = syscmdkeys.CMD_LOGINSTART
CMD_NOINPUT = syscmdkeys.CMD_NOINPUT
CMD_NOMATCH = syscmdkeys.CMD_NOMATCH
CONNECTION_SCREEN_MODULE = settings.CONNECTION_SCREEN_MODULE
# Commands run on the unloggedin screen. Note that this is not using
# settings.UNLOGGEDIN_CMDSET but the menu system, which is why some are
# named for the numbers in the menu.
#
# Also note that the menu system will automatically assign all
# commands used in its structure a property "menutree" holding a reference
# back to the menutree. This allows the commands to do direct manipulation
# for example by triggering a conditional jump to another node.
#
# Menu entry 1a - Entering a Username
class CmdBackToStart(Command):
"""
Step back to node0
"""
key = CMD_NOINPUT
locks = "cmd:all()"
def func(self):
"Execute the command"
self.menutree.goto("START")
class CmdUsernameSelect(Command):
"""
Handles the entering of a username and
checks if it exists.
"""
key = CMD_NOMATCH
locks = "cmd:all()"
def func(self):
"Execute the command"
player = managers.players.get_player_from_name(self.args)
if not player:
self.caller.msg("{rThis account name couldn't be found. Did you create it? If you did, make sure you spelled it right (case doesn't matter).{n")
self.menutree.goto("node1a")
else:
# store the player so next step can find it
self.menutree.player = player
self.caller.msg(echo=False)
self.menutree.goto("node1b")
# Menu entry 1b - Entering a Password
class CmdPasswordSelectBack(Command):
"""
Steps back from the Password selection
"""
key = CMD_NOINPUT
locks = "cmd:all()"
def func(self):
"Execute the command"
self.menutree.goto("node1a")
self.caller.msg(echo=True)
class CmdPasswordSelect(Command):
"""
Handles the entering of a password and logs into the game.
"""
key = CMD_NOMATCH
locks = "cmd:all()"
def func(self):
"Execute the command"
self.caller.msg(echo=True)
if not hasattr(self.menutree, "player"):
self.caller.msg("{rSomething went wrong! The player was not remembered from last step!{n")
self.menutree.goto("node1a")
return
player = self.menutree.player
if not player.check_password(self.args):
self.caller.msg("{rIncorrect password.{n")
self.menutree.goto("node1b")
return
# before going on, check eventual bans
bans = ServerConfig.objects.conf("server_bans")
if bans and (any(tup[0]==player.name.lower() for tup in bans)
or
any(tup[2].match(self.caller.address) for tup in bans if tup[2])):
# this is a banned IP or name!
string = "{rYou have been banned and cannot continue from here."
string += "\nIf you feel this ban is in error, please email an admin.{x"
self.caller.msg(string)
self.caller.sessionhandler.disconnect(self.caller, "Good bye! Disconnecting...")
return
# we are ok, log us in.
self.caller.msg("{gWelcome %s! Logging in ...{n" % player.key)
#self.caller.session_login(player)
self.caller.sessionhandler.login(self.caller, player)
# abort menu, do cleanup.
self.menutree.goto("END")
# we are logged in. Look around.
character = player.character
if character:
character.execute_cmd("look")
else:
# we have no character yet; use player's look, if it exists
player.execute_cmd("look")
# Menu entry 2a - Creating a Username
class CmdUsernameCreate(Command):
"""
Handle the creation of a valid username
"""
key = CMD_NOMATCH
locks = "cmd:all()"
def func(self):
"Execute the command"
playername = self.args
# sanity check on the name
if not re.findall('^[\w. @+-]+$', playername) or not (3 <= len(playername) <= 30):
self.caller.msg("\n\r {rAccount name should be between 3 and 30 characters. Letters, spaces, dig\
its and @/./+/-/_ only.{n") # this echoes the restrictions made by django's auth module.
self.menutree.goto("node2a")
return
if managers.players.get_player_from_name(playername):
self.caller.msg("\n\r {rAccount name %s already exists.{n" % playername)
self.menutree.goto("node2a")
return
# store the name for the next step
self.menutree.playername = playername
self.caller.msg(echo=False)
self.menutree.goto("node2b")
# Menu entry 2b - Creating a Password
class CmdPasswordCreateBack(Command):
"Step back from the password creation"
key = CMD_NOINPUT
locks = "cmd:all()"
def func(self):
"Execute the command"
self.caller.msg(echo=True)
self.menutree.goto("node2a")
class CmdPasswordCreate(Command):
"Handle the creation of a password. This also creates the actual Player/User object."
key = CMD_NOMATCH
locks = "cmd:all()"
def func(self):
"Execute the command"
password = self.args
self.caller.msg(echo=False)
if not hasattr(self.menutree, 'playername'):
self.caller.msg("{rSomething went wrong! Playername not remembered from previous step!{n")
self.menutree.goto("node2a")
return
playername = self.menutree.playername
if len(password) < 3:
# too short password
string = "{rYour password must be at least 3 characters or longer."
string += "\n\rFor best security, make it at least 8 characters "
string += "long, avoid making it a real word and mix numbers "
string += "into it.{n"
self.caller.msg(string)
self.menutree.goto("node2b")
return
# everything's ok. Create the new player account. Don't create
# a Character here.
try:
permissions = settings.PERMISSION_PLAYER_DEFAULT
typeclass = settings.BASE_PLAYER_TYPECLASS
new_player = create_player(playername, None, password,
typeclass=typeclass,
permissions=permissions)
if not new_player:
self.msg("There was an error creating the Player. This error was logged. Contact an admin.")
self.menutree.goto("START")
return
utils.init_new_player(new_player)
# join the new player to the public channel
pchanneldef = settings.CHANNEL_PUBLIC
if pchanneldef:
pchannel = managers.channels.get_channel(pchanneldef[0])
if not pchannel.connect(new_player):
string = "New player '%s' could not connect to public channel!" % new_player.key
logger.log_errmsg(string)
# tell the caller everything went well.
string = "{gA new account '%s' was created. Now go log in from the menu!{n"
self.caller.msg(string % (playername))
self.menutree.goto("START")
except Exception:
# We are in the middle between logged in and -not, so we have
# to handle tracebacks ourselves at this point. If we don't, we
# won't see any errors at all.
string = "%s\nThis is a bug. Please e-mail an admin if the problem persists."
self.caller.msg(string % (traceback.format_exc()))
logger.log_errmsg(traceback.format_exc())
# Menu entry 3 - help screen
LOGIN_SCREEN_HELP = \
"""
Welcome to %s!
To login you need to first create an account. This is easy and
free to do: Choose option {w(1){n in the menu and enter an account
name and password when prompted. Obs- the account name is {wnot{n
the name of the Character you will play in the game!
It's always a good idea (not only here, but everywhere on the net)
to not use a regular word for your password. Make it longer than 3
characters (ideally 6 or more) and mix numbers and capitalization
into it. The password also handles whitespace, so why not make it
a small sentence - easy to remember, hard for a computer to crack.
Once you have an account, use option {w(2){n to log in using the
account name and password you specified.
Use the {whelp{n command once you're logged in to get more
aid. Hope you enjoy your stay!
(return to go back)""" % settings.SERVERNAME
# Menu entry 4
class CmdUnloggedinQuit(Command):
"""
We maintain a different version of the quit command
here for unconnected players for the sake of simplicity. The logged in
version is a bit more complicated.
"""
key = "4"
aliases = ["quit", "qu", "q"]
locks = "cmd:all()"
def func(self):
"Simply close the connection."
self.menutree.goto("END")
self.caller.sessionhandler.disconnect(self.caller, "Good bye! Disconnecting...")
# The login menu tree, using the commands above
START = MenuNode("START", text=utils.random_string_from_module(CONNECTION_SCREEN_MODULE),
links=["node1a", "node2a", "node3", "END"],
linktexts=["Log in with an existing account",
"Create a new account",
"Help",
"Quit"],
selectcmds=[None, None, None, CmdUnloggedinQuit])
node1a = MenuNode("node1a", text="Please enter your account name (empty to abort).",
links=["START", "node1b"],
helptext=["Enter the account name you previously registered with."],
keywords=[CMD_NOINPUT, CMD_NOMATCH],
selectcmds=[CmdBackToStart, CmdUsernameSelect],
nodefaultcmds=True) # if we don't, default help/look will be triggered by names starting with l/h ...
node1b = MenuNode("node1b", text="Please enter your password (empty to go back).",
links=["node1a", "END"],
keywords=[CMD_NOINPUT, CMD_NOMATCH],
selectcmds=[CmdPasswordSelectBack, CmdPasswordSelect],
nodefaultcmds=True)
node2a = MenuNode("node2a", text="Please enter your desired account name (empty to abort).",
links=["START", "node2b"],
helptext="Account name can max be 30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only.",
keywords=[CMD_NOINPUT, CMD_NOMATCH],
selectcmds=[CmdBackToStart, CmdUsernameCreate],
nodefaultcmds=True)
node2b = MenuNode("node2b", text="Please enter your password (empty to go back).",
links=["node2a", "START"],
helptext="Your password cannot contain any characters.",
keywords=[CMD_NOINPUT, CMD_NOMATCH],
selectcmds=[CmdPasswordCreateBack, CmdPasswordCreate],
nodefaultcmds=True)
node3 = MenuNode("node3", text=LOGIN_SCREEN_HELP,
links=["START"],
helptext="",
keywords=[CMD_NOINPUT],
selectcmds=[CmdBackToStart])
# access commands
class UnloggedInCmdSet(CmdSet):
"Cmdset for the unloggedin state"
key = "UnloggedinState"
priority = 0
def at_cmdset_creation(self):
"Called when cmdset is first created"
self.add(CmdUnloggedinLook())
class CmdUnloggedinLook(Command):
"""
An unloggedin version of the look command. This is called by the server
when the player first connects. It sets up the menu before handing off
to the menu's own look command..
"""
key = CMD_LOGINSTART
locks = "cmd:all()"
def func(self):
"Execute the menu"
menu = MenuTree(self.caller, nodes=(START, node1a, node1b,
node2a, node2b, node3),
exec_end=None)
menu.start()
| GhostshipSoftware/avaloria | contrib/menu_login.py | Python | bsd-3-clause | 13,491 |
<?php
/* @var $this \yii\web\View */
/* @var $content string */
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use frontend\assets\AppAsset;
use common\widgets\Alert;
AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="yandex-verification" content="e9fed1796d9b482a" />
<?= Html::csrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
<script type="text/javascript" src="//vk.com/js/api/openapi.js?139"></script>
<script type="text/javascript">
// window.onload = function () {
VK.init({apiId: 5877934, onlyWidgets: true});
// }
</script>
</head>
<body class="home">
<?php
NavBar::begin([
'brandLabel' => 'Judlit',
'brandUrl' => Yii::$app->homeUrl,
'options' => [
'class' => 'navbar navbar-inverse navbar-fixed-top headroom',
],
]);
$menuItems = [
['label' => 'Главная', 'url' => ['/']],
// ['label' => 'О проекте', 'url' => ['/site/about']],
// ['label' => 'Контакты', 'url' => ['/site/contact']],
];
if (Yii::$app->user->isGuest) {
$menuItems[] = ['label' => 'Статьи', 'url' => ['/articles']];
// $menuItems[] = ['label' => 'Регистрация', 'url' => ['/site/signup']];
$menuItems[] = ['label' => 'Вход', 'url' => ['/site/login']];
} else {
$menuItems[] = ['label' => 'Категории', 'url' => ['/category/index']];
$menuItems[] = ['label' => 'Статьи', 'url' => ['/article/index']];
$menuItems[] = ['label' => 'Новые темы', 'url' => ['/article/question-index']];
$menuItems[] = '<li>'
. Html::beginForm(['/site/logout'], 'post')
. Html::submitButton(
'Выход (' . Yii::$app->user->identity->username . ')'
)
. Html::endForm()
. '</li>';
}
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => $menuItems,
]);
NavBar::end();
?>
<?php $this->beginBody() ?>
<?php if (Yii::$app->controller->id == 'site' and Yii::$app->controller->action->id == 'index') { ?>
<!-- Header -->
<!-- <header id="head">-->
<!-- <div class="container">-->
<!-- <div class="row">-->
<!-- <h1 class="lead">AWESOME, CUSTOMIZABLE, FREE</h1>-->
<!-- <p class="tagline">PROGRESSUS: free business bootstrap template by <a-->
<!-- href="http://www.gettemplate.com/?utm_source=progressus&utm_medium=template&utm_campaign=progressus">GetTemplate</a>-->
<!-- </p>-->
<!-- <p><a class="btn btn-default btn-lg" role="button">MORE INFO</a> <a class="btn btn-action btn-lg"-->
<!-- role="button">DOWNLOAD NOW</a></p>-->
<!-- </div>-->
<!-- </div>-->
<!-- </header>-->
<!-- /Header -->
<!-- Intro -->
<div class="white-row">
<div class="container text-center">
<br> <br>
<h2 class="thin">Юридическая грамотность</h2>
<p class="text-muted">
Правовая сторона неприятных ситуаций, с которыми мы, порой, сталкиваемся в жизни.<br>
В статьях данного сервиса представлены краткие ответы на возникающие в таких ситуациях вопросы - ничего
лишнего.
</p>
<br>
<!-- SEARCH FORM -->
<?php
$model = new \common\models\ArticleSearch();
$model->scenario = \common\models\ArticleSearch::SCENARIO_PUBLIC_SEARCH;
echo $this->render('/article/_article-search-form', [
'model' => $model
]);
?>
<!-- END SEARCH FORM -->
<p class="text-muted">
Не нашли что искали? <a href="#lets-comment">предложите тему для статьи</a>.
</p>
</div>
</div>
<!-- /Intro-->
<?php } ?>
<div class="container" style="padding-top: 50px">
<?= Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>
<?= Alert::widget() ?>
<?= $content ?>
</div>
<!-- Social links. @TODO: replace by link/instructions in template -->
<!--<section id="social">-->
<!-- <div class="container">-->
<!-- <div class="wrapper clearfix">-->
<!-- AddThis Button BEGIN -->
<!-- <div class="addthis_toolbox addthis_default_style">-->
<!-- <a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>-->
<!-- <a class="addthis_button_tweet"></a>-->
<!-- <a class="addthis_button_linkedin_counter"></a>-->
<!-- <a class="addthis_button_google_plusone" g:plusone:size="medium"></a>-->
<!-- </div>-->
<!-- AddThis Button END -->
<!-- </div>-->
<!-- </div>-->
<!--</section>-->
<!-- /social links -->
<?php //if (Yii::$app->controller->id == 'site' and Yii::$app->controller->action->id == 'index') { ?>
<!-- Intro -->
<!--<div class="white-row" style="background: #fff; padding-top: 20px">-->
<!-- <div class="container" id="lets-comment">-->
<!-- <h2 class="thin">Предложите тему для статьи</h2>-->
<!-- <p class="text-muted">-->
<!-- Напишите, на какой вопрос Вы хотели бы получить лаконичный ответ с юридической точки зрения, и мы обязательно его рассмотрим.-->
<!-- </p>-->
<!---->
<!-- --><?php
//
// $model = new \frontend\models\QuestionForm();
// echo $this->render('/article/_question-form', [
// 'model' => $model
// ]);
//
// ?>
<!-- <div id="new-artices-ideas"></div>-->
<!-- <script type="text/javascript">-->
<!-- window.onload = function () {-->
<!-- VK.Widgets.Comments("new-artices-ideas", {-->
<!-- limit: 10,-->
<!-- attach: "*"-->
<!-- }, 'new-artices-ideas-main-page');-->
<!-- }-->
<!-- </script>-->
<!-- </div>-->
<!--</div>-->
<!-- /Intro-->
<?php //} ?>
<footer id="footer">
<div class="footer1">
<div class="container">
<div class="row">
<div class="col-md-6 widget">
<h3 class="widget-title">Judlit.ru</h3>
<div class="widget-body">
<p>Юридическая грамотность</p>
</div>
</div>
<div class="col-md-3 widget">
<h3 class="widget-title">Контакты</h3>
<div class="widget-body">
<p>
<a href="mailto:#">info@judlit.ru</a><br>
</p>
</div>
</div>
<!-- <div class="col-md-3 widget">-->
<!-- <h3 class="widget-title">Мы в соц. сетях</h3>-->
<!-- <div class="widget-body">-->
<!-- <p class="follow-me-icons">-->
<!-- <a href=""><i class="fa fa-twitter fa-2"></i></a>-->
<!-- <a href=""><i class="fa fa-dribbble fa-2"></i></a>-->
<!-- <a href=""><i class="fa fa-github fa-2"></i></a>-->
<!-- <a href=""><i class="fa fa-facebook fa-2"></i></a>-->
<!-- </p>-->
<!-- </div>-->
<!-- </div>-->
</div> <!-- /row of widgets -->
</div>
</div>
<div class="footer2">
<div class="container">
<div class="row">
<div class="col-md-6 widget">
<div class="widget-body">
<p class="simplenav">
<a href="/">Главная</a> |
<!-- <a href="/site/contact">Контакты</a> |-->
<a href="/articles">Статьи</a>
</p>
</div>
</div>
<div class="col-md-6 widget">
<div class="widget-body">
<p class="text-right">
Все права защищены © 2016, <b style="color: #fff">judlit.ru</b>, Россия.
</p>
</div>
</div>
</div> <!-- /row of widgets -->
</div>
</div>
</footer>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
| FeR-S/judlit | frontend/views/layouts/main.php | PHP | bsd-3-clause | 9,460 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_BROWSER_H_
#define CHROME_BROWSER_UI_BROWSER_H_
#include <map>
#include <set>
#include <string>
#include <vector>
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/gtest_prod_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/prefs/pref_change_registrar.h"
#include "base/prefs/pref_member.h"
#include "base/scoped_observer.h"
#include "base/strings/string16.h"
#include "chrome/browser/devtools/devtools_toggle_action.h"
#include "chrome/browser/ui/bookmarks/bookmark_bar.h"
#include "chrome/browser/ui/bookmarks/bookmark_tab_helper_delegate.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/browser/ui/chrome_web_modal_dialog_manager_delegate.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h"
#include "chrome/browser/ui/host_desktop.h"
#include "chrome/browser/ui/search/search_tab_helper_delegate.h"
#include "chrome/browser/ui/search_engines/search_engine_tab_helper_delegate.h"
#include "chrome/browser/ui/tab_contents/core_tab_helper_delegate.h"
#include "chrome/browser/ui/tabs/tab_strip_model_observer.h"
#include "chrome/browser/ui/toolbar/toolbar_model.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/content_settings/core/common/content_settings_types.h"
#include "components/sessions/session_id.h"
#include "components/translate/content/browser/content_translate_driver.h"
#include "components/ui/zoom/zoom_observer.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/page_navigator.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/common/page_zoom.h"
#include "ui/base/page_transition_types.h"
#include "ui/base/ui_base_types.h"
#include "ui/base/window_open_disposition.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/shell_dialogs/select_file_dialog.h"
#if defined(ENABLE_EXTENSIONS)
#include "extensions/browser/extension_registry_observer.h"
#endif
class BrowserContentSettingBubbleModelDelegate;
class BrowserInstantController;
class BrowserSyncedWindowDelegate;
class BrowserToolbarModelDelegate;
class BrowserTabRestoreServiceDelegate;
class BrowserWindow;
class FindBarController;
class PrefService;
class Profile;
class SearchDelegate;
class SearchModel;
class StatusBubble;
class TabStripModel;
class TabStripModelDelegate;
class ValidationMessageBubble;
struct WebApplicationInfo;
namespace chrome {
class BrowserCommandController;
class FastUnloadController;
class UnloadController;
}
namespace content {
class NavigationController;
class PageState;
class SessionStorageNamespace;
}
namespace extensions {
class BookmarkAppBrowserController;
class Extension;
class ExtensionRegistry;
class WindowController;
}
namespace gfx {
class Image;
class Point;
}
namespace ui {
struct SelectedFileInfo;
class WebDialogDelegate;
}
namespace web_modal {
class PopupManager;
class WebContentsModalDialogHost;
}
class Browser : public TabStripModelObserver,
public content::WebContentsDelegate,
public CoreTabHelperDelegate,
public SearchEngineTabHelperDelegate,
public SearchTabHelperDelegate,
public ChromeWebModalDialogManagerDelegate,
public BookmarkTabHelperDelegate,
public ui_zoom::ZoomObserver,
public content::PageNavigator,
public content::NotificationObserver,
#if defined(ENABLE_EXTENSIONS)
public extensions::ExtensionRegistryObserver,
#endif
public translate::ContentTranslateDriver::Observer,
public ui::SelectFileDialog::Listener {
public:
// SessionService::WindowType mirrors these values. If you add to this
// enum, look at SessionService::WindowType to see if it needs to be
// updated.
enum Type {
// If you add a new type, consider updating the test
// BrowserTest.StartMaximized.
TYPE_TABBED = 1,
TYPE_POPUP = 2
};
// Possible elements of the Browser window.
enum WindowFeature {
FEATURE_NONE = 0,
FEATURE_TITLEBAR = 1,
FEATURE_TABSTRIP = 2,
FEATURE_TOOLBAR = 4,
FEATURE_LOCATIONBAR = 8,
FEATURE_BOOKMARKBAR = 16,
FEATURE_INFOBAR = 32,
FEATURE_DOWNLOADSHELF = 64,
FEATURE_WEBAPPFRAME = 128,
FEATURE_SIDEBAR = 256
};
// The context for a download blocked notification from
// OkToCloseWithInProgressDownloads.
enum DownloadClosePreventionType {
// Browser close is not blocked by download state.
DOWNLOAD_CLOSE_OK,
// The browser is shutting down and there are active downloads
// that would be cancelled.
DOWNLOAD_CLOSE_BROWSER_SHUTDOWN,
// There are active downloads associated with this incognito profile
// that would be canceled.
DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE,
};
struct CreateParams {
CreateParams(Profile* profile, chrome::HostDesktopType host_desktop_type);
CreateParams(Type type,
Profile* profile,
chrome::HostDesktopType host_desktop_type);
static CreateParams CreateForApp(const std::string& app_name,
bool trusted_source,
const gfx::Rect& window_bounds,
Profile* profile,
chrome::HostDesktopType host_desktop_type);
static CreateParams CreateForDevTools(
Profile* profile,
chrome::HostDesktopType host_desktop_type);
// The browser type.
Type type;
// The associated profile.
Profile* profile;
// The host desktop the browser is created on.
chrome::HostDesktopType host_desktop_type;
// Specifies the browser is_trusted_source_ value.
bool trusted_source;
// The bounds of the window to open.
gfx::Rect initial_bounds;
ui::WindowShowState initial_show_state;
bool is_session_restore;
// Supply a custom BrowserWindow implementation, to be used instead of the
// default. Intended for testing.
BrowserWindow* window;
private:
friend class Browser;
// The application name that is also the name of the window to the shell.
// Do not set this value directly, use CreateForApp.
// This name will be set for:
// 1) v1 applications launched via an application shortcut or extension API.
// 2) undocked devtool windows.
// 3) popup windows spawned from v1 applications.
std::string app_name;
};
// Constructors, Creation, Showing //////////////////////////////////////////
explicit Browser(const CreateParams& params);
~Browser() override;
// Set overrides for the initial window bounds and maximized state.
void set_override_bounds(const gfx::Rect& bounds) {
override_bounds_ = bounds;
}
ui::WindowShowState initial_show_state() const { return initial_show_state_; }
void set_initial_show_state(ui::WindowShowState initial_show_state) {
initial_show_state_ = initial_show_state;
}
// Return true if the initial window bounds have been overridden.
bool bounds_overridden() const {
return !override_bounds_.IsEmpty();
}
// Set indicator that this browser is being created via session restore.
// This is used on the Mac (only) to determine animation style when the
// browser window is shown.
void set_is_session_restore(bool is_session_restore) {
is_session_restore_ = is_session_restore;
}
bool is_session_restore() const {
return is_session_restore_;
}
chrome::HostDesktopType host_desktop_type() const {
return host_desktop_type_;
}
// Accessors ////////////////////////////////////////////////////////////////
Type type() const { return type_; }
const std::string& app_name() const { return app_name_; }
bool is_trusted_source() const { return is_trusted_source_; }
Profile* profile() const { return profile_; }
gfx::Rect override_bounds() const { return override_bounds_; }
// |window()| will return NULL if called before |CreateBrowserWindow()|
// is done.
BrowserWindow* window() const { return window_; }
ToolbarModel* toolbar_model() { return toolbar_model_.get(); }
const ToolbarModel* toolbar_model() const { return toolbar_model_.get(); }
#if defined(UNIT_TEST)
void swap_toolbar_models(scoped_ptr<ToolbarModel>* toolbar_model) {
toolbar_model->swap(toolbar_model_);
}
#endif
web_modal::PopupManager* popup_manager() {
return popup_manager_.get();
}
TabStripModel* tab_strip_model() const { return tab_strip_model_.get(); }
chrome::BrowserCommandController* command_controller() {
return command_controller_.get();
}
SearchModel* search_model() { return search_model_.get(); }
const SearchModel* search_model() const {
return search_model_.get();
}
SearchDelegate* search_delegate() {
return search_delegate_.get();
}
const SessionID& session_id() const { return session_id_; }
BrowserContentSettingBubbleModelDelegate*
content_setting_bubble_model_delegate() {
return content_setting_bubble_model_delegate_.get();
}
BrowserTabRestoreServiceDelegate* tab_restore_service_delegate() {
return tab_restore_service_delegate_.get();
}
BrowserSyncedWindowDelegate* synced_window_delegate() {
return synced_window_delegate_.get();
}
BrowserInstantController* instant_controller() {
return instant_controller_.get();
}
extensions::BookmarkAppBrowserController* bookmark_app_controller() {
return bookmark_app_controller_.get();
}
// Get the FindBarController for this browser, creating it if it does not
// yet exist.
FindBarController* GetFindBarController();
// Returns true if a FindBarController exists for this browser.
bool HasFindBarController() const;
// Returns the state of the bookmark bar.
BookmarkBar::State bookmark_bar_state() const { return bookmark_bar_state_; }
// State Storage and Retrieval for UI ///////////////////////////////////////
// Gets the Favicon of the page in the selected tab.
gfx::Image GetCurrentPageIcon() const;
// Gets the title of the window based on the selected tab's title.
base::string16 GetWindowTitleForCurrentTab() const;
// Prepares a title string for display (removes embedded newlines, etc).
static void FormatTitleForDisplay(base::string16* title);
// OnBeforeUnload handling //////////////////////////////////////////////////
// Gives beforeunload handlers the chance to cancel the close. Returns whether
// to proceed with the close. If called while the process begun by
// CallBeforeUnloadHandlers is in progress, returns false without taking
// action.
bool ShouldCloseWindow();
// Begins the process of confirming whether the associated browser can be
// closed. If there are no tabs with beforeunload handlers it will immediately
// return false. Otherwise, it starts prompting the user, returns true and
// will call |on_close_confirmed| with the result of the user's decision.
// After calling this function, if the window will not be closed, call
// ResetBeforeUnloadHandlers() to reset all beforeunload handlers; calling
// this function multiple times without an intervening call to
// ResetBeforeUnloadHandlers() will run only the beforeunload handlers
// registered since the previous call.
bool CallBeforeUnloadHandlers(
const base::Callback<void(bool)>& on_close_confirmed);
// Clears the results of any beforeunload confirmation dialogs triggered by a
// CallBeforeUnloadHandlers call.
void ResetBeforeUnloadHandlers();
// Figure out if there are tabs that have beforeunload handlers.
// It starts beforeunload/unload processing as a side-effect.
bool TabsNeedBeforeUnloadFired();
// Returns true if all tabs' beforeunload/unload events have fired.
bool HasCompletedUnloadProcessing() const;
bool IsAttemptingToCloseBrowser() const;
// Invoked when the window containing us is closing. Performs the necessary
// cleanup.
void OnWindowClosing();
// In-progress download termination handling /////////////////////////////////
// Called when the user has decided whether to proceed or not with the browser
// closure. |cancel_downloads| is true if the downloads should be canceled
// and the browser closed, false if the browser should stay open and the
// downloads running.
void InProgressDownloadResponse(bool cancel_downloads);
// Indicates whether or not this browser window can be closed, or
// would be blocked by in-progress downloads.
// If executing downloads would be cancelled by this window close,
// then |*num_downloads_blocking| is updated with how many downloads
// would be canceled if the close continued.
DownloadClosePreventionType OkToCloseWithInProgressDownloads(
int* num_downloads_blocking) const;
// External state change handling ////////////////////////////////////////////
// Invoked when the fullscreen state of the window changes.
// BrowserWindow::EnterFullscreen invokes this after the window has become
// fullscreen.
void WindowFullscreenStateChanged();
// Assorted browser commands ////////////////////////////////////////////////
// NOTE: Within each of the following sections, the IDs are ordered roughly by
// how they appear in the GUI/menus (left to right, top to bottom, etc.).
// See the description of
// FullscreenController::ToggleFullscreenModeWithExtension.
void ToggleFullscreenModeWithExtension(const GURL& extension_url);
#if defined(OS_WIN)
// See the description of FullscreenController::ToggleMetroSnapMode.
void SetMetroSnapMode(bool enable);
#endif
// Returns true if the Browser supports the specified feature. The value of
// this varies during the lifetime of the browser. For example, if the window
// is fullscreen this may return a different value. If you only care about
// whether or not it's possible for the browser to support a particular
// feature use |CanSupportWindowFeature|.
bool SupportsWindowFeature(WindowFeature feature) const;
// Returns true if the Browser can support the specified feature. See comment
// in |SupportsWindowFeature| for details on this.
bool CanSupportWindowFeature(WindowFeature feature) const;
// TODO(port): port these, and re-merge the two function declaration lists.
// Page-related commands.
void ToggleEncodingAutoDetect();
void OverrideEncoding(int encoding_id);
// Show various bits of UI
void OpenFile();
void UpdateDownloadShelfVisibility(bool visible);
/////////////////////////////////////////////////////////////////////////////
// Called by chrome::Navigate() when a navigation has occurred in a tab in
// this Browser. Updates the UI for the start of this navigation.
void UpdateUIForNavigationInTab(content::WebContents* contents,
ui::PageTransition transition,
bool user_initiated);
// Interface implementations ////////////////////////////////////////////////
// Overridden from content::PageNavigator:
content::WebContents* OpenURL(const content::OpenURLParams& params) override;
// Overridden from TabStripModelObserver:
void TabInsertedAt(content::WebContents* contents,
int index,
bool foreground) override;
void TabClosingAt(TabStripModel* tab_strip_model,
content::WebContents* contents,
int index) override;
void TabDetachedAt(content::WebContents* contents, int index) override;
void TabDeactivated(content::WebContents* contents) override;
void ActiveTabChanged(content::WebContents* old_contents,
content::WebContents* new_contents,
int index,
int reason) override;
void TabMoved(content::WebContents* contents,
int from_index,
int to_index) override;
void TabReplacedAt(TabStripModel* tab_strip_model,
content::WebContents* old_contents,
content::WebContents* new_contents,
int index) override;
void TabPinnedStateChanged(content::WebContents* contents,
int index) override;
void TabStripEmpty() override;
// Overridden from content::WebContentsDelegate:
bool CanOverscrollContent() const override;
bool ShouldPreserveAbortedURLs(content::WebContents* source) override;
bool PreHandleKeyboardEvent(content::WebContents* source,
const content::NativeWebKeyboardEvent& event,
bool* is_keyboard_shortcut) override;
void HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) override;
void ShowValidationMessage(content::WebContents* web_contents,
const gfx::Rect& anchor_in_root_view,
const base::string16& main_text,
const base::string16& sub_text) override;
void HideValidationMessage(content::WebContents* web_contents) override;
void MoveValidationMessage(content::WebContents* web_contents,
const gfx::Rect& anchor_in_root_view) override;
bool PreHandleGestureEvent(content::WebContents* source,
const blink::WebGestureEvent& event) override;
bool CanDragEnter(content::WebContents* source,
const content::DropData& data,
blink::WebDragOperationsMask operations_allowed) override;
bool is_type_tabbed() const { return type_ == TYPE_TABBED; }
bool is_type_popup() const { return type_ == TYPE_POPUP; }
bool is_app() const;
bool is_devtools() const;
// True when the mouse cursor is locked.
bool IsMouseLocked() const;
// Called each time the browser window is shown.
void OnWindowDidShow();
// Show the first run search engine bubble on the location bar.
void ShowFirstRunBubble();
// Show a download on the download shelf.
void ShowDownload(content::DownloadItem* download);
ExclusiveAccessManager* exclusive_access_manager() {
return exclusive_access_manager_.get();
}
extensions::WindowController* extension_window_controller() const {
return extension_window_controller_.get();
}
private:
friend class BrowserTest;
friend class FullscreenControllerInteractiveTest;
friend class FullscreenControllerTest;
FRIEND_TEST_ALL_PREFIXES(AppModeTest, EnableAppModeTest);
FRIEND_TEST_ALL_PREFIXES(BrowserCommandControllerTest,
IsReservedCommandOrKeyIsApp);
FRIEND_TEST_ALL_PREFIXES(BrowserCommandControllerTest, AppFullScreen);
FRIEND_TEST_ALL_PREFIXES(BrowserTest, NoTabsInPopups);
FRIEND_TEST_ALL_PREFIXES(BrowserTest, ConvertTabToAppShortcut);
FRIEND_TEST_ALL_PREFIXES(BrowserTest, OpenAppWindowLikeNtp);
FRIEND_TEST_ALL_PREFIXES(BrowserTest, AppIdSwitch);
FRIEND_TEST_ALL_PREFIXES(BrowserTest, ShouldShowLocationBar);
FRIEND_TEST_ALL_PREFIXES(ExclusiveAccessBubbleWindowControllerTest,
DenyExitsFullscreen);
FRIEND_TEST_ALL_PREFIXES(FullscreenControllerTest,
TabEntersPresentationModeFromWindowed);
FRIEND_TEST_ALL_PREFIXES(StartupBrowserCreatorTest, OpenAppShortcutNoPref);
FRIEND_TEST_ALL_PREFIXES(StartupBrowserCreatorTest,
OpenAppShortcutWindowPref);
FRIEND_TEST_ALL_PREFIXES(StartupBrowserCreatorTest, OpenAppShortcutTabPref);
class InterstitialObserver;
// Used to describe why a tab is being detached. This is used by
// TabDetachedAtImpl.
enum DetachType {
// Result of TabDetachedAt.
DETACH_TYPE_DETACH,
// Result of TabReplacedAt.
DETACH_TYPE_REPLACE,
// Result of the tab strip not having any significant tabs.
DETACH_TYPE_EMPTY
};
// Describes where the bookmark bar state change originated from.
enum BookmarkBarStateChangeReason {
// From the constructor.
BOOKMARK_BAR_STATE_CHANGE_INIT,
// Change is the result of the active tab changing.
BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH,
// Change is the result of the bookmark bar pref changing.
BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE,
// Change is the result of a state change in the active tab.
BOOKMARK_BAR_STATE_CHANGE_TAB_STATE,
// Change is the result of window toggling in/out of fullscreen mode.
BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN,
};
// Overridden from content::WebContentsDelegate:
content::WebContents* OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) override;
void NavigationStateChanged(content::WebContents* source,
content::InvalidateTypes changed_flags) override;
void VisibleSSLStateChanged(const content::WebContents* source) override;
void AddNewContents(content::WebContents* source,
content::WebContents* new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_rect,
bool user_gesture,
bool* was_blocked) override;
void ActivateContents(content::WebContents* contents) override;
void DeactivateContents(content::WebContents* contents) override;
void LoadingStateChanged(content::WebContents* source,
bool to_different_document) override;
void CloseContents(content::WebContents* source) override;
void MoveContents(content::WebContents* source,
const gfx::Rect& pos) override;
bool IsPopupOrPanel(const content::WebContents* source) const override;
void UpdateTargetURL(content::WebContents* source, const GURL& url) override;
void ContentsMouseEvent(content::WebContents* source,
const gfx::Point& location,
bool motion) override;
void ContentsZoomChange(bool zoom_in) override;
bool TakeFocus(content::WebContents* source, bool reverse) override;
gfx::Rect GetRootWindowResizerRect() const override;
void BeforeUnloadFired(content::WebContents* source,
bool proceed,
bool* proceed_to_fire_unload) override;
bool ShouldFocusLocationBarByDefault(content::WebContents* source) override;
void SetFocusToLocationBar(bool select_all) override;
void ViewSourceForTab(content::WebContents* source,
const GURL& page_url) override;
void ViewSourceForFrame(content::WebContents* source,
const GURL& frame_url,
const content::PageState& frame_page_state) override;
void ShowRepostFormWarningDialog(content::WebContents* source) override;
bool ShouldCreateWebContents(
content::WebContents* web_contents,
int route_id,
int main_frame_route_id,
WindowContainerType window_container_type,
const base::string16& frame_name,
const GURL& target_url,
const std::string& partition_id,
content::SessionStorageNamespace* session_storage_namespace) override;
void WebContentsCreated(content::WebContents* source_contents,
int opener_render_frame_id,
const base::string16& frame_name,
const GURL& target_url,
content::WebContents* new_contents) override;
void RendererUnresponsive(content::WebContents* source) override;
void RendererResponsive(content::WebContents* source) override;
void WorkerCrashed(content::WebContents* source) override;
void DidNavigateMainFramePostCommit(
content::WebContents* web_contents) override;
content::JavaScriptDialogManager* GetJavaScriptDialogManager(
content::WebContents* source) override;
content::ColorChooser* OpenColorChooser(
content::WebContents* web_contents,
SkColor color,
const std::vector<content::ColorSuggestion>& suggestions) override;
void RunFileChooser(content::WebContents* web_contents,
const content::FileChooserParams& params) override;
void EnumerateDirectory(content::WebContents* web_contents,
int request_id,
const base::FilePath& path) override;
bool EmbedsFullscreenWidget() const override;
void EnterFullscreenModeForTab(content::WebContents* web_contents,
const GURL& origin) override;
void ExitFullscreenModeForTab(content::WebContents* web_contents) override;
bool IsFullscreenForTabOrPending(
const content::WebContents* web_contents) const override;
void RegisterProtocolHandler(content::WebContents* web_contents,
const std::string& protocol,
const GURL& url,
bool user_gesture) override;
void UnregisterProtocolHandler(content::WebContents* web_contents,
const std::string& protocol,
const GURL& url,
bool user_gesture) override;
void UpdatePreferredSize(content::WebContents* source,
const gfx::Size& pref_size) override;
void ResizeDueToAutoResize(content::WebContents* source,
const gfx::Size& new_size) override;
void FindReply(content::WebContents* web_contents,
int request_id,
int number_of_matches,
const gfx::Rect& selection_rect,
int active_match_ordinal,
bool final_update) override;
void RequestToLockMouse(content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target) override;
void LostMouseLock() override;
void RequestMediaAccessPermission(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
const content::MediaResponseCallback& callback) override;
bool CheckMediaAccessPermission(content::WebContents* web_contents,
const GURL& security_origin,
content::MediaStreamType type) override;
bool RequestPpapiBrokerPermission(
content::WebContents* web_contents,
const GURL& url,
const base::FilePath& plugin_path,
const base::Callback<void(bool)>& callback) override;
gfx::Size GetSizeForNewRenderView(
content::WebContents* web_contents) const override;
// Overridden from CoreTabHelperDelegate:
// Note that the caller is responsible for deleting |old_contents|.
void SwapTabContents(content::WebContents* old_contents,
content::WebContents* new_contents,
bool did_start_load,
bool did_finish_load) override;
bool CanReloadContents(content::WebContents* web_contents) const override;
bool CanSaveContents(content::WebContents* web_contents) const override;
// Overridden from SearchEngineTabHelperDelegate:
void ConfirmAddSearchProvider(TemplateURL* template_url,
Profile* profile) override;
// Overridden from SearchTabHelperDelegate:
void NavigateOnThumbnailClick(const GURL& url,
WindowOpenDisposition disposition,
content::WebContents* source_contents) override;
void OnWebContentsInstantSupportDisabled(
const content::WebContents* web_contents) override;
OmniboxView* GetOmniboxView() override;
std::set<std::string> GetOpenUrls() override;
// Overridden from WebContentsModalDialogManagerDelegate:
void SetWebContentsBlocked(content::WebContents* web_contents,
bool blocked) override;
web_modal::WebContentsModalDialogHost* GetWebContentsModalDialogHost()
override;
// Overridden from BookmarkTabHelperDelegate:
void URLStarredChanged(content::WebContents* web_contents,
bool starred) override;
// Overridden from ZoomObserver:
void OnZoomChanged(
const ui_zoom::ZoomController::ZoomChangedEventData& data) override;
// Overridden from SelectFileDialog::Listener:
void FileSelected(const base::FilePath& path,
int index,
void* params) override;
void FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file_info,
int index,
void* params) override;
// Overridden from content::NotificationObserver:
void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) override;
#if defined(ENABLE_EXTENSIONS)
// Overridden from extensions::ExtensionRegistryObserver:
void OnExtensionUninstalled(content::BrowserContext* browser_context,
const extensions::Extension* extension,
extensions::UninstallReason reason) override;
void OnExtensionLoaded(content::BrowserContext* browser_context,
const extensions::Extension* extension) override;
void OnExtensionUnloaded(
content::BrowserContext* browser_context,
const extensions::Extension* extension,
extensions::UnloadedExtensionInfo::Reason reason) override;
#endif
// Overridden from translate::ContentTranslateDriver::Observer:
void OnIsPageTranslatedChanged(content::WebContents* source) override;
void OnTranslateEnabledChanged(content::WebContents* source) override;
// Command and state updating ///////////////////////////////////////////////
// Handle changes to kDevTools preference.
void OnDevToolsDisabledChanged();
// UI update coalescing and handling ////////////////////////////////////////
// Asks the toolbar (and as such the location bar) to update its state to
// reflect the current tab's current URL, security state, etc.
// If |should_restore_state| is true, we're switching (back?) to this tab and
// should restore any previous location bar state (such as user editing) as
// well.
void UpdateToolbar(bool should_restore_state);
// Does one or both of the following for each bit in |changed_flags|:
// . If the update should be processed immediately, it is.
// . If the update should processed asynchronously (to avoid lots of ui
// updates), then scheduled_updates_ is updated for the |source| and update
// pair and a task is scheduled (assuming it isn't running already)
// that invokes ProcessPendingUIUpdates.
void ScheduleUIUpdate(content::WebContents* source,
unsigned changed_flags);
// Processes all pending updates to the UI that have been scheduled by
// ScheduleUIUpdate in scheduled_updates_.
void ProcessPendingUIUpdates();
// Removes all entries from scheduled_updates_ whose source is contents.
void RemoveScheduledUpdatesFor(content::WebContents* contents);
// Getters for UI ///////////////////////////////////////////////////////////
// TODO(beng): remove, and provide AutomationProvider a better way to access
// the LocationBarView's edit.
friend class AutomationProvider;
friend class BrowserProxy;
// Returns the StatusBubble from the current toolbar. It is possible for
// this to return NULL if called before the toolbar has initialized.
// TODO(beng): remove this.
StatusBubble* GetStatusBubble();
// Session restore functions ////////////////////////////////////////////////
// Notifies the history database of the index for all tabs whose index is
// >= index.
void SyncHistoryWithTabs(int index);
// In-progress download termination handling /////////////////////////////////
// Called when the window is closing to check if potential in-progress
// downloads should prevent it from closing.
// Returns true if the window can close, false otherwise.
bool CanCloseWithInProgressDownloads();
// Assorted utility functions ///////////////////////////////////////////////
// Sets the specified browser as the delegate of the WebContents and all the
// associated tab helpers that are needed. If |set_delegate| is true, this
// browser object is set as a delegate for |web_contents| components, else
// is is removed as a delegate.
void SetAsDelegate(content::WebContents* web_contents, bool set_delegate);
// Shows the Find Bar, optionally selecting the next entry that matches the
// existing search string for that Tab. |forward_direction| controls the
// search direction.
void FindInPage(bool find_next, bool forward_direction);
// Closes the frame.
// TODO(beng): figure out if we need this now that the frame itself closes
// after a return to the message loop.
void CloseFrame();
void TabDetachedAtImpl(content::WebContents* contents,
int index,
DetachType type);
// Shared code between Reload() and ReloadIgnoringCache().
void ReloadInternal(WindowOpenDisposition disposition, bool ignore_cache);
// Returns true if the Browser window supports a location bar. Having support
// for the location bar does not mean it will be visible.
bool SupportsLocationBar() const;
// Returns true if the Browser window should show the location bar.
bool ShouldShowLocationBar() const;
// Returns true if the Browser window should use a web app style frame.
bool ShouldUseWebAppFrame() const;
// Implementation of SupportsWindowFeature and CanSupportWindowFeature. If
// |check_fullscreen| is true, the set of features reflect the actual state of
// the browser, otherwise the set of features reflect the possible state of
// the browser.
bool SupportsWindowFeatureImpl(WindowFeature feature,
bool check_fullscreen) const;
// Resets |bookmark_bar_state_| based on the active tab. Notifies the
// BrowserWindow if necessary.
void UpdateBookmarkBarState(BookmarkBarStateChangeReason reason);
bool ShouldHideUIForFullscreen() const;
// Creates a BackgroundContents if appropriate; return true if one was
// created.
bool MaybeCreateBackgroundContents(
int route_id,
int main_frame_route_id,
content::WebContents* opener_web_contents,
const base::string16& frame_name,
const GURL& target_url,
const std::string& partition_id,
content::SessionStorageNamespace* session_storage_namespace);
// Data members /////////////////////////////////////////////////////////////
std::vector<InterstitialObserver*> interstitial_observers_;
content::NotificationRegistrar registrar_;
#if defined(ENABLE_EXTENSIONS)
ScopedObserver<extensions::ExtensionRegistry,
extensions::ExtensionRegistryObserver>
extension_registry_observer_;
#endif
PrefChangeRegistrar profile_pref_registrar_;
// This Browser's type.
const Type type_;
// This Browser's profile.
Profile* const profile_;
// This Browser's window.
BrowserWindow* window_;
// Manages popup windows (bubbles, tab-modals) visible overlapping this
// window. JS alerts are not handled by this manager.
scoped_ptr<web_modal::PopupManager> popup_manager_;
scoped_ptr<TabStripModelDelegate> tab_strip_model_delegate_;
scoped_ptr<TabStripModel> tab_strip_model_;
// The application name that is also the name of the window to the shell.
// This name should be set when:
// 1) we launch an application via an application shortcut or extension API.
// 2) we launch an undocked devtool window.
std::string app_name_;
// True if the source is trusted (i.e. we do not need to show the URL in a
// a popup window). Also used to determine which app windows to save and
// restore on Chrome OS.
bool is_trusted_source_;
// Unique identifier of this browser for session restore. This id is only
// unique within the current session, and is not guaranteed to be unique
// across sessions.
const SessionID session_id_;
// The model for the toolbar view.
scoped_ptr<ToolbarModel> toolbar_model_;
// The model for the "active" search state. There are per-tab search models
// as well. When a tab is active its model is kept in sync with this one.
// When a new tab is activated its model state is propagated to this active
// model. This way, observers only have to attach to this single model for
// updates, and don't have to worry about active tab changes directly.
scoped_ptr<SearchModel> search_model_;
// UI update coalescing and handling ////////////////////////////////////////
typedef std::map<const content::WebContents*, int> UpdateMap;
// Maps from WebContents to pending UI updates that need to be processed.
// We don't update things like the URL or tab title right away to avoid
// flickering and extra painting.
// See ScheduleUIUpdate and ProcessPendingUIUpdates.
UpdateMap scheduled_updates_;
// In-progress download termination handling /////////////////////////////////
enum CancelDownloadConfirmationState {
NOT_PROMPTED, // We have not asked the user.
WAITING_FOR_RESPONSE, // We have asked the user and have not received a
// reponse yet.
RESPONSE_RECEIVED // The user was prompted and made a decision already.
};
// State used to figure-out whether we should prompt the user for confirmation
// when the browser is closed with in-progress downloads.
CancelDownloadConfirmationState cancel_download_confirmation_state_;
/////////////////////////////////////////////////////////////////////////////
// Override values for the bounds of the window and its maximized or minimized
// state.
// These are supplied by callers that don't want to use the default values.
// The default values are typically loaded from local state (last session),
// obtained from the last window of the same type, or obtained from the
// shell shortcut's startup info.
gfx::Rect override_bounds_;
ui::WindowShowState initial_show_state_;
// Tracks when this browser is being created by session restore.
bool is_session_restore_;
const chrome::HostDesktopType host_desktop_type_;
scoped_ptr<chrome::UnloadController> unload_controller_;
scoped_ptr<chrome::FastUnloadController> fast_unload_controller_;
// The Find Bar. This may be NULL if there is no Find Bar, and if it is
// non-NULL, it may or may not be visible.
scoped_ptr<FindBarController> find_bar_controller_;
// Dialog box used for opening and saving files.
scoped_refptr<ui::SelectFileDialog> select_file_dialog_;
// Keep track of the encoding auto detect pref.
BooleanPrefMember encoding_auto_detect_;
// Helper which implements the ContentSettingBubbleModel interface.
scoped_ptr<BrowserContentSettingBubbleModelDelegate>
content_setting_bubble_model_delegate_;
// Helper which implements the ToolbarModelDelegate interface.
scoped_ptr<BrowserToolbarModelDelegate> toolbar_model_delegate_;
// A delegate that handles the details of updating the "active"
// |search_model_| state with the tab's state.
scoped_ptr<SearchDelegate> search_delegate_;
// Helper which implements the TabRestoreServiceDelegate interface.
scoped_ptr<BrowserTabRestoreServiceDelegate> tab_restore_service_delegate_;
// Helper which implements the SyncedWindowDelegate interface.
scoped_ptr<BrowserSyncedWindowDelegate> synced_window_delegate_;
scoped_ptr<BrowserInstantController> instant_controller_;
// Helper which handles bookmark app specific browser configuration.
scoped_ptr<extensions::BookmarkAppBrowserController> bookmark_app_controller_;
BookmarkBar::State bookmark_bar_state_;
scoped_ptr<ExclusiveAccessManager> exclusive_access_manager_;
scoped_ptr<extensions::WindowController> extension_window_controller_;
scoped_ptr<chrome::BrowserCommandController> command_controller_;
// True if the browser window has been shown at least once.
bool window_has_shown_;
scoped_ptr<ValidationMessageBubble> validation_message_bubble_;
// The following factory is used for chrome update coalescing.
base::WeakPtrFactory<Browser> chrome_updater_factory_;
// The following factory is used to close the frame at a later time.
base::WeakPtrFactory<Browser> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(Browser);
};
#endif // CHROME_BROWSER_UI_BROWSER_H_
| ltilve/chromium | chrome/browser/ui/browser.h | C | bsd-3-clause | 40,773 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/quic/crypto/quic_crypto_server_config.h"
#include <stdlib.h>
#include <algorithm>
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "crypto/hkdf.h"
#include "crypto/secure_hash.h"
#include "net/base/ip_address.h"
#include "net/quic/crypto/aes_128_gcm_12_decrypter.h"
#include "net/quic/crypto/aes_128_gcm_12_encrypter.h"
#include "net/quic/crypto/cert_compressor.h"
#include "net/quic/crypto/chacha20_poly1305_rfc7539_encrypter.h"
#include "net/quic/crypto/channel_id.h"
#include "net/quic/crypto/crypto_framer.h"
#include "net/quic/crypto/crypto_handshake_message.h"
#include "net/quic/crypto/crypto_server_config_protobuf.h"
#include "net/quic/crypto/crypto_utils.h"
#include "net/quic/crypto/curve25519_key_exchange.h"
#include "net/quic/crypto/ephemeral_key_source.h"
#include "net/quic/crypto/key_exchange.h"
#include "net/quic/crypto/local_strike_register_client.h"
#include "net/quic/crypto/p256_key_exchange.h"
#include "net/quic/crypto/proof_source.h"
#include "net/quic/crypto/quic_decrypter.h"
#include "net/quic/crypto/quic_encrypter.h"
#include "net/quic/crypto/quic_random.h"
#include "net/quic/crypto/strike_register.h"
#include "net/quic/crypto/strike_register_client.h"
#include "net/quic/proto/source_address_token.pb.h"
#include "net/quic/quic_bug_tracker.h"
#include "net/quic/quic_clock.h"
#include "net/quic/quic_flags.h"
#include "net/quic/quic_protocol.h"
#include "net/quic/quic_socket_address_coder.h"
#include "net/quic/quic_utils.h"
using base::StringPiece;
using crypto::SecureHash;
using std::map;
using std::sort;
using std::string;
using std::vector;
namespace net {
namespace {
// kMultiplier is the multiple of the CHLO message size that a REJ message
// must stay under when the client doesn't present a valid source-address
// token. This is used to protect QUIC from amplification attacks.
// TODO(rch): Reduce this to 2 again once b/25933682 is fixed.
const size_t kMultiplier = 3;
const int kMaxTokenAddresses = 4;
string DeriveSourceAddressTokenKey(StringPiece source_address_token_secret) {
crypto::HKDF hkdf(source_address_token_secret, StringPiece() /* no salt */,
"QUIC source address token key",
CryptoSecretBoxer::GetKeySize(), 0 /* no fixed IV needed */,
0 /* no subkey secret */);
return hkdf.server_write_key().as_string();
}
IPAddress DualstackIPAddress(const IPAddress& ip) {
if (ip.IsIPv4()) {
return ConvertIPv4ToIPv4MappedIPv6(ip);
}
return ip;
}
} // namespace
class ValidateClientHelloHelper {
public:
ValidateClientHelloHelper(ValidateClientHelloResultCallback::Result* result,
ValidateClientHelloResultCallback* done_cb)
: result_(result), done_cb_(done_cb) {}
~ValidateClientHelloHelper() {
QUIC_BUG_IF(done_cb_ != nullptr)
<< "Deleting ValidateClientHelloHelper with a pending callback.";
}
void ValidationComplete(QuicErrorCode error_code, const char* error_details) {
result_->error_code = error_code;
result_->error_details = error_details;
done_cb_->Run(result_);
DetachCallback();
}
void StartedAsyncCallback() { DetachCallback(); }
private:
void DetachCallback() {
QUIC_BUG_IF(done_cb_ == nullptr) << "Callback already detached.";
done_cb_ = nullptr;
}
ValidateClientHelloResultCallback::Result* result_;
ValidateClientHelloResultCallback* done_cb_;
DISALLOW_COPY_AND_ASSIGN(ValidateClientHelloHelper);
};
class VerifyNonceIsValidAndUniqueCallback
: public StrikeRegisterClient::ResultCallback {
public:
VerifyNonceIsValidAndUniqueCallback(
ValidateClientHelloResultCallback::Result* result,
ValidateClientHelloResultCallback* done_cb)
: result_(result), done_cb_(done_cb) {}
protected:
void RunImpl(bool nonce_is_valid_and_unique,
InsertStatus nonce_error) override {
DVLOG(1) << "Using client nonce, unique: " << nonce_is_valid_and_unique
<< " nonce_error: " << nonce_error;
if (!nonce_is_valid_and_unique) {
HandshakeFailureReason client_nonce_error;
switch (nonce_error) {
case NONCE_INVALID_FAILURE:
client_nonce_error = CLIENT_NONCE_INVALID_FAILURE;
break;
case NONCE_NOT_UNIQUE_FAILURE:
client_nonce_error = CLIENT_NONCE_NOT_UNIQUE_FAILURE;
break;
case NONCE_INVALID_ORBIT_FAILURE:
client_nonce_error = CLIENT_NONCE_INVALID_ORBIT_FAILURE;
break;
case NONCE_INVALID_TIME_FAILURE:
client_nonce_error = CLIENT_NONCE_INVALID_TIME_FAILURE;
break;
case STRIKE_REGISTER_TIMEOUT:
client_nonce_error = CLIENT_NONCE_STRIKE_REGISTER_TIMEOUT;
break;
case STRIKE_REGISTER_FAILURE:
client_nonce_error = CLIENT_NONCE_STRIKE_REGISTER_FAILURE;
break;
case NONCE_UNKNOWN_FAILURE:
client_nonce_error = CLIENT_NONCE_UNKNOWN_FAILURE;
break;
case NONCE_OK:
default:
QUIC_BUG << "Unexpected client nonce error: " << nonce_error;
client_nonce_error = CLIENT_NONCE_UNKNOWN_FAILURE;
break;
}
result_->info.reject_reasons.push_back(client_nonce_error);
}
done_cb_->Run(result_);
}
private:
ValidateClientHelloResultCallback::Result* result_;
ValidateClientHelloResultCallback* done_cb_;
DISALLOW_COPY_AND_ASSIGN(VerifyNonceIsValidAndUniqueCallback);
};
// static
const char QuicCryptoServerConfig::TESTING[] = "secret string for testing";
ClientHelloInfo::ClientHelloInfo(const IPAddress& in_client_ip,
QuicWallTime in_now)
: client_ip(in_client_ip), now(in_now), valid_source_address_token(false) {}
ClientHelloInfo::~ClientHelloInfo() {}
PrimaryConfigChangedCallback::PrimaryConfigChangedCallback() {}
PrimaryConfigChangedCallback::~PrimaryConfigChangedCallback() {}
ValidateClientHelloResultCallback::Result::Result(
const CryptoHandshakeMessage& in_client_hello,
IPAddress in_client_ip,
QuicWallTime in_now)
: client_hello(in_client_hello),
info(in_client_ip, in_now),
error_code(QUIC_NO_ERROR) {}
ValidateClientHelloResultCallback::Result::~Result() {}
ValidateClientHelloResultCallback::ValidateClientHelloResultCallback() {}
ValidateClientHelloResultCallback::~ValidateClientHelloResultCallback() {}
void ValidateClientHelloResultCallback::Run(const Result* result) {
RunImpl(result->client_hello, *result);
delete result;
delete this;
}
QuicCryptoServerConfig::ConfigOptions::ConfigOptions()
: expiry_time(QuicWallTime::Zero()),
channel_id_enabled(false),
token_binding_enabled(false),
p256(false) {}
QuicCryptoServerConfig::ConfigOptions::ConfigOptions(
const ConfigOptions& other) = default;
QuicCryptoServerConfig::QuicCryptoServerConfig(
StringPiece source_address_token_secret,
QuicRandom* server_nonce_entropy,
ProofSource* proof_source)
: replay_protection_(true),
chlo_multiplier_(kMultiplier),
configs_lock_(),
primary_config_(nullptr),
next_config_promotion_time_(QuicWallTime::Zero()),
server_nonce_strike_register_lock_(),
proof_source_(proof_source),
strike_register_no_startup_period_(false),
strike_register_max_entries_(1 << 10),
strike_register_window_secs_(600),
source_address_token_future_secs_(3600),
source_address_token_lifetime_secs_(86400),
server_nonce_strike_register_max_entries_(1 << 10),
server_nonce_strike_register_window_secs_(120),
enable_serving_sct_(false) {
DCHECK(proof_source_.get());
default_source_address_token_boxer_.SetKeys(
{DeriveSourceAddressTokenKey(source_address_token_secret)});
// Generate a random key and orbit for server nonces.
server_nonce_entropy->RandBytes(server_nonce_orbit_,
sizeof(server_nonce_orbit_));
const size_t key_size = server_nonce_boxer_.GetKeySize();
scoped_ptr<uint8_t[]> key_bytes(new uint8_t[key_size]);
server_nonce_entropy->RandBytes(key_bytes.get(), key_size);
server_nonce_boxer_.SetKeys(
{string(reinterpret_cast<char*>(key_bytes.get()), key_size)});
}
QuicCryptoServerConfig::~QuicCryptoServerConfig() {
primary_config_ = nullptr;
}
// static
QuicServerConfigProtobuf* QuicCryptoServerConfig::GenerateConfig(
QuicRandom* rand,
const QuicClock* clock,
const ConfigOptions& options) {
CryptoHandshakeMessage msg;
const string curve25519_private_key =
Curve25519KeyExchange::NewPrivateKey(rand);
scoped_ptr<Curve25519KeyExchange> curve25519(
Curve25519KeyExchange::New(curve25519_private_key));
StringPiece curve25519_public_value = curve25519->public_value();
string encoded_public_values;
// First three bytes encode the length of the public value.
DCHECK_LT(curve25519_public_value.size(), (1U << 24));
encoded_public_values.push_back(
static_cast<char>(curve25519_public_value.size()));
encoded_public_values.push_back(
static_cast<char>(curve25519_public_value.size() >> 8));
encoded_public_values.push_back(
static_cast<char>(curve25519_public_value.size() >> 16));
encoded_public_values.append(curve25519_public_value.data(),
curve25519_public_value.size());
string p256_private_key;
if (options.p256) {
p256_private_key = P256KeyExchange::NewPrivateKey();
scoped_ptr<P256KeyExchange> p256(P256KeyExchange::New(p256_private_key));
StringPiece p256_public_value = p256->public_value();
DCHECK_LT(p256_public_value.size(), (1U << 24));
encoded_public_values.push_back(
static_cast<char>(p256_public_value.size()));
encoded_public_values.push_back(
static_cast<char>(p256_public_value.size() >> 8));
encoded_public_values.push_back(
static_cast<char>(p256_public_value.size() >> 16));
encoded_public_values.append(p256_public_value.data(),
p256_public_value.size());
}
msg.set_tag(kSCFG);
if (options.p256) {
msg.SetTaglist(kKEXS, kC255, kP256, 0);
} else {
msg.SetTaglist(kKEXS, kC255, 0);
}
if (FLAGS_quic_crypto_server_config_default_has_chacha20 &&
ChaCha20Poly1305Rfc7539Encrypter::IsSupported()) {
msg.SetTaglist(kAEAD, kAESG, kCC20, 0);
} else {
msg.SetTaglist(kAEAD, kAESG, 0);
}
msg.SetStringPiece(kPUBS, encoded_public_values);
if (options.expiry_time.IsZero()) {
const QuicWallTime now = clock->WallNow();
const QuicWallTime expiry = now.Add(QuicTime::Delta::FromSeconds(
60 * 60 * 24 * 180 /* 180 days, ~six months */));
const uint64_t expiry_seconds = expiry.ToUNIXSeconds();
msg.SetValue(kEXPY, expiry_seconds);
} else {
msg.SetValue(kEXPY, options.expiry_time.ToUNIXSeconds());
}
char orbit_bytes[kOrbitSize];
if (options.orbit.size() == sizeof(orbit_bytes)) {
memcpy(orbit_bytes, options.orbit.data(), sizeof(orbit_bytes));
} else {
DCHECK(options.orbit.empty());
rand->RandBytes(orbit_bytes, sizeof(orbit_bytes));
}
msg.SetStringPiece(kORBT, StringPiece(orbit_bytes, sizeof(orbit_bytes)));
if (options.channel_id_enabled) {
msg.SetTaglist(kPDMD, kCHID, 0);
}
if (options.token_binding_enabled) {
msg.SetTaglist(kTBKP, kP256, 0);
}
if (options.id.empty()) {
// We need to ensure that the SCID changes whenever the server config does
// thus we make it a hash of the rest of the server config.
scoped_ptr<QuicData> serialized(
CryptoFramer::ConstructHandshakeMessage(msg));
scoped_ptr<SecureHash> hash(SecureHash::Create(SecureHash::SHA256));
hash->Update(serialized->data(), serialized->length());
char scid_bytes[16];
hash->Finish(scid_bytes, sizeof(scid_bytes));
msg.SetStringPiece(kSCID, StringPiece(scid_bytes, sizeof(scid_bytes)));
} else {
msg.SetStringPiece(kSCID, options.id);
}
// Don't put new tags below this point. The SCID generation should hash over
// everything but itself and so extra tags should be added prior to the
// preceeding if block.
scoped_ptr<QuicData> serialized(CryptoFramer::ConstructHandshakeMessage(msg));
scoped_ptr<QuicServerConfigProtobuf> config(new QuicServerConfigProtobuf);
config->set_config(serialized->AsStringPiece());
QuicServerConfigProtobuf::PrivateKey* curve25519_key = config->add_key();
curve25519_key->set_tag(kC255);
curve25519_key->set_private_key(curve25519_private_key);
if (options.p256) {
QuicServerConfigProtobuf::PrivateKey* p256_key = config->add_key();
p256_key->set_tag(kP256);
p256_key->set_private_key(p256_private_key);
}
return config.release();
}
CryptoHandshakeMessage* QuicCryptoServerConfig::AddConfig(
QuicServerConfigProtobuf* protobuf,
const QuicWallTime now) {
scoped_ptr<CryptoHandshakeMessage> msg(
CryptoFramer::ParseMessage(protobuf->config()));
if (!msg.get()) {
LOG(WARNING) << "Failed to parse server config message";
return nullptr;
}
scoped_refptr<Config> config(ParseConfigProtobuf(protobuf));
if (!config.get()) {
LOG(WARNING) << "Failed to parse server config message";
return nullptr;
}
{
base::AutoLock locked(configs_lock_);
if (configs_.find(config->id) != configs_.end()) {
LOG(WARNING) << "Failed to add config because another with the same "
"server config id already exists: "
<< base::HexEncode(config->id.data(), config->id.size());
return nullptr;
}
configs_[config->id] = config;
SelectNewPrimaryConfig(now);
DCHECK(primary_config_.get());
DCHECK_EQ(configs_.find(primary_config_->id)->second, primary_config_);
}
return msg.release();
}
CryptoHandshakeMessage* QuicCryptoServerConfig::AddDefaultConfig(
QuicRandom* rand,
const QuicClock* clock,
const ConfigOptions& options) {
scoped_ptr<QuicServerConfigProtobuf> config(
GenerateConfig(rand, clock, options));
return AddConfig(config.get(), clock->WallNow());
}
bool QuicCryptoServerConfig::SetConfigs(
const vector<QuicServerConfigProtobuf*>& protobufs,
const QuicWallTime now) {
vector<scoped_refptr<Config>> parsed_configs;
bool ok = true;
for (vector<QuicServerConfigProtobuf*>::const_iterator i = protobufs.begin();
i != protobufs.end(); ++i) {
scoped_refptr<Config> config(ParseConfigProtobuf(*i));
if (!config.get()) {
ok = false;
break;
}
parsed_configs.push_back(config);
}
if (parsed_configs.empty()) {
LOG(WARNING) << "New config list is empty.";
ok = false;
}
if (!ok) {
LOG(WARNING) << "Rejecting QUIC configs because of above errors";
} else {
VLOG(1) << "Updating configs:";
base::AutoLock locked(configs_lock_);
ConfigMap new_configs;
for (vector<scoped_refptr<Config>>::const_iterator i =
parsed_configs.begin();
i != parsed_configs.end(); ++i) {
scoped_refptr<Config> config = *i;
ConfigMap::iterator it = configs_.find(config->id);
if (it != configs_.end()) {
VLOG(1) << "Keeping scid: "
<< base::HexEncode(config->id.data(), config->id.size())
<< " orbit: "
<< base::HexEncode(reinterpret_cast<const char*>(config->orbit),
kOrbitSize)
<< " new primary_time " << config->primary_time.ToUNIXSeconds()
<< " old primary_time "
<< it->second->primary_time.ToUNIXSeconds() << " new priority "
<< config->priority << " old priority " << it->second->priority;
// Update primary_time and priority.
it->second->primary_time = config->primary_time;
it->second->priority = config->priority;
new_configs.insert(*it);
} else {
VLOG(1) << "Adding scid: "
<< base::HexEncode(config->id.data(), config->id.size())
<< " orbit: "
<< base::HexEncode(reinterpret_cast<const char*>(config->orbit),
kOrbitSize)
<< " primary_time " << config->primary_time.ToUNIXSeconds()
<< " priority " << config->priority;
new_configs.insert(std::make_pair(config->id, config));
}
}
configs_.swap(new_configs);
SelectNewPrimaryConfig(now);
DCHECK(primary_config_.get());
DCHECK_EQ(configs_.find(primary_config_->id)->second, primary_config_);
}
return ok;
}
void QuicCryptoServerConfig::SetDefaultSourceAddressTokenKeys(
const vector<string>& keys) {
default_source_address_token_boxer_.SetKeys(keys);
}
void QuicCryptoServerConfig::GetConfigIds(vector<string>* scids) const {
base::AutoLock locked(configs_lock_);
for (ConfigMap::const_iterator it = configs_.begin(); it != configs_.end();
++it) {
scids->push_back(it->first);
}
}
void QuicCryptoServerConfig::ValidateClientHello(
const CryptoHandshakeMessage& client_hello,
const IPAddress& client_ip,
const IPAddress& server_ip,
QuicVersion version,
const QuicClock* clock,
QuicCryptoProof* crypto_proof,
ValidateClientHelloResultCallback* done_cb) const {
const QuicWallTime now(clock->WallNow());
ValidateClientHelloResultCallback::Result* result =
new ValidateClientHelloResultCallback::Result(client_hello, client_ip,
now);
StringPiece requested_scid;
client_hello.GetStringPiece(kSCID, &requested_scid);
uint8_t primary_orbit[kOrbitSize];
scoped_refptr<Config> requested_config;
scoped_refptr<Config> primary_config;
{
base::AutoLock locked(configs_lock_);
if (!primary_config_.get()) {
result->error_code = QUIC_CRYPTO_INTERNAL_ERROR;
result->error_details = "No configurations loaded";
} else {
if (!next_config_promotion_time_.IsZero() &&
next_config_promotion_time_.IsAfter(now)) {
SelectNewPrimaryConfig(now);
DCHECK(primary_config_.get());
DCHECK_EQ(configs_.find(primary_config_->id)->second, primary_config_);
}
memcpy(primary_orbit, primary_config_->orbit, sizeof(primary_orbit));
}
requested_config = GetConfigWithScid(requested_scid);
primary_config = primary_config_;
crypto_proof->config = primary_config_;
}
if (result->error_code == QUIC_NO_ERROR) {
EvaluateClientHello(server_ip, version, primary_orbit, requested_config,
primary_config, crypto_proof, result, done_cb);
} else {
done_cb->Run(result);
}
}
QuicErrorCode QuicCryptoServerConfig::ProcessClientHello(
const ValidateClientHelloResultCallback::Result& validate_chlo_result,
QuicConnectionId connection_id,
const IPAddress& server_ip,
const IPEndPoint& client_address,
QuicVersion version,
const QuicVersionVector& supported_versions,
bool use_stateless_rejects,
QuicConnectionId server_designated_connection_id,
const QuicClock* clock,
QuicRandom* rand,
QuicCompressedCertsCache* compressed_certs_cache,
QuicCryptoNegotiatedParameters* params,
QuicCryptoProof* crypto_proof,
CryptoHandshakeMessage* out,
string* error_details) const {
DCHECK(error_details);
const CryptoHandshakeMessage& client_hello =
validate_chlo_result.client_hello;
const ClientHelloInfo& info = validate_chlo_result.info;
QuicErrorCode valid = CryptoUtils::ValidateClientHello(
client_hello, version, supported_versions, error_details);
if (valid != QUIC_NO_ERROR)
return valid;
StringPiece requested_scid;
client_hello.GetStringPiece(kSCID, &requested_scid);
const QuicWallTime now(clock->WallNow());
scoped_refptr<Config> requested_config;
scoped_refptr<Config> primary_config;
{
base::AutoLock locked(configs_lock_);
if (!primary_config_.get()) {
*error_details = "No configurations loaded";
return QUIC_CRYPTO_INTERNAL_ERROR;
}
if (!next_config_promotion_time_.IsZero() &&
next_config_promotion_time_.IsAfter(now)) {
SelectNewPrimaryConfig(now);
DCHECK(primary_config_.get());
DCHECK_EQ(configs_.find(primary_config_->id)->second, primary_config_);
}
// Use the config that the client requested in order to do key-agreement.
// Otherwise give it a copy of |primary_config_| to use.
primary_config = crypto_proof->config;
requested_config = GetConfigWithScid(requested_scid);
}
if (validate_chlo_result.error_code != QUIC_NO_ERROR) {
*error_details = validate_chlo_result.error_details;
return validate_chlo_result.error_code;
}
out->Clear();
bool x509_supported = false;
bool x509_ecdsa_supported = false;
ParseProofDemand(client_hello, &x509_supported, &x509_ecdsa_supported);
DCHECK(proof_source_.get());
string chlo_hash;
CryptoUtils::HashHandshakeMessage(client_hello, &chlo_hash);
if (!crypto_proof->chain &&
!proof_source_->GetProof(
server_ip, info.sni.as_string(), primary_config->serialized, version,
chlo_hash, x509_ecdsa_supported, &crypto_proof->chain,
&crypto_proof->signature, &crypto_proof->cert_sct)) {
return QUIC_HANDSHAKE_FAILED;
}
if (version > QUIC_VERSION_29) {
StringPiece cert_sct;
if (client_hello.GetStringPiece(kCertificateSCTTag, &cert_sct) &&
cert_sct.empty()) {
params->sct_supported_by_client = true;
}
}
if (!info.reject_reasons.empty() || !requested_config.get()) {
BuildRejection(version, *primary_config, client_hello, info,
validate_chlo_result.cached_network_params,
use_stateless_rejects, server_designated_connection_id, rand,
compressed_certs_cache, params, *crypto_proof, out);
return QUIC_NO_ERROR;
}
const QuicTag* their_aeads;
const QuicTag* their_key_exchanges;
size_t num_their_aeads, num_their_key_exchanges;
if (client_hello.GetTaglist(kAEAD, &their_aeads, &num_their_aeads) !=
QUIC_NO_ERROR ||
client_hello.GetTaglist(kKEXS, &their_key_exchanges,
&num_their_key_exchanges) != QUIC_NO_ERROR ||
num_their_aeads != 1 || num_their_key_exchanges != 1) {
*error_details = "Missing or invalid AEAD or KEXS";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
size_t key_exchange_index;
if (!QuicUtils::FindMutualTag(requested_config->aead, their_aeads,
num_their_aeads, QuicUtils::LOCAL_PRIORITY,
¶ms->aead, nullptr) ||
!QuicUtils::FindMutualTag(requested_config->kexs, their_key_exchanges,
num_their_key_exchanges,
QuicUtils::LOCAL_PRIORITY,
¶ms->key_exchange, &key_exchange_index)) {
*error_details = "Unsupported AEAD or KEXS";
return QUIC_CRYPTO_NO_SUPPORT;
}
if (!requested_config->tb_key_params.empty()) {
const QuicTag* their_tbkps;
size_t num_their_tbkps;
switch (client_hello.GetTaglist(kTBKP, &their_tbkps, &num_their_tbkps)) {
case QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND:
break;
case QUIC_NO_ERROR:
if (QuicUtils::FindMutualTag(
requested_config->tb_key_params, their_tbkps, num_their_tbkps,
QuicUtils::LOCAL_PRIORITY, ¶ms->token_binding_key_param,
nullptr)) {
break;
}
default:
*error_details = "Invalid Token Binding key parameter";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
}
StringPiece public_value;
if (!client_hello.GetStringPiece(kPUBS, &public_value)) {
*error_details = "Missing public value";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
const KeyExchange* key_exchange =
requested_config->key_exchanges[key_exchange_index];
if (!key_exchange->CalculateSharedKey(public_value,
¶ms->initial_premaster_secret)) {
*error_details = "Invalid public value";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
if (!info.sni.empty()) {
scoped_ptr<char[]> sni_tmp(new char[info.sni.length() + 1]);
memcpy(sni_tmp.get(), info.sni.data(), info.sni.length());
sni_tmp[info.sni.length()] = 0;
params->sni = CryptoUtils::NormalizeHostname(sni_tmp.get());
}
string hkdf_suffix;
const QuicData& client_hello_serialized = client_hello.GetSerialized();
hkdf_suffix.reserve(sizeof(connection_id) + client_hello_serialized.length() +
requested_config->serialized.size());
hkdf_suffix.append(reinterpret_cast<char*>(&connection_id),
sizeof(connection_id));
hkdf_suffix.append(client_hello_serialized.data(),
client_hello_serialized.length());
hkdf_suffix.append(requested_config->serialized);
DCHECK(proof_source_.get());
if (version > QUIC_VERSION_25) {
if (crypto_proof->chain->certs.empty()) {
*error_details = "Failed to get certs";
return QUIC_CRYPTO_INTERNAL_ERROR;
}
hkdf_suffix.append(crypto_proof->chain->certs.at(0));
}
StringPiece cetv_ciphertext;
if (requested_config->channel_id_enabled &&
client_hello.GetStringPiece(kCETV, &cetv_ciphertext)) {
CryptoHandshakeMessage client_hello_copy(client_hello);
client_hello_copy.Erase(kCETV);
client_hello_copy.Erase(kPAD);
const QuicData& client_hello_copy_serialized =
client_hello_copy.GetSerialized();
string hkdf_input;
hkdf_input.append(QuicCryptoConfig::kCETVLabel,
strlen(QuicCryptoConfig::kCETVLabel) + 1);
hkdf_input.append(reinterpret_cast<char*>(&connection_id),
sizeof(connection_id));
hkdf_input.append(client_hello_copy_serialized.data(),
client_hello_copy_serialized.length());
hkdf_input.append(requested_config->serialized);
CrypterPair crypters;
if (!CryptoUtils::DeriveKeys(params->initial_premaster_secret, params->aead,
info.client_nonce, info.server_nonce,
hkdf_input, Perspective::IS_SERVER, &crypters,
nullptr /* subkey secret */)) {
*error_details = "Symmetric key setup failed";
return QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED;
}
char plaintext[kMaxPacketSize];
size_t plaintext_length = 0;
const bool success = crypters.decrypter->DecryptPacket(
kDefaultPathId, 0 /* packet number */,
StringPiece() /* associated data */, cetv_ciphertext, plaintext,
&plaintext_length, kMaxPacketSize);
if (!success) {
*error_details = "CETV decryption failure";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
scoped_ptr<CryptoHandshakeMessage> cetv(
CryptoFramer::ParseMessage(StringPiece(plaintext, plaintext_length)));
if (!cetv.get()) {
*error_details = "CETV parse error";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
StringPiece key, signature;
if (cetv->GetStringPiece(kCIDK, &key) &&
cetv->GetStringPiece(kCIDS, &signature)) {
if (!ChannelIDVerifier::Verify(key, hkdf_input, signature)) {
*error_details = "ChannelID signature failure";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
params->channel_id = key.as_string();
}
}
string hkdf_input;
size_t label_len = strlen(QuicCryptoConfig::kInitialLabel) + 1;
hkdf_input.reserve(label_len + hkdf_suffix.size());
hkdf_input.append(QuicCryptoConfig::kInitialLabel, label_len);
hkdf_input.append(hkdf_suffix);
string* subkey_secret = ¶ms->initial_subkey_secret;
if (!CryptoUtils::DeriveKeys(params->initial_premaster_secret, params->aead,
info.client_nonce, info.server_nonce, hkdf_input,
Perspective::IS_SERVER,
¶ms->initial_crypters, subkey_secret)) {
*error_details = "Symmetric key setup failed";
return QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED;
}
string forward_secure_public_value;
if (ephemeral_key_source_.get()) {
params->forward_secure_premaster_secret =
ephemeral_key_source_->CalculateForwardSecureKey(
key_exchange, rand, clock->ApproximateNow(), public_value,
&forward_secure_public_value);
} else {
scoped_ptr<KeyExchange> forward_secure_key_exchange(
key_exchange->NewKeyPair(rand));
forward_secure_public_value =
forward_secure_key_exchange->public_value().as_string();
if (!forward_secure_key_exchange->CalculateSharedKey(
public_value, ¶ms->forward_secure_premaster_secret)) {
*error_details = "Invalid public value";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
}
string forward_secure_hkdf_input;
label_len = strlen(QuicCryptoConfig::kForwardSecureLabel) + 1;
forward_secure_hkdf_input.reserve(label_len + hkdf_suffix.size());
forward_secure_hkdf_input.append(QuicCryptoConfig::kForwardSecureLabel,
label_len);
forward_secure_hkdf_input.append(hkdf_suffix);
string shlo_nonce;
if (version > QUIC_VERSION_26) {
shlo_nonce = NewServerNonce(rand, info.now);
out->SetStringPiece(kServerNonceTag, shlo_nonce);
}
if (!CryptoUtils::DeriveKeys(
params->forward_secure_premaster_secret, params->aead,
info.client_nonce,
shlo_nonce.empty() ? info.server_nonce : shlo_nonce,
forward_secure_hkdf_input, Perspective::IS_SERVER,
¶ms->forward_secure_crypters, ¶ms->subkey_secret)) {
*error_details = "Symmetric key setup failed";
return QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED;
}
out->set_tag(kSHLO);
QuicTagVector supported_version_tags;
for (size_t i = 0; i < supported_versions.size(); ++i) {
supported_version_tags.push_back(
QuicVersionToQuicTag(supported_versions[i]));
}
out->SetVector(kVER, supported_version_tags);
out->SetStringPiece(
kSourceAddressTokenTag,
NewSourceAddressToken(*requested_config.get(), info.source_address_tokens,
client_address.address(), rand, info.now, nullptr));
QuicSocketAddressCoder address_coder(client_address);
out->SetStringPiece(kCADR, address_coder.Encode());
out->SetStringPiece(kPUBS, forward_secure_public_value);
return QUIC_NO_ERROR;
}
scoped_refptr<QuicCryptoServerConfig::Config>
QuicCryptoServerConfig::GetConfigWithScid(StringPiece requested_scid) const {
// In Chromium, we will dead lock if the lock is held by the current thread.
// Chromium doesn't have AssertReaderHeld API call.
// configs_lock_.AssertReaderHeld();
if (!requested_scid.empty()) {
ConfigMap::const_iterator it = configs_.find(requested_scid.as_string());
if (it != configs_.end()) {
// We'll use the config that the client requested in order to do
// key-agreement.
return scoped_refptr<Config>(it->second);
}
}
return scoped_refptr<Config>();
}
// ConfigPrimaryTimeLessThan is a comparator that implements "less than" for
// Config's based on their primary_time.
// static
bool QuicCryptoServerConfig::ConfigPrimaryTimeLessThan(
const scoped_refptr<Config>& a,
const scoped_refptr<Config>& b) {
if (a->primary_time.IsBefore(b->primary_time) ||
b->primary_time.IsBefore(a->primary_time)) {
// Primary times differ.
return a->primary_time.IsBefore(b->primary_time);
} else if (a->priority != b->priority) {
// Primary times are equal, sort backwards by priority.
return a->priority < b->priority;
} else {
// Primary times and priorities are equal, sort by config id.
return a->id < b->id;
}
}
void QuicCryptoServerConfig::SelectNewPrimaryConfig(
const QuicWallTime now) const {
vector<scoped_refptr<Config>> configs;
configs.reserve(configs_.size());
for (ConfigMap::const_iterator it = configs_.begin(); it != configs_.end();
++it) {
// TODO(avd) Exclude expired configs?
configs.push_back(it->second);
}
if (configs.empty()) {
if (primary_config_.get()) {
QUIC_BUG << "No valid QUIC server config. Keeping the current config.";
} else {
QUIC_BUG << "No valid QUIC server config.";
}
return;
}
std::sort(configs.begin(), configs.end(), ConfigPrimaryTimeLessThan);
Config* best_candidate = configs[0].get();
for (size_t i = 0; i < configs.size(); ++i) {
const scoped_refptr<Config> config(configs[i]);
if (!config->primary_time.IsAfter(now)) {
if (config->primary_time.IsAfter(best_candidate->primary_time)) {
best_candidate = config.get();
}
continue;
}
// This is the first config with a primary_time in the future. Thus the
// previous Config should be the primary and this one should determine the
// next_config_promotion_time_.
scoped_refptr<Config> new_primary(best_candidate);
if (i == 0) {
// We need the primary_time of the next config.
if (configs.size() > 1) {
next_config_promotion_time_ = configs[1]->primary_time;
} else {
next_config_promotion_time_ = QuicWallTime::Zero();
}
} else {
next_config_promotion_time_ = config->primary_time;
}
if (primary_config_.get()) {
primary_config_->is_primary = false;
}
primary_config_ = new_primary;
new_primary->is_primary = true;
DVLOG(1) << "New primary config. orbit: "
<< base::HexEncode(
reinterpret_cast<const char*>(primary_config_->orbit),
kOrbitSize);
if (primary_config_changed_cb_.get() != nullptr) {
primary_config_changed_cb_->Run(primary_config_->id);
}
return;
}
// All config's primary times are in the past. We should make the most recent
// and highest priority candidate primary.
scoped_refptr<Config> new_primary(best_candidate);
if (primary_config_.get()) {
primary_config_->is_primary = false;
}
primary_config_ = new_primary;
new_primary->is_primary = true;
DVLOG(1) << "New primary config. orbit: "
<< base::HexEncode(
reinterpret_cast<const char*>(primary_config_->orbit),
kOrbitSize)
<< " scid: " << base::HexEncode(primary_config_->id.data(),
primary_config_->id.size());
next_config_promotion_time_ = QuicWallTime::Zero();
if (primary_config_changed_cb_.get() != nullptr) {
primary_config_changed_cb_->Run(primary_config_->id);
}
}
void QuicCryptoServerConfig::EvaluateClientHello(
const IPAddress& server_ip,
QuicVersion version,
const uint8_t* primary_orbit,
scoped_refptr<Config> requested_config,
scoped_refptr<Config> primary_config,
QuicCryptoProof* crypto_proof,
ValidateClientHelloResultCallback::Result* client_hello_state,
ValidateClientHelloResultCallback* done_cb) const {
ValidateClientHelloHelper helper(client_hello_state, done_cb);
const CryptoHandshakeMessage& client_hello = client_hello_state->client_hello;
ClientHelloInfo* info = &(client_hello_state->info);
if (client_hello.size() < kClientHelloMinimumSize) {
helper.ValidationComplete(QUIC_CRYPTO_INVALID_VALUE_LENGTH,
"Client hello too small");
return;
}
if (client_hello.GetStringPiece(kSNI, &info->sni) &&
!CryptoUtils::IsValidSNI(info->sni)) {
helper.ValidationComplete(QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER,
"Invalid SNI name");
return;
}
client_hello.GetStringPiece(kUAID, &info->user_agent_id);
HandshakeFailureReason source_address_token_error = MAX_FAILURE_REASON;
StringPiece srct;
if (client_hello.GetStringPiece(kSourceAddressTokenTag, &srct)) {
Config& config =
requested_config != nullptr ? *requested_config : *primary_config;
source_address_token_error =
ParseSourceAddressToken(config, srct, &info->source_address_tokens);
if (source_address_token_error == HANDSHAKE_OK) {
source_address_token_error = ValidateSourceAddressTokens(
info->source_address_tokens, info->client_ip, info->now,
&client_hello_state->cached_network_params);
}
info->valid_source_address_token =
(source_address_token_error == HANDSHAKE_OK);
} else {
source_address_token_error = SOURCE_ADDRESS_TOKEN_INVALID_FAILURE;
}
if (!requested_config.get()) {
StringPiece requested_scid;
if (client_hello.GetStringPiece(kSCID, &requested_scid)) {
info->reject_reasons.push_back(SERVER_CONFIG_UNKNOWN_CONFIG_FAILURE);
} else {
info->reject_reasons.push_back(SERVER_CONFIG_INCHOATE_HELLO_FAILURE);
}
// No server config with the requested ID.
helper.ValidationComplete(QUIC_NO_ERROR, "");
return;
}
if (!client_hello.GetStringPiece(kNONC, &info->client_nonce)) {
info->reject_reasons.push_back(SERVER_CONFIG_INCHOATE_HELLO_FAILURE);
// Report no client nonce as INCHOATE_HELLO_FAILURE.
helper.ValidationComplete(QUIC_NO_ERROR, "");
return;
}
bool found_error = false;
if (source_address_token_error != HANDSHAKE_OK) {
info->reject_reasons.push_back(source_address_token_error);
// No valid source address token.
if (FLAGS_use_early_return_when_verifying_chlo) {
helper.ValidationComplete(QUIC_NO_ERROR, "");
return;
}
found_error = true;
}
if (version > QUIC_VERSION_25) {
bool x509_supported = false;
bool x509_ecdsa_supported = false;
ParseProofDemand(client_hello, &x509_supported, &x509_ecdsa_supported);
string serialized_config = primary_config->serialized;
string chlo_hash;
CryptoUtils::HashHandshakeMessage(client_hello, &chlo_hash);
if (!proof_source_->GetProof(
server_ip, info->sni.as_string(), serialized_config, version,
chlo_hash, x509_ecdsa_supported, &crypto_proof->chain,
&crypto_proof->signature, &crypto_proof->cert_sct)) {
found_error = true;
info->reject_reasons.push_back(SERVER_CONFIG_UNKNOWN_CONFIG_FAILURE);
}
if (!ValidateExpectedLeafCertificate(client_hello, *crypto_proof)) {
found_error = true;
info->reject_reasons.push_back(INVALID_EXPECTED_LEAF_CERTIFICATE);
}
}
if (info->client_nonce.size() != kNonceSize) {
info->reject_reasons.push_back(CLIENT_NONCE_INVALID_FAILURE);
// Invalid client nonce.
LOG(ERROR) << "Invalid client nonce: " << client_hello.DebugString();
DVLOG(1) << "Invalid client nonce.";
if (FLAGS_use_early_return_when_verifying_chlo) {
helper.ValidationComplete(QUIC_NO_ERROR, "");
return;
}
found_error = true;
}
// Server nonce is optional, and used for key derivation if present.
client_hello.GetStringPiece(kServerNonceTag, &info->server_nonce);
if (version > QUIC_VERSION_32) {
DVLOG(1) << "No 0-RTT replay protection in QUIC_VERSION_33 and higher.";
// If the server nonce is empty and we're requiring handshake confirmation
// for DoS reasons then we must reject the CHLO.
if (FLAGS_quic_require_handshake_confirmation &&
info->server_nonce.empty()) {
info->reject_reasons.push_back(SERVER_NONCE_REQUIRED_FAILURE);
}
helper.ValidationComplete(QUIC_NO_ERROR, "");
return;
}
if (!replay_protection_) {
DVLOG(1) << "No replay protection.";
helper.ValidationComplete(QUIC_NO_ERROR, "");
return;
}
if (!info->server_nonce.empty()) {
// If the server nonce is present, use it to establish uniqueness.
HandshakeFailureReason server_nonce_error =
ValidateServerNonce(info->server_nonce, info->now);
bool is_unique = server_nonce_error == HANDSHAKE_OK;
if (!is_unique) {
info->reject_reasons.push_back(server_nonce_error);
}
DVLOG(1) << "Using server nonce, unique: " << is_unique;
helper.ValidationComplete(QUIC_NO_ERROR, "");
return;
}
// If we hit this block, the server nonce was empty. If we're requiring
// handshake confirmation for DoS reasons and there's no server nonce present,
// reject the CHLO.
if (FLAGS_quic_require_handshake_confirmation) {
info->reject_reasons.push_back(SERVER_NONCE_REQUIRED_FAILURE);
helper.ValidationComplete(QUIC_NO_ERROR, "");
return;
}
// We want to contact strike register only if there are no errors because it
// is a RPC call and is expensive.
if (found_error) {
helper.ValidationComplete(QUIC_NO_ERROR, "");
return;
}
// Use the client nonce to establish uniqueness.
StrikeRegisterClient* strike_register_client;
{
base::AutoLock locked(strike_register_client_lock_);
strike_register_client = strike_register_client_.get();
}
if (!strike_register_client) {
// Either a valid server nonces or a strike register is required.
// Since neither are present, reject the handshake which will send a
// server nonce to the client.
info->reject_reasons.push_back(SERVER_NONCE_REQUIRED_FAILURE);
helper.ValidationComplete(QUIC_NO_ERROR, "");
return;
}
strike_register_client->VerifyNonceIsValidAndUnique(
info->client_nonce, info->now,
new VerifyNonceIsValidAndUniqueCallback(client_hello_state, done_cb));
helper.StartedAsyncCallback();
}
bool QuicCryptoServerConfig::BuildServerConfigUpdateMessage(
QuicVersion version,
const SourceAddressTokens& previous_source_address_tokens,
const IPAddress& server_ip,
const IPAddress& client_ip,
const QuicClock* clock,
QuicRandom* rand,
QuicCompressedCertsCache* compressed_certs_cache,
const QuicCryptoNegotiatedParameters& params,
const CachedNetworkParameters* cached_network_params,
CryptoHandshakeMessage* out) const {
base::AutoLock locked(configs_lock_);
out->set_tag(kSCUP);
out->SetStringPiece(kSCFG, primary_config_->serialized);
out->SetStringPiece(
kSourceAddressTokenTag,
NewSourceAddressToken(*primary_config_.get(),
previous_source_address_tokens, client_ip, rand,
clock->WallNow(), cached_network_params));
scoped_refptr<ProofSource::Chain> chain;
string signature;
string cert_sct;
if (!proof_source_->GetProof(server_ip, params.sni,
primary_config_->serialized, version,
params.client_nonce, params.x509_ecdsa_supported,
&chain, &signature, &cert_sct)) {
DVLOG(1) << "Server: failed to get proof.";
return false;
}
const string compressed = CompressChain(
compressed_certs_cache, chain, params.client_common_set_hashes,
params.client_cached_cert_hashes, primary_config_->common_cert_sets);
out->SetStringPiece(kCertificateTag, compressed);
out->SetStringPiece(kPROF, signature);
if (params.sct_supported_by_client && version > QUIC_VERSION_29 &&
enable_serving_sct_) {
if (cert_sct.empty()) {
DLOG(WARNING) << "SCT is expected but it is empty.";
} else {
out->SetStringPiece(kCertificateSCTTag, cert_sct);
}
}
return true;
}
void QuicCryptoServerConfig::BuildRejection(
QuicVersion version,
const Config& config,
const CryptoHandshakeMessage& client_hello,
const ClientHelloInfo& info,
const CachedNetworkParameters& cached_network_params,
bool use_stateless_rejects,
QuicConnectionId server_designated_connection_id,
QuicRandom* rand,
QuicCompressedCertsCache* compressed_certs_cache,
QuicCryptoNegotiatedParameters* params,
const QuicCryptoProof& crypto_proof,
CryptoHandshakeMessage* out) const {
if (FLAGS_enable_quic_stateless_reject_support && use_stateless_rejects) {
DVLOG(1) << "QUIC Crypto server config returning stateless reject "
<< "with server-designated connection ID "
<< server_designated_connection_id;
out->set_tag(kSREJ);
out->SetValue(kRCID, server_designated_connection_id);
} else {
out->set_tag(kREJ);
}
out->SetStringPiece(kSCFG, config.serialized);
out->SetStringPiece(
kSourceAddressTokenTag,
NewSourceAddressToken(config, info.source_address_tokens, info.client_ip,
rand, info.now, &cached_network_params));
if (replay_protection_) {
out->SetStringPiece(kServerNonceTag, NewServerNonce(rand, info.now));
}
// Send client the reject reason for debugging purposes.
DCHECK_LT(0u, info.reject_reasons.size());
out->SetVector(kRREJ, info.reject_reasons);
// The client may have requested a certificate chain.
bool x509_supported = false;
ParseProofDemand(client_hello, &x509_supported,
¶ms->x509_ecdsa_supported);
if (!x509_supported) {
return;
}
StringPiece client_common_set_hashes;
if (client_hello.GetStringPiece(kCCS, &client_common_set_hashes)) {
params->client_common_set_hashes = client_common_set_hashes.as_string();
}
StringPiece client_cached_cert_hashes;
if (client_hello.GetStringPiece(kCCRT, &client_cached_cert_hashes)) {
params->client_cached_cert_hashes = client_cached_cert_hashes.as_string();
}
const string compressed =
CompressChain(compressed_certs_cache, crypto_proof.chain,
params->client_common_set_hashes,
params->client_cached_cert_hashes, config.common_cert_sets);
// kREJOverheadBytes is a very rough estimate of how much of a REJ
// message is taken up by things other than the certificates.
// STK: 56 bytes
// SNO: 56 bytes
// SCFG
// SCID: 16 bytes
// PUBS: 38 bytes
const size_t kREJOverheadBytes = 166;
// max_unverified_size is the number of bytes that the certificate chain,
// signature, and (optionally) signed certificate timestamp can consume before
// we will demand a valid source-address token.
const size_t max_unverified_size =
client_hello.size() * chlo_multiplier_ - kREJOverheadBytes;
static_assert(kClientHelloMinimumSize * kMultiplier >= kREJOverheadBytes,
"overhead calculation may underflow");
bool should_return_sct = params->sct_supported_by_client &&
version > QUIC_VERSION_29 && enable_serving_sct_;
const size_t sct_size = should_return_sct ? crypto_proof.cert_sct.size() : 0;
if (info.valid_source_address_token ||
crypto_proof.signature.size() + compressed.size() + sct_size <
max_unverified_size) {
out->SetStringPiece(kCertificateTag, compressed);
out->SetStringPiece(kPROF, crypto_proof.signature);
if (should_return_sct) {
if (crypto_proof.cert_sct.empty()) {
DLOG(WARNING) << "SCT is expected but it is empty.";
} else {
out->SetStringPiece(kCertificateSCTTag, crypto_proof.cert_sct);
}
}
}
}
const string QuicCryptoServerConfig::CompressChain(
QuicCompressedCertsCache* compressed_certs_cache,
const scoped_refptr<ProofSource::Chain>& chain,
const string& client_common_set_hashes,
const string& client_cached_cert_hashes,
const CommonCertSets* common_sets) const {
// Check whether the compressed certs is available in the cache.
if (FLAGS_quic_use_cached_compressed_certs) {
DCHECK(compressed_certs_cache);
const string* cached_value = compressed_certs_cache->GetCompressedCert(
chain, client_common_set_hashes, client_cached_cert_hashes);
if (cached_value) {
return *cached_value;
}
}
const string compressed =
CertCompressor::CompressChain(chain->certs, client_common_set_hashes,
client_common_set_hashes, common_sets);
// Insert the newly compressed cert to cache.
if (FLAGS_quic_use_cached_compressed_certs) {
compressed_certs_cache->Insert(chain, client_common_set_hashes,
client_cached_cert_hashes, compressed);
}
return compressed;
}
scoped_refptr<QuicCryptoServerConfig::Config>
QuicCryptoServerConfig::ParseConfigProtobuf(
QuicServerConfigProtobuf* protobuf) {
scoped_ptr<CryptoHandshakeMessage> msg(
CryptoFramer::ParseMessage(protobuf->config()));
if (msg->tag() != kSCFG) {
LOG(WARNING) << "Server config message has tag " << msg->tag()
<< " expected " << kSCFG;
return nullptr;
}
scoped_refptr<Config> config(new Config);
config->serialized = protobuf->config();
if (!protobuf->has_source_address_token_secret_override()) {
// Use the default boxer.
config->source_address_token_boxer = &default_source_address_token_boxer_;
} else {
// Create override boxer instance.
CryptoSecretBoxer* boxer = new CryptoSecretBoxer;
boxer->SetKeys({DeriveSourceAddressTokenKey(
protobuf->source_address_token_secret_override())});
config->source_address_token_boxer_storage.reset(boxer);
config->source_address_token_boxer = boxer;
}
if (protobuf->has_primary_time()) {
config->primary_time =
QuicWallTime::FromUNIXSeconds(protobuf->primary_time());
}
config->priority = protobuf->priority();
StringPiece scid;
if (!msg->GetStringPiece(kSCID, &scid)) {
LOG(WARNING) << "Server config message is missing SCID";
return nullptr;
}
config->id = scid.as_string();
const QuicTag* aead_tags;
size_t aead_len;
if (msg->GetTaglist(kAEAD, &aead_tags, &aead_len) != QUIC_NO_ERROR) {
LOG(WARNING) << "Server config message is missing AEAD";
return nullptr;
}
config->aead = vector<QuicTag>(aead_tags, aead_tags + aead_len);
const QuicTag* kexs_tags;
size_t kexs_len;
if (msg->GetTaglist(kKEXS, &kexs_tags, &kexs_len) != QUIC_NO_ERROR) {
LOG(WARNING) << "Server config message is missing KEXS";
return nullptr;
}
const QuicTag* tbkp_tags;
size_t tbkp_len;
QuicErrorCode err;
if ((err = msg->GetTaglist(kTBKP, &tbkp_tags, &tbkp_len)) !=
QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND &&
err != QUIC_NO_ERROR) {
LOG(WARNING) << "Server config message is missing or has invalid TBKP";
return nullptr;
}
config->tb_key_params = vector<QuicTag>(tbkp_tags, tbkp_tags + tbkp_len);
StringPiece orbit;
if (!msg->GetStringPiece(kORBT, &orbit)) {
LOG(WARNING) << "Server config message is missing ORBT";
return nullptr;
}
if (orbit.size() != kOrbitSize) {
LOG(WARNING) << "Orbit value in server config is the wrong length."
" Got "
<< orbit.size() << " want " << kOrbitSize;
return nullptr;
}
static_assert(sizeof(config->orbit) == kOrbitSize,
"orbit has incorrect size");
memcpy(config->orbit, orbit.data(), sizeof(config->orbit));
{
StrikeRegisterClient* strike_register_client;
{
base::AutoLock locked(strike_register_client_lock_);
strike_register_client = strike_register_client_.get();
}
if (strike_register_client != nullptr &&
!strike_register_client->IsKnownOrbit(orbit)) {
LOG(WARNING)
<< "Rejecting server config with orbit that the strike register "
"client doesn't know about.";
return nullptr;
}
}
if (kexs_len != protobuf->key_size()) {
LOG(WARNING) << "Server config has " << kexs_len
<< " key exchange methods configured, but "
<< protobuf->key_size() << " private keys";
return nullptr;
}
const QuicTag* proof_demand_tags;
size_t num_proof_demand_tags;
if (msg->GetTaglist(kPDMD, &proof_demand_tags, &num_proof_demand_tags) ==
QUIC_NO_ERROR) {
for (size_t i = 0; i < num_proof_demand_tags; i++) {
if (proof_demand_tags[i] == kCHID) {
config->channel_id_enabled = true;
break;
}
}
}
for (size_t i = 0; i < kexs_len; i++) {
const QuicTag tag = kexs_tags[i];
string private_key;
config->kexs.push_back(tag);
for (size_t j = 0; j < protobuf->key_size(); j++) {
const QuicServerConfigProtobuf::PrivateKey& key = protobuf->key(i);
if (key.tag() == tag) {
private_key = key.private_key();
break;
}
}
if (private_key.empty()) {
LOG(WARNING) << "Server config contains key exchange method without "
"corresponding private key: "
<< tag;
return nullptr;
}
scoped_ptr<KeyExchange> ka;
switch (tag) {
case kC255:
ka.reset(Curve25519KeyExchange::New(private_key));
if (!ka.get()) {
LOG(WARNING) << "Server config contained an invalid curve25519"
" private key.";
return nullptr;
}
break;
case kP256:
ka.reset(P256KeyExchange::New(private_key));
if (!ka.get()) {
LOG(WARNING) << "Server config contained an invalid P-256"
" private key.";
return nullptr;
}
break;
default:
LOG(WARNING) << "Server config message contains unknown key exchange "
"method: "
<< tag;
return nullptr;
}
for (const KeyExchange* key_exchange : config->key_exchanges) {
if (key_exchange->tag() == tag) {
LOG(WARNING) << "Duplicate key exchange in config: " << tag;
return nullptr;
}
}
config->key_exchanges.push_back(ka.release());
}
return config;
}
void QuicCryptoServerConfig::SetEphemeralKeySource(
EphemeralKeySource* ephemeral_key_source) {
ephemeral_key_source_.reset(ephemeral_key_source);
}
void QuicCryptoServerConfig::SetStrikeRegisterClient(
StrikeRegisterClient* strike_register_client) {
base::AutoLock locker(strike_register_client_lock_);
DCHECK(!strike_register_client_.get());
strike_register_client_.reset(strike_register_client);
}
void QuicCryptoServerConfig::set_replay_protection(bool on) {
replay_protection_ = on;
}
void QuicCryptoServerConfig::set_chlo_multiplier(size_t multiplier) {
chlo_multiplier_ = multiplier;
}
void QuicCryptoServerConfig::set_strike_register_no_startup_period() {
base::AutoLock locker(strike_register_client_lock_);
DCHECK(!strike_register_client_.get());
strike_register_no_startup_period_ = true;
}
void QuicCryptoServerConfig::set_strike_register_max_entries(
uint32_t max_entries) {
base::AutoLock locker(strike_register_client_lock_);
DCHECK(!strike_register_client_.get());
strike_register_max_entries_ = max_entries;
}
void QuicCryptoServerConfig::set_strike_register_window_secs(
uint32_t window_secs) {
base::AutoLock locker(strike_register_client_lock_);
DCHECK(!strike_register_client_.get());
strike_register_window_secs_ = window_secs;
}
void QuicCryptoServerConfig::set_source_address_token_future_secs(
uint32_t future_secs) {
source_address_token_future_secs_ = future_secs;
}
void QuicCryptoServerConfig::set_source_address_token_lifetime_secs(
uint32_t lifetime_secs) {
source_address_token_lifetime_secs_ = lifetime_secs;
}
void QuicCryptoServerConfig::set_server_nonce_strike_register_max_entries(
uint32_t max_entries) {
DCHECK(!server_nonce_strike_register_.get());
server_nonce_strike_register_max_entries_ = max_entries;
}
void QuicCryptoServerConfig::set_server_nonce_strike_register_window_secs(
uint32_t window_secs) {
DCHECK(!server_nonce_strike_register_.get());
server_nonce_strike_register_window_secs_ = window_secs;
}
void QuicCryptoServerConfig::set_enable_serving_sct(bool enable_serving_sct) {
enable_serving_sct_ = enable_serving_sct;
}
void QuicCryptoServerConfig::AcquirePrimaryConfigChangedCb(
PrimaryConfigChangedCallback* cb) {
base::AutoLock locked(configs_lock_);
primary_config_changed_cb_.reset(cb);
}
string QuicCryptoServerConfig::NewSourceAddressToken(
const Config& config,
const SourceAddressTokens& previous_tokens,
const IPAddress& ip,
QuicRandom* rand,
QuicWallTime now,
const CachedNetworkParameters* cached_network_params) const {
SourceAddressTokens source_address_tokens;
SourceAddressToken* source_address_token = source_address_tokens.add_tokens();
source_address_token->set_ip(IPAddressToPackedString(DualstackIPAddress(ip)));
source_address_token->set_timestamp(now.ToUNIXSeconds());
if (cached_network_params != nullptr) {
*(source_address_token->mutable_cached_network_parameters()) =
*cached_network_params;
}
// Append previous tokens.
for (const SourceAddressToken& token : previous_tokens.tokens()) {
if (source_address_tokens.tokens_size() > kMaxTokenAddresses) {
break;
}
if (token.ip() == source_address_token->ip()) {
// It's for the same IP address.
continue;
}
if (ValidateSourceAddressTokenTimestamp(token, now) != HANDSHAKE_OK) {
continue;
}
*(source_address_tokens.add_tokens()) = token;
}
return config.source_address_token_boxer->Box(
rand, source_address_tokens.SerializeAsString());
}
int QuicCryptoServerConfig::NumberOfConfigs() const {
base::AutoLock locked(configs_lock_);
return configs_.size();
}
HandshakeFailureReason QuicCryptoServerConfig::ParseSourceAddressToken(
const Config& config,
StringPiece token,
SourceAddressTokens* tokens) const {
string storage;
StringPiece plaintext;
if (!config.source_address_token_boxer->Unbox(token, &storage, &plaintext)) {
return SOURCE_ADDRESS_TOKEN_DECRYPTION_FAILURE;
}
if (!tokens->ParseFromArray(plaintext.data(), plaintext.size())) {
// Some clients might still be using the old source token format so
// attempt to parse that format.
// TODO(rch): remove this code once the new format is ubiquitous.
SourceAddressToken source_address_token;
if (!source_address_token.ParseFromArray(plaintext.data(),
plaintext.size())) {
return SOURCE_ADDRESS_TOKEN_PARSE_FAILURE;
}
*tokens->add_tokens() = source_address_token;
}
return HANDSHAKE_OK;
}
HandshakeFailureReason QuicCryptoServerConfig::ValidateSourceAddressTokens(
const SourceAddressTokens& source_address_tokens,
const IPAddress& ip,
QuicWallTime now,
CachedNetworkParameters* cached_network_params) const {
HandshakeFailureReason reason =
SOURCE_ADDRESS_TOKEN_DIFFERENT_IP_ADDRESS_FAILURE;
for (const SourceAddressToken& token : source_address_tokens.tokens()) {
reason = ValidateSingleSourceAddressToken(token, ip, now);
if (reason == HANDSHAKE_OK) {
if (token.has_cached_network_parameters()) {
*cached_network_params = token.cached_network_parameters();
}
break;
}
}
return reason;
}
HandshakeFailureReason QuicCryptoServerConfig::ValidateSingleSourceAddressToken(
const SourceAddressToken& source_address_token,
const IPAddress& ip,
QuicWallTime now) const {
if (source_address_token.ip() !=
IPAddressToPackedString(DualstackIPAddress(ip))) {
// It's for a different IP address.
return SOURCE_ADDRESS_TOKEN_DIFFERENT_IP_ADDRESS_FAILURE;
}
return ValidateSourceAddressTokenTimestamp(source_address_token, now);
}
HandshakeFailureReason
QuicCryptoServerConfig::ValidateSourceAddressTokenTimestamp(
const SourceAddressToken& source_address_token,
QuicWallTime now) const {
const QuicWallTime timestamp(
QuicWallTime::FromUNIXSeconds(source_address_token.timestamp()));
const QuicTime::Delta delta(now.AbsoluteDifference(timestamp));
if (now.IsBefore(timestamp) &&
delta.ToSeconds() > source_address_token_future_secs_) {
return SOURCE_ADDRESS_TOKEN_CLOCK_SKEW_FAILURE;
}
if (now.IsAfter(timestamp) &&
delta.ToSeconds() > source_address_token_lifetime_secs_) {
return SOURCE_ADDRESS_TOKEN_EXPIRED_FAILURE;
}
return HANDSHAKE_OK;
}
// kServerNoncePlaintextSize is the number of bytes in an unencrypted server
// nonce.
static const size_t kServerNoncePlaintextSize =
4 /* timestamp */ + 20 /* random bytes */;
string QuicCryptoServerConfig::NewServerNonce(QuicRandom* rand,
QuicWallTime now) const {
const uint32_t timestamp = static_cast<uint32_t>(now.ToUNIXSeconds());
uint8_t server_nonce[kServerNoncePlaintextSize];
static_assert(sizeof(server_nonce) > sizeof(timestamp), "nonce too small");
server_nonce[0] = static_cast<uint8_t>(timestamp >> 24);
server_nonce[1] = static_cast<uint8_t>(timestamp >> 16);
server_nonce[2] = static_cast<uint8_t>(timestamp >> 8);
server_nonce[3] = static_cast<uint8_t>(timestamp);
rand->RandBytes(&server_nonce[sizeof(timestamp)],
sizeof(server_nonce) - sizeof(timestamp));
return server_nonce_boxer_.Box(
rand,
StringPiece(reinterpret_cast<char*>(server_nonce), sizeof(server_nonce)));
}
HandshakeFailureReason QuicCryptoServerConfig::ValidateServerNonce(
StringPiece token,
QuicWallTime now) const {
string storage;
StringPiece plaintext;
if (!server_nonce_boxer_.Unbox(token, &storage, &plaintext)) {
return SERVER_NONCE_DECRYPTION_FAILURE;
}
// plaintext contains:
// uint32_t timestamp
// uint8_t[20] random bytes
if (plaintext.size() != kServerNoncePlaintextSize) {
// This should never happen because the value decrypted correctly.
QUIC_BUG << "Seemingly valid server nonce had incorrect length.";
return SERVER_NONCE_INVALID_FAILURE;
}
uint8_t server_nonce[32];
memcpy(server_nonce, plaintext.data(), 4);
memcpy(server_nonce + 4, server_nonce_orbit_, sizeof(server_nonce_orbit_));
memcpy(server_nonce + 4 + sizeof(server_nonce_orbit_), plaintext.data() + 4,
20);
static_assert(4 + sizeof(server_nonce_orbit_) + 20 == sizeof(server_nonce),
"bad nonce buffer length");
InsertStatus nonce_error;
{
base::AutoLock auto_lock(server_nonce_strike_register_lock_);
if (server_nonce_strike_register_.get() == nullptr) {
server_nonce_strike_register_.reset(new StrikeRegister(
server_nonce_strike_register_max_entries_,
static_cast<uint32_t>(now.ToUNIXSeconds()),
server_nonce_strike_register_window_secs_, server_nonce_orbit_,
StrikeRegister::NO_STARTUP_PERIOD_NEEDED));
}
nonce_error = server_nonce_strike_register_->Insert(
server_nonce, static_cast<uint32_t>(now.ToUNIXSeconds()));
}
switch (nonce_error) {
case NONCE_OK:
return HANDSHAKE_OK;
case NONCE_INVALID_FAILURE:
case NONCE_INVALID_ORBIT_FAILURE:
return SERVER_NONCE_INVALID_FAILURE;
case NONCE_NOT_UNIQUE_FAILURE:
return SERVER_NONCE_NOT_UNIQUE_FAILURE;
case NONCE_INVALID_TIME_FAILURE:
return SERVER_NONCE_INVALID_TIME_FAILURE;
case NONCE_UNKNOWN_FAILURE:
case STRIKE_REGISTER_TIMEOUT:
case STRIKE_REGISTER_FAILURE:
default:
QUIC_BUG << "Unexpected server nonce error: " << nonce_error;
return SERVER_NONCE_NOT_UNIQUE_FAILURE;
}
}
bool QuicCryptoServerConfig::ValidateExpectedLeafCertificate(
const CryptoHandshakeMessage& client_hello,
const QuicCryptoProof& crypto_proof) const {
if (crypto_proof.chain->certs.empty()) {
return false;
}
uint64_t hash_from_client;
if (client_hello.GetUint64(kXLCT, &hash_from_client) != QUIC_NO_ERROR) {
return false;
}
return CryptoUtils::ComputeLeafCertHash(crypto_proof.chain->certs.at(0)) ==
hash_from_client;
}
void QuicCryptoServerConfig::ParseProofDemand(
const CryptoHandshakeMessage& client_hello,
bool* x509_supported,
bool* x509_ecdsa_supported) const {
const QuicTag* their_proof_demands;
size_t num_their_proof_demands;
if (client_hello.GetTaglist(kPDMD, &their_proof_demands,
&num_their_proof_demands) != QUIC_NO_ERROR) {
return;
}
*x509_supported = false;
for (size_t i = 0; i < num_their_proof_demands; i++) {
switch (their_proof_demands[i]) {
case kX509:
*x509_supported = true;
*x509_ecdsa_supported = true;
break;
case kX59R:
*x509_supported = true;
break;
}
}
}
QuicCryptoServerConfig::Config::Config()
: channel_id_enabled(false),
is_primary(false),
primary_time(QuicWallTime::Zero()),
priority(0),
source_address_token_boxer(nullptr) {}
QuicCryptoServerConfig::Config::~Config() {
STLDeleteElements(&key_exchanges);
}
QuicCryptoProof::QuicCryptoProof() {}
QuicCryptoProof::~QuicCryptoProof() {}
} // namespace net
| was4444/chromium.src | net/quic/crypto/quic_crypto_server_config.cc | C++ | bsd-3-clause | 64,803 |
#!/usr/bin/env python
#
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Runs Android's lint tool."""
import argparse
import os
import re
import sys
import traceback
from xml.dom import minidom
from util import build_utils
_SRC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__),
'..', '..', '..'))
def _OnStaleMd5(changes, lint_path, config_path, processed_config_path,
manifest_path, result_path, product_dir, sources, jar_path,
cache_dir, android_sdk_version, resource_dir=None,
classpath=None, can_fail_build=False, silent=False):
def _RelativizePath(path):
"""Returns relative path to top-level src dir.
Args:
path: A path relative to cwd.
"""
return os.path.relpath(os.path.abspath(path), _SRC_ROOT)
def _ProcessConfigFile():
if not config_path or not processed_config_path:
return
if not build_utils.IsTimeStale(processed_config_path, [config_path]):
return
with open(config_path, 'rb') as f:
content = f.read().replace(
'PRODUCT_DIR', _RelativizePath(product_dir))
with open(processed_config_path, 'wb') as f:
f.write(content)
def _ProcessResultFile():
with open(result_path, 'rb') as f:
content = f.read().replace(
_RelativizePath(product_dir), 'PRODUCT_DIR')
with open(result_path, 'wb') as f:
f.write(content)
def _ParseAndShowResultFile():
dom = minidom.parse(result_path)
issues = dom.getElementsByTagName('issue')
if not silent:
print >> sys.stderr
for issue in issues:
issue_id = issue.attributes['id'].value
message = issue.attributes['message'].value
location_elem = issue.getElementsByTagName('location')[0]
path = location_elem.attributes['file'].value
line = location_elem.getAttribute('line')
if line:
error = '%s:%s %s: %s [warning]' % (path, line, message, issue_id)
else:
# Issues in class files don't have a line number.
error = '%s %s: %s [warning]' % (path, message, issue_id)
print >> sys.stderr, error.encode('utf-8')
for attr in ['errorLine1', 'errorLine2']:
error_line = issue.getAttribute(attr)
if error_line:
print >> sys.stderr, error_line.encode('utf-8')
return len(issues)
# Need to include all sources when a resource_dir is set so that resources are
# not marked as unused.
# TODO(agrieve): Figure out how IDEs do incremental linting.
if not resource_dir and changes.AddedOrModifiedOnly():
changed_paths = set(changes.IterChangedPaths())
sources = [s for s in sources if s in changed_paths]
with build_utils.TempDir() as temp_dir:
_ProcessConfigFile()
cmd = [
_RelativizePath(lint_path), '-Werror', '--exitcode', '--showall',
'--xml', _RelativizePath(result_path),
]
if jar_path:
# --classpath is just for .class files for this one target.
cmd.extend(['--classpath', _RelativizePath(jar_path)])
if processed_config_path:
cmd.extend(['--config', _RelativizePath(processed_config_path)])
if resource_dir:
cmd.extend(['--resources', _RelativizePath(resource_dir)])
if classpath:
# --libraries is the classpath (excluding active target).
cp = ':'.join(_RelativizePath(p) for p in classpath)
cmd.extend(['--libraries', cp])
# There may be multiple source files with the same basename (but in
# different directories). It is difficult to determine what part of the path
# corresponds to the java package, and so instead just link the source files
# into temporary directories (creating a new one whenever there is a name
# conflict).
src_dirs = []
def NewSourceDir():
new_dir = os.path.join(temp_dir, str(len(src_dirs)))
os.mkdir(new_dir)
src_dirs.append(new_dir)
return new_dir
def PathInDir(d, src):
return os.path.join(d, os.path.basename(src))
for src in sources:
src_dir = None
for d in src_dirs:
if not os.path.exists(PathInDir(d, src)):
src_dir = d
break
if not src_dir:
src_dir = NewSourceDir()
cmd.extend(['--sources', _RelativizePath(src_dir)])
os.symlink(os.path.abspath(src), PathInDir(src_dir, src))
project_dir = NewSourceDir()
if android_sdk_version:
# Create dummy project.properies file in a temporary "project" directory.
# It is the only way to add Android SDK to the Lint's classpath. Proper
# classpath is necessary for most source-level checks.
with open(os.path.join(project_dir, 'project.properties'), 'w') \
as propfile:
print >> propfile, 'target=android-{}'.format(android_sdk_version)
# Put the manifest in a temporary directory in order to avoid lint detecting
# sibling res/ and src/ directories (which should be pass explicitly if they
# are to be included).
if manifest_path:
os.symlink(os.path.abspath(manifest_path),
PathInDir(project_dir, manifest_path))
cmd.append(project_dir)
if os.path.exists(result_path):
os.remove(result_path)
env = {}
stderr_filter = None
if cache_dir:
env['_JAVA_OPTIONS'] = '-Duser.home=%s' % _RelativizePath(cache_dir)
# When _JAVA_OPTIONS is set, java prints to stderr:
# Picked up _JAVA_OPTIONS: ...
#
# We drop all lines that contain _JAVA_OPTIONS from the output
stderr_filter = lambda l: re.sub(r'.*_JAVA_OPTIONS.*\n?', '', l)
try:
build_utils.CheckOutput(cmd, cwd=_SRC_ROOT, env=env or None,
stderr_filter=stderr_filter)
except build_utils.CalledProcessError:
# There is a problem with lint usage
if not os.path.exists(result_path):
raise
# Sometimes produces empty (almost) files:
if os.path.getsize(result_path) < 10:
if can_fail_build:
raise
elif not silent:
traceback.print_exc()
return
# There are actual lint issues
try:
num_issues = _ParseAndShowResultFile()
except Exception: # pylint: disable=broad-except
if not silent:
print 'Lint created unparseable xml file...'
print 'File contents:'
with open(result_path) as f:
print f.read()
if not can_fail_build:
return
if can_fail_build and not silent:
traceback.print_exc()
# There are actual lint issues
try:
num_issues = _ParseAndShowResultFile()
except Exception: # pylint: disable=broad-except
if not silent:
print 'Lint created unparseable xml file...'
print 'File contents:'
with open(result_path) as f:
print f.read()
raise
_ProcessResultFile()
msg = ('\nLint found %d new issues.\n'
' - For full explanation refer to %s\n' %
(num_issues,
_RelativizePath(result_path)))
if config_path:
msg += (' - Wanna suppress these issues?\n'
' 1. Read comment in %s\n'
' 2. Run "python %s %s"\n' %
(_RelativizePath(config_path),
_RelativizePath(os.path.join(_SRC_ROOT, 'build', 'android',
'lint', 'suppress.py')),
_RelativizePath(result_path)))
if not silent:
print >> sys.stderr, msg
if can_fail_build:
raise Exception('Lint failed.')
def main():
parser = argparse.ArgumentParser()
build_utils.AddDepfileOption(parser)
parser.add_argument('--lint-path', required=True,
help='Path to lint executable.')
parser.add_argument('--product-dir', required=True,
help='Path to product dir.')
parser.add_argument('--result-path', required=True,
help='Path to XML lint result file.')
parser.add_argument('--cache-dir', required=True,
help='Path to the directory in which the android cache '
'directory tree should be stored.')
parser.add_argument('--platform-xml-path', required=True,
help='Path to api-platforms.xml')
parser.add_argument('--android-sdk-version',
help='Version (API level) of the Android SDK used for '
'building.')
parser.add_argument('--create-cache', action='store_true',
help='Mark the lint cache file as an output rather than '
'an input.')
parser.add_argument('--can-fail-build', action='store_true',
help='If set, script will exit with nonzero exit status'
' if lint errors are present')
parser.add_argument('--config-path',
help='Path to lint suppressions file.')
parser.add_argument('--enable', action='store_true',
help='Run lint instead of just touching stamp.')
parser.add_argument('--jar-path',
help='Jar file containing class files.')
parser.add_argument('--java-files',
help='Paths to java files.')
parser.add_argument('--manifest-path',
help='Path to AndroidManifest.xml')
parser.add_argument('--classpath', default=[], action='append',
help='GYP-list of classpath .jar files')
parser.add_argument('--processed-config-path',
help='Path to processed lint suppressions file.')
parser.add_argument('--resource-dir',
help='Path to resource dir.')
parser.add_argument('--silent', action='store_true',
help='If set, script will not log anything.')
parser.add_argument('--src-dirs',
help='Directories containing java files.')
parser.add_argument('--stamp',
help='Path to touch on success.')
args = parser.parse_args(build_utils.ExpandFileArgs(sys.argv[1:]))
if args.enable:
sources = []
if args.src_dirs:
src_dirs = build_utils.ParseGypList(args.src_dirs)
sources = build_utils.FindInDirectories(src_dirs, '*.java')
elif args.java_files:
sources = build_utils.ParseGypList(args.java_files)
if args.config_path and not args.processed_config_path:
parser.error('--config-path specified without --processed-config-path')
elif args.processed_config_path and not args.config_path:
parser.error('--processed-config-path specified without --config-path')
input_paths = [
args.lint_path,
args.platform_xml_path,
]
if args.config_path:
input_paths.append(args.config_path)
if args.jar_path:
input_paths.append(args.jar_path)
if args.manifest_path:
input_paths.append(args.manifest_path)
if args.resource_dir:
input_paths.extend(build_utils.FindInDirectory(args.resource_dir, '*'))
if sources:
input_paths.extend(sources)
classpath = []
for gyp_list in args.classpath:
classpath.extend(build_utils.ParseGypList(gyp_list))
input_paths.extend(classpath)
input_strings = []
if args.android_sdk_version:
input_strings.append(args.android_sdk_version)
if args.processed_config_path:
input_strings.append(args.processed_config_path)
output_paths = [ args.result_path ]
build_utils.CallAndWriteDepfileIfStale(
lambda changes: _OnStaleMd5(changes, args.lint_path,
args.config_path,
args.processed_config_path,
args.manifest_path, args.result_path,
args.product_dir, sources,
args.jar_path,
args.cache_dir,
args.android_sdk_version,
resource_dir=args.resource_dir,
classpath=classpath,
can_fail_build=args.can_fail_build,
silent=args.silent),
args,
input_paths=input_paths,
input_strings=input_strings,
output_paths=output_paths,
pass_changes=True,
depfile_deps=classpath)
if __name__ == '__main__':
sys.exit(main())
| was4444/chromium.src | build/android/gyp/lint.py | Python | bsd-3-clause | 12,623 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fscanf_14.c
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE129.label.xml
Template File: sources-sinks-14.tmpl.c
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: fscanf Read data from the console using fscanf()
* GoodSource: Larger than zero but less than 10
* Sinks:
* GoodSink: Ensure the array index is valid
* BadSink : Improperly check the array index by not checking the upper bound
* Flow Variant: 14 Control flow: if(globalFive==5) and if(globalFive!=5)
*
* */
#include "std_testcase.h"
#ifndef OMITBAD
void CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fscanf_14_bad()
{
int data;
/* Initialize data */
data = -1;
if(globalFive==5)
{
/* POTENTIAL FLAW: Read data from the console using fscanf() */
fscanf(stdin, "%d", &data);
}
if(globalFive==5)
{
{
int i;
int * buffer = (int *)malloc(10 * sizeof(int));
if (buffer == NULL) {exit(-1);}
/* initialize buffer */
for (i = 0; i < 10; i++)
{
buffer[i] = 0;
}
/* POTENTIAL FLAW: Attempt to write to an index of the array that is above the upper bound
* This code does check to see if the array index is negative */
if (data >= 0)
{
buffer[data] = 1;
/* Print the array values */
for(i = 0; i < 10; i++)
{
printIntLine(buffer[i]);
}
}
else
{
printLine("ERROR: Array index is negative.");
}
free(buffer);
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G1() - use badsource and goodsink by changing the second globalFive==5 to globalFive!=5 */
static void goodB2G1()
{
int data;
/* Initialize data */
data = -1;
if(globalFive==5)
{
/* POTENTIAL FLAW: Read data from the console using fscanf() */
fscanf(stdin, "%d", &data);
}
if(globalFive!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
{
int i;
int * buffer = (int *)malloc(10 * sizeof(int));
if (buffer == NULL) {exit(-1);}
/* initialize buffer */
for (i = 0; i < 10; i++)
{
buffer[i] = 0;
}
/* FIX: Properly validate the array index and prevent a buffer overflow */
if (data >= 0 && data < (10))
{
buffer[data] = 1;
/* Print the array values */
for(i = 0; i < 10; i++)
{
printIntLine(buffer[i]);
}
}
else
{
printLine("ERROR: Array index is out-of-bounds");
}
free(buffer);
}
}
}
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */
static void goodB2G2()
{
int data;
/* Initialize data */
data = -1;
if(globalFive==5)
{
/* POTENTIAL FLAW: Read data from the console using fscanf() */
fscanf(stdin, "%d", &data);
}
if(globalFive==5)
{
{
int i;
int * buffer = (int *)malloc(10 * sizeof(int));
if (buffer == NULL) {exit(-1);}
/* initialize buffer */
for (i = 0; i < 10; i++)
{
buffer[i] = 0;
}
/* FIX: Properly validate the array index and prevent a buffer overflow */
if (data >= 0 && data < (10))
{
buffer[data] = 1;
/* Print the array values */
for(i = 0; i < 10; i++)
{
printIntLine(buffer[i]);
}
}
else
{
printLine("ERROR: Array index is out-of-bounds");
}
free(buffer);
}
}
}
/* goodG2B1() - use goodsource and badsink by changing the first globalFive==5 to globalFive!=5 */
static void goodG2B1()
{
int data;
/* Initialize data */
data = -1;
if(globalFive!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Use a value greater than 0, but less than 10 to avoid attempting to
* access an index of the array in the sink that is out-of-bounds */
data = 7;
}
if(globalFive==5)
{
{
int i;
int * buffer = (int *)malloc(10 * sizeof(int));
if (buffer == NULL) {exit(-1);}
/* initialize buffer */
for (i = 0; i < 10; i++)
{
buffer[i] = 0;
}
/* POTENTIAL FLAW: Attempt to write to an index of the array that is above the upper bound
* This code does check to see if the array index is negative */
if (data >= 0)
{
buffer[data] = 1;
/* Print the array values */
for(i = 0; i < 10; i++)
{
printIntLine(buffer[i]);
}
}
else
{
printLine("ERROR: Array index is negative.");
}
free(buffer);
}
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */
static void goodG2B2()
{
int data;
/* Initialize data */
data = -1;
if(globalFive==5)
{
/* FIX: Use a value greater than 0, but less than 10 to avoid attempting to
* access an index of the array in the sink that is out-of-bounds */
data = 7;
}
if(globalFive==5)
{
{
int i;
int * buffer = (int *)malloc(10 * sizeof(int));
if (buffer == NULL) {exit(-1);}
/* initialize buffer */
for (i = 0; i < 10; i++)
{
buffer[i] = 0;
}
/* POTENTIAL FLAW: Attempt to write to an index of the array that is above the upper bound
* This code does check to see if the array index is negative */
if (data >= 0)
{
buffer[data] = 1;
/* Print the array values */
for(i = 0; i < 10; i++)
{
printIntLine(buffer[i]);
}
}
else
{
printLine("ERROR: Array index is negative.");
}
free(buffer);
}
}
}
void CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fscanf_14_good()
{
goodB2G1();
goodB2G2();
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fscanf_14_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fscanf_14_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s06/CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fscanf_14.c | C | bsd-3-clause | 8,100 |
{-# LANGUAGE LambdaCase #-}
module Main (main) where
import System.Environment (getArgs)
eyes = cycle ["⦿⦿", "⦾⦾", "⟐⟐", "⪽⪾", "⨷⨷", "⨸⨸", "☯☯", "⊙⊙", "⊚⊚", "⊛⊛", "⨕⨕", "⊗⊗", "⊘⊘", "⊖⊖", "⁌⁍", "✩✩", "❈❈"]
shells = cycle ["()", "{}", "[]", "⨭⨮", "⨴⨵", "⊆⊇", "∣∣"]
bodies = cycle ["███", "XXX", "⧱⧰⧱", "⧯⧮⧯", "⧲⧳⧲","🁢🁢🁢", "✚✚✚", "⧓⧒⧑", "⦁⦁⦁", "☗☗☗", "❝❝❝"]
arthropod k = (face k):(repeat $ body k)
face k = let (l:r:[]) = eyes !! k
in "╚" ++ l:" " ++ r:"╝"
body k = let (l:r:[]) = shells !! k
c = bodies !! k
in "╚═" ++ l:c ++ r:"═╝"
wiggle = map (flip replicate ' ') (4 : cycle [2,1,0,1,2,3,4,3])
millipede = zipWith (++) wiggle . arthropod
main :: IO ()
main = getArgs >>= \case
[] -> beautiful $ millipede 0
(x:[]) -> beautiful $ millipede (read x)
where beautiful = putStrLn . unlines . take 20
| getmillipede/millipede-haskell | app/Main.hs | Haskell | bsd-3-clause | 1,023 |
<?php
/**
* JJPHP 视图基本类
* @package comm
* @author zhuli <www.initphp.com>
* @author zhengyouxiangxiang <zhengyouxiang00@gmail.com>
* @copyright www.111work.com
*/
class View extends JJBase
{
public $variable = array(); //视图变量
private $templates = array(); //视图存放器
private $header;
private $footer;
/**
* 模板-设置模板变量
* @param string $key KEY值-模板中的变量名称
* @param string $value value值
* @return array
*/
public function assign($key, $value) {
$this->variable[$key] = $value;
}
/**
* 设置尾模板..
* @param $footer
*/
public function setFooter($footer='footer')
{
$this->footer=$footer;
}
/**
* 设置头模板..
* @param $header
*/
public function setHeader($header='header')
{
$this->header=$header;
}
/**
* 设置模板
* @param string $viewName 模板名称
*/
public function setView($viewName) {
$this->templates[]=$viewName;
}
/**
* 设置默认模版
*/
protected function returnDefaultDisplayName()
{
$name=$this->getContrNameExceptContr().'_'.$this->getAction();
return $this->returnIncludeViewName($name);
}
/**
*return include view下的文件..
* @param $name
*/
protected function returnIncludeViewName($name)
{
$name=strtolower($name);
$filename=JJPATH.'/web/view/'.$name.'.php';
if(!$this->fileExists($filename)) throw new JJException('不存在view: '.$name);
return $filename;
}
/**
* 模板-显示视图
*/
public function display() {
if (is_array($this->variable)) {
foreach ($this->variable as $key => $val) {
$$key = $val;
}
}
if(isset($this->header)) include_once ($this->returnIncludeViewName($this->header));
if(empty($this->templates)) include_once($this->returnDefaultDisplayName());
foreach ($this->templates as $name) {
include_once ($this->returnIncludeViewName($name));
}
if(isset($this->footer)) include_once ($this->returnIncludeViewName($this->footer));
}
} | zhengyouxiang/JVPHP | core/comm/View.php | PHP | bsd-3-clause | 2,004 |
/*
* Copyright (C) 2015-2019 Fabrice Bouyé
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
package api.web.gw2.mapping.v2.professions;
import api.web.gw2.mapping.core.IdValue;
import api.web.gw2.mapping.core.LocalizedResource;
import api.web.gw2.mapping.core.MapValue;
import api.web.gw2.mapping.core.SetValue;
import api.web.gw2.mapping.core.URLReference;
import api.web.gw2.mapping.core.URLValue;
import api.web.gw2.mapping.v2.APIv2;
import java.util.Map;
import java.util.Set;
/**
* Defines a profession.
* @author Fabrice Bouyé
*/
@APIv2(endpoint = "v2/professions") // NOI18N.
public interface Profession {
/**
* Gets the id of this profession.
* @return A {@code String} never {@code null}.
* @see api.web.gw2.mapping.v2.characters.CharacterProfession
*/
@IdValue(flavor = IdValue.Flavor.STRING)
String getId();
/**
* Gets the i18n name of the profession (non-gender specific).
* @return A {@code String} never {@code null}.
*/
@LocalizedResource
String getName();
/**
* Gets the url to the icon of this profession.
* @return A {@code URLReference} instance, never {@code null}.
*/
@URLValue
URLReference getIcon();
/**
* Gets the url to the large icon of this profession.
* @return A {@code URLReference} instance, never {@code null}.
*/
@URLValue
URLReference getIconBig();
/**
* Gets the set of ids of this profession's specializations.
* @return A non-modifiable {@code Set<Integer>} instance, never {@code null}.
*/
@IdValue
@SetValue
Set<Integer> getSpecializations();
/**
* Gets the weapons skills for this profession.
* @return A non-modifiable {@code Map<ProfessionWeaponType, ProfessionWeaponSkillSet>} instance, never {@code null}.
*/
@MapValue
Map<ProfessionWeaponType, ProfessionWeaponSkillSet> getWeapons();
/**
* Gets all training tracks in this profession.
* @return A non-modifiable {@code Set<ProfessionTrack>} instance, never {@code null}.
*/
@SetValue
Set<ProfessionTrack> getTraining();
}
| fabricebouye/gw2-web-api-mapping | src/api/web/gw2/mapping/v2/professions/Profession.java | Java | bsd-3-clause | 2,236 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Form
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: TableRow.php 24594 2012-01-05 21:27:01Z matthew $
*/
require_once 'Zend/Form/Decorator/Abstract.php';
/**
* Mock file for testbed
*
* @category Zend
* @package Zend_Form
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class My_Decorator_TableRow extends Zend_Form_Decorator_Abstract
{
/**
* Test Function for render
*
* @param string $content Content to display
* @return string
*/
public function render($content)
{
$e = $this->getElement();
return "<tr><td>{$e->getLabel()}</td><td>{$content}</td><td>{$e->getDescription()}</td></tr>";
}
}
| karthiksekarnz/educulas | tests/Zend/Form/_files/decorators/TableRow.php | PHP | bsd-3-clause | 1,481 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1008
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace XnatWebBrowser {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class SR {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal SR() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("XnatWebBrowser.SR", typeof(SR).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to AIM Tools.
/// </summary>
internal static string MenuAimTools {
get {
return ResourceManager.GetString("MenuAimTools", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to XNAT Imaging.
/// </summary>
internal static string MenuXnatImaging {
get {
return ResourceManager.GetString("MenuXnatImaging", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to XNAT Imaging.
/// </summary>
internal static string WorkspaceName {
get {
return ResourceManager.GetString("WorkspaceName", resourceCulture);
}
}
}
}
| NCIP/annotation-and-image-markup | AimPlugin4.5/XnatWebBrowser/SR.Designer.cs | C# | bsd-3-clause | 3,623 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__delete_array_class_malloc_18.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete_array.label.xml
Template File: sources-sinks-18.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: malloc Allocate data using malloc()
* GoodSource: Allocate data using new []
* Sinks:
* GoodSink: Deallocate data using free()
* BadSink : Deallocate data using delete []
* Flow Variant: 18 Control flow: goto statements
* */
#include "std_testcase.h"
namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_class_malloc_18
{
#ifndef OMITBAD
void bad()
{
TwoIntsClass * data;
/* Initialize data*/
data = NULL;
goto source;
source:
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (TwoIntsClass *)malloc(100*sizeof(TwoIntsClass));
if (data == NULL) {exit(-1);}
goto sink;
sink:
/* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete [] data;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G() - use badsource and goodsink by reversing the blocks on the second goto statement */
static void goodB2G()
{
TwoIntsClass * data;
/* Initialize data*/
data = NULL;
goto source;
source:
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (TwoIntsClass *)malloc(100*sizeof(TwoIntsClass));
if (data == NULL) {exit(-1);}
goto sink;
sink:
/* FIX: Free memory using free() */
free(data);
}
/* goodG2B() - use goodsource and badsink by reversing the blocks on the first goto statement */
static void goodG2B()
{
TwoIntsClass * data;
/* Initialize data*/
data = NULL;
goto source;
source:
/* FIX: Allocate memory using new [] */
data = new TwoIntsClass[100];
goto sink;
sink:
/* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete [] data;
}
void good()
{
goodB2G();
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 CWE762_Mismatched_Memory_Management_Routines__delete_array_class_malloc_18; /* 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/CWE762_Mismatched_Memory_Management_Routines/s01/CWE762_Mismatched_Memory_Management_Routines__delete_array_class_malloc_18.cpp | C++ | bsd-3-clause | 3,254 |
"""
Concurrent downloaders
"""
import os
import sys
import signal
import logging
import itertools
from functools import partial
from concurrent.futures import ProcessPoolExecutor
from pomp.core.base import (
BaseCrawler, BaseDownloader, BaseCrawlException,
)
from pomp.contrib.urllibtools import UrllibDownloadWorker
from pomp.core.utils import iterator, Planned
log = logging.getLogger('pomp.contrib.concurrent')
def _run_download_worker(params, request):
pid = os.getpid()
log.debug("Download worker pid=%s params=%s", pid, params)
try:
# Initialize worker and call get_one method
return params['worker_class'](
**params.get('worker_kwargs', {})
).process(request)
except Exception:
log.exception(
"Exception on download worker pid=%s request=%s", pid, request
)
raise
def _run_crawler_worker(params, response):
pid = os.getpid()
log.debug("Crawler worker pid=%s params=%s", pid, params)
try:
# Initialize crawler worker
worker = params['worker_class'](**params.get('worker_kwargs', {}))
# process response
items = worker.extract_items(response)
next_requests = worker.next_requests(response)
if next_requests:
return list(
itertools.chain(
iterator(items),
iterator(next_requests),
)
)
return list(iterator(items))
except Exception:
log.exception(
"Exception on crawler worker pid=%s request=%s", pid, response
)
raise
class ConcurrentMixin(object):
def _done(self, request, done_future, future):
try:
response = future.result()
except Exception as e:
log.exception('Exception on %s', request)
done_future.set_result(BaseCrawlException(
request,
exception=e,
exc_info=sys.exc_info(),
))
else:
done_future.set_result(response)
class ConcurrentDownloader(BaseDownloader, ConcurrentMixin):
"""Concurrent ProcessPoolExecutor downloader
:param pool_size: size of ThreadPoolExecutor
:param timeout: request timeout in seconds
"""
def __init__(
self, worker_class,
worker_kwargs=None, pool_size=5,):
# configure executor
self.pool_size = pool_size
self.executor = ProcessPoolExecutor(max_workers=self.pool_size)
# prepare worker params
self.worker_params = {
'worker_class': worker_class,
'worker_kwargs': worker_kwargs or {},
}
# ctrl-c support for python2.x
# trap sigint
signal.signal(signal.SIGINT, lambda s, f: s)
super(ConcurrentDownloader, self).__init__()
def process(self, crawler, request):
# delegate request processing to the executor
future = self.executor.submit(
_run_download_worker, self.worker_params, request,
)
# build Planned object
done_future = Planned()
# when executor finish request - fire done_future
future.add_done_callback(
partial(self._done, request, done_future)
)
return done_future
def get_workers_count(self):
return self.pool_size
def stop(self, crawler):
self.executor.shutdown()
class ConcurrentUrllibDownloader(ConcurrentDownloader):
"""Concurrent ProcessPoolExecutor downloader for fetching data with urllib
:class:`pomp.contrib.SimpleDownloader`
:param pool_size: pool size of ProcessPoolExecutor
:param timeout: request timeout in seconds
"""
def __init__(self, pool_size=5, timeout=None):
super(ConcurrentUrllibDownloader, self).__init__(
pool_size=pool_size,
worker_class=UrllibDownloadWorker,
worker_kwargs={
'timeout': timeout
},
)
class ConcurrentCrawler(BaseCrawler, ConcurrentMixin):
"""Concurrent ProcessPoolExecutor crawler
:param pool_size: pool size of ProcessPoolExecutor
:param timeout: request timeout in seconds
"""
def __init__(self, worker_class, worker_kwargs=None, pool_size=5):
# configure executor
self.pool_size = pool_size
self.executor = ProcessPoolExecutor(max_workers=self.pool_size)
# prepare worker params
self.worker_params = {
'worker_class': worker_class,
'worker_kwargs': worker_kwargs or {},
}
# inherit ENTRY_REQUESTS from worker_class
self.ENTRY_REQUESTS = getattr(worker_class, 'ENTRY_REQUESTS', None)
def process(self, response):
# delegate response processing to the executor
future = self.executor.submit(
_run_crawler_worker, self.worker_params, response,
)
# build Planned object
done_future = Planned()
# when executor finish response processing - fire done_future
future.add_done_callback(
partial(self._done, response, done_future)
)
return done_future
| estin/pomp | pomp/contrib/concurrenttools.py | Python | bsd-3-clause | 5,193 |
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model common\models\Docreceive */
$this->title = 'Update Docreceive: ' . $model->id;
$this->params['breadcrumbs'][] = ['label' => 'Docreceives', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = 'Update';
?>
<div class="docreceive-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
| N1kolayS/PCExpert | backend/views/docreceive/update.php | PHP | bsd-3-clause | 538 |
var map;
window.onload = function() {
var mm = com.modestmaps;
var dmap = document.getElementById('map');
wax.tilejson('https://a.tiles.mapbox.com/v3/examples.map-i86l3621.jsonp',
function(tj) {
map = new com.modestmaps.Map(dmap,
new wax.mm.connector(tj), null, [
easey_handlers.DragHandler(),
easey_handlers.TouchHandler(),
easey_handlers.MouseWheelHandler(),
easey_handlers.DoubleClickHandler()
]);
map.setCenterZoom(new com.modestmaps.Location(-10, 50), 3);
map.addCallback('zoomed', function() {
// console.log(map.getZoom());
});
var pres = document.getElementsByTagName('pre');
for (var i = 0; i < pres.length; i++) {
pres[i].onclick = function() {
eval(this.innerHTML);
};
}
var scrolly = document.getElementById('scrolly');
var positions = [
map.locationCoordinate({ lat: 33.5, lon: 65.6 }).zoomTo(6),
map.locationCoordinate({ lat: 33.1, lon: 44.6 }).zoomTo(6),
map.locationCoordinate({ lat: 28.7, lon: 69.2 }).zoomTo(6)];
var ea = easey().map(map).easing('easeInOut');
function update() {
var pos = scrolly.scrollTop / 200;
ea.from(positions[Math.floor(pos)])
.to(positions[Math.ceil(pos)])
.t(pos - Math.floor(pos));
}
scrolly.addEventListener('scroll', update, false);
});
};
| mapbox/easey-DEAD | index.js | JavaScript | bsd-3-clause | 1,531 |
#ifndef FUNCTION_TRAITS_HPP_071DD1DD_F933_40DC_A662_CB85F7BE7F00
#define FUNCTION_TRAITS_HPP_071DD1DD_F933_40DC_A662_CB85F7BE7F00
#pragma once
/*
function_traits.hpp
*/
/*
Copyright © 2014 Far Group
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <tuple>
//----------------------------------------------------------------------------
namespace detail
{
template<typename result, typename, typename... args>
struct function_traits_impl
{
using result_type = result;
static constexpr auto arity = sizeof...(args);
template<size_t i>
using arg = std::tuple_element_t<i, std::tuple<args...>>;
};
}
template<typename object>
struct function_traits: function_traits<decltype(&object::operator())> {};
template<typename result, typename... args>
struct function_traits<result(args...)>: ::detail::function_traits_impl<result, void, args...> {};
template<typename result, typename... args>
struct function_traits<result(*)(args...)>: ::detail::function_traits_impl<result, void, args...> {};
template<typename result, typename object, typename... args>
struct function_traits<result(object::*)(args...)>: ::detail::function_traits_impl<result, object, args...> {};
template<typename result, typename object, typename... args>
struct function_traits<result(object::*)(args...) const>: ::detail::function_traits_impl<result, object, args...> {};
#define FN_RETURN_TYPE(...) std::decay_t<function_traits<decltype(&__VA_ARGS__)>::result_type>
#endif // FUNCTION_TRAITS_HPP_071DD1DD_F933_40DC_A662_CB85F7BE7F00
| FarGroup/FarManager | far/common/function_traits.hpp | C++ | bsd-3-clause | 2,852 |
/*
- Fahre zu Position Start
- Falls nicht moeglich, emergencyStop
- Mache x milisekunden Xsens-Following, dann einen Turn
- Falls nicht moeglich, state ueberspringen
- Fahre zu Position B
- Falls nicht moeglich, emergencyStop
- Mache Turn 180
- Falls nicht moeglich, state ueberspringen
- Fahre zu Position End
- Falls nicht moeglich, emergencyStop
*/
#include "taskxsensnavigation.h"
#include "taskxsensnavigationform.h"
#include <QtGui>
#include <Module_Simulation/module_simulation.h>
#include <Behaviour_XsensFollowing/behaviour_xsensfollowing.h>
#include <Module_Navigation/module_navigation.h>
#include <Behaviour_TurnOneEighty/behaviour_turnoneeighty.h>
TaskXsensNavigation::TaskXsensNavigation(QString id, Module_Simulation *sim, Behaviour_XsensFollowing *xf, Module_Navigation *n, Behaviour_TurnOneEighty *o180)
: RobotBehaviour(id)
{
this->sim = sim;
this->xsensfollow = xf;
this->navi = n;
this->turn180 = o180;
}
bool TaskXsensNavigation::isActive(){
return active;
}
void TaskXsensNavigation::init(){
logger->debug("taskxsensnavigation init");
active = false;
setEnabled(false);
// Default task settings
this->setDefaultValue("description", "");
this->setDefaultValue("taskStopTime",120000);
this->setDefaultValue("signalTimer",1000);
this->setDefaultValue("startNavigation", "a");
this->setDefaultValue("startTolerance", 2);
this->setDefaultValue("bNavigation", "b");
this->setDefaultValue("bTolerance", 2);
this->setDefaultValue("targetNavigation", "c");
this->setDefaultValue("targetTolerance", 2);
this->setDefaultValue("timerActivated", true);
this->setDefaultValue("loopActivated", true);
// Default xsensfollow settings
this->setDefaultValue("ffSpeed", 0.5);
this->setDefaultValue("kp", 0.4);
this->setDefaultValue("delta", 10);
this->setDefaultValue("timer", 30);
this->setDefaultValue("driveTime", 10000);
this->setDefaultValue("waitTime", 10000);
// Default turn180 settings
this->setDefaultValue("hysteresis", 10);
this->setDefaultValue("p", 0.4);
this->setDefaultValue("degree", 180);
taskTimer.setSingleShot(true);
taskTimer.moveToThread(this);
connect(this, SIGNAL(enabled(bool)), this, SLOT(controlEnabledChanged(bool)));
connect(navi, SIGNAL(reachedWaypoint(QString)), this, SLOT(reachedWaypoint(QString)));
connect(turn180, SIGNAL(turn180finished()), this, SLOT(turn180Finished()));
connect(this, SIGNAL(setNewWaypoint(QString)), navi, SLOT(gotoWayPoint(QString)));
}
void TaskXsensNavigation::startBehaviour(){
if (isActive()){
logger->info("Already active!");
return;
}
this->reset();
logger->info("Taskxsensnavigation started" );
setHealthToOk();
// Stateoverview
emit newStateOverview("Move to start");
emit newStateOverview("Do xsensfollowing");
emit newStateOverview("Move to B");
emit newStateOverview("Turn180");
emit newStateOverview("Move to end");
if(this->getSettingsValue("loopActivated").toBool()){
emit newStateOverview("...in a loop");
}
active = true;
if(!isEnabled()){
setEnabled(true);
}
emit started(this);
// Enable all components
if(!this->navi->isEnabled()) {
this->navi->setEnabled(true);
}
state = XSENS_NAV_STATE_MOVE_START;
addData("loop", this->getSettingsValue("loopActivated").toBool());
addData("timer", this->getSettingsValue("timerActivated").toBool());
addData("state", state);
emit dataChanged(this);
emit updateSettings();
if(this->getSettingsValue("timerActivated").toBool()){
logger->debug("Taskxsensnavigation with timer stop");
taskTimer.singleShot(this->getSettingsValue("taskStopTime").toInt(),this, SLOT(timeoutStop()));
taskTimer.start();
}
taskTimer.singleShot(0, this, SLOT(stateChanged()));
}
void TaskXsensNavigation::stateChanged()
{
if(!isActive()){
return;
}
if (state == XSENS_NAV_STATE_MOVE_START) {
if (this->navi->getHealthStatus().isHealthOk()) {
logger->debug("move to start");
emit setNewWaypoint(this->getSettingsValue("startNavigation").toString());
} else {
logger->info("move to start not possible!");
emergencyStop();
}
} else if (state == XSENS_NAV_STATE_FOLLOW_XSENS) {
if (this->xsensfollow->getHealthStatus().isHealthOk()) {
logger->debug("xsens following");
initBehaviourParameters();
if (!this->xsensfollow->isEnabled()) {
logger->debug("enable xsensfollow");
QTimer::singleShot(0, xsensfollow, SLOT(startBehaviour()));
} else {
QTimer::singleShot(0, xsensfollow, SLOT(reset()));
}
// Finish state after drivetime msec and a little bit time to finish turn
int tempWait = this->getSettingsValue("driveTime").toInt() + this->getSettingsValue("waitTime").toInt();
QTimer::singleShot(tempWait, this, SLOT(xsensFollowFinished()));
} else {
logger->info("xsens following not possible!");
state = XSENS_NAV_STATE_MOVE_B;
QTimer::singleShot(0, this, SLOT(stateChanged()));
}
} else if (state == XSENS_NAV_STATE_MOVE_B) {
if (this->navi->getHealthStatus().isHealthOk()) {
logger->debug("move to B");
emit setNewWaypoint(this->getSettingsValue("bNavigation").toString());
} else {
logger->info("move to B not possible!");
emergencyStop();
}
} else if (state == XSENS_NAV_STATE_TURN_180) {
if(this->turn180->getHealthStatus().isHealthOk()) {
logger->debug("turn 180 degrees");
initBehaviourParameters();
if (!this->turn180->isEnabled()){
logger->debug("enable turn180");
QTimer::singleShot(0, turn180, SLOT(startBehaviour()));
} else {
QTimer::singleShot(0, turn180, SLOT(reset()));
}
} else {
logger->info("turn 180 degrees not possible!");
state = XSENS_NAV_STATE_MOVE_END;
QTimer::singleShot(0, this, SLOT(stateChanged()));
}
} else if (state == XSENS_NAV_STATE_MOVE_END) {
if (this->navi->getHealthStatus().isHealthOk()) {
logger->debug("move to end");
emit setNewWaypoint(this->getSettingsValue("targetNavigation").toString());
} else {
logger->info("move to end not possible!");
emergencyStop();
}
} else if (state == XSENS_NAV_STATE_DONE) {
logger->debug("idle, controlNextState");
if(this->getSettingsValue("loopActivated").toBool()){
logger->debug("start again");
state = XSENS_NAV_STATE_MOVE_START;
QTimer::singleShot(0, this, SLOT(stateChanged()));
} else {
// Task finished, stop
stop();
}
}
addData("state", state);
emit dataChanged(this);
QString navstate = this->navi->getDataValue("state").toString();
QString navsubstate = this->navi->getDataValue("substate").toString();
QString stateComment = state + " - "+ navstate + " - " + navsubstate;
emit newState(this->getId(),stateComment);
}
void TaskXsensNavigation::initBehaviourParameters()
{
if (state == XSENS_NAV_STATE_FOLLOW_XSENS) {
this->xsensfollow->setSettingsValue("ffSpeed", this->getSettingsValue("ffSpeed").toString());
this->xsensfollow->setSettingsValue("kp", this->getSettingsValue("kp").toString());
this->xsensfollow->setSettingsValue("delta", this->getSettingsValue("delta").toString());
this->xsensfollow->setSettingsValue("timer", this->getSettingsValue("timer").toString());
this->xsensfollow->setSettingsValue("turnClockwise", true);
this->xsensfollow->setSettingsValue("driveTime", this->getSettingsValue("driveTime").toString());
} else if (state == XSENS_NAV_STATE_TURN_180) {
this->turn180->setSettingsValue("hysteresis", this->getSettingsValue("hysteresis").toFloat());
this->turn180->setSettingsValue("p", this->getSettingsValue("p").toFloat());
this->turn180->setSettingsValue("degree", this->getSettingsValue("degree").toFloat());
}
}
void TaskXsensNavigation::reachedWaypoint(QString)
{
if (state == XSENS_NAV_STATE_MOVE_START) {
state = XSENS_NAV_STATE_FOLLOW_XSENS;
} else if (state == XSENS_NAV_STATE_MOVE_B) {
state = XSENS_NAV_STATE_TURN_180;
} else if (state == XSENS_NAV_STATE_MOVE_END) {
state = XSENS_NAV_STATE_DONE;
}
taskTimer.singleShot(0, this, SLOT(stateChanged()));
}
void TaskXsensNavigation::xsensFollowFinished()
{
QTimer::singleShot(0, xsensfollow, SLOT(stop()));
state = XSENS_NAV_STATE_MOVE_B;
taskTimer.singleShot(0, this, SLOT(stateChanged()));
}
void TaskXsensNavigation::turn180Finished()
{
QTimer::singleShot(0, turn180, SLOT(stop()));
state = XSENS_NAV_STATE_MOVE_END;
taskTimer.singleShot(0, this, SLOT(stateChanged()));
}
void TaskXsensNavigation::stop(){
if(!isActive()){
logger->info("Not active!");
return;
}
logger->info("Taskxsensnavigation stopped");
active = false;
setEnabled(false);
this->taskTimer.stop();
this->navi->setEnabled(false);
this->xsensfollow->setEnabled(false);
QTimer::singleShot(0, xsensfollow, SLOT(stop()));
emit finished(this,true);
}
void TaskXsensNavigation::timeoutStop(){
if(!isActive()){
return;
}
logger->info("Taskxsensnavigation timeout stopped");
active = false;
setEnabled(false);
this->taskTimer.stop();
this->navi->setEnabled(false);
this->xsensfollow->setEnabled(false);
QTimer::singleShot(0, xsensfollow, SLOT(stop()));
emit finished(this,false);
}
void TaskXsensNavigation::emergencyStop(){
if (!isActive()){
logger->info("Not active, no emergency stop needed");
return;
}
logger->info("Taskxsensnavigation emergency stopped");
active = false;
setEnabled(false);
this->taskTimer.stop();
this->navi->setEnabled(false);
this->xsensfollow->setEnabled(false);
QTimer::singleShot(0, xsensfollow, SLOT(stop()));
emit finished(this,false);
}
void TaskXsensNavigation::terminate()
{
this->stop();
RobotModule::terminate();
}
QWidget* TaskXsensNavigation::createView(QWidget *parent)
{
return new TaskXsensNavigationForm(this, parent);
}
QList<RobotModule*> TaskXsensNavigation::getDependencies()
{
QList<RobotModule*> ret;
ret.append(xsensfollow);
ret.append(sim);
return ret;
}
void TaskXsensNavigation::controlEnabledChanged(bool enabled){
if(!enabled && isActive()){
logger->info("Disable and deactivate TaskXsensNavigation");
stop();
} else if(!enabled && !isActive()){
//logger->info("Still deactivated");
} else if(enabled && !isActive()){
//logger->info("Enable and activate TaskXsensNavigation");
//startBehaviour();
} else {
//logger->info("Still activated");
}
}
| iti-luebeck/HANSE2011 | Hanse/TaskXsensNavigation/taskxsensnavigation.cpp | C++ | bsd-3-clause | 11,340 |
/**
*
*/
package gov.nih.nci.cagrid.portal.portlet.discovery.list;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.springframework.orm.hibernate3.HibernateTemplate;
import gov.nih.nci.cagrid.portal.domain.DomainObject;
import gov.nih.nci.cagrid.portal.portlet.discovery.dir.AbstractDirectoryBean;
import gov.nih.nci.cagrid.portal.portlet.util.Scroller;
/**
* @author <a href="mailto:joshua.phillips@semanticbits.com">Joshua Phillips</a>
*
*/
public class ListBean extends AbstractDirectoryBean {
private String type;
private Scroller scroller;
private HibernateTemplate hibernateTemplate;
/**
*
*/
public ListBean() {
}
public void refresh() {
List refreshed = new ArrayList();
for(Iterator i = getScroller().getObjects().iterator(); i.hasNext();){
DomainObject obj = (DomainObject)i.next();
obj = (DomainObject)getHibernateTemplate().get(obj.getClass(), obj.getId());
if(obj != null){
refreshed.add(obj);
}
}
getScroller().setObjects(refreshed);
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Scroller getScroller() {
return scroller;
}
public void setScroller(Scroller scroller) {
this.scroller = scroller;
}
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
}
| NCIP/cagrid | cagrid/Software/portal/cagrid-portal/portlets/src/java/gov/nih/nci/cagrid/portal/portlet/discovery/list/ListBean.java | Java | bsd-3-clause | 1,495 |
<?php
require __DIR__ . '/src/Beers/Module.php'; | fxcosta/APIgility-skeleton | module/Beers/Module.php | PHP | bsd-3-clause | 48 |
/*
Copyright (c) 2007, Robert Wallström, smithimage.com
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* 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 SMITHIMAGE 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.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace MIMER.RFC822
{
public class Field
{
protected string m_Name;
public string Name
{
get { return m_Name; }
set { m_Name = value; }
}
protected string m_Body;
public string Body
{
get { return m_Body; }
set { m_Body = value; }
}
}
}
| smithimage/MIMER | MIMER/RFC822/Field.cs | C# | bsd-3-clause | 2,010 |
package com.jamierf.rsc.dataserver.api;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class SessionCredentials extends UserCredentials {
public static boolean isValid(String username, String password, int[] keys) {
return UserCredentials.isValid(username, password) && keys != null && keys.length == 4;
}
@JsonProperty
private int clientVersion;
@JsonProperty
private int[] keys;
@JsonCreator
public SessionCredentials(
@JsonProperty("username") String username,
@JsonProperty("password") String password,
@JsonProperty("clientVersion") int clientVersion,
@JsonProperty("keys") int[] keys) {
super(username, password);
this.clientVersion = clientVersion;
this.keys = keys;
}
public int getClientVersion() {
return clientVersion;
}
public int[] getKeys() {
return keys;
}
}
| reines/rsc | dataserver/dataserver-api/src/main/java/com/jamierf/rsc/dataserver/api/SessionCredentials.java | Java | bsd-3-clause | 998 |
<?php
/**
* @see https://github.com/laminas/laminas-view for the canonical source repository
* @copyright https://github.com/laminas/laminas-view/blob/master/COPYRIGHT.md
* @license https://github.com/laminas/laminas-view/blob/master/LICENSE.md New BSD License
*/
namespace Laminas\View\Helper;
use Laminas\View\Exception;
/**
* Helper for ordered and unordered lists
*/
class HtmlList extends AbstractHtmlElement
{
/**
* Generates a 'List' element.
*
* @param array $items Array with the elements of the list
* @param bool $ordered Specifies ordered/unordered list; default unordered
* @param array $attribs Attributes for the ol/ul tag.
* @param bool $escape Escape the items.
* @throws Exception\InvalidArgumentException
* @return string The list XHTML.
*/
public function __invoke(array $items, $ordered = false, $attribs = false, $escape = true)
{
if (empty($items)) {
throw new Exception\InvalidArgumentException(sprintf(
'$items array can not be empty in %s',
__METHOD__
));
}
$list = '';
foreach ($items as $item) {
if (! is_array($item)) {
if ($escape) {
$escaper = $this->getView()->plugin('escapeHtml');
$item = $escaper($item);
}
$list .= '<li>' . $item . '</li>' . PHP_EOL;
} else {
$itemLength = 5 + strlen(PHP_EOL);
if ($itemLength < strlen($list)) {
$list = substr($list, 0, strlen($list) - $itemLength)
. $this($item, $ordered, $attribs, $escape) . '</li>' . PHP_EOL;
} else {
$list .= '<li>' . $this($item, $ordered, $attribs, $escape) . '</li>' . PHP_EOL;
}
}
}
if ($attribs) {
$attribs = $this->htmlAttribs($attribs);
} else {
$attribs = '';
}
$tag = ($ordered) ? 'ol' : 'ul';
return '<' . $tag . $attribs . '>' . PHP_EOL . $list . '</' . $tag . '>' . PHP_EOL;
}
}
| deforay/odkdash | vendor/laminas/laminas-view/src/Helper/HtmlList.php | PHP | bsd-3-clause | 2,190 |
<?php
use yii\helpers\Html;
/**
* @var yii\web\View $this
* @var app\models\UnidadeGeografica $model
*/
$this->title = 'Editar Unidade Geográfica ' . $model->getLabel() . '';
$this->params['breadcrumbs'][] = ['label' => 'Unidades Geográficas', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => (string) $model->getLabel(), 'url' => ['view', 'idUnidadeGeografica' => $model->idUnidadeGeografica]];
$this->params['breadcrumbs'][] = 'Editar';
?>
<div class="unidade-geografica-update">
<p>
<?= Html::a('<span class="glyphicon glyphicon-eye-open"></span> Detalhes', ['view', 'idUnidadeGeografica' => $model->idUnidadeGeografica], ['class' => 'btn btn-info']) ?>
</p>
<?php
echo $this->render('_form', [
'model' => $model,
]);
?>
</div>
| schvarcz/SisBIO | views/unidade-geografica/update.php | PHP | bsd-3-clause | 798 |
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/importer/firefox_importer_utils.h"
#include "base/file_util.h"
FilePath GetProfilesINI() {
FilePath ini_file;
// The default location of the profile folder containing user data is
// under user HOME directory in .mozilla/firefox folder on Linux.
const char *home = getenv("HOME");
if (home && home[0]) {
ini_file = FilePath(home).Append(".mozilla/firefox/profiles.ini");
}
if (file_util::PathExists(ini_file))
return ini_file;
return FilePath();
}
| rwatson/chromium-capsicum | chrome/browser/importer/firefox_importer_utils_linux.cc | C++ | bsd-3-clause | 670 |
<!-- BEGIN AUTHORED CONTENT -->
<p id="classSummary">
The <code>chrome.types</code> module contains type declarations for Chrome.
Currently this comprises only a prototype for giving other
modules access to manage Chrome browser settings. This prototype is used,
for example, for <a
href="proxy.html#property-settings"><code>chrome.proxy.settings</code></a>.
</p>
<h2 id="ChromeSetting">Chrome settings</h2>
<p>
The <code>ChromeSetting</code> prototype provides a common set of functions
(<code>get()</code>, <code>set()</code>, and <code>clear()</code>) as
well as an event publisher (<code>onChange</code>) for settings of the
Chrome browser. The <a href="proxy.html#overview-examples">proxy settings
examples</a> demonstrate how these functions are intended to be used.
</p>
<h3 id="ChromeSetting-lifecycle">Scope and life cycle</h3>
<p>
Chrome distinguishes between three different scopes of browser settings:
<dl>
<dt><code>regular</code></dt>
<dd>Settings set in the <code>regular</code> scope apply to regular
browser windows and are inherited by incognito windows if they are not
overwritten. These settings are stored to disk and remain in place until
they are cleared by the governing extension, or the governing extension is
disabled or uninstalled.</dd>
<dt><code>incognito_persistent</code></dt>
<dd>Settings set in the <code>incognito_persistent</code> scope apply only
to incognito windows. For these, they override <code>regular</code>
settings. These settings are stored to disk and remain in place until
they are cleared by the governing extension, or the governing extension is
disabled or uninstalled.</dd>
<dt><code>incognito_session_only</code></dt>
<dd>Settings set in the <code>incognito_session_only</code> scope apply only
to incognito windows. For these, they override <code>regular</code> and
<code>incognito_session_only</code> settings. These settings are not
stored to disk and are cleared when the last incognito window is closed. They
can only be set when at least one incognito window is open.</dd>
</dl>
</p>
<h3 id="ChromeSetting-precedence">Precedence</h3>
<p>
Chrome manages settings on different layers. The following list describes the
layers that may influence the effective settings, in increasing order of
precedence.
<ol>
<li>System settings provided by the operating system</li>
<li>Command-line parameters</li>
<li>Settings provided by extensions</li>
<li>Policies</li>
</ol>
</p>
<p>
As the list implies, policies might overrule any changes that you specify with
your extension. You can use the <code>get()</code> function to determine whether
your extension is capable of providing a setting or whether this setting would
be overridden.
</p>
<p>
As discussed above, Chrome allows using different settings for regular
windows and incognito windows. The following example illustrates the behavior.
Assume that no policy overrides the settings and that an extension can set
settings for regular windows <b>(R)</b> and settings for incognito windows
<b>(I)</b>.
</p>
<p>
<ul>
<li>If only <b>(R)</b> is set, these settings are effective for both
regular and incognito windows.</li>
<li>If only <b>(I)</b> is set, these settings are effective for only
incognito windows. Regular windows use the settings determined by the lower
layers (command-line options and system settings).</li>
<li>If both <b>(R)</b> and <b>(I)</b> are set, the respective settings are
used for regular and incognito windows.</li>
</ul>
</p>
<p>
If two or more extensions want to set the same setting to different values,
the extension installed most recently takes precedence over the other
extensions. If the most recently installed extension sets only <b>(I)</b>, the
settings of regular windows can be defined by previously installed extensions.
</p>
<p>
The <em>effective</em> value of a setting is the one that results from
considering the precedence rules. It is used by Chrome.
<p>
<!-- END AUTHORED CONTENT -->
| keishi/chromium | chrome/common/extensions/docs/server2/templates/intros/types.html | HTML | bsd-3-clause | 4,011 |
// Copyright (c) 2016-2018 Vivaldi Technologies AS. All rights reserved
#include "extensions/api/access_keys/access_keys_api.h"
#include <vector>
#include "app/vivaldi_apptools.h"
#include "extensions/api/tabs/tabs_private_api.h"
#include "extensions/schema/access_keys.h"
#include "ui/vivaldi_ui_utils.h"
namespace extensions {
ExtensionFunction::ResponseAction
AccessKeysGetAccessKeysForPageFunction::Run() {
using vivaldi::access_keys::GetAccessKeysForPage::Params;
std::unique_ptr<Params> params = Params::Create(args());
EXTENSION_FUNCTION_VALIDATE(params.get());
std::string error;
VivaldiPrivateTabObserver* tab_api = VivaldiPrivateTabObserver::FromTabId(
browser_context(), params->tab_id, &error);
if (!tab_api)
return RespondNow(Error(error));
tab_api->GetAccessKeys(base::BindOnce(
&AccessKeysGetAccessKeysForPageFunction::AccessKeysReceived, this));
return RespondLater();
}
void AccessKeysGetAccessKeysForPageFunction::AccessKeysReceived(
std::vector<::vivaldi::mojom::AccessKeyPtr> access_keys) {
namespace Results = vivaldi::access_keys::GetAccessKeysForPage::Results;
std::vector<vivaldi::access_keys::AccessKeyDefinition> access_key_list;
for (auto& key : access_keys) {
vivaldi::access_keys::AccessKeyDefinition entry;
// The key elements will always be defined, but empty if the elements
// doesn't contain that attribute
entry.access_key = key->access_key;
entry.tagname = key->tagname;
entry.title = key->title;
entry.href = key->href;
entry.value = key->value;
entry.id = key->id;
entry.text_content = key->text_content;
access_key_list.push_back(std::move(entry));
}
Respond(ArgumentList(Results::Create(access_key_list)));
}
ExtensionFunction::ResponseAction AccessKeysActionFunction::Run() {
using vivaldi::access_keys::Action::Params;
std::unique_ptr<Params> params = Params::Create(args());
EXTENSION_FUNCTION_VALIDATE(params.get());
std::string id = params->id;
std::string error;
VivaldiPrivateTabObserver* tab_api = VivaldiPrivateTabObserver::FromTabId(
browser_context(), params->tab_id, &error);
if (!tab_api)
return RespondNow(Error(error));
tab_api->AccessKeyAction(id);
return RespondNow(NoArguments());
}
} // namespace extensions
| ric2b/Vivaldi-browser | extensions/api/access_keys/access_keys_api.cc | C++ | bsd-3-clause | 2,307 |
import {Content} from './Content';
export interface GuideCategory {
id: number;
name: string;
content: Content;
displayOrder: number;
summary: string;
description: string;
additionalInfo: string;
icon: string;
}
| UoA-eResearch/research-hub | src/app/model/GuideCategory.ts | TypeScript | bsd-3-clause | 229 |
/* Title: Tools/jEdit/src/font_info.scala
Author: Makarius
Font information, derived from main jEdit view font.
*/
package isabelle.jedit
import isabelle._
import java.awt.Font
import org.gjt.sp.jedit.{jEdit, View}
object Font_Info
{
/* size range */
val min_size = 5
val max_size = 250
def restrict_size(size: Float): Float = size max min_size min max_size
/* main jEdit font */
def main_family(): String = jEdit.getProperty("view.font")
def main_size(scale: Double = 1.0): Float =
restrict_size(jEdit.getIntegerProperty("view.fontsize", 16).toFloat * scale.toFloat)
def main(scale: Double = 1.0): Font_Info =
Font_Info(main_family(), main_size(scale))
/* incremental size change */
object main_change
{
private def change_size(change: Float => Float)
{
GUI_Thread.require {}
val size0 = main_size()
val size = restrict_size(change(size0)).round
if (size != size0) {
jEdit.setIntegerProperty("view.fontsize", size)
jEdit.propertiesChanged()
jEdit.saveSettings()
jEdit.getActiveView().getStatus.setMessageAndClear("Text font size: " + size)
}
}
// owned by GUI thread
private var steps = 0
private val delay = GUI_Thread.delay_last(PIDE.options.seconds("editor_input_delay"))
{
change_size(size =>
{
var i = size.round
while (steps != 0 && i > 0) {
if (steps > 0)
{ i += (i / 10) max 1; steps -= 1 }
else
{ i -= (i / 10) max 1; steps += 1 }
}
steps = 0
i.toFloat
})
}
def step(i: Int)
{
steps += i
delay.invoke()
}
def reset(size: Float)
{
delay.revoke()
steps = 0
change_size(_ => size)
}
}
/* zoom box */
abstract class Zoom_Box extends GUI.Zoom_Box { tooltip = "Zoom factor for output font size" }
}
sealed case class Font_Info(family: String, size: Float)
{
def font: Font = new Font(family, Font.PLAIN, size.round)
}
| MerelyAPseudonym/isabelle | src/Tools/jEdit/src/font_info.scala | Scala | bsd-3-clause | 2,074 |
package com.dslplatform.api.client
import com.dslplatform.api.patterns.AggregateRoot
import com.dslplatform.api.patterns.Identifiable
import scala.reflect.ClassTag
import scala.concurrent.Future
class HttpCrudProxy(httpClient: HttpClient)
extends CrudProxy {
import HttpClientUtil._
private val CrudUri = "Crud.svc"
def read[TIdentifiable <: Identifiable: ClassTag](
uri: String): Future[TIdentifiable] = {
val domainName: String = httpClient.getDslName[TIdentifiable]
httpClient.sendRequest[TIdentifiable](
GET, CrudUri / domainName + "?uri=" + encode(uri), Set(200))
}
def create[TAggregateRoot <: AggregateRoot: ClassTag](
aggregate: TAggregateRoot): Future[TAggregateRoot] = {
val service: String = CrudUri / httpClient.getDslName[TAggregateRoot]
httpClient.sendRequest[TAggregateRoot](
POST(aggregate), service, Set(201))
}
def update[TAggregate <: AggregateRoot: ClassTag](
aggregate: TAggregate): Future[TAggregate] = {
val uri: String = aggregate.URI
val domainName: String = httpClient.getDslName[TAggregate]
httpClient.sendRequest[TAggregate](
PUT(aggregate),
CrudUri / domainName + "?uri=" + encode(uri),
Set(200))
}
def delete[TAggregateRoot <: AggregateRoot: ClassTag](
uri: String): Future[TAggregateRoot] = {
val domainName: String = httpClient.getDslName[TAggregateRoot]
httpClient.sendRequest[TAggregateRoot](
DELETE,
CrudUri / domainName + "?uri=" + encode(uri),
Set(200))
}
}
| ngs-doo/dsl-client-scala | http/src/main/scala/com/dslplatform/api/client/HttpCrudProxy.scala | Scala | bsd-3-clause | 1,536 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include "base/threading/platform_thread.h"
#include "gpu/command_buffer/tests/gl_manager.h"
#include "gpu/command_buffer/tests/gl_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace gpu {
class QueryTest : public testing::Test {
protected:
virtual void SetUp() {
gl_.Initialize(gfx::Size(2, 2));
}
virtual void TearDown() {
gl_.Destroy();
}
GLManager gl_;
};
TEST_F(QueryTest, GetErrorBasic) {
EXPECT_TRUE(GLTestHelper::HasExtension("GL_CHROMIUM_get_error_query"));
GLuint query = 0;
glGenQueriesEXT(1, &query);
GLuint query_status = 0;
GLuint result = 0;
glBeginQueryEXT(GL_GET_ERROR_QUERY_CHROMIUM, query);
glEnable(GL_TEXTURE_2D); // Generates an INVALID_ENUM error
glEndQueryEXT(GL_GET_ERROR_QUERY_CHROMIUM);
glFinish();
query_status = 0;
result = 0;
glGetQueryObjectuivEXT(query, GL_QUERY_RESULT_AVAILABLE_EXT, &result);
EXPECT_TRUE(result);
glGetQueryObjectuivEXT(query, GL_QUERY_RESULT_EXT, &query_status);
EXPECT_EQ(static_cast<uint32>(GL_INVALID_ENUM), query_status);
}
TEST_F(QueryTest, DISABLED_LatencyQueryBasic) {
EXPECT_TRUE(GLTestHelper::HasExtension(
"GL_CHROMIUM_command_buffer_latency_query"));
GLuint query = 0;
glGenQueriesEXT(1, &query);
GLuint query_result = 0;
GLuint available = 0;
// First test a query with a ~1ms "latency".
const unsigned int kExpectedLatencyMicroseconds = 2000;
const unsigned int kTimePrecisionMicroseconds = 1000;
glBeginQueryEXT(GL_LATENCY_QUERY_CHROMIUM, query);
// Usually, we want to measure gpu-side latency, but we fake it by
// adding client side latency for our test because it's easier.
base::PlatformThread::Sleep(
base::TimeDelta::FromMicroseconds(kExpectedLatencyMicroseconds));
glEndQueryEXT(GL_LATENCY_QUERY_CHROMIUM);
glFinish();
query_result = 0;
available = 0;
glGetQueryObjectuivEXT(query, GL_QUERY_RESULT_AVAILABLE_EXT, &available);
EXPECT_TRUE(available);
glGetQueryObjectuivEXT(query, GL_QUERY_RESULT_EXT, &query_result);
EXPECT_GE(query_result, kExpectedLatencyMicroseconds
- kTimePrecisionMicroseconds);
EXPECT_LE(query_result, kExpectedLatencyMicroseconds
+ kTimePrecisionMicroseconds);
// Then test a query with the lowest latency possible.
glBeginQueryEXT(GL_LATENCY_QUERY_CHROMIUM, query);
glEndQueryEXT(GL_LATENCY_QUERY_CHROMIUM);
glFinish();
query_result = 0;
available = 0;
glGetQueryObjectuivEXT(query, GL_QUERY_RESULT_AVAILABLE_EXT, &available);
EXPECT_TRUE(available);
glGetQueryObjectuivEXT(query, GL_QUERY_RESULT_EXT, &query_result);
EXPECT_LE(query_result, kTimePrecisionMicroseconds);
}
} // namespace gpu
| junmin-zhu/chromium-rivertrail | gpu/command_buffer/tests/gl_query_unittests.cc | C++ | bsd-3-clause | 2,990 |
<?php
namespace Artist\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Class Genre
* @package Artist\Entity
* @ORM\Entity
* @ORM\Table(name="genres")
*/
class Genre {
/**
* @ORM\OneToMany(targetEntity="Artist", mappedBy="genre")
*/
private $artists;
/**
* @ORM\OneToMany(targetEntity="Genre", mappedBy="parentGenre")
*/
private $childrenGenres;
/**
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Column(type="integer", length=5, name="genre_id")
*/
private $genreId;
/**
* @ORM\Column(type="string", length=50)
*/
private $name;
/**
* @ORM\ManyToOne(targetEntity="Genre", inversedBy="childrenGenres")
* @ORM\JoinColumn(name="parent_genre_id", referencedColumnName="genre_id")
*/
private $parentGenre;
public function __construct(){
$this->artists = new ArrayCollection();
$this->childrenGenres = new ArrayCollection();
}
/**
* @return mixed
*/
public function getChildrenGenres()
{
return $this->childrenGenres;
}
/**
* @param mixed $childrenGenres
*/
public function setChildrenGenres($childrenGenres)
{
$this->childrenGenres = $childrenGenres;
}
public function addChildrenGenres($childrenGenres){
foreach($childrenGenres as $genre)
if(!$this->childrenGenres->contains($genre))
$this->childrenGenres->add($genre);
}
public function removeChildrenGenres($childrenGenres){
foreach($childrenGenres as $genre)
if($this->childrenGenres->contains($genre))
$this->childrenGenres->removeElement($genre);
}
/**
* @return mixed
*/
public function getGenreId()
{
return $this->genreId;
}
/**
* @param mixed $genreId
*/
public function setGenreId($genreId)
{
$this->genreId = $genreId;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return mixed
*/
public function getParentGenre()
{
return $this->parentGenre;
}
/**
* @param mixed $parentGenre
*/
public function setParentGenre($parentGenre)
{
$this->parentGenre = $parentGenre;
}
} | JoshBour/byband | module/Artist/src/Artist/Entity/Genre.php | PHP | bsd-3-clause | 2,512 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/predictors/autocomplete_action_predictor.h"
#include <math.h>
#include <vector>
#include "base/bind.h"
#include "base/guid.h"
#include "base/i18n/case_conversion.h"
#include "base/metrics/histogram.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/autocomplete/autocomplete_log.h"
#include "chrome/browser/autocomplete/autocomplete_match.h"
#include "chrome/browser/autocomplete/autocomplete_result.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/history/history_notifications.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/browser/history/in_memory_database.h"
#include "chrome/browser/predictors/autocomplete_action_predictor_factory.h"
#include "chrome/browser/predictors/predictor_database.h"
#include "chrome/browser/predictors/predictor_database_factory.h"
#include "chrome/browser/prerender/prerender_field_trial.h"
#include "chrome/browser/prerender/prerender_handle.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/prerender/prerender_manager_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
namespace {
const float kConfidenceCutoff[] = {
0.8f,
0.5f
};
COMPILE_ASSERT(arraysize(kConfidenceCutoff) ==
predictors::AutocompleteActionPredictor::LAST_PREDICT_ACTION,
ConfidenceCutoff_count_mismatch);
const size_t kMinimumUserTextLength = 1;
const int kMinimumNumberOfHits = 3;
enum DatabaseAction {
DATABASE_ACTION_ADD,
DATABASE_ACTION_UPDATE,
DATABASE_ACTION_DELETE_SOME,
DATABASE_ACTION_DELETE_ALL,
DATABASE_ACTION_COUNT
};
bool IsAutocompleteMatchSearchType(const AutocompleteMatch& match) {
switch (match.type) {
// Matches using the user's default search engine.
case AutocompleteMatch::SEARCH_WHAT_YOU_TYPED:
case AutocompleteMatch::SEARCH_HISTORY:
case AutocompleteMatch::SEARCH_SUGGEST:
// A match that uses a non-default search engine (e.g. for tab-to-search).
case AutocompleteMatch::SEARCH_OTHER_ENGINE:
return true;
default:
return false;
}
}
} // namespace
namespace predictors {
const int AutocompleteActionPredictor::kMaximumDaysToKeepEntry = 14;
AutocompleteActionPredictor::AutocompleteActionPredictor(Profile* profile)
: profile_(profile),
main_profile_predictor_(NULL),
incognito_predictor_(NULL),
initialized_(false) {
if (profile_->IsOffTheRecord()) {
main_profile_predictor_ = AutocompleteActionPredictorFactory::GetForProfile(
profile_->GetOriginalProfile());
DCHECK(main_profile_predictor_);
main_profile_predictor_->incognito_predictor_ = this;
if (main_profile_predictor_->initialized_)
CopyFromMainProfile();
} else {
// Request the in-memory database from the history to force it to load so
// it's available as soon as possible.
HistoryService* history_service =
profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
if (history_service)
history_service->InMemoryDatabase();
table_ =
PredictorDatabaseFactory::GetForProfile(profile_)->autocomplete_table();
// Create local caches using the database as loaded. We will garbage collect
// rows from the caches and the database once the history service is
// available.
std::vector<AutocompleteActionPredictorTable::Row>* rows =
new std::vector<AutocompleteActionPredictorTable::Row>();
content::BrowserThread::PostTaskAndReply(content::BrowserThread::DB,
FROM_HERE,
base::Bind(&AutocompleteActionPredictorTable::GetAllRows, table_, rows),
base::Bind(&AutocompleteActionPredictor::CreateCaches, AsWeakPtr(),
base::Owned(rows)));
}
}
AutocompleteActionPredictor::~AutocompleteActionPredictor() {
if (main_profile_predictor_)
main_profile_predictor_->incognito_predictor_ = NULL;
else if (incognito_predictor_)
incognito_predictor_->main_profile_predictor_ = NULL;
if (prerender_handle_.get())
prerender_handle_->OnCancel();
}
void AutocompleteActionPredictor::RegisterTransitionalMatches(
const string16& user_text,
const AutocompleteResult& result) {
if (user_text.length() < kMinimumUserTextLength)
return;
const string16 lower_user_text(base::i18n::ToLower(user_text));
// Merge this in to an existing match if we already saw |user_text|
std::vector<TransitionalMatch>::iterator match_it =
std::find(transitional_matches_.begin(), transitional_matches_.end(),
lower_user_text);
if (match_it == transitional_matches_.end()) {
TransitionalMatch transitional_match;
transitional_match.user_text = lower_user_text;
match_it = transitional_matches_.insert(transitional_matches_.end(),
transitional_match);
}
for (AutocompleteResult::const_iterator i(result.begin()); i != result.end();
++i) {
if (std::find(match_it->urls.begin(), match_it->urls.end(),
i->destination_url) == match_it->urls.end()) {
match_it->urls.push_back(i->destination_url);
}
}
}
void AutocompleteActionPredictor::ClearTransitionalMatches() {
transitional_matches_.clear();
}
void AutocompleteActionPredictor::StartPrerendering(
const GURL& url,
content::SessionStorageNamespace* session_storage_namespace,
const gfx::Size& size) {
if (prerender_handle_.get())
prerender_handle_->OnNavigateAway();
if (prerender::PrerenderManager* prerender_manager =
prerender::PrerenderManagerFactory::GetForProfile(profile_)) {
prerender_handle_.reset(
prerender_manager->AddPrerenderFromOmnibox(
url, session_storage_namespace, size));
} else {
prerender_handle_.reset();
}
}
// Given a match, return a recommended action.
AutocompleteActionPredictor::Action
AutocompleteActionPredictor::RecommendAction(
const string16& user_text,
const AutocompleteMatch& match) const {
bool is_in_db = false;
const double confidence = CalculateConfidence(user_text, match, &is_in_db);
DCHECK(confidence >= 0.0 && confidence <= 1.0);
UMA_HISTOGRAM_BOOLEAN("AutocompleteActionPredictor.MatchIsInDb", is_in_db);
if (is_in_db) {
// Multiple enties with the same URL are fine as the confidence may be
// different.
tracked_urls_.push_back(std::make_pair(match.destination_url, confidence));
UMA_HISTOGRAM_COUNTS_100("AutocompleteActionPredictor.Confidence",
confidence * 100);
}
// Map the confidence to an action.
Action action = ACTION_NONE;
for (int i = 0; i < LAST_PREDICT_ACTION; ++i) {
if (confidence >= kConfidenceCutoff[i]) {
action = static_cast<Action>(i);
break;
}
}
// Downgrade prerender to preconnect if this is a search match or if omnibox
// prerendering is disabled. There are cases when Instant will not handle a
// search suggestion and in those cases it would be good to prerender the
// search results, however search engines have not been set up to correctly
// handle being prerendered and until they are we should avoid it.
// http://crbug.com/117495
if (action == ACTION_PRERENDER &&
(IsAutocompleteMatchSearchType(match) ||
!prerender::IsOmniboxEnabled(profile_))) {
action = ACTION_PRECONNECT;
}
return action;
}
// Return true if the suggestion type warrants a TCP/IP preconnection.
// i.e., it is now quite likely that the user will select the related domain.
// static
bool AutocompleteActionPredictor::IsPreconnectable(
const AutocompleteMatch& match) {
return IsAutocompleteMatchSearchType(match);
}
void AutocompleteActionPredictor::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_HISTORY_URLS_DELETED: {
DCHECK(initialized_);
const content::Details<const history::URLsDeletedDetails>
urls_deleted_details =
content::Details<const history::URLsDeletedDetails>(details);
if (urls_deleted_details->all_history)
DeleteAllRows();
else
DeleteRowsWithURLs(urls_deleted_details->rows);
break;
}
// This notification does not catch all instances of the user navigating
// from the Omnibox, but it does catch the cases where the dropdown is open
// and those are the events we're most interested in.
case chrome::NOTIFICATION_OMNIBOX_OPENED_URL: {
DCHECK(initialized_);
// TODO(dominich): This doesn't need to be synchronous. Investigate
// posting it as a task to be run later.
OnOmniboxOpenedUrl(*content::Details<AutocompleteLog>(details).ptr());
break;
}
case chrome::NOTIFICATION_HISTORY_LOADED: {
TryDeleteOldEntries(content::Details<HistoryService>(details).ptr());
notification_registrar_.Remove(this,
chrome::NOTIFICATION_HISTORY_LOADED,
content::Source<Profile>(profile_));
break;
}
default:
NOTREACHED() << "Unexpected notification observed.";
break;
}
}
void AutocompleteActionPredictor::DeleteAllRows() {
if (!initialized_)
return;
db_cache_.clear();
db_id_cache_.clear();
if (table_.get()) {
content::BrowserThread::PostTask(content::BrowserThread::DB, FROM_HERE,
base::Bind(&AutocompleteActionPredictorTable::DeleteAllRows,
table_));
}
UMA_HISTOGRAM_ENUMERATION("AutocompleteActionPredictor.DatabaseAction",
DATABASE_ACTION_DELETE_ALL, DATABASE_ACTION_COUNT);
}
void AutocompleteActionPredictor::DeleteRowsWithURLs(
const history::URLRows& rows) {
if (!initialized_)
return;
std::vector<AutocompleteActionPredictorTable::Row::Id> id_list;
for (DBCacheMap::iterator it = db_cache_.begin(); it != db_cache_.end();) {
if (std::find_if(rows.begin(), rows.end(),
history::URLRow::URLRowHasURL(it->first.url)) != rows.end()) {
const DBIdCacheMap::iterator id_it = db_id_cache_.find(it->first);
DCHECK(id_it != db_id_cache_.end());
id_list.push_back(id_it->second);
db_id_cache_.erase(id_it);
db_cache_.erase(it++);
} else {
++it;
}
}
if (table_.get()) {
content::BrowserThread::PostTask(content::BrowserThread::DB, FROM_HERE,
base::Bind(&AutocompleteActionPredictorTable::DeleteRows, table_,
id_list));
}
UMA_HISTOGRAM_ENUMERATION("AutocompleteActionPredictor.DatabaseAction",
DATABASE_ACTION_DELETE_SOME, DATABASE_ACTION_COUNT);
}
void AutocompleteActionPredictor::OnOmniboxOpenedUrl(
const AutocompleteLog& log) {
if (log.text.length() < kMinimumUserTextLength)
return;
const AutocompleteMatch& match = log.result.match_at(log.selected_index);
UMA_HISTOGRAM_BOOLEAN(
StringPrintf("Prerender.OmniboxNavigationsCouldPrerender%s",
prerender::PrerenderManager::GetModeString()).c_str(),
prerender::IsOmniboxEnabled(profile_));
const GURL& opened_url = match.destination_url;
const string16 lower_user_text(base::i18n::ToLower(log.text));
// Traverse transitional matches for those that have a user_text that is a
// prefix of |lower_user_text|.
std::vector<AutocompleteActionPredictorTable::Row> rows_to_add;
std::vector<AutocompleteActionPredictorTable::Row> rows_to_update;
for (std::vector<TransitionalMatch>::const_iterator it =
transitional_matches_.begin(); it != transitional_matches_.end();
++it) {
if (!StartsWith(lower_user_text, it->user_text, true))
continue;
// Add entries to the database for those matches.
for (std::vector<GURL>::const_iterator url_it = it->urls.begin();
url_it != it->urls.end(); ++url_it) {
DCHECK(it->user_text.length() >= kMinimumUserTextLength);
const DBCacheKey key = { it->user_text, *url_it };
const bool is_hit = (*url_it == opened_url);
AutocompleteActionPredictorTable::Row row;
row.user_text = key.user_text;
row.url = key.url;
DBCacheMap::iterator it = db_cache_.find(key);
if (it == db_cache_.end()) {
row.id = base::GenerateGUID();
row.number_of_hits = is_hit ? 1 : 0;
row.number_of_misses = is_hit ? 0 : 1;
rows_to_add.push_back(row);
} else {
DCHECK(db_id_cache_.find(key) != db_id_cache_.end());
row.id = db_id_cache_.find(key)->second;
row.number_of_hits = it->second.number_of_hits + (is_hit ? 1 : 0);
row.number_of_misses = it->second.number_of_misses + (is_hit ? 0 : 1);
rows_to_update.push_back(row);
}
}
}
if (rows_to_add.size() > 0 || rows_to_update.size() > 0)
AddAndUpdateRows(rows_to_add, rows_to_update);
ClearTransitionalMatches();
// Check against tracked urls and log accuracy for the confidence we
// predicted.
for (std::vector<std::pair<GURL, double> >::const_iterator it =
tracked_urls_.begin(); it != tracked_urls_.end();
++it) {
if (opened_url == it->first) {
UMA_HISTOGRAM_COUNTS_100("AutocompleteActionPredictor.AccurateCount",
it->second * 100);
}
}
tracked_urls_.clear();
}
void AutocompleteActionPredictor::AddAndUpdateRows(
const AutocompleteActionPredictorTable::Rows& rows_to_add,
const AutocompleteActionPredictorTable::Rows& rows_to_update) {
if (!initialized_)
return;
for (AutocompleteActionPredictorTable::Rows::const_iterator it =
rows_to_add.begin(); it != rows_to_add.end(); ++it) {
const DBCacheKey key = { it->user_text, it->url };
DBCacheValue value = { it->number_of_hits, it->number_of_misses };
DCHECK(db_cache_.find(key) == db_cache_.end());
db_cache_[key] = value;
db_id_cache_[key] = it->id;
UMA_HISTOGRAM_ENUMERATION("AutocompleteActionPredictor.DatabaseAction",
DATABASE_ACTION_ADD, DATABASE_ACTION_COUNT);
}
for (AutocompleteActionPredictorTable::Rows::const_iterator it =
rows_to_update.begin(); it != rows_to_update.end(); ++it) {
const DBCacheKey key = { it->user_text, it->url };
DBCacheMap::iterator db_it = db_cache_.find(key);
DCHECK(db_it != db_cache_.end());
DCHECK(db_id_cache_.find(key) != db_id_cache_.end());
db_it->second.number_of_hits = it->number_of_hits;
db_it->second.number_of_misses = it->number_of_misses;
UMA_HISTOGRAM_ENUMERATION("AutocompleteActionPredictor.DatabaseAction",
DATABASE_ACTION_UPDATE, DATABASE_ACTION_COUNT);
}
if (table_.get()) {
content::BrowserThread::PostTask(content::BrowserThread::DB, FROM_HERE,
base::Bind(&AutocompleteActionPredictorTable::AddAndUpdateRows,
table_, rows_to_add, rows_to_update));
}
}
void AutocompleteActionPredictor::CreateCaches(
std::vector<AutocompleteActionPredictorTable::Row>* rows) {
CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
DCHECK(!profile_->IsOffTheRecord());
DCHECK(!initialized_);
DCHECK(db_cache_.empty());
DCHECK(db_id_cache_.empty());
for (std::vector<AutocompleteActionPredictorTable::Row>::const_iterator it =
rows->begin(); it != rows->end(); ++it) {
const DBCacheKey key = { it->user_text, it->url };
const DBCacheValue value = { it->number_of_hits, it->number_of_misses };
db_cache_[key] = value;
db_id_cache_[key] = it->id;
}
// If the history service is ready, delete any old or invalid entries.
HistoryService* history_service =
HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
if (!TryDeleteOldEntries(history_service)) {
// Wait for the notification that the history service is ready and the URL
// DB is loaded.
notification_registrar_.Add(this, chrome::NOTIFICATION_HISTORY_LOADED,
content::Source<Profile>(profile_));
}
}
bool AutocompleteActionPredictor::TryDeleteOldEntries(HistoryService* service) {
CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
DCHECK(!profile_->IsOffTheRecord());
DCHECK(!initialized_);
if (!service)
return false;
history::URLDatabase* url_db = service->InMemoryDatabase();
if (!url_db)
return false;
DeleteOldEntries(url_db);
return true;
}
void AutocompleteActionPredictor::DeleteOldEntries(
history::URLDatabase* url_db) {
CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
DCHECK(!profile_->IsOffTheRecord());
DCHECK(!initialized_);
DCHECK(table_.get());
std::vector<AutocompleteActionPredictorTable::Row::Id> ids_to_delete;
DeleteOldIdsFromCaches(url_db, &ids_to_delete);
content::BrowserThread::PostTask(content::BrowserThread::DB, FROM_HERE,
base::Bind(&AutocompleteActionPredictorTable::DeleteRows, table_,
ids_to_delete));
FinishInitialization();
if (incognito_predictor_)
incognito_predictor_->CopyFromMainProfile();
}
void AutocompleteActionPredictor::DeleteOldIdsFromCaches(
history::URLDatabase* url_db,
std::vector<AutocompleteActionPredictorTable::Row::Id>* id_list) {
CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
DCHECK(!profile_->IsOffTheRecord());
DCHECK(!initialized_);
DCHECK(url_db);
DCHECK(id_list);
id_list->clear();
for (DBCacheMap::iterator it = db_cache_.begin(); it != db_cache_.end();) {
history::URLRow url_row;
if ((url_db->GetRowForURL(it->first.url, &url_row) == 0) ||
((base::Time::Now() - url_row.last_visit()).InDays() >
kMaximumDaysToKeepEntry)) {
const DBIdCacheMap::iterator id_it = db_id_cache_.find(it->first);
DCHECK(id_it != db_id_cache_.end());
id_list->push_back(id_it->second);
db_id_cache_.erase(id_it);
db_cache_.erase(it++);
} else {
++it;
}
}
}
void AutocompleteActionPredictor::CopyFromMainProfile() {
CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
DCHECK(profile_->IsOffTheRecord());
DCHECK(!initialized_);
DCHECK(main_profile_predictor_);
DCHECK(main_profile_predictor_->initialized_);
db_cache_ = main_profile_predictor_->db_cache_;
db_id_cache_ = main_profile_predictor_->db_id_cache_;
FinishInitialization();
}
void AutocompleteActionPredictor::FinishInitialization() {
CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
DCHECK(!initialized_);
// Incognito and normal profiles should listen only to omnibox notifications
// from their own profile, but both should listen to history deletions from
// the main profile, since opening the history page in either case actually
// opens the non-incognito history (and lets users delete from there).
notification_registrar_.Add(this, chrome::NOTIFICATION_OMNIBOX_OPENED_URL,
content::Source<Profile>(profile_));
notification_registrar_.Add(this, chrome::NOTIFICATION_HISTORY_URLS_DELETED,
content::Source<Profile>(profile_->GetOriginalProfile()));
initialized_ = true;
}
double AutocompleteActionPredictor::CalculateConfidence(
const string16& user_text,
const AutocompleteMatch& match,
bool* is_in_db) const {
const DBCacheKey key = { user_text, match.destination_url };
*is_in_db = false;
if (user_text.length() < kMinimumUserTextLength)
return 0.0;
const DBCacheMap::const_iterator iter = db_cache_.find(key);
if (iter == db_cache_.end())
return 0.0;
*is_in_db = true;
return CalculateConfidenceForDbEntry(iter);
}
double AutocompleteActionPredictor::CalculateConfidenceForDbEntry(
DBCacheMap::const_iterator iter) const {
const DBCacheValue& value = iter->second;
if (value.number_of_hits < kMinimumNumberOfHits)
return 0.0;
const double number_of_hits = static_cast<double>(value.number_of_hits);
return number_of_hits / (number_of_hits + value.number_of_misses);
}
AutocompleteActionPredictor::TransitionalMatch::TransitionalMatch() {
}
AutocompleteActionPredictor::TransitionalMatch::~TransitionalMatch() {
}
} // namespace predictors
| keishi/chromium | chrome/browser/predictors/autocomplete_action_predictor.cc | C++ | bsd-3-clause | 20,718 |
//
// NSItemProvider+TJImageCache.h
// Wootie
//
// Created by Tim Johnsen on 5/13/20.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSItemProvider (TJImageCache)
+ (nullable instancetype)tj_itemProviderForImageURLString:(nullable NSString *const)imageURLString;
@end
NS_ASSUME_NONNULL_END
| timonus/TJImageCache | TJImageCache/NSItemProvider+TJImageCache.h | C | bsd-3-clause | 325 |
# -*- tab-width : 4 -*-
#=======================================================================
# @file
# @brief RX72N Makefile
# @author 平松邦仁 (hira@rvf-rc45.net)
# @copyright Copyright (C) 2020, 2021 Kunihito Hiramatsu @n
# Released under the MIT license @n
# https://github.com/hirakuni45/RX/blob/master/LICENSE
#=======================================================================
TARGET = can_sample
DEVICE = R5F572NN
RX_DEF = SIG_RX72N
BUILD = release
# BUILD = debug
VPATH = ../../
ASOURCES = common/start.s
CSOURCES = common/init.c \
common/vect.c \
common/syscalls.c
PSOURCES = CAN_sample/main.cpp \
common/stdapi.cpp
USER_LIBS = supc++ m
USER_DEFS =
INC_APP = . ../ ../../
AS_OPT =
CP_OPT = -Wall -Werror \
-Wno-unused-variable \
-Wno-unused-function \
-fno-exceptions
CC_OPT = -Wall -Werror \
-Wno-unused-variable \
-fno-exceptions
ifeq ($(BUILD),debug)
CC_OPT += -g -DDEBUG
CP_OPT += -g -DDEBUG
OPTIMIZE = -O0
endif
ifeq ($(BUILD),release)
CC_OPT += -DNDEBUG
CP_OPT += -DNDEBUG
OPTIMIZE = -O3
endif
-include ../../common/makefile
-include $(DEPENDS)
| hirakuni45/RX | CAN_sample/RX72N/Makefile | Makefile | bsd-3-clause | 1,163 |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import os
import time
import traceback
import urlparse
import random
import csv
from chrome_remote_control import page_test
from chrome_remote_control import util
from chrome_remote_control import wpr_modes
class PageState(object):
def __init__(self):
self.did_login = False
class PageRunner(object):
"""Runs a given test against a given test."""
def __init__(self, page_set):
self.page_set = page_set
def __enter__(self):
return self
def __exit__(self, *args):
self.Close()
def _ReorderPageSet(self, test_shuffle_order_file):
page_set_dict = {}
for page in self.page_set:
page_set_dict[page.url] = page
self.page_set.pages = []
with open(test_shuffle_order_file, 'rb') as csv_file:
csv_reader = csv.reader(csv_file)
csv_header = csv_reader.next()
if 'url' not in csv_header:
raise Exception('Unusable test_shuffle_order_file.')
url_index = csv_header.index('url')
for csv_row in csv_reader:
if csv_row[url_index] in page_set_dict:
self.page_set.pages.append(page_set_dict[csv_row[url_index]])
else:
raise Exception('Unusable test_shuffle_order_file.')
def Run(self, options, possible_browser, test, results):
archive_path = os.path.abspath(os.path.join(self.page_set.base_dir,
self.page_set.archive_path))
if options.wpr_mode == wpr_modes.WPR_OFF:
if os.path.isfile(archive_path):
possible_browser.options.wpr_mode = wpr_modes.WPR_REPLAY
else:
possible_browser.options.wpr_mode = wpr_modes.WPR_OFF
logging.warning("""
The page set archive %s does not exist, benchmarking against live sites!
Results won't be repeatable or comparable.
To fix this, either add svn-internal to your .gclient using
http://goto/read-src-internal, or create a new archive using --record.
""", os.path.relpath(archive_path))
credentials_path = None
if self.page_set.credentials_path:
credentials_path = os.path.join(self.page_set.base_dir,
self.page_set.credentials_path)
if not os.path.exists(credentials_path):
credentials_path = None
with possible_browser.Create() as b:
b.credentials.credentials_path = credentials_path
test.SetUpBrowser(b)
b.credentials.WarnIfMissingCredentials(self.page_set)
if not options.test_shuffle and options.test_shuffle_order_file is not\
None:
raise Exception('--test-shuffle-order-file requires --test-shuffle.')
# Set up a random generator for shuffling the page running order.
test_random = random.Random()
b.SetReplayArchivePath(archive_path)
with b.ConnectToNthTab(0) as tab:
if options.test_shuffle_order_file is None:
for _ in range(int(options.pageset_repeat)):
if options.test_shuffle:
test_random.shuffle(self.page_set)
for page in self.page_set:
for _ in range(int(options.page_repeat)):
self._RunPage(options, page, tab, test, results)
else:
self._ReorderPageSet(options.test_shuffle_order_file)
for page in self.page_set:
self._RunPage(options, page, tab, test, results)
def _RunPage(self, options, page, tab, test, results):
logging.info('Running %s' % page.url)
page_state = PageState()
try:
did_prepare = self.PreparePage(page, tab, page_state, results)
except Exception, ex:
logging.error('Unexpected failure while running %s: %s',
page.url, traceback.format_exc())
self.CleanUpPage(page, tab, page_state)
raise
if not did_prepare:
self.CleanUpPage(page, tab, page_state)
return
try:
test.Run(options, page, tab, results)
except page_test.Failure, ex:
logging.info('%s: %s', ex, page.url)
results.AddFailure(page, ex, traceback.format_exc())
return
except util.TimeoutException, ex:
logging.warning('Timed out while running %s', page.url)
results.AddFailure(page, ex, traceback.format_exc())
return
except Exception, ex:
logging.error('Unexpected failure while running %s: %s',
page.url, traceback.format_exc())
raise
finally:
self.CleanUpPage(page, tab, page_state)
def Close(self):
pass
@staticmethod
def WaitForPageToLoad(expression, tab):
def IsPageLoaded():
return tab.runtime.Evaluate(expression)
# Wait until the form is submitted and the page completes loading.
util.WaitFor(lambda: IsPageLoaded(), 60) # pylint: disable=W0108
def PreparePage(self, page, tab, page_state, results):
parsed_url = urlparse.urlparse(page.url)
if parsed_url[0] == 'file':
path = os.path.join(self.page_set.base_dir,
parsed_url.netloc) # pylint: disable=E1101
dirname, filename = os.path.split(path)
tab.browser.SetHTTPServerDirectory(dirname)
target_side_url = tab.browser.http_server.UrlOf(filename)
else:
target_side_url = page.url
if page.credentials:
page_state.did_login = tab.browser.credentials.LoginNeeded(
tab, page.credentials)
if not page_state.did_login:
msg = 'Could not login to %s on %s' % (page.credentials,
target_side_url)
logging.info(msg)
results.AddFailure(page, msg, "")
return False
tab.page.Navigate(target_side_url)
# Wait for unpredictable redirects.
if page.wait_time_after_navigate:
time.sleep(page.wait_time_after_navigate)
if page.wait_for_javascript_expression is not None:
self.WaitForPageToLoad(page.wait_for_javascript_expression, tab)
tab.WaitForDocumentReadyStateToBeInteractiveOrBetter()
return True
def CleanUpPage(self, page, tab, page_state): # pylint: disable=R0201
if page.credentials and page_state.did_login:
tab.browser.credentials.LoginNoLongerNeeded(tab, page.credentials)
tab.runtime.Evaluate("""chrome && chrome.benchmarking &&
chrome.benchmarking.closeConnections()""")
| junmin-zhu/chromium-rivertrail | tools/chrome_remote_control/chrome_remote_control/page_runner.py | Python | bsd-3-clause | 6,385 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/browser_event_router.h"
#include "base/json/json_writer.h"
#include "base/values.h"
#include "chrome/browser/extensions/api/extension_action/extension_page_actions_api_constants.h"
#include "chrome/browser/extensions/api/tabs/tabs_constants.h"
#include "chrome/browser/extensions/event_names.h"
#include "chrome/browser/extensions/extension_action.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/extensions/window_controller.h"
#include "chrome/browser/extensions/window_event_router.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/tab_contents/tab_contents.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/web_contents.h"
namespace events = extensions::event_names;
namespace tab_keys = extensions::tabs_constants;
namespace page_action_keys = extension_page_actions_api_constants;
using content::NavigationController;
using content::WebContents;
namespace extensions {
BrowserEventRouter::TabEntry::TabEntry()
: complete_waiting_on_load_(false),
url_() {
}
DictionaryValue* BrowserEventRouter::TabEntry::UpdateLoadState(
const WebContents* contents) {
// The tab may go in & out of loading (for instance if iframes navigate).
// We only want to respond to the first change from loading to !loading after
// the NAV_ENTRY_COMMITTED was fired.
if (!complete_waiting_on_load_ || contents->IsLoading())
return NULL;
// Send "complete" state change.
complete_waiting_on_load_ = false;
DictionaryValue* changed_properties = new DictionaryValue();
changed_properties->SetString(tab_keys::kStatusKey,
tab_keys::kStatusValueComplete);
return changed_properties;
}
DictionaryValue* BrowserEventRouter::TabEntry::DidNavigate(
const WebContents* contents) {
// Send "loading" state change.
complete_waiting_on_load_ = true;
DictionaryValue* changed_properties = new DictionaryValue();
changed_properties->SetString(tab_keys::kStatusKey,
tab_keys::kStatusValueLoading);
if (contents->GetURL() != url_) {
url_ = contents->GetURL();
changed_properties->SetString(tab_keys::kUrlKey, url_.spec());
}
return changed_properties;
}
void BrowserEventRouter::Init() {
if (initialized_)
return;
BrowserList::AddObserver(this);
// Init() can happen after the browser is running, so catch up with any
// windows that already exist.
for (BrowserList::const_iterator iter = BrowserList::begin();
iter != BrowserList::end(); ++iter) {
RegisterForBrowserNotifications(*iter);
// Also catch up our internal bookkeeping of tab entries.
Browser* browser = *iter;
if (browser->tab_strip_model()) {
for (int i = 0; i < browser->tab_strip_model()->count(); ++i) {
WebContents* contents =
chrome::GetTabContentsAt(browser, i)->web_contents();
int tab_id = ExtensionTabUtil::GetTabId(contents);
tab_entries_[tab_id] = TabEntry();
}
}
}
initialized_ = true;
}
BrowserEventRouter::BrowserEventRouter(Profile* profile)
: initialized_(false),
profile_(profile) {
DCHECK(!profile->IsOffTheRecord());
}
BrowserEventRouter::~BrowserEventRouter() {
BrowserList::RemoveObserver(this);
}
void BrowserEventRouter::OnBrowserAdded(Browser* browser) {
RegisterForBrowserNotifications(browser);
}
void BrowserEventRouter::RegisterForBrowserNotifications(Browser* browser) {
if (!profile_->IsSameProfile(browser->profile()))
return;
// Start listening to TabStripModel events for this browser.
browser->tab_strip_model()->AddObserver(this);
for (int i = 0; i < browser->tab_strip_model()->count(); ++i) {
RegisterForTabNotifications(
chrome::GetTabContentsAt(browser, i)->web_contents());
}
}
void BrowserEventRouter::RegisterForTabNotifications(WebContents* contents) {
registrar_.Add(
this, content::NOTIFICATION_NAV_ENTRY_COMMITTED,
content::Source<NavigationController>(&contents->GetController()));
// Observing NOTIFICATION_WEB_CONTENTS_DESTROYED is necessary because it's
// possible for tabs to be created, detached and then destroyed without
// ever having been re-attached and closed. This happens in the case of
// a devtools WebContents that is opened in window, docked, then closed.
registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
content::Source<WebContents>(contents));
}
void BrowserEventRouter::UnregisterForTabNotifications(WebContents* contents) {
registrar_.Remove(this, content::NOTIFICATION_NAV_ENTRY_COMMITTED,
content::Source<NavigationController>(&contents->GetController()));
registrar_.Remove(this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
content::Source<WebContents>(contents));
}
void BrowserEventRouter::OnBrowserRemoved(Browser* browser) {
if (!profile_->IsSameProfile(browser->profile()))
return;
// Stop listening to TabStripModel events for this browser.
browser->tab_strip_model()->RemoveObserver(this);
}
void BrowserEventRouter::OnBrowserSetLastActive(Browser* browser) {
ExtensionService* service =
extensions::ExtensionSystem::Get(profile_)->extension_service();
if (service) {
service->window_event_router()->OnActiveWindowChanged(
browser ? browser->extension_window_controller() : NULL);
}
}
void BrowserEventRouter::TabCreatedAt(WebContents* contents,
int index,
bool active) {
Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext());
const EventListenerMap::ListenerList& listeners(
ExtensionSystem::Get(profile)->event_router()->
listeners().GetEventListenersByName(events::kOnTabCreated));
for (EventListenerMap::ListenerList::const_iterator it = listeners.begin();
it != listeners.end();
++it) {
scoped_ptr<ListValue> args(new ListValue());
DictionaryValue* tab_value = ExtensionTabUtil::CreateTabValue(
contents,
profile->GetExtensionService()->extensions()->GetByID(
(*it)->extension_id));
args->Append(tab_value);
tab_value->SetBoolean(tab_keys::kSelectedKey, active);
DispatchEventToExtension(profile, (*it)->extension_id,
events::kOnTabCreated, args.Pass(),
EventRouter::USER_GESTURE_NOT_ENABLED);
}
RegisterForTabNotifications(contents);
}
void BrowserEventRouter::TabInsertedAt(TabContents* contents,
int index,
bool active) {
// If tab is new, send created event.
int tab_id = ExtensionTabUtil::GetTabId(contents->web_contents());
if (!GetTabEntry(contents->web_contents())) {
tab_entries_[tab_id] = TabEntry();
TabCreatedAt(contents->web_contents(), index, active);
return;
}
scoped_ptr<ListValue> args(new ListValue());
args->Append(Value::CreateIntegerValue(tab_id));
DictionaryValue* object_args = new DictionaryValue();
object_args->Set(tab_keys::kNewWindowIdKey, Value::CreateIntegerValue(
ExtensionTabUtil::GetWindowIdOfTab(contents->web_contents())));
object_args->Set(tab_keys::kNewPositionKey, Value::CreateIntegerValue(
index));
args->Append(object_args);
DispatchEvent(contents->profile(), events::kOnTabAttached, args.Pass(),
EventRouter::USER_GESTURE_UNKNOWN);
}
void BrowserEventRouter::TabDetachedAt(TabContents* contents, int index) {
if (!GetTabEntry(contents->web_contents())) {
// The tab was removed. Don't send detach event.
return;
}
scoped_ptr<ListValue> args(new ListValue());
args->Append(Value::CreateIntegerValue(
ExtensionTabUtil::GetTabId(contents->web_contents())));
DictionaryValue* object_args = new DictionaryValue();
object_args->Set(tab_keys::kOldWindowIdKey, Value::CreateIntegerValue(
ExtensionTabUtil::GetWindowIdOfTab(contents->web_contents())));
object_args->Set(tab_keys::kOldPositionKey, Value::CreateIntegerValue(
index));
args->Append(object_args);
DispatchEvent(contents->profile(), events::kOnTabDetached, args.Pass(),
EventRouter::USER_GESTURE_UNKNOWN);
}
void BrowserEventRouter::TabClosingAt(TabStripModel* tab_strip_model,
TabContents* contents,
int index) {
int tab_id = ExtensionTabUtil::GetTabId(contents->web_contents());
scoped_ptr<ListValue> args(new ListValue());
args->Append(Value::CreateIntegerValue(tab_id));
DictionaryValue* object_args = new DictionaryValue();
object_args->SetBoolean(tab_keys::kWindowClosing,
tab_strip_model->closing_all());
args->Append(object_args);
DispatchEvent(contents->profile(), events::kOnTabRemoved, args.Pass(),
EventRouter::USER_GESTURE_UNKNOWN);
int removed_count = tab_entries_.erase(tab_id);
DCHECK_GT(removed_count, 0);
UnregisterForTabNotifications(contents->web_contents());
}
void BrowserEventRouter::ActiveTabChanged(TabContents* old_contents,
TabContents* new_contents,
int index,
bool user_gesture) {
scoped_ptr<ListValue> args(new ListValue());
int tab_id = ExtensionTabUtil::GetTabId(new_contents->web_contents());
args->Append(Value::CreateIntegerValue(tab_id));
DictionaryValue* object_args = new DictionaryValue();
object_args->Set(tab_keys::kWindowIdKey, Value::CreateIntegerValue(
ExtensionTabUtil::GetWindowIdOfTab(new_contents->web_contents())));
args->Append(object_args);
// The onActivated event replaced onActiveChanged and onSelectionChanged. The
// deprecated events take two arguments: tabId, {windowId}.
Profile* profile = new_contents->profile();
EventRouter::UserGestureState gesture = user_gesture ?
EventRouter::USER_GESTURE_ENABLED : EventRouter::USER_GESTURE_NOT_ENABLED;
DispatchEvent(profile, events::kOnTabSelectionChanged,
scoped_ptr<ListValue>(args->DeepCopy()), gesture);
DispatchEvent(profile, events::kOnTabActiveChanged,
scoped_ptr<ListValue>(args->DeepCopy()), gesture);
// The onActivated event takes one argument: {windowId, tabId}.
args->Remove(0, NULL);
object_args->Set(tab_keys::kTabIdKey, Value::CreateIntegerValue(tab_id));
DispatchEvent(profile, events::kOnTabActivated, args.Pass(), gesture);
}
void BrowserEventRouter::TabSelectionChanged(
TabStripModel* tab_strip_model,
const TabStripSelectionModel& old_model) {
TabStripSelectionModel::SelectedIndices new_selection =
tab_strip_model->selection_model().selected_indices();
ListValue* all = new ListValue();
for (size_t i = 0; i < new_selection.size(); ++i) {
int index = new_selection[i];
TabContents* contents = tab_strip_model->GetTabContentsAt(index);
if (!contents)
break;
int tab_id = ExtensionTabUtil::GetTabId(contents->web_contents());
all->Append(Value::CreateIntegerValue(tab_id));
}
scoped_ptr<ListValue> args(new ListValue());
DictionaryValue* select_info = new DictionaryValue();
select_info->Set(tab_keys::kWindowIdKey, Value::CreateIntegerValue(
ExtensionTabUtil::GetWindowIdOfTabStripModel(tab_strip_model)));
select_info->Set(tab_keys::kTabIdsKey, all);
args->Append(select_info);
// The onHighlighted event replaced onHighlightChanged.
Profile* profile = tab_strip_model->profile();
DispatchEvent(profile, events::kOnTabHighlightChanged,
scoped_ptr<ListValue>(args->DeepCopy()),
EventRouter::USER_GESTURE_UNKNOWN);
DispatchEvent(profile, events::kOnTabHighlighted, args.Pass(),
EventRouter::USER_GESTURE_UNKNOWN);
}
void BrowserEventRouter::TabMoved(TabContents* contents,
int from_index,
int to_index) {
scoped_ptr<ListValue> args(new ListValue());
args->Append(Value::CreateIntegerValue(
ExtensionTabUtil::GetTabId(contents->web_contents())));
DictionaryValue* object_args = new DictionaryValue();
object_args->Set(tab_keys::kWindowIdKey, Value::CreateIntegerValue(
ExtensionTabUtil::GetWindowIdOfTab(contents->web_contents())));
object_args->Set(tab_keys::kFromIndexKey, Value::CreateIntegerValue(
from_index));
object_args->Set(tab_keys::kToIndexKey, Value::CreateIntegerValue(
to_index));
args->Append(object_args);
DispatchEvent(contents->profile(), events::kOnTabMoved, args.Pass(),
EventRouter::USER_GESTURE_UNKNOWN);
}
void BrowserEventRouter::TabUpdated(WebContents* contents, bool did_navigate) {
TabEntry* entry = GetTabEntry(contents);
DictionaryValue* changed_properties = NULL;
DCHECK(entry);
if (did_navigate)
changed_properties = entry->DidNavigate(contents);
else
changed_properties = entry->UpdateLoadState(contents);
if (changed_properties)
DispatchTabUpdatedEvent(contents, changed_properties);
}
void BrowserEventRouter::DispatchEvent(
Profile* profile,
const char* event_name,
scoped_ptr<ListValue> args,
EventRouter::UserGestureState user_gesture) {
if (!profile_->IsSameProfile(profile) ||
!extensions::ExtensionSystem::Get(profile)->event_router())
return;
extensions::ExtensionSystem::Get(profile)->event_router()->
DispatchEventToRenderers(event_name, args.Pass(), profile, GURL(),
user_gesture);
}
void BrowserEventRouter::DispatchEventToExtension(
Profile* profile,
const std::string& extension_id,
const char* event_name,
scoped_ptr<ListValue> event_args,
EventRouter::UserGestureState user_gesture) {
if (!profile_->IsSameProfile(profile) ||
!extensions::ExtensionSystem::Get(profile)->event_router())
return;
extensions::ExtensionSystem::Get(profile)->event_router()->
DispatchEventToExtension(extension_id, event_name, event_args.Pass(),
profile, GURL(), user_gesture);
}
void BrowserEventRouter::DispatchEventsAcrossIncognito(
Profile* profile,
const char* event_name,
scoped_ptr<ListValue> event_args,
scoped_ptr<ListValue> cross_incognito_args) {
if (!profile_->IsSameProfile(profile) ||
!extensions::ExtensionSystem::Get(profile)->event_router())
return;
extensions::ExtensionSystem::Get(profile)->event_router()->
DispatchEventsToRenderersAcrossIncognito(event_name, event_args.Pass(),
profile, cross_incognito_args.Pass(), GURL());
}
void BrowserEventRouter::DispatchSimpleBrowserEvent(
Profile* profile, const int window_id, const char* event_name) {
if (!profile_->IsSameProfile(profile))
return;
scoped_ptr<ListValue> args(new ListValue());
args->Append(Value::CreateIntegerValue(window_id));
DispatchEvent(profile, event_name, args.Pass(),
EventRouter::USER_GESTURE_UNKNOWN);
}
void BrowserEventRouter::DispatchTabUpdatedEvent(
WebContents* contents, DictionaryValue* changed_properties) {
DCHECK(changed_properties);
DCHECK(contents);
// The state of the tab (as seen from the extension point of view) has
// changed. Send a notification to the extension.
scoped_ptr<ListValue> args_base(new ListValue());
// First arg: The id of the tab that changed.
args_base->AppendInteger(ExtensionTabUtil::GetTabId(contents));
// Second arg: An object containing the changes to the tab state.
args_base->Append(changed_properties);
// Third arg: An object containing the state of the tab.
Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext());
const EventListenerMap::ListenerList& listeners(
ExtensionSystem::Get(profile)->event_router()->
listeners().GetEventListenersByName(events::kOnTabUpdated));
for (EventListenerMap::ListenerList::const_iterator it = listeners.begin();
it != listeners.end();
++it) {
scoped_ptr<ListValue> args(args_base->DeepCopy());
DictionaryValue* tab_value = ExtensionTabUtil::CreateTabValue(
contents,
profile->GetExtensionService()->extensions()->GetByID(
(*it)->extension_id));
args->Append(tab_value);
DispatchEventToExtension(profile, (*it)->extension_id,
events::kOnTabUpdated, args.Pass(),
EventRouter::USER_GESTURE_UNKNOWN);
}
}
BrowserEventRouter::TabEntry* BrowserEventRouter::GetTabEntry(
const WebContents* contents) {
int tab_id = ExtensionTabUtil::GetTabId(contents);
std::map<int, TabEntry>::iterator i = tab_entries_.find(tab_id);
if (tab_entries_.end() == i)
return NULL;
return &i->second;
}
void BrowserEventRouter::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
if (type == content::NOTIFICATION_NAV_ENTRY_COMMITTED) {
NavigationController* source_controller =
content::Source<NavigationController>(source).ptr();
TabUpdated(source_controller->GetWebContents(), true);
} else if (type == content::NOTIFICATION_WEB_CONTENTS_DESTROYED) {
// Tab was destroyed after being detached (without being re-attached).
WebContents* contents = content::Source<WebContents>(source).ptr();
registrar_.Remove(this, content::NOTIFICATION_NAV_ENTRY_COMMITTED,
content::Source<NavigationController>(&contents->GetController()));
registrar_.Remove(this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
content::Source<WebContents>(contents));
} else {
NOTREACHED();
}
}
void BrowserEventRouter::TabChangedAt(TabContents* contents,
int index,
TabChangeType change_type) {
TabUpdated(contents->web_contents(), false);
}
void BrowserEventRouter::TabReplacedAt(TabStripModel* tab_strip_model,
TabContents* old_contents,
TabContents* new_contents,
int index) {
TabClosingAt(tab_strip_model, old_contents, index);
TabInsertedAt(new_contents, index, tab_strip_model->active_index() == index);
}
void BrowserEventRouter::TabPinnedStateChanged(TabContents* contents,
int index) {
TabStripModel* tab_strip = NULL;
int tab_index;
if (ExtensionTabUtil::GetTabStripModel(
contents->web_contents(), &tab_strip, &tab_index)) {
DictionaryValue* changed_properties = new DictionaryValue();
changed_properties->SetBoolean(tab_keys::kPinnedKey,
tab_strip->IsTabPinned(tab_index));
DispatchTabUpdatedEvent(contents->web_contents(), changed_properties);
}
}
void BrowserEventRouter::TabStripEmpty() {}
void BrowserEventRouter::DispatchOldPageActionEvent(
Profile* profile,
const std::string& extension_id,
const std::string& page_action_id,
int tab_id,
const std::string& url,
int button) {
scoped_ptr<ListValue> args(new ListValue());
args->Append(Value::CreateStringValue(page_action_id));
DictionaryValue* data = new DictionaryValue();
data->Set(tab_keys::kTabIdKey, Value::CreateIntegerValue(tab_id));
data->Set(tab_keys::kTabUrlKey, Value::CreateStringValue(url));
data->Set(page_action_keys::kButtonKey, Value::CreateIntegerValue(button));
args->Append(data);
DispatchEventToExtension(profile, extension_id, "pageActions", args.Pass(),
EventRouter::USER_GESTURE_ENABLED);
}
void BrowserEventRouter::BrowserActionExecuted(
const ExtensionAction& browser_action,
Browser* browser) {
Profile* profile = browser->profile();
TabContents* tab_contents = NULL;
int tab_id = 0;
if (!ExtensionTabUtil::GetDefaultTab(browser, &tab_contents, &tab_id))
return;
ExtensionActionExecuted(profile, browser_action, tab_contents);
}
void BrowserEventRouter::PageActionExecuted(Profile* profile,
const ExtensionAction& page_action,
int tab_id,
const std::string& url,
int button) {
DispatchOldPageActionEvent(profile, page_action.extension_id(),
page_action.id(), tab_id, url, button);
TabContents* tab_contents = NULL;
if (!ExtensionTabUtil::GetTabById(tab_id, profile, profile->IsOffTheRecord(),
NULL, NULL, &tab_contents, NULL)) {
return;
}
ExtensionActionExecuted(profile, page_action, tab_contents);
}
void BrowserEventRouter::ScriptBadgeExecuted(
Profile* profile,
const ExtensionAction& script_badge,
int tab_id) {
TabContents* tab_contents = NULL;
if (!ExtensionTabUtil::GetTabById(tab_id, profile, profile->IsOffTheRecord(),
NULL, NULL, &tab_contents, NULL)) {
return;
}
ExtensionActionExecuted(profile, script_badge, tab_contents);
}
void BrowserEventRouter::CommandExecuted(Profile* profile,
const std::string& extension_id,
const std::string& command) {
scoped_ptr<ListValue> args(new ListValue());
args->Append(Value::CreateStringValue(command));
DispatchEventToExtension(profile,
extension_id,
"commands.onCommand",
args.Pass(),
EventRouter::USER_GESTURE_ENABLED);
}
void BrowserEventRouter::ExtensionActionExecuted(
Profile* profile,
const ExtensionAction& extension_action,
TabContents* tab_contents) {
const char* event_name = NULL;
switch (extension_action.action_type()) {
case Extension::ActionInfo::TYPE_BROWSER:
event_name = "browserAction.onClicked";
break;
case Extension::ActionInfo::TYPE_PAGE:
event_name = "pageAction.onClicked";
break;
case Extension::ActionInfo::TYPE_SCRIPT_BADGE:
event_name = "scriptBadge.onClicked";
break;
}
if (event_name) {
scoped_ptr<ListValue> args(new ListValue());
DictionaryValue* tab_value = ExtensionTabUtil::CreateTabValue(
tab_contents->web_contents(),
ExtensionTabUtil::INCLUDE_PRIVACY_SENSITIVE_FIELDS);
args->Append(tab_value);
DispatchEventToExtension(profile,
extension_action.extension_id(),
event_name,
args.Pass(),
EventRouter::USER_GESTURE_ENABLED);
}
}
} // namespace extensions
| junmin-zhu/chromium-rivertrail | chrome/browser/extensions/browser_event_router.cc | C++ | bsd-3-clause | 23,531 |
import * as asn1js from "asn1js";
import { getParametersValue, clearProps } from "pvutils";
import CertID from "./CertID.js";
import Extension from "./Extension.js";
//**************************************************************************************
/**
* Class from RFC6960
*/
export default class Request
{
//**********************************************************************************
/**
* Constructor for Request class
* @param {Object} [parameters={}]
* @param {Object} [parameters.schema] asn1js parsed value to initialize the class from
*/
constructor(parameters = {})
{
//region Internal properties of the object
/**
* @type {CertID}
* @desc reqCert
*/
this.reqCert = getParametersValue(parameters, "reqCert", Request.defaultValues("reqCert"));
if("singleRequestExtensions" in parameters)
/**
* @type {Array.<Extension>}
* @desc singleRequestExtensions
*/
this.singleRequestExtensions = getParametersValue(parameters, "singleRequestExtensions", Request.defaultValues("singleRequestExtensions"));
//endregion
//region If input argument array contains "schema" for this object
if("schema" in parameters)
this.fromSchema(parameters.schema);
//endregion
}
//**********************************************************************************
/**
* Return default values for all class members
* @param {string} memberName String name for a class member
*/
static defaultValues(memberName)
{
switch(memberName)
{
case "reqCert":
return new CertID();
case "singleRequestExtensions":
return [];
default:
throw new Error(`Invalid member name for Request class: ${memberName}`);
}
}
//**********************************************************************************
/**
* Compare values with default values for all class members
* @param {string} memberName String name for a class member
* @param {*} memberValue Value to compare with default value
*/
static compareWithDefault(memberName, memberValue)
{
switch(memberName)
{
case "reqCert":
return (memberValue.isEqual(Request.defaultValues(memberName)));
case "singleRequestExtensions":
return (memberValue.length === 0);
default:
throw new Error(`Invalid member name for Request class: ${memberName}`);
}
}
//**********************************************************************************
/**
* Return value of pre-defined ASN.1 schema for current class
*
* ASN.1 schema:
* ```asn1
* Request ::= SEQUENCE {
* reqCert CertID,
* singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL }
* ```
*
* @param {Object} parameters Input parameters for the schema
* @returns {Object} asn1js schema object
*/
static schema(parameters = {})
{
/**
* @type {Object}
* @property {string} [blockName]
* @property {string} [reqCert]
* @property {string} [extensions]
* @property {string} [singleRequestExtensions]
*/
const names = getParametersValue(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || ""),
value: [
CertID.schema(names.reqCert || {}),
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [Extension.schema(names.extensions || {
names: {
blockName: (names.singleRequestExtensions || "")
}
})]
})
]
}));
}
//**********************************************************************************
/**
* Convert parsed asn1js object into current class
* @param {!Object} schema
*/
fromSchema(schema)
{
//region Clear input data first
clearProps(schema, [
"reqCert",
"singleRequestExtensions"
]);
//endregion
//region Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
Request.schema({
names: {
reqCert: {
names: {
blockName: "reqCert"
}
},
singleRequestExtensions: {
names: {
blockName: "singleRequestExtensions"
}
}
}
})
);
if(asn1.verified === false)
throw new Error("Object's schema was not verified against input data for Request");
//endregion
//region Get internal properties from parsed schema
this.reqCert = new CertID({ schema: asn1.result.reqCert });
if("singleRequestExtensions" in asn1.result)
this.singleRequestExtensions = Array.from(asn1.result.singleRequestExtensions.valueBlock.value, element => new Extension({ schema: element }));
//endregion
}
//**********************************************************************************
/**
* Convert current object to asn1js object and set correct values
* @returns {Object} asn1js object
*/
toSchema()
{
//region Create array for output sequence
const outputArray = [];
outputArray.push(this.reqCert.toSchema());
if("singleRequestExtensions" in this)
{
outputArray.push(new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
new asn1js.Sequence({
value: Array.from(this.singleRequestExtensions, element => element.toSchema())
})
]
}));
}
//endregion
//region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
//endregion
}
//**********************************************************************************
/**
* Convertion for the class to JSON object
* @returns {Object}
*/
toJSON()
{
const _object = {
reqCert: this.reqCert.toJSON()
};
if("singleRequestExtensions" in this)
_object.singleRequestExtensions = Array.from(this.singleRequestExtensions, element => element.toJSON());
return _object;
}
//**********************************************************************************
}
//**************************************************************************************
| GlobalSign/PKI.js | src/Request.js | JavaScript | bsd-3-clause | 6,218 |
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */
#ifndef NATIVE_EXTENSION_VTK_VTKINTERACTORSTYLEJOYSTICKACTORWRAP_H
#define NATIVE_EXTENSION_VTK_VTKINTERACTORSTYLEJOYSTICKACTORWRAP_H
#include <nan.h>
#include <vtkSmartPointer.h>
#include <vtkInteractorStyleJoystickActor.h>
#include "vtkInteractorStyleWrap.h"
#include "../../plus/plus.h"
class VtkInteractorStyleJoystickActorWrap : public VtkInteractorStyleWrap
{
public:
using Nan::ObjectWrap::Wrap;
static void Init(v8::Local<v8::Object> exports);
static void InitPtpl();
static void ConstructorGetter(
v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info);
VtkInteractorStyleJoystickActorWrap(vtkSmartPointer<vtkInteractorStyleJoystickActor>);
VtkInteractorStyleJoystickActorWrap();
~VtkInteractorStyleJoystickActorWrap( );
static Nan::Persistent<v8::FunctionTemplate> ptpl;
private:
static void New(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void Dolly(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void OnLeftButtonDown(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void OnLeftButtonUp(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void OnMiddleButtonDown(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void OnMiddleButtonUp(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void OnMouseMove(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void OnRightButtonDown(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void OnRightButtonUp(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void Pan(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void Rotate(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void Spin(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void UniformScale(const Nan::FunctionCallbackInfo<v8::Value>& info);
#ifdef VTK_NODE_PLUS_VTKINTERACTORSTYLEJOYSTICKACTORWRAP_CLASSDEF
VTK_NODE_PLUS_VTKINTERACTORSTYLEJOYSTICKACTORWRAP_CLASSDEF
#endif
};
#endif
| axkibe/node-vtk | wrappers/8.1.1/vtkInteractorStyleJoystickActorWrap.h | C | bsd-3-clause | 2,242 |
// $Id$
// Copyright (c) 2008-2009 Oliver Lau <oliver@von-und-fuer-lau.de>
// Alle Rechte vorbehalten.
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS 1
#endif
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>
#include <cmath>
#include <errno.h>
#include <getopt.h>
#include "gpslib/Track.h"
#include "gpslib/GPXFile.h"
#include "gpslib/helper.h"
// gettext-Dummy
#define _(s) s
using namespace std;
using namespace GPS;
bool quiet = false;
int verbose = 1;
enum _long_options {
SELECT_HELP,
SELECT_DEBUG,
SELECT_QUIET,
SELECT_VERBOSE,
SELECT_VERSION
};
static const string VERSION = "0.9.0-BETA";
static struct option long_options[] = {
{ "help", no_argument, 0, SELECT_HELP },
{ "quiet", no_argument, 0, SELECT_QUIET },
{ "verbose", no_argument, 0, SELECT_VERBOSE },
{ "version", no_argument, 0, SELECT_VERSION },
{ 0, 0, 0, 0 }
};
void disclaimer(void)
{
std::cout << "areameter - Von einem Track eingeschlossene Fläche berechnen." << endl
<< "Copyright (c) 2008-2009 Oliver Lau <oliver@von-und-fuer-lau.de>" << endl
<< "Alle Rechte vorbehalten." << endl << endl;
}
void usage(void)
{
cout << _("Aufruf: areameter track.gpx\n") << endl
<< endl
<< _("Optionen:\n"
" -v Mehr Information über Verarbeitungsschritte ausgeben\n"
" -q Sämtliche Ausgaben unterdrücken\n"
" --version Versionsinformationen ausgeben")
<< endl << endl;
}
void errmsg(std::string str, int rc = 0, bool _usage = true)
{
std::cerr << endl << "FEHLER (" << ((rc != 0)? rc : errno) << "): " << str << endl;
if (_usage)
usage();
exit(EXIT_FAILURE);
}
void warnmsg(std::string str)
{
std::cerr << endl << "WARNUNG: " << str << endl;
}
int main(int argc, char* argv[])
{
for (;;) {
int option_index = 0;
int c = getopt_long(argc, argv, "h?vq", long_options, &option_index);
if (c == -1)
break;
switch (c)
{
case 'h':
/* fall-through */
case '?':
/* fall-through */
case SELECT_HELP:
usage();
return 0;
break;
case SELECT_VERBOSE:
/* fall-through */
case 'v':
++verbose;
break;
case SELECT_QUIET:
/* fall-through */
case 'q':
quiet = true;
break;
case SELECT_VERSION:
disclaimer();
cout << "Version: " << VERSION << endl << endl;
exit(EXIT_SUCCESS);
break;
default:
usage();
exit(EXIT_FAILURE);
break;
}
}
if (!quiet)
disclaimer();
if ((argc - optind) < 1) {
usage();
exit(EXIT_FAILURE);
}
string gpxFilename = argv[optind];
if (gpxFilename == "") {
usage();
exit(EXIT_FAILURE);
}
cout << "Laden von " << gpxFilename << " .." << endl;
GPXFile gpxFile;
int rc = gpxFile.load(gpxFilename);
if (rc != 0)
errmsg("Kann GPX-Datei nicht laden", rc);
TrackList allTracks;
for (TrackList::const_iterator i = gpxFile.tracks().begin(); i != gpxFile.tracks().end(); ++i)
{
Track* trk = (*i);
if (trk != NULL)
{
cout << "Track: " << trk->name() << endl;
if (trk->isEmpty())
errmsg("Der Track enthält keine Trackpunkte");
if (!trk->hasDistance())
errmsg("Der Track enthält keine Positionsangaben");
cout << " Flächeninhalt: ";
double area = trk->area();
if (area > 1e6)
cout << 1e-6 * area << " qkm";
else
cout << area << " qm";
if (area > 1e3)
cout << " (" << 1e-4 * area << " ha)";
cout << endl << endl;
}
}
return EXIT_SUCCESS;
}
| ola-ct/gpstools | areameter/areameter.cpp | C++ | bsd-3-clause | 4,031 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_75) on Sun Mar 22 18:10:17 CET 2015 -->
<title>Uses of Class thobe.logfileviewer.gui.RestrictedTextFieldRegexp</title>
<meta name="date" content="2015-03-22">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class thobe.logfileviewer.gui.RestrictedTextFieldRegexp";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../thobe/logfileviewer/gui/RestrictedTextFieldRegexp.html" title="class in thobe.logfileviewer.gui">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?thobe/logfileviewer/gui/class-use/RestrictedTextFieldRegexp.html" target="_top">Frames</a></li>
<li><a href="RestrictedTextFieldRegexp.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class thobe.logfileviewer.gui.RestrictedTextFieldRegexp" class="title">Uses of Class<br>thobe.logfileviewer.gui.RestrictedTextFieldRegexp</h2>
</div>
<div class="classUseContainer">No usage of thobe.logfileviewer.gui.RestrictedTextFieldRegexp</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../thobe/logfileviewer/gui/RestrictedTextFieldRegexp.html" title="class in thobe.logfileviewer.gui">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?thobe/logfileviewer/gui/class-use/RestrictedTextFieldRegexp.html" target="_top">Frames</a></li>
<li><a href="RestrictedTextFieldRegexp.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| ThomasObenaus/LogFileViewer | api/thobe/logfileviewer/gui/class-use/RestrictedTextFieldRegexp.html | HTML | bsd-3-clause | 4,239 |
package info.tregmine.database;
public interface IContextFactory
{
public IContext createContext() throws DAOException;
}
| EmilHernvall/tregmine | src/info/tregmine/database/IContextFactory.java | Java | bsd-3-clause | 127 |
/*
* Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider,
* Jérémie Comarmond, Didier Colin.
* 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 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 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 "CreateUserAccount.h"
namespace HOOUserProtocol
{
//-----------------------------------------------------------------------------
// CreateUserAccount
//-----------------------------------------------------------------------------
void CreateUserAccount::read(Core::InputStream & inputStream)
{
inputStream.readSafe(_login, SAFE_STRING_LENGTH);
inputStream.readSafe(_password, SAFE_STRING_LENGTH);
inputStream.readSafe(_mail, SAFE_STRING_LENGTH);
inputStream.read(_newsletter);
}
void CreateUserAccount::write(Core::OutputStream & outputStream) const
{
outputStream.write(getType());
outputStream.write(_login);
outputStream.write(_password);
outputStream.write(_mail);
outputStream.write(_newsletter);
}
//-----------------------------------------------------------------------------
// CreateUserAccountAnswer
//-----------------------------------------------------------------------------
void CreateUserAccountAnswer::read(Core::InputStream & inputStream)
{
inputStream.readData(&_answerType, sizeof(ECreateUserAccountAnswerType));
if(_answerType == USER_ACCOUNT_CREATED)
_accountInfos.read(inputStream);
}
void CreateUserAccountAnswer::write(Core::OutputStream & outputStream) const
{
outputStream.write(getType());
outputStream.write(_answerType);
if(_answerType == USER_ACCOUNT_CREATED)
_accountInfos.write(outputStream);
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
}//namespace HOOUserProtocol | benkaraban/anima-games-engine | Sources/HOO/HOOUserProtocol/CreateUserAccount.cpp | C++ | bsd-3-clause | 3,320 |
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Facebook;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using OrchardCore.DisplayManagement.Handlers;
using OrchardCore.Facebook.Login.Configuration;
using OrchardCore.Facebook.Login.Drivers;
using OrchardCore.Facebook.Login.Recipes;
using OrchardCore.Facebook.Login.Services;
using OrchardCore.Modules;
using OrchardCore.Navigation;
using OrchardCore.Recipes;
using OrchardCore.Settings;
namespace OrchardCore.Facebook
{
[Feature(FacebookConstants.Features.Login)]
public class StartupLogin : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddScoped<INavigationProvider, AdminMenuLogin>();
services.AddSingleton<IFacebookLoginService, FacebookLoginService>();
services.AddScoped<IDisplayDriver<ISite>, FacebookLoginSettingsDisplayDriver>();
services.AddRecipeExecutionStep<FacebookLoginSettingsStep>();
// Register the options initializers required by the Facebook handler.
services.TryAddEnumerable(new[]
{
// Orchard-specific initializers:
ServiceDescriptor.Transient<IConfigureOptions<AuthenticationOptions>, FacebookLoginConfiguration>(),
ServiceDescriptor.Transient<IConfigureOptions<FacebookOptions>, FacebookLoginConfiguration>(),
// Built-in initializers:
ServiceDescriptor.Transient<IPostConfigureOptions<FacebookOptions>, OAuthPostConfigureOptions<FacebookOptions, FacebookHandler>>()
});
}
}
}
| petedavis/Orchard2 | src/OrchardCore.Modules/OrchardCore.Facebook/StartupLogin.cs | C# | bsd-3-clause | 1,754 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/drive/drive_scheduler.h"
#include "base/bind.h"
#include "base/threading/sequenced_worker_pool.h"
#include "chrome/browser/chromeos/drive/drive_test_util.h"
#include "chrome/browser/chromeos/drive/file_system/drive_operations.h"
#include "chrome/browser/chromeos/drive/file_system/remove_operation.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/testing_profile.h"
#include "content/public/test/test_browser_thread.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::AnyNumber;
using ::testing::DoAll;
using ::testing::Return;
using ::testing::StrictMock;
using ::testing::_;
namespace drive {
namespace {
class MockNetworkChangeNotifier : public net::NetworkChangeNotifier {
public:
MOCK_CONST_METHOD0(GetCurrentConnectionType,
net::NetworkChangeNotifier::ConnectionType());
};
class MockRemoveOperation : public file_system::RemoveOperation {
public:
MockRemoveOperation()
: file_system::RemoveOperation(NULL, NULL, NULL, NULL) {
}
MOCK_METHOD3(Remove, void(const FilePath& file_path,
bool is_recursive,
const FileOperationCallback& callback));
};
// Action used to set mock expectations for
// DriveFunctionRemove::Remove().
ACTION_P(MockRemove, status) {
base::MessageLoopProxy::current()->PostTask(FROM_HERE,
base::Bind(arg2, status));
}
} // namespace
class DriveSchedulerTest : public testing::Test {
public:
DriveSchedulerTest()
: ui_thread_(content::BrowserThread::UI, &message_loop_),
profile_(new TestingProfile) {
}
virtual void SetUp() OVERRIDE {
mock_network_change_notifier_.reset(new MockNetworkChangeNotifier);
mock_remove_operation_ = new StrictMock<MockRemoveOperation>();
drive_operations_.InitForTesting(NULL, NULL, mock_remove_operation_);
scheduler_.reset(new DriveScheduler(profile_.get(),
&drive_operations_));
scheduler_->Initialize();
scheduler_->SetDisableThrottling(true);
}
virtual void TearDown() OVERRIDE {
// The scheduler should be deleted before NetworkLibrary, as it
// registers itself as observer of NetworkLibrary.
scheduler_.reset();
google_apis::test_util::RunBlockingPoolTask();
mock_network_change_notifier_.reset();
}
// Sets up MockNetworkChangeNotifier as if it's connected to a network with
// the specified connection type.
void ChangeConnectionType(net::NetworkChangeNotifier::ConnectionType type) {
EXPECT_CALL(*mock_network_change_notifier_, GetCurrentConnectionType())
.WillRepeatedly(Return(type));
// Notify the sync client that the network is changed. This is done via
// NetworkChangeNotifier in production, but here, we simulate the behavior
// by directly calling OnConnectionTypeChanged().
scheduler_->OnConnectionTypeChanged(type);
}
// Sets up MockNetworkChangeNotifier as if it's connected to wifi network.
void ConnectToWifi() {
ChangeConnectionType(net::NetworkChangeNotifier::CONNECTION_WIFI);
}
// Sets up MockNetworkChangeNotifier as if it's connected to cellular network.
void ConnectToCellular() {
ChangeConnectionType(net::NetworkChangeNotifier::CONNECTION_2G);
}
// Sets up MockNetworkChangeNotifier as if it's connected to wimax network.
void ConnectToWimax() {
ChangeConnectionType(net::NetworkChangeNotifier::CONNECTION_4G);
}
// Sets up MockNetworkChangeNotifier as if it's disconnected.
void ConnectToNone() {
ChangeConnectionType(net::NetworkChangeNotifier::CONNECTION_NONE);
}
protected:
MessageLoopForUI message_loop_;
content::TestBrowserThread ui_thread_;
scoped_ptr<TestingProfile> profile_;
scoped_ptr<DriveScheduler> scheduler_;
scoped_ptr<MockNetworkChangeNotifier> mock_network_change_notifier_;
file_system::DriveOperations drive_operations_;
StrictMock<MockRemoveOperation>* mock_remove_operation_;
};
TEST_F(DriveSchedulerTest, RemoveFile) {
ConnectToWifi();
FilePath file_in_root(FILE_PATH_LITERAL("drive/File 1.txt"));
EXPECT_CALL(*mock_remove_operation_, Remove(file_in_root, _, _))
.WillOnce(MockRemove(DRIVE_FILE_OK));
DriveFileError error;
scheduler_->Remove(
file_in_root, false,
base::Bind(&test_util::CopyErrorCodeFromFileOperationCallback, &error));
google_apis::test_util::RunBlockingPoolTask();
ASSERT_EQ(DRIVE_FILE_OK, error);
}
TEST_F(DriveSchedulerTest, RemoveFileRetry) {
ConnectToWifi();
FilePath file_in_root(FILE_PATH_LITERAL("drive/File 1.txt"));
EXPECT_CALL(*mock_remove_operation_, Remove(file_in_root, _, _))
.WillOnce(MockRemove(DRIVE_FILE_ERROR_THROTTLED))
.WillOnce(MockRemove(DRIVE_FILE_OK));
DriveFileError error;
scheduler_->Remove(
file_in_root, false,
base::Bind(&test_util::CopyErrorCodeFromFileOperationCallback, &error));
google_apis::test_util::RunBlockingPoolTask();
ASSERT_EQ(DRIVE_FILE_OK, error);
}
TEST_F(DriveSchedulerTest, QueueOperation_Offline) {
ConnectToNone();
// This file will not be removed, as network is not connected.
EXPECT_CALL(*mock_remove_operation_, Remove(_, _, _)).Times(0);
FilePath file_in_root(FILE_PATH_LITERAL("drive/File 1.txt"));
DriveFileError error;
scheduler_->Remove(
file_in_root, false,
base::Bind(&test_util::CopyErrorCodeFromFileOperationCallback, &error));
google_apis::test_util::RunBlockingPoolTask();
}
TEST_F(DriveSchedulerTest, QueueOperation_CelluarDisabled) {
ConnectToCellular();
// This file will not be removed, as fetching over cellular network is
// disabled by default.
EXPECT_CALL(*mock_remove_operation_, Remove(_, _, _)).Times(0);
FilePath file_in_root(FILE_PATH_LITERAL("drive/File 1.txt"));
DriveFileError error;
scheduler_->Remove(
file_in_root, false,
base::Bind(&test_util::CopyErrorCodeFromFileOperationCallback, &error));
google_apis::test_util::RunBlockingPoolTask();
}
TEST_F(DriveSchedulerTest, QueueOperation_CelluarEnabled) {
// Enable fetching over cellular network.
profile_->GetPrefs()->SetBoolean(prefs::kDisableDriveOverCellular, false);
ConnectToCellular();
// This file will be removed, as syncing over cellular network is explicitly
// enabled.
EXPECT_CALL(*mock_remove_operation_, Remove(_, _, _)).Times(1);
FilePath file_in_root(FILE_PATH_LITERAL("drive/File 1.txt"));
DriveFileError error;
scheduler_->Remove(
file_in_root, false,
base::Bind(&test_util::CopyErrorCodeFromFileOperationCallback, &error));
google_apis::test_util::RunBlockingPoolTask();
}
TEST_F(DriveSchedulerTest, QueueOperation_WimaxDisabled) {
// Then connect to wimax. This will kick off StartSyncLoop().
ConnectToWimax();
// This file will not be removed, as syncing over wimax network is disabled
// by default.
EXPECT_CALL(*mock_remove_operation_, Remove(_, _, _)).Times(0);
FilePath file_in_root(FILE_PATH_LITERAL("drive/File 1.txt"));
DriveFileError error;
scheduler_->Remove(
file_in_root, false,
base::Bind(&test_util::CopyErrorCodeFromFileOperationCallback, &error));
google_apis::test_util::RunBlockingPoolTask();
}
TEST_F(DriveSchedulerTest, QueueOperation_CelluarEnabledWithWimax) {
// Enable fetching over cellular network.
profile_->GetPrefs()->SetBoolean(prefs::kDisableDriveOverCellular, false);
ConnectToWimax();
// This file will be removed, as syncing over cellular network is explicitly
// enabled.
EXPECT_CALL(*mock_remove_operation_, Remove(_, _, _)).Times(1);
FilePath file_in_root(FILE_PATH_LITERAL("drive/File 1.txt"));
DriveFileError error;
scheduler_->Remove(
file_in_root, false,
base::Bind(&test_util::CopyErrorCodeFromFileOperationCallback, &error));
google_apis::test_util::RunBlockingPoolTask();
}
TEST_F(DriveSchedulerTest, QueueOperation_DriveDisabled) {
// Disable the Drive feature.
profile_->GetPrefs()->SetBoolean(prefs::kDisableDrive, true);
// This file will not be removed, as the Drive feature is disabled.
EXPECT_CALL(*mock_remove_operation_, Remove(_, _, _)).Times(0);
FilePath file_in_root(FILE_PATH_LITERAL("drive/File 1.txt"));
DriveFileError error;
scheduler_->Remove(
file_in_root, false,
base::Bind(&test_util::CopyErrorCodeFromFileOperationCallback, &error));
google_apis::test_util::RunBlockingPoolTask();
}
} // namespace drive
| junmin-zhu/chromium-rivertrail | chrome/browser/chromeos/drive/drive_scheduler_unittest.cc | C++ | bsd-3-clause | 8,727 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
-- | This module builds Docker (OpenContainer) images.
module Stack.Image
(stageContainerImageArtifacts, createContainerImageFromStage,
imgCmdName, imgDockerCmdName, imgOptsFromMonoid,
imgDockerOptsFromMonoid, imgOptsParser, imgDockerOptsParser)
where
import Control.Applicative
import Control.Exception.Lifted hiding (finally)
import Control.Monad
import Control.Monad.Catch hiding (bracket)
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader
import Control.Monad.Trans.Control
import Data.Char (toLower)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import Data.Typeable
import Options.Applicative
import Path
import Path.Extra
import Path.IO
import Stack.Constants
import Stack.Types
import Stack.Types.Internal
import System.Process.Run
type Build e m = (HasBuildConfig e, HasConfig e, HasEnvConfig e, HasTerminal e, MonadBaseControl IO m, MonadCatch m, MonadIO m, MonadLogger m, MonadReader e m)
type Assemble e m = (HasConfig e, HasTerminal e, MonadBaseControl IO m, MonadCatch m, MonadIO m, MonadLogger m, MonadMask m, MonadReader e m)
-- | Stages the executables & additional content in a staging
-- directory under '.stack-work'
stageContainerImageArtifacts :: Build e m
=> m ()
stageContainerImageArtifacts = do
imageDir <- imageStagingDir <$> getWorkingDir
removeTreeIfExists imageDir
createTree imageDir
stageExesInDir imageDir
syncAddContentToDir imageDir
-- | Builds a Docker (OpenContainer) image extending the `base` image
-- specified in the project's stack.yaml. Then new image will be
-- extended with an ENTRYPOINT specified for each `entrypoint` listed
-- in the config file.
createContainerImageFromStage :: Assemble e m
=> m ()
createContainerImageFromStage = do
imageDir <- imageStagingDir <$> getWorkingDir
createDockerImage imageDir
extendDockerImageWithEntrypoint imageDir
-- | Stage all the Package executables in the usr/local/bin
-- subdirectory of a temp directory.
stageExesInDir :: Build e m => Path Abs Dir -> m ()
stageExesInDir dir = do
srcBinPath <-
(</> $(mkRelDir "bin")) <$>
installationRootLocal
let destBinPath = dir </>
$(mkRelDir "usr/local/bin")
createTree destBinPath
copyDirectoryRecursive srcBinPath destBinPath
-- | Add any additional files into the temp directory, respecting the
-- (Source, Destination) mapping.
syncAddContentToDir :: Build e m => Path Abs Dir -> m ()
syncAddContentToDir dir = do
config <- asks getConfig
bconfig <- asks getBuildConfig
let imgAdd = maybe Map.empty imgDockerAdd (imgDocker (configImage config))
forM_
(Map.toList imgAdd)
(\(source,dest) ->
do sourcePath <- parseRelDir source
destPath <- parseAbsDir dest
let destFullPath = dir </> dropRoot destPath
createTree destFullPath
copyDirectoryRecursive
(bcRoot bconfig </> sourcePath)
destFullPath)
-- | Derive an image name from the project directory.
imageName :: Path Abs Dir -> String
imageName = map toLower . toFilePathNoTrailingSep . dirname
-- | Create a general purpose docker image from the temporary
-- directory of executables & static content.
createDockerImage :: Assemble e m => Path Abs Dir -> m ()
createDockerImage dir = do
menv <- getMinimalEnvOverride
config <- asks getConfig
let dockerConfig = imgDocker (configImage config)
case imgDockerBase =<< dockerConfig of
Nothing -> throwM StackImageDockerBaseUnspecifiedException
Just base -> do
liftIO
(writeFile
(toFilePath
(dir </>
$(mkRelFile "Dockerfile")))
(unlines ["FROM " ++ base, "ADD ./ /"]))
callProcess
Nothing
menv
"docker"
[ "build"
, "-t"
, fromMaybe
(imageName (parent (parent dir)))
(imgDockerImageName =<< dockerConfig)
, toFilePathNoTrailingSep dir]
-- | Extend the general purpose docker image with entrypoints (if
-- specified).
extendDockerImageWithEntrypoint :: Assemble e m => Path Abs Dir -> m ()
extendDockerImageWithEntrypoint dir = do
menv <- getMinimalEnvOverride
config <- asks getConfig
let dockerConfig = imgDocker (configImage config)
let dockerImageName = fromMaybe
(imageName (parent (parent dir)))
(imgDockerImageName =<< dockerConfig)
let imgEntrypoints = maybe Nothing imgDockerEntrypoints dockerConfig
case imgEntrypoints of
Nothing -> return ()
Just eps ->
forM_
eps
(\ep -> do
liftIO
(writeFile
(toFilePath
(dir </>
$(mkRelFile "Dockerfile")))
(unlines
[ "FROM " ++ dockerImageName
, "ENTRYPOINT [\"/usr/local/bin/" ++
ep ++ "\"]"
, "CMD []"]))
callProcess
Nothing
menv
"docker"
[ "build"
, "-t"
, dockerImageName ++ "-" ++ ep
, toFilePathNoTrailingSep dir])
-- | The command name for dealing with images.
imgCmdName :: String
imgCmdName = "image"
-- | The command name for building a docker container.
imgDockerCmdName :: String
imgDockerCmdName = "container"
-- | A parser for ImageOptsMonoid.
imgOptsParser :: Parser ImageOptsMonoid
imgOptsParser = ImageOptsMonoid <$>
optional
(subparser
(command
imgDockerCmdName
(info
imgDockerOptsParser
(progDesc "Create a container image (EXPERIMENTAL)"))))
-- | A parser for ImageDockerOptsMonoid.
imgDockerOptsParser :: Parser ImageDockerOptsMonoid
imgDockerOptsParser = ImageDockerOptsMonoid <$>
optional
(option
str
(long (imgDockerCmdName ++ "-" ++ T.unpack imgDockerBaseArgName) <>
metavar "NAME" <>
help "Docker base image name")) <*>
pure Nothing <*>
pure Nothing <*>
pure Nothing
-- | Convert image opts monoid to image options.
imgOptsFromMonoid :: ImageOptsMonoid -> ImageOpts
imgOptsFromMonoid ImageOptsMonoid{..} = ImageOpts
{ imgDocker = imgDockerOptsFromMonoid <$> imgMonoidDocker
}
-- | Convert Docker image opts monoid to Docker image options.
imgDockerOptsFromMonoid :: ImageDockerOptsMonoid -> ImageDockerOpts
imgDockerOptsFromMonoid ImageDockerOptsMonoid{..} = ImageDockerOpts
{ imgDockerBase = emptyToNothing imgDockerMonoidBase
, imgDockerEntrypoints = emptyToNothing imgDockerMonoidEntrypoints
, imgDockerAdd = fromMaybe Map.empty imgDockerMonoidAdd
, imgDockerImageName = emptyToNothing imgDockerMonoidImageName
}
where emptyToNothing Nothing = Nothing
emptyToNothing (Just s)
| null s =
Nothing
| otherwise =
Just s
-- | Stack image exceptions.
data StackImageException =
StackImageDockerBaseUnspecifiedException
deriving (Typeable)
instance Exception StackImageException
instance Show StackImageException where
show StackImageDockerBaseUnspecifiedException = "You must specify a base docker image on which to place your haskell executables."
| rvion/stack | src/Stack/Image.hs | Haskell | bsd-3-clause | 8,426 |
<?php
/*
* This file is part of Cachet.
*
* (c) Alt Three Services Limited
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
return [
// Setup form fields
'setup' => [
'email' => 'Email',
'username' => 'Emri i përdoruesit',
'password' => 'Fjalëkalimi',
'site_name' => 'Emri Faqes',
'site_domain' => 'Site Domain',
'site_timezone' => 'Zgjidh orën e zonës tuaj',
'site_locale' => 'Zgjidhni gjuhën tuaj',
'enable_google2fa' => 'Aktivizo Dy-Faktorin e identifikimit te Google',
'cache_driver' => 'Cache Driver',
'session_driver' => 'Session Driver',
],
// Login form fields
'login' => [
'login' => 'Username or Email',
'email' => 'Email',
'password' => 'Fjalëkalimi',
'2fauth' => 'Kodi i identifikimit',
'invalid' => 'Invalid username or password',
'invalid-token' => '"Token" i pavlefshëm',
'cookies' => 'You must enable cookies to login.',
],
// Incidents form fields
'incidents' => [
'name' => 'Emri',
'status' => 'Statusi',
'component' => 'Përbërësit',
'message' => 'Mesazhi',
'message-help' => 'You may also use Markdown.',
'scheduled_at' => 'When to schedule the maintenance for?',
'incident_time' => 'When did this incident occur?',
'notify_subscribers' => 'Notify subscribers?',
'visibility' => 'Incident Visibility',
'public' => 'Viewable by public',
'logged_in_only' => 'Only visible to logged in users',
'templates' => [
'name' => 'Emri',
'template' => 'Paraqitja',
'twig' => 'Incident Templates can make use of the <a href="http://twig.sensiolabs.org/" target="_blank">Twig</a> templating language.',
],
],
// Components form fields
'components' => [
'name' => 'Emri',
'status' => 'Statusi',
'group' => 'Group',
'description' => 'Përshkrimi',
'link' => 'Nderlidhja',
'tags' => 'Etiketa',
'tags-help' => 'Comma separated.',
'enabled' => 'Component enabled?',
'groups' => [
'name' => 'Emri',
'collapsing' => 'Choose visibility of the group',
'visible' => 'Always expanded',
'collapsed' => 'Collapse the group by default',
'collapsed_incident' => 'Collapse the group, but expand if there are issues',
],
],
// Metric form fields
'metrics' => [
'name' => 'Emri',
'suffix' => 'Suffix',
'description' => 'Përshkrimi',
'description-help' => 'You may also use Markdown.',
'display-chart' => 'Display chart on status page?',
'default-value' => 'Default value',
'calc_type' => 'Calculation of metrics',
'type_sum' => 'Sum',
'type_avg' => 'Average',
'places' => 'Decimal places',
'default_view' => 'Default view',
'points' => [
'value' => 'Value',
],
],
// Settings
'settings' => [
/// Application setup
'app-setup' => [
'site-name' => 'Emri Faqes',
'site-url' => 'Nderlidhja Faqes',
'display-graphs' => 'Display graphs on status page?',
'about-this-page' => 'Rreth faqes',
'days-of-incidents' => 'How many days of incidents to show?',
'banner' => 'Banner Image',
'banner-help' => "It's recommended that you upload files no bigger than 930px wide .",
'subscribers' => 'Allow people to signup to email notifications?',
],
'analytics' => [
'analytics_google' => 'Google Analytics code',
'analytics_gosquared' => 'GoSquared Analytics code',
'analytics_piwik_url' => 'URL of your Piwik instance (without http(s)://)',
'analytics_piwik_siteid' => 'Piwik\'s site id',
],
'localization' => [
'site-timezone' => 'Site timezone',
'site-locale' => 'Site language',
'date-format' => 'Date format',
'incident-date-format' => 'Incident timestamp format',
],
'security' => [
'allowed-domains' => 'Allowed domains',
'allowed-domains-help' => 'Comma separated. The domain set above is automatically allowed by default.',
],
'stylesheet' => [
'custom-css' => 'Custom Stylesheet',
],
'theme' => [
'background-color' => 'Background Color',
'background-fills' => 'Background fills (components, incidents, footer)',
'banner-background-color' => 'Banner background color',
'banner-padding' => 'Banner padding',
'fullwidth-banner' => 'Enable fullwidth banner?',
'text-color' => 'Text Color',
'dashboard-login' => 'Show dashboard button in the footer?',
'reds' => 'Red (used for errors)',
'blues' => 'Blue (used for information)',
'greens' => 'Green (used for success)',
'yellows' => 'Yellow (used for alerts)',
'oranges' => 'Orange (used for notices)',
'metrics' => 'Metrics fill',
'links' => 'Links',
],
],
'user' => [
'username' => 'Emri i përdoruesit',
'email' => 'Email',
'password' => 'Fjalëkalimi',
'api-token' => 'API Token',
'api-token-help' => 'Regenerating your API token will prevent existing applications from accessing Cachet.',
'gravatar' => 'Change your profile picture at Gravatar.',
'user_level' => 'User Level',
'levels' => [
'admin' => 'Admin',
'user' => 'User',
],
'2fa' => [
'help' => 'Enabling two factor authentication increases security of your account. You will need to download <a href="https://support.google.com/accounts/answer/1066447?hl=en">Google Authenticator</a> or a similar app on to your mobile device. When you login you will be asked to provide a token generated by the app.',
],
'team' => [
'description' => 'Invite your team members by entering their email addresses here.',
'email' => 'Email #:id',
],
],
// Buttons
'add' => 'Shto',
'save' => 'Ruaj',
'update' => ' Përditëso',
'create' => 'Krijo',
'edit' => 'Ndrysho',
'delete' => 'Fshije',
'submit' => 'Parashtroje',
'cancel' => 'Anulloje',
'remove' => 'Hiqe',
'invite' => 'Invite',
'signup' => 'Sign Up',
// Other
'optional' => '* Optional',
];
| thijs1108/ParnasSys-statuspage | resources/lang/sq/forms.php | PHP | bsd-3-clause | 7,472 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* Global wallpaperManager reference useful for poking at from the console.
*/
var wallpaperManager;
function init() {
window.addEventListener('load',
windowStateManager.saveStates.bind(windowStateManager));
window.addEventListener('unload',
windowStateManager.restoreStates.bind(windowStateManager));
WallpaperManager.initStrings(function() {
wallpaperManager = new WallpaperManager(document.body);
});
}
document.addEventListener('DOMContentLoaded', init);
| junmin-zhu/chromium-rivertrail | chrome/browser/resources/chromeos/wallpaper_manager/js/main.js | JavaScript | bsd-3-clause | 659 |
function FileData_Pairs(x)
{
x.t("managing","samples");
x.t("clear","fields");
x.t("home","page");
x.t("required","click");
x.t("having","entered");
x.t("execute","copy");
x.t("copying","existing");
x.t("icon","having");
x.t("icon","search");
x.t("entitled","new");
x.t("sample","managing");
x.t("sample","copying");
x.t("sample","entitled");
x.t("sample","copied");
x.t("sample","link");
x.t("sample","want");
x.t("sample","features");
x.t("sample","entered");
x.t("sample","follow");
x.t("sample","whose");
x.t("sample","click");
x.t("sample","page");
x.t("sample","appropriate");
x.t("sample","copy");
x.t("sample","names");
x.t("reset","clear");
x.t("editing","sample");
x.t("copied","sample");
x.t("copied","fields");
x.t("partial","text");
x.t("partial","search");
x.t("text","sample");
x.t("text","complete");
x.t("text","system");
x.t("new","sample");
x.t("new","name");
x.t("link","copy");
x.t("want","copy");
x.t("again","cananolab");
x.t("menu","option");
x.t("complete","search");
x.t("complete","exact");
x.t("results","sample");
x.t("features","annotations");
x.t("creating","new");
x.t("name","copied");
x.t("name","complete");
x.t("name","entered");
x.t("name","assigned");
x.t("anyway","sample");
x.t("enables","existing");
x.t("searches","database");
x.t("edit","copied");
x.t("entered","text");
x.t("entered","partial");
x.t("entered","exact");
x.t("entered","enter");
x.t("cananolab","opens");
x.t("cananolab","database");
x.t("skip","search");
x.t("updating","sample");
x.t("search","execute");
x.t("search","icon");
x.t("search","sample");
x.t("search","partial");
x.t("search","results");
x.t("search","cananolab");
x.t("fields","begin");
x.t("fields","page");
x.t("contain","entered");
x.t("request","select");
x.t("begin","again");
x.t("select","search");
x.t("annotations","facilitate");
x.t("samples","home");
x.t("samples","editing");
x.t("samples","menu");
x.t("samples","enables");
x.t("opens","update");
x.t("assigned","edit");
x.t("follow","steps");
x.t("steps","click");
x.t("option","manage");
x.t("exact","text");
x.t("exact","search");
x.t("database","sample");
x.t("database","anyway");
x.t("click","reset");
x.t("click","search");
x.t("click","samples");
x.t("click","submit");
x.t("click","copy");
x.t("enter","name");
x.t("whose","name");
x.t("existing","sample");
x.t("existing","samples");
x.t("page","required");
x.t("page","copied");
x.t("page","click");
x.t("page","enter");
x.t("facilitate","creating");
x.t("information","updating");
x.t("appropriate","information");
x.t("submit","click");
x.t("copy","sample");
x.t("copy","skip");
x.t("copy","request");
x.t("copy","existing");
x.t("manage","samples");
x.t("system","searches");
x.t("names","contain");
x.t("update","sample");
}
| NCIP/cananolab | docs/webappOnlineHelp/wwhdata/js/search/pairs/pair25.js | JavaScript | bsd-3-clause | 2,843 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_URL_REQUEST_URL_REQUEST_CONTEXT_STORAGE_H_
#define NET_URL_REQUEST_URL_REQUEST_CONTEXT_STORAGE_H_
#include "base/basictypes.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "net/base/net_export.h"
namespace net {
class CertVerifier;
class CookieStore;
class FraudulentCertificateReporter;
class FtpTransactionFactory;
class HostResolver;
class HttpAuthHandlerFactory;
class HttpServerProperties;
class HttpTransactionFactory;
class NetLog;
class NetworkDelegate;
class ServerBoundCertService;
class ProxyService;
class SSLConfigService;
class TransportSecurityState;
class URLRequestContext;
class URLRequestJobFactory;
class URLRequestThrottlerManager;
// URLRequestContextStorage is a helper class that provides storage for unowned
// member variables of URLRequestContext.
class NET_EXPORT URLRequestContextStorage {
public:
// Note that URLRequestContextStorage does not acquire a reference to
// URLRequestContext, since it is often designed to be embedded in a
// URLRequestContext subclass.
explicit URLRequestContextStorage(URLRequestContext* context);
~URLRequestContextStorage();
// These setters will set both the member variables and call the setter on the
// URLRequestContext object. In all cases, ownership is passed to |this|.
void set_net_log(NetLog* net_log);
void set_host_resolver(scoped_ptr<HostResolver> host_resolver);
void set_cert_verifier(CertVerifier* cert_verifier);
void set_server_bound_cert_service(
ServerBoundCertService* server_bound_cert_service);
void set_fraudulent_certificate_reporter(
FraudulentCertificateReporter* fraudulent_certificate_reporter);
void set_http_auth_handler_factory(
HttpAuthHandlerFactory* http_auth_handler_factory);
void set_proxy_service(ProxyService* proxy_service);
void set_ssl_config_service(SSLConfigService* ssl_config_service);
void set_network_delegate(NetworkDelegate* network_delegate);
void set_http_server_properties(HttpServerProperties* http_server_properties);
void set_cookie_store(CookieStore* cookie_store);
void set_transport_security_state(
TransportSecurityState* transport_security_state);
void set_http_transaction_factory(
HttpTransactionFactory* http_transaction_factory);
void set_ftp_transaction_factory(
FtpTransactionFactory* ftp_transaction_factory);
void set_job_factory(URLRequestJobFactory* job_factory);
void set_throttler_manager(URLRequestThrottlerManager* throttler_manager);
private:
// We use a raw pointer to prevent reference cycles, since
// URLRequestContextStorage can often be contained within a URLRequestContext
// subclass.
URLRequestContext* const context_;
// Owned members.
scoped_ptr<NetLog> net_log_;
scoped_ptr<HostResolver> host_resolver_;
scoped_ptr<CertVerifier> cert_verifier_;
scoped_ptr<ServerBoundCertService> server_bound_cert_service_;
scoped_ptr<FraudulentCertificateReporter> fraudulent_certificate_reporter_;
scoped_ptr<HttpAuthHandlerFactory> http_auth_handler_factory_;
scoped_ptr<ProxyService> proxy_service_;
// TODO(willchan): Remove refcounting on these members.
scoped_refptr<SSLConfigService> ssl_config_service_;
scoped_ptr<NetworkDelegate> network_delegate_;
scoped_ptr<HttpServerProperties> http_server_properties_;
scoped_refptr<CookieStore> cookie_store_;
scoped_ptr<TransportSecurityState> transport_security_state_;
scoped_ptr<HttpTransactionFactory> http_transaction_factory_;
scoped_ptr<FtpTransactionFactory> ftp_transaction_factory_;
scoped_ptr<URLRequestJobFactory> job_factory_;
scoped_ptr<URLRequestThrottlerManager> throttler_manager_;
DISALLOW_COPY_AND_ASSIGN(URLRequestContextStorage);
};
} // namespace net
#endif // NET_URL_REQUEST_URL_REQUEST_CONTEXT_STORAGE_H_
| junmin-zhu/chromium-rivertrail | net/url_request/url_request_context_storage.h | C | bsd-3-clause | 3,981 |
<?php
namespace Alpha\Controller;
use Alpha\Util\Logging\Logger;
use Alpha\Util\Logging\KPI;
use Alpha\Util\Config\ConfigProvider;
use Alpha\Util\Security\SecurityUtils;
use Alpha\Util\Extension\TCPDFFacade;
use Alpha\Util\Http\Request;
use Alpha\Util\Http\Response;
use Alpha\Util\Service\ServiceFactory;
use Alpha\Util\File\FileUtils;
use Alpha\Model\Article;
use Alpha\Model\ArticleComment;
use Alpha\Model\Type\Relation;
use Alpha\View\View;
use Alpha\View\ViewState;
use Alpha\View\Widget\Button;
use Alpha\Exception\SecurityException;
use Alpha\Exception\AlphaException;
use Alpha\Exception\RecordNotFoundException;
use Alpha\Exception\IllegalArguementException;
use Alpha\Exception\ResourceNotFoundException;
use Alpha\Exception\FileNotFoundException;
use Alpha\Model\ActiveRecord;
use Alpha\Controller\Front\FrontController;
/**
* Controller used handle Article objects.
*
* @since 1.0
*
* @author John Collins <dev@alphaframework.org>
* @license http://www.opensource.org/licenses/bsd-license.php The BSD License
* @copyright Copyright (c) 2021, John Collins (founder of Alpha Framework).
* All rights reserved.
*
* <pre>
* 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 Alpha Framework 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.
* </pre>
*/
class ArticleController extends ActiveRecordController implements ControllerInterface
{
/**
* The Article record object that this controller is currently working with.
*
* @var \Alpha\Model\Article
*
* @since 3.0
*/
protected $record = null;
/**
* Trace logger.
*
* @var \Alpha\Util\Logging\Logger
*
* @since 1.0
*/
private static $logger = null;
/**
* constructor to set up the object.
*
* @since 1.0
*/
public function __construct()
{
self::$logger = new Logger('ArticleController');
self::$logger->debug('>>__construct()');
// ensure that the super class constructor is called, indicating the rights group
parent::__construct('Public');
self::$logger->debug('<<__construct');
}
/**
* Handle GET requests.
*
* @param \Alpha\Util\Http\Request $request
*
* @throws \Alpha\Exception\ResourceNotFoundException
*
* @since 1.0
*/
public function doGET(\Alpha\Util\Http\Request $request): \Alpha\Util\Http\Response
{
self::$logger->debug('>>doGET($request=['.var_export($request, true).'])');
$config = ConfigProvider::getInstance();
$params = $request->getParams();
$body = '';
// handle requests for PDFs
if (isset($params['title']) && (isset($params['pdf']) || $request->getHeader('Accept') == 'application/pdf')) {
try {
$title = str_replace($config->get('cms.url.title.separator'), ' ', $params['title']);
if (isset($params['ActiveRecordType']) && class_exists($params['ActiveRecordType'])) {
$record = new $params['ActiveRecordType']();
} else {
$record = new Article();
}
$record->loadByAttribute('title', $title);
$this->record = $record;
ActiveRecord::disconnect();
$pdf = new TCPDFFacade($record);
$pdfData = $pdf->getPDFData();
$pdfDownloadName = str_replace(' ', '-', $record->get('title').'.pdf');
$headers = array(
'Pragma' => 'public',
'Expires' => 0,
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-Transfer-Encoding' => 'binary',
'Content-Type' => 'application/pdf',
'Content-Length' => strlen($pdfData),
'Content-Disposition' => 'attachment; filename="'.$pdfDownloadName.'";',
);
return new Response(200, $pdfData, $headers);
} catch (IllegalArguementException $e) {
self::$logger->error($e->getMessage());
throw new ResourceNotFoundException($e->getMessage());
} catch (RecordNotFoundException $e) {
self::$logger->error($e->getMessage());
throw new ResourceNotFoundException($e->getMessage());
}
}
// view edit article requests
if ((isset($params['view']) && $params['view'] == 'edit') && (isset($params['title']) || isset($params['ActiveRecordID']))) {
if (isset($params['ActiveRecordType']) && class_exists($params['ActiveRecordType'])) {
$record = new $params['ActiveRecordType']();
} else {
$record = new Article();
}
try {
if (isset($params['title'])) {
$title = str_replace($config->get('cms.url.title.separator'), ' ', $params['title']);
$record->loadByAttribute('title', $title);
} else {
$record->load($params['ActiveRecordID']);
}
} catch (RecordNotFoundException $e) {
self::$logger->warn($e->getMessage());
$body .= View::renderErrorPage(404, 'Failed to find the requested article!');
return new Response(404, $body, array('Content-Type' => 'text/html'));
}
ActiveRecord::disconnect();
$this->record = $record;
$view = View::getInstance($record);
// set up the title and meta details
$this->setTitle($record->get('title').' (editing)');
$this->setDescription('Page to edit '.$record->get('title').'.');
$this->setKeywords('edit,article');
$body .= View::displayPageHead($this);
$message = $this->getStatusMessage();
if (!empty($message)) {
$body .= $message;
}
$body .= $view->editView(array('URI' => $request->getURI()));
$body .= View::renderDeleteForm($request->getURI());
$body .= View::displayPageFoot($this);
self::$logger->debug('<<doGET');
return new Response(200, $body, array('Content-Type' => 'text/html'));
}
// handle requests for viewing articles
if (isset($params['title']) || isset($params['ActiveRecordID'])) {
$KDP = new KPI('viewarticle');
if (isset($params['ActiveRecordType']) && class_exists($params['ActiveRecordType'])) {
$record = new $params['ActiveRecordType']();
} else {
$record = new Article();
}
try {
if (isset($params['title'])) {
$title = str_replace($config->get('cms.url.title.separator'), ' ', $params['title']);
$record->loadByAttribute('title', $title, false, array('ID', 'version_num', 'created_ts', 'updated_ts', 'title', 'author', 'published', 'content', 'headerContent'));
} else {
$record->load($params['ActiveRecordID']);
}
if (!$record->get('published')) {
throw new RecordNotFoundException('Attempted to load an article which is not published yet');
}
$record->set('tags', $record->getID());
} catch (IllegalArguementException $e) {
self::$logger->warn($e->getMessage());
throw new ResourceNotFoundException('The file that you have requested cannot be found!');
} catch (RecordNotFoundException $e) {
self::$logger->warn($e->getMessage());
throw new ResourceNotFoundException('The article that you have requested cannot be found!');
}
$this->record = $record;
$this->setTitle($record->get('title'));
$this->setDescription($record->get('description'));
$recordView = View::getInstance($record);
$body .= View::displayPageHead($this);
$message = $this->getStatusMessage();
if (!empty($message)) {
$body .= $message;
}
$body .= $recordView->markdownView();
$body .= View::displayPageFoot($this);
$KDP->log();
return new Response(200, $body, array('Content-Type' => 'text/html'));
}
// handle requests to view an article stored in a file
if (isset($params['file'])) {
try {
$record = new Article();
// just checking to see if the file path is absolute or not
if (mb_substr($params['file'], 0, 1) == '/') {
$record->loadContentFromFile($params['file']);
} else {
$record->loadContentFromFile($config->get('app.root').'docs/'.$params['file']);
}
} catch (IllegalArguementException $e) {
self::$logger->error($e->getMessage());
throw new ResourceNotFoundException($e->getMessage());
} catch (FileNotFoundException $e) {
self::$logger->warn($e->getMessage().' File path is ['.$params['file'].']');
throw new ResourceNotFoundException('Failed to load the requested article from the file system!');
}
$this->record = $record;
$this->setTitle($record->get('title'));
$recordView = View::getInstance($record);
$body .= View::displayPageHead($this, false);
$body .= $recordView->markdownView();
$body .= View::displayPageFoot($this);
return new Response(200, $body, array('Content-Type' => 'text/html'));
}
// handle requests to view a list of articles
if (isset($params['start'])) {
return parent::doGET($request);
}
// create a new article requests
$record = new Article();
$view = View::getInstance($record);
// set up the title and meta details
$this->setTitle('Creating article');
$this->setDescription('Page to create a new article.');
$this->setKeywords('create,article');
$body .= View::displayPageHead($this);
$message = $this->getStatusMessage();
if (!empty($message)) {
$body .= $message;
}
$fields = array('formAction' => $this->request->getURI());
$body .= $view->createView($fields);
$body .= View::displayPageFoot($this);
self::$logger->debug('<<doGET');
return new Response(200, $body, array('Content-Type' => 'text/html'));
}
/**
* Method to handle PUT requests.
*
* @param \Alpha\Util\Http\Request $request
*
* @since 1.0
*/
public function doPUT(\Alpha\Util\Http\Request $request): \Alpha\Util\Http\Response
{
self::$logger->debug('>>doPUT($request=['.var_export($request, true).'])');
$config = ConfigProvider::getInstance();
$params = $request->getParams();
if (!isset($params['ActiveRecordID']) && isset($params['title'])) {
$title = str_replace($config->get('cms.url.title.separator'), ' ', $params['title']);
$record = new Article();
$record->loadByAttribute('title', $title);
$params['ActiveRecordID'] = $record->getID();
$request->addParams(array('ActiveRecordID' => $params['ActiveRecordID']));
}
if (!isset($params['ActiveRecordType'])) {
$request->addParams(array('ActiveRecordType' => 'Alpha\Model\Article'));
}
$response = parent::doPUT($request);
if ($this->getNextJob() != '') {
$response->redirect($this->getNextJob());
} else {
if ($this->request->isSecureURI()) {
$response->redirect(FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType=Alpha\Model\Article&ActiveRecordID='.$this->record->getID().'&view=edit'));
} else {
$title = str_replace(' ', $config->get('cms.url.title.separator'), $this->record->get('title'));
$response->redirect($config->get('app.url').'/a/'.$title.'/edit');
}
}
self::$logger->debug('<<doPUT');
return $response;
}
/**
* Method to handle DELETE requests.
*
* @param \Alpha\Util\Http\Request
*
* @since 2.0
*/
public function doDELETE($request): \Alpha\Util\Http\Response
{
self::$logger->debug('>>doDELETE($request=['.var_export($request, true).'])');
$config = ConfigProvider::getInstance();
$params = $request->getParams();
$this->setUnitOfWork(array());
if (!isset($params['ActiveRecordID']) && isset($params['title'])) {
$title = str_replace($config->get('cms.url.title.separator'), ' ', $params['title']);
$record = new Article();
$record->loadByAttribute('title', $title);
$params['ActiveRecordID'] = $record->getID();
$request->addParams(array('ActiveRecordID' => $params['ActiveRecordID']));
}
if (!isset($params['ActiveRecordType'])) {
$request->addParams(array('ActiveRecordType' => 'Alpha\Model\Article'));
}
self::$logger->debug('<<doDELETE');
return parent::doDELETE($request);
}
/**
* Renders custom HTML header content.
*
* @since 1.0
*/
public function duringDisplayPageHead(): string
{
$config = ConfigProvider::getInstance();
$params = $this->request->getParams();
$html = '';
if ((isset($params['view']) && ($params['view'] == 'edit' || $params['view'] == 'create')) || (isset($params['ActiveRecordType']) && !isset($params['ActiveRecordID']))) {
$fieldid = ($config->get('security.encrypt.http.fieldnames') ? 'text_field_'.base64_encode(SecurityUtils::encrypt('content')).'_0' : 'text_field_content_0');
$html .= '
<script type="text/javascript">
$(document).ready(function() {
$(\'[id="'.$fieldid.'"]\').pagedownBootstrap({
\'sanatize\': false
});
});
</script>';
} elseif (isset($params['view']) && $params['view'] == 'print') {
$html .= '<link rel="StyleSheet" type="text/css" href="'.$config->get('app.url').'/css/print.css">';
}
if ($this->record instanceof Article) {
$headerContent = $this->record->get('headerContent');
if ($headerContent != '') {
$html .= $headerContent;
}
}
return $html;
}
/**
* Callback that inserts the CMS level header.
*
* @since 1.0
*/
public function insertCMSDisplayStandardHeader(): string
{
if ($this->request->getParam('token') != null) {
return '';
}
if (!$this->record instanceof Article) {
return '';
}
$config = ConfigProvider::getInstance();
$html = '';
if ($config->get('cms.display.standard.header')) {
$html .= '<p><a href="'.$config->get('app.url').'">'.$config->get('app.title').'</a> ';
$html .= 'Date Added: <em>'.$this->record->getCreateTS()->getDate().'</em> ';
$html .= 'Last Updated: <em>'.$this->record->getUpdateTS()->getDate().'</em> ';
$html .= 'Revision: <em>'.$this->record->getVersion().'</em></p>';
}
$html .= $config->get('cms.header');
return $html;
}
/**
* Callback used to render footer content, including comments, votes and print/PDF buttons when
* enabled to do so.
*
* @since 1.0
*/
public function beforeDisplayPageFoot(): string
{
$config = ConfigProvider::getInstance();
$sessionProvider = $config->get('session.provider.name');
$session = ServiceFactory::getInstance($sessionProvider, 'Alpha\Util\Http\Session\SessionProviderInterface');
$html = '';
$params = $this->request->getParams();
// this will ensure that direct requests to ActiveRecordController will be re-directed here.
if (isset($this->record) && !$this->record->isTransient()) {
$this->setName($config->get('app.url').$this->request->getURI());
$this->setUnitOfWork(array($config->get('app.url').$this->request->getURI(), $config->get('app.url').$this->request->getURI()));
} else {
$this->setUnitOfWork(array());
}
if ($this->record != null) {
if (isset($params['view']) && $params['view'] == 'detailed') {
if ($config->get('cms.display.comments')) {
$html .= $this->renderComments();
}
if ($config->get('cms.display.tags')) {
$html .= $this->renderTags();
}
if ($config->get('cms.display.votes')) {
$rating = $this->record->getArticleScore();
$votes = $this->record->getArticleVotes();
$html .= '<p>Average Article User Rating: <strong>'.$rating.'</strong> out of 10 (based on <strong>'.count($votes).'</strong> votes)</p>';
}
if (!$this->record->checkUserVoted() && $config->get('cms.voting.allowed')) {
$html .= $this->renderVotes();
}
ActiveRecord::disconnect();
if ($config->get('cms.allow.print.versions')) {
$html .= ' ';
$temp = new Button("window.open('".$this->record->get('printURL')."')", 'Open Printer Version', 'printBut');
$html .= $temp->render();
}
$html .= ' ';
if ($config->get('cms.allow.pdf.versions')) {
$html .= ' ';
$temp = new Button("document.location = '".FrontController::generateSecureURL("act=Alpha\Controller\ArticleController&mode=pdf&title=".$this->record->get('title'))."';", 'Open PDF Version', 'pdfBut');
$html .= $temp->render();
}
// render edit button for admins only
if ($session->get('currentUser') instanceof \Alpha\Model\Person && $session->get('currentUser')->inGroup('Admin')) {
$html .= ' ';
$button = new Button("document.location = '".FrontController::generateSecureURL('act=Alpha\Controller\ArticleController&mode=edit&ActiveRecordID='.$this->record->getID())."'", 'Edit', 'editBut');
$html .= $button->render();
}
}
if ($config->get('cms.display.standard.footer')) {
$html .= $this->renderStandardFooter();
}
}
$html .= $config->get('cms.footer');
return $html;
}
/**
* Method for displaying the user comments for the article.
*
* @since 1.0
*/
private function renderComments(): string
{
$config = ConfigProvider::getInstance();
$sessionProvider = $config->get('session.provider.name');
$session = ServiceFactory::getInstance($sessionProvider, 'Alpha\Util\Http\Session\SessionProviderInterface');
$html = '';
$comments = $this->record->getArticleComments();
$commentsCount = count($comments);
$URL = FrontController::generateSecureURL('act=Alpha\Controller\ActiveRecordController&ActiveRecordType=Alpha\Model\ArticleComment');
$fields = array('formAction' => $URL);
if ($config->get('cms.display.comments') && $commentsCount > 0) {
$html .= '<h2>There are ['.$commentsCount.'] user comments for this article</h2>';
for ($i = 0; $i < $commentsCount; ++$i) {
$view = View::getInstance($comments[$i]);
$html .= $view->markdownView($fields);
}
}
if ($session->get('currentUser') != null && $config->get('cms.comments.allowed')) {
$comment = new ArticleComment();
$comment->set('articleID', $this->record->getID());
$view = View::getInstance($comment);
$html .= $view->createView($fields);
}
return $html;
}
/**
* Method for displaying the tags for the article.
*
* @since 3.0
*/
private function renderTags(): string
{
$config = ConfigProvider::getInstance();
$relation = $this->record->getPropObject('tags');
$html = '';
if ($relation instanceof Relation) {
$tags = $relation->getRelated();
if (count($tags) > 0) {
$html .= '<p>Tags:';
foreach ($tags as $tag) {
$html .= ' <a href="'.$config->get('app.url').'/search/'.$tag->get('content').'">'.$tag->get('content').'</a>';
}
$html .= '</p>';
}
}
return $html;
}
/**
* Method for displaying the votes for the article.
*
* @since 3.0
*/
private function renderVotes(): string
{
$config = ConfigProvider::getInstance();
$sessionProvider = $config->get('session.provider.name');
$session = ServiceFactory::getInstance($sessionProvider, 'Alpha\Util\Http\Session\SessionProviderInterface');
$URL = FrontController::generateSecureURL('act=Alpha\Controller\ActiveRecordController&ActiveRecordType=Alpha\Model\ArticleVote');
$html = '<form action="'.$URL.'" method="post" accept-charset="UTF-8">';
$fieldname = ($config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('score')) : 'score');
$html .= '<p>Please rate this article from 1-10 (10 being the best):'.
'<select name="'.$fieldname.'">'.
'<option value="1">1'.
'<option value="2">2'.
'<option value="3">3'.
'<option value="4">4'.
'<option value="5">5'.
'<option value="6">6'.
'<option value="7">7'.
'<option value="8">8'.
'<option value="9">9'.
'<option value="10">10'.
'</select></p> ';
$fieldname = ($config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('articleID')) : 'articleID');
$html .= '<input type="hidden" name="'.$fieldname.'" value="'.$this->record->getID().'"/>';
$fieldname = ($config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('personID')) : 'personID');
$html .= '<input type="hidden" name="'.$fieldname.'" value="'.$session->get('currentUser')->getID().'"/>';
$fieldname = ($config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('statusMessage')) : 'statusMessage');
$html .= '<input type="hidden" name="'.$fieldname.'" value="Thank you for rating this article!"/>';
$temp = new Button('submit', 'Vote!', 'voteBut');
$html .= $temp->render();
$html .= View::renderSecurityFields();
$html .= '<form>';
return $html;
}
/**
* Method for displaying the standard CMS footer for the article.
*
* @since 3.0
*/
private function renderStandardFooter(): string
{
$html = '<p>Article URL: <a href="'.$this->record->get('URL').'">'.$this->record->get('URL').'</a><br>';
$html .= 'Title: '.$this->record->get('title').'<br>';
$html .= 'Author: '.$this->record->get('author').'</p>';
return $html;
}
}
| alphadevx/alpha | Alpha/Controller/ArticleController.php | PHP | bsd-3-clause | 25,517 |
<?php
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use Monolog\Logger;
/**
* NativeMailerHandler uses the mail() function to send the emails
*
* @author Christophe Coevoet <stof@notk.org>
* @author Mark Garrett <mark@moderndeveloperllc.com>
*/
class NativeMailerHandler extends MailHandler
{
/**
* The email addresses to which the message will be sent
* @var array
*/
protected $to;
/**
* The subject of the email
* @var string
*/
protected $subject;
/**
* Optional headers for the message
* @var array
*/
protected $headers = array();
/**
* Optional parameters for the message
* @var array
*/
protected $parameters = array();
/**
* The wordwrap length for the message
* @var integer
*/
protected $maxColumnWidth;
/**
* The Content-type for the message
* @var string
*/
protected $contentType = 'text/plain';
/**
* The encoding for the message
* @var string
*/
protected $encoding = 'utf-8';
/**
* @param string|array $to The receiver of the mail
* @param string $subject The subject of the mail
* @param string $from The sender of the mail
* @param integer $level The minimum logging level at which this handler will be triggered
* @param boolean $bubble Whether the messages that are handled can bubble up the stack or not
* @param int $maxColumnWidth The maximum column width that the message lines will have
*/
public function __construct($to, $subject, $from, $level = Logger::ERROR, $bubble = true, $maxColumnWidth = 70)
{
parent::__construct($level, $bubble);
$this->to = is_array($to) ? $to : array($to);
$this->subject = $subject;
$this->addHeader(sprintf('From: %s', $from));
$this->maxColumnWidth = $maxColumnWidth;
}
/**
* Add headers to the message
*
* @param string|array $headers Custom added headers
* @return self
*/
public function addHeader($headers)
{
foreach ((array) $headers as $header) {
if (strpos($header, "\n") !== false || strpos($header, "\r") !== false) {
throw new \InvalidArgumentException('Headers can not contain newline characters for security reasons');
}
$this->headers[] = $header;
}
return $this;
}
/**
* Add parameters to the message
*
* @param string|array $parameters Custom added parameters
* @return self
*/
public function addParameter($parameters)
{
$this->parameters = array_merge($this->parameters, (array) $parameters);
return $this;
}
/**
* {@inheritdoc}
*/
protected function send($content, array $records)
{
$content = wordwrap($content, $this->maxColumnWidth);
$headers = ltrim(implode("\r\n", $this->headers) . "\r\n", "\r\n");
$headers .= 'Content-type: ' . $this->getContentType() . '; charset=' . $this->getEncoding() . "\r\n";
if ($this->getContentType() == 'text/html' && false === strpos($headers, 'MIME-Version:')) {
$headers .= 'MIME-Version: 1.0' . "\r\n";
}
foreach ($this->to as $to) {
mail($to, $this->subject, $content, $headers, implode(' ', $this->parameters));
}
}
/**
* @return string $contentType
*/
public function getContentType()
{
return $this->contentType;
}
/**
* @return string $encoding
*/
public function getEncoding()
{
return $this->encoding;
}
/**
* @param string $contentType The content type of the email - Defaults to text/plain. Use text/html for HTML
* messages.
* @return self
*/
public function setContentType($contentType)
{
if (strpos($contentType, "\n") !== false || strpos($contentType, "\r") !== false) {
throw new \InvalidArgumentException('The content type can not contain newline characters to prevent email header injection');
}
$this->contentType = $contentType;
return $this;
}
/**
* @param string $encoding
* @return self
*/
public function setEncoding($encoding)
{
if (strpos($encoding, "\n") !== false || strpos($encoding, "\r") !== false) {
throw new \InvalidArgumentException('The encoding can not contain newline characters to prevent email header injection');
}
$this->encoding = $encoding;
return $this;
}
}
| ruitiagocosta/veinteractive | www/veinteractive/vendor/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php | PHP | mit | 4,920 |
/*
* The Yices SMT Solver. Copyright 2014 SRI International.
*
* This program may only be used subject to the noncommercial end user
* license agreement which is downloadable along with this program.
*/
/***********************************************************
* EXTENSION OF THE EGRAPH TO DEAL WITH FUNCTION UPDATES *
**********************************************************/
#include <assert.h>
#include "scratch/update_graph.h"
#include "solvers/egraph/composites.h"
#include "solvers/egraph/egraph.h"
#include "utils/memalloc.h"
#include "utils/pointer_vectors.h"
#include "utils/tagged_pointers.h"
/****************
* QUEUE/TREE *
***************/
/*
* Initialization: nothing allocated yet
*/
static void init_ugraph_queue(ugraph_queue_t *queue) {
queue->size = 0;
queue->top = 0;
queue->ptr = 0;
queue->data = NULL;
}
/*
* Make room
*/
static void extend_ugraph_queue(ugraph_queue_t *queue) {
uint32_t n;
n = queue->size;
if (n == 0) {
n = DEF_UGRAPH_QUEUE_SIZE;
assert(n <= MAX_UGRAPH_QUEUE_SIZE);
queue->data = (ugraph_visit_t *) safe_malloc(n * sizeof(ugraph_visit_t));
queue->size = n;
} else {
// try 50% larger
n ++;
n += n>>1;
if (n > MAX_UGRAPH_QUEUE_SIZE) {
out_of_memory();
}
queue->data = (ugraph_visit_t *) safe_realloc(queue->data, n * sizeof(ugraph_visit_t));
queue->size = n;
}
}
/*
* Delete the queue
*/
static void delete_ugraph_queue(ugraph_queue_t *queue) {
safe_free(queue->data);
queue->data = NULL;
}
/*
* Reset the queue
*/
static void reset_ugraph_queue(ugraph_queue_t *queue) {
queue->top = 0;
queue->ptr = 0;
}
/*
* Push triple (x, p, u) at the end of the queue
* - x = node index
* - p = previous record
* - u = edge (update composite)
*/
static void ugraph_queue_push(ugraph_queue_t *queue, int32_t x, int32_t p, composite_t *u) {
uint32_t i;
i = queue->top;
if (i == queue->size) {
extend_ugraph_queue(queue);
}
assert(i < queue->size);
queue->data[i].node = x;
queue->data[i].pre = p;
queue->data[i].edge = u;
queue->top = i+1;
}
/*
* Add a root node x
*/
static inline void ugraph_queue_push_root(ugraph_queue_t *queue, int32_t x) {
assert(queue->top == 0 && queue->ptr == 0);
ugraph_queue_push(queue, x, -1, NULL);
}
/*
* Add node y
* - y must be a successor of the node stored in queue->data[ptr]
* - u = edge from the current node to y
*/
static inline void ugraph_queue_push_next(ugraph_queue_t *queue, int32_t y, composite_t *u) {
assert(queue->top > 0);
ugraph_queue_push(queue, y, queue->ptr, u);
}
/*
* Check whether the queue is empty
*/
static inline bool empty_ugraph_queue(ugraph_queue_t *queue) {
return queue->top == queue->ptr;
}
/*
* Get the id of the current node (at index ptr)
*/
static inline int32_t ugraph_queue_current_node(ugraph_queue_t *queue) {
assert(queue->ptr < queue->top);
return queue->data[queue->ptr].node;
}
/*
* Move to the next node
*/
static inline void ugraph_queue_pop(ugraph_queue_t *queue) {
assert(queue->ptr < queue->top);
queue->ptr ++;
}
/*************************************
* SET OF PAIRS (tags, range type) *
************************************/
/*
* Initialize to the empty set
* - types = the relevant type table
*/
static void init_lpair_set(lpair_set_t *set, type_table_t *types) {
set->size = 0;
set->nelems = 0;
set->data = NULL;
set->types = types;
}
/*
* Make the array larger
*/
static void extend_lpair_set(lpair_set_t *set) {
uint32_t n;
n = set->size;
if (n == 0) {
n = DEF_LPAIR_SET_SIZE;
assert(n <= MAX_LPAIR_SET_SIZE);
set->data = (lambda_pair_t *) safe_malloc(n * sizeof(lambda_pair_t));
set->size = n;
} else {
n ++;
n += n>>1;
if (n > MAX_LPAIR_SET_SIZE) {
out_of_memory();
}
set->data = (lambda_pair_t *) safe_realloc(set->data, n * sizeof(lambda_pair_t));
set->size = n;
}
}
/*
* Add pair [tag, tau] at the end of set->data
*/
static void lpair_set_push(lpair_set_t *set, int32_t tag, type_t tau) {
uint32_t i;
i = set->nelems;
if (i == set->size) {
extend_lpair_set(set);
}
assert(i < set->size);
set->data[i].tag = tag;
set->data[i].range = tau;
set->nelems = i+1;
}
/*
* Empty the table
*/
static inline void reset_lpair_set(lpair_set_t *set) {
set->nelems = 0;
}
/*
* Free memory
*/
static void delete_lpair_set(lpair_set_t *set) {
safe_free(set->data);
set->data = NULL;
}
/*
* Check whether the set is empty
*/
#ifndef NDEBUG
static inline bool lpair_set_is_empty(lpair_set_t *set) {
return set->nelems == 0;
}
#endif
/*
* Check whether the set contains a pair [tag, sigma]
* where sigma is compatible with tau
*/
static bool lpair_set_has_match(lpair_set_t *set, int32_t tag, type_t tau) {
lambda_pair_t *data;
uint32_t i, n;
assert(good_type(set->types, tau));
n = set->nelems;
data = set->data;
for (i=0; i<n; i++) {
if (data->tag == tag &&
(data->range == tau || compatible_types(set->types, tau, data->range))) {
return true;
}
data ++;
}
return false;
}
/*
* Check whether the set contains the pair [tag, tau]
*/
static bool lpair_set_member(lpair_set_t *set, int32_t tag, type_t tau) {
lambda_pair_t *data;
uint32_t i, n;
assert(good_type(set->types, tau));
n = set->nelems;
data = set->data;
for (i=0; i<n; i++) {
if (data->tag == tag && data->range == tau) {
return true;
}
data ++;
}
return false;
}
/*
* Add pair [tag, tau] to the set. No change if the pair is already in the set.
*/
static void lpair_set_add(lpair_set_t *set, int32_t tag, type_t tau) {
if (! lpair_set_member(set, tag, tau)) {
lpair_set_push(set, tag, tau);
}
}
/*
* Add the pair [tag, sigma] where sigma = range type for tau
*/
static inline void lpair_set_add_ftype(lpair_set_t *set, int32_t tag, type_t tau) {
lpair_set_add(set, tag, function_type_range(set->types, tau));
}
/*********************
* PARTITION TABLE *
********************/
/*
* Hash and match function required for the partition table:
* - the table store composites of the form (apply f t_1 ... t_n)
* - two composites c and d match each other if their arguments t_1 ... t_n
* and u_1 ... u_n are equal in the Egraph
*/
static uint32_t ugraph_hash_arg(egraph_t *egraph, composite_t *c) {
return hash_arg_signature(c, egraph->terms.label);
}
static uint32_t ugraph_match_arg(egraph_t *egraph, composite_t *c, composite_t *d) {
return same_arg_signature(c, d, egraph->terms.label);
}
/*
* Initialize the partition table
*/
static inline void init_ugraph_partition(ppart_t *partition, egraph_t *egraph) {
init_ptr_partition(partition, 0, egraph, (ppart_hash_fun_t) ugraph_hash_arg, (ppart_match_fun_t) ugraph_match_arg);
}
/***********************
* STATISTICS RECORD *
**********************/
static void init_ugraph_stats(ugraph_stats_t *stats) {
stats->num_update_props = 0;
stats->num_lambda_props = 0;
stats->num_update_conflicts = 0;
stats->num_lambda_conflicts = 0;
}
static inline void reset_ugraph_stats(ugraph_stats_t *stats) {
init_ugraph_stats(stats);
}
/******************
* UPDATE GRAPH *
*****************/
/*
* Initialize ugraph (to the empty graph)
*/
void init_ugraph(update_graph_t *ugraph, egraph_t *egraph) {
ugraph->egraph = egraph;
ugraph->size = 0;
ugraph->nodes = 0;
ugraph->class = NULL;
ugraph->edges = NULL;
ugraph->tag = NULL;
ugraph->mark = NULL;
ugraph->nclasses = 0;
ugraph->class2node = NULL;
init_ugraph_queue(&ugraph->queue);
init_ugraph_partition(&ugraph->partition, egraph);
init_lpair_set(&ugraph->lpair_set, egraph->types);
init_ugraph_stats(&ugraph->stats);
init_ivector(&ugraph->aux_vector, 10);
init_ivector(&ugraph->lemma_vector, 10);
}
/*
* Make room for new nodes
*/
static void extend_ugraph_nodes(update_graph_t *ugraph) {
uint32_t n;
n = ugraph->size;
if (n == 0) {
// first allocation: use the default size
n = DEF_UGRAPH_SIZE;
assert(n <= MAX_UGRAPH_SIZE);
ugraph->class = (class_t *) safe_malloc(n * sizeof(class_t));
ugraph->edges = (void ***) safe_malloc(n * sizeof(void **));
ugraph->tag = (int32_t *) safe_malloc(n * sizeof(int32_t));
ugraph->mark = allocate_bitvector(n);
ugraph->size = n;
} else {
// increase the size by 50%
n += ((n + 1) >> 1);
if (n > MAX_UGRAPH_SIZE) {
out_of_memory();
}
ugraph->class = (class_t *) safe_realloc(ugraph->class, n * sizeof(class_t));
ugraph->edges = (void ***) safe_realloc(ugraph->edges, n * sizeof(void **));
ugraph->tag = (int32_t *) safe_realloc(ugraph->tag, n * sizeof(int32_t));
ugraph->mark = extend_bitvector(ugraph->mark, n);
ugraph->size = n;
}
}
/*
* Extend the class2node array to size large enough to store n classes
* - do nothing if the array is large enough already
* - extend the current array otherwise and initialize class2node[i] to -1 for all new i
*/
static void ugraph_resize_classes(update_graph_t *ugraph, uint32_t n) {
uint32_t i;
if (n >= ugraph->nclasses) {
if (n > MAX_UGRAPH_NCLASSES) {
out_of_memory();
}
ugraph->class2node = (int32_t *) safe_realloc(ugraph->class2node, n * sizeof(int32_t));
for (i= ugraph->nclasses; i<n; i++) {
ugraph->class2node[i] = -1;
}
ugraph->nclasses = n;
}
}
/*
* Add a new node to represent class c
* - tag = lambda tag for class c
* - return the node id
*/
static int32_t ugraph_add_node(update_graph_t *ugraph, class_t c, int32_t tag) {
uint32_t i;
i = ugraph->nodes;
if (i == ugraph->size) {
extend_ugraph_nodes(ugraph);
}
assert(i < ugraph->size);
ugraph->class[i] = c;
ugraph->edges[i] = NULL;
ugraph->tag[i] = tag;
clr_bit(ugraph->mark, i);
ugraph->nodes = i+1;
return i;
}
/*
* Reset to the empty graph
*/
void reset_ugraph(update_graph_t *ugraph) {
uint32_t i, n;
n = ugraph->nodes;
for (i=0; i<n; i++) {
reset_ptr_vector(ugraph->edges[i]);
}
ugraph->nodes = 0;
n = ugraph->nclasses;
for (i=0; i<n; i++) {
ugraph->class2node[i] = -1;
}
reset_ugraph_queue(&ugraph->queue);
reset_ptr_partition(&ugraph->partition);
reset_lpair_set(&ugraph->lpair_set);
reset_ugraph_stats(&ugraph->stats);
ivector_reset(&ugraph->aux_vector);
ivector_reset(&ugraph->lemma_vector);
}
/*
* Delete ugraph:
* - free all internal structures
*/
void delete_ugraph(update_graph_t *ugraph) {
uint32_t i, n;
n = ugraph->nodes;
for (i=0; i<n; i++) {
delete_ptr_vector(ugraph->edges[i]);
}
safe_free(ugraph->class);
safe_free(ugraph->edges);
safe_free(ugraph->tag);
delete_bitvector(ugraph->mark);
safe_free(ugraph->class2node);
ugraph->class = NULL;
ugraph->edges = NULL;
ugraph->tag = NULL;
ugraph->mark = NULL;
ugraph->class2node = NULL;
delete_ugraph_queue(&ugraph->queue);
delete_ptr_partition(&ugraph->partition);
delete_lpair_set(&ugraph->lpair_set);
delete_ivector(&ugraph->aux_vector);
delete_ivector(&ugraph->lemma_vector);
}
/*
* Get the node if for class c
*/
static inline int32_t node_of_class(update_graph_t *ugraph, class_t c) {
assert(0 <= c && c < ugraph->nclasses);
return ugraph->class2node[c];
}
/*
* Store i as the node id for class c
*/
static inline void set_node_of_class(update_graph_t *ugraph, class_t c, int32_t i) {
assert(0 <= c && c < ugraph->nclasses && 0 <= i && i < ugraph->nodes && ugraph->class2node[c] < 0);
ugraph->class2node[c] = i;
}
/*
* Add a term t to the update graph
* - c = class of t
* - tau = type of t
* - create a new node for c if there's not one already
*/
static void ugraph_add_term(update_graph_t *ugraph, eterm_t t, class_t c, type_t tau) {
int32_t node;
int32_t tag;
node = node_of_class(ugraph, c);
if (node < 0) {
tag = egraph_get_lambda_tag(ugraph->egraph, tau);
node = ugraph_add_node(ugraph, c, tag);
set_node_of_class(ugraph, c, node);
// if t is a lambda term: store the pair [tag, sigma]
// where sigma = range of type tau
if (egraph_term_is_lambda(ugraph->egraph, t)) {
lpair_set_add_ftype(&ugraph->lpair_set, tag, tau);
}
}
}
/*
* Add cmp as a new edge from a to b
* - also add the reverse edge from b to a
* - the reverse edge is tagged with 01
*/
static void ugraph_add_edge(update_graph_t *ugraph, int32_t a, int32_t b, composite_t *cmp) {
assert(0 <= a && a < ugraph->nodes && 0 <= b && b < ugraph->nodes);
add_ptr_to_vector(ugraph->edges + a, cmp);
add_ptr_to_vector(ugraph->edges + b, tag_ptr(cmp, 1));
}
/*
* Get the node id for term t
*/
static inline int32_t node_of_term(update_graph_t *ugraph, eterm_t t) {
return node_of_class(ugraph, egraph_term_class(ugraph->egraph, t));
}
/*
* Add the two edges defined by update term cmp
*/
static void ugraph_add_edges_for_update(update_graph_t *ugraph, composite_t *cmp) {
int32_t source, target;
assert(composite_kind(cmp) == COMPOSITE_UPDATE);
source = node_of_term(ugraph, cmp->child[0]);
target = node_of_term(ugraph, cmp->id);
ugraph_add_edge(ugraph, source, target, cmp);
}
/*
* Build ugraph based on the current egraph partition
* - one node is created for each egraph class that has function type
* - for each update term b = (update a ... ) that's in the congruence
* table (congruence root), we create two edges:
* a direct edge from node[class[a]] to node[class[b]]
* a reverse edge from node[class[b]] to node[class[a]]
*/
void build_ugraph(update_graph_t *ugraph) {
egraph_t *egraph;
uint32_t i, n;
type_t tau;
composite_t *cmp;
assert(ugraph->nodes == 0 &&
ptr_partition_is_empty(&ugraph->partition) &&
lpair_set_is_empty(&ugraph->lpair_set));
egraph = ugraph->egraph;
/*
* First pass: create the nodes and build the lpair_set
*/
ugraph_resize_classes(ugraph, egraph->classes.nclasses);
n = egraph->terms.nterms;
for (i=0; i<n; i++) {
tau = egraph_term_real_type(egraph, i);
if (is_function_type(egraph->types, tau)) {
ugraph_add_term(ugraph, i, egraph_term_class(egraph, i), tau);
}
}
/*
* Second pass: add the edges and build the apply term partition
*/
for (i=0; i<n; i++) {
cmp = egraph_term_body(egraph, i);
if (composite_body(cmp)) {
switch (composite_kind(cmp)) {
case COMPOSITE_APPLY:
// add cmp to the partition (if it's a congruence root)
if (congruence_table_is_root(&egraph->ctable, cmp, egraph->terms.label)) {
ptr_partition_add(&ugraph->partition, cmp);
}
break;
case COMPOSITE_UPDATE:
// add cmp as an edge (it it's a congruence root)
if (congruence_table_is_root(&egraph->ctable, cmp, egraph->terms.label)) {
ugraph_add_edges_for_update(ugraph, cmp);
}
break;
default:
break;
}
}
}
}
/*************************************
* PROPAGATION IN THE UPDATE GRAPH *
************************************/
/*
* Given an edge u = (update _ x1 ... xn _) and a term a = (apply _ t1 ... tn)
* - the edge is opaque for a if t1 == x1 and .... and tn == xn.
* - the edge is transparent if the disequality ti /= xi holds in the Egraph
* for some index i
*
* Propagation through update chains
* ---------------------------------
* If we have two terms a = (apply f t1 ... t_n) and b = (apply g u1 ... u_n),
* such that t1 == u1 .... tn == un, and there's a path from
* node(f) to node(g) that's transparent for a, then we can deduce
* that a and b must be equal (by the array update axioms).
*
* If we have terms a = (apply f t1 ... tn) and g = (lambda ... b)
* and there's a path from node(f) to g that's transparent for a
* then we can deduce a = b.
*
* Final check
* -----------
* We generate instances of the update axiom by searching for
* terms a = (apply f t1 ... tn) and b = (apply g u1 ... u_n)
* such that:
* 1) t1 == u1 ... t_n == u_n
* 2) a and b are in distinct egraph classes
* 3) there's a path from node(f) to node(g) that contains no edge
* opaque for a
*
* For g = (lambda .. b ..), we add an instance of path => (apply f t1 ... tn) = b
* if there's a path from node(f) to node(g) that doesn't contain an edge
* opaque to a.
*/
static bool opaque_edge(egraph_t *egraph, composite_t *u, composite_t *a) {
uint32_t i, n;
assert(composite_kind(u) == COMPOSITE_UPDATE && composite_kind(a) == COMPOSITE_APPLY);
n = composite_arity(a);
assert(composite_arity(u) == n+1);
for (i=1; i<n; i++) {
if (! egraph_check_eq(egraph, a->child[i], u->child[i])) {
return false;
}
}
return true;
}
static bool transparent_edge(egraph_t *egraph, composite_t *u, composite_t *a) {
uint32_t i, n;
assert(composite_kind(u) == COMPOSITE_UPDATE && composite_kind(a) == COMPOSITE_APPLY);
n = composite_arity(a);
assert(composite_arity(u) == n+1);
for (i=1; i<n; i++) {
if (egraph_check_diseq(egraph, a->child[i], u->child[i])) {
return true;
}
}
return false;
}
/*
* Check whether c is relevant to propagation
* - c is relevant if there's another term d such that the arguments of c and d are equal
* or if there's a lambda term that has a type compatible with c
* - for the first part, we check whether c's class in the partition table contains
* at least two elements
*
* We could do more:
* - if c and d are in the same class in the partition table
* then there's no path from c to d if they have incompatible types
* - if c and d are already equal in the egraph, then we don't care
* whether a path exists
*/
// x must be the node of c->child[0]
static bool compatible_lambda(update_graph_t *ugraph, int32_t x, composite_t *c) {
type_t tau;
assert(composite_kind(c) == COMPOSITE_APPLY && 0 <= x && x < ugraph->nodes);
tau = egraph_term_real_type(ugraph->egraph, c->id); // c has type tau
return lpair_set_has_match(&ugraph->lpair_set, ugraph->tag[x], tau);
}
// x must be the node of c->child[0]
static bool relevant_apply(update_graph_t *ugraph, int32_t x, composite_t *c) {
int32_t k;
k = ptr_partition_get_index(&ugraph->partition, c);
return k>=0 || compatible_lambda(ugraph, x, c);
}
/*
* Return a term whose signature matches [ label[y], label[i_1], ..., label[i_n] ]
* - y = node in the update graph
* - c = composite of the form (apply f i_1 ... i_n)
*/
static composite_t *find_modified_application(update_graph_t *ugraph, int32_t y, composite_t *c) {
egraph_t *egraph;
signature_t *sgn;
elabel_t *label;
assert(composite_kind(c) == COMPOSITE_APPLY);
assert(0 <= y && y < ugraph->nodes);
egraph = ugraph->egraph;
label = egraph->terms.label;
sgn = &egraph->sgn;
signature_modified_apply2(c, pos_label(ugraph->class[y]), label, sgn);
return congruence_table_find(&egraph->ctable, sgn, label);
}
/*
* Return the lambda term in node y
* - return NULL if there's no lambda term in this node
*
* TODO: for this to work, we must change egraph.c so that the theory
* variable attached to a function class is the representative lambda
* term for that class.
*/
static composite_t *find_lambda_term(update_graph_t *ugraph, int32_t y) {
egraph_t *egraph;
composite_t *d;
class_t c;
eterm_t lambda;
assert(0 <= y && y < ugraph->nodes);
egraph= ugraph->egraph;
d = NULL;
c = ugraph->class[y];
assert(egraph_class_is_function(egraph, c));
lambda = egraph_class_thvar(egraph, c);
if (lambda >= 0) {
// lambda is an egraph term
d = egraph_term_body(egraph, lambda);
assert(composite_body(d) && composite_kind(d) == COMPOSITE_LAMBDA);
}
return d;
}
/*
* For debugging: check that no node is marked
*/
#ifndef NDEBUG
static bool no_node_is_marked(update_graph_t *ugraph) {
uint32_t i, n;
n = ugraph->nodes;
for (i=0; i<n; i++) {
if (ugraph_node_is_marked(ugraph, i)) {
return false;
}
}
return true;
}
#endif
/*
* Empty the queue and remove the mark of all nodes in the queue
*/
static void ugraph_unmark_queued_nodes(update_graph_t *ugraph, ugraph_queue_t *queue) {
uint32_t i, n;
int32_t x;
n = queue->top;
for (i=0; i<n; i++) {
x = queue->data[i].node;
assert(ugraph_node_is_marked(ugraph, x));
clear_ugraph_node_mark(ugraph, x);
}
reset_ugraph_queue(queue);
assert(no_node_is_marked(ugraph));
}
/*
* BASE-LEVEL PROPAGATION
*/
/*
* Push all unmarked successors of x that can be reached by an edge transparent to c
* into queue
*/
static void ugraph_push_transparent_successors(update_graph_t *ugraph, ugraph_queue_t *queue, int32_t x, composite_t *c) {
void **edges;
composite_t *u;
uint32_t i, n;
int32_t y;
assert(0 <= x && x < ugraph->nodes);
edges = ugraph->edges[x];
if (edges != NULL) {
n = pv_size(edges);
for (i=0; i<n; i++) {
u = edges[i];
if (ptr_tag(u) == 0) {
// direct edge of the form g := (update f ...) for f in class[x]
y = node_of_term(ugraph, u->id);
} else {
// reverse edge: f := (update g ...) for f in class[x]
u = untag_ptr(u);
y = node_of_term(ugraph, term_of_occ(u->child[0]));
}
assert(0 <= y && y < ugraph->nodes);
if (ugraph_node_is_unmarked(ugraph, y) && transparent_edge(ugraph->egraph, u, c)) {
ugraph_queue_push_next(queue, y, u); // u is not used here
}
}
}
}
/*
* Propagation through transparent edges
* - propagate c through all transparent edges from node x
* - c must be of the form (apply f t_1 ... t_n)
* - x should be the node for class of f
*
* Whenever we find a term d = (apply g t_1 ... t_n) then
* we add the constraint d == c to the egraph (as a toplevel axiom).
* - return the number of equalities propagated
*/
static uint32_t ugraph_base_propagate_application(update_graph_t *ugraph, int32_t x, composite_t *c) {
ugraph_queue_t *queue;
composite_t *d;
uint32_t neqs;
int32_t y;
queue = &ugraph->queue;
assert(empty_ugraph_queue(queue) && no_node_is_marked(ugraph));
neqs = 0;
ugraph_queue_push_root(queue, x);
ugraph_mark_node(ugraph, x);
ugraph_push_transparent_successors(ugraph, queue, x, c);
ugraph_queue_pop(queue);
while (! empty_ugraph_queue(queue)) {
y = ugraph_queue_current_node(queue);
d = find_modified_application(ugraph, y, c);
if (d != NULL) {
if (! egraph_equal_occ(ugraph->egraph, pos_occ(c->id), pos_occ(d->id))) {
egraph_assert_eq_axiom(ugraph->egraph, pos_occ(c->id), pos_occ(d->id));
ugraph->stats.num_update_props ++;
neqs ++;
}
/*
* If d and c are equal, there's no point propagating c to y's neighbors
* (the propagations we miss now were or will be done when we propagate d) .
*/
} else {
d = find_lambda_term(ugraph, y);
if (d != NULL && !egraph_equal_occ(ugraph->egraph, pos_occ(c->id), d->child[0])) {
egraph_assert_eq_axiom(ugraph->egraph, pos_occ(c->id), d->child[0]);
ugraph->stats.num_lambda_props ++;
neqs ++;
}
ugraph_push_transparent_successors(ugraph, queue, y, c);
ugraph_queue_pop(queue);
}
}
ugraph_unmark_queued_nodes(ugraph, queue);
return neqs;
}
/*
* Full propagation at the base level
* - go through all relevant composite and propagate
* - return the total number of propagated equalities
*/
uint32_t ugraph_base_propagate(update_graph_t *ugraph) {
egraph_t *egraph;
composite_t *c;
uint32_t i, n, neqs;
int32_t x;
neqs = 0;
egraph = ugraph->egraph;
n = egraph->terms.nterms;
for (i=0; i<n; i++) {
c = egraph_term_body(egraph, i);
if (composite_body(c) &&
composite_kind(c) == COMPOSITE_APPLY &&
congruence_table_is_root(&egraph->ctable, c, egraph->terms.label)) {
// c is of the form (apply f ... ) is a congruence root
x = node_of_term(ugraph, term_of_occ(c->child[0])); // x := node of f
if (relevant_apply(ugraph, x, c)) {
neqs += ugraph_base_propagate_application(ugraph, x, c);
}
}
}
return neqs;
}
/*
* SEARCH FOR INSTANCES OF UPDATE/LAMBDA AXIOMS
*/
/*
* Push all unmarked successors of x that can be reached by a non-opaque edge for c
*/
static void ugraph_push_successors(update_graph_t *ugraph, ugraph_queue_t *queue, int32_t x, composite_t *c) {
void **edges;
composite_t *u, *v;
uint32_t i, n;
int32_t y;
assert(0 <= x && x < ugraph->nodes);
edges = ugraph->edges[x];
if (edges != NULL) {
n = pv_size(edges);
for (i=0; i<n; i++) {
u = edges[i];
v = untag_ptr(u);
if (ptr_tag(u) == 0) {
// direct edge of the form g := (update f ...) for f in class[x]
y = node_of_term(ugraph, u->id);
} else {
// reverse edge: f := (update g ...) for f in class[x]
y = node_of_term(ugraph, term_of_occ(u->child[0]));
}
assert(0 <= y && y < ugraph->nodes);
if (ugraph_node_is_unmarked(ugraph, y) && !opaque_edge(ugraph->egraph, v, c)) {
ugraph_queue_push_next(queue, y, u);
}
}
}
}
/*
* Propagate c through non-opaque edges and search for instances
* the update/lambda axioms.
* - c must be of the form (apply f t_1 ... t_n)
* - x should be the node for class of f
*/
static uint32_t ugraph_propagate_application(update_graph_t *ugraph, int32_t x, composite_t *c) {
ugraph_queue_t *queue;
composite_t *d;
uint32_t nlemmas;
int32_t y;
queue = &ugraph->queue;
assert(empty_ugraph_queue(queue) && no_node_is_marked(ugraph));
nlemmas = 0;
ugraph_queue_push_root(queue, x);
ugraph_mark_node(ugraph, x);
ugraph_push_successors(ugraph, queue, x, c);
ugraph_queue_pop(queue);
while (! empty_ugraph_queue(queue)) {
y = ugraph_queue_current_node(queue);
d = find_modified_application(ugraph, y, c);
if (d != NULL) {
if (! egraph_equal_occ(ugraph->egraph, pos_occ(c->id), pos_occ(d->id))) {
// found instance of the update axiom
// TBD
nlemmas ++;
}
} else {
d = find_lambda_term(ugraph, y);;
if (d != NULL && !egraph_equal_occ(ugraph->egraph, pos_occ(c->id), d->child[0])) {
// found instance of the lambda/update axiom
// TBD
nlemmas ++;
}
ugraph_push_successors(ugraph, queue, y, c);
ugraph_queue_pop(queue);;
}
}
ugraph_unmark_queued_nodes(ugraph, queue);
return nlemmas;
}
/*
* Full propagation
*/
uint32_t ugraph_propagate(update_graph_t *ugraph) {
egraph_t *egraph;
composite_t *c;
uint32_t i, n, nlemmas;
int32_t x;
nlemmas = 0;
egraph = ugraph->egraph;
n = egraph->terms.nterms;
for (i=0; i<n; i++) {
c = egraph_term_body(egraph, i);
if (composite_body(c) &&
composite_kind(c) == COMPOSITE_APPLY &&
congruence_table_is_root(&egraph->ctable, c, egraph->terms.label)) {
// c is of the form (apply f ... ) and is a congruence root
x = node_of_term(ugraph, term_of_occ(c->child[0])); // x := node of f
if (relevant_apply(ugraph, x, c)) {
nlemmas += ugraph_propagate_application(ugraph, x, c);
}
}
}
return nlemmas;
}
| maelvalais/ocamlyices2 | ext/yices/src/scratch/update_graph.c | C | isc | 27,220 |
/*-
* Copyright (c) 1991 Keith Muller.
* Copyright (c) 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Keith Muller of the University of California, San Diego.
*
* 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
*/
#if 0
#ifndef lint
static char sccsid[] = "@(#)egetopt.c 8.1 (Berkeley) 6/6/93";
#endif /* not lint */
#endif
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include "extern.h"
/*
* egetopt: get option letter from argument vector (an extended
* version of getopt).
*
* Non standard additions to the ostr specs are:
* 1) '?': immediate value following arg is optional (no white space
* between the arg and the value)
* 2) '#': +/- followed by a number (with an optional sign but
* no white space between the arg and the number). The - may be
* combined with other options, but the + cannot.
*/
int eopterr = 1; /* if error message should be printed */
int eoptind = 1; /* index into parent argv vector */
int eoptopt; /* character checked for validity */
char *eoptarg; /* argument associated with option */
#define BADCH (int)'?'
static char emsg[] = "";
int
egetopt(int nargc, char * const *nargv, const char *ostr)
{
static char *place = emsg; /* option letter processing */
char *oli; /* option letter list index */
static int delim; /* which option delimiter */
char *p;
static char savec = '\0';
if (savec != '\0') {
*place = savec;
savec = '\0';
}
if (!*place) {
/*
* update scanning pointer
*/
if ((eoptind >= nargc) ||
((*(place = nargv[eoptind]) != '-') && (*place != '+'))) {
place = emsg;
return (-1);
}
delim = (int)*place;
if (place[1] && *++place == '-' && !place[1]) {
/*
* found "--"
*/
++eoptind;
place = emsg;
return (-1);
}
}
/*
* check option letter
*/
if ((eoptopt = (int)*place++) == (int)':' || (eoptopt == (int)'?') ||
!(oli = strchr(ostr, eoptopt))) {
/*
* if the user didn't specify '-' as an option,
* assume it means -1 when by itself.
*/
if ((eoptopt == (int)'-') && !*place)
return (-1);
if (strchr(ostr, '#') && (isdigit(eoptopt) ||
(((eoptopt == (int)'-') || (eoptopt == (int)'+')) &&
isdigit(*place)))) {
/*
* # option: +/- with a number is ok
*/
for (p = place; *p != '\0'; ++p) {
if (!isdigit(*p))
break;
}
eoptarg = place-1;
if (*p == '\0') {
place = emsg;
++eoptind;
} else {
place = p;
savec = *p;
*place = '\0';
}
return (delim);
}
if (!*place)
++eoptind;
if (eopterr) {
if (!(p = strrchr(*nargv, '/')))
p = *nargv;
else
++p;
(void)fprintf(stderr, "%s: illegal option -- %c\n",
p, eoptopt);
}
return (BADCH);
}
if (delim == (int)'+') {
/*
* '+' is only allowed with numbers
*/
if (!*place)
++eoptind;
if (eopterr) {
if (!(p = strrchr(*nargv, '/')))
p = *nargv;
else
++p;
(void)fprintf(stderr,
"%s: illegal '+' delimiter with option -- %c\n",
p, eoptopt);
}
return (BADCH);
}
++oli;
if ((*oli != ':') && (*oli != '?')) {
/*
* don't need argument
*/
eoptarg = NULL;
if (!*place)
++eoptind;
return (eoptopt);
}
if (*place) {
/*
* no white space
*/
eoptarg = place;
} else if (*oli == '?') {
/*
* no arg, but NOT required
*/
eoptarg = NULL;
} else if (nargc <= ++eoptind) {
/*
* no arg, but IS required
*/
place = emsg;
if (eopterr) {
if (!(p = strrchr(*nargv, '/')))
p = *nargv;
else
++p;
(void)fprintf(stderr,
"%s: option requires an argument -- %c\n", p,
eoptopt);
}
return (BADCH);
} else {
/*
* arg has white space
*/
eoptarg = nargv[eoptind];
}
place = emsg;
++eoptind;
return (eoptopt);
}
| TigerBSD/TigerBSD | FreeBSD/usr.bin/pr/egetopt.c | C | isc | 5,577 |
//===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is a utility pass used for testing the InstructionSimplify analysis.
// The analysis is applied to every instruction, and if it simplifies then the
// instruction is replaced by the simplification. If you are looking for a pass
// that performs serious instruction folding, use the instcombine pass instead.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Transforms/Utils/BuildLibCalls.h"
#include "llvm/Transforms/Utils/Local.h"
using namespace llvm;
using namespace PatternMatch;
static cl::opt<bool>
ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
cl::desc("Treat error-reporting calls as cold"));
static cl::opt<bool>
EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
cl::init(false),
cl::desc("Enable unsafe double to float "
"shrinking for math lib calls"));
//===----------------------------------------------------------------------===//
// Helper Functions
//===----------------------------------------------------------------------===//
static bool ignoreCallingConv(LibFunc::Func Func) {
return Func == LibFunc::abs || Func == LibFunc::labs ||
Func == LibFunc::llabs || Func == LibFunc::strlen;
}
/// Return true if it only matters that the value is equal or not-equal to zero.
static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
for (User *U : V->users()) {
if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
if (IC->isEquality())
if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
if (C->isNullValue())
continue;
// Unknown instruction.
return false;
}
return true;
}
/// Return true if it is only used in equality comparisons with With.
static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
for (User *U : V->users()) {
if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
if (IC->isEquality() && IC->getOperand(1) == With)
continue;
// Unknown instruction.
return false;
}
return true;
}
static bool callHasFloatingPointArgument(const CallInst *CI) {
return std::any_of(CI->op_begin(), CI->op_end(), [](const Use &OI) {
return OI->getType()->isFloatingPointTy();
});
}
/// \brief Check whether the overloaded unary floating point function
/// corresponding to \a Ty is available.
static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
LibFunc::Func LongDoubleFn) {
switch (Ty->getTypeID()) {
case Type::FloatTyID:
return TLI->has(FloatFn);
case Type::DoubleTyID:
return TLI->has(DoubleFn);
default:
return TLI->has(LongDoubleFn);
}
}
/// \brief Check whether we can use unsafe floating point math for
/// the function passed as input.
static bool canUseUnsafeFPMath(Function *F) {
// FIXME: For finer-grain optimization, we need intrinsics to have the same
// fast-math flag decorations that are applied to FP instructions. For now,
// we have to rely on the function-level unsafe-fp-math attribute to do this
// optimization because there's no other way to express that the call can be
// relaxed.
if (F->hasFnAttribute("unsafe-fp-math")) {
Attribute Attr = F->getFnAttribute("unsafe-fp-math");
if (Attr.getValueAsString() == "true")
return true;
}
return false;
}
/// \brief Returns whether \p F matches the signature expected for the
/// string/memory copying library function \p Func.
/// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
/// Their fortified (_chk) counterparts are also accepted.
static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
const DataLayout &DL = F->getParent()->getDataLayout();
FunctionType *FT = F->getFunctionType();
LLVMContext &Context = F->getContext();
Type *PCharTy = Type::getInt8PtrTy(Context);
Type *SizeTTy = DL.getIntPtrType(Context);
unsigned NumParams = FT->getNumParams();
// All string libfuncs return the same type as the first parameter.
if (FT->getReturnType() != FT->getParamType(0))
return false;
switch (Func) {
default:
llvm_unreachable("Can't check signature for non-string-copy libfunc.");
case LibFunc::stpncpy_chk:
case LibFunc::strncpy_chk:
--NumParams; // fallthrough
case LibFunc::stpncpy:
case LibFunc::strncpy: {
if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
return false;
break;
}
case LibFunc::strcpy_chk:
case LibFunc::stpcpy_chk:
--NumParams; // fallthrough
case LibFunc::stpcpy:
case LibFunc::strcpy: {
if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
FT->getParamType(0) != PCharTy)
return false;
break;
}
case LibFunc::memmove_chk:
case LibFunc::memcpy_chk:
--NumParams; // fallthrough
case LibFunc::memmove:
case LibFunc::memcpy: {
if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
!FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
return false;
break;
}
case LibFunc::memset_chk:
--NumParams; // fallthrough
case LibFunc::memset: {
if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
!FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
return false;
break;
}
}
// If this is a fortified libcall, the last parameter is a size_t.
if (NumParams == FT->getNumParams() - 1)
return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
return true;
}
//===----------------------------------------------------------------------===//
// String and Memory Library Call Optimizations
//===----------------------------------------------------------------------===//
Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
// Verify the "strcat" function prototype.
FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 2||
FT->getReturnType() != B.getInt8PtrTy() ||
FT->getParamType(0) != FT->getReturnType() ||
FT->getParamType(1) != FT->getReturnType())
return nullptr;
// Extract some information from the instruction
Value *Dst = CI->getArgOperand(0);
Value *Src = CI->getArgOperand(1);
// See if we can get the length of the input string.
uint64_t Len = GetStringLength(Src);
if (Len == 0)
return nullptr;
--Len; // Unbias length.
// Handle the simple, do-nothing case: strcat(x, "") -> x
if (Len == 0)
return Dst;
return emitStrLenMemCpy(Src, Dst, Len, B);
}
Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
IRBuilder<> &B) {
// We need to find the end of the destination string. That's where the
// memory is to be moved to. We just generate a call to strlen.
Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
if (!DstLen)
return nullptr;
// Now that we have the destination's length, we must index into the
// destination's pointer to get the actual memcpy destination (end of
// the string .. we're concatenating).
Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
// We have enough information to now generate the memcpy call to do the
// concatenation for us. Make a memcpy to copy the nul byte with align = 1.
B.CreateMemCpy(CpyDst, Src,
ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
1);
return Dst;
}
Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
// Verify the "strncat" function prototype.
FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
FT->getParamType(0) != FT->getReturnType() ||
FT->getParamType(1) != FT->getReturnType() ||
!FT->getParamType(2)->isIntegerTy())
return nullptr;
// Extract some information from the instruction.
Value *Dst = CI->getArgOperand(0);
Value *Src = CI->getArgOperand(1);
uint64_t Len;
// We don't do anything if length is not constant.
if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
Len = LengthArg->getZExtValue();
else
return nullptr;
// See if we can get the length of the input string.
uint64_t SrcLen = GetStringLength(Src);
if (SrcLen == 0)
return nullptr;
--SrcLen; // Unbias length.
// Handle the simple, do-nothing cases:
// strncat(x, "", c) -> x
// strncat(x, c, 0) -> x
if (SrcLen == 0 || Len == 0)
return Dst;
// We don't optimize this case.
if (Len < SrcLen)
return nullptr;
// strncat(x, s, c) -> strcat(x, s)
// s is constant so the strcat can be optimized further.
return emitStrLenMemCpy(Src, Dst, SrcLen, B);
}
Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
// Verify the "strchr" function prototype.
FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
FT->getParamType(0) != FT->getReturnType() ||
!FT->getParamType(1)->isIntegerTy(32))
return nullptr;
Value *SrcStr = CI->getArgOperand(0);
// If the second operand is non-constant, see if we can compute the length
// of the input string and turn this into memchr.
ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
if (!CharC) {
uint64_t Len = GetStringLength(SrcStr);
if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
return nullptr;
return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
B, DL, TLI);
}
// Otherwise, the character is a constant, see if the first argument is
// a string literal. If so, we can constant fold.
StringRef Str;
if (!getConstantStringInfo(SrcStr, Str)) {
if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
return B.CreateGEP(B.getInt8Ty(), SrcStr, EmitStrLen(SrcStr, B, DL, TLI),
"strchr");
return nullptr;
}
// Compute the offset, make sure to handle the case when we're searching for
// zero (a weird way to spell strlen).
size_t I = (0xFF & CharC->getSExtValue()) == 0
? Str.size()
: Str.find(CharC->getSExtValue());
if (I == StringRef::npos) // Didn't find the char. strchr returns null.
return Constant::getNullValue(CI->getType());
// strchr(s+n,c) -> gep(s+n+i,c)
return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
}
Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
// Verify the "strrchr" function prototype.
FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
FT->getParamType(0) != FT->getReturnType() ||
!FT->getParamType(1)->isIntegerTy(32))
return nullptr;
Value *SrcStr = CI->getArgOperand(0);
ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
// Cannot fold anything if we're not looking for a constant.
if (!CharC)
return nullptr;
StringRef Str;
if (!getConstantStringInfo(SrcStr, Str)) {
// strrchr(s, 0) -> strchr(s, 0)
if (CharC->isZero())
return EmitStrChr(SrcStr, '\0', B, TLI);
return nullptr;
}
// Compute the offset.
size_t I = (0xFF & CharC->getSExtValue()) == 0
? Str.size()
: Str.rfind(CharC->getSExtValue());
if (I == StringRef::npos) // Didn't find the char. Return null.
return Constant::getNullValue(CI->getType());
// strrchr(s+n,c) -> gep(s+n+i,c)
return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
}
Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
// Verify the "strcmp" function prototype.
FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
FT->getParamType(0) != FT->getParamType(1) ||
FT->getParamType(0) != B.getInt8PtrTy())
return nullptr;
Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
if (Str1P == Str2P) // strcmp(x,x) -> 0
return ConstantInt::get(CI->getType(), 0);
StringRef Str1, Str2;
bool HasStr1 = getConstantStringInfo(Str1P, Str1);
bool HasStr2 = getConstantStringInfo(Str2P, Str2);
// strcmp(x, y) -> cnst (if both x and y are constant strings)
if (HasStr1 && HasStr2)
return ConstantInt::get(CI->getType(), Str1.compare(Str2));
if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
return B.CreateNeg(
B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
// strcmp(P, "x") -> memcmp(P, "x", 2)
uint64_t Len1 = GetStringLength(Str1P);
uint64_t Len2 = GetStringLength(Str2P);
if (Len1 && Len2) {
return EmitMemCmp(Str1P, Str2P,
ConstantInt::get(DL.getIntPtrType(CI->getContext()),
std::min(Len1, Len2)),
B, DL, TLI);
}
return nullptr;
}
Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
// Verify the "strncmp" function prototype.
FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
FT->getParamType(0) != FT->getParamType(1) ||
FT->getParamType(0) != B.getInt8PtrTy() ||
!FT->getParamType(2)->isIntegerTy())
return nullptr;
Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
if (Str1P == Str2P) // strncmp(x,x,n) -> 0
return ConstantInt::get(CI->getType(), 0);
// Get the length argument if it is constant.
uint64_t Length;
if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
Length = LengthArg->getZExtValue();
else
return nullptr;
if (Length == 0) // strncmp(x,y,0) -> 0
return ConstantInt::get(CI->getType(), 0);
if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
StringRef Str1, Str2;
bool HasStr1 = getConstantStringInfo(Str1P, Str1);
bool HasStr2 = getConstantStringInfo(Str2P, Str2);
// strncmp(x, y) -> cnst (if both x and y are constant strings)
if (HasStr1 && HasStr2) {
StringRef SubStr1 = Str1.substr(0, Length);
StringRef SubStr2 = Str2.substr(0, Length);
return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
}
if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
return B.CreateNeg(
B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
return nullptr;
}
Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
return nullptr;
Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
if (Dst == Src) // strcpy(x,x) -> x
return Src;
// See if we can get the length of the input string.
uint64_t Len = GetStringLength(Src);
if (Len == 0)
return nullptr;
// We have enough information to now generate the memcpy call to do the
// copy for us. Make a memcpy to copy the nul byte with align = 1.
B.CreateMemCpy(Dst, Src,
ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
return Dst;
}
Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
return nullptr;
Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Value *StrLen = EmitStrLen(Src, B, DL, TLI);
return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
}
// See if we can get the length of the input string.
uint64_t Len = GetStringLength(Src);
if (Len == 0)
return nullptr;
Type *PT = Callee->getFunctionType()->getParamType(0);
Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
// We have enough information to now generate the memcpy call to do the
// copy for us. Make a memcpy to copy the nul byte with align = 1.
B.CreateMemCpy(Dst, Src, LenV, 1);
return DstEnd;
}
Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
return nullptr;
Value *Dst = CI->getArgOperand(0);
Value *Src = CI->getArgOperand(1);
Value *LenOp = CI->getArgOperand(2);
// See if we can get the length of the input string.
uint64_t SrcLen = GetStringLength(Src);
if (SrcLen == 0)
return nullptr;
--SrcLen;
if (SrcLen == 0) {
// strncpy(x, "", y) -> memset(x, '\0', y, 1)
B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
return Dst;
}
uint64_t Len;
if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
Len = LengthArg->getZExtValue();
else
return nullptr;
if (Len == 0)
return Dst; // strncpy(x, y, 0) -> x
// Let strncpy handle the zero padding
if (Len > SrcLen + 1)
return nullptr;
Type *PT = Callee->getFunctionType()->getParamType(0);
// strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
return Dst;
}
Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
!FT->getReturnType()->isIntegerTy())
return nullptr;
Value *Src = CI->getArgOperand(0);
// Constant folding: strlen("xyz") -> 3
if (uint64_t Len = GetStringLength(Src))
return ConstantInt::get(CI->getType(), Len - 1);
// strlen(x?"foo":"bars") --> x ? 3 : 4
if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
uint64_t LenTrue = GetStringLength(SI->getTrueValue());
uint64_t LenFalse = GetStringLength(SI->getFalseValue());
if (LenTrue && LenFalse) {
Function *Caller = CI->getParent()->getParent();
emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
SI->getDebugLoc(),
"folded strlen(select) to select of constants");
return B.CreateSelect(SI->getCondition(),
ConstantInt::get(CI->getType(), LenTrue - 1),
ConstantInt::get(CI->getType(), LenFalse - 1));
}
}
// strlen(x) != 0 --> *x != 0
// strlen(x) == 0 --> *x == 0
if (isOnlyUsedInZeroEqualityComparison(CI))
return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
return nullptr;
}
Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
FT->getParamType(1) != FT->getParamType(0) ||
FT->getReturnType() != FT->getParamType(0))
return nullptr;
StringRef S1, S2;
bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
// strpbrk(s, "") -> nullptr
// strpbrk("", s) -> nullptr
if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
return Constant::getNullValue(CI->getType());
// Constant folding.
if (HasS1 && HasS2) {
size_t I = S1.find_first_of(S2);
if (I == StringRef::npos) // No match.
return Constant::getNullValue(CI->getType());
return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
"strpbrk");
}
// strpbrk(s, "a") -> strchr(s, 'a')
if (HasS2 && S2.size() == 1)
return EmitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
return nullptr;
}
Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
FunctionType *FT = Callee->getFunctionType();
if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
!FT->getParamType(0)->isPointerTy() ||
!FT->getParamType(1)->isPointerTy())
return nullptr;
Value *EndPtr = CI->getArgOperand(1);
if (isa<ConstantPointerNull>(EndPtr)) {
// With a null EndPtr, this function won't capture the main argument.
// It would be readonly too, except that it still may write to errno.
CI->addAttribute(1, Attribute::NoCapture);
}
return nullptr;
}
Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
FT->getParamType(1) != FT->getParamType(0) ||
!FT->getReturnType()->isIntegerTy())
return nullptr;
StringRef S1, S2;
bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
// strspn(s, "") -> 0
// strspn("", s) -> 0
if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
return Constant::getNullValue(CI->getType());
// Constant folding.
if (HasS1 && HasS2) {
size_t Pos = S1.find_first_not_of(S2);
if (Pos == StringRef::npos)
Pos = S1.size();
return ConstantInt::get(CI->getType(), Pos);
}
return nullptr;
}
Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
FT->getParamType(1) != FT->getParamType(0) ||
!FT->getReturnType()->isIntegerTy())
return nullptr;
StringRef S1, S2;
bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
// strcspn("", s) -> 0
if (HasS1 && S1.empty())
return Constant::getNullValue(CI->getType());
// Constant folding.
if (HasS1 && HasS2) {
size_t Pos = S1.find_first_of(S2);
if (Pos == StringRef::npos)
Pos = S1.size();
return ConstantInt::get(CI->getType(), Pos);
}
// strcspn(s, "") -> strlen(s)
if (HasS2 && S2.empty())
return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
return nullptr;
}
Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
!FT->getParamType(1)->isPointerTy() ||
!FT->getReturnType()->isPointerTy())
return nullptr;
// fold strstr(x, x) -> x.
if (CI->getArgOperand(0) == CI->getArgOperand(1))
return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
// fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
if (!StrLen)
return nullptr;
Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
StrLen, B, DL, TLI);
if (!StrNCmp)
return nullptr;
for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
ICmpInst *Old = cast<ICmpInst>(*UI++);
Value *Cmp =
B.CreateICmp(Old->getPredicate(), StrNCmp,
ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
replaceAllUsesWith(Old, Cmp);
}
return CI;
}
// See if either input string is a constant string.
StringRef SearchStr, ToFindStr;
bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
// fold strstr(x, "") -> x.
if (HasStr2 && ToFindStr.empty())
return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
// If both strings are known, constant fold it.
if (HasStr1 && HasStr2) {
size_t Offset = SearchStr.find(ToFindStr);
if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
return Constant::getNullValue(CI->getType());
// strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Value *Result = CastToCStr(CI->getArgOperand(0), B);
Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
return B.CreateBitCast(Result, CI->getType());
}
// fold strstr(x, "y") -> strchr(x, 'y').
if (HasStr2 && ToFindStr.size() == 1) {
Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
}
return nullptr;
}
Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
!FT->getParamType(1)->isIntegerTy(32) ||
!FT->getParamType(2)->isIntegerTy() ||
!FT->getReturnType()->isPointerTy())
return nullptr;
Value *SrcStr = CI->getArgOperand(0);
ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
// memchr(x, y, 0) -> null
if (LenC && LenC->isNullValue())
return Constant::getNullValue(CI->getType());
// From now on we need at least constant length and string.
StringRef Str;
if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
return nullptr;
// Truncate the string to LenC. If Str is smaller than LenC we will still only
// scan the string, as reading past the end of it is undefined and we can just
// return null if we don't find the char.
Str = Str.substr(0, LenC->getZExtValue());
// If the char is variable but the input str and length are not we can turn
// this memchr call into a simple bit field test. Of course this only works
// when the return value is only checked against null.
//
// It would be really nice to reuse switch lowering here but we can't change
// the CFG at this point.
//
// memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
// after bounds check.
if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
unsigned char Max =
*std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
reinterpret_cast<const unsigned char *>(Str.end()));
// Make sure the bit field we're about to create fits in a register on the
// target.
// FIXME: On a 64 bit architecture this prevents us from using the
// interesting range of alpha ascii chars. We could do better by emitting
// two bitfields or shifting the range by 64 if no lower chars are used.
if (!DL.fitsInLegalInteger(Max + 1))
return nullptr;
// For the bit field use a power-of-2 type with at least 8 bits to avoid
// creating unnecessary illegal types.
unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
// Now build the bit field.
APInt Bitfield(Width, 0);
for (char C : Str)
Bitfield.setBit((unsigned char)C);
Value *BitfieldC = B.getInt(Bitfield);
// First check that the bit field access is within bounds.
Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
"memchr.bounds");
// Create code that checks if the given bit is set in the field.
Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
// Finally merge both checks and cast to pointer type. The inttoptr
// implicitly zexts the i1 to intptr type.
return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
}
// Check if all arguments are constants. If so, we can constant fold.
if (!CharC)
return nullptr;
// Compute the offset.
size_t I = Str.find(CharC->getSExtValue() & 0xFF);
if (I == StringRef::npos) // Didn't find the char. memchr returns null.
return Constant::getNullValue(CI->getType());
// memchr(s+n,c,l) -> gep(s+n+i,c)
return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
}
Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
!FT->getParamType(1)->isPointerTy() ||
!FT->getReturnType()->isIntegerTy(32))
return nullptr;
Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
if (LHS == RHS) // memcmp(s,s,x) -> 0
return Constant::getNullValue(CI->getType());
// Make sure we have a constant length.
ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
if (!LenC)
return nullptr;
uint64_t Len = LenC->getZExtValue();
if (Len == 0) // memcmp(s1,s2,0) -> 0
return Constant::getNullValue(CI->getType());
// memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
if (Len == 1) {
Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
CI->getType(), "lhsv");
Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
CI->getType(), "rhsv");
return B.CreateSub(LHSV, RHSV, "chardiff");
}
// memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
Type *LHSPtrTy =
IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
Type *RHSPtrTy =
IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
Value *LHSV =
B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
Value *RHSV =
B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
}
}
// Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
StringRef LHSStr, RHSStr;
if (getConstantStringInfo(LHS, LHSStr) &&
getConstantStringInfo(RHS, RHSStr)) {
// Make sure we're not reading out-of-bounds memory.
if (Len > LHSStr.size() || Len > RHSStr.size())
return nullptr;
// Fold the memcmp and normalize the result. This way we get consistent
// results across multiple platforms.
uint64_t Ret = 0;
int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
if (Cmp < 0)
Ret = -1;
else if (Cmp > 0)
Ret = 1;
return ConstantInt::get(CI->getType(), Ret);
}
return nullptr;
}
Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
return nullptr;
// memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
CI->getArgOperand(2), 1);
return CI->getArgOperand(0);
}
Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
return nullptr;
// memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
CI->getArgOperand(2), 1);
return CI->getArgOperand(0);
}
Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
return nullptr;
// memset(p, v, n) -> llvm.memset(p, v, n, 1)
Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
return CI->getArgOperand(0);
}
//===----------------------------------------------------------------------===//
// Math Library Optimizations
//===----------------------------------------------------------------------===//
/// Return a variant of Val with float type.
/// Currently this works in two cases: If Val is an FPExtension of a float
/// value to something bigger, simply return the operand.
/// If Val is a ConstantFP but can be converted to a float ConstantFP without
/// loss of precision do so.
static Value *valueHasFloatPrecision(Value *Val) {
if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
Value *Op = Cast->getOperand(0);
if (Op->getType()->isFloatTy())
return Op;
}
if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
APFloat F = Const->getValueAPF();
bool losesInfo;
(void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
&losesInfo);
if (!losesInfo)
return ConstantFP::get(Const->getContext(), F);
}
return nullptr;
}
/// Any floating-point library function that we're trying to simplify will have
/// a signature of the form: fptype foo(fptype param1, fptype param2, ...).
/// CheckDoubleTy indicates that 'fptype' must be 'double'.
static bool matchesFPLibFunctionSignature(const Function *F, unsigned NumParams,
bool CheckDoubleTy) {
FunctionType *FT = F->getFunctionType();
if (FT->getNumParams() != NumParams)
return false;
// The return type must match what we're looking for.
Type *RetTy = FT->getReturnType();
if (CheckDoubleTy ? !RetTy->isDoubleTy() : !RetTy->isFloatingPointTy())
return false;
// Each parameter must match the return type, and therefore, match every other
// parameter too.
for (const Type *ParamTy : FT->params())
if (ParamTy != RetTy)
return false;
return true;
}
/// Shrink double -> float for unary functions like 'floor'.
static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
bool CheckRetType) {
Function *Callee = CI->getCalledFunction();
if (!matchesFPLibFunctionSignature(Callee, 1, true))
return nullptr;
if (CheckRetType) {
// Check if all the uses for function like 'sin' are converted to float.
for (User *U : CI->users()) {
FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
if (!Cast || !Cast->getType()->isFloatTy())
return nullptr;
}
}
// If this is something like 'floor((double)floatval)', convert to floorf.
Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
if (V == nullptr)
return nullptr;
// Propagate fast-math flags from the existing call to the new call.
IRBuilder<>::FastMathFlagGuard Guard(B);
B.setFastMathFlags(CI->getFastMathFlags());
// floor((double)floatval) -> (double)floorf(floatval)
if (Callee->isIntrinsic()) {
Module *M = CI->getModule();
Intrinsic::ID IID = Callee->getIntrinsicID();
Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
V = B.CreateCall(F, V);
} else {
// The call is a library call rather than an intrinsic.
V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
}
return B.CreateFPExt(V, B.getDoubleTy());
}
/// Shrink double -> float for binary functions like 'fmin/fmax'.
static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
if (!matchesFPLibFunctionSignature(Callee, 2, true))
return nullptr;
// If this is something like 'fmin((double)floatval1, (double)floatval2)',
// or fmin(1.0, (double)floatval), then we convert it to fminf.
Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
if (V1 == nullptr)
return nullptr;
Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
if (V2 == nullptr)
return nullptr;
// Propagate fast-math flags from the existing call to the new call.
IRBuilder<>::FastMathFlagGuard Guard(B);
B.setFastMathFlags(CI->getFastMathFlags());
// fmin((double)floatval1, (double)floatval2)
// -> (double)fminf(floatval1, floatval2)
// TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
Callee->getAttributes());
return B.CreateFPExt(V, B.getDoubleTy());
}
Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
Value *Ret = nullptr;
StringRef Name = Callee->getName();
if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Ret = optimizeUnaryDoubleFP(CI, B, true);
FunctionType *FT = Callee->getFunctionType();
// Just make sure this has 1 argument of FP type, which matches the
// result type.
if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
!FT->getParamType(0)->isFloatingPointTy())
return Ret;
// cos(-x) -> cos(x)
Value *Op1 = CI->getArgOperand(0);
if (BinaryOperator::isFNeg(Op1)) {
BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
}
return Ret;
}
static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
// Multiplications calculated using Addition Chains.
// Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
assert(Exp != 0 && "Incorrect exponent 0 not handled");
if (InnerChain[Exp])
return InnerChain[Exp];
static const unsigned AddChain[33][2] = {
{0, 0}, // Unused.
{0, 0}, // Unused (base case = pow1).
{1, 1}, // Unused (pre-computed).
{1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
{1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
{3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
{6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
{3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
};
InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
getPow(InnerChain, AddChain[Exp][1], B));
return InnerChain[Exp];
}
Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
Value *Ret = nullptr;
StringRef Name = Callee->getName();
if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Ret = optimizeUnaryDoubleFP(CI, B, true);
FunctionType *FT = Callee->getFunctionType();
// Just make sure this has 2 arguments of the same FP type, which match the
// result type.
if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
FT->getParamType(0) != FT->getParamType(1) ||
!FT->getParamType(0)->isFloatingPointTy())
return Ret;
Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
// pow(1.0, x) -> 1.0
if (Op1C->isExactlyValue(1.0))
return Op1C;
// pow(2.0, x) -> exp2(x)
if (Op1C->isExactlyValue(2.0) &&
hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
LibFunc::exp2l))
return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp2), B,
Callee->getAttributes());
// pow(10.0, x) -> exp10(x)
if (Op1C->isExactlyValue(10.0) &&
hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
LibFunc::exp10l))
return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
Callee->getAttributes());
}
// FIXME: Use instruction-level FMF.
bool UnsafeFPMath = canUseUnsafeFPMath(CI->getParent()->getParent());
// pow(exp(x), y) -> exp(x * y)
// pow(exp2(x), y) -> exp2(x * y)
// We enable these only with fast-math. Besides rounding differences, the
// transformation changes overflow and underflow behavior quite dramatically.
// Example: x = 1000, y = 0.001.
// pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
auto *OpC = dyn_cast<CallInst>(Op1);
if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
LibFunc::Func Func;
Function *OpCCallee = OpC->getCalledFunction();
if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
TLI->has(Func) && (Func == LibFunc::exp || Func == LibFunc::exp2)) {
IRBuilder<>::FastMathFlagGuard Guard(B);
B.setFastMathFlags(CI->getFastMathFlags());
Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
return EmitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
OpCCallee->getAttributes());
}
}
ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
if (!Op2C)
return Ret;
if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
return ConstantFP::get(CI->getType(), 1.0);
if (Op2C->isExactlyValue(0.5) &&
hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
LibFunc::sqrtl) &&
hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
LibFunc::fabsl)) {
// In -ffast-math, pow(x, 0.5) -> sqrt(x).
if (CI->hasUnsafeAlgebra()) {
IRBuilder<>::FastMathFlagGuard Guard(B);
B.setFastMathFlags(CI->getFastMathFlags());
return EmitUnaryFloatFnCall(Op1, TLI->getName(LibFunc::sqrt), B,
Callee->getAttributes());
}
// Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
// This is faster than calling pow, and still handles negative zero
// and negative infinity correctly.
// TODO: In finite-only mode, this could be just fabs(sqrt(x)).
Value *Inf = ConstantFP::getInfinity(CI->getType());
Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
Value *FAbs =
EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
return Sel;
}
if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
return Op1;
if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
return B.CreateFMul(Op1, Op1, "pow2");
if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
// In -ffast-math, generate repeated fmul instead of generating pow(x, n).
if (UnsafeFPMath) {
APFloat V = abs(Op2C->getValueAPF());
// We limit to a max of 7 fmul(s). Thus max exponent is 32.
// This transformation applies to integer exponents only.
if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
!V.isInteger())
return nullptr;
// We will memoize intermediate products of the Addition Chain.
Value *InnerChain[33] = {nullptr};
InnerChain[1] = Op1;
InnerChain[2] = B.CreateFMul(Op1, Op1);
// We cannot readily convert a non-double type (like float) to a double.
// So we first convert V to something which could be converted to double.
bool ignored;
V.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &ignored);
Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
// For negative exponents simply compute the reciprocal.
if (Op2C->isNegative())
FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
return FMul;
}
return nullptr;
}
Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
Function *Caller = CI->getParent()->getParent();
Value *Ret = nullptr;
StringRef Name = Callee->getName();
if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Ret = optimizeUnaryDoubleFP(CI, B, true);
FunctionType *FT = Callee->getFunctionType();
// Just make sure this has 1 argument of FP type, which matches the
// result type.
if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
!FT->getParamType(0)->isFloatingPointTy())
return Ret;
Value *Op = CI->getArgOperand(0);
// Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
// Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
LibFunc::Func LdExp = LibFunc::ldexpl;
if (Op->getType()->isFloatTy())
LdExp = LibFunc::ldexpf;
else if (Op->getType()->isDoubleTy())
LdExp = LibFunc::ldexp;
if (TLI->has(LdExp)) {
Value *LdExpArg = nullptr;
if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
} else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
}
if (LdExpArg) {
Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
if (!Op->getType()->isFloatTy())
One = ConstantExpr::getFPExtend(One, Op->getType());
Module *M = Caller->getParent();
Value *Callee =
M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Op->getType(), B.getInt32Ty(), nullptr);
CallInst *CI = B.CreateCall(Callee, {One, LdExpArg});
if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
CI->setCallingConv(F->getCallingConv());
return CI;
}
}
return Ret;
}
Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
Value *Ret = nullptr;
StringRef Name = Callee->getName();
if (Name == "fabs" && hasFloatVersion(Name))
Ret = optimizeUnaryDoubleFP(CI, B, false);
FunctionType *FT = Callee->getFunctionType();
// Make sure this has 1 argument of FP type which matches the result type.
if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
!FT->getParamType(0)->isFloatingPointTy())
return Ret;
Value *Op = CI->getArgOperand(0);
if (Instruction *I = dyn_cast<Instruction>(Op)) {
// Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
if (I->getOpcode() == Instruction::FMul)
if (I->getOperand(0) == I->getOperand(1))
return Op;
}
return Ret;
}
Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
// If we can shrink the call to a float function rather than a double
// function, do that first.
Function *Callee = CI->getCalledFunction();
StringRef Name = Callee->getName();
if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
return Ret;
// Make sure this has 2 arguments of FP type which match the result type.
FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
FT->getParamType(0) != FT->getParamType(1) ||
!FT->getParamType(0)->isFloatingPointTy())
return nullptr;
IRBuilder<>::FastMathFlagGuard Guard(B);
FastMathFlags FMF;
if (CI->hasUnsafeAlgebra()) {
// Unsafe algebra sets all fast-math-flags to true.
FMF.setUnsafeAlgebra();
} else {
// At a minimum, no-nans-fp-math must be true.
if (!CI->hasNoNaNs())
return nullptr;
// No-signed-zeros is implied by the definitions of fmax/fmin themselves:
// "Ideally, fmax would be sensitive to the sign of zero, for example
// fmax(-0. 0, +0. 0) would return +0; however, implementation in software
// might be impractical."
FMF.setNoSignedZeros();
FMF.setNoNaNs();
}
B.setFastMathFlags(FMF);
// We have a relaxed floating-point environment. We can ignore NaN-handling
// and transform to a compare and select. We do not have to consider errno or
// exceptions, because fmin/fmax do not have those.
Value *Op0 = CI->getArgOperand(0);
Value *Op1 = CI->getArgOperand(1);
Value *Cmp = Callee->getName().startswith("fmin") ?
B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
return B.CreateSelect(Cmp, Op0, Op1);
}
Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
Value *Ret = nullptr;
StringRef Name = Callee->getName();
if (UnsafeFPShrink && hasFloatVersion(Name))
Ret = optimizeUnaryDoubleFP(CI, B, true);
FunctionType *FT = Callee->getFunctionType();
// Just make sure this has 1 argument of FP type, which matches the
// result type.
if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
!FT->getParamType(0)->isFloatingPointTy())
return Ret;
if (!CI->hasUnsafeAlgebra())
return Ret;
Value *Op1 = CI->getArgOperand(0);
auto *OpC = dyn_cast<CallInst>(Op1);
// The earlier call must also be unsafe in order to do these transforms.
if (!OpC || !OpC->hasUnsafeAlgebra())
return Ret;
// log(pow(x,y)) -> y*log(x)
// This is only applicable to log, log2, log10.
if (Name != "log" && Name != "log2" && Name != "log10")
return Ret;
IRBuilder<>::FastMathFlagGuard Guard(B);
FastMathFlags FMF;
FMF.setUnsafeAlgebra();
B.setFastMathFlags(FMF);
LibFunc::Func Func;
Function *F = OpC->getCalledFunction();
if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
Func == LibFunc::pow) || F->getIntrinsicID() == Intrinsic::pow))
return B.CreateFMul(OpC->getArgOperand(1),
EmitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Callee->getAttributes()), "mul");
// log(exp2(y)) -> y*log(2)
if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
TLI->has(Func) && Func == LibFunc::exp2)
return B.CreateFMul(
OpC->getArgOperand(0),
EmitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Callee->getName(), B, Callee->getAttributes()),
"logmul");
return Ret;
}
Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
Value *Ret = nullptr;
if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
Callee->getIntrinsicID() == Intrinsic::sqrt))
Ret = optimizeUnaryDoubleFP(CI, B, true);
// FIXME: Refactor - this check is repeated all over this file and even in the
// preceding call to shrink double -> float.
// Make sure this has 1 argument of FP type, which matches the result type.
FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
!FT->getParamType(0)->isFloatingPointTy())
return Ret;
if (!CI->hasUnsafeAlgebra())
return Ret;
Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
return Ret;
// We're looking for a repeated factor in a multiplication tree,
// so we can do this fold: sqrt(x * x) -> fabs(x);
// or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Value *Op0 = I->getOperand(0);
Value *Op1 = I->getOperand(1);
Value *RepeatOp = nullptr;
Value *OtherOp = nullptr;
if (Op0 == Op1) {
// Simple match: the operands of the multiply are identical.
RepeatOp = Op0;
} else {
// Look for a more complicated pattern: one of the operands is itself
// a multiply, so search for a common factor in that multiply.
// Note: We don't bother looking any deeper than this first level or for
// variations of this pattern because instcombine's visitFMUL and/or the
// reassociation pass should give us this form.
Value *OtherMul0, *OtherMul1;
if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
// Pattern: sqrt((x * y) * z)
if (OtherMul0 == OtherMul1 &&
cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
// Matched: sqrt((x * x) * z)
RepeatOp = OtherMul0;
OtherOp = Op1;
}
}
}
if (!RepeatOp)
return Ret;
// Fast math flags for any created instructions should match the sqrt
// and multiply.
IRBuilder<>::FastMathFlagGuard Guard(B);
B.setFastMathFlags(I->getFastMathFlags());
// If we found a repeated factor, hoist it out of the square root and
// replace it with the fabs of that factor.
Module *M = Callee->getParent();
Type *ArgType = I->getType();
Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
if (OtherOp) {
// If we found a non-repeated factor, we still need to get its square
// root. We then multiply that by the value that was simplified out
// of the square root calculation.
Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
return B.CreateFMul(FabsCall, SqrtCall);
}
return FabsCall;
}
// TODO: Generalize to handle any trig function and its inverse.
Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
Value *Ret = nullptr;
StringRef Name = Callee->getName();
if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Ret = optimizeUnaryDoubleFP(CI, B, true);
FunctionType *FT = Callee->getFunctionType();
// Just make sure this has 1 argument of FP type, which matches the
// result type.
if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
!FT->getParamType(0)->isFloatingPointTy())
return Ret;
Value *Op1 = CI->getArgOperand(0);
auto *OpC = dyn_cast<CallInst>(Op1);
if (!OpC)
return Ret;
// Both calls must allow unsafe optimizations in order to remove them.
if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
return Ret;
// tan(atan(x)) -> x
// tanf(atanf(x)) -> x
// tanl(atanl(x)) -> x
LibFunc::Func Func;
Function *F = OpC->getCalledFunction();
if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
((Func == LibFunc::atan && Callee->getName() == "tan") ||
(Func == LibFunc::atanf && Callee->getName() == "tanf") ||
(Func == LibFunc::atanl && Callee->getName() == "tanl")))
Ret = OpC->getArgOperand(0);
return Ret;
}
static bool isTrigLibCall(CallInst *CI);
static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
bool UseFloat, Value *&Sin, Value *&Cos,
Value *&SinCos);
Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
// Make sure the prototype is as expected, otherwise the rest of the
// function is probably invalid and likely to abort.
if (!isTrigLibCall(CI))
return nullptr;
Value *Arg = CI->getArgOperand(0);
SmallVector<CallInst *, 1> SinCalls;
SmallVector<CallInst *, 1> CosCalls;
SmallVector<CallInst *, 1> SinCosCalls;
bool IsFloat = Arg->getType()->isFloatTy();
// Look for all compatible sinpi, cospi and sincospi calls with the same
// argument. If there are enough (in some sense) we can make the
// substitution.
for (User *U : Arg->users())
classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
SinCosCalls);
// It's only worthwhile if both sinpi and cospi are actually used.
if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
return nullptr;
Value *Sin, *Cos, *SinCos;
insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
replaceTrigInsts(SinCalls, Sin);
replaceTrigInsts(CosCalls, Cos);
replaceTrigInsts(SinCosCalls, SinCos);
return nullptr;
}
static bool isTrigLibCall(CallInst *CI) {
Function *Callee = CI->getCalledFunction();
FunctionType *FT = Callee->getFunctionType();
// We can only hope to do anything useful if we can ignore things like errno
// and floating-point exceptions.
bool AttributesSafe =
CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
// Other than that we need float(float) or double(double)
return AttributesSafe && FT->getNumParams() == 1 &&
FT->getReturnType() == FT->getParamType(0) &&
(FT->getParamType(0)->isFloatTy() ||
FT->getParamType(0)->isDoubleTy());
}
void
LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
SmallVectorImpl<CallInst *> &SinCalls,
SmallVectorImpl<CallInst *> &CosCalls,
SmallVectorImpl<CallInst *> &SinCosCalls) {
CallInst *CI = dyn_cast<CallInst>(Val);
if (!CI)
return;
Function *Callee = CI->getCalledFunction();
LibFunc::Func Func;
if (!Callee || !TLI->getLibFunc(Callee->getName(), Func) || !TLI->has(Func) ||
!isTrigLibCall(CI))
return;
if (IsFloat) {
if (Func == LibFunc::sinpif)
SinCalls.push_back(CI);
else if (Func == LibFunc::cospif)
CosCalls.push_back(CI);
else if (Func == LibFunc::sincospif_stret)
SinCosCalls.push_back(CI);
} else {
if (Func == LibFunc::sinpi)
SinCalls.push_back(CI);
else if (Func == LibFunc::cospi)
CosCalls.push_back(CI);
else if (Func == LibFunc::sincospi_stret)
SinCosCalls.push_back(CI);
}
}
void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
Value *Res) {
for (CallInst *C : Calls)
replaceAllUsesWith(C, Res);
}
void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
Type *ArgTy = Arg->getType();
Type *ResTy;
StringRef Name;
Triple T(OrigCallee->getParent()->getTargetTriple());
if (UseFloat) {
Name = "__sincospif_stret";
assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
// x86_64 can't use {float, float} since that would be returned in both
// xmm0 and xmm1, which isn't what a real struct would do.
ResTy = T.getArch() == Triple::x86_64
? static_cast<Type *>(VectorType::get(ArgTy, 2))
: static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
} else {
Name = "__sincospi_stret";
ResTy = StructType::get(ArgTy, ArgTy, nullptr);
}
Module *M = OrigCallee->getParent();
Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
ResTy, ArgTy, nullptr);
if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
// If the argument is an instruction, it must dominate all uses so put our
// sincos call there.
B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
} else {
// Otherwise (e.g. for a constant) the beginning of the function is as
// good a place as any.
BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
B.SetInsertPoint(&EntryBB, EntryBB.begin());
}
SinCos = B.CreateCall(Callee, Arg, "sincospi");
if (SinCos->getType()->isStructTy()) {
Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
Cos = B.CreateExtractValue(SinCos, 1, "cospi");
} else {
Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
"sinpi");
Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
"cospi");
}
}
//===----------------------------------------------------------------------===//
// Integer Library Call Optimizations
//===----------------------------------------------------------------------===//
static bool checkIntUnaryReturnAndParam(Function *Callee) {
FunctionType *FT = Callee->getFunctionType();
return FT->getNumParams() == 1 && FT->getReturnType()->isIntegerTy(32) &&
FT->getParamType(0)->isIntegerTy();
}
Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
if (!checkIntUnaryReturnAndParam(Callee))
return nullptr;
Value *Op = CI->getArgOperand(0);
// Constant fold.
if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
if (CI->isZero()) // ffs(0) -> 0.
return B.getInt32(0);
// ffs(c) -> cttz(c)+1
return B.getInt32(CI->getValue().countTrailingZeros() + 1);
}
// ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Type *ArgType = Op->getType();
Value *F =
Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
V = B.CreateIntCast(V, B.getInt32Ty(), false);
Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
return B.CreateSelect(Cond, V, B.getInt32(0));
}
Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
FunctionType *FT = Callee->getFunctionType();
// We require integer(integer) where the types agree.
if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
FT->getParamType(0) != FT->getReturnType())
return nullptr;
// abs(x) -> x >s -1 ? x : -x
Value *Op = CI->getArgOperand(0);
Value *Pos =
B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
Value *Neg = B.CreateNeg(Op, "neg");
return B.CreateSelect(Pos, Op, Neg);
}
Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
return nullptr;
// isdigit(c) -> (c-'0') <u 10
Value *Op = CI->getArgOperand(0);
Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
return B.CreateZExt(Op, CI->getType());
}
Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
return nullptr;
// isascii(c) -> c <u 128
Value *Op = CI->getArgOperand(0);
Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
return B.CreateZExt(Op, CI->getType());
}
Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
return nullptr;
// toascii(c) -> c & 0x7f
return B.CreateAnd(CI->getArgOperand(0),
ConstantInt::get(CI->getType(), 0x7F));
}
//===----------------------------------------------------------------------===//
// Formatting and IO Library Call Optimizations
//===----------------------------------------------------------------------===//
static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
int StreamArg) {
// Error reporting calls should be cold, mark them as such.
// This applies even to non-builtin calls: it is only a hint and applies to
// functions that the frontend might not understand as builtins.
// This heuristic was suggested in:
// Improving Static Branch Prediction in a Compiler
// Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
// Proceedings of PACT'98, Oct. 1998, IEEE
Function *Callee = CI->getCalledFunction();
if (!CI->hasFnAttr(Attribute::Cold) &&
isReportingError(Callee, CI, StreamArg)) {
CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
}
return nullptr;
}
static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
if (!ColdErrorCalls || !Callee || !Callee->isDeclaration())
return false;
if (StreamArg < 0)
return true;
// These functions might be considered cold, but only if their stream
// argument is stderr.
if (StreamArg >= (int)CI->getNumArgOperands())
return false;
LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
if (!LI)
return false;
GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
if (!GV || !GV->isDeclaration())
return false;
return GV->getName() == "stderr";
}
Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
// Check for a fixed format string.
StringRef FormatStr;
if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
return nullptr;
// Empty format string -> noop.
if (FormatStr.empty()) // Tolerate printf's declared void.
return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
// Do not do any of the following transformations if the printf return value
// is used, in general the printf return value is not compatible with either
// putchar() or puts().
if (!CI->use_empty())
return nullptr;
// printf("x") -> putchar('x'), even for '%'.
if (FormatStr.size() == 1) {
Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
if (CI->use_empty() || !Res)
return Res;
return B.CreateIntCast(Res, CI->getType(), true);
}
// printf("foo\n") --> puts("foo")
if (FormatStr[FormatStr.size() - 1] == '\n' &&
FormatStr.find('%') == StringRef::npos) { // No format characters.
// Create a string literal with no \n on it. We expect the constant merge
// pass to be run after this pass, to merge duplicate strings.
FormatStr = FormatStr.drop_back();
Value *GV = B.CreateGlobalString(FormatStr, "str");
Value *NewCI = EmitPutS(GV, B, TLI);
return (CI->use_empty() || !NewCI)
? NewCI
: ConstantInt::get(CI->getType(), FormatStr.size() + 1);
}
// Optimize specific format strings.
// printf("%c", chr) --> putchar(chr)
if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
CI->getArgOperand(1)->getType()->isIntegerTy()) {
Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
if (CI->use_empty() || !Res)
return Res;
return B.CreateIntCast(Res, CI->getType(), true);
}
// printf("%s\n", str) --> puts(str)
if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
CI->getArgOperand(1)->getType()->isPointerTy()) {
return EmitPutS(CI->getArgOperand(1), B, TLI);
}
return nullptr;
}
Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
// Require one fixed pointer argument and an integer/void result.
FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
!(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
return nullptr;
if (Value *V = optimizePrintFString(CI, B)) {
return V;
}
// printf(format, ...) -> iprintf(format, ...) if no floating point
// arguments.
if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
Module *M = B.GetInsertBlock()->getParent()->getParent();
Constant *IPrintFFn =
M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
CallInst *New = cast<CallInst>(CI->clone());
New->setCalledFunction(IPrintFFn);
B.Insert(New);
return New;
}
return nullptr;
}
Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
// Check for a fixed format string.
StringRef FormatStr;
if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
return nullptr;
// If we just have a format string (nothing else crazy) transform it.
if (CI->getNumArgOperands() == 2) {
// Make sure there's no % in the constant array. We could try to handle
// %% -> % in the future if we cared.
for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
if (FormatStr[i] == '%')
return nullptr; // we found a format specifier, bail out.
// sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
ConstantInt::get(DL.getIntPtrType(CI->getContext()),
FormatStr.size() + 1),
1); // Copy the null byte.
return ConstantInt::get(CI->getType(), FormatStr.size());
}
// The remaining optimizations require the format string to be "%s" or "%c"
// and have an extra operand.
if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
CI->getNumArgOperands() < 3)
return nullptr;
// Decode the second character of the format string.
if (FormatStr[1] == 'c') {
// sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
if (!CI->getArgOperand(2)->getType()->isIntegerTy())
return nullptr;
Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
B.CreateStore(V, Ptr);
Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
B.CreateStore(B.getInt8(0), Ptr);
return ConstantInt::get(CI->getType(), 1);
}
if (FormatStr[1] == 's') {
// sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
if (!CI->getArgOperand(2)->getType()->isPointerTy())
return nullptr;
Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
if (!Len)
return nullptr;
Value *IncLen =
B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
// The sprintf result is the unincremented number of bytes in the string.
return B.CreateIntCast(Len, CI->getType(), false);
}
return nullptr;
}
Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
// Require two fixed pointer arguments and an integer result.
FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
!FT->getParamType(1)->isPointerTy() ||
!FT->getReturnType()->isIntegerTy())
return nullptr;
if (Value *V = optimizeSPrintFString(CI, B)) {
return V;
}
// sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
// point arguments.
if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
Module *M = B.GetInsertBlock()->getParent()->getParent();
Constant *SIPrintFFn =
M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
CallInst *New = cast<CallInst>(CI->clone());
New->setCalledFunction(SIPrintFFn);
B.Insert(New);
return New;
}
return nullptr;
}
Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
optimizeErrorReporting(CI, B, 0);
// All the optimizations depend on the format string.
StringRef FormatStr;
if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
return nullptr;
// Do not do any of the following transformations if the fprintf return
// value is used, in general the fprintf return value is not compatible
// with fwrite(), fputc() or fputs().
if (!CI->use_empty())
return nullptr;
// fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
if (CI->getNumArgOperands() == 2) {
for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
return nullptr; // We found a format specifier.
return EmitFWrite(
CI->getArgOperand(1),
ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
CI->getArgOperand(0), B, DL, TLI);
}
// The remaining optimizations require the format string to be "%s" or "%c"
// and have an extra operand.
if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
CI->getNumArgOperands() < 3)
return nullptr;
// Decode the second character of the format string.
if (FormatStr[1] == 'c') {
// fprintf(F, "%c", chr) --> fputc(chr, F)
if (!CI->getArgOperand(2)->getType()->isIntegerTy())
return nullptr;
return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
}
if (FormatStr[1] == 's') {
// fprintf(F, "%s", str) --> fputs(str, F)
if (!CI->getArgOperand(2)->getType()->isPointerTy())
return nullptr;
return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
}
return nullptr;
}
Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
// Require two fixed paramters as pointers and integer result.
FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
!FT->getParamType(1)->isPointerTy() ||
!FT->getReturnType()->isIntegerTy())
return nullptr;
if (Value *V = optimizeFPrintFString(CI, B)) {
return V;
}
// fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
// floating point arguments.
if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
Module *M = B.GetInsertBlock()->getParent()->getParent();
Constant *FIPrintFFn =
M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
CallInst *New = cast<CallInst>(CI->clone());
New->setCalledFunction(FIPrintFFn);
B.Insert(New);
return New;
}
return nullptr;
}
Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
optimizeErrorReporting(CI, B, 3);
Function *Callee = CI->getCalledFunction();
// Require a pointer, an integer, an integer, a pointer, returning integer.
FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
!FT->getParamType(1)->isIntegerTy() ||
!FT->getParamType(2)->isIntegerTy() ||
!FT->getParamType(3)->isPointerTy() ||
!FT->getReturnType()->isIntegerTy())
return nullptr;
// Get the element size and count.
ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
if (!SizeC || !CountC)
return nullptr;
uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
// If this is writing zero records, remove the call (it's a noop).
if (Bytes == 0)
return ConstantInt::get(CI->getType(), 0);
// If this is writing one byte, turn it into fputc.
// This optimisation is only valid, if the return value is unused.
if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
}
return nullptr;
}
Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
optimizeErrorReporting(CI, B, 1);
Function *Callee = CI->getCalledFunction();
// Require two pointers. Also, we can't optimize if return value is used.
FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
!FT->getParamType(1)->isPointerTy() || !CI->use_empty())
return nullptr;
// fputs(s,F) --> fwrite(s,1,strlen(s),F)
uint64_t Len = GetStringLength(CI->getArgOperand(0));
if (!Len)
return nullptr;
// Known to have no uses (see above).
return EmitFWrite(
CI->getArgOperand(0),
ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
CI->getArgOperand(1), B, DL, TLI);
}
Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
// Require one fixed pointer argument and an integer/void result.
FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
!(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
return nullptr;
// Check for a constant string.
StringRef Str;
if (!getConstantStringInfo(CI->getArgOperand(0), Str))
return nullptr;
if (Str.empty() && CI->use_empty()) {
// puts("") -> putchar('\n')
Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
if (CI->use_empty() || !Res)
return Res;
return B.CreateIntCast(Res, CI->getType(), true);
}
return nullptr;
}
bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
LibFunc::Func Func;
SmallString<20> FloatFuncName = FuncName;
FloatFuncName += 'f';
if (TLI->getLibFunc(FloatFuncName, Func))
return TLI->has(Func);
return false;
}
Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
IRBuilder<> &Builder) {
LibFunc::Func Func;
Function *Callee = CI->getCalledFunction();
StringRef FuncName = Callee->getName();
// Check for string/memory library functions.
if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
// Make sure we never change the calling convention.
assert((ignoreCallingConv(Func) ||
CI->getCallingConv() == llvm::CallingConv::C) &&
"Optimizing string/memory libcall would change the calling convention");
switch (Func) {
case LibFunc::strcat:
return optimizeStrCat(CI, Builder);
case LibFunc::strncat:
return optimizeStrNCat(CI, Builder);
case LibFunc::strchr:
return optimizeStrChr(CI, Builder);
case LibFunc::strrchr:
return optimizeStrRChr(CI, Builder);
case LibFunc::strcmp:
return optimizeStrCmp(CI, Builder);
case LibFunc::strncmp:
return optimizeStrNCmp(CI, Builder);
case LibFunc::strcpy:
return optimizeStrCpy(CI, Builder);
case LibFunc::stpcpy:
return optimizeStpCpy(CI, Builder);
case LibFunc::strncpy:
return optimizeStrNCpy(CI, Builder);
case LibFunc::strlen:
return optimizeStrLen(CI, Builder);
case LibFunc::strpbrk:
return optimizeStrPBrk(CI, Builder);
case LibFunc::strtol:
case LibFunc::strtod:
case LibFunc::strtof:
case LibFunc::strtoul:
case LibFunc::strtoll:
case LibFunc::strtold:
case LibFunc::strtoull:
return optimizeStrTo(CI, Builder);
case LibFunc::strspn:
return optimizeStrSpn(CI, Builder);
case LibFunc::strcspn:
return optimizeStrCSpn(CI, Builder);
case LibFunc::strstr:
return optimizeStrStr(CI, Builder);
case LibFunc::memchr:
return optimizeMemChr(CI, Builder);
case LibFunc::memcmp:
return optimizeMemCmp(CI, Builder);
case LibFunc::memcpy:
return optimizeMemCpy(CI, Builder);
case LibFunc::memmove:
return optimizeMemMove(CI, Builder);
case LibFunc::memset:
return optimizeMemSet(CI, Builder);
default:
break;
}
}
return nullptr;
}
Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
if (CI->isNoBuiltin())
return nullptr;
LibFunc::Func Func;
Function *Callee = CI->getCalledFunction();
StringRef FuncName = Callee->getName();
SmallVector<OperandBundleDef, 2> OpBundles;
CI->getOperandBundlesAsDefs(OpBundles);
IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
// Command-line parameter overrides function attribute.
if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
UnsafeFPShrink = EnableUnsafeFPShrink;
else if (canUseUnsafeFPMath(Callee))
UnsafeFPShrink = true;
// First, check for intrinsics.
if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
if (!isCallingConvC)
return nullptr;
switch (II->getIntrinsicID()) {
case Intrinsic::pow:
return optimizePow(CI, Builder);
case Intrinsic::exp2:
return optimizeExp2(CI, Builder);
case Intrinsic::fabs:
return optimizeFabs(CI, Builder);
case Intrinsic::log:
return optimizeLog(CI, Builder);
case Intrinsic::sqrt:
return optimizeSqrt(CI, Builder);
default:
return nullptr;
}
}
// Also try to simplify calls to fortified library functions.
if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
// Try to further simplify the result.
CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
// Use an IR Builder from SimplifiedCI if available instead of CI
// to guarantee we reach all uses we might replace later on.
IRBuilder<> TmpBuilder(SimplifiedCI);
if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
// If we were able to further simplify, remove the now redundant call.
SimplifiedCI->replaceAllUsesWith(V);
SimplifiedCI->eraseFromParent();
return V;
}
}
return SimplifiedFortifiedCI;
}
// Then check for known library functions.
if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
// We never change the calling convention.
if (!ignoreCallingConv(Func) && !isCallingConvC)
return nullptr;
if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
return V;
switch (Func) {
case LibFunc::cosf:
case LibFunc::cos:
case LibFunc::cosl:
return optimizeCos(CI, Builder);
case LibFunc::sinpif:
case LibFunc::sinpi:
case LibFunc::cospif:
case LibFunc::cospi:
return optimizeSinCosPi(CI, Builder);
case LibFunc::powf:
case LibFunc::pow:
case LibFunc::powl:
return optimizePow(CI, Builder);
case LibFunc::exp2l:
case LibFunc::exp2:
case LibFunc::exp2f:
return optimizeExp2(CI, Builder);
case LibFunc::fabsf:
case LibFunc::fabs:
case LibFunc::fabsl:
return optimizeFabs(CI, Builder);
case LibFunc::sqrtf:
case LibFunc::sqrt:
case LibFunc::sqrtl:
return optimizeSqrt(CI, Builder);
case LibFunc::ffs:
case LibFunc::ffsl:
case LibFunc::ffsll:
return optimizeFFS(CI, Builder);
case LibFunc::abs:
case LibFunc::labs:
case LibFunc::llabs:
return optimizeAbs(CI, Builder);
case LibFunc::isdigit:
return optimizeIsDigit(CI, Builder);
case LibFunc::isascii:
return optimizeIsAscii(CI, Builder);
case LibFunc::toascii:
return optimizeToAscii(CI, Builder);
case LibFunc::printf:
return optimizePrintF(CI, Builder);
case LibFunc::sprintf:
return optimizeSPrintF(CI, Builder);
case LibFunc::fprintf:
return optimizeFPrintF(CI, Builder);
case LibFunc::fwrite:
return optimizeFWrite(CI, Builder);
case LibFunc::fputs:
return optimizeFPuts(CI, Builder);
case LibFunc::log:
case LibFunc::log10:
case LibFunc::log1p:
case LibFunc::log2:
case LibFunc::logb:
return optimizeLog(CI, Builder);
case LibFunc::puts:
return optimizePuts(CI, Builder);
case LibFunc::tan:
case LibFunc::tanf:
case LibFunc::tanl:
return optimizeTan(CI, Builder);
case LibFunc::perror:
return optimizeErrorReporting(CI, Builder);
case LibFunc::vfprintf:
case LibFunc::fiprintf:
return optimizeErrorReporting(CI, Builder, 0);
case LibFunc::fputc:
return optimizeErrorReporting(CI, Builder, 1);
case LibFunc::ceil:
case LibFunc::floor:
case LibFunc::rint:
case LibFunc::round:
case LibFunc::nearbyint:
case LibFunc::trunc:
if (hasFloatVersion(FuncName))
return optimizeUnaryDoubleFP(CI, Builder, false);
return nullptr;
case LibFunc::acos:
case LibFunc::acosh:
case LibFunc::asin:
case LibFunc::asinh:
case LibFunc::atan:
case LibFunc::atanh:
case LibFunc::cbrt:
case LibFunc::cosh:
case LibFunc::exp:
case LibFunc::exp10:
case LibFunc::expm1:
case LibFunc::sin:
case LibFunc::sinh:
case LibFunc::tanh:
if (UnsafeFPShrink && hasFloatVersion(FuncName))
return optimizeUnaryDoubleFP(CI, Builder, true);
return nullptr;
case LibFunc::copysign:
if (hasFloatVersion(FuncName))
return optimizeBinaryDoubleFP(CI, Builder);
return nullptr;
case LibFunc::fminf:
case LibFunc::fmin:
case LibFunc::fminl:
case LibFunc::fmaxf:
case LibFunc::fmax:
case LibFunc::fmaxl:
return optimizeFMinFMax(CI, Builder);
default:
return nullptr;
}
}
return nullptr;
}
LibCallSimplifier::LibCallSimplifier(
const DataLayout &DL, const TargetLibraryInfo *TLI,
function_ref<void(Instruction *, Value *)> Replacer)
: FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Replacer(Replacer) {}
void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
// Indirect through the replacer used in this instance.
Replacer(I, With);
}
// TODO:
// Additional cases that we need to add to this file:
//
// cbrt:
// * cbrt(expN(X)) -> expN(x/3)
// * cbrt(sqrt(x)) -> pow(x,1/6)
// * cbrt(cbrt(x)) -> pow(x,1/9)
//
// exp, expf, expl:
// * exp(log(x)) -> x
//
// log, logf, logl:
// * log(exp(x)) -> x
// * log(exp(y)) -> y*log(e)
// * log(exp10(y)) -> y*log(10)
// * log(sqrt(x)) -> 0.5*log(x)
//
// lround, lroundf, lroundl:
// * lround(cnst) -> cnst'
//
// pow, powf, powl:
// * pow(sqrt(x),y) -> pow(x,y*0.5)
// * pow(pow(x,y),z)-> pow(x,y*z)
//
// round, roundf, roundl:
// * round(cnst) -> cnst'
//
// signbit:
// * signbit(cnst) -> cnst'
// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
//
// sqrt, sqrtf, sqrtl:
// * sqrt(expN(x)) -> expN(x*0.5)
// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
//
// trunc, truncf, truncl:
// * trunc(cnst) -> cnst'
//
//
//===----------------------------------------------------------------------===//
// Fortified Library Call Optimizations
//===----------------------------------------------------------------------===//
bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
unsigned ObjSizeOp,
unsigned SizeOp,
bool isString) {
if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
return true;
if (ConstantInt *ObjSizeCI =
dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
if (ObjSizeCI->isAllOnesValue())
return true;
// If the object size wasn't -1 (unknown), bail out if we were asked to.
if (OnlyLowerUnknownSize)
return false;
if (isString) {
uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
// If the length is 0 we don't know how long it is and so we can't
// remove the check.
if (Len == 0)
return false;
return ObjSizeCI->getZExtValue() >= Len;
}
if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
}
return false;
}
Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
return nullptr;
if (isFortifiedCallFoldable(CI, 3, 2, false)) {
B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
CI->getArgOperand(2), 1);
return CI->getArgOperand(0);
}
return nullptr;
}
Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
return nullptr;
if (isFortifiedCallFoldable(CI, 3, 2, false)) {
B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
CI->getArgOperand(2), 1);
return CI->getArgOperand(0);
}
return nullptr;
}
Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
IRBuilder<> &B) {
Function *Callee = CI->getCalledFunction();
if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
return nullptr;
if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
return CI->getArgOperand(0);
}
return nullptr;
}
Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
IRBuilder<> &B,
LibFunc::Func Func) {
Function *Callee = CI->getCalledFunction();
StringRef Name = Callee->getName();
const DataLayout &DL = CI->getModule()->getDataLayout();
if (!checkStringCopyLibFuncSignature(Callee, Func))
return nullptr;
Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
*ObjSize = CI->getArgOperand(2);
// __stpcpy_chk(x,x,...) -> x+strlen(x)
if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Value *StrLen = EmitStrLen(Src, B, DL, TLI);
return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
}
// If a) we don't have any length information, or b) we know this will
// fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
// st[rp]cpy_chk call which may fail at runtime if the size is too long.
// TODO: It might be nice to get a maximum length out of the possible
// string lengths for varying.
if (isFortifiedCallFoldable(CI, 2, 1, true))
return EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
if (OnlyLowerUnknownSize)
return nullptr;
// Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
uint64_t Len = GetStringLength(Src);
if (Len == 0)
return nullptr;
Type *SizeTTy = DL.getIntPtrType(CI->getContext());
Value *LenV = ConstantInt::get(SizeTTy, Len);
Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
// If the function was an __stpcpy_chk, and we were able to fold it into
// a __memcpy_chk, we still need to return the correct end pointer.
if (Ret && Func == LibFunc::stpcpy_chk)
return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
return Ret;
}
Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
IRBuilder<> &B,
LibFunc::Func Func) {
Function *Callee = CI->getCalledFunction();
StringRef Name = Callee->getName();
if (!checkStringCopyLibFuncSignature(Callee, Func))
return nullptr;
if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
return Ret;
}
return nullptr;
}
Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
// FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
// Some clang users checked for _chk libcall availability using:
// __has_builtin(__builtin___memcpy_chk)
// When compiling with -fno-builtin, this is always true.
// When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
// end up with fortified libcalls, which isn't acceptable in a freestanding
// environment which only provides their non-fortified counterparts.
//
// Until we change clang and/or teach external users to check for availability
// differently, disregard the "nobuiltin" attribute and TLI::has.
//
// PR23093.
LibFunc::Func Func;
Function *Callee = CI->getCalledFunction();
StringRef FuncName = Callee->getName();
SmallVector<OperandBundleDef, 2> OpBundles;
CI->getOperandBundlesAsDefs(OpBundles);
IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
// First, check that this is a known library functions.
if (!TLI->getLibFunc(FuncName, Func))
return nullptr;
// We never change the calling convention.
if (!ignoreCallingConv(Func) && !isCallingConvC)
return nullptr;
switch (Func) {
case LibFunc::memcpy_chk:
return optimizeMemCpyChk(CI, Builder);
case LibFunc::memmove_chk:
return optimizeMemMoveChk(CI, Builder);
case LibFunc::memset_chk:
return optimizeMemSetChk(CI, Builder);
case LibFunc::stpcpy_chk:
case LibFunc::strcpy_chk:
return optimizeStrpCpyChk(CI, Builder, Func);
case LibFunc::stpncpy_chk:
case LibFunc::strncpy_chk:
return optimizeStrpNCpyChk(CI, Builder, Func);
default:
break;
}
return nullptr;
}
FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
: TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}
| TigerBSD/TigerBSD | FreeBSD/contrib/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp | C++ | isc | 94,896 |
package com.j256.ormlite.android.apptools;
import java.sql.SQLException;
import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.widget.CursorAdapter;
import com.j256.ormlite.android.AndroidDatabaseResults;
import com.j256.ormlite.stmt.PreparedQuery;
/**
* Cursor adapter base class.
*
* @author emmby
*/
public abstract class OrmLiteCursorAdapter<T, ViewType extends View> extends CursorAdapter {
protected PreparedQuery<T> preparedQuery;
public OrmLiteCursorAdapter(Context context) {
super(context, null, false);
}
/**
* Bind the view to a particular item.
*/
public abstract void bindView(ViewType itemView, Context context, T item);
/**
* Final to prevent subclasses from accidentally overriding. Intentional overriding can be accomplished by
* overriding {@link #doBindView(View, Context, Cursor)}.
*
* @see CursorAdapter#bindView(View, Context, Cursor)
*/
@Override
public final void bindView(View itemView, Context context, Cursor cursor) {
doBindView(itemView, context, cursor);
}
/**
* This is here to make sure that the user really wants to override it.
*/
protected void doBindView(View itemView, Context context, Cursor cursor) {
try {
@SuppressWarnings("unchecked")
ViewType itemViewType = (ViewType) itemView;
bindView(itemViewType, context, preparedQuery.mapRow(new AndroidDatabaseResults(cursor, null)));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* Show not be used. Instead use {@link #changeCursor(Cursor, PreparedQuery)}
*/
@Override
public final void changeCursor(Cursor cursor) {
throw new UnsupportedOperationException(
"Please use OrmLiteCursorAdapter.changeCursor(Cursor,PreparedQuery) instead");
}
/**
* Change the cursor associated with the prepared query.
*/
public void changeCursor(Cursor cursor, PreparedQuery<T> preparedQuery) {
setPreparedQuery(preparedQuery);
super.changeCursor(cursor);
}
public void setPreparedQuery(PreparedQuery<T> preparedQuery) {
this.preparedQuery = preparedQuery;
}
}
| dankito/ormlite-jpa-android | src/main/java/com/j256/ormlite/android/apptools/OrmLiteCursorAdapter.java | Java | isc | 2,099 |
'use strict'
/* global describe it beforeEach afterEach */
const cli = require('heroku-cli-util')
const { expect } = require('chai')
const nock = require('nock')
const proxyquire = require('proxyquire')
const addon = {
id: 1,
name: 'postgres-1',
plan: { name: 'heroku-postgresql:standard-0' }
}
const fetcher = () => {
return {
addon: () => addon
}
}
const cmd = proxyquire('../../commands/reset', {
'../lib/fetcher': fetcher
})
describe('pg:reset', () => {
let api, pg
beforeEach(() => {
api = nock('https://api.heroku.com')
pg = nock('https://postgres-api.heroku.com')
cli.mockConsole()
})
afterEach(() => {
nock.cleanAll()
pg.done()
api.done()
})
it('reset db', () => {
pg.put('/client/v11/databases/1/reset').reply(200)
return cmd.run({ app: 'myapp', args: {}, flags: { confirm: 'myapp' } })
.then(() => expect(cli.stderr).to.equal('Resetting postgres-1... done\n'))
})
})
| heroku/cli | packages/pg-v5/test/commands/reset.js | JavaScript | isc | 952 |
/* $OpenBSD: rt2860reg.h,v 1.19 2009/05/18 19:25:07 damien Exp $ */
/*-
* Copyright (c) 2007
* Damien Bergamini <damien.bergamini@free.fr>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* $FreeBSD$
*/
#ifndef _IF_RUNREG_H_
#define _IF_RUNREG_H_
#define RT2860_CONFIG_NO 1
#define RT2860_IFACE_INDEX 0
#define RT3070_OPT_14 0x0114
/* SCH/DMA registers */
#define RT2860_INT_STATUS 0x0200
#define RT2860_INT_MASK 0x0204
#define RT2860_WPDMA_GLO_CFG 0x0208
#define RT2860_WPDMA_RST_IDX 0x020c
#define RT2860_DELAY_INT_CFG 0x0210
#define RT2860_WMM_AIFSN_CFG 0x0214
#define RT2860_WMM_CWMIN_CFG 0x0218
#define RT2860_WMM_CWMAX_CFG 0x021c
#define RT2860_WMM_TXOP0_CFG 0x0220
#define RT2860_WMM_TXOP1_CFG 0x0224
#define RT2860_GPIO_CTRL 0x0228
#define RT2860_MCU_CMD_REG 0x022c
#define RT2860_TX_BASE_PTR(qid) (0x0230 + (qid) * 16)
#define RT2860_TX_MAX_CNT(qid) (0x0234 + (qid) * 16)
#define RT2860_TX_CTX_IDX(qid) (0x0238 + (qid) * 16)
#define RT2860_TX_DTX_IDX(qid) (0x023c + (qid) * 16)
#define RT2860_RX_BASE_PTR 0x0290
#define RT2860_RX_MAX_CNT 0x0294
#define RT2860_RX_CALC_IDX 0x0298
#define RT2860_FS_DRX_IDX 0x029c
#define RT2860_USB_DMA_CFG 0x02a0 /* RT2870 only */
#define RT2860_US_CYC_CNT 0x02a4
/* PBF registers */
#define RT2860_SYS_CTRL 0x0400
#define RT2860_HOST_CMD 0x0404
#define RT2860_PBF_CFG 0x0408
#define RT2860_MAX_PCNT 0x040c
#define RT2860_BUF_CTRL 0x0410
#define RT2860_MCU_INT_STA 0x0414
#define RT2860_MCU_INT_ENA 0x0418
#define RT2860_TXQ_IO(qid) (0x041c + (qid) * 4)
#define RT2860_RX0Q_IO 0x0424
#define RT2860_BCN_OFFSET0 0x042c
#define RT2860_BCN_OFFSET1 0x0430
#define RT2860_TXRXQ_STA 0x0434
#define RT2860_TXRXQ_PCNT 0x0438
#define RT2860_PBF_DBG 0x043c
#define RT2860_CAP_CTRL 0x0440
/* RT3070 registers */
#define RT3070_RF_CSR_CFG 0x0500
#define RT3070_EFUSE_CTRL 0x0580
#define RT3070_EFUSE_DATA0 0x0590
#define RT3070_EFUSE_DATA1 0x0594
#define RT3070_EFUSE_DATA2 0x0598
#define RT3070_EFUSE_DATA3 0x059c
#define RT3070_LDO_CFG0 0x05d4
#define RT3070_GPIO_SWITCH 0x05dc
/* RT5592 registers */
#define RT5592_DEBUG_INDEX 0x05e8
/* MAC registers */
#define RT2860_ASIC_VER_ID 0x1000
#define RT2860_MAC_SYS_CTRL 0x1004
#define RT2860_MAC_ADDR_DW0 0x1008
#define RT2860_MAC_ADDR_DW1 0x100c
#define RT2860_MAC_BSSID_DW0 0x1010
#define RT2860_MAC_BSSID_DW1 0x1014
#define RT2860_MAX_LEN_CFG 0x1018
#define RT2860_BBP_CSR_CFG 0x101c
#define RT2860_RF_CSR_CFG0 0x1020
#define RT2860_RF_CSR_CFG1 0x1024
#define RT2860_RF_CSR_CFG2 0x1028
#define RT2860_LED_CFG 0x102c
/* undocumented registers */
#define RT2860_DEBUG 0x10f4
/* MAC Timing control registers */
#define RT2860_XIFS_TIME_CFG 0x1100
#define RT2860_BKOFF_SLOT_CFG 0x1104
#define RT2860_NAV_TIME_CFG 0x1108
#define RT2860_CH_TIME_CFG 0x110c
#define RT2860_PBF_LIFE_TIMER 0x1110
#define RT2860_BCN_TIME_CFG 0x1114
#define RT2860_TBTT_SYNC_CFG 0x1118
#define RT2860_TSF_TIMER_DW0 0x111c
#define RT2860_TSF_TIMER_DW1 0x1120
#define RT2860_TBTT_TIMER 0x1124
#define RT2860_INT_TIMER_CFG 0x1128
#define RT2860_INT_TIMER_EN 0x112c
#define RT2860_CH_IDLE_TIME 0x1130
/* MAC Power Save configuration registers */
#define RT2860_MAC_STATUS_REG 0x1200
#define RT2860_PWR_PIN_CFG 0x1204
#define RT2860_AUTO_WAKEUP_CFG 0x1208
/* MAC TX configuration registers */
#define RT2860_EDCA_AC_CFG(aci) (0x1300 + (aci) * 4)
#define RT2860_EDCA_TID_AC_MAP 0x1310
#define RT2860_TX_PWR_CFG(ridx) (0x1314 + (ridx) * 4)
#define RT2860_TX_PIN_CFG 0x1328
#define RT2860_TX_BAND_CFG 0x132c
#define RT2860_TX_SW_CFG0 0x1330
#define RT2860_TX_SW_CFG1 0x1334
#define RT2860_TX_SW_CFG2 0x1338
#define RT2860_TXOP_THRES_CFG 0x133c
#define RT2860_TXOP_CTRL_CFG 0x1340
#define RT2860_TX_RTS_CFG 0x1344
#define RT2860_TX_TIMEOUT_CFG 0x1348
#define RT2860_TX_RTY_CFG 0x134c
#define RT2860_TX_LINK_CFG 0x1350
#define RT2860_HT_FBK_CFG0 0x1354
#define RT2860_HT_FBK_CFG1 0x1358
#define RT2860_LG_FBK_CFG0 0x135c
#define RT2860_LG_FBK_CFG1 0x1360
#define RT2860_CCK_PROT_CFG 0x1364
#define RT2860_OFDM_PROT_CFG 0x1368
#define RT2860_MM20_PROT_CFG 0x136c
#define RT2860_MM40_PROT_CFG 0x1370
#define RT2860_GF20_PROT_CFG 0x1374
#define RT2860_GF40_PROT_CFG 0x1378
#define RT2860_EXP_CTS_TIME 0x137c
#define RT2860_EXP_ACK_TIME 0x1380
/* MAC RX configuration registers */
#define RT2860_RX_FILTR_CFG 0x1400
#define RT2860_AUTO_RSP_CFG 0x1404
#define RT2860_LEGACY_BASIC_RATE 0x1408
#define RT2860_HT_BASIC_RATE 0x140c
#define RT2860_HT_CTRL_CFG 0x1410
#define RT2860_SIFS_COST_CFG 0x1414
#define RT2860_RX_PARSER_CFG 0x1418
/* MAC Security configuration registers */
#define RT2860_TX_SEC_CNT0 0x1500
#define RT2860_RX_SEC_CNT0 0x1504
#define RT2860_CCMP_FC_MUTE 0x1508
/* MAC HCCA/PSMP configuration registers */
#define RT2860_TXOP_HLDR_ADDR0 0x1600
#define RT2860_TXOP_HLDR_ADDR1 0x1604
#define RT2860_TXOP_HLDR_ET 0x1608
#define RT2860_QOS_CFPOLL_RA_DW0 0x160c
#define RT2860_QOS_CFPOLL_A1_DW1 0x1610
#define RT2860_QOS_CFPOLL_QC 0x1614
/* MAC Statistics Counters */
#define RT2860_RX_STA_CNT0 0x1700
#define RT2860_RX_STA_CNT1 0x1704
#define RT2860_RX_STA_CNT2 0x1708
#define RT2860_TX_STA_CNT0 0x170c
#define RT2860_TX_STA_CNT1 0x1710
#define RT2860_TX_STA_CNT2 0x1714
#define RT2860_TX_STAT_FIFO 0x1718
/* RX WCID search table */
#define RT2860_WCID_ENTRY(wcid) (0x1800 + (wcid) * 8)
#define RT2860_FW_BASE 0x2000
#define RT2870_FW_BASE 0x3000
/* Pair-wise key table */
#define RT2860_PKEY(wcid) (0x4000 + (wcid) * 32)
/* IV/EIV table */
#define RT2860_IVEIV(wcid) (0x6000 + (wcid) * 8)
/* WCID attribute table */
#define RT2860_WCID_ATTR(wcid) (0x6800 + (wcid) * 4)
/* Shared Key Table */
#define RT2860_SKEY(vap, kidx) (0x6c00 + (vap) * 128 + (kidx) * 32)
/* Shared Key Mode */
#define RT2860_SKEY_MODE_0_7 0x7000
#define RT2860_SKEY_MODE_8_15 0x7004
#define RT2860_SKEY_MODE_16_23 0x7008
#define RT2860_SKEY_MODE_24_31 0x700c
/* Shared Memory between MCU and host */
#define RT2860_H2M_MAILBOX 0x7010
#define RT2860_H2M_MAILBOX_CID 0x7014
#define RT2860_H2M_MAILBOX_STATUS 0x701c
#define RT2860_H2M_INTSRC 0x7024
#define RT2860_H2M_BBPAGENT 0x7028
#define RT2860_BCN_BASE(vap) (0x7800 + (vap) * 512)
/* possible flags for register RT2860_PCI_EECTRL */
#define RT2860_C (1 << 0)
#define RT2860_S (1 << 1)
#define RT2860_D (1 << 2)
#define RT2860_SHIFT_D 2
#define RT2860_Q (1 << 3)
#define RT2860_SHIFT_Q 3
/* possible flags for registers INT_STATUS/INT_MASK */
#define RT2860_TX_COHERENT (1 << 17)
#define RT2860_RX_COHERENT (1 << 16)
#define RT2860_MAC_INT_4 (1 << 15)
#define RT2860_MAC_INT_3 (1 << 14)
#define RT2860_MAC_INT_2 (1 << 13)
#define RT2860_MAC_INT_1 (1 << 12)
#define RT2860_MAC_INT_0 (1 << 11)
#define RT2860_TX_RX_COHERENT (1 << 10)
#define RT2860_MCU_CMD_INT (1 << 9)
#define RT2860_TX_DONE_INT5 (1 << 8)
#define RT2860_TX_DONE_INT4 (1 << 7)
#define RT2860_TX_DONE_INT3 (1 << 6)
#define RT2860_TX_DONE_INT2 (1 << 5)
#define RT2860_TX_DONE_INT1 (1 << 4)
#define RT2860_TX_DONE_INT0 (1 << 3)
#define RT2860_RX_DONE_INT (1 << 2)
#define RT2860_TX_DLY_INT (1 << 1)
#define RT2860_RX_DLY_INT (1 << 0)
/* possible flags for register WPDMA_GLO_CFG */
#define RT2860_HDR_SEG_LEN_SHIFT 8
#define RT2860_BIG_ENDIAN (1 << 7)
#define RT2860_TX_WB_DDONE (1 << 6)
#define RT2860_WPDMA_BT_SIZE_SHIFT 4
#define RT2860_WPDMA_BT_SIZE16 0
#define RT2860_WPDMA_BT_SIZE32 1
#define RT2860_WPDMA_BT_SIZE64 2
#define RT2860_WPDMA_BT_SIZE128 3
#define RT2860_RX_DMA_BUSY (1 << 3)
#define RT2860_RX_DMA_EN (1 << 2)
#define RT2860_TX_DMA_BUSY (1 << 1)
#define RT2860_TX_DMA_EN (1 << 0)
/* possible flags for register DELAY_INT_CFG */
#define RT2860_TXDLY_INT_EN (1U << 31)
#define RT2860_TXMAX_PINT_SHIFT 24
#define RT2860_TXMAX_PTIME_SHIFT 16
#define RT2860_RXDLY_INT_EN (1 << 15)
#define RT2860_RXMAX_PINT_SHIFT 8
#define RT2860_RXMAX_PTIME_SHIFT 0
/* possible flags for register GPIO_CTRL */
#define RT2860_GPIO_D_SHIFT 8
#define RT2860_GPIO_O_SHIFT 0
/* possible flags for register USB_DMA_CFG */
#define RT2860_USB_TX_BUSY (1U << 31)
#define RT2860_USB_RX_BUSY (1 << 30)
#define RT2860_USB_EPOUT_VLD_SHIFT 24
#define RT2860_USB_TX_EN (1 << 23)
#define RT2860_USB_RX_EN (1 << 22)
#define RT2860_USB_RX_AGG_EN (1 << 21)
#define RT2860_USB_TXOP_HALT (1 << 20)
#define RT2860_USB_TX_CLEAR (1 << 19)
#define RT2860_USB_PHY_WD_EN (1 << 16)
#define RT2860_USB_RX_AGG_LMT(x) ((x) << 8) /* in unit of 1KB */
#define RT2860_USB_RX_AGG_TO(x) ((x) & 0xff) /* in unit of 33ns */
/* possible flags for register US_CYC_CNT */
#define RT2860_TEST_EN (1 << 24)
#define RT2860_TEST_SEL_SHIFT 16
#define RT2860_BT_MODE_EN (1 << 8)
#define RT2860_US_CYC_CNT_SHIFT 0
/* possible flags for register SYS_CTRL */
#define RT2860_HST_PM_SEL (1 << 16)
#define RT2860_CAP_MODE (1 << 14)
#define RT2860_PME_OEN (1 << 13)
#define RT2860_CLKSELECT (1 << 12)
#define RT2860_PBF_CLK_EN (1 << 11)
#define RT2860_MAC_CLK_EN (1 << 10)
#define RT2860_DMA_CLK_EN (1 << 9)
#define RT2860_MCU_READY (1 << 7)
#define RT2860_ASY_RESET (1 << 4)
#define RT2860_PBF_RESET (1 << 3)
#define RT2860_MAC_RESET (1 << 2)
#define RT2860_DMA_RESET (1 << 1)
#define RT2860_MCU_RESET (1 << 0)
/* possible values for register HOST_CMD */
#define RT2860_MCU_CMD_SLEEP 0x30
#define RT2860_MCU_CMD_WAKEUP 0x31
#define RT2860_MCU_CMD_LEDS 0x50
#define RT2860_MCU_CMD_LED_RSSI 0x51
#define RT2860_MCU_CMD_LED1 0x52
#define RT2860_MCU_CMD_LED2 0x53
#define RT2860_MCU_CMD_LED3 0x54
#define RT2860_MCU_CMD_RFRESET 0x72
#define RT2860_MCU_CMD_ANTSEL 0x73
#define RT2860_MCU_CMD_BBP 0x80
#define RT2860_MCU_CMD_PSLEVEL 0x83
/* possible flags for register PBF_CFG */
#define RT2860_TX1Q_NUM_SHIFT 21
#define RT2860_TX2Q_NUM_SHIFT 16
#define RT2860_NULL0_MODE (1 << 15)
#define RT2860_NULL1_MODE (1 << 14)
#define RT2860_RX_DROP_MODE (1 << 13)
#define RT2860_TX0Q_MANUAL (1 << 12)
#define RT2860_TX1Q_MANUAL (1 << 11)
#define RT2860_TX2Q_MANUAL (1 << 10)
#define RT2860_RX0Q_MANUAL (1 << 9)
#define RT2860_HCCA_EN (1 << 8)
#define RT2860_TX0Q_EN (1 << 4)
#define RT2860_TX1Q_EN (1 << 3)
#define RT2860_TX2Q_EN (1 << 2)
#define RT2860_RX0Q_EN (1 << 1)
/* possible flags for register BUF_CTRL */
#define RT2860_WRITE_TXQ(qid) (1 << (11 - (qid)))
#define RT2860_NULL0_KICK (1 << 7)
#define RT2860_NULL1_KICK (1 << 6)
#define RT2860_BUF_RESET (1 << 5)
#define RT2860_READ_TXQ(qid) (1 << (3 - (qid))
#define RT2860_READ_RX0Q (1 << 0)
/* possible flags for registers MCU_INT_STA/MCU_INT_ENA */
#define RT2860_MCU_MAC_INT_8 (1 << 24)
#define RT2860_MCU_MAC_INT_7 (1 << 23)
#define RT2860_MCU_MAC_INT_6 (1 << 22)
#define RT2860_MCU_MAC_INT_4 (1 << 20)
#define RT2860_MCU_MAC_INT_3 (1 << 19)
#define RT2860_MCU_MAC_INT_2 (1 << 18)
#define RT2860_MCU_MAC_INT_1 (1 << 17)
#define RT2860_MCU_MAC_INT_0 (1 << 16)
#define RT2860_DTX0_INT (1 << 11)
#define RT2860_DTX1_INT (1 << 10)
#define RT2860_DTX2_INT (1 << 9)
#define RT2860_DRX0_INT (1 << 8)
#define RT2860_HCMD_INT (1 << 7)
#define RT2860_N0TX_INT (1 << 6)
#define RT2860_N1TX_INT (1 << 5)
#define RT2860_BCNTX_INT (1 << 4)
#define RT2860_MTX0_INT (1 << 3)
#define RT2860_MTX1_INT (1 << 2)
#define RT2860_MTX2_INT (1 << 1)
#define RT2860_MRX0_INT (1 << 0)
/* possible flags for register TXRXQ_PCNT */
#define RT2860_RX0Q_PCNT_MASK 0xff000000
#define RT2860_TX2Q_PCNT_MASK 0x00ff0000
#define RT2860_TX1Q_PCNT_MASK 0x0000ff00
#define RT2860_TX0Q_PCNT_MASK 0x000000ff
/* possible flags for register CAP_CTRL */
#define RT2860_CAP_ADC_FEQ (1U << 31)
#define RT2860_CAP_START (1 << 30)
#define RT2860_MAN_TRIG (1 << 29)
#define RT2860_TRIG_OFFSET_SHIFT 16
#define RT2860_START_ADDR_SHIFT 0
/* possible flags for register RF_CSR_CFG */
#define RT3070_RF_KICK (1 << 17)
#define RT3070_RF_WRITE (1 << 16)
/* possible flags for register EFUSE_CTRL */
#define RT3070_SEL_EFUSE (1U << 31)
#define RT3070_EFSROM_KICK (1 << 30)
#define RT3070_EFSROM_AIN_MASK 0x03ff0000
#define RT3070_EFSROM_AIN_SHIFT 16
#define RT3070_EFSROM_MODE_MASK 0x000000c0
#define RT3070_EFUSE_AOUT_MASK 0x0000003f
/* possible flag for register DEBUG_INDEX */
#define RT5592_SEL_XTAL (1U << 31)
/* possible flags for register MAC_SYS_CTRL */
#define RT2860_RX_TS_EN (1 << 7)
#define RT2860_WLAN_HALT_EN (1 << 6)
#define RT2860_PBF_LOOP_EN (1 << 5)
#define RT2860_CONT_TX_TEST (1 << 4)
#define RT2860_MAC_RX_EN (1 << 3)
#define RT2860_MAC_TX_EN (1 << 2)
#define RT2860_BBP_HRST (1 << 1)
#define RT2860_MAC_SRST (1 << 0)
/* possible flags for register MAC_BSSID_DW1 */
#define RT2860_MULTI_BCN_NUM_SHIFT 18
#define RT2860_MULTI_BSSID_MODE_SHIFT 16
/* possible flags for register MAX_LEN_CFG */
#define RT2860_MIN_MPDU_LEN_SHIFT 16
#define RT2860_MAX_PSDU_LEN_SHIFT 12
#define RT2860_MAX_PSDU_LEN8K 0
#define RT2860_MAX_PSDU_LEN16K 1
#define RT2860_MAX_PSDU_LEN32K 2
#define RT2860_MAX_PSDU_LEN64K 3
#define RT2860_MAX_MPDU_LEN_SHIFT 0
/* possible flags for registers BBP_CSR_CFG/H2M_BBPAGENT */
#define RT2860_BBP_RW_PARALLEL (1 << 19)
#define RT2860_BBP_PAR_DUR_112_5 (1 << 18)
#define RT2860_BBP_CSR_KICK (1 << 17)
#define RT2860_BBP_CSR_READ (1 << 16)
#define RT2860_BBP_ADDR_SHIFT 8
#define RT2860_BBP_DATA_SHIFT 0
/* possible flags for register RF_CSR_CFG0 */
#define RT2860_RF_REG_CTRL (1U << 31)
#define RT2860_RF_LE_SEL1 (1 << 30)
#define RT2860_RF_LE_STBY (1 << 29)
#define RT2860_RF_REG_WIDTH_SHIFT 24
#define RT2860_RF_REG_0_SHIFT 0
/* possible flags for register RF_CSR_CFG1 */
#define RT2860_RF_DUR_5 (1 << 24)
#define RT2860_RF_REG_1_SHIFT 0
/* possible flags for register LED_CFG */
#define RT2860_LED_POL (1 << 30)
#define RT2860_Y_LED_MODE_SHIFT 28
#define RT2860_G_LED_MODE_SHIFT 26
#define RT2860_R_LED_MODE_SHIFT 24
#define RT2860_LED_MODE_OFF 0
#define RT2860_LED_MODE_BLINK_TX 1
#define RT2860_LED_MODE_SLOW_BLINK 2
#define RT2860_LED_MODE_ON 3
#define RT2860_SLOW_BLK_TIME_SHIFT 16
#define RT2860_LED_OFF_TIME_SHIFT 8
#define RT2860_LED_ON_TIME_SHIFT 0
/* possible flags for register XIFS_TIME_CFG */
#define RT2860_BB_RXEND_EN (1 << 29)
#define RT2860_EIFS_TIME_SHIFT 20
#define RT2860_OFDM_XIFS_TIME_SHIFT 16
#define RT2860_OFDM_SIFS_TIME_SHIFT 8
#define RT2860_CCK_SIFS_TIME_SHIFT 0
/* possible flags for register BKOFF_SLOT_CFG */
#define RT2860_CC_DELAY_TIME_SHIFT 8
#define RT2860_SLOT_TIME 0
/* possible flags for register NAV_TIME_CFG */
#define RT2860_NAV_UPD (1U << 31)
#define RT2860_NAV_UPD_VAL_SHIFT 16
#define RT2860_NAV_CLR_EN (1 << 15)
#define RT2860_NAV_TIMER_SHIFT 0
/* possible flags for register CH_TIME_CFG */
#define RT2860_EIFS_AS_CH_BUSY (1 << 4)
#define RT2860_NAV_AS_CH_BUSY (1 << 3)
#define RT2860_RX_AS_CH_BUSY (1 << 2)
#define RT2860_TX_AS_CH_BUSY (1 << 1)
#define RT2860_CH_STA_TIMER_EN (1 << 0)
/* possible values for register BCN_TIME_CFG */
#define RT2860_TSF_INS_COMP_SHIFT 24
#define RT2860_BCN_TX_EN (1 << 20)
#define RT2860_TBTT_TIMER_EN (1 << 19)
#define RT2860_TSF_SYNC_MODE_SHIFT 17
#define RT2860_TSF_SYNC_MODE_DIS 0
#define RT2860_TSF_SYNC_MODE_STA 1
#define RT2860_TSF_SYNC_MODE_IBSS 2
#define RT2860_TSF_SYNC_MODE_HOSTAP 3
#define RT2860_TSF_TIMER_EN (1 << 16)
#define RT2860_BCN_INTVAL_SHIFT 0
/* possible flags for register TBTT_SYNC_CFG */
#define RT2860_BCN_CWMIN_SHIFT 20
#define RT2860_BCN_AIFSN_SHIFT 16
#define RT2860_BCN_EXP_WIN_SHIFT 8
#define RT2860_TBTT_ADJUST_SHIFT 0
/* possible flags for register INT_TIMER_CFG */
#define RT2860_GP_TIMER_SHIFT 16
#define RT2860_PRE_TBTT_TIMER_SHIFT 0
/* possible flags for register INT_TIMER_EN */
#define RT2860_GP_TIMER_EN (1 << 1)
#define RT2860_PRE_TBTT_INT_EN (1 << 0)
/* possible flags for register MAC_STATUS_REG */
#define RT2860_RX_STATUS_BUSY (1 << 1)
#define RT2860_TX_STATUS_BUSY (1 << 0)
/* possible flags for register PWR_PIN_CFG */
#define RT2860_IO_ADDA_PD (1 << 3)
#define RT2860_IO_PLL_PD (1 << 2)
#define RT2860_IO_RA_PE (1 << 1)
#define RT2860_IO_RF_PE (1 << 0)
/* possible flags for register AUTO_WAKEUP_CFG */
#define RT2860_AUTO_WAKEUP_EN (1 << 15)
#define RT2860_SLEEP_TBTT_NUM_SHIFT 8
#define RT2860_WAKEUP_LEAD_TIME_SHIFT 0
/* possible flags for register TX_PIN_CFG */
#define RT2860_TRSW_POL (1 << 19)
#define RT2860_TRSW_EN (1 << 18)
#define RT2860_RFTR_POL (1 << 17)
#define RT2860_RFTR_EN (1 << 16)
#define RT2860_LNA_PE_G1_POL (1 << 15)
#define RT2860_LNA_PE_A1_POL (1 << 14)
#define RT2860_LNA_PE_G0_POL (1 << 13)
#define RT2860_LNA_PE_A0_POL (1 << 12)
#define RT2860_LNA_PE_G1_EN (1 << 11)
#define RT2860_LNA_PE_A1_EN (1 << 10)
#define RT2860_LNA_PE1_EN (RT2860_LNA_PE_A1_EN | RT2860_LNA_PE_G1_EN)
#define RT2860_LNA_PE_G0_EN (1 << 9)
#define RT2860_LNA_PE_A0_EN (1 << 8)
#define RT2860_LNA_PE0_EN (RT2860_LNA_PE_A0_EN | RT2860_LNA_PE_G0_EN)
#define RT2860_PA_PE_G1_POL (1 << 7)
#define RT2860_PA_PE_A1_POL (1 << 6)
#define RT2860_PA_PE_G0_POL (1 << 5)
#define RT2860_PA_PE_A0_POL (1 << 4)
#define RT2860_PA_PE_G1_EN (1 << 3)
#define RT2860_PA_PE_A1_EN (1 << 2)
#define RT2860_PA_PE_G0_EN (1 << 1)
#define RT2860_PA_PE_A0_EN (1 << 0)
/* possible flags for register TX_BAND_CFG */
#define RT2860_5G_BAND_SEL_N (1 << 2)
#define RT2860_5G_BAND_SEL_P (1 << 1)
#define RT2860_TX_BAND_SEL (1 << 0)
/* possible flags for register TX_SW_CFG0 */
#define RT2860_DLY_RFTR_EN_SHIFT 24
#define RT2860_DLY_TRSW_EN_SHIFT 16
#define RT2860_DLY_PAPE_EN_SHIFT 8
#define RT2860_DLY_TXPE_EN_SHIFT 0
/* possible flags for register TX_SW_CFG1 */
#define RT2860_DLY_RFTR_DIS_SHIFT 16
#define RT2860_DLY_TRSW_DIS_SHIFT 8
#define RT2860_DLY_PAPE_DIS SHIFT 0
/* possible flags for register TX_SW_CFG2 */
#define RT2860_DLY_LNA_EN_SHIFT 24
#define RT2860_DLY_LNA_DIS_SHIFT 16
#define RT2860_DLY_DAC_EN_SHIFT 8
#define RT2860_DLY_DAC_DIS_SHIFT 0
/* possible flags for register TXOP_THRES_CFG */
#define RT2860_TXOP_REM_THRES_SHIFT 24
#define RT2860_CF_END_THRES_SHIFT 16
#define RT2860_RDG_IN_THRES 8
#define RT2860_RDG_OUT_THRES 0
/* possible flags for register TXOP_CTRL_CFG */
#define RT2860_EXT_CW_MIN_SHIFT 16
#define RT2860_EXT_CCA_DLY_SHIFT 8
#define RT2860_EXT_CCA_EN (1 << 7)
#define RT2860_LSIG_TXOP_EN (1 << 6)
#define RT2860_TXOP_TRUN_EN_MIMOPS (1 << 4)
#define RT2860_TXOP_TRUN_EN_TXOP (1 << 3)
#define RT2860_TXOP_TRUN_EN_RATE (1 << 2)
#define RT2860_TXOP_TRUN_EN_AC (1 << 1)
#define RT2860_TXOP_TRUN_EN_TIMEOUT (1 << 0)
/* possible flags for register TX_RTS_CFG */
#define RT2860_RTS_FBK_EN (1 << 24)
#define RT2860_RTS_THRES_SHIFT 8
#define RT2860_RTS_RTY_LIMIT_SHIFT 0
/* possible flags for register TX_TIMEOUT_CFG */
#define RT2860_TXOP_TIMEOUT_SHIFT 16
#define RT2860_RX_ACK_TIMEOUT_SHIFT 8
#define RT2860_MPDU_LIFE_TIME_SHIFT 4
/* possible flags for register TX_RTY_CFG */
#define RT2860_TX_AUTOFB_EN (1 << 30)
#define RT2860_AGG_RTY_MODE_TIMER (1 << 29)
#define RT2860_NAG_RTY_MODE_TIMER (1 << 28)
#define RT2860_LONG_RTY_THRES_SHIFT 16
#define RT2860_LONG_RTY_LIMIT_SHIFT 8
#define RT2860_SHORT_RTY_LIMIT_SHIFT 0
/* possible flags for register TX_LINK_CFG */
#define RT2860_REMOTE_MFS_SHIFT 24
#define RT2860_REMOTE_MFB_SHIFT 16
#define RT2860_TX_CFACK_EN (1 << 12)
#define RT2860_TX_RDG_EN (1 << 11)
#define RT2860_TX_MRQ_EN (1 << 10)
#define RT2860_REMOTE_UMFS_EN (1 << 9)
#define RT2860_TX_MFB_EN (1 << 8)
#define RT2860_REMOTE_MFB_LT_SHIFT 0
/* possible flags for registers *_PROT_CFG */
#define RT2860_RTSTH_EN (1 << 26)
#define RT2860_TXOP_ALLOW_GF40 (1 << 25)
#define RT2860_TXOP_ALLOW_GF20 (1 << 24)
#define RT2860_TXOP_ALLOW_MM40 (1 << 23)
#define RT2860_TXOP_ALLOW_MM20 (1 << 22)
#define RT2860_TXOP_ALLOW_OFDM (1 << 21)
#define RT2860_TXOP_ALLOW_CCK (1 << 20)
#define RT2860_TXOP_ALLOW_ALL (0x3f << 20)
#define RT2860_PROT_NAV_SHORT (1 << 18)
#define RT2860_PROT_NAV_LONG (2 << 18)
#define RT2860_PROT_CTRL_RTS_CTS (1 << 16)
#define RT2860_PROT_CTRL_CTS (2 << 16)
/* possible flags for registers EXP_{CTS,ACK}_TIME */
#define RT2860_EXP_OFDM_TIME_SHIFT 16
#define RT2860_EXP_CCK_TIME_SHIFT 0
/* possible flags for register RX_FILTR_CFG */
#define RT2860_DROP_CTRL_RSV (1 << 16)
#define RT2860_DROP_BAR (1 << 15)
#define RT2860_DROP_BA (1 << 14)
#define RT2860_DROP_PSPOLL (1 << 13)
#define RT2860_DROP_RTS (1 << 12)
#define RT2860_DROP_CTS (1 << 11)
#define RT2860_DROP_ACK (1 << 10)
#define RT2860_DROP_CFEND (1 << 9)
#define RT2860_DROP_CFACK (1 << 8)
#define RT2860_DROP_DUPL (1 << 7)
#define RT2860_DROP_BC (1 << 6)
#define RT2860_DROP_MC (1 << 5)
#define RT2860_DROP_VER_ERR (1 << 4)
#define RT2860_DROP_NOT_MYBSS (1 << 3)
#define RT2860_DROP_UC_NOME (1 << 2)
#define RT2860_DROP_PHY_ERR (1 << 1)
#define RT2860_DROP_CRC_ERR (1 << 0)
/* possible flags for register AUTO_RSP_CFG */
#define RT2860_CTRL_PWR_BIT (1 << 7)
#define RT2860_BAC_ACK_POLICY (1 << 6)
#define RT2860_CCK_SHORT_EN (1 << 4)
#define RT2860_CTS_40M_REF_EN (1 << 3)
#define RT2860_CTS_40M_MODE_EN (1 << 2)
#define RT2860_BAC_ACKPOLICY_EN (1 << 1)
#define RT2860_AUTO_RSP_EN (1 << 0)
/* possible flags for register SIFS_COST_CFG */
#define RT2860_OFDM_SIFS_COST_SHIFT 8
#define RT2860_CCK_SIFS_COST_SHIFT 0
/* possible flags for register TXOP_HLDR_ET */
#define RT2860_TXOP_ETM1_EN (1 << 25)
#define RT2860_TXOP_ETM0_EN (1 << 24)
#define RT2860_TXOP_ETM_THRES_SHIFT 16
#define RT2860_TXOP_ETO_EN (1 << 8)
#define RT2860_TXOP_ETO_THRES_SHIFT 1
#define RT2860_PER_RX_RST_EN (1 << 0)
/* possible flags for register TX_STAT_FIFO */
#define RT2860_TXQ_MCS_SHIFT 16
#define RT2860_TXQ_WCID_SHIFT 8
#define RT2860_TXQ_ACKREQ (1 << 7)
#define RT2860_TXQ_AGG (1 << 6)
#define RT2860_TXQ_OK (1 << 5)
#define RT2860_TXQ_PID_SHIFT 1
#define RT2860_TXQ_VLD (1 << 0)
/* possible flags for register WCID_ATTR */
#define RT2860_MODE_NOSEC 0
#define RT2860_MODE_WEP40 1
#define RT2860_MODE_WEP104 2
#define RT2860_MODE_TKIP 3
#define RT2860_MODE_AES_CCMP 4
#define RT2860_MODE_CKIP40 5
#define RT2860_MODE_CKIP104 6
#define RT2860_MODE_CKIP128 7
#define RT2860_RX_PKEY_EN (1 << 0)
/* possible flags for register H2M_MAILBOX */
#define RT2860_H2M_BUSY (1 << 24)
#define RT2860_TOKEN_NO_INTR 0xff
/* possible flags for MCU command RT2860_MCU_CMD_LEDS */
#define RT2860_LED_RADIO (1 << 13)
#define RT2860_LED_LINK_2GHZ (1 << 14)
#define RT2860_LED_LINK_5GHZ (1 << 15)
/* possible flags for RT3020 RF register 1 */
#define RT3070_RF_BLOCK (1 << 0)
#define RT3070_PLL_PD (1 << 1)
#define RT3070_RX0_PD (1 << 2)
#define RT3070_TX0_PD (1 << 3)
#define RT3070_RX1_PD (1 << 4)
#define RT3070_TX1_PD (1 << 5)
#define RT3070_RX2_PD (1 << 6)
#define RT3070_TX2_PD (1 << 7)
/* possible flags for RT3020 RF register 15 */
#define RT3070_TX_LO2 (1 << 3)
/* possible flags for RT3020 RF register 17 */
#define RT3070_TX_LO1 (1 << 3)
/* possible flags for RT3020 RF register 20 */
#define RT3070_RX_LO1 (1 << 3)
/* possible flags for RT3020 RF register 21 */
#define RT3070_RX_LO2 (1 << 3)
/* possible flags for RT3053 RF register 18 */
#define RT3593_AUTOTUNE_BYPASS (1 << 6)
/* possible flags for RT3053 RF register 50 */
#define RT3593_TX_LO2 (1 << 4)
/* possible flags for RT3053 RF register 51 */
#define RT3593_TX_LO1 (1 << 4)
/* Possible flags for RT5390 RF register 2. */
#define RT5390_RESCAL (1 << 7)
/* Possible flags for RT5390 RF register 3. */
#define RT5390_VCOCAL (1 << 7)
/* Possible flags for RT5390 RF register 38. */
#define RT5390_RX_LO1 (1 << 5)
/* Possible flags for RT5390 RF register 39. */
#define RT5390_RX_LO2 (1 << 7)
/* Possible flags for RT5390 BBP register 4. */
#define RT5390_MAC_IF_CTRL (1 << 6)
/* Possible flags for RT5390 BBP register 105. */
#define RT5390_MLD (1 << 2)
#define RT5390_EN_SIG_MODULATION (1 << 3)
/* RT2860 TX descriptor */
struct rt2860_txd {
uint32_t sdp0; /* Segment Data Pointer 0 */
uint16_t sdl1; /* Segment Data Length 1 */
#define RT2860_TX_BURST (1 << 15)
#define RT2860_TX_LS1 (1 << 14) /* SDP1 is the last segment */
uint16_t sdl0; /* Segment Data Length 0 */
#define RT2860_TX_DDONE (1 << 15)
#define RT2860_TX_LS0 (1 << 14) /* SDP0 is the last segment */
uint32_t sdp1; /* Segment Data Pointer 1 */
uint8_t reserved[3];
uint8_t flags;
#define RT2860_TX_QSEL_SHIFT 1
#define RT2860_TX_QSEL_MGMT (0 << 1)
#define RT2860_TX_QSEL_HCCA (1 << 1)
#define RT2860_TX_QSEL_EDCA (2 << 1)
#define RT2860_TX_WIV (1 << 0)
} __packed;
/* RT2870 TX descriptor */
struct rt2870_txd {
uint16_t len;
uint8_t pad;
uint8_t flags;
} __packed;
/* TX Wireless Information */
struct rt2860_txwi {
uint8_t flags;
#define RT2860_TX_MPDU_DSITY_SHIFT 5
#define RT2860_TX_AMPDU (1 << 4)
#define RT2860_TX_TS (1 << 3)
#define RT2860_TX_CFACK (1 << 2)
#define RT2860_TX_MMPS (1 << 1)
#define RT2860_TX_FRAG (1 << 0)
uint8_t txop;
#define RT2860_TX_TXOP_HT 0
#define RT2860_TX_TXOP_PIFS 1
#define RT2860_TX_TXOP_SIFS 2
#define RT2860_TX_TXOP_BACKOFF 3
uint16_t phy;
#define RT2860_PHY_MODE 0xc000
#define RT2860_PHY_CCK (0 << 14)
#define RT2860_PHY_OFDM (1 << 14)
#define RT2860_PHY_HT (2 << 14)
#define RT2860_PHY_HT_GF (3 << 14)
#define RT2860_PHY_SGI (1 << 8)
#define RT2860_PHY_BW40 (1 << 7)
#define RT2860_PHY_MCS 0x7f
#define RT2860_PHY_SHPRE (1 << 3)
uint8_t xflags;
#define RT2860_TX_BAWINSIZE_SHIFT 2
#define RT2860_TX_NSEQ (1 << 1)
#define RT2860_TX_ACK (1 << 0)
uint8_t wcid; /* Wireless Client ID */
uint16_t len;
#define RT2860_TX_PID_SHIFT 12
uint32_t iv;
uint32_t eiv;
} __packed;
/* RT2860 RX descriptor */
struct rt2860_rxd {
uint32_t sdp0;
uint16_t sdl1; /* unused */
uint16_t sdl0;
#define RT2860_RX_DDONE (1 << 15)
#define RT2860_RX_LS0 (1 << 14)
uint32_t sdp1; /* unused */
uint32_t flags;
#define RT2860_RX_DEC (1 << 16)
#define RT2860_RX_AMPDU (1 << 15)
#define RT2860_RX_L2PAD (1 << 14)
#define RT2860_RX_RSSI (1 << 13)
#define RT2860_RX_HTC (1 << 12)
#define RT2860_RX_AMSDU (1 << 11)
#define RT2860_RX_MICERR (1 << 10)
#define RT2860_RX_ICVERR (1 << 9)
#define RT2860_RX_CRCERR (1 << 8)
#define RT2860_RX_MYBSS (1 << 7)
#define RT2860_RX_BC (1 << 6)
#define RT2860_RX_MC (1 << 5)
#define RT2860_RX_UC2ME (1 << 4)
#define RT2860_RX_FRAG (1 << 3)
#define RT2860_RX_NULL (1 << 2)
#define RT2860_RX_DATA (1 << 1)
#define RT2860_RX_BA (1 << 0)
} __packed;
/* RT2870 RX descriptor */
struct rt2870_rxd {
/* single 32-bit field */
uint32_t flags;
} __packed;
/* RX Wireless Information */
struct rt2860_rxwi {
uint8_t wcid;
uint8_t keyidx;
#define RT2860_RX_UDF_SHIFT 5
#define RT2860_RX_BSS_IDX_SHIFT 2
uint16_t len;
#define RT2860_RX_TID_SHIFT 12
uint16_t seq;
uint16_t phy;
uint8_t rssi[3];
uint8_t reserved1;
uint8_t snr[2];
uint16_t reserved2;
} __packed;
#define RT2860_RF_2820 0x0001 /* 2T3R */
#define RT2860_RF_2850 0x0002 /* dual-band 2T3R */
#define RT2860_RF_2720 0x0003 /* 1T2R */
#define RT2860_RF_2750 0x0004 /* dual-band 1T2R */
#define RT3070_RF_3020 0x0005 /* 1T1R */
#define RT3070_RF_2020 0x0006 /* b/g */
#define RT3070_RF_3021 0x0007 /* 1T2R */
#define RT3070_RF_3022 0x0008 /* 2T2R */
#define RT3070_RF_3052 0x0009 /* dual-band 2T2R */
#define RT3593_RF_3053 0x000d /* dual-band 3T3R */
#define RT5592_RF_5592 0x000f /* dual-band 2T2R */
#define RT5390_RF_5370 0x5370 /* 1T1R */
#define RT5390_RF_5372 0x5372 /* 2T2R */
/* USB commands for RT2870 only */
#define RT2870_RESET 1
#define RT2870_WRITE_2 2
#define RT2870_WRITE_REGION_1 6
#define RT2870_READ_REGION_1 7
#define RT2870_EEPROM_READ 9
#define RT2860_EEPROM_DELAY 1 /* minimum hold time (microsecond) */
#define RT2860_EEPROM_VERSION 0x01
#define RT2860_EEPROM_MAC01 0x02
#define RT2860_EEPROM_MAC23 0x03
#define RT2860_EEPROM_MAC45 0x04
#define RT2860_EEPROM_PCIE_PSLEVEL 0x11
#define RT2860_EEPROM_REV 0x12
#define RT2860_EEPROM_ANTENNA 0x1a
#define RT2860_EEPROM_CONFIG 0x1b
#define RT2860_EEPROM_COUNTRY 0x1c
#define RT2860_EEPROM_FREQ_LEDS 0x1d
#define RT2860_EEPROM_LED1 0x1e
#define RT2860_EEPROM_LED2 0x1f
#define RT2860_EEPROM_LED3 0x20
#define RT2860_EEPROM_LNA 0x22
#define RT2860_EEPROM_RSSI1_2GHZ 0x23
#define RT2860_EEPROM_RSSI2_2GHZ 0x24
#define RT2860_EEPROM_RSSI1_5GHZ 0x25
#define RT2860_EEPROM_RSSI2_5GHZ 0x26
#define RT2860_EEPROM_DELTAPWR 0x28
#define RT2860_EEPROM_PWR2GHZ_BASE1 0x29
#define RT2860_EEPROM_PWR2GHZ_BASE2 0x30
#define RT2860_EEPROM_TSSI1_2GHZ 0x37
#define RT2860_EEPROM_TSSI2_2GHZ 0x38
#define RT2860_EEPROM_TSSI3_2GHZ 0x39
#define RT2860_EEPROM_TSSI4_2GHZ 0x3a
#define RT2860_EEPROM_TSSI5_2GHZ 0x3b
#define RT2860_EEPROM_PWR5GHZ_BASE1 0x3c
#define RT2860_EEPROM_PWR5GHZ_BASE2 0x53
#define RT2860_EEPROM_TSSI1_5GHZ 0x6a
#define RT2860_EEPROM_TSSI2_5GHZ 0x6b
#define RT2860_EEPROM_TSSI3_5GHZ 0x6c
#define RT2860_EEPROM_TSSI4_5GHZ 0x6d
#define RT2860_EEPROM_TSSI5_5GHZ 0x6e
#define RT2860_EEPROM_RPWR 0x6f
#define RT2860_EEPROM_BBP_BASE 0x78
#define RT3071_EEPROM_RF_BASE 0x82
/* EEPROM registers for RT3593. */
#define RT3593_EEPROM_FREQ_LEDS 0x21
#define RT3593_EEPROM_FREQ 0x22
#define RT3593_EEPROM_LED1 0x22
#define RT3593_EEPROM_LED2 0x23
#define RT3593_EEPROM_LED3 0x24
#define RT3593_EEPROM_LNA 0x26
#define RT3593_EEPROM_LNA_5GHZ 0x27
#define RT3593_EEPROM_RSSI1_2GHZ 0x28
#define RT3593_EEPROM_RSSI2_2GHZ 0x29
#define RT3593_EEPROM_RSSI1_5GHZ 0x2a
#define RT3593_EEPROM_RSSI2_5GHZ 0x2b
#define RT3593_EEPROM_PWR2GHZ_BASE1 0x30
#define RT3593_EEPROM_PWR2GHZ_BASE2 0x37
#define RT3593_EEPROM_PWR2GHZ_BASE3 0x3e
#define RT3593_EEPROM_PWR5GHZ_BASE1 0x4b
#define RT3593_EEPROM_PWR5GHZ_BASE2 0x65
#define RT3593_EEPROM_PWR5GHZ_BASE3 0x7f
/*
* EEPROM IQ calibration.
*/
#define RT5390_EEPROM_IQ_GAIN_CAL_TX0_2GHZ 0x130
#define RT5390_EEPROM_IQ_PHASE_CAL_TX0_2GHZ 0x131
#define RT5390_EEPROM_IQ_GAIN_CAL_TX1_2GHZ 0x133
#define RT5390_EEPROM_IQ_PHASE_CAL_TX1_2GHZ 0x134
#define RT5390_EEPROM_RF_IQ_COMPENSATION_CTL 0x13c
#define RT5390_EEPROM_RF_IQ_IMBALANCE_COMPENSATION_CTL 0x13d
#define RT5390_EEPROM_IQ_GAIN_CAL_TX0_CH36_TO_CH64_5GHZ 0x144
#define RT5390_EEPROM_IQ_PHASE_CAL_TX0_CH36_TO_CH64_5GHZ 0x145
#define RT5390_EEPROM_IQ_GAIN_CAL_TX0_CH100_TO_CH138_5GHZ 0x146
#define RT5390_EEPROM_IQ_PHASE_CAL_TX0_CH100_TO_CH138_5GHZ 0x147
#define RT5390_EEPROM_IQ_GAIN_CAL_TX0_CH140_TO_CH165_5GHZ 0x148
#define RT5390_EEPROM_IQ_PHASE_CAL_TX0_CH140_TO_CH165_5GHZ 0x149
#define RT5390_EEPROM_IQ_GAIN_CAL_TX1_CH36_TO_CH64_5GHZ 0x14a
#define RT5390_EEPROM_IQ_PHASE_CAL_TX1_CH36_TO_CH64_5GHZ 0x14b
#define RT5390_EEPROM_IQ_GAIN_CAL_TX1_CH100_TO_CH138_5GHZ 0x14c
#define RT5390_EEPROM_IQ_PHASE_CAL_TX1_CH100_TO_CH138_5GHZ 0x14d
#define RT5390_EEPROM_IQ_GAIN_CAL_TX1_CH140_TO_CH165_5GHZ 0x14e
#define RT5390_EEPROM_IQ_PHASE_CAL_TX1_CH140_TO_CH165_5GHZ 0x14f
#define RT2860_RIDX_CCK1 0
#define RT2860_RIDX_CCK11 3
#define RT2860_RIDX_OFDM6 4
#define RT2860_RIDX_MAX 12
/*
* EEPROM access macro.
*/
#define RT2860_EEPROM_CTL(sc, val) do { \
RAL_WRITE((sc), RT2860_PCI_EECTRL, (val)); \
RAL_BARRIER_READ_WRITE((sc)); \
DELAY(RT2860_EEPROM_DELAY); \
} while (/* CONSTCOND */0)
/*
* Default values for MAC registers; values taken from the reference driver.
*/
#define RT2870_DEF_MAC \
{ RT2860_BCN_OFFSET0, 0xf8f0e8e0 }, \
{ RT2860_BCN_OFFSET1, 0x6f77d0c8 }, \
{ RT2860_LEGACY_BASIC_RATE, 0x0000013f }, \
{ RT2860_HT_BASIC_RATE, 0x00008003 }, \
{ RT2860_MAC_SYS_CTRL, 0x00000000 }, \
{ RT2860_BKOFF_SLOT_CFG, 0x00000209 }, \
{ RT2860_TX_SW_CFG0, 0x00000000 }, \
{ RT2860_TX_SW_CFG1, 0x00080606 }, \
{ RT2860_TX_LINK_CFG, 0x00001020 }, \
{ RT2860_TX_TIMEOUT_CFG, 0x000a2090 }, \
{ RT2860_MAX_LEN_CFG, 0x00001f00 }, \
{ RT2860_LED_CFG, 0x7f031e46 }, \
{ RT2860_WMM_AIFSN_CFG, 0x00002273 }, \
{ RT2860_WMM_CWMIN_CFG, 0x00002344 }, \
{ RT2860_WMM_CWMAX_CFG, 0x000034aa }, \
{ RT2860_MAX_PCNT, 0x1f3fbf9f }, \
{ RT2860_TX_RTY_CFG, 0x47d01f0f }, \
{ RT2860_AUTO_RSP_CFG, 0x00000013 }, \
{ RT2860_CCK_PROT_CFG, 0x05740003 }, \
{ RT2860_OFDM_PROT_CFG, 0x05740003 }, \
{ RT2860_PBF_CFG, 0x00f40006 }, \
{ RT2860_WPDMA_GLO_CFG, 0x00000030 }, \
{ RT2860_GF20_PROT_CFG, 0x01744004 }, \
{ RT2860_GF40_PROT_CFG, 0x03f44084 }, \
{ RT2860_MM20_PROT_CFG, 0x01744004 }, \
{ RT2860_MM40_PROT_CFG, 0x03f44084 }, \
{ RT2860_TXOP_CTRL_CFG, 0x0000583f }, \
{ RT2860_TXOP_HLDR_ET, 0x00000002 }, \
{ RT2860_TX_RTS_CFG, 0x00092b20 }, \
{ RT2860_EXP_ACK_TIME, 0x002400ca }, \
{ RT2860_XIFS_TIME_CFG, 0x33a41010 }, \
{ RT2860_PWR_PIN_CFG, 0x00000003 }
/*
* Default values for BBP registers; values taken from the reference driver.
*/
#define RT2860_DEF_BBP \
{ 65, 0x2c }, \
{ 66, 0x38 }, \
{ 68, 0x0b }, \
{ 69, 0x12 }, \
{ 70, 0x0a }, \
{ 73, 0x10 }, \
{ 81, 0x37 }, \
{ 82, 0x62 }, \
{ 83, 0x6a }, \
{ 84, 0x99 }, \
{ 86, 0x00 }, \
{ 91, 0x04 }, \
{ 92, 0x00 }, \
{ 103, 0x00 }, \
{ 105, 0x05 }, \
{ 106, 0x35 }
#define RT5390_DEF_BBP \
{ 31, 0x08 }, \
{ 65, 0x2c }, \
{ 66, 0x38 }, \
{ 68, 0x0b }, \
{ 69, 0x0d }, \
{ 70, 0x06 }, \
{ 73, 0x13 }, \
{ 75, 0x46 }, \
{ 76, 0x28 }, \
{ 77, 0x59 }, \
{ 81, 0x37 }, \
{ 82, 0x62 }, \
{ 83, 0x7a }, \
{ 84, 0x9a }, \
{ 86, 0x38 }, \
{ 91, 0x04 }, \
{ 92, 0x02 }, \
{ 103, 0xc0 }, \
{ 104, 0x92 }, \
{ 105, 0x3c }, \
{ 106, 0x03 }, \
{ 128, 0x12 }
#define RT5592_DEF_BBP \
{ 20, 0x06 }, \
{ 31, 0x08 }, \
{ 65, 0x2c }, \
{ 66, 0x38 }, \
{ 68, 0xdd }, \
{ 69, 0x1a }, \
{ 70, 0x05 }, \
{ 73, 0x13 }, \
{ 74, 0x0f }, \
{ 75, 0x4f }, \
{ 76, 0x28 }, \
{ 77, 0x59 }, \
{ 81, 0x37 }, \
{ 82, 0x62 }, \
{ 83, 0x6a }, \
{ 84, 0x9a }, \
{ 86, 0x38 }, \
{ 88, 0x90 }, \
{ 91, 0x04 }, \
{ 92, 0x02 }, \
{ 95, 0x9a }, \
{ 98, 0x12 }, \
{ 103, 0xc0 }, \
{ 104, 0x92 }, \
{ 105, 0x3c }, \
{ 106, 0x35 }, \
{ 128, 0x12 }, \
{ 134, 0xd0 }, \
{ 135, 0xf6 }, \
{ 137, 0x0f }
/*
* Channel map for run(4) driver; taken from the table below.
*/
static const uint8_t run_chan_2ghz[] =
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };
static const uint8_t run_chan_5ghz[] =
{ 36, 38, 40, 44, 46, 48, 52, 54, 56, 60, 62, 64, 100, 102, 104,
108, 110, 112, 116, 118, 120, 124, 126, 128, 132, 134, 136, 140,
149, 151, 153, 157, 159, 161, 165, 167, 169, 171, 173,
184, 188, 192, 196, 208, 212, 216 };
/*
* Default settings for RF registers; values derived from the reference driver.
*/
#define RT2860_RF2850 \
{ 1, 0x98402ecc, 0x984c0786, 0x9816b455, 0x9800510b }, \
{ 2, 0x98402ecc, 0x984c0786, 0x98168a55, 0x9800519f }, \
{ 3, 0x98402ecc, 0x984c078a, 0x98168a55, 0x9800518b }, \
{ 4, 0x98402ecc, 0x984c078a, 0x98168a55, 0x9800519f }, \
{ 5, 0x98402ecc, 0x984c078e, 0x98168a55, 0x9800518b }, \
{ 6, 0x98402ecc, 0x984c078e, 0x98168a55, 0x9800519f }, \
{ 7, 0x98402ecc, 0x984c0792, 0x98168a55, 0x9800518b }, \
{ 8, 0x98402ecc, 0x984c0792, 0x98168a55, 0x9800519f }, \
{ 9, 0x98402ecc, 0x984c0796, 0x98168a55, 0x9800518b }, \
{ 10, 0x98402ecc, 0x984c0796, 0x98168a55, 0x9800519f }, \
{ 11, 0x98402ecc, 0x984c079a, 0x98168a55, 0x9800518b }, \
{ 12, 0x98402ecc, 0x984c079a, 0x98168a55, 0x9800519f }, \
{ 13, 0x98402ecc, 0x984c079e, 0x98168a55, 0x9800518b }, \
{ 14, 0x98402ecc, 0x984c07a2, 0x98168a55, 0x98005193 }, \
{ 36, 0x98402ecc, 0x984c099a, 0x98158a55, 0x980ed1a3 }, \
{ 38, 0x98402ecc, 0x984c099e, 0x98158a55, 0x980ed193 }, \
{ 40, 0x98402ec8, 0x984c0682, 0x98158a55, 0x980ed183 }, \
{ 44, 0x98402ec8, 0x984c0682, 0x98158a55, 0x980ed1a3 }, \
{ 46, 0x98402ec8, 0x984c0686, 0x98158a55, 0x980ed18b }, \
{ 48, 0x98402ec8, 0x984c0686, 0x98158a55, 0x980ed19b }, \
{ 52, 0x98402ec8, 0x984c068a, 0x98158a55, 0x980ed193 }, \
{ 54, 0x98402ec8, 0x984c068a, 0x98158a55, 0x980ed1a3 }, \
{ 56, 0x98402ec8, 0x984c068e, 0x98158a55, 0x980ed18b }, \
{ 60, 0x98402ec8, 0x984c0692, 0x98158a55, 0x980ed183 }, \
{ 62, 0x98402ec8, 0x984c0692, 0x98158a55, 0x980ed193 }, \
{ 64, 0x98402ec8, 0x984c0692, 0x98158a55, 0x980ed1a3 }, \
{ 100, 0x98402ec8, 0x984c06b2, 0x98178a55, 0x980ed783 }, \
{ 102, 0x98402ec8, 0x985c06b2, 0x98578a55, 0x980ed793 }, \
{ 104, 0x98402ec8, 0x985c06b2, 0x98578a55, 0x980ed1a3 }, \
{ 108, 0x98402ecc, 0x985c0a32, 0x98578a55, 0x980ed193 }, \
{ 110, 0x98402ecc, 0x984c0a36, 0x98178a55, 0x980ed183 }, \
{ 112, 0x98402ecc, 0x984c0a36, 0x98178a55, 0x980ed19b }, \
{ 116, 0x98402ecc, 0x984c0a3a, 0x98178a55, 0x980ed1a3 }, \
{ 118, 0x98402ecc, 0x984c0a3e, 0x98178a55, 0x980ed193 }, \
{ 120, 0x98402ec4, 0x984c0382, 0x98178a55, 0x980ed183 }, \
{ 124, 0x98402ec4, 0x984c0382, 0x98178a55, 0x980ed193 }, \
{ 126, 0x98402ec4, 0x984c0382, 0x98178a55, 0x980ed15b }, \
{ 128, 0x98402ec4, 0x984c0382, 0x98178a55, 0x980ed1a3 }, \
{ 132, 0x98402ec4, 0x984c0386, 0x98178a55, 0x980ed18b }, \
{ 134, 0x98402ec4, 0x984c0386, 0x98178a55, 0x980ed193 }, \
{ 136, 0x98402ec4, 0x984c0386, 0x98178a55, 0x980ed19b }, \
{ 140, 0x98402ec4, 0x984c038a, 0x98178a55, 0x980ed183 }, \
{ 149, 0x98402ec4, 0x984c038a, 0x98178a55, 0x980ed1a7 }, \
{ 151, 0x98402ec4, 0x984c038e, 0x98178a55, 0x980ed187 }, \
{ 153, 0x98402ec4, 0x984c038e, 0x98178a55, 0x980ed18f }, \
{ 157, 0x98402ec4, 0x984c038e, 0x98178a55, 0x980ed19f }, \
{ 159, 0x98402ec4, 0x984c038e, 0x98178a55, 0x980ed1a7 }, \
{ 161, 0x98402ec4, 0x984c0392, 0x98178a55, 0x980ed187 }, \
{ 165, 0x98402ec4, 0x984c0392, 0x98178a55, 0x980ed197 }, \
{ 167, 0x98402ec4, 0x984c03d2, 0x98179855, 0x9815531f }, \
{ 169, 0x98402ec4, 0x984c03d2, 0x98179855, 0x98155327 }, \
{ 171, 0x98402ec4, 0x984c03d6, 0x98179855, 0x98155307 }, \
{ 173, 0x98402ec4, 0x984c03d6, 0x98179855, 0x9815530f }, \
{ 184, 0x95002ccc, 0x9500491e, 0x9509be55, 0x950c0a0b }, \
{ 188, 0x95002ccc, 0x95004922, 0x9509be55, 0x950c0a13 }, \
{ 192, 0x95002ccc, 0x95004926, 0x9509be55, 0x950c0a1b }, \
{ 196, 0x95002ccc, 0x9500492a, 0x9509be55, 0x950c0a23 }, \
{ 208, 0x95002ccc, 0x9500493a, 0x9509be55, 0x950c0a13 }, \
{ 212, 0x95002ccc, 0x9500493e, 0x9509be55, 0x950c0a1b }, \
{ 216, 0x95002ccc, 0x95004982, 0x9509be55, 0x950c0a23 }
#define RT3070_RF3052 \
{ 0xf1, 2, 2 }, \
{ 0xf1, 2, 7 }, \
{ 0xf2, 2, 2 }, \
{ 0xf2, 2, 7 }, \
{ 0xf3, 2, 2 }, \
{ 0xf3, 2, 7 }, \
{ 0xf4, 2, 2 }, \
{ 0xf4, 2, 7 }, \
{ 0xf5, 2, 2 }, \
{ 0xf5, 2, 7 }, \
{ 0xf6, 2, 2 }, \
{ 0xf6, 2, 7 }, \
{ 0xf7, 2, 2 }, \
{ 0xf8, 2, 4 }, \
{ 0x56, 0, 4 }, \
{ 0x56, 0, 6 }, \
{ 0x56, 0, 8 }, \
{ 0x57, 0, 0 }, \
{ 0x57, 0, 2 }, \
{ 0x57, 0, 4 }, \
{ 0x57, 0, 8 }, \
{ 0x57, 0, 10 }, \
{ 0x58, 0, 0 }, \
{ 0x58, 0, 4 }, \
{ 0x58, 0, 6 }, \
{ 0x58, 0, 8 }, \
{ 0x5b, 0, 8 }, \
{ 0x5b, 0, 10 }, \
{ 0x5c, 0, 0 }, \
{ 0x5c, 0, 4 }, \
{ 0x5c, 0, 6 }, \
{ 0x5c, 0, 8 }, \
{ 0x5d, 0, 0 }, \
{ 0x5d, 0, 2 }, \
{ 0x5d, 0, 4 }, \
{ 0x5d, 0, 8 }, \
{ 0x5d, 0, 10 }, \
{ 0x5e, 0, 0 }, \
{ 0x5e, 0, 4 }, \
{ 0x5e, 0, 6 }, \
{ 0x5e, 0, 8 }, \
{ 0x5f, 0, 0 }, \
{ 0x5f, 0, 9 }, \
{ 0x5f, 0, 11 }, \
{ 0x60, 0, 1 }, \
{ 0x60, 0, 5 }, \
{ 0x60, 0, 7 }, \
{ 0x60, 0, 9 }, \
{ 0x61, 0, 1 }, \
{ 0x61, 0, 3 }, \
{ 0x61, 0, 5 }, \
{ 0x61, 0, 7 }, \
{ 0x61, 0, 9 }
#define RT5592_RF5592_20MHZ \
{ 0x1e2, 4, 10, 3 }, \
{ 0x1e3, 4, 10, 3 }, \
{ 0x1e4, 4, 10, 3 }, \
{ 0x1e5, 4, 10, 3 }, \
{ 0x1e6, 4, 10, 3 }, \
{ 0x1e7, 4, 10, 3 }, \
{ 0x1e8, 4, 10, 3 }, \
{ 0x1e9, 4, 10, 3 }, \
{ 0x1ea, 4, 10, 3 }, \
{ 0x1eb, 4, 10, 3 }, \
{ 0x1ec, 4, 10, 3 }, \
{ 0x1ed, 4, 10, 3 }, \
{ 0x1ee, 4, 10, 3 }, \
{ 0x1f0, 8, 10, 3 }, \
{ 0xac, 8, 12, 1 }, \
{ 0xad, 0, 12, 1 }, \
{ 0xad, 4, 12, 1 }, \
{ 0xae, 0, 12, 1 }, \
{ 0xae, 4, 12, 1 }, \
{ 0xae, 8, 12, 1 }, \
{ 0xaf, 4, 12, 1 }, \
{ 0xaf, 8, 12, 1 }, \
{ 0xb0, 0, 12, 1 }, \
{ 0xb0, 8, 12, 1 }, \
{ 0xb1, 0, 12, 1 }, \
{ 0xb1, 4, 12, 1 }, \
{ 0xb7, 4, 12, 1 }, \
{ 0xb7, 8, 12, 1 }, \
{ 0xb8, 0, 12, 1 }, \
{ 0xb8, 8, 12, 1 }, \
{ 0xb9, 0, 12, 1 }, \
{ 0xb9, 4, 12, 1 }, \
{ 0xba, 0, 12, 1 }, \
{ 0xba, 4, 12, 1 }, \
{ 0xba, 8, 12, 1 }, \
{ 0xbb, 4, 12, 1 }, \
{ 0xbb, 8, 12, 1 }, \
{ 0xbc, 0, 12, 1 }, \
{ 0xbc, 8, 12, 1 }, \
{ 0xbd, 0, 12, 1 }, \
{ 0xbd, 4, 12, 1 }, \
{ 0xbe, 0, 12, 1 }, \
{ 0xbf, 6, 12, 1 }, \
{ 0xbf, 10, 12, 1 }, \
{ 0xc0, 2, 12, 1 }, \
{ 0xc0, 10, 12, 1 }, \
{ 0xc1, 2, 12, 1 }, \
{ 0xc1, 6, 12, 1 }, \
{ 0xc2, 2, 12, 1 }, \
{ 0xa4, 0, 12, 1 }, \
{ 0xa4, 4, 12, 1 }, \
{ 0xa5, 8, 12, 1 }, \
{ 0xa6, 0, 12, 1 }
#define RT5592_RF5592_40MHZ \
{ 0xf1, 2, 10, 3 }, \
{ 0xf1, 7, 10, 3 }, \
{ 0xf2, 2, 10, 3 }, \
{ 0xf2, 7, 10, 3 }, \
{ 0xf3, 2, 10, 3 }, \
{ 0xf3, 7, 10, 3 }, \
{ 0xf4, 2, 10, 3 }, \
{ 0xf4, 7, 10, 3 }, \
{ 0xf5, 2, 10, 3 }, \
{ 0xf5, 7, 10, 3 }, \
{ 0xf6, 2, 10, 3 }, \
{ 0xf6, 7, 10, 3 }, \
{ 0xf7, 2, 10, 3 }, \
{ 0xf8, 4, 10, 3 }, \
{ 0x56, 4, 12, 1 }, \
{ 0x56, 6, 12, 1 }, \
{ 0x56, 8, 12, 1 }, \
{ 0x57, 0, 12, 1 }, \
{ 0x57, 2, 12, 1 }, \
{ 0x57, 4, 12, 1 }, \
{ 0x57, 8, 12, 1 }, \
{ 0x57, 10, 12, 1 }, \
{ 0x58, 0, 12, 1 }, \
{ 0x58, 4, 12, 1 }, \
{ 0x58, 6, 12, 1 }, \
{ 0x58, 8, 12, 1 }, \
{ 0x5b, 8, 12, 1 }, \
{ 0x5b, 10, 12, 1 }, \
{ 0x5c, 0, 12, 1 }, \
{ 0x5c, 4, 12, 1 }, \
{ 0x5c, 6, 12, 1 }, \
{ 0x5c, 8, 12, 1 }, \
{ 0x5d, 0, 12, 1 }, \
{ 0x5d, 2, 12, 1 }, \
{ 0x5d, 4, 12, 1 }, \
{ 0x5d, 8, 12, 1 }, \
{ 0x5d, 10, 12, 1 }, \
{ 0x5e, 0, 12, 1 }, \
{ 0x5e, 4, 12, 1 }, \
{ 0x5e, 6, 12, 1 }, \
{ 0x5e, 8, 12, 1 }, \
{ 0x5f, 0, 12, 1 }, \
{ 0x5f, 9, 12, 1 }, \
{ 0x5f, 11, 12, 1 }, \
{ 0x60, 1, 12, 1 }, \
{ 0x60, 5, 12, 1 }, \
{ 0x60, 7, 12, 1 }, \
{ 0x60, 9, 12, 1 }, \
{ 0x61, 1, 12, 1 }, \
{ 0x52, 0, 12, 1 }, \
{ 0x52, 4, 12, 1 }, \
{ 0x52, 8, 12, 1 }, \
{ 0x53, 0, 12, 1 }
#define RT3070_DEF_RF \
{ 4, 0x40 }, \
{ 5, 0x03 }, \
{ 6, 0x02 }, \
{ 7, 0x60 }, \
{ 9, 0x0f }, \
{ 10, 0x41 }, \
{ 11, 0x21 }, \
{ 12, 0x7b }, \
{ 14, 0x90 }, \
{ 15, 0x58 }, \
{ 16, 0xb3 }, \
{ 17, 0x92 }, \
{ 18, 0x2c }, \
{ 19, 0x02 }, \
{ 20, 0xba }, \
{ 21, 0xdb }, \
{ 24, 0x16 }, \
{ 25, 0x03 }, \
{ 29, 0x1f }
#define RT3572_DEF_RF \
{ 0, 0x70 }, \
{ 1, 0x81 }, \
{ 2, 0xf1 }, \
{ 3, 0x02 }, \
{ 4, 0x4c }, \
{ 5, 0x05 }, \
{ 6, 0x4a }, \
{ 7, 0xd8 }, \
{ 9, 0xc3 }, \
{ 10, 0xf1 }, \
{ 11, 0xb9 }, \
{ 12, 0x70 }, \
{ 13, 0x65 }, \
{ 14, 0xa0 }, \
{ 15, 0x53 }, \
{ 16, 0x4c }, \
{ 17, 0x23 }, \
{ 18, 0xac }, \
{ 19, 0x93 }, \
{ 20, 0xb3 }, \
{ 21, 0xd0 }, \
{ 22, 0x00 }, \
{ 23, 0x3c }, \
{ 24, 0x16 }, \
{ 25, 0x15 }, \
{ 26, 0x85 }, \
{ 27, 0x00 }, \
{ 28, 0x00 }, \
{ 29, 0x9b }, \
{ 30, 0x09 }, \
{ 31, 0x10 }
#define RT3593_DEF_RF \
{ 1, 0x03 }, \
{ 3, 0x80 }, \
{ 5, 0x00 }, \
{ 6, 0x40 }, \
{ 8, 0xf1 }, \
{ 9, 0x02 }, \
{ 10, 0xd3 }, \
{ 11, 0x40 }, \
{ 12, 0x4e }, \
{ 13, 0x12 }, \
{ 18, 0x40 }, \
{ 22, 0x20 }, \
{ 30, 0x10 }, \
{ 31, 0x80 }, \
{ 32, 0x78 }, \
{ 33, 0x3b }, \
{ 34, 0x3c }, \
{ 35, 0xe0 }, \
{ 38, 0x86 }, \
{ 39, 0x23 }, \
{ 44, 0xd3 }, \
{ 45, 0xbb }, \
{ 46, 0x60 }, \
{ 49, 0x81 }, \
{ 50, 0x86 }, \
{ 51, 0x75 }, \
{ 52, 0x45 }, \
{ 53, 0x18 }, \
{ 54, 0x18 }, \
{ 55, 0x18 }, \
{ 56, 0xdb }, \
{ 57, 0x6e }
#define RT5390_DEF_RF \
{ 1, 0x0f }, \
{ 2, 0x80 }, \
{ 3, 0x88 }, \
{ 5, 0x10 }, \
{ 6, 0xa0 }, \
{ 7, 0x00 }, \
{ 10, 0x53 }, \
{ 11, 0x4a }, \
{ 12, 0x46 }, \
{ 13, 0x9f }, \
{ 14, 0x00 }, \
{ 15, 0x00 }, \
{ 16, 0x00 }, \
{ 18, 0x03 }, \
{ 19, 0x00 }, \
{ 20, 0x00 }, \
{ 21, 0x00 }, \
{ 22, 0x20 }, \
{ 23, 0x00 }, \
{ 24, 0x00 }, \
{ 25, 0xc0 }, \
{ 26, 0x00 }, \
{ 27, 0x09 }, \
{ 28, 0x00 }, \
{ 29, 0x10 }, \
{ 30, 0x10 }, \
{ 31, 0x80 }, \
{ 32, 0x80 }, \
{ 33, 0x00 }, \
{ 34, 0x07 }, \
{ 35, 0x12 }, \
{ 36, 0x00 }, \
{ 37, 0x08 }, \
{ 38, 0x85 }, \
{ 39, 0x1b }, \
{ 40, 0x0b }, \
{ 41, 0xbb }, \
{ 42, 0xd2 }, \
{ 43, 0x9a }, \
{ 44, 0x0e }, \
{ 45, 0xa2 }, \
{ 46, 0x7b }, \
{ 47, 0x00 }, \
{ 48, 0x10 }, \
{ 49, 0x94 }, \
{ 52, 0x38 }, \
{ 53, 0x84 }, \
{ 54, 0x78 }, \
{ 55, 0x44 }, \
{ 56, 0x22 }, \
{ 57, 0x80 }, \
{ 58, 0x7f }, \
{ 59, 0x8f }, \
{ 60, 0x45 }, \
{ 61, 0xdd }, \
{ 62, 0x00 }, \
{ 63, 0x00 }
#define RT5392_DEF_RF \
{ 1, 0x17 }, \
{ 3, 0x88 }, \
{ 5, 0x10 }, \
{ 6, 0xe0 }, \
{ 7, 0x00 }, \
{ 10, 0x53 }, \
{ 11, 0x4a }, \
{ 12, 0x46 }, \
{ 13, 0x9f }, \
{ 14, 0x00 }, \
{ 15, 0x00 }, \
{ 16, 0x00 }, \
{ 18, 0x03 }, \
{ 19, 0x4d }, \
{ 20, 0x00 }, \
{ 21, 0x8d }, \
{ 22, 0x20 }, \
{ 23, 0x0b }, \
{ 24, 0x44 }, \
{ 25, 0x80 }, \
{ 26, 0x82 }, \
{ 27, 0x09 }, \
{ 28, 0x00 }, \
{ 29, 0x10 }, \
{ 30, 0x10 }, \
{ 31, 0x80 }, \
{ 32, 0x20 }, \
{ 33, 0xc0 }, \
{ 34, 0x07 }, \
{ 35, 0x12 }, \
{ 36, 0x00 }, \
{ 37, 0x08 }, \
{ 38, 0x89 }, \
{ 39, 0x1b }, \
{ 40, 0x0f }, \
{ 41, 0xbb }, \
{ 42, 0xd5 }, \
{ 43, 0x9b }, \
{ 44, 0x0e }, \
{ 45, 0xa2 }, \
{ 46, 0x73 }, \
{ 47, 0x0c }, \
{ 48, 0x10 }, \
{ 49, 0x94 }, \
{ 50, 0x94 }, \
{ 51, 0x3a }, \
{ 52, 0x48 }, \
{ 53, 0x44 }, \
{ 54, 0x38 }, \
{ 55, 0x43 }, \
{ 56, 0xa1 }, \
{ 57, 0x00 }, \
{ 58, 0x39 }, \
{ 59, 0x07 }, \
{ 60, 0x45 }, \
{ 61, 0x91 }, \
{ 62, 0x39 }, \
{ 63, 0x07 }
#define RT5592_DEF_RF \
{ 1, 0x3f }, \
{ 3, 0x08 }, \
{ 5, 0x10 }, \
{ 6, 0xe4 }, \
{ 7, 0x00 }, \
{ 14, 0x00 }, \
{ 15, 0x00 }, \
{ 16, 0x00 }, \
{ 18, 0x03 }, \
{ 19, 0x4d }, \
{ 20, 0x10 }, \
{ 21, 0x8d }, \
{ 26, 0x82 }, \
{ 28, 0x00 }, \
{ 29, 0x10 }, \
{ 33, 0xc0 }, \
{ 34, 0x07 }, \
{ 35, 0x12 }, \
{ 47, 0x0c }, \
{ 53, 0x22 }, \
{ 63, 0x07 }
#define RT5592_2GHZ_DEF_RF \
{ 10, 0x90 }, \
{ 11, 0x4a }, \
{ 12, 0x52 }, \
{ 13, 0x42 }, \
{ 22, 0x40 }, \
{ 24, 0x4a }, \
{ 25, 0x80 }, \
{ 27, 0x42 }, \
{ 36, 0x80 }, \
{ 37, 0x08 }, \
{ 38, 0x89 }, \
{ 39, 0x1b }, \
{ 40, 0x0d }, \
{ 41, 0x9b }, \
{ 42, 0xd5 }, \
{ 43, 0x72 }, \
{ 44, 0x0e }, \
{ 45, 0xa2 }, \
{ 46, 0x6b }, \
{ 48, 0x10 }, \
{ 51, 0x3e }, \
{ 52, 0x48 }, \
{ 54, 0x38 }, \
{ 56, 0xa1 }, \
{ 57, 0x00 }, \
{ 58, 0x39 }, \
{ 60, 0x45 }, \
{ 61, 0x91 }, \
{ 62, 0x39 }
#define RT5592_5GHZ_DEF_RF \
{ 10, 0x97 }, \
{ 11, 0x40 }, \
{ 25, 0xbf }, \
{ 27, 0x42 }, \
{ 36, 0x00 }, \
{ 37, 0x04 }, \
{ 38, 0x85 }, \
{ 40, 0x42 }, \
{ 41, 0xbb }, \
{ 42, 0xd7 }, \
{ 45, 0x41 }, \
{ 48, 0x00 }, \
{ 57, 0x77 }, \
{ 60, 0x05 }, \
{ 61, 0x01 }
#define RT5592_CHAN_5GHZ \
{ 36, 64, 12, 0x2e }, \
{ 100, 165, 12, 0x0e }, \
{ 36, 64, 13, 0x22 }, \
{ 100, 165, 13, 0x42 }, \
{ 36, 64, 22, 0x60 }, \
{ 100, 165, 22, 0x40 }, \
{ 36, 64, 23, 0x7f }, \
{ 100, 153, 23, 0x3c }, \
{ 155, 165, 23, 0x38 }, \
{ 36, 50, 24, 0x09 }, \
{ 52, 64, 24, 0x07 }, \
{ 100, 153, 24, 0x06 }, \
{ 155, 165, 24, 0x05 }, \
{ 36, 64, 39, 0x1c }, \
{ 100, 138, 39, 0x1a }, \
{ 140, 165, 39, 0x18 }, \
{ 36, 64, 43, 0x5b }, \
{ 100, 138, 43, 0x3b }, \
{ 140, 165, 43, 0x1b }, \
{ 36, 64, 44, 0x40 }, \
{ 100, 138, 44, 0x20 }, \
{ 140, 165, 44, 0x10 }, \
{ 36, 64, 46, 0x00 }, \
{ 100, 138, 46, 0x18 }, \
{ 140, 165, 46, 0x08 }, \
{ 36, 64, 51, 0xfe }, \
{ 100, 124, 51, 0xfc }, \
{ 126, 165, 51, 0xec }, \
{ 36, 64, 52, 0x0c }, \
{ 100, 138, 52, 0x06 }, \
{ 140, 165, 52, 0x06 }, \
{ 36, 64, 54, 0xf8 }, \
{ 100, 165, 54, 0xeb }, \
{ 36, 50, 55, 0x06 }, \
{ 52, 64, 55, 0x04 }, \
{ 100, 138, 55, 0x01 }, \
{ 140, 165, 55, 0x00 }, \
{ 36, 50, 56, 0xd3 }, \
{ 52, 128, 56, 0xbb }, \
{ 130, 165, 56, 0xab }, \
{ 36, 64, 58, 0x15 }, \
{ 100, 116, 58, 0x1d }, \
{ 118, 165, 58, 0x15 }, \
{ 36, 64, 59, 0x7f }, \
{ 100, 138, 59, 0x3f }, \
{ 140, 165, 59, 0x7c }, \
{ 36, 64, 62, 0x15 }, \
{ 100, 116, 62, 0x1d }, \
{ 118, 165, 62, 0x15 }
union run_stats {
uint32_t raw;
struct {
uint16_t fail;
uint16_t pad;
} error;
struct {
uint16_t success;
uint16_t retry;
} tx;
} __aligned(4);
#endif /* _IF_RUNREG_H_ */
| eriknstr/ThinkPad-FreeBSD-setup | FreeBSD/sys/dev/usb/wlan/if_runreg.h | C | isc | 48,436 |
/*-
* Copyright 2008 Nathan Whitehorn. All rights reserved.
* Copyright 2003 by Peter Grehan. All rights reserved.
* Copyright (C) 1998, 1999, 2000 Tsubai Masanari. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* From:
* NetBSD: if_bm.c,v 1.9.2.1 2000/11/01 15:02:49 tv Exp
*/
/*
* BMAC/BMAC+ Macio cell 10/100 ethernet driver
* The low-cost, low-feature Apple variant of the Sun HME
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/sockio.h>
#include <sys/endian.h>
#include <sys/mbuf.h>
#include <sys/module.h>
#include <sys/malloc.h>
#include <sys/kernel.h>
#include <sys/socket.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_var.h>
#include <net/if_arp.h>
#include <net/ethernet.h>
#include <net/if_dl.h>
#include <net/if_media.h>
#include <net/if_types.h>
#include <machine/pio.h>
#include <machine/bus.h>
#include <machine/resource.h>
#include <sys/bus.h>
#include <sys/rman.h>
#include <dev/mii/mii.h>
#include <dev/mii/mii_bitbang.h>
#include <dev/mii/miivar.h>
#include <dev/ofw/ofw_bus.h>
#include <dev/ofw/openfirm.h>
#include <machine/dbdma.h>
MODULE_DEPEND(bm, ether, 1, 1, 1);
MODULE_DEPEND(bm, miibus, 1, 1, 1);
/* "controller miibus0" required. See GENERIC if you get errors here. */
#include "miibus_if.h"
#include "if_bmreg.h"
#include "if_bmvar.h"
static int bm_probe (device_t);
static int bm_attach (device_t);
static int bm_detach (device_t);
static int bm_shutdown (device_t);
static void bm_start (struct ifnet *);
static void bm_start_locked (struct ifnet *);
static int bm_encap (struct bm_softc *sc, struct mbuf **m_head);
static int bm_ioctl (struct ifnet *, u_long, caddr_t);
static void bm_init (void *);
static void bm_init_locked (struct bm_softc *sc);
static void bm_chip_setup (struct bm_softc *sc);
static void bm_stop (struct bm_softc *sc);
static void bm_setladrf (struct bm_softc *sc);
static void bm_dummypacket (struct bm_softc *sc);
static void bm_txintr (void *xsc);
static void bm_rxintr (void *xsc);
static int bm_add_rxbuf (struct bm_softc *sc, int i);
static int bm_add_rxbuf_dma (struct bm_softc *sc, int i);
static void bm_enable_interrupts (struct bm_softc *sc);
static void bm_disable_interrupts (struct bm_softc *sc);
static void bm_tick (void *xsc);
static int bm_ifmedia_upd (struct ifnet *);
static void bm_ifmedia_sts (struct ifnet *, struct ifmediareq *);
static int bm_miibus_readreg (device_t, int, int);
static int bm_miibus_writereg (device_t, int, int, int);
static void bm_miibus_statchg (device_t);
/*
* MII bit-bang glue
*/
static uint32_t bm_mii_bitbang_read(device_t);
static void bm_mii_bitbang_write(device_t, uint32_t);
static const struct mii_bitbang_ops bm_mii_bitbang_ops = {
bm_mii_bitbang_read,
bm_mii_bitbang_write,
{
BM_MII_DATAOUT, /* MII_BIT_MDO */
BM_MII_DATAIN, /* MII_BIT_MDI */
BM_MII_CLK, /* MII_BIT_MDC */
BM_MII_OENABLE, /* MII_BIT_DIR_HOST_PHY */
0, /* MII_BIT_DIR_PHY_HOST */
}
};
static device_method_t bm_methods[] = {
/* Device interface */
DEVMETHOD(device_probe, bm_probe),
DEVMETHOD(device_attach, bm_attach),
DEVMETHOD(device_detach, bm_detach),
DEVMETHOD(device_shutdown, bm_shutdown),
/* MII interface */
DEVMETHOD(miibus_readreg, bm_miibus_readreg),
DEVMETHOD(miibus_writereg, bm_miibus_writereg),
DEVMETHOD(miibus_statchg, bm_miibus_statchg),
DEVMETHOD_END
};
static driver_t bm_macio_driver = {
"bm",
bm_methods,
sizeof(struct bm_softc)
};
static devclass_t bm_devclass;
DRIVER_MODULE(bm, macio, bm_macio_driver, bm_devclass, 0, 0);
DRIVER_MODULE(miibus, bm, miibus_driver, miibus_devclass, 0, 0);
/*
* MII internal routines
*/
/*
* Write the MII serial port for the MII bit-bang module.
*/
static void
bm_mii_bitbang_write(device_t dev, uint32_t val)
{
struct bm_softc *sc;
sc = device_get_softc(dev);
CSR_WRITE_2(sc, BM_MII_CSR, val);
CSR_BARRIER(sc, BM_MII_CSR, 2,
BUS_SPACE_BARRIER_READ | BUS_SPACE_BARRIER_WRITE);
}
/*
* Read the MII serial port for the MII bit-bang module.
*/
static uint32_t
bm_mii_bitbang_read(device_t dev)
{
struct bm_softc *sc;
uint32_t reg;
sc = device_get_softc(dev);
reg = CSR_READ_2(sc, BM_MII_CSR);
CSR_BARRIER(sc, BM_MII_CSR, 2,
BUS_SPACE_BARRIER_READ | BUS_SPACE_BARRIER_WRITE);
return (reg);
}
/*
* MII bus i/f
*/
static int
bm_miibus_readreg(device_t dev, int phy, int reg)
{
return (mii_bitbang_readreg(dev, &bm_mii_bitbang_ops, phy, reg));
}
static int
bm_miibus_writereg(device_t dev, int phy, int reg, int data)
{
mii_bitbang_readreg(dev, &bm_mii_bitbang_ops, phy, reg);
return (0);
}
static void
bm_miibus_statchg(device_t dev)
{
struct bm_softc *sc = device_get_softc(dev);
uint16_t reg;
int new_duplex;
reg = CSR_READ_2(sc, BM_TX_CONFIG);
new_duplex = IFM_OPTIONS(sc->sc_mii->mii_media_active) & IFM_FDX;
if (new_duplex != sc->sc_duplex) {
/* Turn off TX MAC while we fiddle its settings */
reg &= ~BM_ENABLE;
CSR_WRITE_2(sc, BM_TX_CONFIG, reg);
while (CSR_READ_2(sc, BM_TX_CONFIG) & BM_ENABLE)
DELAY(10);
}
if (new_duplex && !sc->sc_duplex)
reg |= BM_TX_IGNORECOLL | BM_TX_FULLDPX;
else if (!new_duplex && sc->sc_duplex)
reg &= ~(BM_TX_IGNORECOLL | BM_TX_FULLDPX);
if (new_duplex != sc->sc_duplex) {
/* Turn TX MAC back on */
reg |= BM_ENABLE;
CSR_WRITE_2(sc, BM_TX_CONFIG, reg);
sc->sc_duplex = new_duplex;
}
}
/*
* ifmedia/mii callbacks
*/
static int
bm_ifmedia_upd(struct ifnet *ifp)
{
struct bm_softc *sc = ifp->if_softc;
int error;
BM_LOCK(sc);
error = mii_mediachg(sc->sc_mii);
BM_UNLOCK(sc);
return (error);
}
static void
bm_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifm)
{
struct bm_softc *sc = ifp->if_softc;
BM_LOCK(sc);
mii_pollstat(sc->sc_mii);
ifm->ifm_active = sc->sc_mii->mii_media_active;
ifm->ifm_status = sc->sc_mii->mii_media_status;
BM_UNLOCK(sc);
}
/*
* Macio probe/attach
*/
static int
bm_probe(device_t dev)
{
const char *dname = ofw_bus_get_name(dev);
const char *dcompat = ofw_bus_get_compat(dev);
/*
* BMAC+ cells have a name of "ethernet" and
* a compatible property of "bmac+"
*/
if (strcmp(dname, "bmac") == 0) {
device_set_desc(dev, "Apple BMAC Ethernet Adaptor");
} else if (strcmp(dcompat, "bmac+") == 0) {
device_set_desc(dev, "Apple BMAC+ Ethernet Adaptor");
} else
return (ENXIO);
return (0);
}
static int
bm_attach(device_t dev)
{
phandle_t node;
u_char *eaddr;
struct ifnet *ifp;
int error, cellid, i;
struct bm_txsoft *txs;
struct bm_softc *sc = device_get_softc(dev);
ifp = sc->sc_ifp = if_alloc(IFT_ETHER);
ifp->if_softc = sc;
sc->sc_dev = dev;
sc->sc_duplex = ~IFM_FDX;
error = 0;
mtx_init(&sc->sc_mtx, device_get_nameunit(dev), MTX_NETWORK_LOCK,
MTX_DEF);
callout_init_mtx(&sc->sc_tick_ch, &sc->sc_mtx, 0);
/* Check for an improved version of Paddington */
sc->sc_streaming = 0;
cellid = -1;
node = ofw_bus_get_node(dev);
OF_getprop(node, "cell-id", &cellid, sizeof(cellid));
if (cellid >= 0xc4)
sc->sc_streaming = 1;
sc->sc_memrid = 0;
sc->sc_memr = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
&sc->sc_memrid, RF_ACTIVE);
if (sc->sc_memr == NULL) {
device_printf(dev, "Could not alloc chip registers!\n");
return (ENXIO);
}
sc->sc_txdmarid = BM_TXDMA_REGISTERS;
sc->sc_rxdmarid = BM_RXDMA_REGISTERS;
sc->sc_txdmar = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
&sc->sc_txdmarid, RF_ACTIVE);
sc->sc_rxdmar = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
&sc->sc_rxdmarid, RF_ACTIVE);
if (sc->sc_txdmar == NULL || sc->sc_rxdmar == NULL) {
device_printf(dev, "Could not map DBDMA registers!\n");
return (ENXIO);
}
error = dbdma_allocate_channel(sc->sc_txdmar, 0, bus_get_dma_tag(dev),
BM_MAX_DMA_COMMANDS, &sc->sc_txdma);
error += dbdma_allocate_channel(sc->sc_rxdmar, 0, bus_get_dma_tag(dev),
BM_MAX_DMA_COMMANDS, &sc->sc_rxdma);
if (error) {
device_printf(dev,"Could not allocate DBDMA channel!\n");
return (ENXIO);
}
/* alloc DMA tags and buffers */
error = bus_dma_tag_create(bus_get_dma_tag(dev), 1, 0,
BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
BUS_SPACE_MAXSIZE_32BIT, 0, BUS_SPACE_MAXSIZE_32BIT, 0, NULL,
NULL, &sc->sc_pdma_tag);
if (error) {
device_printf(dev,"Could not allocate DMA tag!\n");
return (ENXIO);
}
error = bus_dma_tag_create(sc->sc_pdma_tag, 1, 0, BUS_SPACE_MAXADDR,
BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES, 1, MCLBYTES,
BUS_DMA_ALLOCNOW, NULL, NULL, &sc->sc_rdma_tag);
if (error) {
device_printf(dev,"Could not allocate RX DMA channel!\n");
return (ENXIO);
}
error = bus_dma_tag_create(sc->sc_pdma_tag, 1, 0, BUS_SPACE_MAXADDR,
BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES * BM_NTXSEGS, BM_NTXSEGS,
MCLBYTES, BUS_DMA_ALLOCNOW, NULL, NULL, &sc->sc_tdma_tag);
if (error) {
device_printf(dev,"Could not allocate TX DMA tag!\n");
return (ENXIO);
}
/* init transmit descriptors */
STAILQ_INIT(&sc->sc_txfreeq);
STAILQ_INIT(&sc->sc_txdirtyq);
/* create TX DMA maps */
error = ENOMEM;
for (i = 0; i < BM_MAX_TX_PACKETS; i++) {
txs = &sc->sc_txsoft[i];
txs->txs_mbuf = NULL;
error = bus_dmamap_create(sc->sc_tdma_tag, 0, &txs->txs_dmamap);
if (error) {
device_printf(sc->sc_dev,
"unable to create TX DMA map %d, error = %d\n",
i, error);
}
STAILQ_INSERT_TAIL(&sc->sc_txfreeq, txs, txs_q);
}
/* Create the receive buffer DMA maps. */
for (i = 0; i < BM_MAX_RX_PACKETS; i++) {
error = bus_dmamap_create(sc->sc_rdma_tag, 0,
&sc->sc_rxsoft[i].rxs_dmamap);
if (error) {
device_printf(sc->sc_dev,
"unable to create RX DMA map %d, error = %d\n",
i, error);
}
sc->sc_rxsoft[i].rxs_mbuf = NULL;
}
/* alloc interrupt */
bm_disable_interrupts(sc);
sc->sc_txdmairqid = BM_TXDMA_INTERRUPT;
sc->sc_txdmairq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
&sc->sc_txdmairqid, RF_ACTIVE);
if (error) {
device_printf(dev,"Could not allocate TX interrupt!\n");
return (ENXIO);
}
bus_setup_intr(dev,sc->sc_txdmairq,
INTR_TYPE_MISC | INTR_MPSAFE | INTR_ENTROPY, NULL, bm_txintr, sc,
&sc->sc_txihtx);
sc->sc_rxdmairqid = BM_RXDMA_INTERRUPT;
sc->sc_rxdmairq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
&sc->sc_rxdmairqid, RF_ACTIVE);
if (error) {
device_printf(dev,"Could not allocate RX interrupt!\n");
return (ENXIO);
}
bus_setup_intr(dev,sc->sc_rxdmairq,
INTR_TYPE_MISC | INTR_MPSAFE | INTR_ENTROPY, NULL, bm_rxintr, sc,
&sc->sc_rxih);
/*
* Get the ethernet address from OpenFirmware
*/
eaddr = sc->sc_enaddr;
OF_getprop(node, "local-mac-address", eaddr, ETHER_ADDR_LEN);
/*
* Setup MII
* On Apple BMAC controllers, we end up in a weird state of
* partially-completed autonegotiation on boot. So we force
* autonegotation to try again.
*/
error = mii_attach(dev, &sc->sc_miibus, ifp, bm_ifmedia_upd,
bm_ifmedia_sts, BMSR_DEFCAPMASK, MII_PHY_ANY, MII_OFFSET_ANY,
MIIF_FORCEANEG);
if (error != 0) {
device_printf(dev, "attaching PHYs failed\n");
return (error);
}
/* reset the adapter */
bm_chip_setup(sc);
sc->sc_mii = device_get_softc(sc->sc_miibus);
if_initname(ifp, device_get_name(sc->sc_dev),
device_get_unit(sc->sc_dev));
ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
ifp->if_start = bm_start;
ifp->if_ioctl = bm_ioctl;
ifp->if_init = bm_init;
IFQ_SET_MAXLEN(&ifp->if_snd, BM_MAX_TX_PACKETS);
ifp->if_snd.ifq_drv_maxlen = BM_MAX_TX_PACKETS;
IFQ_SET_READY(&ifp->if_snd);
/* Attach the interface. */
ether_ifattach(ifp, sc->sc_enaddr);
ifp->if_hwassist = 0;
return (0);
}
static int
bm_detach(device_t dev)
{
struct bm_softc *sc = device_get_softc(dev);
BM_LOCK(sc);
bm_stop(sc);
BM_UNLOCK(sc);
callout_drain(&sc->sc_tick_ch);
ether_ifdetach(sc->sc_ifp);
bus_teardown_intr(dev, sc->sc_txdmairq, sc->sc_txihtx);
bus_teardown_intr(dev, sc->sc_rxdmairq, sc->sc_rxih);
dbdma_free_channel(sc->sc_txdma);
dbdma_free_channel(sc->sc_rxdma);
bus_release_resource(dev, SYS_RES_MEMORY, sc->sc_memrid, sc->sc_memr);
bus_release_resource(dev, SYS_RES_MEMORY, sc->sc_txdmarid,
sc->sc_txdmar);
bus_release_resource(dev, SYS_RES_MEMORY, sc->sc_rxdmarid,
sc->sc_rxdmar);
bus_release_resource(dev, SYS_RES_IRQ, sc->sc_txdmairqid,
sc->sc_txdmairq);
bus_release_resource(dev, SYS_RES_IRQ, sc->sc_rxdmairqid,
sc->sc_rxdmairq);
mtx_destroy(&sc->sc_mtx);
if_free(sc->sc_ifp);
return (0);
}
static int
bm_shutdown(device_t dev)
{
struct bm_softc *sc;
sc = device_get_softc(dev);
BM_LOCK(sc);
bm_stop(sc);
BM_UNLOCK(sc);
return (0);
}
static void
bm_dummypacket(struct bm_softc *sc)
{
struct mbuf *m;
struct ifnet *ifp;
ifp = sc->sc_ifp;
MGETHDR(m, M_NOWAIT, MT_DATA);
if (m == NULL)
return;
bcopy(sc->sc_enaddr,
mtod(m, struct ether_header *)->ether_dhost, ETHER_ADDR_LEN);
bcopy(sc->sc_enaddr,
mtod(m, struct ether_header *)->ether_shost, ETHER_ADDR_LEN);
mtod(m, struct ether_header *)->ether_type = htons(3);
mtod(m, unsigned char *)[14] = 0;
mtod(m, unsigned char *)[15] = 0;
mtod(m, unsigned char *)[16] = 0xE3;
m->m_len = m->m_pkthdr.len = sizeof(struct ether_header) + 3;
IF_ENQUEUE(&ifp->if_snd, m);
bm_start_locked(ifp);
}
static void
bm_rxintr(void *xsc)
{
struct bm_softc *sc = xsc;
struct ifnet *ifp = sc->sc_ifp;
struct mbuf *m;
int i, prev_stop, new_stop;
uint16_t status;
BM_LOCK(sc);
status = dbdma_get_chan_status(sc->sc_rxdma);
if (status & DBDMA_STATUS_DEAD) {
dbdma_reset(sc->sc_rxdma);
BM_UNLOCK(sc);
return;
}
if (!(status & DBDMA_STATUS_RUN)) {
device_printf(sc->sc_dev,"Bad RX Interrupt!\n");
BM_UNLOCK(sc);
return;
}
prev_stop = sc->next_rxdma_slot - 1;
if (prev_stop < 0)
prev_stop = sc->rxdma_loop_slot - 1;
if (prev_stop < 0) {
BM_UNLOCK(sc);
return;
}
new_stop = -1;
dbdma_sync_commands(sc->sc_rxdma, BUS_DMASYNC_POSTREAD);
for (i = sc->next_rxdma_slot; i < BM_MAX_RX_PACKETS; i++) {
if (i == sc->rxdma_loop_slot)
i = 0;
if (i == prev_stop)
break;
status = dbdma_get_cmd_status(sc->sc_rxdma, i);
if (status == 0)
break;
m = sc->sc_rxsoft[i].rxs_mbuf;
if (bm_add_rxbuf(sc, i)) {
if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
m = NULL;
continue;
}
if (m == NULL)
continue;
if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
m->m_pkthdr.rcvif = ifp;
m->m_len -= (dbdma_get_residuals(sc->sc_rxdma, i) + 2);
m->m_pkthdr.len = m->m_len;
/* Send up the stack */
BM_UNLOCK(sc);
(*ifp->if_input)(ifp, m);
BM_LOCK(sc);
/* Clear all fields on this command */
bm_add_rxbuf_dma(sc, i);
new_stop = i;
}
/* Change the last packet we processed to the ring buffer terminator,
* and restore a receive buffer to the old terminator */
if (new_stop >= 0) {
dbdma_insert_stop(sc->sc_rxdma, new_stop);
bm_add_rxbuf_dma(sc, prev_stop);
if (i < sc->rxdma_loop_slot)
sc->next_rxdma_slot = i;
else
sc->next_rxdma_slot = 0;
}
dbdma_sync_commands(sc->sc_rxdma, BUS_DMASYNC_PREWRITE);
dbdma_wake(sc->sc_rxdma);
BM_UNLOCK(sc);
}
static void
bm_txintr(void *xsc)
{
struct bm_softc *sc = xsc;
struct ifnet *ifp = sc->sc_ifp;
struct bm_txsoft *txs;
int progress = 0;
BM_LOCK(sc);
while ((txs = STAILQ_FIRST(&sc->sc_txdirtyq)) != NULL) {
if (!dbdma_get_cmd_status(sc->sc_txdma, txs->txs_lastdesc))
break;
STAILQ_REMOVE_HEAD(&sc->sc_txdirtyq, txs_q);
bus_dmamap_unload(sc->sc_tdma_tag, txs->txs_dmamap);
if (txs->txs_mbuf != NULL) {
m_freem(txs->txs_mbuf);
txs->txs_mbuf = NULL;
}
/* Set the first used TXDMA slot to the location of the
* STOP/NOP command associated with this packet. */
sc->first_used_txdma_slot = txs->txs_stopdesc;
STAILQ_INSERT_TAIL(&sc->sc_txfreeq, txs, txs_q);
if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
progress = 1;
}
if (progress) {
/*
* We freed some descriptors, so reset IFF_DRV_OACTIVE
* and restart.
*/
ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
sc->sc_wdog_timer = STAILQ_EMPTY(&sc->sc_txdirtyq) ? 0 : 5;
if ((ifp->if_drv_flags & IFF_DRV_RUNNING) &&
!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
bm_start_locked(ifp);
}
BM_UNLOCK(sc);
}
static void
bm_start(struct ifnet *ifp)
{
struct bm_softc *sc = ifp->if_softc;
BM_LOCK(sc);
bm_start_locked(ifp);
BM_UNLOCK(sc);
}
static void
bm_start_locked(struct ifnet *ifp)
{
struct bm_softc *sc = ifp->if_softc;
struct mbuf *mb_head;
int prev_stop;
int txqueued = 0;
/*
* We lay out our DBDMA program in the following manner:
* OUTPUT_MORE
* ...
* OUTPUT_LAST (+ Interrupt)
* STOP
*
* To extend the channel, we append a new program,
* then replace STOP with NOP and wake the channel.
* If we stalled on the STOP already, the program proceeds,
* if not it will sail through the NOP.
*/
while (!IFQ_DRV_IS_EMPTY(&ifp->if_snd)) {
IFQ_DRV_DEQUEUE(&ifp->if_snd, mb_head);
if (mb_head == NULL)
break;
prev_stop = sc->next_txdma_slot - 1;
if (bm_encap(sc, &mb_head)) {
/* Put the packet back and stop */
ifp->if_drv_flags |= IFF_DRV_OACTIVE;
IFQ_DRV_PREPEND(&ifp->if_snd, mb_head);
break;
}
dbdma_insert_nop(sc->sc_txdma, prev_stop);
txqueued = 1;
BPF_MTAP(ifp, mb_head);
}
dbdma_sync_commands(sc->sc_txdma, BUS_DMASYNC_PREWRITE);
if (txqueued) {
dbdma_wake(sc->sc_txdma);
sc->sc_wdog_timer = 5;
}
}
static int
bm_encap(struct bm_softc *sc, struct mbuf **m_head)
{
bus_dma_segment_t segs[BM_NTXSEGS];
struct bm_txsoft *txs;
struct mbuf *m;
int nsegs = BM_NTXSEGS;
int error = 0;
uint8_t branch_type;
int i;
/* Limit the command size to the number of free DBDMA slots */
if (sc->next_txdma_slot >= sc->first_used_txdma_slot)
nsegs = BM_MAX_DMA_COMMANDS - 2 - sc->next_txdma_slot +
sc->first_used_txdma_slot; /* -2 for branch and indexing */
else
nsegs = sc->first_used_txdma_slot - sc->next_txdma_slot;
/* Remove one slot for the STOP/NOP terminator */
nsegs--;
if (nsegs > BM_NTXSEGS)
nsegs = BM_NTXSEGS;
/* Get a work queue entry. */
if ((txs = STAILQ_FIRST(&sc->sc_txfreeq)) == NULL) {
/* Ran out of descriptors. */
return (ENOBUFS);
}
error = bus_dmamap_load_mbuf_sg(sc->sc_tdma_tag, txs->txs_dmamap,
*m_head, segs, &nsegs, BUS_DMA_NOWAIT);
if (error == EFBIG) {
m = m_collapse(*m_head, M_NOWAIT, nsegs);
if (m == NULL) {
m_freem(*m_head);
*m_head = NULL;
return (ENOBUFS);
}
*m_head = m;
error = bus_dmamap_load_mbuf_sg(sc->sc_tdma_tag,
txs->txs_dmamap, *m_head, segs, &nsegs, BUS_DMA_NOWAIT);
if (error != 0) {
m_freem(*m_head);
*m_head = NULL;
return (error);
}
} else if (error != 0)
return (error);
if (nsegs == 0) {
m_freem(*m_head);
*m_head = NULL;
return (EIO);
}
txs->txs_ndescs = nsegs;
txs->txs_firstdesc = sc->next_txdma_slot;
for (i = 0; i < nsegs; i++) {
/* Loop back to the beginning if this is our last slot */
if (sc->next_txdma_slot == (BM_MAX_DMA_COMMANDS - 1))
branch_type = DBDMA_ALWAYS;
else
branch_type = DBDMA_NEVER;
if (i+1 == nsegs)
txs->txs_lastdesc = sc->next_txdma_slot;
dbdma_insert_command(sc->sc_txdma, sc->next_txdma_slot++,
(i + 1 < nsegs) ? DBDMA_OUTPUT_MORE : DBDMA_OUTPUT_LAST,
0, segs[i].ds_addr, segs[i].ds_len,
(i + 1 < nsegs) ? DBDMA_NEVER : DBDMA_ALWAYS,
branch_type, DBDMA_NEVER, 0);
if (branch_type == DBDMA_ALWAYS)
sc->next_txdma_slot = 0;
}
/* We have a corner case where the STOP command is the last slot,
* but you can't branch in STOP commands. So add a NOP branch here
* and the STOP in slot 0. */
if (sc->next_txdma_slot == (BM_MAX_DMA_COMMANDS - 1)) {
dbdma_insert_branch(sc->sc_txdma, sc->next_txdma_slot, 0);
sc->next_txdma_slot = 0;
}
txs->txs_stopdesc = sc->next_txdma_slot;
dbdma_insert_stop(sc->sc_txdma, sc->next_txdma_slot++);
STAILQ_REMOVE_HEAD(&sc->sc_txfreeq, txs_q);
STAILQ_INSERT_TAIL(&sc->sc_txdirtyq, txs, txs_q);
txs->txs_mbuf = *m_head;
return (0);
}
static int
bm_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
{
struct bm_softc *sc = ifp->if_softc;
struct ifreq *ifr = (struct ifreq *)data;
int error;
error = 0;
switch(cmd) {
case SIOCSIFFLAGS:
BM_LOCK(sc);
if ((ifp->if_flags & IFF_UP) != 0) {
if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0 &&
((ifp->if_flags ^ sc->sc_ifpflags) &
(IFF_ALLMULTI | IFF_PROMISC)) != 0)
bm_setladrf(sc);
else
bm_init_locked(sc);
} else if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0)
bm_stop(sc);
sc->sc_ifpflags = ifp->if_flags;
BM_UNLOCK(sc);
break;
case SIOCADDMULTI:
case SIOCDELMULTI:
BM_LOCK(sc);
bm_setladrf(sc);
BM_UNLOCK(sc);
case SIOCGIFMEDIA:
case SIOCSIFMEDIA:
error = ifmedia_ioctl(ifp, ifr, &sc->sc_mii->mii_media, cmd);
break;
default:
error = ether_ioctl(ifp, cmd, data);
break;
}
return (error);
}
static void
bm_setladrf(struct bm_softc *sc)
{
struct ifnet *ifp = sc->sc_ifp;
struct ifmultiaddr *inm;
uint16_t hash[4];
uint16_t reg;
uint32_t crc;
reg = BM_CRC_ENABLE | BM_REJECT_OWN_PKTS;
/* Turn off RX MAC while we fiddle its settings */
CSR_WRITE_2(sc, BM_RX_CONFIG, reg);
while (CSR_READ_2(sc, BM_RX_CONFIG) & BM_ENABLE)
DELAY(10);
if ((ifp->if_flags & IFF_PROMISC) != 0) {
reg |= BM_PROMISC;
CSR_WRITE_2(sc, BM_RX_CONFIG, reg);
DELAY(15);
reg = CSR_READ_2(sc, BM_RX_CONFIG);
reg |= BM_ENABLE;
CSR_WRITE_2(sc, BM_RX_CONFIG, reg);
return;
}
if ((ifp->if_flags & IFF_ALLMULTI) != 0) {
hash[3] = hash[2] = hash[1] = hash[0] = 0xffff;
} else {
/* Clear the hash table. */
memset(hash, 0, sizeof(hash));
if_maddr_rlock(ifp);
TAILQ_FOREACH(inm, &ifp->if_multiaddrs, ifma_link) {
if (inm->ifma_addr->sa_family != AF_LINK)
continue;
crc = ether_crc32_le(LLADDR((struct sockaddr_dl *)
inm->ifma_addr), ETHER_ADDR_LEN);
/* We just want the 6 most significant bits */
crc >>= 26;
/* Set the corresponding bit in the filter. */
hash[crc >> 4] |= 1 << (crc & 0xf);
}
if_maddr_runlock(ifp);
}
/* Write out new hash table */
CSR_WRITE_2(sc, BM_HASHTAB0, hash[0]);
CSR_WRITE_2(sc, BM_HASHTAB1, hash[1]);
CSR_WRITE_2(sc, BM_HASHTAB2, hash[2]);
CSR_WRITE_2(sc, BM_HASHTAB3, hash[3]);
/* And turn the RX MAC back on, this time with the hash bit set */
reg |= BM_HASH_FILTER_ENABLE;
CSR_WRITE_2(sc, BM_RX_CONFIG, reg);
while (!(CSR_READ_2(sc, BM_RX_CONFIG) & BM_HASH_FILTER_ENABLE))
DELAY(10);
reg = CSR_READ_2(sc, BM_RX_CONFIG);
reg |= BM_ENABLE;
CSR_WRITE_2(sc, BM_RX_CONFIG, reg);
}
static void
bm_init(void *xsc)
{
struct bm_softc *sc = xsc;
BM_LOCK(sc);
bm_init_locked(sc);
BM_UNLOCK(sc);
}
static void
bm_chip_setup(struct bm_softc *sc)
{
uint16_t reg;
uint16_t *eaddr_sect;
eaddr_sect = (uint16_t *)(sc->sc_enaddr);
dbdma_stop(sc->sc_txdma);
dbdma_stop(sc->sc_rxdma);
/* Reset chip */
CSR_WRITE_2(sc, BM_RX_RESET, 0x0000);
CSR_WRITE_2(sc, BM_TX_RESET, 0x0001);
do {
DELAY(10);
reg = CSR_READ_2(sc, BM_TX_RESET);
} while (reg & 0x0001);
/* Some random junk. OS X uses the system time. We use
* the low 16 bits of the MAC address. */
CSR_WRITE_2(sc, BM_TX_RANDSEED, eaddr_sect[2]);
/* Enable transmit */
reg = CSR_READ_2(sc, BM_TX_IFC);
reg |= BM_ENABLE;
CSR_WRITE_2(sc, BM_TX_IFC, reg);
CSR_READ_2(sc, BM_TX_PEAKCNT);
}
static void
bm_stop(struct bm_softc *sc)
{
struct bm_txsoft *txs;
uint16_t reg;
/* Disable TX and RX MACs */
reg = CSR_READ_2(sc, BM_TX_CONFIG);
reg &= ~BM_ENABLE;
CSR_WRITE_2(sc, BM_TX_CONFIG, reg);
reg = CSR_READ_2(sc, BM_RX_CONFIG);
reg &= ~BM_ENABLE;
CSR_WRITE_2(sc, BM_RX_CONFIG, reg);
DELAY(100);
/* Stop DMA engine */
dbdma_stop(sc->sc_rxdma);
dbdma_stop(sc->sc_txdma);
sc->next_rxdma_slot = 0;
sc->rxdma_loop_slot = 0;
/* Disable interrupts */
bm_disable_interrupts(sc);
/* Don't worry about pending transmits anymore */
while ((txs = STAILQ_FIRST(&sc->sc_txdirtyq)) != NULL) {
STAILQ_REMOVE_HEAD(&sc->sc_txdirtyq, txs_q);
if (txs->txs_ndescs != 0) {
bus_dmamap_sync(sc->sc_tdma_tag, txs->txs_dmamap,
BUS_DMASYNC_POSTWRITE);
bus_dmamap_unload(sc->sc_tdma_tag, txs->txs_dmamap);
if (txs->txs_mbuf != NULL) {
m_freem(txs->txs_mbuf);
txs->txs_mbuf = NULL;
}
}
STAILQ_INSERT_TAIL(&sc->sc_txfreeq, txs, txs_q);
}
/* And we're down */
sc->sc_ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
sc->sc_wdog_timer = 0;
callout_stop(&sc->sc_tick_ch);
}
static void
bm_init_locked(struct bm_softc *sc)
{
uint16_t reg;
uint16_t *eaddr_sect;
struct bm_rxsoft *rxs;
int i;
eaddr_sect = (uint16_t *)(sc->sc_enaddr);
/* Zero RX slot info and stop DMA */
dbdma_stop(sc->sc_rxdma);
dbdma_stop(sc->sc_txdma);
sc->next_rxdma_slot = 0;
sc->rxdma_loop_slot = 0;
/* Initialize TX/RX DBDMA programs */
dbdma_insert_stop(sc->sc_rxdma, 0);
dbdma_insert_stop(sc->sc_txdma, 0);
dbdma_set_current_cmd(sc->sc_rxdma, 0);
dbdma_set_current_cmd(sc->sc_txdma, 0);
sc->next_rxdma_slot = 0;
sc->next_txdma_slot = 1;
sc->first_used_txdma_slot = 0;
for (i = 0; i < BM_MAX_RX_PACKETS; i++) {
rxs = &sc->sc_rxsoft[i];
rxs->dbdma_slot = i;
if (rxs->rxs_mbuf == NULL) {
bm_add_rxbuf(sc, i);
if (rxs->rxs_mbuf == NULL) {
/* If we can't add anymore, mark the problem */
rxs->dbdma_slot = -1;
break;
}
}
if (i > 0)
bm_add_rxbuf_dma(sc, i);
}
/*
* Now terminate the RX ring buffer, and follow with the loop to
* the beginning.
*/
dbdma_insert_stop(sc->sc_rxdma, i - 1);
dbdma_insert_branch(sc->sc_rxdma, i, 0);
sc->rxdma_loop_slot = i;
/* Now add in the first element of the RX DMA chain */
bm_add_rxbuf_dma(sc, 0);
dbdma_sync_commands(sc->sc_rxdma, BUS_DMASYNC_PREWRITE);
dbdma_sync_commands(sc->sc_txdma, BUS_DMASYNC_PREWRITE);
/* Zero collision counters */
CSR_WRITE_2(sc, BM_TX_NCCNT, 0);
CSR_WRITE_2(sc, BM_TX_FCCNT, 0);
CSR_WRITE_2(sc, BM_TX_EXCNT, 0);
CSR_WRITE_2(sc, BM_TX_LTCNT, 0);
/* Zero receive counters */
CSR_WRITE_2(sc, BM_RX_FRCNT, 0);
CSR_WRITE_2(sc, BM_RX_LECNT, 0);
CSR_WRITE_2(sc, BM_RX_AECNT, 0);
CSR_WRITE_2(sc, BM_RX_FECNT, 0);
CSR_WRITE_2(sc, BM_RXCV, 0);
/* Prime transmit */
CSR_WRITE_2(sc, BM_TX_THRESH, 0xff);
CSR_WRITE_2(sc, BM_TXFIFO_CSR, 0);
CSR_WRITE_2(sc, BM_TXFIFO_CSR, 0x0001);
/* Prime receive */
CSR_WRITE_2(sc, BM_RXFIFO_CSR, 0);
CSR_WRITE_2(sc, BM_RXFIFO_CSR, 0x0001);
/* Clear status reg */
CSR_READ_2(sc, BM_STATUS);
/* Zero hash filters */
CSR_WRITE_2(sc, BM_HASHTAB0, 0);
CSR_WRITE_2(sc, BM_HASHTAB1, 0);
CSR_WRITE_2(sc, BM_HASHTAB2, 0);
CSR_WRITE_2(sc, BM_HASHTAB3, 0);
/* Write MAC address to chip */
CSR_WRITE_2(sc, BM_MACADDR0, eaddr_sect[0]);
CSR_WRITE_2(sc, BM_MACADDR1, eaddr_sect[1]);
CSR_WRITE_2(sc, BM_MACADDR2, eaddr_sect[2]);
/* Final receive engine setup */
reg = BM_CRC_ENABLE | BM_REJECT_OWN_PKTS | BM_HASH_FILTER_ENABLE;
CSR_WRITE_2(sc, BM_RX_CONFIG, reg);
/* Now turn it all on! */
dbdma_reset(sc->sc_rxdma);
dbdma_reset(sc->sc_txdma);
/* Enable RX and TX MACs. Setting the address filter has
* the side effect of enabling the RX MAC. */
bm_setladrf(sc);
reg = CSR_READ_2(sc, BM_TX_CONFIG);
reg |= BM_ENABLE;
CSR_WRITE_2(sc, BM_TX_CONFIG, reg);
/*
* Enable interrupts, unwedge the controller with a dummy packet,
* and nudge the DMA queue.
*/
bm_enable_interrupts(sc);
bm_dummypacket(sc);
dbdma_wake(sc->sc_rxdma); /* Nudge RXDMA */
sc->sc_ifp->if_drv_flags |= IFF_DRV_RUNNING;
sc->sc_ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
sc->sc_ifpflags = sc->sc_ifp->if_flags;
/* Resync PHY and MAC states */
sc->sc_mii = device_get_softc(sc->sc_miibus);
sc->sc_duplex = ~IFM_FDX;
mii_mediachg(sc->sc_mii);
/* Start the one second timer. */
sc->sc_wdog_timer = 0;
callout_reset(&sc->sc_tick_ch, hz, bm_tick, sc);
}
static void
bm_tick(void *arg)
{
struct bm_softc *sc = arg;
/* Read error counters */
if_inc_counter(sc->sc_ifp, IFCOUNTER_COLLISIONS,
CSR_READ_2(sc, BM_TX_NCCNT) + CSR_READ_2(sc, BM_TX_FCCNT) +
CSR_READ_2(sc, BM_TX_EXCNT) + CSR_READ_2(sc, BM_TX_LTCNT));
if_inc_counter(sc->sc_ifp, IFCOUNTER_IERRORS,
CSR_READ_2(sc, BM_RX_LECNT) + CSR_READ_2(sc, BM_RX_AECNT) +
CSR_READ_2(sc, BM_RX_FECNT));
/* Zero collision counters */
CSR_WRITE_2(sc, BM_TX_NCCNT, 0);
CSR_WRITE_2(sc, BM_TX_FCCNT, 0);
CSR_WRITE_2(sc, BM_TX_EXCNT, 0);
CSR_WRITE_2(sc, BM_TX_LTCNT, 0);
/* Zero receive counters */
CSR_WRITE_2(sc, BM_RX_FRCNT, 0);
CSR_WRITE_2(sc, BM_RX_LECNT, 0);
CSR_WRITE_2(sc, BM_RX_AECNT, 0);
CSR_WRITE_2(sc, BM_RX_FECNT, 0);
CSR_WRITE_2(sc, BM_RXCV, 0);
/* Check for link changes and run watchdog */
mii_tick(sc->sc_mii);
bm_miibus_statchg(sc->sc_dev);
if (sc->sc_wdog_timer == 0 || --sc->sc_wdog_timer != 0) {
callout_reset(&sc->sc_tick_ch, hz, bm_tick, sc);
return;
}
/* Problems */
device_printf(sc->sc_dev, "device timeout\n");
bm_init_locked(sc);
}
static int
bm_add_rxbuf(struct bm_softc *sc, int idx)
{
struct bm_rxsoft *rxs = &sc->sc_rxsoft[idx];
struct mbuf *m;
bus_dma_segment_t segs[1];
int error, nsegs;
m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
if (m == NULL)
return (ENOBUFS);
m->m_len = m->m_pkthdr.len = m->m_ext.ext_size;
if (rxs->rxs_mbuf != NULL) {
bus_dmamap_sync(sc->sc_rdma_tag, rxs->rxs_dmamap,
BUS_DMASYNC_POSTREAD);
bus_dmamap_unload(sc->sc_rdma_tag, rxs->rxs_dmamap);
}
error = bus_dmamap_load_mbuf_sg(sc->sc_rdma_tag, rxs->rxs_dmamap, m,
segs, &nsegs, BUS_DMA_NOWAIT);
if (error != 0) {
device_printf(sc->sc_dev,
"cannot load RS DMA map %d, error = %d\n", idx, error);
m_freem(m);
return (error);
}
/* If nsegs is wrong then the stack is corrupt. */
KASSERT(nsegs == 1,
("%s: too many DMA segments (%d)", __func__, nsegs));
rxs->rxs_mbuf = m;
rxs->segment = segs[0];
bus_dmamap_sync(sc->sc_rdma_tag, rxs->rxs_dmamap, BUS_DMASYNC_PREREAD);
return (0);
}
static int
bm_add_rxbuf_dma(struct bm_softc *sc, int idx)
{
struct bm_rxsoft *rxs = &sc->sc_rxsoft[idx];
dbdma_insert_command(sc->sc_rxdma, idx, DBDMA_INPUT_LAST, 0,
rxs->segment.ds_addr, rxs->segment.ds_len, DBDMA_ALWAYS,
DBDMA_NEVER, DBDMA_NEVER, 0);
return (0);
}
static void
bm_enable_interrupts(struct bm_softc *sc)
{
CSR_WRITE_2(sc, BM_INTR_DISABLE,
(sc->sc_streaming) ? BM_INTR_NONE : BM_INTR_NORMAL);
}
static void
bm_disable_interrupts(struct bm_softc *sc)
{
CSR_WRITE_2(sc, BM_INTR_DISABLE, BM_INTR_NONE);
}
| TigerBSD/TigerBSD | FreeBSD/sys/dev/bm/if_bm.c | C | isc | 31,727 |
(function(){/*
OverlappingMarkerSpiderfier
https://github.com/jawj/OverlappingMarkerSpiderfier-Leaflet
Copyright (c) 2011 - 2012 George MacKerron
Released under the MIT licence: http://opensource.org/licenses/mit-license
Note: The Leaflet maps API must be included *before* this code
*/
(function(){var q={}.hasOwnProperty,r=[].slice;null!=this.L&&(this.OverlappingMarkerSpiderfier=function(){function n(c,b){var a,e,g,f,d=this;this.map=c;null==b&&(b={});for(a in b)q.call(b,a)&&(e=b[a],this[a]=e);this.initMarkerArrays();this.listeners={};f=["click","zoomend"];e=0;for(g=f.length;e<g;e++)a=f[e],this.map.addEventListener(a,function(){return d.unspiderfy()})}var d,k;d=n.prototype;d.VERSION="0.2.6";k=2*Math.PI;d.keepSpiderfied=!1;d.nearbyDistance=20;d.circleSpiralSwitchover=9;d.circleFootSeparation=
25;d.circleStartAngle=k/12;d.spiralFootSeparation=28;d.spiralLengthStart=11;d.spiralLengthFactor=5;d.legWeight=1.5;d.legColors={usual:"#222",highlighted:"#f00"};d.initMarkerArrays=function(){this.markers=[];return this.markerListeners=[]};d.addMarker=function(c){var b,a=this;if(null!=c._oms)return this;c._oms=!0;b=function(){return a.spiderListener(c)};c.addEventListener("click",b);this.markerListeners.push(b);this.markers.push(c);return this};d.getMarkers=function(){return this.markers.slice(0)};
d.removeMarker=function(c){var b,a;null!=c._omsData&&this.unspiderfy();b=this.arrIndexOf(this.markers,c);if(0>b)return this;a=this.markerListeners.splice(b,1)[0];c.removeEventListener("click",a);delete c._oms;this.markers.splice(b,1);return this};d.clearMarkers=function(){var c,b,a,e,g;this.unspiderfy();g=this.markers;c=a=0;for(e=g.length;a<e;c=++a)b=g[c],c=this.markerListeners[c],b.removeEventListener("click",c),delete b._oms;this.initMarkerArrays();return this};d.addListener=function(c,b){var a,
e;(null!=(e=(a=this.listeners)[c])?e:a[c]=[]).push(b);return this};d.removeListener=function(c,b){var a;a=this.arrIndexOf(this.listeners[c],b);0>a||this.listeners[c].splice(a,1);return this};d.clearListeners=function(c){this.listeners[c]=[];return this};d.trigger=function(){var c,b,a,e,g,f;b=arguments[0];c=2<=arguments.length?r.call(arguments,1):[];b=null!=(a=this.listeners[b])?a:[];f=[];e=0;for(g=b.length;e<g;e++)a=b[e],f.push(a.apply(null,c));return f};d.generatePtsCircle=function(c,b){var a,e,
g,f,d;g=this.circleFootSeparation*(2+c)/k;e=k/c;d=[];for(a=f=0;0<=c?f<c:f>c;a=0<=c?++f:--f)a=this.circleStartAngle+a*e,d.push(new L.Point(b.x+g*Math.cos(a),b.y+g*Math.sin(a)));return d};d.generatePtsSpiral=function(c,b){var a,e,g,f,d;g=this.spiralLengthStart;a=0;d=[];for(e=f=0;0<=c?f<c:f>c;e=0<=c?++f:--f)a+=this.spiralFootSeparation/g+5E-4*e,e=new L.Point(b.x+g*Math.cos(a),b.y+g*Math.sin(a)),g+=k*this.spiralLengthFactor/a,d.push(e);return d};d.spiderListener=function(c){var b,a,e,g,f,d,h,k,l;(b=null!=
c._omsData)&&this.keepSpiderfied||this.unspiderfy();if(b)return this.trigger("click",c);g=[];f=[];d=this.nearbyDistance*this.nearbyDistance;e=this.map.latLngToLayerPoint(c.getLatLng());l=this.markers;h=0;for(k=l.length;h<k;h++)b=l[h],this.map.hasLayer(b)&&(a=this.map.latLngToLayerPoint(b.getLatLng()),this.ptDistanceSq(a,e)<d?g.push({marker:b,markerPt:a}):f.push(b));return 1===g.length?this.trigger("click",c):this.spiderfy(g,f)};d.makeHighlightListeners=function(c){var b=this;return{highlight:function(){return c._omsData.leg.setStyle({color:b.legColors.highlighted})},
unhighlight:function(){return c._omsData.leg.setStyle({color:b.legColors.usual})}}};d.spiderfy=function(c,b){var a,e,g,d,p,h,k,l,n,m;this.spiderfying=!0;m=c.length;a=this.ptAverage(function(){var a,b,e;e=[];a=0;for(b=c.length;a<b;a++)k=c[a],e.push(k.markerPt);return e}());d=m>=this.circleSpiralSwitchover?this.generatePtsSpiral(m,a).reverse():this.generatePtsCircle(m,a);a=function(){var a,b,k,m=this;k=[];a=0;for(b=d.length;a<b;a++)g=d[a],e=this.map.layerPointToLatLng(g),n=this.minExtract(c,function(a){return m.ptDistanceSq(a.markerPt,
g)}),h=n.marker,p=new L.Polyline([h.getLatLng(),e],{color:this.legColors.usual,weight:this.legWeight,interactive:!1}),this.map.addLayer(p),h._omsData={usualPosition:h.getLatLng(),leg:p},this.legColors.highlighted!==this.legColors.usual&&(l=this.makeHighlightListeners(h),h._omsData.highlightListeners=l,h.addEventListener("mouseover",l.highlight),h.addEventListener("mouseout",l.unhighlight)),h.setLatLng(e),h.setZIndexOffset(1E6),k.push(h);return k}.call(this);delete this.spiderfying;this.spiderfied=!0;
return this.trigger("spiderfy",a,b)};d.unspiderfy=function(c){var b,a,e,d,f,k,h;null==c&&(c=null);if(null==this.spiderfied)return this;this.unspiderfying=!0;d=[];e=[];h=this.markers;f=0;for(k=h.length;f<k;f++)b=h[f],null!=b._omsData?(this.map.removeLayer(b._omsData.leg),b!==c&&b.setLatLng(b._omsData.usualPosition),b.setZIndexOffset(0),a=b._omsData.highlightListeners,null!=a&&(b.removeEventListener("mouseover",a.highlight),b.removeEventListener("mouseout",a.unhighlight)),delete b._omsData,d.push(b)):
e.push(b);delete this.unspiderfying;delete this.spiderfied;this.trigger("unspiderfy",d,e);return this};d.ptDistanceSq=function(c,b){var a,e;a=c.x-b.x;e=c.y-b.y;return a*a+e*e};d.ptAverage=function(c){var b,a,e,d,f;d=a=e=0;for(f=c.length;d<f;d++)b=c[d],a+=b.x,e+=b.y;c=c.length;return new L.Point(a/c,e/c)};d.minExtract=function(c,b){var a,d,g,f,k,h;g=k=0;for(h=c.length;k<h;g=++k)if(f=c[g],f=b(f),"undefined"===typeof a||null===a||f<d)d=f,a=g;return c.splice(a,1)[0]};d.arrIndexOf=function(c,b){var a,
d,g,f;if(null!=c.indexOf)return c.indexOf(b);a=g=0;for(f=c.length;g<f;a=++g)if(d=c[a],d===b)return a;return-1};return n}())}).call(this);}).call(this);
/* Mon 14 Oct 2013 10:54:59 BST */
| Hubertzhang/ingress-intel-total-conversion | external/oms.min.js | JavaScript | isc | 5,632 |
/*-
* Copyright (c) 2012 Oleksandr Tymoshenko <gonzo@freebsd.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/bus.h>
#include <sys/kernel.h>
#include <sys/lock.h>
#include <sys/malloc.h>
#include <sys/module.h>
#include <sys/mutex.h>
#include <sys/rman.h>
#include <sys/sysctl.h>
#include <sys/taskqueue.h>
#include <machine/bus.h>
#include <dev/fdt/fdt_common.h>
#include <dev/ofw/ofw_bus.h>
#include <dev/ofw/ofw_bus_subr.h>
#include <dev/mmc/bridge.h>
#include <dev/mmc/mmcreg.h>
#include <dev/mmc/mmcbrvar.h>
#include <dev/sdhci/sdhci.h>
#include "sdhci_if.h"
#include "bcm2835_dma.h"
#include <arm/broadcom/bcm2835/bcm2835_mbox_prop.h>
#include "bcm2835_vcbus.h"
#define BCM2835_DEFAULT_SDHCI_FREQ 50
#define BCM_SDHCI_BUFFER_SIZE 512
#define NUM_DMA_SEGS 2
#ifdef DEBUG
#define dprintf(fmt, args...) do { printf("%s(): ", __func__); \
printf(fmt,##args); } while (0)
#else
#define dprintf(fmt, args...)
#endif
static int bcm2835_sdhci_hs = 1;
static int bcm2835_sdhci_pio_mode = 0;
TUNABLE_INT("hw.bcm2835.sdhci.hs", &bcm2835_sdhci_hs);
TUNABLE_INT("hw.bcm2835.sdhci.pio_mode", &bcm2835_sdhci_pio_mode);
struct bcm_sdhci_softc {
device_t sc_dev;
struct resource * sc_mem_res;
struct resource * sc_irq_res;
bus_space_tag_t sc_bst;
bus_space_handle_t sc_bsh;
void * sc_intrhand;
struct mmc_request * sc_req;
struct sdhci_slot sc_slot;
int sc_dma_ch;
bus_dma_tag_t sc_dma_tag;
bus_dmamap_t sc_dma_map;
vm_paddr_t sc_sdhci_buffer_phys;
uint32_t cmd_and_mode;
bus_addr_t dmamap_seg_addrs[NUM_DMA_SEGS];
bus_size_t dmamap_seg_sizes[NUM_DMA_SEGS];
int dmamap_seg_count;
int dmamap_seg_index;
int dmamap_status;
};
static int bcm_sdhci_probe(device_t);
static int bcm_sdhci_attach(device_t);
static int bcm_sdhci_detach(device_t);
static void bcm_sdhci_intr(void *);
static int bcm_sdhci_get_ro(device_t, device_t);
static void bcm_sdhci_dma_intr(int ch, void *arg);
static void
bcm_sdhci_dmacb(void *arg, bus_dma_segment_t *segs, int nseg, int err)
{
struct bcm_sdhci_softc *sc = arg;
int i;
sc->dmamap_status = err;
sc->dmamap_seg_count = nseg;
/* Note nseg is guaranteed to be zero if err is non-zero. */
for (i = 0; i < nseg; i++) {
sc->dmamap_seg_addrs[i] = segs[i].ds_addr;
sc->dmamap_seg_sizes[i] = segs[i].ds_len;
}
}
static int
bcm_sdhci_probe(device_t dev)
{
if (!ofw_bus_status_okay(dev))
return (ENXIO);
if (!ofw_bus_is_compatible(dev, "broadcom,bcm2835-sdhci"))
return (ENXIO);
device_set_desc(dev, "Broadcom 2708 SDHCI controller");
return (BUS_PROBE_DEFAULT);
}
static int
bcm_sdhci_attach(device_t dev)
{
struct bcm_sdhci_softc *sc = device_get_softc(dev);
int rid, err;
phandle_t node;
pcell_t cell;
u_int default_freq;
sc->sc_dev = dev;
sc->sc_req = NULL;
err = bcm2835_mbox_set_power_state(BCM2835_MBOX_POWER_ID_EMMC,
TRUE);
if (err != 0) {
if (bootverbose)
device_printf(dev, "Unable to enable the power\n");
return (err);
}
default_freq = 0;
err = bcm2835_mbox_get_clock_rate(BCM2835_MBOX_CLOCK_ID_EMMC,
&default_freq);
if (err == 0) {
/* Convert to MHz */
default_freq /= 1000000;
}
if (default_freq == 0) {
node = ofw_bus_get_node(sc->sc_dev);
if ((OF_getencprop(node, "clock-frequency", &cell,
sizeof(cell))) > 0)
default_freq = cell / 1000000;
}
if (default_freq == 0)
default_freq = BCM2835_DEFAULT_SDHCI_FREQ;
if (bootverbose)
device_printf(dev, "SDHCI frequency: %dMHz\n", default_freq);
rid = 0;
sc->sc_mem_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
RF_ACTIVE);
if (!sc->sc_mem_res) {
device_printf(dev, "cannot allocate memory window\n");
err = ENXIO;
goto fail;
}
sc->sc_bst = rman_get_bustag(sc->sc_mem_res);
sc->sc_bsh = rman_get_bushandle(sc->sc_mem_res);
rid = 0;
sc->sc_irq_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
RF_ACTIVE);
if (!sc->sc_irq_res) {
device_printf(dev, "cannot allocate interrupt\n");
err = ENXIO;
goto fail;
}
if (bus_setup_intr(dev, sc->sc_irq_res, INTR_TYPE_BIO | INTR_MPSAFE,
NULL, bcm_sdhci_intr, sc, &sc->sc_intrhand)) {
device_printf(dev, "cannot setup interrupt handler\n");
err = ENXIO;
goto fail;
}
if (!bcm2835_sdhci_pio_mode)
sc->sc_slot.opt = SDHCI_PLATFORM_TRANSFER;
sc->sc_slot.caps = SDHCI_CAN_VDD_330 | SDHCI_CAN_VDD_180;
if (bcm2835_sdhci_hs)
sc->sc_slot.caps |= SDHCI_CAN_DO_HISPD;
sc->sc_slot.caps |= (default_freq << SDHCI_CLOCK_BASE_SHIFT);
sc->sc_slot.quirks = SDHCI_QUIRK_DATA_TIMEOUT_USES_SDCLK
| SDHCI_QUIRK_BROKEN_TIMEOUT_VAL
| SDHCI_QUIRK_DONT_SET_HISPD_BIT
| SDHCI_QUIRK_MISSING_CAPS;
sdhci_init_slot(dev, &sc->sc_slot, 0);
sc->sc_dma_ch = bcm_dma_allocate(BCM_DMA_CH_ANY);
if (sc->sc_dma_ch == BCM_DMA_CH_INVALID)
goto fail;
bcm_dma_setup_intr(sc->sc_dma_ch, bcm_sdhci_dma_intr, sc);
/* Allocate bus_dma resources. */
err = bus_dma_tag_create(bus_get_dma_tag(dev),
1, 0, BUS_SPACE_MAXADDR_32BIT,
BUS_SPACE_MAXADDR, NULL, NULL,
BCM_SDHCI_BUFFER_SIZE, NUM_DMA_SEGS, BCM_SDHCI_BUFFER_SIZE,
BUS_DMA_ALLOCNOW, NULL, NULL,
&sc->sc_dma_tag);
if (err) {
device_printf(dev, "failed allocate DMA tag");
goto fail;
}
err = bus_dmamap_create(sc->sc_dma_tag, 0, &sc->sc_dma_map);
if (err) {
device_printf(dev, "bus_dmamap_create failed\n");
goto fail;
}
sc->sc_sdhci_buffer_phys = BUS_SPACE_PHYSADDR(sc->sc_mem_res,
SDHCI_BUFFER);
bus_generic_probe(dev);
bus_generic_attach(dev);
sdhci_start_slot(&sc->sc_slot);
return (0);
fail:
if (sc->sc_intrhand)
bus_teardown_intr(dev, sc->sc_irq_res, sc->sc_intrhand);
if (sc->sc_irq_res)
bus_release_resource(dev, SYS_RES_IRQ, 0, sc->sc_irq_res);
if (sc->sc_mem_res)
bus_release_resource(dev, SYS_RES_MEMORY, 0, sc->sc_mem_res);
return (err);
}
static int
bcm_sdhci_detach(device_t dev)
{
return (EBUSY);
}
static void
bcm_sdhci_intr(void *arg)
{
struct bcm_sdhci_softc *sc = arg;
sdhci_generic_intr(&sc->sc_slot);
}
static int
bcm_sdhci_get_ro(device_t bus, device_t child)
{
return (0);
}
static inline uint32_t
RD4(struct bcm_sdhci_softc *sc, bus_size_t off)
{
uint32_t val = bus_space_read_4(sc->sc_bst, sc->sc_bsh, off);
return val;
}
static inline void
WR4(struct bcm_sdhci_softc *sc, bus_size_t off, uint32_t val)
{
bus_space_write_4(sc->sc_bst, sc->sc_bsh, off, val);
/*
* The Arasan HC has a bug where it may lose the content of
* consecutive writes to registers that are within two SD-card
* clock cycles of each other (a clock domain crossing problem).
*/
if (sc->sc_slot.clock > 0)
DELAY(((2 * 1000000) / sc->sc_slot.clock) + 1);
}
static uint8_t
bcm_sdhci_read_1(device_t dev, struct sdhci_slot *slot, bus_size_t off)
{
struct bcm_sdhci_softc *sc = device_get_softc(dev);
uint32_t val = RD4(sc, off & ~3);
return ((val >> (off & 3)*8) & 0xff);
}
static uint16_t
bcm_sdhci_read_2(device_t dev, struct sdhci_slot *slot, bus_size_t off)
{
struct bcm_sdhci_softc *sc = device_get_softc(dev);
uint32_t val = RD4(sc, off & ~3);
/*
* Standard 32-bit handling of command and transfer mode.
*/
if (off == SDHCI_TRANSFER_MODE) {
return (sc->cmd_and_mode >> 16);
} else if (off == SDHCI_COMMAND_FLAGS) {
return (sc->cmd_and_mode & 0x0000ffff);
}
return ((val >> (off & 3)*8) & 0xffff);
}
static uint32_t
bcm_sdhci_read_4(device_t dev, struct sdhci_slot *slot, bus_size_t off)
{
struct bcm_sdhci_softc *sc = device_get_softc(dev);
return RD4(sc, off);
}
static void
bcm_sdhci_read_multi_4(device_t dev, struct sdhci_slot *slot, bus_size_t off,
uint32_t *data, bus_size_t count)
{
struct bcm_sdhci_softc *sc = device_get_softc(dev);
bus_space_read_multi_4(sc->sc_bst, sc->sc_bsh, off, data, count);
}
static void
bcm_sdhci_write_1(device_t dev, struct sdhci_slot *slot, bus_size_t off, uint8_t val)
{
struct bcm_sdhci_softc *sc = device_get_softc(dev);
uint32_t val32 = RD4(sc, off & ~3);
val32 &= ~(0xff << (off & 3)*8);
val32 |= (val << (off & 3)*8);
WR4(sc, off & ~3, val32);
}
static void
bcm_sdhci_write_2(device_t dev, struct sdhci_slot *slot, bus_size_t off, uint16_t val)
{
struct bcm_sdhci_softc *sc = device_get_softc(dev);
uint32_t val32;
if (off == SDHCI_COMMAND_FLAGS)
val32 = sc->cmd_and_mode;
else
val32 = RD4(sc, off & ~3);
val32 &= ~(0xffff << (off & 3)*8);
val32 |= (val << (off & 3)*8);
if (off == SDHCI_TRANSFER_MODE)
sc->cmd_and_mode = val32;
else {
WR4(sc, off & ~3, val32);
if (off == SDHCI_COMMAND_FLAGS)
sc->cmd_and_mode = val32;
}
}
static void
bcm_sdhci_write_4(device_t dev, struct sdhci_slot *slot, bus_size_t off, uint32_t val)
{
struct bcm_sdhci_softc *sc = device_get_softc(dev);
WR4(sc, off, val);
}
static void
bcm_sdhci_write_multi_4(device_t dev, struct sdhci_slot *slot, bus_size_t off,
uint32_t *data, bus_size_t count)
{
struct bcm_sdhci_softc *sc = device_get_softc(dev);
bus_space_write_multi_4(sc->sc_bst, sc->sc_bsh, off, data, count);
}
static void
bcm_sdhci_start_dma_seg(struct bcm_sdhci_softc *sc)
{
struct sdhci_slot *slot;
vm_paddr_t pdst, psrc;
int err, idx, len, sync_op;
slot = &sc->sc_slot;
idx = sc->dmamap_seg_index++;
len = sc->dmamap_seg_sizes[idx];
slot->offset += len;
if (slot->curcmd->data->flags & MMC_DATA_READ) {
bcm_dma_setup_src(sc->sc_dma_ch, BCM_DMA_DREQ_EMMC,
BCM_DMA_SAME_ADDR, BCM_DMA_32BIT);
bcm_dma_setup_dst(sc->sc_dma_ch, BCM_DMA_DREQ_NONE,
BCM_DMA_INC_ADDR,
(len & 0xf) ? BCM_DMA_32BIT : BCM_DMA_128BIT);
psrc = sc->sc_sdhci_buffer_phys;
pdst = sc->dmamap_seg_addrs[idx];
sync_op = BUS_DMASYNC_PREREAD;
} else {
bcm_dma_setup_src(sc->sc_dma_ch, BCM_DMA_DREQ_NONE,
BCM_DMA_INC_ADDR,
(len & 0xf) ? BCM_DMA_32BIT : BCM_DMA_128BIT);
bcm_dma_setup_dst(sc->sc_dma_ch, BCM_DMA_DREQ_EMMC,
BCM_DMA_SAME_ADDR, BCM_DMA_32BIT);
psrc = sc->dmamap_seg_addrs[idx];
pdst = sc->sc_sdhci_buffer_phys;
sync_op = BUS_DMASYNC_PREWRITE;
}
/*
* When starting a new DMA operation do the busdma sync operation, and
* disable SDCHI data interrrupts because we'll be driven by DMA
* interrupts (or SDHCI error interrupts) until the IO is done.
*/
if (idx == 0) {
bus_dmamap_sync(sc->sc_dma_tag, sc->sc_dma_map, sync_op);
slot->intmask &= ~(SDHCI_INT_DATA_AVAIL |
SDHCI_INT_SPACE_AVAIL | SDHCI_INT_DATA_END);
bcm_sdhci_write_4(sc->sc_dev, &sc->sc_slot, SDHCI_SIGNAL_ENABLE,
slot->intmask);
}
/*
* Start the DMA transfer. Only programming errors (like failing to
* allocate a channel) cause a non-zero return from bcm_dma_start().
*/
err = bcm_dma_start(sc->sc_dma_ch, psrc, pdst, len);
KASSERT((err == 0), ("bcm2835_sdhci: failed DMA start"));
}
static void
bcm_sdhci_dma_intr(int ch, void *arg)
{
struct bcm_sdhci_softc *sc = (struct bcm_sdhci_softc *)arg;
struct sdhci_slot *slot = &sc->sc_slot;
uint32_t reg, mask;
int left, sync_op;
mtx_lock(&slot->mtx);
/*
* If there are more segments for the current dma, start the next one.
* Otherwise unload the dma map and decide what to do next based on the
* status of the sdhci controller and whether there's more data left.
*/
if (sc->dmamap_seg_index < sc->dmamap_seg_count) {
bcm_sdhci_start_dma_seg(sc);
mtx_unlock(&slot->mtx);
return;
}
if (slot->curcmd->data->flags & MMC_DATA_READ) {
sync_op = BUS_DMASYNC_POSTREAD;
mask = SDHCI_INT_DATA_AVAIL;
} else {
sync_op = BUS_DMASYNC_POSTWRITE;
mask = SDHCI_INT_SPACE_AVAIL;
}
bus_dmamap_sync(sc->sc_dma_tag, sc->sc_dma_map, sync_op);
bus_dmamap_unload(sc->sc_dma_tag, sc->sc_dma_map);
sc->dmamap_seg_count = 0;
sc->dmamap_seg_index = 0;
left = min(BCM_SDHCI_BUFFER_SIZE,
slot->curcmd->data->len - slot->offset);
/* DATA END? */
reg = bcm_sdhci_read_4(slot->bus, slot, SDHCI_INT_STATUS);
if (reg & SDHCI_INT_DATA_END) {
/* ACK for all outstanding interrupts */
bcm_sdhci_write_4(slot->bus, slot, SDHCI_INT_STATUS, reg);
/* enable INT */
slot->intmask |= SDHCI_INT_DATA_AVAIL | SDHCI_INT_SPACE_AVAIL
| SDHCI_INT_DATA_END;
bcm_sdhci_write_4(slot->bus, slot, SDHCI_SIGNAL_ENABLE,
slot->intmask);
/* finish this data */
sdhci_finish_data(slot);
}
else {
/* already available? */
if (reg & mask) {
/* ACK for DATA_AVAIL or SPACE_AVAIL */
bcm_sdhci_write_4(slot->bus, slot,
SDHCI_INT_STATUS, mask);
/* continue next DMA transfer */
if (bus_dmamap_load(sc->sc_dma_tag, sc->sc_dma_map,
(uint8_t *)slot->curcmd->data->data +
slot->offset, left, bcm_sdhci_dmacb, sc,
BUS_DMA_NOWAIT) != 0 || sc->dmamap_status != 0) {
slot->curcmd->error = MMC_ERR_NO_MEMORY;
sdhci_finish_data(slot);
} else {
bcm_sdhci_start_dma_seg(sc);
}
} else {
/* wait for next data by INT */
/* enable INT */
slot->intmask |= SDHCI_INT_DATA_AVAIL |
SDHCI_INT_SPACE_AVAIL | SDHCI_INT_DATA_END;
bcm_sdhci_write_4(slot->bus, slot, SDHCI_SIGNAL_ENABLE,
slot->intmask);
}
}
mtx_unlock(&slot->mtx);
}
static void
bcm_sdhci_read_dma(device_t dev, struct sdhci_slot *slot)
{
struct bcm_sdhci_softc *sc = device_get_softc(slot->bus);
size_t left;
if (sc->dmamap_seg_count != 0) {
device_printf(sc->sc_dev, "DMA in use\n");
return;
}
left = min(BCM_SDHCI_BUFFER_SIZE,
slot->curcmd->data->len - slot->offset);
KASSERT((left & 3) == 0,
("%s: len = %d, not word-aligned", __func__, left));
if (bus_dmamap_load(sc->sc_dma_tag, sc->sc_dma_map,
(uint8_t *)slot->curcmd->data->data + slot->offset, left,
bcm_sdhci_dmacb, sc, BUS_DMA_NOWAIT) != 0 ||
sc->dmamap_status != 0) {
slot->curcmd->error = MMC_ERR_NO_MEMORY;
return;
}
/* DMA start */
bcm_sdhci_start_dma_seg(sc);
}
static void
bcm_sdhci_write_dma(device_t dev, struct sdhci_slot *slot)
{
struct bcm_sdhci_softc *sc = device_get_softc(slot->bus);
size_t left;
if (sc->dmamap_seg_count != 0) {
device_printf(sc->sc_dev, "DMA in use\n");
return;
}
left = min(BCM_SDHCI_BUFFER_SIZE,
slot->curcmd->data->len - slot->offset);
KASSERT((left & 3) == 0,
("%s: len = %d, not word-aligned", __func__, left));
if (bus_dmamap_load(sc->sc_dma_tag, sc->sc_dma_map,
(uint8_t *)slot->curcmd->data->data + slot->offset, left,
bcm_sdhci_dmacb, sc, BUS_DMA_NOWAIT) != 0 ||
sc->dmamap_status != 0) {
slot->curcmd->error = MMC_ERR_NO_MEMORY;
return;
}
/* DMA start */
bcm_sdhci_start_dma_seg(sc);
}
static int
bcm_sdhci_will_handle_transfer(device_t dev, struct sdhci_slot *slot)
{
size_t left;
/*
* Do not use DMA for transfers less than block size or with a length
* that is not a multiple of four.
*/
left = min(BCM_DMA_BLOCK_SIZE,
slot->curcmd->data->len - slot->offset);
if (left < BCM_DMA_BLOCK_SIZE)
return (0);
if (left & 0x03)
return (0);
return (1);
}
static void
bcm_sdhci_start_transfer(device_t dev, struct sdhci_slot *slot,
uint32_t *intmask)
{
/* DMA transfer FIFO 1KB */
if (slot->curcmd->data->flags & MMC_DATA_READ)
bcm_sdhci_read_dma(dev, slot);
else
bcm_sdhci_write_dma(dev, slot);
}
static void
bcm_sdhci_finish_transfer(device_t dev, struct sdhci_slot *slot)
{
sdhci_finish_data(slot);
}
static device_method_t bcm_sdhci_methods[] = {
/* Device interface */
DEVMETHOD(device_probe, bcm_sdhci_probe),
DEVMETHOD(device_attach, bcm_sdhci_attach),
DEVMETHOD(device_detach, bcm_sdhci_detach),
/* Bus interface */
DEVMETHOD(bus_read_ivar, sdhci_generic_read_ivar),
DEVMETHOD(bus_write_ivar, sdhci_generic_write_ivar),
DEVMETHOD(bus_print_child, bus_generic_print_child),
/* MMC bridge interface */
DEVMETHOD(mmcbr_update_ios, sdhci_generic_update_ios),
DEVMETHOD(mmcbr_request, sdhci_generic_request),
DEVMETHOD(mmcbr_get_ro, bcm_sdhci_get_ro),
DEVMETHOD(mmcbr_acquire_host, sdhci_generic_acquire_host),
DEVMETHOD(mmcbr_release_host, sdhci_generic_release_host),
/* Platform transfer methods */
DEVMETHOD(sdhci_platform_will_handle, bcm_sdhci_will_handle_transfer),
DEVMETHOD(sdhci_platform_start_transfer, bcm_sdhci_start_transfer),
DEVMETHOD(sdhci_platform_finish_transfer, bcm_sdhci_finish_transfer),
/* SDHCI registers accessors */
DEVMETHOD(sdhci_read_1, bcm_sdhci_read_1),
DEVMETHOD(sdhci_read_2, bcm_sdhci_read_2),
DEVMETHOD(sdhci_read_4, bcm_sdhci_read_4),
DEVMETHOD(sdhci_read_multi_4, bcm_sdhci_read_multi_4),
DEVMETHOD(sdhci_write_1, bcm_sdhci_write_1),
DEVMETHOD(sdhci_write_2, bcm_sdhci_write_2),
DEVMETHOD(sdhci_write_4, bcm_sdhci_write_4),
DEVMETHOD(sdhci_write_multi_4, bcm_sdhci_write_multi_4),
{ 0, 0 }
};
static devclass_t bcm_sdhci_devclass;
static driver_t bcm_sdhci_driver = {
"sdhci_bcm",
bcm_sdhci_methods,
sizeof(struct bcm_sdhci_softc),
};
DRIVER_MODULE(sdhci_bcm, simplebus, bcm_sdhci_driver, bcm_sdhci_devclass, 0, 0);
MODULE_DEPEND(sdhci_bcm, sdhci, 1, 1, 1);
DRIVER_MODULE(mmc, sdhci_bcm, mmc_driver, mmc_devclass, NULL, NULL);
MODULE_DEPEND(sdhci_bcm, mmc, 1, 1, 1);
| TigerBSD/TigerBSD | FreeBSD/sys/arm/broadcom/bcm2835/bcm2835_sdhci.c | C | isc | 18,232 |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_putnbr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ayip <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/09/21 04:56:41 by ayip #+# #+# */
/* Updated: 2017/09/21 05:10:51 by ayip ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
void ft_putnbr(int nb)
{
char c;
if (nb == -2147483648)
{
write(1, "-2147483648", 11);
return ;
}
if (nb < 0)
{
write(1, "-", 1);
nb = 0 - nb;
}
if (nb >= 10)
ft_putnbr(nb / 10);
c = '0' + nb % 10;
write(1, &c, 1);
}
| ayip001/42 | libft/ft_putnbr.c | C | mit | 1,151 |
//
// OAAlarmWidget.h
// OsmAnd
//
// Created by Alexey Kulish on 29/12/2017.
// Copyright © 2017 OsmAnd. All rights reserved.
//
#import <Foundation/Foundation.h>
@protocol OAWidgetListener;
@interface OAAlarmWidget : UIView
@property (nonatomic, weak) id<OAWidgetListener> delegate;
- (BOOL) updateInfo;
@end
| Zahnstocher/OsmAnd-ios | Sources/Controllers/Map/Widgets/OAAlarmWidget.h | C | mit | 322 |
#!/bin/env bash
usage() {
cat >&2 << EOF
Usage: ${0##*/} <pid>...
Wait for <pid>... to finish execution.
EOF
}
main() {
if [[ -z $@ ]];then
usage
exit 1
fi
echo "PID's: $@" >&2
local -a pids=()
while [[ -n $1 ]]; do
check_pid_exists "$1" &
pids+=($!)
shift
done
progress &
rc=$!
wait ${pids[@]}
kill $rc
echo -e "\nwait complete" >&2
}
progress_output() {
case "$1" in
"0")
echo -ne "\rsleeping |"
;;
"1")
echo -ne "\rsleeping /"
;;
"2")
echo -ne "\rsleeping -"
;;
"3")
echo -ne "\rsleeping \\"
;;
*)
;;
esac
sleep 1
}
progress() {
declare -i cycle=0
while :; do
if (($cycle%4 == 0 ));then
let cycle=0
fi
progress_output $cycle >&2
let cycle++
done
}
check_pid_exists() {
while [[ -e "/proc/$1" ]]; do
sleep 1
done
}
main "$@"
| dgengtek/scripts | tools/wait_pid.sh | Shell | mit | 902 |
---
layout: post
title: "Daily Scrum and Sprints - The Scrum Guide Continued"
date: 2015-10-28 1:00:00
categories: scrum
tags: scrum
image:
---
Continued: We just finished discussing what a Sprint was and how it worked. Next we will look at the Daily Scrum, Sprint Reviews, and more.
[Reading Material](http://www.scrumguides.org/scrum-guide.html)
## Daily Scrum
The **Daily Scrum** is a **15 minute** time-boxed event for the Development Team. In the Daily Scrum, the team synchronizes activities and creates a plan for the next 24 hours. Work is inspected since the last Daily Scrum and work is forcasted for what can be done before the next one.
The Daily Scrum is held at the same time and place each day.
The Development Team members must explain:
* What did I do yesterday? Specifically, what did I do that helped the Development Team meet the Sprint Goal?
* What will I do today? Specifically, what will I do to help the Development Team meet the Sprint Goal?
* What implediments are preventing me from meeting the Sprint Goal?
Progress is inspected, helping ensure that the Development Team meets the Sprint Goal.
Only the Development Team members participate in the Daily Scrum; ensuring this is the job of the Scrum Master.
## Sprint Review
A **Sprint Review** is held at the end of the Sprint. In it, the Increment is inspected and the Product Backlog is adapted.
The Scrum Team and stakeholders collaborate about what was done in the Sprint.
The is a four hour time boxed meeting for one month Sprints. Two week Sprints usually have a 2 hour meeting.
The Increment is presented to elicit feedback and foster collaboration.
The following elements are part of the Sprint Review:
* The Scrum Team and stakeholders are invited by the Product Owner
* The Product Owner explains what Product Backlog items have been "Done" and what has not been "Done"
* The Development Team discusses what went well during the Sprint, what problems it ran into, and how those problems were solved
* The Development Team demonstrates the work that it has "Done" and answers questions about the Increment
* The Product Owner discusses the Product Backlog as it stands; projects likely completion dates based on the progress to date
* The entire group collaborates on what to do next, so that the Sprint Review provides valuable input into the next Sprint Planning
* Review of how the marketplace or potential use of the product might have changed what is the most valuable thing to do next
* Review of the timeline, budget, potential capabilities, and marketplace for the next anticipated release of the product
## Sprint Retropective
The **Sprint Retrospective** is an opportunity for the Scrum Team to inspect itself and create a plan for improvements to be enacted during the next Sprint.
The Sprint Retrospective occurs after the Sprint Review and prior to the next Sprint Planning.
It is time-boxed to 3 hours for 1 month Sprints. Or about 1 to 2 hours for two week Sprints.
The Scrum Master ensures that the event takes place ad that attendants understand its purpose. The Scrum Master teaches all to keep it within the time-box. The Scrum Master participates as a peer team member in the meeting from the accountability over the Scrum process.
The purpose of the Sprint Retrospective is to:
* Inspect how the last Sprint went with regards to people, relationships, process, and tools
* Identify and order the major items that went well and potential improvements
* Create a plan for implementing improvements to the way the Scrum Team does its work
The Scrum Master encourages the Scrum team to improve its development process and practices to make it more effective.
The Scrum Team plans ways to increase product quality by adapting the definition of "Done" as appropriate.
The Scrum Team should identify improvements that will be implemented in the next Sprint.
| idmontie/ProjectManagementBlog | _posts/2015-10-28-the-scrum-guide-continued.md | Markdown | mit | 3,888 |
<?php
namespace FreeAgent\Bitter\tests\units;
require_once __DIR__ . '/../../vendor/autoload.php';
use \mageekguy\atoum;
use \DateTime;
use FreeAgent\Bitter\Bitter as TestedBitter;
use FreeAgent\Bitter\UnitOfTime\Day;
/**
* @engine isolate
* @author Jérémy Romey <jeremy@free-agent.fr>
*/
class Bitter extends atoum\test
{
public function dataProviderTestedClients()
{
$clients = array(
new \Predis\Client(),
);
if (class_exists('\Redis')) {
$conn = new \Redis();
$conn->connect('127.0.0.1');
$clients[] = $conn;
}
return $clients;
}
private function getPrefixKey()
{
return 'test_bitter:';
}
private function getPrefixTempKey()
{
return 'test_bitter_temp:';
}
private function removeAll($redisClient)
{
$keys_chunk = array_chunk($redisClient->keys($this->getPrefixKey() . '*'), 100);
foreach ($keys_chunk as $keys) {
$redisClient->del($keys);
}
$keys_chunk = array_chunk($redisClient->keys($this->getPrefixTempKey() . '*'), 100);
foreach ($keys_chunk as $keys) {
$redisClient->del($keys);
}
}
/**
* @dataProvider dataProviderTestedClients
*/
public function testConstruct($redisClient)
{
$bitter = new TestedBitter($redisClient, $this->getPrefixKey(), $this->getPrefixTempKey());
$this
->object($bitter->getRedisClient())
->isIdenticalTo($redisClient)
;
}
/**
* @dataProvider dataProviderTestedClients
*/
public function testMarkUnitOfTime($redisClient)
{
$bitter = new TestedBitter($redisClient, $this->getPrefixKey(), $this->getPrefixTempKey());
$this->removeAll($redisClient);
$dateTime = DateTime::createFromFormat('Y-m-d H:i:s', '2012-11-06 15:30:45');
$day = new Day('drink_a_bitter_beer', $dateTime);
$this
->integer($bitter->count($day))
->isIdenticalTo(0)
;
$this
->boolean($bitter->in(404, $day))
->isFalse()
;
$this
->object($bitter->mark('drink_a_bitter_beer', 404, $dateTime))
->isIdenticalTo($bitter)
;
$this
->integer($bitter->count($day))
->isIdenticalTo(1)
;
$this
->boolean($bitter->in(404, $day))
->isTrue()
;
// Adding it a second time with the same dateTime !
$bitter->mark('drink_a_bitter_beer', 404, $dateTime);
$this
->integer($bitter->count($day))
->isIdenticalTo(1)
;
$this
->boolean($bitter->in(404, $day))
->isTrue()
;
$this->removeAll($redisClient);
$day = new Day('drink_a_bitter_beer', new DateTime());
$this
->boolean($bitter->in(13, $day))
->isFalse()
;
$bitter->mark('drink_a_bitter_beer', 13);
$this
->boolean($bitter->in(13, $day))
->isTrue()
;
$this->removeAll($redisClient);
}
/**
* @dataProvider dataProviderTestedClients
*/
public function testbitOpAnd($redisClient)
{
$bitter = new TestedBitter($redisClient, $this->getPrefixKey(), $this->getPrefixTempKey());
$this->removeAll($redisClient);
$yesterday = new Day('drink_a_bitter_beer', new DateTime('yesterday'));
$today = new Day('drink_a_bitter_beer', new DateTime('today'));
$bitter->mark('drink_a_bitter_beer', 13, new DateTime('today'));
$bitter->mark('drink_a_bitter_beer', 13, new DateTime('yesterday'));
$bitter->mark('drink_a_bitter_beer', 404, new DateTime('yesterday'));
$this
->object($bitter->bitOpAnd('test_a', $today, $yesterday))
->isIdenticalTo($bitter)
;
$this
->boolean($bitter->bitOpAnd('test_b', $today, $yesterday)->in(13, 'test_b'))
->isTrue()
;
$this
->boolean($bitter->bitOpAnd('test_c', $today, $yesterday)->in(404, 'test_c'))
->isFalse()
;
$this->removeAll($redisClient);
}
/**
* @dataProvider dataProviderTestedClients
*/
public function testbitOpOr($redisClient)
{
$bitter = new TestedBitter($redisClient, $this->getPrefixKey(), $this->getPrefixTempKey());
$this->removeAll($redisClient);
$twoDaysAgo = new Day('drink_a_bitter_beer', new DateTime('2 days ago'));
$yesterday = new Day('drink_a_bitter_beer', new DateTime('yesterday'));
$today = new Day('drink_a_bitter_beer', new DateTime('today'));
$bitter->mark('drink_a_bitter_beer', 13, new DateTime('today'));
$bitter->mark('drink_a_bitter_beer', 13, new DateTime('yesterday'));
$bitter->mark('drink_a_bitter_beer', 404, new DateTime('yesterday'));
$this
->object($bitter->bitOpOr('test_a', $today, $yesterday))
->isIdenticalTo($bitter)
;
$this
->boolean($bitter->bitOpOr('test_b', $today, $yesterday)->in(13, 'test_b'))
->isTrue()
;
$this
->boolean($bitter->bitOpOr('test_c', $today, $twoDaysAgo)->in(13, 'test_c'))
->isTrue()
;
$this
->boolean($bitter->bitOpOr('test_d', $today, $twoDaysAgo)->in(404, 'test_d'))
->isFalse()
;
$this->removeAll($redisClient);
}
/**
* @dataProvider dataProviderTestedClients
*/
public function testbitOpXor($redisClient)
{
$bitter = new TestedBitter($redisClient, $this->getPrefixKey(), $this->getPrefixTempKey());
$this->removeAll($redisClient);
$yesterday = new Day('drink_a_bitter_beer', new DateTime('yesterday'));
$today = new Day('drink_a_bitter_beer', new DateTime('today'));
$bitter->mark('drink_a_bitter_beer', 13, new DateTime('today'));
$bitter->mark('drink_a_bitter_beer', 13, new DateTime('yesterday'));
$bitter->mark('drink_a_bitter_beer', 404, new DateTime('yesterday'));
$this
->object($bitter->bitOpXor('test_a', $today, $yesterday))
->isIdenticalTo($bitter)
;
$this
->boolean($bitter->bitOpXor('test_b', $today, $yesterday)->in(13, 'test_b'))
->isFalse()
;
$this
->boolean($bitter->bitOpXor('test_c', $today, $yesterday)->in(404, 'test_c'))
->isTrue()
;
$this->removeAll($redisClient);
}
/**
* @dataProvider dataProviderTestedClients
*/
public function testBitDateRange($redisClient)
{
$bitter = new TestedBitter($redisClient, $this->getPrefixKey(), $this->getPrefixTempKey());
$this->removeAll($redisClient);
$dateTime = DateTime::createFromFormat('Y-m-d H:i:s', '2011-11-06 15:30:45');
$bitter->mark('drink_a_bitter_beer', 1, $dateTime);
$dateTime = DateTime::createFromFormat('Y-m-d H:i:s', '2012-10-12 15:30:45');
$bitter->mark('drink_a_bitter_beer', 2, $dateTime);
$this
->if($from = DateTime::createFromFormat('Y-m-d H:i:s', '2012-10-05 15:30:45'))
->and($to = DateTime::createFromFormat('Y-m-d H:i:s', '2012-12-07 15:30:45'))
->and($bitter->bitDateRange('drink_a_bitter_beer', 'test_create_date_period', $from, $to))
->then()
->object($bitter->bitDateRange('drink_a_bitter_beer', 'test_create_date_period', $from, $to))
->isIdenticalTo($bitter)
;
$this
->if($prefixKey = $this->getPrefixKey())
->and($prefixTempKey = $this->getPrefixTempKey())
->exception(
function() use ($redisClient, $prefixKey, $prefixTempKey) {
$bitter = new TestedBitter($redisClient, $prefixKey, $prefixTempKey);
$from = DateTime::createFromFormat('Y-m-d H:i:s', '2012-12-07 15:30:45');
$to = DateTime::createFromFormat('Y-m-d H:i:s', '2012-12-07 14:30:45');
$bitter->bitDateRange('drink_a_bitter_beer', 'test_create_date_period', $from, $to);
}
)
->hasMessage("DateTime from (2012-12-07 15:30:45) must be anterior to DateTime to (2012-12-07 14:30:45).")
;
$this
->if($from = DateTime::createFromFormat('Y-m-d H:i:s', '2010-10-05 20:30:45'))
->and($to = DateTime::createFromFormat('Y-m-d H:i:s', '2012-12-07 12:30:45'))
->and($bitter->bitDateRange('drink_a_bitter_beer', 'test_create_date_period', $from, $to))
->then()
->boolean($bitter->in(1, 'test_create_date_period'))
->isTrue()
->boolean($bitter->in(2, 'test_create_date_period'))
->isTrue()
->integer($bitter->count('test_create_date_period'))
->isEqualTo(2)
;
$this
->if($from = DateTime::createFromFormat('Y-m-d H:i:s', '2012-09-05 20:30:45'))
->and($to = DateTime::createFromFormat('Y-m-d H:i:s', '2012-12-07 12:30:45'))
->and($bitter->bitDateRange('drink_a_bitter_beer', 'test_create_date_period', $from, $to))
->then()
->boolean($bitter->in(1, 'test_create_date_period'))
->isFalse()
->boolean($bitter->in(2, 'test_create_date_period'))
->isTrue()
->integer($bitter->count('test_create_date_period'))
->isEqualTo(1)
;
$this->removeAll($redisClient);
}
/**
* @dataProvider dataProviderTestedClients
*/
public function testGetIds($redisClient)
{
$bitter = new TestedBitter($redisClient, $this->getPrefixKey(), $this->getPrefixTempKey());
$this->removeAll($redisClient);
$eventKey = 'liloo_multipass';
$dateTime = new DateTime('2012-10-12 15:30:45');
$event = new Day($eventKey, $dateTime);
$ids = array(1, 13, 404, 2, 12700042, 13003, 99);
foreach ($ids as $id) {
$bitter->mark($eventKey, $id, $dateTime);
}
sort($ids);
$this
->array($bitter->getIds($event))
->isIdenticalTo($ids)
;
$this->removeAll($redisClient);
}
/**
* @dataProvider dataProviderTestedClients
*/
public function testRemoveAll($redisClient)
{
$this->removeAll($redisClient);
$this
->array($redisClient->keys($this->getPrefixKey() . '*'))
->isEmpty()
;
$bitter = new TestedBitter($redisClient, $this->getPrefixKey(), $this->getPrefixTempKey());
$yesterday = new Day('drink_a_bitter_beer', new DateTime('yesterday'));
$today = new Day('drink_a_bitter_beer', new DateTime('today'));
$bitter->mark('drink_a_bitter_beer', 13, new DateTime('today'));
$bitter->mark('drink_a_bitter_beer', 13, new DateTime('yesterday'));
$bitter->mark('drink_a_bitter_beer', 404, new DateTime('yesterday'));
$this
->array($redisClient->keys($this->getPrefixKey() . '*'))
->isNotEmpty()
;
$this
->object($bitter->removeAll())
->isIdenticalTo($bitter)
;
$this
->array($redisClient->keys($this->getPrefixKey() . '*'))
->strictlyContains($this->getPrefixKey() . 'keys')
;
$this->removeAll($redisClient);
}
/**
* @dataProvider dataProviderTestedClients
*/
public function testRemoveTemp($redisClient)
{
$keys_chunk = array_chunk($redisClient->keys($this->getPrefixKey() . '*'), 100);
foreach ($keys_chunk as $keys) {
$redisClient->del($keys);
}
$this
->array($redisClient->keys($this->getPrefixKey() . '*'))
->isEmpty()
;
$bitter = new TestedBitter($redisClient, $this->getPrefixKey(), $this->getPrefixTempKey());
$yesterday = new Day('drink_a_bitter_beer', new DateTime('yesterday'));
$today = new Day('drink_a_bitter_beer', new DateTime('today'));
$bitter->mark('drink_a_bitter_beer', 13, new DateTime('today'));
$bitter->mark('drink_a_bitter_beer', 13, new DateTime('yesterday'));
$bitter->mark('drink_a_bitter_beer', 404, new DateTime('yesterday'));
$bitter->bitOpOr('test_b', $today, $yesterday);
$this
->array($redisClient->keys($this->getPrefixKey() . '*'))
->isNotEmpty()
;
$this
->array($redisClient->keys($this->getPrefixTempKey() . '*'))
->isNotEmpty()
;
$this
->object($bitter->removeTemp())
->isIdenticalTo($bitter)
;
$this
->array($redisClient->keys($this->getPrefixTempKey() . '*'))
->strictlyContains($this->getPrefixTempKey() . 'keys')
;
$this
->array($redisClient->keys($this->getPrefixKey() . '*'))
->isNotEmpty()
;
// Expire timeout
$this->removeAll($redisClient);
$bitter = new TestedBitter($redisClient, $this->getPrefixKey(), $this->getPrefixTempKey(), 2);
$bitter->mark('drink_a_bitter_beer', 13, new DateTime('today'));
$bitter->mark('drink_a_bitter_beer', 13, new DateTime('yesterday'));
$bitter->mark('drink_a_bitter_beer', 404, new DateTime('yesterday'));
$bitter->bitOpOr('test_b', $today, $yesterday);
$this
->array($redisClient->keys($this->getPrefixTempKey() . '*'))
->isNotEmpty()
;
sleep(3);
$this
->array($redisClient->keys($this->getPrefixTempKey() . '*'))
->strictlyContains($this->getPrefixTempKey() . 'keys')
;
$this->removeAll($redisClient);
}
}
| jeremyFreeAgent/Bitter | tests/units/Bitter.php | PHP | mit | 14,112 |
@(title: String)(style: Html)(content: Html)
<!DOCTYPE html>
<html lang="en">
<head>
<title>@title</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
@style
</head>
<body>
<div class="container">
@content
</div>
</body>
</html>
| davidgraig/foosball | server/app/views/main.scala.html | HTML | mit | 304 |
<?php
/*
* Created on 2013-5-31
*
* To change the template for this generated file go to
* Window - Preferences - PHPeclipse - PHP - Code Templates
*/
class config_content
{
public $fields = array('contentid','contentcatid','contentmoduleid','contentuserid','contentusername','contenttitle','contentthumb','contentlink','contentinputtime','contentmodifytime','contentsequence','contentdescribe','contentstatus','contenttemplate','contenttext');
}
?>
| PhotoArtLife/Personal-Blog | project/demo/kaoshi/app/content/cls/config.cls.php | PHP | mit | 468 |
## Submit a feature request or bug report
- [ ] I've read the guidelines for Contributing to this project in the README.md
- [ ] This is a feature request
- [ ] This is a bug report
- [ ] This request isn't a duplicate of an [existing issue](https://github.com/helloensoul/rankz/issues)
- [ ] I've read the [README](https://github.com/helloensoul/rankz/blob/master/README.md) and followed its instructions (if applicable)
Replace any `X` with your information.
---
**What is the current behavior?**
X
**What is the expected or desired behavior?**
X
---
## Bug report
(delete this section if not applicable)
**Please provide steps to reproduce, including full log output:**
X
**Please describe your local environment:**
Rankz version: X
WordPress version: X
Active theme: X
Active plugins: X
**Where did the bug happen? Development or remote servers?**
X
---
## Feature Request
(delete this section if not applicable)
**Please provide use cases for changing the current behavior:**
X
**Other relevant information:**
X
| valentinocossar/ranks | .github/ISSUE_TEMPLATE.md | Markdown | mit | 1,044 |
module Fe
class OptionGroup
attr_reader :label
attr_reader :group
def initialize(label, group)
@label = label
@group = group
end
end
end
| CruGlobal/qe | app/models/fe/option_group.rb | Ruby | mit | 169 |
package vezzoni.api.controller.impl;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import vezzoni.api.controller.PingController;
@Path(value = "/ping")
@Consumes(value = {MediaType.WILDCARD})
@Produces(value = {MediaType.APPLICATION_JSON})
public class PingControllerImpl implements PingController {
@GET
@Path(value = "/")
@Produces(value = {MediaType.TEXT_HTML})
@Override
public Response ping() {
return Response
.status(Response.Status.OK)
.entity("PONG")
.build();
}
}
| vezzoni/rest-easy-spring-jpa | src/main/java/vezzoni/api/controller/impl/PingControllerImpl.java | Java | mit | 692 |
const log = msg => console.log(msg);
module.exports = log;
| JoeKarlsson1/bechdel-test | src/server/helper/log.js | JavaScript | mit | 60 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2018 Karl STEIN
*
* 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.
*/
let Router = window.Router;
function getTemplate(name) {
let tpl = $("template[name=\"" + name + "\"]");
if (tpl.length) {
return tpl.eq(0).html();
}
}
let userIsConnected = false;
Router.autoRun = true;
Router.on("route", function () {
console.log("go to " + this.path);
});
Router.on("beforeRender", function () {
console.log("before " + this.path);
});
Router.on("afterRender", function () {
console.log("after " + this.path);
});
// Declare not found route
Router.notFound = function () {
this.render(getTemplate("not-found"));
};
// Declare root route
Router.route("/", {
name: "home",
action: function () {
this.render(getTemplate("home"));
this.on("leave", function () {
console.log("good bye Home");
});
}
});
Router.route("/pages/:id", {
name: "page",
action: function () {
this.render(getTemplate("page-" + this.params.id));
this.on("leave", function () {
let field = $("[name=field]").val();
if (typeof field === "string" && field.length) {
return confirm("Are you sure you want to quit this page ?");
}
});
}
});
Router.route("/forbidden", {
action: function () {
this.render(getTemplate("forbidden"));
}
});
Router.route("/form", {
action: function () {
this.render(getTemplate("form"));
}
});
Router.route("/login", {
action: function () {
userIsConnected = true;
this.render(getTemplate("login"));
}
});
Router.route("/logout", {
action: function () {
userIsConnected = false;
this.render(getTemplate("logout"));
}
});
Router.route("/account", {
action: function () {
if (userIsConnected) {
this.render(getTemplate("account"));
} else {
this.redirect("/login");
}
}
});
| jalik/jk-router | docs/routes.js | JavaScript | mit | 3,052 |
namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models
{
public class AddBasketItemRequest
{
public int CatalogItemId { get; set; }
public string BasketId { get; set; }
public int Quantity { get; set; }
public AddBasketItemRequest()
{
Quantity = 1;
}
}
}
| albertodall/eShopOnContainers | src/ApiGateways/Mobile.Bff.Shopping/aggregator/Models/AddBasketItemRequest.cs | C# | mit | 354 |
#pragma once
#include <ev++.h>
#include <functional>
#include <cstdint>
#include "lev/lev.h"
namespace lev
{
class loop;
class timer
{
public:
typedef std::function<void()> TimerFiredEvent;
timer(loop& loop);
void StartOneShot(uint32_t ms, TimerFiredEvent func = nullptr);
void StartInterval(uint32_t intervalms, TimerFiredEvent func = nullptr);
// in milliseconds
void StartTimer(uint32_t ms, uint32_t repeat_ms = 0);
void StopTimer();
TimerFiredEvent OnTimerFired;
private:
ev::timer m_timer;
};
}; | ksophocleous/levlib | include/lev/timer.h | C | mit | 547 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html><head><title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>
<script type="text/javascript" src="search.js"></script>
</head>
<body class="SRPage">
<div id="SRIndex">
<div class="SRStatus" id="Loading">Loading...</div>
<div class="SRResult" id="SR_tester_2eh">
<div class="SREntry">
<a id="Item0" onkeydown="return searchResults.Nav(event,0)" onkeypress="return searchResults.Nav(event,0)" onkeyup="return searchResults.Nav(event,0)" class="SRSymbol" href="../tester_8h.html" target="_parent">tester.h</a>
</div>
</div>
<div class="SRResult" id="SR_time_2eh">
<div class="SREntry">
<a id="Item1" onkeydown="return searchResults.Nav(event,1)" onkeypress="return searchResults.Nav(event,1)" onkeyup="return searchResults.Nav(event,1)" class="SRSymbol" href="../time_8h.html" target="_parent">time.h</a>
</div>
</div>
<div class="SRResult" id="SR_typedefs_2eh">
<div class="SREntry">
<a id="Item2" onkeydown="return searchResults.Nav(event,2)" onkeypress="return searchResults.Nav(event,2)" onkeyup="return searchResults.Nav(event,2)" class="SRSymbol" href="../typedefs_8h.html" target="_parent">typedefs.h</a>
</div>
</div>
<div class="SRStatus" id="Searching">Searching...</div>
<div class="SRStatus" id="NoMatches">No Matches</div>
<script type="text/javascript"><!--
document.getElementById("Loading").style.display="none";
document.getElementById("NoMatches").style.display="none";
var searchResults = new SearchResults("searchResults");
searchResults.Search();
--></script>
</div>
</body>
</html>
| XadillaX/node-simple-ini | src/miniini-0.9/doc/html/search/files_74.html | HTML | mit | 1,729 |
"""Migrate review conditions from settings
Revision ID: 933665578547
Revises: 02bf20df06b3
Create Date: 2020-04-02 11:13:58.931020
"""
import json
from collections import defaultdict
from uuid import uuid4
from alembic import context, op
from indico.modules.events.editing.models.editable import EditableType
# revision identifiers, used by Alembic.
revision = '933665578547'
down_revision = '02bf20df06b3'
branch_labels = None
depends_on = None
def upgrade():
if context.is_offline_mode():
raise Exception('This upgrade is only possible in online mode')
conn = op.get_bind()
for type_ in EditableType:
res = conn.execute(
"SELECT event_id, value FROM events.settings WHERE module = 'editing' AND name = %s",
(f'{type_.name}_review_conditions',),
)
for event_id, value in res:
for condition in value:
res2 = conn.execute(
'INSERT INTO event_editing.review_conditions (type, event_id) VALUES (%s, %s) RETURNING id',
(type_, event_id),
)
revcon_id = res2.fetchone()[0]
for file_type in condition[1]:
conn.execute('''
INSERT INTO event_editing.review_condition_file_types (file_type_id, review_condition_id)
VALUES (%s, %s)
''', (file_type, revcon_id),
)
conn.execute(
"DELETE FROM events.settings WHERE module = 'editing' AND name = %s",
(f'{type_.name}_review_conditions',),
)
def downgrade():
if context.is_offline_mode():
raise Exception('This upgrade is only possible in online mode')
conn = op.get_bind()
for type_ in EditableType:
res = conn.execute('SELECT id, event_id FROM event_editing.review_conditions WHERE type = %s', (type_.value,))
review_conditions = defaultdict(list)
for id, event_id in res:
file_types = conn.execute(
'SELECT file_type_id FROM event_editing.review_condition_file_types WHERE review_condition_id = %s',
(id,),
)
value = [str(uuid4()), [f[0] for f in file_types.fetchall()]]
review_conditions[event_id].append(value)
for key, value in review_conditions.items():
conn.execute(
"INSERT INTO events.settings (event_id, module, name, value) VALUES (%s, 'editing', %s, %s)",
(key, f'{type_.name}_review_conditions', json.dumps(value)),
)
conn.execute('DELETE FROM event_editing.review_condition_file_types')
conn.execute('DELETE FROM event_editing.review_conditions')
| ThiefMaster/indico | indico/migrations/versions/20200402_1113_933665578547_migrate_review_conditions_from_settings.py | Python | mit | 2,739 |
"""
PynamoDB exceptions
"""
from typing import Any, Optional
import botocore.exceptions
class PynamoDBException(Exception):
"""
A common exception class
"""
def __init__(self, msg: Optional[str] = None, cause: Optional[Exception] = None) -> None:
self.msg = msg
self.cause = cause
super(PynamoDBException, self).__init__(self.msg)
@property
def cause_response_code(self) -> Optional[str]:
return getattr(self.cause, 'response', {}).get('Error', {}).get('Code')
@property
def cause_response_message(self) -> Optional[str]:
return getattr(self.cause, 'response', {}).get('Error', {}).get('Message')
class PynamoDBConnectionError(PynamoDBException):
"""
A base class for connection errors
"""
msg = "Connection Error"
class DeleteError(PynamoDBConnectionError):
"""
Raised when an error occurs deleting an item
"""
msg = "Error deleting item"
class QueryError(PynamoDBConnectionError):
"""
Raised when queries fail
"""
msg = "Error performing query"
class ScanError(PynamoDBConnectionError):
"""
Raised when a scan operation fails
"""
msg = "Error performing scan"
class PutError(PynamoDBConnectionError):
"""
Raised when an item fails to be created
"""
msg = "Error putting item"
class UpdateError(PynamoDBConnectionError):
"""
Raised when an item fails to be updated
"""
msg = "Error updating item"
class GetError(PynamoDBConnectionError):
"""
Raised when an item fails to be retrieved
"""
msg = "Error getting item"
class TableError(PynamoDBConnectionError):
"""
An error involving a dynamodb table operation
"""
msg = "Error performing a table operation"
class DoesNotExist(PynamoDBException):
"""
Raised when an item queried does not exist
"""
msg = "Item does not exist"
class TableDoesNotExist(PynamoDBException):
"""
Raised when an operation is attempted on a table that doesn't exist
"""
def __init__(self, table_name: str) -> None:
msg = "Table does not exist: `{}`".format(table_name)
super(TableDoesNotExist, self).__init__(msg)
class TransactWriteError(PynamoDBException):
"""
Raised when a TransactWrite operation fails
"""
pass
class TransactGetError(PynamoDBException):
"""
Raised when a TransactGet operation fails
"""
pass
class InvalidStateError(PynamoDBException):
"""
Raises when the internal state of an operation context is invalid
"""
msg = "Operation in invalid state"
class AttributeDeserializationError(TypeError):
"""
Raised when attribute type is invalid
"""
def __init__(self, attr_name: str, attr_type: str):
msg = "Cannot deserialize '{}' attribute from type: {}".format(attr_name, attr_type)
super(AttributeDeserializationError, self).__init__(msg)
class AttributeNullError(ValueError):
def __init__(self, attr_name: str) -> None:
self.attr_path = attr_name
def __str__(self):
return f"Attribute '{self.attr_path}' cannot be None"
def prepend_path(self, attr_name: str) -> None:
self.attr_path = attr_name + '.' + self.attr_path
class VerboseClientError(botocore.exceptions.ClientError):
def __init__(self, error_response: Any, operation_name: str, verbose_properties: Optional[Any] = None):
""" Modify the message template to include the desired verbose properties """
if not verbose_properties:
verbose_properties = {}
self.MSG_TEMPLATE = (
'An error occurred ({{error_code}}) on request ({request_id}) '
'on table ({table_name}) when calling the {{operation_name}} '
'operation: {{error_message}}'
).format(request_id=verbose_properties.get('request_id'), table_name=verbose_properties.get('table_name'))
super(VerboseClientError, self).__init__(error_response, operation_name)
| pynamodb/PynamoDB | pynamodb/exceptions.py | Python | mit | 4,009 |
@extends('app')
@section('title', trans('access.title_edit_access'))
@section('content')
@include('errors.form-error')
{!! Form::model($access, ['route' => ['project.access.update', $project->slug, $access], 'method' => 'PUT']) !!}
@include('accesses.form')
{!! Form::close() !!}
{!! Form::model($project, ['route' => ['project.access.destroy', $project->slug, $access], 'method' => 'DELETE']) !!}
<div class="form-group">
{!! Form::submit(trans('access.delete'), ['class' => 'btn btn-primary'])!!}
</div>
{!! Form::close() !!}
@endsection | Fwagra/Gazl | resources/views/accesses/edit.blade.php | PHP | mit | 570 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.