repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
ZhnZhn/ZhnZhn.github.io
src/constants/WatchDefault.js
const WatchDefault = { groups : [ { caption : 'Economic Metrics', lists : [ { caption : 'List1'}, { caption : 'List2'}, { caption : 'List3'} ] }, { caption : 'Currencies' , lists : [ { caption : 'List1' }, { caption : 'List2' }, { caption : 'List3' } ] }, { caption : 'Commodities', lists : [ { caption : 'List1' }, { caption : 'List2' }, { caption : 'List3' } ] }, { caption : 'Stocks' , lists : [ { caption : 'List1' }, { caption : 'List2' }, { caption : 'List3' } ] }, { caption : 'Indexes', lists : [ { caption : 'List1' }, { caption : 'List2' }, { caption : 'List3' } ] }, { caption : 'Futures', lists : [ { caption : 'List1' }, { caption : 'List2' }, { caption : 'List3' } ] } ] } export default WatchDefault
ptoussai/dito
packages/utils/src/object/equals.test.js
<gh_stars>10-100 import { equals } from './equals' describe('equals()', () => { const symbol1 = Symbol('a') const symbol2 = Symbol('b') describe.each([ [1, 1, true], [1, Object(1), true], [1, '1', false], [1, 2, false], [-0, -0, true], [0, 0, true], [0, Object(0), true], [Object(0), Object(0), true], [-0, 0, true], [0, '0', false], [0, null, false], [NaN, NaN, true], [NaN, Object(NaN), true], [Object(NaN), Object(NaN), true], [NaN, 'a', false], [NaN, Infinity, false], ['a', 'a', true], ['a', Object('a'), true], [Object('a'), Object('a'), true], ['a', 'b', false], ['a', ['a'], false], [true, true, true], [true, Object(true), true], [Object(true), Object(true), true], [true, 1, false], [true, 'a', false], [false, false, true], [false, Object(false), true], [Object(false), Object(false), true], [false, 0, false], [false, '', false], [symbol1, symbol1, true], [symbol1, Object(symbol1), true], [Object(symbol1), Object(symbol1), true], [symbol1, symbol2, false], [null, null, true], [null, undefined, false], [null, {}, false], [null, '', false], [undefined, undefined, true], [undefined, null, false], [undefined, '', false] ])( 'equals(%o, %o) (should compare primitives)', (a, b, expected) => { it(`returns ${expected}`, () => { expect(equals(a, b)).toBe(expected) }) } ) it('should compare arrays', () => { let array1 = [true, null, 1, 'a', undefined] let array2 = [true, null, 1, 'a', undefined] expect(equals(array1, array2)).toBe(true) array1 = [[1, 2, 3], new Date(2012, 4, 23), /x/, { e: 1 }] array2 = [[1, 2, 3], new Date(2012, 4, 23), /x/, { e: 1 }] expect(equals(array1, array2)).toBe(true) array1 = [1] array1[2] = 3 array2 = [1] array2[1] = undefined array2[2] = 3 expect(equals(array1, array2)).toBe(true) array1 = [ Object(1), false, Object('a'), /x/, new Date(2012, 4, 23), ['a', 'b', [Object('c')]], { a: 1 } ] array2 = [ 1, Object(false), 'a', /x/, new Date(2012, 4, 23), ['a', Object('b'), ['c']], { a: 1 } ] expect(equals(array1, array2)).toBe(true) array1 = [1, 2, 3] array2 = [3, 2, 1] expect(equals(array1, array2)).toBe(false) array1 = [1, 2] array2 = [1, 2, 3] expect(equals(array1, array2)).toBe(false) }) it(`should treat arrays with identical values but different non-index properties as equal`, () => { let array1 = [1, 2, 3] let array2 = [1, 2, 3] array1.every = array1.filter = array1.forEach = array1.indexOf = array1.lastIndexOf = array1.map = array1.some = array1.reduce = array1.reduceRight = null array2.concat = array2.join = array2.pop = array2.reverse = array2.shift = array2.slice = array2.sort = array2.splice = array2.unshift = null expect(equals(array1, array2)).toBe(true) array1 = [1, 2, 3] array1.a = 1 array2 = [1, 2, 3] array2.b = 1 expect(equals(array1, array2)).toBe(true) array1 = /c/.exec('abcde') array2 = ['c'] expect(equals(array1, array2)).toBe(true) }) it('should compare sparse arrays', () => { const array = Array(1) expect(equals(array, Array(1))).toBe(true) expect(equals(array, [undefined])).toBe(true) expect(equals(array, Array(2))).toBe(false) }) it('should compare plain objects', () => { let object1 = { a: true, b: null, c: 1, d: 'a', e: undefined } let object2 = { a: true, b: null, c: 1, d: 'a', e: undefined } expect(equals(object1, object2)).toBe(true) object1 = { a: [1, 2, 3], b: new Date(2012, 4, 23), c: /x/, d: { e: 1 } } object2 = { a: [1, 2, 3], b: new Date(2012, 4, 23), c: /x/, d: { e: 1 } } expect(equals(object1, object2)).toBe(true) object1 = { a: 1, b: 2, c: 3 } object2 = { a: 3, b: 2, c: 1 } expect(equals(object1, object2)).toBe(false) object1 = { a: 1, b: 2, c: 3 } object2 = { d: 1, e: 2, f: 3 } expect(equals(object1, object2)).toBe(false) object1 = { a: 1, b: 2 } object2 = { a: 1, b: 2, c: 3 } expect(equals(object1, object2)).toBe(false) }) it('should compare objects regardless of key order', () => { const object1 = { a: 1, b: 2, c: 3 } const object2 = { c: 3, a: 1, b: 2 } expect(equals(object1, object2)).toBe(true) }) it('should compare nested objects', () => { function noop() {} const object1 = { a: [1, 2, 3], b: true, c: Object(1), d: 'a', e: { f: ['a', Object('b'), 'c'], g: Object(false), h: new Date(2012, 4, 23), i: noop, j: 'a' } } const object2 = { a: [1, Object(2), 3], b: Object(true), c: 1, d: Object('a'), e: { f: ['a', 'b', 'c'], g: false, h: new Date(2012, 4, 23), i: noop, j: 'a' } } expect(equals(object1, object2)).toBe(true) }) it('should compare objects with shared property values', () => { const object1 = { a: [1, 2] } const object2 = { a: [1, 2], b: [1, 2] } object1.b = object1.a expect(equals(object1, object2)).toBe(true) }) it('should avoid common type coercions', () => { expect(equals(true, Object(false))).toBe(false) expect(equals(Object(false), Object(0))).toBe(false) expect(equals(false, Object(''))).toBe(false) expect(equals(Object(36), Object('36'))).toBe(false) expect(equals(0, '')).toBe(false) expect(equals(1, true)).toBe(false) expect(equals(1337756400000, new Date(2012, 4, 23))).toBe(false) expect(equals('36', 36)).toBe(false) expect(equals(36, '36')).toBe(false) }) it('should compare functions', () => { function a() { return 1 + 2 } function b() { return 1 + 2 } expect(equals(a, a)).toBe(true) expect(equals(a, b)).toBe(false) }) })
pelagios/peripleo2
app/controllers/api/admin/TaskAPIController.scala
<reponame>pelagios/peripleo2 package controllers.api.admin import com.mohiva.play.silhouette.api.Silhouette import controllers.{BaseAuthController, HasPrettyPrintJSON, Security} import javax.inject.{Inject, Singleton} import play.api.Configuration import play.api.libs.json.Json import play.api.mvc.{AbstractController, AnyContent, ControllerComponents, Request } import services.task.TaskService import scala.concurrent.ExecutionContext import services.task.TaskType import services.user.{UserService, Role} @Singleton class TaskAPIController @Inject() ( val components: ControllerComponents, val config: Configuration, val users: UserService, val taskService: TaskService, val silhouette: Silhouette[Security.Env], implicit val ctx: ExecutionContext ) extends BaseAuthController(components) with HasPrettyPrintJSON { def list(typeFilter: Option[String], offset: Int, limit: Int) = silhouette.SecuredAction(Security.WithRole(Role.ADMIN)).async { implicit request => val f = typeFilter match { case Some(taskType) => taskService.findByType(TaskType(taskType), offset, limit) case None => taskService.listAll(offset, limit) } f.map { page => jsonOk(Json.toJson(page)) } } }
MrLiuFang/pepper-discreteness
discreteness-cache/discreteness-cache-business/src/main/java/com/pepper/service/redis/string/serializer/impl/StringRedisTemplateServiceImpl.java
<reponame>MrLiuFang/pepper-discreteness<filename>discreteness-cache/discreteness-cache-business/src/main/java/com/pepper/service/redis/string/serializer/impl/StringRedisTemplateServiceImpl.java<gh_stars>1-10 package com.pepper.service.redis.string.serializer.impl; import java.io.Closeable; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.dubbo.config.annotation.Service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.DependsOn; import org.springframework.data.redis.connection.DataType; import org.springframework.data.redis.core.BoundGeoOperations; import org.springframework.data.redis.core.BoundHashOperations; import org.springframework.data.redis.core.BoundListOperations; import org.springframework.data.redis.core.BoundSetOperations; import org.springframework.data.redis.core.BoundValueOperations; import org.springframework.data.redis.core.BoundZSetOperations; import org.springframework.data.redis.core.BulkMapper; import org.springframework.data.redis.core.ClusterOperations; import org.springframework.data.redis.core.GeoOperations; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.HyperLogLogOperations; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.SessionCallback; import org.springframework.data.redis.core.SetOperations; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.data.redis.core.ZSetOperations; import org.springframework.data.redis.core.query.SortQuery; import org.springframework.data.redis.core.script.RedisScript; import org.springframework.data.redis.core.types.RedisClientInfo; import org.springframework.data.redis.serializer.RedisSerializer; import com.pepper.service.redis.string.serializer.StringRedisTemplateService; /** * * @author mrliu * */ @Service(interfaceClass = StringRedisTemplateService.class) @DependsOn(value={"redisTemplate"}) public class StringRedisTemplateServiceImpl implements StringRedisTemplateService { @Autowired private StringRedisTemplate stringRedisTemplate; @Override public <T> T execute(RedisCallback<T> action) { return stringRedisTemplate.execute(action); } @Override public <T> T execute(SessionCallback<T> session) { return stringRedisTemplate.execute(session); } @Override public List<Object> executePipelined(RedisCallback<?> action) { return stringRedisTemplate.executePipelined(action); } @Override public List<Object> executePipelined(RedisCallback<?> action, RedisSerializer<?> resultSerializer) { return stringRedisTemplate.executePipelined(action, resultSerializer); } @Override public List<Object> executePipelined(SessionCallback<?> session) { return stringRedisTemplate.executePipelined(session); } @Override public List<Object> executePipelined(SessionCallback<?> session, RedisSerializer<?> resultSerializer) { return stringRedisTemplate.executePipelined(session, resultSerializer); } @Override public <T> T execute(RedisScript<T> script, List<String> keys, Object... args) { return stringRedisTemplate.execute(script, keys, args); } @Override public <T> T execute(RedisScript<T> script, RedisSerializer<?> argsSerializer, RedisSerializer<T> resultSerializer, List<String> keys, Object... args) { return stringRedisTemplate.execute(script, argsSerializer, resultSerializer, keys, args); } @Override public <T extends Closeable> T executeWithStickyConnection(RedisCallback<T> callback) { return stringRedisTemplate.executeWithStickyConnection(callback); } @Override public Boolean hasKey(String key) { return stringRedisTemplate.hasKey(key); } @Override public Boolean delete(String key) { return stringRedisTemplate.delete(key); } @Override public Long delete(Collection<String> keys) { return stringRedisTemplate.delete(keys); } @Override public DataType type(String key) { return stringRedisTemplate.type(key); } @Override public Set<String> keys(String pattern) { return stringRedisTemplate.keys(pattern); } @Override public String randomKey() { return stringRedisTemplate.randomKey(); } @Override public void rename(String oldKey, String newKey) { stringRedisTemplate.rename(oldKey, newKey); } @Override public Boolean renameIfAbsent(String oldKey, String newKey) { return stringRedisTemplate.renameIfAbsent(oldKey, newKey); } @Override public Boolean expire(String key, long timeout, TimeUnit unit) { return stringRedisTemplate.expire(key, timeout, unit); } @Override public Boolean expireAt(String key, Date date) { return stringRedisTemplate.expireAt(key, date); } @Override public Boolean persist(String key) { return stringRedisTemplate.persist(key); } @Override public Boolean move(String key, int dbIndex) { return stringRedisTemplate.move(key, dbIndex); } @Override public byte[] dump(String key) { return stringRedisTemplate.dump(key); } @Override public void restore(String key, byte[] value, long timeToLive, TimeUnit unit) { stringRedisTemplate.restore(key, value, timeToLive, unit); } @Override public Long getExpire(String key) { return stringRedisTemplate.getExpire(key); } @Override public Long getExpire(String key, TimeUnit timeUnit) { return stringRedisTemplate.getExpire(key); } @Override public List<String> sort(SortQuery<String> query) { return stringRedisTemplate.sort(query); } @Override public <T> List<T> sort(SortQuery<String> query, RedisSerializer<T> resultSerializer) { return stringRedisTemplate.sort(query, resultSerializer); } @Override public <T> List<T> sort(SortQuery<String> query, BulkMapper<T, String> bulkMapper) { return stringRedisTemplate.sort(query, bulkMapper); } @Override public <T, S> List<T> sort(SortQuery<String> query, BulkMapper<T, S> bulkMapper, RedisSerializer<S> resultSerializer) { return stringRedisTemplate.sort(query, bulkMapper, resultSerializer); } @Override public Long sort(SortQuery<String> query, String storeKey) { return stringRedisTemplate.sort(query, storeKey); } @Override public void watch(String key) { stringRedisTemplate.watch(key); } @Override public void watch(Collection<String> keys) { stringRedisTemplate.watch(keys); } @Override public void unwatch() { stringRedisTemplate.unwatch(); } @Override public void multi() { stringRedisTemplate.multi(); } @Override public void discard() { stringRedisTemplate.discard(); } @Override public List<Object> exec() { return stringRedisTemplate.exec(); } @Override public List<Object> exec(RedisSerializer<?> valueSerializer) { return stringRedisTemplate.exec(valueSerializer); } @Override public List<RedisClientInfo> getClientList() { return stringRedisTemplate.getClientList(); } @Override public void killClient(String host, int port) { stringRedisTemplate.killClient(host, port); } @Override public void slaveOf(String host, int port) { stringRedisTemplate.slaveOf(host, port); } @Override public void slaveOfNoOne() { stringRedisTemplate.slaveOfNoOne(); } @Override public void convertAndSend(String destination, Object message) { stringRedisTemplate.convertAndSend(destination, message); } @Override public ClusterOperations<String, String> opsForCluster() { return stringRedisTemplate.opsForCluster(); } @Override public GeoOperations<String, String> opsForGeo() { return stringRedisTemplate.opsForGeo(); } @Override public BoundGeoOperations<String, String> boundGeoOps(String key) { return stringRedisTemplate.boundGeoOps(key); } @Override public <HK, HV> HashOperations<String, HK, HV> opsForHash() { return stringRedisTemplate.opsForHash(); } @Override public <HK, HV> BoundHashOperations<String, HK, HV> boundHashOps(String key) { return stringRedisTemplate.boundHashOps(key); } @Override public HyperLogLogOperations<String, String> opsForHyperLogLog() { return stringRedisTemplate.opsForHyperLogLog(); } @Override public ListOperations<String, String> opsForList() { return stringRedisTemplate.opsForList(); } @Override public BoundListOperations<String, String> boundListOps(String key) { return stringRedisTemplate.boundListOps(key); } @Override public SetOperations<String, String> opsForSet() { return stringRedisTemplate.opsForSet(); } @Override public BoundSetOperations<String, String> boundSetOps(String key) { return stringRedisTemplate.boundSetOps(key); } @Override public ValueOperations<String, String> opsForValue() { return stringRedisTemplate.opsForValue(); } @Override public BoundValueOperations<String, String> boundValueOps(String key) { return stringRedisTemplate.boundValueOps(key); } @Override public ZSetOperations<String, String> opsForZSet() { return stringRedisTemplate.opsForZSet(); } @Override public BoundZSetOperations<String, String> boundZSetOps(String key) { return stringRedisTemplate.boundZSetOps(key); } @Override public RedisSerializer<?> getKeySerializer() { return stringRedisTemplate.getKeySerializer(); } @Override public RedisSerializer<?> getValueSerializer() { return stringRedisTemplate.getValueSerializer(); } @Override public RedisSerializer<?> getHashKeySerializer() { return stringRedisTemplate.getHashKeySerializer(); } @Override public RedisSerializer<?> getHashValueSerializer() { return stringRedisTemplate.getHashValueSerializer(); } @Override public Long countExistingKeys(Collection<String> keys) { return stringRedisTemplate.countExistingKeys(keys); } @Override public Boolean unlink(String key) { return stringRedisTemplate.unlink(key); } @Override public Long unlink(Collection<String> keys) { return stringRedisTemplate.unlink(keys); } @Override public void restore(String key, byte[] value, long timeToLive, TimeUnit unit, boolean replace) { stringRedisTemplate.restore(key, value, timeToLive, unit, replace); } @Override public void setBeanClassLoader(ClassLoader classLoader) { stringRedisTemplate.setBeanClassLoader(classLoader); } }
Braagaa/java-server-side-sdk
src/main/java/io/loginid/sdk/java/auth/Authentication.java
/* * LoginID Service API * # Introduction <span class=\"subtext\"> Welcome to the LoginID API docs. This documentation will help understand the API calls being made behind our SDKs. These APIs can be used to manage authentication, users, and user credentials. </span> # Authentication <span class=\"subtext\"> There is one main form of authentication for the API: <br/>&bull; API Service Token </span> * * OpenAPI spec version: 0.1.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package io.loginid.sdk.java.auth; import io.loginid.sdk.java.invokers.Pair; import java.util.List; import java.util.Map; public interface Authentication { /** * Apply authentication settings to header and query params. * * @param queryParams List of query parameters * @param headerParams Map of header parameters */ void applyToParams(List<Pair> queryParams, Map<String, String> headerParams); }
ggallotti/JavaClasses
java/src/main/java/com/genexus/db/IRemoteDataStoreHelper.java
<filename>java/src/main/java/com/genexus/db/IRemoteDataStoreHelper.java<gh_stars>10-100 package com.genexus.db; import java.sql.SQLException; import com.genexus.GXParameterPacker; import com.genexus.GXParameterUnpacker; public interface IRemoteDataStoreHelper extends IDataStoreHelper { void setParameters(int cursor, IFieldSetter stmt, GXParameterUnpacker unpacker) throws SQLException; void getResults(int cursor, IFieldGetter sent, GXParameterPacker packer) throws SQLException; int getReadBuffer(); }
ghsecuritylab/Alios_SDK
tools/testbed/utilities/device_info_poll.py
import sys, json from autotest import Autotest def print_help(): print "Usages:" print "1. list devices: python {0} --list [--server serverip] [--port port]".format(sys.argv[0]) print "2. get device nerghbors: python {0} --nbrs device_string [--server serverip] [--port port]".format(sys.argv[0]) def list_devices(at): ret={} devices = at.get_device_list() for i in range(len(devices)): index = str(i) devstr = devices[i].split(',')[2] devstr = devstr.replace('/dev/', '') if at.device_subscribe({index:devstr}) == False: continue mac = at.device_run_cmd(index, ['umesh', 'macaddr'], 1, 1, [':']) if mac == False or len(mac) != 1: continue mac = mac[0].replace(':', '') ret[devstr] = mac retstr = json.dumps(ret, sort_keys=True, indent=4) print retstr return True def get_nbrs(at, devices): ret = {} fail_num = 0 for i in range(len(devices)): index = str(i) devstr = devices[i] ret[devstr] = {} if at.device_subscribe({index:devstr}) == False: fail_num += 1 continue nbrs = at.device_run_cmd(index, ['umesh', 'nbrs'], 32, 2, [',']) if nbrs == False or len(nbrs) == 0: fail_num += 1 continue index = 0 for j in range(len(nbrs)): if nbrs[j].startswith('\t') == False: continue nbr_index = '{0:02d}'.format(index) index += 1 nbr = nbrs[j].replace('\t', '') ret[devstr][nbr_index] = nbr retstr = json.dumps(ret, sort_keys=True, indent=4) print retstr return (fail_num == 0) operation = None serverip = '10.125.52.132' serverport = 34568 i = 1 while i < len(sys.argv): arg = sys.argv[i] if arg == '--list': operation = 'list_devices' elif arg == '--nbrs' and (i + 1) < len(sys.argv): operation = 'get_nbrs' devices = sys.argv[i + 1].split(',') i += 1 elif arg == '--server' and (i + 1) < len(sys.argv): serverip = sys.argv[i + 1] i += 1 elif arg == '--port' and (i + 1) < len(sys.argv) and sys.argv[i+1].isdigit(): serverport = int(sys.argv[i + 1]) i += 1 elif arg == '--help': print_help() i += 1 if operation == None: sys.exit(0) at=Autotest() if at.start(serverip, serverport) == False: print 'error: connect to server {0}:{1} failed'.format(serverip, serverport) exit(1) if operation == 'list_devices': ret = list_devices(at) elif operation == 'get_nbrs': ret = get_nbrs(at, devices) at.stop() exit(ret == True)
Joose/Joose
t/071_reflection_current_method.t.js
StartTest(function (t) { //================================================================================================================================================================================== t.diag("Reflection - currentMethod") Class('TestClass1', { has : { attribute1 : null, attribute2 : null }, methods : { method1 : function () { var method = this.meta.getCurrentMethod() t.ok(method == this.meta.getMethod('method1'), 'Correct method returned') t.ok(method.name == 'method1', 'Correct name for method') t.ok(/getCurrentMethod/.test(method.value.toString()), 'Correct content for method') }, method2 : function () {} } }) var a1 = new TestClass1() a1.method1() Class('TestClass2', { isa : TestClass1, has : { attribute3 : null, attribute4 : null }, before : { method1 : function () { var method = this.meta.getCurrentMethod() t.isa_ok(method, Joose.Managed.Property.MethodModifier.Before, 'Correct method returned - `before` modifier') t.ok(method.name == 'method1', 'Correct name for modifier') t.ok(/Joose.Managed.Property.MethodModifier.Before/.test(method.value.toString()), 'Correct content for modifier') } } }) var a2 = new TestClass2() a2.method1() t.expectGlobals('TestClass1', 'TestClass2') t.done() })
onebytecode/musicConnects-web
logging/logging_dev.js
const colors = require('colors') const messageAnalyser = require('./messageAnalyser') module.exports = (message, err, type) => { let errorMessage = '' if (message) errorMessage += messageAnalyser(message, type) if (err) errorMessage += '\n' + err return console.log(errorMessage); }
wstong999/AliOS-Things
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/TrimDocumentRequest.cc
<gh_stars>1000+ /* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/ocr/model/TrimDocumentRequest.h> using AlibabaCloud::Ocr::Model::TrimDocumentRequest; TrimDocumentRequest::TrimDocumentRequest() : RpcServiceRequest("ocr", "2019-12-30", "TrimDocument") { setMethod(HttpRequest::Method::Post); } TrimDocumentRequest::~TrimDocumentRequest() {} std::string TrimDocumentRequest::getFileType()const { return fileType_; } void TrimDocumentRequest::setFileType(const std::string& fileType) { fileType_ = fileType; setBodyParameter("FileType", fileType); } bool TrimDocumentRequest::getAsync()const { return async_; } void TrimDocumentRequest::setAsync(bool async) { async_ = async; setBodyParameter("Async", async ? "true" : "false"); } std::string TrimDocumentRequest::getFileURL()const { return fileURL_; } void TrimDocumentRequest::setFileURL(const std::string& fileURL) { fileURL_ = fileURL; setBodyParameter("FileURL", fileURL); } std::string TrimDocumentRequest::getOutputType()const { return outputType_; } void TrimDocumentRequest::setOutputType(const std::string& outputType) { outputType_ = outputType; setBodyParameter("OutputType", outputType); }
Kishore-abhimanyu/Side-Projects
CodingProblem/dcp/codes/trie.h
<reponame>Kishore-abhimanyu/Side-Projects<filename>CodingProblem/dcp/codes/trie.h #ifndef TRIE_H #define TRIE_H // Each node has 26 (alphabet) possibilites of // characters #define POS 26 struct trie{ struct trie* alphabetlinks[POS]; int leaf; // used to identify the end of the word }; struct trie *node(); void insert(struct trie *head, char *string); int search(struct trie *head, char *string); void autocomplete(struct trie *temp, char * string); void printTrie(struct trie * temp, char *string); char * concatString(char * string, int slice); #endif
PavlidisLab/Gemma
gemma-core/src/main/java/ubic/gemma/core/job/executor/webapp/SubmittedTaskLocal.java
<reponame>PavlidisLab/Gemma /* * The Gemma project * * Copyright (c) 2013 University of British Columbia * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package ubic.gemma.core.job.executor.webapp; import com.google.common.util.concurrent.ListenableFuture; import ubic.gemma.core.job.EmailNotificationContext; import ubic.gemma.core.job.TaskCommand; import ubic.gemma.core.job.TaskResult; import ubic.gemma.core.job.executor.common.TaskPostProcessing; import java.util.Date; import java.util.Deque; import java.util.Queue; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingDeque; /** * SubmittedTask implementation representing the task running on local TaskRunningService. */ public class SubmittedTaskLocal<T extends TaskResult> extends SubmittedTaskAbstract<T> { private final TaskPostProcessing taskPostProcessing; private final Deque<String> progressUpdates = new LinkedBlockingDeque<>(); private final Executor executor; private ListenableFuture<T> future; public SubmittedTaskLocal( TaskCommand taskCommand, TaskPostProcessing taskPostProcessing, Executor executor ) { super( taskCommand ); this.taskPostProcessing = taskPostProcessing; this.executor = executor; } @Override public synchronized Queue<String> getProgressUpdates() { return this.progressUpdates; } @Override public String getLastProgressUpdates() { return this.progressUpdates.peekLast(); } @Override public synchronized Date getSubmissionTime() { return this.submissionTime; } @Override public synchronized Date getStartTime() { return this.startTime; } @Override public synchronized Date getFinishTime() { return this.finishTime; } @Override public synchronized Status getStatus() { return status; } @Override public T getResult() throws ExecutionException, InterruptedException { // blocking call. return this.future.get(); } @Override public synchronized void requestCancellation() { boolean isCancelled = this.future.cancel( true ); if ( isCancelled ) { status = Status.CANCELLING; } } @SuppressWarnings("unchecked") @Override public synchronized void addEmailAlert() { if ( emailAlert ) return; emailAlert = true; assert taskPostProcessing != null : "Task postprocessing was null"; taskPostProcessing.addEmailNotification( ( ListenableFuture<TaskResult> ) future, new EmailNotificationContext( taskCommand.getTaskId(), taskCommand.getSubmitter(), taskCommand.getTaskClass().getSimpleName() ), executor ); } @Override public synchronized boolean isEmailAlert() { return this.emailAlert; } /** * @return false */ @Override public boolean isRunningRemotely() { return false; } @Override public synchronized boolean isDone() { return super.isDone(); } @SuppressWarnings("unused") // Possible external use ListenableFuture<T> getFuture() { return future; } /* * Package-private methods, used by TaskRunningService */ void setFuture( ListenableFuture<T> future ) { this.future = future; } synchronized void updateStatus( Status s, Date timeStamp ) { this.setTimeStampAndStatus( s, timeStamp ); } }
FlorentRevest/Enlightenment
src/bin/e_toolbar.c
#include "e.h" /* local function protos */ static void _e_toolbar_free(E_Toolbar *tbar); static void _e_toolbar_cb_mouse_down(void *data, Evas *evas, Evas_Object *obj, void *event_info); static void _e_toolbar_menu_cb_post(void *data, E_Menu *mn); static void _e_toolbar_menu_cb_pre(void *data, E_Menu *mn); static void _e_toolbar_menu_append(E_Toolbar *tbar, E_Menu *mn); //static void _e_toolbar_menu_cb_edit(void *data, E_Menu *mn, E_Menu_Item *mi); static void _e_toolbar_menu_cb_config(void *data, E_Menu *mn, E_Menu_Item *mi); //static void _e_toolbar_menu_cb_contents(void *data, E_Menu *mn, E_Menu_Item *mi); static void _e_toolbar_gadcon_size_request(void *data, E_Gadcon *gc, Evas_Coord w, Evas_Coord h); static const char *_e_toolbar_orient_string_get(E_Toolbar *tbar); static void _e_toolbar_fm2_changed(void *data, Evas_Object *obj, void *event_info); static void _e_toolbar_fm2_dir_changed(void *data, Evas_Object *obj, void *event_info); static void _e_toolbar_fm2_dir_deleted(void *data, Evas_Object *obj, void *event_info); static void _e_toolbar_fm2_files_deleted(void *data, Evas_Object *obj, void *event_info); static void _e_toolbar_fm2_selected(void *data, Evas_Object *obj, void *event_info); static void _e_toolbar_fm2_selection_changed(void *data, Evas_Object *obj, void *event_info); static void _e_toolbar_menu_items_append(void *data, E_Gadcon_Client *gcc, E_Menu *mn); /* local vars */ static Eina_List *toolbars = NULL; static E_Gadcon_Location *tb_location = NULL; static void _tb_resize(void *data, Evas *e EINA_UNUSED, Evas_Object *obj, void *info EINA_UNUSED) { E_Toolbar *tbar = data; Evas_Coord w, h; evas_object_geometry_get(obj, NULL, NULL, &w, &h); if (tbar->gadcon) e_gadcon_swallowed_min_size_set(tbar->gadcon, w, h); } /* static void _e_toolbar_gadget_remove(void *data EINA_UNUSED, E_Gadcon_Client *gcc) { E_Toolbar *tbar = eina_list_data_get(toolbars); Eina_List *l; if (!tbar) { E_Config_Gadcon *cf_gc; EINA_LIST_FOREACH(e_config->gadcons, l, cf_gc) { if (e_util_strcmp(cf_gc->name, "toolbar")) continue; cf_gc->clients = eina_list_remove(cf_gc->clients, gcc->cf); break; } if (!cf_gc) return; } else if (gcc->cf) e_gadcon_client_config_del(tbar->gadcon->cf, gcc->cf); EINA_LIST_FOREACH(toolbars, l, tbar) e_gadcon_repopulate(tbar->gadcon); e_config_save_queue(); } static int _e_toolbar_gadget_add(void *data EINA_UNUSED, E_Gadcon_Client *gcc, const E_Gadcon_Client_Class *cc) { E_Toolbar *tbar = eina_list_data_get(toolbars); E_Config_Gadcon *cf_gc = NULL; E_Gadcon *gc = NULL; Eina_List *l; E_Config_Gadcon_Client *cf_gcc = gcc->cf; if (!tbar) { E_Config_Gadcon *cf_gc2; EINA_LIST_FOREACH(e_config->gadcons, l, cf_gc2) { if (e_util_strcmp(cf_gc2->name, "toolbar")) continue; cf_gc = cf_gc2; break; } if (!cf_gc) return 0; } else gc = tbar->gadcon, cf_gc = gc->cf; if (gcc) { gcc->gadcon->cf->clients = eina_list_remove(gcc->gadcon->cf->clients, cf_gcc); if (gc && gc->zone) cf_gcc->geom.res = gc->zone->w; else if (gc && gc->o_container) { int w, h; evas_object_geometry_get(gc->o_container, NULL, NULL, &w, &h); switch (gc->orient) { case E_GADCON_ORIENT_VERT: case E_GADCON_ORIENT_LEFT: case E_GADCON_ORIENT_RIGHT: case E_GADCON_ORIENT_CORNER_LT: case E_GADCON_ORIENT_CORNER_RT: case E_GADCON_ORIENT_CORNER_LB: case E_GADCON_ORIENT_CORNER_RB: cf_gcc->geom.res = h; break; default: cf_gcc->geom.res = w; } } else cf_gcc->geom.res = 800; cf_gcc->geom.size = 80; cf_gcc->geom.pos = cf_gcc->geom.res - cf_gcc->geom.size; cf_gc->clients = eina_list_append(cf_gc->clients, cf_gcc); } else { if (!gc); // FIXME: okay...need to create a gcc from nothing and add it to nothing... else if (!e_gadcon_client_config_new(gc, cc->name)) return 0; } EINA_LIST_FOREACH(toolbars, l, tbar) e_gadcon_repopulate(tbar->gadcon); if (gc || gcc) e_config_save_queue(); return (gc || gcc); } */ EINTERN int e_toolbar_init(void) { tb_location = e_gadcon_location_new(_("EFM Toolbar"), E_GADCON_SITE_EFM_TOOLBAR, NULL, NULL, NULL, NULL); //_e_toolbar_gadget_add, NULL, //_e_toolbar_gadget_remove, NULL); e_gadcon_location_set_icon_name(tb_location, "configure-toolbars"); e_gadcon_location_register(tb_location); return 1; } EINTERN int e_toolbar_shutdown(void) { while (toolbars) { E_Toolbar *tbar; tbar = eina_list_data_get(toolbars); e_object_del(E_OBJECT(tbar)); } e_gadcon_location_unregister(tb_location); E_FREE_FUNC(tb_location, e_gadcon_location_free); return 1; } E_API E_Toolbar * e_toolbar_new(Evas *evas, const char *name, Evas_Object *fwin, Evas_Object *fm2) { E_Toolbar *tbar = NULL; if (!name) return NULL; if ((!fwin) || (!fm2)) return NULL; tbar = E_OBJECT_ALLOC(E_Toolbar, E_TOOLBAR_TYPE, _e_toolbar_free); if (!tbar) return NULL; tbar->id = 1; // tbar->id = eina_list_count(toolbars) + 1; tbar->evas = evas; tbar->name = eina_stringshare_add(name); tbar->fwin = fwin; tbar->fm2 = fm2; evas_object_smart_callback_add(tbar->fm2, "changed", _e_toolbar_fm2_changed, tbar); evas_object_smart_callback_add(tbar->fm2, "dir_changed", _e_toolbar_fm2_dir_changed, tbar); evas_object_smart_callback_add(tbar->fm2, "dir_deleted", _e_toolbar_fm2_dir_deleted, tbar); evas_object_smart_callback_add(tbar->fm2, "files_deleted", _e_toolbar_fm2_files_deleted, tbar); evas_object_smart_callback_add(tbar->fm2, "selected", _e_toolbar_fm2_selected, tbar); evas_object_smart_callback_add(tbar->fm2, "selection_change", _e_toolbar_fm2_selection_changed, tbar); tbar->o_base = edje_object_add(evas); e_theme_edje_object_set(tbar->o_base, "base/theme/fileman/toolbar", "e/fileman/toolbar/default/base"); evas_object_event_callback_add(tbar->o_base, EVAS_CALLBACK_RESIZE, _tb_resize, tbar); tbar->o_event = evas_object_rectangle_add(evas); evas_object_color_set(tbar->o_event, 0, 0, 0, 0); evas_object_show(tbar->o_event); edje_object_part_swallow(tbar->o_base, "e.swallow.event", tbar->o_event); evas_object_event_callback_add(tbar->o_event, EVAS_CALLBACK_MOUSE_DOWN, _e_toolbar_cb_mouse_down, tbar); tbar->gadcon = e_gadcon_swallowed_new(tbar->name, tbar->id, tbar->o_base, "e.swallow.content"); e_gadcon_size_request_callback_set(tbar->gadcon, _e_toolbar_gadcon_size_request, tbar); /* FIXME: We want to implement "styles" here ? */ e_toolbar_orient(tbar, E_GADCON_ORIENT_TOP); e_gadcon_toolbar_set(tbar->gadcon, tbar); tbar->gadcon->location = tb_location; e_gadcon_ecore_evas_set(tbar->gadcon, ecore_evas_ecore_evas_get(evas_object_evas_get(tbar->fwin))); e_gadcon_util_menu_attach_func_set(tbar->gadcon, _e_toolbar_menu_items_append, tbar); e_gadcon_populate(tbar->gadcon); _e_toolbar_gadcon_size_request(tbar, tbar->gadcon, 0, 0); toolbars = eina_list_append(toolbars, tbar); return tbar; } E_API void e_toolbar_fwin_set(E_Toolbar *tbar, Evas_Object *fwin) { E_OBJECT_CHECK(tbar); E_OBJECT_TYPE_CHECK(tbar, E_TOOLBAR_TYPE); tbar->fwin = fwin; } E_API Evas_Object * e_toolbar_fwin_get(E_Toolbar *tbar) { E_OBJECT_CHECK_RETURN(tbar, NULL); E_OBJECT_TYPE_CHECK_RETURN(tbar, E_TOOLBAR_TYPE, NULL); return tbar->fwin; } E_API void e_toolbar_fm2_set(E_Toolbar *tbar, Evas_Object *fm2) { E_OBJECT_CHECK(tbar); E_OBJECT_TYPE_CHECK(tbar, E_TOOLBAR_TYPE); tbar->fm2 = fm2; } E_API Evas_Object * e_toolbar_fm2_get(E_Toolbar *tbar) { E_OBJECT_CHECK_RETURN(tbar, NULL); E_OBJECT_TYPE_CHECK_RETURN(tbar, E_TOOLBAR_TYPE, NULL); return tbar->fm2; } E_API void e_toolbar_orient(E_Toolbar *tbar, E_Gadcon_Orient orient) { char buf[4096]; E_OBJECT_CHECK(tbar); E_OBJECT_TYPE_CHECK(tbar, E_TOOLBAR_TYPE); e_gadcon_orient(tbar->gadcon, orient); snprintf(buf, sizeof(buf), "e,state,orientation,%s", _e_toolbar_orient_string_get(tbar)); edje_object_signal_emit(tbar->o_base, buf, "e"); edje_object_message_signal_process(tbar->o_base); } E_API void e_toolbar_populate(E_Toolbar *tbar) { E_OBJECT_CHECK(tbar); E_OBJECT_TYPE_CHECK(tbar, E_TOOLBAR_TYPE); e_gadcon_populate(tbar->gadcon); } /* local functions */ static void _e_toolbar_free(E_Toolbar *tbar) { toolbars = eina_list_remove(toolbars, tbar); evas_object_smart_callback_del_full(tbar->fm2, "changed", _e_toolbar_fm2_changed, tbar); evas_object_smart_callback_del_full(tbar->fm2, "dir_changed", _e_toolbar_fm2_dir_changed, tbar); evas_object_smart_callback_del_full(tbar->fm2, "dir_deleted", _e_toolbar_fm2_dir_deleted, tbar); evas_object_smart_callback_del_full(tbar->fm2, "files_deleted", _e_toolbar_fm2_files_deleted, tbar); evas_object_smart_callback_del_full(tbar->fm2, "selected", _e_toolbar_fm2_selected, tbar); evas_object_smart_callback_del_full(tbar->fm2, "selection_change", _e_toolbar_fm2_selection_changed, tbar); if (tbar->menu) { e_menu_post_deactivate_callback_set(tbar->menu, NULL, NULL); e_object_del(E_OBJECT(tbar->menu)); tbar->menu = NULL; } if (tbar->cfg_dlg) e_object_del(E_OBJECT(tbar->cfg_dlg)); e_object_del(E_OBJECT(tbar->gadcon)); if (tbar->name) eina_stringshare_del(tbar->name); evas_object_del(tbar->o_event); evas_object_del(tbar->o_base); E_FREE(tbar); } static void _e_toolbar_cb_mouse_down(void *data, Evas *evas EINA_UNUSED, Evas_Object *obj EINA_UNUSED, void *event_info) { Evas_Event_Mouse_Down *ev; E_Toolbar *tbar; E_Menu *mn; E_Zone *zone; int x, y; ev = event_info; tbar = data; if (ev->button != 3) return; mn = e_menu_new(); e_menu_post_deactivate_callback_set(mn, _e_toolbar_menu_cb_post, tbar); tbar->menu = mn; _e_toolbar_menu_append(tbar, mn); zone = e_zone_current_get(); ecore_evas_pointer_xy_get(e_comp->ee, &x, &y); e_menu_activate_mouse(mn, zone, x, y, 1, 1, E_MENU_POP_DIRECTION_DOWN, ev->timestamp); } static void _e_toolbar_menu_cb_post(void *data, E_Menu *mn EINA_UNUSED) { E_Toolbar *tbar; tbar = data; if (!tbar->menu) return; e_object_del(E_OBJECT(tbar->menu)); tbar->menu = NULL; } static void _e_toolbar_menu_cb_pre(void *data, E_Menu *mn) { E_Toolbar *tbar; E_Menu_Item *mi; tbar = data; e_menu_pre_activate_callback_set(mn, NULL, NULL); /* mi = e_menu_item_new(mn); if (tbar->gadcon->editing) e_menu_item_label_set(mi, _("Stop Moving Items")); else e_menu_item_label_set(mi, _("Begin Moving Items")); e_util_menu_item_theme_icon_set(mi, "transform-scale"); e_menu_item_callback_set(mi, _e_toolbar_menu_cb_edit, tbar); mi = e_menu_item_new(mn); e_menu_item_separator_set(mi, 1); */ mi = e_menu_item_new(mn); e_menu_item_label_set(mi, _("Toolbar Settings")); e_util_menu_item_theme_icon_set(mi, "configure"); e_menu_item_callback_set(mi, _e_toolbar_menu_cb_config, tbar); /* mi = e_menu_item_new(mn); e_menu_item_label_set(mi, _("Set Toolbar Contents")); e_util_menu_item_theme_icon_set(mi, "preferences-toolbar"); e_menu_item_callback_set(mi, _e_toolbar_menu_cb_contents, tbar); */ } static void _e_toolbar_menu_items_append(void *data, E_Gadcon_Client *gcc EINA_UNUSED, E_Menu *mn) { E_Toolbar *tbar; tbar = data; _e_toolbar_menu_append(tbar, mn); } static void _e_toolbar_menu_append(E_Toolbar *tbar, E_Menu *mn) { E_Menu_Item *mi; E_Menu *subm; subm = e_menu_new(); mi = e_menu_item_new(mn); e_menu_item_label_set(mi, tbar->name); e_util_menu_item_theme_icon_set(mi, "preferences-toolbar"); e_menu_pre_activate_callback_set(subm, _e_toolbar_menu_cb_pre, tbar); e_menu_item_submenu_set(mi, subm); e_object_unref(E_OBJECT(subm)); } /* static void _e_toolbar_menu_cb_edit(void *data, E_Menu *mn EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Toolbar *tbar; tbar = data; if (tbar->gadcon->editing) e_gadcon_edit_end(tbar->gadcon); else e_gadcon_edit_begin(tbar->gadcon); } */ static void _e_toolbar_menu_cb_config(void *data, E_Menu *mn EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Toolbar *tbar; tbar = data; if (!tbar->cfg_dlg) e_int_toolbar_config(tbar); } /* static void _e_toolbar_menu_cb_contents(void *data, E_Menu *mn EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Toolbar *tbar; tbar = data; if (!tbar->gadcon->config_dialog) e_int_gadcon_config_toolbar(tbar->gadcon); } */ static void _e_toolbar_gadcon_size_request(void *data, E_Gadcon *gc, Evas_Coord w, Evas_Coord h) { E_Toolbar *tbar; Evas_Coord ww, hh, nw, nh; tbar = data; ww = hh = 0; evas_object_geometry_get(gc->o_container, NULL, NULL, &ww, &hh); switch (gc->orient) { case E_GADCON_ORIENT_TOP: case E_GADCON_ORIENT_BOTTOM: w = ww; h = 32; break; case E_GADCON_ORIENT_LEFT: case E_GADCON_ORIENT_RIGHT: w = 32; h = hh; break; default: break; } e_gadcon_swallowed_min_size_set(gc, w, h); edje_object_size_min_calc(tbar->o_base, &nw, &nh); tbar->minw = nw; tbar->minh = nh; } static const char * _e_toolbar_orient_string_get(E_Toolbar *tbar) { const char *sig = ""; switch (tbar->gadcon->orient) { case E_GADCON_ORIENT_HORIZ: sig = "horizontal"; break; case E_GADCON_ORIENT_VERT: sig = "vertical"; break; case E_GADCON_ORIENT_LEFT: sig = "left"; break; case E_GADCON_ORIENT_RIGHT: sig = "right"; break; case E_GADCON_ORIENT_TOP: sig = "top"; break; case E_GADCON_ORIENT_BOTTOM: sig = "bottom"; break; default: break; } return sig; } static void _e_toolbar_fm2_changed(void *data, Evas_Object *obj EINA_UNUSED, void *event_info EINA_UNUSED) { E_Toolbar *tbar; Eina_List *l = NULL; E_Gadcon_Client *gcc = NULL; tbar = data; if (!tbar) return; EINA_LIST_FOREACH(tbar->gadcon->clients, l, gcc) { if (!gcc) continue; evas_object_smart_callback_call(gcc->o_base, "changed", tbar); } } static void _e_toolbar_fm2_dir_changed(void *data, Evas_Object *obj EINA_UNUSED, void *event_info EINA_UNUSED) { E_Toolbar *tbar; Eina_List *l = NULL; E_Gadcon_Client *gcc = NULL; tbar = data; if (!tbar) return; EINA_LIST_FOREACH(tbar->gadcon->clients, l, gcc) { if (!gcc) continue; evas_object_smart_callback_call(gcc->o_base, "dir_changed", tbar); } } static void _e_toolbar_fm2_dir_deleted(void *data, Evas_Object *obj EINA_UNUSED, void *event_info EINA_UNUSED) { E_Toolbar *tbar; Eina_List *l = NULL; E_Gadcon_Client *gcc = NULL; tbar = data; if (!tbar) return; EINA_LIST_FOREACH(tbar->gadcon->clients, l, gcc) { if (!gcc) continue; evas_object_smart_callback_call(gcc->o_base, "dir_deleted", tbar); } } static void _e_toolbar_fm2_files_deleted(void *data, Evas_Object *obj EINA_UNUSED, void *event_info EINA_UNUSED) { E_Toolbar *tbar; Eina_List *l = NULL; E_Gadcon_Client *gcc = NULL; tbar = data; if (!tbar) return; EINA_LIST_FOREACH(tbar->gadcon->clients, l, gcc) { if (!gcc) continue; evas_object_smart_callback_call(gcc->o_base, "files_deleted", tbar); } } static void _e_toolbar_fm2_selected(void *data, Evas_Object *obj EINA_UNUSED, void *event_info EINA_UNUSED) { E_Toolbar *tbar; Eina_List *l = NULL; E_Gadcon_Client *gcc = NULL; tbar = data; if (!tbar) return; EINA_LIST_FOREACH(tbar->gadcon->clients, l, gcc) { if (!gcc) continue; evas_object_smart_callback_call(gcc->o_base, "selected", tbar); } } static void _e_toolbar_fm2_selection_changed(void *data, Evas_Object *obj EINA_UNUSED, void *event_info EINA_UNUSED) { E_Toolbar *tbar; Eina_List *l = NULL; E_Gadcon_Client *gcc = NULL; tbar = data; if (!tbar) return; EINA_LIST_FOREACH(tbar->gadcon->clients, l, gcc) { if (!gcc) continue; evas_object_smart_callback_call(gcc->o_base, "selection_changed", tbar); } }
joeylamcy/gchp
ESMF/src/Infrastructure/Mesh/src/Moab/parallel/moab_mpi_config.h
<filename>ESMF/src/Infrastructure/Mesh/src/Moab/parallel/moab_mpi_config.h<gh_stars>1-10 /* src/parallel/moab_mpi_config.h. Generated from moab_mpi_config.h.in by configure. */ #include "moab/MOABConfig.h" /* MPICH_IGNORE_CXX_SEEK is not sufficient to avoid conflicts */ /* #undef MB_MPI_CXX_CONFLICT */ /* "Value of C SEEK_CUR" */ /* #undef MB_SEEK_CUR */ /* "Value of C SEEK_END" */ /* #undef MB_SEEK_END */ /* "Value of C SEEK_SET" */ /* #undef MB_SEEK_SET */
halfreal/spezi-gdx
spezi-gdx/src/main/java/de/halfreal/spezi/gdx/utils/DragAndDrop.java
<reponame>halfreal/spezi-gdx<filename>spezi-gdx/src/main/java/de/halfreal/spezi/gdx/utils/DragAndDrop.java package de.halfreal.spezi.gdx.utils; import static com.badlogic.gdx.scenes.scene2d.actions.Actions.*; import com.badlogic.gdx.Input.Buttons; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.Touchable; import com.badlogic.gdx.scenes.scene2d.utils.DragListener; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ObjectMap; /** * Manages drag and drop operations through registered drag sources and drop * targets. * * @author <NAME> */ public class DragAndDrop { /** * The payload of a drag and drop operation. Actors can be optionally * provided to follow the cursor and change when over a target. */ static public class Payload { Actor dragActor, validDragActor, invalidDragActor; Object object; public Actor getDragActor() { return dragActor; } public Actor getInvalidDragActor() { return invalidDragActor; } public Object getObject() { return object; } public Actor getValidDragActor() { return validDragActor; } public void setDragActor(Actor dragActor) { this.dragActor = dragActor; } public void setInvalidDragActor(Actor invalidDragActor) { this.invalidDragActor = invalidDragActor; } public void setObject(Object object) { this.object = object; } public void setValidDragActor(Actor validDragActor) { this.validDragActor = validDragActor; } } /** * A target where a payload can be dragged from. * * @author <NAME> */ static abstract public class Source { final Actor actor; public Source(Actor actor) { if (actor == null) { throw new IllegalArgumentException("actor cannot be null."); } this.actor = actor; } /** @return May be null. */ abstract public Payload dragStart(InputEvent event, float x, float y, int pointer); /** * @param target * null if not dropped on a valid target. */ public void dragStop(InputEvent event, float x, float y, int pointer, Target target) { } public Actor getActor() { return actor; } } /** * A target where a payload can be dropped to. * * @author <NAME> */ public static abstract class Target { final Actor actor; public Target(Actor actor) { if (actor == null) { throw new IllegalArgumentException("actor cannot be null."); } this.actor = actor; Stage stage = actor.getStage(); if (stage != null && actor == stage.getRoot()) { throw new IllegalArgumentException( "The stage root cannot be a drag and drop target."); } } /** * Called when the object is dragged over the target. The coordinates * are in the target's local coordinate system. * * @return true if this is a valid target for the object. */ abstract public boolean drag(Source source, Payload payload, float x, float y, int pointer); abstract public void drop(Source source, Payload payload, float x, float y, int pointer); public Actor getActor() { return actor; } /** * Called when the object is no longer over the target, whether because * the touch was moved or a drop occurred. */ public void reset(Source source, Payload payload) { } } static final Vector2 tmpVector = new Vector2(); int activePointer = -1; private int button; Actor dragActor; float dragActorX = 14, dragActorY = -20; long dragStartTime; int dragTime = 250; boolean isValidTarget; Payload payload; Source source; ObjectMap<Source, DragListener> sourceListeners = new ObjectMap(); private float tapSquareSize = 8; Target target; Array<Target> targets = new Array(); public void addSource(final Source source) { DragListener listener = new DragListener() { @Override public void drag(InputEvent event, float x, float y, int pointer) { if (payload == null) { return; } if (pointer != activePointer) { return; } Stage stage = event.getStage(); Touchable dragActorTouchable = null; if (dragActor != null) { dragActorTouchable = dragActor.getTouchable(); dragActor.setTouchable(Touchable.disabled); } // Find target. Target newTarget = null; isValidTarget = false; Actor hit = event.getStage().hit(event.getStageX(), event.getStageY(), true); // Prefer touchable actors. if (hit == null) { hit = event.getStage().hit(event.getStageX(), event.getStageY(), false); } if (hit != null) { for (int i = 0, n = targets.size; i < n; i++) { Target target = targets.get(i); if (!target.actor.isAscendantOf(hit)) { continue; } newTarget = target; target.actor.stageToLocalCoordinates(tmpVector.set( event.getStageX(), event.getStageY())); isValidTarget = target.drag(source, payload, tmpVector.x, tmpVector.y, pointer); break; } } if (newTarget != target) { if (target != null) { target.reset(source, payload); } target = newTarget; } if (dragActor != null) { dragActor.setTouchable(dragActorTouchable); } // Add/remove and position the drag actor. Actor actor = null; if (target != null) { actor = isValidTarget ? payload.validDragActor : payload.invalidDragActor; } if (actor == null) { actor = payload.dragActor; } if (actor == null) { return; } if (dragActor != actor) { if (dragActor != null) { dragActor.remove(); } dragActor = actor; stage.addActor(actor); } float actorX = event.getStageX() + dragActorX; float actorY = event.getStageY() + dragActorY - actor.getHeight(); if (actorX < 0) { actorX = 0; } if (actorY < 0) { actorY = 0; } if (actorX + actor.getWidth() > stage.getWidth()) { actorX = stage.getWidth() - actor.getWidth(); } if (actorY + actor.getHeight() > stage.getHeight()) { actorY = stage.getHeight() - actor.getHeight(); } actor.setPosition(actorX, actorY); } @Override public void dragStart(InputEvent event, float x, float y, int pointer) { if (activePointer != -1) { event.stop(); return; } activePointer = pointer; dragStartTime = System.currentTimeMillis(); payload = source.dragStart(event, getTouchDownX(), getTouchDownY(), pointer); event.stop(); } @Override public void dragStop(InputEvent event, float x, float y, int pointer) { if (pointer != activePointer) { return; } activePointer = -1; if (payload == null) { return; } if (System.currentTimeMillis() - dragStartTime < dragTime) { isValidTarget = false; } if (dragActor != null) { dragActor.remove(); } if (isValidTarget) { target.actor.stageToLocalCoordinates(tmpVector.set( event.getStageX(), event.getStageY())); target.drop(source, payload, tmpVector.x, tmpVector.y, pointer); } source.dragStop(event, x, y, pointer, isValidTarget ? target : null); if (target != null) { target.reset(source, payload); } DragAndDrop.this.source = null; payload = null; target = null; isValidTarget = false; dragActor = null; } }; listener.setTapSquareSize(tapSquareSize); listener.setButton(button); source.actor.addCaptureListener(listener); sourceListeners.put(source, listener); } public void addTarget(Target target) { targets.add(target); } /** * drops an Actor automatically to any fitting target * * @param sourceActor * @param source */ public void autoDrop(final Source source) { for (final Target target : targets) { autoDrop(source, target); } } /** * drops a source to a specific target * * @param source * @param target */ public void autoDrop(final Source source, final Target target) { Actor sourceActor = source.getActor(); Stage stage = sourceActor.getStage(); if (stage != null) { final Payload payload = source.dragStart(null, 0, 0, 0); if (target.drag(source, payload, 0, 0, 0)) { Actor dragActor = payload.getDragActor(); Vector2 stageCords = sourceActor .localToStageCoordinates(new Vector2()); dragActor.setPosition(stageCords.x, stageCords.y); stage.addActor(dragActor); Actor targetActor = target.getActor(); Vector2 stageCordsTarget = targetActor .localToStageCoordinates(new Vector2()); float targetX = stageCordsTarget.x; float targetY = stageCordsTarget.y; dragActor.addAction(sequence(moveTo(targetX, targetY, 0.15f), run(new Runnable() { @Override public void run() { target.drop(source, payload, 0, 0, 0); target.reset(source, payload); } }), removeActor())); return; } } } /** Returns the current drag actor, or null. */ public Actor getDragActor() { return dragActor; } public Array<Target> getTargets() { return targets; } public boolean isDragging() { return payload != null; } public void removeSource(Source source) { DragListener dragListener = sourceListeners.remove(source); source.actor.removeCaptureListener(dragListener); } public void removeTarget(Target target) { targets.removeValue(target, true); } /** * Sets the button to listen for, all other buttons are ignored. Default is * {@link Buttons#LEFT}. Use -1 for any button. */ public void setButton(int button) { this.button = button; } public void setDragActorPosition(float dragActorX, float dragActorY) { this.dragActorX = dragActorX; this.dragActorY = dragActorY; } /** * Time in milliseconds that a drag must take before a drop will be * considered valid. This ignores an accidental drag and drop that was meant * to be a click. Default is 250. */ public void setDragTime(int dragMillis) { dragTime = dragMillis; } /** Sets the distance a touch must travel before being considered a drag. */ public void setTapSquareSize(float halfTapSquareSize) { tapSquareSize = halfTapSquareSize; } }
vot-developer/practice
src/main/java/org/algorithms/coding_patterns/educative/reversal_linkedlist/ReverseSubList.java
<filename>src/main/java/org/algorithms/coding_patterns/educative/reversal_linkedlist/ReverseSubList.java package org.algorithms.coding_patterns.educative.reversal_linkedlist; /* Given the head of a LinkedList and two positions 'p' and 'q', reverse the LinkedList from position 'p' to 'q'. */ public class ReverseSubList { //time - O(n), space - O(1) public static ListNode reverse(ListNode head, int p, int q) { if (head.next == null || p == q) return head; ListNode current = head; ListNode prev = null, next = null; for (int i = 1; i < p && current != null; i++){ prev = current; current = current.next; } ListNode beforeP = prev; ListNode nodeP = current; for (int i = 0; i < q - p + 1 && current != null; i++){ //finish on q + 1 node; next = current.next; current.next = prev; prev = current; current = next; } if (beforeP != null) beforeP.next = prev; else head = prev; nodeP.next = current; return head; } }
verlandz/go-pkg
log/const.go
package log import "github.com/rs/zerolog" type LogLevel int const ( ZLOG_PANIC LogLevel = LogLevel(zerolog.PanicLevel) ZLOG_FATAL LogLevel = LogLevel(zerolog.FatalLevel) ZLOG_ERROR LogLevel = LogLevel(zerolog.ErrorLevel) ZLOG_WARN LogLevel = LogLevel(zerolog.WarnLevel) ZLOG_INFO LogLevel = LogLevel(zerolog.InfoLevel) ZLOG_DEBUG LogLevel = LogLevel(zerolog.DebugLevel) ZLOG_TRACE LogLevel = LogLevel(zerolog.TraceLevel) )
alejandrolozano2/OpenGL_DemoFramework
DemoFramework/FslUtil/Vulkan1_0/source/FslUtil/Vulkan1_0/Extend/BufferEx.cpp
<filename>DemoFramework/FslUtil/Vulkan1_0/source/FslUtil/Vulkan1_0/Extend/BufferEx.cpp /**************************************************************************************************************************************************** * Copyright (c) 2016 Freescale Semiconductor, 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 the Freescale Semiconductor, Inc. nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT 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 <FslUtil/Vulkan1_0/Extend/BufferEx.hpp> #include <FslUtil/Vulkan1_0/Exceptions.hpp> #include <RapidVulkan/Check.hpp> #include <cassert> #include <cstring> #include <utility> namespace Fsl { namespace Vulkan { // move assignment operator BufferEx& BufferEx::operator=(BufferEx&& other) { if (this != &other) { // Free existing resources then transfer the content of other to this one and fill other with default values Reset(); // Claim ownership here m_buffer = std::move(other.m_buffer); //m_createInfo = std::move(other.m_createInfo); m_size = other.m_size; m_usage = other.m_usage; m_accessMask = other.m_accessMask; // Remove the data from other other.m_accessMask = 0; other.m_size = 0; other.m_usage = 0; } return *this; } // Transfer ownership from other to this BufferEx::BufferEx(BufferEx&& other) : m_buffer(std::move(other.m_buffer)) //, m_createInfo(std::move(other.m_createInfo)) , m_size(other.m_size) , m_usage(other.m_usage) , m_accessMask(other.m_accessMask) { // Remove the data from other other.m_accessMask = 0; other.m_size = 0; other.m_usage = 0; } // For now we implement the code here, if this turns out to be a performance problem we can move the code // to the header file to ensure its inlined. BufferEx::BufferEx() : m_buffer() //, m_createInfo() , m_size(0) , m_usage(0) , m_accessMask(0) { } BufferEx::BufferEx(const VkDevice device, const VkBufferCreateFlags flags, const VkDeviceSize size, const VkBufferUsageFlags usage, const VkSharingMode sharingMode, const uint32_t queueFamilyIndexCount, const uint32_t*const pQueueFamilyIndices) : BufferEx() { Reset(device, flags, size, usage, sharingMode, queueFamilyIndexCount, pQueueFamilyIndices); } BufferEx::BufferEx(const VkDevice device, const VkBufferCreateInfo& createInfo) : BufferEx() { Reset(device, createInfo); } BufferEx::~BufferEx() { Reset(); } void BufferEx::Reset() { if (! m_buffer.IsValid()) return; m_buffer.Reset(); //m_createInfo.Reset(); m_size = 0; m_usage = 0; m_accessMask = 0; } void BufferEx::Reset(const VkDevice device, const VkBufferCreateFlags flags, const VkDeviceSize size, const VkBufferUsageFlags usage, const VkSharingMode sharingMode, const uint32_t queueFamilyIndexCount, const uint32_t*const pQueueFamilyIndices) { VkBufferCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; createInfo.flags = flags; createInfo.size = size; createInfo.usage = usage; createInfo.sharingMode = sharingMode; createInfo.queueFamilyIndexCount = queueFamilyIndexCount; createInfo.pQueueFamilyIndices = pQueueFamilyIndices; Reset(device, createInfo); } void BufferEx::Reset(const VkDevice device, const VkBufferCreateInfo& createInfo) { m_buffer.Reset(device, createInfo); //m_createInfo.Reset(createInfo); m_size = createInfo.size; m_usage = createInfo.usage; m_accessMask = 0; } void BufferEx::CmdPipelineBarrier(const VkCommandBuffer cmdBuffer, const VkAccessFlags dstAccessMask) { if (m_accessMask == dstAccessMask) return; VkBufferMemoryBarrier bufferMemoryBarrier{}; bufferMemoryBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; bufferMemoryBarrier.srcAccessMask = m_accessMask; bufferMemoryBarrier.dstAccessMask = dstAccessMask; bufferMemoryBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; bufferMemoryBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; bufferMemoryBarrier.buffer = m_buffer.Get(); bufferMemoryBarrier.offset = 0; bufferMemoryBarrier.size = GetSize(); vkCmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 0, nullptr, 1, &bufferMemoryBarrier, 0, nullptr); m_accessMask = dstAccessMask; } } }
ZHAOZhengyi-tgx/BE-Supporter_2016
BE_Supporter/MtnAlgo/MtnAFT/src/MtnTune_b1w.cpp
<gh_stars>0 //The MIT License (MIT) // //Copyright (c) 2016 ZHAOZhengyi-tgx // //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. // (c)All right reserved, <EMAIL> #include "stdafx.h" #include "math.h" #include "MtnTune.h" #include "MtnInitAcs.h" #include "GA.h" #include "acs_buff_prog.h" static BUFFER_DATA_WB_TUNE stBufferDataEmuB1W; static WB_ONE_WIRE_PERFORMANCE_CALC astWbEmuB1WPerformance[NUM_TOTAL_WIRE_IN_ONE_SCOPE]; // WB_ONE_WIRE_PERFORMANCE_CALC stBestB1W_Performance[NUM_TOTAL_WIRE_IN_ONE_SCOPE]; // 20110523 // BOND_HEAD_PERFORMANCE stBondHeadPerformanceBestB1W_; // 20110523 extern WB_ONE_WIRE_PERFORMANCE_CALC astWbOneWirePerformance[NUM_TOTAL_WIRE_IN_ONE_SCOPE]; // 20110529 extern MTN_TUNE_CASE astMotionTuneHistory[MAX_CASE_TUNING_HISTORY_BUFFER]; extern void mtn_tune_round_parameter_to_nearest_1(MTN_TUNE_PARAMETER_SET *stpMtnParaRoundIn, MTN_TUNE_PARAMETER_SET *stpMtnParaRoundOut); extern MTN_TUNE_CASE astMotionTuneFeasibleParameterB1W[MAX_CASE_FEASIBLE_B1W_PARAMETER]; extern int nFeasibleParameter; char cFlagStopTuneB1W; void mtn_wb_tune_b1w_stop() { cFlagStopTuneB1W = TRUE; } extern unsigned int idxCurrCase1By1, nTotalCases1By1; extern double dBestTuneObj1By1; WB_TUNE_B1W_STOP_SRCH_CFG stWbTuneB1W_StopSrch; #include "AcsServo.h" #include "MotAlgo_DLL.h" int mtn_wb_tune_b1w_stop_srch_init_cfg(HANDLE hAcsHandle) { int iRet = MTN_API_OK_ZERO; if(acs_buffprog_get_num_lines_at_buff(DEF_WB_BOND_PROGRAM_IN_BUFF_IDX) > 1) { int iSrchHt; if(!acsc_ReadInteger(hAcsHandle, DEF_WB_BOND_PROGRAM_IN_BUFF_IDX, "IntData", 0, 0, 3, 3, &iSrchHt, NULL )) { iRet = MTN_API_ERROR_ACS_BUFF_PROG; } else { stWbTuneB1W_StopSrch.iSrchHeightPosn = iSrchHt; } int iSrchVel; if(!acsc_ReadInteger(hAcsHandle, DEF_WB_BOND_PROGRAM_IN_BUFF_IDX, "IntData", 0, 0, 4, 4, &iSrchVel, NULL )) { iRet = MTN_API_ERROR_ACS_BUFF_PROG; } else { if(iSrchVel == 0) {iSrchVel = DEF_SRCH_VELOCITY;} // 20120802, protection in case WireBonder is in Dry-run mode stWbTuneB1W_StopSrch.iSrchVelocity = iSrchVel; } int iTailDist; if(!acsc_ReadInteger(hAcsHandle, DEF_WB_BOND_PROGRAM_IN_BUFF_IDX, "IntData", 0, 0, 31, 31, &iTailDist, NULL )) { iRet = MTN_API_ERROR_ACS_BUFF_PROG; } else { stWbTuneB1W_StopSrch.iTailDistance = iTailDist; } int iResetPosn; if(!acsc_ReadInteger(hAcsHandle, DEF_WB_BOND_PROGRAM_IN_BUFF_IDX, "IntData", 0, 0, 32, 32, &iResetPosn, NULL )) { iRet = MTN_API_ERROR_ACS_BUFF_PROG; } else { stWbTuneB1W_StopSrch.iResetPosn = iResetPosn; } } else { iRet = mtn_wb_tune_b1w_update_search_height(hAcsHandle); mtn_wb_tune_b1w_init_search_cfg(); // stWbTuneB1W_StopSrch. } return iRet; } #define DEF_SEARCH_HEIGHT_ABOVE_CONTACT_LEVEL 500 int mtn_wb_tune_b1w_update_search_height(HANDLE hAcsHandle) { int iRet = MTN_API_OK_ZERO; double dLowLimitPosn; int iContactPosnReg; if(!acsc_ReadInteger(hAcsHandle, BUFFER_ID_SEARCH_CONTACT, "CONTACT_POSN_REG", 0, 0, 0, 0, &iContactPosnReg, NULL )) { iRet = MTN_API_ERROR_ACS_BUFF_PROG; } else { if(iContactPosnReg < 0) { stWbTuneB1W_StopSrch.iSrchHeightPosn = iContactPosnReg + DEF_SEARCH_HEIGHT_ABOVE_CONTACT_LEVEL; // 20120726 } else { iRet = MTN_API_ERROR_ACS_BUFF_PROG; } } if(iRet == MTN_API_ERROR_ACS_BUFF_PROG) { if(aft_teach_lower_limit(hAcsHandle, sys_get_acs_axis_id_bnd_z(), 0, &dLowLimitPosn) != MTN_API_OK_ZERO) { iRet = MTN_API_ERROR_DOWNLOAD_DATA; } else { stWbTuneB1W_StopSrch.iSrchHeightPosn = (int)dLowLimitPosn + DEF_SEARCH_HEIGHT_ABOVE_CONTACT_LEVEL; // 20120726 } } return iRet; } void mtn_wb_tune_b1w_init_search_cfg() { #define DEF_RESET_LEVEL_ABOVE_SEARCH_HEIGHT 7500 if(theAcsServo.GetServoOperationMode() == ONLINE_MODE) { // stWbTuneB1W_StopSrch.iResetPosn = (int)mtn_wb_init_bh_relax_position_from_sp(hAcsHandle); // stOutputPosnCompensationTune.iEncoderOffsetSP; stWbTuneB1W_StopSrch.iResetPosn = stWbTuneB1W_StopSrch.iSrchHeightPosn + DEF_RESET_LEVEL_ABOVE_SEARCH_HEIGHT; // 20120727 int iPosnUpperLimitBH = (int)mtn_wb_get_bh_upper_limit_position() - 500; if(stWbTuneB1W_StopSrch.iResetPosn > iPosnUpperLimitBH) { stWbTuneB1W_StopSrch.iResetPosn = iPosnUpperLimitBH; } } else { stWbTuneB1W_StopSrch.iResetPosn = 5000; } stWbTuneB1W_StopSrch.iSrchVelocity = DEF_SRCH_VELOCITY; stWbTuneB1W_StopSrch.iTailDistance = DEF_TAIL_DIST; stWbTuneB1W_StopSrch.i2ndSrchHeightPosn = stWbTuneB1W_StopSrch.iSrchHeightPosn; stWbTuneB1W_StopSrch.i2ndSrchVelocity = DEF_SRCH_VELOCITY; stWbTuneB1W_StopSrch.iKinkHeight = 100; stWbTuneB1W_StopSrch.iLoopTop = 1000; stWbTuneB1W_StopSrch.iRevHeight = 400; } int mtn_wb_tune_b1w_check_valid_search_height() { if( stWbTuneB1W_StopSrch.iSrchHeightPosn == DEF_SEARCH_HEIGHT_ABOVE_CONTACT_LEVEL || stWbTuneB1W_StopSrch.iSrchHeightPosn == 0) { return FALSE; } else { return TRUE; } } int mtn_wb_tune_b1w_update_search_height_posn_by_low_limit(HANDLE hAcsHandle, int iLowLimit) { int iRet = MTN_API_OK_ZERO; if(!acsc_WriteInteger(hAcsHandle, BUFFER_ID_SEARCH_CONTACT, "CONTACT_POSN_REG", 0, 0, 0, 0, &iLowLimit, NULL )) { iRet = MTN_API_ERROR_ACS_BUFF_PROG; } stWbTuneB1W_StopSrch.iSrchHeightPosn = DEF_SEARCH_HEIGHT_ABOVE_CONTACT_LEVEL + iLowLimit; return iRet; } int mtn_wb_tune_b1w_stop_srch_download_cfg() { int iRet = MTN_API_OK_ZERO; acs_set_search_height_posn(stWbTuneB1W_StopSrch.iSrchHeightPosn); acs_set_search_velocity(stWbTuneB1W_StopSrch.iSrchVelocity); // acs_set_search_stop_position(stWbTuneB1W_StopSrch.); acs_set_search_tune_bnd_z_tail_dist(stWbTuneB1W_StopSrch.iTailDistance); acs_set_search_tune_bnd_z_reset_posn(stWbTuneB1W_StopSrch.iResetPosn); acs_set_search_tune_bnd_z_reverse_height(stWbTuneB1W_StopSrch.iRevHeight); return iRet; } double adScopeCollectDataB1W[30000]; double *pRPOS; double *pPE; double *pRVEL; double *pFVEL; double *pDCOM; double *pDOUT; double adVelErr_cnt_p_ms[1000]; extern double fRefPosnZ[LEN_UPLOAD_ARRAY]; extern double fPosnErrZ[LEN_UPLOAD_ARRAY]; extern double fRefVelZ[LEN_UPLOAD_ARRAY]; extern double fFeedVelZ[LEN_UPLOAD_ARRAY]; int mtn_wb_tune_b1w_stop_srch_trig_once(HANDLE hAcsHandle) { int iRet; iRet = MTN_API_OK_ZERO; while(qc_is_axis_still_acc_dec(hAcsHandle, ACSC_AXIS_A)) { Sleep(10); //Sleep(2); } Sleep(10); mtn_run_srch_contact_b1w(hAcsHandle); while(qc_is_axis_still_acc_dec(hAcsHandle, ACSC_AXIS_A)) { Sleep(10); //Sleep(2); } MTN_SCOPE stScopeB1W; stScopeB1W.uiDataLen = 1000; stScopeB1W.uiNumData = 7; stScopeB1W.dSamplePeriod_ms = sys_get_controller_ts(); if (!acsc_ReadReal( hAcsHandle, BUFFER_ID_SEARCH_CONTACT, "rAFT_Scope", 0, stScopeB1W.uiNumData-1, 0, stScopeB1W.uiDataLen - 1, adScopeCollectDataB1W, NULL)) { iRet = MTN_API_ERROR_UPLOAD_DATA; } if (!acsc_ReadReal( hAcsHandle, BUFFER_ID_SEARCH_CONTACT, "rAFT_Scope", 0, 0, 0, LEN_UPLOAD_ARRAY - 1, fRefPosnZ, NULL)) { iRet = MTN_API_ERROR_UPLOAD_DATA; } if (!acsc_ReadReal( hAcsHandle, BUFFER_ID_SEARCH_CONTACT, "rAFT_Scope", 1, 1, 0, LEN_UPLOAD_ARRAY - 1, fPosnErrZ, NULL)) { iRet = MTN_API_ERROR_UPLOAD_DATA; } if (!acsc_ReadReal( hAcsHandle, BUFFER_ID_SEARCH_CONTACT, "rAFT_Scope", 2, 2, 0, LEN_UPLOAD_ARRAY - 1, fRefVelZ, NULL)) { iRet = MTN_API_ERROR_UPLOAD_DATA; } double dCountPerSec = 1000.0; // / sys_get_controller_ts(); int ii; for(ii=0; ii<LEN_UPLOAD_ARRAY; ii++) { fRefVelZ[ii] /= dCountPerSec; } if (!acsc_ReadReal( hAcsHandle, BUFFER_ID_SEARCH_CONTACT, "rAFT_Scope", 3, 3, 0, LEN_UPLOAD_ARRAY - 1, fFeedVelZ, NULL)) { iRet = MTN_API_ERROR_UPLOAD_DATA; } for(ii=0; ii<LEN_UPLOAD_ARRAY; ii++) { fFeedVelZ[ii] /= dCountPerSec; } return iRet; } extern double f_get_mean(double *afIn, int nLen); extern double f_get_std(double *afIn, double fMean, int nLen); extern double f_get_abs_max(double *afIn, int nLen); extern double f_get_min(double *afIn, int nLen); extern double f_get_max(double *afIn, int nLen); extern double f_get_rms_max_err_w_offset(double *afIn, int nLen, double dOffset); int mtn_wb_tune_b1w_stop_srch_calc_bh_obj( MTN_SCOPE *stpScopeB1W, double adScopeDataB1W[], WB_TUNE_B1W_BH_OBJ *stpWbTuneB1wObj) { TIME_POINTS_OF_BONDHEAD_Z stTimePointsOfBondHeadZ; memset(&stTimePointsOfBondHeadZ, 0, sizeof(stTimePointsOfBondHeadZ)); pRPOS = fRefPosnZ;//&adScopeDataB1W[0]; pPE = fPosnErrZ;//&adScopeDataB1W[stpScopeB1W->uiDataLen]; pRVEL = fRefVelZ;//&adScopeDataB1W[stpScopeB1W->uiDataLen * 2]; pFVEL = fFeedVelZ;//&adScopeDataB1W[stpScopeB1W->uiDataLen * 3]; pDCOM = &adScopeDataB1W[stpScopeB1W->uiDataLen * 4]; pDOUT = &adScopeDataB1W[stpScopeB1W->uiDataLen * 5]; //memcpy(fRefPosnZ, pRPOS, LEN_UPLOAD_ARRAY * sizeof(double)); //memcpy(fPosnErrZ, pPE, LEN_UPLOAD_ARRAY * sizeof(double)); //memcpy(fRefVelZ, pRVEL, LEN_UPLOAD_ARRAY * sizeof(double)); //memcpy(fFeedVelZ, pFVEL, LEN_UPLOAD_ARRAY * sizeof(double)); double dCountPerSec = 1000.0; // / sys_get_controller_ts(); unsigned int ii; double dFbAcc[LEN_UPLOAD_ARRAY]; for(ii=0; ii<LEN_UPLOAD_ARRAY - 1; ii++) { dFbAcc[ii] = pFVEL[ii] - pFVEL[ii-1]; } //for(ii = 0; ii< LEN_UPLOAD_ARRAY; ii++) //{ // fFeedVelZ[ii] = fFeedVelZ[ii]/dCountPerSec; // fRefVelZ[ii] = fRefVelZ[ii]/dCountPerSec; //} unsigned int idxStartMoveSrchHt, idxEndMoveSrchHt, idxStartSearch, idxStopSearch, idxStartMoveTail, idxEndMoveTail, idxEndMoveReset; unsigned int idxStartLooping, idxEndLooping, idxStartLoopTop, idxEndLoopTop, idxStartTraj, idxEndTraj, idxStart2ndSrch, idxEnd2ndSrch; int iFlagStartTraj; double dStartPosn; idxStartLooping = idxEndLooping = idxStartLoopTop = idxEndLoopTop = idxStartTraj = idxEndTraj = idxStart2ndSrch = idxEnd2ndSrch = 0; idxStartMoveSrchHt = idxEndMoveSrchHt = idxStartSearch = idxStartMoveTail = idxEndMoveTail = idxStopSearch = idxEndMoveReset = 0; iFlagStartTraj = 0; for(ii=0; ii<LEN_UPLOAD_ARRAY; ii++) { if(idxStartMoveSrchHt == 0 && pRVEL[ii + 1] < -0.5 && fabs(pRVEL[ii]) < 0.5 ) { idxStartMoveSrchHt = ii+1; dStartPosn = pRPOS[ii]; } if( pRVEL[ii] < 0 && (fabs(pRVEL[ii + 2] - pRVEL[ii + 1])< 0.01 || fabs(pRVEL[ii + 1]) <= 0.5) //pRPOS[ii] <= stWbTuneB1W_StopSrch.iSrchHeightPosn && idxEndMoveSrchHt == 0 && idxStartMoveSrchHt != 0) { idxEndMoveSrchHt = ii + 1; } if( fabs(pRVEL[ii + 1] - pRVEL[ii]) < 0.5 && fabs(pRVEL[ii] * dCountPerSec - stWbTuneB1W_StopSrch.iSrchVelocity ) < 0.01 && idxStartSearch == 0 && idxEndMoveSrchHt != 0) { idxStartSearch = ii; } if(idxStopSearch == 0 && idxStartSearch !=0 && fabs(pRVEL[ii]) < 0.5 ) { idxStopSearch = ii; break; } } if(idxStartSearch == 0) { idxStartSearch = idxEndMoveSrchHt; idxStopSearch = idxStartSearch + 12;} // 20120802 for(ii=idxStopSearch; ii<LEN_UPLOAD_ARRAY; ii++) { if(idxStartLooping == 0 && pRVEL[ii] > 0 && pRVEL[ii- 1] <=0 ) { idxStartLooping = ii; } if(idxStartLooping != 0 && iFlagStartTraj == 0 && (pRVEL[ii] <= -1E2 ) // 1E5 // || pRPOS[ii+2] <= stWbTuneB1W_StopSrch.i2ndSrchHeightPosn) ) { iFlagStartTraj = 1; //if(pRPOS[ii] <= stWbTuneB1W_StopSrch.i2ndSrchHeightPosn) //{ // idxEndTraj = ii; //} } if(idxEndTraj == 0 && iFlagStartTraj != 0 && pRVEL[ii] < 0 && (pRVEL[ii + 1] == 0 || fabs(pRVEL[ii + 1] - pRVEL[ii + 2])<0.5) )//pRPOS[ii] <= stWbTuneB1W_StopSrch.i2ndSrchHeightPosn) { idxEndTraj = ii; break; } } for(ii = idxEndTraj; ii>= idxStopSearch; ii--) { if(idxStartTraj == 0 && (pRVEL[ii-1] >= 0 && pRVEL[ii] < 0) ) { idxStartTraj = ii; } if(idxEndLoopTop == 0 && idxStartTraj != 0 && (pRVEL[ii-1] > 0 && pRVEL[ii] <= 0 ) ) { idxEndLoopTop = ii; } if(idxStartLoopTop == 0 && idxEndLoopTop != 0 && ( (pRVEL[ii-1] <= 0 && pRVEL[ii] > 0 ) || (pRVEL[ii-1] <= pRVEL[ii] && pRVEL[ii-1] <= pRVEL[ii - 2]) ) ) { idxStartLoopTop = ii; idxEndLooping = ii; } if( idxEndLooping != 0 && idxStartLooping == 0 && fabs(pRVEL[ii]) < 0.5 && pRVEL[ii+1] > 0.5) { idxStartLooping = ii; break; } } for(ii=idxEndTraj; ii<LEN_UPLOAD_ARRAY; ii++) { // 20120512 if(idxStart2ndSrch == 0 && fabs(pRVEL[ii] * dCountPerSec - stWbTuneB1W_StopSrch.i2ndSrchVelocity ) < 0.01 ) { idxStart2ndSrch = ii; } if(idxEnd2ndSrch == 0 && idxStart2ndSrch !=0 && fabs(pRVEL[ii]) < 0.5 ) { idxEnd2ndSrch = ii; } // 20120512 if(idxEnd2ndSrch != 0 // idxStopSearch && idxStartMoveTail == 0 && fabs(pRVEL[ii]) < 0.5 && pRVEL[ii+1] > 0.5) { idxStartMoveTail = ii; } if( idxStartMoveTail != 0 && idxEndMoveTail == 0 && pRVEL[ii] > 0.5 && fabs(pRVEL[ii + 1] ) < 0.5) { idxEndMoveTail = ii + 1; } if(idxEndMoveTail != 0 && idxEndMoveReset == 0 && pRVEL[ii] > 0.5 && fabs(pRVEL[ii + 1] ) < 0.5 && fabs(pRPOS[ii + 1] - dStartPosn) < 0.5 ) // && fabs(pRPOS[ii] - stWbTuneB1W_StopSrch.iResetPosn ) < 0.5 ) { idxEndMoveReset = ii + 1; break; } } if(idxStart2ndSrch == 0) {idxStart2ndSrch = idxEndTraj; idxEnd2ndSrch = idxStart2ndSrch + 12; } // 20120802 stTimePointsOfBondHeadZ.idxStartMove1stBondSearchHeight = idxStartMoveSrchHt; stTimePointsOfBondHeadZ.idxEndMove1stBondSearchHeight = idxEndMoveSrchHt; stTimePointsOfBondHeadZ.idxStart1stBondForceCtrl = idxStopSearch; stTimePointsOfBondHeadZ.idxEnd1stBondForceCtrl = idxStopSearch; stTimePointsOfBondHeadZ.idxStartMoveLoopTop = idxStartLoopTop; stTimePointsOfBondHeadZ.idxEndMoveLoopTop = idxEndLoopTop; stTimePointsOfBondHeadZ.idxStartReverseHeight = idxStartLooping; stTimePointsOfBondHeadZ.idxEndReverseHeight = idxEndLooping; stTimePointsOfBondHeadZ.idxStartKinkHeight = idxEndLooping; stTimePointsOfBondHeadZ.idxEndKinkHeight = idxEndLooping; stTimePointsOfBondHeadZ.idxStartTrajectory = idxStartTraj; stTimePointsOfBondHeadZ.idxEndTrajectory2ndBondSearchHeight = idxStart2ndSrch; stTimePointsOfBondHeadZ.idxEndTrajectory2ndBondSearchHeight = idxEndTraj; stTimePointsOfBondHeadZ.idxStart2ndBondSearchContact = idxStart2ndSrch; stTimePointsOfBondHeadZ.idxStart2ndBondForceCtrl = idxEnd2ndSrch; stTimePointsOfBondHeadZ.idxEnd2ndBondForceCtrl = idxEnd2ndSrch; stTimePointsOfBondHeadZ.idxStartTail = idxStartMoveTail; stTimePointsOfBondHeadZ.idxEndTail = idxEndMoveTail; stTimePointsOfBondHeadZ.idxStartFireLevel = idxEndMoveTail + 1; stTimePointsOfBondHeadZ.idxEndFireLevel = idxEndMoveReset; //// for(ii = 0; ii< idxEndMoveReset + 100; ii++) { adVelErr_cnt_p_ms[ii] = (pRVEL[ii] - pFVEL[ii]); ///dCountPerSec; // 1000.0; } stpWbTuneB1wObj->dObj[WB_BH_SRCH_HT] = fabs(pPE[idxEndMoveSrchHt]) + fabs(adVelErr_cnt_p_ms[idxEndMoveSrchHt]); stpWbTuneB1wObj->dObj[WB_BH_SRCH_HT] += fabs(pPE[idxEndMoveSrchHt + 1]) + fabs(adVelErr_cnt_p_ms[idxEndMoveSrchHt + 1]); stpWbTuneB1wObj->dObj[WB_BH_SRCH_HT] += fabs(pPE[idxEndMoveSrchHt + 2]) + fabs(adVelErr_cnt_p_ms[idxEndMoveSrchHt + 2]); stpWbTuneB1wObj->dObj[WB_BH_SRCH_HT] += fabs(pPE[idxEndMoveSrchHt - 1]) + fabs(adVelErr_cnt_p_ms[idxEndMoveSrchHt - 1]); //stpWbTuneB1wObj->dObj[WB_BH_SRCH_HT] += fabs(pPE[idxEndMoveSrchHt - 2]) + fabs(adVelErr_cnt_p_ms[idxEndMoveSrchHt - 2]); //stpWbTuneB1wObj->dObj[WB_BH_SRCH_HT] += fabs(pPE[idxEndMoveSrchHt - 3]) + fabs(adVelErr_cnt_p_ms[idxEndMoveSrchHt - 3]); //stpWbTuneB1wObj->dObj[WB_BH_SRCH_HT] += fabs(pPE[idxEndMoveSrchHt - 4]) + fabs(adVelErr_cnt_p_ms[idxEndMoveSrchHt - 4]); //stpWbTuneB1wObj->dObj[WB_BH_SRCH_HT] += fabs(pPE[idxEndMoveSrchHt - 5]) + fabs(adVelErr_cnt_p_ms[idxEndMoveSrchHt - 5]); int nSrchLen = idxStopSearch - idxStartSearch; double dMeanVelErr = f_get_mean(&adVelErr_cnt_p_ms[idxStartSearch], nSrchLen ); // +8 - 8 // 20121108 double dStdVelErr = f_get_std(&adVelErr_cnt_p_ms[idxStartSearch], dMeanVelErr, nSrchLen ); // +8 - 8 // 20121108 stpWbTuneB1wObj->dObj[WB_BH_SRCH_HT] += dStdVelErr; //// 20120802 double dVelErrP2P = f_get_max(&adVelErr_cnt_p_ms[idxStartSearch], nSrchLen ) - f_get_min(&adVelErr_cnt_p_ms[idxStartSearch], nSrchLen); // 20121108 double dMaxPosnErr = f_get_abs_max(&pPE[idxStartSearch], nSrchLen); // 20121108 double dRmsPosnErrWithOffset = f_get_rms_max_err_w_offset(&pPE[idxStartSearch], nSrchLen, 0.0); //// 20121108 double dStdFbAcc = f_get_std(&dFbAcc[idxStartSearch ], 0, nSrchLen); // 20121108 stpWbTuneB1wObj->dObj[WB_BH_1ST_CONTACT] = dRmsPosnErrWithOffset * dRmsPosnErrWithOffset * 2.0 // 20120802 + dStdFbAcc * dStdFbAcc; // EXPECT_POSN_ERR_FB_LEAD_CMD_SRCH_CONTACT // + dVelErrP2P/2.0 * dVelErrP2P / 2.0 // + dMeanVelErr * dMeanVelErr; stpWbTuneB1wObj->dObj[WB_BH_TAIL] = fabs(pPE[idxEndMoveTail]); stpWbTuneB1wObj->dObj[WB_BH_TAIL] += fabs(pPE[idxEndMoveTail + 1] ); if(pFVEL[idxEndMoveTail] < 0) { stpWbTuneB1wObj->dObj[WB_BH_TAIL] = stpWbTuneB1wObj->dObj[WB_BH_TAIL] + fabs(pFVEL[idxEndMoveTail]) + fabs(pPE[idxEndMoveTail]); //1000 } if(pFVEL[idxEndMoveTail + 1] < 0) { stpWbTuneB1wObj->dObj[WB_BH_TAIL] = stpWbTuneB1wObj->dObj[WB_BH_TAIL] + fabs(pFVEL[idxEndMoveTail + 1]) + fabs(pPE[idxEndMoveTail + 1] ); //1000 } stpWbTuneB1wObj->dObj[WB_BH_RESET] = fabs(pPE[idxEndMoveReset]) + fabs(adVelErr_cnt_p_ms[idxEndMoveReset]); //1000 stpWbTuneB1wObj->dObj[WB_BH_RESET] += fabs(pPE[idxEndMoveReset-1]) + fabs(adVelErr_cnt_p_ms[idxEndMoveReset-1]); //1000 stpWbTuneB1wObj->dObj[WB_BH_RESET] += fabs(pPE[idxEndMoveReset-2]) + fabs(adVelErr_cnt_p_ms[idxEndMoveReset-2]); //1000 stpWbTuneB1wObj->dObj[WB_BH_RESET] += fabs(pPE[idxEndMoveReset+1]) + fabs(adVelErr_cnt_p_ms[idxEndMoveReset+1]); //1000 stpWbTuneB1wObj->dObj[WB_BH_RESET] += fabs(pPE[idxEndMoveReset+2]) + fabs(adVelErr_cnt_p_ms[idxEndMoveReset+2]); //1000 // stpWbTuneB1wObj->dObj[WB_BH_2ND_CONTACT] = ; // double dMeanVelErr = f_get_mean(&adVelErr_cnt_p_ms[idxEndMoveReset], 8); double dVelErrRMS = f_get_std(&adVelErr_cnt_p_ms[idxEndMoveReset ], 0, 40); // 20120802 double dPosnErrRMS = f_get_std(&pPE[idxEndMoveReset ], 0, 40); // 20120802 stpWbTuneB1wObj->dObj[WB_BH_IDLE] = dVelErrRMS + dPosnErrRMS; stpWbTuneB1wObj->dObj[WB_BH_TRAJECTORY] = fabs(pPE[idxEndTraj]) + fabs(adVelErr_cnt_p_ms[idxEndTraj]); stpWbTuneB1wObj->dObj[WB_BH_TRAJECTORY] += fabs(pPE[idxEndTraj + 1]) + fabs(adVelErr_cnt_p_ms[idxEndTraj + 1]); stpWbTuneB1wObj->dObj[WB_BH_TRAJECTORY] += fabs(pPE[idxEndTraj + 2]) + fabs(adVelErr_cnt_p_ms[idxEndTraj + 2]); stpWbTuneB1wObj->dObj[WB_BH_TRAJECTORY] += fabs(pPE[idxEndTraj + 3]) + fabs(adVelErr_cnt_p_ms[idxEndTraj + 3]); stpWbTuneB1wObj->dObj[WB_BH_TRAJECTORY] += fabs(pPE[idxEndTraj - 1]) + fabs(adVelErr_cnt_p_ms[idxEndTraj - 1]); // stpWbTuneB1wObj->dObj[WB_BH_TRAJECTORY] += fabs(pPE[idxEndTraj - 2]) + fabs(adVelErr_cnt_p_ms[idxEndTraj - 2]); //stpWbTuneB1wObj->dObj[WB_BH_TRAJECTORY] += fabs(pPE[idxEndTraj - 3]) + fabs(adVelErr_cnt_p_ms[idxEndTraj - 3]); //stpWbTuneB1wObj->dObj[WB_BH_TRAJECTORY] += fabs(pPE[idxEndTraj - 4]) + fabs(adVelErr_cnt_p_ms[idxEndTraj - 4]); //stpWbTuneB1wObj->dObj[WB_BH_TRAJECTORY] += fabs(pPE[idxEndTraj - 5]) + fabs(adVelErr_cnt_p_ms[idxEndTraj - 5]); stpWbTuneB1wObj->dObj[WB_BH_LOOP_TOP] = fabs(pPE[idxEndLoopTop]) + fabs(adVelErr_cnt_p_ms[idxEndLoopTop]); stpWbTuneB1wObj->dObj[WB_BH_LOOP_TOP] += fabs(pPE[idxEndLoopTop+1]) + fabs(adVelErr_cnt_p_ms[idxEndLoopTop+1]); stpWbTuneB1wObj->dObj[WB_BH_LOOP_TOP] += fabs(pPE[idxEndLoopTop+2]) + fabs(adVelErr_cnt_p_ms[idxEndLoopTop+2]); // stpWbTuneB1wObj->dObj[WB_BH_LOOP_TOP] += fabs(pPE[idxEndLoopTop+3]) + fabs(adVelErr_cnt_p_ms[idxEndLoopTop+3]); // stpWbTuneB1wObj->dObj[WB_BH_LOOP_TOP] += fabs(pPE[idxEndLoopTop+4]) + fabs(adVelErr_cnt_p_ms[idxEndLoopTop+4]); //WB_TUNE_B1W_BH_OBJ stWbTuneB1wObj; // // memset(&stWbTuneB1wObj, 0, sizeof(stWbTuneB1wObj)); // stpWbTuneB1wObj->dObj[WB_BH_SRCH_HT] = mtn_wb_tune_b1w_calc_bh_obj(&stTimePointsOfBondHeadZ, WB_BH_SRCH_HT); // // stpWbTuneB1wObj->dObj[WB_BH_1ST_CONTACT] = mtn_wb_tune_b1w_calc_bh_obj(&stTimePointsOfBondHeadZ, WB_BH_1ST_CONTACT); // // stpWbTuneB1wObj->dObj[WB_BH_TAIL] = mtn_wb_tune_b1w_calc_bh_obj(&stTimePointsOfBondHeadZ, WB_BH_TAIL); // // stpWbTuneB1wObj->dObj[WB_BH_RESET] = mtn_wb_tune_b1w_calc_bh_obj(&stTimePointsOfBondHeadZ, WB_BH_RESET); // // stpWbTuneB1wObj->dObj[WB_BH_IDLE] = mtn_wb_tune_b1w_calc_bh_obj(&stTimePointsOfBondHeadZ, WB_BH_IDLE); // // stpWbTuneB1wObj->dObj[WB_BH_TRAJECTORY] = mtn_wb_tune_b1w_calc_bh_obj(&stTimePointsOfBondHeadZ, WB_BH_TRAJECTORY); // nSrchLen = idxEnd2ndSrch - idxEndTraj; dMeanVelErr = f_get_mean(&adVelErr_cnt_p_ms[idxEndTraj], nSrchLen); // 20121108 dStdVelErr = f_get_std(&adVelErr_cnt_p_ms[idxEndTraj], dMeanVelErr, nSrchLen); // 20121108 dVelErrP2P = f_get_max(&adVelErr_cnt_p_ms[idxEndTraj], nSrchLen ) - f_get_min(&adVelErr_cnt_p_ms[idxEndTraj], nSrchLen); // 20121108 dMaxPosnErr = f_get_abs_max(&pPE[idxEndTraj], nSrchLen); dRmsPosnErrWithOffset = f_get_rms_max_err_w_offset(&pPE[idxStartSearch], nSrchLen, 0.0); //// 20121108 dStdFbAcc = f_get_std(&dFbAcc[idxEndTraj], 0, nSrchLen); // 20121108 stpWbTuneB1wObj->dObj[WB_BH_2ND_CONTACT] = dRmsPosnErrWithOffset * dRmsPosnErrWithOffset * 2.0 // 20120802 + dStdFbAcc * dStdFbAcc; // dMaxPosnErr // EXPECT_POSN_ERR_FB_LEAD_CMD_SRCH_CONTACT // + dVelErrP2P/2.0 * dVelErrP2P / 2.0 // + dMeanVelErr * dMeanVelErr; // 20120802 stpWbTuneB1wObj->dObj[WB_BH_LOOP_TOP] += stpWbTuneB1wObj->dObj[WB_BH_TRAJECTORY]/10.0; stpWbTuneB1wObj->dObj[WB_BH_TRAJECTORY] += stpWbTuneB1wObj->dObj[WB_BH_2ND_CONTACT]/10.0; // 20120802 // 20120512 stpWbTuneB1wObj->dObj[WB_BH_LOOPING] = mtn_wb_tune_b1w_calc_bh_obj(&stTimePointsOfBondHeadZ, WB_BH_LOOPING); // // stpWbTuneB1wObj->dObj[WB_BH_LOOP_TOP] = mtn_wb_tune_b1w_calc_bh_obj(&stTimePointsOfBondHeadZ, WB_BH_LOOP_TOP); // // stpWbTuneB1wObj->dObj[WB_BH_2ND_CONTACT] = mtn_wb_tune_b1w_calc_bh_obj(&stTimePointsOfBondHeadZ, WB_BH_2ND_CONTACT); // return MTN_API_OK_ZERO; } #define MAX_CASE_B1W_EACH_PARA 3 extern int idxBestParaSet; int mtn_wb_tune_bond_1_wire_bh(MTN_TUNE_GENETIC_INPUT *stpMtnTuneInput, MTN_TUNE_GENETIC_OUTPUT *stpMtnTuneOutput, int iObjSectionFlagB1W) { //int nTotalNumWire; HANDLE stCommHandle = stpMtnTuneInput->stCommHandle; MTN_TUNE_THEME *stpTuningTheme = &stpMtnTuneInput->stTuningTheme; TUNE_ALGO_SETTING *stpTuningAlgoSetting = &stpMtnTuneInput->stTuningAlgoSetting; MTN_TUNE_PARA_UNION *stpTuningParameterIni = &stpMtnTuneInput->stTuningParameterIni; MTN_TUNE_PARA_UNION *stpTuningParameterUppBound = &stpMtnTuneInput->stTuningParameterUppBound; MTN_TUNE_PARA_UNION *stpTuningParameterLowBound = &stpMtnTuneInput->stTuningParameterLowBound; MTN_TUNE_CONDITION *stpTuningCondition = &stpMtnTuneInput->stTuningCondition; MTN_TUNE_ENC_TIME_CFG *stpTuningEncTimeConfig = &stpMtnTuneInput->stTuningEncTimeConfig; MTN_TUNE_SPECIFICATION *stpTuningPassSpecfication = &stpMtnTuneInput->stTuningPassSpecfication; int iAxisTuningACS = stpMtnTuneInput->iAxisTuning; double adParaPosnKP[2 * NUM_POINTS_ONE_DIM_MESH], dStepPosnKP; double adParaVelKP[2 * NUM_POINTS_ONE_DIM_MESH], dStepVelKP; double adParaVelKI[2 * NUM_POINTS_ONE_DIM_MESH], dStepVelKI; double adParaAccFFC[2 * NUM_POINTS_ONE_DIM_MESH], dStepAccFFC; double adParaJerkFFC[2 * NUM_POINTS_ONE_DIM_MESH], dStepJerkFFC; // 20110529 int ii, jj, kk, ll, nActualPointsTunePKP, nActualPointsTuneVKP, nActualPointsTuneAccFF, nActualPointsTuneVKI, nActualPointsTuneJerkFF, cc; // mm, double cTempObjCaseInB1W; short sRet = MTN_API_OK_ZERO; // int idxBestParaSet; // Backup and relax the safety parameters SAFETY_PARA_ACS stSafetyParaBak, stSafetyParaCurr; mtnapi_upload_safety_parameter_acs_per_axis(stCommHandle, iAxisTuningACS, &stSafetyParaBak); stSafetyParaCurr = stSafetyParaBak; stSafetyParaCurr.dCriticalPosnErrAcc = 5000; stSafetyParaCurr.dCriticalPosnErrIdle = 5000; stSafetyParaCurr.dCriticalPosnErrVel = 1000; stSafetyParaCurr.dRMS_DrvCmdX = stSafetyParaCurr.dRMS_DrvCmdX * 2; stSafetyParaCurr.dRMS_DrvCmdIdle = stSafetyParaCurr.dRMS_DrvCmdIdle * 2; stSafetyParaCurr.dRMS_DrvCmdMtn = 100; // 20120717, must release to 100% for motion tuning mtnapi_download_safety_parameter_acs_per_axis(stCommHandle, iAxisTuningACS, &stSafetyParaCurr); // Backup and relax Safety parameter for WireClamp SAFETY_PARA_ACS stSafetyParaBakWCL, stSafetyParaCurrWCL; mtnapi_upload_safety_parameter_acs_per_axis(stCommHandle, sys_get_acs_axis_id_wire_clamp(), &stSafetyParaBakWCL); stSafetyParaCurrWCL = stSafetyParaBakWCL; stSafetyParaCurrWCL.dRMS_DrvCmdX = stSafetyParaBakWCL.dRMS_DrvCmdX * 2; if(stSafetyParaCurrWCL.dRMS_DrvCmdX > 100) { stSafetyParaCurrWCL.dRMS_DrvCmdX = 100; } stSafetyParaCurrWCL.dRMS_TimeConst = stSafetyParaBakWCL.dRMS_TimeConst * 6; mtnapi_download_safety_parameter_acs_per_axis(stCommHandle, sys_get_acs_axis_id_wire_clamp(), &stSafetyParaCurrWCL); //int iFlagDoingTest; //Clear the tuning history buffer idxCurrCase1By1 = idxBestParaSet = 0; memset(astMotionTuneHistory, 0, sizeof(MTN_TUNE_CASE) * MAX_CASE_TUNING_HISTORY_BUFFER); // Init Parameter MTN_TUNE_PARAMETER_SET stCurrTuneBondHeadParaB1W = stpTuningParameterIni->stMtnPara; // Start EmuB1W if(mtn_b1w_write_para_bh_servo_readve(stCommHandle, &stCurrTuneBondHeadParaB1W, iObjSectionFlagB1W) != MTN_API_OK_ZERO) { sRet = MTN_API_ERROR_DOWNLOAD_DATA; goto label_mtn_wb_tune_bond_1_wire_bh; } int uiTotalNumPointsOneDim = NUM_POINTS_ONE_DIM_MESH; if(iObjSectionFlagB1W == WB_BH_1ST_CONTACT || iObjSectionFlagB1W == WB_BH_2ND_CONTACT) { uiTotalNumPointsOneDim = 2 * NUM_POINTS_ONE_DIM_MESH; } for(cc = 0, cTempObjCaseInB1W=0; cc<MAX_CASE_B1W_EACH_PARA; cc++) { //if(mtnapi_wait_axis_settling(stCommHandle, iAxisTuningACS, POSN_SETTLE_TH_DURING_TUNING) != MTN_API_OK_ZERO) //{ // sRet = MTN_API_ERROR_ACS_ERROR_SETTLING;// // goto label_mtn_wb_tune_bond_1_wire_bh; //} if(acs_bufprog_start_buff_b1w_(&astWbEmuB1WPerformance[cc]) != MTN_API_OK_ZERO) { sRet = MTN_API_ERROR_UPLOAD_DATA;// goto label_mtn_wb_tune_bond_1_wire_bh; } cTempObjCaseInB1W = cTempObjCaseInB1W + mtn_tune_calc_b1w_bh_performance(&astWbEmuB1WPerformance[cc], stpTuningTheme, iObjSectionFlagB1W); } astMotionTuneHistory[idxCurrCase1By1].dTuningObj = cTempObjCaseInB1W/MAX_CASE_B1W_EACH_PARA; stpMtnTuneOutput->dInitialObj = astMotionTuneHistory[idxCurrCase1By1].dTuningObj; // mtn_tune_calc_b1w_bh_performance(&astWbEmuB1WPerformance[0], stpTuningTheme, iObjSectionFlagB1W); stpMtnTuneOutput->stInitialB1WPerformanceBH = astWbEmuB1WPerformance[0].stBondHeadPerformance; dBestTuneObj1By1 = stpMtnTuneOutput->dInitialObj; // astMotionTuneHistory[idxCurrCase1By1].dTuningObj = mtn_tune_calc_b1w_bh_performance(&astWbEmuB1WPerformance[0], stpTuningTheme, iObjSectionFlagB1W); astMotionTuneHistory[idxCurrCase1By1].stTuneBondHeadPerformanceB1W = astWbEmuB1WPerformance[0].stBondHeadPerformance; astMotionTuneHistory[idxCurrCase1By1].stServoPara.stMtnPara = stCurrTuneBondHeadParaB1W; // Init Parameter and step size MTN_TUNE_PARA_UNION stCurrTuneParaUppBound, stCurrTuneParaLowBound; stCurrTuneParaUppBound.stMtnPara = stpTuningParameterUppBound->stMtnPara; stCurrTuneParaLowBound.stMtnPara = stpTuningParameterLowBound->stMtnPara; dStepPosnKP = (stCurrTuneParaUppBound.stMtnPara.dPosnLoopKP - stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP)/(uiTotalNumPointsOneDim - 1); dStepVelKP = (stCurrTuneParaUppBound.stMtnPara.dVelLoopKP - stCurrTuneParaLowBound.stMtnPara.dVelLoopKP)/(uiTotalNumPointsOneDim - 1); dStepVelKI = (stCurrTuneParaUppBound.stMtnPara.dVelLoopKI - stCurrTuneParaLowBound.stMtnPara.dVelLoopKI)/(uiTotalNumPointsOneDim - 1); dStepAccFFC = (stCurrTuneParaUppBound.stMtnPara.dAccFFC - stCurrTuneParaLowBound.stMtnPara.dAccFFC)/(uiTotalNumPointsOneDim - 1); dStepJerkFFC = (stCurrTuneParaUppBound.stMtnPara.dJerkFf - stCurrTuneParaLowBound.stMtnPara.dJerkFf)/(uiTotalNumPointsOneDim - 1); for(ii =0; ii<uiTotalNumPointsOneDim; ii++) { adParaPosnKP[ii] = stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP + dStepPosnKP * ii; adParaVelKP[ii] = stCurrTuneParaLowBound.stMtnPara.dVelLoopKP + dStepVelKP * ii; adParaVelKI[ii] = stCurrTuneParaLowBound.stMtnPara.dVelLoopKI + dStepVelKI * ii; adParaAccFFC[ii] = stCurrTuneParaLowBound.stMtnPara.dAccFFC + dStepAccFFC * ii; adParaJerkFFC[ii] = stCurrTuneParaLowBound.stMtnPara.dJerkFf + dStepJerkFFC * ii; // 20110529 } nTotalCases1By1 = stpTuningAlgoSetting->uiMaxGeneration * 5 * uiTotalNumPointsOneDim; //10000; // NUM_POINTS_ONE_DIM_MESH * NUM_POINTS_ONE_DIM_MESH * NUM_POINTS_ONE_DIM_MESH * NUM_POINTS_ONE_DIM_MESH; if(nTotalCases1By1 > MAX_CASE_TUNING_HISTORY_BUFFER) { nTotalCases1By1 = MAX_CASE_TUNING_HISTORY_BUFFER; } unsigned int iCurrLoop =0; nActualPointsTunePKP = nActualPointsTuneVKP = nActualPointsTuneAccFF = nActualPointsTuneJerkFF = nActualPointsTuneVKI = uiTotalNumPointsOneDim; ///////////// Check upper and lower boundary // 20110529 // AccFF if(stCurrTuneBondHeadParaB1W.dAccFFC > stCurrTuneParaUppBound.stMtnPara.dAccFFC) { stCurrTuneBondHeadParaB1W.dAccFFC = stCurrTuneParaUppBound.stMtnPara.dAccFFC; } if(stCurrTuneBondHeadParaB1W.dAccFFC < stCurrTuneParaLowBound.stMtnPara.dAccFFC) { stCurrTuneBondHeadParaB1W.dAccFFC = stCurrTuneParaLowBound.stMtnPara.dAccFFC; } if(fabs(stCurrTuneParaUppBound.stMtnPara.dAccFFC - stCurrTuneParaLowBound.stMtnPara.dAccFFC) <= 1.5) { stCurrTuneBondHeadParaB1W.dAccFFC = (stCurrTuneParaUppBound.stMtnPara.dAccFFC + stCurrTuneParaLowBound.stMtnPara.dAccFFC)/2.0; nActualPointsTuneAccFF = 0; } // PosnLoopKP if(stCurrTuneBondHeadParaB1W.dPosnLoopKP > stCurrTuneParaUppBound.stMtnPara.dPosnLoopKP) { stCurrTuneBondHeadParaB1W.dPosnLoopKP = stCurrTuneParaUppBound.stMtnPara.dPosnLoopKP; } if(stCurrTuneBondHeadParaB1W.dPosnLoopKP < stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP) { stCurrTuneBondHeadParaB1W.dPosnLoopKP = stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP; } if(fabs(stCurrTuneParaUppBound.stMtnPara.dPosnLoopKP - stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP) <= 1.5) { stCurrTuneBondHeadParaB1W.dPosnLoopKP = (stCurrTuneParaUppBound.stMtnPara.dPosnLoopKP + stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP)/2.0; nActualPointsTunePKP = 0; } // dVelLoopKI if(stCurrTuneBondHeadParaB1W.dVelLoopKI > stCurrTuneParaUppBound.stMtnPara.dVelLoopKI) { stCurrTuneBondHeadParaB1W.dVelLoopKI = stCurrTuneParaUppBound.stMtnPara.dVelLoopKI; } if(stCurrTuneBondHeadParaB1W.dVelLoopKI < stCurrTuneParaLowBound.stMtnPara.dVelLoopKI) { stCurrTuneBondHeadParaB1W.dVelLoopKI = stCurrTuneParaLowBound.stMtnPara.dVelLoopKI; } if(fabs(stCurrTuneParaUppBound.stMtnPara.dVelLoopKI - stCurrTuneParaLowBound.stMtnPara.dVelLoopKI) <= 1.5) { stCurrTuneBondHeadParaB1W.dVelLoopKI = (stCurrTuneParaUppBound.stMtnPara.dVelLoopKI + stCurrTuneParaLowBound.stMtnPara.dVelLoopKI)/2.0; nActualPointsTuneVKI = 0; } // dVelLoopKP if(stCurrTuneBondHeadParaB1W.dVelLoopKP > stCurrTuneParaUppBound.stMtnPara.dVelLoopKP) { stCurrTuneBondHeadParaB1W.dVelLoopKP = stCurrTuneParaUppBound.stMtnPara.dVelLoopKP; } if(stCurrTuneBondHeadParaB1W.dVelLoopKP < stCurrTuneParaLowBound.stMtnPara.dVelLoopKP) { stCurrTuneBondHeadParaB1W.dVelLoopKP = stCurrTuneParaLowBound.stMtnPara.dVelLoopKP; } if(fabs(stCurrTuneParaUppBound.stMtnPara.dVelLoopKP - stCurrTuneParaLowBound.stMtnPara.dVelLoopKP) <= 1.5) { stCurrTuneBondHeadParaB1W.dVelLoopKP = (stCurrTuneParaUppBound.stMtnPara.dVelLoopKP + stCurrTuneParaLowBound.stMtnPara.dVelLoopKP)/2.0; nActualPointsTuneVKP = 1; } // JerkFF if(stCurrTuneBondHeadParaB1W.dJerkFf > stCurrTuneParaUppBound.stMtnPara.dJerkFf) { stCurrTuneBondHeadParaB1W.dJerkFf = stCurrTuneParaUppBound.stMtnPara.dJerkFf; } if(stCurrTuneBondHeadParaB1W.dJerkFf < stCurrTuneParaLowBound.stMtnPara.dJerkFf) { stCurrTuneBondHeadParaB1W.dJerkFf = stCurrTuneParaLowBound.stMtnPara.dJerkFf; } if(fabs(stCurrTuneParaUppBound.stMtnPara.dJerkFf - stCurrTuneParaLowBound.stMtnPara.dJerkFf) <= 1.5 || iObjSectionFlagB1W != WB_BH_SRCH_HT) { stCurrTuneBondHeadParaB1W.dJerkFf = (stCurrTuneParaUppBound.stMtnPara.dJerkFf + stCurrTuneParaLowBound.stMtnPara.dJerkFf)/2.0; nActualPointsTuneJerkFF = 0; } // 20110529 while( (nActualPointsTuneAccFF >= 1 || nActualPointsTunePKP >= 1 || nActualPointsTuneVKI >= 1 || nActualPointsTuneVKP >= 1 || nActualPointsTuneJerkFF >= 1) // 20110529 && (idxCurrCase1By1 < nTotalCases1By1) && (iCurrLoop < stpTuningAlgoSetting->uiMaxGeneration) ) { //// VKI for(jj = 0; jj<nActualPointsTuneVKI; jj++) { stCurrTuneBondHeadParaB1W.dVelLoopKI= adParaVelKI[jj]; if(mtn_b1w_write_para_bh_servo_readve(stCommHandle, &stCurrTuneBondHeadParaB1W, iObjSectionFlagB1W) != MTN_API_OK_ZERO) { sRet = MTN_API_ERROR_DOWNLOAD_DATA; goto label_mtn_wb_tune_bond_1_wire_bh; } // Execute B1W for(cc = 0, cTempObjCaseInB1W=0; cc<MAX_CASE_B1W_EACH_PARA; cc++) { if(mtnapi_wait_axis_settling(stCommHandle, iAxisTuningACS, POSN_SETTLE_TH_DURING_TUNING) != MTN_API_OK_ZERO) { sRet = MTN_API_ERROR_ACS_ERROR_SETTLING;// goto label_mtn_wb_tune_bond_1_wire_bh; } if(acs_bufprog_start_buff_b1w_(&astWbEmuB1WPerformance[cc]) != MTN_API_OK_ZERO) { sRet = MTN_API_ERROR_UPLOAD_DATA;// goto label_mtn_wb_tune_bond_1_wire_bh; } cTempObjCaseInB1W = cTempObjCaseInB1W + mtn_tune_calc_b1w_bh_performance(&astWbEmuB1WPerformance[cc], stpTuningTheme, iObjSectionFlagB1W); } astMotionTuneHistory[idxCurrCase1By1].dTuningObj = cTempObjCaseInB1W/MAX_CASE_B1W_EACH_PARA; astMotionTuneHistory[idxCurrCase1By1].stTuneBondHeadPerformanceB1W = astWbEmuB1WPerformance[0].stBondHeadPerformance; astMotionTuneHistory[idxCurrCase1By1].stServoPara.stMtnPara = stCurrTuneBondHeadParaB1W; if(idxCurrCase1By1 ==0) { dBestTuneObj1By1 = astMotionTuneHistory[idxCurrCase1By1].dTuningObj; idxBestParaSet = idxCurrCase1By1; astWbOneWirePerformance[0].stBondHeadPerformance = astMotionTuneHistory[idxBestParaSet].stTuneBondHeadPerformanceB1W; // 20110523 } else { if(dBestTuneObj1By1 > astMotionTuneHistory[idxCurrCase1By1].dTuningObj) { dBestTuneObj1By1 = astMotionTuneHistory[idxCurrCase1By1].dTuningObj; idxBestParaSet = idxCurrCase1By1; } } idxCurrCase1By1++; if(idxCurrCase1By1 >= nTotalCases1By1 || cFlagStopTuneB1W == TRUE || qc_is_axis_not_safe(stCommHandle, iAxisTuningACS)) { goto label_mtn_wb_tune_bond_1_wire_bh; } } stCurrTuneBondHeadParaB1W.dVelLoopKI = astMotionTuneHistory[idxBestParaSet].stServoPara.stMtnPara.dVelLoopKI; if(stCurrTuneParaLowBound.stMtnPara.dVelLoopKI < (stCurrTuneBondHeadParaB1W.dVelLoopKI - RESCALE_FACTOR_PREV_STEP_SIZE * dStepVelKI)) { stCurrTuneParaLowBound.stMtnPara.dVelLoopKI = stCurrTuneBondHeadParaB1W.dVelLoopKI - RESCALE_FACTOR_PREV_STEP_SIZE * dStepVelKI; } if(stCurrTuneParaLowBound.stMtnPara.dVelLoopKI <= 0) { stCurrTuneParaLowBound.stMtnPara.dVelLoopKI = stpTuningParameterLowBound->stMtnPara.dVelLoopKI; } if(stCurrTuneParaUppBound.stMtnPara.dVelLoopKI > (stCurrTuneBondHeadParaB1W.dVelLoopKI + RESCALE_FACTOR_PREV_STEP_SIZE * dStepVelKI)) { stCurrTuneParaUppBound.stMtnPara.dVelLoopKI = (stCurrTuneBondHeadParaB1W.dVelLoopKI + RESCALE_FACTOR_PREV_STEP_SIZE * dStepVelKI); } dStepVelKI = (stCurrTuneParaUppBound.stMtnPara.dVelLoopKI - stCurrTuneParaLowBound.stMtnPara.dVelLoopKI)/(uiTotalNumPointsOneDim - 1); if(fabs(dStepVelKI) > 10) { nActualPointsTuneVKI = uiTotalNumPointsOneDim; for(ii =0; ii<uiTotalNumPointsOneDim; ii++) { adParaVelKI[ii] = stCurrTuneParaLowBound.stMtnPara.dVelLoopKI + dStepVelKI * ii; } } else { nActualPointsTuneVKI = 0; } astWbOneWirePerformance[0].stBondHeadPerformance = astMotionTuneHistory[idxBestParaSet].stTuneBondHeadPerformanceB1W; /// 20110523 if(iObjSectionFlagB1W != WB_BH_2ND_CONTACT && iObjSectionFlagB1W != WB_BH_1ST_CONTACT && iObjSectionFlagB1W != WB_BH_IDLE) //// Skip tunning parameter for 1st and 2nd contact, 20101002 { // AccFFC for(kk = 0; kk<nActualPointsTuneAccFF; kk++) { stCurrTuneBondHeadParaB1W.dAccFFC = adParaAccFFC[kk]; if(mtn_b1w_write_para_bh_servo_readve(stCommHandle, &stCurrTuneBondHeadParaB1W, iObjSectionFlagB1W) != MTN_API_OK_ZERO) { sRet = MTN_API_ERROR_DOWNLOAD_DATA; goto label_mtn_wb_tune_bond_1_wire_bh; } // Execute B1W for(cc = 0, cTempObjCaseInB1W=0; cc<MAX_CASE_B1W_EACH_PARA; cc++) { if(mtnapi_wait_axis_settling(stCommHandle, iAxisTuningACS, POSN_SETTLE_TH_DURING_TUNING) != MTN_API_OK_ZERO) { sRet = MTN_API_ERROR_ACS_ERROR_SETTLING;// goto label_mtn_wb_tune_bond_1_wire_bh; } if(acs_bufprog_start_buff_b1w_(&astWbEmuB1WPerformance[cc]) != MTN_API_OK_ZERO) { sRet = MTN_API_ERROR_UPLOAD_DATA;// goto label_mtn_wb_tune_bond_1_wire_bh; } cTempObjCaseInB1W = cTempObjCaseInB1W + mtn_tune_calc_b1w_bh_performance(&astWbEmuB1WPerformance[cc], stpTuningTheme, iObjSectionFlagB1W); } astMotionTuneHistory[idxCurrCase1By1].dTuningObj = cTempObjCaseInB1W/MAX_CASE_B1W_EACH_PARA; astMotionTuneHistory[idxCurrCase1By1].stTuneBondHeadPerformanceB1W = astWbEmuB1WPerformance[0].stBondHeadPerformance; astMotionTuneHistory[idxCurrCase1By1].stServoPara.stMtnPara = stCurrTuneBondHeadParaB1W; if(dBestTuneObj1By1 > astMotionTuneHistory[idxCurrCase1By1].dTuningObj) { dBestTuneObj1By1 = astMotionTuneHistory[idxCurrCase1By1].dTuningObj; idxBestParaSet = idxCurrCase1By1; } idxCurrCase1By1++; if(idxCurrCase1By1 >= nTotalCases1By1 || cFlagStopTuneB1W == TRUE || qc_is_axis_not_safe(stCommHandle, iAxisTuningACS)) { goto label_mtn_wb_tune_bond_1_wire_bh; } } stCurrTuneBondHeadParaB1W.dAccFFC = astMotionTuneHistory[idxBestParaSet].stServoPara.stMtnPara.dAccFFC; if(stCurrTuneParaLowBound.stMtnPara.dAccFFC < (stCurrTuneBondHeadParaB1W.dAccFFC - RESCALE_FACTOR_PREV_STEP_SIZE * dStepAccFFC)) { stCurrTuneParaLowBound.stMtnPara.dAccFFC = stCurrTuneBondHeadParaB1W.dAccFFC - RESCALE_FACTOR_PREV_STEP_SIZE * dStepAccFFC; } if(stCurrTuneParaLowBound.stMtnPara.dAccFFC <= 0) { stCurrTuneParaLowBound.stMtnPara.dAccFFC = stpTuningParameterLowBound->stMtnPara.dAccFFC; } if(stCurrTuneParaUppBound.stMtnPara.dAccFFC > (stCurrTuneBondHeadParaB1W.dAccFFC + RESCALE_FACTOR_PREV_STEP_SIZE * dStepAccFFC)) { stCurrTuneParaUppBound.stMtnPara.dAccFFC = (stCurrTuneBondHeadParaB1W.dAccFFC + RESCALE_FACTOR_PREV_STEP_SIZE * dStepAccFFC); } dStepAccFFC = (stCurrTuneParaUppBound.stMtnPara.dAccFFC - stCurrTuneParaLowBound.stMtnPara.dAccFFC)/(uiTotalNumPointsOneDim - 1); if(fabs(dStepAccFFC) > 2) { nActualPointsTuneAccFF = uiTotalNumPointsOneDim; for(ii =0; ii<uiTotalNumPointsOneDim; ii++) { adParaAccFFC[ii] = stCurrTuneParaLowBound.stMtnPara.dAccFFC + dStepAccFFC * ii; } } else { nActualPointsTuneAccFF = 0; } ////// JerkFF, 20110529 if(iObjSectionFlagB1W == WB_BH_SRCH_HT) { for(kk = 0; kk<nActualPointsTuneJerkFF; kk++) { stCurrTuneBondHeadParaB1W.dJerkFf = adParaJerkFFC[kk]; if(mtn_b1w_write_para_bh_servo_readve(stCommHandle, &stCurrTuneBondHeadParaB1W, iObjSectionFlagB1W) != MTN_API_OK_ZERO) { sRet = MTN_API_ERROR_DOWNLOAD_DATA; goto label_mtn_wb_tune_bond_1_wire_bh; } // Execute B1W for(cc = 0, cTempObjCaseInB1W=0; cc<MAX_CASE_B1W_EACH_PARA; cc++) { if(mtnapi_wait_axis_settling(stCommHandle, iAxisTuningACS, POSN_SETTLE_TH_DURING_TUNING) != MTN_API_OK_ZERO) { sRet = MTN_API_ERROR_ACS_ERROR_SETTLING;// goto label_mtn_wb_tune_bond_1_wire_bh; } if(acs_bufprog_start_buff_b1w_(&astWbEmuB1WPerformance[cc]) != MTN_API_OK_ZERO) { sRet = MTN_API_ERROR_UPLOAD_DATA;// goto label_mtn_wb_tune_bond_1_wire_bh; } cTempObjCaseInB1W = cTempObjCaseInB1W + mtn_tune_calc_b1w_bh_performance(&astWbEmuB1WPerformance[cc], stpTuningTheme, iObjSectionFlagB1W); } astMotionTuneHistory[idxCurrCase1By1].dTuningObj = cTempObjCaseInB1W/MAX_CASE_B1W_EACH_PARA; astMotionTuneHistory[idxCurrCase1By1].stTuneBondHeadPerformanceB1W = astWbEmuB1WPerformance[0].stBondHeadPerformance; astMotionTuneHistory[idxCurrCase1By1].stServoPara.stMtnPara = stCurrTuneBondHeadParaB1W; if(dBestTuneObj1By1 > astMotionTuneHistory[idxCurrCase1By1].dTuningObj) { dBestTuneObj1By1 = astMotionTuneHistory[idxCurrCase1By1].dTuningObj; idxBestParaSet = idxCurrCase1By1; } idxCurrCase1By1++; if(idxCurrCase1By1 >= nTotalCases1By1 || cFlagStopTuneB1W == TRUE || qc_is_axis_not_safe(stCommHandle, iAxisTuningACS)) { goto label_mtn_wb_tune_bond_1_wire_bh; } } stCurrTuneBondHeadParaB1W.dJerkFf = astMotionTuneHistory[idxBestParaSet].stServoPara.stMtnPara.dJerkFf; if(stCurrTuneParaLowBound.stMtnPara.dJerkFf < (stCurrTuneBondHeadParaB1W.dJerkFf - RESCALE_FACTOR_PREV_STEP_SIZE * dStepJerkFFC)) { stCurrTuneParaLowBound.stMtnPara.dJerkFf = stCurrTuneBondHeadParaB1W.dJerkFf - RESCALE_FACTOR_PREV_STEP_SIZE * dStepJerkFFC; } if(stCurrTuneParaLowBound.stMtnPara.dJerkFf <= 0) { stCurrTuneParaLowBound.stMtnPara.dJerkFf = stpTuningParameterLowBound->stMtnPara.dJerkFf; } if(stCurrTuneParaUppBound.stMtnPara.dJerkFf > (stCurrTuneBondHeadParaB1W.dJerkFf + RESCALE_FACTOR_PREV_STEP_SIZE * dStepJerkFFC)) { stCurrTuneParaUppBound.stMtnPara.dJerkFf = (stCurrTuneBondHeadParaB1W.dJerkFf + RESCALE_FACTOR_PREV_STEP_SIZE * dStepJerkFFC); } dStepJerkFFC = (stCurrTuneParaUppBound.stMtnPara.dJerkFf - stCurrTuneParaLowBound.stMtnPara.dJerkFf)/(uiTotalNumPointsOneDim - 1); if(fabs(dStepJerkFFC) > 10) { nActualPointsTuneJerkFF = uiTotalNumPointsOneDim; for(ii =0; ii<uiTotalNumPointsOneDim; ii++) { adParaJerkFFC[ii] = stCurrTuneParaLowBound.stMtnPara.dJerkFf + dStepJerkFFC * ii; } } else { nActualPointsTuneJerkFF = 0; } } } astWbOneWirePerformance[0].stBondHeadPerformance = astMotionTuneHistory[idxBestParaSet].stTuneBondHeadPerformanceB1W; /// 20110523 // PosnKP for(ll = 0; ll<nActualPointsTunePKP; ll++) { stCurrTuneBondHeadParaB1W.dPosnLoopKP = adParaPosnKP[ll]; if(stCurrTuneBondHeadParaB1W.dPosnLoopKP < stpTuningParameterLowBound->stMtnPara.dPosnLoopKP) { stCurrTuneBondHeadParaB1W.dPosnLoopKP = stpTuningParameterLowBound->stMtnPara.dPosnLoopKP; } if(mtn_b1w_write_para_bh_servo_readve(stCommHandle, &stCurrTuneBondHeadParaB1W, iObjSectionFlagB1W) != MTN_API_OK_ZERO) { CString cstrTemp; cstrTemp.Format(_T("Error Parameter: %4f, %4f, %4f, %4f, %4f, %4f, %4f, %4f, %4f"), adParaPosnKP[0], adParaPosnKP[1], adParaPosnKP[2], adParaPosnKP[3], adParaPosnKP[4], adParaPosnKP[5], adParaPosnKP[6], adParaPosnKP[7], adParaPosnKP[8]); AfxMessageBox(cstrTemp); sRet = MTN_API_ERROR_DOWNLOAD_DATA; goto label_mtn_wb_tune_bond_1_wire_bh; } // Execute B1W for(cc = 0, cTempObjCaseInB1W=0; cc<MAX_CASE_B1W_EACH_PARA; cc++) { if(mtnapi_wait_axis_settling(stCommHandle, iAxisTuningACS, POSN_SETTLE_TH_DURING_TUNING) != MTN_API_OK_ZERO) { sRet = MTN_API_ERROR_ACS_ERROR_SETTLING;// goto label_mtn_wb_tune_bond_1_wire_bh; } if(acs_bufprog_start_buff_b1w_(&astWbEmuB1WPerformance[cc]) != MTN_API_OK_ZERO) { sRet = MTN_API_ERROR_UPLOAD_DATA;// goto label_mtn_wb_tune_bond_1_wire_bh; } cTempObjCaseInB1W = cTempObjCaseInB1W + mtn_tune_calc_b1w_bh_performance(&astWbEmuB1WPerformance[cc], stpTuningTheme, iObjSectionFlagB1W); } astMotionTuneHistory[idxCurrCase1By1].dTuningObj = cTempObjCaseInB1W/MAX_CASE_B1W_EACH_PARA; astMotionTuneHistory[idxCurrCase1By1].stTuneBondHeadPerformanceB1W = astWbEmuB1WPerformance[0].stBondHeadPerformance; astMotionTuneHistory[idxCurrCase1By1].stServoPara.stMtnPara = stCurrTuneBondHeadParaB1W; if(dBestTuneObj1By1 > astMotionTuneHistory[idxCurrCase1By1].dTuningObj) { dBestTuneObj1By1 = astMotionTuneHistory[idxCurrCase1By1].dTuningObj; idxBestParaSet = idxCurrCase1By1; } idxCurrCase1By1++; if(idxCurrCase1By1 >= nTotalCases1By1 || cFlagStopTuneB1W == TRUE || qc_is_axis_not_safe(stCommHandle, iAxisTuningACS)) { goto label_mtn_wb_tune_bond_1_wire_bh; } } stCurrTuneBondHeadParaB1W.dPosnLoopKP = astMotionTuneHistory[idxBestParaSet].stServoPara.stMtnPara.dPosnLoopKP; if(stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP < (stCurrTuneBondHeadParaB1W.dPosnLoopKP - RESCALE_FACTOR_PREV_STEP_SIZE * dStepPosnKP)) { stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP = stCurrTuneBondHeadParaB1W.dPosnLoopKP - RESCALE_FACTOR_PREV_STEP_SIZE * dStepPosnKP; } if(stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP <= 0) { stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP = stpTuningParameterLowBound->stMtnPara.dPosnLoopKP; } if(stCurrTuneParaUppBound.stMtnPara.dPosnLoopKP > (stCurrTuneBondHeadParaB1W.dPosnLoopKP + RESCALE_FACTOR_PREV_STEP_SIZE * dStepPosnKP)) { stCurrTuneParaUppBound.stMtnPara.dPosnLoopKP = (stCurrTuneBondHeadParaB1W.dPosnLoopKP + RESCALE_FACTOR_PREV_STEP_SIZE * dStepPosnKP); } dStepPosnKP = (stCurrTuneParaUppBound.stMtnPara.dPosnLoopKP - stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP)/(uiTotalNumPointsOneDim - 1); if(dStepPosnKP > 10) { nActualPointsTunePKP = uiTotalNumPointsOneDim; for(ii =0; ii<uiTotalNumPointsOneDim; ii++) { adParaPosnKP[ii] = stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP + dStepPosnKP * ii; } } else { nActualPointsTunePKP = 0; } astWbOneWirePerformance[0].stBondHeadPerformance = astMotionTuneHistory[idxBestParaSet].stTuneBondHeadPerformanceB1W; /// 20110523 // End one loop iCurrLoop ++; } label_mtn_wb_tune_bond_1_wire_bh: stpMtnTuneOutput->dTuningObj = dBestTuneObj1By1; stpMtnTuneOutput->stResultResponse = astMotionTuneHistory[idxBestParaSet].stServoTuneIndex; // Tuning pass (iFlagTuningIsFail = FALSE ) iff the obj is better than initial value <=> (dTuningObj < dInitialObj) if(stpMtnTuneOutput->dTuningObj < stpMtnTuneOutput->dInitialObj) { stpMtnTuneOutput->iFlagTuningIsFail = FALSE; // Failure is FALSE, meaning PASS, download the best parameter set mtn_b1w_write_para_bh_servo_readve(stCommHandle, &stpMtnTuneOutput->stBestParameterSet, iObjSectionFlagB1W); // stCurrTuneBondHeadParaB1W stpMtnTuneOutput->stBestParameterSet = astMotionTuneHistory[idxBestParaSet].stServoPara.stMtnPara; // Only update when TuneOut better than init mtn_tune_round_parameter_to_nearest_1(&astMotionTuneHistory[idxBestParaSet].stServoPara.stMtnPara, &stpMtnTuneOutput->stBestParameterSet); // APP_Z_BOND_ACS_I // // Parameter rounding } else { stpMtnTuneOutput->iFlagTuningIsFail = TRUE; } // Restore the safety parameters mtnapi_download_safety_parameter_acs_per_axis(stCommHandle, iAxisTuningACS, &stSafetyParaBak); mtnapi_download_safety_parameter_acs_per_axis(stCommHandle, sys_get_acs_axis_id_wire_clamp(), &stSafetyParaBakWCL); if(stpMtnTuneInput->iDebugFlag == TRUE) { mtn_tune_save_tuning_history(stpMtnTuneInput, stpMtnTuneOutput, idxCurrCase1By1); } return sRet; } #include "ForceCali.h" #define FILE_NAME_SEARCH_CONTACT_INIT_B1W "SrchContact_InitB1W.m" #define FILE_NAME_SEARCH_CONTACT_FINAL "SrchContact_FinalB1W.m" void mtn_wb_b1w_tune_check_upp_low_bound( MTN_TUNE_PARAMETER_SET *stpTuningPara, MTN_TUNE_PARA_UNION *stpTuneParaUppBound, MTN_TUNE_PARA_UNION *stpTuneParaLowBound) { ///////////// Check upper and lower boundary // 20110529 // AccFF if(stpTuningPara->dAccFFC > stpTuneParaUppBound->stMtnPara.dAccFFC) { stpTuningPara->dAccFFC = stpTuneParaUppBound->stMtnPara.dAccFFC; } if(stpTuningPara->dAccFFC < stpTuneParaLowBound->stMtnPara.dAccFFC) { stpTuningPara->dAccFFC = stpTuneParaLowBound->stMtnPara.dAccFFC; } // PosnLoopKP if(stpTuningPara->dPosnLoopKP > stpTuneParaUppBound->stMtnPara.dPosnLoopKP) { stpTuningPara->dPosnLoopKP = stpTuneParaUppBound->stMtnPara.dPosnLoopKP; } if(stpTuningPara->dPosnLoopKP < stpTuneParaLowBound->stMtnPara.dPosnLoopKP) { stpTuningPara->dPosnLoopKP = stpTuneParaLowBound->stMtnPara.dPosnLoopKP; } // dVelLoopKI if(stpTuningPara->dVelLoopKI > stpTuneParaUppBound->stMtnPara.dVelLoopKI) { stpTuningPara->dVelLoopKI = stpTuneParaUppBound->stMtnPara.dVelLoopKI; } if(stpTuningPara->dVelLoopKI < stpTuneParaLowBound->stMtnPara.dVelLoopKI) { stpTuningPara->dVelLoopKI = stpTuneParaLowBound->stMtnPara.dVelLoopKI; } // dVelLoopKP if(stpTuningPara->dVelLoopKP > stpTuneParaUppBound->stMtnPara.dVelLoopKP) { stpTuningPara->dVelLoopKP = stpTuneParaUppBound->stMtnPara.dVelLoopKP; } if(stpTuningPara->dVelLoopKP < stpTuneParaLowBound->stMtnPara.dVelLoopKP) { stpTuningPara->dVelLoopKP = stpTuneParaLowBound->stMtnPara.dVelLoopKP; } // JerkFF if(stpTuningPara->dJerkFf > stpTuneParaUppBound->stMtnPara.dJerkFf) { stpTuningPara->dJerkFf = stpTuneParaUppBound->stMtnPara.dJerkFf; } if(stpTuningPara->dJerkFf < stpTuneParaLowBound->stMtnPara.dJerkFf) { stpTuningPara->dJerkFf = stpTuneParaLowBound->stMtnPara.dJerkFf; } } int mtn_wb_tune_bh_b1w_stop_srch(MTN_TUNE_GENETIC_INPUT *stpMtnTuneInput, MTN_TUNE_GENETIC_OUTPUT *stpMtnTuneOutput, int iObjSectionFlagB1W) { //int nTotalNumWire; HANDLE stCommHandle = stpMtnTuneInput->stCommHandle; MTN_TUNE_THEME *stpTuningTheme = &stpMtnTuneInput->stTuningTheme; TUNE_ALGO_SETTING *stpTuningAlgoSetting = &stpMtnTuneInput->stTuningAlgoSetting; MTN_TUNE_PARA_UNION *stpTuningParameterIni = &stpMtnTuneInput->stTuningParameterIni; MTN_TUNE_PARA_UNION *stpTuningParameterUppBound = &stpMtnTuneInput->stTuningParameterUppBound; MTN_TUNE_PARA_UNION *stpTuningParameterLowBound = &stpMtnTuneInput->stTuningParameterLowBound; MTN_TUNE_CONDITION *stpTuningCondition = &stpMtnTuneInput->stTuningCondition; MTN_TUNE_ENC_TIME_CFG *stpTuningEncTimeConfig = &stpMtnTuneInput->stTuningEncTimeConfig; MTN_TUNE_SPECIFICATION *stpTuningPassSpecfication = &stpMtnTuneInput->stTuningPassSpecfication; int iAxisTuningACS = stpMtnTuneInput->iAxisTuning; double adParaPosnKP[2 * NUM_POINTS_ONE_DIM_MESH], dStepPosnKP; double adParaVelKP[2 * NUM_POINTS_ONE_DIM_MESH], dStepVelKP; double adParaVelKI[2 * NUM_POINTS_ONE_DIM_MESH], dStepVelKI; double adParaAccFFC[2 * NUM_POINTS_ONE_DIM_MESH], dStepAccFFC; double adParaJerkFFC[2 * NUM_POINTS_ONE_DIM_MESH], dStepJerkFFC; // 20110529 int ii, jj, kk, ll, nActualPointsTunePKP, nActualPointsTuneVKP, nActualPointsTuneAccFF, nActualPointsTuneVKI, nActualPointsTuneJerkFF, cc; // mm, double cTempObjCaseInB1W; short sRet = MTN_API_OK_ZERO; // Backup and relax the safety parameters SAFETY_PARA_ACS stSafetyParaBak, stSafetyParaCurr; mtnapi_upload_safety_parameter_acs_per_axis(stCommHandle, iAxisTuningACS, &stSafetyParaBak); stSafetyParaCurr = stSafetyParaBak; stSafetyParaCurr.dCriticalPosnErrAcc *= 32; stSafetyParaCurr.dCriticalPosnErrIdle *= 8; stSafetyParaCurr.dCriticalPosnErrVel *= 16; stSafetyParaCurr.dRMS_DrvCmdX = stSafetyParaCurr.dRMS_DrvCmdX * 2; stSafetyParaCurr.dRMS_DrvCmdIdle = stSafetyParaCurr.dRMS_DrvCmdIdle * 2; stSafetyParaCurr.dRMS_DrvCmdMtn = 100; // 20120717, must release to 100% for motion tuning mtnapi_download_safety_parameter_acs_per_axis(stCommHandle, iAxisTuningACS, &stSafetyParaCurr); mtn_wb_tune_b1w_stop_srch_init_cfg(stCommHandle); mtn_wb_tune_b1w_stop_srch_download_cfg(); //int iFlagDoingTest; //Clear the tuning history buffer idxCurrCase1By1 = idxBestParaSet = 0; memset(astMotionTuneHistory, 0, sizeof(MTN_TUNE_CASE) * MAX_CASE_TUNING_HISTORY_BUFFER); // Init Parameter MTN_TUNE_PARAMETER_SET stCurrTuneBondHeadParaB1W = stpTuningParameterIni->stMtnPara; // Start EmuB1W if(mtn_b1w_write_para_bh_servo_readve(stCommHandle, &stCurrTuneBondHeadParaB1W, iObjSectionFlagB1W) != MTN_API_OK_ZERO) { sRet = MTN_API_ERROR_DOWNLOAD_DATA; goto label_mtn_wb_tune_bh_b1w_stop_srch; } int uiTotalNumPointsOneDim = NUM_POINTS_ONE_DIM_MESH; if(iObjSectionFlagB1W == WB_BH_1ST_CONTACT || iObjSectionFlagB1W == WB_BH_2ND_CONTACT) { uiTotalNumPointsOneDim = 2 * NUM_POINTS_ONE_DIM_MESH; } WB_TUNE_B1W_BH_OBJ stWbTuneB1wObj; // TEACH_CONTACT_INPUT stTeachContactParameter; acsc_upload_search_contact_parameter(stCommHandle, &stTeachContactParameter); for(cc = 0, cTempObjCaseInB1W=0; cc<MAX_CASE_B1W_EACH_PARA; cc++) { //if(mtnapi_wait_axis_settling(stCommHandle, iAxisTuningACS, POSN_SETTLE_TH_DURING_TUNING) != MTN_API_OK_ZERO) //{ // sRet = MTN_API_ERROR_ACS_ERROR_SETTLING;// // goto label_mtn_wb_tune_bh_b1w_stop_srch; //} mtn_wb_tune_b1w_stop_srch_trig_once(stCommHandle); while(qc_is_axis_still_acc_dec(stCommHandle, iAxisTuningACS)) { Sleep(10); //Sleep(2); } mtn_wb_tune_b1w_stop_srch_calc_bh_obj(&gstSystemScope, &gdScopeCollectData[0], &stWbTuneB1wObj); cTempObjCaseInB1W = cTempObjCaseInB1W + stWbTuneB1wObj.dObj[iObjSectionFlagB1W]; //mtn_tune_calc_b1w_bh_performance(&astWbEmuB1WPerformance[cc], stpTuningTheme, iObjSectionFlagB1W); } astMotionTuneHistory[idxCurrCase1By1].dTuningObj = cTempObjCaseInB1W/MAX_CASE_B1W_EACH_PARA; gstSystemScope.uiNumData = 7; gstSystemScope.uiDataLen = 3000; gstSystemScope.dSamplePeriod_ms = 1; mtn_tune_contact_save_data(stCommHandle, &gstSystemScope, stTeachContactParameter.iAxis, FILE_NAME_SEARCH_CONTACT_INIT_B1W, "%% ACSC Controller, Axis- %d: RPOS(AXIS), PE(AXIS), RVEL(AXIS), FVEL(AXIS), DCOM(AXIS), DOUT(AXIS), SLAFF(AXIS) \n"); stpMtnTuneOutput->dInitialObj = astMotionTuneHistory[idxCurrCase1By1].dTuningObj; // mtn_tune_calc_b1w_bh_performance(&astWbEmuB1WPerformance[0], stpTuningTheme, iObjSectionFlagB1W); stpMtnTuneOutput->stInitialB1WPerformanceBH = astWbEmuB1WPerformance[0].stBondHeadPerformance; dBestTuneObj1By1 = stpMtnTuneOutput->dInitialObj; // astMotionTuneHistory[idxCurrCase1By1].dTuningObj = mtn_tune_calc_b1w_bh_performance(&astWbEmuB1WPerformance[0], stpTuningTheme, iObjSectionFlagB1W); astMotionTuneHistory[idxCurrCase1By1].stTuneBondHeadPerformanceB1W = astWbEmuB1WPerformance[0].stBondHeadPerformance; astMotionTuneHistory[idxCurrCase1By1].stServoPara.stMtnPara = stCurrTuneBondHeadParaB1W; // Init Parameter and step size MTN_TUNE_PARA_UNION stCurrTuneParaUppBound, stCurrTuneParaLowBound; stCurrTuneParaUppBound.stMtnPara = stpTuningParameterUppBound->stMtnPara; stCurrTuneParaLowBound.stMtnPara = stpTuningParameterLowBound->stMtnPara; dStepPosnKP = (stCurrTuneParaUppBound.stMtnPara.dPosnLoopKP - stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP)/(uiTotalNumPointsOneDim - 1); dStepVelKP = (stCurrTuneParaUppBound.stMtnPara.dVelLoopKP - stCurrTuneParaLowBound.stMtnPara.dVelLoopKP)/(uiTotalNumPointsOneDim - 1); dStepVelKI = (stCurrTuneParaUppBound.stMtnPara.dVelLoopKI - stCurrTuneParaLowBound.stMtnPara.dVelLoopKI)/(uiTotalNumPointsOneDim - 1); dStepAccFFC = (stCurrTuneParaUppBound.stMtnPara.dAccFFC - stCurrTuneParaLowBound.stMtnPara.dAccFFC)/(uiTotalNumPointsOneDim - 1); dStepJerkFFC = (stCurrTuneParaUppBound.stMtnPara.dJerkFf - stCurrTuneParaLowBound.stMtnPara.dJerkFf)/(uiTotalNumPointsOneDim - 1); for(ii =0; ii<uiTotalNumPointsOneDim; ii++) { adParaPosnKP[ii] = stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP + dStepPosnKP * ii; adParaVelKP[ii] = stCurrTuneParaLowBound.stMtnPara.dVelLoopKP + dStepVelKP * ii; adParaVelKI[ii] = stCurrTuneParaLowBound.stMtnPara.dVelLoopKI + dStepVelKI * ii; adParaAccFFC[ii] = stCurrTuneParaLowBound.stMtnPara.dAccFFC + dStepAccFFC * ii; adParaJerkFFC[ii] = stCurrTuneParaLowBound.stMtnPara.dJerkFf + dStepJerkFFC * ii; // 20110529 } nTotalCases1By1 = stpTuningAlgoSetting->uiMaxGeneration * 5 * uiTotalNumPointsOneDim; //10000; // NUM_POINTS_ONE_DIM_MESH * NUM_POINTS_ONE_DIM_MESH * NUM_POINTS_ONE_DIM_MESH * NUM_POINTS_ONE_DIM_MESH; if(nTotalCases1By1 > MAX_CASE_TUNING_HISTORY_BUFFER) { nTotalCases1By1 = MAX_CASE_TUNING_HISTORY_BUFFER; } unsigned int iCurrLoop =0; nActualPointsTunePKP = nActualPointsTuneVKP = nActualPointsTuneAccFF = nActualPointsTuneJerkFF = nActualPointsTuneVKI = uiTotalNumPointsOneDim; // Check with upper and lower bound mtn_wb_b1w_tune_check_upp_low_bound( &stCurrTuneBondHeadParaB1W, &stCurrTuneParaUppBound, &stCurrTuneParaLowBound); // Check tuning iterations if(fabs(stCurrTuneParaUppBound.stMtnPara.dAccFFC - stCurrTuneParaLowBound.stMtnPara.dAccFFC) <= 1.5) { stCurrTuneBondHeadParaB1W.dAccFFC = (stCurrTuneParaUppBound.stMtnPara.dAccFFC + stCurrTuneParaLowBound.stMtnPara.dAccFFC)/2.0; nActualPointsTuneAccFF = 0; } if(fabs(stCurrTuneParaUppBound.stMtnPara.dPosnLoopKP - stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP) <= 1.5) { stCurrTuneBondHeadParaB1W.dPosnLoopKP = (stCurrTuneParaUppBound.stMtnPara.dPosnLoopKP + stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP)/2.0; nActualPointsTunePKP = 0; } if(fabs(stCurrTuneParaUppBound.stMtnPara.dVelLoopKI - stCurrTuneParaLowBound.stMtnPara.dVelLoopKI) <= 1.5) { stCurrTuneBondHeadParaB1W.dVelLoopKI = (stCurrTuneParaUppBound.stMtnPara.dVelLoopKI + stCurrTuneParaLowBound.stMtnPara.dVelLoopKI)/2.0; nActualPointsTuneVKI = 0; } if(fabs(stCurrTuneParaUppBound.stMtnPara.dVelLoopKP - stCurrTuneParaLowBound.stMtnPara.dVelLoopKP) <= 1.5) { stCurrTuneBondHeadParaB1W.dVelLoopKP = (stCurrTuneParaUppBound.stMtnPara.dVelLoopKP + stCurrTuneParaLowBound.stMtnPara.dVelLoopKP)/2.0; nActualPointsTuneVKP = 1; } if(fabs(stCurrTuneParaUppBound.stMtnPara.dJerkFf - stCurrTuneParaLowBound.stMtnPara.dJerkFf) <= 1.5 || iObjSectionFlagB1W != WB_BH_SRCH_HT) { stCurrTuneBondHeadParaB1W.dJerkFf = (stCurrTuneParaUppBound.stMtnPara.dJerkFf + stCurrTuneParaLowBound.stMtnPara.dJerkFf)/2.0; nActualPointsTuneJerkFF = 0; } // 20110529 WB_TUNE_B1W_BH_PASS_FLAG stWbTuneB1wPassFlag; while( (nActualPointsTuneAccFF >= 1 || nActualPointsTunePKP >= 1 || nActualPointsTuneVKI >= 1 || nActualPointsTuneVKP >= 1 || nActualPointsTuneJerkFF >= 1) // 20110529 && (idxCurrCase1By1 < nTotalCases1By1) && (iCurrLoop < stpTuningAlgoSetting->uiMaxGeneration) ) { // VKP for(ii = 0; ii<nActualPointsTuneVKP; ii++) { stCurrTuneBondHeadParaB1W.dVelLoopKP = adParaVelKP[ii]; if(mtn_b1w_write_para_bh_servo_readve(stCommHandle, &stCurrTuneBondHeadParaB1W, iObjSectionFlagB1W) != MTN_API_OK_ZERO) { sRet = MTN_API_ERROR_DOWNLOAD_DATA; goto label_mtn_wb_tune_bh_b1w_stop_srch; } // Execute B1W, cTempObjCaseInB1W for(cc = 0, cTempObjCaseInB1W=0; cc<MAX_CASE_B1W_EACH_PARA; cc++) { //if(mtnapi_wait_axis_settling(stCommHandle, iAxisTuningACS, POSN_SETTLE_TH_DURING_TUNING) != MTN_API_OK_ZERO) //{ // sRet = MTN_API_ERROR_ACS_ERROR_SETTLING;// // goto label_mtn_wb_tune_bh_b1w_stop_srch; //} mtn_wb_tune_b1w_stop_srch_trig_once(stCommHandle); while(qc_is_axis_still_acc_dec(stCommHandle, iAxisTuningACS)) { Sleep(10); //Sleep(2); } mtn_wb_tune_b1w_stop_srch_calc_bh_obj(&gstSystemScope, &gdScopeCollectData[0], &stWbTuneB1wObj); cTempObjCaseInB1W = cTempObjCaseInB1W + stWbTuneB1wObj.dObj[iObjSectionFlagB1W]; //mtn_tune_calc_b1w_bh_performance(&astWbEmuB1WPerformance[cc], stpTuningTheme, iObjSectionFlagB1W); } astMotionTuneHistory[idxCurrCase1By1].dTuningObj = cTempObjCaseInB1W/MAX_CASE_B1W_EACH_PARA; astMotionTuneHistory[idxCurrCase1By1].stTuneBondHeadPerformanceB1W = astWbEmuB1WPerformance[0].stBondHeadPerformance; astMotionTuneHistory[idxCurrCase1By1].stServoPara.stMtnPara = stCurrTuneBondHeadParaB1W; astMotionTuneHistory[idxCurrCase1By1].stTuneB1wObjValues = stWbTuneB1wObj; if(mtn_wb_tune_b1w_check_is_feasible_parameter(&stWbTuneB1wObj.dObj[0], &stWbTuneB1wPassFlag) == TRUE) { mtn_wb_tune_b1w_record_feasible_parameter(&stWbTuneB1wObj, &astWbEmuB1WPerformance[0].stBondHeadPerformance, iObjSectionFlagB1W, &stCurrTuneBondHeadParaB1W); } if(idxCurrCase1By1 ==0) { dBestTuneObj1By1 = astMotionTuneHistory[idxCurrCase1By1].dTuningObj; idxBestParaSet = idxCurrCase1By1; astWbOneWirePerformance[0].stBondHeadPerformance = astMotionTuneHistory[idxBestParaSet].stTuneBondHeadPerformanceB1W; // 20110523 } else { if(dBestTuneObj1By1 > astMotionTuneHistory[idxCurrCase1By1].dTuningObj) { dBestTuneObj1By1 = astMotionTuneHistory[idxCurrCase1By1].dTuningObj; idxBestParaSet = idxCurrCase1By1; } } idxCurrCase1By1++; if(idxCurrCase1By1 >= nTotalCases1By1 || cFlagStopTuneB1W == TRUE || qc_is_axis_not_safe(stCommHandle, iAxisTuningACS)) { goto label_mtn_wb_tune_bh_b1w_stop_srch; } } stCurrTuneBondHeadParaB1W.dVelLoopKP = astMotionTuneHistory[idxBestParaSet].stServoPara.stMtnPara.dVelLoopKP; if(stCurrTuneParaLowBound.stMtnPara.dVelLoopKP < (stCurrTuneBondHeadParaB1W.dVelLoopKP - RESCALE_FACTOR_PREV_STEP_SIZE * dStepVelKP)) { stCurrTuneParaLowBound.stMtnPara.dVelLoopKP = stCurrTuneBondHeadParaB1W.dVelLoopKP - RESCALE_FACTOR_PREV_STEP_SIZE * dStepVelKP; } if(stCurrTuneParaLowBound.stMtnPara.dVelLoopKP <= 0) { stCurrTuneParaLowBound.stMtnPara.dVelLoopKP = stpTuningParameterLowBound->stMtnPara.dVelLoopKP; } if(stCurrTuneParaUppBound.stMtnPara.dVelLoopKP > (stCurrTuneBondHeadParaB1W.dVelLoopKP + RESCALE_FACTOR_PREV_STEP_SIZE * dStepVelKP)) { stCurrTuneParaUppBound.stMtnPara.dVelLoopKP = (stCurrTuneBondHeadParaB1W.dVelLoopKP + RESCALE_FACTOR_PREV_STEP_SIZE * dStepVelKP); } dStepVelKP = (stCurrTuneParaUppBound.stMtnPara.dVelLoopKP - stCurrTuneParaLowBound.stMtnPara.dVelLoopKP)/(uiTotalNumPointsOneDim - 1); if(fabs(dStepVelKP) > 0.5) // 20120727 { nActualPointsTuneVKP = uiTotalNumPointsOneDim; for(ii =0; ii<uiTotalNumPointsOneDim; ii++) { adParaVelKP[ii] = stCurrTuneParaLowBound.stMtnPara.dVelLoopKP + dStepVelKP * ii; } } else { nActualPointsTuneVKP = 0; } //// VKI for(jj = 0; jj<nActualPointsTuneVKI; jj++) { stCurrTuneBondHeadParaB1W.dVelLoopKI= adParaVelKI[jj]; if(mtn_b1w_write_para_bh_servo_readve(stCommHandle, &stCurrTuneBondHeadParaB1W, iObjSectionFlagB1W) != MTN_API_OK_ZERO) { sRet = MTN_API_ERROR_DOWNLOAD_DATA; goto label_mtn_wb_tune_bh_b1w_stop_srch; } // Execute B1W for(cc = 0, cTempObjCaseInB1W=0; cc<MAX_CASE_B1W_EACH_PARA; cc++) { //if(mtnapi_wait_axis_settling(stCommHandle, iAxisTuningACS, POSN_SETTLE_TH_DURING_TUNING) != MTN_API_OK_ZERO) //{ // sRet = MTN_API_ERROR_ACS_ERROR_SETTLING;// // goto label_mtn_wb_tune_bh_b1w_stop_srch; //} mtn_wb_tune_b1w_stop_srch_trig_once(stCommHandle); while(qc_is_axis_still_acc_dec(stCommHandle, iAxisTuningACS)) { Sleep(100); //Sleep(2); } mtn_wb_tune_b1w_stop_srch_calc_bh_obj(&gstSystemScope, &gdScopeCollectData[0], &stWbTuneB1wObj); cTempObjCaseInB1W = cTempObjCaseInB1W + stWbTuneB1wObj.dObj[iObjSectionFlagB1W]; //mtn_tune_calc_b1w_bh_performance(&astWbEmuB1WPerformance[cc], stpTuningTheme, iObjSectionFlagB1W); } astMotionTuneHistory[idxCurrCase1By1].dTuningObj = cTempObjCaseInB1W/MAX_CASE_B1W_EACH_PARA; astMotionTuneHistory[idxCurrCase1By1].stTuneBondHeadPerformanceB1W = astWbEmuB1WPerformance[0].stBondHeadPerformance; astMotionTuneHistory[idxCurrCase1By1].stServoPara.stMtnPara = stCurrTuneBondHeadParaB1W; astMotionTuneHistory[idxCurrCase1By1].stTuneB1wObjValues = stWbTuneB1wObj; if(dBestTuneObj1By1 > astMotionTuneHistory[idxCurrCase1By1].dTuningObj) { dBestTuneObj1By1 = astMotionTuneHistory[idxCurrCase1By1].dTuningObj; idxBestParaSet = idxCurrCase1By1; } idxCurrCase1By1++; if(mtn_wb_tune_b1w_check_is_feasible_parameter(&stWbTuneB1wObj.dObj[0], &stWbTuneB1wPassFlag) == TRUE) { mtn_wb_tune_b1w_record_feasible_parameter(&stWbTuneB1wObj, &astWbEmuB1WPerformance[0].stBondHeadPerformance, iObjSectionFlagB1W, &stCurrTuneBondHeadParaB1W); } if(idxCurrCase1By1 >= nTotalCases1By1 || cFlagStopTuneB1W == TRUE || qc_is_axis_not_safe(stCommHandle, iAxisTuningACS)) { goto label_mtn_wb_tune_bh_b1w_stop_srch; } } stCurrTuneBondHeadParaB1W.dVelLoopKI = astMotionTuneHistory[idxBestParaSet].stServoPara.stMtnPara.dVelLoopKI; if(stCurrTuneParaLowBound.stMtnPara.dVelLoopKI < (stCurrTuneBondHeadParaB1W.dVelLoopKI - RESCALE_FACTOR_PREV_STEP_SIZE * dStepVelKI)) { stCurrTuneParaLowBound.stMtnPara.dVelLoopKI = stCurrTuneBondHeadParaB1W.dVelLoopKI - RESCALE_FACTOR_PREV_STEP_SIZE * dStepVelKI; } if(stCurrTuneParaLowBound.stMtnPara.dVelLoopKI <= 0) { stCurrTuneParaLowBound.stMtnPara.dVelLoopKI = stpTuningParameterLowBound->stMtnPara.dVelLoopKI; } if(stCurrTuneParaUppBound.stMtnPara.dVelLoopKI > (stCurrTuneBondHeadParaB1W.dVelLoopKI + RESCALE_FACTOR_PREV_STEP_SIZE * dStepVelKI)) { stCurrTuneParaUppBound.stMtnPara.dVelLoopKI = (stCurrTuneBondHeadParaB1W.dVelLoopKI + RESCALE_FACTOR_PREV_STEP_SIZE * dStepVelKI); } dStepVelKI = (stCurrTuneParaUppBound.stMtnPara.dVelLoopKI - stCurrTuneParaLowBound.stMtnPara.dVelLoopKI)/(uiTotalNumPointsOneDim - 1); if(fabs(dStepVelKI) > 1) // 20120727 { nActualPointsTuneVKI = uiTotalNumPointsOneDim; for(ii =0; ii<uiTotalNumPointsOneDim; ii++) { adParaVelKI[ii] = stCurrTuneParaLowBound.stMtnPara.dVelLoopKI + dStepVelKI * ii; } } else { nActualPointsTuneVKI = 0; } astWbOneWirePerformance[0].stBondHeadPerformance = astMotionTuneHistory[idxBestParaSet].stTuneBondHeadPerformanceB1W; /// 20110523 if(iObjSectionFlagB1W != WB_BH_2ND_CONTACT && iObjSectionFlagB1W != WB_BH_1ST_CONTACT && iObjSectionFlagB1W != WB_BH_IDLE) //// Skip tunning parameter for 1st and 2nd contact, 20101002 { // AccFFC for(kk = 0; kk<nActualPointsTuneAccFF; kk++) { stCurrTuneBondHeadParaB1W.dAccFFC = adParaAccFFC[kk]; if(mtn_b1w_write_para_bh_servo_readve(stCommHandle, &stCurrTuneBondHeadParaB1W, iObjSectionFlagB1W) != MTN_API_OK_ZERO) { sRet = MTN_API_ERROR_DOWNLOAD_DATA; goto label_mtn_wb_tune_bh_b1w_stop_srch; } // Execute B1W for(cc = 0, cTempObjCaseInB1W=0; cc<MAX_CASE_B1W_EACH_PARA; cc++) { //if(mtnapi_wait_axis_settling(stCommHandle, iAxisTuningACS, POSN_SETTLE_TH_DURING_TUNING) != MTN_API_OK_ZERO) //{ // sRet = MTN_API_ERROR_ACS_ERROR_SETTLING;// // goto label_mtn_wb_tune_bh_b1w_stop_srch; //} mtn_wb_tune_b1w_stop_srch_trig_once(stCommHandle); while(qc_is_axis_still_acc_dec(stCommHandle, iAxisTuningACS)) { Sleep(100); //Sleep(2); } mtn_wb_tune_b1w_stop_srch_calc_bh_obj(&gstSystemScope, &gdScopeCollectData[0], &stWbTuneB1wObj); cTempObjCaseInB1W = cTempObjCaseInB1W + stWbTuneB1wObj.dObj[iObjSectionFlagB1W]; //mtn_tune_calc_b1w_bh_performance(&astWbEmuB1WPerformance[cc], stpTuningTheme, iObjSectionFlagB1W); } astMotionTuneHistory[idxCurrCase1By1].dTuningObj = cTempObjCaseInB1W/MAX_CASE_B1W_EACH_PARA; astMotionTuneHistory[idxCurrCase1By1].stTuneBondHeadPerformanceB1W = astWbEmuB1WPerformance[0].stBondHeadPerformance; astMotionTuneHistory[idxCurrCase1By1].stServoPara.stMtnPara = stCurrTuneBondHeadParaB1W; astMotionTuneHistory[idxCurrCase1By1].stTuneB1wObjValues = stWbTuneB1wObj; if(dBestTuneObj1By1 > astMotionTuneHistory[idxCurrCase1By1].dTuningObj) { dBestTuneObj1By1 = astMotionTuneHistory[idxCurrCase1By1].dTuningObj; idxBestParaSet = idxCurrCase1By1; } idxCurrCase1By1++; if(mtn_wb_tune_b1w_check_is_feasible_parameter(&stWbTuneB1wObj.dObj[0], &stWbTuneB1wPassFlag) == TRUE) { mtn_wb_tune_b1w_record_feasible_parameter(&stWbTuneB1wObj, &astWbEmuB1WPerformance[0].stBondHeadPerformance, iObjSectionFlagB1W, &stCurrTuneBondHeadParaB1W); } if(idxCurrCase1By1 >= nTotalCases1By1 || cFlagStopTuneB1W == TRUE || qc_is_axis_not_safe(stCommHandle, iAxisTuningACS)) { goto label_mtn_wb_tune_bh_b1w_stop_srch; } } stCurrTuneBondHeadParaB1W.dAccFFC = astMotionTuneHistory[idxBestParaSet].stServoPara.stMtnPara.dAccFFC; if(stCurrTuneParaLowBound.stMtnPara.dAccFFC < (stCurrTuneBondHeadParaB1W.dAccFFC - RESCALE_FACTOR_PREV_STEP_SIZE * dStepAccFFC)) { stCurrTuneParaLowBound.stMtnPara.dAccFFC = stCurrTuneBondHeadParaB1W.dAccFFC - RESCALE_FACTOR_PREV_STEP_SIZE * dStepAccFFC; } if(stCurrTuneParaLowBound.stMtnPara.dAccFFC <= 0) { stCurrTuneParaLowBound.stMtnPara.dAccFFC = stpTuningParameterLowBound->stMtnPara.dAccFFC; } if(stCurrTuneParaUppBound.stMtnPara.dAccFFC > (stCurrTuneBondHeadParaB1W.dAccFFC + RESCALE_FACTOR_PREV_STEP_SIZE * dStepAccFFC)) { stCurrTuneParaUppBound.stMtnPara.dAccFFC = (stCurrTuneBondHeadParaB1W.dAccFFC + RESCALE_FACTOR_PREV_STEP_SIZE * dStepAccFFC); } dStepAccFFC = (stCurrTuneParaUppBound.stMtnPara.dAccFFC - stCurrTuneParaLowBound.stMtnPara.dAccFFC)/(uiTotalNumPointsOneDim - 1); if(fabs(dStepAccFFC) >= 1) // 20120727 { nActualPointsTuneAccFF = uiTotalNumPointsOneDim; for(ii =0; ii<uiTotalNumPointsOneDim; ii++) { adParaAccFFC[ii] = stCurrTuneParaLowBound.stMtnPara.dAccFFC + dStepAccFFC * ii; } } else { nActualPointsTuneAccFF = 0; } ////// JerkFF, 20110529 if(iObjSectionFlagB1W == WB_BH_SRCH_HT) { for(kk = 0; kk<nActualPointsTuneJerkFF; kk++) { stCurrTuneBondHeadParaB1W.dJerkFf = adParaJerkFFC[kk]; //if(mtn_b1w_write_para_bh_servo_readve(stCommHandle, &stCurrTuneBondHeadParaB1W, iObjSectionFlagB1W) != MTN_API_OK_ZERO) //{ // sRet = MTN_API_ERROR_DOWNLOAD_DATA; // goto label_mtn_wb_tune_bh_b1w_stop_srch; //} mtnapi_download_acs_sp_parameter_jerk_ff(stCommHandle, iAxisTuningACS, stCurrTuneBondHeadParaB1W.dJerkFf); // 20110524 // Execute B1W for(cc = 0, cTempObjCaseInB1W=0; cc<MAX_CASE_B1W_EACH_PARA; cc++) { //if(mtnapi_wait_axis_settling(stCommHandle, iAxisTuningACS, POSN_SETTLE_TH_DURING_TUNING) != MTN_API_OK_ZERO) //{ // sRet = MTN_API_ERROR_ACS_ERROR_SETTLING;// // goto label_mtn_wb_tune_bh_b1w_stop_srch; //} mtn_wb_tune_b1w_stop_srch_trig_once(stCommHandle); while(qc_is_axis_still_acc_dec(stCommHandle, iAxisTuningACS)) { Sleep(100); //Sleep(2); } mtn_wb_tune_b1w_stop_srch_calc_bh_obj(&gstSystemScope, &gdScopeCollectData[0], &stWbTuneB1wObj); cTempObjCaseInB1W = cTempObjCaseInB1W + stWbTuneB1wObj.dObj[iObjSectionFlagB1W]; //mtn_tune_calc_b1w_bh_performance(&astWbEmuB1WPerformance[cc], stpTuningTheme, iObjSectionFlagB1W); } astMotionTuneHistory[idxCurrCase1By1].dTuningObj = cTempObjCaseInB1W/MAX_CASE_B1W_EACH_PARA; astMotionTuneHistory[idxCurrCase1By1].stTuneBondHeadPerformanceB1W = astWbEmuB1WPerformance[0].stBondHeadPerformance; astMotionTuneHistory[idxCurrCase1By1].stServoPara.stMtnPara = stCurrTuneBondHeadParaB1W; astMotionTuneHistory[idxCurrCase1By1].stTuneB1wObjValues = stWbTuneB1wObj; if(dBestTuneObj1By1 > astMotionTuneHistory[idxCurrCase1By1].dTuningObj) { dBestTuneObj1By1 = astMotionTuneHistory[idxCurrCase1By1].dTuningObj; idxBestParaSet = idxCurrCase1By1; } idxCurrCase1By1++; if(mtn_wb_tune_b1w_check_is_feasible_parameter(&stWbTuneB1wObj.dObj[0], &stWbTuneB1wPassFlag) == TRUE) { mtn_wb_tune_b1w_record_feasible_parameter(&stWbTuneB1wObj, &astWbEmuB1WPerformance[0].stBondHeadPerformance, iObjSectionFlagB1W, &stCurrTuneBondHeadParaB1W); } if(idxCurrCase1By1 >= nTotalCases1By1 || cFlagStopTuneB1W == TRUE || qc_is_axis_not_safe(stCommHandle, iAxisTuningACS)) { goto label_mtn_wb_tune_bh_b1w_stop_srch; } } stCurrTuneBondHeadParaB1W.dJerkFf = astMotionTuneHistory[idxBestParaSet].stServoPara.stMtnPara.dJerkFf; if(stCurrTuneParaLowBound.stMtnPara.dJerkFf < (stCurrTuneBondHeadParaB1W.dJerkFf - RESCALE_FACTOR_PREV_STEP_SIZE * dStepJerkFFC)) { stCurrTuneParaLowBound.stMtnPara.dJerkFf = stCurrTuneBondHeadParaB1W.dJerkFf - RESCALE_FACTOR_PREV_STEP_SIZE * dStepJerkFFC; } if(stCurrTuneParaLowBound.stMtnPara.dJerkFf <= 0) { stCurrTuneParaLowBound.stMtnPara.dJerkFf = stpTuningParameterLowBound->stMtnPara.dJerkFf; } if(stCurrTuneParaUppBound.stMtnPara.dJerkFf > (stCurrTuneBondHeadParaB1W.dJerkFf + RESCALE_FACTOR_PREV_STEP_SIZE * dStepJerkFFC)) { stCurrTuneParaUppBound.stMtnPara.dJerkFf = (stCurrTuneBondHeadParaB1W.dJerkFf + RESCALE_FACTOR_PREV_STEP_SIZE * dStepJerkFFC); } dStepJerkFFC = (stCurrTuneParaUppBound.stMtnPara.dJerkFf - stCurrTuneParaLowBound.stMtnPara.dJerkFf)/(uiTotalNumPointsOneDim - 1); if(fabs(dStepJerkFFC) > 1) // 20120727 { nActualPointsTuneJerkFF = uiTotalNumPointsOneDim; for(ii =0; ii<uiTotalNumPointsOneDim; ii++) { adParaJerkFFC[ii] = stCurrTuneParaLowBound.stMtnPara.dJerkFf + dStepJerkFFC * ii; } } else { nActualPointsTuneJerkFF = 0; } } } astWbOneWirePerformance[0].stBondHeadPerformance = astMotionTuneHistory[idxBestParaSet].stTuneBondHeadPerformanceB1W; /// 20110523 // PosnKP for(ll = 0; ll<nActualPointsTunePKP; ll++) { stCurrTuneBondHeadParaB1W.dPosnLoopKP = adParaPosnKP[ll]; if(stCurrTuneBondHeadParaB1W.dPosnLoopKP < stpTuningParameterLowBound->stMtnPara.dPosnLoopKP) { stCurrTuneBondHeadParaB1W.dPosnLoopKP = stpTuningParameterLowBound->stMtnPara.dPosnLoopKP; } if(mtn_b1w_write_para_bh_servo_readve(stCommHandle, &stCurrTuneBondHeadParaB1W, iObjSectionFlagB1W) != MTN_API_OK_ZERO) { CString cstrTemp; cstrTemp.Format(_T("Error Parameter: %4f, %4f, %4f, %4f, %4f, %4f, %4f, %4f, %4f"), adParaPosnKP[0], adParaPosnKP[1], adParaPosnKP[2], adParaPosnKP[3], adParaPosnKP[4], adParaPosnKP[5], adParaPosnKP[6], adParaPosnKP[7], adParaPosnKP[8]); AfxMessageBox(cstrTemp); sRet = MTN_API_ERROR_DOWNLOAD_DATA; goto label_mtn_wb_tune_bh_b1w_stop_srch; } // Execute B1W for(cc = 0, cTempObjCaseInB1W=0; cc<MAX_CASE_B1W_EACH_PARA; cc++) { //if(mtnapi_wait_axis_settling(stCommHandle, iAxisTuningACS, POSN_SETTLE_TH_DURING_TUNING) != MTN_API_OK_ZERO) //{ // sRet = MTN_API_ERROR_ACS_ERROR_SETTLING;// // goto label_mtn_wb_tune_bh_b1w_stop_srch; //} mtn_wb_tune_b1w_stop_srch_trig_once(stCommHandle); while(qc_is_axis_still_acc_dec(stCommHandle, iAxisTuningACS)) { Sleep(100); //Sleep(2); } mtn_wb_tune_b1w_stop_srch_calc_bh_obj(&gstSystemScope, &gdScopeCollectData[0], &stWbTuneB1wObj); cTempObjCaseInB1W = cTempObjCaseInB1W + stWbTuneB1wObj.dObj[iObjSectionFlagB1W]; //mtn_tune_calc_b1w_bh_performance(&astWbEmuB1WPerformance[cc], stpTuningTheme, iObjSectionFlagB1W); } astMotionTuneHistory[idxCurrCase1By1].dTuningObj = cTempObjCaseInB1W/MAX_CASE_B1W_EACH_PARA; astMotionTuneHistory[idxCurrCase1By1].stTuneBondHeadPerformanceB1W = astWbEmuB1WPerformance[0].stBondHeadPerformance; astMotionTuneHistory[idxCurrCase1By1].stServoPara.stMtnPara = stCurrTuneBondHeadParaB1W; astMotionTuneHistory[idxCurrCase1By1].stTuneB1wObjValues = stWbTuneB1wObj; if(dBestTuneObj1By1 > astMotionTuneHistory[idxCurrCase1By1].dTuningObj) { dBestTuneObj1By1 = astMotionTuneHistory[idxCurrCase1By1].dTuningObj; idxBestParaSet = idxCurrCase1By1; } idxCurrCase1By1++; if(mtn_wb_tune_b1w_check_is_feasible_parameter(&stWbTuneB1wObj.dObj[0], &stWbTuneB1wPassFlag) == TRUE) { mtn_wb_tune_b1w_record_feasible_parameter(&stWbTuneB1wObj, &astWbEmuB1WPerformance[0].stBondHeadPerformance, iObjSectionFlagB1W, &stCurrTuneBondHeadParaB1W); } if(idxCurrCase1By1 >= nTotalCases1By1 || cFlagStopTuneB1W == TRUE || qc_is_axis_not_safe(stCommHandle, iAxisTuningACS)) { goto label_mtn_wb_tune_bh_b1w_stop_srch; } } stCurrTuneBondHeadParaB1W.dPosnLoopKP = astMotionTuneHistory[idxBestParaSet].stServoPara.stMtnPara.dPosnLoopKP; if(stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP < (stCurrTuneBondHeadParaB1W.dPosnLoopKP - RESCALE_FACTOR_PREV_STEP_SIZE * dStepPosnKP)) { stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP = stCurrTuneBondHeadParaB1W.dPosnLoopKP - RESCALE_FACTOR_PREV_STEP_SIZE * dStepPosnKP; } if(stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP <= 0) { stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP = stpTuningParameterLowBound->stMtnPara.dPosnLoopKP; } if(stCurrTuneParaUppBound.stMtnPara.dPosnLoopKP > (stCurrTuneBondHeadParaB1W.dPosnLoopKP + RESCALE_FACTOR_PREV_STEP_SIZE * dStepPosnKP)) { stCurrTuneParaUppBound.stMtnPara.dPosnLoopKP = (stCurrTuneBondHeadParaB1W.dPosnLoopKP + RESCALE_FACTOR_PREV_STEP_SIZE * dStepPosnKP); } dStepPosnKP = (stCurrTuneParaUppBound.stMtnPara.dPosnLoopKP - stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP)/(uiTotalNumPointsOneDim - 1); if(dStepPosnKP > 1) // 20120727 { nActualPointsTunePKP = uiTotalNumPointsOneDim; for(ii =0; ii<uiTotalNumPointsOneDim; ii++) { adParaPosnKP[ii] = stCurrTuneParaLowBound.stMtnPara.dPosnLoopKP + dStepPosnKP * ii; } } else { nActualPointsTunePKP = 0; } astWbOneWirePerformance[0].stBondHeadPerformance = astMotionTuneHistory[idxBestParaSet].stTuneBondHeadPerformanceB1W; /// 20110523 // End one loop iCurrLoop ++; } label_mtn_wb_tune_bh_b1w_stop_srch: stpMtnTuneOutput->dTuningObj = dBestTuneObj1By1; gstSystemScope.uiNumData = 7; gstSystemScope.uiDataLen = 3000; gstSystemScope.dSamplePeriod_ms = 1; mtn_tune_contact_save_data(stCommHandle, &gstSystemScope, stTeachContactParameter.iAxis, FILE_NAME_SEARCH_CONTACT_FINAL, "%% ACSC Controller, Axis- %d: RPOS(AXIS), PE(AXIS), RVEL(AXIS), FVEL(AXIS), DCOM(AXIS), DOUT(AXIS), SLAFF(AXIS) \n "); stpMtnTuneOutput->stResultResponse = astMotionTuneHistory[idxBestParaSet].stServoTuneIndex; // Tuning pass (iFlagTuningIsFail = FALSE ) iff the obj is better than initial value <=> (dTuningObj < dInitialObj) if(stpMtnTuneOutput->dTuningObj < stpMtnTuneOutput->dInitialObj) { stpMtnTuneOutput->iFlagTuningIsFail = FALSE; // Failure is FALSE, meaning PASS, download the best parameter set stpMtnTuneOutput->stBestParameterSet = astMotionTuneHistory[idxBestParaSet].stServoPara.stMtnPara; // Only update when TuneOut better than init mtn_tune_round_parameter_to_nearest_1(&astMotionTuneHistory[idxBestParaSet].stServoPara.stMtnPara, &stpMtnTuneOutput->stBestParameterSet); // APP_Z_BOND_ACS_I // // Parameter rounding mtn_b1w_write_para_bh_servo_readve(stCommHandle, &stpMtnTuneOutput->stBestParameterSet, iObjSectionFlagB1W); // stCurrTuneBondHeadParaB1W // mtn_b1w_write_para_bh_servo( } else { stpMtnTuneOutput->iFlagTuningIsFail = TRUE; } // Restore the safety parameters mtnapi_download_safety_parameter_acs_per_axis(stCommHandle, iAxisTuningACS, &stSafetyParaBak); if(stpMtnTuneInput->iDebugFlag == TRUE) { mtn_tune_save_tuning_history(stpMtnTuneInput, stpMtnTuneOutput, idxCurrCase1By1); } return sRet; } #ifdef __B1W_STOP_SRCH__ #endif
react-storefront-foundation/react-storefront
src/mock-connector/product.js
import getBase64ForImage from 'react-storefront/utils/getBase64ForImage' import fulfillAPIRequest from '../props/fulfillAPIRequest' import createProduct from './utils/createProduct' import createAppData from './utils/createAppData' function asciiSum(string = '') { return string.split('').reduce((s, e) => s + e.charCodeAt(), 0) } export default async function product(params, req) { const { id, color, size } = params const result = await fulfillAPIRequest(req, { appData: createAppData, pageData: () => getPageData(id), }) // When a query parameter exists, we can fetch custom product data // pertaining to specific filters. if (color || size) { const data = await getPageData(id) data.carousel = { index: 0 } // A price for the fetched product variant would be included in // the response, but for demo purposes only, we are setting the // price based on the color name. const mockPrice = (asciiSum(color) + asciiSum(size)) / 100 data.product.price = mockPrice data.product.priceText = `$${mockPrice.toFixed(2)}` return data } return result } async function getPageData(id) { const result = { title: `Product ${id}`, product: createProduct(id), breadcrumbs: [ { text: 'Home', href: '/', }, { text: `Subcategory ${id}`, as: `/s/${id}`, href: '/s/[subcategoryId]', }, ], } const mainProductImage = result.product.media.full[0] mainProductImage.src = await getBase64ForImage(mainProductImage.src) return result }
openharmony-gitee-mirror/ace_ace_engine
frameworks/core/image/image_provider.cpp
<filename>frameworks/core/image/image_provider.cpp /* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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 "core/image/image_provider.h" #include "experimental/svg/model/SkSVGDOM.h" #include "third_party/skia/include/core/SkGraphics.h" #include "third_party/skia/include/core/SkStream.h" #include "base/thread/background_task_executor.h" #include "core/components/image/flutter_render_image.h" #include "core/event/ace_event_helper.h" #include "core/image/flutter_image_cache.h" #include "core/image/image_object.h" namespace OHOS::Ace { namespace { constexpr double RESIZE_MAX_PROPORTION = 0.5 * 0.5; // Cache image when resize exceeds 25% // If a picture is a wide color gamut picture, its area value will be larger than this threshold. constexpr double SRGB_GAMUT_AREA = 0.104149; } // namespace void ImageProvider::FetchImageObject( ImageSourceInfo imageInfo, ImageObjSuccessCallback successCallback, UploadSuccessCallback uploadSuccessCallback, FailedCallback failedCallback, const WeakPtr<PipelineContext> context, bool syncMode, bool useSkiaSvg, bool needAutoResize, const std::optional<Color>& color, RefPtr<FlutterRenderTaskHolder>& renderTaskHolder, OnPostBackgroundTask onBackgroundTaskPostCallback) { auto task = [ context, imageInfo, successCallback, failedCallback, useSkiaSvg, color, &renderTaskHolder, uploadSuccessCallback, needAutoResize] () { auto pipelineContext = context.Upgrade(); if (!pipelineContext) { LOGE("pipline context has been released. imageInfo: %{private}s", imageInfo.ToString().c_str()); return; } auto taskExecutor = pipelineContext->GetTaskExecutor(); if (!taskExecutor) { LOGE("task executor is null. imageInfo: %{private}s", imageInfo.ToString().c_str()); return; } RefPtr<ImageObject> imageObj = QueryImageObjectFromCache(imageInfo, pipelineContext); if (!imageObj) { // if image object is not in cache, generate a new one. imageObj = GeneraterAceImageObject(imageInfo, pipelineContext, useSkiaSvg, color); } if (!imageObj) { // if it fails to generate an image object, trigger fail callback. taskExecutor->PostTask([failedCallback, imageInfo] { failedCallback(imageInfo); }, TaskExecutor::TaskType::UI); return; } taskExecutor->PostTask([ successCallback, imageInfo, imageObj ] () { successCallback(imageInfo, imageObj); }, TaskExecutor::TaskType::UI); bool canStartUploadImageObj = !needAutoResize && (imageObj->GetFrameCount() == 1); if (canStartUploadImageObj) { bool forceResize = (!imageObj->IsSvg()) && (imageInfo.IsSourceDimensionValid()); FlutterRenderImage::UploadImageObjToGpuForRender(imageObj, context, renderTaskHolder, uploadSuccessCallback, failedCallback, imageObj->GetImageSize(), forceResize, true); } }; if (syncMode) { task(); return; } CancelableTask cancelableTask(std::move(task)); if (onBackgroundTaskPostCallback) { onBackgroundTaskPostCallback(cancelableTask); } BackgroundTaskExecutor::GetInstance().PostTask(cancelableTask); } RefPtr<ImageObject> ImageProvider::QueryImageObjectFromCache( const ImageSourceInfo& imageInfo, const RefPtr<PipelineContext>& pipelineContext) { auto imageCache = pipelineContext->GetImageCache(); if (!imageCache) { return nullptr; } return imageCache->GetCacheImgObj(imageInfo.ToString()); } RefPtr<ImageObject> ImageProvider::GeneraterAceImageObject( const ImageSourceInfo& imageInfo, const RefPtr<PipelineContext> context, bool useSkiaSvg, const std::optional<Color>& color) { auto imageData = LoadImageRawData(imageInfo, context); if (!imageData) { LOGE("load image data failed. imageInfo: %{private}s", imageInfo.ToString().c_str()); return nullptr; } return ImageObject::BuildImageObject(imageInfo, context, imageData, useSkiaSvg, color); } sk_sp<SkData> ImageProvider::LoadImageRawData( const ImageSourceInfo& imageInfo, const RefPtr<PipelineContext> context, const Size& targetSize) { auto imageCache = context->GetImageCache(); if (imageCache) { // 1. try get data from cache. auto cacheData = imageCache->GetCacheImageData(imageInfo.GetSrc()); if (cacheData) { LOGD("sk data from memory cache."); return AceType::DynamicCast<SkiaCachedImageData>(cacheData)->imageData; } // 2 try get data from file cache. if (targetSize.IsValid()) { LOGD("size valid try load from cache."); std::string cacheFilePath = ImageCache::GetImageCacheFilePath(ImageObject::GenerateCacheKey(imageInfo.GetSrc(), targetSize)); LOGD("cache file path: %{private}s", cacheFilePath.c_str()); auto data = imageCache->GetDataFromCacheFile(cacheFilePath); if (data) { LOGD("cache file found : %{public}s", cacheFilePath.c_str()); return AceType::DynamicCast<SkiaCachedImageData>(data)->imageData; } } else { LOGD("target size is not valid, load raw image file."); } } // 3. try load raw image file. auto imageLoader = ImageLoader::CreateImageLoader(imageInfo); if (!imageLoader) { LOGE("imageLoader create failed. imageInfo: %{private}s", imageInfo.ToString().c_str()); return nullptr; } auto data = imageLoader->LoadImageData(imageInfo.GetSrc(), context); if (data && imageCache) { // cache sk data. imageCache->CacheImageData(imageInfo.GetSrc(), AceType::MakeRefPtr<SkiaCachedImageData>(data)); } return data; } void ImageProvider::GetSVGImageDOMAsyncFromSrc( const std::string& src, std::function<void(const sk_sp<SkSVGDOM>&)> successCallback, std::function<void()> failedCallback, const WeakPtr<PipelineContext> context, uint64_t svgThemeColor, OnPostBackgroundTask onBackgroundTaskPostCallback) { auto task = [ src, successCallback, failedCallback, context, svgThemeColor ] { auto pipelineContext = context.Upgrade(); if (!pipelineContext) { LOGW("render image or pipeline has been released. src: %{private}s", src.c_str()); return; } auto taskExecutor = pipelineContext->GetTaskExecutor(); if (!taskExecutor) { return; } auto imageLoader = ImageLoader::CreateImageLoader(ImageSourceInfo(src)); if (!imageLoader) { LOGE("load image failed when create image loader. src: %{private}s", src.c_str()); return; } auto imageData = imageLoader->LoadImageData(src, context); if (imageData) { const auto svgStream = std::make_unique<SkMemoryStream>(std::move(imageData)); if (svgStream) { auto skiaDom = SkSVGDOM::MakeFromStream(*svgStream, svgThemeColor); if (skiaDom) { taskExecutor->PostTask( [successCallback, skiaDom] { successCallback(skiaDom); }, TaskExecutor::TaskType::UI); return; } } } LOGE("svg data wrong! src: %{private}s", src.c_str()); taskExecutor->PostTask([failedCallback] { failedCallback(); }, TaskExecutor::TaskType::UI); }; CancelableTask cancelableTask(std::move(task)); if (onBackgroundTaskPostCallback) { onBackgroundTaskPostCallback(cancelableTask); } BackgroundTaskExecutor::GetInstance().PostTask(cancelableTask); } void ImageProvider::GetSVGImageDOMAsyncFromData( const sk_sp<SkData>& skData, std::function<void(const sk_sp<SkSVGDOM>&)> successCallback, std::function<void()> failedCallback, const WeakPtr<PipelineContext> context, uint64_t svgThemeColor, OnPostBackgroundTask onBackgroundTaskPostCallback) { auto task = [ skData, successCallback, failedCallback, context, svgThemeColor ] { auto pipelineContext = context.Upgrade(); if (!pipelineContext) { LOGW("render image or pipeline has been released."); return; } auto taskExecutor = pipelineContext->GetTaskExecutor(); if (!taskExecutor) { return; } const auto svgStream = std::make_unique<SkMemoryStream>(skData); if (svgStream) { auto skiaDom = SkSVGDOM::MakeFromStream(*svgStream, svgThemeColor); if (skiaDom) { taskExecutor->PostTask( [successCallback, skiaDom] { successCallback(skiaDom); }, TaskExecutor::TaskType::UI); return; } } LOGE("svg data wrong!"); taskExecutor->PostTask([failedCallback] { failedCallback(); }, TaskExecutor::TaskType::UI); }; CancelableTask cancelableTask(std::move(task)); if (onBackgroundTaskPostCallback) { onBackgroundTaskPostCallback(cancelableTask); } BackgroundTaskExecutor::GetInstance().PostTask(cancelableTask); } void ImageProvider::UploadImageToGPUForRender( const sk_sp<SkImage>& image, const std::function<void(flutter::SkiaGPUObject<SkImage>)>&& callback, const RefPtr<FlutterRenderTaskHolder>& renderTaskHolder) { if (!renderTaskHolder) { LOGW("renderTaskHolder has been released."); return; } #if defined(DUMP_DRAW_CMD) || defined(GPU_DISABLED) // If want to dump draw command or gpu disabled, should use CPU image. callback({ image, renderTaskHolder->unrefQueue }); #else // TODO: software render not upload to gpu auto rasterizedImage = image->makeRasterImage(); if (!rasterizedImage) { LOGW("Rasterize image failed. callback."); callback({ image, renderTaskHolder->unrefQueue }); return; } auto task = [rasterizedImage, callback, renderTaskHolder] () { if (!renderTaskHolder) { LOGW("renderTaskHolder has been released."); return; } // weak reference of io manager must be check and used on io thread, because io manager is created on io thread. if (!renderTaskHolder->ioManager) { // Shell is closing. callback({ rasterizedImage, renderTaskHolder->unrefQueue }); return; } ACE_DCHECK(!rasterizedImage->isTextureBacked()); auto resContext = renderTaskHolder->ioManager->GetResourceContext(); if (!resContext) { callback({ rasterizedImage, renderTaskHolder->unrefQueue }); return; } SkPixmap pixmap; if (!rasterizedImage->peekPixels(&pixmap)) { LOGW("Could not peek pixels of image for texture upload."); callback({ rasterizedImage, renderTaskHolder->unrefQueue }); return; } auto textureImage = SkImage::MakeCrossContextFromPixmap(resContext.get(), pixmap, true, pixmap.colorSpace(), true); callback({ textureImage ? textureImage : rasterizedImage, renderTaskHolder->unrefQueue }); // Trigger purge cpu bitmap resource, after image upload to gpu. SkGraphics::PurgeResourceCache(); }; renderTaskHolder->ioTaskRunner->PostTask(std::move(task)); #endif } sk_sp<SkImage> ImageProvider::ResizeSkImage( const sk_sp<SkImage>& rawImage, const std::string& src, Size imageSize, bool forceResize) { if (!imageSize.IsValid()) { LOGE("not valid size!, imageSize: %{private}s, src: %{private}s", imageSize.ToString().c_str(), src.c_str()); return rawImage; } int32_t dstWidth = static_cast<int32_t>(imageSize.Width() + 0.5); int32_t dstHeight = static_cast<int32_t>(imageSize.Height() + 0.5); bool needResize = false; if (!forceResize) { if (rawImage->width() > dstWidth) { needResize = true; } else { dstWidth = rawImage->width(); } if (rawImage->height() > dstHeight) { needResize = true; } else { dstHeight = rawImage->height(); } } if (!needResize && !forceResize) { return rawImage; } return ApplySizeToSkImage( rawImage, dstWidth, dstHeight, ImageObject::GenerateCacheKey(src, imageSize)); } sk_sp<SkImage> ImageProvider::ApplySizeToSkImage( const sk_sp<SkImage>& rawImage, int32_t dstWidth, int32_t dstHeight, const std::string& srcKey) { auto scaledImageInfo = SkImageInfo::Make(dstWidth, dstHeight, rawImage->colorType(), rawImage->alphaType(), rawImage->refColorSpace()); SkBitmap scaledBitmap; if (!scaledBitmap.tryAllocPixels(scaledImageInfo)) { LOGE("Could not allocate bitmap when attempting to scale. srcKey: %{private}s, destination size: [%{public}d x" " %{public}d], raw image size: [%{public}d x %{public}d]", srcKey.c_str(), dstWidth, dstHeight, rawImage->width(), rawImage->height()); return rawImage; } if (!rawImage->scalePixels(scaledBitmap.pixmap(), kLow_SkFilterQuality, SkImage::kDisallow_CachingHint)) { LOGE("Could not scale pixels srcKey: %{private}s, destination size: [%{public}d x" " %{public}d], raw image size: [%{public}d x %{public}d]", srcKey.c_str(), dstWidth, dstHeight, rawImage->width(), rawImage->height()); return rawImage; } // Marking this as immutable makes the MakeFromBitmap call share the pixels instead of copying. scaledBitmap.setImmutable(); auto scaledImage = SkImage::MakeFromBitmap(scaledBitmap); if (scaledImage) { bool needCacheResizedImageFile = (1.0 * dstWidth * dstHeight) / (rawImage->width() * rawImage->height()) < RESIZE_MAX_PROPORTION; if (needCacheResizedImageFile && !srcKey.empty()) { auto data = scaledImage->encodeToData(SkEncodedImageFormat::kPNG, 100); if (data) { LOGD("write cache file: %{private}s", srcKey.c_str()); ImageCache::WriteCacheFile(srcKey, data->data(), data->size()); } } return scaledImage; } LOGE("Could not create a scaled image from a scaled bitmap. srcKey: %{private}s, destination size: [%{public}d x" " %{public}d], raw image size: [%{public}d x %{public}d]", srcKey.c_str(), dstWidth, dstHeight, rawImage->width(), rawImage->height()); return rawImage; } sk_sp<SkImage> ImageProvider::GetSkImage( const std::string& src, const WeakPtr<PipelineContext> context, Size targetSize) { auto imageLoader = ImageLoader::CreateImageLoader(ImageSourceInfo(src)); auto imageSkData = imageLoader->LoadImageData(src, context); if (!imageSkData) { LOGE("fetch data failed. src: %{private}s", src.c_str()); return nullptr; } auto rawImage = SkImage::MakeFromEncoded(imageSkData); if (!rawImage) { LOGE("MakeFromEncoded failed! src: %{private}s", src.c_str()); return nullptr; } auto image = ResizeSkImage(rawImage, src, targetSize); return image; } void ImageProvider::CanLoadImage( const RefPtr<PipelineContext>& context, const std::string& src, const std::map<std::string, EventMarker>& callbacks) { if (callbacks.find("success") == callbacks.end() || callbacks.find("fail") == callbacks.end()) { return; } auto onSuccess = AceAsyncEvent<void()>::Create(callbacks.at("success"), context); auto onFail = AceAsyncEvent<void()>::Create(callbacks.at("fail"), context); BackgroundTaskExecutor::GetInstance().PostTask([src, onSuccess, onFail, context]() { auto taskExecutor = context->GetTaskExecutor(); if (!taskExecutor) { return; } auto image = ImageProvider::GetSkImage(src, context); if (image) { taskExecutor->PostTask( [onSuccess] { onSuccess(); }, TaskExecutor::TaskType::UI); return; } taskExecutor->PostTask( [onFail] { onFail(); }, TaskExecutor::TaskType::UI); }); } bool ImageProvider::IsWideGamut(const sk_sp<SkColorSpace>& colorSpace) { skcms_ICCProfile encodedProfile; colorSpace->toProfile(&encodedProfile); if (!encodedProfile.has_toXYZD50) { LOGI("This profile's gamut can not be represented by a 3x3 transform to XYZD50"); return false; } // Normalize gamut by 1. // rgb[3] represents the point of Red, Green and Blue coordinate in color space diagram. Point rgb[3]; auto xyzGamut = encodedProfile.toXYZD50; for (int32_t i = 0; i < 3; i++) { auto sum = xyzGamut.vals[i][0] + xyzGamut.vals[i][1] + xyzGamut.vals[i][2]; rgb[i].SetX(xyzGamut.vals[i][0] / sum); rgb[i].SetY(xyzGamut.vals[i][1] / sum); } // Calculate the area enclosed by the coordinates of the three RGB points Point red = rgb[0]; Point green = rgb[1]; Point blue = rgb[2]; // Assuming there is a triangle enclosed by three points: A(x1, y1), B(x2, y2), C(x3, y3), // the formula for calculating the area of triangle ABC is as follows: // S = (x1 * y2 + x2 * y3 + x3 * y1 - x1 * y3 - x2 * y1 - x3 * y2) / 2.0 auto areaOfPoint = std::fabs(red.GetX() * green.GetY() + green.GetX() * blue.GetY() + blue.GetX() * green.GetY() - red.GetX() * blue.GetY() - blue.GetX() * green.GetY() - green.GetX() * red.GetY()) / 2.0; return GreatNotEqual(areaOfPoint, SRGB_GAMUT_AREA); } } // namespace OHOS::Ace
oct16/leetcode-javascript
70.climbing-stairs.js
<gh_stars>1-10 /* * @lc app=leetcode id=70 lang=javascript * * [70] Climbing Stairs */ // @lc code=start /** * @param {number} n * @return {number} */ var climbStairs = function(n) { const cached = new Array(0, 1, 2, 3) function climb(n) { if (cached[n]) { return cached[n] } const step = climb(n - 1) + climb(n - 2) cached[n] = step return step } return climb(n) } // @lc code=end
ivankravets/Arduino-Libs
RedFly/RedFlyNBNS.h
#ifndef REDFLYNBNS_h #define REDFLYNBNS_h #include <inttypes.h> #if (defined(__AVR__) || defined(ARDUINO_ARCH_AVR)) # include <avr/pgmspace.h> #endif #include "RedFlyServer.h" class RedFlyNBNS : RedFlyServer { public: RedFlyNBNS(void); RedFlyNBNS(char *name); ~RedFlyNBNS(void); void setName(char *name); #if (defined(__AVR__) || defined(ARDUINO_ARCH_AVR)) void setNamePGM(PGM_P name); #endif uint8_t service(void); private: char devname[16+1]; uint8_t decode(char *dst, char *src); void encode(char *dst, char *src, uint8_t type); }; #endif //REDFLYNBNS_h
zkat/esm
src/hook/process.js
<filename>src/hook/process.js import ESM from "../constant/esm.js" import Loader from "../loader.js" import Wrapper from "../wrapper.js" import isError from "../util/is-error.js" import isStackTraceMasked from "../util/is-stack-trace-masked.js" import maskStackTrace from "../error/mask-stack-trace.js" import scrubStackTrace from "../error/scrub-stack-trace.js" const { PACKAGE_RANGE } = ESM function hook(process) { function exceptionManagerWrapper(manager, func, args) { const wrapped = Wrapper.find(process, "_fatalException", PACKAGE_RANGE) return wrapped ? Reflect.apply(wrapped, this, [manager, func, args]) : Reflect.apply(func, this, args) } function exceptionMethodWrapper(manager, func, args) { const [error] = args if (! Loader.state.package.default.options.debug && isError(error) && ! isStackTraceMasked(error)) { maskStackTrace(error) } return Reflect.apply(func, this, args) } function warningManagerWrapper(manager, func, args) { const wrapped = Wrapper.find(process, "emitWarning", PACKAGE_RANGE) return wrapped ? Reflect.apply(wrapped, this, [manager, func, args]) : Reflect.apply(func, this, args) } function warningMethodWrapper(manager, func, args) { const [stack] = args if (typeof stack === "string") { args[0] = scrubStackTrace(stack) } return Reflect.apply(func, this, args) } Wrapper.manage(process, "_fatalException", exceptionManagerWrapper) Wrapper.wrap(process, "_fatalException", exceptionMethodWrapper) Wrapper.manage(process, "emitWarning", warningManagerWrapper) Wrapper.wrap(process, "emitWarning", warningMethodWrapper) } export default hook
xiong222/AsosClone
app/template/components/SearchDropdown/SearchDropdown.js
import React, { Component } from "react"; import { PropTypes } from "prop-types"; import withTranslation from "../translation"; import ResultList from "./ResultList"; import styles from "./index.css"; class SearchDropdown extends Component { static propTypes = { recentSearches: PropTypes.arrayOf(PropTypes.string), suggestions: PropTypes.arrayOf(PropTypes.object), formatTranslation: PropTypes.func.isRequired, clearRecentSearches: PropTypes.func.isRequired, focusSearchBox: PropTypes.func.isRequired, listRef: PropTypes.func.isRequired }; render() { const { recentSearches, suggestions } = this.props; if (!recentSearches.length && !suggestions.length) return null; return ( <div className={styles.container}> {suggestions.length ? this.renderSuggestions() : this.renderSearches()} </div> ); } renderSuggestions() { return ( <ResultList items={this.props.suggestions} focusSearchBox={this.props.focusSearchBox} listRef={this.props.listRef} /> ); } renderSearches() { const { recentSearches, formatTranslation, clearRecentSearches, focusSearchBox } = this.props; // normalise searches to be the same format as suggestions const searches = recentSearches.map(searchTerm => ({ searchTerm })); return ( <div> <h3 className={styles.recentSearchesHeader}> {formatTranslation("SearchBar.RecentSearches")} </h3> <button className={styles.recentSearchesClear} aria-label={formatTranslation("SearchBar.ClearRecentSearchesLabel")} onClick={() => { clearRecentSearches(); focusSearchBox(); }} data-testid="clear-recent-searches" > {formatTranslation("SearchBar.ClearRecentSearchesText")} </button> <ResultList items={searches} focusSearchBox={focusSearchBox} listRef={this.props.listRef} /> </div> ); } } export default withTranslation(SearchDropdown);
sigurasg/ghidra
Ghidra/Framework/Docking/src/main/java/docking/widgets/filechooser/FileEditor.java
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package docking.widgets.filechooser; import java.awt.*; import java.awt.event.*; import java.io.File; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.table.TableCellEditor; import docking.widgets.label.GDLabel; import ghidra.util.Msg; import ghidra.util.filechooser.GhidraFileChooserModel; class FileEditor extends AbstractCellEditor implements TableCellEditor { private GhidraFileChooser chooser; private DirectoryTable directoryTable; private DirectoryTableModel model; private JPanel editor; private JLabel iconLabel; private JTextField nameField; private File originalFile; private File editedFile; FileEditor(GhidraFileChooser chooser, DirectoryTable table, DirectoryTableModel model) { this.chooser = chooser; this.directoryTable = table; this.model = model; iconLabel = new GDLabel(); iconLabel.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { if (e.getClickCount() == 2) { handleDoubleClick(e.getPoint()); } } }); nameField = new JTextField(); nameField.setName("TABLE_EDITOR_FIELD"); nameField.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { directoryTable.editingCanceled(new ChangeEvent(FileEditor.this)); e.consume(); } else if (e.getKeyCode() == KeyEvent.VK_ENTER) { String invalidFilenameMessage = chooser.getInvalidFilenameMessage(nameField.getText()); if (invalidFilenameMessage != null) { chooser.setStatusText(invalidFilenameMessage); e.consume(); } } } @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { directoryTable.editingCanceled(new ChangeEvent(FileEditor.this)); e.consume(); } else if (e.getKeyCode() == KeyEvent.VK_ENTER) { String invalidFilenameMessage = chooser.getInvalidFilenameMessage(nameField.getText()); if (invalidFilenameMessage != null) { chooser.setStatusText(invalidFilenameMessage); } else { directoryTable.editingStopped(new ChangeEvent(FileEditor.this)); } e.consume(); } } }); nameField.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); editor = new JPanel(new BorderLayout()) { // make sure the name field gets the focus, not the container @Override public void requestFocus() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { nameField.requestFocus(); } }); } }; editor.add(iconLabel, BorderLayout.WEST); editor.add(nameField, BorderLayout.CENTER); // match the spacing of non-editing cells editor.setBorder( BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0), BorderFactory.createLineBorder(Color.GRAY))); } private void handleDoubleClick(Point p) { directoryTable.editingCanceled(null); int row = directoryTable.rowAtPoint(p); File file = model.getFile(row); chooser.setCurrentDirectory(file); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { editedFile = null; originalFile = model.getFile(row); String name = originalFile.getName(); Icon icon = chooser.getModel().getIcon(originalFile); iconLabel.setIcon(icon); nameField.setText(name); nameField.requestFocus(); if (name.length() > 0) { nameField.setCaretPosition(name.length()); nameField.selectAll(); } nameField.repaint(); editor.setVisible(true); return editor; } @Override public Object getCellEditorValue() { if (originalFile == null) { return null; } if (editedFile != null) { return editedFile; } editedFile = getNewFile(); return editedFile; } private File getNewFile() { String invalidFilenameMessage = chooser.getInvalidFilenameMessage(nameField.getText()); if (invalidFilenameMessage != null) { chooser.setStatusText("Rename aborted - " + invalidFilenameMessage); return originalFile; } GhidraFileChooserModel fileChooserModel = chooser.getModel(); File newFile = new GhidraFile(originalFile.getParentFile(), nameField.getText(), fileChooserModel.getSeparator()); if (fileChooserModel.renameFile(originalFile, newFile)) { return newFile; } Msg.showError(this, chooser.getComponent(), "Rename Failed", "Unable to rename file: " + originalFile); return null; } }
apparentlymart/perkeep
pkg/serverinit/serverinit_test.go
<gh_stars>0 /* Copyright 2012 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package serverinit_test import ( "bytes" "encoding/json" "errors" "flag" "fmt" "io" "io/ioutil" "os" "path/filepath" "sort" "strings" "testing" "camlistore.org/pkg/jsonconfig" "camlistore.org/pkg/serverinit" "camlistore.org/pkg/test" "camlistore.org/pkg/types/serverconfig" ) var updateGolden = flag.Bool("update_golden", false, "Update golden *.want files") const ( // relativeRing points to a real secret ring, but serverinit // rewrites it to be an absolute path. We then canonicalize // it to secringPlaceholder in the golden files. relativeRing = "../jsonsign/testdata/test-secring.gpg" secringPlaceholder = "/path/to/secring" ) func init() { // Avoid Linux vs. OS X differences in tests. serverinit.SetTempDirFunc(func() string { return "/tmp" }) serverinit.SetNoMkdir(true) } func sortedKeys(m map[string]interface{}) (keys []string) { for k := range m { keys = append(keys, k) } sort.Strings(keys) return } func prettyPrint(t *testing.T, w io.Writer, i interface{}, indent int) { out, err := json.MarshalIndent(i, "", " ") if err != nil { t.Fatal(err) } w.Write(out) } func TestConfigs(t *testing.T) { dir, err := os.Open("testdata") if err != nil { t.Fatal(err) } names, err := dir.Readdirnames(-1) if err != nil { t.Fatal(err) } for _, name := range names { if strings.HasSuffix(name, ".json") { if strings.HasSuffix(name, "-want.json") { continue } testConfig(filepath.Join("testdata", name), t) } } } type namedReadSeeker struct { name string io.ReadSeeker } func (n namedReadSeeker) Name() string { return n.name } func (n namedReadSeeker) Close() error { return nil } // configParser returns a custom jsonconfig ConfigParser whose reader rewrites "/path/to/secring" to the absolute path of the jsonconfig test-secring.gpg file. func configParser() *jsonconfig.ConfigParser { return &jsonconfig.ConfigParser{ Open: func(path string) (jsonconfig.File, error) { slurp, err := replaceRingPath(path) if err != nil { return nil, err } return namedReadSeeker{path, bytes.NewReader(slurp)}, nil }, } } // replaceRingPath returns the contents of the file at path with secringPlaceholder replaced with the absolute path of relativeRing. func replaceRingPath(path string) ([]byte, error) { secRing, err := filepath.Abs(relativeRing) if err != nil { return nil, fmt.Errorf("Could not get absolute path of %v: %v", relativeRing, err) } slurpBytes, err := ioutil.ReadFile(path) if err != nil { return nil, err } return bytes.Replace(slurpBytes, []byte(secringPlaceholder), []byte(secRing), 1), nil } func testConfig(name string, t *testing.T) { wantedError := func() error { slurp, err := ioutil.ReadFile(strings.Replace(name, ".json", ".err", 1)) if os.IsNotExist(err) { return nil } if err != nil { t.Fatalf("Error reading .err file: %v", err) } return errors.New(string(slurp)) } b, err := replaceRingPath(name) if err != nil { t.Fatalf("Could not read %s: %v", name, err) } var hiLevelConf serverconfig.Config if err := json.Unmarshal(b, &hiLevelConf); err != nil { t.Fatalf("Could not unmarshal %s into a serverconfig.Config: %v", name, err) } lowLevelConf, err := serverinit.GenLowLevelConfig(&hiLevelConf) if g, w := strings.TrimSpace(fmt.Sprint(err)), strings.TrimSpace(fmt.Sprint(wantedError())); g != w { t.Fatalf("test %s: got GenLowLevelConfig error %q; want %q", name, g, w) } if err != nil { return } wantFile := strings.Replace(name, ".json", "-want.json", 1) wantConf, err := configParser().ReadFile(wantFile) if err != nil { t.Fatalf("test %s: ReadFile: %v", name, err) } var got, want bytes.Buffer prettyPrint(t, &got, lowLevelConf.Obj, 0) prettyPrint(t, &want, wantConf, 0) if got.String() != want.String() { if *updateGolden { contents, err := json.MarshalIndent(lowLevelConf.Obj, "", "\t") if err != nil { t.Fatal(err) } contents = canonicalizeGolden(t, contents) if err := ioutil.WriteFile(wantFile, contents, 0644); err != nil { t.Fatal(err) } } t.Errorf("test %s configurations differ.\nGot:\n%s\nWant:\n%s\nDiff (got -> want), %s:\n%s", name, &got, &want, name, test.Diff(got.Bytes(), want.Bytes())) } } func canonicalizeGolden(t *testing.T, v []byte) []byte { localPath, err := filepath.Abs(relativeRing) if err != nil { t.Fatal(err) } v = bytes.Replace(v, []byte(localPath), []byte(secringPlaceholder), 1) if !bytes.HasSuffix(v, []byte("\n")) { v = append(v, '\n') } return v }
Ron423c/chromium
chrome/updater/app/server/win/com_classes.cc
// Copyright 2020 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/updater/app/server/win/com_classes.h" #include "base/bind.h" #include "base/callback_helpers.h" #include "base/logging.h" #include "base/memory/scoped_refptr.h" #include "base/strings/utf_string_conversions.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/version.h" #include "base/win/scoped_bstr.h" #include "chrome/updater/app/server/win/server.h" #include "chrome/updater/updater_version.h" namespace updater { STDMETHODIMP UpdateStateImpl::get_state(LONG* state) { DCHECK(state); *state = static_cast<LONG>(update_state_.state); return S_OK; } STDMETHODIMP UpdateStateImpl::get_appId(BSTR* app_id) { DCHECK(app_id); *app_id = base::win::ScopedBstr(base::UTF8ToWide(update_state_.app_id)).Release(); return S_OK; } STDMETHODIMP UpdateStateImpl::get_nextVersion(BSTR* next_version) { DCHECK(next_version); *next_version = base::win::ScopedBstr( update_state_.next_version.IsValid() ? base::UTF8ToWide(update_state_.next_version.GetString()) : L"") .Release(); return S_OK; } STDMETHODIMP UpdateStateImpl::get_downloadedBytes(LONGLONG* downloaded_bytes) { DCHECK(downloaded_bytes); *downloaded_bytes = LONGLONG{update_state_.downloaded_bytes}; return S_OK; } STDMETHODIMP UpdateStateImpl::get_totalBytes(LONGLONG* total_bytes) { DCHECK(total_bytes); *total_bytes = LONGLONG{update_state_.total_bytes}; return S_OK; } STDMETHODIMP UpdateStateImpl::get_installProgress(LONG* install_progress) { DCHECK(install_progress); *install_progress = LONG{update_state_.install_progress}; return S_OK; } STDMETHODIMP UpdateStateImpl::get_errorCategory(LONG* error_category) { DCHECK(error_category); *error_category = static_cast<LONG>(update_state_.error_category); return S_OK; } STDMETHODIMP UpdateStateImpl::get_errorCode(LONG* error_code) { DCHECK(error_code); *error_code = LONG{update_state_.error_code}; return S_OK; } STDMETHODIMP UpdateStateImpl::get_extraCode1(LONG* extra_code1) { DCHECK(extra_code1); *extra_code1 = LONG{update_state_.extra_code1}; return S_OK; } STDMETHODIMP CompleteStatusImpl::get_statusCode(LONG* code) { DCHECK(code); *code = code_; return S_OK; } STDMETHODIMP CompleteStatusImpl::get_statusMessage(BSTR* message) { DCHECK(message); *message = base::win::ScopedBstr(message_).Release(); return S_OK; } HRESULT UpdaterImpl::GetVersion(BSTR* version) { DCHECK(version); // Return the hardcoded version instead of calling the corresponding // non-blocking function of `UpdateServiceImpl`. This results in some // code duplication but it avoids the complexities of making this function // non-blocking. *version = base::win::ScopedBstr( base::UTF8ToWide(base::Version(UPDATER_VERSION_STRING).GetString())) .Release(); return S_OK; } HRESULT UpdaterImpl::CheckForUpdate(const wchar_t* app_id) { return E_NOTIMPL; } HRESULT UpdaterImpl::Register(const wchar_t* app_id, const wchar_t* brand_code, const wchar_t* tag, const wchar_t* version, const wchar_t* existence_checker_path) { return E_NOTIMPL; } // Called by the COM RPC runtime on one of its threads. Invokes the in-process // |update_service| on the main sequence. The callbacks received from // |update_service| arrive in the main sequence too. Since handling these // callbacks involves issuing outgoing COM RPC calls, which block, such COM // calls must be done through a task runner, bound to the closures provided // as parameters for the UpdateService::Update call. HRESULT UpdaterImpl::Update(const wchar_t* app_id, IUpdaterObserver* observer) { using IUpdaterObserverPtr = Microsoft::WRL::ComPtr<IUpdaterObserver>; scoped_refptr<ComServerApp> com_server = AppServerSingletonInstance(); // This task runner is responsible for sequencing the callbacks posted // by the |UpdateService| and calling the outbound COM functions to // notify the client about state changes in the |UpdateService|. auto task_runner = base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); com_server->main_task_runner()->PostTask( FROM_HERE, base::BindOnce( [](scoped_refptr<UpdateService> update_service, scoped_refptr<base::SequencedTaskRunner> task_runner, const std::string app_id, IUpdaterObserverPtr observer) { update_service->Update( app_id, UpdateService::Priority::kForeground, base::BindRepeating( [](scoped_refptr<base::SequencedTaskRunner> task_runner, IUpdaterObserverPtr observer, UpdateService::UpdateState update_state) { task_runner->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&IUpdaterObserver::OnStateChange, observer, Microsoft::WRL::Make<UpdateStateImpl>( update_state)), base::BindOnce([](HRESULT hr) { DVLOG(4) << "IUpdaterObserver::OnStateChange returned " << std::hex << hr; })); }, task_runner, observer), base::BindOnce( [](scoped_refptr<base::SequencedTaskRunner> task_runner, IUpdaterObserverPtr observer, UpdateService::Result result) { task_runner->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce( &IUpdaterObserver::OnComplete, observer, Microsoft::WRL::Make<CompleteStatusImpl>( static_cast<int>(result), L"")), base::BindOnce([](HRESULT hr) { DVLOG(2) << "UpdaterImpl::Update " << "callback returned " << std::hex << hr; })); }, task_runner, observer)); }, com_server->update_service(), task_runner, base::WideToUTF8(app_id), IUpdaterObserverPtr(observer))); // Always return S_OK from this function. Errors must be reported using the // observer interface. return S_OK; } // See the comment for the UpdaterImpl::Update. HRESULT UpdaterImpl::UpdateAll(IUpdaterObserver* observer) { using IUpdaterObserverPtr = Microsoft::WRL::ComPtr<IUpdaterObserver>; scoped_refptr<ComServerApp> com_server = AppServerSingletonInstance(); auto task_runner = base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); com_server->main_task_runner()->PostTask( FROM_HERE, base::BindOnce( [](scoped_refptr<UpdateService> update_service, scoped_refptr<base::SequencedTaskRunner> task_runner, IUpdaterObserverPtr observer) { update_service->UpdateAll( base::DoNothing(), base::BindOnce( [](scoped_refptr<base::SequencedTaskRunner> task_runner, IUpdaterObserverPtr observer, UpdateService::Result result) { // The COM RPC outgoing call blocks and it must be posted // through the thread pool. task_runner->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce( &IUpdaterObserver::OnComplete, observer, Microsoft::WRL::Make<CompleteStatusImpl>( static_cast<int>(result), L"")), base::BindOnce([](HRESULT hr) { DVLOG(2) << "UpdaterImpl::UpdateAll " << "callback returned " << std::hex << hr; })); }, task_runner, observer)); }, com_server->update_service(), task_runner, IUpdaterObserverPtr(observer))); // Always return S_OK from this function. Errors must be reported using the // observer interface. return S_OK; } // See the comment for the UpdaterImpl::Update. HRESULT UpdaterInternalImpl::Run(IUpdaterInternalCallback* callback) { using IUpdaterInternalCallbackPtr = Microsoft::WRL::ComPtr<IUpdaterInternalCallback>; scoped_refptr<ComServerApp> com_server = AppServerSingletonInstance(); auto task_runner = base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); com_server->main_task_runner()->PostTask( FROM_HERE, base::BindOnce( [](scoped_refptr<UpdateServiceInternal> update_service_internal, scoped_refptr<base::SequencedTaskRunner> task_runner, IUpdaterInternalCallbackPtr callback) { update_service_internal->Run(base::BindOnce( [](scoped_refptr<base::SequencedTaskRunner> task_runner, IUpdaterInternalCallbackPtr callback) { task_runner->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&IUpdaterInternalCallback::Run, callback, 0), base::BindOnce([](HRESULT hr) { DVLOG(2) << "UpdaterInternalImpl::Run " << "callback returned " << std::hex << hr; })); }, task_runner, callback)); }, com_server->update_service_internal(), task_runner, IUpdaterInternalCallbackPtr(callback))); // Always return S_OK from this function. Errors must be reported using the // callback interface. return S_OK; } HRESULT UpdaterInternalImpl::InitializeUpdateService( IUpdaterInternalCallback* callback) { using IUpdaterInternalCallbackPtr = Microsoft::WRL::ComPtr<IUpdaterInternalCallback>; scoped_refptr<ComServerApp> com_server = AppServerSingletonInstance(); auto task_runner = base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); com_server->main_task_runner()->PostTask( FROM_HERE, base::BindOnce( [](scoped_refptr<UpdateServiceInternal> update_service_internal, scoped_refptr<base::SequencedTaskRunner> task_runner, IUpdaterInternalCallbackPtr callback) { update_service_internal->InitializeUpdateService(base::BindOnce( [](scoped_refptr<base::SequencedTaskRunner> task_runner, IUpdaterInternalCallbackPtr callback) { task_runner->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&IUpdaterInternalCallback::Run, callback, 0), base::BindOnce([](HRESULT hr) { DVLOG(2) << "UpdaterInternalImpl::InitializeUpdateService " << "callback returned " << std::hex << hr; })); }, task_runner, callback)); }, com_server->update_service_internal(), task_runner, IUpdaterInternalCallbackPtr(callback))); // Always return S_OK from this function. Errors must be reported using the // callback interface. return S_OK; } } // namespace updater
dnsdb-team/getdns4j
src/test/java/io/dnsdb/getdns4j/test/TestApplication.java
<reponame>dnsdb-team/getdns4j package io.dnsdb.getdns4j.test; import io.dnsdb.getdns4j.Application; import io.dnsdb.getdns4j.cmd.SubCommandManager; import org.junit.Assert; import org.junit.Test; /** * <code>TestApplication</code>测试类用于测试{@link Application} * * @author Remonsan */ public class TestApplication { @Test public void testGetParser() { SubCommandManager commandManager = new SubCommandManager(); Application.getParser(commandManager); Assert.assertEquals(3, commandManager.getSubCommands().size()); Assert.assertEquals("search", commandManager.getSubCommands().get(0).getCommand()); Assert.assertEquals("api-user", commandManager.getSubCommands().get(1).getCommand()); Assert.assertEquals("config", commandManager.getSubCommands().get(2).getCommand()); } }
onnoA/springboot-sample
chapter02-springboot-spring-security-oauth2/spring-boot-security-oauth2-server/src/mian/java/com/onnoa/springboot/security/oauth2/server/service/impl/TbUserServiceImpl.java
package com.onnoa.springboot.security.oauth2.server.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.onnoa.springboot.security.oauth2.server.domain.TbUser; import com.onnoa.springboot.security.oauth2.server.mapper.TbUserMapper; import com.onnoa.springboot.security.oauth2.server.service.TbUserService; /** * @Description: * @Author: onnoA * @Date: 2019/11/1 09:16 */ @Service public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser> implements TbUserService{ @Autowired private TbUserMapper tbUserMapper; @Override public List<TbUser> getByUsername(String username) { QueryWrapper<TbUser> qw = new QueryWrapper<>(); qw.eq("username",username); List<TbUser> tbUserList = tbUserMapper.selectList(qw); return tbUserList; } }
bangchuanliu/algorithm-examples
algorithms-stanford/src/main/java/course4/assignment1/WeighedDiGraph.java
<filename>algorithms-stanford/src/main/java/course4/assignment1/WeighedDiGraph.java<gh_stars>0 package course4.assignment1; import java.util.LinkedList; import java.util.List; public class WeighedDiGraph { private int V; private int E; private LinkedList<Edge>[] adj; public WeighedDiGraph(int V) { adj = new LinkedList[V + 1]; this.V = V; for (int v = 0; v <= V; v++) { adj[v] = new LinkedList<>(); } } public int V() { return V; } public int E() { return E; } public void addEdge(int v, int w, int weight) { Edge edge = new Edge(w, weight); adj[v].addFirst(edge); E++; } public class Edge { int v; int weight; Edge(int v, int weight) { this.v = v; this.weight = weight; } } public List<Edge> adj(int v) { return adj[v]; } }
ChiaChia1114/Free5gc_docker
NFs/upf/updk/src/third_party/libgtp5gnl/include/linux/gtp5g.h
#ifndef _UAPI_LINUX_GTP5G_H__ #define _UAPI_LINUX_GTP5G_H__ enum gtp5g_genl_cmds { GTP5G_CMD_UNSPEC = 0, GTP5G_CMD_ADD_PDR, GTP5G_CMD_ADD_FAR, GTP5G_CMD_ADD_QER, GTP5G_CMD_DEL_PDR, GTP5G_CMD_DEL_FAR, GTP5G_CMD_DEL_QER, GTP5G_CMD_GET_PDR, GTP5G_CMD_GET_FAR, GTP5G_CMD_GET_QER, __GTP5G_CMD_MAX, }; enum gtp5g_device_attrs { GTP5G_LINK = 1, GTP5G_NET_NS_FD, }; enum gtp5g_pdr_attrs { /* gtp5g_device_attrs in this part */ GTP5G_PDR_ID = 3, GTP5G_PDR_PRECEDENCE, GTP5G_PDR_PDI, GTP5G_OUTER_HEADER_REMOVAL, GTP5G_PDR_FAR_ID, /* Not in 3GPP spec, just used for routing */ GTP5G_PDR_ROLE_ADDR_IPV4, /* Not in 3GPP spec, just used for buffering */ GTP5G_PDR_UNIX_SOCKET_PATH, GTP5G_PDR_QER_ID, /* Add newly supported feature ON ABOVE * for compatability with older version of * free5GC's UPF or gtp5g * */ __GTP5G_PDR_ATTR_MAX, }; #define GTP5G_PDR_ATTR_MAX (__GTP5G_PDR_ATTR_MAX - 1) /* Nest in GTP5G_PDR_PDI */ enum gtp5g_pdi_attrs { GTP5G_PDI_UE_ADDR_IPV4 = 1, GTP5G_PDI_F_TEID, GTP5G_PDI_SDF_FILTER, __GTP5G_PDI_ATTR_MAX, }; #define GTP5G_PDI_ATTR_MAX (__GTP5G_PDI_ATTR_MAX - 1) /* Nest in GTP5G_PDI_F_TEID */ enum gtp5g_f_teid_attrs { GTP5G_F_TEID_I_TEID = 1, GTP5G_F_TEID_GTPU_ADDR_IPV4, __GTP5G_F_TEID_ATTR_MAX, }; #define GTP5G_F_TEID_ATTR_MAX (__GTP5G_F_TEID_ATTR_MAX - 1) /* Nest in GTP5G_PDI_SDF_FILTER */ enum gtp5g_sdf_filter_attrs { GTP5G_SDF_FILTER_FLOW_DESCRIPTION = 1, GTP5G_SDF_FILTER_TOS_TRAFFIC_CLASS, GTP5G_SDF_FILTER_SECURITY_PARAMETER_INDEX, GTP5G_SDF_FILTER_FLOW_LABEL, GTP5G_SDF_FILTER_SDF_FILTER_ID, __GTP5G_SDF_FILTER_ATTR_MAX, }; #define GTP5G_SDF_FILTER_ATTR_MAX (__GTP5G_SDF_FILTER_ATTR_MAX - 1) /* Nest in GTP5G_SDF_FILTER_FLOW_DESCRIPTION */ enum gtp5g_flow_description_attrs { GTP5G_FLOW_DESCRIPTION_ACTION = 1, // Only "permit" GTP5G_FLOW_DESCRIPTION_DIRECTION, GTP5G_FLOW_DESCRIPTION_PROTOCOL, GTP5G_FLOW_DESCRIPTION_SRC_IPV4, GTP5G_FLOW_DESCRIPTION_SRC_MASK, GTP5G_FLOW_DESCRIPTION_DEST_IPV4, GTP5G_FLOW_DESCRIPTION_DEST_MASK, GTP5G_FLOW_DESCRIPTION_SRC_PORT, GTP5G_FLOW_DESCRIPTION_DEST_PORT, __GTP5G_FLOW_DESCRIPTION_ATTR_MAX, }; #define GTP5G_FLOW_DESCRIPTION_ATTR_MAX (__GTP5G_FLOW_DESCRIPTION_ATTR_MAX - 1) enum gtp5g_far_attrs { /* gtp5g_device_attrs in this part */ GTP5G_FAR_ID = 3, GTP5G_FAR_APPLY_ACTION, GTP5G_FAR_FORWARDING_PARAMETER, /* Not IEs in 3GPP Spec, for other purpose */ GTP5G_FAR_RELATED_TO_PDR, __GTP5G_FAR_ATTR_MAX, }; #define GTP5G_FAR_ATTR_MAX (__GTP5G_FAR_ATTR_MAX - 1) /* Nest in GTP5G_FAR_FORWARDING_PARAMETER */ enum gtp5g_forwarding_parameter_attrs { GTP5G_FORWARDING_PARAMETER_OUTER_HEADER_CREATION = 1, GTP5G_FORWARDING_PARAMETER_FORWARDING_POLICY, __GTP5G_FORWARDING_PARAMETER_ATTR_MAX, }; #define GTP5G_FORWARDING_PARAMETER_ATTR_MAX (__GTP5G_FORWARDING_PARAMETER_ATTR_MAX - 1) /* Nest in GTP5G_FORWARDING_PARAMETER_OUTER_HEADER_CREATION */ enum gtp5g_outer_header_creation_attrs { GTP5G_OUTER_HEADER_CREATION_DESCRIPTION = 1, GTP5G_OUTER_HEADER_CREATION_O_TEID, GTP5G_OUTER_HEADER_CREATION_PEER_ADDR_IPV4, GTP5G_OUTER_HEADER_CREATION_PORT, __GTP5G_OUTER_HEADER_CREATION_ATTR_MAX, }; #define GTP5G_OUTER_HEADER_CREATION_ATTR_MAX (__GTP5G_OUTER_HEADER_CREATION_ATTR_MAX - 1) enum { GTP5G_SDF_FILTER_ACTION_UNSPEC = 0, GTP5G_SDF_FILTER_PERMIT, __GTP5G_SDF_FILTER_ACTION_MAX, }; #define GTP5G_SDF_FILTER_ACTION_MAX (__GTP5G_SDF_FILTER_ACTION_MAX - 1) enum { GTP5G_SDF_FILTER_DIRECTION_UNSPEC = 0, GTP5G_SDF_FILTER_IN, GTP5G_SDF_FILTER_OUT, __GTP5G_SDF_FILTER_DIRECTION_MAX, }; #define GTP5G_SDF_FILTER_DIRECTION_MAX (__GTP5G_SDF_FILTER_DIRECTION_MAX - 1) /* ------------------------------------------------------------------ * QER * ------------------------------------------------------------------ * */ enum gtp5g_qer_attrs { /* gtp5g_device_attrs in this part */ GTP5G_QER_ID = 3, GTP5G_QER_GATE, GTP5G_QER_MBR, GTP5G_QER_GBR, GTP5G_QER_CORR_ID, GTP5G_QER_RQI, GTP5G_QER_QFI, GTP5G_QER_PPI, GTP5G_QER_RCSR, /* Not IEs in 3GPP Spec, for other purpose */ GTP5G_QER_RELATED_TO_PDR, __GTP5G_QER_ATTR_MAX, }; #define GTP5G_QER_ATTR_MAX (__GTP5G_QER_ATTR_MAX - 1) /* Nest in GTP5G_QER_MBR */ enum gtp5g_qer_mbr_attrs { GTP5G_QER_MBR_UL_HIGH32 = 1, GTP5G_QER_MBR_UL_LOW8, GTP5G_QER_MBR_DL_HIGH32, GTP5G_QER_MBR_DL_LOW8, __GTP5G_QER_MBR_ATTR_MAX, }; #define GTP5G_QER_MBR_ATTR_MAX (__GTP5G_QER_MBR_ATTR_MAX - 1) /* Nest in GTP5G_QER_GBR */ enum gtp5g_qer_gbr_attrs { GTP5G_QER_GBR_UL_HIGH32 = 1, GTP5G_QER_GBR_UL_LOW8, GTP5G_QER_GBR_DL_HIGH32, GTP5G_QER_GBR_DL_LOW8, __GTP5G_QER_GBR_ATTR_MAX, }; #define GTP5G_QER_GBR_ATTR_MAX (__GTP5G_QER_GBR_ATTR_MAX - 1) #endif /* _UAPI_LINUX_GTP_H_ */
tungdduy/funixCP
SourceCode/XeKhachTools/src/main/java/generator/ts/url/declare/Url.java
package generator.ts.url.declare; import lombok.Getter; import lombok.Setter; import java.util.ArrayList; import java.util.List; @Getter @Setter public class Url { private String config; private String key; private final List<Url> children = new ArrayList<>(); }
sin-ivan/AdiumPipeEvent
adium/Frameworks/libpurple.framework/Versions/2.10.7r5340f4a9bd6a/Headers/blist.h
/** * @file blist.h Buddy List API * @ingroup core * @see @ref blist-signals */ /* purple * * Purple is the legal property of its developers, whose names are too numerous * to list here. Please refer to the COPYRIGHT file distributed with this * source distribution. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA */ #ifndef _PURPLE_BLIST_H_ #define _PURPLE_BLIST_H_ /* I can't believe I let ChipX86 inspire me to write good code. -Sean */ #include <glib.h> /** @copydoc _PurpleBuddyList */ typedef struct _PurpleBuddyList PurpleBuddyList; /** @copydoc _PurpleBlistUiOps */ typedef struct _PurpleBlistUiOps PurpleBlistUiOps; /** @copydoc _PurpleBlistNode */ typedef struct _PurpleBlistNode PurpleBlistNode; /** @copydoc _PurpleChat */ typedef struct _PurpleChat PurpleChat; /** @copydoc _PurpleGroup */ typedef struct _PurpleGroup PurpleGroup; /** @copydoc _PurpleContact */ typedef struct _PurpleContact PurpleContact; /** @copydoc _PurpleBuddy */ typedef struct _PurpleBuddy PurpleBuddy; /**************************************************************************/ /* Enumerations */ /**************************************************************************/ typedef enum { PURPLE_BLIST_GROUP_NODE, PURPLE_BLIST_CONTACT_NODE, PURPLE_BLIST_BUDDY_NODE, PURPLE_BLIST_CHAT_NODE, PURPLE_BLIST_OTHER_NODE } PurpleBlistNodeType; #define PURPLE_BLIST_NODE_IS_CHAT(n) (purple_blist_node_get_type(n) == PURPLE_BLIST_CHAT_NODE) #define PURPLE_BLIST_NODE_IS_BUDDY(n) (purple_blist_node_get_type(n) == PURPLE_BLIST_BUDDY_NODE) #define PURPLE_BLIST_NODE_IS_CONTACT(n) (purple_blist_node_get_type(n) == PURPLE_BLIST_CONTACT_NODE) #define PURPLE_BLIST_NODE_IS_GROUP(n) (purple_blist_node_get_type(n) == PURPLE_BLIST_GROUP_NODE) #define PURPLE_BUDDY_IS_ONLINE(b) \ ((b) != NULL && purple_account_is_connected(purple_buddy_get_account(b)) && \ purple_presence_is_online(purple_buddy_get_presence(b))) typedef enum { PURPLE_BLIST_NODE_FLAG_NO_SAVE = 1 << 0 /**< node should not be saved with the buddy list */ } PurpleBlistNodeFlags; /** * @since 2.6.0 */ #define PURPLE_BLIST_NODE(obj) ((PurpleBlistNode *)(obj)) #define PURPLE_BLIST_NODE_HAS_FLAG(b, f) (purple_blist_node_get_flags((PurpleBlistNode*)(b)) & (f)) #define PURPLE_BLIST_NODE_SHOULD_SAVE(b) (! PURPLE_BLIST_NODE_HAS_FLAG(b, PURPLE_BLIST_NODE_FLAG_NO_SAVE)) #define PURPLE_BLIST_NODE_NAME(n) (purple_blist_node_get_type(n) == PURPLE_BLIST_CHAT_NODE ? purple_chat_get_name((PurpleChat*)n) : \ purple_blist_node_get_type(n) == PURPLE_BLIST_BUDDY_NODE ? purple_buddy_get_name((PurpleBuddy*)n) : NULL) /** * @since 2.6.0 */ #define PURPLE_GROUP(obj) ((PurpleGroup *)(obj)) /** * @since 2.6.0 */ #define PURPLE_CONTACT(obj) ((PurpleContact *)(obj)) /** * @since 2.6.0 */ #define PURPLE_BUDDY(obj) ((PurpleBuddy *)(obj)) /** * @since 2.6.0 */ #define PURPLE_CHAT(obj) ((PurpleChat *)(obj)) #include "account.h" #include "buddyicon.h" #include "media.h" #include "status.h" /**************************************************************************/ /* Data Structures */ /**************************************************************************/ #if !(defined PURPLE_HIDE_STRUCTS) || (defined _PURPLE_BLIST_C_) /** * A Buddy list node. This can represent a group, a buddy, or anything else. * This is a base class for PurpleBuddy, PurpleContact, PurpleGroup, and for * anything else that wants to put itself in the buddy list. */ struct _PurpleBlistNode { PurpleBlistNodeType type; /**< The type of node this is */ PurpleBlistNode *prev; /**< The sibling before this buddy. */ PurpleBlistNode *next; /**< The sibling after this buddy. */ PurpleBlistNode *parent; /**< The parent of this node */ PurpleBlistNode *child; /**< The child of this node */ GHashTable *settings; /**< per-node settings */ void *ui_data; /**< The UI can put data here. */ PurpleBlistNodeFlags flags; /**< The buddy flags */ }; /** * A buddy. This contains everything Purple will ever need to know about someone on the buddy list. Everything. */ struct _PurpleBuddy { PurpleBlistNode node; /**< The node that this buddy inherits from */ char *name; /**< The name of the buddy. */ char *alias; /**< The user-set alias of the buddy */ char *server_alias; /**< The server-specified alias of the buddy. (i.e. MSN "Friendly Names") */ void *proto_data; /**< This allows the prpl to associate whatever data it wants with a buddy */ PurpleBuddyIcon *icon; /**< The buddy icon. */ PurpleAccount *account; /**< the account this buddy belongs to */ PurplePresence *presence; PurpleMediaCaps media_caps; /**< The media capabilities of the buddy. */ }; /** * A contact. This contains everything Purple will ever need to know about a contact. */ struct _PurpleContact { PurpleBlistNode node; /**< The node that this contact inherits from. */ char *alias; /**< The user-set alias of the contact */ int totalsize; /**< The number of buddies in this contact */ int currentsize; /**< The number of buddies in this contact corresponding to online accounts */ int online; /**< The number of buddies in this contact who are currently online */ PurpleBuddy *priority; /**< The "top" buddy for this contact */ gboolean priority_valid; /**< Is priority valid? */ }; /** * A group. This contains everything Purple will ever need to know about a group. */ struct _PurpleGroup { PurpleBlistNode node; /**< The node that this group inherits from */ char *name; /**< The name of this group. */ int totalsize; /**< The number of chats and contacts in this group */ int currentsize; /**< The number of chats and contacts in this group corresponding to online accounts */ int online; /**< The number of chats and contacts in this group who are currently online */ }; /** * A chat. This contains everything Purple needs to put a chat room in the * buddy list. */ struct _PurpleChat { PurpleBlistNode node; /**< The node that this chat inherits from */ char *alias; /**< The display name of this chat. */ GHashTable *components; /**< the stuff the protocol needs to know to join the chat */ PurpleAccount *account; /**< The account this chat is attached to */ }; /** * The Buddy List */ struct _PurpleBuddyList { PurpleBlistNode *root; /**< The first node in the buddy list */ GHashTable *buddies; /**< Every buddy in this list */ void *ui_data; /**< UI-specific data. */ }; #endif /* PURPLE_HIDE_STRUCTS && PURPLE_BLIST_STRUCTS */ /** * Buddy list UI operations. * * Any UI representing a buddy list must assign a filled-out PurpleBlistUiOps * structure to the buddy list core. */ struct _PurpleBlistUiOps { void (*new_list)(PurpleBuddyList *list); /**< Sets UI-specific data on a buddy list. */ void (*new_node)(PurpleBlistNode *node); /**< Sets UI-specific data on a node. */ void (*show)(PurpleBuddyList *list); /**< The core will call this when it's finished doing its core stuff */ void (*update)(PurpleBuddyList *list, PurpleBlistNode *node); /**< This will update a node in the buddy list. */ void (*remove)(PurpleBuddyList *list, PurpleBlistNode *node); /**< This removes a node from the list */ void (*destroy)(PurpleBuddyList *list); /**< When the list is destroyed, this is called to destroy the UI. */ void (*set_visible)(PurpleBuddyList *list, gboolean show); /**< Hides or unhides the buddy list */ void (*request_add_buddy)(PurpleAccount *account, const char *username, const char *group, const char *alias); void (*request_add_chat)(PurpleAccount *account, PurpleGroup *group, const char *alias, const char *name); void (*request_add_group)(void); /** * This is called when a node has been modified and should be saved. * * Implementation of this UI op is OPTIONAL. If not implemented, it will * be set to a fallback function that saves data to blist.xml like in * previous libpurple versions. * * @param node The node which has been modified. * * @since 2.6.0. */ void (*save_node)(PurpleBlistNode *node); /** * Called when a node is about to be removed from the buddy list. * The UI op should update the relevant data structures to remove this * node (for example, removing a buddy from the group this node is in). * * Implementation of this UI op is OPTIONAL. If not implemented, it will * be set to a fallback function that saves data to blist.xml like in * previous libpurple versions. * * @param node The node which has been modified. * @since 2.6.0. */ void (*remove_node)(PurpleBlistNode *node); /** * Called to save all the data for an account. If the UI sets this, * the callback must save the privacy and buddy list data for an account. * If the account is NULL, save the data for all accounts. * * Implementation of this UI op is OPTIONAL. If not implemented, it will * be set to a fallback function that saves data to blist.xml like in * previous libpurple versions. * * @param account The account whose data to save. If NULL, save all data * for all accounts. * @since 2.6.0. */ void (*save_account)(PurpleAccount *account); void (*_purple_reserved1)(void); }; #ifdef __cplusplus extern "C" { #endif /**************************************************************************/ /** @name Buddy List API */ /**************************************************************************/ /*@{*/ /** * Creates a new buddy list * * @return The new buddy list. * @deprecated In 3.0.0, this will be handled by purple_blist_init() */ PurpleBuddyList *purple_blist_new(void); /** * Sets the main buddy list. * * @param blist The buddy list you want to use. * @deprecated In 3.0.0, this will be handled by purple_blist_init() */ void purple_set_blist(PurpleBuddyList *blist); /** * Returns the main buddy list. * * @return The main buddy list. */ PurpleBuddyList *purple_get_blist(void); /** * Returns the root node of the main buddy list. * * @return The root node. */ PurpleBlistNode *purple_blist_get_root(void); /** * Returns a list of every buddy in the list. Use of this function is * discouraged if you do not actually need every buddy in the list. Use * purple_find_buddies instead. * * @return A list of every buddy in the list. Caller is responsible for * freeing the list. * * @see purple_find_buddies * @since 2.6.0 */ GSList *purple_blist_get_buddies(void); /** * Returns the UI data for the list. * * @return The UI data for the list. * * @since 2.6.0 */ gpointer purple_blist_get_ui_data(void); /** * Sets the UI data for the list. * * @param ui_data The UI data for the list. * * @since 2.6.0 */ void purple_blist_set_ui_data(gpointer ui_data); /** * Returns the next node of a given node. This function is to be used to iterate * over the tree returned by purple_get_blist. * * @param node A node. * @param offline Whether to include nodes for offline accounts * @return The next node * @see purple_blist_node_get_parent * @see purple_blist_node_get_first_child * @see purple_blist_node_get_sibling_next * @see purple_blist_node_get_sibling_prev */ PurpleBlistNode *purple_blist_node_next(PurpleBlistNode *node, gboolean offline); /** * Returns the parent node of a given node. * * @param node A node. * @return The parent node. * @since 2.4.0 * @see purple_blist_node_get_first_child * @see purple_blist_node_get_sibling_next * @see purple_blist_node_get_sibling_prev * @see purple_blist_node_next */ PurpleBlistNode *purple_blist_node_get_parent(PurpleBlistNode *node); /** * Returns the the first child node of a given node. * * @param node A node. * @return The child node. * @since 2.4.0 * @see purple_blist_node_get_parent * @see purple_blist_node_get_sibling_next * @see purple_blist_node_get_sibling_prev * @see purple_blist_node_next */ PurpleBlistNode *purple_blist_node_get_first_child(PurpleBlistNode *node); /** * Returns the sibling node of a given node. * * @param node A node. * @return The sibling node. * @since 2.4.0 * @see purple_blist_node_get_parent * @see purple_blist_node_get_first_child * @see purple_blist_node_get_sibling_prev * @see purple_blist_node_next */ PurpleBlistNode *purple_blist_node_get_sibling_next(PurpleBlistNode *node); /** * Returns the previous sibling node of a given node. * * @param node A node. * @return The sibling node. * @since 2.4.0 * @see purple_blist_node_get_parent * @see purple_blist_node_get_first_child * @see purple_blist_node_get_sibling_next * @see purple_blist_node_next */ PurpleBlistNode *purple_blist_node_get_sibling_prev(PurpleBlistNode *node); /** * Returns the UI data of a given node. * * @param node The node. * @return The UI data. * @since 2.6.0 */ gpointer purple_blist_node_get_ui_data(const PurpleBlistNode *node); /** * Sets the UI data of a given node. * * @param node The node. * @param ui_data The UI data. * * @since 2.6.0 */ void purple_blist_node_set_ui_data(PurpleBlistNode *node, gpointer ui_data); /** * Shows the buddy list, creating a new one if necessary. */ void purple_blist_show(void); /** * Destroys the buddy list window. * * @deprecated The UI is responsible for cleaning up the * PurpleBuddyList->ui_data. purple_blist_uninit() will free the * PurpleBuddyList* itself. */ void purple_blist_destroy(void); /** * Hides or unhides the buddy list. * * @param show Whether or not to show the buddy list */ void purple_blist_set_visible(gboolean show); /** * Updates a buddy's status. * * This should only be called from within Purple. * * @param buddy The buddy whose status has changed. * @param old_status The status from which we are changing. */ void purple_blist_update_buddy_status(PurpleBuddy *buddy, PurpleStatus *old_status); /** * Updates a node's custom icon. * * @param node The PurpleBlistNode whose custom icon has changed. * * @since 2.5.0 */ void purple_blist_update_node_icon(PurpleBlistNode *node); #if !(defined PURPLE_DISABLE_DEPRECATED) || (defined _PURPLE_BLIST_C_) /** * Updates a buddy's icon. * * @param buddy The buddy whose buddy icon has changed * @deprecated Use purple_blist_update_node_icon() instead. */ void purple_blist_update_buddy_icon(PurpleBuddy *buddy); #endif /** * Renames a buddy in the buddy list. * * @param buddy The buddy whose name will be changed. * @param name The new name of the buddy. */ void purple_blist_rename_buddy(PurpleBuddy *buddy, const char *name); /** * Aliases a contact in the buddy list. * * @param contact The contact whose alias will be changed. * @param alias The contact's alias. */ void purple_blist_alias_contact(PurpleContact *contact, const char *alias); /** * Aliases a buddy in the buddy list. * * @param buddy The buddy whose alias will be changed. * @param alias The buddy's alias. */ void purple_blist_alias_buddy(PurpleBuddy *buddy, const char *alias); /** * Sets the server-sent alias of a buddy in the buddy list. * PRPLs should call serv_got_alias() instead of this. * * @param buddy The buddy whose alias will be changed. * @param alias The buddy's "official" alias. */ void purple_blist_server_alias_buddy(PurpleBuddy *buddy, const char *alias); /** * Aliases a chat in the buddy list. * * @param chat The chat whose alias will be changed. * @param alias The chat's new alias. */ void purple_blist_alias_chat(PurpleChat *chat, const char *alias); /** * Renames a group * * @param group The group to rename * @param name The new name */ void purple_blist_rename_group(PurpleGroup *group, const char *name); /** * Creates a new chat for the buddy list * * @param account The account this chat will get added to * @param alias The alias of the new chat * @param components The info the prpl needs to join the chat. The * hash function should be g_str_hash() and the * equal function should be g_str_equal(). * @return A newly allocated chat */ PurpleChat *purple_chat_new(PurpleAccount *account, const char *alias, GHashTable *components); /** * Destroys a chat * * @param chat The chat to destroy */ void purple_chat_destroy(PurpleChat *chat); /** * Adds a new chat to the buddy list. * * The chat will be inserted right after node or appended to the end * of group if node is NULL. If both are NULL, the buddy will be added to * the "Chats" group. * * @param chat The new chat who gets added * @param group The group to add the new chat to. * @param node The insertion point */ void purple_blist_add_chat(PurpleChat *chat, PurpleGroup *group, PurpleBlistNode *node); /** * Creates a new buddy. * * This function only creates the PurpleBuddy. Use purple_blist_add_buddy * to add the buddy to the list and purple_account_add_buddy to sync up * with the server. * * @param account The account this buddy will get added to * @param name The name of the new buddy * @param alias The alias of the new buddy (or NULL if unaliased) * @return A newly allocated buddy * * @see purple_account_add_buddy * @see purple_blist_add_buddy */ PurpleBuddy *purple_buddy_new(PurpleAccount *account, const char *name, const char *alias); /** * Destroys a buddy * * @param buddy The buddy to destroy */ void purple_buddy_destroy(PurpleBuddy *buddy); /** * Sets a buddy's icon. * * This should only be called from within Purple. You probably want to * call purple_buddy_icon_set_data(). * * @param buddy The buddy. * @param icon The buddy icon. * * @see purple_buddy_icon_set_data() */ void purple_buddy_set_icon(PurpleBuddy *buddy, PurpleBuddyIcon *icon); /** * Returns a buddy's account. * * @param buddy The buddy. * * @return The account */ PurpleAccount *purple_buddy_get_account(const PurpleBuddy *buddy); /** * Returns a buddy's name * * @param buddy The buddy. * * @return The name. */ const char *purple_buddy_get_name(const PurpleBuddy *buddy); /** * Returns a buddy's icon. * * @param buddy The buddy. * * @return The buddy icon. */ PurpleBuddyIcon *purple_buddy_get_icon(const PurpleBuddy *buddy); /** * Returns a buddy's protocol-specific data. * * This should only be called from the associated prpl. * * @param buddy The buddy. * @return The protocol data. * * @see purple_buddy_set_protocol_data() * @since 2.6.0 */ gpointer purple_buddy_get_protocol_data(const PurpleBuddy *buddy); /** * Sets a buddy's protocol-specific data. * * This should only be called from the associated prpl. * * @param buddy The buddy. * @param data The data. * * @see purple_buddy_get_protocol_data() * @since 2.6.0 */ void purple_buddy_set_protocol_data(PurpleBuddy *buddy, gpointer data); /** * Returns a buddy's contact. * * @param buddy The buddy. * * @return The buddy's contact. */ PurpleContact *purple_buddy_get_contact(PurpleBuddy *buddy); /** * Returns a buddy's presence. * * @param buddy The buddy. * * @return The buddy's presence. */ PurplePresence *purple_buddy_get_presence(const PurpleBuddy *buddy); /** * Gets the media caps from a buddy. * * @param buddy The buddy. * @return The media caps. * * @since 2.7.0 */ PurpleMediaCaps purple_buddy_get_media_caps(const PurpleBuddy *buddy); /** * Sets the media caps for a buddy. * * @param buddy The PurpleBuddy. * @param media_caps The PurpleMediaCaps. */ void purple_buddy_set_media_caps(PurpleBuddy *buddy, PurpleMediaCaps media_caps); /** * Adds a new buddy to the buddy list. * * The buddy will be inserted right after node or prepended to the * group if node is NULL. If both are NULL, the buddy will be added to * the "Buddies" group. * * @param buddy The new buddy who gets added * @param contact The optional contact to place the buddy in. * @param group The group to add the new buddy to. * @param node The insertion point. Pass in NULL to add the node as * the first child in the given group. */ void purple_blist_add_buddy(PurpleBuddy *buddy, PurpleContact *contact, PurpleGroup *group, PurpleBlistNode *node); /** * Creates a new group * * You can't have more than one group with the same name. Sorry. If you pass * this the name of a group that already exists, it will return that group. * * @param name The name of the new group * @return A new group struct */ PurpleGroup *purple_group_new(const char *name); /** * Destroys a group * * @param group The group to destroy */ void purple_group_destroy(PurpleGroup *group); /** * Adds a new group to the buddy list. * * The new group will be inserted after insert or prepended to the list if * node is NULL. * * @param group The group * @param node The insertion point */ void purple_blist_add_group(PurpleGroup *group, PurpleBlistNode *node); /** * Creates a new contact * * @return A new contact struct */ PurpleContact *purple_contact_new(void); /** * Destroys a contact * * @param contact The contact to destroy */ void purple_contact_destroy(PurpleContact *contact); /** * Gets the PurpleGroup from a PurpleContact * * @param contact The contact * @return The group * * @since 2.7.0 */ PurpleGroup *purple_contact_get_group(const PurpleContact *contact); /** * Adds a new contact to the buddy list. * * The new contact will be inserted after insert or prepended to the list if * node is NULL. * * @param contact The contact * @param group The group to add the contact to * @param node The insertion point */ void purple_blist_add_contact(PurpleContact *contact, PurpleGroup *group, PurpleBlistNode *node); /** * Merges two contacts * * All of the buddies from source will be moved to target * * @param source The contact to merge * @param node The place to merge to (a buddy or contact) */ void purple_blist_merge_contact(PurpleContact *source, PurpleBlistNode *node); /** * Returns the highest priority buddy for a given contact. * * @param contact The contact * @return The highest priority buddy */ PurpleBuddy *purple_contact_get_priority_buddy(PurpleContact *contact); #if !(defined PURPLE_DISABLE_DEPRECATED) || (defined _PURPLE_BLIST_C_) /** * Sets the alias for a contact. * * @param contact The contact * @param alias The alias to set, or NULL to unset * * @deprecated Use purple_blist_alias_contact() instead. */ void purple_contact_set_alias(PurpleContact *contact, const char *alias); #endif /** * Gets the alias for a contact. * * @param contact The contact * @return The alias, or NULL if it is not set. */ const char *purple_contact_get_alias(PurpleContact *contact); /** * Determines whether an account owns any buddies in a given contact * * @param contact The contact to search through. * @param account The account. * * @return TRUE if there are any buddies from account in the contact, or FALSE otherwise. */ gboolean purple_contact_on_account(PurpleContact *contact, PurpleAccount *account); /** * Invalidates the priority buddy so that the next call to * purple_contact_get_priority_buddy recomputes it. * * @param contact The contact */ void purple_contact_invalidate_priority_buddy(PurpleContact *contact); /** * Removes a buddy from the buddy list and frees the memory allocated to it. * This doesn't actually try to remove the buddy from the server list. * * @param buddy The buddy to be removed * * @see purple_account_remove_buddy */ void purple_blist_remove_buddy(PurpleBuddy *buddy); /** * Removes a contact, and any buddies it contains, and frees the memory * allocated to it. This calls purple_blist_remove_buddy and therefore * doesn't remove the buddies from the server list. * * @param contact The contact to be removed * * @see purple_blist_remove_buddy */ void purple_blist_remove_contact(PurpleContact *contact); /** * Removes a chat from the buddy list and frees the memory allocated to it. * * @param chat The chat to be removed */ void purple_blist_remove_chat(PurpleChat *chat); /** * Removes a group from the buddy list and frees the memory allocated to it and to * its children * * @param group The group to be removed */ void purple_blist_remove_group(PurpleGroup *group); /** * Returns the alias of a buddy. * * @param buddy The buddy whose name will be returned. * @return The alias (if set), server alias (if set), * or NULL. */ const char *purple_buddy_get_alias_only(PurpleBuddy *buddy); /** * Gets the server alias for a buddy. * * @param buddy The buddy whose name will be returned * @return The server alias, or NULL if it is not set. */ const char *purple_buddy_get_server_alias(PurpleBuddy *buddy); /** * Returns the correct name to display for a buddy, taking the contact alias * into account. In order of precedence: the buddy's alias; the buddy's * contact alias; the buddy's server alias; the buddy's user name. * * @param buddy The buddy whose name will be returned * @return The appropriate name or alias, or NULL. * */ const char *purple_buddy_get_contact_alias(PurpleBuddy *buddy); #if !(defined PURPLE_DISABLE_DEPRECATED) || (defined _PURPLE_BLIST_C_) /** * Returns the correct alias for this user, ignoring server aliases. Used * when a user-recognizable name is required. In order: buddy's alias; buddy's * contact alias; buddy's user name. * * @param buddy The buddy whose alias will be returned. * @return The appropriate name or alias. * @deprecated Try purple_buddy_get_alias(), if server aliases are okay. */ const char *purple_buddy_get_local_alias(PurpleBuddy *buddy); #endif /** * Returns the correct name to display for a buddy. In order of precedence: * the buddy's alias; the buddy's server alias; the buddy's contact alias; * the buddy's user name. * * @param buddy The buddy whose name will be returned. * @return The appropriate name or alias, or NULL */ const char *purple_buddy_get_alias(PurpleBuddy *buddy); /** * Returns the local alias for the buddy, or @c NULL if none exists. * * @param buddy The buddy * @return The local alias for the buddy * * @since 2.6.0 */ const char *purple_buddy_get_local_buddy_alias(PurpleBuddy *buddy); /** * Returns the correct name to display for a blist chat. * * @param chat The chat whose name will be returned. * @return The alias (if set), or first component value. */ const char *purple_chat_get_name(PurpleChat *chat); /** * Finds the buddy struct given a name and an account * * @param account The account this buddy belongs to * @param name The buddy's name * @return The buddy or NULL if the buddy does not exist */ PurpleBuddy *purple_find_buddy(PurpleAccount *account, const char *name); /** * Finds the buddy struct given a name, an account, and a group * * @param account The account this buddy belongs to * @param name The buddy's name * @param group The group to look in * @return The buddy or NULL if the buddy does not exist in the group */ PurpleBuddy *purple_find_buddy_in_group(PurpleAccount *account, const char *name, PurpleGroup *group); /** * Finds all PurpleBuddy structs given a name and an account * * @param account The account this buddy belongs to * @param name The buddy's name (or NULL to return all buddies for the account) * * @return A GSList of buddies (which must be freed), or NULL if the buddy doesn't exist */ GSList *purple_find_buddies(PurpleAccount *account, const char *name); /** * Finds a group by name * * @param name The group's name * @return The group or NULL if the group does not exist */ PurpleGroup *purple_find_group(const char *name); /** * Finds a chat by name. * * @param account The chat's account. * @param name The chat's name. * * @return The chat, or @c NULL if the chat does not exist. */ PurpleChat *purple_blist_find_chat(PurpleAccount *account, const char *name); /** * Returns the group of which the chat is a member. * * @param chat The chat. * * @return The parent group, or @c NULL if the chat is not in a group. */ PurpleGroup *purple_chat_get_group(PurpleChat *chat); /** * Returns the account the chat belongs to. * * @param chat The chat. * * @return The account the chat belongs to. * * @since 2.4.0 */ PurpleAccount *purple_chat_get_account(PurpleChat *chat); /** * Get a hashtable containing information about a chat. * * @param chat The chat. * * @constreturn The hashtable. * * @since 2.4.0 */ GHashTable *purple_chat_get_components(PurpleChat *chat); /** * Returns the group of which the buddy is a member. * * @param buddy The buddy * @return The group or NULL if the buddy is not in a group */ PurpleGroup *purple_buddy_get_group(PurpleBuddy *buddy); /** * Returns a list of accounts that have buddies in this group * * @param g The group * * @return A GSList of accounts (which must be freed), or NULL if the group * has no accounts. */ GSList *purple_group_get_accounts(PurpleGroup *g); /** * Determines whether an account owns any buddies in a given group * * @param g The group to search through. * @param account The account. * * @return TRUE if there are any buddies in the group, or FALSE otherwise. */ gboolean purple_group_on_account(PurpleGroup *g, PurpleAccount *account); /** * Returns the name of a group. * * @param group The group. * * @return The name of the group. */ const char *purple_group_get_name(PurpleGroup *group); /** * Called when an account connects. Tells the UI to update all the * buddies. * * @param account The account */ void purple_blist_add_account(PurpleAccount *account); /** * Called when an account disconnects. Sets the presence of all the buddies to 0 * and tells the UI to update them. * * @param account The account */ void purple_blist_remove_account(PurpleAccount *account); /** * Determines the total size of a group * * @param group The group * @param offline Count buddies in offline accounts * @return The number of buddies in the group */ int purple_blist_get_group_size(PurpleGroup *group, gboolean offline); /** * Determines the number of online buddies in a group * * @param group The group * @return The number of online buddies in the group, or 0 if the group is NULL */ int purple_blist_get_group_online_count(PurpleGroup *group); /*@}*/ /****************************************************************************************/ /** @name Buddy list file management API */ /****************************************************************************************/ /** * Loads the buddy list from ~/.purple/blist.xml. */ void purple_blist_load(void); /** * Schedule a save of the blist.xml file. This is used by the privacy * API whenever the privacy settings are changed. If you make a change * to blist.xml using one of the functions in the buddy list API, then * the buddy list is saved automatically, so you should not need to * call this. */ void purple_blist_schedule_save(void); /** * Requests from the user information needed to add a buddy to the * buddy list. * * @param account The account the buddy is added to. * @param username The username of the buddy. * @param group The name of the group to place the buddy in. * @param alias The optional alias for the buddy. */ void purple_blist_request_add_buddy(PurpleAccount *account, const char *username, const char *group, const char *alias); /** * Requests from the user information needed to add a chat to the * buddy list. * * @param account The account the buddy is added to. * @param group The optional group to add the chat to. * @param alias The optional alias for the chat. * @param name The required chat name. */ void purple_blist_request_add_chat(PurpleAccount *account, PurpleGroup *group, const char *alias, const char *name); /** * Requests from the user information needed to add a group to the * buddy list. */ void purple_blist_request_add_group(void); /** * Associates a boolean with a node in the buddy list * * @param node The node to associate the data with * @param key The identifier for the data * @param value The value to set */ void purple_blist_node_set_bool(PurpleBlistNode *node, const char *key, gboolean value); /** * Retrieves a named boolean setting from a node in the buddy list * * @param node The node to retrieve the data from * @param key The identifier of the data * * @return The value, or FALSE if there is no setting */ gboolean purple_blist_node_get_bool(PurpleBlistNode *node, const char *key); /** * Associates an integer with a node in the buddy list * * @param node The node to associate the data with * @param key The identifier for the data * @param value The value to set */ void purple_blist_node_set_int(PurpleBlistNode *node, const char *key, int value); /** * Retrieves a named integer setting from a node in the buddy list * * @param node The node to retrieve the data from * @param key The identifier of the data * * @return The value, or 0 if there is no setting */ int purple_blist_node_get_int(PurpleBlistNode *node, const char *key); /** * Associates a string with a node in the buddy list * * @param node The node to associate the data with * @param key The identifier for the data * @param value The value to set */ void purple_blist_node_set_string(PurpleBlistNode *node, const char *key, const char *value); /** * Retrieves a named string setting from a node in the buddy list * * @param node The node to retrieve the data from * @param key The identifier of the data * * @return The value, or NULL if there is no setting */ const char *purple_blist_node_get_string(PurpleBlistNode *node, const char *key); /** * Removes a named setting from a blist node * * @param node The node from which to remove the setting * @param key The name of the setting */ void purple_blist_node_remove_setting(PurpleBlistNode *node, const char *key); /** * Set the flags for the given node. Setting a node's flags will overwrite * the old flags, so if you want to save them, you must first call * purple_blist_node_get_flags and modify that appropriately. * * @param node The node on which to set the flags. * @param flags The flags to set. This is a bitmask. */ void purple_blist_node_set_flags(PurpleBlistNode *node, PurpleBlistNodeFlags flags); /** * Get the current flags on a given node. * * @param node The node from which to get the flags. * * @return The flags on the node. This is a bitmask. */ PurpleBlistNodeFlags purple_blist_node_get_flags(PurpleBlistNode *node); /** * Get the type of a given node. * * @param node The node. * * @return The type of the node. * * @since 2.1.0 */ PurpleBlistNodeType purple_blist_node_get_type(PurpleBlistNode *node); /*@}*/ /** * Retrieves the extended menu items for a buddy list node. * @param n The blist node for which to obtain the extended menu items. * @return A list of PurpleMenuAction items, as harvested by the * blist-node-extended-menu signal. */ GList *purple_blist_node_get_extended_menu(PurpleBlistNode *n); /**************************************************************************/ /** @name UI Registration Functions */ /**************************************************************************/ /*@{*/ /** * Sets the UI operations structure to be used for the buddy list. * * @param ops The ops struct. */ void purple_blist_set_ui_ops(PurpleBlistUiOps *ops); /** * Returns the UI operations structure to be used for the buddy list. * * @return The UI operations structure. */ PurpleBlistUiOps *purple_blist_get_ui_ops(void); /*@}*/ /**************************************************************************/ /** @name Buddy List Subsystem */ /**************************************************************************/ /*@{*/ /** * Returns the handle for the buddy list subsystem. * * @return The buddy list subsystem handle. */ void *purple_blist_get_handle(void); /** * Initializes the buddy list subsystem. */ void purple_blist_init(void); /** * Uninitializes the buddy list subsystem. */ void purple_blist_uninit(void); /*@}*/ #ifdef __cplusplus } #endif #endif /* _PURPLE_BLIST_H_ */
Acrylic125/AcrylicMinecraftLib
Universal/src/main/java/com/acrylic/universal/utils/MetadataMap.java
package com.acrylic.universal.utils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.Map; import java.util.function.BiConsumer; public interface MetadataMap<T extends Metadata> { @NotNull Map<String, T> getMetadataMap(); @Nullable @SuppressWarnings("all") default <E extends T> E getMetadata(@NotNull String key, Class<E> ofType) { T metadata = getMetadataMap().get(key); return (ofType.isInstance(metadata)) ? (E) metadata : null; } @Nullable default T getMetadataOrDefault(@NotNull String key, @NotNull T defaultValue) { return getMetadataMap().getOrDefault(key, defaultValue); } default void addMetadata(@NotNull T value) { addMetadata(value.getMetadataName(), value); } default void addMetadata(@NotNull T... values) { for (T value : values) addMetadata(value); } default void addMetadata(@NotNull Collection<T> values) { for (T value : values) addMetadata(value); } default void addMetadata(@NotNull String key, @NotNull T value) { getMetadataMap().put(key, value); } default void iterateMetadata(@NotNull BiConsumer<String, T> action) { getMetadataMap().forEach(action); } default void clear() { getMetadataMap().clear(); } }
gouline/terraform-provider-snowflake
pkg/datasources/external_functions.go
<gh_stars>100-1000 package datasources import ( "database/sql" "fmt" "log" "github.com/chanzuckerberg/terraform-provider-snowflake/pkg/snowflake" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) var externalFunctionsSchema = map[string]*schema.Schema{ "database": { Type: schema.TypeString, Required: true, Description: "The database from which to return the schemas from.", }, "schema": { Type: schema.TypeString, Required: true, Description: "The schema from which to return the external functions from.", }, "external_functions": { Type: schema.TypeList, Computed: true, Description: "The external functions in the schema", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, Computed: true, }, "database": { Type: schema.TypeString, Computed: true, }, "schema": { Type: schema.TypeString, Computed: true, }, "comment": { Type: schema.TypeString, Optional: true, Computed: true, }, "language": { Type: schema.TypeString, Optional: true, Computed: true, }, }, }, }, } func ExternalFunctions() *schema.Resource { return &schema.Resource{ Read: ReadExternalFunctions, Schema: externalFunctionsSchema, } } func ReadExternalFunctions(d *schema.ResourceData, meta interface{}) error { db := meta.(*sql.DB) databaseName := d.Get("database").(string) schemaName := d.Get("schema").(string) currentExternalFunctions, err := snowflake.ListExternalFunctions(databaseName, schemaName, db) if err == sql.ErrNoRows { // If not found, mark resource to be removed from statefile during apply or refresh log.Printf("[DEBUG] external functions in schema (%s) not found", d.Id()) d.SetId("") return nil } else if err != nil { log.Printf("[DEBUG] unable to parse external functions in schema (%s)", d.Id()) d.SetId("") return nil } externalFunctions := []map[string]interface{}{} for _, externalFunction := range currentExternalFunctions { externalFunctionMap := map[string]interface{}{} externalFunctionMap["name"] = externalFunction.ExternalFunctionName.String externalFunctionMap["database"] = externalFunction.DatabaseName.String externalFunctionMap["schema"] = externalFunction.SchemaName.String externalFunctionMap["comment"] = externalFunction.Comment.String externalFunctionMap["language"] = externalFunction.Language.String externalFunctions = append(externalFunctions, externalFunctionMap) } d.SetId(fmt.Sprintf(`%v|%v`, databaseName, schemaName)) return d.Set("external_functions", externalFunctions) }
masami256/dfly-3.0.2-bhyve
sys/dev/netif/iwn/if_iwn.c
/*- * Copyright (c) 2007-2009 * <NAME> <<EMAIL>> * Copyright (c) 2008 * <NAME> <<EMAIL>> * Copyright (c) 2008 <NAME>, Errno Consulting * * 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. */ /* * Driver for Intel WiFi Link 4965 and 1000/5000/6000 Series 802.11 network * adapters. */ /* $FreeBSD$ */ #include <sys/param.h> #include <sys/sockio.h> #include <sys/sysctl.h> #include <sys/mbuf.h> #include <sys/kernel.h> #include <sys/socket.h> #include <sys/systm.h> #include <sys/malloc.h> #include <sys/bus.h> #include <sys/rman.h> #include <sys/endian.h> #include <sys/firmware.h> #include <sys/limits.h> #include <sys/module.h> #include <sys/queue.h> #include <sys/taskqueue.h> #include <sys/libkern.h> #include <sys/bus.h> #include <sys/resource.h> #include <machine/clock.h> #include <bus/pci/pcireg.h> #include <bus/pci/pcivar.h> #include <net/bpf.h> #include <net/if.h> #include <net/if_arp.h> #include <net/ifq_var.h> #include <net/ethernet.h> #include <net/if_dl.h> #include <net/if_media.h> #include <net/if_types.h> #include <netinet/in.h> #include <netinet/in_systm.h> #include <netinet/in_var.h> #include <netinet/if_ether.h> #include <netinet/ip.h> #include <netproto/802_11/ieee80211_var.h> #include <netproto/802_11/ieee80211_radiotap.h> #include <netproto/802_11/ieee80211_regdomain.h> #include <netproto/802_11/ieee80211_ratectl.h> #include "if_iwnreg.h" #include "if_iwnvar.h" static int iwn_pci_probe(device_t); static int iwn_pci_attach(device_t); static const struct iwn_hal *iwn_hal_attach(struct iwn_softc *); static void iwn_radiotap_attach(struct iwn_softc *); static struct ieee80211vap *iwn_vap_create(struct ieee80211com *, const char name[IFNAMSIZ], int unit, int opmode, int flags, const uint8_t bssid[IEEE80211_ADDR_LEN], const uint8_t mac[IEEE80211_ADDR_LEN]); static void iwn_vap_delete(struct ieee80211vap *); static int iwn_cleanup(device_t); static int iwn_pci_detach(device_t); static int iwn_nic_lock(struct iwn_softc *); static int iwn_eeprom_lock(struct iwn_softc *); static int iwn_init_otprom(struct iwn_softc *); static int iwn_read_prom_data(struct iwn_softc *, uint32_t, void *, int); static void iwn_dma_map_addr(void *, bus_dma_segment_t *, int, int); static int iwn_dma_contig_alloc(struct iwn_softc *, struct iwn_dma_info *, void **, bus_size_t, bus_size_t, int); static void iwn_dma_contig_free(struct iwn_dma_info *); static int iwn_alloc_sched(struct iwn_softc *); static void iwn_free_sched(struct iwn_softc *); static int iwn_alloc_kw(struct iwn_softc *); static void iwn_free_kw(struct iwn_softc *); static int iwn_alloc_ict(struct iwn_softc *); static void iwn_free_ict(struct iwn_softc *); static int iwn_alloc_fwmem(struct iwn_softc *); static void iwn_free_fwmem(struct iwn_softc *); static int iwn_alloc_rx_ring(struct iwn_softc *, struct iwn_rx_ring *); static void iwn_reset_rx_ring(struct iwn_softc *, struct iwn_rx_ring *); static void iwn_free_rx_ring(struct iwn_softc *, struct iwn_rx_ring *); static int iwn_alloc_tx_ring(struct iwn_softc *, struct iwn_tx_ring *, int); static void iwn_reset_tx_ring(struct iwn_softc *, struct iwn_tx_ring *); static void iwn_free_tx_ring(struct iwn_softc *, struct iwn_tx_ring *); static void iwn5000_ict_reset(struct iwn_softc *); static int iwn_read_eeprom(struct iwn_softc *, uint8_t macaddr[IEEE80211_ADDR_LEN]); static void iwn4965_read_eeprom(struct iwn_softc *); static void iwn4965_print_power_group(struct iwn_softc *, int); static void iwn5000_read_eeprom(struct iwn_softc *); static uint32_t iwn_eeprom_channel_flags(struct iwn_eeprom_chan *); static void iwn_read_eeprom_band(struct iwn_softc *, int); #if 0 /* HT */ static void iwn_read_eeprom_ht40(struct iwn_softc *, int); #endif static void iwn_read_eeprom_channels(struct iwn_softc *, int, uint32_t); static void iwn_read_eeprom_enhinfo(struct iwn_softc *); static struct ieee80211_node *iwn_node_alloc(struct ieee80211vap *, const uint8_t mac[IEEE80211_ADDR_LEN]); static void iwn_newassoc(struct ieee80211_node *, int); static int iwn_media_change(struct ifnet *); static int iwn_newstate(struct ieee80211vap *, enum ieee80211_state, int); static void iwn_rx_phy(struct iwn_softc *, struct iwn_rx_desc *, struct iwn_rx_data *); static void iwn_timer_callout(void *); static void iwn_calib_reset(struct iwn_softc *); static void iwn_rx_done(struct iwn_softc *, struct iwn_rx_desc *, struct iwn_rx_data *); #if 0 /* HT */ static void iwn_rx_compressed_ba(struct iwn_softc *, struct iwn_rx_desc *, struct iwn_rx_data *); #endif static void iwn5000_rx_calib_results(struct iwn_softc *, struct iwn_rx_desc *, struct iwn_rx_data *); static void iwn_rx_statistics(struct iwn_softc *, struct iwn_rx_desc *, struct iwn_rx_data *); static void iwn4965_tx_done(struct iwn_softc *, struct iwn_rx_desc *, struct iwn_rx_data *); static void iwn5000_tx_done(struct iwn_softc *, struct iwn_rx_desc *, struct iwn_rx_data *); static void iwn_tx_done(struct iwn_softc *, struct iwn_rx_desc *, int, uint8_t); static void iwn_cmd_done(struct iwn_softc *, struct iwn_rx_desc *); static void iwn_notif_intr(struct iwn_softc *); static void iwn_wakeup_intr(struct iwn_softc *); static void iwn_rftoggle_intr(struct iwn_softc *); static void iwn_fatal_intr(struct iwn_softc *); static void iwn_intr(void *); static void iwn4965_update_sched(struct iwn_softc *, int, int, uint8_t, uint16_t); static void iwn5000_update_sched(struct iwn_softc *, int, int, uint8_t, uint16_t); #ifdef notyet static void iwn5000_reset_sched(struct iwn_softc *, int, int); #endif static uint8_t iwn_plcp_signal(int); static int iwn_tx_data(struct iwn_softc *, struct mbuf *, struct ieee80211_node *, struct iwn_tx_ring *); static int iwn_raw_xmit(struct ieee80211_node *, struct mbuf *, const struct ieee80211_bpf_params *); static void iwn_start(struct ifnet *); static void iwn_start_locked(struct ifnet *); static void iwn_watchdog(struct iwn_softc *sc); static int iwn_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *); static int iwn_cmd(struct iwn_softc *, int, const void *, int, int); static int iwn4965_add_node(struct iwn_softc *, struct iwn_node_info *, int); static int iwn5000_add_node(struct iwn_softc *, struct iwn_node_info *, int); static int iwn_set_link_quality(struct iwn_softc *, uint8_t, int); static int iwn_add_broadcast_node(struct iwn_softc *, int); static int iwn_wme_update(struct ieee80211com *); static void iwn_update_mcast(struct ifnet *); static void iwn_set_led(struct iwn_softc *, uint8_t, uint8_t, uint8_t); static int iwn_set_critical_temp(struct iwn_softc *); static int iwn_set_timing(struct iwn_softc *, struct ieee80211_node *); static void iwn4965_power_calibration(struct iwn_softc *, int); static int iwn4965_set_txpower(struct iwn_softc *, struct ieee80211_channel *, int); static int iwn5000_set_txpower(struct iwn_softc *, struct ieee80211_channel *, int); static int iwn4965_get_rssi(struct iwn_softc *, struct iwn_rx_stat *); static int iwn5000_get_rssi(struct iwn_softc *, struct iwn_rx_stat *); static int iwn_get_noise(const struct iwn_rx_general_stats *); static int iwn4965_get_temperature(struct iwn_softc *); static int iwn5000_get_temperature(struct iwn_softc *); static int iwn_init_sensitivity(struct iwn_softc *); static void iwn_collect_noise(struct iwn_softc *, const struct iwn_rx_general_stats *); static int iwn4965_init_gains(struct iwn_softc *); static int iwn5000_init_gains(struct iwn_softc *); static int iwn4965_set_gains(struct iwn_softc *); static int iwn5000_set_gains(struct iwn_softc *); static void iwn_tune_sensitivity(struct iwn_softc *, const struct iwn_rx_stats *); static int iwn_send_sensitivity(struct iwn_softc *); static int iwn_set_pslevel(struct iwn_softc *, int, int, int); static int iwn_config(struct iwn_softc *); static int iwn_scan(struct iwn_softc *); static int iwn_auth(struct iwn_softc *, struct ieee80211vap *vap); static int iwn_run(struct iwn_softc *, struct ieee80211vap *vap); #if 0 /* HT */ static int iwn_ampdu_rx_start(struct ieee80211com *, struct ieee80211_node *, uint8_t); static void iwn_ampdu_rx_stop(struct ieee80211com *, struct ieee80211_node *, uint8_t); static int iwn_ampdu_tx_start(struct ieee80211com *, struct ieee80211_node *, uint8_t); static void iwn_ampdu_tx_stop(struct ieee80211com *, struct ieee80211_node *, uint8_t); static void iwn4965_ampdu_tx_start(struct iwn_softc *, struct ieee80211_node *, uint8_t, uint16_t); static void iwn4965_ampdu_tx_stop(struct iwn_softc *, uint8_t, uint16_t); static void iwn5000_ampdu_tx_start(struct iwn_softc *, struct ieee80211_node *, uint8_t, uint16_t); static void iwn5000_ampdu_tx_stop(struct iwn_softc *, uint8_t, uint16_t); #endif static int iwn5000_query_calibration(struct iwn_softc *); static int iwn5000_send_calibration(struct iwn_softc *); static int iwn5000_send_wimax_coex(struct iwn_softc *); static int iwn4965_post_alive(struct iwn_softc *); static int iwn5000_post_alive(struct iwn_softc *); static int iwn4965_load_bootcode(struct iwn_softc *, const uint8_t *, int); static int iwn4965_load_firmware(struct iwn_softc *); static int iwn5000_load_firmware_section(struct iwn_softc *, uint32_t, const uint8_t *, int); static int iwn5000_load_firmware(struct iwn_softc *); static int iwn_read_firmware(struct iwn_softc *); static int iwn_clock_wait(struct iwn_softc *); static int iwn_apm_init(struct iwn_softc *); static void iwn_apm_stop_master(struct iwn_softc *); static void iwn_apm_stop(struct iwn_softc *); static int iwn4965_nic_config(struct iwn_softc *); static int iwn5000_nic_config(struct iwn_softc *); static int iwn_hw_prepare(struct iwn_softc *); static int iwn_hw_init(struct iwn_softc *); static void iwn_hw_stop(struct iwn_softc *); static void iwn_init_locked(struct iwn_softc *); static void iwn_init(void *); static void iwn_stop_locked(struct iwn_softc *); static void iwn_stop(struct iwn_softc *); static void iwn_scan_start(struct ieee80211com *); static void iwn_scan_end(struct ieee80211com *); static void iwn_set_channel(struct ieee80211com *); static void iwn_scan_curchan(struct ieee80211_scan_state *, unsigned long); static void iwn_scan_mindwell(struct ieee80211_scan_state *); static struct iwn_eeprom_chan *iwn_find_eeprom_channel(struct iwn_softc *, struct ieee80211_channel *); static int iwn_setregdomain(struct ieee80211com *, struct ieee80211_regdomain *, int, struct ieee80211_channel []); static void iwn_hw_reset_task(void *, int); static void iwn_radio_on_task(void *, int); static void iwn_radio_off_task(void *, int); static void iwn_sysctlattach(struct iwn_softc *); static int iwn_pci_shutdown(device_t); static int iwn_pci_suspend(device_t); static int iwn_pci_resume(device_t); #define IWN_DEBUG #ifdef IWN_DEBUG enum { IWN_DEBUG_XMIT = 0x00000001, /* basic xmit operation */ IWN_DEBUG_RECV = 0x00000002, /* basic recv operation */ IWN_DEBUG_STATE = 0x00000004, /* 802.11 state transitions */ IWN_DEBUG_TXPOW = 0x00000008, /* tx power processing */ IWN_DEBUG_RESET = 0x00000010, /* reset processing */ IWN_DEBUG_OPS = 0x00000020, /* iwn_ops processing */ IWN_DEBUG_BEACON = 0x00000040, /* beacon handling */ IWN_DEBUG_WATCHDOG = 0x00000080, /* watchdog timeout */ IWN_DEBUG_INTR = 0x00000100, /* ISR */ IWN_DEBUG_CALIBRATE = 0x00000200, /* periodic calibration */ IWN_DEBUG_NODE = 0x00000400, /* node management */ IWN_DEBUG_LED = 0x00000800, /* led management */ IWN_DEBUG_CMD = 0x00001000, /* cmd submission */ IWN_DEBUG_FATAL = 0x80000000, /* fatal errors */ IWN_DEBUG_ANY = 0xffffffff }; #define DPRINTF(sc, m, fmt, ...) do { \ if (sc->sc_debug & (m)) \ kprintf(fmt, __VA_ARGS__); \ } while (0) static const char *iwn_intr_str(uint8_t); #else #define DPRINTF(sc, m, fmt, ...) do { (void) sc; } while (0) #endif struct iwn_ident { uint16_t vendor; uint16_t device; const char *name; }; static const struct iwn_ident iwn_ident_table [] = { { 0x8086, 0x4229, "Intel(R) PRO/Wireless 4965BGN" }, { 0x8086, 0x422D, "Intel(R) PRO/Wireless 4965BGN" }, { 0x8086, 0x4230, "Intel(R) PRO/Wireless 4965BGN" }, { 0x8086, 0x4233, "Intel(R) PRO/Wireless 4965BGN" }, { 0x8086, 0x4232, "Intel(R) PRO/Wireless 5100" }, { 0x8086, 0x4237, "Intel(R) PRO/Wireless 5100" }, { 0x8086, 0x423C, "Intel(R) PRO/Wireless 5150" }, { 0x8086, 0x423D, "Intel(R) PRO/Wireless 5150" }, { 0x8086, 0x4235, "Intel(R) PRO/Wireless 5300" }, { 0x8086, 0x4236, "Intel(R) PRO/Wireless 5300" }, { 0x8086, 0x423A, "Intel(R) PRO/Wireless 5350" }, { 0x8086, 0x423B, "Intel(R) PRO/Wireless 5350" }, { 0x8086, 0x0083, "Intel(R) PRO/Wireless 1000" }, { 0x8086, 0x0084, "Intel(R) PRO/Wireless 1000" }, { 0x8086, 0x008D, "Intel(R) PRO/Wireless 6000" }, { 0x8086, 0x008E, "Intel(R) PRO/Wireless 6000" }, { 0x8086, 0x4238, "Intel(R) PRO/Wireless 6000" }, { 0x8086, 0x4239, "Intel(R) PRO/Wireless 6000" }, { 0x8086, 0x422B, "Intel(R) PRO/Wireless 6000" }, { 0x8086, 0x422C, "Intel(R) PRO/Wireless 6000" }, { 0x8086, 0x0086, "Intel(R) PRO/Wireless 6050" }, { 0x8086, 0x0087, "Intel(R) PRO/Wireless 6050" }, { 0, 0, NULL } }; static const struct iwn_hal iwn4965_hal = { iwn4965_load_firmware, iwn4965_read_eeprom, iwn4965_post_alive, iwn4965_nic_config, iwn4965_update_sched, iwn4965_get_temperature, iwn4965_get_rssi, iwn4965_set_txpower, iwn4965_init_gains, iwn4965_set_gains, iwn4965_add_node, iwn4965_tx_done, #if 0 /* HT */ iwn4965_ampdu_tx_start, iwn4965_ampdu_tx_stop, #endif IWN4965_NTXQUEUES, IWN4965_NDMACHNLS, IWN4965_ID_BROADCAST, IWN4965_RXONSZ, IWN4965_SCHEDSZ, IWN4965_FW_TEXT_MAXSZ, IWN4965_FW_DATA_MAXSZ, IWN4965_FWSZ, IWN4965_SCHED_TXFACT }; static const struct iwn_hal iwn5000_hal = { iwn5000_load_firmware, iwn5000_read_eeprom, iwn5000_post_alive, iwn5000_nic_config, iwn5000_update_sched, iwn5000_get_temperature, iwn5000_get_rssi, iwn5000_set_txpower, iwn5000_init_gains, iwn5000_set_gains, iwn5000_add_node, iwn5000_tx_done, #if 0 /* HT */ iwn5000_ampdu_tx_start, iwn5000_ampdu_tx_stop, #endif IWN5000_NTXQUEUES, IWN5000_NDMACHNLS, IWN5000_ID_BROADCAST, IWN5000_RXONSZ, IWN5000_SCHEDSZ, IWN5000_FW_TEXT_MAXSZ, IWN5000_FW_DATA_MAXSZ, IWN5000_FWSZ, IWN5000_SCHED_TXFACT }; static int iwn_pci_probe(device_t dev) { const struct iwn_ident *ident; /* no wlan serializer needed */ for (ident = iwn_ident_table; ident->name != NULL; ident++) { if (pci_get_vendor(dev) == ident->vendor && pci_get_device(dev) == ident->device) { device_set_desc(dev, ident->name); return 0; } } return ENXIO; } static int iwn_pci_attach(device_t dev) { struct iwn_softc *sc = (struct iwn_softc *)device_get_softc(dev); struct ieee80211com *ic; struct ifnet *ifp; const struct iwn_hal *hal; uint32_t tmp; int i, error; #ifdef OLD_MSI int result; #endif uint8_t macaddr[IEEE80211_ADDR_LEN]; wlan_serialize_enter(); sc->sc_dev = dev; sc->sc_dmat = NULL; if (bus_dma_tag_create(sc->sc_dmat, 1, 0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, BUS_SPACE_MAXSIZE, IWN_MAX_SCATTER, BUS_SPACE_MAXSIZE, BUS_DMA_ALLOCNOW, &sc->sc_dmat)) { device_printf(dev, "cannot allocate DMA tag\n"); error = ENOMEM; goto fail; } /* prepare sysctl tree for use in sub modules */ sysctl_ctx_init(&sc->sc_sysctl_ctx); sc->sc_sysctl_tree = SYSCTL_ADD_NODE(&sc->sc_sysctl_ctx, SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO, device_get_nameunit(sc->sc_dev), CTLFLAG_RD, 0, ""); /* * Get the offset of the PCI Express Capability Structure in PCI * Configuration Space. */ error = pci_find_extcap(dev, PCIY_EXPRESS, &sc->sc_cap_off); if (error != 0) { device_printf(dev, "PCIe capability structure not found!\n"); goto fail2; } /* Clear device-specific "PCI retry timeout" register (41h). */ pci_write_config(dev, 0x41, 0, 1); /* Hardware bug workaround. */ tmp = pci_read_config(dev, PCIR_COMMAND, 1); if (tmp & PCIM_CMD_INTxDIS) { DPRINTF(sc, IWN_DEBUG_RESET, "%s: PCIe INTx Disable set\n", __func__); tmp &= ~PCIM_CMD_INTxDIS; pci_write_config(dev, PCIR_COMMAND, tmp, 1); } /* Enable bus-mastering. */ pci_enable_busmaster(dev); sc->mem_rid = PCIR_BAR(0); sc->mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &sc->mem_rid, RF_ACTIVE); if (sc->mem == NULL ) { device_printf(dev, "could not allocate memory resources\n"); error = ENOMEM; goto fail2; } sc->sc_st = rman_get_bustag(sc->mem); sc->sc_sh = rman_get_bushandle(sc->mem); sc->irq_rid = 0; #ifdef OLD_MSI if ((result = pci_msi_count(dev)) == 1 && pci_alloc_msi(dev, &result) == 0) sc->irq_rid = 1; #endif sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->irq_rid, RF_ACTIVE | RF_SHAREABLE); if (sc->irq == NULL) { device_printf(dev, "could not allocate interrupt resource\n"); error = ENOMEM; goto fail; } callout_init(&sc->sc_timer_to); TASK_INIT(&sc->sc_reinit_task, 0, iwn_hw_reset_task, sc ); TASK_INIT(&sc->sc_radioon_task, 0, iwn_radio_on_task, sc ); TASK_INIT(&sc->sc_radiooff_task, 0, iwn_radio_off_task, sc ); /* Attach Hardware Abstraction Layer. */ hal = iwn_hal_attach(sc); if (hal == NULL) { error = ENXIO; /* XXX: Wrong error code? */ goto fail; } error = iwn_hw_prepare(sc); if (error != 0) { device_printf(dev, "hardware not ready, error %d\n", error); goto fail; } /* Allocate DMA memory for firmware transfers. */ error = iwn_alloc_fwmem(sc); if (error != 0) { device_printf(dev, "could not allocate memory for firmware, error %d\n", error); goto fail; } /* Allocate "Keep Warm" page. */ error = iwn_alloc_kw(sc); if (error != 0) { device_printf(dev, "could not allocate \"Keep Warm\" page, error %d\n", error); goto fail; } /* Allocate ICT table for 5000 Series. */ if (sc->hw_type != IWN_HW_REV_TYPE_4965 && (error = iwn_alloc_ict(sc)) != 0) { device_printf(dev, "%s: could not allocate ICT table, error %d\n", __func__, error); goto fail; } /* Allocate TX scheduler "rings". */ error = iwn_alloc_sched(sc); if (error != 0) { device_printf(dev, "could not allocate TX scheduler rings, error %d\n", error); goto fail; } /* Allocate TX rings (16 on 4965AGN, 20 on 5000). */ for (i = 0; i < hal->ntxqs; i++) { error = iwn_alloc_tx_ring(sc, &sc->txq[i], i); if (error != 0) { device_printf(dev, "could not allocate Tx ring %d, error %d\n", i, error); goto fail; } } /* Allocate RX ring. */ error = iwn_alloc_rx_ring(sc, &sc->rxq); if (error != 0 ){ device_printf(dev, "could not allocate Rx ring, error %d\n", error); goto fail; } /* Clear pending interrupts. */ IWN_WRITE(sc, IWN_INT, 0xffffffff); /* Count the number of available chains. */ sc->ntxchains = ((sc->txchainmask >> 2) & 1) + ((sc->txchainmask >> 1) & 1) + ((sc->txchainmask >> 0) & 1); sc->nrxchains = ((sc->rxchainmask >> 2) & 1) + ((sc->rxchainmask >> 1) & 1) + ((sc->rxchainmask >> 0) & 1); ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211); if (ifp == NULL) { device_printf(dev, "can not allocate ifnet structure\n"); goto fail; } ic = ifp->if_l2com; ic->ic_ifp = ifp; ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */ ic->ic_opmode = IEEE80211_M_STA; /* default to BSS mode */ /* Set device capabilities. */ ic->ic_caps = IEEE80211_C_STA /* station mode supported */ | IEEE80211_C_MONITOR /* monitor mode supported */ | IEEE80211_C_TXPMGT /* tx power management */ | IEEE80211_C_SHSLOT /* short slot time supported */ | IEEE80211_C_WPA | IEEE80211_C_SHPREAMBLE /* short preamble supported */ | IEEE80211_C_BGSCAN /* background scanning */ #if 0 | IEEE80211_C_IBSS /* ibss/adhoc mode */ #endif | IEEE80211_C_WME /* WME */ ; #if 0 /* HT */ /* XXX disable until HT channel setup works */ ic->ic_htcaps = IEEE80211_HTCAP_SMPS_ENA /* SM PS mode enabled */ | IEEE80211_HTCAP_CHWIDTH40 /* 40MHz channel width */ | IEEE80211_HTCAP_SHORTGI20 /* short GI in 20MHz */ | IEEE80211_HTCAP_SHORTGI40 /* short GI in 40MHz */ | IEEE80211_HTCAP_RXSTBC_2STREAM/* 1-2 spatial streams */ | IEEE80211_HTCAP_MAXAMSDU_3839 /* max A-MSDU length */ /* s/w capabilities */ | IEEE80211_HTC_HT /* HT operation */ | IEEE80211_HTC_AMPDU /* tx A-MPDU */ | IEEE80211_HTC_AMSDU /* tx A-MSDU */ ; /* Set HT capabilities. */ ic->ic_htcaps = #if IWN_RBUF_SIZE == 8192 IEEE80211_HTCAP_AMSDU7935 | #endif IEEE80211_HTCAP_CBW20_40 | IEEE80211_HTCAP_SGI20 | IEEE80211_HTCAP_SGI40; if (sc->hw_type != IWN_HW_REV_TYPE_4965) ic->ic_htcaps |= IEEE80211_HTCAP_GF; if (sc->hw_type == IWN_HW_REV_TYPE_6050) ic->ic_htcaps |= IEEE80211_HTCAP_SMPS_DYN; else ic->ic_htcaps |= IEEE80211_HTCAP_SMPS_DIS; #endif /* Read MAC address, channels, etc from EEPROM. */ error = iwn_read_eeprom(sc, macaddr); if (error != 0) { device_printf(dev, "could not read EEPROM, error %d\n", error); goto fail; } device_printf(sc->sc_dev, "MIMO %dT%dR, %.4s, address %6D\n", sc->ntxchains, sc->nrxchains, sc->eeprom_domain, macaddr, ":"); #if 0 /* HT */ /* Set supported HT rates. */ ic->ic_sup_mcs[0] = 0xff; if (sc->nrxchains > 1) ic->ic_sup_mcs[1] = 0xff; if (sc->nrxchains > 2) ic->ic_sup_mcs[2] = 0xff; #endif if_initname(ifp, device_get_name(dev), device_get_unit(dev)); ifp->if_softc = sc; ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST; ifp->if_init = iwn_init; ifp->if_ioctl = iwn_ioctl; ifp->if_start = iwn_start; ifq_set_maxlen(&ifp->if_snd, IFQ_MAXLEN); ifq_set_ready(&ifp->if_snd); ieee80211_ifattach(ic, macaddr); ic->ic_vap_create = iwn_vap_create; ic->ic_vap_delete = iwn_vap_delete; ic->ic_raw_xmit = iwn_raw_xmit; ic->ic_node_alloc = iwn_node_alloc; ic->ic_newassoc = iwn_newassoc; ic->ic_wme.wme_update = iwn_wme_update; ic->ic_update_mcast = iwn_update_mcast; ic->ic_scan_start = iwn_scan_start; ic->ic_scan_end = iwn_scan_end; ic->ic_set_channel = iwn_set_channel; ic->ic_scan_curchan = iwn_scan_curchan; ic->ic_scan_mindwell = iwn_scan_mindwell; ic->ic_setregdomain = iwn_setregdomain; #if 0 /* HT */ ic->ic_ampdu_rx_start = iwn_ampdu_rx_start; ic->ic_ampdu_rx_stop = iwn_ampdu_rx_stop; ic->ic_ampdu_tx_start = iwn_ampdu_tx_start; ic->ic_ampdu_tx_stop = iwn_ampdu_tx_stop; #endif iwn_radiotap_attach(sc); iwn_sysctlattach(sc); /* * Hook our interrupt after all initialization is complete. */ error = bus_setup_intr(dev, sc->irq, INTR_MPSAFE, iwn_intr, sc, &sc->sc_ih, &wlan_global_serializer); if (error != 0) { device_printf(dev, "could not set up interrupt, error %d\n", error); goto fail; } ieee80211_announce(ic); wlan_serialize_exit(); return 0; fail: iwn_cleanup(dev); fail2: wlan_serialize_exit(); return error; } static const struct iwn_hal * iwn_hal_attach(struct iwn_softc *sc) { sc->hw_type = (IWN_READ(sc, IWN_HW_REV) >> 4) & 0xf; switch (sc->hw_type) { case IWN_HW_REV_TYPE_4965: sc->sc_hal = &iwn4965_hal; sc->limits = &iwn4965_sensitivity_limits; sc->fwname = "iwn4965fw"; sc->txchainmask = IWN_ANT_AB; sc->rxchainmask = IWN_ANT_ABC; break; case IWN_HW_REV_TYPE_5100: sc->sc_hal = &iwn5000_hal; sc->limits = &iwn5000_sensitivity_limits; sc->fwname = "iwn5000fw"; sc->txchainmask = IWN_ANT_B; sc->rxchainmask = IWN_ANT_AB; break; case IWN_HW_REV_TYPE_5150: sc->sc_hal = &iwn5000_hal; sc->limits = &iwn5150_sensitivity_limits; sc->fwname = "iwn5150fw"; sc->txchainmask = IWN_ANT_A; sc->rxchainmask = IWN_ANT_AB; break; case IWN_HW_REV_TYPE_5300: case IWN_HW_REV_TYPE_5350: sc->sc_hal = &iwn5000_hal; sc->limits = &iwn5000_sensitivity_limits; sc->fwname = "iwn5000fw"; sc->txchainmask = IWN_ANT_ABC; sc->rxchainmask = IWN_ANT_ABC; break; case IWN_HW_REV_TYPE_1000: sc->sc_hal = &iwn5000_hal; sc->limits = &iwn1000_sensitivity_limits; sc->fwname = "iwn1000fw"; sc->txchainmask = IWN_ANT_A; sc->rxchainmask = IWN_ANT_AB; break; case IWN_HW_REV_TYPE_6000: sc->sc_hal = &iwn5000_hal; sc->limits = &iwn6000_sensitivity_limits; sc->fwname = "iwn6000fw"; switch (pci_get_device(sc->sc_dev)) { case 0x422C: case 0x4239: sc->sc_flags |= IWN_FLAG_INTERNAL_PA; sc->txchainmask = IWN_ANT_BC; sc->rxchainmask = IWN_ANT_BC; break; default: sc->txchainmask = IWN_ANT_ABC; sc->rxchainmask = IWN_ANT_ABC; break; } break; case IWN_HW_REV_TYPE_6050: sc->sc_hal = &iwn5000_hal; sc->limits = &iwn6000_sensitivity_limits; sc->fwname = "iwn6000fw"; sc->txchainmask = IWN_ANT_AB; sc->rxchainmask = IWN_ANT_AB; break; default: device_printf(sc->sc_dev, "adapter type %d not supported\n", sc->hw_type); return NULL; } return sc->sc_hal; } /* * Attach the interface to 802.11 radiotap. */ static void iwn_radiotap_attach(struct iwn_softc *sc) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; ieee80211_radiotap_attach(ic, &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap), IWN_TX_RADIOTAP_PRESENT, &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap), IWN_RX_RADIOTAP_PRESENT); } static struct ieee80211vap * iwn_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit, int opmode, int flags, const uint8_t bssid[IEEE80211_ADDR_LEN], const uint8_t mac[IEEE80211_ADDR_LEN]) { struct iwn_vap *ivp; struct ieee80211vap *vap; if (!TAILQ_EMPTY(&ic->ic_vaps)) /* only one at a time */ return NULL; ivp = (struct iwn_vap *) kmalloc(sizeof(struct iwn_vap), M_80211_VAP, M_INTWAIT | M_ZERO); if (ivp == NULL) return NULL; vap = &ivp->iv_vap; ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid, mac); vap->iv_bmissthreshold = 10; /* override default */ /* Override with driver methods. */ ivp->iv_newstate = vap->iv_newstate; vap->iv_newstate = iwn_newstate; ieee80211_ratectl_init(vap); /* Complete setup. */ ieee80211_vap_attach(vap, iwn_media_change, ieee80211_media_status); ic->ic_opmode = opmode; return vap; } static void iwn_vap_delete(struct ieee80211vap *vap) { struct iwn_vap *ivp = IWN_VAP(vap); ieee80211_ratectl_deinit(vap); ieee80211_vap_detach(vap); kfree(ivp, M_80211_VAP); } static int iwn_cleanup(device_t dev) { struct iwn_softc *sc = device_get_softc(dev); struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic; int i; if (ifp != NULL) { ic = ifp->if_l2com; ieee80211_draintask(ic, &sc->sc_reinit_task); ieee80211_draintask(ic, &sc->sc_radioon_task); ieee80211_draintask(ic, &sc->sc_radiooff_task); iwn_stop(sc); callout_stop(&sc->sc_timer_to); ieee80211_ifdetach(ic); } /* cleanup sysctl nodes */ sysctl_ctx_free(&sc->sc_sysctl_ctx); /* Free DMA resources. */ iwn_free_rx_ring(sc, &sc->rxq); if (sc->sc_hal != NULL) for (i = 0; i < sc->sc_hal->ntxqs; i++) iwn_free_tx_ring(sc, &sc->txq[i]); iwn_free_sched(sc); iwn_free_kw(sc); if (sc->ict != NULL) { iwn_free_ict(sc); sc->ict = NULL; } iwn_free_fwmem(sc); if (sc->irq != NULL) { bus_teardown_intr(dev, sc->irq, sc->sc_ih); bus_release_resource(dev, SYS_RES_IRQ, sc->irq_rid, sc->irq); if (sc->irq_rid == 1) pci_release_msi(dev); sc->irq = NULL; } if (sc->mem != NULL) { bus_release_resource(dev, SYS_RES_MEMORY, sc->mem_rid, sc->mem); sc->mem = NULL; } if (ifp != NULL) { if_free(ifp); sc->sc_ifp = NULL; } return 0; } static int iwn_pci_detach(device_t dev) { struct iwn_softc *sc = (struct iwn_softc *)device_get_softc(dev); wlan_serialize_enter(); iwn_cleanup(dev); bus_dma_tag_destroy(sc->sc_dmat); wlan_serialize_exit(); return 0; } static int iwn_nic_lock(struct iwn_softc *sc) { int ntries; /* Request exclusive access to NIC. */ IWN_SETBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_MAC_ACCESS_REQ); /* Spin until we actually get the lock. */ for (ntries = 0; ntries < 1000; ntries++) { if ((IWN_READ(sc, IWN_GP_CNTRL) & (IWN_GP_CNTRL_MAC_ACCESS_ENA | IWN_GP_CNTRL_SLEEP)) == IWN_GP_CNTRL_MAC_ACCESS_ENA) return 0; DELAY(10); } return ETIMEDOUT; } static __inline void iwn_nic_unlock(struct iwn_softc *sc) { IWN_CLRBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_MAC_ACCESS_REQ); } static __inline uint32_t iwn_prph_read(struct iwn_softc *sc, uint32_t addr) { IWN_WRITE(sc, IWN_PRPH_RADDR, IWN_PRPH_DWORD | addr); IWN_BARRIER_READ_WRITE(sc); return IWN_READ(sc, IWN_PRPH_RDATA); } static __inline void iwn_prph_write(struct iwn_softc *sc, uint32_t addr, uint32_t data) { IWN_WRITE(sc, IWN_PRPH_WADDR, IWN_PRPH_DWORD | addr); IWN_BARRIER_WRITE(sc); IWN_WRITE(sc, IWN_PRPH_WDATA, data); } static __inline void iwn_prph_setbits(struct iwn_softc *sc, uint32_t addr, uint32_t mask) { iwn_prph_write(sc, addr, iwn_prph_read(sc, addr) | mask); } static __inline void iwn_prph_clrbits(struct iwn_softc *sc, uint32_t addr, uint32_t mask) { iwn_prph_write(sc, addr, iwn_prph_read(sc, addr) & ~mask); } static __inline void iwn_prph_write_region_4(struct iwn_softc *sc, uint32_t addr, const uint32_t *data, int count) { for (; count > 0; count--, data++, addr += 4) iwn_prph_write(sc, addr, *data); } static __inline uint32_t iwn_mem_read(struct iwn_softc *sc, uint32_t addr) { IWN_WRITE(sc, IWN_MEM_RADDR, addr); IWN_BARRIER_READ_WRITE(sc); return IWN_READ(sc, IWN_MEM_RDATA); } static __inline void iwn_mem_write(struct iwn_softc *sc, uint32_t addr, uint32_t data) { IWN_WRITE(sc, IWN_MEM_WADDR, addr); IWN_BARRIER_WRITE(sc); IWN_WRITE(sc, IWN_MEM_WDATA, data); } static __inline void iwn_mem_write_2(struct iwn_softc *sc, uint32_t addr, uint16_t data) { uint32_t tmp; tmp = iwn_mem_read(sc, addr & ~3); if (addr & 3) tmp = (tmp & 0x0000ffff) | data << 16; else tmp = (tmp & 0xffff0000) | data; iwn_mem_write(sc, addr & ~3, tmp); } static __inline void iwn_mem_read_region_4(struct iwn_softc *sc, uint32_t addr, uint32_t *data, int count) { for (; count > 0; count--, addr += 4) *data++ = iwn_mem_read(sc, addr); } static __inline void iwn_mem_set_region_4(struct iwn_softc *sc, uint32_t addr, uint32_t val, int count) { for (; count > 0; count--, addr += 4) iwn_mem_write(sc, addr, val); } static int iwn_eeprom_lock(struct iwn_softc *sc) { int i, ntries; for (i = 0; i < 100; i++) { /* Request exclusive access to EEPROM. */ IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_EEPROM_LOCKED); /* Spin until we actually get the lock. */ for (ntries = 0; ntries < 100; ntries++) { if (IWN_READ(sc, IWN_HW_IF_CONFIG) & IWN_HW_IF_CONFIG_EEPROM_LOCKED) return 0; DELAY(10); } } return ETIMEDOUT; } static __inline void iwn_eeprom_unlock(struct iwn_softc *sc) { IWN_CLRBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_EEPROM_LOCKED); } /* * Initialize access by host to One Time Programmable ROM. * NB: This kind of ROM can be found on 1000 or 6000 Series only. */ static int iwn_init_otprom(struct iwn_softc *sc) { uint16_t prev, base, next; int count, error; /* Wait for clock stabilization before accessing prph. */ error = iwn_clock_wait(sc); if (error != 0) return error; error = iwn_nic_lock(sc); if (error != 0) return error; iwn_prph_setbits(sc, IWN_APMG_PS, IWN_APMG_PS_RESET_REQ); DELAY(5); iwn_prph_clrbits(sc, IWN_APMG_PS, IWN_APMG_PS_RESET_REQ); iwn_nic_unlock(sc); /* Set auto clock gate disable bit for HW with OTP shadow RAM. */ if (sc->hw_type != IWN_HW_REV_TYPE_1000) { IWN_SETBITS(sc, IWN_DBG_LINK_PWR_MGMT, IWN_RESET_LINK_PWR_MGMT_DIS); } IWN_CLRBITS(sc, IWN_EEPROM_GP, IWN_EEPROM_GP_IF_OWNER); /* Clear ECC status. */ IWN_SETBITS(sc, IWN_OTP_GP, IWN_OTP_GP_ECC_CORR_STTS | IWN_OTP_GP_ECC_UNCORR_STTS); /* * Find the block before last block (contains the EEPROM image) * for HW without OTP shadow RAM. */ if (sc->hw_type == IWN_HW_REV_TYPE_1000) { /* Switch to absolute addressing mode. */ IWN_CLRBITS(sc, IWN_OTP_GP, IWN_OTP_GP_RELATIVE_ACCESS); base = prev = 0; for (count = 0; count < IWN1000_OTP_NBLOCKS; count++) { error = iwn_read_prom_data(sc, base, &next, 2); if (error != 0) return error; if (next == 0) /* End of linked-list. */ break; prev = base; base = le16toh(next); } if (count == 0 || count == IWN1000_OTP_NBLOCKS) return EIO; /* Skip "next" word. */ sc->prom_base = prev + 1; } return 0; } static int iwn_read_prom_data(struct iwn_softc *sc, uint32_t addr, void *data, int count) { uint32_t val, tmp; int ntries; uint8_t *out = data; addr += sc->prom_base; for (; count > 0; count -= 2, addr++) { IWN_WRITE(sc, IWN_EEPROM, addr << 2); for (ntries = 0; ntries < 10; ntries++) { val = IWN_READ(sc, IWN_EEPROM); if (val & IWN_EEPROM_READ_VALID) break; DELAY(5); } if (ntries == 10) { device_printf(sc->sc_dev, "timeout reading ROM at 0x%x\n", addr); return ETIMEDOUT; } if (sc->sc_flags & IWN_FLAG_HAS_OTPROM) { /* OTPROM, check for ECC errors. */ tmp = IWN_READ(sc, IWN_OTP_GP); if (tmp & IWN_OTP_GP_ECC_UNCORR_STTS) { device_printf(sc->sc_dev, "OTPROM ECC error at 0x%x\n", addr); return EIO; } if (tmp & IWN_OTP_GP_ECC_CORR_STTS) { /* Correctable ECC error, clear bit. */ IWN_SETBITS(sc, IWN_OTP_GP, IWN_OTP_GP_ECC_CORR_STTS); } } *out++ = val >> 16; if (count > 1) *out++ = val >> 24; } return 0; } static void iwn_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nsegs, int error) { if (error != 0) return; KASSERT(nsegs == 1, ("too many DMA segments, %d should be 1", nsegs)); *(bus_addr_t *)arg = segs[0].ds_addr; } static int iwn_dma_contig_alloc(struct iwn_softc *sc, struct iwn_dma_info *dma, void **kvap, bus_size_t size, bus_size_t alignment, int flags) { int error; dma->size = size; dma->tag = NULL; error = bus_dma_tag_create(sc->sc_dmat, alignment, 0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, size, 1, size, flags, &dma->tag); if (error != 0) { device_printf(sc->sc_dev, "%s: bus_dma_tag_create failed, error %d\n", __func__, error); goto fail; } error = bus_dmamem_alloc(dma->tag, (void **)&dma->vaddr, flags | BUS_DMA_ZERO, &dma->map); if (error != 0) { device_printf(sc->sc_dev, "%s: bus_dmamem_alloc failed, error %d\n", __func__, error); goto fail; } error = bus_dmamap_load(dma->tag, dma->map, dma->vaddr, size, iwn_dma_map_addr, &dma->paddr, flags); if (error != 0) { device_printf(sc->sc_dev, "%s: bus_dmamap_load failed, error %d\n", __func__, error); goto fail; } if (kvap != NULL) *kvap = dma->vaddr; return 0; fail: iwn_dma_contig_free(dma); return error; } static void iwn_dma_contig_free(struct iwn_dma_info *dma) { if (dma->tag != NULL) { if (dma->map != NULL) { if (dma->paddr == 0) { bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_POSTREAD|BUS_DMASYNC_POSTWRITE); bus_dmamap_unload(dma->tag, dma->map); } bus_dmamap_destroy(dma->tag, dma->map); } bus_dmamem_free(dma->tag, dma->vaddr, dma->map); bus_dma_tag_destroy(dma->tag); } } static int iwn_alloc_sched(struct iwn_softc *sc) { /* TX scheduler rings must be aligned on a 1KB boundary. */ return iwn_dma_contig_alloc(sc, &sc->sched_dma, (void **)&sc->sched, sc->sc_hal->schedsz, 1024, BUS_DMA_NOWAIT); } static void iwn_free_sched(struct iwn_softc *sc) { iwn_dma_contig_free(&sc->sched_dma); } static int iwn_alloc_kw(struct iwn_softc *sc) { /* "Keep Warm" page must be aligned on a 4KB boundary. */ return iwn_dma_contig_alloc(sc, &sc->kw_dma, NULL, 4096, 4096, BUS_DMA_NOWAIT); } static void iwn_free_kw(struct iwn_softc *sc) { iwn_dma_contig_free(&sc->kw_dma); } static int iwn_alloc_ict(struct iwn_softc *sc) { /* ICT table must be aligned on a 4KB boundary. */ return iwn_dma_contig_alloc(sc, &sc->ict_dma, (void **)&sc->ict, IWN_ICT_SIZE, 4096, BUS_DMA_NOWAIT); } static void iwn_free_ict(struct iwn_softc *sc) { iwn_dma_contig_free(&sc->ict_dma); } static int iwn_alloc_fwmem(struct iwn_softc *sc) { /* Must be aligned on a 16-byte boundary. */ return iwn_dma_contig_alloc(sc, &sc->fw_dma, NULL, sc->sc_hal->fwsz, 16, BUS_DMA_NOWAIT); } static void iwn_free_fwmem(struct iwn_softc *sc) { iwn_dma_contig_free(&sc->fw_dma); } static int iwn_alloc_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring) { bus_size_t size; int i, error; ring->cur = 0; /* Allocate RX descriptors (256-byte aligned). */ size = IWN_RX_RING_COUNT * sizeof (uint32_t); error = iwn_dma_contig_alloc(sc, &ring->desc_dma, (void **)&ring->desc, size, 256, BUS_DMA_NOWAIT); if (error != 0) { device_printf(sc->sc_dev, "%s: could not allocate Rx ring DMA memory, error %d\n", __func__, error); goto fail; } error = bus_dma_tag_create(sc->sc_dmat, 1, 0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MJUMPAGESIZE, 1, MJUMPAGESIZE, BUS_DMA_NOWAIT, &ring->data_dmat); if (error != 0) { device_printf(sc->sc_dev, "%s: bus_dma_tag_create_failed, error %d\n", __func__, error); goto fail; } /* Allocate RX status area (16-byte aligned). */ error = iwn_dma_contig_alloc(sc, &ring->stat_dma, (void **)&ring->stat, sizeof (struct iwn_rx_status), 16, BUS_DMA_NOWAIT); if (error != 0) { device_printf(sc->sc_dev, "%s: could not allocate Rx status DMA memory, error %d\n", __func__, error); goto fail; } /* * Allocate and map RX buffers. */ for (i = 0; i < IWN_RX_RING_COUNT; i++) { struct iwn_rx_data *data = &ring->data[i]; bus_addr_t paddr; error = bus_dmamap_create(ring->data_dmat, 0, &data->map); if (error != 0) { device_printf(sc->sc_dev, "%s: bus_dmamap_create failed, error %d\n", __func__, error); goto fail; } data->m = m_getjcl(MB_DONTWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE); if (data->m == NULL) { device_printf(sc->sc_dev, "%s: could not allocate rx mbuf\n", __func__); error = ENOMEM; goto fail; } /* Map page. */ error = bus_dmamap_load(ring->data_dmat, data->map, mtod(data->m, caddr_t), MJUMPAGESIZE, iwn_dma_map_addr, &paddr, BUS_DMA_NOWAIT); if (error != 0 && error != EFBIG) { device_printf(sc->sc_dev, "%s: bus_dmamap_load failed, error %d\n", __func__, error); m_freem(data->m); error = ENOMEM; /* XXX unique code */ goto fail; } bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE); /* Set physical address of RX buffer (256-byte aligned). */ ring->desc[i] = htole32(paddr >> 8); } bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map, BUS_DMASYNC_PREWRITE); return 0; fail: iwn_free_rx_ring(sc, ring); return error; } static void iwn_reset_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring) { int ntries; if (iwn_nic_lock(sc) == 0) { IWN_WRITE(sc, IWN_FH_RX_CONFIG, 0); for (ntries = 0; ntries < 1000; ntries++) { if (IWN_READ(sc, IWN_FH_RX_STATUS) & IWN_FH_RX_STATUS_IDLE) break; DELAY(10); } iwn_nic_unlock(sc); #ifdef IWN_DEBUG if (ntries == 1000) DPRINTF(sc, IWN_DEBUG_ANY, "%s\n", "timeout resetting Rx ring"); #endif } ring->cur = 0; sc->last_rx_valid = 0; } static void iwn_free_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring) { int i; iwn_dma_contig_free(&ring->desc_dma); iwn_dma_contig_free(&ring->stat_dma); for (i = 0; i < IWN_RX_RING_COUNT; i++) { struct iwn_rx_data *data = &ring->data[i]; if (data->m != NULL) { bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD); bus_dmamap_unload(ring->data_dmat, data->map); m_freem(data->m); } if (data->map != NULL) bus_dmamap_destroy(ring->data_dmat, data->map); } } static int iwn_alloc_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring, int qid) { bus_size_t size; bus_addr_t paddr; int i, error; ring->qid = qid; ring->queued = 0; ring->cur = 0; /* Allocate TX descriptors (256-byte aligned.) */ size = IWN_TX_RING_COUNT * sizeof(struct iwn_tx_desc); error = iwn_dma_contig_alloc(sc, &ring->desc_dma, (void **)&ring->desc, size, 256, BUS_DMA_NOWAIT); if (error != 0) { device_printf(sc->sc_dev, "%s: could not allocate TX ring DMA memory, error %d\n", __func__, error); goto fail; } /* * We only use rings 0 through 4 (4 EDCA + cmd) so there is no need * to allocate commands space for other rings. */ if (qid > 4) return 0; size = IWN_TX_RING_COUNT * sizeof(struct iwn_tx_cmd); error = iwn_dma_contig_alloc(sc, &ring->cmd_dma, (void **)&ring->cmd, size, 4, BUS_DMA_NOWAIT); if (error != 0) { device_printf(sc->sc_dev, "%s: could not allocate TX cmd DMA memory, error %d\n", __func__, error); goto fail; } error = bus_dma_tag_create(sc->sc_dmat, 1, 0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MJUMPAGESIZE, IWN_MAX_SCATTER - 1, MJUMPAGESIZE, BUS_DMA_NOWAIT, &ring->data_dmat); if (error != 0) { device_printf(sc->sc_dev, "%s: bus_dma_tag_create_failed, error %d\n", __func__, error); goto fail; } paddr = ring->cmd_dma.paddr; for (i = 0; i < IWN_TX_RING_COUNT; i++) { struct iwn_tx_data *data = &ring->data[i]; data->cmd_paddr = paddr; data->scratch_paddr = paddr + 12; paddr += sizeof (struct iwn_tx_cmd); error = bus_dmamap_create(ring->data_dmat, 0, &data->map); if (error != 0) { device_printf(sc->sc_dev, "%s: bus_dmamap_create failed, error %d\n", __func__, error); goto fail; } bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE); } return 0; fail: iwn_free_tx_ring(sc, ring); return error; } static void iwn_reset_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring) { int i; for (i = 0; i < IWN_TX_RING_COUNT; i++) { struct iwn_tx_data *data = &ring->data[i]; if (data->m != NULL) { bus_dmamap_unload(ring->data_dmat, data->map); m_freem(data->m); data->m = NULL; } } /* Clear TX descriptors. */ memset(ring->desc, 0, ring->desc_dma.size); bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map, BUS_DMASYNC_PREWRITE); sc->qfullmsk &= ~(1 << ring->qid); ring->queued = 0; ring->cur = 0; } static void iwn_free_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring) { int i; iwn_dma_contig_free(&ring->desc_dma); iwn_dma_contig_free(&ring->cmd_dma); for (i = 0; i < IWN_TX_RING_COUNT; i++) { struct iwn_tx_data *data = &ring->data[i]; if (data->m != NULL) { bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTWRITE); bus_dmamap_unload(ring->data_dmat, data->map); m_freem(data->m); } if (data->map != NULL) bus_dmamap_destroy(ring->data_dmat, data->map); } } static void iwn5000_ict_reset(struct iwn_softc *sc) { /* Disable interrupts. */ IWN_WRITE(sc, IWN_INT_MASK, 0); /* Reset ICT table. */ memset(sc->ict, 0, IWN_ICT_SIZE); sc->ict_cur = 0; /* Set physical address of ICT table (4KB aligned.) */ DPRINTF(sc, IWN_DEBUG_RESET, "%s: enabling ICT\n", __func__); IWN_WRITE(sc, IWN_DRAM_INT_TBL, IWN_DRAM_INT_TBL_ENABLE | IWN_DRAM_INT_TBL_WRAP_CHECK | sc->ict_dma.paddr >> 12); /* Enable periodic RX interrupt. */ sc->int_mask |= IWN_INT_RX_PERIODIC; /* Switch to ICT interrupt mode in driver. */ sc->sc_flags |= IWN_FLAG_USE_ICT; /* Re-enable interrupts. */ IWN_WRITE(sc, IWN_INT, 0xffffffff); IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask); } static int iwn_read_eeprom(struct iwn_softc *sc, uint8_t macaddr[IEEE80211_ADDR_LEN]) { const struct iwn_hal *hal = sc->sc_hal; int error; uint16_t val; /* Check whether adapter has an EEPROM or an OTPROM. */ if (sc->hw_type >= IWN_HW_REV_TYPE_1000 && (IWN_READ(sc, IWN_OTP_GP) & IWN_OTP_GP_DEV_SEL_OTP)) sc->sc_flags |= IWN_FLAG_HAS_OTPROM; DPRINTF(sc, IWN_DEBUG_RESET, "%s found\n", (sc->sc_flags & IWN_FLAG_HAS_OTPROM) ? "OTPROM" : "EEPROM"); /* Adapter has to be powered on for EEPROM access to work. */ error = iwn_apm_init(sc); if (error != 0) { device_printf(sc->sc_dev, "%s: could not power ON adapter, error %d\n", __func__, error); return error; } if ((IWN_READ(sc, IWN_EEPROM_GP) & 0x7) == 0) { device_printf(sc->sc_dev, "%s: bad ROM signature\n", __func__); return EIO; } error = iwn_eeprom_lock(sc); if (error != 0) { device_printf(sc->sc_dev, "%s: could not lock ROM, error %d\n", __func__, error); return error; } if (sc->sc_flags & IWN_FLAG_HAS_OTPROM) { error = iwn_init_otprom(sc); if (error != 0) { device_printf(sc->sc_dev, "%s: could not initialize OTPROM, error %d\n", __func__, error); return error; } } iwn_read_prom_data(sc, IWN_EEPROM_RFCFG, &val, 2); sc->rfcfg = le16toh(val); DPRINTF(sc, IWN_DEBUG_RESET, "radio config=0x%04x\n", sc->rfcfg); /* Read MAC address. */ iwn_read_prom_data(sc, IWN_EEPROM_MAC, macaddr, 6); /* Read adapter-specific information from EEPROM. */ hal->read_eeprom(sc); iwn_apm_stop(sc); /* Power OFF adapter. */ iwn_eeprom_unlock(sc); return 0; } static void iwn4965_read_eeprom(struct iwn_softc *sc) { uint32_t addr; int i; uint16_t val; /* Read regulatory domain (4 ASCII characters.) */ iwn_read_prom_data(sc, IWN4965_EEPROM_DOMAIN, sc->eeprom_domain, 4); /* Read the list of authorized channels (20MHz ones only.) */ for (i = 0; i < 5; i++) { addr = iwn4965_regulatory_bands[i]; iwn_read_eeprom_channels(sc, i, addr); } /* Read maximum allowed TX power for 2GHz and 5GHz bands. */ iwn_read_prom_data(sc, IWN4965_EEPROM_MAXPOW, &val, 2); sc->maxpwr2GHz = val & 0xff; sc->maxpwr5GHz = val >> 8; /* Check that EEPROM values are within valid range. */ if (sc->maxpwr5GHz < 20 || sc->maxpwr5GHz > 50) sc->maxpwr5GHz = 38; if (sc->maxpwr2GHz < 20 || sc->maxpwr2GHz > 50) sc->maxpwr2GHz = 38; DPRINTF(sc, IWN_DEBUG_RESET, "maxpwr 2GHz=%d 5GHz=%d\n", sc->maxpwr2GHz, sc->maxpwr5GHz); /* Read samples for each TX power group. */ iwn_read_prom_data(sc, IWN4965_EEPROM_BANDS, sc->bands, sizeof sc->bands); /* Read voltage at which samples were taken. */ iwn_read_prom_data(sc, IWN4965_EEPROM_VOLTAGE, &val, 2); sc->eeprom_voltage = (int16_t)le16toh(val); DPRINTF(sc, IWN_DEBUG_RESET, "voltage=%d (in 0.3V)\n", sc->eeprom_voltage); #ifdef IWN_DEBUG /* Print samples. */ if (sc->sc_debug & IWN_DEBUG_ANY) { for (i = 0; i < IWN_NBANDS; i++) iwn4965_print_power_group(sc, i); } #endif } #ifdef IWN_DEBUG static void iwn4965_print_power_group(struct iwn_softc *sc, int i) { struct iwn4965_eeprom_band *band = &sc->bands[i]; struct iwn4965_eeprom_chan_samples *chans = band->chans; int j, c; kprintf("===band %d===\n", i); kprintf("chan lo=%d, chan hi=%d\n", band->lo, band->hi); kprintf("chan1 num=%d\n", chans[0].num); for (c = 0; c < 2; c++) { for (j = 0; j < IWN_NSAMPLES; j++) { kprintf("chain %d, sample %d: temp=%d gain=%d " "power=%d pa_det=%d\n", c, j, chans[0].samples[c][j].temp, chans[0].samples[c][j].gain, chans[0].samples[c][j].power, chans[0].samples[c][j].pa_det); } } kprintf("chan2 num=%d\n", chans[1].num); for (c = 0; c < 2; c++) { for (j = 0; j < IWN_NSAMPLES; j++) { kprintf("chain %d, sample %d: temp=%d gain=%d " "power=%d pa_det=%d\n", c, j, chans[1].samples[c][j].temp, chans[1].samples[c][j].gain, chans[1].samples[c][j].power, chans[1].samples[c][j].pa_det); } } } #endif static void iwn5000_read_eeprom(struct iwn_softc *sc) { struct iwn5000_eeprom_calib_hdr hdr; int32_t temp, volt; uint32_t addr, base; int i; uint16_t val; /* Read regulatory domain (4 ASCII characters.) */ iwn_read_prom_data(sc, IWN5000_EEPROM_REG, &val, 2); base = le16toh(val); iwn_read_prom_data(sc, base + IWN5000_EEPROM_DOMAIN, sc->eeprom_domain, 4); /* Read the list of authorized channels (20MHz ones only.) */ for (i = 0; i < 5; i++) { addr = base + iwn5000_regulatory_bands[i]; iwn_read_eeprom_channels(sc, i, addr); } /* Read enhanced TX power information for 6000 Series. */ if (sc->hw_type >= IWN_HW_REV_TYPE_6000) iwn_read_eeprom_enhinfo(sc); iwn_read_prom_data(sc, IWN5000_EEPROM_CAL, &val, 2); base = le16toh(val); iwn_read_prom_data(sc, base, &hdr, sizeof hdr); DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: calib version=%u pa type=%u voltage=%u\n", __func__, hdr.version, hdr.pa_type, le16toh(hdr.volt)); sc->calib_ver = hdr.version; if (sc->hw_type == IWN_HW_REV_TYPE_5150) { /* Compute temperature offset. */ iwn_read_prom_data(sc, base + IWN5000_EEPROM_TEMP, &val, 2); temp = le16toh(val); iwn_read_prom_data(sc, base + IWN5000_EEPROM_VOLT, &val, 2); volt = le16toh(val); sc->temp_off = temp - (volt / -5); DPRINTF(sc, IWN_DEBUG_CALIBRATE, "temp=%d volt=%d offset=%dK\n", temp, volt, sc->temp_off); } else { /* Read crystal calibration. */ iwn_read_prom_data(sc, base + IWN5000_EEPROM_CRYSTAL, &sc->eeprom_crystal, sizeof (uint32_t)); DPRINTF(sc, IWN_DEBUG_CALIBRATE, "crystal calibration 0x%08x\n", le32toh(sc->eeprom_crystal)); } } /* * Translate EEPROM flags to net80211. */ static uint32_t iwn_eeprom_channel_flags(struct iwn_eeprom_chan *channel) { uint32_t nflags; nflags = 0; if ((channel->flags & IWN_EEPROM_CHAN_ACTIVE) == 0) nflags |= IEEE80211_CHAN_PASSIVE; if ((channel->flags & IWN_EEPROM_CHAN_IBSS) == 0) nflags |= IEEE80211_CHAN_NOADHOC; if (channel->flags & IWN_EEPROM_CHAN_RADAR) { nflags |= IEEE80211_CHAN_DFS; /* XXX apparently IBSS may still be marked */ nflags |= IEEE80211_CHAN_NOADHOC; } return nflags; } static void iwn_read_eeprom_band(struct iwn_softc *sc, int n) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct iwn_eeprom_chan *channels = sc->eeprom_channels[n]; const struct iwn_chan_band *band = &iwn_bands[n]; struct ieee80211_channel *c; int i, chan, nflags; for (i = 0; i < band->nchan; i++) { if (!(channels[i].flags & IWN_EEPROM_CHAN_VALID)) { DPRINTF(sc, IWN_DEBUG_RESET, "skip chan %d flags 0x%x maxpwr %d\n", band->chan[i], channels[i].flags, channels[i].maxpwr); continue; } chan = band->chan[i]; nflags = iwn_eeprom_channel_flags(&channels[i]); DPRINTF(sc, IWN_DEBUG_RESET, "add chan %d flags 0x%x maxpwr %d\n", chan, channels[i].flags, channels[i].maxpwr); c = &ic->ic_channels[ic->ic_nchans++]; c->ic_ieee = chan; c->ic_maxregpower = channels[i].maxpwr; c->ic_maxpower = 2*c->ic_maxregpower; /* Save maximum allowed TX power for this channel. */ sc->maxpwr[chan] = channels[i].maxpwr; if (n == 0) { /* 2GHz band */ c->ic_freq = ieee80211_ieee2mhz(chan, IEEE80211_CHAN_G); /* G =>'s B is supported */ c->ic_flags = IEEE80211_CHAN_B | nflags; c = &ic->ic_channels[ic->ic_nchans++]; c[0] = c[-1]; c->ic_flags = IEEE80211_CHAN_G | nflags; } else { /* 5GHz band */ c->ic_freq = ieee80211_ieee2mhz(chan, IEEE80211_CHAN_A); c->ic_flags = IEEE80211_CHAN_A | nflags; sc->sc_flags |= IWN_FLAG_HAS_5GHZ; } #if 0 /* HT */ /* XXX no constraints on using HT20 */ /* add HT20, HT40 added separately */ c = &ic->ic_channels[ic->ic_nchans++]; c[0] = c[-1]; c->ic_flags |= IEEE80211_CHAN_HT20; /* XXX NARROW =>'s 1/2 and 1/4 width? */ #endif } } #if 0 /* HT */ static void iwn_read_eeprom_ht40(struct iwn_softc *sc, int n) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct iwn_eeprom_chan *channels = sc->eeprom_channels[n]; const struct iwn_chan_band *band = &iwn_bands[n]; struct ieee80211_channel *c, *cent, *extc; int i; for (i = 0; i < band->nchan; i++) { if (!(channels[i].flags & IWN_EEPROM_CHAN_VALID) || !(channels[i].flags & IWN_EEPROM_CHAN_WIDE)) { DPRINTF(sc, IWN_DEBUG_RESET, "skip chan %d flags 0x%x maxpwr %d\n", band->chan[i], channels[i].flags, channels[i].maxpwr); continue; } /* * Each entry defines an HT40 channel pair; find the * center channel, then the extension channel above. */ cent = ieee80211_find_channel_byieee(ic, band->chan[i], band->flags & ~IEEE80211_CHAN_HT); if (cent == NULL) { /* XXX shouldn't happen */ device_printf(sc->sc_dev, "%s: no entry for channel %d\n", __func__, band->chan[i]); continue; } extc = ieee80211_find_channel(ic, cent->ic_freq+20, band->flags & ~IEEE80211_CHAN_HT); if (extc == NULL) { DPRINTF(sc, IWN_DEBUG_RESET, "skip chan %d, extension channel not found\n", band->chan[i]); continue; } DPRINTF(sc, IWN_DEBUG_RESET, "add ht40 chan %d flags 0x%x maxpwr %d\n", band->chan[i], channels[i].flags, channels[i].maxpwr); c = &ic->ic_channels[ic->ic_nchans++]; c[0] = cent[0]; c->ic_extieee = extc->ic_ieee; c->ic_flags &= ~IEEE80211_CHAN_HT; c->ic_flags |= IEEE80211_CHAN_HT40U; c = &ic->ic_channels[ic->ic_nchans++]; c[0] = extc[0]; c->ic_extieee = cent->ic_ieee; c->ic_flags &= ~IEEE80211_CHAN_HT; c->ic_flags |= IEEE80211_CHAN_HT40D; } } #endif static void iwn_read_eeprom_channels(struct iwn_softc *sc, int n, uint32_t addr) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; iwn_read_prom_data(sc, addr, &sc->eeprom_channels[n], iwn_bands[n].nchan * sizeof (struct iwn_eeprom_chan)); if (n < 5) iwn_read_eeprom_band(sc, n); #if 0 /* HT */ else iwn_read_eeprom_ht40(sc, n); #endif ieee80211_sort_channels(ic->ic_channels, ic->ic_nchans); } static void iwn_read_eeprom_enhinfo(struct iwn_softc *sc) { struct iwn_eeprom_enhinfo enhinfo[35]; uint16_t val, base; int8_t maxpwr; int i; iwn_read_prom_data(sc, IWN5000_EEPROM_REG, &val, 2); base = le16toh(val); iwn_read_prom_data(sc, base + IWN6000_EEPROM_ENHINFO, enhinfo, sizeof enhinfo); memset(sc->enh_maxpwr, 0, sizeof sc->enh_maxpwr); for (i = 0; i < NELEM(enhinfo); i++) { if (enhinfo[i].chan == 0 || enhinfo[i].reserved != 0) continue; /* Skip invalid entries. */ maxpwr = 0; if (sc->txchainmask & IWN_ANT_A) maxpwr = MAX(maxpwr, enhinfo[i].chain[0]); if (sc->txchainmask & IWN_ANT_B) maxpwr = MAX(maxpwr, enhinfo[i].chain[1]); if (sc->txchainmask & IWN_ANT_C) maxpwr = MAX(maxpwr, enhinfo[i].chain[2]); if (sc->ntxchains == 2) maxpwr = MAX(maxpwr, enhinfo[i].mimo2); else if (sc->ntxchains == 3) maxpwr = MAX(maxpwr, enhinfo[i].mimo3); maxpwr /= 2; /* Convert half-dBm to dBm. */ DPRINTF(sc, IWN_DEBUG_RESET, "enhinfo %d, maxpwr=%d\n", i, maxpwr); sc->enh_maxpwr[i] = maxpwr; } } static struct ieee80211_node * iwn_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN]) { return kmalloc(sizeof (struct iwn_node), M_80211_NODE,M_INTWAIT | M_ZERO); } static void iwn_newassoc(struct ieee80211_node *ni, int isnew) { /* XXX move */ //if (!isnew) { ieee80211_ratectl_node_deinit(ni); //} ieee80211_ratectl_node_init(ni); } static int iwn_media_change(struct ifnet *ifp) { int error = ieee80211_media_change(ifp); /* NB: only the fixed rate can change and that doesn't need a reset */ return (error == ENETRESET ? 0 : error); } static int iwn_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg) { struct iwn_vap *ivp = IWN_VAP(vap); struct ieee80211com *ic = vap->iv_ic; struct iwn_softc *sc = ic->ic_ifp->if_softc; int error; DPRINTF(sc, IWN_DEBUG_STATE, "%s: %s -> %s\n", __func__, ieee80211_state_name[vap->iv_state], ieee80211_state_name[nstate]); callout_stop(&sc->sc_timer_to); if (nstate == IEEE80211_S_AUTH && vap->iv_state != IEEE80211_S_AUTH) { /* !AUTH -> AUTH requires adapter config */ /* Reset state to handle reassociations correctly. */ sc->rxon.associd = 0; sc->rxon.filter &= ~htole32(IWN_FILTER_BSS); iwn_calib_reset(sc); error = iwn_auth(sc, vap); } if (nstate == IEEE80211_S_RUN && vap->iv_state != IEEE80211_S_RUN) { /* * !RUN -> RUN requires setting the association id * which is done with a firmware cmd. We also defer * starting the timers until that work is done. */ error = iwn_run(sc, vap); } if (nstate == IEEE80211_S_RUN) { /* * RUN -> RUN transition; just restart the timers. */ iwn_calib_reset(sc); } return ivp->iv_newstate(vap, nstate, arg); } /* * Process an RX_PHY firmware notification. This is usually immediately * followed by an MPDU_RX_DONE notification. */ static void iwn_rx_phy(struct iwn_softc *sc, struct iwn_rx_desc *desc, struct iwn_rx_data *data) { struct iwn_rx_stat *stat = (struct iwn_rx_stat *)(desc + 1); DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: received PHY stats\n", __func__); bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD); /* Save RX statistics, they will be used on MPDU_RX_DONE. */ memcpy(&sc->last_rx_stat, stat, sizeof (*stat)); sc->last_rx_valid = 1; } static void iwn_timer_callout(void *arg) { struct iwn_softc *sc = arg; uint32_t flags = 0; wlan_serialize_enter(); if (sc->calib_cnt && --sc->calib_cnt == 0) { DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s\n", "send statistics request"); (void) iwn_cmd(sc, IWN_CMD_GET_STATISTICS, &flags, sizeof flags, 1); sc->calib_cnt = 60; /* do calibration every 60s */ } iwn_watchdog(sc); /* NB: piggyback tx watchdog */ callout_reset(&sc->sc_timer_to, hz, iwn_timer_callout, sc); wlan_serialize_exit(); } static void iwn_calib_reset(struct iwn_softc *sc) { callout_reset(&sc->sc_timer_to, hz, iwn_timer_callout, sc); sc->calib_cnt = 60; /* do calibration every 60s */ } /* * Process an RX_DONE (4965AGN only) or MPDU_RX_DONE firmware notification. * Each MPDU_RX_DONE notification must be preceded by an RX_PHY one. */ static void iwn_rx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc, struct iwn_rx_data *data) { const struct iwn_hal *hal = sc->sc_hal; struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct iwn_rx_ring *ring = &sc->rxq; struct ieee80211_frame *wh; struct ieee80211_node *ni; struct mbuf *m, *m1; struct iwn_rx_stat *stat; caddr_t head; bus_addr_t paddr; uint32_t flags; int error, len, rssi, nf; if (desc->type == IWN_MPDU_RX_DONE) { /* Check for prior RX_PHY notification. */ if (!sc->last_rx_valid) { DPRINTF(sc, IWN_DEBUG_ANY, "%s: missing RX_PHY\n", __func__); ifp->if_ierrors++; return; } sc->last_rx_valid = 0; stat = &sc->last_rx_stat; } else stat = (struct iwn_rx_stat *)(desc + 1); bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD); if (stat->cfg_phy_len > IWN_STAT_MAXLEN) { device_printf(sc->sc_dev, "%s: invalid rx statistic header, len %d\n", __func__, stat->cfg_phy_len); ifp->if_ierrors++; return; } if (desc->type == IWN_MPDU_RX_DONE) { struct iwn_rx_mpdu *mpdu = (struct iwn_rx_mpdu *)(desc + 1); head = (caddr_t)(mpdu + 1); len = le16toh(mpdu->len); } else { head = (caddr_t)(stat + 1) + stat->cfg_phy_len; len = le16toh(stat->len); } flags = le32toh(*(uint32_t *)(head + len)); /* Discard frames with a bad FCS early. */ if ((flags & IWN_RX_NOERROR) != IWN_RX_NOERROR) { DPRINTF(sc, IWN_DEBUG_RECV, "%s: rx flags error %x\n", __func__, flags); ifp->if_ierrors++; return; } /* Discard frames that are too short. */ if (len < sizeof (*wh)) { DPRINTF(sc, IWN_DEBUG_RECV, "%s: frame too short: %d\n", __func__, len); ifp->if_ierrors++; return; } /* XXX don't need mbuf, just dma buffer */ m1 = m_getjcl(MB_DONTWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE); if (m1 == NULL) { DPRINTF(sc, IWN_DEBUG_ANY, "%s: no mbuf to restock ring\n", __func__); ifp->if_ierrors++; return; } bus_dmamap_unload(ring->data_dmat, data->map); error = bus_dmamap_load(ring->data_dmat, data->map, mtod(m1, caddr_t), MJUMPAGESIZE, iwn_dma_map_addr, &paddr, BUS_DMA_NOWAIT); if (error != 0 && error != EFBIG) { device_printf(sc->sc_dev, "%s: bus_dmamap_load failed, error %d\n", __func__, error); m_freem(m1); ifp->if_ierrors++; return; } m = data->m; data->m = m1; /* Update RX descriptor. */ ring->desc[ring->cur] = htole32(paddr >> 8); bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map, BUS_DMASYNC_PREWRITE); /* Finalize mbuf. */ m->m_pkthdr.rcvif = ifp; m->m_data = head; m->m_pkthdr.len = m->m_len = len; rssi = hal->get_rssi(sc, stat); /* Grab a reference to the source node. */ wh = mtod(m, struct ieee80211_frame *); ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh); nf = (ni != NULL && ni->ni_vap->iv_state == IEEE80211_S_RUN && (ic->ic_flags & IEEE80211_F_SCAN) == 0) ? sc->noise : -95; if (ieee80211_radiotap_active(ic)) { struct iwn_rx_radiotap_header *tap = &sc->sc_rxtap; tap->wr_tsft = htole64(stat->tstamp); tap->wr_flags = 0; if (stat->flags & htole16(IWN_STAT_FLAG_SHPREAMBLE)) tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE; switch (stat->rate) { /* CCK rates. */ case 10: tap->wr_rate = 2; break; case 20: tap->wr_rate = 4; break; case 55: tap->wr_rate = 11; break; case 110: tap->wr_rate = 22; break; /* OFDM rates. */ case 0xd: tap->wr_rate = 12; break; case 0xf: tap->wr_rate = 18; break; case 0x5: tap->wr_rate = 24; break; case 0x7: tap->wr_rate = 36; break; case 0x9: tap->wr_rate = 48; break; case 0xb: tap->wr_rate = 72; break; case 0x1: tap->wr_rate = 96; break; case 0x3: tap->wr_rate = 108; break; /* Unknown rate: should not happen. */ default: tap->wr_rate = 0; } tap->wr_dbm_antsignal = rssi; tap->wr_dbm_antnoise = nf; } /* Send the frame to the 802.11 layer. */ if (ni != NULL) { (void) ieee80211_input(ni, m, rssi - nf, nf); /* Node is no longer needed. */ ieee80211_free_node(ni); } else { (void) ieee80211_input_all(ic, m, rssi - nf, nf); } } #if 0 /* HT */ /* Process an incoming Compressed BlockAck. */ static void iwn_rx_compressed_ba(struct iwn_softc *sc, struct iwn_rx_desc *desc, struct iwn_rx_data *data) { struct iwn_compressed_ba *ba = (struct iwn_compressed_ba *)(desc + 1); struct iwn_tx_ring *txq; txq = &sc->txq[letoh16(ba->qid)]; /* XXX TBD */ } #endif /* * Process a CALIBRATION_RESULT notification sent by the initialization * firmware on response to a CMD_CALIB_CONFIG command (5000 only.) */ static void iwn5000_rx_calib_results(struct iwn_softc *sc, struct iwn_rx_desc *desc, struct iwn_rx_data *data) { struct iwn_phy_calib *calib = (struct iwn_phy_calib *)(desc + 1); int len, idx = -1; /* Runtime firmware should not send such a notification. */ if (sc->sc_flags & IWN_FLAG_CALIB_DONE) return; bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD); len = (le32toh(desc->len) & 0x3fff) - 4; switch (calib->code) { case IWN5000_PHY_CALIB_DC: if (sc->hw_type == IWN_HW_REV_TYPE_5150 || sc->hw_type == IWN_HW_REV_TYPE_6050) idx = 0; break; case IWN5000_PHY_CALIB_LO: idx = 1; break; case IWN5000_PHY_CALIB_TX_IQ: idx = 2; break; case IWN5000_PHY_CALIB_TX_IQ_PERIODIC: if (sc->hw_type < IWN_HW_REV_TYPE_6000 && sc->hw_type != IWN_HW_REV_TYPE_5150) idx = 3; break; case IWN5000_PHY_CALIB_BASE_BAND: idx = 4; break; } if (idx == -1) /* Ignore other results. */ return; /* Save calibration result. */ if (sc->calibcmd[idx].buf != NULL) kfree(sc->calibcmd[idx].buf, M_DEVBUF); sc->calibcmd[idx].buf = kmalloc(len, M_DEVBUF, M_INTWAIT); if (sc->calibcmd[idx].buf == NULL) { DPRINTF(sc, IWN_DEBUG_CALIBRATE, "not enough memory for calibration result %d\n", calib->code); return; } DPRINTF(sc, IWN_DEBUG_CALIBRATE, "saving calibration result code=%d len=%d\n", calib->code, len); sc->calibcmd[idx].len = len; memcpy(sc->calibcmd[idx].buf, calib, len); } /* * Process an RX_STATISTICS or BEACON_STATISTICS firmware notification. * The latter is sent by the firmware after each received beacon. */ static void iwn_rx_statistics(struct iwn_softc *sc, struct iwn_rx_desc *desc, struct iwn_rx_data *data) { const struct iwn_hal *hal = sc->sc_hal; struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps); struct iwn_calib_state *calib = &sc->calib; struct iwn_stats *stats = (struct iwn_stats *)(desc + 1); int temp; /* Beacon stats are meaningful only when associated and not scanning. */ if (vap->iv_state != IEEE80211_S_RUN || (ic->ic_flags & IEEE80211_F_SCAN)) return; bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD); DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: cmd %d\n", __func__, desc->type); iwn_calib_reset(sc); /* Reset TX power calibration timeout. */ /* Test if temperature has changed. */ if (stats->general.temp != sc->rawtemp) { /* Convert "raw" temperature to degC. */ sc->rawtemp = stats->general.temp; temp = hal->get_temperature(sc); DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: temperature %d\n", __func__, temp); /* Update TX power if need be (4965AGN only.) */ if (sc->hw_type == IWN_HW_REV_TYPE_4965) iwn4965_power_calibration(sc, temp); } if (desc->type != IWN_BEACON_STATISTICS) return; /* Reply to a statistics request. */ sc->noise = iwn_get_noise(&stats->rx.general); DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: noise %d\n", __func__, sc->noise); /* Test that RSSI and noise are present in stats report. */ if (le32toh(stats->rx.general.flags) != 1) { DPRINTF(sc, IWN_DEBUG_ANY, "%s\n", "received statistics without RSSI"); return; } if (calib->state == IWN_CALIB_STATE_ASSOC) iwn_collect_noise(sc, &stats->rx.general); else if (calib->state == IWN_CALIB_STATE_RUN) iwn_tune_sensitivity(sc, &stats->rx); } /* * Process a TX_DONE firmware notification. Unfortunately, the 4965AGN * and 5000 adapters have different incompatible TX status formats. */ static void iwn4965_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc, struct iwn_rx_data *data) { struct iwn4965_tx_stat *stat = (struct iwn4965_tx_stat *)(desc + 1); struct iwn_tx_ring *ring = &sc->txq[desc->qid & 0xf]; DPRINTF(sc, IWN_DEBUG_XMIT, "%s: " "qid %d idx %d retries %d nkill %d rate %x duration %d status %x\n", __func__, desc->qid, desc->idx, stat->ackfailcnt, stat->btkillcnt, stat->rate, le16toh(stat->duration), le32toh(stat->status)); bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD); iwn_tx_done(sc, desc, stat->ackfailcnt, le32toh(stat->status) & 0xff); } static void iwn5000_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc, struct iwn_rx_data *data) { struct iwn5000_tx_stat *stat = (struct iwn5000_tx_stat *)(desc + 1); struct iwn_tx_ring *ring = &sc->txq[desc->qid & 0xf]; DPRINTF(sc, IWN_DEBUG_XMIT, "%s: " "qid %d idx %d retries %d nkill %d rate %x duration %d status %x\n", __func__, desc->qid, desc->idx, stat->ackfailcnt, stat->btkillcnt, stat->rate, le16toh(stat->duration), le32toh(stat->status)); #ifdef notyet /* Reset TX scheduler slot. */ iwn5000_reset_sched(sc, desc->qid & 0xf, desc->idx); #endif bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD); iwn_tx_done(sc, desc, stat->ackfailcnt, le16toh(stat->status) & 0xff); } /* * Adapter-independent backend for TX_DONE firmware notifications. */ static void iwn_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc, int ackfailcnt, uint8_t status) { struct ifnet *ifp = sc->sc_ifp; struct iwn_tx_ring *ring = &sc->txq[desc->qid & 0xf]; struct iwn_tx_data *data = &ring->data[desc->idx]; struct mbuf *m; struct ieee80211_node *ni; struct ieee80211vap *vap; KASSERT(data->ni != NULL, ("no node")); /* Unmap and free mbuf. */ bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTWRITE); bus_dmamap_unload(ring->data_dmat, data->map); m = data->m, data->m = NULL; ni = data->ni, data->ni = NULL; vap = ni->ni_vap; if (m->m_flags & M_TXCB) { /* * Channels marked for "radar" require traffic to be received * to unlock before we can transmit. Until traffic is seen * any attempt to transmit is returned immediately with status * set to IWN_TX_FAIL_TX_LOCKED. Unfortunately this can easily * happen on first authenticate after scanning. To workaround * this we ignore a failure of this sort in AUTH state so the * 802.11 layer will fall back to using a timeout to wait for * the AUTH reply. This allows the firmware time to see * traffic so a subsequent retry of AUTH succeeds. It's * unclear why the firmware does not maintain state for * channels recently visited as this would allow immediate * use of the channel after a scan (where we see traffic). */ if (status == IWN_TX_FAIL_TX_LOCKED && ni->ni_vap->iv_state == IEEE80211_S_AUTH) ieee80211_process_callback(ni, m, 0); else ieee80211_process_callback(ni, m, (status & IWN_TX_FAIL) != 0); } /* * Update rate control statistics for the node. */ if (status & 0x80) { ifp->if_oerrors++; ieee80211_ratectl_tx_complete(vap, ni, IEEE80211_RATECTL_TX_FAILURE, &ackfailcnt, NULL); } else { ieee80211_ratectl_tx_complete(vap, ni, IEEE80211_RATECTL_TX_SUCCESS, &ackfailcnt, NULL); } m_freem(m); ieee80211_free_node(ni); sc->sc_tx_timer = 0; if (--ring->queued < IWN_TX_RING_LOMARK) { sc->qfullmsk &= ~(1 << ring->qid); if (sc->qfullmsk == 0 && (ifp->if_flags & IFF_OACTIVE)) { ifp->if_flags &= ~IFF_OACTIVE; iwn_start_locked(ifp); } } } /* * Process a "command done" firmware notification. This is where we wakeup * processes waiting for a synchronous command completion. */ static void iwn_cmd_done(struct iwn_softc *sc, struct iwn_rx_desc *desc) { struct iwn_tx_ring *ring = &sc->txq[4]; struct iwn_tx_data *data; if ((desc->qid & 0xf) != 4) return; /* Not a command ack. */ data = &ring->data[desc->idx]; /* If the command was mapped in an mbuf, free it. */ if (data->m != NULL) { bus_dmamap_unload(ring->data_dmat, data->map); m_freem(data->m); data->m = NULL; } wakeup(&ring->desc[desc->idx]); } /* * Process an INT_FH_RX or INT_SW_RX interrupt. */ static void iwn_notif_intr(struct iwn_softc *sc) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps); uint16_t hw; bus_dmamap_sync(sc->rxq.stat_dma.tag, sc->rxq.stat_dma.map, BUS_DMASYNC_POSTREAD); hw = le16toh(sc->rxq.stat->closed_count) & 0xfff; while (sc->rxq.cur != hw) { struct iwn_rx_data *data = &sc->rxq.data[sc->rxq.cur]; struct iwn_rx_desc *desc; bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD); desc = mtod(data->m, struct iwn_rx_desc *); DPRINTF(sc, IWN_DEBUG_RECV, "%s: qid %x idx %d flags %x type %d(%s) len %d\n", __func__, desc->qid & 0xf, desc->idx, desc->flags, desc->type, iwn_intr_str(desc->type), le16toh(desc->len)); if (!(desc->qid & 0x80)) /* Reply to a command. */ iwn_cmd_done(sc, desc); switch (desc->type) { case IWN_RX_PHY: iwn_rx_phy(sc, desc, data); break; case IWN_RX_DONE: /* 4965AGN only. */ case IWN_MPDU_RX_DONE: /* An 802.11 frame has been received. */ iwn_rx_done(sc, desc, data); break; #if 0 /* HT */ case IWN_RX_COMPRESSED_BA: /* A Compressed BlockAck has been received. */ iwn_rx_compressed_ba(sc, desc, data); break; #endif case IWN_TX_DONE: /* An 802.11 frame has been transmitted. */ sc->sc_hal->tx_done(sc, desc, data); break; case IWN_RX_STATISTICS: case IWN_BEACON_STATISTICS: iwn_rx_statistics(sc, desc, data); break; case IWN_BEACON_MISSED: { struct iwn_beacon_missed *miss = (struct iwn_beacon_missed *)(desc + 1); int misses; bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD); misses = le32toh(miss->consecutive); /* XXX not sure why we're notified w/ zero */ if (misses == 0) break; DPRINTF(sc, IWN_DEBUG_STATE, "%s: beacons missed %d/%d\n", __func__, misses, le32toh(miss->total)); /* * If more than 5 consecutive beacons are missed, * reinitialize the sensitivity state machine. */ if (vap->iv_state == IEEE80211_S_RUN && misses > 5) (void) iwn_init_sensitivity(sc); if (misses >= vap->iv_bmissthreshold) ieee80211_beacon_miss(ic); break; } case IWN_UC_READY: { struct iwn_ucode_info *uc = (struct iwn_ucode_info *)(desc + 1); /* The microcontroller is ready. */ bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD); DPRINTF(sc, IWN_DEBUG_RESET, "microcode alive notification version=%d.%d " "subtype=%x alive=%x\n", uc->major, uc->minor, uc->subtype, le32toh(uc->valid)); if (le32toh(uc->valid) != 1) { device_printf(sc->sc_dev, "microcontroller initialization failed"); break; } if (uc->subtype == IWN_UCODE_INIT) { /* Save microcontroller report. */ memcpy(&sc->ucode_info, uc, sizeof (*uc)); } /* Save the address of the error log in SRAM. */ sc->errptr = le32toh(uc->errptr); break; } case IWN_STATE_CHANGED: { uint32_t *status = (uint32_t *)(desc + 1); /* * State change allows hardware switch change to be * noted. However, we handle this in iwn_intr as we * get both the enable/disble intr. */ bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD); DPRINTF(sc, IWN_DEBUG_INTR, "state changed to %x\n", le32toh(*status)); break; } case IWN_START_SCAN: { struct iwn_start_scan *scan = (struct iwn_start_scan *)(desc + 1); bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD); DPRINTF(sc, IWN_DEBUG_ANY, "%s: scanning channel %d status %x\n", __func__, scan->chan, le32toh(scan->status)); break; } case IWN_STOP_SCAN: { struct iwn_stop_scan *scan = (struct iwn_stop_scan *)(desc + 1); bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD); DPRINTF(sc, IWN_DEBUG_STATE, "scan finished nchan=%d status=%d chan=%d\n", scan->nchan, scan->status, scan->chan); ieee80211_scan_next(vap); break; } case IWN5000_CALIBRATION_RESULT: iwn5000_rx_calib_results(sc, desc, data); break; case IWN5000_CALIBRATION_DONE: sc->sc_flags |= IWN_FLAG_CALIB_DONE; wakeup(sc); break; } sc->rxq.cur = (sc->rxq.cur + 1) % IWN_RX_RING_COUNT; } /* Tell the firmware what we have processed. */ hw = (hw == 0) ? IWN_RX_RING_COUNT - 1 : hw - 1; IWN_WRITE(sc, IWN_FH_RX_WPTR, hw & ~7); } /* * Process an INT_WAKEUP interrupt raised when the microcontroller wakes up * from power-down sleep mode. */ static void iwn_wakeup_intr(struct iwn_softc *sc) { int qid; DPRINTF(sc, IWN_DEBUG_RESET, "%s: ucode wakeup from power-down sleep\n", __func__); /* Wakeup RX and TX rings. */ IWN_WRITE(sc, IWN_FH_RX_WPTR, sc->rxq.cur & ~7); for (qid = 0; qid < sc->sc_hal->ntxqs; qid++) { struct iwn_tx_ring *ring = &sc->txq[qid]; IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | ring->cur); } } static void iwn_rftoggle_intr(struct iwn_softc *sc) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; uint32_t tmp = IWN_READ(sc, IWN_GP_CNTRL); device_printf(sc->sc_dev, "RF switch: radio %s\n", (tmp & IWN_GP_CNTRL_RFKILL) ? "enabled" : "disabled"); if (tmp & IWN_GP_CNTRL_RFKILL) ieee80211_runtask(ic, &sc->sc_radioon_task); else ieee80211_runtask(ic, &sc->sc_radiooff_task); } /* * Dump the error log of the firmware when a firmware panic occurs. Although * we can't debug the firmware because it is neither open source nor free, it * can help us to identify certain classes of problems. */ static void iwn_fatal_intr(struct iwn_softc *sc) { const struct iwn_hal *hal = sc->sc_hal; struct iwn_fw_dump dump; int i; /* Force a complete recalibration on next init. */ sc->sc_flags &= ~IWN_FLAG_CALIB_DONE; /* Check that the error log address is valid. */ if (sc->errptr < IWN_FW_DATA_BASE || sc->errptr + sizeof (dump) > IWN_FW_DATA_BASE + hal->fw_data_maxsz) { kprintf("%s: bad firmware error log address 0x%08x\n", __func__, sc->errptr); return; } if (iwn_nic_lock(sc) != 0) { kprintf("%s: could not read firmware error log\n", __func__); return; } /* Read firmware error log from SRAM. */ iwn_mem_read_region_4(sc, sc->errptr, (uint32_t *)&dump, sizeof (dump) / sizeof (uint32_t)); iwn_nic_unlock(sc); if (dump.valid == 0) { kprintf("%s: firmware error log is empty\n", __func__); return; } kprintf("firmware error log:\n"); kprintf(" error type = \"%s\" (0x%08X)\n", (dump.id < NELEM(iwn_fw_errmsg)) ? iwn_fw_errmsg[dump.id] : "UNKNOWN", dump.id); kprintf(" program counter = 0x%08X\n", dump.pc); kprintf(" source line = 0x%08X\n", dump.src_line); kprintf(" error data = 0x%08X%08X\n", dump.error_data[0], dump.error_data[1]); kprintf(" branch link = 0x%08X%08X\n", dump.branch_link[0], dump.branch_link[1]); kprintf(" interrupt link = 0x%08X%08X\n", dump.interrupt_link[0], dump.interrupt_link[1]); kprintf(" time = %u\n", dump.time[0]); /* Dump driver status (TX and RX rings) while we're here. */ kprintf("driver status:\n"); for (i = 0; i < hal->ntxqs; i++) { struct iwn_tx_ring *ring = &sc->txq[i]; kprintf(" tx ring %2d: qid=%-2d cur=%-3d queued=%-3d\n", i, ring->qid, ring->cur, ring->queued); } kprintf(" rx ring: cur=%d\n", sc->rxq.cur); } static void iwn_intr(void *arg) { struct iwn_softc *sc = arg; struct ifnet *ifp = sc->sc_ifp; uint32_t r1, r2, tmp; /* Disable interrupts. */ IWN_WRITE(sc, IWN_INT_MASK, 0); /* Read interrupts from ICT (fast) or from registers (slow). */ if (sc->sc_flags & IWN_FLAG_USE_ICT) { tmp = 0; while (sc->ict[sc->ict_cur] != 0) { tmp |= sc->ict[sc->ict_cur]; sc->ict[sc->ict_cur] = 0; /* Acknowledge. */ sc->ict_cur = (sc->ict_cur + 1) % IWN_ICT_COUNT; } tmp = le32toh(tmp); if (tmp == 0xffffffff) /* Shouldn't happen. */ tmp = 0; else if (tmp & 0xc0000) /* Workaround a HW bug. */ tmp |= 0x8000; r1 = (tmp & 0xff00) << 16 | (tmp & 0xff); r2 = 0; /* Unused. */ } else { r1 = IWN_READ(sc, IWN_INT); if (r1 == 0xffffffff || (r1 & 0xfffffff0) == 0xa5a5a5a0) return; /* Hardware gone! */ r2 = IWN_READ(sc, IWN_FH_INT); } DPRINTF(sc, IWN_DEBUG_INTR, "interrupt reg1=%x reg2=%x\n", r1, r2); if (r1 == 0 && r2 == 0) goto done; /* Interrupt not for us. */ /* Acknowledge interrupts. */ IWN_WRITE(sc, IWN_INT, r1); if (!(sc->sc_flags & IWN_FLAG_USE_ICT)) IWN_WRITE(sc, IWN_FH_INT, r2); if (r1 & IWN_INT_RF_TOGGLED) { iwn_rftoggle_intr(sc); goto done; } if (r1 & IWN_INT_CT_REACHED) { device_printf(sc->sc_dev, "%s: critical temperature reached!\n", __func__); } if (r1 & (IWN_INT_SW_ERR | IWN_INT_HW_ERR)) { iwn_fatal_intr(sc); ifp->if_flags &= ~IFF_UP; iwn_stop_locked(sc); goto done; } if ((r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX | IWN_INT_RX_PERIODIC)) || (r2 & IWN_FH_INT_RX)) { if (sc->sc_flags & IWN_FLAG_USE_ICT) { if (r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX)) IWN_WRITE(sc, IWN_FH_INT, IWN_FH_INT_RX); IWN_WRITE_1(sc, IWN_INT_PERIODIC, IWN_INT_PERIODIC_DIS); iwn_notif_intr(sc); if (r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX)) { IWN_WRITE_1(sc, IWN_INT_PERIODIC, IWN_INT_PERIODIC_ENA); } } else iwn_notif_intr(sc); } if ((r1 & IWN_INT_FH_TX) || (r2 & IWN_FH_INT_TX)) { if (sc->sc_flags & IWN_FLAG_USE_ICT) IWN_WRITE(sc, IWN_FH_INT, IWN_FH_INT_TX); wakeup(sc); /* FH DMA transfer completed. */ } if (r1 & IWN_INT_ALIVE) wakeup(sc); /* Firmware is alive. */ if (r1 & IWN_INT_WAKEUP) iwn_wakeup_intr(sc); done: /* Re-enable interrupts. */ if (ifp->if_flags & IFF_UP) IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask); } /* * Update TX scheduler ring when transmitting an 802.11 frame (4965AGN and * 5000 adapters use a slightly different format.) */ static void iwn4965_update_sched(struct iwn_softc *sc, int qid, int idx, uint8_t id, uint16_t len) { uint16_t *w = &sc->sched[qid * IWN4965_SCHED_COUNT + idx]; *w = htole16(len + 8); bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map, BUS_DMASYNC_PREWRITE); if (idx < IWN_SCHED_WINSZ) { *(w + IWN_TX_RING_COUNT) = *w; bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map, BUS_DMASYNC_PREWRITE); } } static void iwn5000_update_sched(struct iwn_softc *sc, int qid, int idx, uint8_t id, uint16_t len) { uint16_t *w = &sc->sched[qid * IWN5000_SCHED_COUNT + idx]; *w = htole16(id << 12 | (len + 8)); bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map, BUS_DMASYNC_PREWRITE); if (idx < IWN_SCHED_WINSZ) { *(w + IWN_TX_RING_COUNT) = *w; bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map, BUS_DMASYNC_PREWRITE); } } #ifdef notyet static void iwn5000_reset_sched(struct iwn_softc *sc, int qid, int idx) { uint16_t *w = &sc->sched[qid * IWN5000_SCHED_COUNT + idx]; *w = (*w & htole16(0xf000)) | htole16(1); bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map, BUS_DMASYNC_PREWRITE); if (idx < IWN_SCHED_WINSZ) { *(w + IWN_TX_RING_COUNT) = *w; bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map, BUS_DMASYNC_PREWRITE); } } #endif static uint8_t iwn_plcp_signal(int rate) { int i; for (i = 0; i < IWN_RIDX_MAX + 1; i++) { if (rate == iwn_rates[i].rate) return i; } return 0; } static int iwn_tx_data(struct iwn_softc *sc, struct mbuf *m, struct ieee80211_node *ni, struct iwn_tx_ring *ring) { const struct iwn_hal *hal = sc->sc_hal; const struct ieee80211_txparam *tp; const struct iwn_rate *rinfo; struct ieee80211vap *vap = ni->ni_vap; struct ieee80211com *ic = ni->ni_ic; struct iwn_node *wn = (void *)ni; struct iwn_tx_desc *desc; struct iwn_tx_data *data; struct iwn_tx_cmd *cmd; struct iwn_cmd_data *tx; struct ieee80211_frame *wh; struct ieee80211_key *k = NULL; struct mbuf *mnew; bus_dma_segment_t segs[IWN_MAX_SCATTER]; uint32_t flags; u_int hdrlen; int totlen, error, pad, nsegs = 0, i, rate; uint8_t ridx, type, txant; wh = mtod(m, struct ieee80211_frame *); hdrlen = ieee80211_anyhdrsize(wh); type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK; desc = &ring->desc[ring->cur]; data = &ring->data[ring->cur]; /* Choose a TX rate index. */ tp = &vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)]; if (type == IEEE80211_FC0_TYPE_MGT) rate = tp->mgmtrate; else if (IEEE80211_IS_MULTICAST(wh->i_addr1)) rate = tp->mcastrate; else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE) rate = tp->ucastrate; else { /* XXX pass pktlen */ ieee80211_ratectl_rate(ni, NULL, 0); rate = ni->ni_txrate; } ridx = iwn_plcp_signal(rate); rinfo = &iwn_rates[ridx]; /* Encrypt the frame if need be. */ if (wh->i_fc[1] & IEEE80211_FC1_WEP) { k = ieee80211_crypto_encap(ni, m); if (k == NULL) { m_freem(m); return ENOBUFS; } /* Packet header may have moved, reset our local pointer. */ wh = mtod(m, struct ieee80211_frame *); } totlen = m->m_pkthdr.len; if (ieee80211_radiotap_active_vap(vap)) { struct iwn_tx_radiotap_header *tap = &sc->sc_txtap; tap->wt_flags = 0; tap->wt_rate = rinfo->rate; if (k != NULL) tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP; ieee80211_radiotap_tx(vap, m); } /* Prepare TX firmware command. */ cmd = &ring->cmd[ring->cur]; cmd->code = IWN_CMD_TX_DATA; cmd->flags = 0; cmd->qid = ring->qid; cmd->idx = ring->cur; tx = (struct iwn_cmd_data *)cmd->data; /* NB: No need to clear tx, all fields are reinitialized here. */ tx->scratch = 0; /* clear "scratch" area */ flags = 0; if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) flags |= IWN_TX_NEED_ACK; if ((wh->i_fc[0] & (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) == (IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_BAR)) flags |= IWN_TX_IMM_BA; /* Cannot happen yet. */ if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG) flags |= IWN_TX_MORE_FRAG; /* Cannot happen yet. */ /* Check if frame must be protected using RTS/CTS or CTS-to-self. */ if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) { /* NB: Group frames are sent using CCK in 802.11b/g. */ if (totlen + IEEE80211_CRC_LEN > vap->iv_rtsthreshold) { flags |= IWN_TX_NEED_RTS; } else if ((ic->ic_flags & IEEE80211_F_USEPROT) && ridx >= IWN_RIDX_OFDM6) { if (ic->ic_protmode == IEEE80211_PROT_CTSONLY) flags |= IWN_TX_NEED_CTS; else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS) flags |= IWN_TX_NEED_RTS; } if (flags & (IWN_TX_NEED_RTS | IWN_TX_NEED_CTS)) { if (sc->hw_type != IWN_HW_REV_TYPE_4965) { /* 5000 autoselects RTS/CTS or CTS-to-self. */ flags &= ~(IWN_TX_NEED_RTS | IWN_TX_NEED_CTS); flags |= IWN_TX_NEED_PROTECTION; } else flags |= IWN_TX_FULL_TXOP; } } if (IEEE80211_IS_MULTICAST(wh->i_addr1) || type != IEEE80211_FC0_TYPE_DATA) tx->id = hal->broadcast_id; else tx->id = wn->id; if (type == IEEE80211_FC0_TYPE_MGT) { uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK; /* Tell HW to set timestamp in probe responses. */ if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP) flags |= IWN_TX_INSERT_TSTAMP; if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ || subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ) tx->timeout = htole16(3); else tx->timeout = htole16(2); } else tx->timeout = htole16(0); if (hdrlen & 3) { /* First segment length must be a multiple of 4. */ flags |= IWN_TX_NEED_PADDING; pad = 4 - (hdrlen & 3); } else pad = 0; tx->len = htole16(totlen); tx->tid = 0; tx->rts_ntries = 60; tx->data_ntries = 15; tx->lifetime = htole32(IWN_LIFETIME_INFINITE); tx->plcp = rinfo->plcp; tx->rflags = rinfo->flags; if (tx->id == hal->broadcast_id) { /* Group or management frame. */ tx->linkq = 0; /* XXX Alternate between antenna A and B? */ txant = IWN_LSB(sc->txchainmask); tx->rflags |= IWN_RFLAG_ANT(txant); } else { tx->linkq = IWN_RIDX_OFDM54 - ridx; flags |= IWN_TX_LINKQ; /* enable MRR */ } /* Set physical address of "scratch area". */ tx->loaddr = htole32(IWN_LOADDR(data->scratch_paddr)); tx->hiaddr = IWN_HIADDR(data->scratch_paddr); /* Copy 802.11 header in TX command. */ memcpy((uint8_t *)(tx + 1), wh, hdrlen); /* Trim 802.11 header. */ m_adj(m, hdrlen); tx->security = 0; tx->flags = htole32(flags); if (m->m_len > 0) { error = bus_dmamap_load_mbuf_segment(ring->data_dmat, data->map, m, segs, IWN_MAX_SCATTER - 1, &nsegs, BUS_DMA_NOWAIT); if (error == EFBIG) { /* too many fragments, linearize */ mnew = m_defrag(m, MB_DONTWAIT); if (mnew == NULL) { device_printf(sc->sc_dev, "%s: could not defrag mbuf\n", __func__); m_freem(m); return ENOBUFS; } m = mnew; error = bus_dmamap_load_mbuf_segment(ring->data_dmat, data->map, m, segs, IWN_MAX_SCATTER - 1, &nsegs, BUS_DMA_NOWAIT); } if (error != 0) { device_printf(sc->sc_dev, "%s: bus_dmamap_load_mbuf_segment failed, error %d\n", __func__, error); m_freem(m); return error; } } data->m = m; data->ni = ni; DPRINTF(sc, IWN_DEBUG_XMIT, "%s: qid %d idx %d len %d nsegs %d\n", __func__, ring->qid, ring->cur, m->m_pkthdr.len, nsegs); /* Fill TX descriptor. */ desc->nsegs = 1 + nsegs; /* First DMA segment is used by the TX command. */ desc->segs[0].addr = htole32(IWN_LOADDR(data->cmd_paddr)); desc->segs[0].len = htole16(IWN_HIADDR(data->cmd_paddr) | (4 + sizeof (*tx) + hdrlen + pad) << 4); /* Other DMA segments are for data payload. */ for (i = 1; i <= nsegs; i++) { desc->segs[i].addr = htole32(IWN_LOADDR(segs[i - 1].ds_addr)); desc->segs[i].len = htole16(IWN_HIADDR(segs[i - 1].ds_addr) | segs[i - 1].ds_len << 4); } bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE); bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map, BUS_DMASYNC_PREWRITE); bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map, BUS_DMASYNC_PREWRITE); #ifdef notyet /* Update TX scheduler. */ hal->update_sched(sc, ring->qid, ring->cur, tx->id, totlen); #endif /* Kick TX ring. */ ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT; IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur); /* Mark TX ring as full if we reach a certain threshold. */ if (++ring->queued > IWN_TX_RING_HIMARK) sc->qfullmsk |= 1 << ring->qid; return 0; } static int iwn_tx_data_raw(struct iwn_softc *sc, struct mbuf *m, struct ieee80211_node *ni, struct iwn_tx_ring *ring, const struct ieee80211_bpf_params *params) { const struct iwn_hal *hal = sc->sc_hal; const struct iwn_rate *rinfo; struct ifnet *ifp = sc->sc_ifp; struct ieee80211vap *vap = ni->ni_vap; struct ieee80211com *ic = ifp->if_l2com; struct iwn_tx_cmd *cmd; struct iwn_cmd_data *tx; struct ieee80211_frame *wh; struct iwn_tx_desc *desc; struct iwn_tx_data *data; struct mbuf *mnew; bus_addr_t paddr; bus_dma_segment_t segs[IWN_MAX_SCATTER]; uint32_t flags; u_int hdrlen; int totlen, error, pad, nsegs = 0, i, rate; uint8_t ridx, type, txant; wh = mtod(m, struct ieee80211_frame *); hdrlen = ieee80211_anyhdrsize(wh); type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK; desc = &ring->desc[ring->cur]; data = &ring->data[ring->cur]; /* Choose a TX rate index. */ rate = params->ibp_rate0; if (!ieee80211_isratevalid(ic->ic_rt, rate)) { /* XXX fall back to mcast/mgmt rate? */ m_freem(m); return EINVAL; } ridx = iwn_plcp_signal(rate); rinfo = &iwn_rates[ridx]; totlen = m->m_pkthdr.len; /* Prepare TX firmware command. */ cmd = &ring->cmd[ring->cur]; cmd->code = IWN_CMD_TX_DATA; cmd->flags = 0; cmd->qid = ring->qid; cmd->idx = ring->cur; tx = (struct iwn_cmd_data *)cmd->data; /* NB: No need to clear tx, all fields are reinitialized here. */ tx->scratch = 0; /* clear "scratch" area */ flags = 0; if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0) flags |= IWN_TX_NEED_ACK; if (params->ibp_flags & IEEE80211_BPF_RTS) { if (sc->hw_type != IWN_HW_REV_TYPE_4965) { /* 5000 autoselects RTS/CTS or CTS-to-self. */ flags &= ~IWN_TX_NEED_RTS; flags |= IWN_TX_NEED_PROTECTION; } else flags |= IWN_TX_NEED_RTS | IWN_TX_FULL_TXOP; } if (params->ibp_flags & IEEE80211_BPF_CTS) { if (sc->hw_type != IWN_HW_REV_TYPE_4965) { /* 5000 autoselects RTS/CTS or CTS-to-self. */ flags &= ~IWN_TX_NEED_CTS; flags |= IWN_TX_NEED_PROTECTION; } else flags |= IWN_TX_NEED_CTS | IWN_TX_FULL_TXOP; } if (type == IEEE80211_FC0_TYPE_MGT) { uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK; if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP) flags |= IWN_TX_INSERT_TSTAMP; if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ || subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ) tx->timeout = htole16(3); else tx->timeout = htole16(2); } else tx->timeout = htole16(0); if (hdrlen & 3) { /* First segment length must be a multiple of 4. */ flags |= IWN_TX_NEED_PADDING; pad = 4 - (hdrlen & 3); } else pad = 0; if (ieee80211_radiotap_active_vap(vap)) { struct iwn_tx_radiotap_header *tap = &sc->sc_txtap; tap->wt_flags = 0; tap->wt_rate = rate; ieee80211_radiotap_tx(vap, m); } tx->len = htole16(totlen); tx->tid = 0; tx->id = hal->broadcast_id; tx->rts_ntries = params->ibp_try1; tx->data_ntries = params->ibp_try0; tx->lifetime = htole32(IWN_LIFETIME_INFINITE); tx->plcp = rinfo->plcp; tx->rflags = rinfo->flags; /* Group or management frame. */ tx->linkq = 0; txant = IWN_LSB(sc->txchainmask); tx->rflags |= IWN_RFLAG_ANT(txant); /* Set physical address of "scratch area". */ paddr = ring->cmd_dma.paddr + ring->cur * sizeof (struct iwn_tx_cmd); tx->loaddr = htole32(IWN_LOADDR(paddr)); tx->hiaddr = IWN_HIADDR(paddr); /* Copy 802.11 header in TX command. */ memcpy((uint8_t *)(tx + 1), wh, hdrlen); /* Trim 802.11 header. */ m_adj(m, hdrlen); tx->security = 0; tx->flags = htole32(flags); if (m->m_len > 0) { error = bus_dmamap_load_mbuf_segment(ring->data_dmat, data->map, m, segs, IWN_MAX_SCATTER - 1, &nsegs, BUS_DMA_NOWAIT); if (error == EFBIG) { /* Too many fragments, linearize. */ mnew = m_defrag(m, MB_DONTWAIT); if (mnew == NULL) { device_printf(sc->sc_dev, "%s: could not defrag mbuf\n", __func__); m_freem(m); return ENOBUFS; } m = mnew; error = bus_dmamap_load_mbuf_segment(ring->data_dmat, data->map, m, segs, IWN_MAX_SCATTER - 1, &nsegs, BUS_DMA_NOWAIT); } if (error != 0) { device_printf(sc->sc_dev, "%s: bus_dmamap_load_mbuf_segment failed, error %d\n", __func__, error); m_freem(m); return error; } } data->m = m; data->ni = ni; DPRINTF(sc, IWN_DEBUG_XMIT, "%s: qid %d idx %d len %d nsegs %d\n", __func__, ring->qid, ring->cur, m->m_pkthdr.len, nsegs); /* Fill TX descriptor. */ desc->nsegs = 1 + nsegs; /* First DMA segment is used by the TX command. */ desc->segs[0].addr = htole32(IWN_LOADDR(data->cmd_paddr)); desc->segs[0].len = htole16(IWN_HIADDR(data->cmd_paddr) | (4 + sizeof (*tx) + hdrlen + pad) << 4); /* Other DMA segments are for data payload. */ for (i = 1; i <= nsegs; i++) { desc->segs[i].addr = htole32(IWN_LOADDR(segs[i - 1].ds_addr)); desc->segs[i].len = htole16(IWN_HIADDR(segs[i - 1].ds_addr) | segs[i - 1].ds_len << 4); } bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE); bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map, BUS_DMASYNC_PREWRITE); bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map, BUS_DMASYNC_PREWRITE); #ifdef notyet /* Update TX scheduler. */ hal->update_sched(sc, ring->qid, ring->cur, tx->id, totlen); #endif /* Kick TX ring. */ ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT; IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur); /* Mark TX ring as full if we reach a certain threshold. */ if (++ring->queued > IWN_TX_RING_HIMARK) sc->qfullmsk |= 1 << ring->qid; return 0; } static int iwn_raw_xmit(struct ieee80211_node *ni, struct mbuf *m, const struct ieee80211_bpf_params *params) { struct ieee80211com *ic = ni->ni_ic; struct ifnet *ifp = ic->ic_ifp; struct iwn_softc *sc = ifp->if_softc; struct iwn_tx_ring *txq; int error = 0; if ((ifp->if_flags & IFF_RUNNING) == 0) { ieee80211_free_node(ni); m_freem(m); return ENETDOWN; } if (params == NULL) txq = &sc->txq[M_WME_GETAC(m)]; else txq = &sc->txq[params->ibp_pri & 3]; if (params == NULL) { /* * Legacy path; interpret frame contents to decide * precisely how to send the frame. */ error = iwn_tx_data(sc, m, ni, txq); } else { /* * Caller supplied explicit parameters to use in * sending the frame. */ error = iwn_tx_data_raw(sc, m, ni, txq, params); } if (error != 0) { /* NB: m is reclaimed on tx failure */ ieee80211_free_node(ni); ifp->if_oerrors++; } return error; } static void iwn_start(struct ifnet *ifp) { struct iwn_softc *sc; sc = ifp->if_softc; wlan_serialize_enter(); iwn_start_locked(ifp); wlan_serialize_exit(); } static void iwn_start_locked(struct ifnet *ifp) { struct iwn_softc *sc = ifp->if_softc; struct ieee80211_node *ni; struct iwn_tx_ring *txq; struct mbuf *m; int pri; for (;;) { if (sc->qfullmsk != 0) { ifp->if_flags |= IFF_OACTIVE; break; } m = ifq_dequeue(&ifp->if_snd, NULL); if (m == NULL) break; KKASSERT(M_TRAILINGSPACE(m) >= 0); ni = (struct ieee80211_node *)m->m_pkthdr.rcvif; pri = M_WME_GETAC(m); txq = &sc->txq[pri]; if (iwn_tx_data(sc, m, ni, txq) != 0) { ifp->if_oerrors++; ieee80211_free_node(ni); break; } sc->sc_tx_timer = 5; } } static void iwn_watchdog(struct iwn_softc *sc) { if (sc->sc_tx_timer > 0 && --sc->sc_tx_timer == 0) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; if_printf(ifp, "device timeout\n"); ieee80211_runtask(ic, &sc->sc_reinit_task); } } static int iwn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data, struct ucred *ucred) { struct iwn_softc *sc = ifp->if_softc; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps); struct ifreq *ifr = (struct ifreq *) data; int error = 0, startall = 0, stop = 0; switch (cmd) { case SIOCSIFFLAGS: if (ifp->if_flags & IFF_UP) { if (!(ifp->if_flags & IFF_RUNNING)) { iwn_init_locked(sc); if (IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_RFKILL) startall = 1; else stop = 1; } } else { if (ifp->if_flags & IFF_RUNNING) iwn_stop_locked(sc); } if (startall) ieee80211_start_all(ic); else if (vap != NULL && stop) ieee80211_stop(vap); break; case SIOCGIFMEDIA: error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd); break; case SIOCGIFADDR: error = ether_ioctl(ifp, cmd, data); break; default: error = EINVAL; break; } return error; } /* * Send a command to the firmware. */ static int iwn_cmd(struct iwn_softc *sc, int code, const void *buf, int size, int async) { struct iwn_tx_ring *ring = &sc->txq[4]; struct iwn_tx_desc *desc; struct iwn_tx_data *data; struct iwn_tx_cmd *cmd; struct mbuf *m; bus_addr_t paddr; int totlen, error; desc = &ring->desc[ring->cur]; data = &ring->data[ring->cur]; totlen = 4 + size; if (size > sizeof cmd->data) { /* Command is too large to fit in a descriptor. */ if (totlen > MJUMPAGESIZE) return EINVAL; m = m_getjcl(MB_DONTWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE); if (m == NULL) return ENOMEM; cmd = mtod(m, struct iwn_tx_cmd *); error = bus_dmamap_load(ring->data_dmat, data->map, cmd, totlen, iwn_dma_map_addr, &paddr, BUS_DMA_NOWAIT); if (error != 0) { m_freem(m); return error; } data->m = m; } else { cmd = &ring->cmd[ring->cur]; paddr = data->cmd_paddr; } cmd->code = code; cmd->flags = 0; cmd->qid = ring->qid; cmd->idx = ring->cur; memcpy(cmd->data, buf, size); desc->nsegs = 1; desc->segs[0].addr = htole32(IWN_LOADDR(paddr)); desc->segs[0].len = htole16(IWN_HIADDR(paddr) | totlen << 4); DPRINTF(sc, IWN_DEBUG_CMD, "%s: %s (0x%x) flags %d qid %d idx %d\n", __func__, iwn_intr_str(cmd->code), cmd->code, cmd->flags, cmd->qid, cmd->idx); if (size > sizeof cmd->data) { bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE); } else { bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map, BUS_DMASYNC_PREWRITE); } bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map, BUS_DMASYNC_PREWRITE); #ifdef notyet /* Update TX scheduler. */ sc->sc_hal->update_sched(sc, ring->qid, ring->cur, 0, 0); #endif /* Kick command ring. */ ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT; IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur); if (async) error = 0; else error = zsleep(desc, &wlan_global_serializer, 0, "iwncmd", hz); return error; } static int iwn4965_add_node(struct iwn_softc *sc, struct iwn_node_info *node, int async) { struct iwn4965_node_info hnode; caddr_t src, dst; /* * We use the node structure for 5000 Series internally (it is * a superset of the one for 4965AGN). We thus copy the common * fields before sending the command. */ src = (caddr_t)node; dst = (caddr_t)&hnode; memcpy(dst, src, 48); /* Skip TSC, RX MIC and TX MIC fields from ``src''. */ memcpy(dst + 48, src + 72, 20); return iwn_cmd(sc, IWN_CMD_ADD_NODE, &hnode, sizeof hnode, async); } static int iwn5000_add_node(struct iwn_softc *sc, struct iwn_node_info *node, int async) { /* Direct mapping. */ return iwn_cmd(sc, IWN_CMD_ADD_NODE, node, sizeof (*node), async); } #if 0 /* HT */ static const uint8_t iwn_ridx_to_plcp[] = { 10, 20, 55, 110, /* CCK */ 0xd, 0xf, 0x5, 0x7, 0x9, 0xb, 0x1, 0x3, 0x3 /* OFDM R1-R4 */ }; static const uint8_t iwn_siso_mcs_to_plcp[] = { 0, 0, 0, 0, /* CCK */ 0, 0, 1, 2, 3, 4, 5, 6, 7 /* HT */ }; static const uint8_t iwn_mimo_mcs_to_plcp[] = { 0, 0, 0, 0, /* CCK */ 8, 8, 9, 10, 11, 12, 13, 14, 15 /* HT */ }; #endif static const uint8_t iwn_prev_ridx[] = { /* NB: allow fallback from CCK11 to OFDM9 and from OFDM6 to CCK5 */ 0, 0, 1, 5, /* CCK */ 2, 4, 3, 6, 7, 8, 9, 10, 10 /* OFDM */ }; /* * Configure hardware link parameters for the specified * node operating on the specified channel. */ static int iwn_set_link_quality(struct iwn_softc *sc, uint8_t id, int async) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct iwn_cmd_link_quality linkq; const struct iwn_rate *rinfo; int i; uint8_t txant, ridx; /* Use the first valid TX antenna. */ txant = IWN_LSB(sc->txchainmask); memset(&linkq, 0, sizeof linkq); linkq.id = id; linkq.antmsk_1stream = txant; linkq.antmsk_2stream = IWN_ANT_AB; linkq.ampdu_max = 31; linkq.ampdu_threshold = 3; linkq.ampdu_limit = htole16(4000); /* 4ms */ #if 0 /* HT */ if (IEEE80211_IS_CHAN_HT(c)) linkq.mimo = 1; #endif if (id == IWN_ID_BSS) ridx = IWN_RIDX_OFDM54; else if (IEEE80211_IS_CHAN_A(ic->ic_curchan)) ridx = IWN_RIDX_OFDM6; else ridx = IWN_RIDX_CCK1; for (i = 0; i < IWN_MAX_TX_RETRIES; i++) { rinfo = &iwn_rates[ridx]; #if 0 /* HT */ if (IEEE80211_IS_CHAN_HT40(c)) { linkq.retry[i].plcp = iwn_mimo_mcs_to_plcp[ridx] | IWN_RIDX_MCS; linkq.retry[i].rflags = IWN_RFLAG_HT | IWN_RFLAG_HT40; /* XXX shortGI */ } else if (IEEE80211_IS_CHAN_HT(c)) { linkq.retry[i].plcp = iwn_siso_mcs_to_plcp[ridx] | IWN_RIDX_MCS; linkq.retry[i].rflags = IWN_RFLAG_HT; /* XXX shortGI */ } else #endif { linkq.retry[i].plcp = rinfo->plcp; linkq.retry[i].rflags = rinfo->flags; } linkq.retry[i].rflags |= IWN_RFLAG_ANT(txant); ridx = iwn_prev_ridx[ridx]; } #ifdef IWN_DEBUG if (sc->sc_debug & IWN_DEBUG_STATE) { kprintf("%s: set link quality for node %d, mimo %d ssmask %d\n", __func__, id, linkq.mimo, linkq.antmsk_1stream); kprintf("%s:", __func__); for (i = 0; i < IWN_MAX_TX_RETRIES; i++) kprintf(" %d:%x", linkq.retry[i].plcp, linkq.retry[i].rflags); kprintf("\n"); } #endif return iwn_cmd(sc, IWN_CMD_LINK_QUALITY, &linkq, sizeof linkq, async); } /* * Broadcast node is used to send group-addressed and management frames. */ static int iwn_add_broadcast_node(struct iwn_softc *sc, int async) { const struct iwn_hal *hal = sc->sc_hal; struct ifnet *ifp = sc->sc_ifp; struct iwn_node_info node; int error; memset(&node, 0, sizeof node); IEEE80211_ADDR_COPY(node.macaddr, ifp->if_broadcastaddr); node.id = hal->broadcast_id; DPRINTF(sc, IWN_DEBUG_RESET, "%s: adding broadcast node\n", __func__); error = hal->add_node(sc, &node, async); if (error != 0) return error; error = iwn_set_link_quality(sc, hal->broadcast_id, async); return error; } static int iwn_wme_update(struct ieee80211com *ic) { #define IWN_EXP2(x) ((1 << (x)) - 1) /* CWmin = 2^ECWmin - 1 */ #define IWN_TXOP_TO_US(v) (v<<5) struct iwn_softc *sc = ic->ic_ifp->if_softc; struct iwn_edca_params cmd; int i; memset(&cmd, 0, sizeof cmd); cmd.flags = htole32(IWN_EDCA_UPDATE); for (i = 0; i < WME_NUM_AC; i++) { const struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[i]; cmd.ac[i].aifsn = wmep->wmep_aifsn; cmd.ac[i].cwmin = htole16(IWN_EXP2(wmep->wmep_logcwmin)); cmd.ac[i].cwmax = htole16(IWN_EXP2(wmep->wmep_logcwmax)); cmd.ac[i].txoplimit = htole16(IWN_TXOP_TO_US(wmep->wmep_txopLimit)); } (void) iwn_cmd(sc, IWN_CMD_EDCA_PARAMS, &cmd, sizeof cmd, 1 /*async*/); return 0; #undef IWN_TXOP_TO_US #undef IWN_EXP2 } static void iwn_update_mcast(struct ifnet *ifp) { /* Ignore */ } static void iwn_set_led(struct iwn_softc *sc, uint8_t which, uint8_t off, uint8_t on) { struct iwn_cmd_led led; /* Clear microcode LED ownership. */ IWN_CLRBITS(sc, IWN_LED, IWN_LED_BSM_CTRL); led.which = which; led.unit = htole32(10000); /* on/off in unit of 100ms */ led.off = off; led.on = on; (void)iwn_cmd(sc, IWN_CMD_SET_LED, &led, sizeof led, 1); } /* * Set the critical temperature at which the firmware will stop the radio * and notify us. */ static int iwn_set_critical_temp(struct iwn_softc *sc) { struct iwn_critical_temp crit; int32_t temp; IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_CTEMP_STOP_RF); if (sc->hw_type == IWN_HW_REV_TYPE_5150) temp = (IWN_CTOK(110) - sc->temp_off) * -5; else if (sc->hw_type == IWN_HW_REV_TYPE_4965) temp = IWN_CTOK(110); else temp = 110; memset(&crit, 0, sizeof crit); crit.tempR = htole32(temp); DPRINTF(sc, IWN_DEBUG_RESET, "setting critical temp to %d\n", temp); return iwn_cmd(sc, IWN_CMD_SET_CRITICAL_TEMP, &crit, sizeof crit, 0); } static int iwn_set_timing(struct iwn_softc *sc, struct ieee80211_node *ni) { struct iwn_cmd_timing cmd; uint64_t val, mod; memset(&cmd, 0, sizeof cmd); memcpy(&cmd.tstamp, ni->ni_tstamp.data, sizeof (uint64_t)); cmd.bintval = htole16(ni->ni_intval); cmd.lintval = htole16(10); /* Compute remaining time until next beacon. */ val = (uint64_t)ni->ni_intval * 1024; /* msecs -> usecs */ mod = le64toh(cmd.tstamp) % val; cmd.binitval = htole32((uint32_t)(val - mod)); DPRINTF(sc, IWN_DEBUG_RESET, "timing bintval=%u tstamp=%ju, init=%u\n", ni->ni_intval, le64toh(cmd.tstamp), (uint32_t)(val - mod)); return iwn_cmd(sc, IWN_CMD_TIMING, &cmd, sizeof cmd, 1); } static void iwn4965_power_calibration(struct iwn_softc *sc, int temp) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; /* Adjust TX power if need be (delta >= 3 degC.) */ DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: temperature %d->%d\n", __func__, sc->temp, temp); if (abs(temp - sc->temp) >= 3) { /* Record temperature of last calibration. */ sc->temp = temp; (void)iwn4965_set_txpower(sc, ic->ic_bsschan, 1); } } /* * Set TX power for current channel (each rate has its own power settings). * This function takes into account the regulatory information from EEPROM, * the current temperature and the current voltage. */ static int iwn4965_set_txpower(struct iwn_softc *sc, struct ieee80211_channel *ch, int async) { /* Fixed-point arithmetic division using a n-bit fractional part. */ #define fdivround(a, b, n) \ ((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n)) /* Linear interpolation. */ #define interpolate(x, x1, y1, x2, y2, n) \ ((y1) + fdivround(((int)(x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n)) static const int tdiv[IWN_NATTEN_GROUPS] = { 9, 8, 8, 8, 6 }; struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct iwn_ucode_info *uc = &sc->ucode_info; struct iwn4965_cmd_txpower cmd; struct iwn4965_eeprom_chan_samples *chans; int32_t vdiff, tdiff; int i, c, grp, maxpwr; const uint8_t *rf_gain, *dsp_gain; uint8_t chan; /* Retrieve channel number. */ chan = ieee80211_chan2ieee(ic, ch); DPRINTF(sc, IWN_DEBUG_RESET, "setting TX power for channel %d\n", chan); memset(&cmd, 0, sizeof cmd); cmd.band = IEEE80211_IS_CHAN_5GHZ(ch) ? 0 : 1; cmd.chan = chan; if (IEEE80211_IS_CHAN_5GHZ(ch)) { maxpwr = sc->maxpwr5GHz; rf_gain = iwn4965_rf_gain_5ghz; dsp_gain = iwn4965_dsp_gain_5ghz; } else { maxpwr = sc->maxpwr2GHz; rf_gain = iwn4965_rf_gain_2ghz; dsp_gain = iwn4965_dsp_gain_2ghz; } /* Compute voltage compensation. */ vdiff = ((int32_t)le32toh(uc->volt) - sc->eeprom_voltage) / 7; if (vdiff > 0) vdiff *= 2; if (abs(vdiff) > 2) vdiff = 0; DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW, "%s: voltage compensation=%d (UCODE=%d, EEPROM=%d)\n", __func__, vdiff, le32toh(uc->volt), sc->eeprom_voltage); /* Get channel attenuation group. */ if (chan <= 20) /* 1-20 */ grp = 4; else if (chan <= 43) /* 34-43 */ grp = 0; else if (chan <= 70) /* 44-70 */ grp = 1; else if (chan <= 124) /* 71-124 */ grp = 2; else /* 125-200 */ grp = 3; DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW, "%s: chan %d, attenuation group=%d\n", __func__, chan, grp); /* Get channel sub-band. */ for (i = 0; i < IWN_NBANDS; i++) if (sc->bands[i].lo != 0 && sc->bands[i].lo <= chan && chan <= sc->bands[i].hi) break; if (i == IWN_NBANDS) /* Can't happen in real-life. */ return EINVAL; chans = sc->bands[i].chans; DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW, "%s: chan %d sub-band=%d\n", __func__, chan, i); for (c = 0; c < 2; c++) { uint8_t power, gain, temp; int maxchpwr, pwr, ridx, idx; power = interpolate(chan, chans[0].num, chans[0].samples[c][1].power, chans[1].num, chans[1].samples[c][1].power, 1); gain = interpolate(chan, chans[0].num, chans[0].samples[c][1].gain, chans[1].num, chans[1].samples[c][1].gain, 1); temp = interpolate(chan, chans[0].num, chans[0].samples[c][1].temp, chans[1].num, chans[1].samples[c][1].temp, 1); DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW, "%s: Tx chain %d: power=%d gain=%d temp=%d\n", __func__, c, power, gain, temp); /* Compute temperature compensation. */ tdiff = ((sc->temp - temp) * 2) / tdiv[grp]; DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW, "%s: temperature compensation=%d (current=%d, EEPROM=%d)\n", __func__, tdiff, sc->temp, temp); for (ridx = 0; ridx <= IWN_RIDX_MAX; ridx++) { /* Convert dBm to half-dBm. */ maxchpwr = sc->maxpwr[chan] * 2; if ((ridx / 8) & 1) maxchpwr -= 6; /* MIMO 2T: -3dB */ pwr = maxpwr; /* Adjust TX power based on rate. */ if ((ridx % 8) == 5) pwr -= 15; /* OFDM48: -7.5dB */ else if ((ridx % 8) == 6) pwr -= 17; /* OFDM54: -8.5dB */ else if ((ridx % 8) == 7) pwr -= 20; /* OFDM60: -10dB */ else pwr -= 10; /* Others: -5dB */ /* Do not exceed channel max TX power. */ if (pwr > maxchpwr) pwr = maxchpwr; idx = gain - (pwr - power) - tdiff - vdiff; if ((ridx / 8) & 1) /* MIMO */ idx += (int32_t)le32toh(uc->atten[grp][c]); if (cmd.band == 0) idx += 9; /* 5GHz */ if (ridx == IWN_RIDX_MAX) idx += 5; /* CCK */ /* Make sure idx stays in a valid range. */ if (idx < 0) idx = 0; else if (idx > IWN4965_MAX_PWR_INDEX) idx = IWN4965_MAX_PWR_INDEX; DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW, "%s: Tx chain %d, rate idx %d: power=%d\n", __func__, c, ridx, idx); cmd.power[ridx].rf_gain[c] = rf_gain[idx]; cmd.power[ridx].dsp_gain[c] = dsp_gain[idx]; } } DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW, "%s: set tx power for chan %d\n", __func__, chan); return iwn_cmd(sc, IWN_CMD_TXPOWER, &cmd, sizeof cmd, async); #undef interpolate #undef fdivround } static int iwn5000_set_txpower(struct iwn_softc *sc, struct ieee80211_channel *ch, int async) { struct iwn5000_cmd_txpower cmd; /* * TX power calibration is handled automatically by the firmware * for 5000 Series. */ memset(&cmd, 0, sizeof cmd); cmd.global_limit = 2 * IWN5000_TXPOWER_MAX_DBM; /* 16 dBm */ cmd.flags = IWN5000_TXPOWER_NO_CLOSED; cmd.srv_limit = IWN5000_TXPOWER_AUTO; DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: setting TX power\n", __func__); return iwn_cmd(sc, IWN_CMD_TXPOWER_DBM, &cmd, sizeof cmd, async); } /* * Retrieve the maximum RSSI (in dBm) among receivers. */ static int iwn4965_get_rssi(struct iwn_softc *sc, struct iwn_rx_stat *stat) { struct iwn4965_rx_phystat *phy = (void *)stat->phybuf; uint8_t mask, agc; int rssi; mask = (le16toh(phy->antenna) >> 4) & IWN_ANT_ABC; agc = (le16toh(phy->agc) >> 7) & 0x7f; rssi = 0; #if 0 if (mask & IWN_ANT_A) /* Ant A */ rssi = max(rssi, phy->rssi[0]); if (mask & IWN_ATH_B) /* Ant B */ rssi = max(rssi, phy->rssi[2]); if (mask & IWN_ANT_C) /* Ant C */ rssi = max(rssi, phy->rssi[4]); #else rssi = max(rssi, phy->rssi[0]); rssi = max(rssi, phy->rssi[2]); rssi = max(rssi, phy->rssi[4]); #endif DPRINTF(sc, IWN_DEBUG_RECV, "%s: agc %d mask 0x%x rssi %d %d %d " "result %d\n", __func__, agc, mask, phy->rssi[0], phy->rssi[2], phy->rssi[4], rssi - agc - IWN_RSSI_TO_DBM); return rssi - agc - IWN_RSSI_TO_DBM; } static int iwn5000_get_rssi(struct iwn_softc *sc, struct iwn_rx_stat *stat) { struct iwn5000_rx_phystat *phy = (void *)stat->phybuf; int rssi; uint8_t agc; agc = (le32toh(phy->agc) >> 9) & 0x7f; rssi = MAX(le16toh(phy->rssi[0]) & 0xff, le16toh(phy->rssi[1]) & 0xff); rssi = MAX(le16toh(phy->rssi[2]) & 0xff, rssi); DPRINTF(sc, IWN_DEBUG_RECV, "%s: agc %d rssi %d %d %d " "result %d\n", __func__, agc, phy->rssi[0], phy->rssi[1], phy->rssi[2], rssi - agc - IWN_RSSI_TO_DBM); return rssi - agc - IWN_RSSI_TO_DBM; } /* * Retrieve the average noise (in dBm) among receivers. */ static int iwn_get_noise(const struct iwn_rx_general_stats *stats) { int i, total, nbant, noise; total = nbant = 0; for (i = 0; i < 3; i++) { if ((noise = le32toh(stats->noise[i]) & 0xff) == 0) continue; total += noise; nbant++; } /* There should be at least one antenna but check anyway. */ return (nbant == 0) ? -127 : (total / nbant) - 107; } /* * Compute temperature (in degC) from last received statistics. */ static int iwn4965_get_temperature(struct iwn_softc *sc) { struct iwn_ucode_info *uc = &sc->ucode_info; int32_t r1, r2, r3, r4, temp; r1 = le32toh(uc->temp[0].chan20MHz); r2 = le32toh(uc->temp[1].chan20MHz); r3 = le32toh(uc->temp[2].chan20MHz); r4 = le32toh(sc->rawtemp); if (r1 == r3) /* Prevents division by 0 (should not happen.) */ return 0; /* Sign-extend 23-bit R4 value to 32-bit. */ r4 = (r4 << 8) >> 8; /* Compute temperature in Kelvin. */ temp = (259 * (r4 - r2)) / (r3 - r1); temp = (temp * 97) / 100 + 8; DPRINTF(sc, IWN_DEBUG_ANY, "temperature %dK/%dC\n", temp, IWN_KTOC(temp)); return IWN_KTOC(temp); } static int iwn5000_get_temperature(struct iwn_softc *sc) { int32_t temp; /* * Temperature is not used by the driver for 5000 Series because * TX power calibration is handled by firmware. We export it to * users through the sensor framework though. */ temp = le32toh(sc->rawtemp); if (sc->hw_type == IWN_HW_REV_TYPE_5150) { temp = (temp / -5) + sc->temp_off; temp = IWN_KTOC(temp); } return temp; } /* * Initialize sensitivity calibration state machine. */ static int iwn_init_sensitivity(struct iwn_softc *sc) { const struct iwn_hal *hal = sc->sc_hal; struct iwn_calib_state *calib = &sc->calib; uint32_t flags; int error; /* Reset calibration state machine. */ memset(calib, 0, sizeof (*calib)); calib->state = IWN_CALIB_STATE_INIT; calib->cck_state = IWN_CCK_STATE_HIFA; /* Set initial correlation values. */ calib->ofdm_x1 = sc->limits->min_ofdm_x1; calib->ofdm_mrc_x1 = sc->limits->min_ofdm_mrc_x1; calib->ofdm_x4 = sc->limits->min_ofdm_x4; calib->ofdm_mrc_x4 = sc->limits->min_ofdm_mrc_x4; calib->cck_x4 = 125; calib->cck_mrc_x4 = sc->limits->min_cck_mrc_x4; calib->energy_cck = sc->limits->energy_cck; /* Write initial sensitivity. */ error = iwn_send_sensitivity(sc); if (error != 0) return error; /* Write initial gains. */ error = hal->init_gains(sc); if (error != 0) return error; /* Request statistics at each beacon interval. */ flags = 0; DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: calibrate phy\n", __func__); return iwn_cmd(sc, IWN_CMD_GET_STATISTICS, &flags, sizeof flags, 1); } /* * Collect noise and RSSI statistics for the first 20 beacons received * after association and use them to determine connected antennas and * to set differential gains. */ static void iwn_collect_noise(struct iwn_softc *sc, const struct iwn_rx_general_stats *stats) { const struct iwn_hal *hal = sc->sc_hal; struct iwn_calib_state *calib = &sc->calib; uint32_t val; int i; /* Accumulate RSSI and noise for all 3 antennas. */ for (i = 0; i < 3; i++) { calib->rssi[i] += le32toh(stats->rssi[i]) & 0xff; calib->noise[i] += le32toh(stats->noise[i]) & 0xff; } /* NB: We update differential gains only once after 20 beacons. */ if (++calib->nbeacons < 20) return; /* Determine highest average RSSI. */ val = MAX(calib->rssi[0], calib->rssi[1]); val = MAX(calib->rssi[2], val); /* Determine which antennas are connected. */ sc->chainmask = sc->rxchainmask; for (i = 0; i < 3; i++) if (val - calib->rssi[i] > 15 * 20) sc->chainmask &= ~(1 << i); /* If none of the TX antennas are connected, keep at least one. */ if ((sc->chainmask & sc->txchainmask) == 0) sc->chainmask |= IWN_LSB(sc->txchainmask); (void)hal->set_gains(sc); calib->state = IWN_CALIB_STATE_RUN; #ifdef notyet /* XXX Disable RX chains with no antennas connected. */ sc->rxon.rxchain = htole16(IWN_RXCHAIN_SEL(sc->chainmask)); (void)iwn_cmd(sc, IWN_CMD_RXON, &sc->rxon, hal->rxonsz, 1); #endif #if 0 /* XXX: not yet */ /* Enable power-saving mode if requested by user. */ if (sc->sc_ic.ic_flags & IEEE80211_F_PMGTON) (void)iwn_set_pslevel(sc, 0, 3, 1); #endif } static int iwn4965_init_gains(struct iwn_softc *sc) { struct iwn_phy_calib_gain cmd; memset(&cmd, 0, sizeof cmd); cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN; /* Differential gains initially set to 0 for all 3 antennas. */ DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: setting initial differential gains\n", __func__); return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1); } static int iwn5000_init_gains(struct iwn_softc *sc) { struct iwn_phy_calib cmd; memset(&cmd, 0, sizeof cmd); cmd.code = IWN5000_PHY_CALIB_RESET_NOISE_GAIN; cmd.ngroups = 1; cmd.isvalid = 1; DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: setting initial differential gains\n", __func__); return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1); } static int iwn4965_set_gains(struct iwn_softc *sc) { struct iwn_calib_state *calib = &sc->calib; struct iwn_phy_calib_gain cmd; int i, delta, noise; /* Get minimal noise among connected antennas. */ noise = INT_MAX; /* NB: There's at least one antenna. */ for (i = 0; i < 3; i++) if (sc->chainmask & (1 << i)) noise = MIN(calib->noise[i], noise); memset(&cmd, 0, sizeof cmd); cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN; /* Set differential gains for connected antennas. */ for (i = 0; i < 3; i++) { if (sc->chainmask & (1 << i)) { /* Compute attenuation (in unit of 1.5dB). */ delta = (noise - (int32_t)calib->noise[i]) / 30; /* NB: delta <= 0 */ /* Limit to [-4.5dB,0]. */ cmd.gain[i] = MIN(abs(delta), 3); if (delta < 0) cmd.gain[i] |= 1 << 2; /* sign bit */ } } DPRINTF(sc, IWN_DEBUG_CALIBRATE, "setting differential gains Ant A/B/C: %x/%x/%x (%x)\n", cmd.gain[0], cmd.gain[1], cmd.gain[2], sc->chainmask); return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1); } static int iwn5000_set_gains(struct iwn_softc *sc) { struct iwn_calib_state *calib = &sc->calib; struct iwn_phy_calib_gain cmd; int i, ant, delta, div; /* We collected 20 beacons and !=6050 need a 1.5 factor. */ div = (sc->hw_type == IWN_HW_REV_TYPE_6050) ? 20 : 30; memset(&cmd, 0, sizeof cmd); cmd.code = IWN5000_PHY_CALIB_NOISE_GAIN; cmd.ngroups = 1; cmd.isvalid = 1; /* Get first available RX antenna as referential. */ ant = IWN_LSB(sc->rxchainmask); /* Set differential gains for other antennas. */ for (i = ant + 1; i < 3; i++) { if (sc->chainmask & (1 << i)) { /* The delta is relative to antenna "ant". */ delta = ((int32_t)calib->noise[ant] - (int32_t)calib->noise[i]) / div; /* Limit to [-4.5dB,+4.5dB]. */ cmd.gain[i - 1] = MIN(abs(delta), 3); if (delta < 0) cmd.gain[i - 1] |= 1 << 2; /* sign bit */ } } DPRINTF(sc, IWN_DEBUG_CALIBRATE, "setting differential gains Ant B/C: %x/%x (%x)\n", cmd.gain[0], cmd.gain[1], sc->chainmask); return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1); } /* * Tune RF RX sensitivity based on the number of false alarms detected * during the last beacon period. */ static void iwn_tune_sensitivity(struct iwn_softc *sc, const struct iwn_rx_stats *stats) { #define inc(val, inc, max) \ if ((val) < (max)) { \ if ((val) < (max) - (inc)) \ (val) += (inc); \ else \ (val) = (max); \ needs_update = 1; \ } #define dec(val, dec, min) \ if ((val) > (min)) { \ if ((val) > (min) + (dec)) \ (val) -= (dec); \ else \ (val) = (min); \ needs_update = 1; \ } const struct iwn_sensitivity_limits *limits = sc->limits; struct iwn_calib_state *calib = &sc->calib; uint32_t val, rxena, fa; uint32_t energy[3], energy_min; uint8_t noise[3], noise_ref; int i, needs_update = 0; /* Check that we've been enabled long enough. */ rxena = le32toh(stats->general.load); if (rxena == 0) return; /* Compute number of false alarms since last call for OFDM. */ fa = le32toh(stats->ofdm.bad_plcp) - calib->bad_plcp_ofdm; fa += le32toh(stats->ofdm.fa) - calib->fa_ofdm; fa *= 200 * 1024; /* 200TU */ /* Save counters values for next call. */ calib->bad_plcp_ofdm = le32toh(stats->ofdm.bad_plcp); calib->fa_ofdm = le32toh(stats->ofdm.fa); if (fa > 50 * rxena) { /* High false alarm count, decrease sensitivity. */ DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: OFDM high false alarm count: %u\n", __func__, fa); inc(calib->ofdm_x1, 1, limits->max_ofdm_x1); inc(calib->ofdm_mrc_x1, 1, limits->max_ofdm_mrc_x1); inc(calib->ofdm_x4, 1, limits->max_ofdm_x4); inc(calib->ofdm_mrc_x4, 1, limits->max_ofdm_mrc_x4); } else if (fa < 5 * rxena) { /* Low false alarm count, increase sensitivity. */ DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: OFDM low false alarm count: %u\n", __func__, fa); dec(calib->ofdm_x1, 1, limits->min_ofdm_x1); dec(calib->ofdm_mrc_x1, 1, limits->min_ofdm_mrc_x1); dec(calib->ofdm_x4, 1, limits->min_ofdm_x4); dec(calib->ofdm_mrc_x4, 1, limits->min_ofdm_mrc_x4); } /* Compute maximum noise among 3 receivers. */ for (i = 0; i < 3; i++) noise[i] = (le32toh(stats->general.noise[i]) >> 8) & 0xff; val = MAX(noise[0], noise[1]); val = MAX(noise[2], val); /* Insert it into our samples table. */ calib->noise_samples[calib->cur_noise_sample] = val; calib->cur_noise_sample = (calib->cur_noise_sample + 1) % 20; /* Compute maximum noise among last 20 samples. */ noise_ref = calib->noise_samples[0]; for (i = 1; i < 20; i++) noise_ref = MAX(noise_ref, calib->noise_samples[i]); /* Compute maximum energy among 3 receivers. */ for (i = 0; i < 3; i++) energy[i] = le32toh(stats->general.energy[i]); val = MIN(energy[0], energy[1]); val = MIN(energy[2], val); /* Insert it into our samples table. */ calib->energy_samples[calib->cur_energy_sample] = val; calib->cur_energy_sample = (calib->cur_energy_sample + 1) % 10; /* Compute minimum energy among last 10 samples. */ energy_min = calib->energy_samples[0]; for (i = 1; i < 10; i++) energy_min = MAX(energy_min, calib->energy_samples[i]); energy_min += 6; /* Compute number of false alarms since last call for CCK. */ fa = le32toh(stats->cck.bad_plcp) - calib->bad_plcp_cck; fa += le32toh(stats->cck.fa) - calib->fa_cck; fa *= 200 * 1024; /* 200TU */ /* Save counters values for next call. */ calib->bad_plcp_cck = le32toh(stats->cck.bad_plcp); calib->fa_cck = le32toh(stats->cck.fa); if (fa > 50 * rxena) { /* High false alarm count, decrease sensitivity. */ DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: CCK high false alarm count: %u\n", __func__, fa); calib->cck_state = IWN_CCK_STATE_HIFA; calib->low_fa = 0; if (calib->cck_x4 > 160) { calib->noise_ref = noise_ref; if (calib->energy_cck > 2) dec(calib->energy_cck, 2, energy_min); } if (calib->cck_x4 < 160) { calib->cck_x4 = 161; needs_update = 1; } else inc(calib->cck_x4, 3, limits->max_cck_x4); inc(calib->cck_mrc_x4, 3, limits->max_cck_mrc_x4); } else if (fa < 5 * rxena) { /* Low false alarm count, increase sensitivity. */ DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: CCK low false alarm count: %u\n", __func__, fa); calib->cck_state = IWN_CCK_STATE_LOFA; calib->low_fa++; if (calib->cck_state != IWN_CCK_STATE_INIT && (((int32_t)calib->noise_ref - (int32_t)noise_ref) > 2 || calib->low_fa > 100)) { inc(calib->energy_cck, 2, limits->min_energy_cck); dec(calib->cck_x4, 3, limits->min_cck_x4); dec(calib->cck_mrc_x4, 3, limits->min_cck_mrc_x4); } } else { /* Not worth to increase or decrease sensitivity. */ DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: CCK normal false alarm count: %u\n", __func__, fa); calib->low_fa = 0; calib->noise_ref = noise_ref; if (calib->cck_state == IWN_CCK_STATE_HIFA) { /* Previous interval had many false alarms. */ dec(calib->energy_cck, 8, energy_min); } calib->cck_state = IWN_CCK_STATE_INIT; } if (needs_update) (void)iwn_send_sensitivity(sc); #undef dec #undef inc } static int iwn_send_sensitivity(struct iwn_softc *sc) { struct iwn_calib_state *calib = &sc->calib; struct iwn_sensitivity_cmd cmd; memset(&cmd, 0, sizeof cmd); cmd.which = IWN_SENSITIVITY_WORKTBL; /* OFDM modulation. */ cmd.corr_ofdm_x1 = htole16(calib->ofdm_x1); cmd.corr_ofdm_mrc_x1 = htole16(calib->ofdm_mrc_x1); cmd.corr_ofdm_x4 = htole16(calib->ofdm_x4); cmd.corr_ofdm_mrc_x4 = htole16(calib->ofdm_mrc_x4); cmd.energy_ofdm = htole16(sc->limits->energy_ofdm); cmd.energy_ofdm_th = htole16(62); /* CCK modulation. */ cmd.corr_cck_x4 = htole16(calib->cck_x4); cmd.corr_cck_mrc_x4 = htole16(calib->cck_mrc_x4); cmd.energy_cck = htole16(calib->energy_cck); /* Barker modulation: use default values. */ cmd.corr_barker = htole16(190); cmd.corr_barker_mrc = htole16(390); DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: set sensitivity %d/%d/%d/%d/%d/%d/%d\n", __func__, calib->ofdm_x1, calib->ofdm_mrc_x1, calib->ofdm_x4, calib->ofdm_mrc_x4, calib->cck_x4, calib->cck_mrc_x4, calib->energy_cck); return iwn_cmd(sc, IWN_CMD_SET_SENSITIVITY, &cmd, sizeof cmd, 1); } /* * Set STA mode power saving level (between 0 and 5). * Level 0 is CAM (Continuously Aware Mode), 5 is for maximum power saving. */ static int iwn_set_pslevel(struct iwn_softc *sc, int dtim, int level, int async) { const struct iwn_pmgt *pmgt; struct iwn_pmgt_cmd cmd; uint32_t max, skip_dtim; uint32_t tmp; int i; /* Select which PS parameters to use. */ if (dtim <= 2) pmgt = &iwn_pmgt[0][level]; else if (dtim <= 10) pmgt = &iwn_pmgt[1][level]; else pmgt = &iwn_pmgt[2][level]; memset(&cmd, 0, sizeof cmd); if (level != 0) /* not CAM */ cmd.flags |= htole16(IWN_PS_ALLOW_SLEEP); if (level == 5) cmd.flags |= htole16(IWN_PS_FAST_PD); /* Retrieve PCIe Active State Power Management (ASPM). */ tmp = pci_read_config(sc->sc_dev, sc->sc_cap_off + 0x10, 1); if (!(tmp & 0x1)) /* L0s Entry disabled. */ cmd.flags |= htole16(IWN_PS_PCI_PMGT); cmd.rxtimeout = htole32(pmgt->rxtimeout * 1024); cmd.txtimeout = htole32(pmgt->txtimeout * 1024); if (dtim == 0) { dtim = 1; skip_dtim = 0; } else skip_dtim = pmgt->skip_dtim; if (skip_dtim != 0) { cmd.flags |= htole16(IWN_PS_SLEEP_OVER_DTIM); max = pmgt->intval[4]; if (max == (uint32_t)-1) max = dtim * (skip_dtim + 1); else if (max > dtim) max = (max / dtim) * dtim; } else max = dtim; for (i = 0; i < 5; i++) cmd.intval[i] = htole32(MIN(max, pmgt->intval[i])); DPRINTF(sc, IWN_DEBUG_RESET, "setting power saving level to %d\n", level); return iwn_cmd(sc, IWN_CMD_SET_POWER_MODE, &cmd, sizeof cmd, async); } static int iwn_config(struct iwn_softc *sc) { const struct iwn_hal *hal = sc->sc_hal; struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct iwn_bluetooth bluetooth; uint32_t txmask; int error; uint16_t rxchain; /* Configure valid TX chains for 5000 Series. */ if (sc->hw_type != IWN_HW_REV_TYPE_4965) { txmask = htole32(sc->txchainmask); DPRINTF(sc, IWN_DEBUG_RESET, "%s: configuring valid TX chains 0x%x\n", __func__, txmask); error = iwn_cmd(sc, IWN5000_CMD_TX_ANT_CONFIG, &txmask, sizeof txmask, 0); if (error != 0) { device_printf(sc->sc_dev, "%s: could not configure valid TX chains, " "error %d\n", __func__, error); return error; } } /* Configure bluetooth coexistence. */ memset(&bluetooth, 0, sizeof bluetooth); bluetooth.flags = IWN_BT_COEX_CHAN_ANN | IWN_BT_COEX_BT_PRIO; bluetooth.lead_time = IWN_BT_LEAD_TIME_DEF; bluetooth.max_kill = IWN_BT_MAX_KILL_DEF; DPRINTF(sc, IWN_DEBUG_RESET, "%s: config bluetooth coexistence\n", __func__); error = iwn_cmd(sc, IWN_CMD_BT_COEX, &bluetooth, sizeof bluetooth, 0); if (error != 0) { device_printf(sc->sc_dev, "%s: could not configure bluetooth coexistence, error %d\n", __func__, error); return error; } /* Set mode, channel, RX filter and enable RX. */ memset(&sc->rxon, 0, sizeof (struct iwn_rxon)); IEEE80211_ADDR_COPY(sc->rxon.myaddr, IF_LLADDR(ifp)); IEEE80211_ADDR_COPY(sc->rxon.wlap, IF_LLADDR(ifp)); sc->rxon.chan = ieee80211_chan2ieee(ic, ic->ic_curchan); sc->rxon.flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF); if (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan)) sc->rxon.flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ); switch (ic->ic_opmode) { case IEEE80211_M_STA: sc->rxon.mode = IWN_MODE_STA; sc->rxon.filter = htole32(IWN_FILTER_MULTICAST); break; case IEEE80211_M_MONITOR: sc->rxon.mode = IWN_MODE_MONITOR; sc->rxon.filter = htole32(IWN_FILTER_MULTICAST | IWN_FILTER_CTL | IWN_FILTER_PROMISC); break; default: /* Should not get there. */ break; } sc->rxon.cck_mask = 0x0f; /* not yet negotiated */ sc->rxon.ofdm_mask = 0xff; /* not yet negotiated */ sc->rxon.ht_single_mask = 0xff; sc->rxon.ht_dual_mask = 0xff; sc->rxon.ht_triple_mask = 0xff; rxchain = IWN_RXCHAIN_VALID(sc->rxchainmask) | IWN_RXCHAIN_MIMO_COUNT(2) | IWN_RXCHAIN_IDLE_COUNT(2); sc->rxon.rxchain = htole16(rxchain); DPRINTF(sc, IWN_DEBUG_RESET, "%s: setting configuration\n", __func__); error = iwn_cmd(sc, IWN_CMD_RXON, &sc->rxon, hal->rxonsz, 0); if (error != 0) { device_printf(sc->sc_dev, "%s: RXON command failed\n", __func__); return error; } error = iwn_add_broadcast_node(sc, 0); if (error != 0) { device_printf(sc->sc_dev, "%s: could not add broadcast node\n", __func__); return error; } /* Configuration has changed, set TX power accordingly. */ error = hal->set_txpower(sc, ic->ic_curchan, 0); if (error != 0) { device_printf(sc->sc_dev, "%s: could not set TX power\n", __func__); return error; } error = iwn_set_critical_temp(sc); if (error != 0) { device_printf(sc->sc_dev, "%s: ccould not set critical temperature\n", __func__); return error; } /* Set power saving level to CAM during initialization. */ error = iwn_set_pslevel(sc, 0, 0, 0); if (error != 0) { device_printf(sc->sc_dev, "%s: could not set power saving level\n", __func__); return error; } return 0; } static int iwn_scan(struct iwn_softc *sc) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211_scan_state *ss = ic->ic_scan; /*XXX*/ struct iwn_scan_hdr *hdr; struct iwn_cmd_data *tx; struct iwn_scan_essid *essid; struct iwn_scan_chan *chan; struct ieee80211_frame *wh; struct ieee80211_rateset *rs; struct ieee80211_channel *c; int buflen, error, nrates; uint16_t rxchain; uint8_t *buf, *frm, txant; buf = kmalloc(IWN_SCAN_MAXSZ, M_DEVBUF, M_INTWAIT | M_ZERO); if (buf == NULL) { device_printf(sc->sc_dev, "%s: could not allocate buffer for scan command\n", __func__); return ENOMEM; } hdr = (struct iwn_scan_hdr *)buf; /* * Move to the next channel if no frames are received within 10ms * after sending the probe request. */ hdr->quiet_time = htole16(10); /* timeout in milliseconds */ hdr->quiet_threshold = htole16(1); /* min # of packets */ /* Select antennas for scanning. */ rxchain = IWN_RXCHAIN_VALID(sc->rxchainmask) | IWN_RXCHAIN_FORCE_MIMO_SEL(sc->rxchainmask) | IWN_RXCHAIN_DRIVER_FORCE; if (IEEE80211_IS_CHAN_A(ic->ic_curchan) && sc->hw_type == IWN_HW_REV_TYPE_4965) { /* Ant A must be avoided in 5GHz because of an HW bug. */ rxchain |= IWN_RXCHAIN_FORCE_SEL(IWN_ANT_BC); } else /* Use all available RX antennas. */ rxchain |= IWN_RXCHAIN_FORCE_SEL(sc->rxchainmask); hdr->rxchain = htole16(rxchain); hdr->filter = htole32(IWN_FILTER_MULTICAST | IWN_FILTER_BEACON); tx = (struct iwn_cmd_data *)(hdr + 1); tx->flags = htole32(IWN_TX_AUTO_SEQ); tx->id = sc->sc_hal->broadcast_id; tx->lifetime = htole32(IWN_LIFETIME_INFINITE); if (IEEE80211_IS_CHAN_A(ic->ic_curchan)) { /* Send probe requests at 6Mbps. */ tx->plcp = iwn_rates[IWN_RIDX_OFDM6].plcp; rs = &ic->ic_sup_rates[IEEE80211_MODE_11A]; } else { hdr->flags = htole32(IWN_RXON_24GHZ | IWN_RXON_AUTO); /* Send probe requests at 1Mbps. */ tx->plcp = iwn_rates[IWN_RIDX_CCK1].plcp; tx->rflags = IWN_RFLAG_CCK; rs = &ic->ic_sup_rates[IEEE80211_MODE_11G]; } /* Use the first valid TX antenna. */ txant = IWN_LSB(sc->txchainmask); tx->rflags |= IWN_RFLAG_ANT(txant); essid = (struct iwn_scan_essid *)(tx + 1); if (ss->ss_ssid[0].len != 0) { essid[0].id = IEEE80211_ELEMID_SSID; essid[0].len = ss->ss_ssid[0].len; memcpy(essid[0].data, ss->ss_ssid[0].ssid, ss->ss_ssid[0].len); } /* * Build a probe request frame. Most of the following code is a * copy & paste of what is done in net80211. */ wh = (struct ieee80211_frame *)(essid + 20); wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_REQ; wh->i_fc[1] = IEEE80211_FC1_DIR_NODS; IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr); IEEE80211_ADDR_COPY(wh->i_addr2, IF_LLADDR(ifp)); IEEE80211_ADDR_COPY(wh->i_addr3, ifp->if_broadcastaddr); *(uint16_t *)&wh->i_dur[0] = 0; /* filled by HW */ *(uint16_t *)&wh->i_seq[0] = 0; /* filled by HW */ frm = (uint8_t *)(wh + 1); /* Add SSID IE. */ *frm++ = IEEE80211_ELEMID_SSID; *frm++ = ss->ss_ssid[0].len; memcpy(frm, ss->ss_ssid[0].ssid, ss->ss_ssid[0].len); frm += ss->ss_ssid[0].len; /* Add supported rates IE. */ *frm++ = IEEE80211_ELEMID_RATES; nrates = rs->rs_nrates; if (nrates > IEEE80211_RATE_SIZE) nrates = IEEE80211_RATE_SIZE; *frm++ = nrates; memcpy(frm, rs->rs_rates, nrates); frm += nrates; /* Add supported xrates IE. */ if (rs->rs_nrates > IEEE80211_RATE_SIZE) { nrates = rs->rs_nrates - IEEE80211_RATE_SIZE; *frm++ = IEEE80211_ELEMID_XRATES; *frm++ = (uint8_t)nrates; memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates); frm += nrates; } /* Set length of probe request. */ tx->len = htole16(frm - (uint8_t *)wh); c = ic->ic_curchan; chan = (struct iwn_scan_chan *)frm; chan->chan = htole16(ieee80211_chan2ieee(ic, c)); chan->flags = 0; if (ss->ss_nssid > 0) chan->flags |= htole32(IWN_CHAN_NPBREQS(1)); chan->dsp_gain = 0x6e; if (IEEE80211_IS_CHAN_5GHZ(c) && !(c->ic_flags & IEEE80211_CHAN_PASSIVE)) { chan->rf_gain = 0x3b; chan->active = htole16(24); chan->passive = htole16(110); chan->flags |= htole32(IWN_CHAN_ACTIVE); } else if (IEEE80211_IS_CHAN_5GHZ(c)) { chan->rf_gain = 0x3b; chan->active = htole16(24); if (sc->rxon.associd) chan->passive = htole16(78); else chan->passive = htole16(110); hdr->crc_threshold = 0xffff; } else if (!(c->ic_flags & IEEE80211_CHAN_PASSIVE)) { chan->rf_gain = 0x28; chan->active = htole16(36); chan->passive = htole16(120); chan->flags |= htole32(IWN_CHAN_ACTIVE); } else { chan->rf_gain = 0x28; chan->active = htole16(36); if (sc->rxon.associd) chan->passive = htole16(88); else chan->passive = htole16(120); hdr->crc_threshold = 0xffff; } DPRINTF(sc, IWN_DEBUG_STATE, "%s: chan %u flags 0x%x rf_gain 0x%x " "dsp_gain 0x%x active 0x%x passive 0x%x\n", __func__, chan->chan, chan->flags, chan->rf_gain, chan->dsp_gain, chan->active, chan->passive); hdr->nchan++; chan++; buflen = (uint8_t *)chan - buf; hdr->len = htole16(buflen); DPRINTF(sc, IWN_DEBUG_STATE, "sending scan command nchan=%d\n", hdr->nchan); error = iwn_cmd(sc, IWN_CMD_SCAN, buf, buflen, 1); kfree(buf, M_DEVBUF); return error; } static int iwn_auth(struct iwn_softc *sc, struct ieee80211vap *vap) { const struct iwn_hal *hal = sc->sc_hal; struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211_node *ni = vap->iv_bss; int error; sc->calib.state = IWN_CALIB_STATE_INIT; /* Update adapter configuration. */ IEEE80211_ADDR_COPY(sc->rxon.bssid, ni->ni_bssid); sc->rxon.chan = htole16(ieee80211_chan2ieee(ic, ni->ni_chan)); sc->rxon.flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF); if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan)) sc->rxon.flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ); if (ic->ic_flags & IEEE80211_F_SHSLOT) sc->rxon.flags |= htole32(IWN_RXON_SHSLOT); if (ic->ic_flags & IEEE80211_F_SHPREAMBLE) sc->rxon.flags |= htole32(IWN_RXON_SHPREAMBLE); if (IEEE80211_IS_CHAN_A(ni->ni_chan)) { sc->rxon.cck_mask = 0; sc->rxon.ofdm_mask = 0x15; } else if (IEEE80211_IS_CHAN_B(ni->ni_chan)) { sc->rxon.cck_mask = 0x03; sc->rxon.ofdm_mask = 0; } else { /* XXX assume 802.11b/g */ sc->rxon.cck_mask = 0x0f; sc->rxon.ofdm_mask = 0x15; } DPRINTF(sc, IWN_DEBUG_STATE, "%s: config chan %d mode %d flags 0x%x cck 0x%x ofdm 0x%x " "ht_single 0x%x ht_dual 0x%x rxchain 0x%x " "myaddr %6D wlap %6D bssid %6D associd %d filter 0x%x\n", __func__, le16toh(sc->rxon.chan), sc->rxon.mode, le32toh(sc->rxon.flags), sc->rxon.cck_mask, sc->rxon.ofdm_mask, sc->rxon.ht_single_mask, sc->rxon.ht_dual_mask, le16toh(sc->rxon.rxchain), sc->rxon.myaddr, ":", sc->rxon.wlap, ":", sc->rxon.bssid, ":", le16toh(sc->rxon.associd), le32toh(sc->rxon.filter)); error = iwn_cmd(sc, IWN_CMD_RXON, &sc->rxon, hal->rxonsz, 1); if (error != 0) { device_printf(sc->sc_dev, "%s: RXON command failed, error %d\n", __func__, error); return error; } /* Configuration has changed, set TX power accordingly. */ error = hal->set_txpower(sc, ni->ni_chan, 1); if (error != 0) { device_printf(sc->sc_dev, "%s: could not set Tx power, error %d\n", __func__, error); return error; } /* * Reconfiguring RXON clears the firmware nodes table so we must * add the broadcast node again. */ error = iwn_add_broadcast_node(sc, 1); if (error != 0) { device_printf(sc->sc_dev, "%s: could not add broadcast node, error %d\n", __func__, error); return error; } return 0; } /* * Configure the adapter for associated state. */ static int iwn_run(struct iwn_softc *sc, struct ieee80211vap *vap) { #define MS(v,x) (((v) & x) >> x##_S) const struct iwn_hal *hal = sc->sc_hal; struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211_node *ni = vap->iv_bss; struct iwn_node_info node; int error; sc->calib.state = IWN_CALIB_STATE_INIT; if (ic->ic_opmode == IEEE80211_M_MONITOR) { /* Link LED blinks while monitoring. */ iwn_set_led(sc, IWN_LED_LINK, 5, 5); return 0; } error = iwn_set_timing(sc, ni); if (error != 0) { device_printf(sc->sc_dev, "%s: could not set timing, error %d\n", __func__, error); return error; } /* Update adapter configuration. */ IEEE80211_ADDR_COPY(sc->rxon.bssid, ni->ni_bssid); sc->rxon.chan = htole16(ieee80211_chan2ieee(ic, ni->ni_chan)); sc->rxon.associd = htole16(IEEE80211_AID(ni->ni_associd)); /* Short preamble and slot time are negotiated when associating. */ sc->rxon.flags &= ~htole32(IWN_RXON_SHPREAMBLE | IWN_RXON_SHSLOT); sc->rxon.flags |= htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF); if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan)) sc->rxon.flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ); else sc->rxon.flags &= ~htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ); if (ic->ic_flags & IEEE80211_F_SHSLOT) sc->rxon.flags |= htole32(IWN_RXON_SHSLOT); if (ic->ic_flags & IEEE80211_F_SHPREAMBLE) sc->rxon.flags |= htole32(IWN_RXON_SHPREAMBLE); if (IEEE80211_IS_CHAN_A(ni->ni_chan)) { sc->rxon.cck_mask = 0; sc->rxon.ofdm_mask = 0x15; } else if (IEEE80211_IS_CHAN_B(ni->ni_chan)) { sc->rxon.cck_mask = 0x03; sc->rxon.ofdm_mask = 0; } else { /* XXX assume 802.11b/g */ sc->rxon.cck_mask = 0x0f; sc->rxon.ofdm_mask = 0x15; } #if 0 /* HT */ if (IEEE80211_IS_CHAN_HT(ni->ni_chan)) { sc->rxon.flags &= ~htole32(IWN_RXON_HT); if (IEEE80211_IS_CHAN_HT40U(ni->ni_chan)) sc->rxon.flags |= htole32(IWN_RXON_HT40U); else if (IEEE80211_IS_CHAN_HT40D(ni->ni_chan)) sc->rxon.flags |= htole32(IWN_RXON_HT40D); else sc->rxon.flags |= htole32(IWN_RXON_HT20); sc->rxon.rxchain = htole16( IWN_RXCHAIN_VALID(3) | IWN_RXCHAIN_MIMO_COUNT(3) | IWN_RXCHAIN_IDLE_COUNT(1) | IWN_RXCHAIN_MIMO_FORCE); maxrxampdu = MS(ni->ni_htparam, IEEE80211_HTCAP_MAXRXAMPDU); ampdudensity = MS(ni->ni_htparam, IEEE80211_HTCAP_MPDUDENSITY); } else maxrxampdu = ampdudensity = 0; #endif sc->rxon.filter |= htole32(IWN_FILTER_BSS); DPRINTF(sc, IWN_DEBUG_STATE, "%s: config chan %d mode %d flags 0x%x cck 0x%x ofdm 0x%x " "ht_single 0x%x ht_dual 0x%x rxchain 0x%x " "myaddr %6D wlap %6D bssid %6D associd %d filter 0x%x\n", __func__, le16toh(sc->rxon.chan), sc->rxon.mode, le32toh(sc->rxon.flags), sc->rxon.cck_mask, sc->rxon.ofdm_mask, sc->rxon.ht_single_mask, sc->rxon.ht_dual_mask, le16toh(sc->rxon.rxchain), sc->rxon.myaddr, ":", sc->rxon.wlap, ":", sc->rxon.bssid, ":", le16toh(sc->rxon.associd), le32toh(sc->rxon.filter)); error = iwn_cmd(sc, IWN_CMD_RXON, &sc->rxon, hal->rxonsz, 1); if (error != 0) { device_printf(sc->sc_dev, "%s: could not update configuration, error %d\n", __func__, error); return error; } /* Configuration has changed, set TX power accordingly. */ error = hal->set_txpower(sc, ni->ni_chan, 1); if (error != 0) { device_printf(sc->sc_dev, "%s: could not set Tx power, error %d\n", __func__, error); return error; } /* Add BSS node. */ memset(&node, 0, sizeof node); IEEE80211_ADDR_COPY(node.macaddr, ni->ni_macaddr); node.id = IWN_ID_BSS; #ifdef notyet node.htflags = htole32(IWN_AMDPU_SIZE_FACTOR(3) | IWN_AMDPU_DENSITY(5)); /* 2us */ #endif DPRINTF(sc, IWN_DEBUG_STATE, "%s: add BSS node, id %d htflags 0x%x\n", __func__, node.id, le32toh(node.htflags)); error = hal->add_node(sc, &node, 1); if (error != 0) { device_printf(sc->sc_dev, "could not add BSS node\n"); return error; } DPRINTF(sc, IWN_DEBUG_STATE, "setting link quality for node %d\n", node.id); error = iwn_set_link_quality(sc, node.id, 1); if (error != 0) { device_printf(sc->sc_dev, "%s: could not setup MRR for node %d, error %d\n", __func__, node.id, error); return error; } error = iwn_init_sensitivity(sc); if (error != 0) { device_printf(sc->sc_dev, "%s: could not set sensitivity, error %d\n", __func__, error); return error; } /* Start periodic calibration timer. */ sc->calib.state = IWN_CALIB_STATE_ASSOC; iwn_calib_reset(sc); /* Link LED always on while associated. */ iwn_set_led(sc, IWN_LED_LINK, 0, 1); return 0; #undef MS } #if 0 /* HT */ /* * This function is called by upper layer when an ADDBA request is received * from another STA and before the ADDBA response is sent. */ static int iwn_ampdu_rx_start(struct ieee80211com *ic, struct ieee80211_node *ni, uint8_t tid) { struct ieee80211_rx_ba *ba = &ni->ni_rx_ba[tid]; struct iwn_softc *sc = ic->ic_softc; struct iwn_node *wn = (void *)ni; struct iwn_node_info node; memset(&node, 0, sizeof node); node.id = wn->id; node.control = IWN_NODE_UPDATE; node.flags = IWN_FLAG_SET_ADDBA; node.addba_tid = tid; node.addba_ssn = htole16(ba->ba_winstart); DPRINTF(sc, IWN_DEBUG_RECV, "ADDBA RA=%d TID=%d SSN=%d\n", wn->id, tid, ba->ba_winstart)); return sc->sc_hal->add_node(sc, &node, 1); } /* * This function is called by upper layer on teardown of an HT-immediate * Block Ack agreement (eg. uppon receipt of a DELBA frame.) */ static void iwn_ampdu_rx_stop(struct ieee80211com *ic, struct ieee80211_node *ni, uint8_t tid) { struct iwn_softc *sc = ic->ic_softc; struct iwn_node *wn = (void *)ni; struct iwn_node_info node; memset(&node, 0, sizeof node); node.id = wn->id; node.control = IWN_NODE_UPDATE; node.flags = IWN_FLAG_SET_DELBA; node.delba_tid = tid; DPRINTF(sc, IWN_DEBUG_RECV, "DELBA RA=%d TID=%d\n", wn->id, tid); (void)sc->sc_hal->add_node(sc, &node, 1); } /* * This function is called by upper layer when an ADDBA response is received * from another STA. */ static int iwn_ampdu_tx_start(struct ieee80211com *ic, struct ieee80211_node *ni, uint8_t tid) { struct ieee80211_tx_ba *ba = &ni->ni_tx_ba[tid]; struct iwn_softc *sc = ic->ic_softc; const struct iwn_hal *hal = sc->sc_hal; struct iwn_node *wn = (void *)ni; struct iwn_node_info node; int error; /* Enable TX for the specified RA/TID. */ wn->disable_tid &= ~(1 << tid); memset(&node, 0, sizeof node); node.id = wn->id; node.control = IWN_NODE_UPDATE; node.flags = IWN_FLAG_SET_DISABLE_TID; node.disable_tid = htole16(wn->disable_tid); error = hal->add_node(sc, &node, 1); if (error != 0) return error; if ((error = iwn_nic_lock(sc)) != 0) return error; hal->ampdu_tx_start(sc, ni, tid, ba->ba_winstart); iwn_nic_unlock(sc); return 0; } static void iwn_ampdu_tx_stop(struct ieee80211com *ic, struct ieee80211_node *ni, uint8_t tid) { struct ieee80211_tx_ba *ba = &ni->ni_tx_ba[tid]; struct iwn_softc *sc = ic->ic_softc; int error; error = iwn_nic_lock(sc); if (error != 0) return; sc->sc_hal->ampdu_tx_stop(sc, tid, ba->ba_winstart); iwn_nic_unlock(sc); } static void iwn4965_ampdu_tx_start(struct iwn_softc *sc, struct ieee80211_node *ni, uint8_t tid, uint16_t ssn) { struct iwn_node *wn = (void *)ni; int qid = 7 + tid; /* Stop TX scheduler while we're changing its configuration. */ iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid), IWN4965_TXQ_STATUS_CHGACT); /* Assign RA/TID translation to the queue. */ iwn_mem_write_2(sc, sc->sched_base + IWN4965_SCHED_TRANS_TBL(qid), wn->id << 4 | tid); /* Enable chain-building mode for the queue. */ iwn_prph_setbits(sc, IWN4965_SCHED_QCHAIN_SEL, 1 << qid); /* Set starting sequence number from the ADDBA request. */ IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff)); iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), ssn); /* Set scheduler window size. */ iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid), IWN_SCHED_WINSZ); /* Set scheduler frame limit. */ iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid) + 4, IWN_SCHED_LIMIT << 16); /* Enable interrupts for the queue. */ iwn_prph_setbits(sc, IWN4965_SCHED_INTR_MASK, 1 << qid); /* Mark the queue as active. */ iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid), IWN4965_TXQ_STATUS_ACTIVE | IWN4965_TXQ_STATUS_AGGR_ENA | iwn_tid2fifo[tid] << 1); } static void iwn4965_ampdu_tx_stop(struct iwn_softc *sc, uint8_t tid, uint16_t ssn) { int qid = 7 + tid; /* Stop TX scheduler while we're changing its configuration. */ iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid), IWN4965_TXQ_STATUS_CHGACT); /* Set starting sequence number from the ADDBA request. */ IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff)); iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), ssn); /* Disable interrupts for the queue. */ iwn_prph_clrbits(sc, IWN4965_SCHED_INTR_MASK, 1 << qid); /* Mark the queue as inactive. */ iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid), IWN4965_TXQ_STATUS_INACTIVE | iwn_tid2fifo[tid] << 1); } static void iwn5000_ampdu_tx_start(struct iwn_softc *sc, struct ieee80211_node *ni, uint8_t tid, uint16_t ssn) { struct iwn_node *wn = (void *)ni; int qid = 10 + tid; /* Stop TX scheduler while we're changing its configuration. */ iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid), IWN5000_TXQ_STATUS_CHGACT); /* Assign RA/TID translation to the queue. */ iwn_mem_write_2(sc, sc->sched_base + IWN5000_SCHED_TRANS_TBL(qid), wn->id << 4 | tid); /* Enable chain-building mode for the queue. */ iwn_prph_setbits(sc, IWN5000_SCHED_QCHAIN_SEL, 1 << qid); /* Enable aggregation for the queue. */ iwn_prph_setbits(sc, IWN5000_SCHED_AGGR_SEL, 1 << qid); /* Set starting sequence number from the ADDBA request. */ IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff)); iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), ssn); /* Set scheduler window size and frame limit. */ iwn_mem_write(sc, sc->sched_base + IWN5000_SCHED_QUEUE_OFFSET(qid) + 4, IWN_SCHED_LIMIT << 16 | IWN_SCHED_WINSZ); /* Enable interrupts for the queue. */ iwn_prph_setbits(sc, IWN5000_SCHED_INTR_MASK, 1 << qid); /* Mark the queue as active. */ iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid), IWN5000_TXQ_STATUS_ACTIVE | iwn_tid2fifo[tid]); } static void iwn5000_ampdu_tx_stop(struct iwn_softc *sc, uint8_t tid, uint16_t ssn) { int qid = 10 + tid; /* Stop TX scheduler while we're changing its configuration. */ iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid), IWN5000_TXQ_STATUS_CHGACT); /* Disable aggregation for the queue. */ iwn_prph_clrbits(sc, IWN5000_SCHED_AGGR_SEL, 1 << qid); /* Set starting sequence number from the ADDBA request. */ IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff)); iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), ssn); /* Disable interrupts for the queue. */ iwn_prph_clrbits(sc, IWN5000_SCHED_INTR_MASK, 1 << qid); /* Mark the queue as inactive. */ iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid), IWN5000_TXQ_STATUS_INACTIVE | iwn_tid2fifo[tid]); } #endif /* * Query calibration tables from the initialization firmware. We do this * only once at first boot. Called from a process context. */ static int iwn5000_query_calibration(struct iwn_softc *sc) { struct iwn5000_calib_config cmd; int error; memset(&cmd, 0, sizeof cmd); cmd.ucode.once.enable = 0xffffffff; cmd.ucode.once.start = 0xffffffff; cmd.ucode.once.send = 0xffffffff; cmd.ucode.flags = 0xffffffff; DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: sending calibration query\n", __func__); error = iwn_cmd(sc, IWN5000_CMD_CALIB_CONFIG, &cmd, sizeof cmd, 0); if (error != 0) return error; /* Wait at most two seconds for calibration to complete. */ if (!(sc->sc_flags & IWN_FLAG_CALIB_DONE)) { error = zsleep(sc, &wlan_global_serializer, 0, "iwninit", 2 * hz); } return error; } /* * Send calibration results to the runtime firmware. These results were * obtained on first boot from the initialization firmware. */ static int iwn5000_send_calibration(struct iwn_softc *sc) { int idx, error; for (idx = 0; idx < 5; idx++) { if (sc->calibcmd[idx].buf == NULL) continue; /* No results available. */ DPRINTF(sc, IWN_DEBUG_CALIBRATE, "send calibration result idx=%d len=%d\n", idx, sc->calibcmd[idx].len); error = iwn_cmd(sc, IWN_CMD_PHY_CALIB, sc->calibcmd[idx].buf, sc->calibcmd[idx].len, 0); if (error != 0) { device_printf(sc->sc_dev, "%s: could not send calibration result, error %d\n", __func__, error); return error; } } return 0; } static int iwn5000_send_wimax_coex(struct iwn_softc *sc) { struct iwn5000_wimax_coex wimax; #ifdef notyet if (sc->hw_type == IWN_HW_REV_TYPE_6050) { /* Enable WiMAX coexistence for combo adapters. */ wimax.flags = IWN_WIMAX_COEX_ASSOC_WA_UNMASK | IWN_WIMAX_COEX_UNASSOC_WA_UNMASK | IWN_WIMAX_COEX_STA_TABLE_VALID | IWN_WIMAX_COEX_ENABLE; memcpy(wimax.events, iwn6050_wimax_events, sizeof iwn6050_wimax_events); } else #endif { /* Disable WiMAX coexistence. */ wimax.flags = 0; memset(wimax.events, 0, sizeof wimax.events); } DPRINTF(sc, IWN_DEBUG_RESET, "%s: Configuring WiMAX coexistence\n", __func__); return iwn_cmd(sc, IWN5000_CMD_WIMAX_COEX, &wimax, sizeof wimax, 0); } /* * This function is called after the runtime firmware notifies us of its * readiness (called in a process context.) */ static int iwn4965_post_alive(struct iwn_softc *sc) { int error, qid; if ((error = iwn_nic_lock(sc)) != 0) return error; /* Clear TX scheduler state in SRAM. */ sc->sched_base = iwn_prph_read(sc, IWN_SCHED_SRAM_ADDR); iwn_mem_set_region_4(sc, sc->sched_base + IWN4965_SCHED_CTX_OFF, 0, IWN4965_SCHED_CTX_LEN / sizeof (uint32_t)); /* Set physical address of TX scheduler rings (1KB aligned.) */ iwn_prph_write(sc, IWN4965_SCHED_DRAM_ADDR, sc->sched_dma.paddr >> 10); IWN_SETBITS(sc, IWN_FH_TX_CHICKEN, IWN_FH_TX_CHICKEN_SCHED_RETRY); /* Disable chain mode for all our 16 queues. */ iwn_prph_write(sc, IWN4965_SCHED_QCHAIN_SEL, 0); for (qid = 0; qid < IWN4965_NTXQUEUES; qid++) { iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), 0); IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | 0); /* Set scheduler window size. */ iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid), IWN_SCHED_WINSZ); /* Set scheduler frame limit. */ iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid) + 4, IWN_SCHED_LIMIT << 16); } /* Enable interrupts for all our 16 queues. */ iwn_prph_write(sc, IWN4965_SCHED_INTR_MASK, 0xffff); /* Identify TX FIFO rings (0-7). */ iwn_prph_write(sc, IWN4965_SCHED_TXFACT, 0xff); /* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */ for (qid = 0; qid < 7; qid++) { static uint8_t qid2fifo[] = { 3, 2, 1, 0, 4, 5, 6 }; iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid), IWN4965_TXQ_STATUS_ACTIVE | qid2fifo[qid] << 1); } iwn_nic_unlock(sc); return 0; } /* * This function is called after the initialization or runtime firmware * notifies us of its readiness (called in a process context.) */ static int iwn5000_post_alive(struct iwn_softc *sc) { int error, qid; /* Switch to using ICT interrupt mode. */ iwn5000_ict_reset(sc); error = iwn_nic_lock(sc); if (error != 0) return error; /* Clear TX scheduler state in SRAM. */ sc->sched_base = iwn_prph_read(sc, IWN_SCHED_SRAM_ADDR); iwn_mem_set_region_4(sc, sc->sched_base + IWN5000_SCHED_CTX_OFF, 0, IWN5000_SCHED_CTX_LEN / sizeof (uint32_t)); /* Set physical address of TX scheduler rings (1KB aligned.) */ iwn_prph_write(sc, IWN5000_SCHED_DRAM_ADDR, sc->sched_dma.paddr >> 10); IWN_SETBITS(sc, IWN_FH_TX_CHICKEN, IWN_FH_TX_CHICKEN_SCHED_RETRY); /* Enable chain mode for all queues, except command queue. */ iwn_prph_write(sc, IWN5000_SCHED_QCHAIN_SEL, 0xfffef); iwn_prph_write(sc, IWN5000_SCHED_AGGR_SEL, 0); for (qid = 0; qid < IWN5000_NTXQUEUES; qid++) { iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), 0); IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | 0); iwn_mem_write(sc, sc->sched_base + IWN5000_SCHED_QUEUE_OFFSET(qid), 0); /* Set scheduler window size and frame limit. */ iwn_mem_write(sc, sc->sched_base + IWN5000_SCHED_QUEUE_OFFSET(qid) + 4, IWN_SCHED_LIMIT << 16 | IWN_SCHED_WINSZ); } /* Enable interrupts for all our 20 queues. */ iwn_prph_write(sc, IWN5000_SCHED_INTR_MASK, 0xfffff); /* Identify TX FIFO rings (0-7). */ iwn_prph_write(sc, IWN5000_SCHED_TXFACT, 0xff); /* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */ for (qid = 0; qid < 7; qid++) { static uint8_t qid2fifo[] = { 3, 2, 1, 0, 7, 5, 6 }; iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid), IWN5000_TXQ_STATUS_ACTIVE | qid2fifo[qid]); } iwn_nic_unlock(sc); /* Configure WiMAX coexistence for combo adapters. */ error = iwn5000_send_wimax_coex(sc); if (error != 0) { device_printf(sc->sc_dev, "%s: could not configure WiMAX coexistence, error %d\n", __func__, error); return error; } if (sc->hw_type != IWN_HW_REV_TYPE_5150) { struct iwn5000_phy_calib_crystal cmd; /* Perform crystal calibration. */ memset(&cmd, 0, sizeof cmd); cmd.code = IWN5000_PHY_CALIB_CRYSTAL; cmd.ngroups = 1; cmd.isvalid = 1; cmd.cap_pin[0] = le32toh(sc->eeprom_crystal) & 0xff; cmd.cap_pin[1] = (le32toh(sc->eeprom_crystal) >> 16) & 0xff; DPRINTF(sc, IWN_DEBUG_CALIBRATE, "sending crystal calibration %d, %d\n", cmd.cap_pin[0], cmd.cap_pin[1]); error = iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0); if (error != 0) { device_printf(sc->sc_dev, "%s: crystal calibration failed, error %d\n", __func__, error); return error; } } if (!(sc->sc_flags & IWN_FLAG_CALIB_DONE)) { /* Query calibration from the initialization firmware. */ error = iwn5000_query_calibration(sc); if (error != 0) { device_printf(sc->sc_dev, "%s: could not query calibration, error %d\n", __func__, error); return error; } /* * We have the calibration results now, reboot with the * runtime firmware (call ourselves recursively!) */ iwn_hw_stop(sc); error = iwn_hw_init(sc); } else { /* Send calibration results to runtime firmware. */ error = iwn5000_send_calibration(sc); } return error; } /* * The firmware boot code is small and is intended to be copied directly into * the NIC internal memory (no DMA transfer.) */ static int iwn4965_load_bootcode(struct iwn_softc *sc, const uint8_t *ucode, int size) { int error, ntries; size /= sizeof (uint32_t); error = iwn_nic_lock(sc); if (error != 0) return error; /* Copy microcode image into NIC memory. */ iwn_prph_write_region_4(sc, IWN_BSM_SRAM_BASE, (const uint32_t *)ucode, size); iwn_prph_write(sc, IWN_BSM_WR_MEM_SRC, 0); iwn_prph_write(sc, IWN_BSM_WR_MEM_DST, IWN_FW_TEXT_BASE); iwn_prph_write(sc, IWN_BSM_WR_DWCOUNT, size); /* Start boot load now. */ iwn_prph_write(sc, IWN_BSM_WR_CTRL, IWN_BSM_WR_CTRL_START); /* Wait for transfer to complete. */ for (ntries = 0; ntries < 1000; ntries++) { if (!(iwn_prph_read(sc, IWN_BSM_WR_CTRL) & IWN_BSM_WR_CTRL_START)) break; DELAY(10); } if (ntries == 1000) { device_printf(sc->sc_dev, "%s: could not load boot firmware\n", __func__); iwn_nic_unlock(sc); return ETIMEDOUT; } /* Enable boot after power up. */ iwn_prph_write(sc, IWN_BSM_WR_CTRL, IWN_BSM_WR_CTRL_START_EN); iwn_nic_unlock(sc); return 0; } static int iwn4965_load_firmware(struct iwn_softc *sc) { struct iwn_fw_info *fw = &sc->fw; struct iwn_dma_info *dma = &sc->fw_dma; int error; /* Copy initialization sections into pre-allocated DMA-safe memory. */ memcpy(dma->vaddr, fw->init.data, fw->init.datasz); bus_dmamap_sync(sc->fw_dma.tag, dma->map, BUS_DMASYNC_PREWRITE); memcpy(dma->vaddr + IWN4965_FW_DATA_MAXSZ, fw->init.text, fw->init.textsz); bus_dmamap_sync(sc->fw_dma.tag, dma->map, BUS_DMASYNC_PREWRITE); /* Tell adapter where to find initialization sections. */ error = iwn_nic_lock(sc); if (error != 0) return error; iwn_prph_write(sc, IWN_BSM_DRAM_DATA_ADDR, dma->paddr >> 4); iwn_prph_write(sc, IWN_BSM_DRAM_DATA_SIZE, fw->init.datasz); iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_ADDR, (dma->paddr + IWN4965_FW_DATA_MAXSZ) >> 4); iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_SIZE, fw->init.textsz); iwn_nic_unlock(sc); /* Load firmware boot code. */ error = iwn4965_load_bootcode(sc, fw->boot.text, fw->boot.textsz); if (error != 0) { device_printf(sc->sc_dev, "%s: could not load boot firmware\n", __func__); return error; } /* Now press "execute". */ IWN_WRITE(sc, IWN_RESET, 0); /* Wait at most one second for first alive notification. */ error = zsleep(sc, &wlan_global_serializer, 0, "iwninit", hz); if (error) { device_printf(sc->sc_dev, "%s: timeout waiting for adapter to initialize, error %d\n", __func__, error); return error; } /* Retrieve current temperature for initial TX power calibration. */ sc->rawtemp = sc->ucode_info.temp[3].chan20MHz; sc->temp = iwn4965_get_temperature(sc); /* Copy runtime sections into pre-allocated DMA-safe memory. */ memcpy(dma->vaddr, fw->main.data, fw->main.datasz); bus_dmamap_sync(sc->fw_dma.tag, dma->map, BUS_DMASYNC_PREWRITE); memcpy(dma->vaddr + IWN4965_FW_DATA_MAXSZ, fw->main.text, fw->main.textsz); bus_dmamap_sync(sc->fw_dma.tag, dma->map, BUS_DMASYNC_PREWRITE); /* Tell adapter where to find runtime sections. */ error = iwn_nic_lock(sc); if (error != 0) return error; iwn_prph_write(sc, IWN_BSM_DRAM_DATA_ADDR, dma->paddr >> 4); iwn_prph_write(sc, IWN_BSM_DRAM_DATA_SIZE, fw->main.datasz); iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_ADDR, (dma->paddr + IWN4965_FW_DATA_MAXSZ) >> 4); iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_SIZE, IWN_FW_UPDATED | fw->main.textsz); iwn_nic_unlock(sc); return 0; } static int iwn5000_load_firmware_section(struct iwn_softc *sc, uint32_t dst, const uint8_t *section, int size) { struct iwn_dma_info *dma = &sc->fw_dma; int error; /* Copy firmware section into pre-allocated DMA-safe memory. */ memcpy(dma->vaddr, section, size); bus_dmamap_sync(sc->fw_dma.tag, dma->map, BUS_DMASYNC_PREWRITE); error = iwn_nic_lock(sc); if (error != 0) return error; IWN_WRITE(sc, IWN_FH_TX_CONFIG(IWN_SRVC_DMACHNL), IWN_FH_TX_CONFIG_DMA_PAUSE); IWN_WRITE(sc, IWN_FH_SRAM_ADDR(IWN_SRVC_DMACHNL), dst); IWN_WRITE(sc, IWN_FH_TFBD_CTRL0(IWN_SRVC_DMACHNL), IWN_LOADDR(dma->paddr)); IWN_WRITE(sc, IWN_FH_TFBD_CTRL1(IWN_SRVC_DMACHNL), IWN_HIADDR(dma->paddr) << 28 | size); IWN_WRITE(sc, IWN_FH_TXBUF_STATUS(IWN_SRVC_DMACHNL), IWN_FH_TXBUF_STATUS_TBNUM(1) | IWN_FH_TXBUF_STATUS_TBIDX(1) | IWN_FH_TXBUF_STATUS_TFBD_VALID); /* Kick Flow Handler to start DMA transfer. */ IWN_WRITE(sc, IWN_FH_TX_CONFIG(IWN_SRVC_DMACHNL), IWN_FH_TX_CONFIG_DMA_ENA | IWN_FH_TX_CONFIG_CIRQ_HOST_ENDTFD); iwn_nic_unlock(sc); /* * Wait at most five seconds for FH DMA transfer to complete. */ error = zsleep(sc, &wlan_global_serializer, 0, "iwninit", hz); return (error); } static int iwn5000_load_firmware(struct iwn_softc *sc) { struct iwn_fw_part *fw; int error; /* Load the initialization firmware on first boot only. */ fw = (sc->sc_flags & IWN_FLAG_CALIB_DONE) ? &sc->fw.main : &sc->fw.init; error = iwn5000_load_firmware_section(sc, IWN_FW_TEXT_BASE, fw->text, fw->textsz); if (error != 0) { device_printf(sc->sc_dev, "%s: could not load firmware %s section, error %d\n", __func__, ".text", error); return error; } error = iwn5000_load_firmware_section(sc, IWN_FW_DATA_BASE, fw->data, fw->datasz); if (error != 0) { device_printf(sc->sc_dev, "%s: could not load firmware %s section, error %d\n", __func__, ".data", error); return error; } /* Now press "execute". */ IWN_WRITE(sc, IWN_RESET, 0); return 0; } static int iwn_read_firmware(struct iwn_softc *sc) { const struct iwn_hal *hal = sc->sc_hal; struct iwn_fw_info *fw = &sc->fw; const uint32_t *ptr; uint32_t rev; size_t size; int wlan_serialized; /* * Read firmware image from filesystem. The firmware can block * in a taskq and deadlock against our serializer so unlock * while we do tihs. */ wlan_serialized = IS_SERIALIZED(&wlan_global_serializer); if (wlan_serialized) wlan_serialize_exit(); sc->fw_fp = firmware_get(sc->fwname); if (wlan_serialized) wlan_serialize_enter(); if (sc->fw_fp == NULL) { device_printf(sc->sc_dev, "%s: could not load firmare image \"%s\"\n", __func__, sc->fwname); return EINVAL; } size = sc->fw_fp->datasize; if (size < 28) { device_printf(sc->sc_dev, "%s: truncated firmware header: %zu bytes\n", __func__, size); return EINVAL; } /* Process firmware header. */ ptr = (const uint32_t *)sc->fw_fp->data; rev = le32toh(*ptr++); /* Check firmware API version. */ if (IWN_FW_API(rev) <= 1) { device_printf(sc->sc_dev, "%s: bad firmware, need API version >=2\n", __func__); return EINVAL; } if (IWN_FW_API(rev) >= 3) { /* Skip build number (version 2 header). */ size -= 4; ptr++; } fw->main.textsz = le32toh(*ptr++); fw->main.datasz = le32toh(*ptr++); fw->init.textsz = le32toh(*ptr++); fw->init.datasz = le32toh(*ptr++); fw->boot.textsz = le32toh(*ptr++); size -= 24; /* Sanity-check firmware header. */ if (fw->main.textsz > hal->fw_text_maxsz || fw->main.datasz > hal->fw_data_maxsz || fw->init.textsz > hal->fw_text_maxsz || fw->init.datasz > hal->fw_data_maxsz || fw->boot.textsz > IWN_FW_BOOT_TEXT_MAXSZ || (fw->boot.textsz & 3) != 0) { device_printf(sc->sc_dev, "%s: invalid firmware header\n", __func__); return EINVAL; } /* Check that all firmware sections fit. */ if (fw->main.textsz + fw->main.datasz + fw->init.textsz + fw->init.datasz + fw->boot.textsz > size) { device_printf(sc->sc_dev, "%s: firmware file too short: %zu bytes\n", __func__, size); return EINVAL; } /* Get pointers to firmware sections. */ fw->main.text = (const uint8_t *)ptr; fw->main.data = fw->main.text + fw->main.textsz; fw->init.text = fw->main.data + fw->main.datasz; fw->init.data = fw->init.text + fw->init.textsz; fw->boot.text = fw->init.data + fw->init.datasz; return 0; } static int iwn_clock_wait(struct iwn_softc *sc) { int ntries; /* Set "initialization complete" bit. */ IWN_SETBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_INIT_DONE); /* Wait for clock stabilization. */ for (ntries = 0; ntries < 2500; ntries++) { if (IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_MAC_CLOCK_READY) return 0; DELAY(10); } device_printf(sc->sc_dev, "%s: timeout waiting for clock stabilization\n", __func__); return ETIMEDOUT; } static int iwn_apm_init(struct iwn_softc *sc) { uint32_t tmp; int error; /* Disable L0s exit timer (NMI bug workaround.) */ IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_DIS_L0S_TIMER); /* Don't wait for ICH L0s (ICH bug workaround.) */ IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_L1A_NO_L0S_RX); /* Set FH wait threshold to max (HW bug under stress workaround.) */ IWN_SETBITS(sc, IWN_DBG_HPET_MEM, 0xffff0000); /* Enable HAP INTA to move adapter from L1a to L0s. */ IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_HAP_WAKE_L1A); /* Retrieve PCIe Active State Power Management (ASPM). */ tmp = pci_read_config(sc->sc_dev, sc->sc_cap_off + 0x10, 1); /* Workaround for HW instability in PCIe L0->L0s->L1 transition. */ if (tmp & 0x02) /* L1 Entry enabled. */ IWN_SETBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA); else IWN_CLRBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA); if (sc->hw_type != IWN_HW_REV_TYPE_4965 && sc->hw_type != IWN_HW_REV_TYPE_6000 && sc->hw_type != IWN_HW_REV_TYPE_6050) IWN_SETBITS(sc, IWN_ANA_PLL, IWN_ANA_PLL_INIT); /* Wait for clock stabilization before accessing prph. */ error = iwn_clock_wait(sc); if (error != 0) return error; error = iwn_nic_lock(sc); if (error != 0) return error; if (sc->hw_type == IWN_HW_REV_TYPE_4965) { /* Enable DMA and BSM (Bootstrap State Machine.) */ iwn_prph_write(sc, IWN_APMG_CLK_EN, IWN_APMG_CLK_CTRL_DMA_CLK_RQT | IWN_APMG_CLK_CTRL_BSM_CLK_RQT); } else { /* Enable DMA. */ iwn_prph_write(sc, IWN_APMG_CLK_EN, IWN_APMG_CLK_CTRL_DMA_CLK_RQT); } DELAY(20); /* Disable L1-Active. */ iwn_prph_setbits(sc, IWN_APMG_PCI_STT, IWN_APMG_PCI_STT_L1A_DIS); iwn_nic_unlock(sc); return 0; } static void iwn_apm_stop_master(struct iwn_softc *sc) { int ntries; /* Stop busmaster DMA activity. */ IWN_SETBITS(sc, IWN_RESET, IWN_RESET_STOP_MASTER); for (ntries = 0; ntries < 100; ntries++) { if (IWN_READ(sc, IWN_RESET) & IWN_RESET_MASTER_DISABLED) return; DELAY(10); } device_printf(sc->sc_dev, "%s: timeout waiting for master\n", __func__); } static void iwn_apm_stop(struct iwn_softc *sc) { iwn_apm_stop_master(sc); /* Reset the entire device. */ IWN_SETBITS(sc, IWN_RESET, IWN_RESET_SW); DELAY(10); /* Clear "initialization complete" bit. */ IWN_CLRBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_INIT_DONE); } static int iwn4965_nic_config(struct iwn_softc *sc) { if (IWN_RFCFG_TYPE(sc->rfcfg) == 1) { /* * I don't believe this to be correct but this is what the * vendor driver is doing. Probably the bits should not be * shifted in IWN_RFCFG_*. */ IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_RFCFG_TYPE(sc->rfcfg) | IWN_RFCFG_STEP(sc->rfcfg) | IWN_RFCFG_DASH(sc->rfcfg)); } IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_RADIO_SI | IWN_HW_IF_CONFIG_MAC_SI); return 0; } static int iwn5000_nic_config(struct iwn_softc *sc) { uint32_t tmp; int error; if (IWN_RFCFG_TYPE(sc->rfcfg) < 3) { IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_RFCFG_TYPE(sc->rfcfg) | IWN_RFCFG_STEP(sc->rfcfg) | IWN_RFCFG_DASH(sc->rfcfg)); } IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_RADIO_SI | IWN_HW_IF_CONFIG_MAC_SI); error = iwn_nic_lock(sc); if (error != 0) return error; iwn_prph_setbits(sc, IWN_APMG_PS, IWN_APMG_PS_EARLY_PWROFF_DIS); if (sc->hw_type == IWN_HW_REV_TYPE_1000) { /* * Select first Switching Voltage Regulator (1.32V) to * solve a stability issue related to noisy DC2DC line * in the silicon of 1000 Series. */ tmp = iwn_prph_read(sc, IWN_APMG_DIGITAL_SVR); tmp &= ~IWN_APMG_DIGITAL_SVR_VOLTAGE_MASK; tmp |= IWN_APMG_DIGITAL_SVR_VOLTAGE_1_32; iwn_prph_write(sc, IWN_APMG_DIGITAL_SVR, tmp); } iwn_nic_unlock(sc); if (sc->sc_flags & IWN_FLAG_INTERNAL_PA) { /* Use internal power amplifier only. */ IWN_WRITE(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_RADIO_2X2_IPA); } if (sc->hw_type == IWN_HW_REV_TYPE_6050 && sc->calib_ver >= 6) { /* Indicate that ROM calibration version is >=6. */ IWN_SETBITS(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_CALIB_VER6); } return 0; } /* * Take NIC ownership over Intel Active Management Technology (AMT). */ static int iwn_hw_prepare(struct iwn_softc *sc) { int ntries; /* Check if hardware is ready. */ IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_NIC_READY); for (ntries = 0; ntries < 5; ntries++) { if (IWN_READ(sc, IWN_HW_IF_CONFIG) & IWN_HW_IF_CONFIG_NIC_READY) return 0; DELAY(10); } /* Hardware not ready, force into ready state. */ IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_PREPARE); for (ntries = 0; ntries < 15000; ntries++) { if (!(IWN_READ(sc, IWN_HW_IF_CONFIG) & IWN_HW_IF_CONFIG_PREPARE_DONE)) break; DELAY(10); } if (ntries == 15000) return ETIMEDOUT; /* Hardware should be ready now. */ IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_NIC_READY); for (ntries = 0; ntries < 5; ntries++) { if (IWN_READ(sc, IWN_HW_IF_CONFIG) & IWN_HW_IF_CONFIG_NIC_READY) return 0; DELAY(10); } return ETIMEDOUT; } static int iwn_hw_init(struct iwn_softc *sc) { const struct iwn_hal *hal = sc->sc_hal; int error, chnl, qid; /* Clear pending interrupts. */ IWN_WRITE(sc, IWN_INT, 0xffffffff); error = iwn_apm_init(sc); if (error != 0) { device_printf(sc->sc_dev, "%s: could not power ON adapter, error %d\n", __func__, error); goto done; } /* Select VMAIN power source. */ error = iwn_nic_lock(sc); if (error != 0) goto done; iwn_prph_clrbits(sc, IWN_APMG_PS, IWN_APMG_PS_PWR_SRC_MASK); iwn_nic_unlock(sc); /* Perform adapter-specific initialization. */ error = hal->nic_config(sc); if (error != 0) goto done; /* Initialize RX ring. */ error = iwn_nic_lock(sc); if (error != 0) goto done; IWN_WRITE(sc, IWN_FH_RX_CONFIG, 0); IWN_WRITE(sc, IWN_FH_RX_WPTR, 0); /* Set physical address of RX ring (256-byte aligned.) */ IWN_WRITE(sc, IWN_FH_RX_BASE, sc->rxq.desc_dma.paddr >> 8); /* Set physical address of RX status (16-byte aligned.) */ IWN_WRITE(sc, IWN_FH_STATUS_WPTR, sc->rxq.stat_dma.paddr >> 4); /* Enable RX. */ IWN_WRITE(sc, IWN_FH_RX_CONFIG, IWN_FH_RX_CONFIG_ENA | IWN_FH_RX_CONFIG_IGN_RXF_EMPTY | /* HW bug workaround */ IWN_FH_RX_CONFIG_IRQ_DST_HOST | IWN_FH_RX_CONFIG_SINGLE_FRAME | IWN_FH_RX_CONFIG_RB_TIMEOUT(0) | IWN_FH_RX_CONFIG_NRBD(IWN_RX_RING_COUNT_LOG)); iwn_nic_unlock(sc); IWN_WRITE(sc, IWN_FH_RX_WPTR, (IWN_RX_RING_COUNT - 1) & ~7); error = iwn_nic_lock(sc); if (error != 0) goto done; /* Initialize TX scheduler. */ iwn_prph_write(sc, hal->sched_txfact_addr, 0); /* Set physical address of "keep warm" page (16-byte aligned.) */ IWN_WRITE(sc, IWN_FH_KW_ADDR, sc->kw_dma.paddr >> 4); /* Initialize TX rings. */ for (qid = 0; qid < hal->ntxqs; qid++) { struct iwn_tx_ring *txq = &sc->txq[qid]; /* Set physical address of TX ring (256-byte aligned.) */ IWN_WRITE(sc, IWN_FH_CBBC_QUEUE(qid), txq->desc_dma.paddr >> 8); } iwn_nic_unlock(sc); /* Enable DMA channels. */ for (chnl = 0; chnl < hal->ndmachnls; chnl++) { IWN_WRITE(sc, IWN_FH_TX_CONFIG(chnl), IWN_FH_TX_CONFIG_DMA_ENA | IWN_FH_TX_CONFIG_DMA_CREDIT_ENA); } /* Clear "radio off" and "commands blocked" bits. */ IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL); IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_CMD_BLOCKED); /* Clear pending interrupts. */ IWN_WRITE(sc, IWN_INT, 0xffffffff); /* Enable interrupt coalescing. */ IWN_WRITE(sc, IWN_INT_COALESCING, 512 / 8); /* Enable interrupts. */ IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask); /* _Really_ make sure "radio off" bit is cleared! */ IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL); IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL); error = hal->load_firmware(sc); if (error != 0) { device_printf(sc->sc_dev, "%s: could not load firmware, error %d\n", __func__, error); goto done; } /* Wait at most one second for firmware alive notification. */ error = zsleep(sc, &wlan_global_serializer, 0, "iwninit", hz); if (error != 0) { device_printf(sc->sc_dev, "%s: timeout waiting for adapter to initialize, error %d\n", __func__, error); goto done; } /* Do post-firmware initialization. */ error = hal->post_alive(sc); done: return error; } static void iwn_hw_stop(struct iwn_softc *sc) { const struct iwn_hal *hal = sc->sc_hal; uint32_t tmp; int chnl, qid, ntries; IWN_WRITE(sc, IWN_RESET, IWN_RESET_NEVO); /* Disable interrupts. */ IWN_WRITE(sc, IWN_INT_MASK, 0); IWN_WRITE(sc, IWN_INT, 0xffffffff); IWN_WRITE(sc, IWN_FH_INT, 0xffffffff); sc->sc_flags &= ~IWN_FLAG_USE_ICT; /* Make sure we no longer hold the NIC lock. */ iwn_nic_unlock(sc); /* Stop TX scheduler. */ iwn_prph_write(sc, hal->sched_txfact_addr, 0); /* Stop all DMA channels. */ if (iwn_nic_lock(sc) == 0) { for (chnl = 0; chnl < hal->ndmachnls; chnl++) { IWN_WRITE(sc, IWN_FH_TX_CONFIG(chnl), 0); for (ntries = 0; ntries < 200; ntries++) { tmp = IWN_READ(sc, IWN_FH_TX_STATUS); if ((tmp & IWN_FH_TX_STATUS_IDLE(chnl)) == IWN_FH_TX_STATUS_IDLE(chnl)) break; DELAY(10); } } iwn_nic_unlock(sc); } /* Stop RX ring. */ iwn_reset_rx_ring(sc, &sc->rxq); /* Reset all TX rings. */ for (qid = 0; qid < hal->ntxqs; qid++) iwn_reset_tx_ring(sc, &sc->txq[qid]); if (iwn_nic_lock(sc) == 0) { iwn_prph_write(sc, IWN_APMG_CLK_DIS, IWN_APMG_CLK_CTRL_DMA_CLK_RQT); iwn_nic_unlock(sc); } DELAY(5); /* Power OFF adapter. */ iwn_apm_stop(sc); } static void iwn_init_locked(struct iwn_softc *sc) { struct ifnet *ifp = sc->sc_ifp; int error; int wlan_serializer_needed; /* * The kernel generic firmware loader can wind up calling this * without the wlan serializer, while the wlan subsystem will * call it with the serializer. * * Make sure we hold the serializer or we will have timing issues * with the wlan subsystem. */ wlan_serializer_needed = !IS_SERIALIZED(&wlan_global_serializer); if (wlan_serializer_needed) wlan_serialize_enter(); error = iwn_hw_prepare(sc); if (error != 0) { device_printf(sc->sc_dev, "%s: hardware not ready, eror %d\n", __func__, error); goto fail; } /* Initialize interrupt mask to default value. */ sc->int_mask = IWN_INT_MASK_DEF; sc->sc_flags &= ~IWN_FLAG_USE_ICT; /* Check that the radio is not disabled by hardware switch. */ if (!(IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_RFKILL)) { device_printf(sc->sc_dev, "radio is disabled by hardware switch\n"); /* Enable interrupts to get RF toggle notifications. */ IWN_WRITE(sc, IWN_INT, 0xffffffff); IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask); if (wlan_serializer_needed) wlan_serialize_exit(); return; } /* Read firmware images from the filesystem. */ error = iwn_read_firmware(sc); if (error != 0) { device_printf(sc->sc_dev, "%s: could not read firmware, error %d\n", __func__, error); goto fail; } /* Initialize hardware and upload firmware. */ error = iwn_hw_init(sc); firmware_put(sc->fw_fp, FIRMWARE_UNLOAD); sc->fw_fp = NULL; if (error != 0) { device_printf(sc->sc_dev, "%s: could not initialize hardware, error %d\n", __func__, error); goto fail; } /* Configure adapter now that it is ready. */ error = iwn_config(sc); if (error != 0) { device_printf(sc->sc_dev, "%s: could not configure device, error %d\n", __func__, error); goto fail; } ifp->if_flags &= ~IFF_OACTIVE; ifp->if_flags |= IFF_RUNNING; if (wlan_serializer_needed) wlan_serialize_exit(); return; fail: iwn_stop_locked(sc); if (wlan_serializer_needed) wlan_serialize_exit(); } static void iwn_init(void *arg) { struct iwn_softc *sc = arg; struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; wlan_serialize_enter(); iwn_init_locked(sc); wlan_serialize_exit(); if (ifp->if_flags & IFF_RUNNING) ieee80211_start_all(ic); } static void iwn_stop_locked(struct iwn_softc *sc) { struct ifnet *ifp = sc->sc_ifp; sc->sc_tx_timer = 0; callout_stop(&sc->sc_timer_to); ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE); /* Power OFF hardware. */ iwn_hw_stop(sc); } static void iwn_stop(struct iwn_softc *sc) { wlan_serialize_enter(); iwn_stop_locked(sc); wlan_serialize_exit(); } /* * Callback from net80211 to start a scan. */ static void iwn_scan_start(struct ieee80211com *ic) { struct ifnet *ifp = ic->ic_ifp; struct iwn_softc *sc = ifp->if_softc; /* make the link LED blink while we're scanning */ iwn_set_led(sc, IWN_LED_LINK, 20, 2); } /* * Callback from net80211 to terminate a scan. */ static void iwn_scan_end(struct ieee80211com *ic) { struct ifnet *ifp = ic->ic_ifp; struct iwn_softc *sc = ifp->if_softc; struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps); if (vap->iv_state == IEEE80211_S_RUN) { /* Set link LED to ON status if we are associated */ iwn_set_led(sc, IWN_LED_LINK, 0, 1); } } /* * Callback from net80211 to force a channel change. */ static void iwn_set_channel(struct ieee80211com *ic) { const struct ieee80211_channel *c = ic->ic_curchan; struct ifnet *ifp = ic->ic_ifp; struct iwn_softc *sc = ifp->if_softc; sc->sc_rxtap.wr_chan_freq = htole16(c->ic_freq); sc->sc_rxtap.wr_chan_flags = htole16(c->ic_flags); sc->sc_txtap.wt_chan_freq = htole16(c->ic_freq); sc->sc_txtap.wt_chan_flags = htole16(c->ic_flags); } /* * Callback from net80211 to start scanning of the current channel. */ static void iwn_scan_curchan(struct ieee80211_scan_state *ss, unsigned long maxdwell) { struct ieee80211vap *vap = ss->ss_vap; struct iwn_softc *sc = vap->iv_ic->ic_ifp->if_softc; int error; error = iwn_scan(sc); if (error != 0) ieee80211_cancel_scan(vap); } /* * Callback from net80211 to handle the minimum dwell time being met. * The intent is to terminate the scan but we just let the firmware * notify us when it's finished as we have no safe way to abort it. */ static void iwn_scan_mindwell(struct ieee80211_scan_state *ss) { /* NB: don't try to abort scan; wait for firmware to finish */ } static struct iwn_eeprom_chan * iwn_find_eeprom_channel(struct iwn_softc *sc, struct ieee80211_channel *c) { int i, j; for (j = 0; j < 7; j++) { for (i = 0; i < iwn_bands[j].nchan; i++) { if (iwn_bands[j].chan[i] == c->ic_ieee) return &sc->eeprom_channels[j][i]; } } return NULL; } /* * Enforce flags read from EEPROM. */ static int iwn_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *rd, int nchan, struct ieee80211_channel chans[]) { struct iwn_softc *sc = ic->ic_ifp->if_softc; int i; for (i = 0; i < nchan; i++) { struct ieee80211_channel *c = &chans[i]; struct iwn_eeprom_chan *channel; channel = iwn_find_eeprom_channel(sc, c); if (channel == NULL) { if_printf(ic->ic_ifp, "%s: invalid channel %u freq %u/0x%x\n", __func__, c->ic_ieee, c->ic_freq, c->ic_flags); return EINVAL; } c->ic_flags |= iwn_eeprom_channel_flags(channel); } return 0; } static void iwn_hw_reset_task(void *arg0, int pending) { struct iwn_softc *sc = arg0; struct ifnet *ifp; struct ieee80211com *ic; wlan_serialize_enter(); ifp = sc->sc_ifp; ic = ifp->if_l2com; iwn_stop_locked(sc); iwn_init_locked(sc); ieee80211_notify_radio(ic, 1); wlan_serialize_exit(); } static void iwn_radio_on_task(void *arg0, int pending) { struct iwn_softc *sc = arg0; struct ifnet *ifp; struct ieee80211com *ic; struct ieee80211vap *vap; wlan_serialize_enter(); ifp = sc->sc_ifp; ic = ifp->if_l2com; vap = TAILQ_FIRST(&ic->ic_vaps); if (vap != NULL) { iwn_init_locked(sc); ieee80211_init(vap); } wlan_serialize_exit(); } static void iwn_radio_off_task(void *arg0, int pending) { struct iwn_softc *sc = arg0; struct ifnet *ifp; struct ieee80211com *ic; struct ieee80211vap *vap; wlan_serialize_enter(); ifp = sc->sc_ifp; ic = ifp->if_l2com; vap = TAILQ_FIRST(&ic->ic_vaps); iwn_stop_locked(sc); if (vap != NULL) ieee80211_stop(vap); /* Enable interrupts to get RF toggle notification. */ IWN_WRITE(sc, IWN_INT, 0xffffffff); IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask); wlan_serialize_exit(); } static void iwn_sysctlattach(struct iwn_softc *sc) { struct sysctl_ctx_list *ctx; struct sysctl_oid *tree; ctx = &sc->sc_sysctl_ctx; tree = sc->sc_sysctl_tree; if (tree == NULL) { device_printf(sc->sc_dev, "can't add sysctl node\n"); return; } #ifdef IWN_DEBUG sc->sc_debug = 0; SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "debug", CTLFLAG_RW, &sc->sc_debug, 0, "control debugging printfs"); #endif } static int iwn_pci_shutdown(device_t dev) { struct iwn_softc *sc = device_get_softc(dev); wlan_serialize_enter(); iwn_stop_locked(sc); wlan_serialize_exit(); return 0; } static int iwn_pci_suspend(device_t dev) { struct iwn_softc *sc = device_get_softc(dev); struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps); wlan_serialize_enter(); iwn_stop_locked(sc); if (vap != NULL) ieee80211_stop(vap); wlan_serialize_exit(); return 0; } static int iwn_pci_resume(device_t dev) { struct iwn_softc *sc = device_get_softc(dev); struct ifnet *ifp; struct ieee80211com *ic; struct ieee80211vap *vap; wlan_serialize_enter(); ifp = sc->sc_ifp; ic = ifp->if_l2com; vap = TAILQ_FIRST(&ic->ic_vaps); /* Clear device-specific "PCI retry timeout" register (41h). */ pci_write_config(dev, 0x41, 0, 1); if (ifp->if_flags & IFF_UP) { iwn_init_locked(sc); if (vap != NULL) ieee80211_init(vap); if (ifp->if_flags & IFF_RUNNING) iwn_start_locked(ifp); } wlan_serialize_exit(); return 0; } #ifdef IWN_DEBUG static const char * iwn_intr_str(uint8_t cmd) { switch (cmd) { /* Notifications */ case IWN_UC_READY: return "UC_READY"; case IWN_ADD_NODE_DONE: return "ADD_NODE_DONE"; case IWN_TX_DONE: return "TX_DONE"; case IWN_START_SCAN: return "START_SCAN"; case IWN_STOP_SCAN: return "STOP_SCAN"; case IWN_RX_STATISTICS: return "RX_STATS"; case IWN_BEACON_STATISTICS: return "BEACON_STATS"; case IWN_STATE_CHANGED: return "STATE_CHANGED"; case IWN_BEACON_MISSED: return "BEACON_MISSED"; case IWN_RX_PHY: return "RX_PHY"; case IWN_MPDU_RX_DONE: return "MPDU_RX_DONE"; case IWN_RX_DONE: return "RX_DONE"; /* Command Notifications */ case IWN_CMD_RXON: return "IWN_CMD_RXON"; case IWN_CMD_RXON_ASSOC: return "IWN_CMD_RXON_ASSOC"; case IWN_CMD_EDCA_PARAMS: return "IWN_CMD_EDCA_PARAMS"; case IWN_CMD_TIMING: return "IWN_CMD_TIMING"; case IWN_CMD_LINK_QUALITY: return "IWN_CMD_LINK_QUALITY"; case IWN_CMD_SET_LED: return "IWN_CMD_SET_LED"; case IWN5000_CMD_WIMAX_COEX: return "IWN5000_CMD_WIMAX_COEX"; case IWN5000_CMD_CALIB_CONFIG: return "IWN5000_CMD_CALIB_CONFIG"; case IWN5000_CMD_CALIB_RESULT: return "IWN5000_CMD_CALIB_RESULT"; case IWN5000_CMD_CALIB_COMPLETE: return "IWN5000_CMD_CALIB_COMPLETE"; case IWN_CMD_SET_POWER_MODE: return "IWN_CMD_SET_POWER_MODE"; case IWN_CMD_SCAN: return "IWN_CMD_SCAN"; case IWN_CMD_SCAN_RESULTS: return "IWN_CMD_SCAN_RESULTS"; case IWN_CMD_TXPOWER: return "IWN_CMD_TXPOWER"; case IWN_CMD_TXPOWER_DBM: return "IWN_CMD_TXPOWER_DBM"; case IWN5000_CMD_TX_ANT_CONFIG: return "IWN5000_CMD_TX_ANT_CONFIG"; case IWN_CMD_BT_COEX: return "IWN_CMD_BT_COEX"; case IWN_CMD_SET_CRITICAL_TEMP: return "IWN_CMD_SET_CRITICAL_TEMP"; case IWN_CMD_SET_SENSITIVITY: return "IWN_CMD_SET_SENSITIVITY"; case IWN_CMD_PHY_CALIB: return "IWN_CMD_PHY_CALIB"; } return "UNKNOWN INTR NOTIF/CMD"; } #endif /* IWN_DEBUG */ static device_method_t iwn_methods[] = { /* Device interface */ DEVMETHOD(device_probe, iwn_pci_probe), DEVMETHOD(device_attach, iwn_pci_attach), DEVMETHOD(device_detach, iwn_pci_detach), DEVMETHOD(device_shutdown, iwn_pci_shutdown), DEVMETHOD(device_suspend, iwn_pci_suspend), DEVMETHOD(device_resume, iwn_pci_resume), { 0, 0 } }; static driver_t iwn_driver = { "iwn", iwn_methods, sizeof (struct iwn_softc) }; static devclass_t iwn_devclass; DRIVER_MODULE(iwn, pci, iwn_driver, iwn_devclass, NULL, NULL); MODULE_DEPEND(iwn, pci, 1, 1, 1); MODULE_DEPEND(iwn, firmware, 1, 1, 1); MODULE_DEPEND(iwn, wlan, 1, 1, 1); MODULE_DEPEND(iwn, wlan_amrr, 1, 1, 1);
DirtyDerv/Superalgos
Projects/Foundations/UI/Spaces/Floating-Space/CircularMenuItem.js
<filename>Projects/Foundations/UI/Spaces/Floating-Space/CircularMenuItem.js function newCircularMenuItem() { const MODULE_NAME = 'Circular Menu Iem' let thisObject = { type: undefined, isDeployed: undefined, askConfirmation: undefined, confirmationLabel: undefined, iconOn: undefined, iconOff: undefined, iconProject: undefined, icons: undefined, currentIcon: undefined, disableIfPropertyIsDefined: undefined, propertyToCheckFor: undefined, action: undefined, actionProject: undefined, actionFunction: undefined, actionStatus: undefined, label: undefined, workingLabel: undefined, workDoneLabel: undefined, workFailedLabel: undefined, secondaryAction: undefined, secondaryLabel: undefined, secondaryWorkingLabel: undefined, secondaryWorkDoneLabel: undefined, secondaryWorkFailedLabel: undefined, secondaryIcon: undefined, booleanProperty: undefined, nextAction: undefined, visible: false, iconPathOn: undefined, iconPathOff: undefined, rawRadius: undefined, targetRadius: undefined, currentRadius: undefined, angle: undefined, container: undefined, payload: undefined, relatedUiObject: undefined, relatedUiObjectProject: undefined, dontShowAtFullscreen: undefined, isEnabled: true, shorcutNumber: undefined, internalClick: internalClick, physics: physics, invisiblePhysics: invisiblePhysics, drawBackground: drawBackground, drawForeground: drawForeground, getContainer: getContainer, finalize: finalize, initialize: initialize } thisObject.container = newContainer() thisObject.container.initialize(MODULE_NAME) thisObject.container.isClickeable = true thisObject.container.isDraggeable = false thisObject.container.detectMouseOver = true thisObject.container.frame.radius = 0 thisObject.container.frame.position.x = 0 thisObject.container.frame.position.y = 0 thisObject.container.frame.width = 0 thisObject.container.frame.height = 0 let isMouseOver = false let selfMouseOverEventSubscriptionId let selfMouseClickEventSubscriptionId let selfMouseNotOverEventSubscriptionId let labelToPrint = '' let defaultBackgroudColor = UI_COLOR.BLACK let backgroundColorToUse = UI_COLOR.RED let temporaryStatus = 0 let temporaryStatusCounter = 0 const STATUS_NO_ACTION_TAKEN_YET = 0 const STATUS_PRIMARY_ACTION_WORKING = -1 const STATUS_SECONDARY_ACTION_WORKING = -2 const STATUS_PRIMARY_WORK_DONE = -3 const STATUS_PRIMARY_WORK_FAILED = -4 const STATUS_WAITING_CONFIRMATION = -5 const STATUS_SECONDARY_WORK_DONE = -6 const STATUS_SECONDARY_WORK_FAILED = -7 return thisObject function finalize() { thisObject.container.eventHandler.stopListening(selfMouseOverEventSubscriptionId) thisObject.container.eventHandler.stopListening(selfMouseClickEventSubscriptionId) thisObject.container.eventHandler.stopListening(selfMouseNotOverEventSubscriptionId) thisObject.container.finalize() thisObject.container = undefined thisObject.iconOn = undefined thisObject.iconOff = undefined thisObject.iconProject = undefined thisObject.icons = undefined thisObject.currentIcon = undefined thisObject.payload = undefined thisObject.actionFunction = undefined thisObject.actionStatus = undefined thisObject.disableIfPropertyIsDefined = undefined thisObject.propertyToCheckFor = undefined } function initialize(pPayload) { thisObject.payload = pPayload iconPhysics() if (thisObject.icon === undefined) { console.log('[ERROR] newCircularMenuItem -> initialize -> err = Icon not found, Action: "' + thisObject.action + '", relatedUiObject: "' + thisObject.relatedUiObject + '", label: "' + thisObject.label + '"') } selfMouseOverEventSubscriptionId = thisObject.container.eventHandler.listenToEvent('onMouseOver', onMouseOver) selfMouseClickEventSubscriptionId = thisObject.container.eventHandler.listenToEvent('onMouseClick', onMouseClick) selfMouseNotOverEventSubscriptionId = thisObject.container.eventHandler.listenToEvent('onMouseNotOver', onMouseNotOver) containerPhysics() if (thisObject.booleanProperty !== undefined) { let config = JSON.parse(thisObject.payload.node.config) if (config[thisObject.booleanProperty] === true) { thisObject.nextAction = thisObject.secondaryAction setStatus(thisObject.secondaryLabel, defaultBackgroudColor, undefined, STATUS_PRIMARY_WORK_DONE) } else { thisObject.nextAction = thisObject.action } } else { thisObject.nextAction = thisObject.action } } function getContainer(point) { if (thisObject.dontShowAtFullscreen === true && AT_FULL_SCREEN_MODE === true) { return } let container if (thisObject.isDeployed === true) { if (thisObject.container.frame.isThisPointHere(point, true, false) === true) { return thisObject.container } else { return undefined } } } function invisiblePhysics() { temporaryStatusPhysics() } function temporaryStatusPhysics() { /* Temporary Status impacts on the label to use and the background of that label */ if (temporaryStatusCounter > 0) { temporaryStatusCounter-- } if (temporaryStatusCounter === 0) { temporaryStatus = STATUS_NO_ACTION_TAKEN_YET labelToPrint = thisObject.label backgroundColorToUse = defaultBackgroudColor thisObject.nextAction = thisObject.action } } function physics() { if (thisObject.dontShowAtFullscreen === true && AT_FULL_SCREEN_MODE === true) { return } positionPhysics() temporaryStatusPhysics() disablePhysics() iconPhysics() backgroundColorPhysics() containerPhysics() } function positionPhysics() { let INCREASE_STEP = 2 if (Math.abs(thisObject.currentRadius - thisObject.targetRadius) >= INCREASE_STEP) { if (thisObject.currentRadius < thisObject.targetRadius) { thisObject.currentRadius = thisObject.currentRadius + INCREASE_STEP } else { thisObject.currentRadius = thisObject.currentRadius - INCREASE_STEP } } let radiusGrowthFactor if (thisObject.type === 'Icon Only') { switch (thisObject.ring) { case 1: { radiusGrowthFactor = 5.5 break } case 2: { radiusGrowthFactor = 4.0 break } case 3: { radiusGrowthFactor = 3.0 break } case 4: { radiusGrowthFactor = 2.0 break } } } else { radiusGrowthFactor = 3.2 } radiusGrowthFactor = radiusGrowthFactor * UI.projects.foundations.spaces.floatingSpace.settings.node.menuItem.radiusPercentage / 100 if (thisObject.label !== undefined) { thisObject.container.frame.position.x = thisObject.payload.floatingObject.targetRadius * radiusGrowthFactor / 7 * Math.cos(toRadians(thisObject.angle)) * 1.5 - thisObject.currentRadius * 1.5 - thisObject.payload.floatingObject.targetRadius / 4 thisObject.container.frame.position.y = thisObject.payload.floatingObject.targetRadius * radiusGrowthFactor / 7 * Math.sin(toRadians(thisObject.angle)) * 2 - thisObject.container.frame.height / 2 } else { thisObject.container.frame.position.x = thisObject.payload.floatingObject.targetRadius * radiusGrowthFactor / 7 * Math.cos(toRadians(thisObject.angle)) - thisObject.currentRadius * 1.5 thisObject.container.frame.position.y = thisObject.payload.floatingObject.targetRadius * radiusGrowthFactor / 7 * Math.sin(toRadians(thisObject.angle)) - thisObject.container.frame.height / 2 } } function disablePhysics() { /* Here we will check if we need to monitor a property that influences the status of the Menu Item. */ if (thisObject.disableIfPropertyIsDefined === true) { if (thisObject.payload.node[thisObject.propertyToCheckFor] === undefined) { /* This menu item is enabled. */ thisObject.isEnabled = true } else { /* This menu item is disabled. */ thisObject.isEnabled = false } } } function containerPhysics() { if (thisObject.type === 'Icon & Text') { thisObject.container.frame.width = 220 * UI.projects.foundations.spaces.floatingSpace.settings.node.menuItem.widthPercentage / 100 } else { thisObject.container.frame.width = 50 * UI.projects.foundations.spaces.floatingSpace.settings.node.menuItem.widthPercentage / 100 } thisObject.container.frame.height = 40 * UI.projects.foundations.spaces.floatingSpace.settings.node.menuItem.heightPercentage / 100 } function backgroundColorPhysics() { defaultBackgroudColor = UI.projects.foundations.spaces.floatingSpace.style.node.menuItem.backgroundColor } function iconPhysics() { if ( ( temporaryStatus === STATUS_PRIMARY_WORK_DONE || temporaryStatus === STATUS_SECONDARY_ACTION_WORKING || temporaryStatus === STATUS_SECONDARY_WORK_DONE || temporaryStatus === STATUS_SECONDARY_WORK_FAILED ) && thisObject.secondaryAction !== undefined ) { if (thisObject.iconProject !== undefined) { thisObject.iconOn = UI.projects.foundations.spaces.designSpace.getIconByProjectAndName(thisObject.iconProject, thisObject.secondaryIcon) thisObject.iconOff = UI.projects.foundations.spaces.designSpace.getIconByProjectAndName(thisObject.iconProject, thisObject.secondaryIcon) } else { thisObject.iconOn = UI.projects.foundations.spaces.designSpace.getIconByProjectAndName('Foundations', thisObject.secondaryIcon) thisObject.iconOff = UI.projects.foundations.spaces.designSpace.getIconByProjectAndName('Foundations', thisObject.secondaryIcon) } } else { /* TODO : This code needs to be cleaned and reorganized. It is not clear how a menu item icon is going to be selected. */ if (thisObject.relatedUiObject !== undefined && thisObject.iconProject !== undefined) { thisObject.iconOn = UI.projects.foundations.spaces.designSpace.getIconByProjectAndType(thisObject.iconProject, thisObject.relatedUiObject) thisObject.iconOff = UI.projects.foundations.spaces.designSpace.getIconByProjectAndType(thisObject.iconProject, thisObject.relatedUiObject) } else if (thisObject.relatedUiObject !== undefined && thisObject.iconProject === undefined) { if (thisObject.relatedUiObjectProject !== undefined) { thisObject.iconOn = UI.projects.foundations.spaces.designSpace.getIconByProjectAndType(thisObject.relatedUiObjectProject, thisObject.relatedUiObject) thisObject.iconOff = UI.projects.foundations.spaces.designSpace.getIconByProjectAndType(thisObject.relatedUiObjectProject, thisObject.relatedUiObject) } else { thisObject.iconOn = UI.projects.foundations.spaces.designSpace.getIconByProjectAndType(thisObject.payload.node.project, thisObject.relatedUiObject) thisObject.iconOff = UI.projects.foundations.spaces.designSpace.getIconByProjectAndType(thisObject.payload.node.project, thisObject.relatedUiObject) } } else { if (thisObject.iconPathOn !== undefined && thisObject.iconPathOff !== undefined && thisObject.iconProject !== undefined) { thisObject.iconOn = UI.projects.foundations.spaces.designSpace.getIconByProjectAndName(thisObject.iconProject, thisObject.iconPathOn) thisObject.iconOff = UI.projects.foundations.spaces.designSpace.getIconByProjectAndName(thisObject.iconProject, thisObject.iconPathOff) } else if (thisObject.iconPathOn !== undefined && thisObject.iconPathOff !== undefined && thisObject.iconProject === undefined) { thisObject.iconOn = UI.projects.foundations.spaces.designSpace.getIconByProjectAndName('Foundations', thisObject.iconPathOn) thisObject.iconOff = UI.projects.foundations.spaces.designSpace.getIconByProjectAndName('Foundations', thisObject.iconPathOff) } else { thisObject.iconOn = UI.projects.foundations.spaces.designSpace.getIconByProjectAndName('Foundations', thisObject.icons[thisObject.actionStatus()]) thisObject.iconOff = UI.projects.foundations.spaces.designSpace.getIconByProjectAndName('Foundations', thisObject.icons[thisObject.actionStatus()]) } } } /* Current Status might be linked to some other object status */ if (thisObject.actionStatus !== undefined) { thisObject.currentStatus = thisObject.actionStatus() } /* Current Status sets the icon to be used */ if (thisObject.currentStatus === true) { thisObject.icon = thisObject.iconOn } else { thisObject.icon = thisObject.iconOff } } function onMouseOver(point) { if (thisObject.container.frame.isThisPointHere(point, true, false) === true) { let text = thisObject.action if (thisObject.payload.uiObject.payload.referenceParent !== undefined && thisObject.action === 'Reference Detach') { text = text + ' -> [Existing Reference] Type : [' + thisObject.payload.uiObject.payload.referenceParent.type + '] , Name : [' + thisObject.payload.uiObject.payload.referenceParent.name + ']' } thisObject.payload.uiObject.setInfoMessage(text) isMouseOver = true } else { isMouseOver = false } MENU_ITEM_ON_FOCUS = thisObject } function onMouseNotOver(point) { isMouseOver = false MENU_ITEM_ON_FOCUS = undefined } function internalClick() { if (thisObject.payload === undefined) { return } if (thisObject.shorcutNumber !== undefined) { let label = thisObject.payload.node.name + ' ' + labelToPrint UI.projects.foundations.spaces.cockpitSpace.setStatus(label, 4, UI.projects.foundations.spaces.cockpitSpace.statusTypes.ALL_GOOD) } onMouseClick() } function onMouseClick() { if (thisObject.isEnabled === false) { return } if (thisObject.askConfirmation !== true) { /* No confirmation is needed */ if (temporaryStatus === STATUS_NO_ACTION_TAKEN_YET || temporaryStatus === STATUS_PRIMARY_WORK_DONE) { executeAction() } // Any click out of those states is ignored } else { /* Confirmation is needed */ /* The first click ask for confirmation. */ if (temporaryStatus === STATUS_NO_ACTION_TAKEN_YET) { setStatus(thisObject.confirmationLabel, UI_COLOR.GOLDEN_ORANGE, 250, STATUS_WAITING_CONFIRMATION) return } /* A Click during confirmation executes the pre-defined action. */ if (temporaryStatus === STATUS_WAITING_CONFIRMATION || temporaryStatus === STATUS_PRIMARY_WORK_DONE) { executeAction() if (thisObject.workDoneLabel !== undefined) { setStatus(thisObject.workDoneLabel, UI_COLOR.PATINATED_TURQUOISE, 5, STATUS_SECONDARY_WORK_DONE) } else { setStatus('Done', UI_COLOR.PATINATED_TURQUOISE, 5, STATUS_SECONDARY_WORK_DONE) } return } } function executeAction() { if (temporaryStatus === STATUS_NO_ACTION_TAKEN_YET || temporaryStatus === STATUS_WAITING_CONFIRMATION) { /* We need to execute the main Action */ /* If there is a working label defined, we use it here. */ if (thisObject.workingLabel !== undefined) { setStatus(thisObject.workingLabel, UI_COLOR.GREY, undefined, STATUS_PRIMARY_ACTION_WORKING) // Status will not expire, will only change with a callback. Mouse Clicks will be ignored. } /* Execute the action and wait for callbacks to update our status. */ let relatedNodeProject = thisObject.actionProject if (thisObject.relatedUiObjectProject !== undefined) { relatedNodeProject = thisObject.relatedUiObjectProject } thisObject.actionFunction( { node: thisObject.payload.node, name: thisObject.action, project: thisObject.actionProject, relatedNodeType: thisObject.relatedUiObject, relatedNodeProject: relatedNodeProject, callBackFunction: onPrimaryCallBack } ) return } if (temporaryStatus === STATUS_PRIMARY_WORK_DONE && thisObject.secondaryAction !== undefined) { /* We need to execute the secondary action. */ if (thisObject.secondaryWorkingLabel !== undefined) { setStatus(thisObject.secondaryWorkingLabel, UI_COLOR.GREY, undefined, STATUS_SECONDARY_ACTION_WORKING) // Status will not expire, will only change with a callback. Mouse Clicks will be ignored. } /* Execute the action and wait for callbacks to update our status. */ thisObject.actionFunction({ node: thisObject.payload.node, name: thisObject.secondaryAction, project: thisObject.actionProject, relatedNodeType: thisObject.relatedUiObject, callBackFunction: onSecondaryCallBack }) return } function onPrimaryCallBack(err, event) { /* While the primary action is being executed some event might have happen. Following we process the ones we can */ if (event !== undefined) { if (event.type === 'Secondary Action Already Executed') { setStatus(thisObject.secondaryWorkDoneLabel, UI_COLOR.PATINATED_TURQUOISE, 5, STATUS_SECONDARY_WORK_DONE) return } } /* If there is a secondary action we will act different that if there is not */ if (thisObject.secondaryAction === undefined) { // This means there are no more possible actions. if (err.result === GLOBAL.DEFAULT_OK_RESPONSE.result) { if (thisObject.workDoneLabel !== undefined) { setStatus(thisObject.workDoneLabel, UI_COLOR.PATINATED_TURQUOISE, 5, STATUS_PRIMARY_WORK_DONE) } } else { if (thisObject.workFailedLabel != undefined) { setStatus(thisObject.workFailedLabel, UI_COLOR.TITANIUM_YELLOW, 5, STATUS_PRIMARY_WORK_FAILED) } } } else { if (err.result === GLOBAL.DEFAULT_OK_RESPONSE.result) { if (thisObject.workDoneLabel !== undefined) { thisObject.nextAction = thisObject.secondaryAction setStatus(thisObject.secondaryLabel, defaultBackgroudColor, undefined, STATUS_PRIMARY_WORK_DONE) } } else { if (thisObject.workFailedLabel != undefined) { setStatus(thisObject.workFailedLabel, UI_COLOR.TITANIUM_YELLOW, 5, STATUS_PRIMARY_WORK_FAILED) } } } } function onSecondaryCallBack(err) { if (err.result === GLOBAL.DEFAULT_OK_RESPONSE.result) { if (thisObject.secondaryWorkDoneLabel !== undefined) { setStatus(thisObject.secondaryWorkDoneLabel, UI_COLOR.PATINATED_TURQUOISE, 5, STATUS_SECONDARY_WORK_DONE) } } else { if (thisObject.secondaryWorkFailedLabel != undefined) { setStatus(thisObject.secondaryWorkFailedLabel, UI_COLOR.TITANIUM_YELLOW, 5, STATUS_SECONDARY_WORK_FAILED) } } } } } function setStatus(text, backgroundColor, waitingCycles, newStatus) { labelToPrint = text backgroundColorToUse = backgroundColor temporaryStatus = newStatus temporaryStatusCounter = newStatus // This will often put this into negatives numbers, which will disable the counting back and automatic resetting. if (waitingCycles !== undefined) { // This will override the often negative value with a positive one that will tend to zero onto the default state. temporaryStatusCounter = waitingCycles } } function drawBackground() { if (thisObject.dontShowAtFullscreen === true && AT_FULL_SCREEN_MODE === true) { return } if (thisObject.container.frame.position.x > 0 && thisObject.isDeployed === true && thisObject.currentRadius >= thisObject.targetRadius) { if (thisObject.type === 'Icon & Text') { let backgroundColor = backgroundColorToUse if (thisObject.isEnabled === false) { backgroundColor = UI_COLOR.GREY } let params = { cornerRadius: 5, lineWidth: 0.1, container: thisObject.container, borderColor: backgroundColor, backgroundColor: backgroundColor, castShadow: false, xOffset: 60 } if (isMouseOver === true) { params.opacity = 1 } else { params.opacity = 0.8 } UI.projects.foundations.utilities.drawPrint.roundedCornersBackground(params) } } } function drawForeground() { if (thisObject.dontShowAtFullscreen === true && AT_FULL_SCREEN_MODE === true) { return } let menuPosition = { x: thisObject.currentRadius * 1.5, y: thisObject.container.frame.height / 2 } menuPosition = thisObject.container.frame.frameThisPoint(menuPosition) /* Menu Item */ let iconSize if (isMouseOver === true) { iconSize = UI.projects.foundations.spaces.floatingSpace.style.node.menuItem.imageSize * 150 / 100 } else { iconSize = UI.projects.foundations.spaces.floatingSpace.style.node.menuItem.imageSize } if (thisObject.icon === undefined) { thisObject.icon = UI.projects.foundations.spaces.designSpace.getIconByProjectAndName('Foundations', 'missing-image') } if (thisObject.icon !== undefined) { if (thisObject.icon.canDrawIcon === true && thisObject.currentRadius > 1 && thisObject.isDeployed === true) { browserCanvasContext.drawImage(thisObject.icon, menuPosition.x - iconSize, menuPosition.y - iconSize, iconSize * 2, iconSize * 2) } } /* Menu Label */ if (thisObject.type === 'Icon & Text') { label = labelToPrint if (thisObject.shorcutNumber !== undefined) { label = '' + thisObject.shorcutNumber + '- ' + labelToPrint } let labelPoint let fontSize = UI.projects.foundations.spaces.floatingSpace.style.node.menuItem.fontSize browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY if (thisObject.currentRadius >= thisObject.targetRadius) { labelPoint = { x: menuPosition.x + thisObject.currentRadius + 25, y: menuPosition.y + fontSize * FONT_ASPECT_RATIO } browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY browserCanvasContext.fillStyle = 'rgba(' + UI.projects.foundations.spaces.floatingSpace.style.node.menuItem.fontColor + ', 1)' browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y) } } } }
pwnall/pwnalytics_js
spec/javascripts/post_spec.js
describe("Pwnalytics event posting", function() { beforeEach(function () { Pwnalytics.pendingEvents = 42; }); afterEach(function () { Pwnalytics.pendingEvents = 0; }); describe("eventUrl", function() { var url = null; var unicodeUrl = null; beforeEach(function() { url = Pwnalytics.eventUrl({s1: 'sval1', s2: 'sval&2'}, 'evnm', {ev1: 'evalue1', ev2: 'evalue?2'}); unicodeUrl = Pwnalytics.eventUrl({}, '', {u: '\u4F60\u597D'}); }); it("should include the event name", function() { expect(url).toContain('__=evnm'); }); it("should include the session data", function() { expect(url).toContain('__s1=sval1&__s2=sval%262'); }); it("should include the event data", function() { expect(url).toContain('ev1=evalue1&ev2=evalue%3F2'); }); it("should start with the base URL", function() { expect(url).toMatch(/^bin\/p.gif\?/); }); it("should use UTF-8 to encode unicode data", function() { expect(unicodeUrl).toMatch(/u=%E4%BD%A0%E5%A5%BD/) }) }); describe("image", function() { var fakeImg = null; beforeEach(function() { spyOn(window, "Image").andCallFake(function() { fakeImg = {}; return fakeImg; }); Pwnalytics.image("http://localhost/invalid"); }); it("should construct an Image", function() { expect(Image).toHaveBeenCalledWith(); }); it("should set the image's src to the given source", function() { expect(fakeImg.src).toBe("http://localhost/invalid"); }); it("should set the image's error handlers to same function", function() { expect(fakeImg.onerror).not.toBe(null); expect(fakeImg.onerror).toBe(fakeImg.onabort); }); it("should set the image's load handler correctly", function () { fakeImg.onload(); expect(Pwnalytics.pendingEvents).toBe(41); }); describe("onerror", function() { var delayed = null; var timeout = null; beforeEach(function() { spyOn(window, "setTimeout").andCallFake(function(fn, ms) { delayed = fn; timeout = ms; }); fakeImg.onerror.call({}); spyOn(Pwnalytics, "image"); delayed(); }); it("should delay for 60 seconds", function() { expect(timeout).toBe(60 * 1000); }); it("should call image recursively in the delay", function() { expect(Pwnalytics.image). toHaveBeenCalledWith("http://localhost/invalid"); }); }); }); describe("changePendingEvents", function() { it("should increase pendingEvents when given +1", function() { Pwnalytics.changePendingEvents(1); expect(Pwnalytics.pendingEvents).toBe(43); }) it("should decrease pendingEvents when given -1", function() { Pwnalytics.changePendingEvents(-1); expect(Pwnalytics.pendingEvents).toBe(41); }) }); describe("post", function() { var goldDate = new Date(1337); var goldScreenInfo = '1.3.3.7'; var eventData = {occurred: 'today'}; beforeEach(function() { spyOn(window, 'Date').andReturn(goldDate); spyOn(Pwnalytics, 'screenInfoString').andReturn(goldScreenInfo); spyOn(Pwnalytics, 'eventUrl').andReturn('http://event.url.gif'); spyOn(Pwnalytics, 'image'); Pwnalytics.post('awesomeness', eventData); }); it("should set the session time", function() { expect(Pwnalytics.session.time).toBe(1337); }); it("should set the session screen metrics", function() { expect(Pwnalytics.session.px).toBe(goldScreenInfo); }); it("should generate an image URL", function() { expect(Pwnalytics.eventUrl).toHaveBeenCalledWith( Pwnalytics.session, 'awesomeness', eventData); }); it("should inject an image", function() { expect(Pwnalytics.image).toHaveBeenCalledWith('http://event.url.gif'); }); it("should increase the number of pending events", function () { expect(Pwnalytics.pendingEvents).toBe(43); }); }); });
reactivego/rx
test/Single/doc.go
/* Single enforces that the observable sends exactly one data item and then completes. If the observable sends no data before completing or sends more than 1 item before completing, this is reported as an error to the observer. */ package Single
shmoop207/rocket-engine
test/mock/config/modules/test2/testModule.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Test2Module = void 0; const tslib_1 = require("tslib"); const index_1 = require("../../../../../index"); const test_1 = require("./src/test"); let Test2Module = class Test2Module extends index_1.Module { }; Test2Module = tslib_1.__decorate([ index_1.module({ exports: [test_1.Test2] }) ], Test2Module); exports.Test2Module = Test2Module; //# sourceMappingURL=testModule.js.map
playbar/TeamTalk
ios/TeamTalk/ViewController/My/MTTBubbleShowViewControll.h
// // BubbleShowViewControll.h // TeamTalk // // Created by scorpio on 15/7/3. // Copyright (c) 2015年 MoguIM. All rights reserved. // #import "MTTBaseViewController.h" @interface MTTBubbleShowViewControll : MTTBaseViewController<UICollectionViewDataSource,UICollectionViewDelegate> @property (nonatomic, strong) UICollectionView *collectionView; @property (nonatomic, strong) NSDictionary *bubbles; @property (nonatomic, strong) NSMutableArray *bubbleKeys; @property (nonatomic, strong) UIView *headerView; @property (nonatomic, strong) UILabel *leftBottomLine; @property (nonatomic, strong) UILabel *rightBottomLine; @property (nonatomic, strong) UILabel *leftLabel; @property (nonatomic, strong) UILabel *rightLabel; @property (nonatomic) BOOL isMine; @end
rchavezriosjr/SkyLineWebPage
skyline/components/com_roksprocket/layouts/quotes/assets/js/quotes-speeds.js
/*! * @version $Id: quotes-speeds.js 10889 2013-05-30 07:48:35Z btowles $ * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2019 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only */ ((function(){ var AnimationsSpeed = { fade: { duration: '250ms' }, fadeDelay: { duration: '250ms', delay: 75 }, slide: { duration: '250ms' }, flyIn: { duration: '500ms', delay: 90 }, fallDown: { duration: '250ms', delay: 50 }, floatUp: { duration: '250ms', delay: 50 }, scaleOut: { duration: '250ms', delay: 100 }, scaleIn: { duration: '250ms', delay: 100 } }; this.RokSprocket.Quotes.prototype.AnimationsSpeed = Object.merge({}, this.RokSprocket.Quotes.prototype.AnimationsSpeed, AnimationsSpeed); })());
Grosskopf/openoffice
main/chart2/source/controller/accessibility/ChartElementFactory.cxx
<gh_stars>100-1000 /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "ChartElementFactory.hxx" #include "ObjectIdentifier.hxx" #include "AccessibleChartElement.hxx" namespace chart { AccessibleBase* ChartElementFactory::CreateChartElement( const AccessibleElementInfo& rAccInfo ) { ObjectIdentifier aOID( rAccInfo.m_aOID ); ObjectType eType( aOID.getObjectType() ); switch( eType ) { case OBJECTTYPE_DATA_POINT: case OBJECTTYPE_LEGEND_ENTRY: return new AccessibleChartElement( rAccInfo, false, false ); case OBJECTTYPE_PAGE: case OBJECTTYPE_TITLE: case OBJECTTYPE_LEGEND: case OBJECTTYPE_DIAGRAM: case OBJECTTYPE_DIAGRAM_WALL: case OBJECTTYPE_DIAGRAM_FLOOR: case OBJECTTYPE_AXIS: case OBJECTTYPE_AXIS_UNITLABEL: case OBJECTTYPE_GRID: case OBJECTTYPE_SUBGRID: case OBJECTTYPE_DATA_SERIES: case OBJECTTYPE_DATA_LABELS: case OBJECTTYPE_DATA_LABEL: case OBJECTTYPE_DATA_ERRORS: case OBJECTTYPE_DATA_ERRORS_X: case OBJECTTYPE_DATA_ERRORS_Y: case OBJECTTYPE_DATA_ERRORS_Z: case OBJECTTYPE_DATA_CURVE: // e.g. a statistical method printed as line case OBJECTTYPE_DATA_AVERAGE_LINE: case OBJECTTYPE_DATA_STOCK_RANGE: case OBJECTTYPE_DATA_STOCK_LOSS: case OBJECTTYPE_DATA_STOCK_GAIN: case OBJECTTYPE_DATA_CURVE_EQUATION: return new AccessibleChartElement( rAccInfo, true, false ); case OBJECTTYPE_UNKNOWN: break; default: break; } return 0; /* sal_uInt16 nObjId = rId.GetObjectId(); switch( nObjId ) { case CHOBJID_LEGEND: return new AccLegend( pParent ); case AccLegendEntry::ObjectId: return new AccLegendEntry( pParent, rId.GetIndex1() ); case CHOBJID_TITLE_MAIN: return new AccTitle( pParent, Title::MAIN ); case CHOBJID_TITLE_SUB: return new AccTitle( pParent, Title::SUB ); case CHOBJID_DIAGRAM_TITLE_X_AXIS: return new AccTitle( pParent, Title::X_AXIS ); case CHOBJID_DIAGRAM_TITLE_Y_AXIS: return new AccTitle( pParent, Title::Y_AXIS ); case CHOBJID_DIAGRAM_TITLE_Z_AXIS: return new AccTitle( pParent, Title::Z_AXIS ); case CHOBJID_DIAGRAM: return new AccDiagram( pParent ); // series case CHOBJID_DIAGRAM_ROWGROUP: return new AccDataSeries( pParent, rId.GetIndex1() ); // data points case CHOBJID_DIAGRAM_DATA: return new AccDataPoint( pParent, rId.GetIndex1(), rId.GetIndex2() ); case Axis::X_AXIS: case Axis::Y_AXIS: case Axis::Z_AXIS: case Axis::SEC_X_AXIS: case Axis::SEC_Y_AXIS: return new AccAxis( pParent, static_cast< Axis::AxisType >( nObjId ) ); case Grid::X_MAJOR: case Grid::Y_MAJOR: case Grid::Z_MAJOR: case Grid::X_MINOR: case Grid::Y_MINOR: case Grid::Z_MINOR: return new AccGrid( pParent, static_cast< AccGrid::GridType >( nObjId ) ); case AccStatisticsObject::MEAN_VAL_LINE: case AccStatisticsObject::ERROR_BARS: case AccStatisticsObject::REGRESSION: return new AccStatisticsObject( pParent, static_cast< AccStatisticsObject::StatisticsObjectType >( nObjId ), rId.GetIndex1() ); case CHOBJID_DIAGRAM_WALL: return new AccWall( pParent ); case CHOBJID_DIAGRAM_FLOOR: return new AccFloor( pParent ); case CHOBJID_DIAGRAM_AREA: return new AccArea( pParent ); } */ } } // namespace chart
gauravshankarcan/datatrucker.io
datatrucker_api/app/services/login/handler-local.js
/* * Copyright 2021 Datatrucker.io Inc , Ontario , Canada * * 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. */ async function login(request, reply) { const response = { status: false }; const userdata = await this.knex.from('users').select('username', 'password', 'salt', 'enabled').where({ username: request.body.username, enabled: true }); if (userdata.length > 0) { const newhash = await this.gethash(request.body.username + request.body.password, userdata[0].salt); if (newhash.passwordHash === userdata[0].password) { const levels = await this.knex.select('groups.level as level').from('users').innerJoin('user_mapping', 'user_mapping.userid', 'users.id').innerJoin('groups', 'groups.id', 'user_mapping.groupid') .where({ 'users.username': request.body.username, 'groups.tenantname': request.body.tenant, 'groups.type': 'local', 'users.enabled': true, 'groups.enabled': true }); const payload = { usr: request.body.username, ten: request.body.tenant, sid: this.genRandomString(4) }; if (levels.length > 0) { payload.wrt = 0; Object.keys(levels).forEach((k) => { if (levels[k].level === 'Tenant_Author') { payload.wrt = 1; } }); if (payload.wrt == 0 && request.body.browser) { response.status = false request.log.error("UI requesting read only token") reply.code(401).send(response); } else { const token = this.jwt.sign({payload}); response.status = true; response.username = request.body.username; response.token = token; if (request.body.browser) { reply.setCookie('DataTrucker', token, { httpOnly: true, path: '/', sameSite: true }); } // since login requests dont identify jwt on request , needed as a log identifier request.tenant = payload.ten; request.username = payload.usr; request.sid = payload.sid; reply.code(200).send(response); } } else { this.log.error('Tenant Mapping not found'); reply.code(401).send(response); } } else { this.log.error(`Invalid password attempt: ${request.body.username}`); reply.code(401).send(response); } } else { this.log.error(`Username does not exist: ${request.body.username}`); reply.code(401).send(response); } } async function logout(request, reply) { reply.setCookie('DataTrucker', 'tokenRemoved', { httpOnly: true, path: '/', sameSite: true }); reply.code(200).send({status: true}); } exports.login = login;
antonefremov/jitsu
server/events/js_preprocessor.go
<reponame>antonefremov/jitsu package events import ( "github.com/jitsucom/jitsu/server/jsonutils" "net/http" ) type Preprocessor interface { Preprocess(event Event, r *http.Request) } //JsPreprocessor preprocess client integration events type JsPreprocessor struct { userAgentJSONPath *jsonutils.JSONPath } func NewJsPreprocessor() Preprocessor { return &JsPreprocessor{userAgentJSONPath: jsonutils.NewJSONPath(EventnKey + "/user_agent")} } //Preprocess set user-agent from request header func (jp *JsPreprocessor) Preprocess(event Event, r *http.Request) { clientUserAgent := r.Header.Get("user-agent") if clientUserAgent != "" { jp.userAgentJSONPath.Set(event, clientUserAgent) } }
busunkim96/dbnd
modules/dbnd/src/dbnd/tasks/doctor/system_dbnd.py
<filename>modules/dbnd/src/dbnd/tasks/doctor/system_dbnd.py import logging import os import random from dbnd import log_metric, task from dbnd._core.current import try_get_databand_context from dbnd.tasks.doctor.doctor_report_builder import DoctorStatusReportBuilder logger = logging.getLogger(__name__) @task def dbnd_status(): report = DoctorStatusReportBuilder("Databand Status") report.log("env.DBND_HOME", os.environ.get("DBND_HOME")) dc = try_get_databand_context() report.log("DatabandContext", dc) if dc: report.log("initialized", dc) # calling metrics. log_metric("metric_check", "OK") log_metric("metric_random_value", random.random()) return report.get_status_str()
carlamissiona/prototype
node_modules/vue-bulma-jump/src/index.js
<reponame>carlamissiona/prototype export BackToTop from './BackToTop' export default from './Jump'
baines/engine
include/renderer/texture.h
<reponame>baines/engine #ifndef TEXTURE_H_ #define TEXTURE_H_ #include "common.h" #include "util.h" #include "gl_context.h" #include <tuple> struct RenderState; struct Texture { virtual GLenum getType(void) const = 0; virtual bool isValid(void) const = 0; virtual std::tuple<int, int> getSize() const = 0; virtual bool bind(size_t tex_unit, RenderState& rs) const = 0; virtual bool setSwizzle(const std::array<GLint, 4>& swizzle) = 0; virtual ~Texture(){} }; struct Texture2D : public Texture, public GLObject { Texture2D(); Texture2D(MemBlock mem); Texture2D(GLenum fmt, GLenum int_fmt, int w, int h, const void* data); Texture2D& operator=(const Texture2D&) = delete; Texture2D& operator=(Texture2D&&); GLenum getType(void) const; bool isValid(void) const; std::tuple<int, int> getSize() const; bool bind(size_t tex_unit, RenderState& rs) const; bool setSwizzle(const std::array<GLint, 4>& swizzle); virtual void onGLContextRecreate(); virtual ~Texture2D(); private: GLuint id; int w, h; }; #endif
zchee/vald
internal/net/grpc/status/status.go
<reponame>zchee/vald // // Copyright (C) 2019-2021 vdaas.org vald team <<EMAIL>> // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Package status provides statuses and errors returned by grpc handler functions package status import ( "context" "os" "github.com/vdaas/vald/internal/errors" "github.com/vdaas/vald/internal/info" "github.com/vdaas/vald/internal/log" "github.com/vdaas/vald/internal/net/grpc/codes" "github.com/vdaas/vald/internal/net/grpc/errdetails" "github.com/vdaas/vald/internal/net/grpc/proto" "github.com/vdaas/vald/internal/net/grpc/types" spb "google.golang.org/genproto/googleapis/rpc/status" "google.golang.org/grpc/status" ) type ( Status = status.Status Code = codes.Code ) func New(c codes.Code, msg string) *Status { return status.New(c, msg) } func newStatus(code codes.Code, msg string, err error, details ...interface{}) (st *Status) { st = New(code, msg) return withDetails(st, err, details...) } func WrapWithCanceled(msg string, err error, details ...interface{}) error { return newStatus(codes.Canceled, msg, err, details...).Err() } func WrapWithUnknown(msg string, err error, details ...interface{}) error { return newStatus(codes.Unknown, msg, err, details...).Err() } func WrapWithInvalidArgument(msg string, err error, details ...interface{}) error { return newStatus(codes.InvalidArgument, msg, err, details...).Err() } func WrapWithDeadlineExceeded(msg string, err error, details ...interface{}) error { return newStatus(codes.DeadlineExceeded, msg, err, details...).Err() } func WrapWithNotFound(msg string, err error, details ...interface{}) error { return newStatus(codes.NotFound, msg, err, details...).Err() } func WrapWithAlreadyExists(msg string, err error, details ...interface{}) error { return newStatus(codes.AlreadyExists, msg, err, details...).Err() } func WrapWithPermissionDenied(msg string, err error, details ...interface{}) error { return newStatus(codes.PermissionDenied, msg, err, details...).Err() } func WrapWithResourceExhausted(msg string, err error, details ...interface{}) error { return newStatus(codes.ResourceExhausted, msg, err, details...).Err() } func WrapWithFailedPrecondition(msg string, err error, details ...interface{}) error { return newStatus(codes.FailedPrecondition, msg, err, details...).Err() } func WrapWithAborted(msg string, err error, details ...interface{}) error { return newStatus(codes.Aborted, msg, err, details...).Err() } func WrapWithOutOfRange(msg string, err error, details ...interface{}) error { return newStatus(codes.OutOfRange, msg, err, details...).Err() } func WrapWithUnimplemented(msg string, err error, details ...interface{}) error { return newStatus(codes.Unimplemented, msg, err, details...).Err() } func WrapWithInternal(msg string, err error, details ...interface{}) error { return newStatus(codes.Internal, msg, err, details...).Err() } func WrapWithUnavailable(msg string, err error, details ...interface{}) error { return newStatus(codes.Unavailable, msg, err, details...).Err() } func WrapWithDataLoss(msg string, err error, details ...interface{}) error { return newStatus(codes.DataLoss, msg, err, details...).Err() } func WrapWithUnauthenticated(msg string, err error, details ...interface{}) error { return newStatus(codes.Unauthenticated, msg, err, details...).Err() } func Error(code codes.Code, msg string) error { return status.Error(code, msg) } func Errorf(code codes.Code, format string, args ...interface{}) error { return status.Errorf(code, format, args...) } func ParseError(err error, defaultCode codes.Code, defaultMsg string, details ...interface{}) (st *Status, msg string, rerr error) { if err == nil { st = newStatus(codes.OK, "", nil, details...) msg = st.Message() return st, msg, nil } var ok bool st, ok = FromError(err) if !ok || st == nil { if defaultCode == 0 { defaultCode = codes.Internal } if len(defaultMsg) == 0 { defaultMsg = "failed to parse grpc status from error" } st = newStatus(defaultCode, defaultMsg, err, details...) if st == nil || st.Message() == "" { msg = st.Err().Error() } else { msg = st.Message() } return st, msg, st.Err() } st = withDetails(st, err, details...) msg = st.Message() return st, msg, err } func FromError(err error) (st *Status, ok bool) { if err == nil { return nil, false } root := err for { if st, ok = status.FromError(err); ok && st != nil { return st, true } if uerr := errors.Unwrap(err); uerr != nil { err = uerr } else { switch { case errors.Is(root, context.DeadlineExceeded): st = newStatus(codes.DeadlineExceeded, root.Error(), errors.Unwrap(root)) return st, true case errors.Is(root, context.Canceled): st = newStatus(codes.Canceled, root.Error(), errors.Unwrap(root)) return st, true default: st = newStatus(codes.Unknown, root.Error(), errors.Unwrap(root)) return st, false } } } } func withDetails(st *Status, err error, details ...interface{}) *Status { msgs := make([]proto.MessageV1, 0, len(details)*2) if err != nil { msgs = append(msgs, &errdetails.ErrorInfo{ Reason: err.Error(), Domain: func() (hostname string) { var err error hostname, err = os.Hostname() if err != nil { log.Warn("failed to fetch hostname:", err) } return hostname }(), }) } for _, detail := range details { switch v := detail.(type) { case spb.Status: msgs = append(msgs, proto.ToMessageV1(&v)) case *spb.Status: msgs = append(msgs, proto.ToMessageV1(v)) case status.Status: msgs = append(msgs, proto.ToMessageV1(&spb.Status{ Code: v.Proto().GetCode(), Message: v.Message(), })) for _, d := range v.Proto().Details { msgs = append(msgs, proto.ToMessageV1(errdetails.AnyToErrorDetail(d))) } case *status.Status: msgs = append(msgs, proto.ToMessageV1(&spb.Status{ Code: v.Proto().GetCode(), Message: v.Message(), })) for _, d := range v.Proto().Details { msgs = append(msgs, proto.ToMessageV1(errdetails.AnyToErrorDetail(d))) } case *info.Detail: msgs = append(msgs, errdetails.DebugInfoFromInfoDetail(v)) case info.Detail: msgs = append(msgs, errdetails.DebugInfoFromInfoDetail(&v)) case proto.Message: msgs = append(msgs, proto.ToMessageV1(v)) case *proto.Message: msgs = append(msgs, proto.ToMessageV1(*v)) case proto.MessageV1: msgs = append(msgs, v) case *proto.MessageV1: msgs = append(msgs, *v) case types.Any: msgs = append(msgs, proto.ToMessageV1(errdetails.AnyToErrorDetail(&v))) } } if len(msgs) != 0 { sst, err := st.WithDetails(msgs...) if err == nil && sst != nil { st = sst } else { log.Warn("failed to set error details:", err) } } Log(st.Code(), st.Err()) return st } func Log(code codes.Code, err error) { if err != nil { switch code { case codes.Internal, codes.DataLoss: log.Error(err.Error()) case codes.Unavailable, codes.ResourceExhausted: log.Warn(err.Error()) case codes.FailedPrecondition, codes.InvalidArgument, codes.OutOfRange, codes.Unauthenticated, codes.PermissionDenied, codes.Unknown: log.Debug(err.Error()) case codes.Aborted, codes.Canceled, codes.DeadlineExceeded, codes.AlreadyExists, codes.NotFound, codes.OK, codes.Unimplemented: default: log.Warn(errors.ErrGRPCUnexpectedStatusError(code.String(), err)) } } }
Earchiel/Pixen
Pixel Art Core/Background/PXBackground.h
<filename>Pixel Art Core/Background/PXBackground.h<gh_stars>10-100 // // PXBackground.h // Pixen // @class PXCanvas; @interface PXBackground : NSViewController <NSCoding, NSCopying> { @private NSSize cachedImageSize; } @property (nonatomic, strong) NSImage *cachedImage; @property (nonatomic, copy) NSString *name; - (NSImage *)previewImageOfSize:(NSSize)size; - (NSString *)defaultName; - (void)setConfiguratorEnabled:(BOOL)enabled; - (void)changed; - (void)drawRect:(NSRect)rect withinRect:(NSRect)wholeRect; - (void)drawRect:(NSRect)rect withinRect:(NSRect)wholeRect withTransform:(NSAffineTransform *)aTransform onCanvas:(PXCanvas *)aCanvas; - (void)windowWillClose:(NSNotification *)note; @end
aonguyen123/frontend_KiemDien
src/views/Dashboard/components/PresentStatistical/chart.js
<reponame>aonguyen123/frontend_KiemDien import palette from 'theme/palette'; import moment from 'moment'; export const fillData = (dataPresences, chooseWeek) => { const { indexChoose, chooseWeekDate } = chooseWeek; let data, total = 0, subTotal = 0, Mon = 0, Tue = 0, Wed = 0, Thu = 0, Fri = 0, Sat = 0, Sun = 0; const { checkDates, classPresences } = dataPresences; const dayFirstWeek = moment() .subtract(1, 'weeks') .startOf('isoWeek'), dayLastWeek = moment() .subtract(1, 'weeks') .endOf('isoWeek'); if (indexChoose === '' || indexChoose === 0) { classPresences.forEach(lop => { checkDates.forEach(item => { if (item.idClass === lop._id) { item.dateList.forEach(ngay => { if ( moment(ngay.date, 'DD/MM/YYYY').isBetween( dayFirstWeek, dayLastWeek, null, '[]' ) ) { subTotal++; } }); } }); total += subTotal * lop.dssv.length; subTotal = 0; }); if (total !== 0) { classPresences.forEach(lop => { lop.dssv.forEach(sv => { sv.checkDate.forEach(date => { if ( moment(date.date, 'DD/MM/YYYY').isSame( dayFirstWeek, 'isoWeek' ) && moment(date.date, 'DD/MM/YYYY').format('dddd') === 'Monday' && date.status ) { Mon++; } if ( moment(date.date, 'DD/MM/YYYY').isSame( dayFirstWeek, 'isoWeek' ) && moment(date.date, 'DD/MM/YYYY').format('dddd') === 'Tuesday' && date.status ) { Tue++; } if ( moment(date.date, 'DD/MM/YYYY').isSame( dayFirstWeek, 'isoWeek' ) && moment(date.date, 'DD/MM/YYYY').format('dddd') === 'Wednesday' && date.status ) { Wed++; } if ( moment(date.date, 'DD/MM/YYYY').isSame( dayFirstWeek, 'isoWeek' ) && moment(date.date, 'DD/MM/YYYY').format('dddd') === 'Thursday' && date.status ) { Thu++; } if ( moment(date.date, 'DD/MM/YYYY').isSame( dayFirstWeek, 'isoWeek' ) && moment(date.date, 'DD/MM/YYYY').format('dddd') === 'Friday' && date.status ) { Fri++; } if ( moment(date.date, 'DD/MM/YYYY').isSame( dayFirstWeek, 'isoWeek' ) && moment(date.date, 'DD/MM/YYYY').format('dddd') === 'Saturday' && date.status ) { Sat++; } if ( moment(date.date, 'DD/MM/YYYY').isSame( dayFirstWeek, 'isoWeek' ) && moment(date.date, 'DD/MM/YYYY').format('dddd') === 'Sunday' && date.status ) { Sun++; } }); }); }); data = { labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], datasets: [ { label: 'Present', backgroundColor: 'rgba(241, 91, 193, 0.27)', data: [Mon, Tue, Wed, Thu, Fri, Sat, Sun], fill: 'origin', borderColor: 'rgba(217, 48, 138, 1)', pointBorderWidth: 4 } ] }; } else { data = null; } } if(indexChoose === 1) { total = 0; subTotal = 0; Mon = 0;Tue = 0;Wed = 0;Thu = 0;Fri = 0;Sat = 0;Sun = 0; const dayFirstWeek = moment(chooseWeekDate).startOf('isoWeek'), dayLastWeek = moment(chooseWeekDate).endOf('isoWeek'); classPresences.forEach(lop => { checkDates.forEach(item => { if (item.idClass === lop._id) { item.dateList.forEach(ngay => { if ( moment(ngay.date, 'DD/MM/YYYY').isBetween( dayFirstWeek, dayLastWeek, null, '[]' ) ) { subTotal++; } }); } }); total += subTotal * lop.dssv.length; subTotal = 0; }); if (total !== 0) { classPresences.forEach(lop => { lop.dssv.forEach(sv => { sv.checkDate.forEach(date => { if ( moment(date.date, 'DD/MM/YYYY').isSame( dayFirstWeek, 'isoWeek' ) && moment(date.date, 'DD/MM/YYYY').format('dddd') === 'Monday' && date.status ) { Mon++; } if ( moment(date.date, 'DD/MM/YYYY').isSame( dayFirstWeek, 'isoWeek' ) && moment(date.date, 'DD/MM/YYYY').format('dddd') === 'Tuesday' && date.status ) { Tue++; } if ( moment(date.date, 'DD/MM/YYYY').isSame( dayFirstWeek, 'isoWeek' ) && moment(date.date, 'DD/MM/YYYY').format('dddd') === 'Wednesday' && date.status ) { Wed++; } if ( moment(date.date, 'DD/MM/YYYY').isSame( dayFirstWeek, 'isoWeek' ) && moment(date.date, 'DD/MM/YYYY').format('dddd') === 'Thursday' && date.status ) { Thu++; } if ( moment(date.date, 'DD/MM/YYYY').isSame( dayFirstWeek, 'isoWeek' ) && moment(date.date, 'DD/MM/YYYY').format('dddd') === 'Friday' && date.status ) { Fri++; } if ( moment(date.date, 'DD/MM/YYYY').isSame( dayFirstWeek, 'isoWeek' ) && moment(date.date, 'DD/MM/YYYY').format('dddd') === 'Saturday' && date.status ) { Sat++; } if ( moment(date.date, 'DD/MM/YYYY').isSame( dayFirstWeek, 'isoWeek' ) && moment(date.date, 'DD/MM/YYYY').format('dddd') === 'Sunday' && date.status ) { Sun++; } }); }); }); data = { labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], datasets: [ { label: 'Present', backgroundColor: 'rgba(241, 91, 193, 0.27)', data: [Mon, Tue, Wed, Thu, Fri, Sat, Sun], fill: 'origin' } ] }; } else { data = null; } } return { data }; }; export const options = { responsive: true, maintainAspectRatio: false, animation: { }, legend: { display: false }, lineTension: 0, tooltips: { enabled: true, mode: 'index', intersect: false, borderWidth: 1, borderColor: palette.divider, backgroundColor: palette.white, titleFontColor: palette.text.primary, bodyFontColor: palette.text.secondary, footerFontColor: palette.text.secondary }, layout: { padding: 0 }, scales: { xAxes: [ { gridLines: { borderDash: [2] } } ], yAxes: [ { gridLines: { borderDash: [2], color: palette.divider, zeroLineBorderDash: [2], zeroLineColor: palette.divider } } ] } };
GPUOpen-Tools/radeon_memory_visualizer
source/frontend/views/compare/snapshot_delta_pane.cpp
//============================================================================= // Copyright (c) 2018-2021 Advanced Micro Devices, Inc. All rights reserved. /// @author AMD Developer Tools Team /// @file /// @brief Implementation of the Snapshot delta pane. //============================================================================= #include "views/compare/snapshot_delta_pane.h" #include "qt_common/utils/scaling_manager.h" #include "util/rmv_util.h" #include "util/widget_util.h" typedef struct RmtDataSnapshot RmtDataSnapshot; SnapshotDeltaPane::SnapshotDeltaPane(QWidget* parent) : ComparePane(parent) , ui_(new Ui::SnapshotDeltaPane) { ui_->setupUi(this); rmv::widget_util::ApplyStandardPaneStyle(this, ui_->main_content_, ui_->main_scroll_area_); model_ = new rmv::SnapshotDeltaModel(); model_->InitializeModel(ui_->base_snapshot_label_, rmv::kHeapDeltaCompareBaseName, "text"); model_->InitializeModel(ui_->diff_snapshot_label_, rmv::kHeapDeltaCompareDiffName, "text"); delta_items_.push_back({"Available size", kDeltaValueTypeValueLabeled, false, 0, "", QColor()}); delta_items_.push_back({"Allocated and bound", kDeltaValueTypeValueLabeled, true, 0, "", QColor()}); delta_items_.push_back({"Allocated and unbound", kDeltaValueTypeValueLabeled, true, 0, "", QColor()}); delta_items_.push_back({"Allocations", kDeltaValueTypeValue, true, 0, "", QColor()}); delta_items_.push_back({"Resources", kDeltaValueTypeValue, true, 0, "", QColor()}); delta_line_pairs_[0].display = ui_->delta_view_heap_0_; delta_line_pairs_[0].line = nullptr; delta_line_pairs_[1].display = ui_->delta_view_heap_1_; delta_line_pairs_[1].line = ui_->delta_view_line_1_; delta_line_pairs_[2].display = ui_->delta_view_heap_2_; delta_line_pairs_[2].line = ui_->delta_view_line_2_; for (int32_t current_heap_index = 0; current_heap_index <= kRmtHeapTypeSystem; current_heap_index++) { delta_line_pairs_[current_heap_index].display->Init(model_->GetHeapName(current_heap_index), delta_items_); } rmv::widget_util::InitGraphicsView(ui_->carousel_view_, ScalingManager::Get().Scaled(kCarouselItemHeight)); RMVCarouselConfig config = {}; config.height = ui_->carousel_view_->height(); config.data_type = kCarouselDataTypeDelta; carousel_ = new RMVCarousel(config); ui_->carousel_view_->setScene(carousel_->Scene()); ui_->legends_view_->setFrameStyle(QFrame::NoFrame); ui_->legends_view_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); ui_->legends_view_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); rmv::widget_util::InitColorLegend(legends_, ui_->legends_view_); AddMemoryDeltaLegends(); QRectF legend_rect = legends_->itemsBoundingRect(); ui_->legends_view_->setFixedSize(legend_rect.toRect().size()); ui_->legends_view_->setSceneRect(legend_rect); connect(ui_->switch_button_, &QPushButton::pressed, this, &SnapshotDeltaPane::SwitchSnapshots); connect(&ScalingManager::Get(), &ScalingManager::ScaleFactorChanged, this, &SnapshotDeltaPane::OnScaleFactorChanged); } SnapshotDeltaPane::~SnapshotDeltaPane() { disconnect(&ScalingManager::Get(), &ScalingManager::ScaleFactorChanged, this, &SnapshotDeltaPane::OnScaleFactorChanged); delete carousel_; delete model_; } void SnapshotDeltaPane::showEvent(QShowEvent* event) { Refresh(); QWidget::showEvent(event); } void SnapshotDeltaPane::OnScaleFactorChanged() { // Carousel. ui_->carousel_view_->setFixedHeight(ScalingManager::Get().Scaled(kCarouselItemHeight)); // Legend. QRectF legend_rect = legends_->itemsBoundingRect(); ui_->legends_view_->setFixedSize(legend_rect.toRect().size()); ui_->legends_view_->setSceneRect(legend_rect); // Delta Displays. ui_->delta_view_heap_0_->setFixedHeight(ScalingManager::Get().Scaled(kHeapDeltaWidgetHeight)); ui_->delta_view_heap_1_->setFixedHeight(ScalingManager::Get().Scaled(kHeapDeltaWidgetHeight)); ui_->delta_view_heap_2_->setFixedHeight(ScalingManager::Get().Scaled(kHeapDeltaWidgetHeight)); } void SnapshotDeltaPane::SwitchSnapshots() { if (model_->SwapSnapshots() == true) { UpdateUI(); } } void SnapshotDeltaPane::UpdateUI() { // Update delta information. for (int32_t current_heap_index = 0; current_heap_index <= kRmtHeapTypeSystem; current_heap_index++) { delta_line_pairs_[current_heap_index].display->Init(model_->GetHeapName(current_heap_index), delta_items_); } model_->UpdateCarousel(carousel_); // Update heap data. for (int32_t current_heap_index = 0; current_heap_index <= kRmtHeapTypeSystem; current_heap_index++) { rmv::SnapshotDeltaModel::HeapDeltaData heap_delta_data; if (model_->CalcPerHeapDelta((RmtHeapType)current_heap_index, heap_delta_data) == true) { delta_items_[kSnapshotDeltaTypeAvailableSize].value_num = heap_delta_data.total_available_size; delta_items_[kSnapshotDeltaTypeAllocatedAndBound].value_num = heap_delta_data.total_allocated_and_bound; delta_items_[kSnapshotDeltaTypeAllocatedAndUnbound].value_num = heap_delta_data.total_allocated_and_unbound; delta_items_[kSnapshotDeltaTypeAllocationCount].value_num = heap_delta_data.allocation_count; delta_items_[kSnapshotDeltaTypeResourceCount].value_num = heap_delta_data.resource_count; for (int j = 0; j < kSnapshotDeltaTypeCount; j++) { delta_line_pairs_[current_heap_index].display->UpdateItem(delta_items_[j]); } } } ResizeItems(); } void SnapshotDeltaPane::Refresh() { if (model_->Update() == true) { UpdateUI(); for (int32_t current_heap_index = 0; current_heap_index <= kRmtHeapTypeSystem; current_heap_index++) { if (delta_line_pairs_[current_heap_index].display != nullptr) { delta_line_pairs_[current_heap_index].display->show(); } if (delta_line_pairs_[current_heap_index].line != nullptr) { delta_line_pairs_[current_heap_index].line->show(); } } } } void SnapshotDeltaPane::Reset() { model_->ResetModelValues(); } void SnapshotDeltaPane::ChangeColoring() { legends_->Clear(); AddMemoryDeltaLegends(); } void SnapshotDeltaPane::ResizeItems() { if (carousel_ != nullptr) { carousel_->ResizeEvent(ui_->carousel_view_->width(), ui_->carousel_view_->height()); } } void SnapshotDeltaPane::resizeEvent(QResizeEvent* event) { ResizeItems(); QWidget::resizeEvent(event); } void SnapshotDeltaPane::AddMemoryDeltaLegends() { legends_->AddColorLegendItem(rmv_util::GetDeltaChangeColor(kDeltaChangeIncrease), "Increase"); legends_->AddColorLegendItem(rmv_util::GetDeltaChangeColor(kDeltaChangeDecrease), "Decrease"); legends_->AddColorLegendItem(rmv_util::GetDeltaChangeColor(kDeltaChangeNone), "No delta"); }
Pismery/Study
algorithm/src/test/java/com/pismery/study/algorithm/PerfectSquareTest.java
<filename>algorithm/src/test/java/com/pismery/study/algorithm/PerfectSquareTest.java<gh_stars>0 package com.pismery.study.algorithm; import com.pismery.study.algorithm.PerfectSquare; import org.junit.Test; import static org.junit.Assert.assertEquals; public class PerfectSquareTest { @Test public void squareNumMathematicalFor0() { assertEquals(0, PerfectSquare.squareNumByMathematical(0)); } @Test public void squareNumMathematicalFor1() { assertEquals(1, PerfectSquare.squareNumByMathematical(1)); } @Test public void squareNumMathematicalFor2() { assertEquals(2, PerfectSquare.squareNumByMathematical(2)); } @Test public void squareNumMathematicalFor4() { assertEquals(1, PerfectSquare.squareNumByMathematical(4)); } @Test public void squareNumMathematicalFor8() { assertEquals(2, PerfectSquare.squareNumByMathematical(8)); } @Test public void squareNumMathematicalFor123456() { int result = PerfectSquare.squareNumByMathematical(123456); assertEquals(3, result); } @Test public void squareNumDPFor0() { assertEquals(0, PerfectSquare.squareNumByDP(0)); } @Test public void squareNumDPFor1() { assertEquals(1, PerfectSquare.squareNumByDP(1)); } @Test public void squareNumDPFor2() { assertEquals(2, PerfectSquare.squareNumByDP(2)); } @Test public void squareNumDPFor4() { assertEquals(1, PerfectSquare.squareNumByDP(4)); } @Test public void squareNumDPFor8() { assertEquals(2, PerfectSquare.squareNumByDP(8)); } @Test public void squareNumDPFor123456() { int result = PerfectSquare.squareNumByDP(123456); assertEquals(3, result); } @Test public void squareNumBFSFor0() { int result = PerfectSquare.squareNumByBFS(0); assertEquals(0, result); } @Test public void squareNumBFSFor1() { int result = PerfectSquare.squareNumByBFS(1); assertEquals(1, result); } @Test public void squareNumBFSFor3() { int result = PerfectSquare.squareNumByBFS(3); assertEquals(3, result); } @Test public void squareNumBFSFor4() { int result = PerfectSquare.squareNumByBFS(4); assertEquals(1, result); } @Test public void squareNumBFSFor8() { int result = PerfectSquare.squareNumByBFS(8); assertEquals(2, result); } @Test public void squareNumForBFS123456() { int result = PerfectSquare.squareNumByBFS(123456); assertEquals(3, result); } @Test public void isSqure4() { assertEquals(true, PerfectSquare.isSquare(4)); assertEquals(false, PerfectSquare.isSquare(5)); } }
1690296356/jdk
test/hotspot/jtreg/compiler/arraycopy/TestArrayCopyWithBadOffset.java
/* * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 8224539 * @summary Test arraycopy optimizations with bad src/dst array offsets. * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -Xbatch -XX:+AlwaysIncrementalInline * compiler.arraycopy.TestArrayCopyWithBadOffset */ package compiler.arraycopy; public class TestArrayCopyWithBadOffset { public static byte[] getSrc() { return new byte[5]; } // Test bad src offset public static void test1(byte[] dst) { byte[] src = getSrc(); try { System.arraycopy(src, Integer.MAX_VALUE-1, dst, 0, src.length); } catch (Exception e) { // Expected } } public static byte[] getDst() { return new byte[5]; } // Test bad dst offset public static void test2(byte[] src) { byte[] dst = getDst(); try { System.arraycopy(src, 0, dst, Integer.MAX_VALUE-1, dst.length); } catch (Exception e) { // Expected } } public static void main(String[] args) { byte[] array = new byte[5]; for (int i = 0; i < 10_000; ++i) { test1(array); test2(array); } } }
lastweek/source-freebsd
src/sys/arm/nvidia/drm2/tegra_dc_reg.h
/*- * Copyright 1992-2015 <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #ifndef _TEGRA_DC_REG_H_ #define _TEGRA_DC_REG_H_ /* * !!! WARNING !!! * Tegra manual uses registers index (and not register addreses). * We follow the TRM notation and index is converted to offset in * WR4 / RD4 macros */ /* --------------------------- DC CMD -------------------------------------- */ #define DC_CMD_GENERAL_INCR_SYNCPT 0x000 #define DC_CMD_GENERAL_INCR_SYNCPT_CNTRL 0x001 #define SYNCPT_CNTRL_NO_STALL (1 << 8) #define SYNCPT_CNTRL_SOFT_RESET (1 << 0) #define DC_CMD_GENERAL_INCR_SYNCPT_ERROR 0x002 #define DC_CMD_WIN_A_INCR_SYNCPT 0x008 #define DC_CMD_WIN_A_INCR_SYNCPT_CNTRL 0x009 #define DC_CMD_WIN_A_INCR_SYNCPT_ERROR 0x00a #define DC_CMD_WIN_B_INCR_SYNCPT 0x010 #define DC_CMD_WIN_B_INCR_SYNCPT_CNTRL 0x011 #define DC_CMD_WIN_B_INCR_SYNCPT_ERROR 0x012 #define DC_CMD_WIN_C_INCR_SYNCPT 0x018 #define DC_CMD_WIN_C_INCR_SYNCPT_CNTRL 0x019 #define DC_CMD_WIN_C_INCR_SYNCPT_ERROR 0x01a #define DC_CMD_CONT_SYNCPT_VSYNC 0x028 #define SYNCPT_VSYNC_ENABLE (1 << 8) #define DC_CMD_CTXSW 0x030 #define DC_CMD_DISPLAY_COMMAND_OPTION0 0x031 #define DC_CMD_DISPLAY_COMMAND 0x032 #define DISPLAY_CTRL_MODE(x) ((x) << 5) #define CTRL_MODE_STOP 0 #define CTRL_MODE_C_DISPLAY 1 #define CTRL_MODE_NC_DISPLAY 2 #define DC_CMD_SIGNAL_RAISE 0x033 #define DC_CMD_DISPLAY_POWER_CONTROL 0x036 #define PM1_ENABLE (1 << 18) #define PM0_ENABLE (1 << 16) #define PW4_ENABLE (1 << 8) #define PW3_ENABLE (1 << 6) #define PW2_ENABLE (1 << 4) #define PW1_ENABLE (1 << 2) #define PW0_ENABLE (1 << 0) #define DC_CMD_INT_STATUS 0x037 #define DC_CMD_INT_MASK 0x038 #define DC_CMD_INT_ENABLE 0x039 #define DC_CMD_INT_TYPE 0x03a #define DC_CMD_INT_POLARITY 0x03b #define WIN_T_UF_INT (1 << 25) #define WIN_D_UF_INT (1 << 24) #define HC_UF_INT (1 << 23) #define CMU_LUT_CONFLICT_INT (1 << 22) #define WIN_C_OF_INT (1 << 16) #define WIN_B_OF_INT (1 << 15) #define WIN_A_OF_INT (1 << 14) #define SSF_INT (1 << 13) #define MSF_INT (1 << 12) #define WIN_C_UF_INT (1 << 10) #define WIN_B_UF_INT (1 << 9) #define WIN_A_UF_INT (1 << 8) #define SPI_BUSY_INT (1 << 6) #define V_PULSE2_INT (1 << 5) #define V_PULSE3_INT (1 << 4) #define HBLANK_INT (1 << 3) #define VBLANK_INT (1 << 2) #define FRAME_END_INT (1 << 1) #define DC_CMD_STATE_ACCESS 0x040 #define WRITE_MUX (1 << 2) #define READ_MUX (1 << 0) #define DC_CMD_STATE_CONTROL 0x041 #define NC_HOST_TRIG (1 << 24) #define CURSOR_UPDATE (1 << 15) #define WIN_C_UPDATE (1 << 11) #define WIN_B_UPDATE (1 << 10) #define WIN_A_UPDATE (1 << 9) #define WIN_UPDATE(x) (1 << (9 + (x))) #define GENERAL_UPDATE (1 << 8) #define CURSOR_ACT_REQ (1 << 7) #define WIN_D_ACT_REQ (1 << 4) #define WIN_C_ACT_REQ (1 << 3) #define WIN_B_ACT_REQ (1 << 2) #define WIN_A_ACT_REQ (1 << 1) #define WIN_ACT_REQ(x) (1 << (1 + (x))) #define GENERAL_ACT_REQ (1 << 0) #define DC_CMD_DISPLAY_WINDOW_HEADER 0x042 #define WINDOW_D_SELECT (1 << 7) #define WINDOW_C_SELECT (1 << 6) #define WINDOW_B_SELECT (1 << 5) #define WINDOW_A_SELECT (1 << 4) #define WINDOW_SELECT(x) (1 << (4 + (x))) #define DC_CMD_REG_ACT_CONTROL 0x043 #define DC_CMD_WIN_D_INCR_SYNCPT 0x04c #define DC_CMD_WIN_D_INCR_SYNCPT_CNTRL 0x04d #define DC_CMD_WIN_D_INCR_SYNCPT_ERROR 0x04e /* ---------------------------- DC COM ------------------------------------- */ /* --------------------------- DC DISP ------------------------------------- */ #define DC_DISP_DISP_SIGNAL_OPTIONS0 0x400 #define M1_ENABLE (1 << 26) #define M0_ENABLE (1 << 24) #define V_PULSE2_ENABLE (1 << 18) #define V_PULSE1_ENABLE (1 << 16) #define V_PULSE0_ENABLE (1 << 14) #define H_PULSE2_ENABLE (1 << 12) #define H_PULSE1_ENABLE (1 << 10) #define H_PULSE0_ENABLE (1 << 8) #define DC_DISP_DISP_SIGNAL_OPTIONS1 0x401 #define DC_DISP_DISP_WIN_OPTIONS 0x402 #define HDMI_ENABLE (1 << 30) #define DSI_ENABLE (1 << 29) #define SOR1_TIMING_CYA (1 << 27) #define SOR1_ENABLE (1 << 26) #define SOR_ENABLE (1 << 25) #define CURSOR_ENABLE (1 << 16) #define DC_DISP_DISP_TIMING_OPTIONS 0x405 #define VSYNC_H_POSITION(x) (((x) & 0xfff) << 0) #define DC_DISP_REF_TO_SYNC 0x406 #define DC_DISP_SYNC_WIDTH 0x407 #define DC_DISP_BACK_PORCH 0x408 #define DC_DISP_DISP_ACTIVE 0x409 #define DC_DISP_FRONT_PORCH 0x40a #define DC_DISP_H_PULSE0_CONTROL 0x40b #define DC_DISP_H_PULSE0_POSITION_A 0x40c #define DC_DISP_H_PULSE0_POSITION_B 0x40d #define DC_DISP_H_PULSE0_POSITION_C 0x40e #define DC_DISP_H_PULSE0_POSITION_D 0x40f #define DC_DISP_H_PULSE1_CONTROL 0x410 #define DC_DISP_H_PULSE1_POSITION_A 0x411 #define DC_DISP_H_PULSE1_POSITION_B 0x412 #define DC_DISP_H_PULSE1_POSITION_C 0x413 #define DC_DISP_H_PULSE1_POSITION_D 0x414 #define DC_DISP_H_PULSE2_CONTROL 0x415 #define DC_DISP_H_PULSE2_POSITION_A 0x416 #define DC_DISP_H_PULSE2_POSITION_B 0x417 #define DC_DISP_H_PULSE2_POSITION_C 0x418 #define DC_DISP_H_PULSE2_POSITION_D 0x419 #define DC_DISP_V_PULSE0_CONTROL 0x41a #define DC_DISP_V_PULSE0_POSITION_A 0x41b #define DC_DISP_V_PULSE0_POSITION_B 0x41c #define DC_DISP_V_PULSE0_POSITION_C 0x41d #define DC_DISP_V_PULSE1_CONTROL 0x41e #define DC_DISP_V_PULSE1_POSITION_A 0x41f #define DC_DISP_V_PULSE1_POSITION_B 0x420 #define DC_DISP_V_PULSE1_POSITION_C 0x421 #define DC_DISP_V_PULSE2_CONTROL 0x422 #define DC_DISP_V_PULSE2_POSITION_A 0x423 #define DC_DISP_V_PULSE3_CONTROL 0x424 #define PULSE_CONTROL_LAST(x) (((x) & 0x7f) << 8) #define LAST_START_A 0 #define LAST_END_A 1 #define LAST_START_B 2 #define LAST_END_B 3 #define LAST_START_C 4 #define LAST_END_C 5 #define LAST_START_D 6 #define LAST_END_D 7 #define PULSE_CONTROL_QUAL(x) (((x) & 0x3) << 8) #define QUAL_ALWAYS 0 #define QUAL_VACTIVE 2 #define QUAL_VACTIVE1 3 #define PULSE_POLARITY (1 << 4) #define PULSE_MODE (1 << 3) #define DC_DISP_V_PULSE3_POSITION_A 0x425 #define PULSE_END(x) (((x) & 0xfff) << 16) #define PULSE_START(x) (((x) & 0xfff) << 0) #define DC_DISP_DISP_CLOCK_CONTROL 0x42e #define PIXEL_CLK_DIVIDER(x) (((x) & 0xf) << 8) #define PCD1 0 #define PCD1H 1 #define PCD2 2 #define PCD3 3 #define PCD4 4 #define PCD6 5 #define PCD8 6 #define PCD9 7 #define PCD12 8 #define PCD16 9 #define PCD18 10 #define PCD24 11 #define PCD13 12 #define SHIFT_CLK_DIVIDER(x) ((x) & 0xff) #define DC_DISP_DISP_INTERFACE_CONTROL 0x42f #define DISP_ORDER_BLUE_RED ( 1 << 9) #define DISP_ALIGNMENT_LSB ( 1 << 8) #define DISP_DATA_FORMAT(x) (((x) & 0xf) << 8) #define DF1P1C 0 #define DF1P2C24B 1 #define DF1P2C18B 2 #define DF1P2C16B 3 #define DF1S 4 #define DF2S 5 #define DF3S 6 #define DFSPI 7 #define DF1P3C24B 8 #define DF2P1C18B 9 #define DFDUAL1P1C18B 10 #define DC_DISP_DISP_COLOR_CONTROL 0x430 #define NON_BASE_COLOR (1 << 18) #define BLANK_COLOR (1 << 17) #define DISP_COLOR_SWAP (1 << 16) #define ORD_DITHER_ROTATION(x) (((x) & 0x3) << 12) #define DITHER_CONTROL(x) (((x) & 0x3) << 8) #define DITHER_DISABLE 0 #define DITHER_ORDERED 2 #define DITHER_TEMPORAL 3 #define BASE_COLOR_SIZE(x) (((x) & 0xF) << 0) #define SIZE_BASE666 0 #define SIZE_BASE111 1 #define SIZE_BASE222 2 #define SIZE_BASE333 3 #define SIZE_BASE444 4 #define SIZE_BASE555 5 #define SIZE_BASE565 6 #define SIZE_BASE332 7 #define SIZE_BASE888 8 #define DC_DISP_CURSOR_START_ADDR 0x43e #define CURSOR_CLIP(x) (((x) & 0x3) << 28) #define CC_DISPLAY 0 #define CC_WA 1 #define CC_WB 2 #define CC_WC 3 #define CURSOR_SIZE(x) (((x) & 0x3) << 24) #define C32x32 0 #define C64x64 1 #define C128x128 2 #define C256x256 3 #define CURSOR_START_ADDR(x) (((x) >> 10) & 0x3FFFFF) #define DC_DISP_CURSOR_POSITION 0x440 #define CURSOR_POSITION(h, v) ((((h) & 0x3fff) << 0) | \ (((v) & 0x3fff) << 16)) #define DC_DISP_CURSOR_UNDERFLOW_CTRL 0x4eb #define DC_DISP_BLEND_CURSOR_CONTROL 0x4f1 #define CURSOR_MODE_SELECT (1 << 24) #define CURSOR_DST_BLEND_FACTOR_SELECT(x) (((x) & 0x3) << 16) #define DST_BLEND_ZERO 0 #define DST_BLEND_K1 1 #define DST_NEG_K1_TIMES_SRC 2 #define CURSOR_SRC_BLEND_FACTOR_SELECT(x) (((x) & 0x3) << 8) #define SRC_BLEND_K1 0 #define SRC_BLEND_K1_TIMES_SRC 1 #define CURSOR_ALPHA(x) (((x) & 0xFF) << 0) #define DC_DISP_CURSOR_UFLOW_DBG_PIXEL 0x4f3 #define CURSOR_UFLOW_CYA (1 << 7) #define CURSOR_UFLOW_CTRL_DBG_MODE (1 << 0) /* --------------------------- DC WIN ------------------------------------- */ #define DC_WINC_COLOR_PALETTE 0x500 #define DC_WINC_CSC_YOF 0x611 #define DC_WINC_CSC_KYRGB 0x612 #define DC_WINC_CSC_KUR 0x613 #define DC_WINC_CSC_KVR 0x614 #define DC_WINC_CSC_KUG 0x615 #define DC_WINC_CSC_KVG 0x616 #define DC_WINC_CSC_KUB 0x617 #define DC_WINC_CSC_KVB 0x618 #define DC_WINC_WIN_OPTIONS 0x700 #define H_FILTER_MODE (1U << 31) #define WIN_ENABLE (1 << 30) #define INTERLACE_ENABLE (1 << 23) #define YUV_RANGE_EXPAND (1 << 22) #define DV_ENABLE (1 << 20) #define CSC_ENABLE (1 << 18) #define CP_ENABLE (1 << 16) #define V_FILTER_UV_ALIGN (1 << 14) #define V_FILTER_OPTIMIZE (1 << 12) #define V_FILTER_ENABLE (1 << 10) #define H_FILTER_ENABLE (1 << 8) #define COLOR_EXPAND (1 << 6) #define SCAN_COLUMN (1 << 4) #define V_DIRECTION (1 << 2) #define H_DIRECTION (1 << 0) #define DC_WIN_BYTE_SWAP 0x701 #define BYTE_SWAP(x) (((x) & 0x7) << 0) #define NOSWAP 0 #define SWAP2 1 #define SWAP4 2 #define SWAP4HW 3 #define SWAP02 4 #define SWAPLEFT 5 #define DC_WIN_COLOR_DEPTH 0x703 #define WIN_COLOR_DEPTH_P8 3 #define WIN_COLOR_DEPTH_B4G4R4A4 4 #define WIN_COLOR_DEPTH_B5G5R5A 5 #define WIN_COLOR_DEPTH_B5G6R5 6 #define WIN_COLOR_DEPTH_AB5G5R5 7 #define WIN_COLOR_DEPTH_B8G8R8A8 12 #define WIN_COLOR_DEPTH_R8G8B8A8 13 #define WIN_COLOR_DEPTH_YCbCr422 16 #define WIN_COLOR_DEPTH_YUV422 17 #define WIN_COLOR_DEPTH_YCbCr420P 18 #define WIN_COLOR_DEPTH_YUV420P 19 #define WIN_COLOR_DEPTH_YCbCr422P 20 #define WIN_COLOR_DEPTH_YUV422P 21 #define WIN_COLOR_DEPTH_YCbCr422R 22 #define WIN_COLOR_DEPTH_YUV422R 23 #define WIN_COLOR_DEPTH_YCbCr422RA 24 #define WIN_COLOR_DEPTH_YUV422RA 25 #define DC_WIN_POSITION 0x704 #define WIN_POSITION(h, v) ((((h) & 0x1fff) << 0) | \ (((v) & 0x1fff) << 16)) #define DC_WIN_SIZE 0x705 #define WIN_SIZE(h, v) ((((h) & 0x1fff) << 0) | \ (((v) & 0x1fff) << 16)) #define DC_WIN_PRESCALED_SIZE 0x706 #define WIN_PRESCALED_SIZE(h, v) ((((h) & 0x7fff) << 0) | \ (((v) & 0x1fff) << 16)) #define DC_WIN_H_INITIAL_DDA 0x707 #define DC_WIN_V_INITIAL_DDA 0x708 #define DC_WIN_DDA_INCREMENT 0x709 #define WIN_DDA_INCREMENT(h, v) ((((h) & 0xffff) << 0) | \ (((v) & 0xffff) << 16)) #define DC_WIN_LINE_STRIDE 0x70a /* -------------------------- DC WINBUF ------------------------------------ */ #define DC_WINBUF_START_ADDR 0x800 #define DC_WINBUF_START_ADDR_NS 0x801 #define DC_WINBUF_START_ADDR_U 0x802 #define DC_WINBUF_START_ADDR_U_NS 0x803 #define DC_WINBUF_START_ADDR_V 0x804 #define DC_WINBUF_START_ADDR_V_NS 0x805 #define DC_WINBUF_ADDR_H_OFFSET 0x806 #define DC_WINBUF_ADDR_H_OFFSET_NS 0x807 #define DC_WINBUF_ADDR_V_OFFSET 0x808 #define DC_WINBUF_ADDR_V_OFFSET_NS 0x809 #define DC_WINBUF_UFLOW_STATUS 0x80a #define DC_WINBUF_SURFACE_KIND 0x80b #define SURFACE_KIND_BLOCK_HEIGHT(x) (((x) & 0x7) << 4) #define SURFACE_KIND_PITCH 0 #define SURFACE_KIND_TILED 1 #define SURFACE_KIND_BL_16B2 2 #define DC_WINBUF_SURFACE_WEIGHT 0x80c #define DC_WINBUF_START_ADDR_HI 0x80d #define DC_WINBUF_START_ADDR_HI_NS 0x80e #define DC_WINBUF_START_ADDR_U_HI 0x80f #define DC_WINBUF_START_ADDR_U_HI_NS 0x810 #define DC_WINBUF_START_ADDR_V_HI 0x811 #define DC_WINBUF_START_ADDR_V_HI_NS 0x812 #define DC_WINBUF_UFLOW_CTRL 0x824 #define UFLOW_CTR_ENABLE (1 << 0) #define DC_WINBUF_UFLOW_DBG_PIXEL 0x825 #endif /* _TEGRA_DC_REG_H_ */
asashour/aws-sdk-java
aws-java-sdk-resourcegroups/src/main/java/com/amazonaws/services/resourcegroups/AWSResourceGroupsClient.java
<reponame>asashour/aws-sdk-java /* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.resourcegroups; import org.w3c.dom.*; import java.net.*; import java.util.*; import javax.annotation.Generated; import org.apache.commons.logging.*; import com.amazonaws.*; import com.amazonaws.annotation.SdkInternalApi; import com.amazonaws.auth.*; import com.amazonaws.handlers.*; import com.amazonaws.http.*; import com.amazonaws.internal.*; import com.amazonaws.internal.auth.*; import com.amazonaws.metrics.*; import com.amazonaws.regions.*; import com.amazonaws.transform.*; import com.amazonaws.util.*; import com.amazonaws.protocol.json.*; import com.amazonaws.util.AWSRequestMetrics.Field; import com.amazonaws.annotation.ThreadSafe; import com.amazonaws.client.AwsSyncClientParams; import com.amazonaws.client.builder.AdvancedConfig; import com.amazonaws.services.resourcegroups.AWSResourceGroupsClientBuilder; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.resourcegroups.model.*; import com.amazonaws.services.resourcegroups.model.transform.*; /** * Client for accessing Resource Groups. All service calls made using this client are blocking, and will not return * until the service call completes. * <p> * <fullname>AWS Resource Groups</fullname> * <p> * AWS Resource Groups lets you organize AWS resources such as Amazon EC2 instances, Amazon Relational Database Service * databases, and Amazon S3 buckets into groups using criteria that you define as tags. A resource group is a collection * of resources that match the resource types specified in a query, and share one or more tags or portions of tags. You * can create a group of resources based on their roles in your cloud infrastructure, lifecycle stages, regions, * application layers, or virtually any criteria. Resource groups enable you to automate management tasks, such as those * in AWS Systems Manager Automation documents, on tag-related resources in AWS Systems Manager. Groups of tagged * resources also let you quickly view a custom console in AWS Systems Manager that shows AWS Config compliance and * other monitoring data about member resources. * </p> * <p> * To create a resource group, build a resource query, and specify tags that identify the criteria that members of the * group have in common. Tags are key-value pairs. * </p> * <p> * For more information about Resource Groups, see the <a * href="https://docs.aws.amazon.com/ARG/latest/userguide/welcome.html">AWS Resource Groups User Guide</a>. * </p> * <p> * AWS Resource Groups uses a REST-compliant API that you can use to perform the following types of operations. * </p> * <ul> * <li> * <p> * Create, Read, Update, and Delete (CRUD) operations on resource groups and resource query entities * </p> * </li> * <li> * <p> * Applying, editing, and removing tags from resource groups * </p> * </li> * <li> * <p> * Resolving resource group member ARNs so they can be returned as search results * </p> * </li> * <li> * <p> * Getting data about resources that are members of a group * </p> * </li> * <li> * <p> * Searching AWS resources based on a resource query * </p> * </li> * </ul> */ @ThreadSafe @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AWSResourceGroupsClient extends AmazonWebServiceClient implements AWSResourceGroups { /** Provider for AWS credentials. */ private final AWSCredentialsProvider awsCredentialsProvider; private static final Log log = LogFactory.getLog(AWSResourceGroups.class); /** Default signing name for the service. */ private static final String DEFAULT_SIGNING_NAME = "resource-groups"; /** Client configuration factory providing ClientConfigurations tailored to this client */ protected static final ClientConfigurationFactory configFactory = new ClientConfigurationFactory(); private final AdvancedConfig advancedConfig; private static final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory = new com.amazonaws.protocol.json.SdkJsonProtocolFactory( new JsonClientMetadata() .withProtocolVersion("1.1") .withSupportsCbor(false) .withSupportsIon(false) .withContentTypeOverride("") .addErrorMetadata( new JsonErrorShapeMetadata().withErrorCode("NotFoundException").withExceptionUnmarshaller( com.amazonaws.services.resourcegroups.model.transform.NotFoundExceptionUnmarshaller.getInstance())) .addErrorMetadata( new JsonErrorShapeMetadata().withErrorCode("UnauthorizedException").withExceptionUnmarshaller( com.amazonaws.services.resourcegroups.model.transform.UnauthorizedExceptionUnmarshaller.getInstance())) .addErrorMetadata( new JsonErrorShapeMetadata().withErrorCode("ForbiddenException").withExceptionUnmarshaller( com.amazonaws.services.resourcegroups.model.transform.ForbiddenExceptionUnmarshaller.getInstance())) .addErrorMetadata( new JsonErrorShapeMetadata().withErrorCode("MethodNotAllowedException").withExceptionUnmarshaller( com.amazonaws.services.resourcegroups.model.transform.MethodNotAllowedExceptionUnmarshaller.getInstance())) .addErrorMetadata( new JsonErrorShapeMetadata().withErrorCode("TooManyRequestsException").withExceptionUnmarshaller( com.amazonaws.services.resourcegroups.model.transform.TooManyRequestsExceptionUnmarshaller.getInstance())) .addErrorMetadata( new JsonErrorShapeMetadata().withErrorCode("BadRequestException").withExceptionUnmarshaller( com.amazonaws.services.resourcegroups.model.transform.BadRequestExceptionUnmarshaller.getInstance())) .addErrorMetadata( new JsonErrorShapeMetadata().withErrorCode("InternalServerErrorException").withExceptionUnmarshaller( com.amazonaws.services.resourcegroups.model.transform.InternalServerErrorExceptionUnmarshaller.getInstance())) .withBaseServiceExceptionClass(com.amazonaws.services.resourcegroups.model.AWSResourceGroupsException.class)); public static AWSResourceGroupsClientBuilder builder() { return AWSResourceGroupsClientBuilder.standard(); } /** * Constructs a new client to invoke service methods on Resource Groups using the specified parameters. * * <p> * All service calls made using this new client object are blocking, and will not return until the service call * completes. * * @param clientParams * Object providing client parameters. */ AWSResourceGroupsClient(AwsSyncClientParams clientParams) { this(clientParams, false); } /** * Constructs a new client to invoke service methods on Resource Groups using the specified parameters. * * <p> * All service calls made using this new client object are blocking, and will not return until the service call * completes. * * @param clientParams * Object providing client parameters. */ AWSResourceGroupsClient(AwsSyncClientParams clientParams, boolean endpointDiscoveryEnabled) { super(clientParams); this.awsCredentialsProvider = clientParams.getCredentialsProvider(); this.advancedConfig = clientParams.getAdvancedConfig(); init(); } private void init() { setServiceNameIntern(DEFAULT_SIGNING_NAME); setEndpointPrefix(ENDPOINT_PREFIX); // calling this.setEndPoint(...) will also modify the signer accordingly setEndpoint("resource-groups.us-east-1.amazonaws.com"); HandlerChainFactory chainFactory = new HandlerChainFactory(); requestHandler2s.addAll(chainFactory.newRequestHandlerChain("/com/amazonaws/services/resourcegroups/request.handlers")); requestHandler2s.addAll(chainFactory.newRequestHandler2Chain("/com/amazonaws/services/resourcegroups/request.handler2s")); requestHandler2s.addAll(chainFactory.getGlobalHandlers()); } /** * <p> * Creates a group with a specified name, description, and resource query. * </p> * * @param createGroupRequest * @return Result of the CreateGroup operation returned by the service. * @throws BadRequestException * The request does not comply with validation rules that are defined for the request parameters. * @throws ForbiddenException * The caller is not authorized to make the request. * @throws MethodNotAllowedException * The request uses an HTTP method which is not allowed for the specified resource. * @throws TooManyRequestsException * The caller has exceeded throttling limits. * @throws InternalServerErrorException * An internal error occurred while processing the request. * @sample AWSResourceGroups.CreateGroup * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/CreateGroup" target="_top">AWS * API Documentation</a> */ @Override public CreateGroupResult createGroup(CreateGroupRequest request) { request = beforeClientExecution(request); return executeCreateGroup(request); } @SdkInternalApi final CreateGroupResult executeCreateGroup(CreateGroupRequest createGroupRequest) { ExecutionContext executionContext = createExecutionContext(createGroupRequest); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<CreateGroupRequest> request = null; Response<CreateGroupResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new CreateGroupRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(createGroupRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion()); request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Resource Groups"); request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "CreateGroup"); request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } HttpResponseHandler<AmazonWebServiceResponse<CreateGroupResult>> responseHandler = protocolFactory.createResponseHandler( new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new CreateGroupResultJsonUnmarshaller()); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * Deletes a specified resource group. Deleting a resource group does not delete resources that are members of the * group; it only deletes the group structure. * </p> * * @param deleteGroupRequest * @return Result of the DeleteGroup operation returned by the service. * @throws BadRequestException * The request does not comply with validation rules that are defined for the request parameters. * @throws ForbiddenException * The caller is not authorized to make the request. * @throws NotFoundException * One or more resources specified in the request do not exist. * @throws MethodNotAllowedException * The request uses an HTTP method which is not allowed for the specified resource. * @throws TooManyRequestsException * The caller has exceeded throttling limits. * @throws InternalServerErrorException * An internal error occurred while processing the request. * @sample AWSResourceGroups.DeleteGroup * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/DeleteGroup" target="_top">AWS * API Documentation</a> */ @Override public DeleteGroupResult deleteGroup(DeleteGroupRequest request) { request = beforeClientExecution(request); return executeDeleteGroup(request); } @SdkInternalApi final DeleteGroupResult executeDeleteGroup(DeleteGroupRequest deleteGroupRequest) { ExecutionContext executionContext = createExecutionContext(deleteGroupRequest); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<DeleteGroupRequest> request = null; Response<DeleteGroupResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new DeleteGroupRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(deleteGroupRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion()); request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Resource Groups"); request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "DeleteGroup"); request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } HttpResponseHandler<AmazonWebServiceResponse<DeleteGroupResult>> responseHandler = protocolFactory.createResponseHandler( new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new DeleteGroupResultJsonUnmarshaller()); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * Returns information about a specified resource group. * </p> * * @param getGroupRequest * @return Result of the GetGroup operation returned by the service. * @throws BadRequestException * The request does not comply with validation rules that are defined for the request parameters. * @throws ForbiddenException * The caller is not authorized to make the request. * @throws NotFoundException * One or more resources specified in the request do not exist. * @throws MethodNotAllowedException * The request uses an HTTP method which is not allowed for the specified resource. * @throws TooManyRequestsException * The caller has exceeded throttling limits. * @throws InternalServerErrorException * An internal error occurred while processing the request. * @sample AWSResourceGroups.GetGroup * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/GetGroup" target="_top">AWS API * Documentation</a> */ @Override public GetGroupResult getGroup(GetGroupRequest request) { request = beforeClientExecution(request); return executeGetGroup(request); } @SdkInternalApi final GetGroupResult executeGetGroup(GetGroupRequest getGroupRequest) { ExecutionContext executionContext = createExecutionContext(getGroupRequest); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<GetGroupRequest> request = null; Response<GetGroupResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new GetGroupRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(getGroupRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion()); request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Resource Groups"); request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "GetGroup"); request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } HttpResponseHandler<AmazonWebServiceResponse<GetGroupResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata() .withPayloadJson(true).withHasStreamingSuccessResponse(false), new GetGroupResultJsonUnmarshaller()); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * Returns the resource query associated with the specified resource group. * </p> * * @param getGroupQueryRequest * @return Result of the GetGroupQuery operation returned by the service. * @throws BadRequestException * The request does not comply with validation rules that are defined for the request parameters. * @throws ForbiddenException * The caller is not authorized to make the request. * @throws NotFoundException * One or more resources specified in the request do not exist. * @throws MethodNotAllowedException * The request uses an HTTP method which is not allowed for the specified resource. * @throws TooManyRequestsException * The caller has exceeded throttling limits. * @throws InternalServerErrorException * An internal error occurred while processing the request. * @sample AWSResourceGroups.GetGroupQuery * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/GetGroupQuery" target="_top">AWS * API Documentation</a> */ @Override public GetGroupQueryResult getGroupQuery(GetGroupQueryRequest request) { request = beforeClientExecution(request); return executeGetGroupQuery(request); } @SdkInternalApi final GetGroupQueryResult executeGetGroupQuery(GetGroupQueryRequest getGroupQueryRequest) { ExecutionContext executionContext = createExecutionContext(getGroupQueryRequest); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<GetGroupQueryRequest> request = null; Response<GetGroupQueryResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new GetGroupQueryRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(getGroupQueryRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion()); request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Resource Groups"); request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "GetGroupQuery"); request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } HttpResponseHandler<AmazonWebServiceResponse<GetGroupQueryResult>> responseHandler = protocolFactory.createResponseHandler( new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new GetGroupQueryResultJsonUnmarshaller()); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * Returns a list of tags that are associated with a resource group, specified by an ARN. * </p> * * @param getTagsRequest * @return Result of the GetTags operation returned by the service. * @throws BadRequestException * The request does not comply with validation rules that are defined for the request parameters. * @throws ForbiddenException * The caller is not authorized to make the request. * @throws NotFoundException * One or more resources specified in the request do not exist. * @throws MethodNotAllowedException * The request uses an HTTP method which is not allowed for the specified resource. * @throws TooManyRequestsException * The caller has exceeded throttling limits. * @throws InternalServerErrorException * An internal error occurred while processing the request. * @sample AWSResourceGroups.GetTags * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/GetTags" target="_top">AWS API * Documentation</a> */ @Override public GetTagsResult getTags(GetTagsRequest request) { request = beforeClientExecution(request); return executeGetTags(request); } @SdkInternalApi final GetTagsResult executeGetTags(GetTagsRequest getTagsRequest) { ExecutionContext executionContext = createExecutionContext(getTagsRequest); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<GetTagsRequest> request = null; Response<GetTagsResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new GetTagsRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(getTagsRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion()); request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Resource Groups"); request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "GetTags"); request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } HttpResponseHandler<AmazonWebServiceResponse<GetTagsResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata() .withPayloadJson(true).withHasStreamingSuccessResponse(false), new GetTagsResultJsonUnmarshaller()); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * Returns a list of ARNs of resources that are members of a specified resource group. * </p> * * @param listGroupResourcesRequest * @return Result of the ListGroupResources operation returned by the service. * @throws UnauthorizedException * The request has not been applied because it lacks valid authentication credentials for the target * resource. * @throws BadRequestException * The request does not comply with validation rules that are defined for the request parameters. * @throws ForbiddenException * The caller is not authorized to make the request. * @throws NotFoundException * One or more resources specified in the request do not exist. * @throws MethodNotAllowedException * The request uses an HTTP method which is not allowed for the specified resource. * @throws TooManyRequestsException * The caller has exceeded throttling limits. * @throws InternalServerErrorException * An internal error occurred while processing the request. * @sample AWSResourceGroups.ListGroupResources * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/ListGroupResources" * target="_top">AWS API Documentation</a> */ @Override public ListGroupResourcesResult listGroupResources(ListGroupResourcesRequest request) { request = beforeClientExecution(request); return executeListGroupResources(request); } @SdkInternalApi final ListGroupResourcesResult executeListGroupResources(ListGroupResourcesRequest listGroupResourcesRequest) { ExecutionContext executionContext = createExecutionContext(listGroupResourcesRequest); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<ListGroupResourcesRequest> request = null; Response<ListGroupResourcesResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new ListGroupResourcesRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(listGroupResourcesRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion()); request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Resource Groups"); request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "ListGroupResources"); request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } HttpResponseHandler<AmazonWebServiceResponse<ListGroupResourcesResult>> responseHandler = protocolFactory.createResponseHandler( new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new ListGroupResourcesResultJsonUnmarshaller()); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * Returns a list of existing resource groups in your account. * </p> * * @param listGroupsRequest * @return Result of the ListGroups operation returned by the service. * @throws BadRequestException * The request does not comply with validation rules that are defined for the request parameters. * @throws ForbiddenException * The caller is not authorized to make the request. * @throws MethodNotAllowedException * The request uses an HTTP method which is not allowed for the specified resource. * @throws TooManyRequestsException * The caller has exceeded throttling limits. * @throws InternalServerErrorException * An internal error occurred while processing the request. * @sample AWSResourceGroups.ListGroups * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/ListGroups" target="_top">AWS API * Documentation</a> */ @Override public ListGroupsResult listGroups(ListGroupsRequest request) { request = beforeClientExecution(request); return executeListGroups(request); } @SdkInternalApi final ListGroupsResult executeListGroups(ListGroupsRequest listGroupsRequest) { ExecutionContext executionContext = createExecutionContext(listGroupsRequest); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<ListGroupsRequest> request = null; Response<ListGroupsResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new ListGroupsRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(listGroupsRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion()); request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Resource Groups"); request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "ListGroups"); request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } HttpResponseHandler<AmazonWebServiceResponse<ListGroupsResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata() .withPayloadJson(true).withHasStreamingSuccessResponse(false), new ListGroupsResultJsonUnmarshaller()); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * Returns a list of AWS resource identifiers that matches a specified query. The query uses the same format as a * resource query in a CreateGroup or UpdateGroupQuery operation. * </p> * * @param searchResourcesRequest * @return Result of the SearchResources operation returned by the service. * @throws UnauthorizedException * The request has not been applied because it lacks valid authentication credentials for the target * resource. * @throws BadRequestException * The request does not comply with validation rules that are defined for the request parameters. * @throws ForbiddenException * The caller is not authorized to make the request. * @throws MethodNotAllowedException * The request uses an HTTP method which is not allowed for the specified resource. * @throws TooManyRequestsException * The caller has exceeded throttling limits. * @throws InternalServerErrorException * An internal error occurred while processing the request. * @sample AWSResourceGroups.SearchResources * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/SearchResources" * target="_top">AWS API Documentation</a> */ @Override public SearchResourcesResult searchResources(SearchResourcesRequest request) { request = beforeClientExecution(request); return executeSearchResources(request); } @SdkInternalApi final SearchResourcesResult executeSearchResources(SearchResourcesRequest searchResourcesRequest) { ExecutionContext executionContext = createExecutionContext(searchResourcesRequest); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<SearchResourcesRequest> request = null; Response<SearchResourcesResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new SearchResourcesRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(searchResourcesRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion()); request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Resource Groups"); request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "SearchResources"); request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } HttpResponseHandler<AmazonWebServiceResponse<SearchResourcesResult>> responseHandler = protocolFactory.createResponseHandler( new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new SearchResourcesResultJsonUnmarshaller()); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * Adds tags to a resource group with the specified ARN. Existing tags on a resource group are not changed if they * are not specified in the request parameters. * </p> * * @param tagRequest * @return Result of the Tag operation returned by the service. * @throws BadRequestException * The request does not comply with validation rules that are defined for the request parameters. * @throws ForbiddenException * The caller is not authorized to make the request. * @throws NotFoundException * One or more resources specified in the request do not exist. * @throws MethodNotAllowedException * The request uses an HTTP method which is not allowed for the specified resource. * @throws TooManyRequestsException * The caller has exceeded throttling limits. * @throws InternalServerErrorException * An internal error occurred while processing the request. * @sample AWSResourceGroups.Tag * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/Tag" target="_top">AWS API * Documentation</a> */ @Override public TagResult tag(TagRequest request) { request = beforeClientExecution(request); return executeTag(request); } @SdkInternalApi final TagResult executeTag(TagRequest tagRequest) { ExecutionContext executionContext = createExecutionContext(tagRequest); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<TagRequest> request = null; Response<TagResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new TagRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(tagRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion()); request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Resource Groups"); request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "Tag"); request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } HttpResponseHandler<AmazonWebServiceResponse<TagResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata() .withPayloadJson(true).withHasStreamingSuccessResponse(false), new TagResultJsonUnmarshaller()); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * Deletes specified tags from a specified resource. * </p> * * @param untagRequest * @return Result of the Untag operation returned by the service. * @throws BadRequestException * The request does not comply with validation rules that are defined for the request parameters. * @throws ForbiddenException * The caller is not authorized to make the request. * @throws NotFoundException * One or more resources specified in the request do not exist. * @throws MethodNotAllowedException * The request uses an HTTP method which is not allowed for the specified resource. * @throws TooManyRequestsException * The caller has exceeded throttling limits. * @throws InternalServerErrorException * An internal error occurred while processing the request. * @sample AWSResourceGroups.Untag * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/Untag" target="_top">AWS API * Documentation</a> */ @Override public UntagResult untag(UntagRequest request) { request = beforeClientExecution(request); return executeUntag(request); } @SdkInternalApi final UntagResult executeUntag(UntagRequest untagRequest) { ExecutionContext executionContext = createExecutionContext(untagRequest); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<UntagRequest> request = null; Response<UntagResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new UntagRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(untagRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion()); request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Resource Groups"); request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "Untag"); request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } HttpResponseHandler<AmazonWebServiceResponse<UntagResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata() .withPayloadJson(true).withHasStreamingSuccessResponse(false), new UntagResultJsonUnmarshaller()); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * Updates an existing group with a new or changed description. You cannot update the name of a resource group. * </p> * * @param updateGroupRequest * @return Result of the UpdateGroup operation returned by the service. * @throws BadRequestException * The request does not comply with validation rules that are defined for the request parameters. * @throws ForbiddenException * The caller is not authorized to make the request. * @throws NotFoundException * One or more resources specified in the request do not exist. * @throws MethodNotAllowedException * The request uses an HTTP method which is not allowed for the specified resource. * @throws TooManyRequestsException * The caller has exceeded throttling limits. * @throws InternalServerErrorException * An internal error occurred while processing the request. * @sample AWSResourceGroups.UpdateGroup * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/UpdateGroup" target="_top">AWS * API Documentation</a> */ @Override public UpdateGroupResult updateGroup(UpdateGroupRequest request) { request = beforeClientExecution(request); return executeUpdateGroup(request); } @SdkInternalApi final UpdateGroupResult executeUpdateGroup(UpdateGroupRequest updateGroupRequest) { ExecutionContext executionContext = createExecutionContext(updateGroupRequest); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<UpdateGroupRequest> request = null; Response<UpdateGroupResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new UpdateGroupRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(updateGroupRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion()); request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Resource Groups"); request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "UpdateGroup"); request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } HttpResponseHandler<AmazonWebServiceResponse<UpdateGroupResult>> responseHandler = protocolFactory.createResponseHandler( new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new UpdateGroupResultJsonUnmarshaller()); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * Updates the resource query of a group. * </p> * * @param updateGroupQueryRequest * @return Result of the UpdateGroupQuery operation returned by the service. * @throws BadRequestException * The request does not comply with validation rules that are defined for the request parameters. * @throws ForbiddenException * The caller is not authorized to make the request. * @throws NotFoundException * One or more resources specified in the request do not exist. * @throws MethodNotAllowedException * The request uses an HTTP method which is not allowed for the specified resource. * @throws TooManyRequestsException * The caller has exceeded throttling limits. * @throws InternalServerErrorException * An internal error occurred while processing the request. * @sample AWSResourceGroups.UpdateGroupQuery * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/UpdateGroupQuery" * target="_top">AWS API Documentation</a> */ @Override public UpdateGroupQueryResult updateGroupQuery(UpdateGroupQueryRequest request) { request = beforeClientExecution(request); return executeUpdateGroupQuery(request); } @SdkInternalApi final UpdateGroupQueryResult executeUpdateGroupQuery(UpdateGroupQueryRequest updateGroupQueryRequest) { ExecutionContext executionContext = createExecutionContext(updateGroupQueryRequest); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<UpdateGroupQueryRequest> request = null; Response<UpdateGroupQueryResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new UpdateGroupQueryRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(updateGroupQueryRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion()); request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Resource Groups"); request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "UpdateGroupQuery"); request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } HttpResponseHandler<AmazonWebServiceResponse<UpdateGroupQueryResult>> responseHandler = protocolFactory.createResponseHandler( new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new UpdateGroupQueryResultJsonUnmarshaller()); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * Returns additional metadata for a previously executed successful, request, typically used for debugging issues * where a service isn't acting as expected. This data isn't considered part of the result data returned by an * operation, so it's available through this separate, diagnostic interface. * <p> * Response metadata is only cached for a limited period of time, so if you need to access this extra diagnostic * information for an executed request, you should use this method to retrieve it as soon as possible after * executing the request. * * @param request * The originally executed request * * @return The response metadata for the specified request, or null if none is available. */ public ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest request) { return client.getResponseMetadataForRequest(request); } /** * Normal invoke with authentication. Credentials are required and may be overriden at the request level. **/ private <X, Y extends AmazonWebServiceRequest> Response<X> invoke(Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler, ExecutionContext executionContext) { return invoke(request, responseHandler, executionContext, null, null); } /** * Normal invoke with authentication. Credentials are required and may be overriden at the request level. **/ private <X, Y extends AmazonWebServiceRequest> Response<X> invoke(Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler, ExecutionContext executionContext, URI cachedEndpoint, URI uriFromEndpointTrait) { executionContext.setCredentialsProvider(CredentialUtils.getCredentialsProvider(request.getOriginalRequest(), awsCredentialsProvider)); return doInvoke(request, responseHandler, executionContext, cachedEndpoint, uriFromEndpointTrait); } /** * Invoke with no authentication. Credentials are not required and any credentials set on the client or request will * be ignored for this operation. **/ private <X, Y extends AmazonWebServiceRequest> Response<X> anonymousInvoke(Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler, ExecutionContext executionContext) { return doInvoke(request, responseHandler, executionContext, null, null); } /** * Invoke the request using the http client. Assumes credentials (or lack thereof) have been configured in the * ExecutionContext beforehand. **/ private <X, Y extends AmazonWebServiceRequest> Response<X> doInvoke(Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler, ExecutionContext executionContext, URI discoveredEndpoint, URI uriFromEndpointTrait) { if (discoveredEndpoint != null) { request.setEndpoint(discoveredEndpoint); request.getOriginalRequest().getRequestClientOptions().appendUserAgent("endpoint-discovery"); } else if (uriFromEndpointTrait != null) { request.setEndpoint(uriFromEndpointTrait); } else { request.setEndpoint(endpoint); } request.setTimeOffset(timeOffset); HttpResponseHandler<AmazonServiceException> errorResponseHandler = protocolFactory.createErrorResponseHandler(new JsonErrorResponseMetadata()); return client.execute(request, responseHandler, errorResponseHandler, executionContext); } @com.amazonaws.annotation.SdkInternalApi static com.amazonaws.protocol.json.SdkJsonProtocolFactory getProtocolFactory() { return protocolFactory; } }
semihalf-bernacki-grzegorz/bsa-acs
platform/pal_uefi_dt/src/pal_pe.c
<reponame>semihalf-bernacki-grzegorz/bsa-acs<gh_stars>1-10 /** @file * Copyright (c) 2016-2018, 2021 Arm Limited or its affiliates. All rights reserved. * SPDX-License-Identifier : Apache-2.0 * 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 <Library/BaseLib.h> #include <Library/BaseMemoryLib.h> #include <Library/UefiBootServicesTableLib.h> #include <Library/UefiLib.h> #include "Include/IndustryStandard/Acpi61.h" #include <Include/libfdt.h> #include <Protocol/AcpiTable.h> #include <Protocol/Cpu.h> #include "include/pal_uefi.h" #include "include/pal_dt.h" #include "include/pal_dt_spec.h" static EFI_ACPI_6_1_MULTIPLE_APIC_DESCRIPTION_TABLE_HEADER *gMadtHdr; UINT8 *gSecondaryPeStack; UINT64 gMpidrMax; static UINT32 g_num_pe; static char pmu_dt_arr[][PMU_COMPATIBLE_STR_LEN] = { "arm,armv8-pmuv3", "arm,cortex-a73-pmu", "arm,cortex-a72-pmu", "arm,cortex-a57-pmu", "arm,cortex-a53-pmu", "arm,cortex-a35-pmu", "arm,cortex-a17-pmu", "arm,cortex-a15-pmu", "arm,cortex-a12-pmu", "arm,cortex-a9-pmu", "arm,cortex-a8-pmu", "arm,cortex-a7-pmu", "arm,cortex-a5-pmu", "arm,arm11mpcore-pmu", "arm,arm1176-pmu", "arm,arm1136-pmu" }; #define SIZE_STACK_SECONDARY_PE 0x100 //256 bytes per core #define UPDATE_AFF_MAX(src,dest,mask) ((dest & mask) > (src & mask) ? (dest & mask) : (src & mask)) UINT64 pal_get_madt_ptr(); VOID ArmCallSmc ( IN OUT ARM_SMC_ARGS *Args ); /** @brief Return the base address of the region allocated for Stack use for the Secondary PEs. @param None @return base address of the Stack **/ UINT64 PalGetSecondaryStackBase() { return (UINT64)gSecondaryPeStack; } /** @brief Return the number of PEs in the System. @param None @return num_of_pe **/ UINT32 pal_pe_get_num() { return (UINT32)g_num_pe; } /** @brief Returns the Max of each 8-bit Affinity fields in MPIDR. @param None @return Max MPIDR **/ UINT64 PalGetMaxMpidr() { return gMpidrMax; } /** @brief Allocate memory region for secondary PE stack use. SIZE of stack for each PE is a #define @param mpidr Pass MIPDR register content @return None **/ VOID PalAllocateSecondaryStack(UINT64 mpidr) { EFI_STATUS Status; UINT32 NumPe, Aff0, Aff1, Aff2, Aff3; Aff0 = ((mpidr & 0x00000000ff) >> 0); Aff1 = ((mpidr & 0x000000ff00) >> 8); Aff2 = ((mpidr & 0x0000ff0000) >> 16); Aff3 = ((mpidr & 0xff00000000) >> 32); NumPe = ((Aff3+1) * (Aff2+1) * (Aff1+1) * (Aff0+1)); if (gSecondaryPeStack == NULL) { Status = gBS->AllocatePool ( EfiBootServicesData, (NumPe * SIZE_STACK_SECONDARY_PE), (VOID **) &gSecondaryPeStack); if (EFI_ERROR(Status)) { bsa_print(ACS_PRINT_ERR, L"\n FATAL - Allocation for Seconday stack failed %x \n", Status); } pal_pe_data_cache_ops_by_va((UINT64)&gSecondaryPeStack, CLEAN_AND_INVALIDATE); } } /** @brief This API fills in the PE_INFO Table with information about the PEs in the system. This is achieved by parsing the ACPI - MADT table. @param PeTable - Address where the PE information needs to be filled. @return None **/ VOID pal_pe_create_info_table(PE_INFO_TABLE *PeTable) { EFI_ACPI_6_1_GIC_STRUCTURE *Entry = NULL; PE_INFO_ENTRY *Ptr = NULL; UINT32 TableLength = 0; UINT32 Length = 0; UINT64 MpidrAff0Max = 0, MpidrAff1Max = 0, MpidrAff2Max = 0, MpidrAff3Max = 0; if (PeTable == NULL) { bsa_print(ACS_PRINT_ERR, L" Input PE Table Pointer is NULL. Cannot create PE INFO \n"); return; } pal_pe_create_info_table_dt(PeTable); return; gMadtHdr = (EFI_ACPI_6_1_MULTIPLE_APIC_DESCRIPTION_TABLE_HEADER *) pal_get_madt_ptr(); if (gMadtHdr != NULL) { TableLength = gMadtHdr->Header.Length; bsa_print(ACS_PRINT_INFO, L" MADT is at %x and length is %x \n", gMadtHdr, TableLength); } PeTable->header.num_of_pe = 0; Entry = (EFI_ACPI_6_1_GIC_STRUCTURE *) (gMadtHdr + 1); Length = sizeof (EFI_ACPI_6_1_MULTIPLE_APIC_DESCRIPTION_TABLE_HEADER); Ptr = PeTable->pe_info; do { if (Entry->Type == EFI_ACPI_6_1_GIC) { //Fill in the cpu num and the mpidr in pe info table Ptr->mpidr = Entry->MPIDR; Ptr->pe_num = PeTable->header.num_of_pe; Ptr->pmu_gsiv = Entry->PerformanceInterruptGsiv; bsa_print(ACS_PRINT_DEBUG, L" MPIDR %x PE num %d \n", Ptr->mpidr, Ptr->pe_num); pal_pe_data_cache_ops_by_va((UINT64)Ptr, CLEAN_AND_INVALIDATE); Ptr++; PeTable->header.num_of_pe++; MpidrAff0Max = UPDATE_AFF_MAX(MpidrAff0Max, Entry->MPIDR, 0x000000ff); MpidrAff1Max = UPDATE_AFF_MAX(MpidrAff1Max, Entry->MPIDR, 0x0000ff00); MpidrAff2Max = UPDATE_AFF_MAX(MpidrAff2Max, Entry->MPIDR, 0x00ff0000); MpidrAff3Max = UPDATE_AFF_MAX(MpidrAff3Max, Entry->MPIDR, 0xff00000000); } Length += Entry->Length; Entry = (EFI_ACPI_6_1_GIC_STRUCTURE *) ((UINT8 *)Entry + (Entry->Length)); }while(Length < TableLength); gMpidrMax = MpidrAff0Max | MpidrAff1Max | MpidrAff2Max | MpidrAff3Max; g_num_pe = PeTable->header.num_of_pe; pal_pe_data_cache_ops_by_va((UINT64)PeTable, CLEAN_AND_INVALIDATE); pal_pe_data_cache_ops_by_va((UINT64)&gMpidrMax, CLEAN_AND_INVALIDATE); PalAllocateSecondaryStack(gMpidrMax); } /** @brief Install Exception Handler using UEFI CPU Architecture protocol's Register Interrupt Handler API @param ExceptionType - AARCH64 Exception type @param esr - Function pointer of the exception handler @return status of the API **/ UINT32 pal_pe_install_esr(UINT32 ExceptionType, VOID (*esr)(UINT64, VOID *)) { EFI_STATUS Status; EFI_CPU_ARCH_PROTOCOL *Cpu; // Get the CPU protocol that this driver requires. Status = gBS->LocateProtocol (&gEfiCpuArchProtocolGuid, NULL, (VOID **)&Cpu); if (EFI_ERROR (Status)) { return Status; } // Unregister the default exception handler. Status = Cpu->RegisterInterruptHandler (Cpu, ExceptionType, NULL); if (EFI_ERROR (Status)) { return Status; } // Register to receive interrupts Status = Cpu->RegisterInterruptHandler (Cpu, ExceptionType, (EFI_CPU_INTERRUPT_HANDLER)esr); if (EFI_ERROR (Status)) { return Status; } return EFI_SUCCESS; } /** @brief Make the SMC call using AARCH64 Assembly code SMC calls can take up to 7 arguments and return up to 4 return values. Therefore, the 4 first fields in the ARM_SMC_ARGS structure are used for both input and output values. @param Argumets to pass to the EL3 firmware @return None **/ VOID pal_pe_call_smc(ARM_SMC_ARGS *ArmSmcArgs) { ArmCallSmc (ArmSmcArgs); } VOID ModuleEntryPoint(); /** @brief Make a PSCI CPU_ON call using SMC instruction. Pass PAL Assembly code entry as the start vector for the PSCI ON call @param Argumets to pass to the EL3 firmware @return None **/ VOID pal_pe_execute_payload(ARM_SMC_ARGS *ArmSmcArgs) { ArmSmcArgs->Arg2 = (UINT64)ModuleEntryPoint; pal_pe_call_smc(ArmSmcArgs); } /** @brief Update the ELR to return from exception handler to a desired address @param context - exception context structure @param offset - address with which ELR should be updated @return None **/ VOID pal_pe_update_elr(VOID *context, UINT64 offset) { ((EFI_SYSTEM_CONTEXT_AARCH64*)context)->ELR = offset; } /** @brief Get the Exception syndrome from UEFI exception handler @param context - exception context structure @return ESR **/ UINT64 pal_pe_get_esr(VOID *context) { return ((EFI_SYSTEM_CONTEXT_AARCH64*)context)->ESR; } /** @brief Get the FAR from UEFI exception handler @param context - exception context structure @return FAR **/ UINT64 pal_pe_get_far(VOID *context) { return ((EFI_SYSTEM_CONTEXT_AARCH64*)context)->FAR; } VOID DataCacheCleanInvalidateVA(UINT64 addr); VOID DataCacheCleanVA(UINT64 addr); VOID DataCacheInvalidateVA(UINT64 addr); /** @brief Perform cache maintenance operation on an address @param addr - address on which cache ops to be performed @param type - type of cache ops @return None **/ VOID pal_pe_data_cache_ops_by_va(UINT64 addr, UINT32 type) { switch(type){ case CLEAN_AND_INVALIDATE: DataCacheCleanInvalidateVA(addr); break; case CLEAN: DataCacheCleanVA(addr); break; case INVALIDATE: DataCacheInvalidateVA(addr); break; default: DataCacheCleanInvalidateVA(addr); } } /** @brief This API fills in the PE_INFO_TABLE with information about PMU in the system. This is achieved by parsing the DT. @param PeTable - Address where the PMU information needs to be filled. @return None **/ VOID pal_pe_info_table_pmu_gsiv_dt(PE_INFO_TABLE *PeTable) { int i, offset, prop_len; UINT64 dt_ptr = 0; UINT32 *Pintr; int index = 0; int interrupt_cell, interrupt_frame_count; PE_INFO_ENTRY *Ptr = NULL; int intr_type = 0; int curr_pmu_intr_num = 0, prev_pmu_intr_num = 0; if (PeTable == NULL) return; dt_ptr = pal_get_dt_ptr(); if (dt_ptr == 0) { bsa_print(ACS_PRINT_ERR, L" dt_ptr is NULL \n"); return; } Ptr = PeTable->pe_info; for (i = 0; i < (sizeof(pmu_dt_arr)/PMU_COMPATIBLE_STR_LEN); i++) { /* Search for pmu nodes*/ offset = fdt_node_offset_by_compatible((const void *)dt_ptr, -1, pmu_dt_arr[i]); if (offset < 0) { bsa_print(ACS_PRINT_DEBUG, L" PMU compatible value not found for index:%d\n", i); continue; /* Search for next compatible item*/ } while (offset != -FDT_ERR_NOTFOUND) { /* Get interrupts property from frame */ Pintr = (UINT32 *) fdt_getprop_namelen((void *)dt_ptr, offset, "interrupts", 10, &prop_len); if ((prop_len < 0) || (Pintr == NULL)) { bsa_print(ACS_PRINT_ERR, L" PROPERTY interrupts offset %x, Error %d\n", offset, prop_len); return; } interrupt_cell = fdt_interrupt_cells((const void *)dt_ptr, offset); bsa_print(ACS_PRINT_DEBUG, L" interrupt_cell %d\n", interrupt_cell); if (interrupt_cell < INTERRUPT_CELLS_MIN || interrupt_cell > INTERRUPT_CELLS_MAX) { bsa_print(ACS_PRINT_ERR, L" Invalid interrupt cell : %d \n", interrupt_cell); return; } interrupt_frame_count = ((prop_len/sizeof(int))/interrupt_cell); bsa_print(ACS_PRINT_DEBUG, L" interrupt frame count : %d \n", interrupt_frame_count); if (interrupt_frame_count == 0) { bsa_print(ACS_PRINT_ERR, L" interrupt_frame_count is invalid\n"); return; } index = 0; /* Handle PMU node with multiple/single SPI/PPI frames * the pmu_gsiv should be in same order of CPU nodes */ for (i = 0; i < interrupt_frame_count; i++) { if ((interrupt_cell == 3) || (interrupt_cell == 4)) { intr_type = fdt32_to_cpu(Pintr[index++]); curr_pmu_intr_num = fdt32_to_cpu(Pintr[index++]); index++; /*Skip flag*/ if (interrupt_cell == 4) index++; /*Skip CPU affinity */ } else { /* Skip PMU node , if interrupt type not mentioned*/ Ptr = PeTable->pe_info; for (i = 0; i < PeTable->header.num_of_pe; i++) { Ptr->pmu_gsiv = 0; /* Set to zero*/ Ptr++; } bsa_print(ACS_PRINT_WARN, L" PMU interrupt type not mentioned\n"); return; } bsa_print(ACS_PRINT_DEBUG, L" intr_type : %d \n", intr_type); bsa_print(ACS_PRINT_DEBUG, L" pmu_intr_num : %d \n", curr_pmu_intr_num); if (intr_type == INTERRUPT_TYPE_PPI) { curr_pmu_intr_num += PPI_OFFSET; if ((prev_pmu_intr_num != 0) && (curr_pmu_intr_num != prev_pmu_intr_num)) { Ptr = PeTable->pe_info; for (i = 0; i < PeTable->header.num_of_pe; i++) { Ptr->pmu_gsiv = 0; /* Set to zero*/ Ptr++; } bsa_print(ACS_PRINT_WARN, L" PMU interrupt number mismatch found\n"); return; } if (prev_pmu_intr_num == 0) { /* Update table first time with same id*/ for (i = 0; i < PeTable->header.num_of_pe; i++) { Ptr->pmu_gsiv = curr_pmu_intr_num; Ptr++; } } prev_pmu_intr_num = curr_pmu_intr_num; } else { curr_pmu_intr_num += SPI_OFFSET; Ptr->pmu_gsiv = curr_pmu_intr_num; Ptr++; } } offset = fdt_node_offset_by_compatible((const void *)dt_ptr, offset, pmu_dt_arr[i]); } } } /** @brief This API fills in the PE_INFO Table with information about the PEs in the system. This is achieved by parsing the DT blob. @param PeTable - Address where the PE information needs to be filled. @return None **/ VOID pal_pe_create_info_table_dt(PE_INFO_TABLE *PeTable) { PE_INFO_ENTRY *Ptr = NULL; UINT64 dt_ptr; UINT32 *prop_val; UINT32 reg_val[2]; UINT64 MpidrAff0Max = 0, MpidrAff1Max = 0, MpidrAff2Max = 0, MpidrAff3Max = 0; int prop_len, addr_cell, size_cell; int offset, parent_offset; dt_ptr = pal_get_dt_ptr(); if (dt_ptr == 0) { bsa_print(ACS_PRINT_ERR, L" dt_ptr is NULL\n"); return; } PeTable->header.num_of_pe = 0; /* Find the first cpu node offset in DT blob */ offset = fdt_node_offset_by_prop_value((const void *) dt_ptr, -1, "device_type", "cpu", 4); if (offset != -FDT_ERR_NOTFOUND) { parent_offset = fdt_parent_offset((const void *) dt_ptr, offset); bsa_print(ACS_PRINT_DEBUG, L" NODE cpu offset %d\n", offset); size_cell = fdt_size_cells((const void *) dt_ptr, parent_offset); bsa_print(ACS_PRINT_DEBUG, L" NODE cpu size cell %d\n", size_cell); if (size_cell != 0) { bsa_print(ACS_PRINT_ERR, L" Invalid size cell for node cpu\n"); return; } addr_cell = fdt_address_cells((const void *) dt_ptr, parent_offset); bsa_print(ACS_PRINT_DEBUG, L" NODE cpu addr cell %d\n", addr_cell); if (addr_cell <= 0 || addr_cell > 2) { bsa_print(ACS_PRINT_ERR, L" Invalid address cell for node cpu\n"); return; } } else { bsa_print(ACS_PRINT_ERR, L" No CPU node found \n"); return; } Ptr = PeTable->pe_info; /* Perform a DT traversal till all cpu node are parsed */ while (offset != -FDT_ERR_NOTFOUND) { bsa_print(ACS_PRINT_DEBUG, L" SUBNODE cpu%d offset %x\n", PeTable->header.num_of_pe, offset); prop_val = (UINT32 *)fdt_getprop_namelen((void *)dt_ptr, offset, "reg", 3, &prop_len); if ((prop_len < 0) || (prop_val == NULL)) { bsa_print(ACS_PRINT_ERR, L" PROPERTY reg offset %x, Error %d\n", offset, prop_len); return; } reg_val[0] = fdt32_to_cpu(prop_val[0]); bsa_print(ACS_PRINT_DEBUG, L" reg_val<0> = %x\n", reg_val[0]); if (addr_cell == 2) { reg_val[1] = fdt32_to_cpu(prop_val[1]); bsa_print(ACS_PRINT_DEBUG, L" reg_val<1> = %x\n", reg_val[1]); Ptr->mpidr = (((INT64)(reg_val[0] & PROPERTY_MASK_PE_AFF3) << 32) | (reg_val[1] & PROPERTY_MASK_PE_AFF0_AFF2)); } else { Ptr->mpidr = (reg_val[0] & PROPERTY_MASK_PE_AFF0_AFF2); } Ptr->pe_num = PeTable->header.num_of_pe; pal_pe_data_cache_ops_by_va((UINT64)Ptr, CLEAN_AND_INVALIDATE); PeTable->header.num_of_pe++; MpidrAff0Max = UPDATE_AFF_MAX(MpidrAff0Max, Ptr->mpidr, 0x000000ff); MpidrAff1Max = UPDATE_AFF_MAX(MpidrAff1Max, Ptr->mpidr, 0x0000ff00); MpidrAff2Max = UPDATE_AFF_MAX(MpidrAff2Max, Ptr->mpidr, 0x00ff0000); MpidrAff3Max = UPDATE_AFF_MAX(MpidrAff3Max, Ptr->mpidr, 0xff00000000); Ptr++; offset = fdt_node_offset_by_prop_value((const void *) dt_ptr, offset, "device_type", "cpu", 4); } gMpidrMax = MpidrAff0Max | MpidrAff1Max | MpidrAff2Max | MpidrAff3Max; g_num_pe = PeTable->header.num_of_pe; pal_pe_info_table_pmu_gsiv_dt(PeTable); pal_pe_info_table_gmaint_gsiv_dt(PeTable); pal_pe_data_cache_ops_by_va((UINT64)PeTable, CLEAN_AND_INVALIDATE); pal_pe_data_cache_ops_by_va((UINT64)&gMpidrMax, CLEAN_AND_INVALIDATE); PalAllocateSecondaryStack(gMpidrMax); dt_dump_pe_table(PeTable); }
jagadeesh5113111/facebkk
nbp/src/main/java/jlibs/nbp/Stream.java
<gh_stars>10-100 /** * Copyright 2015 <NAME> * * The JLibs authors license this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package jlibs.nbp; /** * @author <NAME> */ public final class Stream{ final int chars[]; int begin = 0; int end = 0; public Stream(int capacity){ chars = new int[capacity+1]; } int capacity(){ return chars.length-1; } public int length(){ int len = end-begin; return len<0 ? len+chars.length : len; } public int charAt(int index){ assert index>=0 && index<length(); return chars[(begin+index)%chars.length]; } public void clear(){ begin = end = lookAhead.end = 0; } String toString(int length){ StringBuilder buff = new StringBuilder(); for(int i=0; i<length; i++){ int data = charAt(i); if(data==-1) buff.append("<EOF>"); else buff.appendCodePoint(data); } return buff.toString(); } @Override public String toString(){ return toString(length()); } public final LookAhead lookAhead = new LookAhead(); public final class LookAhead{ int end; public int length(){ int len = end-begin; return len<0 ? len+chars.length : len; } public boolean isEmpty(){ return end==begin; } public int charAt(int index){ assert index>=0 && index<length(); return chars[(begin+index)%chars.length]; } // returns true if this was a fresh data added public boolean add(int ch){ if(this.end!=Stream.this.end){ // hasNext() assert getNext()==ch : "expected char: "+ch; end = (end+1)%chars.length; return false; }else{ assert capacity()>Stream.this.length() : "Stream is Full"; chars[end] = ch; this.end = Stream.this.end = (end+1)%chars.length; return true; } } public void consumed(){ assert Stream.this.length()>0 : "nothing found to consume"; if(begin==end) // length()==0 begin = end = (begin+1)%chars.length; else begin = (begin+1)%chars.length; } public void reset(){ end = begin; } public int getNext(){ return this.end==Stream.this.end ? -2 : chars[end]; } @Override public String toString(){ return Stream.this.toString(length()); } } }
iMokhles/MyTheosHeaders
include/UIKitExtensions/UIView/Framing.h
// UIKitExtensions // // UIKitExtensions/UIView/Framing.h // // Copyright (c) 2013 <NAME> // Released under the MIT license // // Inspired by FrameAccessor // https://github.com/AlexDenisov/FrameAccessor/ #import <UIKit/UIKit.h> @interface UIView (Framing) // http://stackoverflow.com/questions/16118106/uitextview-strange-text-clipping // https://github.com/genericspecific/CKUITools/issues/8 @property CGPoint viewOrigin; @property CGSize viewSize; @property CGFloat x; @property CGFloat y; @property CGFloat height; @property CGFloat width; @property CGFloat centerX; @property CGFloat centerY; @end
b41sh/titan
db/lease.go
package db // Lease is an object that can be associated with other objects // those can share the same ttl of the lease type Lease struct { Object TouchedAt int64 }
patrodyne/hisrc-basicjaxb-annox
core/src/test/java/org/jvnet/annox/parser/tests/B.java
<reponame>patrodyne/hisrc-basicjaxb-annox package org.jvnet.annox.parser.tests; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface B { long[] longArrayField(); int[] intArrayField(); short[] shortArrayField(); char[] charArrayField(); byte[] byteArrayField(); double[] doubleArrayField(); float[] floatArrayField(); boolean[] booleanArrayField(); String[] stringArrayField(); E[] enumArrayField(); Class<?>[] classArrayField(); B.C[] annotationArrayField(); @Retention(RetentionPolicy.RUNTIME) public static @interface C { } }
janstey/fabric8
tooling/archetype-builder/src/main/java/io/fabric8/tooling/archetype/builder/Main.java
<gh_stars>0 /** * Copyright 2005-2014 Red Hat, Inc. * * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.fabric8.tooling.archetype.builder; import java.io.File; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Main { public static Logger LOG = LoggerFactory.getLogger(Main.class); public static void main(String[] args) throws Exception { try { String basedir = System.getProperty("basedir"); if (basedir == null) { basedir = "."; } File bomFile = new File(basedir, "../../pom.xml"); File karafProfilesDir = new File(basedir, "../../fabric/fabric8-karaf/src/main/resources/distro/fabric/import/fabric/profiles/").getCanonicalFile(); File catalogFile = new File(basedir, "target/classes/archetype-catalog.xml").getCanonicalFile(); File quickStartJavaSrcDir = new File(basedir, "../../quickstarts/java").getCanonicalFile(); File quickStartKarafSrcDir = new File(basedir, "../../quickstarts/karaf").getCanonicalFile(); File quickStartKarafBeginnerSrcDir = new File(basedir, "../../quickstarts/karaf/beginner").getCanonicalFile(); File quickStartKarafCxfSrcDir = new File(basedir, "../../quickstarts/karaf/cxf").getCanonicalFile(); File quickStartSpringBootSrcDir = new File(basedir, "../../quickstarts/spring-boot").getCanonicalFile(); File quickStartWarSrcDir = new File(basedir, "../../quickstarts/war").getCanonicalFile(); File outputDir = args.length > 0 ? new File(args[0]) : new File(basedir, "../archetypes"); ArchetypeBuilder builder = new ArchetypeBuilder(catalogFile); builder.setBomFile(bomFile); builder.configure(); List<String> dirs = new ArrayList<>(); try { builder.generateArchetypes("java", quickStartJavaSrcDir, outputDir, false, dirs, karafProfilesDir); builder.generateArchetypes("karaf", quickStartKarafSrcDir, outputDir, false, dirs, karafProfilesDir); builder.generateArchetypes("karaf", quickStartKarafBeginnerSrcDir, outputDir, false, dirs, karafProfilesDir); builder.generateArchetypes("karaf", quickStartKarafCxfSrcDir, outputDir, false, dirs, karafProfilesDir); builder.generateArchetypes("springboot", quickStartSpringBootSrcDir, outputDir, false, dirs, karafProfilesDir); builder.generateArchetypes("war", quickStartWarSrcDir, outputDir, false, dirs, karafProfilesDir); } finally { LOG.debug("Completed the generation. Closing!"); builder.close(); } StringBuffer sb = new StringBuffer(); for (String dir : dirs) { sb.append("\n\t<module>" + dir + "</module>"); } LOG.info("Done creating archetypes:\n{}\n\n", sb.toString()); } catch (Exception e) { LOG.error("Caught: " + e.getMessage(), e); } } }
skkuse-adv/2019Fall_team2
analysis/reverse-engineering/decompile-fitts-with-gradle-20191031-2200/src/main/java/com/google/android/gms/measurement/internal/zzbb.java
<filename>analysis/reverse-engineering/decompile-fitts-with-gradle-20191031-2200/src/main/java/com/google/android/gms/measurement/internal/zzbb.java package com.google.android.gms.measurement.internal; import com.google.android.gms.internal.measurement.zzjn; final /* synthetic */ class zzbb implements zzdv { static final zzdv zzji = new zzbb(); private zzbb() { } public final Object get() { return zzjn.zzyv(); } }
Nightwish-cn/my_leetcode
code/308.cpp
<reponame>Nightwish-cn/my_leetcode #include <bits/stdc++.h> #define INF 2000000000 using namespace std; typedef long long ll; int read(){ int f = 1, x = 0; char c = getchar(); while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar();} while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar(); return f * x; } struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; bool isLeaf(TreeNode* root) { return root->left == NULL && root->right == NULL; } struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ostream& operator << (ostream& os, const vector<int>& vec){ for (int x: vec) os << x << " "; os << endl; return os; } ostream& operator << (ostream& os, const vector<vector<int>>& vec){ for (auto& v: vec){ for (int x: v) os << x << " "; os << endl; } return os; } class NumMatrix { vector<vector<int>>& mat; vector<vector<int>> bit, tmp; int n, m; inline int lowbit(int x){ return x & (-x); } inline int query(int r, int c){ if (r < 0 || c < 0) return 0; int res = tmp[r][c]; for (int i = r + 1; i > 0; i -= lowbit(i)) for (int j = c + 1; j > 0; j -= lowbit(j)) res += bit[i - 1][j - 1]; return res; } public: NumMatrix(vector<vector<int>>& matrix): mat(matrix) { n = matrix.size(); if (!n) m = 0; else m = matrix[0].size(); bit = vector<vector<int>>(n, vector<int>(m, 0)); tmp = mat; for (int i = 0; i < n; ++i) for (int j = 1; j < m; ++j) tmp[i][j] += tmp[i][j - 1]; for (int i = 1; i < n; ++i) for (int j = 0; j < m; ++j) tmp[i][j] += tmp[i - 1][j]; } void update(int row, int col, int val) { int delta = val - mat[row][col]; for (int i = row + 1; i <= n; i += lowbit(i)) for (int j = col + 1; j <= m; j += lowbit(j)) bit[i - 1][j - 1] += delta; mat[row][col] = val; } int sumRegion(int row1, int col1, int row2, int col2) { int ans = 0; ans += query(row2, col2); ans -= query(row2, col1 - 1); ans -= query(row1 - 1, col2); ans += query(row1 - 1, col1 - 1); return ans; } }; /** * Your NumMatrix object will be instantiated and called as such: * NumMatrix* obj = new NumMatrix(matrix); * obj->update(row,col,val); * int param_2 = obj->sumRegion(row1,col1,row2,col2); */ void init(){ } void solve(){ // sol.convert(); } int main(){ init(); solve(); return 0; }
pedwards95/Springboard_Class
Notes/41.2-Demo/react-router-patterns-demo/videodemo/router-patterns/src/App.test.js
import React from 'react'; import { render, fireEvent } from '@testing-library/react'; import App from './App'; import { MemoryRouter } from 'react-router-dom' test('/about route', () => { const { getByText } = render(( <MemoryRouter initialEntries={['/about']}> <App /> </MemoryRouter> )); expect(getByText('This is the about page.')).toBeInTheDocument(); }); test('navbar links', () => { const { getByText } = render(( <MemoryRouter initialEntries={['/']}> <App /> </MemoryRouter> )); expect(getByText('This is the home page.')).toBeInTheDocument(); const link = getByText('Contact'); fireEvent.click(link); expect(getByText('This is the contact page.')).toBeInTheDocument(); });
wangwen135/rpm
rpm-common/src/main/java/com/wwh/rpm/common/config/pojo/Arguments.java
<gh_stars>0 package com.wwh.rpm.common.config.pojo; public class Arguments { private boolean enableNettyLog; private String nettyLogLevel; public boolean isEnableNettyLog() { return enableNettyLog; } public void setEnableNettyLog(boolean enableNettyLog) { this.enableNettyLog = enableNettyLog; } public String getNettyLogLevel() { return nettyLogLevel; } public void setNettyLogLevel(String nettyLogLevel) { this.nettyLogLevel = nettyLogLevel; } @Override public String toString() { return "Arguments [enableNettyLog=" + enableNettyLog + ", nettyLogLevel=" + nettyLogLevel + "]"; } public String toPrettyString() { StringBuffer sbuf = new StringBuffer(); if (enableNettyLog) { sbuf.append(" enableNettyLog = ").append(enableNettyLog).append("\n"); sbuf.append(" nettyLogLevel = ").append(nettyLogLevel).append("\n"); } return sbuf.toString(); } }
bytectl/gopkg
crypto/gconfig/gconfig_test.go
<filename>crypto/gconfig/gconfig_test.go package gconfig import "testing" func TestDecryptString(t *testing.T) { str := "enc(3LPBm9MsFrdXcJAEFX9/JA==)" key := []byte("1234567890") decrypted, err := DecryptString(str, key) if err != nil { t.Error(err) } t.Log(decrypted) } func TestEncryptString(t *testing.T) { str := "foo" key := []byte("1234567890") encrypted := EncryptString(str, key) t.Log(encrypted) }
hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism
Variant Programs/1-5/48/store/EntrepotBrimmingOutlier.java
<gh_stars>0 package store; public class EntrepotBrimmingOutlier extends Exception { public EntrepotBrimmingOutlier(String letters) { super(letters); } public EntrepotBrimmingOutlier() { super(); } static final double upstreamBorder = 0.7242031618092498; }
FoxComm/highlander
phoenix-scala/phoenix/app/phoenix/utils/seeds/generators/SeedsGenerator.scala
package phoenix.utils.seeds.generators import core.db._ import core.failures.NotFoundFailure404 import faker.Faker import objectframework.models.ObjectContexts import phoenix.models.{Reason, Reasons} import phoenix.models.account._ import phoenix.models.admin.{AdminData, AdminsData} import phoenix.models.coupon._ import phoenix.models.customer._ import phoenix.models.inventory._ import phoenix.models.location.{Address, Addresses} import phoenix.models.payment.creditcard.CreditCards import phoenix.models.product.SimpleContext import phoenix.models.promotion._ import phoenix.utils.aliases._ import slick.jdbc.PostgresProfile.api._ import scala.concurrent.ExecutionContext.Implicits.global import scala.util.Random object SeedsGenerator extends CustomerGenerator with AddressGenerator with CreditCardGenerator with OrderGenerator with GiftCardGenerator with ProductGenerator with PromotionGenerator with CouponGenerator { def generateAddresses(customers: Seq[User]): Seq[Address] = customers.flatMap { c ⇒ generateAddress(customer = c, isDefault = true) +: ((0 to Random.nextInt(2)) map { i ⇒ generateAddress(customer = c, isDefault = false) }) } def makePromotions(promotionCount: Int) = (1 to promotionCount).par.map { i ⇒ generatePromotion(Random.nextInt(2) match { case 0 ⇒ Promotion.Auto case _ ⇒ Promotion.Coupon }) }.toList def makeCoupons(promotions: Seq[SimplePromotion]) = promotions.par.map { p ⇒ generateCoupon(p) }.toList def pickOne[T](vals: Seq[T]): T = vals(Random.nextInt(vals.length)) def insertRandomizedSeeds(customersCount: Int, appeasementCount: Int)(implicit ec: EC, db: DB, ac: AC, au: AU) = { Faker.locale("en") for { context ← * <~ ObjectContexts.mustFindById404(SimpleContext.id) shipMethods ← * <~ getShipmentRules skus ← * <~ Skus.filter(_.contextId === context.id).result skuIds = skus.map(_.id) generatedCustomers = generateCustomers(customersCount) accountIds ← * <~ Accounts.createAllReturningIds(generatedCustomers.map { _ ⇒ Account() }) accountCustomers = accountIds zip generatedCustomers customers ← * <~ Users.createAllReturningModels(accountCustomers.map { case (accountId, customer) ⇒ customer.copy(accountId = accountId) }) _ ← * <~ CustomersData.createAll(customers.map { c ⇒ CustomerData(accountId = c.accountId, userId = c.id, scope = Scope.current) }) _ ← * <~ Addresses.createAll(generateAddresses(customers)) _ ← * <~ CreditCards.createAll(generateCreditCards(customers)) admin ← * <~ AdminsData.mustFindOneOr(NotFoundFailure404(AdminData, "???")) // FIXME: get this ID from an `INSERT`? @michalrus gcReason ← * <~ Reasons .filter(_.reasonType === (Reason.GiftCardCreation: Reason.ReasonType)) .mustFindOneOr(NotFoundFailure404(Reason, "???")) // FIXME: get this ID from an `INSERT`? @michalrus orderedGcs ← * <~ (1 to appeasementCount).map(_ ⇒ generateGiftCard(admin.accountId, gcReason, context)) appeasements ← * <~ (1 to appeasementCount).map(_ ⇒ generateGiftCardAppeasement(admin.accountId, gcReason)) giftCards ← * <~ orderedGcs ++ appeasements unsavedPromotions = makePromotions(1) promotions ← * <~ generatePromotions(unsavedPromotions) unsavedCoupons ← * <~ makeCoupons(promotions.filter(_.applyType == Promotion.Coupon)) coupons ← * <~ generateCoupons(unsavedCoupons) _ ← * <~ randomSubset(customers, customers.length).map { customer ⇒ generateOrders(customer.accountId, context, skuIds, pickOne(giftCards)) } } yield {} } }
heloisaldanha/FIC_IMD_Studies
Java/ifs/Atividade1.java
package ifs; import java.util.Scanner; public class Atividade1 { /** * Receber 5 números e verificar se a soma deles é múltiplo de dois. */ public static void main(String[] args) { Scanner numeros = new Scanner(System.in); int num1, num2, num3, num4, num5, soma; System.out.println("Digite 5 números inteiros:"); num1 = numeros.nextInt(); num2 = numeros.nextInt(); num3 = numeros.nextInt(); num4 = numeros.nextInt(); num5 = numeros.nextInt(); soma = num1 + num2 + num3 + num4 + num5; if (soma % 2 == 0) { System.out.printf("A soma dos números é igual a %d e é múltiplo de 2.\n", soma); } else { System.out.printf("A soma é igual a %d e não é múltiplo de 2.\n", soma); } } }
krbalag/Tamil
ezhuththu/src/main/java/my/interest/lang/tamil/punar/handler/udambadu/UadambaduMeiHandler.java
<reponame>krbalag/Tamil package my.interest.lang.tamil.punar.handler.udambadu; import tamil.lang.TamilCompoundCharacter; import my.interest.lang.tamil.punar.TamilWordPartContainer; import my.interest.lang.tamil.punar.TamilWordSplitResult; import my.interest.lang.tamil.punar.handler.AbstractPunharchiHandler; import java.util.List; /** * <p> * </p> * * @author velsubra */ public class UadambaduMeiHandler extends AbstractPunharchiHandler { public static final UadambaduMeiHandler HANDLER = new UadambaduMeiHandler(); @Override public String getName() { return "உடம்படுமெய்த்தோன்றல்"; } static final AbstractPunharchiHandler VAGARA = new VagaraUadambaduMeiHandler(); static final AbstractPunharchiHandler YAGARAM = new YagaraUadambaduMeiHandler(); @Override public List<TamilWordSplitResult> split(TamilWordPartContainer nilai, TamilWordPartContainer varumPart) { if (nilai.isKutriyaLugaram() && varumPart.isStartingWithUyirMei() && ( varumPart.isStartingWithOneConsonantOfType(TamilCompoundCharacter.IV) || varumPart.isStartingWithOneConsonantOfType(TamilCompoundCharacter.IY))) { return null; } List<TamilWordSplitResult> list = VAGARA.split(nilai, varumPart); if (list == null || list.isEmpty()) { return YAGARAM.split(nilai, varumPart); } else { return list; } } @Override public TamilWordPartContainer join(TamilWordPartContainer nilai, TamilWordPartContainer varum) { // if (nilai.isEndingWithUyir()) { // return null; // } if (nilai.isKutriyaLugaram() && varum.isStartingWithUyir()) { return null; } TamilWordPartContainer ret = YAGARAM.join(nilai, varum); if (ret == null) { return VAGARA.join(nilai, varum); } else { return ret; } } }
ngc92/branchedflowsim
src/tracer/initial_conditions/planar_wave.hpp
<reponame>ngc92/branchedflowsim<filename>src/tracer/initial_conditions/planar_wave.hpp #ifndef PLANAR_WAVE_HPP_INCLUDED #define PLANAR_WAVE_HPP_INCLUDED #include "initial_conditions.hpp" #include <random> namespace init_cond { // ----------------------------------------------------------------------------------------------------------------- // planar wave // ----------------------------------------------------------------------------------------------------------------- /*! \class PlanarWave * \brief This class represents a simple planar wave, i.e. the rays are all spawned with on a hyperplane, and with * equal velocity. * \details The initial position manifold is formed by linear combinations of the vectors in `mSpanningVectors`, * where the coefficients are simply the manifold coordinates. * The velocity has to be set separately (defaults to "along first axis"), it is not automatically set to * be perpendicular to the spanning plane (nor is that required here). * When the spanning vectors form an orthonomal basis, it is guaranteed that the sampling happens * uniformly on the initial plane. * * Tests can be found in `tracer/test/planar_init_test.cpp`. */ class PlanarWave final : public InitialConditionGenerator { public: // ctor / dtor ///! Constructor, requires the world dimension and the dimension of the manifold / wave. ///! \throw std::logic_error, if \p wave_dim > \p world_dim. PlanarWave(std::size_t world_dim, std::size_t wave_dim); virtual ~PlanarWave() = default; void generate(gen_vect& ray_position, gen_vect& ray_velocity, const manifold_pos& manifold_position) const override; // configuration void setInitialVelocity( gen_vect vel ); void setOrigin( gen_vect origin ); void setSpanningVector(unsigned long index, gen_vect vec ); const gen_vect& getInitialVelocity() const; const gen_vect& getOrigin() const; private: // spanning vectors std::vector<gen_vect> mSpanningVectors; // coordinate system origin gen_vect mOrigin; // initial velocity gen_vect mVelocity; }; // ----------------------------------------------------------------------------------------------------------------- // random planar wave // ----------------------------------------------------------------------------------------------------------------- /*! * \class RandomPlanar * \brief Planar initial condition with random starting position/velocity. * \details For every trajectory, a random direction and starting position are chosen * (unless overridden by setFixedVelocity or setFixedPosition). The "manifold" * from which the ray starts is remembered until the next trajectory is created, * which means that the derivatives can be correctly calculated. * * Tests can be found in `tracer/test/planar_init_test.cpp`. */ class RandomPlanar final : public InitialConditionGenerator { public: explicit RandomPlanar(std::size_t dim); void setFixedVelocity(gen_vect vel); void setFixedPosition(gen_vect pos); boost::optional<gen_vect> getFixedPosition() const; boost::optional<gen_vect> getFixedVelocity() const; private: // overridden/implemented behaviour void next_trajectory(const manifold_pos& pos, MultiIndex& index) override; void generate(gen_vect& ray_position, gen_vect& ray_velocity, const manifold_pos& manifold_position) const override; // helper functions void new_initial_position(); void new_initial_velocity(); // randomization stuff std::default_random_engine mRandomEngine; std::uniform_real_distribution<double> distribution{0.0, 1.0}; // configuration to fix position or velocity boost::optional<gen_vect> mInitialPosition; boost::optional<gen_vect> mInitialVelocity; // conditions for each trajectory, cached to enable generation of deltas gen_vect mCacheInitPosition; gen_vect mCacheInitVelocity; manifold_pos mCacheManifoldStart; std::vector<gen_vect> mCacheManifoldDirections; }; } #endif // PLANAR_WAVE_HPP_INCLUDED
Muhammet-Yildiz/Ecommerce_Website-HepsiOrada
Main/migrations/0017_category_slug.py
<reponame>Muhammet-Yildiz/Ecommerce_Website-HepsiOrada # Generated by Django 3.1.4 on 2021-03-02 20:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Main', '0016_product_slug'), ] operations = [ migrations.AddField( model_name='category', name='slug', field=models.SlugField(blank=True, max_length=250, null=True), ), ]
csixteen/HackerRank
Algorithms/extra_long_factorials.py
def fact(n): f = 1 for i in range(1, n+1): f *= i return f N = int(input()) print(fact(N))
bryansb/SIA
src/ec/edu/ups/jpa/accounting/JPAAccountDAO.java
<reponame>bryansb/SIA package ec.edu.ups.jpa.accounting; import ec.edu.ups.dao.accounting.AccountDAO; import ec.edu.ups.entities.accounting.Account; import ec.edu.ups.jpa.JPAGenericDAO; public class JPAAccountDAO extends JPAGenericDAO<Account, Integer> implements AccountDAO{ public JPAAccountDAO() { super(Account.class); } @Override public Account findByName(String name) { Account account; try { String[][] attributes = {{"name"}}; String[] values = {"equal&" + name}; account = super.findByPath(attributes, values, null, 0, 1, true, false).get(0); } catch (Exception e) { System.out.println(">>> Error >> JPAAccountDAO:findByName > " + e); account = null; } return account; } }
GetlingZ/GwFrame
gwframe/src/main/java/com/getling/gwframe/utils/NotifyUtil.java
package com.getling.gwframe.utils; import android.view.LayoutInflater; import androidx.annotation.StringRes; import com.blankj.utilcode.util.ActivityUtils; import com.blankj.utilcode.util.StringUtils; import com.blankj.utilcode.util.ToastUtils; import com.blankj.utilcode.util.Utils; import com.getling.gwframe.R; import com.getling.gwframe.databinding.ViewToastBinding; /** * @Author: getling * @CreateDate: 2019/11/11 13:59 * @Description: 提示吐司 */ public class NotifyUtil { public static void showWarning(Object obj) { if (obj == null) { showWarning("请求失败,请稍后重试"); return; } if (obj instanceof Integer) { showWarning(StringUtils.getString((Integer) obj)); } else { showWarning(obj.toString()); } } public static void showSuccess(Object obj) { if (obj == null) { showSuccess("操作成功"); return; } if (obj instanceof Integer) { showSuccess(StringUtils.getString((Integer) obj)); } else { showSuccess(obj.toString()); } } public static void showError(Object obj) { if (obj == null) { showError("请求失败,请稍后重试"); return; } if (obj instanceof Integer) { showError(StringUtils.getString((Integer) obj)); } else { showError(obj.toString()); } } public static void showWarning(@StringRes int id) { showWarning(StringUtils.getString(id)); } public static void showSuccess(@StringRes int id) { showSuccess(StringUtils.getString(id)); } public static void showError(@StringRes int id) { showError(StringUtils.getString(id)); } public static void showWarning(String msg) { Utils.runOnUiThread(() -> { ViewToastBinding binding = ViewToastBinding.inflate(LayoutInflater.from(ActivityUtils.getTopActivity())); binding.tvToast.setText(msg); binding.ivToast.setImageResource(R.drawable.icon_warning); ToastUtils.showCustomLong(binding.getRoot()); }); } public static void showSuccess(String msg) { Utils.runOnUiThread(() -> { ViewToastBinding binding = ViewToastBinding.inflate(LayoutInflater.from(ActivityUtils.getTopActivity())); binding.tvToast.setText(msg); binding.ivToast.setImageResource(R.drawable.icon_success); ToastUtils.showCustomLong(binding.getRoot()); }); } public static void showError(String msg) { Utils.runOnUiThread(() -> { ViewToastBinding binding = ViewToastBinding.inflate(LayoutInflater.from(ActivityUtils.getTopActivity())); binding.tvToast.setText(msg); binding.ivToast.setImageResource(R.drawable.icon_error); ToastUtils.showCustomLong(binding.getRoot()); }); } }
yangyxu-project-demo-code/auction
web/src/user/Register.js
<gh_stars>0 var React = require('react'); module.exports = React.createClass({ getInitialState: function() { return { items: [ { type: 'Input', name: 'phone', placeholder: '手机号', icon: 'fa-mobile', required: true }, { type: 'Input', name: 'email', placeholder: '邮箱', icon: 'fa-envelope-o', required: true }, { type: 'Input', attrs: { type: 'password' }, name: 'password', icon: 'fa-unlock-alt', placeholder: '0~10为数字或字母密码', required: true } ] }; }, __onBack: function (){ var _url = '/main/GoodThing'; if(this.props.request.search.forward){ _url = this.props.request.search.forward; } if(_url=='/main/My'&&!zn.react.session.getKeyValue('WAP_LOGIN_USER_TOKEN')){ _url = '/main/GoodThing'; } return zn.react.session.jump(_url), false; }, render: function(){ return ( <zn.react.Page bStyle={{backgroundColor: '#FFF'}} title="账号注册" > <div className="rt-login-page" style={{padding:10}} > <div className="form-login"> <img className="logo" src="./images/logo/logo_72.png" /> <zn.react.Form ref="form" items={this.state.items} btns={[{text:'注册', type: 'submit'}]} onSubmitSuccess={()=>{ zn.toast.success("恭喜您,注册成功!"); zn.react.session.jump('/login'); }} onSubmitError={(error)=>alert(error.result)} action="/auction/user/register" /> <div className="links"> <a href="#/login" >{'去登陆'}</a> <a href="#/forget" >{'忘记密码'}</a> </div> </div> <div className="copy-right"> <a>上海沪春互联网有限公司 @2016-2017</a> </div> </div> </zn.react.Page> ); } });
hporro/grafica_cpp
third_party/OpenMesh-8.1/Documentation/a03073.js
var a03073 = [ [ "HeapT", "a03073.html#a24a2c62d488a9a9e73572ad7820a8e68", null ], [ "HeapT", "a03073.html#a03ec9a9ca32d9d6409e980b90d53f54b", null ], [ "~HeapT", "a03073.html#a7e0a462d94cdd0c68aeeaaeadfa78d2d", null ], [ "check", "a03073.html#a3acd94c1497f8b6afd9548ffd64e2318", null ], [ "clear", "a03073.html#afef1992d5a553b9e8d152af61b9e4fc2", null ], [ "empty", "a03073.html#a536a85f292f05b98593afbb682e54471", null ], [ "front", "a03073.html#a9a19c24235081b7e5fcdbc1ee59453c3", null ], [ "getInterface", "a03073.html#aba777f483777c18a4ce9d7a6a87993c8", null ], [ "getInterface", "a03073.html#ab1c146d6ec9a3460e077d63c759437eb", null ], [ "insert", "a03073.html#a986a09f8eef49ee033663b59fa068c22", null ], [ "is_stored", "a03073.html#af286643ed54c1f7252989b2a525c0c07", null ], [ "pop_front", "a03073.html#aa0f851857c3aee86ea1eb763a5980660", null ], [ "remove", "a03073.html#ac141346bca01e86f1f7d9e4f0f2a9d8c", null ], [ "reserve", "a03073.html#ab25df952eaf2a9195243759dab1c252e", null ], [ "reset_heap_position", "a03073.html#a35feb375cbcf48457e8e2d6307fe7fba", null ], [ "size", "a03073.html#a2c81430f8b72e3aae305b025d83c3307", null ], [ "update", "a03073.html#a5a4198bf734a87481ee5fedc46f2eebd", null ], [ "interface_", "a03073.html#afb629f999cdff18c71780372ffa4a655", null ] ];
kontrollanten/sleipner
src/main/index.js
import path from 'path'; import { app, BrowserWindow, ipcMain, globalShortcut, Menu } from 'electron'; import electronDebug from 'electron-debug'; import tray from './tray'; import installExtension, { REACT_DEVELOPER_TOOLS, REDUX_DEVTOOLS } from 'electron-devtools-installer'; import menu from './menu'; const isDev = process.env.NAME === 'development'; if (isDev) { electronDebug({enabled: true}); require('electron-context-menu')(); } let mainWindow; const isAlreadyRunning = app.makeSingleInstance(() => true); if (isAlreadyRunning) { app.exit(); } function createMainWindow() { const win = new BrowserWindow({ title: app.getName(), show: false, width: isDev ? 1000 : 500, height: isDev ? 800 : 150, frame: false, icon: process.platform === 'linux' && path.join(__dirname, 'images/Icon.png'), alwaysOnTop: !isDev, webPreferences: { preload: './renderer.js', nodeIntegration: true, plugins: true } }); if (isDev) { win.loadURL('http://localhost:8080'); } else { win.loadURL('file://'.concat(__dirname, '/index.html')); } return win; } app.on('ready', () => { if (isDev) { /* eslint-disable no-console */ [REDUX_DEVTOOLS, REACT_DEVELOPER_TOOLS] .forEach(extension => installExtension(extension) .then((name) => console.log(`Added Extension: ${name}`)) .catch((err) => console.log('An error occurred: ', err)) ); /* eslint-enable no-console */ } Menu.setApplicationMenu(menu); tray.create(mainWindow); const openCmd = globalShortcut.register('CommandOrControl+X', () => { if (!mainWindow) { mainWindow = createMainWindow(); } mainWindow.show(); // eslint-disable-next-line no-console console.log('CommandOrControl+X is pressed'); }); if (!openCmd) { // eslint-disable-next-line no-console console.error('registration failed'); } ipcMain.on('resize', (e, height) => { mainWindow.setSize(1000, height); }); mainWindow = createMainWindow(); mainWindow.show(); }); ipcMain.on('hide-window', () => mainWindow.hide());
agoncal/agoncal-fascicle-jpa
mapping/ex03/src/test/java/org/agoncal/fascicle/jpa/mapping/BookTest.java
package org.agoncal.fascicle.jpa.mapping; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author <NAME> * http://www.antoniogoncalves.org * -- */ public class BookTest extends AbstractPersistentTest { // ====================================== // = Unit tests = // ====================================== @Test public void shouldCreateABook() throws Exception { Book book = new Book("The Hitchhiker's Guide to the Galaxy", 12.5F, "The Hitchhiker's Guide to the Galaxy is a science fiction comedy series created by Douglas Adams.", "1-84023-742-2", 354, false); tx.begin(); em.persist(book); tx.commit(); assertNotNull(book.getId(), "Id should not be null"); } @Test @Disabled("updatable = false does not work") public void titleShouldNotBeUpdatable() throws Exception { Book book = new Book("The Hitchhiker's Guide to the Galaxy", 12.5F, "The Hitchhiker's Guide to the Galaxy is a science fiction comedy series created by Douglas Adams.", "1-84023-742-2", 354, false); tx.begin(); em.persist(book); tx.commit(); assertNotNull(book.getId(), "Id should not be null"); assertEquals("Title should be The Hitchhiker's Guide to the Galaxy", "The Hitchhiker's Guide to the Galaxy", book.getTitle()); tx.begin(); book = em.find(Book.class, book.getId()); assertEquals("Title should be The Hitchhiker's Guide to the Galaxy", "The Hitchhiker's Guide to the Galaxy", book.getTitle()); book.setTitle("H2G2"); assertEquals("Title should be H2G2", "H2G2", book.getTitle()); tx.commit(); tx.begin(); book = em.find(Book.class, book.getId()); assertEquals("Title should be The Hitchhiker's Guide to the Galaxy", "The Hitchhiker's Guide to the Galaxy", book.getTitle()); tx.commit(); } }
klisly/fingerpoetry-android
app/src/main/java/com/klisly/bookbox/ui/activity/HomeActivity.java
package com.klisly.bookbox.ui.activity; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.design.widget.NavigationView; import android.support.v4.app.FragmentActivity; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.view.MenuItem; import android.view.View; import android.widget.FrameLayout; import android.widget.TextView; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.view.SimpleDraweeView; import com.klisly.bookbox.BookBoxApplication; import com.klisly.bookbox.BusProvider; import com.klisly.bookbox.Constants; import com.klisly.bookbox.R; import com.klisly.bookbox.api.AccountApi; import com.klisly.bookbox.api.BookRetrofit; import com.klisly.bookbox.domain.ApiResult; import com.klisly.bookbox.domain.LoginData; import com.klisly.bookbox.logic.AccountLogic; import com.klisly.bookbox.model.User; import com.klisly.bookbox.model.Version; import com.klisly.bookbox.ottoevent.LoginEvent; import com.klisly.bookbox.ottoevent.LogoutEvent; import com.klisly.bookbox.ottoevent.ToLoginEvent; import com.klisly.bookbox.subscriber.AbsSubscriber; import com.klisly.bookbox.subscriber.ApiException; import com.klisly.bookbox.ui.base.BaseMainFragment; import com.klisly.bookbox.ui.fragment.AboutFragment; import com.klisly.bookbox.ui.fragment.SettingFragment; import com.klisly.bookbox.ui.fragment.account.LoginFragment; import com.klisly.bookbox.ui.fragment.topic.ChooseTopicFragment; import com.klisly.bookbox.ui.fragment.topic.JokeFragment; import com.klisly.bookbox.ui.fragment.magzine.MagFragment; import com.klisly.bookbox.ui.fragment.novel.NovelFragment; import com.klisly.bookbox.ui.fragment.site.SiteFragment; import com.klisly.bookbox.ui.fragment.user.MineFragment; import com.klisly.bookbox.ui.fragment.wx.WxFragment; import com.klisly.bookbox.utils.ActivityUtil; import com.klisly.bookbox.utils.ToastHelper; import com.klisly.bookbox.widget.update.AppUtils; import com.klisly.bookbox.widget.update.UpdateDialog; import com.squareup.otto.Subscribe; import com.umeng.message.PushAgent; import java.util.HashMap; import java.util.Map; import butterknife.Bind; import butterknife.ButterKnife; import cn.sharesdk.framework.ShareSDK; import me.yokeyword.fragmentation.SupportActivity; import me.yokeyword.fragmentation.SupportFragment; import me.yokeyword.fragmentation.anim.FragmentAnimator; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import timber.log.Timber; public class HomeActivity extends SupportActivity implements NavigationView.OnNavigationItemSelectedListener, BaseMainFragment.OnFragmentOpenDrawerListener { public static final String TAG = HomeActivity.class.getSimpleName(); @Bind(R.id.drawer_layout) DrawerLayout mDrawer; @Bind(R.id.vNavigation) NavigationView mNavigationView; private TextView mTvName; // NavigationView上的名字 private SimpleDraweeView mImgNav; // NavigationView上的头像 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PushAgent.getInstance(getApplicationContext()).onAppStart(); ShareSDK.initSDK(this); Fresco.initialize(this); setContentView(R.layout.activity_main); ButterKnife.bind(this); initView(); checkUpdate(); checkPermission(); mNavigationView.setCheckedItem(R.id.menu_weixin); loadRootFragment(R.id.fl_container, WxFragment.newInstance()); if (savedInstanceState == null) { jumpChooseTopic(); } new Handler().postDelayed(() -> checkNotify(getIntent()), 200); } private void jumpChooseTopic() { String home = BookBoxApplication.getInstance().getPreferenceUtils().getValue(Constants.HOME_FRAG, Constants.FRAG_WX); final SupportFragment topFragment = (SupportFragment) getTopFragment(); if (home.equals(Constants.FRAG_NOVEL)) { mNavigationView.setCheckedItem(R.id.menu_novel); NovelFragment fragment = findFragment(NovelFragment.class); topFragment.start(fragment, SupportFragment.SINGLETASK); } else if (home.equals(Constants.FRAG_SITE)) { mNavigationView.setCheckedItem(R.id.menu_site); SiteFragment fragment = findFragment(SiteFragment.class); topFragment.start(fragment, SupportFragment.SINGLETASK); } else if (home.equals(Constants.FRAG_JOKE)) { mNavigationView.setCheckedItem(R.id.menu_joke); JokeFragment fragment = findFragment(JokeFragment.class); topFragment.start(fragment, SupportFragment.SINGLETASK); } else if (home.equals(Constants.FRAG_MAGZINE)) { mNavigationView.setCheckedItem(R.id.menu_magzine); MagFragment fragment = findFragment(MagFragment.class); topFragment.start(fragment, SupportFragment.SINGLETASK); } } private void checkNotify(Intent intent) { getIntent().putExtra("target", intent.getIntExtra("target", 0)); getIntent().putExtra("cid", intent.getStringExtra("cid")); try { if (intent.getIntExtra("target", 0) == Constants.NOTIFI_ACTION_MOMENT) { mNavigationView.setCheckedItem(R.id.menu_magzine); MagFragment fragment = findFragment(MagFragment.class); if (fragment == null) { popTo(WxFragment.class, false, () -> start(new MagFragment())); } else { fragment.onResume(); start(fragment, SupportFragment.SINGLETASK); } } else if (intent.getIntExtra("target", 0) == Constants.NOTIFI_ACTION_NOVEL_UPDATE) { mNavigationView.setCheckedItem(R.id.menu_novel); NovelFragment fragment = findFragment(NovelFragment.class); if (fragment == null) { popTo(WxFragment.class, false, () -> start(new NovelFragment())); } else { start(fragment, SupportFragment.SINGLETASK); fragment.onResume(); } } } catch (Exception e) { e.printStackTrace(); } } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); checkNotify(intent); } private void checkPermission() { String READ_EXTERNAL_STORAGE = "android.permission.READ_EXTERNAL_STORAGE"; String WRITE_EXTERNAL_STORAGE = "android.permission.WRITE_EXTERNAL_STORAGE"; if (checkCallingOrSelfPermission(READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && checkCallingOrSelfPermission(WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= 23) { requestPermissions(new String[]{ READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE }, 1); return; } } } private void checkUpdate() { BookRetrofit.getInstance().getSysApi().fetch("android").subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new AbsSubscriber<ApiResult<Version>>(HomeActivity.this, false) { @Override protected void onError(ApiException ex) { } @Override protected void onPermissionError(ApiException ex) { } @Override public void onNext(ApiResult<Version> data) { Timber.i("get version info " + data + " cur version code:" + AppUtils.getVersionCode(BookBoxApplication.getInstance())); if (data.getData() != null && data.getData().getVersion() > AppUtils.getVersionCode(BookBoxApplication.getInstance())) { runOnUiThread(() -> UpdateDialog.show(HomeActivity.this, data.getData().getContent().replace(":", "\n").replace(":", "\n"), data.getData().getUrl())); } } }); BookBoxApplication.getInstance() .getPreferenceUtils().setValue(Constants.LAST_CHECK, System.currentTimeMillis()); // } } @Override public FragmentAnimator onCreateFragmentAnimator() { return super.onCreateFragmentAnimator(); // 设置横向(和安卓4.x动画相同) // return new DefaultHorizontalAnimator(); // 设置自定义动画 // return new FragmentAnimator(enter,exit,popEnter,popExit); } private void initView() { ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, mDrawer, R.string.navigation_drawer_open, R.string.navigation_drawer_close); mDrawer.setDrawerListener(toggle); toggle.syncState(); mNavigationView.setNavigationItemSelectedListener(this); mNavigationView.setCheckedItem(R.id.menu_joke); FrameLayout llNavHeader = (FrameLayout) mNavigationView.getHeaderView(0); mTvName = llNavHeader.findViewById(R.id.tvNick); mImgNav = llNavHeader.findViewById(R.id.ivMenuUserAvatar); updateNavData(); llNavHeader.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDrawer.closeDrawer(GravityCompat.START); mDrawer.postDelayed(new Runnable() { @Override public void run() { if (AccountLogic.getInstance().isLogin()) { gotoMine(); } else { goToLogin(); } } }, 250); } }); } @Override protected void onResume() { super.onResume(); BusProvider.getInstance().register(this); } @Override public void onPause() { super.onPause(); BusProvider.getInstance().unregister(this); } @Override protected void onDestroy() { super.onDestroy(); ButterKnife.unbind(this); ShareSDK.stopSDK(this); Fresco.shutDown(); AccountLogic.getInstance().exit(); } long firstTime = 0; @Override public void onBackPressedSupport() { if (mDrawer.isDrawerOpen(GravityCompat.START)) { mDrawer.closeDrawer(GravityCompat.START); } else { if (getTopFragment() instanceof WxFragment) { if (firstTime + 2000 > System.currentTimeMillis()) { finish(); return; } ToastHelper.showShortTip(R.string.exit_tip); firstTime = System.currentTimeMillis(); } else { if (getTopFragment() instanceof BaseMainFragment) { mNavigationView.setCheckedItem(R.id.menu_weixin); } super.onBackPressedSupport(); } } } /** * 打开抽屉 */ @Override public void onOpenDrawer() { if (!mDrawer.isDrawerOpen(GravityCompat.START)) { mDrawer.openDrawer(GravityCompat.START); } } @Override public boolean onNavigationItemSelected(final MenuItem item) { mDrawer.closeDrawer(GravityCompat.START); mDrawer.postDelayed(new Runnable() { @Override public void run() { int id = item.getItemId(); SupportFragment fragment; switch (id) { case R.id.menu_joke: fragment = findFragment(JokeFragment.class); if (fragment == null) { popTo(WxFragment.class, false, new Runnable() { @Override public void run() { start(JokeFragment.newInstance()); } }); } else { // 如果已经在栈内,则以SingleTask模式start start(fragment, SupportFragment.SINGLETASK); } break; case R.id.menu_weixin: fragment = findFragment(WxFragment.class); start(fragment, SupportFragment.SINGLETASK); break; case R.id.menu_novel: fragment = findFragment(NovelFragment.class); if (fragment == null) { popTo(WxFragment.class, false, new Runnable() { @Override public void run() { start(NovelFragment.newInstance()); } }); } else { start(fragment, SupportFragment.SINGLETASK); } break; case R.id.menu_site: fragment = findFragment(SiteFragment.class); if (fragment == null) { popTo(WxFragment.class, false, new Runnable() { @Override public void run() { start(SiteFragment.newInstance()); } }); } else { // 如果已经在栈内,则以SingleTask模式start start(fragment, SupportFragment.SINGLETASK); } break; case R.id.menu_magzine: fragment = findFragment(MagFragment.class); if (fragment == null) { popTo(WxFragment.class, false, new Runnable() { @Override public void run() { start(new MagFragment()); } }); } else { start(fragment, SupportFragment.SINGLETASK); } break; case R.id.menu_mine: if (AccountLogic.getInstance().isLogin()) { gotoMine(); } else { goToLogin(); } break; case R.id.menu_settings: fragment = findFragment(SettingFragment.class); if (fragment == null) { popTo(WxFragment.class, false, new Runnable() { @Override public void run() { start(new SettingFragment()); } }); } else { start(fragment, SupportFragment.SINGLETASK); } break; case R.id.menu_about: fragment = findFragment(AboutFragment.class); if (fragment == null) { popTo(WxFragment.class, false, new Runnable() { @Override public void run() { start(new AboutFragment()); } }); } else { start(fragment, SupportFragment.SINGLETASK); } break; } } }, 250); return true; } private void goToLogin() { start(LoginFragment.newInstance()); } private void gotoMine() { MineFragment fragment = findFragment(MineFragment.class); if (fragment == null) { popTo(WxFragment.class, false, () -> start(MineFragment.newInstance())); } else { start(fragment, SupportFragment.SINGLETASK); } mNavigationView.setCheckedItem(R.id.menu_mine); } @Subscribe public void onToLogin(ToLoginEvent event) { goToLogin(); } @Subscribe public void onLoginSuccess(LoginEvent event) { Timber.i("receive onLoginSuccess"); updateNavData(); // CommonHelper.getTopics(this); // CommonHelper.getUserTopics(this); // CommonHelper.getSites(this); // CommonHelper.getUserSites(this); User user = AccountLogic.getInstance().getNowUser(); if (!user.getIsBasicSet() && Constants.isFirstLaunch()) { Constants.setFirstLaunch(false); user.setBasicSet(true); LoginData data = AccountLogic.getInstance().getLoginData(); data.setUser(user); AccountLogic.getInstance().setLoginData(data); AccountApi accountApi = BookRetrofit.getInstance().getAccountApi(); Map<String, Object> info = new HashMap<>(); info.put("isBasicSet", user.getIsBasicSet()); accountApi.update(info, AccountLogic.getInstance().getToken()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(initObserver(HomeActivity.this)); start(ChooseTopicFragment.newInstance(ChooseTopicFragment.ACTION_SET)); } } private Subscriber<ApiResult<User>> initObserver(FragmentActivity activity) { return new AbsSubscriber<ApiResult<User>>(activity, false) { @Override protected void onError(ApiException ex) { } @Override protected void onPermissionError(ApiException ex) { } @Override public void onNext(ApiResult<User> data) { Timber.i("start init site and topic"); } }; } @Subscribe public void onLogout(LogoutEvent event) { updateNavData(); mNavigationView.setCheckedItem(R.id.menu_joke); } private void updateNavData() { User user = AccountLogic.getInstance().getNowUser(); if (user != null) { Timber.d("cur login user:" + user); mTvName.setText(user.getName()); mImgNav.setImageURI(Uri.parse("https://second.imdao.cn" + user.getAvatar())); } else { mTvName.setText(R.string.register_login); mImgNav.setImageURI(ActivityUtil.getAppResourceUri(R.drawable.menu_user, getPackageName())); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { } }
gilvansfilho/quarkus
extensions/infinispan-client/deployment/src/main/java/io/quarkus/infinispan/client/deployment/devservices/InfinispanDevServiceProcessor.java
package io.quarkus.infinispan.client.deployment.devservices; import static io.quarkus.runtime.LaunchMode.DEVELOPMENT; import static org.infinispan.server.test.core.InfinispanContainer.DEFAULT_USERNAME; import java.io.Closeable; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.OptionalInt; import java.util.function.Supplier; import java.util.stream.Collectors; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.server.test.core.InfinispanContainer; import org.jboss.logging.Logger; import org.jetbrains.annotations.NotNull; import io.quarkus.deployment.Feature; import io.quarkus.deployment.IsNormal; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.builditem.CuratedApplicationShutdownBuildItem; import io.quarkus.deployment.builditem.DevServicesResultBuildItem; import io.quarkus.deployment.builditem.DevServicesResultBuildItem.RunningDevService; import io.quarkus.deployment.builditem.DevServicesSharedNetworkBuildItem; import io.quarkus.deployment.builditem.DockerStatusBuildItem; import io.quarkus.deployment.builditem.LaunchModeBuildItem; import io.quarkus.deployment.console.ConsoleInstalledBuildItem; import io.quarkus.deployment.console.StartupLogCompressor; import io.quarkus.deployment.dev.devservices.GlobalDevServicesConfig; import io.quarkus.deployment.logging.LoggingSetupBuildItem; import io.quarkus.devservices.common.ConfigureUtil; import io.quarkus.devservices.common.ContainerLocator; import io.quarkus.infinispan.client.deployment.InfinispanClientDevServiceBuildTimeConfig; import io.quarkus.runtime.LaunchMode; import io.quarkus.runtime.configuration.ConfigUtils; public class InfinispanDevServiceProcessor { private static final Logger log = Logger.getLogger(InfinispanDevServiceProcessor.class); /** * Label to add to shared Dev Service for Infinispan running in containers. * This allows other applications to discover the running service and use it instead of starting a new instance. */ private static final String DEV_SERVICE_LABEL = "quarkus-dev-service-infinispan"; public static final int DEFAULT_INFINISPAN_PORT = ConfigurationProperties.DEFAULT_HOTROD_PORT; private static final ContainerLocator infinispanContainerLocator = new ContainerLocator(DEV_SERVICE_LABEL, DEFAULT_INFINISPAN_PORT); private static final String DEFAULT_PASSWORD = "password"; private static final String QUARKUS = "quarkus."; private static final String DOT = "."; private static volatile List<RunningDevService> devServices; private static volatile InfinispanClientDevServiceBuildTimeConfig.DevServiceConfiguration capturedDevServicesConfiguration; private static volatile boolean first = true; @BuildStep(onlyIfNot = IsNormal.class, onlyIf = { GlobalDevServicesConfig.Enabled.class }) public List<DevServicesResultBuildItem> startInfinispanContainers(LaunchModeBuildItem launchMode, DockerStatusBuildItem dockerStatusBuildItem, List<DevServicesSharedNetworkBuildItem> devServicesSharedNetworkBuildItem, InfinispanClientDevServiceBuildTimeConfig config, Optional<ConsoleInstalledBuildItem> consoleInstalledBuildItem, CuratedApplicationShutdownBuildItem closeBuildItem, LoggingSetupBuildItem loggingSetupBuildItem, GlobalDevServicesConfig devServicesConfig) { // figure out if we need to shut down and restart existing Infinispan containers // if not and the Infinispan containers have already started we just return if (devServices != null) { boolean restartRequired = !config.devService.equals(capturedDevServicesConfiguration); if (!restartRequired) { return devServices.stream().map(RunningDevService::toBuildItem).collect(Collectors.toList()); } for (Closeable closeable : devServices) { try { closeable.close(); } catch (Throwable e) { log.error("Failed to stop infinispan container", e); } } devServices = null; capturedDevServicesConfiguration = null; } capturedDevServicesConfiguration = config.devService; List<RunningDevService> newDevServices = new ArrayList<>(); StartupLogCompressor compressor = new StartupLogCompressor( (launchMode.isTest() ? "(test) " : "") + "Infinispan Dev Services Starting:", consoleInstalledBuildItem, loggingSetupBuildItem); try { RunningDevService devService = startContainer(dockerStatusBuildItem, config.devService.devservices, launchMode.getLaunchMode(), !devServicesSharedNetworkBuildItem.isEmpty(), devServicesConfig.timeout); if (devService == null) { compressor.closeAndDumpCaptured(); return null; } newDevServices.add(devService); log.infof("The infinispan server is ready to accept connections on %s", devService.getConfig().get(getConfigPrefix() + "server-list")); compressor.close(); } catch (Throwable t) { compressor.closeAndDumpCaptured(); throw new RuntimeException(t); } devServices = newDevServices; if (first) { first = false; Runnable closeTask = () -> { if (devServices != null) { for (Closeable closeable : devServices) { try { closeable.close(); } catch (Throwable t) { log.error("Failed to stop infinispan", t); } } } first = true; devServices = null; capturedDevServicesConfiguration = null; }; closeBuildItem.addCloseTask(closeTask, true); } return devServices.stream().map(RunningDevService::toBuildItem).collect(Collectors.toList()); } private RunningDevService startContainer(DockerStatusBuildItem dockerStatusBuildItem, InfinispanDevServicesConfig devServicesConfig, LaunchMode launchMode, boolean useSharedNetwork, Optional<Duration> timeout) { if (!devServicesConfig.enabled) { // explicitly disabled log.debug("Not starting devservices for Infinispan as it has been disabled in the config"); return null; } String configPrefix = getConfigPrefix(); boolean needToStart = !ConfigUtils.isPropertyPresent(configPrefix + "server-list"); if (!needToStart) { log.debug("Not starting devservices for Infinispan as 'server-list' have been provided"); return null; } if (!dockerStatusBuildItem.isDockerAvailable()) { log.warn("Please configure 'quarkus.infinispan-client.server-list' or get a working docker instance"); return null; } Supplier<RunningDevService> defaultInfinispanServerSupplier = () -> { QuarkusInfinispanContainer infinispanContainer = new QuarkusInfinispanContainer(devServicesConfig.port, launchMode == DEVELOPMENT ? devServicesConfig.serviceName : null, useSharedNetwork, devServicesConfig.artifacts); timeout.ifPresent(infinispanContainer::withStartupTimeout); infinispanContainer.start(); return getRunningDevService(infinispanContainer.getContainerId(), infinispanContainer::close, infinispanContainer.getHost() + ":" + infinispanContainer.getPort(), infinispanContainer.getUser(), infinispanContainer.getPassword()); }; return infinispanContainerLocator.locateContainer(devServicesConfig.serviceName, devServicesConfig.shared, launchMode) .map(containerAddress -> getRunningDevService(containerAddress.getId(), null, containerAddress.getUrl(), DEFAULT_USERNAME, DEFAULT_PASSWORD)) // TODO can this be always right ? .orElseGet(defaultInfinispanServerSupplier); } @NotNull private RunningDevService getRunningDevService(String containerId, Closeable closeable, String serverList, String username, String password) { Map<String, String> config = new HashMap<>(); config.put(getConfigPrefix() + "server-list", serverList); config.put(getConfigPrefix() + "client-intelligence", "BASIC"); config.put(getConfigPrefix() + "auth-username", username); config.put(getConfigPrefix() + "auth-password", password); return new RunningDevService(Feature.INFINISPAN_CLIENT.getName(), containerId, closeable, config); } private String getConfigPrefix() { return QUARKUS + "infinispan-client" + DOT; } private static class QuarkusInfinispanContainer extends InfinispanContainer { private final OptionalInt fixedExposedPort; private final boolean useSharedNetwork; private String hostName = null; public QuarkusInfinispanContainer(OptionalInt fixedExposedPort, String serviceName, boolean useSharedNetwork, Optional<List<String>> artifacts) { super(); this.fixedExposedPort = fixedExposedPort; this.useSharedNetwork = useSharedNetwork; if (serviceName != null) { withLabel(DEV_SERVICE_LABEL, serviceName); } withUser(DEFAULT_USERNAME); withPassword(<PASSWORD>DevServiceProcessor.DEFAULT_PASSWORD); artifacts.ifPresent(a -> withArtifacts(a.toArray(new String[0]))); } @Override protected void configure() { super.configure(); if (useSharedNetwork) { hostName = ConfigureUtil.configureSharedNetwork(this, "infinispan"); return; } if (fixedExposedPort.isPresent()) { addFixedExposedPort(fixedExposedPort.getAsInt(), DEFAULT_INFINISPAN_PORT); } else { addExposedPort(DEFAULT_INFINISPAN_PORT); } } public int getPort() { if (useSharedNetwork) { return DEFAULT_INFINISPAN_PORT; } if (fixedExposedPort.isPresent()) { return fixedExposedPort.getAsInt(); } return super.getFirstMappedPort(); } public String getUser() { return DEFAULT_USERNAME; } public String getPassword() { return InfinispanDevServiceProcessor.DEFAULT_PASSWORD; } @Override public String getHost() { return useSharedNetwork ? hostName : super.getHost(); } } }
commercetools/ui-k
jest.visual.config.js
process.env.ENABLE_NEW_JSX_TRANSFORM = 'true'; /** * @type {import('@jest/types').Config.ProjectConfig} */ module.exports = { preset: 'jest-puppeteer', testRegex: './*\\.visualspec\\.js$', transform: { '^.+\\.[t|j]sx?$': 'babel-jest', }, globals: { HOST: 'http://localhost:3001', }, };
TwFlem/react-cosmos
packages/react-cosmos-playground/src/plugins/ResponsivePreview/Preview/index.js
// @flow import React, { Component } from 'react'; import { isEqual } from 'lodash'; import { Header } from './Header'; import { getPluginConfig, getPluginState, setPluginState, getFixtureViewport, storeViewportInBrowserHistory } from '../shared'; import styles from './index.less'; import type { Node } from 'react'; import type { UiContextParams } from '../../../context'; import type { Viewport } from '../types'; type Props = { children: Node, uiContext: UiContextParams }; type State = { container: ?{ width: number, height: number }, scale: boolean }; const PADDING = 16; const BORDER_WIDTH = 2; export class Preview extends Component<Props, State> { state = { container: null, scale: true }; containerEl: ?HTMLElement; componentDidUpdate() { const container = getContainerSize(this.containerEl); if (!isEqual(container, this.state.container)) { this.setState({ container }); } } handleContainerRef = (el: ?HTMLElement) => { this.containerEl = el; }; handleViewportChange = (viewport: Viewport) => { const { uiContext } = this.props; const { state, editFixture } = uiContext; const pluginState = getPluginState(uiContext); editFixture({ ...state.fixtureBody, viewport }); setPluginState( uiContext, pluginState.enabled ? { enabled: true, viewport } : { enabled: false, viewport } ); storeViewportInBrowserHistory(viewport); }; handleScaleChange = (scale: boolean) => { this.setState({ scale }); }; render() { const { children, uiContext } = this.props; const { options } = uiContext; if (options.platform !== 'web') { return children; } const { devices } = getPluginConfig(uiContext); const pluginState = getPluginState(uiContext); const fixtureViewport = getFixtureViewport(uiContext); const { container, scale } = this.state; const viewport = fixtureViewport || (pluginState.enabled && pluginState.viewport); // We can't simply say // if (!viewport) { return children }; // because this causes flicker when switching between responsive and // non responsive mode as the React component tree is completely different. // The key to preserving the child iframe is the "preview" key. if (!container || !viewport) { return ( <div className={styles.container}> <div key="preview" ref={this.handleContainerRef}> <div> <div>{children}</div> </div> </div> </div> ); } const innerContainer = { width: container.width - 2 * (PADDING + BORDER_WIDTH), height: container.height - 2 * (PADDING + BORDER_WIDTH) }; const { width, height } = viewport; const scaleWidth = Math.min(1, innerContainer.width / width); const scaleHeight = Math.min(1, innerContainer.height / height); const scaleFactor = scale ? Math.min(scaleWidth, scaleHeight) : 1; const scaledWidth = width * scaleFactor; const scaledHeight = height * scaleFactor; const outerWrapperStyle = { justifyContent: scale || scaleWidth === 1 ? 'space-around' : 'flex-start', alignItems: scale || scaleHeight === 1 ? 'center' : 'flex-start', padding: PADDING, overflow: scale ? 'hidden' : 'scroll' }; const middleWrapperStyle = { width: scaledWidth + 2 * BORDER_WIDTH, height: scaledHeight + 2 * BORDER_WIDTH }; const innerWrapperStyle = { borderWidth: BORDER_WIDTH, width: width + 2 * BORDER_WIDTH, height: height + 2 * BORDER_WIDTH, transform: `scale( ${scaleFactor} )` }; return ( <div className={styles.container}> <Header devices={devices} viewport={viewport} container={container} scale={scale} changeViewport={this.handleViewportChange} setScale={this.handleScaleChange} /> <div key="preview" className={styles.outerWrapper} ref={this.handleContainerRef} style={outerWrapperStyle} > <div style={middleWrapperStyle}> <div className={styles.innerWrapper} style={innerWrapperStyle}> {children} </div> </div> </div> </div> ); } } function getContainerSize(containerEl: ?HTMLElement) { if (!containerEl) { return null; } const { width, height } = containerEl.getBoundingClientRect(); return { width, height }; }
MassICTBV/casinocoind
src/beast/include/beast/websocket/impl/read.ipp
<filename>src/beast/include/beast/websocket/impl/read.ipp<gh_stars>1-10 // // Copyright (c) 2013-2017 <NAME> (<EMAIL> at <EMAIL> dot <EMAIL>) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BEAST_WEBSOCKET_IMPL_READ_IPP #define BEAST_WEBSOCKET_IMPL_READ_IPP #include <beast/websocket/teardown.hpp> #include <beast/core/buffer_concepts.hpp> #include <beast/core/handler_helpers.hpp> #include <beast/core/handler_ptr.hpp> #include <beast/core/prepare_buffers.hpp> #include <beast/core/static_streambuf.hpp> #include <beast/core/stream_concepts.hpp> #include <beast/core/detail/clamp.hpp> #include <boost/assert.hpp> #include <boost/optional.hpp> #include <limits> #include <memory> namespace beast { namespace websocket { //------------------------------------------------------------------------------ // Reads a single message frame, // processes any received control frames. // template<class NextLayer> template<class DynamicBuffer, class Handler> class stream<NextLayer>::read_frame_op { using fb_type = detail::frame_streambuf; using fmb_type = typename fb_type::mutable_buffers_type; using dmb_type = typename DynamicBuffer::mutable_buffers_type; struct data : op { bool cont; stream<NextLayer>& ws; frame_info& fi; DynamicBuffer& db; fb_type fb; std::uint64_t remain; detail::frame_header fh; detail::prepared_key key; boost::optional<dmb_type> dmb; boost::optional<fmb_type> fmb; int state = 0; data(Handler& handler, stream<NextLayer>& ws_, frame_info& fi_, DynamicBuffer& sb_) : cont(beast_asio_helpers:: is_continuation(handler)) , ws(ws_) , fi(fi_) , db(sb_) { } }; handler_ptr<data, Handler> d_; public: read_frame_op(read_frame_op&&) = default; read_frame_op(read_frame_op const&) = default; template<class DeducedHandler, class... Args> read_frame_op(DeducedHandler&& h, stream<NextLayer>& ws, Args&&... args) : d_(std::forward<DeducedHandler>(h), ws, std::forward<Args>(args)...) { (*this)(error_code{}, 0, false); } void operator()() { (*this)(error_code{}, 0, true); } void operator()(error_code const& ec) { (*this)(ec, 0, true); } void operator()(error_code ec, std::size_t bytes_transferred); void operator()(error_code ec, std::size_t bytes_transferred, bool again); friend void* asio_handler_allocate( std::size_t size, read_frame_op* op) { return beast_asio_helpers:: allocate(size, op->d_.handler()); } friend void asio_handler_deallocate( void* p, std::size_t size, read_frame_op* op) { return beast_asio_helpers:: deallocate(p, size, op->d_.handler()); } friend bool asio_handler_is_continuation(read_frame_op* op) { return op->d_->cont; } template<class Function> friend void asio_handler_invoke(Function&& f, read_frame_op* op) { return beast_asio_helpers:: invoke(f, op->d_.handler()); } }; template<class NextLayer> template<class DynamicBuffer, class Handler> void stream<NextLayer>::read_frame_op<DynamicBuffer, Handler>:: operator()(error_code ec, std::size_t bytes_transferred) { auto& d = *d_; if(ec) d.ws.failed_ = true; (*this)(ec, bytes_transferred, true); } template<class NextLayer> template<class DynamicBuffer, class Handler> void stream<NextLayer>::read_frame_op<DynamicBuffer, Handler>:: operator()(error_code ec, std::size_t bytes_transferred, bool again) { using beast::detail::clamp; using boost::asio::buffer; enum { do_start = 0, do_read_payload = 1, do_inflate_payload = 30, do_frame_done = 4, do_read_fh = 5, do_control_payload = 8, do_control = 9, do_pong_resume = 10, do_pong = 12, do_close_resume = 14, do_close = 16, do_teardown = 17, do_fail = 19, do_call_handler = 99 }; auto& d = *d_; if(! ec) { d.cont = d.cont || again; close_code::value code = close_code::none; do { switch(d.state) { case do_start: if(d.ws.failed_) { d.state = do_call_handler; d.ws.get_io_service().post( bind_handler(std::move(*this), boost::asio::error::operation_aborted, 0)); return; } d.state = do_read_fh; break; //------------------------------------------------------------------ case do_read_payload: if(d.fh.len == 0) { d.state = do_frame_done; break; } // Enforce message size limit if(d.ws.rd_msg_max_ && d.fh.len > d.ws.rd_msg_max_ - d.ws.rd_.size) { code = close_code::too_big; d.state = do_fail; break; } d.ws.rd_.size += d.fh.len; d.remain = d.fh.len; if(d.fh.mask) detail::prepare_key(d.key, d.fh.key); // fall through case do_read_payload + 1: d.state = do_read_payload + 2; d.dmb = d.db.prepare(clamp(d.remain)); // Read frame payload data d.ws.stream_.async_read_some( *d.dmb, std::move(*this)); return; case do_read_payload + 2: { d.remain -= bytes_transferred; auto const pb = prepare_buffers( bytes_transferred, *d.dmb); if(d.fh.mask) detail::mask_inplace(pb, d.key); if(d.ws.rd_.op == opcode::text) { if(! d.ws.rd_.utf8.write(pb) || (d.remain == 0 && d.fh.fin && ! d.ws.rd_.utf8.finish())) { // invalid utf8 code = close_code::bad_payload; d.state = do_fail; break; } } d.db.commit(bytes_transferred); if(d.remain > 0) { d.state = do_read_payload + 1; break; } d.state = do_frame_done; break; } //------------------------------------------------------------------ case do_inflate_payload: d.remain = d.fh.len; if(d.fh.len == 0) { // inflate even if fh.len == 0, otherwise we // never emit the end-of-stream deflate block. bytes_transferred = 0; d.state = do_inflate_payload + 2; break; } if(d.fh.mask) detail::prepare_key(d.key, d.fh.key); // fall through case do_inflate_payload + 1: { d.state = do_inflate_payload + 2; // Read compressed frame payload data d.ws.stream_.async_read_some( buffer(d.ws.rd_.buf.get(), clamp( d.remain, d.ws.rd_.buf_size)), std::move(*this)); return; } case do_inflate_payload + 2: { d.remain -= bytes_transferred; auto const in = buffer( d.ws.rd_.buf.get(), bytes_transferred); if(d.fh.mask) detail::mask_inplace(in, d.key); auto const prev = d.db.size(); detail::inflate(d.ws.pmd_->zi, d.db, in, ec); d.ws.failed_ = ec != 0; if(d.ws.failed_) break; if(d.remain == 0 && d.fh.fin) { static std::uint8_t constexpr empty_block[4] = { 0x00, 0x00, 0xff, 0xff }; detail::inflate(d.ws.pmd_->zi, d.db, buffer(&empty_block[0], 4), ec); d.ws.failed_ = ec != 0; if(d.ws.failed_) break; } if(d.ws.rd_.op == opcode::text) { consuming_buffers<typename DynamicBuffer::const_buffers_type > cb{d.db.data()}; cb.consume(prev); if(! d.ws.rd_.utf8.write(cb) || (d.remain == 0 && d.fh.fin && ! d.ws.rd_.utf8.finish())) { // invalid utf8 code = close_code::bad_payload; d.state = do_fail; break; } } if(d.remain > 0) { d.state = do_inflate_payload + 1; break; } if(d.fh.fin && ( (d.ws.role_ == detail::role_type::client && d.ws.pmd_config_.server_no_context_takeover) || (d.ws.role_ == detail::role_type::server && d.ws.pmd_config_.client_no_context_takeover))) d.ws.pmd_->zi.reset(); d.state = do_frame_done; break; } //------------------------------------------------------------------ case do_frame_done: // call handler d.fi.op = d.ws.rd_.op; d.fi.fin = d.fh.fin; goto upcall; //------------------------------------------------------------------ case do_read_fh: d.state = do_read_fh + 1; boost::asio::async_read(d.ws.stream_, d.fb.prepare(2), std::move(*this)); return; case do_read_fh + 1: { d.fb.commit(bytes_transferred); code = close_code::none; auto const n = d.ws.read_fh1( d.fh, d.fb, code); if(code != close_code::none) { // protocol error d.state = do_fail; break; } d.state = do_read_fh + 2; if(n == 0) { bytes_transferred = 0; break; } // read variable header boost::asio::async_read(d.ws.stream_, d.fb.prepare(n), std::move(*this)); return; } case do_read_fh + 2: d.fb.commit(bytes_transferred); code = close_code::none; d.ws.read_fh2(d.fh, d.fb, code); if(code != close_code::none) { // protocol error d.state = do_fail; break; } if(detail::is_control(d.fh.op)) { if(d.fh.len > 0) { // read control payload d.state = do_control_payload; d.fmb = d.fb.prepare(static_cast< std::size_t>(d.fh.len)); boost::asio::async_read(d.ws.stream_, *d.fmb, std::move(*this)); return; } d.state = do_control; break; } if(d.fh.op == opcode::text || d.fh.op == opcode::binary) d.ws.rd_begin(); if(d.fh.len == 0 && ! d.fh.fin) { // Empty message frame d.state = do_frame_done; break; } if(! d.ws.pmd_ || ! d.ws.pmd_->rd_set) d.state = do_read_payload; else d.state = do_inflate_payload; break; //------------------------------------------------------------------ case do_control_payload: if(d.fh.mask) { detail::prepare_key(d.key, d.fh.key); detail::mask_inplace(*d.fmb, d.key); } d.fb.commit(bytes_transferred); d.state = do_control; // VFALCO fall through? break; //------------------------------------------------------------------ case do_control: if(d.fh.op == opcode::ping) { ping_data payload; detail::read(payload, d.fb.data()); d.fb.reset(); if(d.ws.ping_cb_) d.ws.ping_cb_(false, payload); if(d.ws.wr_close_) { // ignore ping when closing d.state = do_read_fh; break; } d.ws.template write_ping<static_streambuf>( d.fb, opcode::pong, payload); if(d.ws.wr_block_) { // suspend d.state = do_pong_resume; BOOST_ASSERT(d.ws.wr_block_ != &d); d.ws.rd_op_.template emplace< read_frame_op>(std::move(*this)); return; } d.state = do_pong; break; } else if(d.fh.op == opcode::pong) { code = close_code::none; ping_data payload; detail::read(payload, d.fb.data()); if(d.ws.ping_cb_) d.ws.ping_cb_(true, payload); d.fb.reset(); d.state = do_read_fh; break; } BOOST_ASSERT(d.fh.op == opcode::close); { detail::read(d.ws.cr_, d.fb.data(), code); if(code != close_code::none) { // protocol error d.state = do_fail; break; } if(! d.ws.wr_close_) { auto cr = d.ws.cr_; if(cr.code == close_code::none) cr.code = close_code::normal; cr.reason = ""; d.fb.reset(); d.ws.template write_close< static_streambuf>(d.fb, cr); if(d.ws.wr_block_) { // suspend d.state = do_close_resume; d.ws.rd_op_.template emplace< read_frame_op>(std::move(*this)); return; } d.state = do_close; break; } d.state = do_teardown; break; } //------------------------------------------------------------------ case do_pong_resume: BOOST_ASSERT(! d.ws.wr_block_); d.ws.wr_block_ = &d; d.state = do_pong_resume + 1; d.ws.get_io_service().post(bind_handler( std::move(*this), ec, bytes_transferred)); return; case do_pong_resume + 1: if(d.ws.failed_) { // call handler ec = boost::asio::error::operation_aborted; goto upcall; } // [[fallthrough]] //------------------------------------------------------------------ case do_pong: if(d.ws.wr_close_) { // ignore ping when closing if(d.ws.wr_block_) { BOOST_ASSERT(d.ws.wr_block_ == &d); d.ws.wr_block_ = nullptr; } d.fb.reset(); d.state = do_read_fh; break; } // send pong if(! d.ws.wr_block_) d.ws.wr_block_ = &d; else BOOST_ASSERT(d.ws.wr_block_ == &d); d.state = do_pong + 1; boost::asio::async_write(d.ws.stream_, d.fb.data(), std::move(*this)); return; case do_pong + 1: d.fb.reset(); d.state = do_read_fh; d.ws.wr_block_ = nullptr; break; //------------------------------------------------------------------ case do_close_resume: BOOST_ASSERT(! d.ws.wr_block_); d.ws.wr_block_ = &d; d.state = do_close_resume + 1; // The current context is safe but might not be // the same as the one for this operation (since // we are being called from a write operation). // Call post to make sure we are invoked the same // way as the final handler for this operation. d.ws.get_io_service().post(bind_handler( std::move(*this), ec, bytes_transferred)); return; case do_close_resume + 1: BOOST_ASSERT(d.ws.wr_block_ == &d); if(d.ws.failed_) { // call handler ec = boost::asio::error::operation_aborted; goto upcall; } if(d.ws.wr_close_) { // call handler ec = error::closed; goto upcall; } d.state = do_close; break; //------------------------------------------------------------------ case do_close: if(! d.ws.wr_block_) d.ws.wr_block_ = &d; else BOOST_ASSERT(d.ws.wr_block_ == &d); d.state = do_teardown; d.ws.wr_close_ = true; boost::asio::async_write(d.ws.stream_, d.fb.data(), std::move(*this)); return; //------------------------------------------------------------------ case do_teardown: d.state = do_teardown + 1; websocket_helpers::call_async_teardown( d.ws.next_layer(), std::move(*this)); return; case do_teardown + 1: // call handler ec = error::closed; goto upcall; //------------------------------------------------------------------ case do_fail: if(d.ws.wr_close_) { d.state = do_fail + 4; break; } d.fb.reset(); d.ws.template write_close< static_streambuf>(d.fb, code); if(d.ws.wr_block_) { // suspend d.state = do_fail + 2; d.ws.rd_op_.template emplace< read_frame_op>(std::move(*this)); return; } // fall through case do_fail + 1: d.ws.failed_ = true; // send close frame d.state = do_fail + 4; d.ws.wr_close_ = true; BOOST_ASSERT(! d.ws.wr_block_); d.ws.wr_block_ = &d; boost::asio::async_write(d.ws.stream_, d.fb.data(), std::move(*this)); return; case do_fail + 2: d.state = do_fail + 3; d.ws.get_io_service().post(bind_handler( std::move(*this), ec, bytes_transferred)); return; case do_fail + 3: if(d.ws.failed_) { d.state = do_fail + 5; break; } d.state = do_fail + 1; break; case do_fail + 4: d.state = do_fail + 5; websocket_helpers::call_async_teardown( d.ws.next_layer(), std::move(*this)); return; case do_fail + 5: // call handler ec = error::failed; goto upcall; //------------------------------------------------------------------ case do_call_handler: goto upcall; } } while(! ec); } upcall: if(d.ws.wr_block_ == &d) d.ws.wr_block_ = nullptr; d.ws.ping_op_.maybe_invoke() || d.ws.wr_op_.maybe_invoke(); d_.invoke(ec); } template<class NextLayer> template<class DynamicBuffer, class ReadHandler> typename async_completion< ReadHandler, void(error_code)>::result_type stream<NextLayer>:: async_read_frame(frame_info& fi, DynamicBuffer& dynabuf, ReadHandler&& handler) { static_assert(is_AsyncStream<next_layer_type>::value, "AsyncStream requirements requirements not met"); static_assert(beast::is_DynamicBuffer<DynamicBuffer>::value, "DynamicBuffer requirements not met"); beast::async_completion< ReadHandler, void(error_code)> completion{handler}; read_frame_op<DynamicBuffer, decltype(completion.handler)>{ completion.handler, *this, fi, dynabuf}; return completion.result.get(); } template<class NextLayer> template<class DynamicBuffer> void stream<NextLayer>:: read_frame(frame_info& fi, DynamicBuffer& dynabuf) { static_assert(is_SyncStream<next_layer_type>::value, "SyncStream requirements not met"); static_assert(beast::is_DynamicBuffer<DynamicBuffer>::value, "DynamicBuffer requirements not met"); error_code ec; read_frame(fi, dynabuf, ec); if(ec) throw system_error{ec}; } template<class NextLayer> template<class DynamicBuffer> void stream<NextLayer>:: read_frame(frame_info& fi, DynamicBuffer& dynabuf, error_code& ec) { static_assert(is_SyncStream<next_layer_type>::value, "SyncStream requirements not met"); static_assert(beast::is_DynamicBuffer<DynamicBuffer>::value, "DynamicBuffer requirements not met"); using beast::detail::clamp; using boost::asio::buffer; using boost::asio::buffer_cast; using boost::asio::buffer_size; close_code::value code{}; for(;;) { // Read frame header detail::frame_header fh; detail::frame_streambuf fb; { fb.commit(boost::asio::read( stream_, fb.prepare(2), ec)); failed_ = ec != 0; if(failed_) return; { auto const n = read_fh1(fh, fb, code); if(code != close_code::none) goto do_close; if(n > 0) { fb.commit(boost::asio::read( stream_, fb.prepare(n), ec)); failed_ = ec != 0; if(failed_) return; } } read_fh2(fh, fb, code); failed_ = ec != 0; if(failed_) return; if(code != close_code::none) goto do_close; } if(detail::is_control(fh.op)) { // Read control frame payload if(fh.len > 0) { auto const mb = fb.prepare( static_cast<std::size_t>(fh.len)); fb.commit(boost::asio::read(stream_, mb, ec)); failed_ = ec != 0; if(failed_) return; if(fh.mask) { detail::prepared_key key; detail::prepare_key(key, fh.key); detail::mask_inplace(mb, key); } fb.commit(static_cast<std::size_t>(fh.len)); } // Process control frame if(fh.op == opcode::ping) { ping_data payload; detail::read(payload, fb.data()); fb.reset(); if(ping_cb_) ping_cb_(false, payload); write_ping<static_streambuf>( fb, opcode::pong, payload); boost::asio::write(stream_, fb.data(), ec); failed_ = ec != 0; if(failed_) return; continue; } else if(fh.op == opcode::pong) { ping_data payload; detail::read(payload, fb.data()); if(ping_cb_) ping_cb_(true, payload); continue; } BOOST_ASSERT(fh.op == opcode::close); { detail::read(cr_, fb.data(), code); if(code != close_code::none) goto do_close; if(! wr_close_) { auto cr = cr_; if(cr.code == close_code::none) cr.code = close_code::normal; cr.reason = ""; fb.reset(); wr_close_ = true; write_close<static_streambuf>(fb, cr); boost::asio::write(stream_, fb.data(), ec); failed_ = ec != 0; if(failed_) return; } goto do_close; } } if(fh.op != opcode::cont) rd_begin(); if(fh.len == 0 && ! fh.fin) { // empty frame continue; } auto remain = fh.len; detail::prepared_key key; if(fh.mask) detail::prepare_key(key, fh.key); if(! pmd_ || ! pmd_->rd_set) { // Enforce message size limit if(rd_msg_max_ && fh.len > rd_msg_max_ - rd_.size) { code = close_code::too_big; goto do_close; } rd_.size += fh.len; // Read message frame payload while(remain > 0) { auto b = dynabuf.prepare(clamp(remain)); auto const bytes_transferred = stream_.read_some(b, ec); failed_ = ec != 0; if(failed_) return; BOOST_ASSERT(bytes_transferred > 0); remain -= bytes_transferred; auto const pb = prepare_buffers( bytes_transferred, b); if(fh.mask) detail::mask_inplace(pb, key); if(rd_.op == opcode::text) { if(! rd_.utf8.write(pb) || (remain == 0 && fh.fin && ! rd_.utf8.finish())) { code = close_code::bad_payload; goto do_close; } } dynabuf.commit(bytes_transferred); } } else { // Read compressed message frame payload: // inflate even if fh.len == 0, otherwise we // never emit the end-of-stream deflate block. for(;;) { auto const bytes_transferred = stream_.read_some(buffer(rd_.buf.get(), clamp(remain, rd_.buf_size)), ec); failed_ = ec != 0; if(failed_) return; remain -= bytes_transferred; auto const in = buffer( rd_.buf.get(), bytes_transferred); if(fh.mask) detail::mask_inplace(in, key); auto const prev = dynabuf.size(); detail::inflate(pmd_->zi, dynabuf, in, ec); failed_ = ec != 0; if(failed_) return; if(remain == 0 && fh.fin) { static std::uint8_t constexpr empty_block[4] = { 0x00, 0x00, 0xff, 0xff }; detail::inflate(pmd_->zi, dynabuf, buffer(&empty_block[0], 4), ec); failed_ = ec != 0; if(failed_) return; } if(rd_.op == opcode::text) { consuming_buffers<typename DynamicBuffer::const_buffers_type > cb{dynabuf.data()}; cb.consume(prev); if(! rd_.utf8.write(cb) || ( remain == 0 && fh.fin && ! rd_.utf8.finish())) { code = close_code::bad_payload; goto do_close; } } if(remain == 0) break; } if(fh.fin && ( (role_ == detail::role_type::client && pmd_config_.server_no_context_takeover) || (role_ == detail::role_type::server && pmd_config_.client_no_context_takeover))) pmd_->zi.reset(); } fi.op = rd_.op; fi.fin = fh.fin; return; } do_close: if(code != close_code::none) { // Fail the connection (per rfc6455) if(! wr_close_) { wr_close_ = true; detail::frame_streambuf fb; write_close<static_streambuf>(fb, code); boost::asio::write(stream_, fb.data(), ec); failed_ = ec != 0; if(failed_) return; } websocket_helpers::call_teardown(next_layer(), ec); failed_ = ec != 0; if(failed_) return; ec = error::failed; failed_ = true; return; } if(! ec) websocket_helpers::call_teardown(next_layer(), ec); if(! ec) ec = error::closed; failed_ = ec != 0; } //------------------------------------------------------------------------------ // read an entire message // template<class NextLayer> template<class DynamicBuffer, class Handler> class stream<NextLayer>::read_op { struct data { bool cont; stream<NextLayer>& ws; opcode& op; DynamicBuffer& db; frame_info fi; int state = 0; data(Handler& handler, stream<NextLayer>& ws_, opcode& op_, DynamicBuffer& sb_) : cont(beast_asio_helpers:: is_continuation(handler)) , ws(ws_) , op(op_) , db(sb_) { } }; handler_ptr<data, Handler> d_; public: read_op(read_op&&) = default; read_op(read_op const&) = default; template<class DeducedHandler, class... Args> read_op(DeducedHandler&& h, stream<NextLayer>& ws, Args&&... args) : d_(std::forward<DeducedHandler>(h), ws, std::forward<Args>(args)...) { (*this)(error_code{}, false); } void operator()( error_code const& ec, bool again = true); friend void* asio_handler_allocate( std::size_t size, read_op* op) { return beast_asio_helpers:: allocate(size, op->d_.handler()); } friend void asio_handler_deallocate( void* p, std::size_t size, read_op* op) { return beast_asio_helpers:: deallocate(p, size, op->d_.handler()); } friend bool asio_handler_is_continuation(read_op* op) { return op->d_->cont; } template<class Function> friend void asio_handler_invoke(Function&& f, read_op* op) { return beast_asio_helpers:: invoke(f, op->d_.handler()); } }; template<class NextLayer> template<class DynamicBuffer, class Handler> void stream<NextLayer>::read_op<DynamicBuffer, Handler>:: operator()(error_code const& ec, bool again) { auto& d = *d_; d.cont = d.cont || again; while(! ec) { switch(d.state) { case 0: // read payload d.state = 1; d.ws.async_read_frame( d.fi, d.db, std::move(*this)); return; // got payload case 1: d.op = d.fi.op; if(d.fi.fin) goto upcall; d.state = 0; break; } } upcall: d_.invoke(ec); } template<class NextLayer> template<class DynamicBuffer, class ReadHandler> typename async_completion< ReadHandler, void(error_code)>::result_type stream<NextLayer>:: async_read(opcode& op, DynamicBuffer& dynabuf, ReadHandler&& handler) { static_assert(is_AsyncStream<next_layer_type>::value, "AsyncStream requirements requirements not met"); static_assert(beast::is_DynamicBuffer<DynamicBuffer>::value, "DynamicBuffer requirements not met"); beast::async_completion< ReadHandler, void(error_code) > completion{handler}; read_op<DynamicBuffer, decltype(completion.handler)>{ completion.handler, *this, op, dynabuf}; return completion.result.get(); } template<class NextLayer> template<class DynamicBuffer> void stream<NextLayer>:: read(opcode& op, DynamicBuffer& dynabuf) { static_assert(is_SyncStream<next_layer_type>::value, "SyncStream requirements not met"); static_assert(beast::is_DynamicBuffer<DynamicBuffer>::value, "DynamicBuffer requirements not met"); error_code ec; read(op, dynabuf, ec); if(ec) throw system_error{ec}; } template<class NextLayer> template<class DynamicBuffer> void stream<NextLayer>:: read(opcode& op, DynamicBuffer& dynabuf, error_code& ec) { static_assert(is_SyncStream<next_layer_type>::value, "SyncStream requirements not met"); static_assert(beast::is_DynamicBuffer<DynamicBuffer>::value, "DynamicBuffer requirements not met"); frame_info fi; for(;;) { read_frame(fi, dynabuf, ec); if(ec) break; op = fi.op; if(fi.fin) break; } } //------------------------------------------------------------------------------ } // websocket } // beast #endif
iaxax/leetcode
301-Remove Invalid Parentheses.java
<gh_stars>0 // brute-force + simple prune class Solution { public List<String> removeInvalidParentheses(String s) { HashSet<String> result = new HashSet<>(); int[] maxLen = {0}; int diff = 0; s = trim(s); for (char c : s.toCharArray()) { if (c == '(') { diff += 1; } else if (c == ')') { diff -= 1; } } remove(result, s, maxLen, diff); List<String> list = new ArrayList<>(); for (String str : result) { if (str.length() == maxLen[0]) { list.add(str); } } return list; } private String trim(String s) { StringBuilder pre = new StringBuilder(s.length()); int i = 0, l = s.length(); while (i < l && s.charAt(i) != '(') { if (s.charAt(i) != ')') { pre.append(s.charAt(i)); } ++i; } String post = ""; int j = l - 1; while (j >= i && s.charAt(j) != ')') { if (s.charAt(j) != '(') { post = s.charAt(j) + post; } --j; } return pre + s.substring(i, j + 1) + post; } private void remove(HashSet<String> result, String s, int[] maxLen, int diff) { if (s.length() < maxLen[0]) { return; } if (diff == 0 && valid(s)) { result.add(s); maxLen[0] = s.length(); } else { int length = s.length(); for (int i = 0; i < length; ++i) { char c = s.charAt(i); if (diff < 0 && c == ')') { remove(result, s.substring(0, i) + s.substring(i + 1), maxLen, diff + 1); } else if (diff > 0 && c == '(') { remove(result, s.substring(0, i) + s.substring(i + 1), maxLen, diff - 1); } else if (diff == 0) { remove(result, s.substring(0, i) + s.substring(i + 1), maxLen, 0); } while (i + 1 < length && s.charAt(i + 1) == c) ++i; } } } private boolean valid(String s) { LinkedList<Character> stack = new LinkedList<>(); for (char c : s.toCharArray()) { if (c == '(') { stack.push(c); } else if (c == ')') { if (stack.isEmpty()) return false; stack.pop(); } } return stack.isEmpty(); } } // faster solution class Solution { public List<String> removeInvalidParentheses(String s) { List<String> result = new ArrayList<>(s.length()); int l = 0, r = 0; for (char c : s.toCharArray()) { if (c == '(') ++l; else if (l == 0 && c == ')') ++r; else if (c == ')') --l; } dfs(result, s, 0, l, r); return result; } private void dfs(List<String> result, String s, int start, int l, int r) { if (l == 0 && r == 0) { if (isValid(s)) { result.add(s); } return; } for (int i = start; i < s.length(); ++i) { if (i != start && s.charAt(i) == s.charAt(i - 1)) continue; char c = s.charAt(i); if (c == '(' || c == ')') { String str = s.substring(0, i) + s.substring(i + 1); if (r > 0) { if (c == ')') dfs(result, str, i, l, r - 1); } else if (l > 0) { if (c == '(') dfs(result, str, i, l - 1, r); } } } } private boolean isValid(String s) { int count = 0; for (char c : s.toCharArray()) { if (c == '(') ++count; else if (c == ')') --count; if (count < 0) return false; } return true; } }
starburst-project/Alink
core/src/main/java/com/alibaba/alink/common/dl/DLRunner.java
<reponame>starburst-project/Alink<filename>core/src/main/java/com/alibaba/alink/common/dl/DLRunner.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.alink.common.dl; import java.io.IOException; import java.io.Serializable; import java.net.ServerSocket; import java.util.Map; import com.alibaba.alink.common.AlinkGlobalConfiguration; import com.alibaba.alink.common.utils.JsonConverter; import com.alibaba.flink.ml.cluster.master.meta.AMMeta; import com.alibaba.flink.ml.cluster.master.meta.AMMetaImpl; import com.alibaba.flink.ml.cluster.node.MLContext; import com.alibaba.flink.ml.cluster.node.runner.ExecutionStatus; import com.alibaba.flink.ml.cluster.node.runner.FlinkKillException; import com.alibaba.flink.ml.cluster.node.runner.MLRunner; import com.alibaba.flink.ml.cluster.node.runner.ScriptRunner; import com.alibaba.flink.ml.cluster.node.runner.ScriptRunnerFactory; import com.alibaba.flink.ml.cluster.role.BaseRole; import com.alibaba.flink.ml.cluster.role.PsRole; import com.alibaba.flink.ml.cluster.role.WorkerRole; import com.alibaba.flink.ml.cluster.rpc.NodeServer; import com.alibaba.flink.ml.cluster.rpc.NodeServer.AMCommand; import com.alibaba.flink.ml.proto.MLClusterDef; import com.alibaba.flink.ml.proto.NodeSpec; import com.alibaba.flink.ml.tensorflow2.util.TFConstants; import com.alibaba.flink.ml.util.IpHostUtil; import com.alibaba.flink.ml.util.MLConstants; import com.alibaba.flink.ml.util.MLException; import com.alibaba.flink.ml.util.ProtoUtil; import com.google.common.base.Preconditions; import org.apache.commons.io.IOUtils; import org.apache.flink.api.java.tuple.Tuple2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This runner gets TF cluster info from Flink's broadcast variable instead of * the AM role. It does not interact with AM role at all. So there can be no AM role * when using this runner. */ public class DLRunner implements MLRunner, Serializable { public static final String IPS = "Alink:dl_ips"; public static final String PORTS = "Alink:dl_ports"; private static final Logger LOG = LoggerFactory.getLogger(DLRunner.class); protected long version = 0; protected String localIp; protected NodeServer server; protected volatile MLContext mlContext; protected ScriptRunner scriptRunner; //the execution result of this thread protected ExecutionStatus resultStatus; protected ExecutionStatus currentResultStatus; protected MLClusterDef mlClusterDef; public DLRunner(MLContext mlContext, NodeServer server) { this.mlContext = mlContext; this.server = server; } /** * runner register node information to application master. * * @throws Exception */ @Override public void registerNode() throws Exception { return; } public static Tuple2<BaseRole, Integer> getRoleAndIndex( int flinkTaskIndex, int numTfWorkers) { BaseRole role = flinkTaskIndex < numTfWorkers ? new WorkerRole() : new PsRole(); int roleIndex = flinkTaskIndex < numTfWorkers ? flinkTaskIndex : flinkTaskIndex - numTfWorkers; return Tuple2.of(role, roleIndex); } /** * Get cluster information from MLContext, which origins from Flink's broadcast variable. */ @Override public void getClusterInfo() throws InterruptedException, IOException { AMMeta amMeta = new AMMetaImpl(mlContext); final Map<String, String> mlContextProps = mlContext.getProperties(); // cluster mode if (mlContextProps.containsKey(IPS) && mlContextProps.containsKey(PORTS)) { LOG.info("Running in cluster mode."); int numWorkers = Integer.parseInt(mlContextProps.get(DLConstants.NUM_WORKERS)); String[] ips = JsonConverter.fromJson(mlContextProps.get(IPS), String[].class); int[] ports = JsonConverter.fromJson(mlContextProps.get(PORTS), int[].class); for (int i = 0; i < ips.length; i++) { Tuple2<BaseRole, Integer> roleAndIndex = getRoleAndIndex(i, numWorkers); NodeSpec nodeSpec = NodeSpec.newBuilder() .setIp(ips[i]) .setIndex(roleAndIndex.f1) .setClientPort(0) .setRoleName(roleAndIndex.f0.name()) .putProps(TFConstants.TF_PORT, String.valueOf(ports[i])) .build(); amMeta.saveNodeSpec(nodeSpec); } mlClusterDef = amMeta.restoreClusterDef(); } // standalone mode: each python processes are isolated else { LOG.info("Running in standalone mode."); ServerSocket serverSocket = IpHostUtil.getFreeSocket(); NodeSpec nodeSpec = NodeSpec.newBuilder() .setIp(localIp) .setIndex(mlContext.getIndex()) .setClientPort(server.getPort()) .setRoleName(mlContext.getRoleName()) .putProps(TFConstants.TF_PORT, String.valueOf(serverSocket.getLocalPort())) .build(); serverSocket.close(); amMeta.saveNodeSpec(nodeSpec); mlClusterDef = amMeta.restoreClusterDef(); } } protected void checkEnd() throws MLException { if (resultStatus == ExecutionStatus.KILLED_BY_FLINK) { throw new FlinkKillException("Exit per request."); } } @Override public void run() { resultStatus = ExecutionStatus.RUNNING; currentResultStatus = ExecutionStatus.RUNNING; try { // get ip localIp = IpHostUtil.getIpAddress(); // get cluster getClusterInfo(); Preconditions.checkNotNull(mlClusterDef); checkEnd(); // set machine learning context: the cluster spec, local server ip port resetMLContext(); checkEnd(); // run python script runScript(); checkEnd(); LOG.info("run script."); currentResultStatus = ExecutionStatus.SUCCEED; } catch (Throwable e) { if (e instanceof FlinkKillException || e instanceof InterruptedException) { LOG.info("{} killed by flink.", mlContext.getIdentity()); currentResultStatus = ExecutionStatus.KILLED_BY_FLINK; } else { //no one ask for this thread to stop, thus there must be some error occurs LOG.error("Got exception during python running", e); mlContext.addFailNum(); currentResultStatus = ExecutionStatus.FAILED; } } finally { stopExecution(currentResultStatus == ExecutionStatus.SUCCEED); // set resultStatus value after node notified to am. resultStatus = currentResultStatus; server.setAmCommand(AMCommand.STOP); } } @Override public void runScript() throws Exception { mlContext.getProperties().put("script_runner_class", ProcessPythonRunnerV2.class.getCanonicalName()); scriptRunner = ScriptRunnerFactory.getScriptRunner(mlContext); scriptRunner.runScript(); } @Override public void resetMLContext() { String clusterStr = ProtoUtil.protoToJson(mlClusterDef); LOG.info("java cluster:" + clusterStr); if (AlinkGlobalConfiguration.isPrintProcessInfo()) { System.out.println("java cluster:" + clusterStr); } mlContext.getProperties().put(MLConstants.CONFIG_CLUSTER_PATH, clusterStr); mlContext.setNodeServerIP(localIp); mlContext.setNodeServerPort(server.getPort()); } @Override public void startHeartBeat() throws Exception { } @Override public void getCurrentJobVersion() { } @Override public void initAMClient() throws Exception { } @Override public void waitClusterRunning() throws InterruptedException, MLException { } protected void stopExecution(boolean success) { if (scriptRunner != null) { IOUtils.closeQuietly(scriptRunner); scriptRunner = null; } if (!success) { mlContext.reset(); } } @Override public ExecutionStatus getResultStatus() { return resultStatus; } //called by other thread @Override public void notifyStop() { if (scriptRunner != null) { scriptRunner.notifyKillSignal(); } resultStatus = ExecutionStatus.KILLED_BY_FLINK; } }
natemalek/molen-pater-nathan-rma-thesis-coreference-with-singletons
CoreNLP/src/edu/stanford/nlp/international/morph/AddMorphoAnnotations.java
<filename>CoreNLP/src/edu/stanford/nlp/international/morph/AddMorphoAnnotations.java package edu.stanford.nlp.international.morph; import edu.stanford.nlp.util.logging.Redwood; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.regex.Pattern; import edu.stanford.nlp.ling.CoreLabel; import edu.stanford.nlp.trees.Tree; import edu.stanford.nlp.trees.TreeReader; import edu.stanford.nlp.trees.TreeReaderFactory; import edu.stanford.nlp.trees.international.arabic.ArabicTreeReaderFactory; import edu.stanford.nlp.util.Generics; import edu.stanford.nlp.util.PropertiesUtils; import edu.stanford.nlp.util.StringUtils; /** * Reads in the tree files without any kind of pre-processing. Assumes that the trees * have been processed separately. * <p> * TODO: wsg2011 Extend to other languages. Only supports Arabic right now. * * @author <NAME> * */ public final class AddMorphoAnnotations { /** A logger for this class */ private static Redwood.RedwoodChannels log = Redwood.channels(AddMorphoAnnotations.class); private static final int minArgs = 2; private static String usage() { StringBuilder sb = new StringBuilder(); sb.append(String.format("Usage: java %s [OPTS] morph_file lemma_file < tree_file \n\n",AddMorphoAnnotations.class.getName())); sb.append("Options:\n"); sb.append(" -e enc : Encoding.\n"); sb.append(" -g : Morph file is gold tree file with morph analyses in the pre-terminals."); return sb.toString(); } private static Map<String,Integer> argSpec() { Map<String,Integer> argSpec = Generics.newHashMap(); argSpec.put("g", 0); argSpec.put("e", 1); return argSpec; } /** * Iterate over either strings or leaves. * * @author <NAME> * */ private static class YieldIterator implements Iterator<List<String>> { private List<String> nextYield = null; BufferedReader fileReader = null; TreeReader treeReader = null; public YieldIterator(String fileName, boolean isTree) { try { if (isTree) { TreeReaderFactory trf = new ArabicTreeReaderFactory.ArabicRawTreeReaderFactory(true); treeReader = trf.newTreeReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8")); } else { fileReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8")); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } primeNext(); } private void primeNext() { try { if (treeReader != null) { Tree tree = treeReader.readTree(); if (tree == null) { nextYield = null; } else { List<CoreLabel> mLabeledLeaves = tree.taggedLabeledYield(); nextYield = new ArrayList<>(mLabeledLeaves.size()); for (CoreLabel label : mLabeledLeaves) { nextYield.add(label.tag()); } } } else { String line = fileReader.readLine(); if (line == null) { nextYield = null; } else { nextYield = Arrays.asList(line.split("\\s+")); } } } catch (IOException e) { nextYield = null; e.printStackTrace(); } } @Override public boolean hasNext() { return nextYield != null; } @Override public List<String> next() { if (nextYield == null) { try { if (fileReader != null) { fileReader.close(); fileReader = null; } else if (treeReader != null) { treeReader.close(); treeReader = null; } } catch (IOException e) { e.printStackTrace(); } return null; } else { List<String> next = nextYield; primeNext(); return next; } } @Override public void remove() { throw new UnsupportedOperationException(); } } /** * * @param args */ public static void main(String[] args) { if(args.length < minArgs) { log.info(usage()); System.exit(-1); } Properties options = StringUtils.argsToProperties(args, argSpec()); String encoding = options.getProperty("e", "UTF-8"); boolean isMorphTreeFile = PropertiesUtils.getBool(options, "g", false); String[] parsedArgs = options.getProperty("").split("\\s+"); if (parsedArgs.length != 2) { log.info(usage()); System.exit(-1); } YieldIterator morphIter = new YieldIterator(parsedArgs[0], isMorphTreeFile); YieldIterator lemmaIter = new YieldIterator(parsedArgs[1], false); final Pattern pParenStripper = Pattern.compile("[\\(\\)]"); try { BufferedReader brIn = new BufferedReader(new InputStreamReader(System.in, encoding)); TreeReaderFactory trf = new ArabicTreeReaderFactory.ArabicRawTreeReaderFactory(true); int nTrees = 0; for(String line; (line = brIn.readLine()) != null; ++nTrees) { Tree tree = trf.newTreeReader(new StringReader(line)).readTree(); List<Tree> leaves = tree.getLeaves(); if(!morphIter.hasNext()) { throw new RuntimeException("Mismatch between number of morpho analyses and number of input lines."); } List<String> morphTags = morphIter.next(); if (!lemmaIter.hasNext()) { throw new RuntimeException("Mismatch between number of lemmas and number of input lines."); } List<String> lemmas = lemmaIter.next(); // Sanity checks assert morphTags.size() == lemmas.size(); assert lemmas.size() == leaves.size(); for(int i = 0; i < leaves.size(); ++i) { String morphTag = morphTags.get(i); if (pParenStripper.matcher(morphTag).find()) { morphTag = pParenStripper.matcher(morphTag).replaceAll(""); } String newLeaf = String.format("%s%s%s%s%s", leaves.get(i).value(), MorphoFeatureSpecification.MORPHO_MARK, lemmas.get(i), MorphoFeatureSpecification.LEMMA_MARK, morphTag); leaves.get(i).setValue(newLeaf); } System.out.println(tree.toString()); } // Sanity checks assert !morphIter.hasNext(); assert !lemmaIter.hasNext(); System.err.printf("Processed %d trees%n",nTrees); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
cokeBeer/pyyso
src/pyyso/server/__init__.py
<gh_stars>1-10 from pyyso.server.jrmp import * from pyyso.server.rmi import * from pyyso.server.mysql import * from pyyso.server.ldap import ( LdapSerialized, LdapRemoteRef )
anycollect/anycollect
anycollect-meter-api/src/main/java/io/github/anycollect/meter/api/BaseBuilder.java
<reponame>anycollect/anycollect package io.github.anycollect.meter.api; import io.github.anycollect.metric.Key; import io.github.anycollect.metric.Stat; import io.github.anycollect.metric.Tags; import io.github.anycollect.metric.Type; import javax.annotation.Nonnull; import java.util.Objects; abstract class BaseBuilder<T extends BaseBuilder<T>> { private Key key; private String unit = ""; private Stat stat; private final Tags.Builder tagsBuilder = new Tags.Builder(); private final Tags.Builder metaBuilder = new Tags.Builder(); protected abstract T self(); protected Key getKey() { return key; } protected String getUnit() { return unit; } protected Stat getStat() { return stat; } protected Tags.Builder getTagsBuilder() { return tagsBuilder; } protected Tags.Builder getMetaBuilder() { return metaBuilder; } protected T key(@Nonnull final String key) { return key(Key.of(key)); } protected T key(@Nonnull final Key key) { Objects.requireNonNull(key, "key must not be null"); this.key = key; return self(); } protected T unit(@Nonnull final String unit) { Objects.requireNonNull(unit, "unit must not be null"); this.unit = unit; return self(); } protected T nanos() { return unit("ns"); } protected T stat(@Nonnull final Stat stat) { Objects.requireNonNull(stat, "stat must not be null"); if (!Stat.isValid(stat)) { throw new IllegalArgumentException("stat " + stat + " is not valid"); } this.stat = stat; return self(); } public T tag(@Nonnull final String key, @Nonnull final String value) { tagsBuilder.tag(key, value); return self(); } public T meta(@Nonnull final String key, @Nonnull final String value) { metaBuilder.tag(key, value); return self(); } public T concatTags(@Nonnull final Tags addition) { Objects.requireNonNull(addition, "addition must not be null"); tagsBuilder.concat(addition); return self(); } public T concatMeta(@Nonnull final Tags addition) { Objects.requireNonNull(addition, "addition must not be null"); metaBuilder.concat(addition); return self(); } }
pointhi/sulong
tests/inlineassemblytests/bsr001.c
<reponame>pointhi/sulong int main() { unsigned short arg = 0x1234; unsigned short out = 0; __asm__("bsrw %%ax, %%cx" : "=c"(out) : "a"(arg)); return (out == 12); }
lechium/tvOS144Headers
usr/libexec/appstored/LibraryCatalogObserver.h
// // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 <NAME>. // #import <objc/NSObject.h> @interface LibraryCatalogObserver : NSObject { CDUnknownBlockType _applicationsDidInstall; // 8 = 0x8 } - (void).cxx_destruct; // IMP=0x0000000100154b84 @property(copy) CDUnknownBlockType applicationsDidInstall; // @synthesize applicationsDidInstall=_applicationsDidInstall; @end
tylerjw/SMACC
smacc_sm_reference_library/sm_dance_bot/include/sm_dance_bot/states/s_pattern_states/sti_spattern_forward_1.h
<reponame>tylerjw/SMACC<gh_stars>100-1000 namespace sm_dance_bot { namespace s_pattern_states { // STATE DECLARATION struct StiSPatternForward1 : public smacc::SmaccState<StiSPatternForward1, SS> { using SmaccState::SmaccState; // TRANSITION TABLE typedef mpl::list< Transition<EvCbSuccess<CbNavigateForward, OrNavigation>, StiSPatternRotate2>, Transition<EvCbFailure<CbNavigateForward, OrNavigation>, StiSPatternRotate1> >reactions; // STATE FUNCTIONS static void staticConfigure() { configure_orthogonal<OrLED, CbLEDOn>(); configure_orthogonal<OrNavigation, CbNavigateForward>(SS::pitch1_lenght_meters()); } void runtimeConfigure() { } }; } // namespace s_pattern_states } // namespace sm_dance_bot
tongduchanh/spaceshare-demo
i18n.js
const NextI18Next = require('next-i18next').default module.exports = new NextI18Next({ defaultLanguage: 'vi', otherLanguages: ['eng'], })
1379576648/framework_java_project
framework_api/src/main/java/com/trkj/framework/entity/mybatisplus/RegisterLog.java
package com.trkj.framework.entity.mybatisplus; import com.baomidou.mybatisplus.annotation.*; import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import org.springframework.format.annotation.DateTimeFormat; import java.io.Serializable; import java.util.Date; /** * <p> * 登录日志表 * </p> * * @author 劉祁 * @since 2021-12-28 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @TableName("REGISTER_LOG") @ApiModel(value="RegisterLog对象", description="登录日志表") public class RegisterLog implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value = "登录日志编号") @TableId(value = "REGISTER_LOG_ID") private Long registerLogId; @ApiModelProperty(value = "员工名称") @TableField(value = "REGISTER_LOG_PEOPLE") private String registerLogPeople; @ApiModelProperty(value = "手机号码") @TableField( value = "REGISTER_LOG_PHONE") private Long registerLogPhone; @ApiModelProperty(value = "IP地址") @TableField(value = "REGISTER_LOG_IP") private String registerLogIp; @ApiModelProperty(value = "设登录状态 0:成功 1:失败") @TableField(value = "REGISTER_LOG_TYPE") private String registerLogType; @TableField(value = "REGISTER_LOG_STATE") private Long registerLogState; @ApiModelProperty(value = "浏览器") @TableField(value = "REGISTER_LOG_BROWSER") private String registerLogBrowser; @ApiModelProperty(value = "登录类型 0:人脸 1:密码") @TableField(value = "REGISTER_LOG_GENRE") private Double registerLogGenre; @ApiModelProperty(value = "创建时间 精确到秒") @TableField(value = "CREATED_TIME") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") private Date createdTime; @ApiModelProperty(value = "修改时间 精确到秒") @TableField(value = "UPDATED_TIME") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") private Date updatedTime; @ApiModelProperty(value = "乐观锁") @TableField(value = "REVISION") @Version private Long revision; @ApiModelProperty(value = "IP所在地") @TableField(value = "REGISTER_LOG_IPNAME") private String registerLogIpname; @ApiModelProperty(value = "起始时间") @TableField(exist = false) private Date startTime; @ApiModelProperty(value = "结束时间") @TableField(exist = false) private Date endTime; @ApiModelProperty(value = "当前页") @TableField(exist = false) private Integer currenPage; @ApiModelProperty(value = "页大小") @TableField(exist = false) private Integer pageSize; @ApiModelProperty(value = "逻辑删除 0:未删 1:已删 ") @TableLogic @TableField("IS_DELETED") private Long isDeleted; }
cbosoft/aite
src/object/generate.cpp
#include "../util/random.hpp" #include "star.hpp" #include "planet.hpp" #include "object.hpp" static std::map<SystemObjectType, RandomLikelihood> object_likelihoods = { {SO_Moon, Likelihood_Common}, {SO_Planet, Likelihood_Certain}, {SO_Planetoid, Likelihood_Common}, {SO_GasGiant, Likelihood_Uncommon}, {SO_EarthlikePlanet, Likelihood_Rare}, {SO_Star, Likelihood_Certain}, {SO_MainSequenceStar, Likelihood_Common}, {SO_MassiveStar, Likelihood_Common}, {SO_SupergiantStar, Likelihood_Uncommon}, {SO_Supernova, Likelihood_Rare}, {SO_NeutronStar, Likelihood_Uncommon}, {SO_BlackHole, Likelihood_VeryRare}, {SO_PairedStars, Likelihood_Rare}, {SO_Nebula, Likelihood_Common}, {SO_StellarNebula, Likelihood_Common}, {SO_PlanetaryNebula, Likelihood_Common}, {SO_AsteroidField, Likelihood_Common} }; static std::map<SystemObjectType, std::list<SystemObjectType>> object_subtypes = { {SO_Moon, {SO_Moon}}, {SO_Planet, {SO_Planet, SO_Planetoid, SO_GasGiant, SO_EarthlikePlanet}}, {SO_Star, {SO_Star, SO_MainSequenceStar, SO_MassiveStar, SO_SupergiantStar, SO_Supernova, SO_NeutronStar, SO_BlackHole, SO_PairedStars}}, {SO_Nebula, {SO_Nebula, SO_StellarNebula, SO_PlanetaryNebula}}, {SO_AsteroidField, {SO_AsteroidField}} }; SystemObject_ptr SystemObject::generate_object_or_subtype(System_ptr system, double position, double luminosity, SystemObjectType type) { std::list<SystemObjectType> types = object_subtypes[type]; std::list<RandomLikelihood> likelihoods; for (auto type : types) { likelihoods.push_back(object_likelihoods[type]); } type = probability_weighted_choice(likelihoods, types); return SystemObject::generate(system, position, luminosity, type); } SystemObject_ptr SystemObject::generate(System_ptr system, double position, double luminosity, SystemObjectType type) { SystemObject_ptr obj = nullptr; switch (type) { case SO_Star: obj = Star::generate(system, position); break; default: case SO_Planet: obj = Planet::generate(system, position, luminosity); break; case SO_EarthlikePlanet: obj = EarthlikePlanet::generate(system, position, luminosity); break; } return obj; }
PableteProgramming/download
extern/gtk/gtk/gtkwindowcontrols.c
/* * Copyright (c) 2020 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "gtkwindowcontrols.h" #include "gtkaccessible.h" #include "gtkactionable.h" #include "gtkboxlayout.h" #include "gtkbutton.h" #include "gtkenums.h" #include "gtkicontheme.h" #include "gtkimage.h" #include "gtkintl.h" #include "gtkprivate.h" #include "gtktypebuiltins.h" #include "gtkwindowprivate.h" /** * GtkWindowControls: * * `GtkWindowControls` shows window frame controls. * * Typical window frame controls are minimize, maximize and close buttons, * and the window icon. * * ![An example GtkWindowControls](windowcontrols.png) * * `GtkWindowControls` only displays start or end side of the controls (see * [property@Gtk.WindowControls:side]), so it's intended to be always used * in pair with another `GtkWindowControls` for the opposite side, for example: * * ```xml * <object class="GtkBox"> * <child> * <object class="GtkWindowControls"> * <property name="side">start</property> * </object> * </child> * * ... * * <child> * <object class="GtkWindowControls"> * <property name="side">end</property> * </object> * </child> * </object> * ``` * * # CSS nodes * * ``` * windowcontrols * ├── [image.icon] * ├── [button.minimize] * ├── [button.maximize] * ╰── [button.close] * ``` * * A `GtkWindowControls`' CSS node is called windowcontrols. It contains * subnodes corresponding to each title button. Which of the title buttons * exist and where they are placed exactly depends on the desktop environment * and [<EMAIL>:decoration-layout] value. * * When [property<EMAIL>:empty] is %TRUE, it gets the .empty * style class. * * # Accessibility * * `GtkWindowControls` uses the %GTK_ACCESSIBLE_ROLE_GROUP role. */ struct _GtkWindowControls { GtkWidget parent_instance; GtkPackType side; char *decoration_layout; gboolean empty; }; enum { PROP_0, PROP_SIDE, PROP_DECORATION_LAYOUT, PROP_EMPTY, LAST_PROP }; static GParamSpec *props[LAST_PROP] = { NULL, }; #define WINDOW_ICON_SIZE 16 G_DEFINE_TYPE (GtkWindowControls, gtk_window_controls, GTK_TYPE_WIDGET) static char * get_layout (GtkWindowControls *self) { GtkWidget *widget = GTK_WIDGET (self); GtkRoot *root; char *layout_desc, *layout_half; char **tokens; root = gtk_widget_get_root (widget); if (!root || !GTK_IS_WINDOW (root)) return NULL; if (self->decoration_layout) layout_desc = g_strdup (self->decoration_layout); else g_object_get (gtk_widget_get_settings (widget), "gtk-decoration-layout", &layout_desc, NULL); tokens = g_strsplit (layout_desc, ":", 2); switch (self->side) { case GTK_PACK_START: layout_half = g_strdup (tokens[0]); break; case GTK_PACK_END: layout_half = g_strdup (tokens[1]); break; default: g_assert_not_reached (); } g_free (layout_desc); g_strfreev (tokens); return layout_half; } static GdkPaintable * get_default_icon (GtkWidget *widget) { GdkDisplay *display = gtk_widget_get_display (widget); GtkIconPaintable *info; int scale = gtk_widget_get_scale_factor (widget); info = gtk_icon_theme_lookup_icon (gtk_icon_theme_get_for_display (display), gtk_window_get_default_icon_name (), NULL, WINDOW_ICON_SIZE, scale, gtk_widget_get_direction (widget), 0); return GDK_PAINTABLE (info); } static gboolean update_window_icon (GtkWindow *window, GtkWidget *icon) { GdkPaintable *paintable; if (window) paintable = gtk_window_get_icon_for_size (window, WINDOW_ICON_SIZE); else paintable = get_default_icon (icon); if (paintable) { gtk_image_set_from_paintable (GTK_IMAGE (icon), paintable); g_object_unref (paintable); gtk_widget_show (icon); return TRUE; } return FALSE; } static void set_empty (GtkWindowControls *self, gboolean empty) { if (empty == self->empty) return; self->empty = empty; if (empty) gtk_widget_add_css_class (GTK_WIDGET (self), "empty"); else gtk_widget_remove_css_class (GTK_WIDGET (self), "empty"); g_object_notify_by_pspec (G_OBJECT (self), props[PROP_EMPTY]); } static void clear_controls (GtkWindowControls *self) { GtkWidget *child = gtk_widget_get_first_child (GTK_WIDGET (self)); while (child) { GtkWidget *next = gtk_widget_get_next_sibling (child); gtk_widget_unparent (child); child = next; } } static void update_window_buttons (GtkWindowControls *self) { GtkWidget *widget = GTK_WIDGET (self); char *layout; char **tokens; int i; gboolean is_sovereign_window; gboolean maximized; gboolean resizable; gboolean deletable; gboolean empty = TRUE; GtkRoot *root; GtkWindow *window = NULL; root = gtk_widget_get_root (widget); if (!root || !GTK_IS_WINDOW (root)) { set_empty (self, TRUE); return; } clear_controls (self); window = GTK_WINDOW (root); is_sovereign_window = !gtk_window_get_modal (window) && gtk_window_get_transient_for (window) == NULL; maximized = gtk_window_is_maximized (window); resizable = gtk_window_get_resizable (window); deletable = gtk_window_get_deletable (window); layout = get_layout (self); if (!layout) { set_empty (self, TRUE); return; } tokens = g_strsplit (layout, ",", -1); for (i = 0; tokens[i]; i++) { GtkWidget *button = NULL; GtkWidget *image = NULL; if (strcmp (tokens[i], "icon") == 0 && is_sovereign_window) { /* The icon is not relevant for accessibility purposes */ button = g_object_new (GTK_TYPE_IMAGE, "accessible-role", GTK_ACCESSIBLE_ROLE_PRESENTATION, NULL); gtk_widget_set_valign (button, GTK_ALIGN_CENTER); gtk_widget_add_css_class (button, "icon"); if (!update_window_icon (window, button)) { g_object_ref_sink (button); g_object_unref (button); button = NULL; } } else if (strcmp (tokens[i], "minimize") == 0 && is_sovereign_window) { button = gtk_button_new (); gtk_widget_set_valign (button, GTK_ALIGN_CENTER); gtk_widget_add_css_class (button, "minimize"); /* The icon is not relevant for accessibility purposes */ image = g_object_new (GTK_TYPE_IMAGE, "accessible-role", GTK_ACCESSIBLE_ROLE_PRESENTATION, "icon-name", "window-minimize-symbolic", NULL); g_object_set (image, "use-fallback", TRUE, NULL); gtk_button_set_child (GTK_BUTTON (button), image); gtk_widget_set_can_focus (button, FALSE); gtk_actionable_set_action_name (GTK_ACTIONABLE (button), "window.minimize"); gtk_accessible_update_property (GTK_ACCESSIBLE (button), GTK_ACCESSIBLE_PROPERTY_LABEL, _("Minimize"), GTK_ACCESSIBLE_PROPERTY_DESCRIPTION, _("Minimize the window"), -1); } else if (strcmp (tokens[i], "maximize") == 0 && resizable && is_sovereign_window) { const char *icon_name; icon_name = maximized ? "window-restore-symbolic" : "window-maximize-symbolic"; button = gtk_button_new (); gtk_widget_set_valign (button, GTK_ALIGN_CENTER); gtk_widget_add_css_class (button, "maximize"); /* The icon is not relevant for accessibility purposes */ image = g_object_new (GTK_TYPE_IMAGE, "accessible-role", GTK_ACCESSIBLE_ROLE_PRESENTATION, "icon-name", icon_name, NULL); g_object_set (image, "use-fallback", TRUE, NULL); gtk_button_set_child (GTK_BUTTON (button), image); gtk_widget_set_can_focus (button, FALSE); gtk_actionable_set_action_name (GTK_ACTIONABLE (button), "window.toggle-maximized"); gtk_accessible_update_property (GTK_ACCESSIBLE (button), GTK_ACCESSIBLE_PROPERTY_LABEL, _("Maximize"), GTK_ACCESSIBLE_PROPERTY_DESCRIPTION, _("Maximize the window"), -1); } else if (strcmp (tokens[i], "close") == 0 && deletable) { button = gtk_button_new (); gtk_widget_set_valign (button, GTK_ALIGN_CENTER); /* The icon is not relevant for accessibility purposes */ image = g_object_new (GTK_TYPE_IMAGE, "accessible-role", GTK_ACCESSIBLE_ROLE_PRESENTATION, "icon-name", "window-close-symbolic", NULL); gtk_widget_add_css_class (button, "close"); g_object_set (image, "use-fallback", TRUE, NULL); gtk_button_set_child (GTK_BUTTON (button), image); gtk_widget_set_can_focus (button, FALSE); gtk_actionable_set_action_name (GTK_ACTIONABLE (button), "window.close"); gtk_accessible_update_property (GTK_ACCESSIBLE (button), GTK_ACCESSIBLE_PROPERTY_LABEL, _("Close"), GTK_ACCESSIBLE_PROPERTY_DESCRIPTION, _("Close the window"), -1); } if (button) { gtk_widget_set_parent (button, widget); empty = FALSE; } } g_free (layout); g_strfreev (tokens); set_empty (self, empty); } static void window_notify_cb (GtkWindowControls *self, GParamSpec *pspec, GtkWindow *window) { if (pspec->name == I_("deletable") || pspec->name == I_("icon-name") || pspec->name == I_("maximized") || pspec->name == I_("modal") || pspec->name == I_("resizable") || pspec->name == I_("scale-factor") || pspec->name == I_("transient-for")) update_window_buttons (self); } static void gtk_window_controls_root (GtkWidget *widget) { GtkSettings *settings; GtkWidget *root; GTK_WIDGET_CLASS (gtk_window_controls_parent_class)->root (widget); settings = gtk_widget_get_settings (widget); g_signal_connect_swapped (settings, "notify::gtk-decoration-layout", G_CALLBACK (update_window_buttons), widget); root = GTK_WIDGET (gtk_widget_get_root (widget)); if (GTK_IS_WINDOW (root)) g_signal_connect_swapped (root, "notify", G_CALLBACK (window_notify_cb), widget); update_window_buttons (GTK_WINDOW_CONTROLS (widget)); } static void gtk_window_controls_unroot (GtkWidget *widget) { GtkSettings *settings; settings = gtk_widget_get_settings (widget); g_signal_handlers_disconnect_by_func (settings, update_window_buttons, widget); g_signal_handlers_disconnect_by_func (gtk_widget_get_root (widget), window_notify_cb, widget); GTK_WIDGET_CLASS (gtk_window_controls_parent_class)->unroot (widget); } static void gtk_window_controls_dispose (GObject *object) { GtkWindowControls *self = GTK_WINDOW_CONTROLS (object); clear_controls (self); G_OBJECT_CLASS (gtk_window_controls_parent_class)->dispose (object); } static void gtk_window_controls_finalize (GObject *object) { GtkWindowControls *self = GTK_WINDOW_CONTROLS (object); g_free (self->decoration_layout); G_OBJECT_CLASS (gtk_window_controls_parent_class)->finalize (object); } static void gtk_window_controls_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { GtkWindowControls *self = GTK_WINDOW_CONTROLS (object); switch (prop_id) { case PROP_SIDE: g_value_set_enum (value, gtk_window_controls_get_side (self)); break; case PROP_DECORATION_LAYOUT: g_value_set_string (value, gtk_window_controls_get_decoration_layout (self)); break; case PROP_EMPTY: g_value_set_boolean (value, gtk_window_controls_get_empty (self)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void gtk_window_controls_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { GtkWindowControls *self = GTK_WINDOW_CONTROLS (object); switch (prop_id) { case PROP_SIDE: gtk_window_controls_set_side (self, g_value_get_enum (value)); break; case PROP_DECORATION_LAYOUT: gtk_window_controls_set_decoration_layout (self, g_value_get_string (value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void gtk_window_controls_class_init (GtkWindowControlsClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass); object_class->dispose = gtk_window_controls_dispose; object_class->finalize = gtk_window_controls_finalize; object_class->get_property = gtk_window_controls_get_property; object_class->set_property = gtk_window_controls_set_property; widget_class->root = gtk_window_controls_root; widget_class->unroot = gtk_window_controls_unroot; /** * GtkWindowControls:side: (attributes org.gtk.Property.get=gtk_window_controls_get_side org.gtk.Property.set=gtk_window_controls_set_side) * * Whether the widget shows start or end side of the decoration layout. * * See [<EMAIL>:decoration_layout]. */ props[PROP_SIDE] = g_param_spec_enum ("side", P_("Side"), P_("Whether the widget shows start or end portion of the decoration layout"), GTK_TYPE_PACK_TYPE, GTK_PACK_START, GTK_PARAM_READWRITE | G_PARAM_EXPLICIT_NOTIFY); /** * GtkWindowControls:decoration-layout: (attributes org.gtk.Property.get=gtk_window_controls_get_decoration_layout org.gtk.Property.set=gtk_window_controls_set_decoration_layout) * * The decoration layout for window buttons. * * If this property is not set, the * [<EMAIL>:gtk-decoration-layout] setting is used. */ props[PROP_DECORATION_LAYOUT] = g_param_spec_string ("decoration-layout", P_("Decoration Layout"), P_("The layout for window decorations"), NULL, GTK_PARAM_READWRITE | G_PARAM_EXPLICIT_NOTIFY); /** * GtkWindowControls:empty: (attributes org.gtk.Property.get=gtk_window_controls_get_empty) * * Whether the widget has any window buttons. */ props[PROP_EMPTY] = g_param_spec_boolean ("empty", P_("Empty"), P_("Whether the widget has any window buttons"), TRUE, GTK_PARAM_READABLE | G_PARAM_EXPLICIT_NOTIFY); g_object_class_install_properties (object_class, LAST_PROP, props); gtk_widget_class_set_layout_manager_type (widget_class, GTK_TYPE_BOX_LAYOUT); gtk_widget_class_set_css_name (widget_class, I_("windowcontrols")); gtk_widget_class_set_accessible_role (widget_class, GTK_ACCESSIBLE_ROLE_GROUP); } static void gtk_window_controls_init (GtkWindowControls *self) { self->decoration_layout = NULL; self->side = GTK_PACK_START; self->empty = TRUE; gtk_widget_add_css_class (GTK_WIDGET (self), "empty"); gtk_widget_add_css_class (GTK_WIDGET (self), "start"); gtk_widget_set_can_focus (GTK_WIDGET (self), FALSE); } /** * gtk_window_controls_new: * @side: the side * * Creates a new `GtkWindowControls`. * * Returns: a new `GtkWindowControls`. **/ GtkWidget * gtk_window_controls_new (GtkPackType side) { return g_object_new (GTK_TYPE_WINDOW_CONTROLS, "side", side, NULL); } /** * gtk_window_controls_get_side: (attributes org.gtk.Method.get_property=side) * @self: a `GtkWindowControls` * * Gets the side to which this `GtkWindowControls` instance belongs. * * Returns: the side */ GtkPackType gtk_window_controls_get_side (GtkWindowControls *self) { g_return_val_if_fail (GTK_IS_WINDOW_CONTROLS (self), GTK_PACK_START); return self->side; } /** * gtk_window_controls_set_side: (attributes org.gtk.Method.set_property=side) * @self: a `GtkWindowControls` * @side: a side * * Determines which part of decoration layout the `GtkWindowControls` uses. * * See [<EMAIL>:decoration-layout]. */ void gtk_window_controls_set_side (GtkWindowControls *self, GtkPackType side) { g_return_if_fail (GTK_IS_WINDOW_CONTROLS (self)); if (self->side == side) return; self->side = side; switch (side) { case GTK_PACK_START: gtk_widget_add_css_class (GTK_WIDGET (self), "start"); gtk_widget_remove_css_class (GTK_WIDGET (self), "end"); break; case GTK_PACK_END: gtk_widget_add_css_class (GTK_WIDGET (self), "end"); gtk_widget_remove_css_class (GTK_WIDGET (self), "start"); break; default: g_warning ("Unexpected side: %d", side); break; } update_window_buttons (self); g_object_notify_by_pspec (G_OBJECT (self), props[PROP_SIDE]); } /** * gtk_window_controls_get_decoration_layout: (attributes org.gtk.Method.get_property=decoration-layout) * @self: a `GtkWindowControls` * * Gets the decoration layout of this `GtkWindowControls`. * * Returns: (nullable): the decoration layout or %NULL if it is unset */ const char * gtk_window_controls_get_decoration_layout (GtkWindowControls *self) { g_return_val_if_fail (GTK_IS_WINDOW_CONTROLS (self), NULL); return self->decoration_layout; } /** * gtk_window_controls_set_decoration_layout: (attributes org.gtk.Method.set_property=decoration-layout) * @self: a `GtkWindowControls` * @layout: (nullable): a decoration layout, or %NULL to unset the layout * * Sets the decoration layout for the title buttons. * * This overrides the [<EMAIL>:gtk-decoration-layout] * setting. * * The format of the string is button names, separated by commas. * A colon separates the buttons that should appear on the left * from those on the right. Recognized button names are minimize, * maximize, close and icon (the window icon). * * For example, “icon:minimize,maximize,close” specifies a icon * on the left, and minimize, maximize and close buttons on the right. * * If [property<EMAIL>:side] value is @GTK_PACK_START, @self * will display the part before the colon, otherwise after that. */ void gtk_window_controls_set_decoration_layout (GtkWindowControls *self, const char *layout) { g_return_if_fail (GTK_IS_WINDOW_CONTROLS (self)); g_free (self->decoration_layout); self->decoration_layout = g_strdup (layout); update_window_buttons (self); g_object_notify_by_pspec (G_OBJECT (self), props[PROP_DECORATION_LAYOUT]); } /** * gtk_window_controls_get_empty: (attributes org.gtk.Method.get_property=empty) * @self: a `GtkWindowControls` * * Gets whether the widget has any window buttons. * * Returns: %TRUE if the widget has window buttons, otherwise %FALSE */ gboolean gtk_window_controls_get_empty (GtkWindowControls *self) { g_return_val_if_fail (GTK_IS_WINDOW_CONTROLS (self), FALSE); return self->empty; }
Mu-L/automa
src/content/elementSelector/icons.js
<reponame>Mu-L/automa import { riEyeLine, riCheckLine, riCloseLine, riEyeOffLine, riFileCopyLine, riDragMoveLine, riListUnordered, riArrowLeftLine, riArrowLeftSLine, riInformationLine, riArrowDropDownLine, } from 'v-remixicon/icons'; export default { riEyeLine, riCheckLine, riCloseLine, riEyeOffLine, riFileCopyLine, riDragMoveLine, riListUnordered, riArrowLeftLine, riArrowLeftSLine, riInformationLine, riArrowDropDownLine, };
KBLin1996/Comp546-Computer_Vision
Assignment9/vlfeat-0.9.21/vl/covdet.c
/** @file covdet.c ** @brief Covariant feature detectors - Definition ** @author <NAME> ** @author <NAME> ** @author <NAME> **/ /* Copyright (C) 2013-14 <NAME>. Copyright (C) 2012 <NAME>, <NAME> and <NAME>. All rights reserved. This file is part of the VLFeat library and is made available under the terms of the BSD license (see the COPYING file). */ /** <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @page covdet Covariant feature detectors @author <NAME> @author <NAME> @author <NAME> @tableofcontents <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @ref covdet.h implements a number of covariant feature detectors, based on three cornerness measures (determinant of the Hessian, trace of the Hessian (aka Difference of Gaussians, and Harris). It supprots affine adaptation, orientation estimation, as well as Laplacian scale detection. - @subpage covdet-fundamentals - @subpage covdet-principles - @subpage covdet-differential - @subpage covdet-corner-types <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section covdet-starting Getting started <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> The ::VlCovDet object implements a number of covariant feature detectors: Difference of Gaussian, Harris, determinant of Hessian. Variant of the basic detectors support scale selection by maximizing the Laplacian measure as well as affine normalization. @code // create a detector object VlCovDet * covdet = vl_covdet_new(method) ; // set various parameters (optional) vl_covdet_set_first_octave(covdet, -1) ; // start by doubling the image resolution vl_covdet_set_octave_resolution(covdet, octaveResolution) ; vl_covdet_set_peak_threshold(covdet, peakThreshold) ; vl_covdet_set_edge_threshold(covdet, edgeThreshold) ; // process the image and run the detector vl_covdet_put_image(covdet, image, numRows, numCols) ; vl_covdet_detect(covdet) ; // drop features on the margin (optional) vl_covdet_drop_features_outside (covdet, boundaryMargin) ; // compute the affine shape of the features (optional) vl_covdet_extract_affine_shape(covdet) ; // compute the orientation of the features (optional) vl_covdet_extract_orientations(covdet) ; // get feature frames back vl_size numFeatures = vl_covdet_get_num_features(covdet) ; VlCovDetFeature const * feature = vl_covdet_get_features(covdet) ; // get normalized feature appearance patches (optional) vl_size w = 2*patchResolution + 1 ; for (i = 0 ; i < numFeatures ; ++i) { float * patch = malloc(w*w*sizeof(*desc)) ; vl_covdet_extract_patch_for_frame(covdet, patch, patchResolution, patchRelativeExtent, patchRelativeSmoothing, feature[i].frame) ; // do something with patch } @endcode This example code: - Calls ::vl_covdet_new constructs a new detector object. @ref covdet.h supports a variety of different detectors (see ::VlCovDetMethod). - Optionally calls various functions to set the detector parameters if needed (e.g. ::vl_covdet_set_peak_threshold). - Calls ::vl_covdet_put_image to start processing a new image. It causes the detector to compute the scale space representation of the image, but does not compute the features yet. - Calls ::vl_covdet_detect runs the detector. At this point features are ready to be extracted. However, one or all of the following steps may be executed in order to process the features further. - Optionally calls ::vl_covdet_drop_features_outside to drop features outside the image boundary. - Optionally calls ::vl_covdet_extract_affine_shape to compute the affine shape of features using affine adaptation. - Optionally calls ::vl_covdet_extract_orientations to compute the dominant orientation of features looking for the dominant gradient orientation in patches. - Optionally calls ::vl_covdet_extract_patch_for_frame to extract a normalized feature patch, for example to compute an invariant feature descriptor. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @page covdet-fundamentals Covariant detectors fundamentals @tableofcontents <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> This page describes the fundamental concepts required to understand a covariant feature detector, the geometry of covariant features, and the process of feature normalization. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section covdet-covariance Covariant detection <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> The purpose of a *covariant detector* is to extract from an image a set of local features in a manner which is consistent with spatial transformations of the image itself. For instance, a covariant detector that extracts interest points $\bx_1,\dots,\bx_n$ from image $\ell$ extracts the translated points $\bx_1+T,\dots,\bx_n+T$ from the translated image $\ell'(\bx) = \ell(\bx-T)$. More in general, consider a image $\ell$ and a transformed version $\ell' = \ell \circ w^{-1}$ of it, as in the following figure: @image html covdet.png "Covariant detection of local features." The transformation or <em>warp</em> $w : \real^2 \mapsto \real^2$ is a deformation of the image domain which may capture a change of camera viewpoint or similar imaging factor. Examples of warps typically considered are translations, scaling, rotations, and general affine transformations; however, in $w$ could be another type of continuous and invertible transformation. Given an image $\ell$, a **detector** selects features $R_1,\dots,R_n$ (one such features is shown in the example as a green circle). The detector is said to be **covariant** with the warps $w$ if it extracts the transformed features $w[R_1],\dots, w[R_n]$ from the transformed image $w[\ell]$. Intuitively, this means that the &ldquo;same features&rdquo; are extracted in both cases up to the transformation $w$. This property is described more formally in @ref covdet-principles. Covariance is a key property of local feature detectors as it allows extracting corresponding features from two or more images, making it possible to match them in a meaningful way. The @ref covdet.h module in VLFeat implements an array of feature detection algorithm that have are covariant to different classes of transformations. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section covdet-frame Feature geometry and feature frames <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> As we have seen, local features are subject to image transformations, and they apply a fundamental role in matching and normalizing images. To operates effectively with local features is therefore necessary to understand their geometry. The geometry of a local feature is captured by a <b>feature frame</b> $R$. In VLFeat, depending on the specific detector, the frame can be either a point, a disc, an ellipse, an oriented disc, or an oriented ellipse. A frame captures both the extent of the local features, useful to know which portions of two images are put in correspondence, as well their shape. The latter can be used to associate to diagnose the transformation that affects a feature and remove it through the process of **normalization**. More precisely, in covariant detection feature frames are constructed to be compatible with a certain class of transformations. For example, circles are compatible with similarity transformations as they are closed under them. Likewise, ellipses are compatible with affine transformations. Beyond this closure property, the key idea here is that all feature occurrences can be seen as transformed versions of a base or <b>canonical</b> feature. For example, all discs $R$ can be obtained by applying a similarity transformation to the unit disc $\bar R$ centered at the origin. $\bar R$ is an example of canonical frame as any other disc can be written as $R = w[\bar R]$ for a suitable similarity $w$. @image html frame-canonical.png "The idea of canonical frame and normalization" The equation $R = w[\bar R_0]$ matching the canonical and detected feature frames establishes a constraint on the warp $w$, very similar to the way two reference frames in geometry establish a transformation between spaces. The transformation $w$ can be thought as a the **pose** of the detected feature, a generalization of its location. In the case of discs and similarity transformations, the equation $R = w[\bar R_0]$ fixes $w$ up to a residual rotation. This can be addressed by considering oriented discs instead. An **oriented disc** is a disc with a radius highlighted to represent the feature orientation. While discs are appropriate for similarity transformations, they are not closed under general affine transformations. In this case, one should consider the more general class of (oriented) ellipses. The following image illustrates the five types of feature frames used in VLFeat: @image html frame-types.png "Types of local feature frames: points, discs, oriented discs, ellipses, oriented ellipses." Note that these frames are described respectively by 2, 3, 4, 5 and 6 parameters. The most general type are the oriented ellipses, which can be used to represent all the other frame types as well. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section covdet-frame-transformation Transforming feature frames <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> Consider a warp $w$ mapping image $\ell$ into image $\ell'$ as in the figure below. A feature $R$ in the first image co-variantly transform into a feature $R'=w[R]$ in the second image: @image html covdet-normalization.png "Normalization removes the effect of an image deformation." The poses $u,u'$ of $R=u[R_0]$ and $R' = u'[R_0]$ are then related by the simple expression: \[ u' = w \circ u. \] <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section covdet-frame-normalization Normalizing feature frames <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> In the example above, the poses $u$ and $u'$ relate the two occurrences $R$ and $R'$ of the feature to its canonical version $R_0$. If the pose $u$ of the feature in image $\ell$ is known, the canonical feature appearance can be computed by un-warping it: \[ \ell_0 = u^{-1}[\ell] = \ell \circ u. \] This process is known as **normalization** and is the key in the computation of invariant feature descriptors as well as in the construction of most co-variant detectors. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @page covdet-principles Principles of covariant detection @tableofcontents <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> The goals of a co-variant detector were discussed in @ref covdet-fundamentals. This page introduces a few general principles that are at the basis of most covariant detection algorithms. Consider an input image $\ell$ and a two dimensional continuous and invertible warp $w$. The *warped image* $w[\ell]$ is defined to be \[ w[\ell] = \ell \circ w^{-1}, \] or, equivalently, \[ w[\ell](x,y) = \ell(w^{-1}(x,y)), \qquad \forall (x,y)\in\real^2. \] Note that, while $w$ pushes pixels forward, from the original to the transformed image domain, defining the transformed image $\ell'$ requires inverting the warp and composing $\ell$ with $w^{-1}$. The goal a covariant detector is to extract the same local features irregardless of image transformations. The detector is said to be <b>covariant</b> or <b>equivariant</b> with a class of warps $w\in\mathcal{W}$ if, when the feature $R$ is detected in image $\ell$, then the transformed feature $w[R]$ is detected in the transformed image $w[\ell]$. The net effect is that a covariant feature detector appears to &ldquo;track&rdquo; image transformations; however, it is important to note that a detector *is not a tracker* because it processes images individually rather than jointly as part of a sequence. An intuitive way to construct a covariant feature detector is to extract features in correspondence of images structures that are easily identifiable even after a transformation. Example of specific structures include dots, corners, and blobs. These will be generically indicated as **corners** in the followup. A covariant detector faces two challenges. First, corners have, in practice, an infinite variety of individual appearances and the detector must be able to capture them to be of general applicability. Second, the way corners are identified and detected must remain stable under transformations of the image. These two problems are addressed in @ref covdet-cornerness-localmax and @ref covdet-cornerness-normalization respectively. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section covdet-cornerness Detection using a cornerness measure <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> One way to decide whether an image region $R$ contains a corner is to compare the local appearance to a model or template of the corner; the result of this comparisons produces a *cornerness score* at that location. This page describe general theoretical properties of the cornerness and the detection process. Concrete examples of cornerness are given in @ref covdet-corner-types. A **cornerness measure** associate a score to all possible feature locations in an image $\ell$. As described in @ref covdet-frame, the location or, more in general, pose $u$ of a feature $R$ is the warp $w$ that maps the canonical feature frame $R_0$ to $R$: \[ R = u[R_0]. \] The goal of a cornerness measure is to associate a score $F(u;\ell)$ to all possible feature poses $u$ and use this score to extract a finite number of co-variant features from any image. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @subsection covdet-cornerness-localmax Local maxima of a cornerness measure <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> Given the cornerness of each candidate feature, the detector must extract a finite number of them. However, the cornerness of features with nearly identical pose must be similar (otherwise the cornerness measure would be unstable). As such, simply thresholding $F(w;\ell)$ would detect an infinite number of nearly identical features rather than a finite number. The solution is to detect features in correspondence of the local maxima of the score measure: \[ \{w_1,\dots,w_n\} = \operatorname{localmax}_{w\in\mathcal{W}} F(w;\ell). \] This also means that features are never detected in isolation, but by comparing neighborhoods of them. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @subsection covdet-cornerness-normalization Covariant detection by normalization <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> The next difficulty is to guarantee that detection is co-variant with image transformations. Hence, if $u$ is the pose of a feature extracted from image $\ell$, then the transformed pose $u' = w[u]$ must be detected in the transformed image $\ell' = w[\ell]$. Since features are extracted in correspondence of the local maxima of the cornerness score, a sufficient condition is that corresponding features attain the same score in the two images: \[ \forall u\in\mathcal{W}: \quad F(u;\ell) = F(w[u];w[\ell]), \qquad\text{or}\qquad F(u;\ell) = F(w \circ u ;\ell \circ w^{-1}). \] One simple way to satisfy this equation is to compute a cornerness score *after normalizing the image* by the inverse of the candidate feature pose warp $u$, as follows: \[ F(u;\ell) = F(1;u^{-1}[\ell]) = F(1;\ell \circ u) = \mathcal{F}(\ell \circ u), \] where $1 = u^{-1} \circ u$ is the identity transformation and $\mathcal{F}$ is an arbitrary functional. Intuitively, co-variant detection is obtained by looking if the appearance of the feature resembles a corner only *after normalization*. Formally: @f{align*} F(w[u];w[\ell]) &= F(w \circ u ;\ell \circ w^{-1}) \\ &= F(1; \ell \circ w^{-1} \circ w \circ u) \\ &= \mathcal{F}(\ell\circ u) \\ &= F(u;\ell). @f} Concrete examples of the functional $\mathcal{F}$ are given in @ref covdet-corner-types. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @subsection covdet-locality Locality of the detected features <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> In the definition above, the cornenress functional $\mathcal{F}$ is an arbitrary functional of the entire normalized image $u^{-1}[\ell]$. In practice, one is always interested in detecting **local features** (at the very least because the image extent is finite). This is easily obtained by considering a cornerness $\mathcal{F}$ which only looks in a small region of the normalized image, usually corresponding to the extent of the canonical feature $R_0$ (e.g. a unit disc centered at the origin). In this case the extent of the local feature in the original image is simply given by $R = u[R_0]$. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section covdet-partial Partial and iterated normalization <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> Practical detectors implement variants of the ideas above. Very often, for instance, detection is an iterative process, in which successive parameters of the pose of a feature are determined. For instance, it is typical to first detect the location and scale of a feature using a rotation-invariant cornerness score $\mathcal{F}$. Once these two parameters are known, the rotation can be determined using a different score, sensitive to the orientation of the local image structures. Certain detectors (such as Harris-Laplace and Hessian-Laplace) use even more sophisticated schemes, in which different scores are used to jointly (rather than in succession) different parameters of the pose of a feature, such as its translation and scale. While a formal treatment of these cases is possible as well, we point to the original papers. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @page covdet-differential Differential and integral image operations @tableofcontents <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> Dealing with covariant interest point detector requires working a good deal with derivatives, convolutions, and transformations of images. The notation and fundamental properties of interest here are discussed next. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section covdet-derivatives Derivative operations: gradients <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> For the derivatives, we borrow the notation of @cite{kinghorn96integrals}. Let $f: \mathbb{R}^m \rightarrow \mathbb{R}^n, \bx \mapsto f(\bx)$ be a vector function. The derivative of the function with respect to $\bx$ is given by its *Jacobian matrix* denoted by the symbol: \[ \frac{\partial f}{\partial \bx^\top} = \begin{bmatrix} \frac{\partial f_1}{x_1} & \frac{\partial f_1}{x_2} & \dots \\ \frac{\partial f_2}{x_1} & \frac{\partial f_2}{x_2} & \dots \\ \vdots & \vdots & \ddots \\ \end{bmatrix}. \] When the function $ f $ is scalar ($n=1$), the Jacobian is the same as the gradient of the function (or, in fact, its transpose). More precisely, the <b>gradient</b> $\nabla f $ of $ f $ denotes the column vector of partial derivatives: \[ \nabla f = \frac{\partial f}{\partial \bx} = \begin{bmatrix} \frac{\partial f}{\partial x_1} \\ \frac{\partial f}{\partial x_2} \\ \vdots \end{bmatrix}. \] The second derivative $H_f $ of a scalar function $ f $, or <b>Hessian</b>, is denoted as \[ H_f = \frac{\partial f}{\partial \bx \partial \bx^\top} = \frac{\partial \nabla f}{\partial \bx^\top} = \begin{bmatrix} \frac{\partial f}{\partial x_1 \partial x_1} & \frac{\partial f}{\partial x_1 \partial x_2} & \dots \\ \frac{\partial f}{\partial x_2 \partial x_1} & \frac{\partial f}{\partial x_2 \partial x_2} & \dots \\ \vdots & \vdots & \ddots \\ \end{bmatrix}. \] The determinant of the Hessian is also known as <b>Laplacian</b> and denoted as \[ \Delta f = \operatorname{det} H_f = \frac{\partial f}{\partial x_1^2} + \frac{\partial f}{\partial x_2^2} + \dots \] <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @subsection covdet-derivative-transformations Derivative and image warps <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> In the following, we will often been interested in domain warpings $u: \mathbb{R}^m \rightarrow \mathbb{R}^n, \bx \mapsto u(\bx)$ of a function $f(\bar\bx) $ and its effect on the derivatives of the function. The key transformation is the chain rule: \[ \frac{\partial f \circ u}{\partial \bx^\top} = \left(\frac{\partial f}{\partial \bar\bx^\top} \circ u\right) \frac{\partial u}{\partial \bx^\top} \] In particular, for an affine transformation $u = (A,T) : \bx \mapsto A\bx + T$, one obtains the transformation rules: \[ \begin{align*} \frac{\partial f \circ (A,T)}{\partial \bx^\top} &= \left(\frac{\partial f}{\partial \bar\bx^\top} \circ (A,T)\right)A, \\ \nabla (f \circ (A,T)) &= A^\top (\nabla f) \circ (A,T), \\ H_{f \circ(A,T)} &= A^\top (H_f \circ (A,T)) A, \\ \Delta (f \circ(A,T)) &= \det(A)^2\, (\Delta f) \circ (A,T). \end{align*} \] <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section covdet-smoothing Integral operations: smoothing <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> In practice, given an image $\ell$ expressed in digital format, good derivative approximations can be computed only if the bandwidth of the image is limited and, in particular, compatible with the sampling density. Since it is unreasonable to expect real images to be band-limited, the bandwidth is artificially constrained by suitably smoothing the image prior to computing its derivatives. This is also interpreted as a form of regularization or as a way of focusing on the image content at a particular scale. Formally, we will focus on Gaussian smoothing kernels. For the 2D case $\bx\in\real^2$, the Gaussian kernel of covariance $\Sigma$ is given by \[ g_{\Sigma}(\bx) = \frac{1}{2\pi \sqrt{\det\Sigma}} \exp\left( - \frac{1}{2} \bx^\top \Sigma^{-1} \bx \right). \] The symbol $g_{\sigma^2}$ will be used to denote a Gaussian kernel with isotropic standard deviation $\sigma$, i.e. $\Sigma = \sigma^2 I$. Given an image $\ell$, the symbol $\ell_\Sigma$ will be used to denote the image smoothed by the Gaussian kernel of parameter $\Sigma$: \[ \ell_\Sigma(\bx) = (g_\Sigma * \ell)(\bx) = \int_{\real^m} g_\Sigma(\bx - \by) \ell(\by)\,d\by. \] <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @subsection covdet-smoothing-transformations Smoothing and image warps <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> One advantage of Gaussian kernels is that they are (up to renormalization) closed under a linear warp: \[ |A|\, g_\Sigma \circ A = g_{A^{-1} \Sigma A^{-\top}} \] This also means that smoothing a warped image is the same as warping the result of smoothing the original image by a suitably adjusted Gaussian kernel: \[ g_{\Sigma} * (\ell \circ (A,T)) = (g_{A\Sigma A^\top} * \ell) \circ (A,T). \] <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @page covdet-corner-types Cornerness measures @tableofcontents <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> The goal of a cornerness measure (@ref covdet-cornerness) is to associate to an image patch a score proportional to how strongly the patch contain a certain strucuture, for example a corner or a blob. This page reviews the most important cornerness measures as implemented in VLFeat: - @ref covdet-harris - @ref covdet-laplacian - @ref covdet-hessian This page makes use of notation introduced in @ref covdet-differential. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section covdet-harris Harris corners <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> This section introduces the fist of the cornerness measure $\mathcal{F}[\ell]$. Recall (@ref covdet-cornerness) that the goal of this functional is to respond strongly to images $\ell$ of corner-like structure. Rather than explicitly encoding the appearance of corners, the idea of the Harris measure is to label as corner *any* image patch whose appearance is sufficiently distinctive to allow accurate localization. In particular, consider an image patch $\ell(\bx), \bx\in\Omega$, where $\Omega$ is a smooth circular window of radius approximately $\sigma_i$; at necessary condition for the patch to allow accurate localization is that even a small translation $\ell(\bx+\delta)$ causes the appearance to vary significantly (if not the origin and location $\delta$ would not be distinguishable from the image alone). This variation is measured by the sum of squared differences \[ E(\delta) = \int g_{\sigma_i^2}(\bx) (\ell_{\sigma_d^2}(\bx+\delta) - \ell_{\sigma_d^2}(\bx))^2 \,d\bx \] Note that images are compared at scale $\sigma_d$, known as *differentiation scale* for reasons that will be clear in a moment, and that the squared differences are summed over a window softly defined by $\sigma_i$, also known as *integration scale*. This function can be approximated as $E(\delta)\approx \delta^\top M[\ell;\sigma_i^2,\sigma_d^2] \delta$ where \[ M[\ell;\sigma_i^2,\sigma_d^2] = \int g_{\sigma_i^2}(\bx) (\nabla \ell_{\sigma_d^2}(\bx)) (\nabla \ell_{\sigma_d^2}(\bx))^\top \, d\bx. \] is the so called **structure tensor**. A corner is identified when the sum of squared differences $E(\delta)$ is large for displacements $\delta$ in all directions. This condition is obtained when both the eignenvalues $\lambda_1,\lambda_2$ of the structure tensor $M$ are large. The **Harris cornerness measure** captures this fact: \[ \operatorname{Harris}[\ell;\sigma_i^2,\sigma_d^2] = \det M - \kappa \operatorname{trace}^2 M = \lambda_1\lambda_2 - \kappa (\lambda_1+\lambda_2)^2 \] <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @subsection covdet-harris-warped Harris in the warped domain <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> The cornerness measure of a feature a location $u$ (recall that locations $u$ are in general defined as image warps) should be computed after normalizing the image (by applying to it the warp $u^{-1}$). This section shows that, for affine warps, the Harris cornerness measure can be computed directly in the Gaussian affine scale space of the image. In particular, for similarities, it can be computed in the standard Gaussian scale space. To this end, let $u=(A,T)$ be an affine warp identifying a feature location in image $\ell(\bx)$. Let $\bar\ell(\bar\bx) = \ell(A\bar\bx+T)$ be the normalized image and rewrite the structure tensor of the normalized image as follows: \[ M[\bar\ell; \bar\Sigma_i, \bar\Sigma_d] = M[\bar\ell; \bar\Sigma_i, \bar\Sigma_d](\mathbf{0}) = \left[ g_{\bar\Sigma_i} * (\nabla\bar\ell_{\bar\Sigma_d}) (\nabla\bar\ell_{\bar\Sigma_d})^\top \right](\mathbf{0}) \] This notation emphasizes that the structure tensor is obtained by taking derivatives and convolutions of the image. Using the fact that $\nabla g_{\bar\Sigma_d} * \bar\ell = A^\top (\nabla g_{A\bar\Sigma A^\top} * \ell) \circ (A,T)$ and that $g_{\bar\Sigma} * \bar \ell = (g_{A\bar\Sigma A^\top} * \ell) \circ (A,T)$, we get the equivalent expression: \[ M[\bar\ell; \bar\Sigma_i, \bar\Sigma_d](\mathbf{0}) = A^\top \left[ g_{A\bar\Sigma_i A^\top} * (\nabla\ell_{A\bar\Sigma_dA^\top})(\nabla\ell_{A\bar\Sigma_d A^\top})^\top \right](A\mathbf{0}+T) A. \] In other words, the structure tensor of the normalized image can be computed as: \[ M[\bar\ell; \bar\Sigma_i, \bar\Sigma_d](\mathbf{0}) = A^\top M[\ell; \Sigma_i, \Sigma_d](T) A, \quad \Sigma_{i} = A\bar\Sigma_{i}A^\top, \quad \Sigma_{d} = A\bar\Sigma_{d}A^\top. \] This equation allows to compute the structure tensor for feature at all locations directly in the original image. In particular, features at all translations $T$ can be evaluated efficiently by computing convolutions and derivatives of the image $\ell_{A\bar\Sigma_dA^\top}$. A case of particular instance is when $\bar\Sigma_i= \bar\sigma_i^2 I$ and $\bar\Sigma_d = \bar\sigma_d^2$ are both isotropic covariance matrices and the affine transformation is a similarity $A=sR$. Using the fact that $\det\left( s^2 R^\top M R \right)= s^4 \det M$ and $\operatorname{tr}\left(s^2 R^\top M R\right) = s^2 \operatorname{tr} M$, one obtains the relation \[ \operatorname{Harris}[\bar \ell;\bar\sigma_i^2,\bar\sigma_d^2] = s^4 \operatorname{Harris}[\ell;s^2\bar\sigma_i^2,s^2\bar\sigma_d^2](T). \] This equation indicates that, for similarity transformations, not only the structure tensor, but directly the Harris cornerness measure can be computed on the original image and then be transferred back to the normalized domain. Note, however, that this requires rescaling the measure by the factor $s^4$. Another important consequence of this relation is that the Harris measure is invariant to pure image rotations. It cannot, therefore, be used to associate an orientation to the detected features. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section covdet-hessian Hessian blobs <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> The *(determinant of the) Hessian* cornerness measure is given determinant of the Hessian of the image: \[ \operatorname{DetHess}[\ell;\sigma_d^2] = \det H_{g_{\sigma_d^2} * \ell}(\mathbf{0}) \] This number is large and positive if the image is locally curved (peaked), roughly corresponding to blob-like structures in the image. In particular, a large score requires the product of the eigenvalues of the Hessian to be large, which requires both of them to have the same sign and are large in absolute value. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @subsection covdet-hessian-warped Hessian in the warped domain <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> Similarly to the Harris measure, it is possible to work with the Hessian measure on the original unnormalized image. As before, let $\bar\ell(\bar\bx) = \ell(A\bar\bx+T)$ be the normalized image and rewrite the Hessian of the normalized image as follows: \[ H_{g_{\bar\Sigma_d} * \bar\ell}(\mathbf{0}) = A^\top \left(H_{g_{\Sigma_d} * \ell}(T)\right) A. \] Then \[ \operatorname{DetHess}[\bar\ell;\bar\Sigma_d] = (\det A)^2 \operatorname{DetHess}[\ell;A\bar\Sigma_d A^\top](T). \] In particular, for isotropic covariance matrices and similarity transformations $A=sR$: \[ \operatorname{DetHess}[\bar\ell;\bar\sigma_d^2] = s^4 \operatorname{DetHess}[\ell;s^2\bar\sigma_d^2](T) \] <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section covdet-laplacian Laplacian and Difference of Gaussians blobs <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> The **Laplacian of Gaussian (LoG)** or **trace of the Hessian** cornerness measure is given by the trace of the Hessian of the image: \[ \operatorname{Lap}[\ell;\sigma_d^2] = \operatorname{tr} H_{g_{\sigma_d}^2 * \ell} \] <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @subsection covdet-laplacian-warped Laplacian in the warped domain <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> Similarly to the Hessian measure, the Laplacian cornenress can often be efficiently computed for features at all locations in the original unnormalized image domain. In particular, if the derivative covariance matrix $\Sigma_d$ is isotropic and one considers as warpings similarity transformations $A=sR$, where $R$ is a rotatin and $s$ a rescaling, one has \[ \operatorname{Lap}[\bar\ell;\bar\sigma_d^2] = s^2 \operatorname{Lap}[\ell;s^2\bar\sigma_d^2](T) \] Note that, comparing to the Harris and determinant of Hessian measures, the scaling for the Laplacian is $s^2$ rather than $s^4$. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @subsection covdet-laplacian-matched Laplacian as a matched filter <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> The Laplacian is given by the trace of the Hessian operator. Differently from the determinant of the Hessian, this is a linear operation. This means that computing the Laplacian cornerness measure can be seen as applying a linear filtering operator to the image. This filter can then be interpreted as a *template* of a corner being matched to the image. Hence, the Laplacian cornerness measure can be interpreted as matching this corner template at all possible image locations. To see this formally, compute the Laplacian score in the input image domain: \[ \operatorname{Lap}[\bar\ell;\bar\sigma_d^2] = s^2 \operatorname{Lap}[\ell;s^2\bar\sigma_d^2](T) = s^2 (\Delta g_{s^2\bar\sigma_d^2} * \ell)(T) \] The Laplacian fitler is obtained by moving the Laplacian operator from the image to the Gaussian smoothing kernel: \[ s^2 (\Delta g_{s^2\bar\sigma_d^2} * \ell) = (s^2 \Delta g_{s^2\bar\sigma_d^2}) * \ell \] Note that the filter is rescaled by the $s^2$; sometimes, this factor is incorporated in the Laplacian operator, yielding the so-called normalized Laplacian. The Laplacian of Gaussian is also called *top-hat function* and has the expression: \[ \Delta g_{\sigma^2}(x,y) = \frac{x^2+y^2 - 2 \sigma^2}{\sigma^4} g_{\sigma^2}(x,y). \] This filter, which acts as corner template, resembles a blob (a dark disk surrounded by a bright ring). <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @subsection covdet-laplacian-dog Difference of Gaussians <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> The **Difference of Gaussian** (DoG) cornerness measure can be interpreted as an approximation of the Laplacian that is easy to obtain once a scalespace of the input image has been computed. As noted above, the Laplacian cornerness of the normalized feature can be computed directly from the input image by convolving the image by the normalized Laplacian of Gaussian filter $s^2 \Delta g_{s^2\bar\sigma_d^2}$. Like the other derivative operators, this filter is simpe to discriteize. However, it is often approximated by computing the the *Difference of Gaussians* (DoG) approximation instead. This approximation is obtained from the easily-proved identity: \[ \frac{\partial}{\partial \sigma} g_{\sigma^2} = \sigma \Delta g_{\sigma^2}. \] This indicates that computing the normalized Laplacian of a Gaussian filter is, in the limit, the same as taking the difference between Gaussian filters of slightly increasing standard deviation $\sigma$ and $\kappa\sigma$, where $\kappa \approx 1$: \[ \sigma^2 \Delta g_{\sigma^2} \approx \sigma \frac{g_{(\kappa\sigma)^2} - g_{\sigma^2}}{\kappa\sigma - \sigma} = \frac{1}{\kappa - 1} (g_{(\kappa\sigma)^2} - g_{\sigma^2}). \] One nice propery of this expression is that the factor $\sigma$ cancels out in the right-hand side. Usually, scales $\sigma$ and $\kappa\sigma$ are pre-computed in the image scale-space and successive scales are sampled with uniform geometric spacing, meaning that the factor $\kappa$ is the same for all scales. Then, up to a overall scaling factor, the LoG cornerness measure can be obtained by taking the difference of successive scale space images $\ell_{(\kappa\sigma)^2}$ and $\ell_{\sigma^2}$. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @page covdet-affine-adaptation Affine adaptation <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @page covdet-dominant-orientation Dominant orientation <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> **/ #include "covdet.h" #include <string.h> /** @brief Reallocate buffer ** @param buffer ** @param bufferSize ** @param targetSize ** @return error code **/ static int _vl_resize_buffer (void ** buffer, vl_size * bufferSize, vl_size targetSize) { void * newBuffer ; if (*buffer == NULL) { *buffer = vl_malloc(targetSize) ; if (*buffer) { *bufferSize = targetSize ; return VL_ERR_OK ; } else { *bufferSize = 0 ; return VL_ERR_ALLOC ; } } newBuffer = vl_realloc(*buffer, targetSize) ; if (newBuffer) { *buffer = newBuffer ; *bufferSize = targetSize ; return VL_ERR_OK ; } else { return VL_ERR_ALLOC ; } } /** @brief Enlarge buffer ** @param buffer ** @param bufferSize ** @param targetSize ** @return error code **/ static int _vl_enlarge_buffer (void ** buffer, vl_size * bufferSize, vl_size targetSize) { if (*bufferSize >= targetSize) return VL_ERR_OK ; return _vl_resize_buffer(buffer,bufferSize,targetSize) ; } /* ---------------------------------------------------------------- */ /* Finding local extrema */ /* ---------------------------------------------------------------- */ /* Todo: make this generally available in the library */ typedef struct _VlCovDetExtremum2 { vl_index xi ; vl_index yi ; float x ; float y ; float peakScore ; float edgeScore ; } VlCovDetExtremum2 ; typedef struct _VlCovDetExtremum3 { vl_index xi ; vl_index yi ; vl_index zi ; float x ; float y ; float z ; float peakScore ; float edgeScore ; } VlCovDetExtremum3 ; VL_EXPORT vl_size vl_find_local_extrema_3 (vl_index ** extrema, vl_size * bufferSize, float const * map, vl_size width, vl_size height, vl_size depth, double threshold) ; VL_EXPORT vl_size vl_find_local_extrema_2 (vl_index ** extrema, vl_size * bufferSize, float const * map, vl_size width, vl_size height, double threshold) ; VL_EXPORT vl_bool vl_refine_local_extreum_3 (VlCovDetExtremum3 * refined, float const * map, vl_size width, vl_size height, vl_size depth, vl_index x, vl_index y, vl_index z) ; VL_EXPORT vl_bool vl_refine_local_extreum_2 (VlCovDetExtremum2 * refined, float const * map, vl_size width, vl_size height, vl_index x, vl_index y) ; /** @internal ** @brief Find the extrema of a 3D function ** @param extrema buffer containing the extrema found (in/out). ** @param bufferSize size of the @a extrema buffer in bytes (in/out). ** @param map a 3D array representing the map. ** @param width of the map. ** @param height of the map. ** @param depth of the map. ** @param threshold minumum extremum value. ** @return number of extrema found. ** @see @ref ::vl_refine_local_extreum_2. **/ vl_size vl_find_local_extrema_3 (vl_index ** extrema, vl_size * bufferSize, float const * map, vl_size width, vl_size height, vl_size depth, double threshold) { vl_index x, y, z ; vl_size const xo = 1 ; vl_size const yo = width ; vl_size const zo = width * height ; float const *pt = map + xo + yo + zo ; vl_size numExtrema = 0 ; vl_size requiredSize = 0 ; #define CHECK_NEIGHBORS_3(v,CMP,SGN) (\ v CMP ## = SGN threshold && \ v CMP *(pt + xo) && \ v CMP *(pt - xo) && \ v CMP *(pt + zo) && \ v CMP *(pt - zo) && \ v CMP *(pt + yo) && \ v CMP *(pt - yo) && \ \ v CMP *(pt + yo + xo) && \ v CMP *(pt + yo - xo) && \ v CMP *(pt - yo + xo) && \ v CMP *(pt - yo - xo) && \ \ v CMP *(pt + xo + zo) && \ v CMP *(pt - xo + zo) && \ v CMP *(pt + yo + zo) && \ v CMP *(pt - yo + zo) && \ v CMP *(pt + yo + xo + zo) && \ v CMP *(pt + yo - xo + zo) && \ v CMP *(pt - yo + xo + zo) && \ v CMP *(pt - yo - xo + zo) && \ \ v CMP *(pt + xo - zo) && \ v CMP *(pt - xo - zo) && \ v CMP *(pt + yo - zo) && \ v CMP *(pt - yo - zo) && \ v CMP *(pt + yo + xo - zo) && \ v CMP *(pt + yo - xo - zo) && \ v CMP *(pt - yo + xo - zo) && \ v CMP *(pt - yo - xo - zo) ) for (z = 1 ; z < (signed)depth - 1 ; ++z) { for (y = 1 ; y < (signed)height - 1 ; ++y) { for (x = 1 ; x < (signed)width - 1 ; ++x) { float value = *pt ; if (CHECK_NEIGHBORS_3(value,>,+) || CHECK_NEIGHBORS_3(value,<,-)) { numExtrema ++ ; requiredSize += sizeof(vl_index) * 3 ; if (*bufferSize < requiredSize) { int err = _vl_resize_buffer((void**)extrema, bufferSize, requiredSize + 2000 * 3 * sizeof(vl_index)) ; if (err != VL_ERR_OK) abort() ; } (*extrema) [3 * (numExtrema - 1) + 0] = x ; (*extrema) [3 * (numExtrema - 1) + 1] = y ; (*extrema) [3 * (numExtrema - 1) + 2] = z ; } pt += xo ; } pt += 2*xo ; } pt += 2*yo ; } return numExtrema ; } /** @internal ** @brief Find extrema in a 2D function ** @param extrema buffer containing the found extrema (in/out). ** @param bufferSize size of the @a extrema buffer in bytes (in/out). ** @param map a 3D array representing the map. ** @param width of the map. ** @param height of the map. ** @param threshold minumum extremum value. ** @return number of extrema found. ** ** An extremum contains 2 ::vl_index values; they are arranged ** sequentially. ** ** The function can reuse an already allocated buffer if ** @a extrema and @a bufferSize are initialized on input. ** It may have to @a realloc the memory if the buffer is too small. **/ vl_size vl_find_local_extrema_2 (vl_index ** extrema, vl_size * bufferSize, float const* map, vl_size width, vl_size height, double threshold) { vl_index x, y ; vl_size const xo = 1 ; vl_size const yo = width ; float const *pt = map + xo + yo ; vl_size numExtrema = 0 ; vl_size requiredSize = 0 ; #define CHECK_NEIGHBORS_2(v,CMP,SGN) (\ v CMP ## = SGN threshold && \ v CMP *(pt + xo) && \ v CMP *(pt - xo) && \ v CMP *(pt + yo) && \ v CMP *(pt - yo) && \ \ v CMP *(pt + yo + xo) && \ v CMP *(pt + yo - xo) && \ v CMP *(pt - yo + xo) && \ v CMP *(pt - yo - xo) ) for (y = 1 ; y < (signed)height - 1 ; ++y) { for (x = 1 ; x < (signed)width - 1 ; ++x) { float value = *pt ; if (CHECK_NEIGHBORS_2(value,>,+) || CHECK_NEIGHBORS_2(value,<,-)) { numExtrema ++ ; requiredSize += sizeof(vl_index) * 2 ; if (*bufferSize < requiredSize) { int err = _vl_resize_buffer((void**)extrema, bufferSize, requiredSize + 2000 * 2 * sizeof(vl_index)) ; if (err != VL_ERR_OK) abort() ; } (*extrema) [2 * (numExtrema - 1) + 0] = x ; (*extrema) [2 * (numExtrema - 1) + 1] = y ; } pt += xo ; } pt += 2*xo ; } return numExtrema ; } /** @internal ** @brief Refine the location of a local extremum of a 3D map ** @param refined refined extremum (out). ** @param map a 3D array representing the map. ** @param width of the map. ** @param height of the map. ** @param depth of the map. ** @param x initial x position. ** @param y initial y position. ** @param z initial z position. ** @return a flat indicating whether the extrema refinement was stable. **/ VL_EXPORT vl_bool vl_refine_local_extreum_3 (VlCovDetExtremum3 * refined, float const * map, vl_size width, vl_size height, vl_size depth, vl_index x, vl_index y, vl_index z) { vl_size const xo = 1 ; vl_size const yo = width ; vl_size const zo = width * height ; double Dx=0,Dy=0,Dz=0,Dxx=0,Dyy=0,Dzz=0,Dxy=0,Dxz=0,Dyz=0 ; double A [3*3], b [3] ; #define at(dx,dy,dz) (*(pt + (dx)*xo + (dy)*yo + (dz)*zo)) #define Aat(i,j) (A[(i)+(j)*3]) float const * pt ; vl_index dx = 0 ; vl_index dy = 0 ; /*vl_index dz = 0 ;*/ vl_index iter ; int err ; assert (map) ; assert (1 <= x && x <= (signed)width - 2) ; assert (1 <= y && y <= (signed)height - 2) ; assert (1 <= z && z <= (signed)depth - 2) ; for (iter = 0 ; iter < 5 ; ++iter) { x += dx ; y += dy ; pt = map + x*xo + y*yo + z*zo ; /* compute the gradient */ Dx = 0.5 * (at(+1,0,0) - at(-1,0,0)) ; Dy = 0.5 * (at(0,+1,0) - at(0,-1,0)); Dz = 0.5 * (at(0,0,+1) - at(0,0,-1)) ; /* compute the Hessian */ Dxx = (at(+1,0,0) + at(-1,0,0) - 2.0 * at(0,0,0)) ; Dyy = (at(0,+1,0) + at(0,-1,0) - 2.0 * at(0,0,0)) ; Dzz = (at(0,0,+1) + at(0,0,-1) - 2.0 * at(0,0,0)) ; Dxy = 0.25 * (at(+1,+1,0) + at(-1,-1,0) - at(-1,+1,0) - at(+1,-1,0)) ; Dxz = 0.25 * (at(+1,0,+1) + at(-1,0,-1) - at(-1,0,+1) - at(+1,0,-1)) ; Dyz = 0.25 * (at(0,+1,+1) + at(0,-1,-1) - at(0,-1,+1) - at(0,+1,-1)) ; /* solve linear system */ Aat(0,0) = Dxx ; Aat(1,1) = Dyy ; Aat(2,2) = Dzz ; Aat(0,1) = Aat(1,0) = Dxy ; Aat(0,2) = Aat(2,0) = Dxz ; Aat(1,2) = Aat(2,1) = Dyz ; b[0] = - Dx ; b[1] = - Dy ; b[2] = - Dz ; err = vl_solve_linear_system_3(b, A, b) ; if (err != VL_ERR_OK) { b[0] = 0 ; b[1] = 0 ; b[2] = 0 ; break ; } /* Keep going if there is sufficient translation */ dx = (b[0] > 0.6 && x < (signed)width - 2 ? 1 : 0) + (b[0] < -0.6 && x > 1 ? -1 : 0) ; dy = (b[1] > 0.6 && y < (signed)height - 2 ? 1 : 0) + (b[1] < -0.6 && y > 1 ? -1 : 0) ; if (dx == 0 && dy == 0) break ; } /* check threshold and other conditions */ { double peakScore = at(0,0,0) + 0.5 * (Dx * b[0] + Dy * b[1] + Dz * b[2]) ; double alpha = (Dxx+Dyy)*(Dxx+Dyy) / (Dxx*Dyy - Dxy*Dxy) ; double edgeScore ; if (alpha < 0) { /* not an extremum */ edgeScore = VL_INFINITY_D ; } else { edgeScore = (0.5*alpha - 1) + sqrt(VL_MAX(0.25*alpha - 1,0)*alpha) ; } refined->xi = x ; refined->yi = y ; refined->zi = z ; refined->x = x + b[0] ; refined->y = y + b[1] ; refined->z = z + b[2] ; refined->peakScore = peakScore ; refined->edgeScore = edgeScore ; return err == VL_ERR_OK && vl_abs_d(b[0]) < 1.5 && vl_abs_d(b[1]) < 1.5 && vl_abs_d(b[2]) < 1.5 && 0 <= refined->x && refined->x <= (signed)width - 1 && 0 <= refined->y && refined->y <= (signed)height - 1 && 0 <= refined->z && refined->z <= (signed)depth - 1 ; } #undef Aat #undef at } /** @internal ** @brief Refine the location of a local extremum of a 2D map ** @param refined refined extremum (out). ** @param map a 2D array representing the map. ** @param width of the map. ** @param height of the map. ** @param x initial x position. ** @param y initial y position. ** @return a flat indicating whether the extrema refinement was stable. **/ VL_EXPORT vl_bool vl_refine_local_extreum_2 (VlCovDetExtremum2 * refined, float const * map, vl_size width, vl_size height, vl_index x, vl_index y) { vl_size const xo = 1 ; vl_size const yo = width ; double Dx=0,Dy=0,Dxx=0,Dyy=0,Dxy=0; double A [2*2], b [2] ; #define at(dx,dy) (*(pt + (dx)*xo + (dy)*yo )) #define Aat(i,j) (A[(i)+(j)*2]) float const * pt ; vl_index dx = 0 ; vl_index dy = 0 ; vl_index iter ; int err ; assert (map) ; assert (1 <= x && x <= (signed)width - 2) ; assert (1 <= y && y <= (signed)height - 2) ; for (iter = 0 ; iter < 5 ; ++iter) { x += dx ; y += dy ; pt = map + x*xo + y*yo ; /* compute the gradient */ Dx = 0.5 * (at(+1,0) - at(-1,0)) ; Dy = 0.5 * (at(0,+1) - at(0,-1)); /* compute the Hessian */ Dxx = (at(+1,0) + at(-1,0) - 2.0 * at(0,0)) ; Dyy = (at(0,+1) + at(0,-1) - 2.0 * at(0,0)) ; Dxy = 0.25 * (at(+1,+1) + at(-1,-1) - at(-1,+1) - at(+1,-1)) ; /* solve linear system */ Aat(0,0) = Dxx ; Aat(1,1) = Dyy ; Aat(0,1) = Aat(1,0) = Dxy ; b[0] = - Dx ; b[1] = - Dy ; err = vl_solve_linear_system_2(b, A, b) ; if (err != VL_ERR_OK) { b[0] = 0 ; b[1] = 0 ; break ; } /* Keep going if there is sufficient translation */ dx = (b[0] > 0.6 && x < (signed)width - 2 ? 1 : 0) + (b[0] < -0.6 && x > 1 ? -1 : 0) ; dy = (b[1] > 0.6 && y < (signed)height - 2 ? 1 : 0) + (b[1] < -0.6 && y > 1 ? -1 : 0) ; if (dx == 0 && dy == 0) break ; } /* check threshold and other conditions */ { double peakScore = at(0,0) + 0.5 * (Dx * b[0] + Dy * b[1]) ; double alpha = (Dxx+Dyy)*(Dxx+Dyy) / (Dxx*Dyy - Dxy*Dxy) ; double edgeScore ; if (alpha < 0) { /* not an extremum */ edgeScore = VL_INFINITY_D ; } else { edgeScore = (0.5*alpha - 1) + sqrt(VL_MAX(0.25*alpha - 1,0)*alpha) ; } refined->xi = x ; refined->yi = y ; refined->x = x + b[0] ; refined->y = y + b[1] ; refined->peakScore = peakScore ; refined->edgeScore = edgeScore ; return err == VL_ERR_OK && vl_abs_d(b[0]) < 1.5 && vl_abs_d(b[1]) < 1.5 && 0 <= refined->x && refined->x <= (signed)width - 1 && 0 <= refined->y && refined->y <= (signed)height - 1 ; } #undef Aat #undef at } /* ---------------------------------------------------------------- */ /* Covarant detector */ /* ---------------------------------------------------------------- */ #define VL_COVDET_MAX_NUM_ORIENTATIONS 4 #define VL_COVDET_MAX_NUM_LAPLACIAN_SCALES 4 #define VL_COVDET_AA_PATCH_RESOLUTION 20 #define VL_COVDET_AA_MAX_NUM_ITERATIONS 15 #define VL_COVDET_OR_NUM_ORIENTATION_HISTOGAM_BINS 36 #define VL_COVDET_AA_RELATIVE_INTEGRATION_SIGMA 3 #define VL_COVDET_AA_RELATIVE_DERIVATIVE_SIGMA 1 #define VL_COVDET_AA_MAX_ANISOTROPY 5 #define VL_COVDET_AA_CONVERGENCE_THRESHOLD 1.001 #define VL_COVDET_AA_ACCURATE_SMOOTHING VL_FALSE #define VL_COVDET_AA_PATCH_EXTENT (3*VL_COVDET_AA_RELATIVE_INTEGRATION_SIGMA) #define VL_COVDET_OR_ADDITIONAL_PEAKS_RELATIVE_SIZE 0.8 #define VL_COVDET_LAP_NUM_LEVELS 10 #define VL_COVDET_LAP_PATCH_RESOLUTION 16 #define VL_COVDET_LAP_DEF_PEAK_THRESHOLD 0.01 #define VL_COVDET_DOG_DEF_PEAK_THRESHOLD VL_COVDET_LAP_DEF_PEAK_THRESHOLD #define VL_COVDET_DOG_DEF_EDGE_THRESHOLD 10.0 #define VL_COVDET_HARRIS_DEF_PEAK_THRESHOLD 0.000002 #define VL_COVDET_HARRIS_DEF_EDGE_THRESHOLD 10.0 #define VL_COVDET_HESSIAN_DEF_PEAK_THRESHOLD 0.003 #define VL_COVDET_HESSIAN_DEF_EDGE_THRESHOLD 10.0 #define VL_COVDET_GSS_BASE_SCALE 1.6 /** @brief Covariant feature detector */ struct _VlCovDet { VlScaleSpace *gss ; /**< Gaussian scale space. */ VlScaleSpace *css ; /**< Cornerness scale space. */ VlCovDetMethod method ; /**< feature extraction method. */ double peakThreshold ; /**< peak threshold. */ double edgeThreshold ; /**< edge threshold. */ double lapPeakThreshold; /**< peak threshold for Laplacian scale selection. */ vl_size octaveResolution ; /**< resolution of each octave. */ vl_index numOctaves ; /**< number of octaves */ vl_index firstOctave ; /**< index of the first octave. */ double baseScale ; /**< the base scale of the gss. */ vl_size maxNumOrientations ; /**< max number of detected orientations. */ double nonExtremaSuppression ; vl_size numNonExtremaSuppressed ; VlCovDetFeature *features ; vl_size numFeatures ; vl_size numFeatureBufferSize ; float * patch ; vl_size patchBufferSize ; vl_bool transposed ; VlCovDetFeatureOrientation orientations [VL_COVDET_MAX_NUM_ORIENTATIONS] ; VlCovDetFeatureLaplacianScale scales [VL_COVDET_MAX_NUM_LAPLACIAN_SCALES] ; vl_bool aaAccurateSmoothing ; float aaPatch [(2*VL_COVDET_AA_PATCH_RESOLUTION+1)*(2*VL_COVDET_AA_PATCH_RESOLUTION+1)] ; float aaPatchX [(2*VL_COVDET_AA_PATCH_RESOLUTION+1)*(2*VL_COVDET_AA_PATCH_RESOLUTION+1)] ; float aaPatchY [(2*VL_COVDET_AA_PATCH_RESOLUTION+1)*(2*VL_COVDET_AA_PATCH_RESOLUTION+1)] ; float aaMask [(2*VL_COVDET_AA_PATCH_RESOLUTION+1)*(2*VL_COVDET_AA_PATCH_RESOLUTION+1)] ; float lapPatch [(2*VL_COVDET_LAP_PATCH_RESOLUTION+1)*(2*VL_COVDET_LAP_PATCH_RESOLUTION+1)] ; float laplacians [(2*VL_COVDET_LAP_PATCH_RESOLUTION+1)*(2*VL_COVDET_LAP_PATCH_RESOLUTION+1)*VL_COVDET_LAP_NUM_LEVELS] ; vl_size numFeaturesWithNumScales [VL_COVDET_MAX_NUM_LAPLACIAN_SCALES + 1] ; vl_bool allowPaddedWarping ; } ; VlEnumerator vlCovdetMethods [VL_COVDET_METHOD_NUM] = { {"DoG" , (vl_index)VL_COVDET_METHOD_DOG }, {"Hessian", (vl_index)VL_COVDET_METHOD_HESSIAN }, {"HessianLaplace", (vl_index)VL_COVDET_METHOD_HESSIAN_LAPLACE }, {"HarrisLaplace", (vl_index)VL_COVDET_METHOD_HARRIS_LAPLACE }, {"MultiscaleHessian", (vl_index)VL_COVDET_METHOD_MULTISCALE_HESSIAN}, {"MultiscaleHarris", (vl_index)VL_COVDET_METHOD_MULTISCALE_HARRIS }, {0, 0 } } ; /** @brief Create a new object instance ** @param method method for covariant feature detection. ** @return new covariant detector. **/ VlCovDet * vl_covdet_new (VlCovDetMethod method) { VlCovDet * self = vl_calloc(sizeof(VlCovDet),1) ; self->method = method ; self->octaveResolution = 3 ; self->numOctaves = -1 ; self->firstOctave = -1 ; self->baseScale = VL_COVDET_GSS_BASE_SCALE ; self->maxNumOrientations = VL_COVDET_MAX_NUM_ORIENTATIONS ; switch (self->method) { case VL_COVDET_METHOD_DOG : self->peakThreshold = VL_COVDET_DOG_DEF_PEAK_THRESHOLD ; self->edgeThreshold = VL_COVDET_DOG_DEF_EDGE_THRESHOLD ; self->lapPeakThreshold = 0 ; /* not used */ break ; case VL_COVDET_METHOD_HARRIS_LAPLACE: case VL_COVDET_METHOD_MULTISCALE_HARRIS: self->peakThreshold = VL_COVDET_HARRIS_DEF_PEAK_THRESHOLD ; self->edgeThreshold = VL_COVDET_HARRIS_DEF_EDGE_THRESHOLD ; self->lapPeakThreshold = VL_COVDET_LAP_DEF_PEAK_THRESHOLD ; break ; case VL_COVDET_METHOD_HESSIAN : case VL_COVDET_METHOD_HESSIAN_LAPLACE: case VL_COVDET_METHOD_MULTISCALE_HESSIAN: self->peakThreshold = VL_COVDET_HESSIAN_DEF_PEAK_THRESHOLD ; self->edgeThreshold = VL_COVDET_HESSIAN_DEF_EDGE_THRESHOLD ; self->lapPeakThreshold = VL_COVDET_LAP_DEF_PEAK_THRESHOLD ; break; default: assert(0) ; } self->nonExtremaSuppression = 0.5 ; self->features = NULL ; self->numFeatures = 0 ; self->numFeatureBufferSize = 0 ; self->patch = NULL ; self->patchBufferSize = 0 ; self->transposed = VL_FALSE ; self->aaAccurateSmoothing = VL_COVDET_AA_ACCURATE_SMOOTHING ; self->allowPaddedWarping = VL_TRUE ; { vl_index const w = VL_COVDET_AA_PATCH_RESOLUTION ; vl_index i,j ; double step = (2.0 * VL_COVDET_AA_PATCH_EXTENT) / (2*w+1) ; double sigma = VL_COVDET_AA_RELATIVE_INTEGRATION_SIGMA ; for (j = -w ; j <= w ; ++j) { for (i = -w ; i <= w ; ++i) { double dx = i*step/sigma ; double dy = j*step/sigma ; self->aaMask[(i+w) + (2*w+1)*(j+w)] = exp(-0.5*(dx*dx+dy*dy)) ; } } } { /* Covers one octave of Laplacian filters, from sigma=1 to sigma=2. The spatial sampling step is 0.5. */ vl_index s ; for (s = 0 ; s < VL_COVDET_LAP_NUM_LEVELS ; ++s) { double sigmaLap = pow(2.0, -0.5 + (double)s / (VL_COVDET_LAP_NUM_LEVELS - 1)) ; double const sigmaImage = 1.0 / sqrt(2.0) ; double const step = 0.5 * sigmaImage ; double const sigmaDelta = sqrt(sigmaLap*sigmaLap - sigmaImage*sigmaImage) ; vl_size const w = VL_COVDET_LAP_PATCH_RESOLUTION ; vl_size const num = 2 * w + 1 ; float * pt = self->laplacians + s * (num * num) ; memset(pt, 0, num * num * sizeof(float)) ; #define at(x,y) pt[(x+w)+(y+w)*(2*w+1)] at(0,0) = - 4.0 ; at(-1,0) = 1.0 ; at(+1,0) = 1.0 ; at(0,1) = 1.0 ; at(0,-1) = 1.0 ; #undef at vl_imsmooth_f(pt, num, pt, num, num, num, sigmaDelta / step, sigmaDelta / step) ; #if 0 { char name [200] ; snprintf(name, 200, "/tmp/%f-lap.pgm", sigmaDelta) ; vl_pgm_write_f(name, pt, num, num) ; } #endif } } return self ; } /** @brief Reset object ** @param self object. ** ** This function removes any buffered features and frees other ** internal buffers. **/ void vl_covdet_reset (VlCovDet * self) { if (self->features) { vl_free(self->features) ; self->features = NULL ; } if (self->css) { vl_scalespace_delete(self->css) ; self->css = NULL ; } if (self->gss) { vl_scalespace_delete(self->gss) ; self->gss = NULL ; } } /** @brief Delete object instance ** @param self object. **/ void vl_covdet_delete (VlCovDet * self) { vl_covdet_reset(self) ; if (self->patch) vl_free (self->patch) ; vl_free(self) ; } /** @brief Append a feature to the internal buffer. ** @param self object. ** @param feature a pointer to the feature to append. ** @return status. ** ** The feature is copied. The function may fail with @c status ** equal to ::VL_ERR_ALLOC if there is insufficient memory. **/ int vl_covdet_append_feature (VlCovDet * self, VlCovDetFeature const * feature) { vl_size requiredSize ; assert(self) ; assert(feature) ; self->numFeatures ++ ; requiredSize = self->numFeatures * sizeof(VlCovDetFeature) ; if (requiredSize > self->numFeatureBufferSize) { int err = _vl_resize_buffer((void**)&self->features, &self->numFeatureBufferSize, (self->numFeatures + 1000) * sizeof(VlCovDetFeature)) ; if (err) { self->numFeatures -- ; return err ; } } self->features[self->numFeatures - 1] = *feature ; return VL_ERR_OK ; } /* ---------------------------------------------------------------- */ /* Process a new image */ /* ---------------------------------------------------------------- */ /** @brief Detect features in an image ** @param self object. ** @param image image to process. ** @param width image width. ** @param height image height. ** @return status. ** ** @a width and @a height must be at least one pixel. The function ** fails by returing ::VL_ERR_ALLOC if the memory is insufficient. **/ int vl_covdet_put_image (VlCovDet * self, float const * image, vl_size width, vl_size height) { vl_size const minOctaveSize = 16 ; vl_index lastOctave ; vl_index octaveFirstSubdivision ; vl_index octaveLastSubdivision ; VlScaleSpaceGeometry geom = vl_scalespace_get_default_geometry(width,height) ; assert (self) ; assert (image) ; assert (width >= 1) ; assert (height >= 1) ; /* (minOctaveSize - 1) 2^lastOctave <= min(width,height) - 1 */ lastOctave = vl_floor_d(vl_log2_d(VL_MIN((double)width-1,(double)height-1) / (minOctaveSize - 1))) ; if (self->numOctaves > 0) { lastOctave = VL_MIN((vl_index)self->numOctaves - self->firstOctave - 1, lastOctave); } if (self->method == VL_COVDET_METHOD_DOG) { octaveFirstSubdivision = -1 ; octaveLastSubdivision = self->octaveResolution + 1 ; } else if (self->method == VL_COVDET_METHOD_HESSIAN) { octaveFirstSubdivision = -1 ; octaveLastSubdivision = self->octaveResolution ; } else { octaveFirstSubdivision = 0 ; octaveLastSubdivision = self->octaveResolution - 1 ; } geom.width = width ; geom.height = height ; geom.firstOctave = self->firstOctave ; geom.lastOctave = lastOctave ; geom.octaveResolution = self->octaveResolution ; geom.baseScale = self->baseScale * pow(2.0, 1.0 / self->octaveResolution) ; geom.octaveFirstSubdivision = octaveFirstSubdivision ; geom.octaveLastSubdivision = octaveLastSubdivision ; if (self->gss == NULL || ! vl_scalespacegeometry_is_equal (geom, vl_scalespace_get_geometry(self->gss))) { if (self->gss) vl_scalespace_delete(self->gss) ; self->gss = vl_scalespace_new_with_geometry(geom) ; if (self->gss == NULL) return VL_ERR_ALLOC ; } vl_scalespace_put_image(self->gss, image) ; return VL_ERR_OK ; } /* ---------------------------------------------------------------- */ /* Cornerness measures */ /* ---------------------------------------------------------------- */ /** @brief Scaled derminant of the Hessian filter ** @param hessian output image. ** @param image input image. ** @param width image width. ** @param height image height. ** @param step image sampling step (pixel size). ** @param sigma Gaussian smoothing of the input image. **/ static void _vl_det_hessian_response (float * hessian, float const * image, vl_size width, vl_size height, double step, double sigma) { float factor = (float) pow(sigma/step, 4.0) ; vl_index const xo = 1 ; /* x-stride */ vl_index const yo = width; /* y-stride */ vl_size r, c; float p11, p12, p13, p21, p22, p23, p31, p32, p33; /* setup input pointer to be centered at 0,1 */ float const *in = image + yo ; /* setup output pointer to be centered at 1,1 */ float *out = hessian + xo + yo; /* move 3x3 window and convolve */ for (r = 1; r < height - 1; ++r) { /* fill in shift registers at the beginning of the row */ p11 = in[-yo]; p12 = in[xo - yo]; p21 = in[ 0]; p22 = in[xo ]; p31 = in[+yo]; p32 = in[xo + yo]; /* setup input pointer to (2,1) of the 3x3 square */ in += 2; for (c = 1; c < width - 1; ++c) { float Lxx, Lyy, Lxy; /* fetch remaining values (last column) */ p13 = in[-yo]; p23 = *in; p33 = in[+yo]; /* Compute 3x3 Hessian values from pixel differences. */ Lxx = (-p21 + 2*p22 - p23); Lyy = (-p12 + 2*p22 - p32); Lxy = ((p11 - p31 - p13 + p33)/4.0f); /* normalize and write out */ *out = (Lxx * Lyy - Lxy * Lxy) * factor ; /* move window */ p11=p12; p12=p13; p21=p22; p22=p23; p31=p32; p32=p33; /* move input/output pointers */ in++; out++; } out += 2; } /* Copy the computed values to borders */ in = hessian + yo + xo ; out = hessian + xo ; /* Top row without corners */ memcpy(out, in, (width - 2)*sizeof(float)); out--; in -= yo; /* Left border columns without last row */ for (r = 0; r < height - 1; r++){ *out = *in; *(out + yo - 1) = *(in + yo - 3); in += yo; out += yo; } /* Bottom corners */ in -= yo; *out = *in; *(out + yo - 1) = *(in + yo - 3); /* Bottom row without corners */ out++; memcpy(out, in, (width - 2)*sizeof(float)); } /** @brief Scale-normalised Harris response ** @param harris output image. ** @param image input image. ** @param width image width. ** @param height image height. ** @param step image sampling step (pixel size). ** @param sigma Gaussian smoothing of the input image. ** @param sigmaI integration scale. ** @param alpha factor in the definition of the Harris score. **/ static void _vl_harris_response (float * harris, float const * image, vl_size width, vl_size height, double step, double sigma, double sigmaI, double alpha) { float factor = (float) pow(sigma/step, 4.0) ; vl_index k ; float * LxLx ; float * LyLy ; float * LxLy ; LxLx = vl_malloc(sizeof(float) * width * height) ; LyLy = vl_malloc(sizeof(float) * width * height) ; LxLy = vl_malloc(sizeof(float) * width * height) ; vl_imgradient_f (LxLx, LyLy, 1, width, image, width, height, width) ; for (k = 0 ; k < (signed)(width * height) ; ++k) { float dx = LxLx[k] ; float dy = LyLy[k] ; LxLx[k] = dx*dx ; LyLy[k] = dy*dy ; LxLy[k] = dx*dy ; } vl_imsmooth_f(LxLx, width, LxLx, width, height, width, sigmaI / step, sigmaI / step) ; vl_imsmooth_f(LyLy, width, LyLy, width, height, width, sigmaI / step, sigmaI / step) ; vl_imsmooth_f(LxLy, width, LxLy, width, height, width, sigmaI / step, sigmaI / step) ; for (k = 0 ; k < (signed)(width * height) ; ++k) { float a = LxLx[k] ; float b = LyLy[k] ; float c = LxLy[k] ; float determinant = a * b - c * c ; float trace = a + b ; harris[k] = factor * (determinant - alpha * (trace * trace)) ; } vl_free(LxLy) ; vl_free(LyLy) ; vl_free(LxLx) ; } /** @brief Difference of Gaussian ** @param dog output image. ** @param level1 input image at the smaller Gaussian scale. ** @param level2 input image at the larger Gaussian scale. ** @param width image width. ** @param height image height. **/ static void _vl_dog_response (float * dog, float const * level1, float const * level2, vl_size width, vl_size height) { vl_index k ; for (k = 0 ; k < (signed)(width*height) ; ++k) { dog[k] = level2[k] - level1[k] ; } } /* ---------------------------------------------------------------- */ /* Detect features */ /* ---------------------------------------------------------------- */ /** @brief Detect scale-space features ** @param self object. ** ** This function runs the configured feature detector on the image ** that was passed by using ::vl_covdet_put_image. **/ void vl_covdet_detect (VlCovDet * self) { VlScaleSpaceGeometry geom = vl_scalespace_get_geometry(self->gss) ; VlScaleSpaceGeometry cgeom ; float * levelxx = NULL ; float * levelyy = NULL ; float * levelxy = NULL ; vl_index o, s ; assert (self) ; assert (self->gss) ; /* clear previous detections if any */ self->numFeatures = 0 ; /* prepare buffers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ cgeom = geom ; if (self->method == VL_COVDET_METHOD_DOG) { cgeom.octaveLastSubdivision -= 1 ; } if (!self->css || !vl_scalespacegeometry_is_equal(cgeom, vl_scalespace_get_geometry(self->css))) { if (self->css) vl_scalespace_delete(self->css) ; self->css = vl_scalespace_new_with_geometry(cgeom) ; } if (self->method == VL_COVDET_METHOD_HARRIS_LAPLACE || self->method == VL_COVDET_METHOD_MULTISCALE_HARRIS) { VlScaleSpaceOctaveGeometry oct = vl_scalespace_get_octave_geometry(self->gss, geom.firstOctave) ; levelxx = vl_malloc(oct.width * oct.height * sizeof(float)) ; levelyy = vl_malloc(oct.width * oct.height * sizeof(float)) ; levelxy = vl_malloc(oct.width * oct.height * sizeof(float)) ; } /* compute cornerness ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ for (o = cgeom.firstOctave ; o <= cgeom.lastOctave ; ++o) { VlScaleSpaceOctaveGeometry oct = vl_scalespace_get_octave_geometry(self->css, o) ; for (s = cgeom.octaveFirstSubdivision ; s <= cgeom.octaveLastSubdivision ; ++s) { float * level = vl_scalespace_get_level(self->gss, o, s) ; float * clevel = vl_scalespace_get_level(self->css, o, s) ; double sigma = vl_scalespace_get_level_sigma(self->css, o, s) ; switch (self->method) { case VL_COVDET_METHOD_DOG: _vl_dog_response(clevel, vl_scalespace_get_level(self->gss, o, s + 1), level, oct.width, oct.height) ; break ; case VL_COVDET_METHOD_HARRIS_LAPLACE: case VL_COVDET_METHOD_MULTISCALE_HARRIS: _vl_harris_response(clevel, level, oct.width, oct.height, oct.step, sigma, 1.4 * sigma, 0.05) ; break ; case VL_COVDET_METHOD_HESSIAN: case VL_COVDET_METHOD_HESSIAN_LAPLACE: case VL_COVDET_METHOD_MULTISCALE_HESSIAN: _vl_det_hessian_response(clevel, level, oct.width, oct.height, oct.step, sigma) ; break ; default: assert(0) ; } } } /* find and refine local maxima ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ { vl_index * extrema = NULL ; vl_size extremaBufferSize = 0 ; vl_size numExtrema ; vl_size index ; for (o = cgeom.firstOctave ; o <= cgeom.lastOctave ; ++o) { VlScaleSpaceOctaveGeometry octgeom = vl_scalespace_get_octave_geometry(self->css, o) ; double step = octgeom.step ; vl_size width = octgeom.width ; vl_size height = octgeom.height ; vl_size depth = cgeom.octaveLastSubdivision - cgeom.octaveFirstSubdivision + 1 ; switch (self->method) { case VL_COVDET_METHOD_DOG: case VL_COVDET_METHOD_HESSIAN: { /* scale-space extrema */ float const * octave = vl_scalespace_get_level(self->css, o, cgeom.octaveFirstSubdivision) ; numExtrema = vl_find_local_extrema_3(&extrema, &extremaBufferSize, octave, width, height, depth, 0.8 * self->peakThreshold); for (index = 0 ; index < numExtrema ; ++index) { VlCovDetExtremum3 refined ; VlCovDetFeature feature ; vl_bool ok ; memset(&feature, 0, sizeof(feature)) ; ok = vl_refine_local_extreum_3(&refined, octave, width, height, depth, extrema[3*index+0], extrema[3*index+1], extrema[3*index+2]) ; ok &= fabs(refined.peakScore) > self->peakThreshold ; ok &= refined.edgeScore < self->edgeThreshold ; if (ok) { double sigma = cgeom.baseScale * pow(2.0, o + (refined.z + cgeom.octaveFirstSubdivision) / cgeom.octaveResolution) ; feature.frame.x = refined.x * step ; feature.frame.y = refined.y * step ; feature.frame.a11 = sigma ; feature.frame.a12 = 0.0 ; feature.frame.a21 = 0.0 ; feature.frame.a22 = sigma ; feature.peakScore = refined.peakScore ; feature.edgeScore = refined.edgeScore ; vl_covdet_append_feature(self, &feature) ; } } break ; } default: { for (s = cgeom.octaveFirstSubdivision ; s < cgeom.octaveLastSubdivision ; ++s) { /* space extrema */ float const * level = vl_scalespace_get_level(self->css,o,s) ; numExtrema = vl_find_local_extrema_2(&extrema, &extremaBufferSize, level, width, height, 0.8 * self->peakThreshold); for (index = 0 ; index < numExtrema ; ++index) { VlCovDetExtremum2 refined ; VlCovDetFeature feature ; vl_bool ok ; memset(&feature, 0, sizeof(feature)) ; ok = vl_refine_local_extreum_2(&refined, level, width, height, extrema[2*index+0], extrema[2*index+1]); ok &= fabs(refined.peakScore) > self->peakThreshold ; ok &= refined.edgeScore < self->edgeThreshold ; if (ok) { double sigma = cgeom.baseScale * pow(2.0, o + (double)s / cgeom.octaveResolution) ; feature.frame.x = refined.x * step ; feature.frame.y = refined.y * step ; feature.frame.a11 = sigma ; feature.frame.a12 = 0.0 ; feature.frame.a21 = 0.0 ; feature.frame.a22 = sigma ; feature.peakScore = refined.peakScore ; feature.edgeScore = refined.edgeScore ; vl_covdet_append_feature(self, &feature) ; } } } break ; } } } /* next octave */ if (extrema) { vl_free(extrema) ; extrema = 0 ; } } /* Laplacian scale selection for certain methods */ switch (self->method) { case VL_COVDET_METHOD_HARRIS_LAPLACE : case VL_COVDET_METHOD_HESSIAN_LAPLACE : vl_covdet_extract_laplacian_scales (self) ; break ; default: break ; } if (self->nonExtremaSuppression) { vl_index i, j ; double tol = self->nonExtremaSuppression ; self->numNonExtremaSuppressed = 0 ; for (i = 0 ; i < (signed)self->numFeatures ; ++i) { double x = self->features[i].frame.x ; double y = self->features[i].frame.y ; double sigma = self->features[i].frame.a11 ; double score = self->features[i].peakScore ; for (j = 0 ; j < (signed)self->numFeatures ; ++j) { double dx_ = self->features[j].frame.x - x ; double dy_ = self->features[j].frame.y - y ; double sigma_ = self->features[j].frame.a11 ; double score_ = self->features[j].peakScore ; if (score_ == 0) continue ; if (sigma < (1+tol) * sigma_ && sigma_ < (1+tol) * sigma && vl_abs_d(dx_) < tol * sigma && vl_abs_d(dy_) < tol * sigma && vl_abs_d(score) > vl_abs_d(score_)) { self->features[j].peakScore = 0 ; self->numNonExtremaSuppressed ++ ; } } } j = 0 ; for (i = 0 ; i < (signed)self->numFeatures ; ++i) { VlCovDetFeature feature = self->features[i] ; if (self->features[i].peakScore != 0) { self->features[j++] = feature ; } } self->numFeatures = j ; } if (levelxx) vl_free(levelxx) ; if (levelyy) vl_free(levelyy) ; if (levelxy) vl_free(levelxy) ; } /* ---------------------------------------------------------------- */ /* Extract patches */ /* ---------------------------------------------------------------- */ /** @internal ** @brief Helper for extracting patches ** @param self object. ** @param[out] sigma1 actual patch smoothing along the first axis. ** @param[out] sigma2 actual patch smoothing along the second axis. ** @param patch buffer. ** @param resolution patch resolution. ** @param extent patch extent. ** @param sigma desired smoothing in the patch frame. ** @param A_ linear transfomration from patch to image. ** @param T_ translation from patch to image. ** @param d1 first singular value @a A. ** @param d2 second singular value of @a A. **/ vl_bool vl_covdet_extract_patch_helper (VlCovDet * self, double * sigma1, double * sigma2, float * patch, vl_size resolution, double extent, double sigma, double A_ [4], double T_ [2], double d1, double d2) { vl_index o, s ; double factor ; double sigma_ ; float const * level ; vl_size width, height ; double step ; double A [4] = {A_[0], A_[1], A_[2], A_[3]} ; double T [2] = {T_[0], T_[1]} ; VlScaleSpaceGeometry geom = vl_scalespace_get_geometry(self->gss) ; VlScaleSpaceOctaveGeometry oct ; /* Starting from a pre-smoothed image at scale sigma_ because of the mapping A the resulting smoothing in the warped patch is S, where sigma_^2 I = A S A', S = sigma_^2 inv(A) inv(A)' = sigma_^2 V D^-2 V', A = U D V'. Thus we rotate A by V to obtain an axis-aligned smoothing: A = U*D, S = sigma_^2 D^-2. Then we search the scale-space for the best sigma_ such that the target smoothing is approximated from below: max sigma_(o,s) : simga_(o,s) factor <= sigma, factor = max{abs(D11), abs(D22)}. */ /* Determine the best level (o,s) such that sigma_(o,s) factor <= sigma. This can be obtained by scanning octaves from smallest to largest and stopping when no level in the octave satisfies the relation. Given the range of octave availables, do the best you can. */ factor = 1.0 / VL_MIN(d1, d2) ; for (o = geom.firstOctave + 1 ; o <= geom.lastOctave ; ++o) { s = vl_floor_d(vl_log2_d(sigma / (factor * geom.baseScale)) - o) ; s = VL_MAX(s, geom.octaveFirstSubdivision) ; s = VL_MIN(s, geom.octaveLastSubdivision) ; sigma_ = geom.baseScale * pow(2.0, o + (double)s / geom.octaveResolution) ; /*VL_PRINTF(".. %d D=%g %g; sigma_=%g factor*sigma_=%g\n", o, d1, d2, sigma_, factor* sigma_) ;*/ if (factor * sigma_ > sigma) { o -- ; break ; } } o = VL_MIN(o, geom.lastOctave) ; s = vl_floor_d(vl_log2_d(sigma / (factor * geom.baseScale)) - o) ; s = VL_MAX(s, geom.octaveFirstSubdivision) ; s = VL_MIN(s, geom.octaveLastSubdivision) ; sigma_ = geom.baseScale * pow(2.0, o + (double)s / geom.octaveResolution) ; if (sigma1) *sigma1 = sigma_ / d1 ; if (sigma2) *sigma2 = sigma_ / d2 ; /*VL_PRINTF("%d %d %g %g %g %g\n", o, s, factor, sigma_, factor * sigma_, sigma) ;*/ /* Now the scale space level to be used for this warping has been determined. If the patch is partially or completely out of the image boundary, create a padded copy of the required region first. */ level = vl_scalespace_get_level(self->gss, o, s) ; oct = vl_scalespace_get_octave_geometry(self->gss, o) ; width = oct.width ; height = oct.height ; step = oct.step ; A[0] /= step ; A[1] /= step ; A[2] /= step ; A[3] /= step ; T[0] /= step ; T[1] /= step ; { /* Warp the patch domain [x0hat,y0hat,x1hat,y1hat] to the image domain/ Obtain a box [x0,y0,x1,y1] enclosing that wrapped box, and then an integer vertexes version [x0i, y0i, x1i, y1i], making room for one pixel at the boundary to simplify bilinear interpolation later on. */ vl_index x0i, y0i, x1i, y1i ; double x0 = +VL_INFINITY_D ; double x1 = -VL_INFINITY_D ; double y0 = +VL_INFINITY_D ; double y1 = -VL_INFINITY_D ; double boxx [4] = {extent, extent, -extent, -extent} ; double boxy [4] = {-extent, extent, extent, -extent} ; int i ; for (i = 0 ; i < 4 ; ++i) { double x = A[0] * boxx[i] + A[2] * boxy[i] + T[0] ; double y = A[1] * boxx[i] + A[3] * boxy[i] + T[1] ; x0 = VL_MIN(x0, x) ; x1 = VL_MAX(x1, x) ; y0 = VL_MIN(y0, y) ; y1 = VL_MAX(y1, y) ; } if ((x0 < 0 || x1 > (signed)width-1 || y0 < 0 || y1 > (signed)height-1) && !self->allowPaddedWarping) { return vl_set_last_error(VL_ERR_EOF, "Frame out of image."); } /* Leave one pixel border for bilinear interpolation. */ x0i = floor(x0) - 1 ; y0i = floor(y0) - 1 ; x1i = ceil(x1) + 1 ; y1i = ceil(y1) + 1 ; /* If the box [x0i,y0i,x1i,y1i] is not fully contained in the image domain, then create a copy of this region by padding the image. The image is extended by continuity. */ if (x0i < 0 || x1i > (signed)width-1 || y0i < 0 || y1i > (signed)height-1) { vl_index xi, yi ; /* compute the amount of l,r,t,b padding needed to complete the patch */ vl_index padx0 = VL_MAX(0, - x0i) ; vl_index pady0 = VL_MAX(0, - y0i) ; vl_index padx1 = VL_MAX(0, x1i - ((signed)width - 1)) ; vl_index pady1 = VL_MAX(0, y1i - ((signed)height - 1)) ; /* make enough room for the patch */ vl_index patchWidth = x1i - x0i + 1 ; vl_index patchHeight = y1i - y0i + 1 ; vl_size patchBufferSize = patchWidth * patchHeight * sizeof(float) ; if (patchBufferSize > self->patchBufferSize) { int err = _vl_resize_buffer((void**)&self->patch, &self->patchBufferSize, patchBufferSize) ; if (err) return vl_set_last_error(VL_ERR_ALLOC, "Unable to allocate data.") ; } if (pady0 < patchHeight - pady1) { /* start by filling the central horizontal band */ for (yi = y0i + pady0 ; yi < y0i + patchHeight - pady1 ; ++ yi) { float *dst = self->patch + (yi - y0i) * patchWidth ; float const *src = level + yi * width + VL_MIN(VL_MAX(0, x0i),(signed)width-1) ; for (xi = x0i ; xi < x0i + padx0 ; ++xi) *dst++ = *src ; for ( ; xi < x0i + patchWidth - padx1 - 2 ; ++xi) *dst++ = *src++ ; for ( ; xi < x0i + patchWidth ; ++xi) *dst++ = *src ; } /* now extend the central band up and down */ for (yi = 0 ; yi < pady0 ; ++yi) { memcpy(self->patch + yi * patchWidth, self->patch + pady0 * patchWidth, patchWidth * sizeof(float)) ; } for (yi = patchHeight - pady1 ; yi < patchHeight ; ++yi) { memcpy(self->patch + yi * patchWidth, self->patch + (patchHeight - pady1 - 1) * patchWidth, patchWidth * sizeof(float)) ; } } else { /* should be handled better! */ memset(self->patch, 0, self->patchBufferSize) ; } #if 0 { char name [200] ; snprintf(name, 200, "/tmp/%20.0f-ext.pgm", 1e10*vl_get_cpu_time()) ; vl_pgm_write_f(name, patch, patchWidth, patchWidth) ; } #endif level = self->patch ; width = patchWidth ; height = patchHeight ; T[0] -= x0i ; T[1] -= y0i ; } } /* Resample by using bilinear interpolation. */ { float * pt = patch ; double yhat = -extent ; vl_index xxi ; vl_index yyi ; double stephat = extent / resolution ; for (yyi = 0 ; yyi < 2 * (signed)resolution + 1 ; ++yyi) { double xhat = -extent ; double rx = A[2] * yhat + T[0] ; double ry = A[3] * yhat + T[1] ; for (xxi = 0 ; xxi < 2 * (signed)resolution + 1 ; ++xxi) { double x = A[0] * xhat + rx ; double y = A[1] * xhat + ry ; vl_index xi = vl_floor_d(x) ; vl_index yi = vl_floor_d(y) ; double i00 = level[yi * width + xi] ; double i10 = level[yi * width + xi + 1] ; double i01 = level[(yi + 1) * width + xi] ; double i11 = level[(yi + 1) * width + xi + 1] ; double wx = x - xi ; double wy = y - yi ; assert(xi >= 0 && xi <= (signed)width - 1) ; assert(yi >= 0 && yi <= (signed)height - 1) ; *pt++ = (1.0 - wy) * ((1.0 - wx) * i00 + wx * i10) + wy * ((1.0 - wx) * i01 + wx * i11) ; xhat += stephat ; } yhat += stephat ; } } #if 0 { char name [200] ; snprintf(name, 200, "/tmp/%20.0f.pgm", 1e10*vl_get_cpu_time()) ; vl_pgm_write_f(name, patch, 2*resolution+1, 2*resolution+1) ; } #endif return VL_ERR_OK ; } /** @brief Helper for extracting patches ** @param self object. ** @param patch buffer. ** @param resolution patch resolution. ** @param extent patch extent. ** @param sigma desired smoothing in the patch frame. ** @param frame feature frame. ** ** The function considers a patch of extent <code>[-extent,extent]</code> ** on each side, with a side counting <code>2*resolution+1</code> pixels. ** In attempts to extract from the scale space a patch ** based on the affine warping specified by @a frame in such a way ** that the resulting smoothing of the image is @a sigma (in the ** patch frame). ** ** The transformation is specified by the matrices @c A and @c T ** embedded in the feature @a frame. Note that this transformation maps ** pixels from the patch frame to the image frame. **/ vl_bool vl_covdet_extract_patch_for_frame (VlCovDet * self, float * patch, vl_size resolution, double extent, double sigma, VlFrameOrientedEllipse frame) { double A[2*2] = {frame.a11, frame.a21, frame.a12, frame.a22} ; double T[2] = {frame.x, frame.y} ; double D[4], U[4], V[4] ; vl_svd2(D, U, V, A) ; return vl_covdet_extract_patch_helper (self, NULL, NULL, patch, resolution, extent, sigma, A, T, D[0], D[3]) ; } /* ---------------------------------------------------------------- */ /* Affine shape */ /* ---------------------------------------------------------------- */ /** @brief Extract the affine shape for a feature frame ** @param self object. ** @param adapted the shape-adapted frame. ** @param frame the input frame. ** @return ::VL_ERR_OK if affine adaptation is successful. ** ** This function may fail if adaptation is unsuccessful or if ** memory is insufficient. **/ int vl_covdet_extract_affine_shape_for_frame (VlCovDet * self, VlFrameOrientedEllipse * adapted, VlFrameOrientedEllipse frame) { vl_index iter = 0 ; double A [2*2] = {frame.a11, frame.a21, frame.a12, frame.a22} ; double T [2] = {frame.x, frame.y} ; double U [2*2] ; double V [2*2] ; double D [2*2] ; double M [2*2] ; double P [2*2] ; double P_ [2*2] ; double Q [2*2] ; double sigma1, sigma2 ; double sigmaD = VL_COVDET_AA_RELATIVE_DERIVATIVE_SIGMA ; double factor ; double anisotropy ; double referenceScale ; vl_size const resolution = VL_COVDET_AA_PATCH_RESOLUTION ; vl_size const side = 2*VL_COVDET_AA_PATCH_RESOLUTION + 1 ; double const extent = VL_COVDET_AA_PATCH_EXTENT ; *adapted = frame ; while (1) { double lxx = 0, lxy = 0, lyy = 0 ; vl_index k ; int err ; /* A = U D V' */ vl_svd2(D, U, V, A) ; anisotropy = VL_MAX(D[0]/D[3], D[3]/D[0]) ; /* VL_PRINTF("anisot: %g\n", anisotropy); */ if (anisotropy > VL_COVDET_AA_MAX_ANISOTROPY) { /* diverged, give up with current solution */ break ; } /* make sure that the smallest singluar value stays fixed after the first iteration */ if (iter == 0) { referenceScale = VL_MIN(D[0], D[3]) ; factor = 1.0 ; } else { factor = referenceScale / VL_MIN(D[0],D[3]) ; } D[0] *= factor ; D[3] *= factor ; A[0] = U[0] * D[0] ; A[1] = U[1] * D[0] ; A[2] = U[2] * D[3] ; A[3] = U[3] * D[3] ; adapted->a11 = A[0] ; adapted->a21 = A[1] ; adapted->a12 = A[2] ; adapted->a22 = A[3] ; if (++iter >= VL_COVDET_AA_MAX_NUM_ITERATIONS) break ; err = vl_covdet_extract_patch_helper(self, &sigma1, &sigma2, self->aaPatch, resolution, extent, sigmaD, A, T, D[0], D[3]) ; if (err) return err ; if (self->aaAccurateSmoothing ) { double deltaSigma1 = sqrt(VL_MAX(sigmaD*sigmaD - sigma1*sigma1,0)) ; double deltaSigma2 = sqrt(VL_MAX(sigmaD*sigmaD - sigma2*sigma2,0)) ; double stephat = extent / resolution ; vl_imsmooth_f(self->aaPatch, side, self->aaPatch, side, side, side, deltaSigma1 / stephat, deltaSigma2 / stephat) ; } /* compute second moment matrix */ vl_imgradient_f (self->aaPatchX, self->aaPatchY, 1, side, self->aaPatch, side, side, side) ; for (k = 0 ; k < (signed)(side*side) ; ++k) { double lx = self->aaPatchX[k] ; double ly = self->aaPatchY[k] ; lxx += lx * lx * self->aaMask[k] ; lyy += ly * ly * self->aaMask[k] ; lxy += lx * ly * self->aaMask[k] ; } M[0] = lxx ; M[1] = lxy ; M[2] = lxy ; M[3] = lyy ; if (lxx == 0 || lyy == 0) { *adapted = frame ; break ; } /* decompose M = P * Q * P' */ vl_svd2 (Q, P, P_, M) ; /* Setting A <- A * dA results in M to change approximatively as M --> dA' M dA = dA' P Q P dA To make this proportional to the identity, we set dA ~= P Q^1/2 we also make it so the smallest singular value of A is unchanged. */ if (Q[3]/Q[0] < VL_COVDET_AA_CONVERGENCE_THRESHOLD && Q[0]/Q[3] < VL_COVDET_AA_CONVERGENCE_THRESHOLD) { break ; } { double Ap [4] ; double q0 = sqrt(Q[0]) ; double q1 = sqrt(Q[3]) ; Ap[0] = (A[0] * P[0] + A[2] * P[1]) / q0 ; Ap[1] = (A[1] * P[0] + A[3] * P[1]) / q0 ; Ap[2] = (A[0] * P[2] + A[2] * P[3]) / q1 ; Ap[3] = (A[1] * P[2] + A[3] * P[3]) / q1 ; memcpy(A,Ap,4*sizeof(double)) ; } } /* next iteration */ /* Make upright. Shape adaptation does not estimate rotation. This is fixed by default so that a selected axis is not rotated at all (usually this is the vertical axis for upright features). To do so, the frame is rotated as follows. */ { double A [2*2] = {adapted->a11, adapted->a21, adapted->a12, adapted->a22} ; double ref [2] ; double ref_ [2] ; double angle ; double angle_ ; double dangle ; double r1, r2 ; if (self->transposed) { /* up is the x axis */ ref[0] = 1 ; ref[1] = 0 ; } else { /* up is the y axis */ ref[0] = 0 ; ref[1] = 1 ; } vl_solve_linear_system_2 (ref_, A, ref) ; angle = atan2(ref[1], ref[0]) ; angle_ = atan2(ref_[1], ref_[0]) ; dangle = angle_ - angle ; r1 = cos(dangle) ; r2 = sin(dangle) ; adapted->a11 = + A[0] * r1 + A[2] * r2 ; adapted->a21 = + A[1] * r1 + A[3] * r2 ; adapted->a12 = - A[0] * r2 + A[2] * r1 ; adapted->a22 = - A[1] * r2 + A[3] * r1 ; } return VL_ERR_OK ; } /** @brief Extract the affine shape for the stored features ** @param self object. ** ** This function may discard features for which no affine ** shape can reliably be detected. **/ void vl_covdet_extract_affine_shape (VlCovDet * self) { vl_index i, j = 0 ; vl_size numFeatures = vl_covdet_get_num_features(self) ; VlCovDetFeature * feature = vl_covdet_get_features(self); for (i = 0 ; i < (signed)numFeatures ; ++i) { int status ; VlFrameOrientedEllipse adapted ; status = vl_covdet_extract_affine_shape_for_frame(self, &adapted, feature[i].frame) ; if (status == VL_ERR_OK) { feature[j] = feature[i] ; feature[j].frame = adapted ; ++ j ; } } self->numFeatures = j ; } /* ---------------------------------------------------------------- */ /* Orientation */ /* ---------------------------------------------------------------- */ static int _vl_covdet_compare_orientations_descending (void const * a_, void const * b_) { VlCovDetFeatureOrientation const * a = a_ ; VlCovDetFeatureOrientation const * b = b_ ; if (a->score > b->score) return -1 ; if (a->score < b->score) return +1 ; return 0 ; } /** @brief Extract the orientation(s) for a feature ** @param self object. ** @param numOrientations the number of detected orientations. ** @param frame pose of the feature. ** @return an array of detected orientations with their scores. ** ** The returned array is a matrix of size @f$ 2 \times n @f$ ** where <em>n</em> is the number of detected orientations. ** ** The function returns @c NULL if memory is insufficient. **/ VlCovDetFeatureOrientation * vl_covdet_extract_orientations_for_frame (VlCovDet * self, vl_size * numOrientations, VlFrameOrientedEllipse frame) { int err ; vl_index k, i ; vl_index iter ; double extent = VL_COVDET_AA_PATCH_EXTENT ; vl_size resolution = VL_COVDET_AA_PATCH_RESOLUTION ; vl_size side = 2 * resolution + 1 ; vl_size const numBins = VL_COVDET_OR_NUM_ORIENTATION_HISTOGAM_BINS ; double hist [VL_COVDET_OR_NUM_ORIENTATION_HISTOGAM_BINS] ; double const binExtent = 2 * VL_PI / VL_COVDET_OR_NUM_ORIENTATION_HISTOGAM_BINS ; double const peakRelativeSize = VL_COVDET_OR_ADDITIONAL_PEAKS_RELATIVE_SIZE ; double maxPeakValue ; double A [2*2] = {frame.a11, frame.a21, frame.a12, frame.a22} ; double T [2] = {frame.x, frame.y} ; double U [2*2] ; double V [2*2] ; double D [2*2] ; double sigma1, sigma2 ; double sigmaD = 1.0 ; double theta0 ; assert(self); assert(numOrientations) ; /* The goal is to estimate a rotation R(theta) such that the patch given by the transformation A R(theta) has the strongest average gradient pointing right (or down for transposed conventions). To compensate for tha anisotropic smoothing due to warping, A is decomposed as A = U D V' and the patch is warped by U D only, meaning that the matrix R_(theta) will be estimated instead, where: A R(theta) = U D V' R(theta) = U D R_(theta) such that R(theta) = V R(theta). That is an extra rotation of theta0 = atan2(V(2,1),V(1,1)). */ /* axis aligned anisotropic smoothing for easier compensation */ vl_svd2(D, U, V, A) ; A[0] = U[0] * D[0] ; A[1] = U[1] * D[0] ; A[2] = U[2] * D[3] ; A[3] = U[3] * D[3] ; theta0 = atan2(V[1],V[0]) ; err = vl_covdet_extract_patch_helper(self, &sigma1, &sigma2, self->aaPatch, resolution, extent, sigmaD, A, T, D[0], D[3]) ; if (err) { *numOrientations = 0 ; return NULL ; } if (1) { double deltaSigma1 = sqrt(VL_MAX(sigmaD*sigmaD - sigma1*sigma1,0)) ; double deltaSigma2 = sqrt(VL_MAX(sigmaD*sigmaD - sigma2*sigma2,0)) ; double stephat = extent / resolution ; vl_imsmooth_f(self->aaPatch, side, self->aaPatch, side, side, side, deltaSigma1 / stephat, deltaSigma2 / stephat) ; } /* histogram of oriented gradients */ vl_imgradient_polar_f (self->aaPatchX, self->aaPatchY, 1, side, self->aaPatch, side, side, side) ; memset (hist, 0, sizeof(double) * numBins) ; for (k = 0 ; k < (signed)(side*side) ; ++k) { double modulus = self->aaPatchX[k] ; double angle = self->aaPatchY[k] ; double weight = self->aaMask[k] ; double x = angle / binExtent ; vl_index bin = vl_floor_d(x) ; double w2 = x - bin ; double w1 = 1.0 - w2 ; hist[(bin + numBins) % numBins] += w1 * (modulus * weight) ; hist[(bin + numBins + 1) % numBins] += w2 * (modulus * weight) ; } /* smooth histogram */ for (iter = 0; iter < 6; iter ++) { double prev = hist [numBins - 1] ; double first = hist [0] ; vl_index i ; for (i = 0; i < (signed)numBins - 1; ++i) { double curr = (prev + hist[i] + hist[(i + 1) % numBins]) / 3.0 ; prev = hist[i] ; hist[i] = curr ; } hist[i] = (prev + hist[i] + first) / 3.0 ; } /* find the histogram maximum */ maxPeakValue = 0 ; for (i = 0 ; i < (signed)numBins ; ++i) { maxPeakValue = VL_MAX (maxPeakValue, hist[i]) ; } /* find peaks within 80% from max */ *numOrientations = 0 ; for(i = 0 ; i < (signed)numBins ; ++i) { double h0 = hist [i] ; double hm = hist [(i - 1 + numBins) % numBins] ; double hp = hist [(i + 1 + numBins) % numBins] ; /* is this a peak? */ if (h0 > peakRelativeSize * maxPeakValue && h0 > hm && h0 > hp) { /* quadratic interpolation */ double di = - 0.5 * (hp - hm) / (hp + hm - 2 * h0) ; double th = binExtent * (i + di) + theta0 ; if (self->transposed) { /* the axis to the right is y, measure orientations from this */ th = th - VL_PI/2 ; } self->orientations[*numOrientations].angle = th ; self->orientations[*numOrientations].score = h0 ; *numOrientations += 1 ; //VL_PRINTF("%d %g\n", *numOrientations, th) ; if (*numOrientations >= self->maxNumOrientations) break ; } } /* sort the orientations by decreasing scores */ qsort(self->orientations, *numOrientations, sizeof(VlCovDetFeatureOrientation), _vl_covdet_compare_orientations_descending) ; return self->orientations ; } /** @brief Extract the orientation(s) for the stored features. ** @param self object. ** ** Note that, since more than one orientation can be detected ** for each feature, this function may create copies of them, ** one for each orientation. **/ void vl_covdet_extract_orientations (VlCovDet * self) { vl_index i, j ; vl_size numFeatures = vl_covdet_get_num_features(self) ; for (i = 0 ; i < (signed)numFeatures ; ++i) { vl_size numOrientations ; VlCovDetFeature feature = self->features[i] ; VlCovDetFeatureOrientation* orientations = vl_covdet_extract_orientations_for_frame(self, &numOrientations, feature.frame) ; for (j = 0 ; j < (signed)numOrientations ; ++j) { double A [2*2] = { feature.frame.a11, feature.frame.a21, feature.frame.a12, feature.frame.a22} ; double r1 = cos(orientations[j].angle) ; double r2 = sin(orientations[j].angle) ; VlCovDetFeature * oriented ; if (j == 0) { oriented = & self->features[i] ; } else { vl_covdet_append_feature(self, &feature) ; oriented = & self->features[self->numFeatures -1] ; } oriented->orientationScore = orientations[j].score ; oriented->frame.a11 = + A[0] * r1 + A[2] * r2 ; oriented->frame.a21 = + A[1] * r1 + A[3] * r2 ; oriented->frame.a12 = - A[0] * r2 + A[2] * r1 ; oriented->frame.a22 = - A[1] * r2 + A[3] * r1 ; } } } /* ---------------------------------------------------------------- */ /* Laplacian scales */ /* ---------------------------------------------------------------- */ /** @brief Extract the Laplacian scale(s) for a feature frame. ** @param self object. ** @param numScales the number of detected scales. ** @param frame pose of the feature. ** @return an array of detected scales. ** ** The function returns @c NULL if memory is insufficient. **/ VlCovDetFeatureLaplacianScale * vl_covdet_extract_laplacian_scales_for_frame (VlCovDet * self, vl_size * numScales, VlFrameOrientedEllipse frame) { /* We try to explore one octave, with the nominal detection scale 1.0 (in the patch reference frame) in the middle. Thus the goal is to sample the response of the tr-Laplacian operator at logarithmically spaced scales in 1/sqrt(2), sqrt(2). To this end, the patch is warped with a smoothing of at most sigmaImage = 1 / sqrt(2) (beginning of the scale), sampled at roughly twice the Nyquist frequency (so step = 1 / (2*sqrt(2))). This maes it possible to approximate the Laplacian operator at that scale by simple finite differences. */ int err ; double const sigmaImage = 1.0 / sqrt(2.0) ; double const step = 0.5 * sigmaImage ; double actualSigmaImage ; vl_size const resolution = VL_COVDET_LAP_PATCH_RESOLUTION ; vl_size const num = 2 * resolution + 1 ; double extent = step * resolution ; double scores [VL_COVDET_LAP_NUM_LEVELS] ; double factor = 1.0 ; float const * pt ; vl_index k ; double A[2*2] = {frame.a11, frame.a21, frame.a12, frame.a22} ; double T[2] = {frame.x, frame.y} ; double D[4], U[4], V[4] ; double sigma1, sigma2 ; assert(self) ; assert(numScales) ; *numScales = 0 ; vl_svd2(D, U, V, A) ; err = vl_covdet_extract_patch_helper (self, &sigma1, &sigma2, self->lapPatch, resolution, extent, sigmaImage, A, T, D[0], D[3]) ; if (err) return NULL ; /* the actual smoothing after warping is never the target one */ if (sigma1 == sigma2) { actualSigmaImage = sigma1 ; } else { /* here we could compensate */ actualSigmaImage = sqrt(sigma1*sigma2) ; } /* now multiply by the bank of Laplacians */ pt = self->laplacians ; for (k = 0 ; k < VL_COVDET_LAP_NUM_LEVELS ; ++k) { vl_index q ; double score = 0 ; double sigmaLap = pow(2.0, -0.5 + (double)k / (VL_COVDET_LAP_NUM_LEVELS - 1)) ; /* note that the sqrt argument cannot be negative since by construction sigmaLap >= sigmaImage */ sigmaLap = sqrt(sigmaLap*sigmaLap - sigmaImage*sigmaImage + actualSigmaImage*actualSigmaImage) ; for (q = 0 ; q < (signed)(num * num) ; ++q) { score += (*pt++) * self->lapPatch[q] ; } scores[k] = score * sigmaLap * sigmaLap ; } /* find and interpolate maxima */ for (k = 1 ; k < VL_COVDET_LAP_NUM_LEVELS - 1 ; ++k) { double a = scores[k-1] ; double b = scores[k] ; double c = scores[k+1] ; double t = self->lapPeakThreshold ; if ((((b > a) && (b > c)) || ((b < a) && (b < c))) && (vl_abs_d(b) >= t)) { double dk = - 0.5 * (c - a) / (c + a - 2 * b) ; double s = k + dk ; double sigmaLap = pow(2.0, -0.5 + s / (VL_COVDET_LAP_NUM_LEVELS - 1)) ; double scale ; sigmaLap = sqrt(sigmaLap*sigmaLap - sigmaImage*sigmaImage + actualSigmaImage*actualSigmaImage) ; scale = sigmaLap / 1.0 ; /* VL_PRINTF("** k:%d, s:%f, sigmaLapFilter:%f, sigmaLap%f, scale:%f (%f %f %f)\n", k,s,sigmaLapFilter,sigmaLap,scale,a,b,c) ; */ if (*numScales < VL_COVDET_MAX_NUM_LAPLACIAN_SCALES) { self->scales[*numScales].scale = scale * factor ; self->scales[*numScales].score = b + 0.5 * (c - a) * dk ; *numScales += 1 ; } } } return self->scales ; } /** @brief Extract the Laplacian scales for the stored features ** @param self object. ** ** Note that, since more than one orientation can be detected ** for each feature, this function may create copies of them, ** one for each orientation. **/ void vl_covdet_extract_laplacian_scales (VlCovDet * self) { vl_index i, j ; vl_bool dropFeaturesWithoutScale = VL_TRUE ; vl_size numFeatures = vl_covdet_get_num_features(self) ; memset(self->numFeaturesWithNumScales, 0, sizeof(self->numFeaturesWithNumScales)) ; for (i = 0 ; i < (signed)numFeatures ; ++i) { vl_size numScales ; VlCovDetFeature feature = self->features[i] ; VlCovDetFeatureLaplacianScale const * scales = vl_covdet_extract_laplacian_scales_for_frame(self, &numScales, feature.frame) ; self->numFeaturesWithNumScales[numScales] ++ ; if (numScales == 0 && dropFeaturesWithoutScale) { self->features[i].peakScore = 0 ; } for (j = 0 ; j < (signed)numScales ; ++j) { VlCovDetFeature * scaled ; if (j == 0) { scaled = & self->features[i] ; } else { vl_covdet_append_feature(self, &feature) ; scaled = & self->features[self->numFeatures -1] ; } scaled->laplacianScaleScore = scales[j].score ; scaled->frame.a11 *= scales[j].scale ; scaled->frame.a21 *= scales[j].scale ; scaled->frame.a12 *= scales[j].scale ; scaled->frame.a22 *= scales[j].scale ; } } if (dropFeaturesWithoutScale) { j = 0 ; for (i = 0 ; i < (signed)self->numFeatures ; ++i) { VlCovDetFeature feature = self->features[i] ; if (feature.peakScore) { self->features[j++] = feature ; } } self->numFeatures = j ; } } /* ---------------------------------------------------------------- */ /* Checking that features are inside an image */ /* ---------------------------------------------------------------- */ vl_bool _vl_covdet_check_frame_inside (VlCovDet * self, VlFrameOrientedEllipse frame, double margin) { double extent = margin ; double A [2*2] = {frame.a11, frame.a21, frame.a12, frame.a22} ; double T[2] = {frame.x, frame.y} ; double x0 = +VL_INFINITY_D ; double x1 = -VL_INFINITY_D ; double y0 = +VL_INFINITY_D ; double y1 = -VL_INFINITY_D ; double boxx [4] = {extent, extent, -extent, -extent} ; double boxy [4] = {-extent, extent, extent, -extent} ; VlScaleSpaceGeometry geom = vl_scalespace_get_geometry(self->gss) ; int i ; for (i = 0 ; i < 4 ; ++i) { double x = A[0] * boxx[i] + A[2] * boxy[i] + T[0] ; double y = A[1] * boxx[i] + A[3] * boxy[i] + T[1] ; x0 = VL_MIN(x0, x) ; x1 = VL_MAX(x1, x) ; y0 = VL_MIN(y0, y) ; y1 = VL_MAX(y1, y) ; } return 0 <= x0 && x1 <= geom.width-1 && 0 <= y0 && y1 <= geom.height-1 ; } /** @brief Drop features (partially) outside the image ** @param self object. ** @param margin geometric marging. ** ** The feature extent is defined by @c maring. A bounding box ** in the normalised feature frame containin a circle of radius ** @a maring is created and mapped to the image by ** the feature frame transformation. Then the feature ** is dropped if the bounding box is not contained in the image. ** ** For example, setting @c margin to zero drops a feature only ** if its center is not contained. ** ** Typically a valua of @c margin equal to 1 or 2 is used. **/ void vl_covdet_drop_features_outside (VlCovDet * self, double margin) { vl_index i, j = 0 ; vl_size numFeatures = vl_covdet_get_num_features(self) ; for (i = 0 ; i < (signed)numFeatures ; ++i) { vl_bool inside = _vl_covdet_check_frame_inside (self, self->features[i].frame, margin) ; if (inside) { self->features[j] = self->features[i] ; ++j ; } } self->numFeatures = j ; } /* ---------------------------------------------------------------- */ /* Setters and getters */ /* ---------------------------------------------------------------- */ /* ---------------------------------------------------------------- */ /** @brief Get wether images are passed in transposed ** @param self object. ** @return whether images are transposed. **/ vl_bool vl_covdet_get_transposed (VlCovDet const * self) { return self->transposed ; } /** @brief Set the index of the first octave ** @param self object. ** @param t whether images are transposed. **/ void vl_covdet_set_transposed (VlCovDet * self, vl_bool t) { self->transposed = t ; } /* ---------------------------------------------------------------- */ /** @brief Get the edge threshold ** @param self object. ** @return the edge threshold. **/ double vl_covdet_get_edge_threshold (VlCovDet const * self) { return self->edgeThreshold ; } /** @brief Set the edge threshold ** @param self object. ** @param edgeThreshold the edge threshold. ** ** The edge threshold must be non-negative. **/ void vl_covdet_set_edge_threshold (VlCovDet * self, double edgeThreshold) { assert(edgeThreshold >= 0) ; self->edgeThreshold = edgeThreshold ; } /* ---------------------------------------------------------------- */ /** @brief Get the peak threshold ** @param self object. ** @return the peak threshold. **/ double vl_covdet_get_peak_threshold (VlCovDet const * self) { return self->peakThreshold ; } /** @brief Set the peak threshold ** @param self object. ** @param peakThreshold the peak threshold. ** ** The peak threshold must be non-negative. **/ void vl_covdet_set_peak_threshold (VlCovDet * self, double peakThreshold) { assert(peakThreshold >= 0) ; self->peakThreshold = peakThreshold ; } /* ---------------------------------------------------------------- */ /** @brief Get the Laplacian peak threshold ** @param self object. ** @return the Laplacian peak threshold. ** ** This parameter affects only the detecors using the Laplacian ** scale selectino method such as Harris-Laplace. **/ double vl_covdet_get_laplacian_peak_threshold (VlCovDet const * self) { return self->lapPeakThreshold ; } /** @brief Set the Laplacian peak threshold ** @param self object. ** @param peakThreshold the Laplacian peak threshold. ** ** The peak threshold must be non-negative. **/ void vl_covdet_set_laplacian_peak_threshold (VlCovDet * self, double peakThreshold) { assert(peakThreshold >= 0) ; self->lapPeakThreshold = peakThreshold ; } /* ---------------------------------------------------------------- */ /** @brief Get the index of the first octave ** @param self object. ** @return index of the first octave. **/ vl_index vl_covdet_get_first_octave (VlCovDet const * self) { return self->firstOctave ; } /** @brief Set the index of the first octave ** @param self object. ** @param o index of the first octave. ** ** Calling this function resets the detector. **/ void vl_covdet_set_first_octave (VlCovDet * self, vl_index o) { self->firstOctave = o ; vl_covdet_reset(self) ; } /* ---------------------------------------------------------------- */ /** @brief Get the max number of octaves ** @param self object. ** @return maximal number of octaves. **/ vl_size vl_covdet_get_num_octaves (VlCovDet const * self) { return self->numOctaves ; } /* ---------------------------------------------------------------- */ /** @brief Get the GSS base scale ** @param self object. ** @return The base scale. **/ double vl_covdet_get_base_scale (VlCovDet const * self) { return self->baseScale ; } /** @brief Set the max number of octaves ** @param self object. ** @param o max number of octaves. ** ** Calling this function resets the detector. **/ void vl_covdet_set_num_octaves (VlCovDet * self, vl_size o) { self->numOctaves = o ; vl_covdet_reset(self) ; } /** @brief Set the GSS base scale ** @param self object. ** @param s the base scale. ** ** Calling this function resets the detector. **/ void vl_covdet_set_base_scale (VlCovDet * self, double s) { self->baseScale = s ; vl_covdet_reset(self) ; } /* ---------------------------------------------------------------- */ /** @brief Set the max number of orientations ** @param self object. ** @param m the max number of orientations. ** ** Calling this function resets the detector. **/ void vl_covdet_set_max_num_orientations (VlCovDet * self, vl_size m) { self->maxNumOrientations = m ; } /* ---------------------------------------------------------------- */ /** @brief Get the octave resolution. ** @param self object. ** @return octave resolution. **/ vl_size vl_covdet_get_octave_resolution (VlCovDet const * self) { return self->octaveResolution ; } /** @brief Set the octave resolutuon. ** @param self object. ** @param r octave resoltuion. ** ** Calling this function resets the detector. **/ void vl_covdet_set_octave_resolution (VlCovDet * self, vl_size r) { self->octaveResolution = r ; vl_covdet_reset(self) ; } /* ---------------------------------------------------------------- */ /** @brief Get whether affine adaptation uses accurate smoothing. ** @param self object. ** @return @c true if accurate smoothing is used. **/ vl_bool vl_covdet_get_aa_accurate_smoothing (VlCovDet const * self) { return self->aaAccurateSmoothing ; } /** @brief Set whether affine adaptation uses accurate smoothing. ** @param self object. ** @param x whether accurate smoothing should be usd. **/ void vl_covdet_set_aa_accurate_smoothing (VlCovDet * self, vl_bool x) { self->aaAccurateSmoothing = x ; } /* ---------------------------------------------------------------- */ /** @brief Get the max number of orientations ** @param self object. ** @return maximal number of orientations. **/ vl_size vl_covdet_get_max_num_orientations( VlCovDet const * self) { return self->maxNumOrientations ; } /* ---------------------------------------------------------------- */ /** @brief Get the non-extrema suppression threshold ** @param self object. ** @return threshold. **/ double vl_covdet_get_non_extrema_suppression_threshold (VlCovDet const * self) { return self->nonExtremaSuppression ; } /** @brief Set the non-extrema suppression threshod ** @param self object. ** @param x threshold. **/ void vl_covdet_set_non_extrema_suppression_threshold (VlCovDet * self, double x) { self->nonExtremaSuppression = x ; } /** @brief Get the number of non-extrema suppressed ** @param self object. ** @return number. **/ vl_size vl_covdet_get_num_non_extrema_suppressed (VlCovDet const * self) { return self->numNonExtremaSuppressed ; } /* ---------------------------------------------------------------- */ /** @brief Get number of stored frames ** @return number of frames stored in the detector. **/ vl_size vl_covdet_get_num_features (VlCovDet const * self) { return self->numFeatures ; } /** @brief Get the stored frames ** @return frames stored in the detector. **/ void * vl_covdet_get_features (VlCovDet * self) { return self->features ; } /** @brief Get the Gaussian scale space ** @return Gaussian scale space. ** ** A Gaussian scale space exists only after calling ::vl_covdet_put_image. ** Otherwise the function returns @c NULL. **/ VlScaleSpace * vl_covdet_get_gss (VlCovDet const * self) { return self->gss ; } /** @brief Get the cornerness measure scale space ** @return cornerness measure scale space. ** ** A cornerness measure scale space exists only after calling ** ::vl_covdet_detect. Otherwise the function returns @c NULL. **/ VlScaleSpace * vl_covdet_get_css (VlCovDet const * self) { return self->css ; } /** @brief Get the number of features found with a certain number of scales ** @param self object. ** @param numScales length of the histogram (out). ** @return histogram. ** ** Calling this function makes sense only after running a detector ** that uses the Laplacian as a secondary measure for scale ** detection **/ vl_size const * vl_covdet_get_laplacian_scales_statistics (VlCovDet const * self, vl_size * numScales) { *numScales = VL_COVDET_MAX_NUM_LAPLACIAN_SCALES ; return self->numFeaturesWithNumScales ; } /* ---------------------------------------------------------------- */ /** @brief Get wether to compute padded warped patches ** @param self object. ** @return whether padded warped patches are computed. **/ vl_bool vl_covdet_get_allow_padded_warping (VlCovDet const * self) { return self->allowPaddedWarping ; } /** @brief Set wether to compute padded warped patches ** @param self object. ** @param t whether padded warped patches are computed. **/ void vl_covdet_set_allow_padded_warping (VlCovDet * self, vl_bool t) { self->allowPaddedWarping = t ; }