blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
2ac69c2d5650ce6e777069d072f4f0452be0260f
d041118ac86aa399d40d0cb807476ce8aceb2aad
/Yellow/WeekTwo/DecomDecom.cpp
0e99bfadba3f75a9799ce15c42a61fd51904ecb3
[]
no_license
ElenaDolgova/coursera_white
2795a93807ddfb9dfc2e5422eba4536b48213a81
9c36340af580ab82ef555de441f401bc5cb2e133
refs/heads/main
2023-04-28T03:33:24.081288
2021-05-18T12:33:52
2021-05-18T12:33:52
368,522,962
0
0
null
null
null
null
UTF-8
C++
false
false
5,638
cpp
#include <string> #include <iostream> #include <cassert> #include <vector> #include <map> using namespace std; enum class QueryType { NewBus, BusesForStop, StopsForBus, AllBuses }; struct Query { QueryType type; string bus; string stop; vector<string> stops; }; istream &operator>>(istream &is, Query &q) { string command; is >> command; if (command == "NEW_BUS") { q.type = QueryType::NewBus; is >> q.bus; int count_stop; is >> count_stop; q.stops.clear(); for (int i = 0; i < count_stop; ++i) { string stop; is >> stop; q.stops.push_back(stop); } } else if (command == "BUSES_FOR_STOP") { q.type = QueryType::BusesForStop; is >> q.stop; } else if (command == "STOPS_FOR_BUS") { q.type = QueryType::StopsForBus; is >> q.bus; } else if (command == "ALL_BUSES") { q.type = QueryType::AllBuses; } return is; } struct BusesForStopResponse { bool hasStop; vector<string> buses; }; ostream &operator<<(ostream &os, const BusesForStopResponse &r) { if (!r.hasStop) { os << "No stop"; return os; } bool isFirst = true; for (const string &bus: r.buses) { if (isFirst) { os << bus; isFirst = false; } else { os << " " << bus; } } return os; } struct StopsForBusResponse { bool hasBus; vector<string> stops; map<string, vector<string>> stops_buses; }; ostream &operator<<(ostream &os, const StopsForBusResponse &r) { if (!r.hasBus) { os << "No bus"; return os; } int count = 0; for (const auto &stop: r.stops) { os << "Stop " << stop << ":"; if (r.stops_buses.count(stop) == 0) { os << " no interchange"; } else { for (const auto &bus: r.stops_buses.at(stop)) { os << " " << bus; } } if (count != r.stops.size() - 1) { os << endl; } ++count; } return os; } struct AllBusesResponse { bool hasBuses; vector<string> buses; map<string, vector<string>> bus_stops; }; ostream &operator<<(ostream &os, const AllBusesResponse &r) { if (!r.hasBuses) { os << "No buses"; return os; } int count = 0; for (const auto &bus: r.buses) { os << "Bus " << bus << ":"; for (const auto &stop: r.bus_stops.at(bus)) { os << " " << stop; } if (count != r.buses.size() - 1) { os << endl; } ++count; } return os; } class BusManager { public: map<string, vector<string>> buses_to_stops, stops_to_buses; void AddBus(const string &bus, const vector<string> &stops) { buses_to_stops[bus] = stops; for (const basic_string<char> &stop : stops) { stops_to_buses[stop].push_back(bus); } } BusesForStopResponse GetBusesForStop(const string &stop) const { BusesForStopResponse busesForStopResponse; if (stops_to_buses.count(stop) == 0) { busesForStopResponse.hasStop = false; return busesForStopResponse; } busesForStopResponse.hasStop = true; for (const string &bus : stops_to_buses.at(stop)) { busesForStopResponse.buses.push_back(bus); } return busesForStopResponse; } StopsForBusResponse GetStopsForBus(const string &bus) const { StopsForBusResponse stopsForBusResponse; if (buses_to_stops.count(bus) == 0) { stopsForBusResponse.hasBus = false; return stopsForBusResponse; } stopsForBusResponse.hasBus = true; for (const string &stop : buses_to_stops.at(bus)) { stopsForBusResponse.stops.push_back(stop); if (stops_to_buses.at(stop).size() != 1) { for (const string &other_bus : stops_to_buses.at(stop)) { if (bus != other_bus) { stopsForBusResponse.stops_buses[stop].push_back(other_bus); } } } } return stopsForBusResponse; } AllBusesResponse GetAllBuses() const { AllBusesResponse allBusesResponse; if (buses_to_stops.empty()) { allBusesResponse.hasBuses = false; return allBusesResponse; } allBusesResponse.hasBuses = true; for (const auto &bus_item : buses_to_stops) { allBusesResponse.buses.push_back(bus_item.first); for (const string &stop : bus_item.second) { allBusesResponse.bus_stops[bus_item.first].push_back(stop); } } return allBusesResponse; } }; // Не меняя тела функции main, реализуйте функции и классы выше int main() { int query_count; Query q; cin >> query_count; BusManager bm; for (int i = 0; i < query_count; ++i) { cin >> q; switch (q.type) { case QueryType::NewBus: bm.AddBus(q.bus, q.stops); break; case QueryType::BusesForStop: cout << bm.GetBusesForStop(q.stop) << endl; break; case QueryType::StopsForBus: cout << bm.GetStopsForBus(q.bus) << endl; break; case QueryType::AllBuses: cout << bm.GetAllBuses() << endl; break; } } return 0; }
[ "ms.Elena.Dolgova@ya.ru" ]
ms.Elena.Dolgova@ya.ru
b66e43c866b2709e07307175a8ff7d61b4de68ca
f92ff80d4cd12a62c08e316f1ff6f523b83edd8f
/src/engines/graphics/scenenodeitem.cpp
a6c342203bf41fe26baa2c1daff8f8793ad7d253
[]
no_license
xabufr/pixelwars
70024a557d780b63636e65164fed2468f0f1baaf
11b8c3a759cd0efa006378fa62af505d96eb0a94
refs/heads/master
2020-05-30T08:28:48.017877
2014-06-25T18:47:50
2014-06-25T18:47:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,445
cpp
#include "scenenodeitem.h" SceneNodeItem::SceneNodeItem() { m_relative.rotation=0; m_relative.scale=sf::Vector2f(1,1); m_visible=true; } SceneNodeItem::~SceneNodeItem() { //dtor } const sf::Vector2f& SceneNodeItem::GetRelativePosition() const { return m_relative.position; } float SceneNodeItem::GetRelativeRotation() const { return m_relative.rotation; } const sf::Vector2f& SceneNodeItem::GetRelativeScale() const { return m_relative.scale; } void SceneNodeItem::SetParentPosition(const sf::Vector2f& pos) { m_parent.position=pos; PositionChanged(); } void SceneNodeItem::SetParentRotation(float rot) { m_parent.rotation=rot; RotationChanged(); } void SceneNodeItem::SetParentScale(const sf::Vector2f& scale) { m_parent.scale=scale; ScaleChanged(); } void SceneNodeItem::SetRelativePosition(const sf::Vector2f& pos) { m_relative.position=pos; PositionChanged(); } void SceneNodeItem::SetRelativeRotation(float rot) { m_relative.rotation=rot; RotationChanged(); } void SceneNodeItem::SetRelativeScale(const sf::Vector2f& scale) { m_relative.scale=scale; ScaleChanged(); } void SceneNodeItem::SetAbsolutePosition(const sf::Vector2f& pos) { m_relative.position.x=pos.x-m_parent.position.x; m_relative.position.y=pos.y-m_parent.position.y; PositionChanged(); } void SceneNodeItem::SetAbsoluteRotation(float rot) { m_relative.rotation=rot-m_parent.rotation; RotationChanged(); } void SceneNodeItem::SetAbsoluteScale(const sf::Vector2f& scale) { m_relative.scale.x=scale.x/m_parent.scale.x; m_relative.scale.y=scale.y/m_parent.scale.y; ScaleChanged(); } void SceneNodeItem::SetParentPosition(float x, float y) { SetParentPosition(sf::Vector2f(x,y)); } void SceneNodeItem::SetParentScale(float x, float y) { SetParentScale(sf::Vector2f(x,y)); } void SceneNodeItem::SetRelativePosition(float x, float y) { SetRelativePosition(sf::Vector2f(x,y)); } void SceneNodeItem::SetRelativeScale(float x, float y) { SetRelativeScale(sf::Vector2f(x,y)); } void SceneNodeItem::SetAbsolutePosition(float x, float y) { SetAbsolutePosition(sf::Vector2f(x,y)); } void SceneNodeItem::SetAbsoluteScale(float x, float y) { SetAbsoluteScale(sf::Vector2f(x,y)); } void SceneNodeItem::Show() { SetVisible(true); } void SceneNodeItem::Hide() { SetVisible(false); } void SceneNodeItem::SetVisible(bool vis) { m_visible=vis; }
[ "xabufr@gmail.com" ]
xabufr@gmail.com
b8e659bcfd8e1b39170892211bad7258c08e2ca5
04518b3b97789455e9afd96ab67186ae3bd11b87
/coding/codechef/ckd2.cpp
45305b59679a84f8d7b6c514a232e785e16427fc
[]
no_license
shubhampal077/s_pal1
36e14f47dae2c3666538f3d06e3b0e6a17e60ade
d577f3b587739757b93e6fb3d000adbfc3893386
refs/heads/master
2020-07-06T10:36:12.852462
2019-08-18T10:42:51
2019-08-18T10:42:51
202,988,205
0
0
null
null
null
null
UTF-8
C++
false
false
859
cpp
#include<bits/stdc++.h> using namespace std; typedef long long int ll; #define MOD 1000000007 int mod(string num, int a) { // Initialize result int res = 0; // One by one process all digits of 'num' for (int i = 0; i < num.length(); i++) res = (res*10 + (int)num[i] - '0') %a; return res; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); ll t,n,i,out; string ori,ans; cin>>t; while(t--) { cin>>n; ori=to_string(n); vector<string> vec; for(i=1;i<ori.length();i++) { vec.push_back(ori.substr(i)+ori.substr(0,i)); } ans=ori; for(i=0;i<vec.size();i++) { ans+=vec[i]; } // out=mod(ans); //out=((stoi(ans))%MOD); cout<<out<<endl; } return 0; }
[ "shubhampalggps@gmail.com" ]
shubhampalggps@gmail.com
df148c37ad92334ce3796a82094eb29a97762f6b
ba00658155d78f9a1e66af59e6b2845ef4bdacf3
/philosophers/src/dining_philosopher/src/MonitoredPhilosopher-main.cc
2c16deb977c4f7acc660e225a744a5b5e9a94ee9
[]
no_license
karasavm/philosophers_experiements
72b25002215058688ceaf67196df32ba176ce7b1
162b4a44635ab8a82918490d167d06e0fd81ce5e
refs/heads/master
2021-01-01T20:48:13.840003
2013-12-02T21:53:59
2013-12-02T21:53:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,479
cc
/* * Copyright (C) 2012 Aristotle Univeristy of Thessaloniki, Greece * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "ros/ros.h" #include "dining_philosopher/MonitoredPhilosopher.h" int main(int argc, char** argv) { std::string name = "philosopher"; name += argv[1]; ros::init(argc,argv,name); MonitoredPhilosopher phil( atoi(argv[1]), std::string(argv[2]), atoi(argv[3])); phil.start(); }
[ "karasavm@gmail.com" ]
karasavm@gmail.com
b48137e6b9dc08034ba6cefd29fce1f089b03b67
185412a166cc59dd191ea91ac0ed99e03ff7b08e
/Pizza.cpp
130e86450aa4bd4b04ad31c770d0623c77dfcce6
[]
no_license
RobertLarson/TemplateMethodPattern
6d992cfc759cb68854c1b210741fe6707905747c
3b86a364196bce128f914193177dc0972bd68773
refs/heads/master
2021-01-19T08:46:50.887724
2017-04-09T02:51:30
2017-04-09T02:51:30
87,674,552
1
0
null
null
null
null
UTF-8
C++
false
false
558
cpp
/* * Pizza.cpp * * Created on: Apr 8, 2017 * Author: Robert Larson */ #include "Pizza.h" #include <iostream> Pizza::Pizza(std::string description) : m_description(description) { } Pizza::~Pizza() { } void Pizza::Prepare() { std::cout << "Preparing a " << m_description << "...\n"; PrepareDough(); AddSauce(); AddToppings(); Bake(); std::cout << "\n"; } void Pizza::PrepareDough() { std::cout << "preparing dough\n"; } void Pizza::AddSauce() { std::cout << "adding sauce\n"; } void Pizza::Bake() { std::cout << "bake pizza\n"; }
[ "Robert.Larson@robertlarsononline.com" ]
Robert.Larson@robertlarsononline.com
22827f0adb719ff73e7f4d1e080039840af8e41e
752572bd6010ef068c4851b55a261a2122f29094
/aws-cpp-sdk-rds-data/include/aws/rds-data/model/Value.h
dfb5806253f99c7247e345dbb1d89ba2e05d1288
[ "Apache-2.0", "MIT", "JSON" ]
permissive
cnxtech/aws-sdk-cpp
9b208792b2e81b3a22a850c3d0fbf4724dc65a99
af8089f6277b8fec93c55a815c724444bd159a13
refs/heads/master
2023-08-15T02:01:42.569685
2019-05-08T20:39:01
2019-05-08T20:39:01
185,732,288
0
0
Apache-2.0
2023-07-22T05:12:44
2019-05-09T05:30:49
C++
UTF-8
C++
false
false
9,028
h
/* * Copyright 2010-2017 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. */ #pragma once #include <aws/rds-data/RDSDataService_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/core/utils/Array.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/rds-data/model/StructValue.h> #include <aws/rds-data/model/Value.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace RDSDataService { namespace Model { /** * Column value<p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/rds-data-2018-08-01/Value">AWS API * Reference</a></p> */ class AWS_RDSDATASERVICE_API Value { public: Value(); Value(Aws::Utils::Json::JsonView jsonValue); Value& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * Arbitrarily nested arrays */ inline const Aws::Vector<Value>& GetArrayValues() const{ return m_arrayValues; } /** * Arbitrarily nested arrays */ inline bool ArrayValuesHasBeenSet() const { return m_arrayValuesHasBeenSet; } /** * Arbitrarily nested arrays */ inline void SetArrayValues(const Aws::Vector<Value>& value) { m_arrayValuesHasBeenSet = true; m_arrayValues = value; } /** * Arbitrarily nested arrays */ inline void SetArrayValues(Aws::Vector<Value>&& value) { m_arrayValuesHasBeenSet = true; m_arrayValues = std::move(value); } /** * Arbitrarily nested arrays */ inline Value& WithArrayValues(const Aws::Vector<Value>& value) { SetArrayValues(value); return *this;} /** * Arbitrarily nested arrays */ inline Value& WithArrayValues(Aws::Vector<Value>&& value) { SetArrayValues(std::move(value)); return *this;} /** * Arbitrarily nested arrays */ inline Value& AddArrayValues(const Value& value) { m_arrayValuesHasBeenSet = true; m_arrayValues.push_back(value); return *this; } /** * Arbitrarily nested arrays */ inline Value& AddArrayValues(Value&& value) { m_arrayValuesHasBeenSet = true; m_arrayValues.push_back(std::move(value)); return *this; } /** * Long value */ inline long long GetBigIntValue() const{ return m_bigIntValue; } /** * Long value */ inline bool BigIntValueHasBeenSet() const { return m_bigIntValueHasBeenSet; } /** * Long value */ inline void SetBigIntValue(long long value) { m_bigIntValueHasBeenSet = true; m_bigIntValue = value; } /** * Long value */ inline Value& WithBigIntValue(long long value) { SetBigIntValue(value); return *this;} /** * Bit value */ inline bool GetBitValue() const{ return m_bitValue; } /** * Bit value */ inline bool BitValueHasBeenSet() const { return m_bitValueHasBeenSet; } /** * Bit value */ inline void SetBitValue(bool value) { m_bitValueHasBeenSet = true; m_bitValue = value; } /** * Bit value */ inline Value& WithBitValue(bool value) { SetBitValue(value); return *this;} /** * Blob value */ inline const Aws::Utils::ByteBuffer& GetBlobValue() const{ return m_blobValue; } /** * Blob value */ inline bool BlobValueHasBeenSet() const { return m_blobValueHasBeenSet; } /** * Blob value */ inline void SetBlobValue(const Aws::Utils::ByteBuffer& value) { m_blobValueHasBeenSet = true; m_blobValue = value; } /** * Blob value */ inline void SetBlobValue(Aws::Utils::ByteBuffer&& value) { m_blobValueHasBeenSet = true; m_blobValue = std::move(value); } /** * Blob value */ inline Value& WithBlobValue(const Aws::Utils::ByteBuffer& value) { SetBlobValue(value); return *this;} /** * Blob value */ inline Value& WithBlobValue(Aws::Utils::ByteBuffer&& value) { SetBlobValue(std::move(value)); return *this;} /** * Double value */ inline double GetDoubleValue() const{ return m_doubleValue; } /** * Double value */ inline bool DoubleValueHasBeenSet() const { return m_doubleValueHasBeenSet; } /** * Double value */ inline void SetDoubleValue(double value) { m_doubleValueHasBeenSet = true; m_doubleValue = value; } /** * Double value */ inline Value& WithDoubleValue(double value) { SetDoubleValue(value); return *this;} /** * Integer value */ inline int GetIntValue() const{ return m_intValue; } /** * Integer value */ inline bool IntValueHasBeenSet() const { return m_intValueHasBeenSet; } /** * Integer value */ inline void SetIntValue(int value) { m_intValueHasBeenSet = true; m_intValue = value; } /** * Integer value */ inline Value& WithIntValue(int value) { SetIntValue(value); return *this;} /** * Is column null */ inline bool GetIsNull() const{ return m_isNull; } /** * Is column null */ inline bool IsNullHasBeenSet() const { return m_isNullHasBeenSet; } /** * Is column null */ inline void SetIsNull(bool value) { m_isNullHasBeenSet = true; m_isNull = value; } /** * Is column null */ inline Value& WithIsNull(bool value) { SetIsNull(value); return *this;} /** * Float value */ inline double GetRealValue() const{ return m_realValue; } /** * Float value */ inline bool RealValueHasBeenSet() const { return m_realValueHasBeenSet; } /** * Float value */ inline void SetRealValue(double value) { m_realValueHasBeenSet = true; m_realValue = value; } /** * Float value */ inline Value& WithRealValue(double value) { SetRealValue(value); return *this;} /** * String value */ inline const Aws::String& GetStringValue() const{ return m_stringValue; } /** * String value */ inline bool StringValueHasBeenSet() const { return m_stringValueHasBeenSet; } /** * String value */ inline void SetStringValue(const Aws::String& value) { m_stringValueHasBeenSet = true; m_stringValue = value; } /** * String value */ inline void SetStringValue(Aws::String&& value) { m_stringValueHasBeenSet = true; m_stringValue = std::move(value); } /** * String value */ inline void SetStringValue(const char* value) { m_stringValueHasBeenSet = true; m_stringValue.assign(value); } /** * String value */ inline Value& WithStringValue(const Aws::String& value) { SetStringValue(value); return *this;} /** * String value */ inline Value& WithStringValue(Aws::String&& value) { SetStringValue(std::move(value)); return *this;} /** * String value */ inline Value& WithStringValue(const char* value) { SetStringValue(value); return *this;} /** * Struct or UDT */ inline const StructValue& GetStructValue() const{ return m_structValue; } /** * Struct or UDT */ inline bool StructValueHasBeenSet() const { return m_structValueHasBeenSet; } /** * Struct or UDT */ inline void SetStructValue(const StructValue& value) { m_structValueHasBeenSet = true; m_structValue = value; } /** * Struct or UDT */ inline void SetStructValue(StructValue&& value) { m_structValueHasBeenSet = true; m_structValue = std::move(value); } /** * Struct or UDT */ inline Value& WithStructValue(const StructValue& value) { SetStructValue(value); return *this;} /** * Struct or UDT */ inline Value& WithStructValue(StructValue&& value) { SetStructValue(std::move(value)); return *this;} private: Aws::Vector<Value> m_arrayValues; bool m_arrayValuesHasBeenSet; long long m_bigIntValue; bool m_bigIntValueHasBeenSet; bool m_bitValue; bool m_bitValueHasBeenSet; Aws::Utils::ByteBuffer m_blobValue; bool m_blobValueHasBeenSet; double m_doubleValue; bool m_doubleValueHasBeenSet; int m_intValue; bool m_intValueHasBeenSet; bool m_isNull; bool m_isNullHasBeenSet; double m_realValue; bool m_realValueHasBeenSet; Aws::String m_stringValue; bool m_stringValueHasBeenSet; StructValue m_structValue; bool m_structValueHasBeenSet; }; } // namespace Model } // namespace RDSDataService } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
71c42cfb142d1cf3ed8d34657a4a0ae0aaca5780
b88eeed20d442c3e164c727a97db7bdf1935b70f
/contrib/oxl/mvl/HomgMatchPoint3D2D.h
c337b5856ed4974a70115af8e6ed824defe40db7
[]
no_license
huanghailiang/vxl-1.17.0
be3b4909ef31efc2aa0eb4ee884e5190704ca060
c3076ac1013f10a532fe6d6b3c5f5b78eb26466e
refs/heads/master
2021-07-23T04:05:36.954717
2017-11-01T07:23:22
2017-11-01T07:23:22
109,099,265
0
0
null
null
null
null
UTF-8
C++
false
false
957
h
// This is oxl/mvl/HomgMatchPoint3D2D.h #ifndef HomgMatchPoint3D2D_h_ #define HomgMatchPoint3D2D_h_ #ifdef VCL_NEEDS_PRAGMA_INTERFACE #pragma interface #endif //: // \file // \brief A match between a 3D and 2D point // // A class to hold a match between a 3D and 2D point. // #include <mvl/HomgPoint2D.h> #include <mvl/HomgPoint3D.h> class HomgMatchPoint3D2D { // Data Members------------------------------------------------------------ HomgPoint2D _point2D; HomgPoint3D _point3D; public: // Constructors/Initializers/Destructors----------------------------------- HomgMatchPoint3D2D (); HomgMatchPoint3D2D (HomgPoint3D *point3D_ptr, HomgPoint2D *point2D_ptr); ~HomgMatchPoint3D2D (); // Data Access------------------------------------------------------------- HomgPoint3D get_point3D (void); HomgPoint2D get_point2D (void); void set (HomgPoint3D *point3D_ptr, HomgPoint2D *point2D_ptr); }; #endif // HomgMatchPoint3D2D_h_
[ "huanghailiang711@163.com" ]
huanghailiang711@163.com
e75f285986683e054590a8c69cecdcaca12349d6
eab2ea8f23a1c7d88a69f973e9f32b16ce103259
/equation of a line.cpp
48ae9da7588befd9b80e17dd7e8a1e596142a768
[]
no_license
apaarkamal/miscellaneous-codes
73a973a0f66973c15262b0a0dae2e8776ac3b0ae
df822d1dc06b7cb5426bbb04256179c5b5b04641
refs/heads/master
2020-06-12T19:50:16.772416
2019-12-02T05:59:03
2019-12-02T05:59:03
194,406,672
6
10
null
null
null
null
UTF-8
C++
false
false
2,143
cpp
#include<bits/stdc++.h> using namespace std; #define int long long int #define ld long double #define F first #define S second #define P pair<int,int> #define V vector #define pb push_back #define db(...) __f(#__VA_ARGS__, __VA_ARGS__) template <typename Arg1> void __f(const char* name, Arg1&& arg1) { cerr << name << " : " << arg1 << '\n'; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args) { const char* comma = strchr(names + 1, ','); cerr.write(names, comma - names) << " : " << arg1 << " | "; __f(comma + 1, args...); } const int N = 100005; int32_t main() { ios_base:: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); freopen("debug.txt", "w", stderr); #endif // int t;cin>>t;while(t--) { int i, j, k, n, m, ans = 0, cnt = 0, sum = 0; cin >> n; V<P> v(n); for (i = 0; i < n; i++) { cin >> v[i].F >> v[i].S; } V<V<int>> vv; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { // construct a line passing through (x1, y1) and (x2, y2) // line is expressed as equation ax - by = c with constant a, b, c int num = v[j].S - v[i].S; int den = v[j].F - v[i].F; int g = __gcd(num, den); num /= g; den /= g; if (den < 0 || (den == 0 && num < 0)) { den = abs(den); num = -num; //making num positive } vv.pb({num, den, num*v[i].F - den*v[i].S}); } } sort(vv.begin(), vv.end()); vv.resize(unique(vv.begin(), vv.end()) - vv.begin()); n = vv.size(); j = 0; i = 0; while (i < n) { while (j < n && vv[j][0] == vv[i][0] && vv[i][1] == vv[j][1]) { j++; } cnt = j - i; ans += cnt * (n - cnt - i); i = j; } cout << ans; } }
[ "apaarsaxena@gmail.com" ]
apaarsaxena@gmail.com
e1a817336f81c0f346d202afe17f0da6b2525910
825baeebcab670220ee929252c78a42fe2c5fc7f
/dragonpoop_prealpha/dragonpoop/gfx/model/model_group_instance/model_group_instance_writelock.cpp
93c897a7f534d65c753d8fd894c6620d12974ddd
[]
no_license
rvaughn4/dragonpoop_prealpha
45e381cd06eea83aa022decf730688085e2b87a3
e16b41838a42fed417cfeef075509f744fe6f38a
refs/heads/master
2016-09-05T11:36:02.701048
2015-07-25T02:15:20
2015-07-25T02:15:20
37,826,187
0
0
null
null
null
null
UTF-8
C++
false
false
1,820
cpp
#include "model_group_instance_writelock.h" #include "model_group_instance.h" namespace dragonpoop { //ctor model_group_instance_writelock::model_group_instance_writelock( model_group_instance *t, dpmutex_writelock *l ) : model_component_writelock( t, l ) { this->t = t; } //dtor model_group_instance_writelock::~model_group_instance_writelock( void ) { } //return instance id dpid model_group_instance_writelock::getInstanceId( void ) { return this->t->getInstanceId(); } //return group id dpid model_group_instance_writelock::getGroupId( void ) { return this->t->getGroupId(); } //return partent id dpid model_group_instance_writelock::getParentId( void ) { return this->t->getParentId(); } //returns true if has renderer bool model_group_instance_writelock::hasRenderer( void ) { return this->t->hasRenderer(); } //set renderer void model_group_instance_writelock::setRenderer( shared_obj_writelock *r ) { this->t->setRenderer( r ); } //get renderer shared_obj_ref *model_group_instance_writelock::getRenderer( void ) { return this->t->getRenderer(); } //get vertexes void model_group_instance_writelock::getVertexes( dpvertexindex_buffer *b ) { this->t->getVertexes( b ); } //sync group void model_group_instance_writelock::sync( model_writelock *ml ) { this->t->sync( ml ); } //return material id dpid model_group_instance_writelock::getMaterialId( void ) { return this->t->getMaterialId(); } //returns true if has material bool model_group_instance_writelock::hasMaterial( void ) { return this->t->hasMaterial(); } };
[ "richard@richards-Mac-mini.local" ]
richard@richards-Mac-mini.local
897e3244ffe124f91ccf045a244300f3c95bf89c
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_1483488_1/C++/DenXX/c.cpp
e53d0794630c209fbd0ed9d4dd5392dd57afc86a
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
745
cpp
#include <iostream> #include <vector> #include <set> #include <math.h> using namespace std; int check(int a, int b, int n) { int res = 0; int digcount = (int)(log(n)/log(10)) + 1; set<int> ns; for (int i = 1; i < digcount; ++i) { int dec = pow(10, i); int dec2 = pow(10, digcount - i); int left = n / dec; int right = n % dec; int n1 = right * dec2 + left; if (n1 > n && n1 >= a && n1 <= b && ns.find(n1) == ns.end()) { ns.insert(n1); ++res; } } return res; } int main(int argc, char argv[]) { int t; cin >> t; for (int i = 0; i < t; ++i) { int res = 0; int a, b; cin >> a >> b; for (int j = a; j < b; ++j) res += check(a, b, j); cout << "Case #" << i + 1 << ": " << res << endl; } return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
eee04280c3246d7c601b7a438a089586dbf7a4a7
31ac1d5aa829e459527e110bccce82d0f9d02231
/tomjerry.cpp
28daa92facf55431773af5b75d588d6b338d12b3
[]
no_license
nv-piyush/CodeChef-June-Challenge-2020
67f2d870478b788ae9f3b8067b40306d18bb8c2c
f7a519243ffd0afd5511ead65a805077e9d197a4
refs/heads/master
2022-11-07T15:45:10.083701
2020-06-27T12:19:09
2020-06-27T12:19:09
275,362,167
0
0
null
null
null
null
UTF-8
C++
false
false
822
cpp
#include <iostream> using namespace std; int main() { // your code goes here int t; cin>>t; while(t--){ long long int ts; cin>>ts; while(ts%2==0) ts/=2; ts/=2; cout<<ts<<endl; /*if(ts==1){ cout<<"0"<<endl; } while(i<=ts && ts>1){ if(ts%2==0){ if(i%2==0){ ts/=2; i/=2; } else{ f=1; break; } } else{ if(i%2==0){ cnt++; i++; } else{ f=1; break; } } } if(f==1) cout<<"0"<<endl; else cout<<cnt<<endl;*/ } return 0; }
[ "noreply@github.com" ]
nv-piyush.noreply@github.com
9321de9ca49afe7fa691ee61406a58ed7c4d329e
ab0dcab89f39d12746ad2b3506e1c2c34d8f1bf4
/POJ/1947/9310297_AC_16ms_752kB.cpp
8b260d53f1a854dfa7fd2339aa1b92b52b878e72
[]
no_license
lum7na/ACM
f672583ff3022bc916d9cd3d721f0a464b287042
fa667f4105450ec48e9b1d1b062f1444b6f0da32
refs/heads/main
2023-05-06T21:23:13.069269
2021-06-01T11:56:16
2021-06-01T11:56:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,132
cpp
#include<cstdio> #include<algorithm> #include<cstdlib> #include<iostream> #include<cstring> #include<cmath> using namespace std; const int maxn=150; int root; struct edge { int to,nxt; } edges[maxn+5]; int n,fa[maxn+5],p; int tot,head[maxn+5]; int f[maxn+5][maxn+5]; inline void add_edge(int from,int to) { edges[++tot].to=to; edges[tot].nxt=head[from]; head[from]=tot; return; } void dfs(int u) { int ud=0; for (int i=head[u];i;i=edges[i].nxt) { if (edges[i].to!=fa[u]) { ud++; } } f[u][1]=ud+1; for (int i=2;i<=p;++i) { f[u][i]=maxn<<1; } for (int i=head[u];i;i=edges[i].nxt) { int v=edges[i].to; dfs(v); for (int j=p;j>1;--j) { for (int k=1;k<j;++k) { f[u][j]=min(f[u][j],f[v][k]+f[u][j-k]-2); } } } return; } int main() { scanf("%d%d",&n,&p); int fr,t; for (int i=1;i<=n-1;++i) { scanf("%d%d",&fr,&t); fa[t]=fr; add_edge(fr,t); } root=1; while (fa[root]) { root=fa[root]; } dfs(root); int ans=maxn; f[root][p]--; for (int i=1;i<=n;++i) { ans=min(ans,f[i][p]); } printf("%d\n",ans); return 0; }
[ "aster2632@gmail.com" ]
aster2632@gmail.com
fbfa26849ea73a19b1fa498d8d4c65a4fc20bb73
b8cb3acc677efcb6e73c0f884e2f8a639d5536c3
/variational_fluids/VariationalViscosity3D/pcgsolver/sparse_matrix.h
728e89f628543daab2f7f3107ab6dfe8ecfe72ae
[ "Apache-2.0" ]
permissive
OrionQuest/Nova_Examples
89af95cf696442b198073d06812eea0e3b3526e4
482521902bc3afa7d0caefeb9ce9595456384961
refs/heads/master
2021-06-03T02:25:39.100078
2020-12-13T02:37:23
2020-12-13T02:37:23
141,195,357
3
2
null
null
null
null
UTF-8
C++
false
false
8,114
h
#ifndef SPARSE_MATRIX_H #define SPARSE_MATRIX_H #include <iostream> #include <vector> #include "../util.h" //============================================================================ // Dynamic compressed sparse row matrix. template<class T> struct SparseMatrix { unsigned int n; // dimension std::vector<std::vector<unsigned int> > index; // for each row, a list of all column indices (sorted) std::vector<std::vector<T> > value; // values corresponding to index explicit SparseMatrix(unsigned int n_=0, unsigned int expected_nonzeros_per_row=7) : n(n_), index(n_), value(n_) { for(unsigned int i=0; i<n; ++i){ index[i].reserve(expected_nonzeros_per_row); value[i].reserve(expected_nonzeros_per_row); } } void clear(void) { n=0; index.clear(); value.clear(); } void zero(void) { for(unsigned int i=0; i<n; ++i){ index[i].resize(0); value[i].resize(0); } } void resize(int n_) { n=n_; index.resize(n); value.resize(n); } T operator()(unsigned int i, unsigned int j) const { for(unsigned int k=0; k<index[i].size(); ++k){ if(index[i][k]==j) return value[i][k]; else if(index[i][k]>j) return 0; } return 0; } void set_element(unsigned int i, unsigned int j, T new_value) { unsigned int k=0; for(; k<index[i].size(); ++k){ if(index[i][k]==j){ value[i][k]=new_value; return; }else if(index[i][k]>j){ insert(index[i], k, j); insert(value[i], k, new_value); return; } } index[i].push_back(j); value[i].push_back(new_value); } void add_to_element(unsigned int i, unsigned int j, T increment_value) { unsigned int k=0; for(; k<index[i].size(); ++k){ if(index[i][k]==j){ value[i][k]+=increment_value; return; }else if(index[i][k]>j){ insert(index[i], k, j); insert(value[i], k, increment_value); return; } } index[i].push_back(j); value[i].push_back(increment_value); } // assumes indices is already sorted void add_sparse_row(unsigned int i, const std::vector<unsigned int> &indices, const std::vector<T> &values) { unsigned int j=0, k=0; while(j<indices.size() && k<index[i].size()){ if(index[i][k]<indices[j]){ ++k; }else if(index[i][k]>indices[j]){ insert(index[i], k, indices[j]); insert(value[i], k, values[j]); ++j; }else{ value[i][k]+=values[j]; ++j; ++k; } } for(;j<indices.size(); ++j){ index[i].push_back(indices[j]); value[i].push_back(values[j]); } } // assumes matrix has symmetric structure - so the indices in row i tell us which columns to delete i from void symmetric_remove_row_and_column(unsigned int i) { for(unsigned int a=0; a<index[i].size(); ++a){ unsigned int j=index[i][a]; // for(unsigned int b=0; b<index[j].size(); ++b){ if(index[j][b]==i){ erase(index[j], b); erase(value[j], b); break; } } } index[i].resize(0); value[i].resize(0); } void write_matlab(std::ostream &output, const char *variable_name) { output<<variable_name<<"=sparse(["; for(unsigned int i=0; i<n; ++i){ for(unsigned int j=0; j<index[i].size(); ++j){ output<<i+1<<" "; } } output<<"],...\n ["; for(unsigned int i=0; i<n; ++i){ for(unsigned int j=0; j<index[i].size(); ++j){ output<<index[i][j]+1<<" "; } } output<<"],...\n ["; for(unsigned int i=0; i<n; ++i){ for(unsigned int j=0; j<value[i].size(); ++j){ output<<value[i][j]<<" "; } } output<<"], "<<n<<", "<<n<<");"<<std::endl; } }; typedef SparseMatrix<float> SparseMatrixf; typedef SparseMatrix<double> SparseMatrixd; // perform result=matrix*x template<class T> void multiply(const SparseMatrix<T> &matrix, const std::vector<T> &x, std::vector<T> &result) { assert(matrix.n==x.size()); result.resize(matrix.n); for(unsigned int i=0; i<matrix.n; ++i){ result[i]=0; for(unsigned int j=0; j<matrix.index[i].size(); ++j){ result[i]+=matrix.value[i][j]*x[matrix.index[i][j]]; } } } // perform result=result-matrix*x template<class T> void multiply_and_subtract(const SparseMatrix<T> &matrix, const std::vector<T> &x, std::vector<T> &result) { assert(matrix.n==x.size()); result.resize(matrix.n); for(unsigned int i=0; i<matrix.n; ++i){ for(unsigned int j=0; j<matrix.index[i].size(); ++j){ result[i]-=matrix.value[i][j]*x[matrix.index[i][j]]; } } } //============================================================================ // Fixed version of SparseMatrix. This is not a good structure for dynamically // modifying the matrix, but can be significantly faster for matrix-vector // multiplies due to better data locality. template<class T> struct FixedSparseMatrix { unsigned int n; // dimension std::vector<T> value; // nonzero values row by row std::vector<unsigned int> colindex; // corresponding column indices std::vector<unsigned int> rowstart; // where each row starts in value and colindex (and last entry is one past the end, the number of nonzeros) explicit FixedSparseMatrix(unsigned int n_=0) : n(n_), value(0), colindex(0), rowstart(n_+1) {} void clear(void) { n=0; value.clear(); colindex.clear(); rowstart.clear(); } void resize(int n_) { n=n_; rowstart.resize(n+1); } void construct_from_matrix(const SparseMatrix<T> &matrix) { resize(matrix.n); rowstart[0]=0; for(unsigned int i=0; i<n; ++i){ rowstart[i+1]=rowstart[i]+matrix.index[i].size(); } value.resize(rowstart[n]); colindex.resize(rowstart[n]); unsigned int j=0; for(unsigned int i=0; i<n; ++i){ for(unsigned int k=0; k<matrix.index[i].size(); ++k){ value[j]=matrix.value[i][k]; colindex[j]=matrix.index[i][k]; ++j; } } } void write_matlab(std::ostream &output, const char *variable_name) { output<<variable_name<<"=sparse(["; for(unsigned int i=0; i<n; ++i){ for(unsigned int j=rowstart[i]; j<rowstart[i+1]; ++j){ output<<i+1<<" "; } } output<<"],...\n ["; for(unsigned int i=0; i<n; ++i){ for(unsigned int j=rowstart[i]; j<rowstart[i+1]; ++j){ output<<colindex[j]+1<<" "; } } output<<"],...\n ["; for(unsigned int i=0; i<n; ++i){ for(unsigned int j=rowstart[i]; j<rowstart[i+1]; ++j){ output<<value[j]<<" "; } } output<<"], "<<n<<", "<<n<<");"<<std::endl; } }; typedef FixedSparseMatrix<float> FixedSparseMatrixf; typedef FixedSparseMatrix<double> FixedSparseMatrixd; // perform result=matrix*x template<class T> void multiply(const FixedSparseMatrix<T> &matrix, const std::vector<T> &x, std::vector<T> &result) { assert(matrix.n==x.size()); result.resize(matrix.n); for(unsigned int i=0; i<matrix.n; ++i){ result[i]=0; for(unsigned int j=matrix.rowstart[i]; j<matrix.rowstart[i+1]; ++j){ result[i]+=matrix.value[j]*x[matrix.colindex[j]]; } } } // perform result=result-matrix*x template<class T> void multiply_and_subtract(const FixedSparseMatrix<T> &matrix, const std::vector<T> &x, std::vector<T> &result) { assert(matrix.n==x.size()); result.resize(matrix.n); for(unsigned int i=0; i<matrix.n; ++i){ for(unsigned int j=matrix.rowstart[i]; j<matrix.rowstart[i+1]; ++j){ result[i]-=matrix.value[j]*x[matrix.colindex[j]]; } } } #endif
[ "mridul.aanjaneya@gmail.com" ]
mridul.aanjaneya@gmail.com
23c963fe0be9322bb3edee7faa012f773163756b
07074962be026c67519a0ccfb3d48bd95ede38ed
/Forms/c5saledoc.h
06685ae163cca1ebba2977147efb552467d77df7
[]
no_license
End1-1/Cafe5
2fa65c62f395c186e2204f3fb941a2f93fd3a653
ba2b695c627cf59260a3ac1134927198c004fe53
refs/heads/master
2023-08-17T02:39:29.224396
2023-08-14T06:37:55
2023-08-14T06:37:55
151,380,276
2
1
null
null
null
null
UTF-8
C++
false
false
2,543
h
#ifndef C5SALEDOC_H #define C5SALEDOC_H #include "c5widget.h" #include "cpartners.h" #include "odraftsale.h" #include "odraftsalebody.h" #include <QJsonObject> namespace Ui { class C5SaleDoc; } static const int PRICEMODE_RETAIL = 1; static const int PRICEMODE_WHOSALE = 2; #define REPORT_HANDLER_SALE_DOC_OPEN_DRAFT "39617ca7-8fa4-11ed-8ad3-1078d2d2b808" class C5SaleDoc : public C5Widget { Q_OBJECT public: explicit C5SaleDoc(const QStringList &dbParams, QWidget *parent = nullptr); ~C5SaleDoc(); void setMode(int mode); virtual bool reportHandler(const QString &handleId, const QVariant &data); virtual QToolBar *toolBar() override; bool openDoc(const QString &uuid); private slots: void amountDoubleClicked(); void printSale(); void fiscale(); void createInvoiceAS(); void createRetailAS(); void makeStoreOutput(); void exportToExcel(); void messageResult(QJsonObject jo); void saveDataChanges(); void saveAsDraft(); void saveCopy(); void removeDoc(); void uuidDoubleClicked(); void on_PriceTextChanged(const QString &arg1); void on_QtyTextChanged(const QString &arg1); void on_discountValueChanged(const QString &arg1); void on_leCmd_returnPressed(); void on_btnAddGoods_clicked(); void on_btnRemoveGoods_clicked(); void on_btnEditGoods_clicked(); void on_btnNewGoods_clicked(); void on_cbHall_currentIndexChanged(int index); void on_btnSearchTaxpayer_clicked(); void on_btnRemoveDelivery_clicked(); void on_btnDelivery_clicked(); void on_btnEditPartner_clicked(); void on_btnEditAccounts_clicked(); void on_leCash_textChanged(const QString &arg1); void on_btnDeliveryMan_clicked(); private: Ui::C5SaleDoc *ui; CPartners fPartner; ODraftSale fDraftSale; ODraftSaleBody fDraftSaleBody; int fMode; QAction *fActionSave; QAction *fActionDraft; QAction *fActionCopy; QAction *fRemoveAction; QAction *fPrintTax; int addGoods(int goodsId, C5Database &db); int addGoods(int store, int goodsId, const QString &barcode, const QString &name, const QString &unitname, double qty, double price, double discount, int isService); void countGrandTotal(); bool openDraft(const QString &id); void setPartner(); void setPartner(const CPartners &p); void setDeliveryMan(); void exportToAs(int doctype); bool fOpenedFromDraft; QMap<int, QString> fListOfStorages; QMap<int, double> fSpecialPrices; }; #endif // C5SALEDOC_H
[ "end1_1@yahoo.com" ]
end1_1@yahoo.com
03a303c9b9445d9da259ed70285d63e4c9c298a7
6c66f928a42f891a8b585015b2f71e44ac7b9f8d
/TutIntV30/Act2DosBI.h
1ad857286ced9449fc04096f2a6806d4f11cfdce
[]
no_license
FelipeSegovia/TutInt
5857e20d3aa0b5c10a61a788c2f73d3bde888c75
7b30644d2f9b0ca0f8901da4e70d7b2ff607c53a
refs/heads/master
2020-03-17T19:10:19.103492
2018-05-17T17:53:22
2018-05-17T17:53:22
133,848,477
0
0
null
null
null
null
ISO-8859-1
C++
false
false
30,820
h
#pragma once #include "BaseDeDatos.h" #include "AgenteControlador.h" #include "TiempoMI.h" #include "TiempoGUI.h" namespace TutIntV30 { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Resumen de Act2DosBI /// </summary> public ref class Act2DosBI : public System::Windows::Forms::Form { public: Act2DosBI(void) { InitializeComponent(); // //TODO: agregar código de constructor aquí // } Act2DosBI(Form^ f, BaseDeDatos^ manejador, AgenteControlador* control) { form = f; manejadorBD = manejador; controlador = control; InitializeComponent(); inicializarTam(); inicializarPosiciones(); this->Size = System::Drawing::Size(1050, 598); this->Show(); } protected: /// <summary> /// Limpiar los recursos que se estén usando. /// </summary> ~Act2DosBI() { if (components) { delete components; } } private: int contAyuda = 0; private: BaseDeDatos ^ manejadorBD; private: AgenteControlador * controlador; private: int segundos, minutos, horas; // Para el form private: TiempoGUI ^ t_actividad, ^t_item1, ^t_item2, ^t_item3, ^t_item4; private: Thread ^ hiloAct; private: System::Windows::Forms::Form^ form; private: int wVolver, hVolver, wListo, hListo, wAyuda, hAyuda; private: int posMouseFormX, posMouseFormY; private: int posMouseBtnX, posMouseBtnY; private: int posActBtnX, posActBtnY; private: bool btnPresionado = false; private: int xbtn1, ybtn1, xbtn2, ybtn2, xbtn3, ybtn3, xbtn4, ybtn4; // Guardar la posicion original del boton private: bool listoBtn1, listoBtn2, listoBtn3, listoBtn4; private: System::Windows::Forms::Panel^ panelPrincipal; private: System::Windows::Forms::Panel^ panel13; private: System::Windows::Forms::PictureBox^ btnListo; private: System::Windows::Forms::PictureBox^ btnVolver; private: System::Windows::Forms::Panel^ panel2; private: System::Windows::Forms::PictureBox^ btnAyuda; private: System::Windows::Forms::Panel^ panel9; private: System::Windows::Forms::PictureBox^ pictureBox7; private: System::Windows::Forms::Label^ label6; private: System::Windows::Forms::PictureBox^ picMinimizar; private: System::Windows::Forms::PictureBox^ picCerrar; private: System::Windows::Forms::Timer^ timer1; private: System::Windows::Forms::Button^ btnCuatro; private: System::Windows::Forms::Button^ btnTres; private: System::Windows::Forms::Button^ btnDos; private: System::Windows::Forms::Button^ btnUno; private: System::Windows::Forms::Label^ label4; private: System::Windows::Forms::Label^ label3; private: System::Windows::Forms::Label^ label2; private: System::Windows::Forms::Panel^ panelTres3; private: System::Windows::Forms::Panel^ panelDos3; private: System::Windows::Forms::Panel^ panelTres2; private: System::Windows::Forms::Panel^ panelUno3; private: System::Windows::Forms::Panel^ panelTres1; private: System::Windows::Forms::Panel^ panelDos2; private: System::Windows::Forms::Panel^ panelDos1; private: System::Windows::Forms::Panel^ panelUno2; private: System::Windows::Forms::Panel^ panelUno1; private: System::Windows::Forms::Panel^ panel1; private: System::Windows::Forms::Label^ instruccion1; private: System::Windows::Forms::Label^ instruccion2; private: System::ComponentModel::IContainer^ components; private: /// <summary> /// Variable del diseñador necesaria. /// </summary> #pragma region Windows Form Designer generated code /// <summary> /// Método necesario para admitir el Diseñador. No se puede modificar /// el contenido de este método con el editor de código. /// </summary> void InitializeComponent(void) { this->components = (gcnew System::ComponentModel::Container()); System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(Act2DosBI::typeid)); this->panelPrincipal = (gcnew System::Windows::Forms::Panel()); this->panel13 = (gcnew System::Windows::Forms::Panel()); this->btnListo = (gcnew System::Windows::Forms::PictureBox()); this->btnVolver = (gcnew System::Windows::Forms::PictureBox()); this->panel2 = (gcnew System::Windows::Forms::Panel()); this->btnCuatro = (gcnew System::Windows::Forms::Button()); this->btnTres = (gcnew System::Windows::Forms::Button()); this->btnDos = (gcnew System::Windows::Forms::Button()); this->btnUno = (gcnew System::Windows::Forms::Button()); this->panelTres3 = (gcnew System::Windows::Forms::Panel()); this->panelDos3 = (gcnew System::Windows::Forms::Panel()); this->panelTres2 = (gcnew System::Windows::Forms::Panel()); this->panelUno3 = (gcnew System::Windows::Forms::Panel()); this->panelTres1 = (gcnew System::Windows::Forms::Panel()); this->panelDos2 = (gcnew System::Windows::Forms::Panel()); this->panelDos1 = (gcnew System::Windows::Forms::Panel()); this->panelUno2 = (gcnew System::Windows::Forms::Panel()); this->panelUno1 = (gcnew System::Windows::Forms::Panel()); this->label4 = (gcnew System::Windows::Forms::Label()); this->label3 = (gcnew System::Windows::Forms::Label()); this->label2 = (gcnew System::Windows::Forms::Label()); this->btnAyuda = (gcnew System::Windows::Forms::PictureBox()); this->panel9 = (gcnew System::Windows::Forms::Panel()); this->pictureBox7 = (gcnew System::Windows::Forms::PictureBox()); this->label6 = (gcnew System::Windows::Forms::Label()); this->picMinimizar = (gcnew System::Windows::Forms::PictureBox()); this->picCerrar = (gcnew System::Windows::Forms::PictureBox()); this->timer1 = (gcnew System::Windows::Forms::Timer(this->components)); this->panel1 = (gcnew System::Windows::Forms::Panel()); this->instruccion1 = (gcnew System::Windows::Forms::Label()); this->instruccion2 = (gcnew System::Windows::Forms::Label()); this->panelPrincipal->SuspendLayout(); this->panel13->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->btnListo))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->btnVolver))->BeginInit(); this->panel2->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->btnAyuda))->BeginInit(); this->panel9->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox7))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->picMinimizar))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->picCerrar))->BeginInit(); this->panel1->SuspendLayout(); this->SuspendLayout(); // // panelPrincipal // this->panelPrincipal->BackColor = System::Drawing::Color::Transparent; this->panelPrincipal->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"panelPrincipal.BackgroundImage"))); this->panelPrincipal->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->panelPrincipal->Controls->Add(this->panel1); this->panelPrincipal->Controls->Add(this->panel13); this->panelPrincipal->Controls->Add(this->panel2); this->panelPrincipal->Controls->Add(this->btnAyuda); this->panelPrincipal->Dock = System::Windows::Forms::DockStyle::Fill; this->panelPrincipal->Location = System::Drawing::Point(0, 70); this->panelPrincipal->Name = L"panelPrincipal"; this->panelPrincipal->Size = System::Drawing::Size(2450, 1264); this->panelPrincipal->TabIndex = 2; // // panel13 // this->panel13->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"panel13.BackgroundImage"))); this->panel13->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->panel13->Controls->Add(this->btnListo); this->panel13->Controls->Add(this->btnVolver); this->panel13->Location = System::Drawing::Point(17, 679); this->panel13->Name = L"panel13"; this->panel13->Size = System::Drawing::Size(484, 512); this->panel13->TabIndex = 13; // // btnListo // this->btnListo->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"btnListo.BackgroundImage"))); this->btnListo->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->btnListo->Enabled = false; this->btnListo->Location = System::Drawing::Point(59, 200); this->btnListo->Name = L"btnListo"; this->btnListo->Size = System::Drawing::Size(398, 147); this->btnListo->TabIndex = 1; this->btnListo->TabStop = false; this->btnListo->Visible = false; this->btnListo->Click += gcnew System::EventHandler(this, &Act2DosBI::btnListo_Click); this->btnListo->MouseLeave += gcnew System::EventHandler(this, &Act2DosBI::btnListo_MouseLeave); this->btnListo->MouseHover += gcnew System::EventHandler(this, &Act2DosBI::btnListo_MouseHover); // // btnVolver // this->btnVolver->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"btnVolver.BackgroundImage"))); this->btnVolver->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->btnVolver->Location = System::Drawing::Point(23, 51); this->btnVolver->Name = L"btnVolver"; this->btnVolver->Size = System::Drawing::Size(422, 155); this->btnVolver->TabIndex = 0; this->btnVolver->TabStop = false; this->btnVolver->Click += gcnew System::EventHandler(this, &Act2DosBI::btnVolver_Click); this->btnVolver->MouseLeave += gcnew System::EventHandler(this, &Act2DosBI::btnVolver_MouseLeave); this->btnVolver->MouseHover += gcnew System::EventHandler(this, &Act2DosBI::btnVolver_MouseHover); // // panel2 // this->panel2->BackColor = System::Drawing::Color::Transparent; this->panel2->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"panel2.BackgroundImage"))); this->panel2->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->panel2->Controls->Add(this->btnCuatro); this->panel2->Controls->Add(this->btnTres); this->panel2->Controls->Add(this->btnDos); this->panel2->Controls->Add(this->btnUno); this->panel2->Controls->Add(this->panelTres3); this->panel2->Controls->Add(this->panelDos3); this->panel2->Controls->Add(this->panelTres2); this->panel2->Controls->Add(this->panelUno3); this->panel2->Controls->Add(this->panelTres1); this->panel2->Controls->Add(this->panelDos2); this->panel2->Controls->Add(this->panelDos1); this->panel2->Controls->Add(this->panelUno2); this->panel2->Controls->Add(this->panelUno1); this->panel2->Controls->Add(this->label4); this->panel2->Controls->Add(this->label3); this->panel2->Controls->Add(this->label2); this->panel2->Location = System::Drawing::Point(505, 110); this->panel2->Name = L"panel2"; this->panel2->Size = System::Drawing::Size(1916, 1142); this->panel2->TabIndex = 12; // // btnCuatro // this->btnCuatro->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"btnCuatro.BackgroundImage"))); this->btnCuatro->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->btnCuatro->FlatAppearance->BorderSize = 0; this->btnCuatro->Location = System::Drawing::Point(469, 695); this->btnCuatro->Name = L"btnCuatro"; this->btnCuatro->Size = System::Drawing::Size(293, 222); this->btnCuatro->TabIndex = 3; this->btnCuatro->UseVisualStyleBackColor = true; this->btnCuatro->MouseDown += gcnew System::Windows::Forms::MouseEventHandler(this, &Act2DosBI::btnCuatro_MouseDown); this->btnCuatro->MouseMove += gcnew System::Windows::Forms::MouseEventHandler(this, &Act2DosBI::btnCuatro_MouseMove); this->btnCuatro->MouseUp += gcnew System::Windows::Forms::MouseEventHandler(this, &Act2DosBI::btnCuatro_MouseUp); // // btnTres // this->btnTres->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"btnTres.BackgroundImage"))); this->btnTres->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->btnTres->FlatAppearance->BorderSize = 0; this->btnTres->Location = System::Drawing::Point(152, 508); this->btnTres->Name = L"btnTres"; this->btnTres->Size = System::Drawing::Size(293, 222); this->btnTres->TabIndex = 2; this->btnTres->UseVisualStyleBackColor = true; this->btnTres->MouseDown += gcnew System::Windows::Forms::MouseEventHandler(this, &Act2DosBI::btnTres_MouseDown); this->btnTres->MouseMove += gcnew System::Windows::Forms::MouseEventHandler(this, &Act2DosBI::btnTres_MouseMove); this->btnTres->MouseUp += gcnew System::Windows::Forms::MouseEventHandler(this, &Act2DosBI::btnTres_MouseUp); // // btnDos // this->btnDos->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"btnDos.BackgroundImage"))); this->btnDos->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->btnDos->FlatAppearance->BorderSize = 0; this->btnDos->Location = System::Drawing::Point(469, 306); this->btnDos->Name = L"btnDos"; this->btnDos->Size = System::Drawing::Size(293, 222); this->btnDos->TabIndex = 1; this->btnDos->UseVisualStyleBackColor = true; this->btnDos->MouseDown += gcnew System::Windows::Forms::MouseEventHandler(this, &Act2DosBI::btnDos_MouseDown); this->btnDos->MouseMove += gcnew System::Windows::Forms::MouseEventHandler(this, &Act2DosBI::btnDos_MouseMove); this->btnDos->MouseUp += gcnew System::Windows::Forms::MouseEventHandler(this, &Act2DosBI::btnDos_MouseUp); // // btnUno // this->btnUno->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"btnUno.BackgroundImage"))); this->btnUno->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->btnUno->FlatAppearance->BorderSize = 0; this->btnUno->Location = System::Drawing::Point(152, 139); this->btnUno->Name = L"btnUno"; this->btnUno->Size = System::Drawing::Size(293, 222); this->btnUno->TabIndex = 0; this->btnUno->UseVisualStyleBackColor = true; this->btnUno->MouseDown += gcnew System::Windows::Forms::MouseEventHandler(this, &Act2DosBI::btnUno_MouseDown); this->btnUno->MouseMove += gcnew System::Windows::Forms::MouseEventHandler(this, &Act2DosBI::btnUno_MouseMove); this->btnUno->MouseUp += gcnew System::Windows::Forms::MouseEventHandler(this, &Act2DosBI::btnUno_MouseUp); // // panelTres3 // this->panelTres3->BackColor = System::Drawing::Color::Teal; this->panelTres3->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D; this->panelTres3->Location = System::Drawing::Point(1454, 727); this->panelTres3->Name = L"panelTres3"; this->panelTres3->Size = System::Drawing::Size(293, 222); this->panelTres3->TabIndex = 11; // // panelDos3 // this->panelDos3->BackColor = System::Drawing::Color::Teal; this->panelDos3->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D; this->panelDos3->Location = System::Drawing::Point(1454, 489); this->panelDos3->Name = L"panelDos3"; this->panelDos3->Size = System::Drawing::Size(293, 222); this->panelDos3->TabIndex = 11; // // panelTres2 // this->panelTres2->BackColor = System::Drawing::Color::OliveDrab; this->panelTres2->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D; this->panelTres2->Location = System::Drawing::Point(1148, 727); this->panelTres2->Name = L"panelTres2"; this->panelTres2->Size = System::Drawing::Size(293, 222); this->panelTres2->TabIndex = 10; // // panelUno3 // this->panelUno3->BackColor = System::Drawing::Color::Teal; this->panelUno3->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D; this->panelUno3->Location = System::Drawing::Point(1454, 250); this->panelUno3->Name = L"panelUno3"; this->panelUno3->Size = System::Drawing::Size(293, 222); this->panelUno3->TabIndex = 8; // // panelTres1 // this->panelTres1->BackColor = System::Drawing::Color::DarkOrange; this->panelTres1->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D; this->panelTres1->Location = System::Drawing::Point(842, 727); this->panelTres1->Name = L"panelTres1"; this->panelTres1->Size = System::Drawing::Size(293, 222); this->panelTres1->TabIndex = 9; // // panelDos2 // this->panelDos2->BackColor = System::Drawing::Color::OliveDrab; this->panelDos2->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D; this->panelDos2->Location = System::Drawing::Point(1148, 489); this->panelDos2->Name = L"panelDos2"; this->panelDos2->Size = System::Drawing::Size(293, 222); this->panelDos2->TabIndex = 10; // // panelDos1 // this->panelDos1->BackColor = System::Drawing::Color::DarkOrange; this->panelDos1->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D; this->panelDos1->Location = System::Drawing::Point(842, 489); this->panelDos1->Name = L"panelDos1"; this->panelDos1->Size = System::Drawing::Size(293, 222); this->panelDos1->TabIndex = 9; // // panelUno2 // this->panelUno2->BackColor = System::Drawing::Color::OliveDrab; this->panelUno2->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D; this->panelUno2->Location = System::Drawing::Point(1148, 250); this->panelUno2->Name = L"panelUno2"; this->panelUno2->Size = System::Drawing::Size(293, 222); this->panelUno2->TabIndex = 8; // // panelUno1 // this->panelUno1->BackColor = System::Drawing::Color::DarkOrange; this->panelUno1->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D; this->panelUno1->Location = System::Drawing::Point(842, 250); this->panelUno1->Name = L"panelUno1"; this->panelUno1->Size = System::Drawing::Size(293, 222); this->panelUno1->TabIndex = 7; // // label4 // this->label4->AutoSize = true; this->label4->Font = (gcnew System::Drawing::Font(L"Consolas", 36, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label4->ForeColor = System::Drawing::Color::Teal; this->label4->Location = System::Drawing::Point(1546, 121); this->label4->Name = L"label4"; this->label4->Size = System::Drawing::Size(112, 126); this->label4->TabIndex = 6; this->label4->Text = L"S"; // // label3 // this->label3->AutoSize = true; this->label3->Font = (gcnew System::Drawing::Font(L"Consolas", 36, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label3->ForeColor = System::Drawing::Color::OliveDrab; this->label3->Location = System::Drawing::Point(1247, 121); this->label3->Name = L"label3"; this->label3->Size = System::Drawing::Size(112, 126); this->label3->TabIndex = 5; this->label3->Text = L"P"; // // label2 // this->label2->AutoSize = true; this->label2->Font = (gcnew System::Drawing::Font(L"Consolas", 36, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label2->ForeColor = System::Drawing::Color::DarkOrange; this->label2->Location = System::Drawing::Point(943, 121); this->label2->Name = L"label2"; this->label2->Size = System::Drawing::Size(112, 126); this->label2->TabIndex = 4; this->label2->Text = L"M"; // // btnAyuda // this->btnAyuda->BackColor = System::Drawing::Color::Transparent; this->btnAyuda->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"btnAyuda.BackgroundImage"))); this->btnAyuda->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->btnAyuda->Location = System::Drawing::Point(14, 13); this->btnAyuda->Name = L"btnAyuda"; this->btnAyuda->Size = System::Drawing::Size(300, 270); this->btnAyuda->TabIndex = 8; this->btnAyuda->TabStop = false; this->btnAyuda->Click += gcnew System::EventHandler(this, &Act2DosBI::btnAyuda_Click); this->btnAyuda->MouseLeave += gcnew System::EventHandler(this, &Act2DosBI::btnAyuda_MouseLeave); this->btnAyuda->MouseHover += gcnew System::EventHandler(this, &Act2DosBI::btnAyuda_MouseHover); // // panel9 // this->panel9->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"panel9.BackgroundImage"))); this->panel9->Controls->Add(this->pictureBox7); this->panel9->Controls->Add(this->label6); this->panel9->Controls->Add(this->picMinimizar); this->panel9->Controls->Add(this->picCerrar); this->panel9->Dock = System::Windows::Forms::DockStyle::Top; this->panel9->Location = System::Drawing::Point(0, 0); this->panel9->Name = L"panel9"; this->panel9->Size = System::Drawing::Size(2450, 70); this->panel9->TabIndex = 3; // // pictureBox7 // this->pictureBox7->BackColor = System::Drawing::Color::Transparent; this->pictureBox7->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"pictureBox7.BackgroundImage"))); this->pictureBox7->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->pictureBox7->Location = System::Drawing::Point(12, 4); this->pictureBox7->Name = L"pictureBox7"; this->pictureBox7->Size = System::Drawing::Size(72, 63); this->pictureBox7->TabIndex = 33; this->pictureBox7->TabStop = false; // // label6 // this->label6->AutoSize = true; this->label6->BackColor = System::Drawing::Color::Transparent; this->label6->Font = (gcnew System::Drawing::Font(L"Lucida Sans", 16, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label6->ForeColor = System::Drawing::Color::White; this->label6->Location = System::Drawing::Point(81, 7); this->label6->Name = L"label6"; this->label6->Size = System::Drawing::Size(212, 55); this->label6->TabIndex = 32; this->label6->Text = L"TUTINT"; // // picMinimizar // this->picMinimizar->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right)); this->picMinimizar->BackColor = System::Drawing::Color::Transparent; this->picMinimizar->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"picMinimizar.BackgroundImage"))); this->picMinimizar->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->picMinimizar->Location = System::Drawing::Point(2300, 5); this->picMinimizar->Name = L"picMinimizar"; this->picMinimizar->Size = System::Drawing::Size(64, 59); this->picMinimizar->TabIndex = 31; this->picMinimizar->TabStop = false; this->picMinimizar->Click += gcnew System::EventHandler(this, &Act2DosBI::picMinimizar_Click); // // picCerrar // this->picCerrar->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right)); this->picCerrar->BackColor = System::Drawing::Color::Transparent; this->picCerrar->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"picCerrar.BackgroundImage"))); this->picCerrar->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->picCerrar->Location = System::Drawing::Point(2375, 5); this->picCerrar->Name = L"picCerrar"; this->picCerrar->Size = System::Drawing::Size(64, 59); this->picCerrar->TabIndex = 30; this->picCerrar->TabStop = false; this->picCerrar->Click += gcnew System::EventHandler(this, &Act2DosBI::picCerrar_Click); // // timer1 // this->timer1->Interval = 1; this->timer1->Tick += gcnew System::EventHandler(this, &Act2DosBI::timer1_Tick); // // panel1 // this->panel1->BackColor = System::Drawing::Color::Transparent; this->panel1->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"panel1.BackgroundImage"))); this->panel1->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->panel1->Controls->Add(this->instruccion1); this->panel1->Controls->Add(this->instruccion2); this->panel1->Location = System::Drawing::Point(316, 3); this->panel1->Name = L"panel1"; this->panel1->Size = System::Drawing::Size(2115, 97); this->panel1->TabIndex = 17; // // instruccion1 // this->instruccion1->AutoSize = true; this->instruccion1->Font = (gcnew System::Drawing::Font(L"Comic Sans MS", 16.125F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->instruccion1->ForeColor = System::Drawing::SystemColors::ButtonHighlight; this->instruccion1->Location = System::Drawing::Point(109, 12); this->instruccion1->Name = L"instruccion1"; this->instruccion1->Size = System::Drawing::Size(1902, 68); this->instruccion1->TabIndex = 14; this->instruccion1->Text = L"¿Con qué letra inicia la imágen\? Muévela al cuadro de la letra que corresponde"; // // instruccion2 // this->instruccion2->AutoSize = true; this->instruccion2->Font = (gcnew System::Drawing::Font(L"Comic Sans MS", 16.125F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->instruccion2->ForeColor = System::Drawing::SystemColors::ButtonHighlight; this->instruccion2->Location = System::Drawing::Point(107, 9); this->instruccion2->Name = L"instruccion2"; this->instruccion2->Size = System::Drawing::Size(1555, 68); this->instruccion2->TabIndex = 13; this->instruccion2->Text = L"Arrastra la imagen a la letra con que inicia, según corresponda."; this->instruccion2->Visible = false; // // Act2DosBI // this->AutoScaleDimensions = System::Drawing::SizeF(14, 29); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(2450, 1334); this->Controls->Add(this->panelPrincipal); this->Controls->Add(this->panel9); this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::None; this->Icon = (cli::safe_cast<System::Drawing::Icon^>(resources->GetObject(L"$this.Icon"))); this->Name = L"Act2DosBI"; this->Opacity = 0; this->StartPosition = System::Windows::Forms::FormStartPosition::CenterScreen; this->Text = L"Act2DosBI"; this->Activated += gcnew System::EventHandler(this, &Act2DosBI::Act2DosBI_Activated); this->Deactivate += gcnew System::EventHandler(this, &Act2DosBI::Act2DosBI_Deactivate); this->Load += gcnew System::EventHandler(this, &Act2DosBI::Act2DosBI_Load); this->panelPrincipal->ResumeLayout(false); this->panel13->ResumeLayout(false); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->btnListo))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->btnVolver))->EndInit(); this->panel2->ResumeLayout(false); this->panel2->PerformLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->btnAyuda))->EndInit(); this->panel9->ResumeLayout(false); this->panel9->PerformLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox7))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->picMinimizar))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->picCerrar))->EndInit(); this->panel1->ResumeLayout(false); this->panel1->PerformLayout(); this->ResumeLayout(false); } #pragma endregion private: void inicializarTam(); private: void inicializarPosiciones(); private: void comprobarRespuestas(); private: void sonidoInicial(); private: System::Void btnAyuda_Click(System::Object^ sender, System::EventArgs^ e); private: System::Void btnVolver_Click(System::Object^ sender, System::EventArgs^ e); private: System::Void btnListo_Click(System::Object^ sender, System::EventArgs^ e); private: System::Void btnVolver_MouseHover(System::Object^ sender, System::EventArgs^ e); private: System::Void btnVolver_MouseLeave(System::Object^ sender, System::EventArgs^ e); private: System::Void btnListo_MouseHover(System::Object^ sender, System::EventArgs^ e); private: System::Void btnListo_MouseLeave(System::Object^ sender, System::EventArgs^ e); private: System::Void btnAyuda_MouseHover(System::Object^ sender, System::EventArgs^ e); private: System::Void btnAyuda_MouseLeave(System::Object^ sender, System::EventArgs^ e); private: System::Void picCerrar_Click(System::Object^ sender, System::EventArgs^ e); private: System::Void picMinimizar_Click(System::Object^ sender, System::EventArgs^ e); private: System::Void Act2DosBI_Load(System::Object^ sender, System::EventArgs^ e); private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e); private: System::Void Act2DosBI_Activated(System::Object^ sender, System::EventArgs^ e); private: System::Void Act2DosBI_Deactivate(System::Object^ sender, System::EventArgs^ e); private: System::Void tiempo_respuesta(int numItem, TiempoGUI^ tr_item, bool listoBtn); private: vector<TiempoMI*> obtenerTiempoItems(); private: System::Void moverBoton(System::Windows::Forms::Button^ boton); private: System::Void btnUno_MouseDown(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e); private: System::Void btnDos_MouseDown(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e); private: System::Void btnTres_MouseDown(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e); private: System::Void btnCuatro_MouseDown(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e); private: System::Void btnUno_MouseUp(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e); private: System::Void btnDos_MouseUp(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e); private: System::Void btnTres_MouseUp(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e); private: System::Void btnCuatro_MouseUp(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e); private: System::Void btnUno_MouseMove(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e); private: System::Void btnDos_MouseMove(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e); private: System::Void btnTres_MouseMove(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e); private: System::Void btnCuatro_MouseMove(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e); }; }
[ "felipe.segovia.rod@outlook.com" ]
felipe.segovia.rod@outlook.com
db63a5de55386dfc18dc873daa6cab98dfd6fa1d
4bf98ef4b80d7029eab3873cdf0b09e44d79abac
/include/api/segmenter/segmenter_cimg.hpp
eab354f7b492e86d37052fccef84e2e9f17f8e5a
[]
no_license
cy20lin/2018_fall_image_processing_final_api_segmenter
8899bea3779f5cd4bb52ea2eabd4d988102f2be4
7e727a45d123ba908ad7b42feb1c201dbda6d823
refs/heads/master
2020-04-12T20:52:12.228571
2018-12-27T08:02:43
2018-12-27T08:03:13
162,749,064
0
1
null
null
null
null
UTF-8
C++
false
false
3,950
hpp
#ifndef FINAL_MODULE_SEGMENTER_INCLUDE_API_SEGMENTER_SEGMENTER_CIMG_HPP_INCLUDED #define FINAL_MODULE_SEGMENTER_INCLUDE_API_SEGMENTER_SEGMENTER_CIMG_HPP_INCLUDED #include "core.hpp" #include <exception> // #include "cv_cimg_bridge.hpp" // #include "cv_bridge.hpp" #include "cimg_bridge.hpp" // #include <opencv/cv.h> namespace api { namespace segmenter { class segmenter_cimg { public: segmenter_cimg() = default; segmenter_cimg(segmenter_cimg const &) = default; segmenter_cimg(segmenter_cimg &&) = default; ~segmenter_cimg() = default; std_image_type segment(const std_image_type & source, std_keypoints_type keypoints) { using namespace ::cimg_library; if (std::get<0>(source).first <= 0 || std::get<0>(source).second <=0) { throw std::invalid_argument("invalid source-image size"); } const CImg<std::uint8_t> image(std_image_to_cimg(source)); // const CImg<std::uint8_t> image(std_image_to_cv_mat(source)); // const CImg<std::uint8_t> image(cv::imread("../dataset/4.jpeg")); // cv::imshow("image", image.get_MAT()); // cv::Mat label_mask = cv::imread("../dataset/kp4.png"); // cv::Mat label(cv::Size(label_mask.col, label_mask.row)); // Load input label image. CImg<std::uint8_t> labels(image.width(),image.height(),1,1,0); int xn = image.width(); int yn = image.height(); int x; int y; int label = 0; for (const auto & layer : keypoints) { ++label; for (const auto & pt : layer) { x = pt.first; y = pt.second; if (x < 0 || x >= xn || y < 0 || y >= yn) { throw std::invalid_argument(std::string("keypoint (") + std::to_string(x) + "," + std::to_string(y) + ") out of range size=(" + std::to_string(xn) + "," + std::to_string(yn) + ")"); } labels(x,y,0) = label; // labels(x,y,1) = label; // labels(x,y,2) = label; } } labels.resize(image.width(),image.height(),1,1,0); // Be sure labels has the correct size. // labels.resize(image.width(),image.height(),1,1,0); // Be sure labels has the correct size. // Compute gradients. const float sigma = 0.002f * std::max(image.width(),image.height()); const CImg<std::uint8_t> blurred = image.get_blur(sigma); CImgList<std::uint8_t> gradient = blurred.get_gradient("xy"); // gradient[0] and gradient[1] are two CImg<std::uint8_t> images which contain // respectively the X and Y derivatives of the blurred RGB image. // Compute the potential map P. CImg<float> P(labels); cimg_forXY(P,x,y){ P(x,y) = 1./(1. + cimg::sqr(gradient(0,x,y,0)) + // Rx^2 cimg::sqr(gradient(0,x,y,1)) + // Gx^2 cimg::sqr(gradient(0,x,y,2)) + // Bx^2 cimg::sqr(gradient(1,x,y,0)) + // Ry^2 cimg::sqr(gradient(1,x,y,1)) + // Gy^2 cimg::sqr(gradient(1,x,y,2))); // By^2 } // Run the label propagation algorithm. labels.watershed(P, true); cimg_forXY(labels,x,y){ auto label = labels(x,y); enum { foreground = 1}; labels(x,y) = (label != 2) ? 255 : 0; } // CImg<std::uint8_t> P2(P); // cimg_forXY(P,x,y){ // P2(x,y) = P(x,y)*255; // } // cv::imshow("p", P2.get_MAT()); // cv::imshow("gx", gradient.at(0).get_MAT()); // cv::imshow("gy", gradient.at(1).get_MAT()); return cimg_to_std_image(labels); } }; } // namespace segmenter } // namespace api #endif // FINAL_MODULE_SEGMENTER_INCLUDE_API_SEGMENTER_SEGMENTER_CIMG_HPP_INCLUDED
[ "cy20lin@gmail.com" ]
cy20lin@gmail.com
7dd405f94de1491bbfcf3131eca527d4d7972a1e
42b38ab2e841846d9b63d6dacf1a4227be117308
/Krkr/XP3Viewer-121113/krkr2/tjs2/tjs.tab.h
13ec86cdb4460b29ce3b7bc0aabded71e8bcc585
[]
no_license
Inori/FuckGalEngine
0905a9a2ad17db186a445dd7c938c4730b76fc2c
c966c2bf82975d078beb3b9c0b53f7390d3618d9
refs/heads/master
2023-07-29T00:33:53.672955
2022-02-06T01:52:40
2022-02-06T01:52:40
17,017,253
706
186
null
2022-02-06T01:52:41
2014-02-20T10:49:38
C
UTF-8
C++
false
false
7,997
h
namespace TJS { /* A Bison parser, made by GNU Bison 2.3. */ /* Skeleton interface for Bison's Yacc-like parsers in C Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. 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, 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 02110-1301, USA. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { T_COMMA = 258, T_EQUAL = 259, T_AMPERSANDEQUAL = 260, T_VERTLINEEQUAL = 261, T_CHEVRONEQUAL = 262, T_MINUSEQUAL = 263, T_PLUSEQUAL = 264, T_PERCENTEQUAL = 265, T_SLASHEQUAL = 266, T_BACKSLASHEQUAL = 267, T_ASTERISKEQUAL = 268, T_LOGICALOREQUAL = 269, T_LOGICALANDEQUAL = 270, T_RARITHSHIFTEQUAL = 271, T_LARITHSHIFTEQUAL = 272, T_RBITSHIFTEQUAL = 273, T_QUESTION = 274, T_LOGICALOR = 275, T_LOGICALAND = 276, T_VERTLINE = 277, T_CHEVRON = 278, T_AMPERSAND = 279, T_NOTEQUAL = 280, T_EQUALEQUAL = 281, T_DISCNOTEQUAL = 282, T_DISCEQUAL = 283, T_SWAP = 284, T_LT = 285, T_GT = 286, T_LTOREQUAL = 287, T_GTOREQUAL = 288, T_RARITHSHIFT = 289, T_LARITHSHIFT = 290, T_RBITSHIFT = 291, T_PERCENT = 292, T_SLASH = 293, T_BACKSLASH = 294, T_ASTERISK = 295, T_EXCRAMATION = 296, T_TILDE = 297, T_DECREMENT = 298, T_INCREMENT = 299, T_NEW = 300, T_DELETE = 301, T_TYPEOF = 302, T_PLUS = 303, T_MINUS = 304, T_SHARP = 305, T_DOLLAR = 306, T_ISVALID = 307, T_INVALIDATE = 308, T_INSTANCEOF = 309, T_LPARENTHESIS = 310, T_DOT = 311, T_LBRACKET = 312, T_THIS = 313, T_SUPER = 314, T_GLOBAL = 315, T_RBRACKET = 316, T_CLASS = 317, T_RPARENTHESIS = 318, T_COLON = 319, T_SEMICOLON = 320, T_LBRACE = 321, T_RBRACE = 322, T_CONTINUE = 323, T_FUNCTION = 324, T_DEBUGGER = 325, T_DEFAULT = 326, T_CASE = 327, T_EXTENDS = 328, T_FINALLY = 329, T_PROPERTY = 330, T_PRIVATE = 331, T_PUBLIC = 332, T_PROTECTED = 333, T_STATIC = 334, T_RETURN = 335, T_BREAK = 336, T_EXPORT = 337, T_IMPORT = 338, T_SWITCH = 339, T_IN = 340, T_INCONTEXTOF = 341, T_FOR = 342, T_WHILE = 343, T_DO = 344, T_IF = 345, T_VAR = 346, T_CONST = 347, T_ENUM = 348, T_GOTO = 349, T_THROW = 350, T_TRY = 351, T_SETTER = 352, T_GETTER = 353, T_ELSE = 354, T_CATCH = 355, T_OMIT = 356, T_SYNCHRONIZED = 357, T_WITH = 358, T_INT = 359, T_REAL = 360, T_STRING = 361, T_OCTET = 362, T_FALSE = 363, T_NULL = 364, T_TRUE = 365, T_VOID = 366, T_NAN = 367, T_INFINITY = 368, T_UPLUS = 369, T_UMINUS = 370, T_EVAL = 371, T_POSTDECREMENT = 372, T_POSTINCREMENT = 373, T_IGNOREPROP = 374, T_PROPACCESS = 375, T_ARG = 376, T_EXPANDARG = 377, T_INLINEARRAY = 378, T_ARRAYARG = 379, T_INLINEDIC = 380, T_DICELM = 381, T_WITHDOT = 382, T_THIS_PROXY = 383, T_WITHDOT_PROXY = 384, T_CONSTVAL = 385, T_SYMBOL = 386, T_REGEXP = 387 }; #endif /* Tokens. */ #define T_COMMA 258 #define T_EQUAL 259 #define T_AMPERSANDEQUAL 260 #define T_VERTLINEEQUAL 261 #define T_CHEVRONEQUAL 262 #define T_MINUSEQUAL 263 #define T_PLUSEQUAL 264 #define T_PERCENTEQUAL 265 #define T_SLASHEQUAL 266 #define T_BACKSLASHEQUAL 267 #define T_ASTERISKEQUAL 268 #define T_LOGICALOREQUAL 269 #define T_LOGICALANDEQUAL 270 #define T_RARITHSHIFTEQUAL 271 #define T_LARITHSHIFTEQUAL 272 #define T_RBITSHIFTEQUAL 273 #define T_QUESTION 274 #define T_LOGICALOR 275 #define T_LOGICALAND 276 #define T_VERTLINE 277 #define T_CHEVRON 278 #define T_AMPERSAND 279 #define T_NOTEQUAL 280 #define T_EQUALEQUAL 281 #define T_DISCNOTEQUAL 282 #define T_DISCEQUAL 283 #define T_SWAP 284 #define T_LT 285 #define T_GT 286 #define T_LTOREQUAL 287 #define T_GTOREQUAL 288 #define T_RARITHSHIFT 289 #define T_LARITHSHIFT 290 #define T_RBITSHIFT 291 #define T_PERCENT 292 #define T_SLASH 293 #define T_BACKSLASH 294 #define T_ASTERISK 295 #define T_EXCRAMATION 296 #define T_TILDE 297 #define T_DECREMENT 298 #define T_INCREMENT 299 #define T_NEW 300 #define T_DELETE 301 #define T_TYPEOF 302 #define T_PLUS 303 #define T_MINUS 304 #define T_SHARP 305 #define T_DOLLAR 306 #define T_ISVALID 307 #define T_INVALIDATE 308 #define T_INSTANCEOF 309 #define T_LPARENTHESIS 310 #define T_DOT 311 #define T_LBRACKET 312 #define T_THIS 313 #define T_SUPER 314 #define T_GLOBAL 315 #define T_RBRACKET 316 #define T_CLASS 317 #define T_RPARENTHESIS 318 #define T_COLON 319 #define T_SEMICOLON 320 #define T_LBRACE 321 #define T_RBRACE 322 #define T_CONTINUE 323 #define T_FUNCTION 324 #define T_DEBUGGER 325 #define T_DEFAULT 326 #define T_CASE 327 #define T_EXTENDS 328 #define T_FINALLY 329 #define T_PROPERTY 330 #define T_PRIVATE 331 #define T_PUBLIC 332 #define T_PROTECTED 333 #define T_STATIC 334 #define T_RETURN 335 #define T_BREAK 336 #define T_EXPORT 337 #define T_IMPORT 338 #define T_SWITCH 339 #define T_IN 340 #define T_INCONTEXTOF 341 #define T_FOR 342 #define T_WHILE 343 #define T_DO 344 #define T_IF 345 #define T_VAR 346 #define T_CONST 347 #define T_ENUM 348 #define T_GOTO 349 #define T_THROW 350 #define T_TRY 351 #define T_SETTER 352 #define T_GETTER 353 #define T_ELSE 354 #define T_CATCH 355 #define T_OMIT 356 #define T_SYNCHRONIZED 357 #define T_WITH 358 #define T_INT 359 #define T_REAL 360 #define T_STRING 361 #define T_OCTET 362 #define T_FALSE 363 #define T_NULL 364 #define T_TRUE 365 #define T_VOID 366 #define T_NAN 367 #define T_INFINITY 368 #define T_UPLUS 369 #define T_UMINUS 370 #define T_EVAL 371 #define T_POSTDECREMENT 372 #define T_POSTINCREMENT 373 #define T_IGNOREPROP 374 #define T_PROPACCESS 375 #define T_ARG 376 #define T_EXPANDARG 377 #define T_INLINEARRAY 378 #define T_ARRAYARG 379 #define T_INLINEDIC 380 #define T_DICELM 381 #define T_WITHDOT 382 #define T_THIS_PROXY 383 #define T_WITHDOT_PROXY 384 #define T_CONSTVAL 385 #define T_SYMBOL 386 #define T_REGEXP 387 #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE #line 60 "tjs.y" { tjs_int num; tTJSExprNode * np; } /* Line 1489 of yacc.c. */ #line 318 "tjs.tab.h" YYSTYPE; # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 # define YYSTYPE_IS_TRIVIAL 1 #endif }
[ "811197881@qq.com" ]
811197881@qq.com
b054b91fec32f20447d5f82b98b91b9d9f4edbcc
653afab7f94dfb44c3cf857e845e82ca87214eeb
/src/CryptoFilter.h
44dfdbc9d87179f9b31e2499313d478aa3896922
[ "BSD-2-Clause" ]
permissive
Helios-vmg/zekvok
e98c4f5397e635553ad53c8ff1dba662b93ed799
b90ec897af2bdb55764f9de00d5a1f38f80fe70f
refs/heads/master
2021-01-21T04:33:02.594608
2015-10-31T23:37:29
2015-10-31T23:37:29
43,264,987
1
0
null
null
null
null
UTF-8
C++
false
false
1,375
h
/* Copyright (c), Helios All rights reserved. Distributed under a permissive license. See COPYING.txt for details. */ #pragma once #include "Filters.h" enum class Algorithm{ Rijndael, Twofish, Serpent, }; class CryptoOutputFilter : public OutputFilter{ protected: bool flushed; virtual std::uint8_t *get_buffer(size_t &size) = 0; virtual CryptoPP::StreamTransformationFilter *get_filter() = 0; CryptoOutputFilter(std::ostream &stream): OutputFilter(stream), flushed(false){} bool internal_flush() override; public: virtual ~CryptoOutputFilter(){} static std::shared_ptr<std::ostream> create( Algorithm algo, std::ostream &stream, const CryptoPP::SecByteBlock *key, const CryptoPP::SecByteBlock *iv ); std::streamsize write(const char *s, std::streamsize n) override; }; class CryptoInputFilter : public InputFilter{ bool done; protected: virtual std::uint8_t *get_buffer(size_t &size) = 0; virtual CryptoPP::StreamTransformationFilter *get_filter() = 0; CryptoInputFilter(std::istream &stream): InputFilter(stream), done(false){} public: virtual ~CryptoInputFilter(){} static std::shared_ptr<std::istream> create( Algorithm algo, std::istream &stream, const CryptoPP::SecByteBlock *key, const CryptoPP::SecByteBlock *iv ); std::streamsize read(char *s, std::streamsize n); };
[ "helios.vmg@gmail.com" ]
helios.vmg@gmail.com
2328ffd6676b8dc4c55c782f3de9930307146b05
a1135c0745cf2210d547af55a9bb732818cd4216
/src/cpp/omicron/api/context/__context.hpp
c78a939eeb95c89d40859a6b0118a30a1ecb8371
[]
no_license
DavidSaxon/Omicron
bb8138ed55af8769a757c2493d66174dbd7e80b7
88adf810740f6728deb02ebeeb3808bb4a5f1ed2
refs/heads/master
2020-04-05T22:58:10.105260
2018-01-17T09:57:20
2018-01-17T09:57:20
68,196,461
0
0
null
null
null
null
UTF-8
C++
false
false
368
hpp
/*! * \file * \brief Documents the omi::context namespace. * \author David Saxon */ #ifndef OMICRON_API_CONTEXT_HPP_ #define OMICRON_API_CONTEXT_HPP_ namespace omi { /*! * \brief Module for providing and managing the context in which Omicron is * running. */ namespace context { } // namespace context } // namespace omi #endif
[ "davidesaxon@gmail.com" ]
davidesaxon@gmail.com
239d429cf3c180997a43501a9240f56ebcaaec57
eb583dfc1709950c4f61244d0f0e7666c09e0d8e
/Reverse pair.cpp
9b166200298b4197b7b11e95439e8531016384e7
[]
no_license
tanyasri02/Maths-for-Interview
54005bb581d7536e0ab401c01758eb8444699b38
893650b554490352c7420ca959627eff5b939f72
refs/heads/main
2023-06-26T20:44:59.092739
2021-07-30T05:02:36
2021-07-30T05:02:36
390,594,728
1
0
null
null
null
null
UTF-8
C++
false
false
1,243
cpp
class Solution { public: int merge(vector<int>&nums,int low,int mid,int high) { int count=0; int j=mid+1; for(int i=low;i<=mid;i++) { while(j<=high && nums[i]>nums[j]*2LL) { j++; } count+=(j-(mid+1)); } vector<int>temp; int left=low,right=mid+1; while(left<=mid && right<=high) { if(nums[left]<=nums[right]) temp.push_back(nums[left++]); else temp.push_back(nums[right++]); } while(left<=mid) temp.push_back(nums[left++]); while(right<=high) temp.push_back(nums[right++]); for(int i=low;i<=high;i++) nums[i]=temp[i-low]; return count; } int mergesort(vector<int>& nums,int low, int high) { if(low==high) return 0; int mid=(low+high)/2; int ans=mergesort(nums,low,mid); ans+=mergesort(nums,mid+1,high); ans+=merge(nums,low,mid,high); return ans; } int reversePairs(vector<int>& nums) { return mergesort(nums,0,nums.size()-1); } };
[ "noreply@github.com" ]
tanyasri02.noreply@github.com
852e97c4d3ed73246ce22c3d1c4a0134b301d908
d98404868eafa300b07fc90f98e14890bdf148a4
/preMacro.cpp
a23b0464df793ff753751df7e8182637212fb5f7
[]
no_license
eltroneur/newbeeCpp
4f4974727b33fd9fa64fd334c46775c237943506
d9a8f77b7c9d5e7b8eb2623315d7713ce28c4bea
refs/heads/master
2022-02-10T22:10:37.758263
2022-01-27T09:58:18
2022-01-27T09:58:18
182,321,626
0
0
null
null
null
null
UTF-8
C++
false
false
336
cpp
// preMacro.cpp -- using pre-defined MACRO #include <iostream> int main() { std::cout << "Current line is " << __LINE__ << std::endl; std::cout << "Current filename is " << __FILE__ << std::endl; std::cout << "Current date is " << __DATE__ << std::endl; std::cout << "Current time is " << __TIME__ << std::endl; return 0; }
[ "cherishdevice@163.com" ]
cherishdevice@163.com
d4e3eb0742a8c144eea7cae9c4f894fa18c32639
24e95324f159c58077637c6deaae8073e8052837
/share_tuning/shared_tools/clientMsg&structAnalysis/Analysis/CRange.h
a5bcb591c86632b3a85c5776882028878de09bb0
[]
no_license
jgyh1987/eagle_server
21ff627ef5c9bc0b961f16114c4c0dfce92c9c57
341ea9649b6ddac82fe6ab89a5cb4df044df7443
refs/heads/master
2022-10-07T11:35:18.559726
2020-06-08T11:06:59
2020-06-08T11:06:59
270,552,049
1
2
null
null
null
null
GB18030
C++
false
false
45,682
h
// 从类型库向导中用“添加类”创建的计算机生成的 IDispatch 包装类 //#import "D:\\Office\\Office14\\EXCEL.EXE" no_namespace // CRange 包装类 class CRange : public COleDispatchDriver { public: CRange(){} // 调用 COleDispatchDriver 默认构造函数 CRange(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} CRange(const CRange& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} // 特性 public: // 操作 public: // Range 方法 public: LPDISPATCH get_Application() { LPDISPATCH result; InvokeHelper(0x94, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } long get_Creator() { long result; InvokeHelper(0x95, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } LPDISPATCH get_Parent() { LPDISPATCH result; InvokeHelper(0x96, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } VARIANT Activate() { VARIANT result; InvokeHelper(0x130, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT get_AddIndent() { VARIANT result; InvokeHelper(0x427, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_AddIndent(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x427, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } CString get_Address(VARIANT& RowAbsolute, VARIANT& ColumnAbsolute, long ReferenceStyle, VARIANT& External, VARIANT& RelativeTo) { CString result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT VTS_I4 VTS_VARIANT VTS_VARIANT ; InvokeHelper(0xec, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, parms, &RowAbsolute, &ColumnAbsolute, ReferenceStyle, &External, &RelativeTo); return result; } CString get_AddressLocal(VARIANT& RowAbsolute, VARIANT& ColumnAbsolute, long ReferenceStyle, VARIANT& External, VARIANT& RelativeTo) { CString result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT VTS_I4 VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x1b5, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, parms, &RowAbsolute, &ColumnAbsolute, ReferenceStyle, &External, &RelativeTo); return result; } VARIANT AdvancedFilter(long Action, VARIANT& CriteriaRange, VARIANT& CopyToRange, VARIANT& Unique) { VARIANT result; static BYTE parms[] = VTS_I4 VTS_VARIANT VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x36c, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, Action, &CriteriaRange, &CopyToRange, &Unique); return result; } VARIANT ApplyNames(VARIANT& Names, VARIANT& IgnoreRelativeAbsolute, VARIANT& UseRowColumnNames, VARIANT& OmitColumn, VARIANT& OmitRow, long Order, VARIANT& AppendLast) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_I4 VTS_VARIANT ; InvokeHelper(0x1b9, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &Names, &IgnoreRelativeAbsolute, &UseRowColumnNames, &OmitColumn, &OmitRow, Order, &AppendLast); return result; } VARIANT ApplyOutlineStyles() { VARIANT result; InvokeHelper(0x1c0, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } LPDISPATCH get_Areas() { LPDISPATCH result; InvokeHelper(0x238, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } CString AutoComplete(LPCTSTR String) { CString result; static BYTE parms[] = VTS_BSTR ; InvokeHelper(0x4a1, DISPATCH_METHOD, VT_BSTR, (void*)&result, parms, String); return result; } VARIANT AutoFill(LPDISPATCH Destination, long Type) { VARIANT result; static BYTE parms[] = VTS_DISPATCH VTS_I4 ; InvokeHelper(0x1c1, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, Destination, Type); return result; } VARIANT AutoFilter(VARIANT& Field, VARIANT& Criteria1, long Operator, VARIANT& Criteria2, VARIANT& VisibleDropDown) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT VTS_I4 VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x319, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &Field, &Criteria1, Operator, &Criteria2, &VisibleDropDown); return result; } VARIANT AutoFit() { VARIANT result; InvokeHelper(0xed, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT AutoFormat(long Format, VARIANT& Number, VARIANT& Font, VARIANT& Alignment, VARIANT& Border, VARIANT& Pattern, VARIANT& Width) { VARIANT result; static BYTE parms[] = VTS_I4 VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x72, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, Format, &Number, &Font, &Alignment, &Border, &Pattern, &Width); return result; } VARIANT AutoOutline() { VARIANT result; InvokeHelper(0x40c, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT _BorderAround(VARIANT& LineStyle, long Weight, long ColorIndex, VARIANT& Color) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_I4 VTS_I4 VTS_VARIANT ; InvokeHelper(0x42b, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &LineStyle, Weight, ColorIndex, &Color); return result; } LPDISPATCH get_Borders() { LPDISPATCH result; InvokeHelper(0x1b3, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } VARIANT Calculate() { VARIANT result; InvokeHelper(0x117, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } LPDISPATCH get_Cells() { LPDISPATCH result; InvokeHelper(0xee, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } LPDISPATCH get_Characters(VARIANT& Start, VARIANT& Length) { LPDISPATCH result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x25b, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, parms, &Start, &Length); return result; } VARIANT CheckSpelling(VARIANT& CustomDictionary, VARIANT& IgnoreUppercase, VARIANT& AlwaysSuggest, VARIANT& SpellLang) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x1f9, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &CustomDictionary, &IgnoreUppercase, &AlwaysSuggest, &SpellLang); return result; } VARIANT Clear() { VARIANT result; InvokeHelper(0x6f, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT ClearContents() { VARIANT result; InvokeHelper(0x71, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT ClearFormats() { VARIANT result; InvokeHelper(0x70, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT ClearNotes() { VARIANT result; InvokeHelper(0xef, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT ClearOutline() { VARIANT result; InvokeHelper(0x40d, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } long get_Column() { long result; InvokeHelper(0xf0, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } LPDISPATCH ColumnDifferences(VARIANT& Comparison) { LPDISPATCH result; static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x1fe, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, &Comparison); return result; } LPDISPATCH get_Columns() { LPDISPATCH result; InvokeHelper(0xf1, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } VARIANT get_ColumnWidth() { VARIANT result; InvokeHelper(0xf2, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_ColumnWidth(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0xf2, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } VARIANT Consolidate(VARIANT& Sources, VARIANT& Function, VARIANT& TopRow, VARIANT& LeftColumn, VARIANT& CreateLinks) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x1e2, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &Sources, &Function, &TopRow, &LeftColumn, &CreateLinks); return result; } VARIANT Copy(VARIANT& Destination) { VARIANT result; static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x227, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &Destination); return result; } long CopyFromRecordset(LPUNKNOWN Data, VARIANT& MaxRows, VARIANT& MaxColumns) { long result; static BYTE parms[] = VTS_UNKNOWN VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x480, DISPATCH_METHOD, VT_I4, (void*)&result, parms, Data, &MaxRows, &MaxColumns); return result; } VARIANT CopyPicture(long Appearance, long Format) { VARIANT result; static BYTE parms[] = VTS_I4 VTS_I4 ; InvokeHelper(0xd5, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, Appearance, Format); return result; } long get_Count() { long result; InvokeHelper(0x76, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } VARIANT CreateNames(VARIANT& Top, VARIANT& Left, VARIANT& Bottom, VARIANT& Right) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x1c9, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &Top, &Left, &Bottom, &Right); return result; } VARIANT CreatePublisher(VARIANT& Edition, long Appearance, VARIANT& ContainsPICT, VARIANT& ContainsBIFF, VARIANT& ContainsRTF, VARIANT& ContainsVALU) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_I4 VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x1ca, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &Edition, Appearance, &ContainsPICT, &ContainsBIFF, &ContainsRTF, &ContainsVALU); return result; } LPDISPATCH get_CurrentArray() { LPDISPATCH result; InvokeHelper(0x1f5, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } LPDISPATCH get_CurrentRegion() { LPDISPATCH result; InvokeHelper(0xf3, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } VARIANT Cut(VARIANT& Destination) { VARIANT result; static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x235, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &Destination); return result; } VARIANT DataSeries(VARIANT& Rowcol, long Type, long Date, VARIANT& Step, VARIANT& Stop, VARIANT& Trend) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_I4 VTS_I4 VTS_VARIANT VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x1d0, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &Rowcol, Type, Date, &Step, &Stop, &Trend); return result; } VARIANT get__Default(VARIANT& RowIndex, VARIANT& ColumnIndex) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x0, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, parms, &RowIndex, &ColumnIndex); return result; } void put__Default(VARIANT& RowIndex, VARIANT& ColumnIndex, VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x0, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &RowIndex, &ColumnIndex, &newValue); } VARIANT Delete(VARIANT& Shift) { VARIANT result; static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x75, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &Shift); return result; } LPDISPATCH get_Dependents() { LPDISPATCH result; InvokeHelper(0x21f, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } VARIANT _DialogBox() { VARIANT result; InvokeHelper(0xf5, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } LPDISPATCH get_DirectDependents() { LPDISPATCH result; InvokeHelper(0x221, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } LPDISPATCH get_DirectPrecedents() { LPDISPATCH result; InvokeHelper(0x222, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } VARIANT EditionOptions(long Type, long Option, VARIANT& Name, VARIANT& Reference, long Appearance, long ChartSize, VARIANT& Format) { VARIANT result; static BYTE parms[] = VTS_I4 VTS_I4 VTS_VARIANT VTS_VARIANT VTS_I4 VTS_I4 VTS_VARIANT ; InvokeHelper(0x46b, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, Type, Option, &Name, &Reference, Appearance, ChartSize, &Format); return result; } LPDISPATCH get_End(long Direction) { LPDISPATCH result; static BYTE parms[] = VTS_I4 ; InvokeHelper(0x1f4, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, parms, Direction); return result; } LPDISPATCH get_EntireColumn() { LPDISPATCH result; InvokeHelper(0xf6, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } LPDISPATCH get_EntireRow() { LPDISPATCH result; InvokeHelper(0xf7, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } VARIANT FillDown() { VARIANT result; InvokeHelper(0xf8, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT FillLeft() { VARIANT result; InvokeHelper(0xf9, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT FillRight() { VARIANT result; InvokeHelper(0xfa, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT FillUp() { VARIANT result; InvokeHelper(0xfb, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } LPDISPATCH Find(VARIANT& What, VARIANT& After, VARIANT& LookIn, VARIANT& LookAt, VARIANT& SearchOrder, long SearchDirection, VARIANT& MatchCase, VARIANT& MatchByte, VARIANT& SearchFormat) { LPDISPATCH result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_I4 VTS_VARIANT VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x18e, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, &What, &After, &LookIn, &LookAt, &SearchOrder, SearchDirection, &MatchCase, &MatchByte, &SearchFormat); return result; } LPDISPATCH FindNext(VARIANT& After) { LPDISPATCH result; static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x18f, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, &After); return result; } LPDISPATCH FindPrevious(VARIANT& After) { LPDISPATCH result; static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x190, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, &After); return result; } LPDISPATCH get_Font() { LPDISPATCH result; InvokeHelper(0x92, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } VARIANT get_Formula() { VARIANT result; InvokeHelper(0x105, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_Formula(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x105, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } VARIANT get_FormulaArray() { VARIANT result; InvokeHelper(0x24a, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_FormulaArray(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x24a, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } long get_FormulaLabel() { long result; InvokeHelper(0x564, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void put_FormulaLabel(long newValue) { static BYTE parms[] = VTS_I4 ; InvokeHelper(0x564, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } VARIANT get_FormulaHidden() { VARIANT result; InvokeHelper(0x106, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_FormulaHidden(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x106, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } VARIANT get_FormulaLocal() { VARIANT result; InvokeHelper(0x107, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_FormulaLocal(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x107, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } VARIANT get_FormulaR1C1() { VARIANT result; InvokeHelper(0x108, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_FormulaR1C1(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x108, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } VARIANT get_FormulaR1C1Local() { VARIANT result; InvokeHelper(0x109, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_FormulaR1C1Local(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x109, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } VARIANT FunctionWizard() { VARIANT result; InvokeHelper(0x23b, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } BOOL GoalSeek(VARIANT& Goal, LPDISPATCH ChangingCell) { BOOL result; static BYTE parms[] = VTS_VARIANT VTS_DISPATCH ; InvokeHelper(0x1d8, DISPATCH_METHOD, VT_BOOL, (void*)&result, parms, &Goal, ChangingCell); return result; } VARIANT Group(VARIANT& Start, VARIANT& End, VARIANT& By, VARIANT& Periods) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x2e, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &Start, &End, &By, &Periods); return result; } VARIANT get_HasArray() { VARIANT result; InvokeHelper(0x10a, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT get_HasFormula() { VARIANT result; InvokeHelper(0x10b, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT get_Height() { VARIANT result; InvokeHelper(0x7b, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT get_Hidden() { VARIANT result; InvokeHelper(0x10c, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_Hidden(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x10c, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } VARIANT get_HorizontalAlignment() { VARIANT result; InvokeHelper(0x88, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_HorizontalAlignment(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x88, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } VARIANT get_IndentLevel() { VARIANT result; InvokeHelper(0xc9, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_IndentLevel(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0xc9, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } void InsertIndent(long InsertAmount) { static BYTE parms[] = VTS_I4 ; InvokeHelper(0x565, DISPATCH_METHOD, VT_EMPTY, NULL, parms, InsertAmount); } VARIANT Insert(VARIANT& Shift, VARIANT& CopyOrigin) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT ; InvokeHelper(0xfc, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &Shift, &CopyOrigin); return result; } LPDISPATCH get_Interior() { LPDISPATCH result; InvokeHelper(0x81, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } VARIANT get_Item(VARIANT& RowIndex, VARIANT& ColumnIndex) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT ; InvokeHelper(0xaa, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, parms, &RowIndex, &ColumnIndex); return result; } void put_Item(VARIANT& RowIndex, VARIANT& ColumnIndex, VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT VTS_VARIANT VTS_VARIANT ; InvokeHelper(0xaa, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &RowIndex, &ColumnIndex, &newValue); } VARIANT Justify() { VARIANT result; InvokeHelper(0x1ef, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT get_Left() { VARIANT result; InvokeHelper(0x7f, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } long get_ListHeaderRows() { long result; InvokeHelper(0x4a3, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } VARIANT ListNames() { VARIANT result; InvokeHelper(0xfd, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } long get_LocationInTable() { long result; InvokeHelper(0x2b3, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } VARIANT get_Locked() { VARIANT result; InvokeHelper(0x10d, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_Locked(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x10d, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } void Merge(VARIANT& Across) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x234, DISPATCH_METHOD, VT_EMPTY, NULL, parms, &Across); } void UnMerge() { InvokeHelper(0x568, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } LPDISPATCH get_MergeArea() { LPDISPATCH result; InvokeHelper(0x569, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } VARIANT get_MergeCells() { VARIANT result; InvokeHelper(0xd0, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_MergeCells(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0xd0, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } VARIANT get_Name() { VARIANT result; InvokeHelper(0x6e, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_Name(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x6e, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } VARIANT NavigateArrow(VARIANT& TowardPrecedent, VARIANT& ArrowNumber, VARIANT& LinkNumber) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x408, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &TowardPrecedent, &ArrowNumber, &LinkNumber); return result; } LPUNKNOWN get__NewEnum() { LPUNKNOWN result; InvokeHelper(0xfffffffc, DISPATCH_PROPERTYGET, VT_UNKNOWN, (void*)&result, NULL); return result; } LPDISPATCH get_Next() { LPDISPATCH result; InvokeHelper(0x1f6, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } CString NoteText(VARIANT& Text, VARIANT& Start, VARIANT& Length) { CString result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x467, DISPATCH_METHOD, VT_BSTR, (void*)&result, parms, &Text, &Start, &Length); return result; } VARIANT get_NumberFormat() { VARIANT result; InvokeHelper(0xc1, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_NumberFormat(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0xc1, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } VARIANT get_NumberFormatLocal() { VARIANT result; InvokeHelper(0x449, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_NumberFormatLocal(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x449, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } LPDISPATCH get_Offset(VARIANT& RowOffset, VARIANT& ColumnOffset) { LPDISPATCH result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT ; InvokeHelper(0xfe, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, parms, &RowOffset, &ColumnOffset); return result; } VARIANT get_Orientation() { VARIANT result; InvokeHelper(0x86, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_Orientation(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x86, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } VARIANT get_OutlineLevel() { VARIANT result; InvokeHelper(0x10f, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_OutlineLevel(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x10f, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } long get_PageBreak() { long result; InvokeHelper(0xff, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void put_PageBreak(long newValue) { static BYTE parms[] = VTS_I4 ; InvokeHelper(0xff, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } VARIANT Parse(VARIANT& ParseLine, VARIANT& Destination) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x1dd, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &ParseLine, &Destination); return result; } VARIANT _PasteSpecial(long Paste, long Operation, VARIANT& SkipBlanks, VARIANT& Transpose) { VARIANT result; static BYTE parms[] = VTS_I4 VTS_I4 VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x403, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, Paste, Operation, &SkipBlanks, &Transpose); return result; } LPDISPATCH get_PivotField() { LPDISPATCH result; InvokeHelper(0x2db, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } LPDISPATCH get_PivotItem() { LPDISPATCH result; InvokeHelper(0x2e4, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } LPDISPATCH get_PivotTable() { LPDISPATCH result; InvokeHelper(0x2cc, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } LPDISPATCH get_Precedents() { LPDISPATCH result; InvokeHelper(0x220, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } VARIANT get_PrefixCharacter() { VARIANT result; InvokeHelper(0x1f8, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } LPDISPATCH get_Previous() { LPDISPATCH result; InvokeHelper(0x1f7, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } VARIANT __PrintOut(VARIANT& From, VARIANT& To, VARIANT& Copies, VARIANT& Preview, VARIANT& ActivePrinter, VARIANT& PrintToFile, VARIANT& Collate) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x389, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &From, &To, &Copies, &Preview, &ActivePrinter, &PrintToFile, &Collate); return result; } VARIANT PrintPreview(VARIANT& EnableChanges) { VARIANT result; static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x119, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &EnableChanges); return result; } LPDISPATCH get_QueryTable() { LPDISPATCH result; InvokeHelper(0x56a, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } LPDISPATCH get_Range(VARIANT& Cell1, VARIANT& Cell2) { LPDISPATCH result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT ; InvokeHelper(0xc5, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, parms, &Cell1, &Cell2); return result; } VARIANT RemoveSubtotal() { VARIANT result; InvokeHelper(0x373, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } BOOL Replace(VARIANT& What, VARIANT& Replacement, VARIANT& LookAt, VARIANT& SearchOrder, VARIANT& MatchCase, VARIANT& MatchByte, VARIANT& SearchFormat, VARIANT& ReplaceFormat) { BOOL result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT ; InvokeHelper(0xe2, DISPATCH_METHOD, VT_BOOL, (void*)&result, parms, &What, &Replacement, &LookAt, &SearchOrder, &MatchCase, &MatchByte, &SearchFormat, &ReplaceFormat); return result; } LPDISPATCH get_Resize(VARIANT& RowSize, VARIANT& ColumnSize) { LPDISPATCH result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x100, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, parms, &RowSize, &ColumnSize); return result; } long get_Row() { long result; InvokeHelper(0x101, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } LPDISPATCH RowDifferences(VARIANT& Comparison) { LPDISPATCH result; static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x1ff, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, &Comparison); return result; } VARIANT get_RowHeight() { VARIANT result; InvokeHelper(0x110, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_RowHeight(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x110, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } LPDISPATCH get_Rows() { LPDISPATCH result; InvokeHelper(0x102, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } VARIANT Run(VARIANT& Arg1, VARIANT& Arg2, VARIANT& Arg3, VARIANT& Arg4, VARIANT& Arg5, VARIANT& Arg6, VARIANT& Arg7, VARIANT& Arg8, VARIANT& Arg9, VARIANT& Arg10, VARIANT& Arg11, VARIANT& Arg12, VARIANT& Arg13, VARIANT& Arg14, VARIANT& Arg15, VARIANT& Arg16, VARIANT& Arg17, VARIANT& Arg18, VARIANT& Arg19, VARIANT& Arg20, VARIANT& Arg21, VARIANT& Arg22, VARIANT& Arg23, VARIANT& Arg24, VARIANT& Arg25, VARIANT& Arg26, VARIANT& Arg27, VARIANT& Arg28, VARIANT& Arg29, VARIANT& Arg30) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x103, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &Arg1, &Arg2, &Arg3, &Arg4, &Arg5, &Arg6, &Arg7, &Arg8, &Arg9, &Arg10, &Arg11, &Arg12, &Arg13, &Arg14, &Arg15, &Arg16, &Arg17, &Arg18, &Arg19, &Arg20, &Arg21, &Arg22, &Arg23, &Arg24, &Arg25, &Arg26, &Arg27, &Arg28, &Arg29, &Arg30); return result; } VARIANT Select() { VARIANT result; InvokeHelper(0xeb, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT Show() { VARIANT result; InvokeHelper(0x1f0, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT ShowDependents(VARIANT& Remove) { VARIANT result; static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x36d, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &Remove); return result; } VARIANT get_ShowDetail() { VARIANT result; InvokeHelper(0x249, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_ShowDetail(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x249, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } VARIANT ShowErrors() { VARIANT result; InvokeHelper(0x36e, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT ShowPrecedents(VARIANT& Remove) { VARIANT result; static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x36f, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &Remove); return result; } VARIANT get_ShrinkToFit() { VARIANT result; InvokeHelper(0xd1, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_ShrinkToFit(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0xd1, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } VARIANT Sort(VARIANT& Key1, long Order1, VARIANT& Key2, VARIANT& Type, long Order2, VARIANT& Key3, long Order3, long Header, VARIANT& OrderCustom, VARIANT& MatchCase, long Orientation, long SortMethod, long DataOption1, long DataOption2, long DataOption3) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_I4 VTS_VARIANT VTS_VARIANT VTS_I4 VTS_VARIANT VTS_I4 VTS_I4 VTS_VARIANT VTS_VARIANT VTS_I4 VTS_I4 VTS_I4 VTS_I4 VTS_I4 ; InvokeHelper(0x370, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &Key1, Order1, &Key2, &Type, Order2, &Key3, Order3, Header, &OrderCustom, &MatchCase, Orientation, SortMethod, DataOption1, DataOption2, DataOption3); return result; } VARIANT SortSpecial(long SortMethod, VARIANT& Key1, long Order1, VARIANT& Type, VARIANT& Key2, long Order2, VARIANT& Key3, long Order3, long Header, VARIANT& OrderCustom, VARIANT& MatchCase, long Orientation, long DataOption1, long DataOption2, long DataOption3) { VARIANT result; static BYTE parms[] = VTS_I4 VTS_VARIANT VTS_I4 VTS_VARIANT VTS_VARIANT VTS_I4 VTS_VARIANT VTS_I4 VTS_I4 VTS_VARIANT VTS_VARIANT VTS_I4 VTS_I4 VTS_I4 VTS_I4 ; InvokeHelper(0x371, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, SortMethod, &Key1, Order1, &Type, &Key2, Order2, &Key3, Order3, Header, &OrderCustom, &MatchCase, Orientation, DataOption1, DataOption2, DataOption3); return result; } LPDISPATCH get_SoundNote() { LPDISPATCH result; InvokeHelper(0x394, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } LPDISPATCH SpecialCells(long Type, VARIANT& Value) { LPDISPATCH result; static BYTE parms[] = VTS_I4 VTS_VARIANT ; InvokeHelper(0x19a, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, Type, &Value); return result; } VARIANT get_Style() { VARIANT result; InvokeHelper(0x104, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_Style(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x104, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } VARIANT SubscribeTo(LPCTSTR Edition, long Format) { VARIANT result; static BYTE parms[] = VTS_BSTR VTS_I4 ; InvokeHelper(0x1e1, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, Edition, Format); return result; } VARIANT Subtotal(long GroupBy, long Function, VARIANT& TotalList, VARIANT& Replace, VARIANT& PageBreaks, long SummaryBelowData) { VARIANT result; static BYTE parms[] = VTS_I4 VTS_I4 VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_I4 ; InvokeHelper(0x372, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, GroupBy, Function, &TotalList, &Replace, &PageBreaks, SummaryBelowData); return result; } VARIANT get_Summary() { VARIANT result; InvokeHelper(0x111, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT Table(VARIANT& RowInput, VARIANT& ColumnInput) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x1f1, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &RowInput, &ColumnInput); return result; } VARIANT get_Text() { VARIANT result; InvokeHelper(0x8a, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT TextToColumns(VARIANT& Destination, long DataType, long TextQualifier, VARIANT& ConsecutiveDelimiter, VARIANT& Tab, VARIANT& Semicolon, VARIANT& Comma, VARIANT& Space, VARIANT& Other, VARIANT& OtherChar, VARIANT& FieldInfo, VARIANT& DecimalSeparator, VARIANT& ThousandsSeparator, VARIANT& TrailingMinusNumbers) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_I4 VTS_I4 VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x410, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &Destination, DataType, TextQualifier, &ConsecutiveDelimiter, &Tab, &Semicolon, &Comma, &Space, &Other, &OtherChar, &FieldInfo, &DecimalSeparator, &ThousandsSeparator, &TrailingMinusNumbers); return result; } VARIANT get_Top() { VARIANT result; InvokeHelper(0x7e, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT Ungroup() { VARIANT result; InvokeHelper(0xf4, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT get_UseStandardHeight() { VARIANT result; InvokeHelper(0x112, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_UseStandardHeight(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x112, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } VARIANT get_UseStandardWidth() { VARIANT result; InvokeHelper(0x113, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_UseStandardWidth(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x113, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } LPDISPATCH get_Validation() { LPDISPATCH result; InvokeHelper(0x56b, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } VARIANT get_Value(VARIANT& RangeValueDataType) { VARIANT result; static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x6, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, parms, &RangeValueDataType); return result; } void put_Value(VARIANT& RangeValueDataType, VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x6, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &RangeValueDataType, &newValue); } VARIANT get_Value2() { VARIANT result; InvokeHelper(0x56c, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_Value2(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x56c, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } VARIANT get_VerticalAlignment() { VARIANT result; InvokeHelper(0x89, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_VerticalAlignment(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x89, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } VARIANT get_Width() { VARIANT result; InvokeHelper(0x7a, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } LPDISPATCH get_Worksheet() { LPDISPATCH result; InvokeHelper(0x15c, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } VARIANT get_WrapText() { VARIANT result; InvokeHelper(0x114, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } void put_WrapText(VARIANT& newValue) { static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x114, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, &newValue); } LPDISPATCH AddComment(VARIANT& Text) { LPDISPATCH result; static BYTE parms[] = VTS_VARIANT ; InvokeHelper(0x56d, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, &Text); return result; } LPDISPATCH get_Comment() { LPDISPATCH result; InvokeHelper(0x38e, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } void ClearComments() { InvokeHelper(0x56e, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } LPDISPATCH get_Phonetic() { LPDISPATCH result; InvokeHelper(0x56f, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } LPDISPATCH get_FormatConditions() { LPDISPATCH result; InvokeHelper(0x570, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } long get_ReadingOrder() { long result; InvokeHelper(0x3cf, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void put_ReadingOrder(long newValue) { static BYTE parms[] = VTS_I4 ; InvokeHelper(0x3cf, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } LPDISPATCH get_Hyperlinks() { LPDISPATCH result; InvokeHelper(0x571, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } LPDISPATCH get_Phonetics() { LPDISPATCH result; InvokeHelper(0x713, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } void SetPhonetic() { InvokeHelper(0x714, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } CString get_ID() { CString result; InvokeHelper(0x715, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); return result; } void put_ID(LPCTSTR newValue) { static BYTE parms[] = VTS_BSTR ; InvokeHelper(0x715, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } VARIANT _PrintOut(VARIANT& From, VARIANT& To, VARIANT& Copies, VARIANT& Preview, VARIANT& ActivePrinter, VARIANT& PrintToFile, VARIANT& Collate, VARIANT& PrToFileName) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x6ec, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &From, &To, &Copies, &Preview, &ActivePrinter, &PrintToFile, &Collate, &PrToFileName); return result; } LPDISPATCH get_PivotCell() { LPDISPATCH result; InvokeHelper(0x7dd, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } void Dirty() { InvokeHelper(0x7de, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } LPDISPATCH get_Errors() { LPDISPATCH result; InvokeHelper(0x7df, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } LPDISPATCH get_SmartTags() { LPDISPATCH result; InvokeHelper(0x7e0, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } void Speak(VARIANT& SpeakDirection, VARIANT& SpeakFormulas) { static BYTE parms[] = VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x7e1, DISPATCH_METHOD, VT_EMPTY, NULL, parms, &SpeakDirection, &SpeakFormulas); } VARIANT PasteSpecial(long Paste, long Operation, VARIANT& SkipBlanks, VARIANT& Transpose) { VARIANT result; static BYTE parms[] = VTS_I4 VTS_I4 VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x788, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, Paste, Operation, &SkipBlanks, &Transpose); return result; } BOOL get_AllowEdit() { BOOL result; InvokeHelper(0x7e4, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } LPDISPATCH get_ListObject() { LPDISPATCH result; InvokeHelper(0x8d1, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } LPDISPATCH get_XPath() { LPDISPATCH result; InvokeHelper(0x8d2, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } LPDISPATCH get_ServerActions() { LPDISPATCH result; InvokeHelper(0x9bb, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } void RemoveDuplicates(VARIANT& Columns, long Header) { static BYTE parms[] = VTS_VARIANT VTS_I4 ; InvokeHelper(0x9bc, DISPATCH_METHOD, VT_EMPTY, NULL, parms, &Columns, Header); } VARIANT PrintOut(VARIANT& From, VARIANT& To, VARIANT& Copies, VARIANT& Preview, VARIANT& ActivePrinter, VARIANT& PrintToFile, VARIANT& Collate, VARIANT& PrToFileName) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x939, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &From, &To, &Copies, &Preview, &ActivePrinter, &PrintToFile, &Collate, &PrToFileName); return result; } CString get_MDX() { CString result; InvokeHelper(0x84b, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); return result; } void ExportAsFixedFormat(long Type, VARIANT& Filename, VARIANT& Quality, VARIANT& IncludeDocProperties, VARIANT& IgnorePrintAreas, VARIANT& From, VARIANT& To, VARIANT& OpenAfterPublish, VARIANT& FixedFormatExtClassPtr) { static BYTE parms[] = VTS_I4 VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT ; InvokeHelper(0x9bd, DISPATCH_METHOD, VT_EMPTY, NULL, parms, Type, &Filename, &Quality, &IncludeDocProperties, &IgnorePrintAreas, &From, &To, &OpenAfterPublish, &FixedFormatExtClassPtr); } VARIANT get_CountLarge() { VARIANT result; InvokeHelper(0x9c3, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); return result; } VARIANT CalculateRowMajorOrder() { VARIANT result; InvokeHelper(0x93c, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); return result; } LPDISPATCH get_SparklineGroups() { LPDISPATCH result; InvokeHelper(0xb25, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } void ClearHyperlinks() { InvokeHelper(0xb26, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } LPDISPATCH get_DisplayFormat() { LPDISPATCH result; InvokeHelper(0x29a, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } VARIANT BorderAround(VARIANT& LineStyle, long Weight, long ColorIndex, VARIANT& Color, VARIANT& ThemeColor) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_I4 VTS_I4 VTS_VARIANT VTS_VARIANT ; InvokeHelper(0xad3, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &LineStyle, Weight, ColorIndex, &Color, &ThemeColor); return result; } void AllocateChanges() { InvokeHelper(0xb27, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } void DiscardChanges() { InvokeHelper(0xb28, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } // Range 属性 public: };
[ "jgyh1987@outlook.com" ]
jgyh1987@outlook.com
45253955364c0db8a10e29bae253c14d45c22c56
7068afe0784327e29aef5436762317ff863f8333
/Login.h
5dd758cafe4f74f75e7aa2019f7494ede71ee030
[]
no_license
Michal198803/AdressBookObjectCPP
d97af9784b7ee96590de65335192f187953f9ecf
cc814e1f8b4b5d6d9ceb9d8a210ab1f429efbe16
refs/heads/master
2021-05-03T07:23:48.693110
2018-02-07T11:45:46
2018-02-07T11:45:46
120,607,711
0
0
null
null
null
null
UTF-8
C++
false
false
340
h
#ifndef LOGIN #define LOGIN #include <iostream> using namespace std; class Login { private: int userId; string login; string password; public: string getLogin(); void setLogin(string login); string getpassword(); void setpassword(string password); int getUserID(); void setUserID(int userId); }; #endif
[ "noreply@github.com" ]
Michal198803.noreply@github.com
de3f0598ead2227c2596415e15ae4a9ca57e6fbb
adc6ec6f7845f5c3ca81a17c09a938b6c399c8a7
/Chapter 6 - Threaded safe stack using mutex - A class definition example.cpp
fdf4e18f648d11f0952409562a62007288a1a262
[]
no_license
CyberExplosion/Concurrency-In-Action
57d9eb7cd885c3bb01a2618d94fbfd105239894c
a5786650874bdec36d5dffe34cb677be819c0d7b
refs/heads/main
2023-06-02T11:44:05.662065
2021-06-18T10:49:02
2021-06-18T10:49:02
324,660,323
0
0
null
null
null
null
UTF-8
C++
false
false
1,706
cpp
#include <thread> #include <stack> #include <mutex> #include <exception> using namespace std; struct empty_stack : std::exception { const char* what () const noexcept; }; template <typename T> class threadsafe_stack { private: stack<T> data; mutable mutex m; public: threadsafe_stack () {}; threadsafe_stack (const threadsafe_stack& other) { scoped_lock guard{ m }; data = other.data; //Use the stack assignment op } threadsafe_stack& operator= (const threadsafe_stack&) = delete; //Can't use assignment //no assignment op for mutex. Also only copy-swap idiom makes assignment exception safe void push (T new_value) { //Copy in because thread scoped_lock guard{ m }; data.push (move (new_value)); //Might throw an exception if the move fail //Stack guarantee push to be exception free tho so it's good } shared_ptr<T> pop () { //1 option to return pointer. (Can't return reference because they //can change from the outside scoped_lock guard{ m }; if (data.empty ()) throw empty_stack (); shared_ptr<T> const res{ make_shared<T> (move (data.top ())) }; //Move so no need to //copy the file into making a new value. Also avoid making new data //Also const so you can't do anything funny like swap the pointer or reset it data.pop (); return res; } void pop (T& value) { //2 option to pass in a reference for result scoped_lock guard{ m }; if (data.empty ()) throw empty_stack (); value = move(data.top ()); //Assign to reference so no exception //The move or the inner copy assignment can throw data.pop (); } bool empty () const { scoped_lock guard{ m }; return data.empty (); //Empty never throw so this function is safe } };
[ "minhkhoi632000@gmail.com" ]
minhkhoi632000@gmail.com
00f0ca5d14ff88baae7c7655489c74e858810520
1fdfea493b09e075f4fceb5f9a1ae631a39bed0c
/botDriver/lib/Driving/Driving.cpp
f1c0c67f8e1b346f39e826305aa4e301f18d90da
[]
no_license
datduyng/unlRobotic2018
c14f617250132320f285d3c12fbe5e09bb161cb2
1dd839a2546c2a0aa53823a9d4fc222800ec7470
refs/heads/master
2020-03-19T04:22:24.051655
2018-07-19T14:47:58
2018-07-19T14:47:58
135,820,788
0
0
null
null
null
null
UTF-8
C++
false
false
11,168
cpp
/* Author: CheeTown Liew Version of June 10, 2017 This algorithm is designed to drive the robot and run with precise displacement using motor encoder, the algorithm includes simple proportion controller and displacement-encoder count convertor, speed comparator and path tracking. Micro-controller Board: Arduino Mega Motor Driver: Sabertooth Motor Driver */ #include <Driving.h> #include <math.h> SabertoothSimplified motordriver(Serial3); //declare global & local coordinates float global_x = 0.0; float global_y = 0.0; float local_x = 0.0; float local_y = 0.0; int16_t global_orientation = 0; //declare encoder counter volatile int64_t ECL = 0; //encoder counter - LEFT volatile int64_t ECLM = -1; //encoder counter - LEFT MEMORY volatile int64_t ECR = 0; //encoder counter - RIGHT volatile int64_t ECRM = -1; //encoder counter - RIGHT MEMORY //declare variable bool debug1 = false; void debug ( bool toggle ){ debug1 = toggle; } //Default initiattion to assign I/O pins void dinit (){ //For Channel A attachInterrupt(digitalPinToInterrupt(ECLA), counter1, RISING); //LEFT encoder channel A trigger attachInterrupt(digitalPinToInterrupt(ECRA), counter2, RISING); //RIGHT encoder channel A trigger //For Channel B pinMode(ECLB, INPUT); //LEFT encoder channel B as input digitalWrite(ECLB, LOW); //Pull down LEFT channel B pinMode(ECRB, INPUT); //RIGHT encoder channel B as input digitalWrite(ECRB, LOW); //Pull down RIGHT channel B //Encoder's Vcc pinMode(24, OUTPUT); pinMode(25, OUTPUT); pinMode(26, OUTPUT); pinMode(27, OUTPUT); digitalWrite(24, HIGH); digitalWrite(25, HIGH); digitalWrite(26, LOW); digitalWrite(27, LOW); Serial3.begin(19200); } //Initiator with customize I/O pins, the argument must be pointer to an array with //the format of { Left_Channel_A, Right_Channel_A, Left_Channel_B, Right_Channel_B }; /* void dinit ( uint8_t& pins ){ attachInterrupt( digitalPinToInterrupt( *pins ), counter1, RISING); attachInterrupt( digitalPinToInterrupt( *(pins+1) ), counter2, RISING); pinMode( *(pins+2), INPUT); //LEFT encoder channel B as input digitalWrite(*(pins+2), LOW); //Pull down LEFT channel B pinMode( *(pins+3), INPUT); //RIGHT encoder channel B as input digitalWrite( *(pins+4), LOW); //Pull down RIGHT channel B //Encoder's Vcc pinMode(EPOWERL, OUTPUT); digitalWrite(EPOWERL, HIGH); pinMode(EPOWERR, OUTPUT); digitalWrite(EPOWERR, HIGH); } */ //Left Encoder Counter void static counter1() { ECLM = ECL; if (digitalRead(ECLB) == HIGH) {ECL++;} else {ECL--;} } //Right Encoder Counter void static counter2() { ECRM = ECR; if (digitalRead(ECRB) == HIGH) {ECR++;} else {ECR--;} } int64_t D2C ( float distance ) { return ((double) distance * (double) INCH2C) ; } float C2D (int64_t EncoderCount ){ return ((double) EncoderCount * (double) COUNTER2INCHE); } int comparator( int64_t L, int64_t R ){ return ( ECL - L ) - ( ECR - R ); } int16_t leftDrive = 0; int16_t driving2 = 0; int16_t na = 0; int64_t R2C ( float angle ){ return D2C ( ( angle / 360.0 * WHEELDIA * 3.141592653589 ) ); } int16_t C2R ( int64_t encoderCount ){ return C2D ( encoderCount ) / ( WHEELDIA * 3.141592653589 ) * 360; } void steer(float angle){ const int64_t left_targetcount = ECL + R2C(toAngle + 2); const int64_t right_targetcount = ECR - R2C(toAngle + 2); int ECLO = -1; int ECRO = -1; // Encoder count left/right increment const int ECLI = ECL; const int ECRI = ECR; while ( true ) { leftDrive = constrain( (double) K1 * (left_targetcount - ECL), -113, 112); driving2 = constrain( (double) K2 * (right_targetcount - ECR), -127, 127); /* the comparison value of the encoder count difference per iteration positive mean left motor is faster than the right motor and vise versa */ int16_t v = comparator( ECL, ECR ); if( (v*(float) V) > 30.0 ){} //Serial.println("Warning! There is a large speed differential."); else v *= (float) V; // adjust the increment of each wheel if one go faster than the other. if(v > 0){// left counter is greater than R } } void steer ( int16_t toAngle ){ const int64_t left_targetcount = ECL + R2C(toAngle + 2); const int64_t right_targetcount = ECR - R2C(toAngle + 2); /* Serial.println((int32_t)R2C(toAngle)); Serial.println((int32_t)left_targetcount); Serial.println((int32_t)right_targetcount); */ leftDrive = 0; driving2 = 0; na = 0; int8_t pause = 0; uint64_t timestamp = 0; int ECLO = -1; int ECRO = -1; const int ECLI = ECL; const int ECRI = ECR; while ( true ) { leftDrive = constrain( (double) K1 * (left_targetcount - ECL), -113, 112); driving2 = constrain( (double) K2 * (right_targetcount - ECR), -127, 127); /* the comparison value of the encoder count difference per iteration positive mean left motor is faster than the right motor and vise versa */ int16_t v = comparator( ECLO, ECRO ); if( (v*(float) V) > 30.0 ){} //Serial.println("Warning! There is a large speed differential."); else v *= (float) V; if(toAngle > 0 ){ if( v > 0 ){ if (leftDrive > 0){ leftDrive -= v* (float) V; }else{ leftDrive += v* (float) V; } } else { if (driving2 > 0){ driving2 -= v* (float) V; }else{ leftDrive += v* (float) V; } } }else { if( v > 0 ){ if (leftDrive > 0){ leftDrive -= v* (float) V; }else{ leftDrive += v* (float) V; } } else { if (driving2 > 0){ driving2 -= v* (float) V; }else{ leftDrive += v* (float) V; } } } int16_t integral = comparator( ECLI, ECRI ); // if( integral* (float) I > 20 ) Serial.println("Warning! There is a large integral difference"); // if(toAngle > 0 ){ // if( integral > 0 ){ // if (leftDrive > 0){ // leftDrive -= integral* (float) I; // }else{ // driving2 += integral* (float) I; // } // } else { // if (driving2 > 0){ // driving2 -= integral* (float) I; // }else{ // leftDrive += integral* (float) I; // } // } // }else { // if( integral > 0 ){ // if (leftDrive < 0){ // leftDrive += integral* (float) I; // }else{ // driving2 += integral* (float) I; // } // } else { // if (driving2 < 0){ // driving2 -= integral* (float) I; // }else{ // leftDrive -= integral* (float) I; // } // } // } if (toAngle> 0){ leftDrive = constrain( leftDrive, 0, 112); driving2 = constrain( driving2, -127, 0); }else{ leftDrive = constrain(leftDrive, -113, 0); driving2 = constrain(driving2, 0, 127); } motordriver.motor(1, leftDrive); motordriver.motor(2, driving2); //if the motor(s) stall for 0.1s, quit the iteration if ( ECL == ECLO || ECR == ECRO ) { if ( pause == 0 ) { timestamp = millis(); pause = 1; } else { if ( abs(millis() - timestamp) > 100 ) { pause = 0; break; } } } ECLO = ECL; ECRO = ECR; //if (debug == true)debugMode(); /* Serial.print( (int32_t) ECL); Serial.print("\t"); Serial.print( (int32_t) ECR); Serial.print("\t"); Serial.print(v); Serial.print("\t"); Serial.print(integral); Serial.print("\t"); Serial.print(leftDrive); Serial.print("\t"); Serial.print(driving2); Serial.print("\n"); */ } motordriver.motor(1, 0); motordriver.motor(2, 0); global_orientation += ( ( C2R ( (int64_t) ECL - (int64_t) ECLI ) - C2R( ( int64_t) ECR - (int64_t) ECRI ))/2 ); //global_orientation += toAngle; //global_orientation = constrain(global_orientation, -180, 180); //Serial.println(global_orientation); } void driveto( float distance ) { const int64_t left_targetcount = ECL+ D2C( distance + 0.15 ); const int64_t right_targetcount = ECR + D2C( distance + 0.15 ); leftDrive = 0; driving2 = 0; na = 0; int8_t pause = 0; uint64_t timestamp = 0; int ECLO = -1; int ECRO = -1; const int ECLI = ECL; const int ECRI = ECR; while ( true ) { leftDrive = constrain( (double) K1 * (left_targetcount - ECL), -113, 112); driving2 = constrain( (double) K2 * (right_targetcount - ECR), -127, 127); /* the comparison value of the encoder count difference per iteration positive value indicates left motor is faster than the right motor and vise versa */ int16_t v = comparator( ECLO, ECRO ); if( (v*(float) V) > 30.0 ){} //Serial.println("Warning! There is a large speed differential."); else v *= (float) V; if(distance > 0 ){ if( v > 0 ){ if (leftDrive > 0){ leftDrive -= v* (float) V; }else{ leftDrive += v* (float) V; } } else { if (driving2 > 0){ driving2 -= v* (float) V; }else{ leftDrive += v* (float) V; } } }else { if( v > 0 ){ if (leftDrive > 0){ leftDrive -= v* (float) V; }else{ leftDrive += v* (float) V; } } else { if (driving2 > 0){ driving2 -= v* (float) V; }else{ leftDrive += v* (float) V; } } } int16_t integral = comparator( ECLI, ECRI ); if( integral* (float) I > 20 ){} //Serial.println("Warning! There is a large integral differences."); if(distance > 0 ){ if( integral > 0 ){ if (leftDrive > 0){ leftDrive -= integral* (float) I; }else{ driving2 += integral* (float) I; } } else { if (driving2 > 0){ driving2 -= integral* (float) I; }else{ leftDrive += integral* (float) I; } } }else { if( integral > 0 ){ if (leftDrive < 0){ leftDrive -= integral* (float) I; }else{ driving2 += integral* (float) I; } } else { if (driving2 < 0){ driving2 += integral* (float) I; }else{ leftDrive -= integral* (float) I; } } } if (distance > 0){ //forward motion leftDrive = constrain( leftDrive, 0, 112); driving2 = constrain( driving2, 0, 127); }else{ //backward motion leftDrive = constrain(leftDrive, -113, 0); driving2 = constrain(driving2, -127, 0); } motordriver.motor(1, leftDrive); motordriver.motor(2, driving2); //if the motor(s) stall for 0.1s, quit the iteration if ( ECL == ECLO || ECR == ECRO ) { if ( pause == 0 ) { timestamp = millis(); pause = 1; } else { if ( abs(millis() - timestamp) > 100 ) { pause = 0; break; } } } ECLO = ECL; ECRO = ECR; //if (debug == true)debugMode(); /* Serial.print( (int32_t) ECL); Serial.print("\t"); Serial.print( (int32_t) ECR); Serial.print("\t"); Serial.print(v); Serial.print("\t"); Serial.print(integral); Serial.print("\t"); Serial.print(leftDrive); Serial.print("\t"); Serial.print(driving2); Serial.print("\n"); */ } motordriver.motor(1, 0); motordriver.motor(2, 0); global_x += ( C2D( ECL - ECLI) + C2D (ECR - ECRI) )/2 * cos(global_orientation); global_y += ( C2D( ECL - ECLI) + C2D (ECR - ECRI) )/2 * sin(global_orientation); //global_x = C2D (( ECL + ECR )/2) ; } void debugMode (){ Serial.begin(9600); Serial.print(na); Serial.print("\t"); Serial.print("ECL\t"); Serial.print( (int32_t) ECL); Serial.print("\tECR\t"); Serial.print( (int32_t) ECR); Serial.print("\tV1\t"); Serial.print(leftDrive); Serial.print("\tV2\t"); Serial.println(driving2); }
[ "ctliew2@gmail.com" ]
ctliew2@gmail.com
e5a05e200f69060dc361c41b12108219f358b032
d73597607f21311105742ba4cd27b12091d8169e
/4.cpp
18778eb8dbf761af1cec6d6607385627a0af0646
[]
no_license
kndixx/lab-12
daad32b960c9cde42696979203aea34f91987ee7
ee523cfb622225a6599d913ecfc593d1cf259f63
refs/heads/main
2023-03-03T05:27:19.895535
2021-02-14T13:00:21
2021-02-14T13:00:21
338,805,956
0
0
null
null
null
null
UTF-8
C++
false
false
2,638
cpp
#include <iostream> using namespace std; int main() { int a; int d; cin >> a; d = a / 100; if (d == 1) { cout << "Сто "; } else if (d == 2) { cout << "Двести "; } else if (d == 3) { cout << "Триста "; } else if (d == 4) { cout << "Четыреста "; } else if (d == 5) { cout << "Пятьсот "; } else if (d == 6) { cout << "Шестьсот "; } else if (d == 7) { cout << "Семьсот "; } else if (d == 8) { cout << "Восемьсот "; } else if (d == 9) { cout << "Девятьсот "; } d = a % 100; if (d == 10) { cout << "десять "; } else if (d == 11) { cout << "одиннадцать "; } else if (d == 12) { cout << "двенадцать "; } else if (d == 13) { cout << "тринадцать "; } else if (d == 14) { cout << "четырнадцать "; } else if (d == 15) { cout << "пятнадцать "; } else if (d == 16) { cout << "шестнадцать "; } else if (d == 17) { cout << "семнадцать "; } else if (d == 18) { cout << "восемнадцать "; } else if (d == 19) { cout << "девятнадцать "; } if (d >= 10 && d < 20 || d == 0) { return 0; } d = d / 10; if (d == 2) { cout << "двадцать "; } else if (d == 3) { cout << "тридцать "; } else if (d == 4) { cout << "сорок "; } else if (d == 5) { cout << "пятьдесят "; } else if (d == 6) { cout << "шестьдеяст "; } else if (d == 7) { cout << "семьдесят "; } else if (d == 8) { cout << "восеьмдесят "; } else if (d == 9) { cout << "девяносто "; } d = a % 10; if (d == 0) { return 0; } if (d == 1) { cout << "один"; } else if (d == 2) { cout << "два"; } else if (d == 3) { cout << "три"; } else if (d == 4) { cout << "четыре"; } else if (d == 5) { cout << "пять"; } else if (d == 6) { cout << "шесть"; } else if (d == 7) { cout << "семь"; } else if (d == 8) { cout << "восемь"; } else if (d == 9) { cout << "девять"; } return 0; }
[ "noreply@github.com" ]
kndixx.noreply@github.com
c2eb45cb56d1a4f31c7ec183b071cc642b9c533d
57b96c6b71e76fb7b45f9cc66a64638c31c29c5e
/2_example/example21_talk/example21_talk.ino
019782541d13367ea7cfc5cd327a954a4047a549
[ "MIT" ]
permissive
kghrlabo/esp
04d3b945b8964c8ad40e0d6b94f92055508e2897
64c3f92c90198de3171a2a394231598b9f35f078
refs/heads/master
2020-04-03T11:43:34.139559
2018-10-08T07:49:16
2018-10-08T07:49:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,021
ino
/******************************************************************************* Example 21: AquosTalkを使った音声出力器(HTTP版) Copyright (c) 2016 Wataru KUNINO *******************************************************************************/ #include <ESP8266WiFi.h> // Wi-Fi機能を利用するために必要 extern "C" { #include "user_interface.h" // ESP8266用の拡張IFライブラリ } #include <WiFiUdp.h> // UDP通信を行うライブラリ #define TIMEOUT 20000 // タイムアウト 20秒 #define SSID "1234ABCD" // 無線LANアクセスポイントのSSID #define PASS "password" // パスワード #define PORT 1024 // 受信ポート番号 WiFiUDP udp; // UDP通信用のインスタンスを定義 WiFiServer server(80); // Wi-Fiサーバ(ポート80=HTTP)定義 void setup(){ // 起動時に一度だけ実行する関数 Serial.begin(9600); // AquesTalkとの通信ポート Serial.print("\r$"); // ブレークコマンドを出力する delay(100); // 待ち時間処理 Serial.print("$?kon'nnichi/wa.\r"); // 音声「こんにちわ」を出力する wifi_set_sleep_type(LIGHT_SLEEP_T); // 省電力モード設定 WiFi.mode(WIFI_STA); // 無線LANをSTAモードに設定 WiFi.begin(SSID,PASS); // 無線LANアクセスポイントへ接続 while(WiFi.status() != WL_CONNECTED){ // 接続に成功するまで待つ delay(500); // 待ち時間処理 } server.begin(); // サーバを起動する udp.begin(PORT); // UDP通信御開始 Serial.print("<NUM VAL="); // 数字読み上げ用タグ出力 Serial.print(WiFi.localIP()); // IPアドレスを読み上げる Serial.print(">.\r"); // タグの終了を出力する } void loop(){ // 繰り返し実行する関数 WiFiClient client; // Wi-Fiクライアントの定義 char c; // 文字変数cを定義 char s[65]; // 文字列変数を定義 65バイト64文字 char talk[65]=""; // 音声出力用の文字列変数を定義 int len=0; // 文字列長を示す整数型変数を定義 int t=0; // 待ち受け時間のカウント用の変数 int postF=0; // POSTフラグ(0:未 1:POST 2:BODY) int postL=64; // POSTデータ長 client = server.available(); // 接続されたTCPクライアントを生成 if(client==0){ // TCPクライアントが無かった場合 len = udp.parsePacket(); // UDP受信パケット長を変数lenに代入 if(len==0)return; // TCPとUDPが未受信時にloop()先頭へ memset(s, 0, 49); // 文字列変数sの初期化(49バイト) udp.read(s, 48); // UDP受信データを文字列変数sへ代入 Serial.print(s); // AquesTalkへ出力する Serial.print("\r"); // 改行コード(CR)を出力する return; // loop()の先頭に戻る } while(client.connected()){ // 当該クライアントの接続状態を確認 if(client.available()){ // クライアントからのデータを確認 t=0; // 待ち時間変数をリセット c=client.read(); // データを文字変数cに代入 if(c=='\n'){ // 改行を検出した時 if(postF==0){ // ヘッダ処理 if(len>11 && strncmp(s,"GET /?TEXT=",11)==0){ strncpy(talk,&s[11],64); // 受信文字列をtalkへコピー break; // 解析処理の終了 }else if (len>5 && strncmp(s,"GET /",5)==0){ strcpy(talk,"de'-ta-o'nyu-ryo_kushiteku'dasai."); break; // 解析処理の終了 }else if(len>6 && strncmp(s,"POST /",6)==0){ postF=1; // POSTのBODY待ち状態へ } }else if(postF==1){ if(len>16 && strncmp(s,"Content-Length: ",16)==0){ postL=atoi(&s[16]); // 変数postLにデータ値を代入 } } if( len==0 ) postF++; // ヘッダの終了 len=0; // 文字列長を0に }else if(c!='\r' && c!='\0'){ s[len]=c; // 文字列変数に文字cを追加 len++; // 変数lenに1を加算 s[len]='\0'; // 文字列を終端 if(len>=64) len=63; // 文字列変数の上限 } if(postF>=2){ // POSTのBODY処理 if(postL<=0){ // 受信完了時 if(len>5 && strncmp(s,"TEXT=",5)==0){ strncpy(talk,&s[5],64); // 受信文字列をtalkへコピー } break; // 解析処理の終了 } postL--; // 受信済POSTデータ長の減算 } } t++; // 変数tの値を1だけ増加させる if(t>TIMEOUT) break; else delay(1); // TIMEOUTに到達したらwhileを抜ける } delay(1); // クライアント側の応答待ち時間 if(talk[0]){ // 文字列が代入されていた場合、 trUri2txt(talk); // URLエンコードの変換処理 Serial.print(talk); // 受信文字データを音声出力 Serial.print("\r"); // 改行コード(CR)を出力する } if(client.connected()){ // 当該クライアントの接続状態を確認 html(client,talk,WiFi.localIP()); // HTMLコンテンツを出力する } // client.stop(); // クライアントの切断 }
[ "xbee@dream.jp" ]
xbee@dream.jp
3dad10cdfdf0c06265557453e09bad8b9d417fdd
71dae8653492a02c77f67d03a0824f920d5fd9ee
/Sparky-core/src/graphics/font_manager.cpp
27d03f1f57b246ab960d2dc72119787cc6584004
[ "Apache-2.0" ]
permissive
TheCherno/LD32
8ad6aeb6f1345ecb04a351e2632ac9cf343a595c
9654d71c62d94f3c00de9029ea42e248438fc02a
refs/heads/master
2016-09-06T06:35:55.806350
2015-04-21T05:01:45
2015-04-21T05:01:45
34,146,855
15
1
null
null
null
null
UTF-8
C++
false
false
798
cpp
#include "font_manager.h" namespace sparky { namespace graphics { std::vector<Font*> FontManager::m_Fonts; void FontManager::add(Font* font) { m_Fonts.push_back(font); } Font* FontManager::get() { return m_Fonts[0]; } Font* FontManager::get(const std::string& name) { for (Font* font : m_Fonts) { if (font->getName() == name) return font; } // TODO: Maybe return a default font instead? return nullptr; } Font* FontManager::get(const std::string& name, unsigned int size) { for (Font* font : m_Fonts) { if (font->getSize() == size && font->getName() == name) return font; } // TODO: Maybe return a default font instead? return nullptr; } void FontManager::clean() { for (int i = 0; i < m_Fonts.size(); i++) delete m_Fonts[i]; } } }
[ "cherno21@hotmail.com" ]
cherno21@hotmail.com
08bdb373fdbf67aadfb6f8101385efbb65a38f14
b5a9d42f7ea5e26cd82b3be2b26c324d5da79ba1
/tensorflow/compiler/jit/clone_constants_for_better_clustering_test.cc
7944d8ebd12be754cec6e0c3633ee55bceb1fe5b
[ "Apache-2.0" ]
permissive
uve/tensorflow
e48cb29f39ed24ee27e81afd1687960682e1fbef
e08079463bf43e5963acc41da1f57e95603f8080
refs/heads/master
2020-11-29T11:30:40.391232
2020-01-11T13:43:10
2020-01-11T13:43:10
230,088,347
0
0
Apache-2.0
2019-12-25T10:49:15
2019-12-25T10:49:14
null
UTF-8
C++
false
false
6,717
cc
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/jit/clone_constants_for_better_clustering.h" #include "tensorflow/cc/framework/ops.h" #include "tensorflow/cc/ops/array_ops.h" #include "tensorflow/cc/ops/const_op.h" #include "tensorflow/compiler/jit/node_matchers.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/public/session_options.h" namespace tensorflow { namespace { using ::tensorflow::testing::FindNodeByName; Status CloneConstantsForBetterClustering(const Scope& s, std::unique_ptr<Graph>* result) { auto graph = absl::make_unique<Graph>(OpRegistry::Global()); SessionOptions session_options; session_options.config.mutable_graph_options() ->mutable_optimizer_options() ->set_global_jit_level(OptimizerOptions::ON_2); GraphOptimizationPassOptions options; options.graph = &graph; options.session_options = &session_options; // Scope::ToGraph seems to drop assigned devices, probably because it goes // through a GraphDef. So explicitly maintain the device assignment. // std::unordered_map<string, string> assigned_device_names; // for (Node* n : s.graph()->nodes()) { // assigned_device_names[n->name()] = n->assigned_device_name(); // } GraphConstructorOptions opts; opts.expect_device_spec = true; TF_RETURN_IF_ERROR(s.ToGraph(graph.get(), opts)); // for (Node* n : graph->nodes()) { // n->set_assigned_device_name(assigned_device_names[n->name()]); // } CloneConstantsForBetterClusteringPass rewriter; TF_RETURN_IF_ERROR(rewriter.Run(options)); *result = std::move(graph); return Status::OK(); } const char* kCPU = "/job:localhost/replica:0/task:0/device:CPU:0"; const char* kGPU = "/job:localhost/replica:0/task:0/device:GPU:0"; TEST(CloneConstantsForBetterClusteringTest, Basic) { Scope root = Scope::NewRootScope().ExitOnError(); Scope on_gpu = root.WithAssignedDevice(kGPU).WithDevice(kGPU); Scope on_cpu = root.WithAssignedDevice(kCPU).WithDevice(kCPU); Output in0 = ops::Placeholder(on_gpu.WithOpName("in0"), DT_FLOAT); Output in1 = ops::Placeholder(on_gpu.WithOpName("in1"), DT_FLOAT); Output perm = ops::Const(on_cpu.WithOpName("perm"), {3, 1, 2, 0}); { Output tr0 = ops::Transpose(on_gpu.WithOpName("tr0"), in0, perm); Output tr1 = ops::Transpose(on_gpu.WithOpName("tr1"), in1, perm); } std::unique_ptr<Graph> result; TF_ASSERT_OK(CloneConstantsForBetterClustering(root, &result)); OutputTensor tr0_perm; TF_ASSERT_OK(FindNodeByName(result.get(), "tr0")->input_tensor(1, &tr0_perm)); OutputTensor tr1_perm; TF_ASSERT_OK(FindNodeByName(result.get(), "tr1")->input_tensor(1, &tr1_perm)); EXPECT_NE(tr0_perm.node, tr1_perm.node); } TEST(CloneConstantsForBetterClusteringTest, DontCloneNonHostConstants) { Scope root = Scope::NewRootScope().ExitOnError(); Scope on_gpu = root.WithAssignedDevice(kGPU).WithDevice(kGPU); Output in0 = ops::Placeholder(on_gpu.WithOpName("in0"), DT_FLOAT); Output in1 = ops::Placeholder(on_gpu.WithOpName("in1"), DT_FLOAT); Output perm = ops::Const(on_gpu.WithOpName("perm"), {3, 1, 2, 0}); { Output tr0 = ops::Transpose(on_gpu.WithOpName("tr0"), in0, perm); Output tr1 = ops::Transpose(on_gpu.WithOpName("tr1"), in1, perm); } std::unique_ptr<Graph> result; TF_ASSERT_OK(CloneConstantsForBetterClustering(root, &result)); OutputTensor tr0_perm; TF_ASSERT_OK(FindNodeByName(result.get(), "tr0")->input_tensor(1, &tr0_perm)); OutputTensor tr1_perm; TF_ASSERT_OK(FindNodeByName(result.get(), "tr1")->input_tensor(1, &tr1_perm)); EXPECT_EQ(tr0_perm.node, tr1_perm.node); } TEST(CloneConstantsForBetterClusteringTest, DontCloneLargeConstants) { Scope root = Scope::NewRootScope().ExitOnError(); Scope on_gpu = root.WithAssignedDevice(kGPU).WithDevice(kGPU); Scope on_cpu = root.WithAssignedDevice(kCPU).WithDevice(kCPU); Output in0 = ops::Placeholder(on_gpu.WithOpName("in0"), DT_FLOAT); Output in1 = ops::Placeholder(on_gpu.WithOpName("in1"), DT_FLOAT); Output perm = ops::Const( on_cpu.WithOpName("perm"), {17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}); { Output tr0 = ops::Transpose(on_gpu.WithOpName("tr0"), in0, perm); Output tr1 = ops::Transpose(on_gpu.WithOpName("tr1"), in1, perm); } std::unique_ptr<Graph> result; TF_ASSERT_OK(CloneConstantsForBetterClustering(root, &result)); OutputTensor tr0_perm; TF_ASSERT_OK(FindNodeByName(result.get(), "tr0")->input_tensor(1, &tr0_perm)); OutputTensor tr1_perm; TF_ASSERT_OK(FindNodeByName(result.get(), "tr1")->input_tensor(1, &tr1_perm)); EXPECT_EQ(tr0_perm.node, tr1_perm.node); } TEST(CloneConstantsForBetterClusteringTest, InplaceOps) { Scope root = Scope::NewRootScope().ExitOnError(); Scope on_gpu = root.WithAssignedDevice(kGPU).WithDevice(kGPU); Scope on_cpu = root.WithAssignedDevice(kCPU).WithDevice(kCPU); Output in0 = ops::Placeholder(on_gpu.WithOpName("in0"), DT_FLOAT); Output in1 = ops::Placeholder(on_gpu.WithOpName("in1"), DT_FLOAT); Output perm = ops::Const(on_cpu.WithOpName("perm"), {3, 1, 2, 0}); { Output tr0 = ops::Transpose(on_gpu.WithOpName("tr0"), in0, perm); Output tr1 = ops::Transpose(on_gpu.WithOpName("tr1"), in1, perm); } Output in_place_add = ops::InplaceAdd(on_cpu.WithOpName("tr0"), perm, ops::Placeholder(on_cpu.WithOpName("i"), DT_INT32), perm); std::unique_ptr<Graph> result; TF_ASSERT_OK(CloneConstantsForBetterClustering(root, &result)); OutputTensor tr0_perm; TF_ASSERT_OK(FindNodeByName(result.get(), "tr0")->input_tensor(1, &tr0_perm)); OutputTensor tr1_perm; TF_ASSERT_OK(FindNodeByName(result.get(), "tr1")->input_tensor(1, &tr1_perm)); EXPECT_EQ(tr0_perm.node, tr1_perm.node); } } // namespace } // namespace tensorflow
[ "v-grniki@microsoft.com" ]
v-grniki@microsoft.com
01c243cfaca7d5887fcce46b74cb6dc1d53a14cc
802e71f0fba696021f7e9e2bf11fdd7e72e48529
/project/framework/Source/Util/ShapeX.cpp
6716fb15f1a1296aaca0559ea8ef2876f1987dd4
[]
no_license
Supreeth55/Metronome
7754e303dbe4c02282f865b2331865deaa19202a
244a3f1b61a441ab3565137e32b7af3158e8373f
refs/heads/master
2020-12-20T02:57:31.338973
2020-01-24T04:36:43
2020-01-24T04:36:43
235,939,199
0
0
null
null
null
null
UTF-8
C++
false
false
972
cpp
/** * @file ShapeX.h * @author Romil Tendulkar * @date 10/22/2019 * @brief This file implements the shape classes that are used for collision detection * Copyright (C) 2019 DigiPen Institute of Technology. Reproduction or disclosure of this file or its contents without the prior written consent of DigiPen Institute of Technology is prohibited. */ #include "../pch.h" #include "ShapeX.h" ShapeX::ShapeX() { } /** Initializes the type and the owner body of the shape \param pOwner | Pointer to the body that the shape is initialized for \param ptype | enum for the type of shape */ ShapeX::ShapeX(Body* pOwner,SHAPE_TYPE ptype) { type = ptype; pOwnerBody = pOwner; } /** initializes a AABB shape object \param pOwner | Pointer to the body that the shape is initialized for */ ShapeAABB::ShapeAABB(Body* pOwner) : ShapeX(pOwner,SHAPE_AABB) { mTop = mBottom = mLeft = mRight = mOut = mIn = 0; } ShapeAABB::ShapeAABB() { } ShapeAABB::~ShapeAABB() { }
[ "58317818+Supreeth55@users.noreply.github.com" ]
58317818+Supreeth55@users.noreply.github.com
a70b3a501a3203ad2271f55db077834dd084f1a0
333d2817fe023dc6b25f1669023fcd40dea54bb7
/samples/nanovg/src/nanovg/demo.cpp
2f93e2826e21b5506eccc586f0dff92028699913
[]
no_license
jaune/hope
48f9d8a67f0956e60bb02e0827eb867918ca2076
97a3ecddfdb3119cfbfd4fe693ba0b9c9ba64953
refs/heads/master
2021-01-21T06:59:09.610369
2015-05-22T11:16:09
2015-05-22T11:16:09
35,205,122
0
0
null
null
null
null
UTF-8
C++
false
false
30,766
cpp
#include "demo.h" #include "asset/asset.h" #include <stdio.h> #include <string.h> #include <math.h> #include <GLES2/gl2.h> #include "nanovg.h" #if defined(_MSC_VER) && _MSC_VER >= 1400 #define _CRT_SECURE_NO_WARNINGS // suppress warnings about fopen() #pragma warning(push) #pragma warning(disable:4996) // suppress even more warnings about fopen() #endif #ifdef _MSC_VER #define snprintf _snprintf #elif !defined(__MINGW32__) #include <iconv.h> #endif #define ICON_SEARCH 0x1F50D #define ICON_CIRCLED_CROSS 0x2716 #define ICON_CHEVRON_RIGHT 0xE75E #define ICON_CHECK 0x2713 #define ICON_LOGIN 0xE740 #define ICON_TRASH 0xE729 //static float minf(float a, float b) { return a < b ? a : b; } static float maxf(float a, float b) { return a > b ? a : b; } //static float absf(float a) { return a >= 0.0f ? a : -a; } static float clampf(float a, float mn, float mx) { return a < mn ? mn : (a > mx ? mx : a); } // Returns 1 if col.rgba is 0.0f,0.0f,0.0f,0.0f, 0 otherwise int isBlack(NVGcolor col) { if( col.r == 0.0f && col.g == 0.0f && col.b == 0.0f && col.a == 0.0f ) { return 1; } return 0; } static char* cpToUTF8(int cp, char* str) { int n = 0; if (cp < 0x80) n = 1; else if (cp < 0x800) n = 2; else if (cp < 0x10000) n = 3; else if (cp < 0x200000) n = 4; else if (cp < 0x4000000) n = 5; else if (cp <= 0x7fffffff) n = 6; str[n] = '\0'; switch (n) { case 6: str[5] = 0x80 | (cp & 0x3f); cp = cp >> 6; cp |= 0x4000000; case 5: str[4] = 0x80 | (cp & 0x3f); cp = cp >> 6; cp |= 0x200000; case 4: str[3] = 0x80 | (cp & 0x3f); cp = cp >> 6; cp |= 0x10000; case 3: str[2] = 0x80 | (cp & 0x3f); cp = cp >> 6; cp |= 0x800; case 2: str[1] = 0x80 | (cp & 0x3f); cp = cp >> 6; cp |= 0xc0; case 1: str[0] = cp; } return str; } void drawWindow(NVGcontext* vg, const char* title, float x, float y, float w, float h) { float cornerRadius = 3.0f; NVGpaint shadowPaint; NVGpaint headerPaint; nvgSave(vg); // nvgClearState(vg); // Window nvgBeginPath(vg); nvgRoundedRect(vg, x,y, w,h, cornerRadius); nvgFillColor(vg, nvgRGBA(28,30,34,192)); // nvgFillColor(vg, nvgRGBA(0,0,0,128)); nvgFill(vg); // Drop shadow shadowPaint = nvgBoxGradient(vg, x,y+2, w,h, cornerRadius*2, 10, nvgRGBA(0,0,0,128), nvgRGBA(0,0,0,0)); nvgBeginPath(vg); nvgRect(vg, x-10,y-10, w+20,h+30); nvgRoundedRect(vg, x,y, w,h, cornerRadius); nvgPathWinding(vg, NVG_HOLE); nvgFillPaint(vg, shadowPaint); nvgFill(vg); // Header headerPaint = nvgLinearGradient(vg, x,y,x,y+15, nvgRGBA(255,255,255,8), nvgRGBA(0,0,0,16)); nvgBeginPath(vg); nvgRoundedRect(vg, x+1,y+1, w-2,30, cornerRadius-1); nvgFillPaint(vg, headerPaint); nvgFill(vg); nvgBeginPath(vg); nvgMoveTo(vg, x+0.5f, y+0.5f+30); nvgLineTo(vg, x+0.5f+w-1, y+0.5f+30); nvgStrokeColor(vg, nvgRGBA(0,0,0,32)); nvgStroke(vg); nvgFontSize(vg, 18.0f); nvgFontFace(vg, "sans-bold"); nvgTextAlign(vg,NVG_ALIGN_CENTER|NVG_ALIGN_MIDDLE); nvgFontBlur(vg,2); nvgFillColor(vg, nvgRGBA(0,0,0,128)); nvgText(vg, x+w/2,y+16+1, title, NULL); nvgFontBlur(vg,0); nvgFillColor(vg, nvgRGBA(220,220,220,160)); nvgText(vg, x+w/2,y+16, title, NULL); nvgRestore(vg); } void drawSearchBox(NVGcontext* vg, const char* text, float x, float y, float w, float h) { NVGpaint bg; char icon[8]; float cornerRadius = h/2-1; // Edit bg = nvgBoxGradient(vg, x,y+1.5f, w,h, h/2,5, nvgRGBA(0,0,0,16), nvgRGBA(0,0,0,92)); nvgBeginPath(vg); nvgRoundedRect(vg, x,y, w,h, cornerRadius); nvgFillPaint(vg, bg); nvgFill(vg); /* nvgBeginPath(vg); nvgRoundedRect(vg, x+0.5f,y+0.5f, w-1,h-1, cornerRadius-0.5f); nvgStrokeColor(vg, nvgRGBA(0,0,0,48)); nvgStroke(vg);*/ nvgFontSize(vg, h*1.3f); nvgFontFace(vg, "icons"); nvgFillColor(vg, nvgRGBA(255,255,255,64)); nvgTextAlign(vg,NVG_ALIGN_CENTER|NVG_ALIGN_MIDDLE); nvgText(vg, x+h*0.55f, y+h*0.55f, cpToUTF8(ICON_SEARCH,icon), NULL); nvgFontSize(vg, 20.0f); nvgFontFace(vg, "sans"); nvgFillColor(vg, nvgRGBA(255,255,255,32)); nvgTextAlign(vg,NVG_ALIGN_LEFT|NVG_ALIGN_MIDDLE); nvgText(vg, x+h*1.05f,y+h*0.5f,text, NULL); nvgFontSize(vg, h*1.3f); nvgFontFace(vg, "icons"); nvgFillColor(vg, nvgRGBA(255,255,255,32)); nvgTextAlign(vg,NVG_ALIGN_CENTER|NVG_ALIGN_MIDDLE); nvgText(vg, x+w-h*0.55f, y+h*0.55f, cpToUTF8(ICON_CIRCLED_CROSS,icon), NULL); } void drawDropDown(NVGcontext* vg, const char* text, float x, float y, float w, float h) { NVGpaint bg; char icon[8]; float cornerRadius = 4.0f; bg = nvgLinearGradient(vg, x,y,x,y+h, nvgRGBA(255,255,255,16), nvgRGBA(0,0,0,16)); nvgBeginPath(vg); nvgRoundedRect(vg, x+1,y+1, w-2,h-2, cornerRadius-1); nvgFillPaint(vg, bg); nvgFill(vg); nvgBeginPath(vg); nvgRoundedRect(vg, x+0.5f,y+0.5f, w-1,h-1, cornerRadius-0.5f); nvgStrokeColor(vg, nvgRGBA(0,0,0,48)); nvgStroke(vg); nvgFontSize(vg, 20.0f); nvgFontFace(vg, "sans"); nvgFillColor(vg, nvgRGBA(255,255,255,160)); nvgTextAlign(vg,NVG_ALIGN_LEFT|NVG_ALIGN_MIDDLE); nvgText(vg, x+h*0.3f,y+h*0.5f,text, NULL); nvgFontSize(vg, h*1.3f); nvgFontFace(vg, "icons"); nvgFillColor(vg, nvgRGBA(255,255,255,64)); nvgTextAlign(vg,NVG_ALIGN_CENTER|NVG_ALIGN_MIDDLE); nvgText(vg, x+w-h*0.5f, y+h*0.5f, cpToUTF8(ICON_CHEVRON_RIGHT,icon), NULL); } void drawLabel(NVGcontext* vg, const char* text, float x, float y, float w, float h) { NVG_NOTUSED(w); nvgFontSize(vg, 18.0f); nvgFontFace(vg, "sans"); nvgFillColor(vg, nvgRGBA(255,255,255,128)); nvgTextAlign(vg,NVG_ALIGN_LEFT|NVG_ALIGN_MIDDLE); nvgText(vg, x,y+h*0.5f,text, NULL); } void drawEditBoxBase(NVGcontext* vg, float x, float y, float w, float h) { NVGpaint bg; // Edit bg = nvgBoxGradient(vg, x+1,y+1+1.5f, w-2,h-2, 3,4, nvgRGBA(255,255,255,32), nvgRGBA(32,32,32,32)); nvgBeginPath(vg); nvgRoundedRect(vg, x+1,y+1, w-2,h-2, 4-1); nvgFillPaint(vg, bg); nvgFill(vg); nvgBeginPath(vg); nvgRoundedRect(vg, x+0.5f,y+0.5f, w-1,h-1, 4-0.5f); nvgStrokeColor(vg, nvgRGBA(0,0,0,48)); nvgStroke(vg); } void drawEditBox(NVGcontext* vg, const char* text, float x, float y, float w, float h) { drawEditBoxBase(vg, x,y, w,h); nvgFontSize(vg, 20.0f); nvgFontFace(vg, "sans"); nvgFillColor(vg, nvgRGBA(255,255,255,64)); nvgTextAlign(vg,NVG_ALIGN_LEFT|NVG_ALIGN_MIDDLE); nvgText(vg, x+h*0.3f,y+h*0.5f,text, NULL); } void drawEditBoxNum(NVGcontext* vg, const char* text, const char* units, float x, float y, float w, float h) { float uw; drawEditBoxBase(vg, x,y, w,h); uw = nvgTextBounds(vg, 0,0, units, NULL, NULL); nvgFontSize(vg, 18.0f); nvgFontFace(vg, "sans"); nvgFillColor(vg, nvgRGBA(255,255,255,64)); nvgTextAlign(vg,NVG_ALIGN_RIGHT|NVG_ALIGN_MIDDLE); nvgText(vg, x+w-h*0.3f,y+h*0.5f,units, NULL); nvgFontSize(vg, 20.0f); nvgFontFace(vg, "sans"); nvgFillColor(vg, nvgRGBA(255,255,255,128)); nvgTextAlign(vg,NVG_ALIGN_RIGHT|NVG_ALIGN_MIDDLE); nvgText(vg, x+w-uw-h*0.5f,y+h*0.5f,text, NULL); } void drawCheckBox(NVGcontext* vg, const char* text, float x, float y, float w, float h) { NVGpaint bg; char icon[8]; NVG_NOTUSED(w); nvgFontSize(vg, 18.0f); nvgFontFace(vg, "sans"); nvgFillColor(vg, nvgRGBA(255,255,255,160)); nvgTextAlign(vg,NVG_ALIGN_LEFT|NVG_ALIGN_MIDDLE); nvgText(vg, x+28,y+h*0.5f,text, NULL); bg = nvgBoxGradient(vg, x+1,y+(int)(h*0.5f)-9+1, 18,18, 3,3, nvgRGBA(0,0,0,32), nvgRGBA(0,0,0,92)); nvgBeginPath(vg); nvgRoundedRect(vg, x+1,y+(int)(h*0.5f)-9, 18,18, 3); nvgFillPaint(vg, bg); nvgFill(vg); nvgFontSize(vg, 40); nvgFontFace(vg, "icons"); nvgFillColor(vg, nvgRGBA(255,255,255,128)); nvgTextAlign(vg,NVG_ALIGN_CENTER|NVG_ALIGN_MIDDLE); nvgText(vg, x+9+2, y+h*0.5f, cpToUTF8(ICON_CHECK,icon), NULL); } void drawButton(NVGcontext* vg, int preicon, const char* text, float x, float y, float w, float h, NVGcolor col) { NVGpaint bg; char icon[8]; float cornerRadius = 4.0f; float tw = 0, iw = 0; bg = nvgLinearGradient(vg, x,y,x,y+h, nvgRGBA(255,255,255,isBlack(col)?16:32), nvgRGBA(0,0,0,isBlack(col)?16:32)); nvgBeginPath(vg); nvgRoundedRect(vg, x+1,y+1, w-2,h-2, cornerRadius-1); if (!isBlack(col)) { nvgFillColor(vg, col); nvgFill(vg); } nvgFillPaint(vg, bg); nvgFill(vg); nvgBeginPath(vg); nvgRoundedRect(vg, x+0.5f,y+0.5f, w-1,h-1, cornerRadius-0.5f); nvgStrokeColor(vg, nvgRGBA(0,0,0,48)); nvgStroke(vg); nvgFontSize(vg, 20.0f); nvgFontFace(vg, "sans-bold"); tw = nvgTextBounds(vg, 0,0, text, NULL, NULL); if (preicon != 0) { nvgFontSize(vg, h*1.3f); nvgFontFace(vg, "icons"); iw = nvgTextBounds(vg, 0,0, cpToUTF8(preicon,icon), NULL, NULL); iw += h*0.15f; } if (preicon != 0) { nvgFontSize(vg, h*1.3f); nvgFontFace(vg, "icons"); nvgFillColor(vg, nvgRGBA(255,255,255,96)); nvgTextAlign(vg,NVG_ALIGN_LEFT|NVG_ALIGN_MIDDLE); nvgText(vg, x+w*0.5f-tw*0.5f-iw*0.75f, y+h*0.5f, cpToUTF8(preicon,icon), NULL); } nvgFontSize(vg, 20.0f); nvgFontFace(vg, "sans-bold"); nvgTextAlign(vg,NVG_ALIGN_LEFT|NVG_ALIGN_MIDDLE); nvgFillColor(vg, nvgRGBA(0,0,0,160)); nvgText(vg, x+w*0.5f-tw*0.5f+iw*0.25f,y+h*0.5f-1,text, NULL); nvgFillColor(vg, nvgRGBA(255,255,255,160)); nvgText(vg, x+w*0.5f-tw*0.5f+iw*0.25f,y+h*0.5f,text, NULL); } void drawSlider(NVGcontext* vg, float pos, float x, float y, float w, float h) { NVGpaint bg, knob; float cy = y+(int)(h*0.5f); float kr = (int)(h*0.25f); nvgSave(vg); // nvgClearState(vg); // Slot bg = nvgBoxGradient(vg, x,cy-2+1, w,4, 2,2, nvgRGBA(0,0,0,32), nvgRGBA(0,0,0,128)); nvgBeginPath(vg); nvgRoundedRect(vg, x,cy-2, w,4, 2); nvgFillPaint(vg, bg); nvgFill(vg); // Knob Shadow bg = nvgRadialGradient(vg, x+(int)(pos*w),cy+1, kr-3,kr+3, nvgRGBA(0,0,0,64), nvgRGBA(0,0,0,0)); nvgBeginPath(vg); nvgRect(vg, x+(int)(pos*w)-kr-5,cy-kr-5,kr*2+5+5,kr*2+5+5+3); nvgCircle(vg, x+(int)(pos*w),cy, kr); nvgPathWinding(vg, NVG_HOLE); nvgFillPaint(vg, bg); nvgFill(vg); // Knob knob = nvgLinearGradient(vg, x,cy-kr,x,cy+kr, nvgRGBA(255,255,255,16), nvgRGBA(0,0,0,16)); nvgBeginPath(vg); nvgCircle(vg, x+(int)(pos*w),cy, kr-1); nvgFillColor(vg, nvgRGBA(40,43,48,255)); nvgFill(vg); nvgFillPaint(vg, knob); nvgFill(vg); nvgBeginPath(vg); nvgCircle(vg, x+(int)(pos*w),cy, kr-0.5f); nvgStrokeColor(vg, nvgRGBA(0,0,0,92)); nvgStroke(vg); nvgRestore(vg); } void drawEyes(NVGcontext* vg, float x, float y, float w, float h, float mx, float my, float t) { NVGpaint gloss, bg; float ex = w *0.23f; float ey = h * 0.5f; float lx = x + ex; float ly = y + ey; float rx = x + w - ex; float ry = y + ey; float dx,dy,d; float br = (ex < ey ? ex : ey) * 0.5f; float blink = 1 - pow(sinf(t*0.5f),200)*0.8f; bg = nvgLinearGradient(vg, x,y+h*0.5f,x+w*0.1f,y+h, nvgRGBA(0,0,0,32), nvgRGBA(0,0,0,16)); nvgBeginPath(vg); nvgEllipse(vg, lx+3.0f,ly+16.0f, ex,ey); nvgEllipse(vg, rx+3.0f,ry+16.0f, ex,ey); nvgFillPaint(vg, bg); nvgFill(vg); bg = nvgLinearGradient(vg, x,y+h*0.25f,x+w*0.1f,y+h, nvgRGBA(220,220,220,255), nvgRGBA(128,128,128,255)); nvgBeginPath(vg); nvgEllipse(vg, lx,ly, ex,ey); nvgEllipse(vg, rx,ry, ex,ey); nvgFillPaint(vg, bg); nvgFill(vg); dx = (mx - rx) / (ex * 10); dy = (my - ry) / (ey * 10); d = sqrtf(dx*dx+dy*dy); if (d > 1.0f) { dx /= d; dy /= d; } dx *= ex*0.4f; dy *= ey*0.5f; nvgBeginPath(vg); nvgEllipse(vg, lx+dx,ly+dy+ey*0.25f*(1-blink), br,br*blink); nvgFillColor(vg, nvgRGBA(32,32,32,255)); nvgFill(vg); dx = (mx - rx) / (ex * 10); dy = (my - ry) / (ey * 10); d = sqrtf(dx*dx+dy*dy); if (d > 1.0f) { dx /= d; dy /= d; } dx *= ex*0.4f; dy *= ey*0.5f; nvgBeginPath(vg); nvgEllipse(vg, rx+dx,ry+dy+ey*0.25f*(1-blink), br,br*blink); nvgFillColor(vg, nvgRGBA(32,32,32,255)); nvgFill(vg); gloss = nvgRadialGradient(vg, lx-ex*0.25f,ly-ey*0.5f, ex*0.1f,ex*0.75f, nvgRGBA(255,255,255,128), nvgRGBA(255,255,255,0)); nvgBeginPath(vg); nvgEllipse(vg, lx,ly, ex,ey); nvgFillPaint(vg, gloss); nvgFill(vg); gloss = nvgRadialGradient(vg, rx-ex*0.25f,ry-ey*0.5f, ex*0.1f,ex*0.75f, nvgRGBA(255,255,255,128), nvgRGBA(255,255,255,0)); nvgBeginPath(vg); nvgEllipse(vg, rx,ry, ex,ey); nvgFillPaint(vg, gloss); nvgFill(vg); } void drawGraph(NVGcontext* vg, float x, float y, float w, float h, float t) { NVGpaint bg; float samples[6]; float sx[6], sy[6]; float dx = w/5.0f; int i; samples[0] = (1+sinf(t*1.2345f+cosf(t*0.33457f)*0.44f))*0.5f; samples[1] = (1+sinf(t*0.68363f+cosf(t*1.3f)*1.55f))*0.5f; samples[2] = (1+sinf(t*1.1642f+cosf(t*0.33457)*1.24f))*0.5f; samples[3] = (1+sinf(t*0.56345f+cosf(t*1.63f)*0.14f))*0.5f; samples[4] = (1+sinf(t*1.6245f+cosf(t*0.254f)*0.3f))*0.5f; samples[5] = (1+sinf(t*0.345f+cosf(t*0.03f)*0.6f))*0.5f; for (i = 0; i < 6; i++) { sx[i] = x+i*dx; sy[i] = y+h*samples[i]*0.8f; } // Graph background bg = nvgLinearGradient(vg, x,y,x,y+h, nvgRGBA(0,160,192,0), nvgRGBA(0,160,192,64)); nvgBeginPath(vg); nvgMoveTo(vg, sx[0], sy[0]); for (i = 1; i < 6; i++) nvgBezierTo(vg, sx[i-1]+dx*0.5f,sy[i-1], sx[i]-dx*0.5f,sy[i], sx[i],sy[i]); nvgLineTo(vg, x+w, y+h); nvgLineTo(vg, x, y+h); nvgFillPaint(vg, bg); nvgFill(vg); // Graph line nvgBeginPath(vg); nvgMoveTo(vg, sx[0], sy[0]+2); for (i = 1; i < 6; i++) nvgBezierTo(vg, sx[i-1]+dx*0.5f,sy[i-1]+2, sx[i]-dx*0.5f,sy[i]+2, sx[i],sy[i]+2); nvgStrokeColor(vg, nvgRGBA(0,0,0,32)); nvgStrokeWidth(vg, 3.0f); nvgStroke(vg); nvgBeginPath(vg); nvgMoveTo(vg, sx[0], sy[0]); for (i = 1; i < 6; i++) nvgBezierTo(vg, sx[i-1]+dx*0.5f,sy[i-1], sx[i]-dx*0.5f,sy[i], sx[i],sy[i]); nvgStrokeColor(vg, nvgRGBA(0,160,192,255)); nvgStrokeWidth(vg, 3.0f); nvgStroke(vg); // Graph sample pos for (i = 0; i < 6; i++) { bg = nvgRadialGradient(vg, sx[i],sy[i]+2, 3.0f,8.0f, nvgRGBA(0,0,0,32), nvgRGBA(0,0,0,0)); nvgBeginPath(vg); nvgRect(vg, sx[i]-10, sy[i]-10+2, 20,20); nvgFillPaint(vg, bg); nvgFill(vg); } nvgBeginPath(vg); for (i = 0; i < 6; i++) nvgCircle(vg, sx[i], sy[i], 4.0f); nvgFillColor(vg, nvgRGBA(0,160,192,255)); nvgFill(vg); nvgBeginPath(vg); for (i = 0; i < 6; i++) nvgCircle(vg, sx[i], sy[i], 2.0f); nvgFillColor(vg, nvgRGBA(220,220,220,255)); nvgFill(vg); nvgStrokeWidth(vg, 1.0f); } void drawSpinner(NVGcontext* vg, float cx, float cy, float r, float t) { float a0 = 0.0f + t*6; float a1 = NVG_PI + t*6; float r0 = r; float r1 = r * 0.75f; float ax,ay, bx,by; NVGpaint paint; nvgSave(vg); nvgBeginPath(vg); nvgArc(vg, cx,cy, r0, a0, a1, NVG_CW); nvgArc(vg, cx,cy, r1, a1, a0, NVG_CCW); nvgClosePath(vg); ax = cx + cosf(a0) * (r0+r1)*0.5f; ay = cy + sinf(a0) * (r0+r1)*0.5f; bx = cx + cosf(a1) * (r0+r1)*0.5f; by = cy + sinf(a1) * (r0+r1)*0.5f; paint = nvgLinearGradient(vg, ax,ay, bx,by, nvgRGBA(0,0,0,0), nvgRGBA(0,0,0,128)); nvgFillPaint(vg, paint); nvgFill(vg); nvgRestore(vg); } void drawThumbnails(NVGcontext* vg, float x, float y, float w, float h, const int* images, int nimages, float t) { float cornerRadius = 3.0f; NVGpaint shadowPaint, imgPaint, fadePaint; float ix,iy,iw,ih; float thumb = 60.0f; float arry = 30.5f; int imgw, imgh; float stackh = (nimages/2) * (thumb+10) + 10; int i; float u = (1+cosf(t*0.5f))*0.5f; float u2 = (1-cosf(t*0.2f))*0.5f; float scrollh, dv; nvgSave(vg); // nvgClearState(vg); // Drop shadow shadowPaint = nvgBoxGradient(vg, x,y+4, w,h, cornerRadius*2, 20, nvgRGBA(0,0,0,128), nvgRGBA(0,0,0,0)); nvgBeginPath(vg); nvgRect(vg, x-10,y-10, w+20,h+30); nvgRoundedRect(vg, x,y, w,h, cornerRadius); nvgPathWinding(vg, NVG_HOLE); nvgFillPaint(vg, shadowPaint); nvgFill(vg); // Window nvgBeginPath(vg); nvgRoundedRect(vg, x,y, w,h, cornerRadius); nvgMoveTo(vg, x-10,y+arry); nvgLineTo(vg, x+1,y+arry-11); nvgLineTo(vg, x+1,y+arry+11); nvgFillColor(vg, nvgRGBA(200,200,200,255)); nvgFill(vg); nvgSave(vg); nvgScissor(vg, x,y,w,h); nvgTranslate(vg, 0, -(stackh - h)*u); dv = 1.0f / (float)(nimages-1); for (i = 0; i < nimages; i++) { float tx, ty, v, a; tx = x+10; ty = y+10; tx += (i%2) * (thumb+10); ty += (i/2) * (thumb+10); nvgImageSize(vg, images[i], &imgw, &imgh); if (imgw < imgh) { iw = thumb; ih = iw * (float)imgh/(float)imgw; ix = 0; iy = -(ih-thumb)*0.5f; } else { ih = thumb; iw = ih * (float)imgw/(float)imgh; ix = -(iw-thumb)*0.5f; iy = 0; } v = i * dv; a = clampf((u2-v) / dv, 0, 1); if (a < 1.0f) drawSpinner(vg, tx+thumb/2,ty+thumb/2, thumb*0.25f, t); imgPaint = nvgImagePattern(vg, tx+ix, ty+iy, iw,ih, 0.0f/180.0f*NVG_PI, images[i], a); nvgBeginPath(vg); nvgRoundedRect(vg, tx,ty, thumb,thumb, 5); nvgFillPaint(vg, imgPaint); nvgFill(vg); shadowPaint = nvgBoxGradient(vg, tx-1,ty, thumb+2,thumb+2, 5, 3, nvgRGBA(0,0,0,128), nvgRGBA(0,0,0,0)); nvgBeginPath(vg); nvgRect(vg, tx-5,ty-5, thumb+10,thumb+10); nvgRoundedRect(vg, tx,ty, thumb,thumb, 6); nvgPathWinding(vg, NVG_HOLE); nvgFillPaint(vg, shadowPaint); nvgFill(vg); nvgBeginPath(vg); nvgRoundedRect(vg, tx+0.5f,ty+0.5f, thumb-1,thumb-1, 4-0.5f); nvgStrokeWidth(vg,1.0f); nvgStrokeColor(vg, nvgRGBA(255,255,255,192)); nvgStroke(vg); } nvgRestore(vg); // Hide fades fadePaint = nvgLinearGradient(vg, x,y,x,y+6, nvgRGBA(200,200,200,255), nvgRGBA(200,200,200,0)); nvgBeginPath(vg); nvgRect(vg, x+4,y,w-8,6); nvgFillPaint(vg, fadePaint); nvgFill(vg); fadePaint = nvgLinearGradient(vg, x,y+h,x,y+h-6, nvgRGBA(200,200,200,255), nvgRGBA(200,200,200,0)); nvgBeginPath(vg); nvgRect(vg, x+4,y+h-6,w-8,6); nvgFillPaint(vg, fadePaint); nvgFill(vg); // Scroll bar shadowPaint = nvgBoxGradient(vg, x+w-12+1,y+4+1, 8,h-8, 3,4, nvgRGBA(0,0,0,32), nvgRGBA(0,0,0,92)); nvgBeginPath(vg); nvgRoundedRect(vg, x+w-12,y+4, 8,h-8, 3); nvgFillPaint(vg, shadowPaint); // nvgFillColor(vg, nvgRGBA(255,0,0,128)); nvgFill(vg); scrollh = (h/stackh) * (h-8); shadowPaint = nvgBoxGradient(vg, x+w-12-1,y+4+(h-8-scrollh)*u-1, 8,scrollh, 3,4, nvgRGBA(220,220,220,255), nvgRGBA(128,128,128,255)); nvgBeginPath(vg); nvgRoundedRect(vg, x+w-12+1,y+4+1 + (h-8-scrollh)*u, 8-2,scrollh-2, 2); nvgFillPaint(vg, shadowPaint); // nvgFillColor(vg, nvgRGBA(0,0,0,128)); nvgFill(vg); nvgRestore(vg); } void drawColorwheel(NVGcontext* vg, float x, float y, float w, float h, float t) { int i; float r0, r1, ax,ay, bx,by, cx,cy, aeps, r; float hue = sinf(t * 0.12f); NVGpaint paint; nvgSave(vg); /* nvgBeginPath(vg); nvgRect(vg, x,y,w,h); nvgFillColor(vg, nvgRGBA(255,0,0,128)); nvgFill(vg);*/ cx = x + w*0.5f; cy = y + h*0.5f; r1 = (w < h ? w : h) * 0.5f - 5.0f; r0 = r1 - 20.0f; aeps = 0.5f / r1; // half a pixel arc length in radians (2pi cancels out). for (i = 0; i < 6; i++) { float a0 = (float)i / 6.0f * NVG_PI * 2.0f - aeps; float a1 = (float)(i+1.0f) / 6.0f * NVG_PI * 2.0f + aeps; nvgBeginPath(vg); nvgArc(vg, cx,cy, r0, a0, a1, NVG_CW); nvgArc(vg, cx,cy, r1, a1, a0, NVG_CCW); nvgClosePath(vg); ax = cx + cosf(a0) * (r0+r1)*0.5f; ay = cy + sinf(a0) * (r0+r1)*0.5f; bx = cx + cosf(a1) * (r0+r1)*0.5f; by = cy + sinf(a1) * (r0+r1)*0.5f; paint = nvgLinearGradient(vg, ax,ay, bx,by, nvgHSLA(a0/(NVG_PI*2),1.0f,0.55f,255), nvgHSLA(a1/(NVG_PI*2),1.0f,0.55f,255)); nvgFillPaint(vg, paint); nvgFill(vg); } nvgBeginPath(vg); nvgCircle(vg, cx,cy, r0-0.5f); nvgCircle(vg, cx,cy, r1+0.5f); nvgStrokeColor(vg, nvgRGBA(0,0,0,64)); nvgStrokeWidth(vg, 1.0f); nvgStroke(vg); // Selector nvgSave(vg); nvgTranslate(vg, cx,cy); nvgRotate(vg, hue*NVG_PI*2); // Marker on nvgStrokeWidth(vg, 2.0f); nvgBeginPath(vg); nvgRect(vg, r0-1,-3,r1-r0+2,6); nvgStrokeColor(vg, nvgRGBA(255,255,255,192)); nvgStroke(vg); paint = nvgBoxGradient(vg, r0-3,-5,r1-r0+6,10, 2,4, nvgRGBA(0,0,0,128), nvgRGBA(0,0,0,0)); nvgBeginPath(vg); nvgRect(vg, r0-2-10,-4-10,r1-r0+4+20,8+20); nvgRect(vg, r0-2,-4,r1-r0+4,8); nvgPathWinding(vg, NVG_HOLE); nvgFillPaint(vg, paint); nvgFill(vg); // Center triangle r = r0 - 6; ax = cosf(120.0f/180.0f*NVG_PI) * r; ay = sinf(120.0f/180.0f*NVG_PI) * r; bx = cosf(-120.0f/180.0f*NVG_PI) * r; by = sinf(-120.0f/180.0f*NVG_PI) * r; nvgBeginPath(vg); nvgMoveTo(vg, r,0); nvgLineTo(vg, ax,ay); nvgLineTo(vg, bx,by); nvgClosePath(vg); paint = nvgLinearGradient(vg, r,0, ax,ay, nvgHSLA(hue,1.0f,0.5f,255), nvgRGBA(255,255,255,255)); nvgFillPaint(vg, paint); nvgFill(vg); paint = nvgLinearGradient(vg, (r+ax)*0.5f,(0+ay)*0.5f, bx,by, nvgRGBA(0,0,0,0), nvgRGBA(0,0,0,255)); nvgFillPaint(vg, paint); nvgFill(vg); nvgStrokeColor(vg, nvgRGBA(0,0,0,64)); nvgStroke(vg); // Select circle on triangle ax = cosf(120.0f/180.0f*NVG_PI) * r*0.3f; ay = sinf(120.0f/180.0f*NVG_PI) * r*0.4f; nvgStrokeWidth(vg, 2.0f); nvgBeginPath(vg); nvgCircle(vg, ax,ay,5); nvgStrokeColor(vg, nvgRGBA(255,255,255,192)); nvgStroke(vg); paint = nvgRadialGradient(vg, ax,ay, 7,9, nvgRGBA(0,0,0,64), nvgRGBA(0,0,0,0)); nvgBeginPath(vg); nvgRect(vg, ax-20,ay-20,40,40); nvgCircle(vg, ax,ay,7); nvgPathWinding(vg, NVG_HOLE); nvgFillPaint(vg, paint); nvgFill(vg); nvgRestore(vg); nvgRestore(vg); } void drawLines(NVGcontext* vg, float x, float y, float w, float h, float t) { int i, j; float pad = 5.0f, s = w/9.0f - pad*2; float pts[4*2], fx, fy; int joins[3] = {NVG_MITER, NVG_ROUND, NVG_BEVEL}; int caps[3] = {NVG_BUTT, NVG_ROUND, NVG_SQUARE}; NVG_NOTUSED(h); nvgSave(vg); pts[0] = -s*0.25f + cosf(t*0.3f) * s*0.5f; pts[1] = sinf(t*0.3f) * s*0.5f; pts[2] = -s*0.25; pts[3] = 0; pts[4] = s*0.25f; pts[5] = 0; pts[6] = s*0.25f + cosf(-t*0.3f) * s*0.5f; pts[7] = sinf(-t*0.3f) * s*0.5f; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { fx = x + s*0.5f + (i*3+j)/9.0f*w + pad; fy = y - s*0.5f + pad; nvgLineCap(vg, caps[i]); nvgLineJoin(vg, joins[j]); nvgStrokeWidth(vg, s*0.3f); nvgStrokeColor(vg, nvgRGBA(0,0,0,160)); nvgBeginPath(vg); nvgMoveTo(vg, fx+pts[0], fy+pts[1]); nvgLineTo(vg, fx+pts[2], fy+pts[3]); nvgLineTo(vg, fx+pts[4], fy+pts[5]); nvgLineTo(vg, fx+pts[6], fy+pts[7]); nvgStroke(vg); nvgLineCap(vg, NVG_BUTT); nvgLineJoin(vg, NVG_BEVEL); nvgStrokeWidth(vg, 1.0f); nvgStrokeColor(vg, nvgRGBA(0,192,255,255)); nvgBeginPath(vg); nvgMoveTo(vg, fx+pts[0], fy+pts[1]); nvgLineTo(vg, fx+pts[2], fy+pts[3]); nvgLineTo(vg, fx+pts[4], fy+pts[5]); nvgLineTo(vg, fx+pts[6], fy+pts[7]); nvgStroke(vg); } } nvgRestore(vg); } int loadDemoData(NVGcontext* vg, DemoData* data) { ::hope::asset::Asset asset; int i; if (vg == NULL) return -1; for (i = 0; i < 12; i++) { char file[128]; snprintf(file, 128, "nanovg/images/image%d.jpg", i+1); asset = ::hope::asset::get(file); data->images[i] = nvgCreateImageMem(vg, 0, (unsigned char*)asset.pointer, asset.size); // data->images[i] = nvgCreateImage(vg, file, 0); if (data->images[i] == 0) { printf("Could not load %s.\n", file); return -1; } } asset = ::hope::asset::get("nanovg/entypo.ttf"); data->fontIcons = nvgCreateFontMem(vg, "icons", (unsigned char*)asset.pointer, asset.size, 0); // data->fontIcons = nvgCreateFont(vg, "icons", "nanovg/entypo.ttf"); if (data->fontIcons == -1) { printf("Could not add font icons.\n"); return -1; } asset = ::hope::asset::get("nanovg/Roboto-Regular.ttf"); data->fontNormal = nvgCreateFontMem(vg, "sans", (unsigned char*)asset.pointer, asset.size, 0); // data->fontNormal = nvgCreateFont(vg, "sans", "nanovg/Roboto-Regular.ttf"); if (data->fontNormal == -1) { printf("Could not add font italic.\n"); return -1; } asset = ::hope::asset::get("nanovg/Roboto-Regular.ttf"); data->fontBold = nvgCreateFontMem(vg, "sans-bold", (unsigned char*)asset.pointer, asset.size, 0); // data->fontBold = nvgCreateFont(vg, "sans-bold", "nanovg/Roboto-Bold.ttf"); if (data->fontBold == -1) { printf("Could not add font bold.\n"); return -1; } return 0; } void freeDemoData(NVGcontext* vg, DemoData* data) { int i; if (vg == NULL) return; for (i = 0; i < 12; i++) nvgDeleteImage(vg, data->images[i]); } void drawParagraph(NVGcontext* vg, float x, float y, float width, float height, float mx, float my) { NVGtextRow rows[3]; NVGglyphPosition glyphs[100]; const char* text = "This is longer chunk of text.\n \n Would have used lorem ipsum but she was busy jumping over the lazy dog with the fox and all the men who came to the aid of the party."; const char* start; const char* end; int nrows, i, nglyphs, j, lnum = 0; float lineh; float caretx, px; float bounds[4]; float a; float gx,gy; int gutter = 0; NVG_NOTUSED(height); nvgSave(vg); nvgFontSize(vg, 18.0f); nvgFontFace(vg, "sans"); nvgTextAlign(vg, NVG_ALIGN_LEFT|NVG_ALIGN_TOP); nvgTextMetrics(vg, NULL, NULL, &lineh); // The text break API can be used to fill a large buffer of rows, // or to iterate over the text just few lines (or just one) at a time. // The "next" variable of the last returned item tells where to continue. start = text; end = text + strlen(text); while ((nrows = nvgTextBreakLines(vg, start, end, width, rows, 3))) { for (i = 0; i < nrows; i++) { NVGtextRow* row = &rows[i]; int hit = mx > x && mx < (x+width) && my >= y && my < (y+lineh); nvgBeginPath(vg); nvgFillColor(vg, nvgRGBA(255,255,255,hit?64:16)); nvgRect(vg, x, y, row->width, lineh); nvgFill(vg); nvgFillColor(vg, nvgRGBA(255,255,255,255)); nvgText(vg, x, y, row->start, row->end); if (hit) { caretx = (mx < x+row->width/2) ? x : x+row->width; px = x; nglyphs = nvgTextGlyphPositions(vg, x, y, row->start, row->end, glyphs, 100); for (j = 0; j < nglyphs; j++) { float x0 = glyphs[j].x; float x1 = (j+1 < nglyphs) ? glyphs[j+1].x : x+row->width; float gx = x0 * 0.3f + x1 * 0.7f; if (mx >= px && mx < gx) caretx = glyphs[j].x; px = gx; } nvgBeginPath(vg); nvgFillColor(vg, nvgRGBA(255,192,0,255)); nvgRect(vg, caretx, y, 1, lineh); nvgFill(vg); gutter = lnum+1; gx = x - 10; gy = y + lineh/2; } lnum++; y += lineh; } // Keep going... start = rows[nrows-1].next; } if (gutter) { char txt[16]; snprintf(txt, sizeof(txt), "%d", gutter); nvgFontSize(vg, 13.0f); nvgTextAlign(vg, NVG_ALIGN_RIGHT|NVG_ALIGN_MIDDLE); nvgTextBounds(vg, gx,gy, txt, NULL, bounds); nvgBeginPath(vg); nvgFillColor(vg, nvgRGBA(255,192,0,255)); nvgRoundedRect(vg, (int)bounds[0]-4,(int)bounds[1]-2, (int)(bounds[2]-bounds[0])+8, (int)(bounds[3]-bounds[1])+4, ((int)(bounds[3]-bounds[1])+4)/2-1); nvgFill(vg); nvgFillColor(vg, nvgRGBA(32,32,32,255)); nvgText(vg, gx,gy, txt, NULL); } y += 20.0f; nvgFontSize(vg, 13.0f); nvgTextAlign(vg, NVG_ALIGN_LEFT|NVG_ALIGN_TOP); nvgTextLineHeight(vg, 1.2f); nvgTextBoxBounds(vg, x,y, 150, "Hover your mouse over the text to see calculated caret position.", NULL, bounds); // Fade the tooltip out when close to it. gx = fabsf((mx - (bounds[0]+bounds[2])*0.5f) / (bounds[0] - bounds[2])); gy = fabsf((my - (bounds[1]+bounds[3])*0.5f) / (bounds[1] - bounds[3])); a = maxf(gx, gy) - 0.5f; a = clampf(a, 0, 1); nvgGlobalAlpha(vg, a); nvgBeginPath(vg); nvgFillColor(vg, nvgRGBA(220,220,220,255)); nvgRoundedRect(vg, bounds[0]-2,bounds[1]-2, (int)(bounds[2]-bounds[0])+4, (int)(bounds[3]-bounds[1])+4, 3); px = (int)((bounds[2]+bounds[0])/2); nvgMoveTo(vg, px,bounds[1] - 10); nvgLineTo(vg, px+7,bounds[1]+1); nvgLineTo(vg, px-7,bounds[1]+1); nvgFill(vg); nvgFillColor(vg, nvgRGBA(0,0,0,220)); nvgTextBox(vg, x,y, 150, "Hover your mouse over the text to see calculated caret position.", NULL); nvgRestore(vg); } void drawWidths(NVGcontext* vg, float x, float y, float width) { int i; nvgSave(vg); nvgStrokeColor(vg, nvgRGBA(0,0,0,255)); for (i = 0; i < 20; i++) { float w = (i+0.5f)*0.1f; nvgStrokeWidth(vg, w); nvgBeginPath(vg); nvgMoveTo(vg, x,y); nvgLineTo(vg, x+width,y+width*0.3f); nvgStroke(vg); y += 10; } nvgRestore(vg); } void drawCaps(NVGcontext* vg, float x, float y, float width) { int i; int caps[3] = {NVG_BUTT, NVG_ROUND, NVG_SQUARE}; float lineWidth = 8.0f; nvgSave(vg); nvgBeginPath(vg); nvgRect(vg, x-lineWidth/2, y, width+lineWidth, 40); nvgFillColor(vg, nvgRGBA(255,255,255,32)); nvgFill(vg); nvgBeginPath(vg); nvgRect(vg, x, y, width, 40); nvgFillColor(vg, nvgRGBA(255,255,255,32)); nvgFill(vg); nvgStrokeWidth(vg, lineWidth); for (i = 0; i < 3; i++) { nvgLineCap(vg, caps[i]); nvgStrokeColor(vg, nvgRGBA(0,0,0,255)); nvgBeginPath(vg); nvgMoveTo(vg, x, y + i*10 + 5); nvgLineTo(vg, x+width, y + i*10 + 5); nvgStroke(vg); } nvgRestore(vg); } void drawScissor(NVGcontext* vg, float x, float y, float t) { nvgSave(vg); // Draw first rect and set scissor to it's area. nvgTranslate(vg, x, y); nvgRotate(vg, nvgDegToRad(5)); nvgBeginPath(vg); nvgRect(vg, -20,-20,60,40); nvgFillColor(vg, nvgRGBA(255,0,0,255)); nvgFill(vg); nvgScissor(vg, -20,-20,60,40); // Draw second rectangle with offset and rotation. nvgTranslate(vg, 40,0); nvgRotate(vg, t); // Draw the intended second rectangle without any scissoring. nvgSave(vg); nvgResetScissor(vg); nvgBeginPath(vg); nvgRect(vg, -20,-10,60,30); nvgFillColor(vg, nvgRGBA(255,128,0,64)); nvgFill(vg); nvgRestore(vg); // Draw second rectangle with combined scissoring. nvgIntersectScissor(vg, -20,-10,60,30); nvgBeginPath(vg); nvgRect(vg, -20,-10,60,30); nvgFillColor(vg, nvgRGBA(255,128,0,255)); nvgFill(vg); nvgRestore(vg); } void renderDemo(NVGcontext* vg, float mx, float my, float width, float height, float t, int blowup, DemoData* data) { float x,y,popy; drawEyes(vg, width - 250, 50, 150, 100, mx, my, t); drawParagraph(vg, width - 450, 50, 150, 100, mx, my); drawGraph(vg, 0, height/2, width, height/2, t); drawColorwheel(vg, width - 300, height - 300, 250.0f, 250.0f, t); // Line joints drawLines(vg, 120, height-50, 600, 50, t); // Line caps drawWidths(vg, 10, 50, 30); // Line caps drawCaps(vg, 10, 300, 30); drawScissor(vg, 50, height-80, t); nvgSave(vg); if (blowup) { nvgRotate(vg, sinf(t*0.3f)*5.0f/180.0f*NVG_PI); nvgScale(vg, 2.0f, 2.0f); } // Widgets drawWindow(vg, "Widgets `n Stuff", 50, 50, 300, 400); x = 60; y = 95; drawSearchBox(vg, "Search", x,y,280,25); y += 40; drawDropDown(vg, "Effects", x,y,280,28); popy = y + 14; y += 45; // Form drawLabel(vg, "Login", x,y, 280,20); y += 25; drawEditBox(vg, "Email", x,y, 280,28); y += 35; drawEditBox(vg, "Password", x,y, 280,28); y += 38; drawCheckBox(vg, "Remember me", x,y, 140,28); drawButton(vg, ICON_LOGIN, "Sign in", x+138, y, 140, 28, nvgRGBA(0,96,128,255)); y += 45; // Slider drawLabel(vg, "Diameter", x,y, 280,20); y += 25; drawEditBoxNum(vg, "123.00", "px", x+180,y, 100,28); drawSlider(vg, 0.4f, x,y, 170,28); y += 55; drawButton(vg, ICON_TRASH, "Delete", x, y, 160, 28, nvgRGBA(128,16,8,255)); drawButton(vg, 0, "Cancel", x+170, y, 110, 28, nvgRGBA(0,0,0,0)); // Thumbnails box drawThumbnails(vg, 365, popy-30, 160, 300, data->images, 12, t); nvgRestore(vg); }
[ "JauneLaCouleur@gmail.com" ]
JauneLaCouleur@gmail.com
d5dfc6655be8265a97162ec9f4a42ef9aa2012c3
5740ea2c2d9d5fb5626ff5ad651f3789048ae86b
/Extensions/Editor/AppCommands.cpp
d3de4866c9b37ede48e45d9421a034527b9f65ec
[ "LicenseRef-scancode-scintilla", "MIT" ]
permissive
donovan680/Plasma
4945b92b7c6e642a557f12e05c7d53819186de55
51d40ef0669b7a3015f95e3c84c6d639d5469b62
refs/heads/master
2022-04-15T02:42:26.469268
2020-02-26T22:32:12
2020-02-26T22:32:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,640
cpp
#include "Precompiled.hpp" namespace Plasma { void OpenHelp() { Os::SystemOpenNetworkFile(Urls::cUserHelp); } void OpenPlasmaHub() { Os::SystemOpenNetworkFile(Urls::cUserPlasmaHub); } void OpenDocumentation() { Os::SystemOpenNetworkFile(Urls::cUserOnlineDocs); } void ExitEditor() { PL::gEditor->RequestQuit(false); } void Restart() { bool quitSuccess = PL::gEditor->RequestQuit(true); if(quitSuccess) Os::SystemOpenFile( GetApplication().c_str() ); } void FullScreen(Editor* editor) { OsWindow* osWindow = editor->mOsWindow; if (osWindow->GetState() != WindowState::Fullscreen) osWindow->SetState(WindowState::Fullscreen); else osWindow->SetState(WindowState::Windowed); } void ShowTextWindow(StringParam windowTitle, StringParam windowText) { Window* window = new Window(PL::gEditor); window->SetTitle(windowTitle); window->SetTranslation(Vec3(0, -500, 0)); MultiLineText* textBox = new MultiLineText(window); textBox->SetText(windowText); window->SizeToContents(); CenterToWindow(PL::gEditor, window, true); } void ShowAbout() { String text = "DigiPen Plasma Engine\n" "Copyright: \n" "DigiPen Institute of Technology 2016\n" "All rights reserved. \n" "Version: \n"; ShowTextWindow("About", BuildString(text, GetBuildVersionName())); } DeclareEnum3(VersionStatus, Unknown, UpToDate, NewVersionAvailable); VersionStatus::Type GlobalVersionStatus = VersionStatus::Unknown; void BuildVersion() { String buildVersionString = String::Format("BuildVersion: %s", GetBuildVersionName()); ZPrintFilter(Filter::DefaultFilter, "%s\n", buildVersionString.c_str()); OsShell* platform = PL::gEngine->has(OsShell); platform->SetClipboardText(buildVersionString); } void WriteBuildInfo() { String sourceDir = PL::gEngine->GetConfigCog()->has(MainConfig)->SourceDirectory; Environment* environment = Environment::GetInstance(); String filePath = environment->GetParsedArgument("WriteBuildInfo"); if(filePath.Empty() || filePath == "true") filePath = FilePath::CombineWithExtension(sourceDir, "Meta", ".data"); StringBuilder builder; builder.AppendFormat("MajorVersion %d\n", GetMajorVersion()); builder.AppendFormat("MinorVersion %d\n", GetMinorVersion()); builder.AppendFormat("PatchVersion %d\n", GetPatchVersion()); builder.AppendFormat("RevisionId %d\n", GetRevisionNumber()); builder.AppendFormat("Platform \"%s\"\n", GetPlatformString()); cstr experimentalBranchName = GetExperimentalBranchName(); if(experimentalBranchName != nullptr) builder.AppendFormat("ExperimentalBranchName \"%s\"\n", experimentalBranchName); builder.AppendFormat("ShortChangeSet \"%s\"\n", GetShortChangeSetString()); builder.AppendFormat("ChangeSet \"%s\"\n", GetChangeSetString()); builder.AppendFormat("ChangeSetDate \"%s\"\n", GetChangeSetDateString()); builder.AppendFormat("BuildId \"%s\"\n", GetBuildIdString()); builder.AppendFormat("LauncherMajorVersion %d\n", GetLauncherMajorVersion()); String result = builder.ToString(); WriteStringRangeToFile(filePath, result); ZPrint("Writing build info to '%s'\n", filePath.c_str()); ZPrint("File Contents: %s\n", result.c_str()); PL::gEngine->Terminate(); } void OpenTestWidgetsCommand() { OpenTestWidgets(PL::gEditor); } // Used to test the crash handler void CrashEngine() { PL::gEngine->CrashEngine(); } void SortAndPrintMetaTypeList(StringBuilder& builder, Array<String>& names, cstr category) { if (names.Empty()) return; Sort(names.All()); builder.Append(category); builder.Append(":\n"); forRange(String& name, names.All()) { builder.Append(" "); builder.Append(name); builder.Append("\n"); } builder.Append("\n"); } // Special class to delay dispatching the unit test command until scripts have been compiled class UnitTestDelayRunner : public Composite { public: typedef UnitTestDelayRunner LightningSelf; void OnScriptsCompiled(Event* e) { ActionSequence* seq = new ActionSequence(PL::gEditor, ActionExecuteMode::FrameUpdate); //wait a little bit so we the scripts will be finished compiling (and hooked up) seq->Add(new ActionDelay(0.1f)); seq->Add(new ActionEvent(PL::gEngine, "RunUnitTests", new Event())); //when the game plays the scripts will be compiled again so don't dispatch this event DisconnectAll(PL::gEngine, this); this->Destroy(); } UnitTestDelayRunner(Composite* parent) : Composite(parent) { OnScriptsCompiled(nullptr); } }; void RunUnitTests() { Lightning::Sha1Builder::RunUnitTests(); new UnitTestDelayRunner(PL::gEditor); } void RecordUnitTestFile() { UnitTestSystem* unitTestSystem = PL::gEngine->has(UnitTestSystem); unitTestSystem->RecordToPlasmaTestFile(); } void PlayUnitTestFile() { UnitTestSystem* unitTestSystem = PL::gEngine->has(UnitTestSystem); unitTestSystem->PlayFromPlasmaTestFile(); } void HostLightningDebugger() { LightningManager* manager = LightningManager::GetInstance(); manager->HostDebugger(); } void RunLightningDebugger() { HostLightningDebugger(); String debuggerPath = FilePath::Combine(PL::gContentSystem->ToolPath, "LightningDebugger.html"); Os::SystemOpenFile(debuggerPath.c_str()); } void BindAppCommands(Cog* config, CommandManager* commands) { commands->AddCommand("About", BindCommandFunction(ShowAbout)); commands->AddCommand("Exit", BindCommandFunction(ExitEditor)); commands->AddCommand("ToggleFullScreen", BindCommandFunction(FullScreen)); commands->AddCommand("Restart", BindCommandFunction(Restart)); commands->AddCommand("BuildVersion", BindCommandFunction(BuildVersion)); commands->AddCommand("WriteBuildInfo", BindCommandFunction(WriteBuildInfo)); commands->AddCommand("RunUnitTests", BindCommandFunction(RunUnitTests)); commands->AddCommand("RecordUnitTestFile", BindCommandFunction(RecordUnitTestFile)); commands->AddCommand("PlayUnitTestFile", BindCommandFunction(PlayUnitTestFile)); if(DeveloperConfig* devConfig = PL::gEngine->GetConfigCog()->has(DeveloperConfig)) { commands->AddCommand("OpenTestWidgets", BindCommandFunction(OpenTestWidgetsCommand)); commands->AddCommand("CrashEngine", BindCommandFunction(CrashEngine)); commands->AddCommand("HostLightningDebugger", BindCommandFunction(HostLightningDebugger)); commands->AddCommand("RunLightningDebugger", BindCommandFunction(RunLightningDebugger)); } commands->AddCommand("Help", BindCommandFunction(OpenHelp)); commands->AddCommand("PlasmaHub", BindCommandFunction(OpenPlasmaHub)); commands->AddCommand("Documentation", BindCommandFunction(OpenDocumentation)); } }
[ "dragonCASTjosh@gmail.com" ]
dragonCASTjosh@gmail.com
6dd95251dfbc82633b1cba0a1130f72e4caca765
f28f1ed1620edd7aceb2166b1003d7a492763bda
/algorithms_projects/ga15_pointrobotshortestpath.h
464b5330e3947a0f2a598a9313ecdbd395205e0b
[]
no_license
Augus518/GeometryAlgorithms
047bda393db6f3ae7c1a63084051db334bfdc266
6fae7adcb64803817641c9e43679b1c047c3f9d0
refs/heads/master
2023-03-18T06:36:45.703066
2019-01-14T03:16:08
2019-01-14T03:16:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,107
h
/* Autor: Matei Jon Stancu 1137/2015 Godina: 2018 Kratak opis problema: Dat je skup prepreka u ravni i dve tacke, potrebno je naci najkraci put izmedju datih tacaka, takav da ne sece unutrasnjost datih prepreka. */ #ifndef GA15_POINTROBOTSHORTESTPATH_H #define GA15_POINTROBOTSHORTESTPATH_H #include "algorithmbase.h" #include "ga15_datastructures.h" #include <limits> #include <set> #include <queue> /// /// \brief The PointRobotShortestPath class - klasa koja implementira algoritam najkraceg puta izmedju dve tacke za tackastog robota /// class PointRobotShortestPath : public AlgorithmBase { public: /// /// \brief PointRobotShortestPath - konstruktor za animaciju /// \param pRender - prozor na kojem se iscrtava animacija /// \param delayMs - osvezavanje animacije /// \param fileName - putanja do ulazne datoteke /// \param search - tip pretrage /// \param start - pocetna tacka /// \param end - odrediste /// PointRobotShortestPath(QWidget *pRender, int delayMs, std::string fileName, searchType search, QPoint start, QPoint end); /// /// \brief PointRobotShortestPath - konstruktor za testiranje /// \param pRender - prozor na kojem se iscrtava animacija /// \param delayMs - osvezavanje animacije /// \param fileName - putanja do ulazne datoteke /// \param search - tip prerage /// \param size - dimenzija problema /// PointRobotShortestPath(QWidget *pRender, int delayMs, std::string fileName, searchType search, int size); /// /// \brief runAlgorithm - implementacija naprednog algoritma /// void runAlgorithm(); /// /// \brief drawAlgorithm - iscrtavanje vizualizacije algoritma /// \param painter - QPainter /// void drawAlgorithm(QPainter &painter) const; /// /// \brief runNaiveAlgorithm - implementacija naivnog algoritma /// void runNaiveAlgorithm(); /// /// \brief pointInsidePolygon - provera da li tacka pripada unutrasnjosti poligona /// \param p1 - tacka koja se ispituje /// \return - tacno ako je tacka unutar poligona, netacno inace /// bool pointInsidePolygon(QPointF p1); /// /// \brief shortestPath - geter za najkraci put /// \return - vector koji cuva najkraci put izmedju _pStart i _pEnd /// std::vector<vertex *> shortestPath() const; /// /// \brief shortestPathLength - geter za duzinu najkraceg puta /// \return - duzina najkraceg puta /// double shortestPathLength() const; private: /// /// \brief naiveVisibilityGraph - funkcija koja racuna graf vidljivosti naivnim pristupom /// void naiveVisibilityGraph(); /// /// \brief naiveShortestPath - funkcija koja racuna najkraci put naivnim pristupom /// void naiveShortestPath(); /// /// \brief improvedVisibilityGraph - funkcija koja racuna graf vidljivosti naprednim pristupom /// void improvedVisibilityGraph(); /// /// \brief improvedShortestPath - funkcija koja racuna najkraci put naprednim pristupom /// void improvedShortestPath(); /// /// \brief updateSweepLine - funkcija koja azurira polozaj brisuce prave /// \param p1 - prva tacka koja definise brisucu pravu /// \param p2 - druga tacka koja definise brisucu pravu /// void updateSweepLine(const QPoint p1, const QPoint p2); /// /// \brief initDataQueues - inicijalizacija strukutura podataka /// \param w - cvor grafa u odnosu na kog se vrsi inicijalizacija /// void initDataQueues(vertex *w); /// /// \brief deleteFromStatus - funkcija koja brise duz iz statusa u linearnom vremenu /// \param l - duz koja se brise /// void deleteFromStatus(QLine l); /// /// \brief deleteFromStatus - funkcija koja brise duz iz statusa u logaritamskom vremenu /// \param l - duz koja se brise /// void deleteFromStatus2(QLine l); /// /// \brief updateStatusQueue - funkcija koja azurira status /// \param v - cvor grafa u odnosu na kog se vrsi azuriranje /// void updateStatusQueue(vertex *v); /// /// \brief isVisible - funkcija koja ispituje vidljivost cvora /// \param v - cvor iz kog se ispituje vidljivost /// \param w - cvor do kog se ispituje vidljivost /// \param prevVertex - prethodni cvor za kog je ispitano da li je vidljiv /// \param prevVisible - vidljivost prethodnog cvora /// \return - tacno ako je cvor w vidljiv iz v, netacno inace /// bool isVisible(const vertex *v, const vertex *w, vertex *prevVertex, bool prevVisible); /// /// \brief generateObstacleGrid - funkcija koja generise instance za testiranje /// \param rows - broj redova matrice prepreka /// \param cols - broj kolona matrice prepreka /// \return - putanja do generisane datoteke /// std::string generateObstacleGrid(unsigned rows, unsigned cols) const; /// /// \brief _obstacles - skup prepreka u DCEL formatu /// DCEL _obstacles; /// /// \brief _visibilityGraph - graf vidljivosti /// Graph _visibilityGraph; /// /// \brief _pStart - tacka pocetnog polozaja /// QPoint _pStart; /// /// \brief _pEnd - tacka odredista /// QPoint _pEnd; /// /// \brief _sweepLine - brisuca prava /// QLine _sweepLine; /// /// \brief _shortestPath - najkraci put izmedju _pStart i _pEnd u _visibilityGraph /// std::vector<vertex*> _shortestPath; /// /// \brief _lineSegments - skup ivica prepreka /// std::vector<QLineF> _lineSegments; /// /// \brief _eventQueue - struktura red dogadjaja /// std::set<EventQueueVertex, EventQueueAngleComp> _eventQueue; /// /// \brief _statusQueue - struktura status preseka ivica prepreka sa brisucom pravom /// std::multiset<QLineF, StatusQueueCompare> _statusQueue; /// /// \brief _searchQueue - struktura red sa prioritetom za pretragu najkraceg puta /// std::priority_queue<vertex*, std::vector<vertex*>, SearchQueueCompare> _searchQueue; /// /// \brief _search - tip pretrage /// searchType _search; }; #endif // GA15_POINTROBOTSHORTESTPATH_H
[ "mdfkprekid@gmail.com" ]
mdfkprekid@gmail.com
571f1a62584bad7d372c366ce30f5fe3955fa9a7
9b527d9e39ff2b33e2e86af842031bf27d4bebe4
/C/C-DS/C-AVL/src/main.cpp
c9d602b73ec3b03c5e762a2cf7b2ae65cbab1b2d
[]
no_license
Brinews/jacky
c50cdc5471ef7a764c2a27313ebf848e41c4aee0
e3f0f4bdf4253448f22306b353cb45560e882587
refs/heads/master
2021-01-17T08:32:11.034322
2017-12-03T08:28:17
2017-12-03T08:28:17
14,444,828
1
2
null
null
null
null
UTF-8
C++
false
false
2,753
cpp
#include <iostream> #include <string> #include <cassert> #include <vector> // local includes #include "AVLTree.h" #include "Data.h" using namespace std; void testDoubleData(){ // testing getData DoubleData d1 {}; DoubleData d2 {5}; assert (d1.getData() == 0); // default value assert (d2.getData() == 5); // testing 1-arg constructor DoubleData d3 {d2}; assert (d3.getData() == 5); // testing copy constructor DoubleData d4 {*(new DoubleData(3))}; assert (d4.getData() == 3); // testing move constructor // testing setData double y = 7.5; d1.setData(y); assert (d1.getData() == 7.5); d1.setData(8.5); assert (d1.getData() == 8.5); // testing compare, should be a.compare(b) = a-b assert (d1.compare(d2) == 3.5); } void testAVLTree(){ AVLTree<DoubleData> a {}; std::vector<DoubleData*> v {5, new DoubleData{}}; assert (a.getHeight() == 0 || a.getHeight() == -1); double counter = 0; std::cout << "testing insertion and single rotation cases: " << std::endl; for (auto& x : v){ x = new DoubleData(counter); a.insert(*x); /* These test all the single rotations */ if (counter == 1) {assert(a.getHeight() == 1);} if (counter == 2) {assert(a.getHeight() == 1);} if (counter == 3) {assert(a.getHeight() == 2);} if (counter == 4) {assert(a.getHeight() == 2);} counter++; } std::cout << std::endl; std::cout << "testing double rotation cases: " << std::endl; a.insert(DoubleData(2.5)); assert(a.getHeight() == 2); a.insert(DoubleData(3.5)); a.insert(DoubleData(1.5)); a.insert(DoubleData(1.2)); a.insert(DoubleData(1.7)); a.insert(DoubleData(-1)); a.insert(DoubleData(0.5)); a.insert(DoubleData(1.3)); a.insert(DoubleData(1.1)); a.insert(DoubleData(1.6)); a.insert(DoubleData(-2)); a.insert(DoubleData(1.05)); assert(a.getHeight() == 4); std::cout << std::endl; std::cout<<"testing traversals:"<<std::endl; a.printPreorder(); a.printInorder(); a.printPostorder(); a.printLevelOrder(); std::cout << std::endl; std::cout << "removing 2.5:" << std::endl; a.remove(DoubleData(2.5)); a.printLevelOrder(); std::cout << std::endl; std::cout << "removing 1.5:" << std::endl; a.remove(DoubleData(1.5)); a.printPostorder(); std::cout << std::endl; // // testing copy constructor AVLTree<DoubleData> b {a}; cout << "should be same:" << endl; a.printPostorder(); b.printPostorder(); std::cout << std::endl; a.empty(); cout << "should be empty now:" << endl; assert (a.getHeight() == -1 || // a null tree can have height -1 or 0, a.getHeight() == 0); // which is subject to preference and usage a.printPostorder(); std::cout << "end of test"<< std::endl; } int main (int argc, char* argv []){ testDoubleData(); testAVLTree(); std::cout << "end of main"<< std::endl; }
[ "brinewsor@gmail.com" ]
brinewsor@gmail.com
47febedda61077f35cfd6caec90895854a7d3a41
1d0def2ec8eacce21b33b641229bb8dbcb4dfd8a
/sailfishclient/TapMenu.cpp
98debd00c3313697e4e9e59ad5ff2505d757bb04
[]
no_license
Nokius/monavsailfish
64dda8536c12852545e0454b9fa8a8ac43eac543
a762d58c765a4959d55dc5f31cce669513aaf33b
refs/heads/master
2020-12-24T23:11:30.830226
2015-03-08T18:04:35
2015-03-08T18:04:35
31,856,840
0
0
null
2015-03-08T16:34:03
2015-03-08T16:34:03
null
UTF-8
C++
false
false
1,737
cpp
#include "TapMenu.h" #include "interfaces/iaddresslookup.h" #include "interfaces/irenderer.h" #include "utils/qthelpers.h" #include "client/mapdata.h" #include "client/routinglogic.h" TapMenu::TapMenu(QObject *parent) : QObject(parent) { } TapMenu::~TapMenu() { } void TapMenu::searchTextChanged(QString text) { IAddressLookup* addressLookup = MapData::instance()->addressLookup(); if ( addressLookup == NULL ) return; search_suggestions.clear(); search_dataIndex.clear(); QStringList characters; QStringList placeNames; if (text.length() == 0) { emit searchResultUpdated(search_suggestions, placeNames); return; } Timer time; bool found = addressLookup->GetStreetSuggestions( 0, text, 10, &search_suggestions, &placeNames, &search_dataIndex, &characters ); qDebug() << "Street Lookup:" << time.elapsed() << "ms"; emit searchResultUpdated(search_suggestions, placeNames); } void TapMenu::searchResultSelected(QString command, int index) { IAddressLookup* addressLookup = MapData::instance()->addressLookup(); if ( addressLookup == NULL ) return; qDebug() << search_dataIndex[index]; QVector< int > segmentLength; QVector< UnsignedCoordinate > coordinates; QString place; if ( !addressLookup->GetStreetData( 0, search_suggestions[index], search_dataIndex[index], &segmentLength, &coordinates, &place ) ) return; IRenderer* renderer = MapData::instance()->renderer(); if ( renderer == NULL ) return; if (command == "source") { RoutingLogic::instance()->setSource( coordinates[0] ); } else if (command == "destination") { RoutingLogic::instance()->setTarget( coordinates[0] ); } } void TapMenu::setSourceFollowLocation(bool follow) { RoutingLogic::instance()->setGPSLink(follow); }
[ "jettis@gmail.com" ]
jettis@gmail.com
851fbf1ba4355da7fdab1061d22fa598e4bf2052
d40efadec5724c236f1ec681ac811466fcf848d8
/tags/volition_import/fs2_open/code/network/multiteamselect.cpp
3edeca2fdf8c0c105c4da888ac762f764b53253d
[]
no_license
svn2github/fs2open
0fcbe9345fb54d2abbe45e61ef44a41fa7e02e15
c6d35120e8372c2c74270c85a9e7d88709086278
refs/heads/master
2020-05-17T17:37:03.969697
2015-01-08T15:24:21
2015-01-08T15:24:21
14,258,345
0
0
null
null
null
null
UTF-8
C++
false
false
100,422
cpp
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on the * source. * */ /* * $Logfile: /Freespace2/code/Network/MultiTeamSelect.cpp $ * $Revision: 1.1 $ * $Date: 2002-06-03 03:26:00 $ * $Author: penguin $ * * Multiplayer Team Selection Code * * $Log: not supported by cvs2svn $ * Revision 1.1 2002/05/02 18:03:11 mharris * Initial checkin - converted filenames and includes to lower case * * * 27 9/13/99 12:54p Jefff * coord fix * * 26 9/12/99 3:21p Jefff * commit button coord fix in 640 * * 25 8/05/99 9:57p Jefff * fixed some button wierdness * * 24 8/05/99 5:08p Jefff * fixed some location probs * * 23 7/28/99 5:34p Dave * Nailed the missing stats bug to the wall. Problem was optimized build * and using GET_DATA() with array elements. BLECH. * * 22 7/24/99 6:02p Jefff * Added "lock" text to lock button * * 21 5/03/99 8:32p Dave * New version of multi host options screen. * * 20 3/25/99 6:36p Neilk * more hires coord fixes * * 19 3/25/99 2:44p Neilk * Fixed lock button * * 18 3/23/99 11:56a Neilk * new source safe checkin * * 17 3/10/99 6:50p Dave * Changed the way we buffer packets for all clients. Optimized turret * fired packets. Did some weapon firing optimizations. * * 16 3/09/99 6:24p Dave * More work on object update revamping. Identified several sources of * unnecessary bandwidth. * * 15 2/21/99 6:02p Dave * Fixed standalone WSS packets. * * 14 2/11/99 3:08p Dave * PXO refresh button. Very preliminary squad war support. * * 13 2/01/99 5:55p Dave * Removed the idea of explicit bitmaps for buttons. Fixed text * highlighting for disabled gadgets. * * 12 1/30/99 5:08p Dave * More new hi-res stuff.Support for nice D3D textures. * * 11 1/30/99 1:29a Dave * Fixed nebula thumbnail problem. Full support for 1024x768 choose pilot * screen. Fixed beam weapon death messages. * * 10 1/29/99 5:07p Dave * Fixed multiplayer stuff. Put in multiplayer support for rapid fire * missiles. * * 9 1/13/99 7:19p Neilk * Converted Mission Brief, Barracks, Synch to high res support * * 8 12/18/98 1:13a Dave * Rough 1024x768 support for Direct3D. Proper detection and usage through * the launcher. * * 7 11/30/98 1:07p Dave * 16 bit conversion, first run. * * 6 11/19/98 8:04a Dave * Full support for D3-style reliable sockets. Revamped packet lag/loss * system, made it receiver side and at the lowest possible level. * * 5 11/17/98 11:12a Dave * Removed player identification by address. Now assign explicit id #'s. * * 4 11/05/98 5:55p Dave * Big pass at reducing #includes * * 3 10/13/98 9:29a Dave * Started neatening up freespace.h. Many variables renamed and * reorganized. Added AlphaColors.[h,cpp] * * 2 10/07/98 10:53a Dave * Initial checkin. * * 1 10/07/98 10:50a Dave * * 112 9/18/98 2:22a Dave * Fixed freespace-side PXO api to correctly handle length 10 id strings. * Fixed team select screen to handle alpha/beta/gamma ships which are not * marked as OF_PLAYER_SHIP * * 111 9/17/98 3:08p Dave * PXO to non-pxo game warning popup. Player icon stuff in create and join * game screens. Upped server count refresh time in PXO to 35 secs (from * 20). * * 110 8/20/98 5:31p Dave * Put in handy multiplayer logfile system. Now need to put in useful * applications of it all over the code. * * 109 8/07/98 10:17a Allender * use obj_set_flags for setting COULD_BE_PLAYER flag to trap bugs * * 108 7/24/98 9:27a Dave * Tidied up endgame sequencing by removing several old flags and * standardizing _all_ endgame stuff with a single function call. * * 107 6/13/98 6:01p Hoffoss * Externalized all new (or forgot to be added) strings to all the code. * * 106 6/13/98 3:19p Hoffoss * NOX()ed out a bunch of strings that shouldn't be translated. * * 105 5/19/98 8:35p Dave * Revamp PXO channel listing system. Send campaign goals/events to * clients for evaluation. Made lock button pressable on all screens. * * 104 5/19/98 11:23a Dave * Change mask value for "lock" button. * * 103 5/18/98 12:41a Allender * fixed subsystem problems on clients (i.e. not reporting properly on * damage indicator). Fixed ingame join problem with respawns. minor * comm menu stuff * * 102 5/17/98 1:43a Dave * Eradicated chatbox problems. Remove speed match for observers. Put in * help screens for PXO. Fix messaging and end mission privelges. Fixed * team select screen bugs. Misc UI fixes. * * 101 5/15/98 5:16p Dave * Fix a standalone resetting bug.Tweaked PXO interface. Display captaincy * status for team vs. team. Put in asserts to check for invalid team vs. * team situations. * * 100 5/10/98 7:06p Dave * Fix endgame sequencing ESC key. Changed how host options warning popups * are done. Fixed pause/message scrollback/options screen problems in mp. * Make sure observer HUD doesn't try to lock weapons. * */ #include "multiteamselect.h" #include "ui.h" #include "chatbox.h" #include "bmpman.h" #include "gamesnd.h" #include "key.h" #include "linklist.h" #include "gamesequence.h" #include "font.h" #include "multiutil.h" #include "freespace.h" #include "missionscreencommon.h" #include "missionshipchoice.h" #include "missionweaponchoice.h" #include "missionbrief.h" #include "missionparse.h" #include "multimsgs.h" #include "snazzyui.h" #include "mouse.h" #include "popup.h" #include "multiui.h" #include "multi_endgame.h" #include "alphacolors.h" #include "multi.h" // ------------------------------------------------------------------------------------------------------ // TEAM SELECT DEFINES/VARS // // mission screen common data extern int Next_screen; //XSTR:OFF // bitmap defines #define MULTI_TS_PALETTE "InterfacePalette" char *Multi_ts_bitmap_fname[GR_NUM_RESOLUTIONS] = { "TeamSelect", // GR_640 "2_TeamSelect" // GR_1024 }; char *Multi_ts_bitmap_mask_fname[GR_NUM_RESOLUTIONS] = { "TeamSelect-M", // GR_640 "2_TeamSelect-M" // GR_1024 }; // constants for coordinate lookup #define MULTI_TS_X_COORD 0 #define MULTI_TS_Y_COORD 1 #define MULTI_TS_W_COORD 2 #define MULTI_TS_H_COORD 3 #define MULTI_TS_NUM_BUTTONS 7 #define MULTI_TS_BRIEFING 0 // go to the briefing #define MULTI_TS_SHIP_SELECT 1 // this screen #define MULTI_TS_WEAPON_SELECT 2 // go to the weapon select screen #define MULTI_TS_SHIPS_UP 3 // scroll the ships list up #define MULTI_TS_SHIPS_DOWN 4 // scroll the ships list down #define MULTI_TS_COMMIT 5 // commit #define MULTI_TS_LOCK 6 // lock (free) ship/weapon select ui_button_info Multi_ts_buttons[GR_NUM_RESOLUTIONS][MULTI_TS_NUM_BUTTONS] = { { // GR_640 ui_button_info("CB_00", 7, 3, 37, 7, 0), ui_button_info("CB_01", 7, 19, 37, 23, 1), ui_button_info("CB_02", 7, 35, 37, 39, 2), ui_button_info("TSB_03", 5, 303, -1, -1, 3), ui_button_info("TSB_04", 5, 454, -1, -1, 4), ui_button_info("TSB_09", 571, 425, 572, 413, 9), ui_button_info("TSB_34", 603, 374, 602, 364, 34) }, { // GR_1024 ui_button_info("2_CB_00", 12, 5, 59, 12, 0), ui_button_info("2_CB_01", 12, 31, 59, 37, 1), ui_button_info("2_CB_02", 12, 56, 59, 62, 2), ui_button_info("2_TSB_03", 8, 485, -1, -1, 3), ui_button_info("2_TSB_04", 8, 727, -1, -1, 4), ui_button_info("2_TSB_09", 914, 681, 937, 660, 9), ui_button_info("2_TSB_34", 966, 599, 964, 584, 34) }, }; // players locked ani graphic #define MULTI_TS_NUM_LOCKED_BITMAPS 3 char *Multi_ts_bmap_names[GR_NUM_RESOLUTIONS][3] = { { // GR_640 "TSB_340000", "TSB_340001", "TSB_340002" }, { // GR_1024 "2_TSB_340000", "2_TSB_340001", "2_TSB_340002" } }; int Multi_ts_locked_bitmaps[MULTI_TS_NUM_LOCKED_BITMAPS]; // snazzy menu regions #define TSWING_0_SHIP_0 10 #define TSWING_0_SHIP_1 12 #define TSWING_0_SHIP_2 14 #define TSWING_0_SHIP_3 16 #define TSWING_1_SHIP_0 18 #define TSWING_1_SHIP_1 20 #define TSWING_1_SHIP_2 22 #define TSWING_1_SHIP_3 24 #define TSWING_2_SHIP_0 26 #define TSWING_2_SHIP_1 28 #define TSWING_2_SHIP_2 30 #define TSWING_2_SHIP_3 32 #define TSWING_0_NAME_0 11 #define TSWING_0_NAME_1 13 #define TSWING_0_NAME_2 15 #define TSWING_0_NAME_3 17 #define TSWING_1_NAME_0 19 #define TSWING_1_NAME_1 21 #define TSWING_1_NAME_2 23 #define TSWING_1_NAME_3 25 #define TSWING_2_NAME_0 27 #define TSWING_2_NAME_1 29 #define TSWING_2_NAME_2 31 #define TSWING_2_NAME_3 33 #define TSWING_LIST_0 5 #define TSWING_LIST_1 6 #define TSWING_LIST_2 7 #define TSWING_LIST_3 8 #define MULTI_TS_SLOT_LIST 0 #define MULTI_TS_PLAYER_LIST 1 #define MULTI_TS_AVAIL_LIST 2 // interface data #define MULTI_TS_NUM_SNAZZY_REGIONS 28 int Multi_ts_bitmap; int Multi_ts_mask; int Multi_ts_inited = 0; int Multi_ts_snazzy_regions; ubyte *Multi_ts_mask_data; int Multi_ts_mask_w, Multi_ts_mask_h; MENU_REGION Multi_ts_region[MULTI_TS_NUM_SNAZZY_REGIONS]; UI_WINDOW Multi_ts_window; // ship slot data #define MULTI_TS_NUM_SHIP_SLOTS_TEAM 4 // # of ship slots in team v team #define MULTI_TS_FLAG_NONE -2 // never has any ships #define MULTI_TS_FLAG_EMPTY -1 // currently empty char *Multi_ts_slot_names[MULTI_TS_NUM_SHIP_SLOTS] = { // "alpha 1", "alpha 2", "alpha 3", "alpha 4", "beta 1", "beta 2", "beta 3", "beta 4", "gamma 1", "gamma 2", "gamma 3", "gamma 4" }; char *Multi_ts_slot_team_names[MULTI_TS_MAX_TEAMS][MULTI_TS_NUM_SHIP_SLOTS_TEAM] = { {"alpha 1", "alpha 2", "alpha 3", "alpha 4"}, {"zeta 1", "zeta 2", "zeta 3", "zeta 4"} }; static int Multi_ts_slot_icon_coords[MULTI_TS_NUM_SHIP_SLOTS][GR_NUM_RESOLUTIONS][2] = { // x,y { // {128,301}, // GR_640 {205,482} // GR_1024 }, { // {91,347}, // GR_640 {146,555} // GR_1024 }, { // {166,347}, // GR_640 {266,555} // GR_1024 }, { // alpha {128,395}, // GR_640 {205,632} // GR_1024 }, { // {290,301}, // GR_640 {464,482} // GR_1024 }, { // {253,347}, // GR_640 {405,555} // GR_1024 }, { // {328,347}, // GR_640 {525,555} // GR_1024 }, { // beta {290,395}, // GR_640 {464,632} // GR_1024 }, { // {453,301}, // GR_640 {725,482} // GR_1024 }, { // {416,347}, // GR_640 {666,555} // GR_1024 }, { // {491,347}, // GR_640 {786,555} // GR_1024 }, { // gamma {453,395}, // GR_640 {725,632} // GR_1024 } }; static int Multi_ts_slot_text_coords[MULTI_TS_NUM_SHIP_SLOTS][GR_NUM_RESOLUTIONS][3] = { // x,y,width { // alpha {112,330,181-112}, // GR_640 {187,517,181-112} // GR_1024 }, { // alpha {74,377,143-74}, // GR_640 {126,592,143-74} // GR_1024 }, { // alpha {149,377,218-149},// GR_640 {248,592,218-149} // GR_1024 }, { // alpha {112,424,181-112},// GR_640 {187,667,181-112} // GR_1024 }, { // beta {274,330,343-274},// GR_640 {446,517,343-274} // GR_1024 }, { // beta {236,377,305-236},// GR_640 {385,592,305-236} // GR_1024 }, { // beta {311,377,380-311},// GR_640 {507,592,380-311} // GR_1024 }, { // beta {274,424,343-274},// GR_640 {446,667,343-274} // GR_1024 }, { // gamma {437,330,506-437},// GR_640 {707,517,506-437} // GR_1024 }, { // gamma {399,377,468-399},// GR_640 {646,592,468-399} // GR_1024 }, { // gamma {474,377,543-474},// GR_640 {768,592,543-474} // GR_1024 }, { // gamma {437,424,506-437},// GR_640 {707,667,506-437} // GR_1024 } }; // avail ship list data #define MULTI_TS_AVAIL_MAX_DISPLAY 4 static int Multi_ts_avail_coords[MULTI_TS_AVAIL_MAX_DISPLAY][GR_NUM_RESOLUTIONS][2] = { // x,y coords { // {23,331}, // GR_640 {37,530} // GR_1024 }, { // {23,361}, // GR_640 {37,578} // GR_1024 }, { // {23,391}, // GR_640 {37,626} // GR_1024 }, { // {23,421}, // GR_640 {37,674} // GR_1024 } }; int Multi_ts_avail_start = 0; // starting index of where we will display the available ships int Multi_ts_avail_count = 0; // the # of available ship classes // ship information stuff #define MULTI_TS_SHIP_INFO_MAX_LINE_LEN 150 #define MULTI_TS_SHIP_INFO_MAX_LINES 10 #define MULTI_TS_SHIP_INFO_MAX_TEXT (MULTI_TS_SHIP_INFO_MAX_LINE_LEN * MULTI_TS_SHIP_INFO_MAX_LINES) static int Multi_ts_ship_info_coords[GR_NUM_RESOLUTIONS][3] = { { // GR_640 33, 150, 387 }, { // GR_1024 53, 240, 618 } }; char Multi_ts_ship_info_lines[MULTI_TS_SHIP_INFO_MAX_LINES][MULTI_TS_SHIP_INFO_MAX_LINE_LEN]; char Multi_ts_ship_info_text[MULTI_TS_SHIP_INFO_MAX_TEXT]; int Multi_ts_ship_info_line_count; // status bar mode static int Multi_ts_status_coords[GR_NUM_RESOLUTIONS][3] = { { // GR_640 95, 467, 426 }, { // GR_1024 152, 747, 688 } }; int Multi_ts_status_bar_mode = 0; // carried icon information int Multi_ts_carried_flag = 0; int Multi_ts_clicked_flag = 0; int Multi_ts_clicked_x,Multi_ts_clicked_y; int Multi_ts_carried_ship_class; int Multi_ts_carried_from_type = 0; int Multi_ts_carried_from_index = 0; // selected ship types (for informational purposes) int Multi_ts_select_type = -1; int Multi_ts_select_index = -1; int Multi_ts_select_ship_class = -1; // per-frame mouse hotspot vars int Multi_ts_hotspot_type = -1; int Multi_ts_hotspot_index = -1; // operation types #define TS_GRAB_FROM_LIST 0 #define TS_SWAP_LIST_SLOT 1 #define TS_SWAP_SLOT_SLOT 2 #define TS_DUMP_TO_LIST 3 #define TS_SWAP_PLAYER_PLAYER 4 #define TS_MOVE_PLAYER 5 // packet codes #define TS_CODE_LOCK_TEAM 0 // the specified team's slots are locked #define TS_CODE_PLAYER_UPDATE 1 // a player slot update for the specified team // team data #define MULTI_TS_FLAG_NONE -2 // slot is _always_ empty #define MULTI_TS_FLAG_EMPTY -1 // flag is temporarily empty typedef struct ts_team_data { int multi_ts_objnum[MULTI_TS_NUM_SHIP_SLOTS]; // objnums for all slots in this team net_player *multi_ts_player[MULTI_TS_NUM_SHIP_SLOTS]; // net players corresponding to the same slots int multi_ts_flag[MULTI_TS_NUM_SHIP_SLOTS]; // flags indicating the "status" of a slot int multi_players_locked; // are the players locked into place } ts_team_data; ts_team_data Multi_ts_team[MULTI_TS_MAX_TEAMS]; // data for all teams // deleted ship objnums int Multi_ts_deleted_objnums[MULTI_TS_MAX_TEAMS * MULTI_TS_NUM_SHIP_SLOTS]; int Multi_ts_num_deleted; //XSTR:ON // ------------------------------------------------------------------------------------------------------ // TEAM SELECT FORWARD DECLARATIONS // // check for button presses void multi_ts_check_buttons(); // act on a button press void multi_ts_button_pressed(int n); // initialize all screen data, etc void multi_ts_init_graphics(); // blit all of the icons representing all wings void multi_ts_blit_wings(); // blit all of the player callsigns under the correct ships void multi_ts_blit_wing_callsigns(); // blit the ships on the avail list void multi_ts_blit_avail_ships(); // initialize the snazzy menu stuff for dragging ships,players around void multi_ts_init_snazzy(); // what type of region the index is (0 == ship avail list, 1 == ship slots, 2 == player slot) int multi_ts_region_type(int region); // convert the region num to a ship slot index int multi_ts_slot_index(int region); // convert the region num to an avail list index int multi_ts_avail_index(int region); // convert the region num to a player slot index int multi_ts_player_index(int region); // blit the status bar void multi_ts_blit_status_bar(); // assign the correct players to the correct slots void multi_ts_init_players(); // assign the correct objnums to the correct slots void multi_ts_init_objnums(); // assign the correct flags to the correct slots void multi_ts_init_flags(); // get the proper team and slot index for the given ship name void multi_ts_get_team_and_slot(char *ship_name,int *team_index,int *slot_index); // handle an available ship scroll down button press void multi_ts_avail_scroll_down(); // handle an available ship scroll up button press void multi_ts_avail_scroll_up(); // handle all mouse events (clicking, dragging, and dropping) void multi_ts_handle_mouse(); // can the specified player perform the action he is attempting int multi_ts_can_perform(int from_type,int from_index,int to_type,int to_index,int ship_class,int player_index = -1); // determine the kind of drag and drop operation this is int multi_ts_get_dnd_type(int from_type,int from_index,int to_type,int to_index,int player_index = -1); // swap two player positions int multi_ts_swap_player_player(int from_index,int to_index,int *sound,int player_index = -1); // move a player int multi_ts_move_player(int from_index,int to_index,int *sound,int player_index = -1); // get the ship class of the current index in the avail list or -1 if none exists int multi_ts_get_avail_ship_class(int index); // blit the currently carried icon (if any) void multi_ts_blit_carried_icon(); // if the (console) player is allowed to grab a player slot at this point int multi_ts_can_grab_player(int slot_index,int player_index = -1); // return the bitmap index into the ships icon array (in ship select) which should be displayed for the given slot int multi_ts_slot_bmap_num(int slot_index); // blit any active ship information text void multi_ts_blit_ship_info(); // select the given slot and setup any information, etc void multi_ts_select_ship(); // is it ok for this player to commit int multi_ts_ok_to_commit(); // return the bitmap index into the ships icon array (in ship select) which should be displayed for the given slot int multi_ts_avail_bmap_num(int slot_index); // set the status bar to reflect the status of wing slots (free or not free). 0 or 1 are valid values for now void multi_ts_set_status_bar_mode(int m); // check to see that no illegal ship settings have occurred void multi_ts_check_errors(); // ------------------------------------------------------------------------------------------------------ // TEAM SELECT FUNCTIONS // // initialize the team select screen (always call, even when switching between weapon select, etc) void multi_ts_init() { // if we haven't initialized at all yet, then do it if(!Multi_ts_inited){ multi_ts_init_graphics(); Multi_ts_inited = 1; } // use the common interface palette multi_common_set_palette(); // set the interface palette // common_set_interface_palette(MULTI_TS_PALETTE); Net_player->state = NETPLAYER_STATE_SHIP_SELECT; Current_screen = ON_SHIP_SELECT; } // initialize all critical internal data structures void multi_ts_common_init() { int idx; // reset timestamps here. they seem to get hosed by the loadinh of the mission file multi_reset_timestamps(); // saying "not allowed to mess with ships" Multi_ts_status_bar_mode = 0; // intialize ship info stuff memset(Multi_ts_ship_info_text,0,MULTI_TS_SHIP_INFO_MAX_TEXT); memset(Multi_ts_ship_info_lines,0,MULTI_TS_SHIP_INFO_MAX_TEXT); Multi_ts_ship_info_line_count = 0; // initialize carried icon information Multi_ts_carried_flag = 0; Multi_ts_clicked_flag = 0; Multi_ts_clicked_x = 0; Multi_ts_clicked_y = 0; Multi_ts_carried_ship_class = -1; Multi_ts_carried_from_type = 0; Multi_ts_carried_from_index = 0; // selected slot information (should be default player ship) if(!MULTI_PERM_OBSERVER(Net_players[MY_NET_PLAYER_NUM])){ Multi_ts_select_type = MULTI_TS_SLOT_LIST; Multi_ts_select_index = Net_player->p_info.ship_index; // select this ship and setup his info Multi_ts_select_ship_class = Wss_slots[Multi_ts_select_index].ship_class; multi_ts_select_ship(); } else { Multi_ts_select_type = -1; Multi_ts_select_index = -1; // no ship class selected for information purposes Multi_ts_select_ship_class = -1; } // deleted ship information memset(Multi_ts_deleted_objnums,0,sizeof(int) * MULTI_TS_MAX_TEAMS * MULTI_TS_NUM_SHIP_SLOTS); Multi_ts_num_deleted = 0; // mouse hotspot information Multi_ts_hotspot_type = -1; Multi_ts_hotspot_index = -1; // initialize avail ship list data Multi_ts_avail_start = 0; // load the locked button bitmaps bitmaps for(idx=0;idx<MULTI_TS_NUM_LOCKED_BITMAPS;idx++){ Multi_ts_locked_bitmaps[idx] = -1; Multi_ts_locked_bitmaps[idx] = bm_load(Multi_ts_bmap_names[gr_screen.res][idx]); } // blast the team data clean memset(Multi_ts_team,0,sizeof(ts_team_data) * MULTI_TS_MAX_TEAMS); // assign the correct players to the correct slots multi_ts_init_players(); // assign the correct objnums to the correct slots multi_ts_init_objnums(); // sync the interface as normal multi_ts_sync_interface(); } // do frame for team select void multi_ts_do() { int k = chatbox_process(); k = Multi_ts_window.process(k); // process any keypresses switch(k){ case KEY_ESC : gamesnd_play_iface(SND_USER_SELECT); multi_quit_game(PROMPT_ALL); break; // cycle to the weapon select screen case KEY_TAB : gamesnd_play_iface(SND_USER_SELECT); Next_screen = ON_WEAPON_SELECT; gameseq_post_event(GS_EVENT_WEAPON_SELECTION); break; case KEY_ENTER|KEY_CTRLED: multi_ts_commit_pressed(); break; } // check any button presses multi_ts_check_buttons(); // handle all mouse related events multi_ts_handle_mouse(); // check for errors multi_ts_check_errors(); // draw the background, etc gr_reset_clip(); GR_MAYBE_CLEAR_RES(Multi_ts_bitmap); if(Multi_ts_bitmap != -1){ gr_set_bitmap(Multi_ts_bitmap); gr_bitmap(0,0); } Multi_ts_window.draw(); // render all wings multi_ts_blit_wings(); // blit all callsigns multi_ts_blit_wing_callsigns(); // blit the ships on the available list multi_ts_blit_avail_ships(); // force draw the ship select button Multi_ts_buttons[gr_screen.res][MULTI_TS_SHIP_SELECT].button.draw_forced(2); // force draw the "locked" button if necessary if(multi_ts_is_locked()){ Multi_ts_buttons[gr_screen.res][MULTI_TS_LOCK].button.draw_forced(2); } else { if( ((Netgame.type_flags & NG_TYPE_TEAM) && !(Net_player->flags & NETINFO_FLAG_TEAM_CAPTAIN)) || ((Netgame.type_flags & NG_TYPE_TEAM) && !(Net_player->flags & NETINFO_FLAG_GAME_HOST)) ){ Multi_ts_buttons[gr_screen.res][MULTI_TS_LOCK].button.draw_forced(0); } else { Multi_ts_buttons[gr_screen.res][MULTI_TS_LOCK].button.draw(); } } // blit any active ship information multi_ts_blit_ship_info(); // blit the status bar multi_ts_blit_status_bar(); // render the chatbox chatbox_render(); // render tooltips Multi_ts_window.draw_tooltip(); // display the status of the voice system multi_common_voice_display_status(); // blit any carried icons multi_ts_blit_carried_icon(); // flip the buffer gr_flip(); } // close the team select screen (always call, even when switching between weapon select, etc) void multi_ts_close() { int idx; if(!Multi_ts_inited){ return; } Multi_ts_inited = 0; // shut down the snazzy menu snazzy_menu_close(); // unload any bitmaps if(!bm_unload(Multi_ts_bitmap)){ nprintf(("General","WARNING : could not unload background bitmap %s\n",Multi_ts_bitmap_fname[gr_screen.res])); } for(idx=0;idx<MULTI_TS_NUM_LOCKED_BITMAPS;idx++){ if(Multi_ts_locked_bitmaps[idx] != -1){ bm_release(Multi_ts_locked_bitmaps[idx]); Multi_ts_locked_bitmaps[idx] = -1; } } // destroy the UI_WINDOW Multi_ts_window.destroy(); } // is the given slot disabled for the specified player int multi_ts_disabled_slot(int slot_num, int player_index) { net_player *pl; // get the appropriate net player if(player_index == -1){ pl = Net_player; } else { pl = &Net_players[player_index]; } // if the player is an observer, its _always_ disabled if(pl->flags & NETINFO_FLAG_OBSERVER){ return 1; } // if the flag for this team isn't set to "free" we can't do anything if(!Multi_ts_team[pl->p_info.team].multi_players_locked){ return 1; } // if the "leaders" only flag is set if(Netgame.options.flags & MSO_FLAG_SS_LEADERS){ // in a team vs. team situation if(Netgame.type_flags & NG_TYPE_TEAM){ if(pl->flags & NETINFO_FLAG_TEAM_CAPTAIN){ return 0; } } // in a non team vs. team situation else { if(pl->flags & NETINFO_FLAG_GAME_HOST){ return 0; } } } else { // in a team vs. team situation if(Netgame.type_flags & NG_TYPE_TEAM){ // if i'm the team captain I can mess with my own ships as well as those of the ai ships on my team if(pl->flags & NETINFO_FLAG_TEAM_CAPTAIN){ if((Multi_ts_team[pl->p_info.team].multi_ts_player[slot_num] != NULL) && (Objects[Multi_ts_team[pl->p_info.team].multi_ts_objnum[slot_num]].flags & OF_PLAYER_SHIP) && (slot_num != pl->p_info.ship_index)){ return 1; } return 0; } } // in a non team vs. team situation else { // if we're the host, we can our own ship and ai ships if(pl->flags & NETINFO_FLAG_GAME_HOST){ // can't grab player ships if((Multi_ts_team[pl->p_info.team].multi_ts_player[slot_num] != NULL) && (Objects[Multi_ts_team[pl->p_info.team].multi_ts_objnum[slot_num]].flags & OF_PLAYER_SHIP) && (slot_num != pl->p_info.ship_index)){ return 1; } return 0; } } // if this is our slot, then we can grab it if(slot_num == pl->p_info.ship_index){ return 0; } } return 1; } // is the given slot disabled for the specified player, _and_ it is his ship as well int multi_ts_disabled_high_slot(int slot_index,int player_index) { net_player *pl; // get the appropriate net player if(player_index == -1){ pl = Net_player; } else { pl = &Net_players[player_index]; } // if this is disabled for him and its also _his_ slot if(multi_ts_disabled_slot(slot_index,player_index) && !Multi_ts_team[pl->p_info.team].multi_players_locked && (slot_index == pl->p_info.ship_index)){ return 1; } return 0; } // resynch all display/interface elements based upon all the ship/weapon pool values void multi_ts_sync_interface() { int idx; // item 1 - determine how many ship types are available in the ship pool Multi_ts_avail_count = 0; for(idx=0;idx<MAX_SHIP_TYPES;idx++){ if(Ss_pool[idx] > 0){ Multi_ts_avail_count++; } } // item 2 - make sure our local Multi_ts_slot_flag array is up to date multi_ts_init_flags(); // item 3 - set/unset any necessary flags in underlying ship select data structures for(idx=0;idx<MAX_WSS_SLOTS;idx++){ switch(Multi_ts_team[Net_player->p_info.team].multi_ts_flag[idx]){ case MULTI_TS_FLAG_EMPTY : ss_make_slot_empty(idx); break; case MULTI_TS_FLAG_NONE : break; default : ss_make_slot_full(idx); break; } } // item 4 - reset the locked/unlocked status of all ships in the weapon select screen ss_recalc_multiplayer_slots(); } void multi_ts_assign_players_all() { int idx,team_index,slot_index,found,player_count,shipnum; char name_lookup[100]; object *objp; // set all player ship indices to -1 for(idx=0;idx<MAX_PLAYERS;idx++){ if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_STANDALONE(Net_players[idx])){ Net_players[idx].p_info.ship_index = -1; } } // merge the created object list with the actual object list so we have all available ships obj_merge_created_list(); // get the # of players currently in the game player_count = multi_num_players(); // always assign the host to Alpha 1 (or Zeta 1 in team vs. team - as appropriate) memset(name_lookup,0,100); if(Netgame.type_flags & NG_TYPE_TEAM){ switch(Netgame.host->p_info.team){ case 0 : strcpy(name_lookup,NOX("alpha 1")); break; case 1 : strcpy(name_lookup,NOX("zeta 1")); break; } } else { strcpy(name_lookup,NOX("alpha 1")); } shipnum = ship_name_lookup(name_lookup); // if we couldn't find the ship for the host if(shipnum == -1){ // Netgame.flags |= NG_FLAG_QUITTING; multi_quit_game(PROMPT_NONE, MULTI_END_NOTIFY_NONE, MULTI_END_ERROR_SHIP_ASSIGN); return; } multi_ts_get_team_and_slot(Ships[shipnum].ship_name,&team_index,&slot_index); multi_assign_player_ship(NET_PLAYER_INDEX(Netgame.host),&Objects[Ships[shipnum].objnum],Ships[shipnum].ship_info_index); Netgame.host->p_info.ship_index = slot_index; Assert(Netgame.host->p_info.ship_index >= 0); Netgame.host->p_info.ship_class = Ships[shipnum].ship_info_index; Netgame.host->player->objnum = Ships[shipnum].objnum; // for each netplayer, try and find a ship objp = GET_FIRST(&obj_used_list); while(objp != END_OF_LIST(&obj_used_list)){ // find a valid player ship - ignoring the ship which was assigned to the host if((objp->flags & OF_PLAYER_SHIP) && stricmp(Ships[objp->instance].ship_name,name_lookup)){ // determine what team and slot this ship is multi_ts_get_team_and_slot(Ships[objp->instance].ship_name,&team_index,&slot_index); Assert((team_index != -1) && (slot_index != -1)); // in a team vs. team situation if(Netgame.type_flags & NG_TYPE_TEAM){ // find a player on this team who needs a ship found = 0; for(idx=0;idx<MAX_PLAYERS;idx++){ if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_STANDALONE(Net_players[idx]) && !MULTI_OBSERVER(Net_players[idx]) && (Net_players[idx].p_info.ship_index == -1) && (Net_players[idx].p_info.team == team_index)){ found = 1; break; } } } // in a non team vs. team situation else { // find any player on this who needs a ship found = 0; for(idx=0;idx<MAX_PLAYERS;idx++){ if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_STANDALONE(Net_players[idx]) && !MULTI_OBSERVER(Net_players[idx]) && (Net_players[idx].p_info.ship_index == -1)){ found = 1; break; } } } // if we found a player if(found){ multi_assign_player_ship(idx,objp,Ships[objp->instance].ship_info_index); Net_players[idx].p_info.ship_index = slot_index; Assert(Net_players[idx].p_info.ship_index >= 0); Net_players[idx].p_info.ship_class = Ships[objp->instance].ship_info_index; Net_players[idx].player->objnum = OBJ_INDEX(objp); // decrement the player count player_count--; } else { objp->flags &= ~OF_PLAYER_SHIP; obj_set_flags( objp, objp->flags | OF_COULD_BE_PLAYER ); } // if we've assigned all players, we're done if(player_count <= 0){ break; } } // move to the next item objp = GET_NEXT(objp); } // go through and change any ships marked as player ships to be COULD_BE_PLAYER if ( objp != END_OF_LIST(&obj_used_list) ) { for ( objp = GET_NEXT(objp); objp != END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) { if ( objp->flags & OF_PLAYER_SHIP ){ objp->flags &= ~OF_PLAYER_SHIP; obj_set_flags( objp, objp->flags | OF_COULD_BE_PLAYER ); } } } if(Game_mode & GM_STANDALONE_SERVER){ Player_obj = NULL; Net_player->player->objnum = -1; } // check to make sure all players were assigned correctly for(idx=0;idx<MAX_PLAYERS;idx++){ if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_STANDALONE(Net_players[idx]) && !MULTI_OBSERVER(Net_players[idx])){ // if this guy never got assigned a player ship, there's a mission problem if(Net_players[idx].p_info.ship_index == -1){ // Netgame.flags |= NG_FLAG_QUITTING; multi_quit_game(PROMPT_NONE, MULTI_END_NOTIFY_NONE, MULTI_END_ERROR_SHIP_ASSIGN); return; } } } } // delete ships which have been removed from the game, tidy things void multi_ts_create_wings() { int idx,s_idx; // the standalone never went through this screen so he should never call this function! // the standalone and all other clients will have this equivalent function performed whey they receieve // the post_sync_data_packet!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Assert(!(Game_mode & GM_STANDALONE_SERVER)); // check status of all ships and delete or change ship type as necessary Multi_ts_num_deleted = 0; for(idx=0;idx<MULTI_TS_MAX_TEAMS;idx++){ for(s_idx=0;s_idx<MULTI_TS_NUM_SHIP_SLOTS;s_idx++){ // otherwise if there's a valid ship in this spot if(Multi_ts_team[idx].multi_ts_flag[s_idx] >= 0){ int objnum; // set the ship type appropriately Assert(Wss_slots_teams[idx][s_idx].ship_class >= 0); objnum = Multi_ts_team[idx].multi_ts_objnum[s_idx]; change_ship_type(Objects[objnum].instance,Wss_slots_teams[idx][s_idx].ship_class); // set the ship weapons correctly wl_update_ship_weapons(objnum,&Wss_slots_teams[idx][s_idx]); // assign ts_index of the ship to point to the proper Wss_slots slot Ships[Objects[objnum].instance].ts_index = s_idx; } else if(Multi_ts_team[idx].multi_ts_flag[s_idx] == MULTI_TS_FLAG_EMPTY){ Assert(Multi_ts_team[idx].multi_ts_objnum[s_idx] >= 0); // mark the object as having been deleted Multi_ts_deleted_objnums[Multi_ts_num_deleted] = Multi_ts_team[idx].multi_ts_objnum[s_idx]; // delete the ship ship_add_exited_ship( &Ships[Objects[Multi_ts_deleted_objnums[Multi_ts_num_deleted]].instance], SEF_PLAYER_DELETED ); obj_delete(Multi_ts_deleted_objnums[Multi_ts_num_deleted]); ship_wing_cleanup(Objects[Multi_ts_deleted_objnums[Multi_ts_num_deleted]].instance,&Wings[Ships[Objects[Multi_ts_team[idx].multi_ts_objnum[s_idx]].instance].wingnum]); // increment the # of ships deleted Multi_ts_num_deleted++; } } } } // do any necessary processing for players who have left the game void multi_ts_handle_player_drop() { int idx,s_idx; // find the player for(idx=0;idx<MULTI_TS_MAX_TEAMS;idx++){ for(s_idx=0;s_idx<MULTI_TS_NUM_SHIP_SLOTS;s_idx++){ // if we found him, clear his player slot and set his object back to being OF_COULD_BE_PLAYER if((Multi_ts_team[idx].multi_ts_player[s_idx] != NULL) && !MULTI_CONNECTED((*Multi_ts_team[idx].multi_ts_player[s_idx]))){ Assert(Multi_ts_team[idx].multi_ts_objnum[s_idx] != -1); Multi_ts_team[idx].multi_ts_player[s_idx] = NULL; Objects[Multi_ts_team[idx].multi_ts_objnum[s_idx]].flags &= ~(OF_PLAYER_SHIP); obj_set_flags( &Objects[Multi_ts_team[idx].multi_ts_objnum[s_idx]], Objects[Multi_ts_team[idx].multi_ts_objnum[s_idx]].flags | OF_COULD_BE_PLAYER); } } } } // set the status bar to reflect the status of wing slots (free or not free). 0 or 1 are valid values for now void multi_ts_set_status_bar_mode(int m) { Multi_ts_status_bar_mode = m; } // blit the proper "locked" button - used for weapon select and briefing screens void multi_ts_blit_locked_button() { // if we're locked down and we have a valid bitmap if((Multi_ts_team[Net_player->p_info.team].multi_players_locked) && (Multi_ts_locked_bitmaps[2] != -1)){ gr_set_bitmap(Multi_ts_locked_bitmaps[2]); gr_bitmap(Multi_ts_buttons[gr_screen.res][MULTI_TS_LOCK].x, Multi_ts_buttons[gr_screen.res][MULTI_TS_LOCK].y); } // draw as "not locked" if possible else if(Multi_ts_locked_bitmaps[0] != -1){ gr_set_bitmap(Multi_ts_locked_bitmaps[0]); gr_bitmap( Multi_ts_buttons[gr_screen.res][MULTI_TS_LOCK].x, Multi_ts_buttons[gr_screen.res][MULTI_TS_LOCK].y); } } // the "lock" button has been pressed void multi_ts_lock_pressed() { // do nothing if the button has already been pressed if(multi_ts_is_locked()){ gamesnd_play_iface(SND_GENERAL_FAIL); return; } if(Netgame.type_flags & NG_TYPE_TEAM){ Assert(Net_player->flags & NETINFO_FLAG_TEAM_CAPTAIN); } else { Assert(Net_player->flags & NETINFO_FLAG_GAME_HOST); } gamesnd_play_iface(SND_USER_SELECT); // send a final player slot update packet send_pslot_update_packet(Net_player->p_info.team,TS_CODE_LOCK_TEAM,-1); Multi_ts_team[Net_player->p_info.team].multi_players_locked = 1; // sync interface stuff multi_ts_set_status_bar_mode(1); multi_ts_sync_interface(); ss_recalc_multiplayer_slots(); // disable this button now Multi_ts_buttons[gr_screen.res][MULTI_TS_LOCK].button.disable(); } // if i'm "locked" int multi_ts_is_locked() { return Multi_ts_team[Net_player->p_info.team].multi_players_locked; } // show a popup saying "only host and team captains can modify, etc, etc" void multi_ts_maybe_host_only_popup() { /* // if this is because the "host modifies" option is set if((Netgame.options.flags & MSO_FLAG_SS_LEADERS) && !(Net_player->flags & NETINFO_FLAG_GAME_HOST) && !(Net_player->flags & NETINFO_FLAG_TEAM_CAPTAIN)){ multi_ts_host_only_popup(); } if(Netgame.type == NG_TYPE_TEAM){ popup(PF_USE_AFFIRMATIVE_ICON,1,POPUP_OK,"Only team captains may modify ships and weapons in this game"); } else { popup(PF_USE_AFFIRMATIVE_ICON,1,POPUP_OK,"Only the host may modify ships and weapons in this game"); } */ } // ------------------------------------------------------------------------------------------------------ // TEAM SELECT FORWARD DEFINITIONS // // check for button presses void multi_ts_check_buttons() { int idx; for(idx=0;idx<MULTI_TS_NUM_BUTTONS;idx++){ // we only really need to check for one button pressed at a time, so we can break after // finding one. if(Multi_ts_buttons[gr_screen.res][idx].button.pressed()){ multi_ts_button_pressed(idx); break; } } } // act on a button press void multi_ts_button_pressed(int n) { switch(n){ // back to the briefing screen case MULTI_TS_BRIEFING : gamesnd_play_iface(SND_USER_SELECT); Next_screen = ON_BRIEFING_SELECT; gameseq_post_event( GS_EVENT_START_BRIEFING ); break; // already on this screen case MULTI_TS_SHIP_SELECT: gamesnd_play_iface(SND_GENERAL_FAIL); break; // back to the weapon select screen case MULTI_TS_WEAPON_SELECT: gamesnd_play_iface(SND_USER_SELECT); Next_screen = ON_WEAPON_SELECT; gameseq_post_event(GS_EVENT_WEAPON_SELECTION); break; // scroll the available ships list down case MULTI_TS_SHIPS_DOWN: multi_ts_avail_scroll_down(); break; // scroll the available ships list up case MULTI_TS_SHIPS_UP: multi_ts_avail_scroll_up(); break; // free ship/weapon select case MULTI_TS_LOCK: Assert(Game_mode & GM_MULTIPLAYER); // the "lock" button has been pressed multi_ts_lock_pressed(); // disable the button if it is now locked if(multi_ts_is_locked()){ Multi_ts_buttons[gr_screen.res][MULTI_TS_LOCK].button.disable(); } break; // commit button case MULTI_TS_COMMIT : multi_ts_commit_pressed(); break; default : gamesnd_play_iface(SND_GENERAL_FAIL); break; } } // initialize all screen data, etc void multi_ts_init_graphics() { int idx; // create the interface window Multi_ts_window.create(0,0,gr_screen.max_w,gr_screen.max_h,0); Multi_ts_window.set_mask_bmap(Multi_ts_bitmap_mask_fname[gr_screen.res]); // load the background bitmap Multi_ts_bitmap = bm_load(Multi_ts_bitmap_fname[gr_screen.res]); if(Multi_ts_bitmap < 0){ // we failed to load the bitmap - this is very bad Int3(); } // create the interface buttons for(idx=0;idx<MULTI_TS_NUM_BUTTONS;idx++){ // create the object if((idx == MULTI_TS_SHIPS_UP) || (idx == MULTI_TS_SHIPS_DOWN)){ Multi_ts_buttons[gr_screen.res][idx].button.create(&Multi_ts_window, "", Multi_ts_buttons[gr_screen.res][idx].x, Multi_ts_buttons[gr_screen.res][idx].y, 1, 1, 1, 1); } else { Multi_ts_buttons[gr_screen.res][idx].button.create(&Multi_ts_window, "", Multi_ts_buttons[gr_screen.res][idx].x, Multi_ts_buttons[gr_screen.res][idx].y, 1, 1, 0, 1); } // set the sound to play when highlighted Multi_ts_buttons[gr_screen.res][idx].button.set_highlight_action(common_play_highlight_sound); // set the ani for the button Multi_ts_buttons[gr_screen.res][idx].button.set_bmaps(Multi_ts_buttons[gr_screen.res][idx].filename); // set the hotspot Multi_ts_buttons[gr_screen.res][idx].button.link_hotspot(Multi_ts_buttons[gr_screen.res][idx].hotspot); } // add some text Multi_ts_window.add_XSTR("Briefing", 765, Multi_ts_buttons[gr_screen.res][MULTI_TS_BRIEFING].xt, Multi_ts_buttons[gr_screen.res][MULTI_TS_BRIEFING].yt, &Multi_ts_buttons[gr_screen.res][MULTI_TS_BRIEFING].button, UI_XSTR_COLOR_GREEN); Multi_ts_window.add_XSTR("Ship Selection", 1067, Multi_ts_buttons[gr_screen.res][MULTI_TS_SHIP_SELECT].xt, Multi_ts_buttons[gr_screen.res][MULTI_TS_SHIP_SELECT].yt, &Multi_ts_buttons[gr_screen.res][MULTI_TS_SHIP_SELECT].button, UI_XSTR_COLOR_GREEN); Multi_ts_window.add_XSTR("Weapon Loadout", 1068, Multi_ts_buttons[gr_screen.res][MULTI_TS_WEAPON_SELECT].xt, Multi_ts_buttons[gr_screen.res][MULTI_TS_WEAPON_SELECT].yt, &Multi_ts_buttons[gr_screen.res][MULTI_TS_WEAPON_SELECT].button, UI_XSTR_COLOR_GREEN); Multi_ts_window.add_XSTR("Commit", 1062, Multi_ts_buttons[gr_screen.res][MULTI_TS_COMMIT].xt, Multi_ts_buttons[gr_screen.res][MULTI_TS_COMMIT].yt, &Multi_ts_buttons[gr_screen.res][MULTI_TS_COMMIT].button, UI_XSTR_COLOR_PINK); Multi_ts_window.add_XSTR("Lock", 1270, Multi_ts_buttons[gr_screen.res][MULTI_TS_LOCK].xt, Multi_ts_buttons[gr_screen.res][MULTI_TS_LOCK].yt, &Multi_ts_buttons[gr_screen.res][MULTI_TS_LOCK].button, UI_XSTR_COLOR_GREEN); // Multi_ts_window.add_XSTR("Help", 928, Multi_ts_buttons[Current_screen-1][gr_screen.res][COMMON_HELP_BUTTON].xt, Multi_ts_buttons[Current_screen-1][gr_screen.res][COMMON_HELP_BUTTON].yt, &Multi_ts_buttons[Current_screen-1][gr_screen.res][COMMON_HELP_BUTTON].button, UI_XSTR_COLOR_GREEN); // Multi_ts_window.add_XSTR("Options", 1036, Multi_ts_buttons[Current_screen-1][gr_screen.res][COMMON_OPTIONS_BUTTON].xt, Multi_ts_buttons[Current_screen-1][gr_screen.res][COMMON_OPTIONS_BUTTON].yt, &Multi_ts_buttons[Current_screen-1][gr_screen.res][COMMON_OPTIONS_BUTTON].button, UI_XSTR_COLOR_GREEN); // make the ship scrolling lists // if we're not the host of the game (or a tema captain in team vs. team mode), disable the lock button if (Netgame.type_flags & NG_TYPE_TEAM) { if(!(Net_player->flags & NETINFO_FLAG_TEAM_CAPTAIN)){ Multi_ts_buttons[gr_screen.res][MULTI_TS_LOCK].button.disable(); } } else { if(!(Net_player->flags & NETINFO_FLAG_GAME_HOST)){ Multi_ts_buttons[gr_screen.res][MULTI_TS_LOCK].button.disable(); } } // initialize the snazzy menu stuff (for grabbing ships, names, etc) multi_ts_init_snazzy(); // create the chatbox (again, should not be necessary at this point) chatbox_create(); // sync the interface as normal multi_ts_sync_interface(); } // blit all of the icons representing all wings void multi_ts_blit_wings() { int idx; // blit them all blindly for now for(idx=0;idx<MAX_WSS_SLOTS;idx++){ // if this ship doesn't exist, then continue if(Multi_ts_team[Net_player->p_info.team].multi_ts_flag[idx] == MULTI_TS_FLAG_NONE){ continue; } // otherwise blit the ship icon or the "empty" icon if(Multi_ts_team[Net_player->p_info.team].multi_ts_flag[idx] == MULTI_TS_FLAG_EMPTY){ ss_blit_ship_icon(Multi_ts_slot_icon_coords[idx][gr_screen.res][MULTI_TS_X_COORD],Multi_ts_slot_icon_coords[idx][gr_screen.res][MULTI_TS_Y_COORD],-1,0); } else { ss_blit_ship_icon(Multi_ts_slot_icon_coords[idx][gr_screen.res][MULTI_TS_X_COORD],Multi_ts_slot_icon_coords[idx][gr_screen.res][MULTI_TS_Y_COORD],Wss_slots[idx].ship_class,multi_ts_slot_bmap_num(idx)); // if this is a team vs team game, and the slot is occupised by a team captain, put a c there if((Netgame.type_flags & NG_TYPE_TEAM) && (Multi_ts_team[Net_player->p_info.team].multi_ts_player[idx] != NULL) && (Multi_ts_team[Net_player->p_info.team].multi_ts_player[idx]->flags & NETINFO_FLAG_TEAM_CAPTAIN)){ gr_set_color_fast(&Color_bright); gr_string(Multi_ts_slot_icon_coords[idx][gr_screen.res][MULTI_TS_X_COORD] - 5,Multi_ts_slot_icon_coords[idx][gr_screen.res][MULTI_TS_Y_COORD] - 5,XSTR("C",737)); // [[ Team captain ]] } } } } // blit all of the player callsigns under the correct ships void multi_ts_blit_wing_callsigns() { int idx,callsign_w; char callsign[CALLSIGN_LEN+2]; p_object *pobj; // blit them all blindly for now for(idx=0;idx<MAX_WSS_SLOTS;idx++){ // if this ship doesn't exist, then continue if(Multi_ts_team[Net_player->p_info.team].multi_ts_flag[idx] == MULTI_TS_FLAG_NONE){ continue; } // if there is a player in the slot if(Multi_ts_team[Net_player->p_info.team].multi_ts_player[idx] != NULL){ // make sure the string fits strcpy(callsign,Multi_ts_team[Net_player->p_info.team].multi_ts_player[idx]->player->callsign); } else { // determine if this is a locked AI ship pobj = mission_parse_get_arrival_ship(Ships[Objects[Multi_ts_team[Net_player->p_info.team].multi_ts_objnum[idx]].instance].ship_name); if((pobj == NULL) || !(pobj->flags & OF_PLAYER_SHIP)){ strcpy(callsign, NOX("<")); strcat(callsign,XSTR("AI",738)); // [[ Artificial Intellegence ]] strcat(callsign, NOX(">")); } else { strcpy(callsign,XSTR("AI",738)); // [[ Artificial Intellegence ]] } } gr_force_fit_string(callsign, CALLSIGN_LEN, Multi_ts_slot_text_coords[idx][gr_screen.res][MULTI_TS_W_COORD]); // get the final length gr_get_string_size(&callsign_w, NULL, callsign); // blit the string if((Multi_ts_hotspot_type == MULTI_TS_PLAYER_LIST) && (Multi_ts_hotspot_index == idx) && (Multi_ts_team[Net_player->p_info.team].multi_ts_player[idx] != NULL)){ gr_set_color_fast(&Color_text_active_hi); } else { gr_set_color_fast(&Color_normal); } gr_string(Multi_ts_slot_text_coords[idx][gr_screen.res][MULTI_TS_X_COORD] + ((Multi_ts_slot_text_coords[idx][gr_screen.res][MULTI_TS_W_COORD] - callsign_w)/2),Multi_ts_slot_text_coords[idx][gr_screen.res][MULTI_TS_Y_COORD],callsign); } } // blit the ships on the avail list void multi_ts_blit_avail_ships() { int display_count,ship_count,idx; char count[6]; // blit the availability of all ship counts display_count = 0; ship_count = 0; for(idx=0;idx<MAX_SHIP_TYPES;idx++){ if(Ss_pool[idx] > 0){ // if our starting display index is after this, then skip it if(ship_count < Multi_ts_avail_start){ ship_count++; } else { // blit the icon ss_blit_ship_icon(Multi_ts_avail_coords[display_count][gr_screen.res][MULTI_TS_X_COORD],Multi_ts_avail_coords[display_count][gr_screen.res][MULTI_TS_Y_COORD],idx,multi_ts_avail_bmap_num(display_count)); // blit the ship count available sprintf(count,"%d",Ss_pool[idx]); gr_set_color_fast(&Color_normal); gr_string(Multi_ts_avail_coords[display_count][gr_screen.res][MULTI_TS_X_COORD] - 20,Multi_ts_avail_coords[display_count][gr_screen.res][MULTI_TS_Y_COORD],count); // increment the counts display_count++; ship_count++; } } // if we've reached the max amount we can display, then stop if(display_count >= MULTI_TS_AVAIL_MAX_DISPLAY){ return; } } } // initialize the snazzy menu stuff for dragging ships,players around void multi_ts_init_snazzy() { // initialize the snazzy menu snazzy_menu_init(); // blast the data Multi_ts_snazzy_regions = 0; memset(Multi_ts_region,0,sizeof(MENU_REGION) * MULTI_TS_NUM_SNAZZY_REGIONS); // get a pointer to the mask bitmap data Multi_ts_mask_data = (ubyte*)Multi_ts_window.get_mask_data(&Multi_ts_mask_w, &Multi_ts_mask_h); // add the wing slots information snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_0_SHIP_0, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_0_SHIP_1, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_0_SHIP_2, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_0_SHIP_3, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_1_SHIP_0, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_1_SHIP_1, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_1_SHIP_2, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_1_SHIP_3, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_2_SHIP_0, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_2_SHIP_1, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_2_SHIP_2, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_2_SHIP_3, 0); // add the name slots information snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_0_NAME_0, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_0_NAME_1, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_0_NAME_2, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_0_NAME_3, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_1_NAME_0, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_1_NAME_1, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_1_NAME_2, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_1_NAME_3, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_2_NAME_0, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_2_NAME_1, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_2_NAME_2, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_2_NAME_3, 0); // add the available ships region snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_LIST_0, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_LIST_1, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_LIST_2, 0); snazzy_menu_add_region(&Multi_ts_region[Multi_ts_snazzy_regions++], "", TSWING_LIST_3, 0); } // what type of region the index is (0 == ship avail list, 1 == ship slots, 2 == player slot) int multi_ts_region_type(int region) { if((region == TSWING_0_SHIP_0) || (region == TSWING_0_SHIP_1) || (region == TSWING_0_SHIP_2) || (region == TSWING_0_SHIP_3) || (region == TSWING_1_SHIP_0) || (region == TSWING_1_SHIP_1) || (region == TSWING_1_SHIP_2) || (region == TSWING_1_SHIP_3) || (region == TSWING_2_SHIP_0) || (region == TSWING_2_SHIP_1) || (region == TSWING_2_SHIP_2) || (region == TSWING_2_SHIP_3) ){ return MULTI_TS_SLOT_LIST; } if((region == TSWING_0_NAME_0) || (region == TSWING_0_NAME_1) || (region == TSWING_0_NAME_2) || (region == TSWING_0_NAME_3) || (region == TSWING_1_NAME_0) || (region == TSWING_1_NAME_1) || (region == TSWING_1_NAME_2) || (region == TSWING_1_NAME_3) || (region == TSWING_2_NAME_0) || (region == TSWING_2_NAME_1) || (region == TSWING_2_NAME_2) || (region == TSWING_2_NAME_3) ){ return MULTI_TS_PLAYER_LIST; } if((region == TSWING_LIST_0) || (region == TSWING_LIST_1) || (region == TSWING_LIST_2) || (region == TSWING_LIST_3)){ return MULTI_TS_AVAIL_LIST; } return -1; } // convert the region num to a ship slot index int multi_ts_slot_index(int region) { switch(region){ case TSWING_0_SHIP_0: return 0; case TSWING_0_SHIP_1: return 1; case TSWING_0_SHIP_2: return 2; case TSWING_0_SHIP_3: return 3; case TSWING_1_SHIP_0: return 4; case TSWING_1_SHIP_1: return 5; case TSWING_1_SHIP_2: return 6; case TSWING_1_SHIP_3: return 7; case TSWING_2_SHIP_0: return 8; case TSWING_2_SHIP_1: return 9; case TSWING_2_SHIP_2: return 10; case TSWING_2_SHIP_3: return 11; } return -1; } // convert the region num to an avail list index (starting from absolute 0) int multi_ts_avail_index(int region) { switch(region){ case TSWING_LIST_0: return 0; case TSWING_LIST_1: return 1; case TSWING_LIST_2: return 2; case TSWING_LIST_3: return 3; } return -1; } // convert the region num to a player slot index int multi_ts_player_index(int region) { switch(region){ case TSWING_0_NAME_0: return 0; case TSWING_0_NAME_1: return 1; case TSWING_0_NAME_2: return 2; case TSWING_0_NAME_3: return 3; case TSWING_1_NAME_0: return 4; case TSWING_1_NAME_1: return 5; case TSWING_1_NAME_2: return 6; case TSWING_1_NAME_3: return 7; case TSWING_2_NAME_0: return 8; case TSWING_2_NAME_1: return 9; case TSWING_2_NAME_2: return 10; case TSWING_2_NAME_3: return 11; } return -1; } // blit any active ship information text void multi_ts_blit_ship_info() { int y_start; ship_info *sip; char str[100]; // if we don't have a valid ship selected, do nothing if(Multi_ts_select_ship_class == -1){ return; } // get the ship class sip = &Ship_info[Multi_ts_select_ship_class]; // starting line y_start = Multi_ts_ship_info_coords[gr_screen.res][MULTI_TS_Y_COORD]; memset(str,0,100); // blit the ship class (name) gr_set_color_fast(&Color_normal); gr_string(Multi_ts_ship_info_coords[gr_screen.res][MULTI_TS_X_COORD], y_start,XSTR("Class",739)); if(strlen(sip->name)){ gr_set_color_fast(&Color_bright); gr_string(Multi_ts_ship_info_coords[gr_screen.res][MULTI_TS_X_COORD] + 150, y_start,sip->name); } y_start += 10; // blit the ship type gr_set_color_fast(&Color_normal); gr_string(Multi_ts_ship_info_coords[gr_screen.res][MULTI_TS_X_COORD], y_start,XSTR("Type",740)); if((sip->type_str != NULL) && strlen(sip->type_str)){ gr_set_color_fast(&Color_bright); gr_string(Multi_ts_ship_info_coords[gr_screen.res][MULTI_TS_X_COORD] + 150, y_start,sip->type_str); } y_start += 10; // blit the ship length gr_set_color_fast(&Color_normal); gr_string(Multi_ts_ship_info_coords[gr_screen.res][MULTI_TS_X_COORD], y_start,XSTR("Length",741)); if((sip->ship_length != NULL) && strlen(sip->ship_length)){ gr_set_color_fast(&Color_bright); gr_string(Multi_ts_ship_info_coords[gr_screen.res][MULTI_TS_X_COORD] + 150, y_start,sip->ship_length); } y_start += 10; // blit the max velocity gr_set_color_fast(&Color_normal); gr_string(Multi_ts_ship_info_coords[gr_screen.res][MULTI_TS_X_COORD], y_start,XSTR("Max Velocity",742)); sprintf(str,XSTR("%d m/s",743),(int)sip->max_vel.z); gr_set_color_fast(&Color_bright); gr_string(Multi_ts_ship_info_coords[gr_screen.res][MULTI_TS_X_COORD] + 150, y_start,str); y_start += 10; // blit the maneuverability gr_set_color_fast(&Color_normal); gr_string(Multi_ts_ship_info_coords[gr_screen.res][MULTI_TS_X_COORD], y_start,XSTR("Maneuverability",744)); if((sip->maneuverability_str != NULL) && strlen(sip->maneuverability_str)){ gr_set_color_fast(&Color_bright); gr_string(Multi_ts_ship_info_coords[gr_screen.res][MULTI_TS_X_COORD] + 150, y_start,sip->maneuverability_str); } y_start += 10; // blit the armor gr_set_color_fast(&Color_normal); gr_string(Multi_ts_ship_info_coords[gr_screen.res][MULTI_TS_X_COORD], y_start,XSTR("Armor",745)); if((sip->armor_str != NULL) && strlen(sip->armor_str)){ gr_set_color_fast(&Color_bright); gr_string(Multi_ts_ship_info_coords[gr_screen.res][MULTI_TS_X_COORD] + 150, y_start,sip->armor_str); } y_start += 10; // blit the gun mounts gr_set_color_fast(&Color_normal); gr_string(Multi_ts_ship_info_coords[gr_screen.res][MULTI_TS_X_COORD], y_start,XSTR("Gun Mounts",746)); if((sip->gun_mounts != NULL) && strlen(sip->gun_mounts)){ gr_set_color_fast(&Color_bright); gr_string(Multi_ts_ship_info_coords[gr_screen.res][MULTI_TS_X_COORD] + 150, y_start,sip->gun_mounts); } y_start += 10; // blit the missile banke gr_set_color_fast(&Color_normal); gr_string(Multi_ts_ship_info_coords[gr_screen.res][MULTI_TS_X_COORD], y_start,XSTR("Missile Banks",747)); if((sip->missile_banks != NULL) && strlen(sip->missile_banks)){ gr_set_color_fast(&Color_bright); gr_string(Multi_ts_ship_info_coords[gr_screen.res][MULTI_TS_X_COORD] + 150, y_start,sip->missile_banks); } y_start += 10; // blit the manufacturer gr_set_color_fast(&Color_normal); gr_string(Multi_ts_ship_info_coords[gr_screen.res][MULTI_TS_X_COORD], y_start,XSTR("Manufacturer",748)); if((sip->manufacturer_str != NULL) && strlen(sip->manufacturer_str)){ gr_set_color_fast(&Color_bright); gr_string(Multi_ts_ship_info_coords[gr_screen.res][MULTI_TS_X_COORD] + 150, y_start,sip->manufacturer_str); } y_start += 10; // blit the _short_ text description /* Assert(Multi_ts_ship_info_line_count < 3); gr_set_color_fast(&Color_normal); for(idx=0;idx<Multi_ts_ship_info_line_count;idx++){ gr_string(Multi_ts_ship_info_coords[gr_screen.res][MULTI_TS_X_COORD], y_start, Multi_ts_ship_info_lines[idx]); y_start += 10; } */ } // blit the status bar void multi_ts_blit_status_bar() { char text[50]; int text_w; int blit = 0; // mode specific text switch(Multi_ts_status_bar_mode){ case 0 : strcpy(text,XSTR("Ships/Weapons Locked",749)); blit = 1; break; case 1 : strcpy(text,XSTR("Ships/Weapons Are Now Free",750)); blit = 1; break; } // if we should be blitting if(blit){ gr_get_string_size(&text_w,NULL,text); gr_set_color_fast(&Color_bright_blue); gr_string(Multi_ts_status_coords[gr_screen.res][MULTI_TS_X_COORD] + ((Multi_ts_status_coords[gr_screen.res][MULTI_TS_W_COORD] - text_w)/2),Multi_ts_status_coords[gr_screen.res][MULTI_TS_Y_COORD],text); } } // assign the correct players to the correct slots void multi_ts_init_players() { int idx; // if i'm an observer, i have no ship if(Net_player->flags & NETINFO_FLAG_OBSERVER){ Net_player->p_info.ship_index = -1; } // initialize all players and observer for(idx=0;idx<MAX_PLAYERS;idx++){ if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_STANDALONE(Net_players[idx])){ if(MULTI_OBSERVER(Net_players[idx])){ Net_players[idx].p_info.ship_index = -1; } else { Multi_ts_team[Net_players[idx].p_info.team].multi_ts_player[Net_players[idx].p_info.ship_index] = &Net_players[idx]; } } } } // assign the correct objnums to the correct slots void multi_ts_init_objnums() { int idx,s_idx,team_index,slot_index; object *objp; // zero out the indices for(idx=0;idx<MULTI_TS_MAX_TEAMS;idx++){ for(s_idx=0;s_idx<MULTI_TS_NUM_SHIP_SLOTS;s_idx++){ Multi_ts_team[idx].multi_ts_objnum[s_idx] = -1; } } // set all the objnums objp = GET_FIRST(&obj_used_list); while(objp != END_OF_LIST(&obj_used_list)){ // if its a ship, get its slot index (if any) if(objp->type == OBJ_SHIP){ multi_ts_get_team_and_slot(Ships[objp->instance].ship_name,&team_index,&slot_index); if((slot_index != -1) && (team_index != -1)){ Multi_ts_team[team_index].multi_ts_objnum[slot_index] = Ships[objp->instance].objnum; } } objp = GET_NEXT(objp); } } // get the proper team and slot index for the given ship name void multi_ts_get_team_and_slot(char *ship_name,int *team_index,int *slot_index) { int idx,s_idx; // set the return values to default values *team_index = -1; *slot_index = -1; // if we're in team vs. team mode if(Netgame.type_flags & NG_TYPE_TEAM){ for(idx=0;idx<MULTI_TS_MAX_TEAMS;idx++){ for(s_idx=0;s_idx<MULTI_TS_NUM_SHIP_SLOTS_TEAM;s_idx++){ if(!stricmp(ship_name,Multi_ts_slot_team_names[idx][s_idx])){ *team_index = idx; *slot_index = s_idx; return; } } } } // if we're _not_ in team vs. team mode else { for(idx=0;idx<MULTI_TS_NUM_SHIP_SLOTS;idx++){ if(!stricmp(ship_name,Multi_ts_slot_names[idx])){ *team_index = 0; *slot_index = idx; return; } } } } // function to return the shipname of the ship in the slot designated by the team and slot // parameters char *multi_ts_get_shipname( int team, int slot_index ) { if ( Netgame.type_flags & NG_TYPE_TEAM ) { Assert( (team >= 0) && (team < MULTI_TS_MAX_TEAMS) ); return Multi_ts_slot_team_names[team][slot_index]; } else { Assert( team == 0 ); return Multi_ts_slot_names[slot_index]; } } // assign the correct flags to the correct slots void multi_ts_init_flags() { int idx,s_idx; // zero out the flags for(idx=0;idx<MULTI_TS_MAX_TEAMS;idx++){ for(s_idx=0;s_idx<MULTI_TS_NUM_SHIP_SLOTS;s_idx++){ Multi_ts_team[idx].multi_ts_flag[s_idx] = MULTI_TS_FLAG_NONE; } } // in a team vs. team situation if(Netgame.type_flags & NG_TYPE_TEAM){ for(idx=0;idx<MULTI_TS_MAX_TEAMS;idx++){ for(s_idx=0;s_idx<MULTI_TS_NUM_SHIP_SLOTS_TEAM;s_idx++){ // if the there is an objnum here but no ship class, we know its currently empty if((Multi_ts_team[idx].multi_ts_objnum[s_idx] != -1) && (Wss_slots_teams[idx][s_idx].ship_class == -1)){ Multi_ts_team[idx].multi_ts_flag[s_idx] = MULTI_TS_FLAG_EMPTY; } else if((Multi_ts_team[idx].multi_ts_objnum[s_idx] != -1) && (Wss_slots_teams[idx][s_idx].ship_class != -1)){ Multi_ts_team[idx].multi_ts_flag[s_idx] = Wss_slots_teams[idx][s_idx].ship_class; } } } } // in a non team vs. team situation else { for(idx=0;idx<MULTI_TS_NUM_SHIP_SLOTS;idx++){ // if the there is an objnum here but no ship class, we know its currently empty if((Multi_ts_team[0].multi_ts_objnum[idx] != -1) && (Wss_slots[idx].ship_class == -1)){ Multi_ts_team[0].multi_ts_flag[idx] = MULTI_TS_FLAG_EMPTY; } else if((Multi_ts_team[0].multi_ts_objnum[idx] != -1) && (Wss_slots[idx].ship_class != -1)){ Multi_ts_team[0].multi_ts_flag[idx] = Wss_slots[idx].ship_class; } } } } // handle an available ship scroll down button press void multi_ts_avail_scroll_down() { if((Multi_ts_avail_count - Multi_ts_avail_start) > MULTI_TS_AVAIL_MAX_DISPLAY){ gamesnd_play_iface(SND_USER_SELECT); Multi_ts_avail_start++; } else { gamesnd_play_iface(SND_GENERAL_FAIL); } } // handle an available ship scroll up button press void multi_ts_avail_scroll_up() { if(Multi_ts_avail_start > 0){ gamesnd_play_iface(SND_USER_SELECT); Multi_ts_avail_start--; } else { gamesnd_play_iface(SND_GENERAL_FAIL); } } // handle all mouse events (clicking, dragging, and dropping) void multi_ts_handle_mouse() { int snazzy_region,snazzy_action; int region_type,region_index,region_empty; int mouse_x,mouse_y,ship_class; // get the mouse coords mouse_get_pos(&mouse_x,&mouse_y); // do frame for the snazzy menu snazzy_region = snazzy_menu_do(Multi_ts_mask_data, Multi_ts_mask_w, Multi_ts_mask_h, Multi_ts_snazzy_regions, Multi_ts_region, &snazzy_action, 0); region_type = -1; region_index = -1; region_empty = 1; ship_class = -1; if(snazzy_region != -1){ region_type = multi_ts_region_type(snazzy_region); Assert(region_type != -1); // determine what type of region the mouse is over and the appropriate index switch(region_type){ case MULTI_TS_AVAIL_LIST: region_index = multi_ts_avail_index(snazzy_region); ship_class = multi_ts_get_avail_ship_class(region_index); if(ship_class == -1){ region_empty = 1; } else { region_empty = (Ss_pool[ship_class] > 0) ? 0 : 1; } break; case MULTI_TS_SLOT_LIST: region_index = multi_ts_slot_index(snazzy_region); region_empty = (Multi_ts_team[Net_player->p_info.team].multi_ts_flag[region_index] >= 0) ? 0 : 1; if(!region_empty){ ship_class = Wss_slots[region_index].ship_class; } break; case MULTI_TS_PLAYER_LIST: region_index = multi_ts_player_index(snazzy_region); region_empty = (Multi_ts_team[Net_player->p_info.team].multi_ts_player[region_index] != NULL) ? 0 : 1; break; } } // maybe play a "highlight" sound switch(region_type){ case MULTI_TS_PLAYER_LIST: if((Multi_ts_hotspot_index != region_index) && (region_index >= 0) && (Multi_ts_team[Net_player->p_info.team].multi_ts_player[region_index] != NULL)){ gamesnd_play_iface(SND_USER_SELECT); } break; } // set the current frame mouse hotspot vars Multi_ts_hotspot_type = region_type; Multi_ts_hotspot_index = region_index; // if we currently have clicked on something and have just released it if(!Multi_ts_carried_flag && Multi_ts_clicked_flag && !mouse_down(MOUSE_LEFT_BUTTON)){ Multi_ts_clicked_flag = 0; } // if we're currently not carrying anything and the user has clicked if(!Multi_ts_carried_flag && !Multi_ts_clicked_flag && mouse_down(MOUSE_LEFT_BUTTON) && !region_empty){ // set the "clicked" flag Multi_ts_clicked_flag = 1; // check to see if he clicked on a ship type and highlight if necessary switch(region_type){ // selected a ship in the wing slots case MULTI_TS_SLOT_LIST: Multi_ts_select_type = MULTI_TS_SLOT_LIST; Multi_ts_select_index = region_index; multi_ts_select_ship(); break; // selected a ship on the avail list case MULTI_TS_AVAIL_LIST: Multi_ts_select_type = MULTI_TS_AVAIL_LIST; Multi_ts_select_index = region_index; multi_ts_select_ship(); break; // selected something else - unselect default : Multi_ts_select_type = -1; Multi_ts_select_index = -1; Multi_ts_select_ship_class = -1; break; } Multi_ts_clicked_x = mouse_x; Multi_ts_clicked_y = mouse_y; } // if we had something clicked and have started dragging it if(!Multi_ts_carried_flag && Multi_ts_clicked_flag && mouse_down(MOUSE_LEFT_BUTTON) && ((Multi_ts_clicked_x != mouse_x) || (Multi_ts_clicked_y != mouse_y))){ // if this player is an observer, he shouldn't be able to do jack if(Net_player->flags & NETINFO_FLAG_OBSERVER){ return; } // first we check for illegal conditions (any case where he cannot grab what he is attempting to grab) switch(region_type){ case MULTI_TS_AVAIL_LIST : // if players are not yet locked, can't grab ships if(!Multi_ts_team[Net_player->p_info.team].multi_players_locked){ return; } if(region_empty){ return; } break; case MULTI_TS_SLOT_LIST: // if players are not yet locked, can't grab ships if(!Multi_ts_team[Net_player->p_info.team].multi_players_locked){ return; } if(multi_ts_disabled_slot(region_index)){ multi_ts_maybe_host_only_popup(); return; } if(Multi_ts_team[Net_player->p_info.team].multi_ts_flag[region_index] < 0){ return; } break; case MULTI_TS_PLAYER_LIST: if(!multi_ts_can_grab_player(region_index)){ return; } break; } Multi_ts_clicked_flag = 0; Multi_ts_carried_flag = 1; // set up the carried icon here Multi_ts_carried_from_type = region_type; Multi_ts_carried_from_index = region_index; Multi_ts_carried_ship_class = ship_class; } // if we were carrying something but have dropped it if(Multi_ts_carried_flag && !mouse_down(MOUSE_LEFT_BUTTON)){ Multi_ts_carried_flag = 0; Multi_ts_clicked_flag = 0; // if we're not allowed to drop onto this slot if((region_type == MULTI_TS_SLOT_LIST) && multi_ts_disabled_slot(region_index)){ multi_ts_maybe_host_only_popup(); } // if we're over some kind of valid region, apply multi_ts_drop(Multi_ts_carried_from_type,Multi_ts_carried_from_index,region_type,region_index,Multi_ts_carried_ship_class); } } // can the specified player perform the action he is attempting int multi_ts_can_perform(int from_type,int from_index,int to_type,int to_index,int ship_class,int player_index) { net_player *pl; int op_type; p_object *pobj; // get the appropriate player if(player_index == -1){ pl = Net_player; } else { pl = &Net_players[player_index]; } // get the operation type op_type = multi_ts_get_dnd_type(from_type,from_index,to_type,to_index,player_index); // if either of the indices are bogus, then bail if((from_index == -1) || (to_index == -1)){ return 0; } switch(op_type){ case TS_GRAB_FROM_LIST: // if there are no more of this ship class, its no go if(Ss_pool_teams[pl->p_info.team][ship_class] <= 0){ return 0; } // if he's not allowed to touch the wing slot if(multi_ts_disabled_slot(to_index,player_index)){ return 0; } // if the slot he's trying to drop it on is "permanently" empty if(Multi_ts_team[pl->p_info.team].multi_ts_flag[to_index] == MULTI_TS_FLAG_NONE){ return 0; } break; case TS_SWAP_LIST_SLOT: // if there are no more of this ship class, its no go if(Ss_pool_teams[pl->p_info.team][ship_class] <= 0){ return 0; } // if he's not allowed to touch the wing slot if(multi_ts_disabled_slot(to_index,player_index)){ return 0; } // if the slot we're trying to move to is invalid, then do nothing if(Multi_ts_team[pl->p_info.team].multi_ts_flag[to_index] == MULTI_TS_FLAG_NONE){ return 0; } // if the slot he's trying to drop it on is "permanently" empty if(Multi_ts_team[pl->p_info.team].multi_ts_flag[to_index] == MULTI_TS_FLAG_NONE){ return 0; } break; case TS_SWAP_SLOT_SLOT: // if he's not allowed to touch one of the slots, its no go if(multi_ts_disabled_slot(from_index,player_index) || multi_ts_disabled_slot(to_index,player_index)){ return 0; } // if the slot we're taking from is invalid if(Multi_ts_team[pl->p_info.team].multi_ts_flag[to_index] == MULTI_TS_FLAG_NONE){ return 0; } // if the slot he's trying to drop it on is "permanently" empty if(Multi_ts_team[pl->p_info.team].multi_ts_flag[to_index] == MULTI_TS_FLAG_NONE){ return 0; } break; case TS_DUMP_TO_LIST: // if he's not allowed to be touching the slot to begin with, it no go if(multi_ts_disabled_slot(from_index,player_index)){ return 0; } // if the slot we're trying to move to is invalid, then do nothing if(Multi_ts_team[pl->p_info.team].multi_ts_flag[to_index] == MULTI_TS_FLAG_NONE){ return 0; } break; case TS_SWAP_PLAYER_PLAYER: // if his team is already locked, he cannot do this if(Multi_ts_team[pl->p_info.team].multi_players_locked){ return 0; } // if there isn't a player at one of the positions if((Multi_ts_team[pl->p_info.team].multi_ts_player[from_index] == NULL) || (Multi_ts_team[pl->p_info.team].multi_ts_player[to_index] == NULL)){ return 0; } // if this is not a player ship type object if(Multi_ts_team[pl->p_info.team].multi_ts_objnum[to_index] != -1){ pobj = mission_parse_get_arrival_ship(Ships[Objects[Multi_ts_team[pl->p_info.team].multi_ts_objnum[to_index]].instance].ship_name); if((pobj == NULL) || !(pobj->flags & OF_PLAYER_SHIP)){ return 0; } } if(Netgame.type_flags & NG_TYPE_TEAM){ // if he's not the team captain, he cannot do this if(!(pl->flags & NETINFO_FLAG_TEAM_CAPTAIN)){ return 0; } } else { // if he's not the host, he cannot do this if(!(pl->flags & NETINFO_FLAG_GAME_HOST)){ return 0; } } break; case TS_MOVE_PLAYER: // if his team is already locked, he cannot do this if(Multi_ts_team[pl->p_info.team].multi_players_locked){ return 0; } // if there isn't a player at the _from_ if(Multi_ts_team[pl->p_info.team].multi_ts_player[from_index] == NULL){ return 0; } // if there is no ship at the _to_ location if(Multi_ts_team[pl->p_info.team].multi_ts_objnum[to_index] < 0){ return 0; } // if this is not a player ship type object if(Multi_ts_team[pl->p_info.team].multi_ts_objnum[to_index] != -1){ pobj = mission_parse_get_arrival_ship(Ships[Objects[Multi_ts_team[pl->p_info.team].multi_ts_objnum[to_index]].instance].ship_name); if((pobj == NULL) || !(pobj->flags & OF_PLAYER_SHIP)){ return 0; } } if(Netgame.type_flags & NG_TYPE_TEAM){ // if he's not the team captain, he cannot do this if(!(pl->flags & NETINFO_FLAG_TEAM_CAPTAIN)){ return 0; } } else { // if he's not the host, he cannot do this if(!(pl->flags & NETINFO_FLAG_GAME_HOST)){ return 0; } } break; default : return 0; break; } return 1; } // determine the kind of drag and drop operation this is int multi_ts_get_dnd_type(int from_type,int from_index,int to_type,int to_index,int player_index) { net_player *pl; // get the appropriate player if(player_index == -1){ pl = Net_player; } else { pl = &Net_players[player_index]; } switch(from_type){ // came from the ship avail list case MULTI_TS_AVAIL_LIST : // do nothing if(to_type == MULTI_TS_AVAIL_LIST){ return -1; } // if placing it on a slot if(to_type == MULTI_TS_SLOT_LIST){ if(Wss_slots_teams[pl->p_info.team][to_index].ship_class == -1){ return TS_GRAB_FROM_LIST; } else { return TS_SWAP_LIST_SLOT; } } break; // came from the ship slots case MULTI_TS_SLOT_LIST : if(to_type == MULTI_TS_SLOT_LIST){ return TS_SWAP_SLOT_SLOT; } if(to_type == MULTI_TS_AVAIL_LIST){ return TS_DUMP_TO_LIST; } break; // came from the player lists case MULTI_TS_PLAYER_LIST : if(to_type == MULTI_TS_PLAYER_LIST){ if(Multi_ts_team[pl->p_info.team].multi_ts_player[to_index] == NULL){ return TS_MOVE_PLAYER; } else { return TS_SWAP_PLAYER_PLAYER; } } break; } return -1; } void multi_ts_apply(int from_type,int from_index,int to_type,int to_index,int ship_class,int player_index) { int size,update,sound; ubyte wss_data[MAX_PACKET_SIZE-20]; net_player *pl; // determine what kind of operation this is int type = multi_ts_get_dnd_type(from_type,from_index,to_type,to_index,player_index); // get the proper net player if(player_index == -1){ pl = Net_player; } else { pl = &Net_players[player_index]; } // set the proper pool pointers ss_set_team_pointers(pl->p_info.team); sound = -1; switch(type){ case TS_SWAP_SLOT_SLOT : nprintf(("Network","Apply swap slot slot %d %d\n",from_index,to_index)); update = ss_swap_slot_slot(from_index,to_index,&sound); break; case TS_DUMP_TO_LIST : nprintf(("Network","Apply dump to list %d %d\n",from_index,to_index)); update = ss_dump_to_list(from_index,ship_class,&sound); break; case TS_SWAP_LIST_SLOT : nprintf(("Network","Apply swap list slot %d %d\n",from_index,to_index)); update = ss_swap_list_slot(ship_class,to_index,&sound); break; case TS_GRAB_FROM_LIST : nprintf(("Network","Apply grab from list %d %d\n",from_index,to_index)); update = ss_grab_from_list(ship_class,to_index,&sound); break; case TS_SWAP_PLAYER_PLAYER : nprintf(("Network","Apply swap player player %d %d\n",from_index,to_index)); update = multi_ts_swap_player_player(from_index,to_index,&sound,player_index); break; case TS_MOVE_PLAYER : nprintf(("Network","Apply move player %d %d\n",from_index,to_index)); update = multi_ts_move_player(from_index,to_index,&sound,player_index); default : update = 0; break; } if(update){ // if we're the host, send an update to all players if ( MULTIPLAYER_HOST ) { // send the correct type of update if(type == TS_SWAP_PLAYER_PLAYER){ } else { size = store_wss_data(wss_data, MAX_PACKET_SIZE-20, sound, player_index); send_wss_update_packet(pl->p_info.team,wss_data, size); // send a player slot update packet as well, so ship class information, etc is kept correct send_pslot_update_packet(pl->p_info.team,TS_CODE_PLAYER_UPDATE,-1); } // if the player index == -1, it means the action was done locally - so play a sound if((player_index == -1) && (sound != -1)){ gamesnd_play_iface(sound); } } // sync the interface screen up ourselves, if necessary if(Net_player->p_info.team == pl->p_info.team){ multi_ts_sync_interface(); } // make sure all flags are set properly for all teams multi_ts_init_flags(); } // set the proper pool pointers ss_set_team_pointers(Net_player->p_info.team); } // drop a carried icon void multi_ts_drop(int from_type,int from_index,int to_type,int to_index,int ship_class,int player_index) { // if I'm the host, apply immediately if(Net_player->flags & NETINFO_FLAG_GAME_HOST){ // if this is a legal operation if(multi_ts_can_perform(from_type,from_index,to_type,to_index,ship_class,player_index)){ multi_ts_apply(from_type,from_index,to_type,to_index,ship_class,player_index); } else { nprintf(("Network","Could not apply operation!\n")); } } // otherwise send a request to the host else { send_wss_request_packet(Net_player->player_id, from_type, from_index, to_type, to_index, -1, ship_class, WSS_SHIP_SELECT); } } // swap two player positions int multi_ts_swap_player_player(int from_index,int to_index,int *sound,int player_index) { net_player *pl,*temp; // get the proper player pointer if(player_index == -1){ pl = Net_player; } else { pl = &Net_players[player_index]; } // swap the players temp = Multi_ts_team[pl->p_info.team].multi_ts_player[to_index]; Multi_ts_team[pl->p_info.team].multi_ts_player[to_index] = Multi_ts_team[pl->p_info.team].multi_ts_player[from_index]; Multi_ts_team[pl->p_info.team].multi_ts_player[from_index] = temp; // update netplayer information if necessary if(Multi_ts_team[pl->p_info.team].multi_ts_player[from_index] != NULL){ Multi_ts_team[pl->p_info.team].multi_ts_player[from_index]->p_info.ship_index = from_index; Multi_ts_team[pl->p_info.team].multi_ts_player[from_index]->p_info.ship_class = Wss_slots_teams[pl->p_info.team][from_index].ship_class; multi_assign_player_ship(NET_PLAYER_INDEX(Multi_ts_team[pl->p_info.team].multi_ts_player[from_index]),&Objects[Multi_ts_team[pl->p_info.team].multi_ts_objnum[from_index]],Wss_slots_teams[pl->p_info.team][from_index].ship_class); } if(Multi_ts_team[pl->p_info.team].multi_ts_player[to_index] != NULL){ Multi_ts_team[pl->p_info.team].multi_ts_player[to_index]->p_info.ship_index = to_index; Multi_ts_team[pl->p_info.team].multi_ts_player[to_index]->p_info.ship_class = Wss_slots_teams[pl->p_info.team][to_index].ship_class; multi_assign_player_ship(NET_PLAYER_INDEX(Multi_ts_team[pl->p_info.team].multi_ts_player[to_index]),&Objects[Multi_ts_team[pl->p_info.team].multi_ts_objnum[to_index]],Wss_slots_teams[pl->p_info.team][to_index].ship_class); } // update ship flags Objects[Multi_ts_team[pl->p_info.team].multi_ts_objnum[to_index]].flags &= ~(OF_COULD_BE_PLAYER); Objects[Multi_ts_team[pl->p_info.team].multi_ts_objnum[to_index]].flags &= ~(OF_PLAYER_SHIP); if(Multi_ts_team[pl->p_info.team].multi_ts_player[to_index] != NULL){ Objects[Multi_ts_team[pl->p_info.team].multi_ts_objnum[to_index]].flags |= OF_PLAYER_SHIP; } Objects[Multi_ts_team[pl->p_info.team].multi_ts_objnum[from_index]].flags &= ~(OF_COULD_BE_PLAYER); Objects[Multi_ts_team[pl->p_info.team].multi_ts_objnum[from_index]].flags &= ~(OF_PLAYER_SHIP); if(Multi_ts_team[pl->p_info.team].multi_ts_player[from_index] != NULL){ Objects[Multi_ts_team[pl->p_info.team].multi_ts_objnum[from_index]].flags |= OF_PLAYER_SHIP; } // recalcalate which slots are locked/unlocked, etc ss_recalc_multiplayer_slots(); // send an update packet to all players if(Net_player->flags & NETINFO_FLAG_GAME_HOST){ send_pslot_update_packet(pl->p_info.team,TS_CODE_PLAYER_UPDATE,SND_ICON_DROP_ON_WING); gamesnd_play_iface(SND_ICON_DROP_ON_WING); } *sound = SND_ICON_DROP; return 1; } // move a player int multi_ts_move_player(int from_index,int to_index,int *sound,int player_index) { net_player *pl; // get the proper player pointer if(player_index == -1){ pl = Net_player; } else { pl = &Net_players[player_index]; } // swap the players Multi_ts_team[pl->p_info.team].multi_ts_player[to_index] = Multi_ts_team[pl->p_info.team].multi_ts_player[from_index]; Multi_ts_team[pl->p_info.team].multi_ts_player[from_index] = NULL; // update netplayer information if necessary if(Multi_ts_team[pl->p_info.team].multi_ts_player[from_index] != NULL){ Multi_ts_team[pl->p_info.team].multi_ts_player[from_index]->p_info.ship_index = from_index; Multi_ts_team[pl->p_info.team].multi_ts_player[from_index]->p_info.ship_class = Wss_slots_teams[pl->p_info.team][from_index].ship_class; multi_assign_player_ship(NET_PLAYER_INDEX(Multi_ts_team[pl->p_info.team].multi_ts_player[from_index]),&Objects[Multi_ts_team[pl->p_info.team].multi_ts_objnum[from_index]],Wss_slots_teams[pl->p_info.team][from_index].ship_class); } if(Multi_ts_team[pl->p_info.team].multi_ts_player[to_index] != NULL){ Multi_ts_team[pl->p_info.team].multi_ts_player[to_index]->p_info.ship_index = to_index; Multi_ts_team[pl->p_info.team].multi_ts_player[to_index]->p_info.ship_class = Wss_slots_teams[pl->p_info.team][to_index].ship_class; multi_assign_player_ship(NET_PLAYER_INDEX(Multi_ts_team[pl->p_info.team].multi_ts_player[to_index]),&Objects[Multi_ts_team[pl->p_info.team].multi_ts_objnum[to_index]],Wss_slots_teams[pl->p_info.team][to_index].ship_class); } // update ship flags Objects[Multi_ts_team[pl->p_info.team].multi_ts_objnum[to_index]].flags &= ~(OF_COULD_BE_PLAYER); Objects[Multi_ts_team[pl->p_info.team].multi_ts_objnum[to_index]].flags &= ~(OF_PLAYER_SHIP); if(Multi_ts_team[pl->p_info.team].multi_ts_player[to_index] != NULL){ Objects[Multi_ts_team[pl->p_info.team].multi_ts_objnum[to_index]].flags |= OF_PLAYER_SHIP; } Objects[Multi_ts_team[pl->p_info.team].multi_ts_objnum[from_index]].flags &= ~(OF_COULD_BE_PLAYER); Objects[Multi_ts_team[pl->p_info.team].multi_ts_objnum[from_index]].flags &= ~(OF_PLAYER_SHIP); if(Multi_ts_team[pl->p_info.team].multi_ts_player[from_index] != NULL){ Objects[Multi_ts_team[pl->p_info.team].multi_ts_objnum[from_index]].flags |= OF_PLAYER_SHIP; } // recalcalate which slots are locked/unlocked, etc ss_recalc_multiplayer_slots(); // send an update packet to all players if(Net_player->flags & NETINFO_FLAG_GAME_HOST){ send_pslot_update_packet(pl->p_info.team,TS_CODE_PLAYER_UPDATE,SND_ICON_DROP_ON_WING); gamesnd_play_iface(SND_ICON_DROP_ON_WING); } *sound = SND_ICON_DROP; return 1; } // get the ship class of the current index in the avail list or -1 if none exists int multi_ts_get_avail_ship_class(int index) { int ship_count,class_index; ship_count = index + Multi_ts_avail_start; class_index = 0; while((ship_count >= 0) && (class_index < MAX_SHIP_TYPES)){ if(Ss_pool[class_index] > 0){ ship_count--; } if(ship_count >= 0){ class_index++; } } if(ship_count < 0){ return class_index; } return -1; } // blit the currently carried icon (if any) void multi_ts_blit_carried_icon() { int x,y; int offset_x,offset_y,callsign_w; char callsign[CALLSIGN_LEN+2]; // if we're not carrying anything, then return if(!Multi_ts_carried_flag){ return; } // get the mouse position mouse_get_pos(&x,&y); // if we're carrying an icon of some kind switch(Multi_ts_carried_from_type){ case MULTI_TS_SLOT_LIST: offset_x = Multi_ts_slot_icon_coords[Multi_ts_carried_from_index][gr_screen.res][MULTI_TS_X_COORD] - Multi_ts_clicked_x; offset_y = Multi_ts_slot_icon_coords[Multi_ts_carried_from_index][gr_screen.res][MULTI_TS_Y_COORD] - Multi_ts_clicked_y; // blit the icon ss_blit_ship_icon(x + offset_x,y + offset_y,Multi_ts_carried_ship_class,0); break; case MULTI_TS_AVAIL_LIST: offset_x = Multi_ts_avail_coords[Multi_ts_carried_from_index][gr_screen.res][MULTI_TS_X_COORD] - Multi_ts_clicked_x; offset_y = Multi_ts_avail_coords[Multi_ts_carried_from_index][gr_screen.res][MULTI_TS_Y_COORD] - Multi_ts_clicked_y; // blit the icon ss_blit_ship_icon(x + offset_x,y + offset_y,Multi_ts_carried_ship_class,0); break; case MULTI_TS_PLAYER_LIST: // get the final length of the string so we can calculate a valid offset strcpy(callsign,Multi_ts_team[Net_player->p_info.team].multi_ts_player[Multi_ts_carried_from_index]->player->callsign); gr_force_fit_string(callsign,CALLSIGN_LEN,Multi_ts_slot_text_coords[Multi_ts_carried_from_index][gr_screen.res][MULTI_TS_W_COORD]); gr_get_string_size(&callsign_w,NULL,callsign); // calculate the offsets offset_x = (Multi_ts_slot_text_coords[Multi_ts_carried_from_index][gr_screen.res][MULTI_TS_X_COORD] - Multi_ts_clicked_x) + ((Multi_ts_slot_text_coords[Multi_ts_carried_from_index][gr_screen.res][MULTI_TS_W_COORD] - callsign_w)/2); offset_y = Multi_ts_slot_text_coords[Multi_ts_carried_from_index][gr_screen.res][MULTI_TS_Y_COORD] - Multi_ts_clicked_y; gr_set_color_fast(&Color_normal); gr_string(x + offset_x,y + offset_y,Multi_ts_team[Net_player->p_info.team].multi_ts_player[Multi_ts_carried_from_index]->player->callsign); break; default : break; } } // if the (console) player is allowed to grab a player slot at this point int multi_ts_can_grab_player(int slot_index, int player_index) { net_player *pl; // get a pointe rto the proper net player if(player_index == -1){ pl = Net_player; } else { pl = &Net_players[player_index]; } // if the players are locked in any case, he annot grab it if(Multi_ts_team[pl->p_info.team].multi_players_locked){ return 0; } if(Netgame.type_flags & NG_TYPE_TEAM){ // if he's not the team captain, he cannot do this if(!(pl->flags & NETINFO_FLAG_TEAM_CAPTAIN)){ return 0; } } else { // if he's not the host, he cannot do this if(!(pl->flags & NETINFO_FLAG_GAME_HOST)){ return 0; } } // if the slot is empty if(Multi_ts_team[pl->p_info.team].multi_ts_player[slot_index] == NULL){ return 0; } return 1; } // get the team # of the given ship int multi_ts_get_team(char *ship_name) { int idx,s_idx; // lookup through all team ship names for(idx=0;idx<MULTI_TS_MAX_TEAMS;idx++){ for(s_idx=0;s_idx<MULTI_TS_NUM_SHIP_SLOTS_TEAM;s_idx++){ if(!stricmp(ship_name,Multi_ts_slot_team_names[idx][s_idx])){ return idx; } } } // always on team 0 if not found otherwise return 0; } // return the bitmap index into the ships icon array (in ship select) which should be displayed for the given slot int multi_ts_avail_bmap_num(int slot_index) { // if this slot has been highlighted for informational purposes if((Multi_ts_select_type == MULTI_TS_AVAIL_LIST) && (Multi_ts_select_index == slot_index)){ return ICON_FRAME_SELECTED; } // if its otherwise being lit by the mouse if((Multi_ts_hotspot_type == MULTI_TS_AVAIL_LIST) && (Multi_ts_hotspot_index == slot_index)){ return ICON_FRAME_HOT; } return ICON_FRAME_NORMAL; } // return the bitmap index into the ships icon array (in ship select) which should be displayed for the given slot int multi_ts_slot_bmap_num(int slot_index) { // special case - slot is disabled, its my ship and the host hasn't locked the ships yet if(multi_ts_disabled_high_slot(slot_index)){ return ICON_FRAME_DISABLED_HIGH; } // if this slot is disabled for us, then show it as such if(multi_ts_disabled_slot(slot_index)){ return ICON_FRAME_DISABLED; } // if this slot has been highlighted for informational purposes if((Multi_ts_select_type == MULTI_TS_SLOT_LIST) && (Multi_ts_select_index == slot_index)){ return ICON_FRAME_SELECTED; } // if this is our ship, then highlight it as so if(Net_player->p_info.ship_index == slot_index){ return ICON_FRAME_PLAYER; } // if its otherwise being lit by the mouse if((Multi_ts_hotspot_type == MULTI_TS_SLOT_LIST) && (Multi_ts_hotspot_index == slot_index)){ return ICON_FRAME_HOT; } // normal unhighlighted frame return ICON_FRAME_NORMAL; } // select the given slot and setup any information, etc void multi_ts_select_ship() { /* int n_lines, idx; int n_chars[MAX_BRIEF_LINES]; char ship_desc[1000]; char *p_str[MAX_BRIEF_LINES]; char *token; */ // blast all current text memset(Multi_ts_ship_info_lines,0,MULTI_TS_SHIP_INFO_MAX_TEXT); memset(Multi_ts_ship_info_text,0,MULTI_TS_SHIP_INFO_MAX_TEXT); // get the selected ship class Assert(Multi_ts_select_index >= 0); Multi_ts_select_ship_class = -1; switch(Multi_ts_select_type){ case MULTI_TS_SLOT_LIST: Multi_ts_select_ship_class = Wss_slots[Multi_ts_select_index].ship_class; break; case MULTI_TS_AVAIL_LIST: Multi_ts_select_ship_class = multi_ts_get_avail_ship_class(Multi_ts_select_index); // if he has selected an empty slot, don't do anything if(Multi_ts_select_ship_class < 0){ return; } break; default : // should always have one of the 2 above types selected Int3(); break; } // split the text info up /* Assert(Multi_ts_select_ship_class >= 0); Assert((Ship_info[Multi_ts_select_ship_class].desc != NULL) && strlen(Ship_info[Multi_ts_select_ship_class].desc)); // strip out newlines memset(ship_desc,0,1000); strcpy(ship_desc,Ship_info[Multi_ts_select_ship_class].desc); token = strtok(ship_desc,"\n"); if(token != NULL){ strcpy(Multi_ts_ship_info_text,token); while(token != NULL){ token = strtok(NULL,"\n"); if(token != NULL){ strcat(Multi_ts_ship_info_text," "); strcat(Multi_ts_ship_info_text,token); } } } if(strlen(Multi_ts_ship_info_text) > 0){ // split the string into multiple lines n_lines = split_str(Multi_ts_ship_info_text, Multi_ts_ship_info_coords[gr_screen.res][MULTI_TS_W_COORD], n_chars, p_str, MULTI_TS_SHIP_INFO_MAX_LINES, 0); // copy the split up lines into the text lines array for (idx=0;idx<n_lines;idx++ ) { Assert(n_chars[idx] < MULTI_TS_SHIP_INFO_MAX_LINE_LEN); strncpy(Multi_ts_ship_info_lines[idx], p_str[idx], n_chars[idx]); Multi_ts_ship_info_lines[idx][n_chars[idx]] = 0; drop_leading_white_space(Multi_ts_ship_info_lines[idx]); } // get the line count Multi_ts_ship_info_line_count = n_lines; } else { // set the line count to Multi_ts_ship_info_line_count = 0; } */ } // handle all details when the commit button is pressed (including possibly reporting errors/popups) void multi_ts_commit_pressed() { // if my team's slots are still not "locked", we cannot commit unless we're the only player in the game if(!Multi_ts_team[Net_player->p_info.team].multi_players_locked){ if(multi_num_players() != 1){ popup(PF_USE_AFFIRMATIVE_ICON | PF_BODY_BIG,1,POPUP_OK,XSTR("Players have not yet been assigned to their ships",751)); return; } else { Multi_ts_team[Net_player->p_info.team].multi_players_locked = 1; } } // check to see if its not ok for this player to commit switch(multi_ts_ok_to_commit()){ // yes, it _is_ ok to commit case 0: extern void commit_pressed(); commit_pressed(); break; // player has not assigned all necessary ships case 1: gamesnd_play_iface(SND_GENERAL_FAIL); popup(PF_USE_AFFIRMATIVE_ICON | PF_BODY_BIG,1,POPUP_OK,XSTR("You have not yet assigned all necessary ships",752)); break; // there are ships without primary weapons case 2: gamesnd_play_iface(SND_GENERAL_FAIL); popup(PF_USE_AFFIRMATIVE_ICON | PF_BODY_BIG,1,POPUP_OK,XSTR("There are ships without primary weapons!",753)); break; // there are ships without secondary weapons case 3: gamesnd_play_iface(SND_GENERAL_FAIL); popup(PF_USE_AFFIRMATIVE_ICON | PF_BODY_BIG,1,POPUP_OK,XSTR("There are ships without secondary weapons!",754)); break; } } // is it ok for this player to commit int multi_ts_ok_to_commit() { int idx,s_idx; int primary_ok,secondary_ok; // if this player is an observer, he can always commit if(Net_player->flags & NETINFO_FLAG_OBSERVER){ return 0; } for(idx=0;idx<MULTI_TS_NUM_SHIP_SLOTS;idx++){ // if this is a player slot this player can modify and it is empty, then he cannot continue // implies there is never an object in this slot if((Multi_ts_team[Net_player->p_info.team].multi_ts_objnum[idx] != -1) && // implies player can't touch this slot anyway !multi_ts_disabled_slot(idx) && // implies that there should be a player ship here but there isn't ((Multi_ts_team[Net_player->p_info.team].multi_ts_player[idx] != NULL) && (Multi_ts_team[Net_player->p_info.team].multi_ts_flag[idx] == MULTI_TS_FLAG_EMPTY)) ){ return 1; } // if the ship in this slot has a ship which can be a player but has 0 primary or secondary weapons, then he cannot continue if( (Multi_ts_team[Net_player->p_info.team].multi_ts_objnum[idx] != -1) && ((Objects[Multi_ts_team[Net_player->p_info.team].multi_ts_objnum[idx]].flags & OF_COULD_BE_PLAYER) || (Objects[Multi_ts_team[Net_player->p_info.team].multi_ts_objnum[idx]].flags & OF_PLAYER_SHIP)) && !multi_ts_disabled_slot(idx)){ primary_ok = 0; secondary_ok = 0; // go through all weapons in the list for(s_idx=0;s_idx<MAX_WL_WEAPONS;s_idx++){ // if this slot has a weapon with a greater than 0 count, check if((Wss_slots_teams[Net_player->p_info.team][idx].wep[s_idx] >= 0) && (Wss_slots_teams[Net_player->p_info.team][idx].wep_count[s_idx] > 0)){ switch(Weapon_info[Wss_slots_teams[Net_player->p_info.team][idx].wep[s_idx]].subtype){ case WP_LASER: primary_ok = 1; break; case WP_MISSILE: secondary_ok = 1; break; default : Int3(); } } // if we've got both primary and secondary weapons if(primary_ok && secondary_ok){ break; } } // if the ship doesn't have primary weapons if(!primary_ok){ return 2; } // if the ship doesn't have secondary weapons if(!secondary_ok){ return 3; } } } return 0; } // check to see that no illegal ship settings have occurred void multi_ts_check_errors() { /* int idx; ship *shipp; for(idx=0;idx<MULTI_TS_NUM_SHIP_SLOTS;idx++){ if(Multi_ts_team[0].multi_ts_objnum[idx] == -1){ continue; } shipp = &Ships[Objects[Multi_ts_team[0].multi_ts_objnum[idx]].instance]; Assert((shipp->weapons.current_primary_bank != -1) && (shipp->weapons.current_secondary_bank != -1)); } */ } // ------------------------------------------------------------------------------------------------------ // TEAM SELECT PACKET HANDLERS // // send a player slot position update void send_pslot_update_packet(int team,int code,int sound) { ubyte data[MAX_PACKET_SIZE],stop,val; short s_sound; int idx; int packet_size = 0; int i_tmp; // build the header and add the data BUILD_HEADER(SLOT_UPDATE); // add the opcode val = (ubyte)code; ADD_DATA(val); // add the team val = (ubyte)team; ADD_DATA(val); // add the sound to play s_sound = (short)sound; ADD_DATA(s_sound); // add data based upon the packet code switch(code){ case TS_CODE_LOCK_TEAM: // don't have to do anything break; case TS_CODE_PLAYER_UPDATE: // only the host should ever be doing this Assert(Net_player->flags & NETINFO_FLAG_GAME_HOST); // add individual slot data for(idx=0;idx<MAX_WSS_SLOTS;idx++){ if(Multi_ts_team[team].multi_ts_flag[idx] != MULTI_TS_FLAG_NONE){ // add a stop byte stop = 0x0; ADD_DATA(stop); // add the slot # val = (ubyte)idx; ADD_DATA(val); // add the ship class val = (ubyte)Wss_slots_teams[team][idx].ship_class; ADD_DATA(val); // add the objnum we're working with i_tmp = Multi_ts_team[team].multi_ts_objnum[idx]; ADD_DATA(i_tmp); // add a byte indicating if a player is here or not if(Multi_ts_team[team].multi_ts_player[idx] == NULL){ val = 0; } else { val = 1; } ADD_DATA(val); // if there's a player, add his address if(val){ ADD_DATA(Multi_ts_team[team].multi_ts_player[idx]->player_id); // should also update his p_info settings locally Multi_ts_team[team].multi_ts_player[idx]->p_info.ship_class = Wss_slots_teams[team][idx].ship_class; Multi_ts_team[team].multi_ts_player[idx]->p_info.ship_index = idx; } // add a byte indicating what object flag should be set (0 == ~(OF_COULD_BE_PLAYER | OF_PLAYER_SHIP), 1 == player ship, 2 == could be player ship) if(Objects[Multi_ts_team[team].multi_ts_objnum[idx]].flags & OF_COULD_BE_PLAYER){ val = 2; } else if(Objects[Multi_ts_team[team].multi_ts_objnum[idx]].flags & OF_PLAYER_SHIP){ val = 1; } else { val = 0; } ADD_DATA(val); } } // add a final stop byte val = 0xff; ADD_DATA(val); break; default : Int3(); break; } // send the packet to the standalone if(Net_player->flags & NETINFO_FLAG_AM_MASTER) { multi_io_send_to_all_reliable(data, packet_size); } else { multi_io_send_reliable(Net_player, data, packet_size); } } // process a player slot position update void process_pslot_update_packet(ubyte *data, header *hinfo) { int offset = HEADER_LENGTH; int my_index; int player_index,idx,team,code,objnum; short sound; short player_id; ubyte stop,val,slot_num,ship_class; my_index = Net_player->p_info.ship_index; // if we're the standalone, then we should be routing this data to all the other clients player_index = -1; if(Net_player->flags & NETINFO_FLAG_AM_MASTER){ // fill in the address information of where this came from player_index = find_player_id(hinfo->id); Assert(player_index != -1); } // get the opcode GET_DATA(val); code = (int)val; // get the team GET_DATA(val); team = (int)val; // get the sound to play GET_DATA(sound); // process the different opcodes switch(code){ case TS_CODE_LOCK_TEAM: // lock the team Multi_ts_team[team].multi_players_locked = 1; // if this was my team, sync stuff up if((team == Net_player->p_info.team) && !(Game_mode & GM_STANDALONE_SERVER)){ multi_ts_set_status_bar_mode(1); multi_ts_sync_interface(); ss_recalc_multiplayer_slots(); } // if this is the standalone server, we need to re-route the packet here and there if(Net_player->flags & NETINFO_FLAG_AM_MASTER){ // in team vs team mode, only a team captain should ever be sending this if(Netgame.type_flags & NG_TYPE_TEAM){ Assert(Net_players[player_index].flags & NETINFO_FLAG_TEAM_CAPTAIN); } // in any other mode, it better be coming from the game host else { Assert(Net_players[player_index].flags & NETINFO_FLAG_GAME_HOST); } // re-route to all other players for(idx=0;idx<MAX_PLAYERS;idx++){ if(MULTI_CONNECTED(Net_players[idx]) && (&Net_players[idx] != Net_player) && (&Net_players[idx] != &Net_players[player_index]) ){ multi_io_send_reliable(&Net_players[idx], data, offset); } } } break; case TS_CODE_PLAYER_UPDATE: // get the first stop byte GET_DATA(stop); while(stop != 0xff){ // get the slot # GET_DATA(slot_num); // get the ship class GET_DATA(ship_class); // get the objnum GET_DATA(objnum); // flag indicating if a player is in this slot GET_DATA(val); if(val){ // look the player up GET_DATA(player_id); player_index = find_player_id(player_id); // if we couldn't find him if(player_index == -1){ nprintf(("Network","Couldn't find player for pslot update!\n")); Multi_ts_team[team].multi_ts_player[slot_num] = NULL; } // if we found him, assign him to this ship else { Net_players[player_index].p_info.ship_class = (int)ship_class; Net_players[player_index].p_info.ship_index = (int)slot_num; multi_assign_player_ship(player_index,&Objects[objnum],(int)ship_class); // ui stuff Multi_ts_team[team].multi_ts_player[slot_num] = &Net_players[player_index]; // if this was me and my ship index changed, update the weapon select screen if(my_index != Net_player->p_info.ship_index){ wl_reset_selected_slot(); my_index = Net_player->p_info.ship_index; } } } else { Multi_ts_team[team].multi_ts_player[slot_num] = NULL; } // get the ship flag byte GET_DATA(val); Objects[objnum].flags &= ~(OF_PLAYER_SHIP | OF_COULD_BE_PLAYER); switch(val){ case 1 : Objects[objnum].flags |= OF_PLAYER_SHIP; break; case 2 : obj_set_flags( &Objects[objnum], Objects[objnum].flags | OF_COULD_BE_PLAYER ); break; } // get the next stop byte GET_DATA(stop); } // if we have a sound we're supposed to play if((sound != -1) && !(Game_mode & GM_STANDALONE_SERVER) && (gameseq_get_state() == GS_STATE_TEAM_SELECT)){ gamesnd_play_iface(sound); } // if i'm the standalone server, I should rebroadcast this packet if(Game_mode & GM_STANDALONE_SERVER){ for(idx=0;idx<MAX_PLAYERS;idx++){ if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_HOST(Net_players[idx]) && (Net_player != &Net_players[idx])){ multi_io_send_reliable(&Net_players[idx], data, offset); } } } break; } PACKET_SET_SIZE(); // recalculate stuff if(!(Game_mode & GM_STANDALONE_SERVER)){ ss_recalc_multiplayer_slots(); } }
[ "(no author)@387891d4-d844-0410-90c0-e4c51a9137d3" ]
(no author)@387891d4-d844-0410-90c0-e4c51a9137d3
602554a88c73c1f548cabb64b767c372b4c88526
98ab3e12ce3db4896ffa976fd258dffdbadb138c
/oxygine-framework/oxygine/src/Polygon.h
6fff8918d0bb586161ebcbcf61c93836f309a8e0
[ "MIT" ]
permissive
vlad-d-markin/dethgame
ce0a0f7868e59f12824fe9120c895a49ff3d1e19
bcb4bf7f432c14faf77ae9a7411c3c9df629bbd1
refs/heads/master
2021-01-17T16:56:34.567317
2016-07-19T21:42:01
2016-07-19T21:42:01
62,659,600
6
2
null
2016-07-17T21:06:13
2016-07-05T18:22:24
C
UTF-8
C++
false
false
902
h
#pragma once #include "oxygine_include.h" #include "Sprite.h" namespace oxygine { class ResAnim; DECLARE_SMART(Polygon, spPolygon); class Polygon : public _Sprite { public: DECLARE_COPYCLONE_NEW(Polygon); Polygon(); ~Polygon(); /** if *own* is true Polygon will delete[] data array; */ void setVertices(const void* data, int size, int bformat, bool own); void serialize(serializedata* data); void deserialize(const deserializedata* data); std::string dump(const dumpOptions&) const; protected: void doRender(const RenderState& rs); const VertexDeclaration* _vdecl; bool _own; const unsigned char* _verticesData; int _verticesSize; }; } #ifdef OX_EDITOR #include "EditorPolygon.h" #else namespace oxygine { typedef Polygon _Polygon; } #endif
[ "vlad.d.markin@gmail.com" ]
vlad.d.markin@gmail.com
b3c2f91638773c24d19815fb73b012aa51d7d493
5499e8b91353ef910d2514c8a57a80565ba6f05b
/zircon/system/utest/nand-redundant-storage/nand-rs-tests.cc
621b0b70cab556cd7b8b21716abf65bb3b346f22
[ "BSD-3-Clause", "MIT" ]
permissive
winksaville/fuchsia
410f451b8dfc671f6372cb3de6ff0165a2ef30ec
a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f
refs/heads/master
2022-11-01T11:57:38.343655
2019-11-01T17:06:19
2019-11-01T17:06:19
223,695,500
3
2
BSD-3-Clause
2022-10-13T13:47:02
2019-11-24T05:08:59
C++
UTF-8
C++
false
false
7,163
cc
// Copyright 2019 The Fuchsia 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 <lib/mtd/mtd-interface.h> #include <lib/nand-redundant-storage/nand-redundant-storage.h> #include <stdint.h> #include <vector> #include <zxtest/zxtest.h> // This NAND interface test relies on an MTD device file located at /dev/mtd0/ // for non-astro tests, and /dev/mtd/mtd9 for astro-based tests. // // On the host machine, nandsim is used to create a virtual MTD device. // The following command was used to create the device for this test. // // $ sudo modprobe nandsim id_bytes=0x2c,0xdc,0x90,0xa6,0x54,0x0 badblocks=5 using namespace nand_rs; namespace { #ifdef ASTRO constexpr const char* kTestDevicePath = "/dev/mtd/mtd9"; #else constexpr const char* kTestDevicePath = "/dev/mtd0"; #endif class MtdRsTest : public zxtest::Test { protected: void Wipe() { for (uint32_t offset = 0; offset < mtd_ptr_->Size(); offset += mtd_ptr_->BlockSize()) { bool is_bad_block; ASSERT_OK(mtd_ptr_->IsBadBlock(offset, &is_bad_block)); if (is_bad_block) { continue; } ASSERT_OK(mtd_ptr_->EraseBlock(offset)); } } // Zero-index-based block erase. void EraseBlockAtIndex(uint32_t index) { ASSERT_OK(mtd_ptr_->EraseBlock(mtd_ptr_->BlockSize() * index)); } void SetUp() override { auto mtd = mtd::MtdInterface::Create(kTestDevicePath); mtd_ptr_ = mtd.get(); // Sanity "test" to make sure the interface is valid. ASSERT_NE(nullptr, mtd_ptr_, "Failed to initialize nand_ with device %s", kTestDevicePath); nand_ = NandRedundantStorage::Create(std::move(mtd)); max_blocks_ = mtd_ptr_->Size() / mtd_ptr_->BlockSize(); num_copies_written_ = 0; Wipe(); } std::vector<uint8_t> MakeFakePage(uint8_t value, uint32_t checksum, uint32_t file_size) { std::vector<uint8_t> res(mtd_ptr_->PageSize(), value); res[0] = 'Z'; res[1] = 'N'; res[2] = 'N'; res[3] = 'D'; // Avoid byte-masking, as the struct is just copied into memory. auto checksum_ptr = reinterpret_cast<uint32_t*>(&res[4]); *checksum_ptr = checksum; auto file_size_ptr = reinterpret_cast<uint32_t*>(&res[8]); *file_size_ptr = file_size; return res; } mtd::MtdInterface* mtd_ptr_; std::unique_ptr<NandRedundantStorage> nand_; std::vector<uint8_t> out_buffer_; uint32_t num_copies_written_; uint32_t max_blocks_; }; TEST_F(MtdRsTest, ReadWriteTest) { std::vector<uint8_t> nonsense_buffer = {12, 14, 22, 0, 12, 8, 0, 0, 0, 3, 45, 0xFF}; ASSERT_OK(nand_->WriteBuffer(nonsense_buffer, 10, &num_copies_written_)); ASSERT_EQ(10, num_copies_written_); ASSERT_OK(nand_->ReadToBuffer(&out_buffer_)); ASSERT_BYTES_EQ(out_buffer_.data(), nonsense_buffer.data(), nonsense_buffer.size()); std::vector<uint8_t> page_crossing_buffer(mtd_ptr_->PageSize() * 2 + 13, 0xF5); ASSERT_OK(nand_->WriteBuffer(page_crossing_buffer, 10, &num_copies_written_)); ASSERT_EQ(10, num_copies_written_); ASSERT_OK(nand_->ReadToBuffer(&out_buffer_)); ASSERT_BYTES_EQ(out_buffer_.data(), page_crossing_buffer.data(), page_crossing_buffer.size()); } TEST_F(MtdRsTest, WriteNoHeaderTest) { std::vector<uint8_t> nonsense_buffer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; size_t buffer_size = nonsense_buffer.size(); ASSERT_OK(nand_->WriteBuffer(nonsense_buffer, 10, &num_copies_written_, true)); ASSERT_EQ(10, num_copies_written_); ASSERT_OK(nand_->ReadToBuffer(&out_buffer_, true, buffer_size)); ASSERT_BYTES_EQ(out_buffer_.data(), nonsense_buffer.data(), nonsense_buffer.size()); } TEST_F(MtdRsTest, WriteNoHeaderWithoutFileSizeTest) { std::vector<uint8_t> nonsense_buffer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; ASSERT_OK(nand_->WriteBuffer(nonsense_buffer, 10, &num_copies_written_, true)); ASSERT_EQ(10, num_copies_written_); ASSERT_EQ(ZX_ERR_INVALID_ARGS, nand_->ReadToBuffer(&out_buffer_, true)); } TEST_F(MtdRsTest, ReadWriteTestWithErasedBlock) { std::vector<uint8_t> page_crossing_buffer(mtd_ptr_->PageSize() * 2 + 13, 0xF5); ASSERT_OK(nand_->WriteBuffer(page_crossing_buffer, 20, &num_copies_written_)); ASSERT_EQ(20, num_copies_written_); EraseBlockAtIndex(0); EraseBlockAtIndex(1); EraseBlockAtIndex(2); EraseBlockAtIndex(3); ASSERT_OK(nand_->ReadToBuffer(&out_buffer_)); ASSERT_BYTES_EQ(out_buffer_.data(), page_crossing_buffer.data(), page_crossing_buffer.size()); } TEST_F(MtdRsTest, ReadWriteTestWithCorruptedBlockValidHeader) { std::vector<uint8_t> page_crossing_buffer(mtd_ptr_->PageSize() * 2 + 13, 0xF5); ASSERT_OK(nand_->WriteBuffer(page_crossing_buffer, 10, &num_copies_written_)); ASSERT_EQ(10, num_copies_written_); EraseBlockAtIndex(0); EraseBlockAtIndex(1); EraseBlockAtIndex(2); EraseBlockAtIndex(3); uint32_t block_three_start = mtd_ptr_->BlockSize() * 2; std::vector<uint8_t> page_of_nonsense = MakeFakePage(0x40, 0x40404040, 0x40404040); ASSERT_OK(mtd_ptr_->WritePage(block_three_start, page_of_nonsense.data(), nullptr)); ASSERT_OK(nand_->ReadToBuffer(&out_buffer_)); ASSERT_BYTES_EQ(out_buffer_.data(), page_crossing_buffer.data(), page_crossing_buffer.size()); } TEST_F(MtdRsTest, ReadWiteTestWithCorruptedBlockWrongCrc) { std::vector<uint8_t> page_crossing_buffer(mtd_ptr_->PageSize() * 2 + 13, 0xF5); ASSERT_OK(nand_->WriteBuffer(page_crossing_buffer, 10, &num_copies_written_)); ASSERT_EQ(10, num_copies_written_); EraseBlockAtIndex(0); EraseBlockAtIndex(1); EraseBlockAtIndex(2); EraseBlockAtIndex(3); // Nonsense block, but with valid looking CRC and file size. uint32_t block_three_start = mtd_ptr_->BlockSize() * 2; std::vector<uint8_t> page_of_nonsense = MakeFakePage(0x40, 1, 34); ASSERT_OK(mtd_ptr_->WritePage(block_three_start, page_of_nonsense.data(), nullptr)); ASSERT_OK(nand_->ReadToBuffer(&out_buffer_)); ASSERT_BYTES_EQ(out_buffer_.data(), page_crossing_buffer.data(), page_crossing_buffer.size()); } TEST_F(MtdRsTest, ReadWriteTestWithCorruptedBlockWrongHeader) { std::vector<uint8_t> page_crossing_buffer(mtd_ptr_->PageSize() * 2 + 13, 0xF5); ASSERT_OK(nand_->WriteBuffer(page_crossing_buffer, 10, &num_copies_written_)); ASSERT_EQ(10, num_copies_written_); EraseBlockAtIndex(0); EraseBlockAtIndex(1); EraseBlockAtIndex(2); EraseBlockAtIndex(3); // Nonsense block, but with invalid header. uint32_t block_three_start = mtd_ptr_->BlockSize() * 2; std::vector<uint8_t> page_of_nonsense = MakeFakePage(0x40, 1, 34); page_of_nonsense[0] = 'z'; ASSERT_OK(mtd_ptr_->WritePage(block_three_start, page_of_nonsense.data(), nullptr)); ASSERT_OK(nand_->ReadToBuffer(&out_buffer_)); ASSERT_BYTES_EQ(out_buffer_.data(), page_crossing_buffer.data(), page_crossing_buffer.size()); } TEST_F(MtdRsTest, ReadEmptyMtd) { ASSERT_EQ(ZX_ERR_IO, nand_->ReadToBuffer(&out_buffer_)); } TEST_F(MtdRsTest, TestBlockWriteLimits) { std::vector<uint8_t> some_bits = {1, 2, 3, 5, 10, 9, 25, 83}; ASSERT_OK(nand_->WriteBuffer(some_bits, max_blocks_, &num_copies_written_)); ASSERT_EQ(max_blocks_ - 1, num_copies_written_); } } // namespace
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
eb3afd1aa517b5baadf8fda81b2dd795c77500f2
91b36a305a65a601f93fad94ef19b995db6e5d83
/NativePlugin/Src/Runtime/GfxDevice/opengles/ApiGLES.cpp
e17459a42962abe7915baa7794c2a1995e558b3e
[]
no_license
maksym-pasichnyk/NativeParticleSystem
0d79d093ef1144f60afb941d1928546005ebca62
35187e5d9a43e7db5264d1f953f4383873d3decf
refs/heads/master
2021-12-14T15:41:24.820604
2017-05-10T16:42:23
2017-05-10T16:42:23
437,383,171
1
1
null
2021-12-11T20:34:42
2021-12-11T20:34:41
null
UTF-8
C++
false
false
46,262
cpp
#include "PluginPrefix.h" #include "ApiTranslateGLES.h" #include "ApiGLES.h" #include "ApiConstantsGLES.h" #include "GfxContextGLES.h" #include "DeviceStateGLES.h" #include "Runtime/GfxDevice/opengles/AssertGLES.h" #include "Runtime/Shaders/GraphicsCaps.h" #include "Runtime/Utilities/ArrayUtility.h" //#include "Runtime/Utilities/Argv.h" #define GLES_DEBUG_CHECK_LOG 0 namespace { const GLenum GL_VENDOR = 0x1F00; const GLenum GL_EXTENSIONS = 0x1F03; const GLenum GL_NUM_EXTENSIONS = 0x821D; // Debug const GLenum GL_DEBUG_SOURCE_APPLICATION = 0x824A; // Query enums const GLenum GL_SAMPLES = 0x80A9; const GLenum GL_READ_BUFFER = 0x0C02; // Framebuffer enums const GLenum GL_SCALED_RESOLVE_NICEST_EXT = 0x90BB; const GLenum GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8CD0; const GLenum GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8CD1; // Polygon mode const GLenum GL_LINE = 0x1B01; const GLenum GL_FILL = 0x1B02; const GLenum GL_TEXTURE = 0x1702; const GLenum GL_PATCHES = 0x000E; const GLenum GL_INFO_LOG_LENGTH = 0x8B84; const GLenum GL_COMPILE_STATUS = 0x8B81; const GLenum GL_SHADER_SOURCE_LENGTH = 0x8B88; const GLenum GL_SHADER_TYPE = 0x8B4F; const GLenum GL_TEXTURE_MAX_ANISOTROPY_EXT = 0x84FE; const GLenum GL_TEXTURE_LOD_BIAS = 0x8501; const GLenum GL_TEXTURE_BASE_LEVEL = 0x813C; const GLenum GL_TEXTURE0 = 0x84C0; const GLenum GL_TEXTURE_SWIZZLE_R = 0x8E42; const GLenum GL_TEXTURE_SWIZZLE_G = 0x8E43; const GLenum GL_TEXTURE_SWIZZLE_B = 0x8E44; const GLenum GL_TEXTURE_SWIZZLE_A = 0x8E45; const GLenum GL_TEXTURE_SWIZZLE_RGBA = 0x8E46; const GLenum GL_FRONT_AND_BACK = 0x0408; const GLenum GL_PATCH_VERTICES = 0x8E72; const GLenum GL_UNPACK_ROW_LENGTH = 0x0CF2; const GLenum GL_PACK_ALIGNMENT = 0x0D05; const GLenum GL_UNPACK_ALIGNMENT = 0x0CF5; const GLenum GL_RED_BITS = 0x0D52; const GLenum GL_GREEN_BITS = 0x0D53; const GLenum GL_BLUE_BITS = 0x0D54; const GLenum GL_ALPHA_BITS = 0x0D55; const GLenum GL_DEPTH_BITS = 0x0D56; const GLenum GL_STENCIL_BITS = 0x0D57; const GLenum GL_COVERAGE_BUFFERS_NV = 0x8ED3; const GLenum GL_COVERAGE_SAMPLES_NV = 0x8ED4; const GLenum GL_TEXTURE_SPARSE_ARB = 0x91A6; const GLenum GL_NUM_SPARSE_LEVELS_ARB = 0x91AA; const GLenum GL_VIRTUAL_PAGE_SIZE_X_ARB = 0x9195; const GLenum GL_VIRTUAL_PAGE_SIZE_Y_ARB = 0x9196; const GLenum GL_R32UI = 0x8236; const GLenum GL_TEXTURE_SRGB_DECODE_EXT = 0x8A48; const char* GetDebugFramebufferAttachmentType(GLint type) { switch (type) { case GL_RENDERBUFFER: return "GL_RENDERBUFFER"; case GL_TEXTURE: return "GL_TEXTURE"; default: return "GL_NONE"; } } }//namespace namespace gles { void InitCaps(ApiGLES * api, GraphicsCaps* caps, GfxDeviceLevelGL &level); void InitRenderTextureFormatSupport(ApiGLES * api, GraphicsCaps* caps); }//namespace gles namespace { namespace BuggyBindElementArrayBufferWorkaround { // Vivante GC1000 driver (Samsung Galaxy Tab 3 7.0 lite) sometimes(!) changes GL_ARRAY_BUFFER_BINDING when calling glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer). // To workaround this, we replace glBindBuffer with a wrapper that reverses this unwanted modification of GL_ARRAY_BUFFER_BINDING. static GLuint s_ArrayBufferBinding; static gl::BindBufferFunc s_OriginalBindBuffer; void GLES_APIENTRY BindBufferWrapper(const GLenum target, const GLuint buffer) { s_OriginalBindBuffer(target, buffer); if (target == GL_ELEMENT_ARRAY_BUFFER) s_OriginalBindBuffer(GL_ARRAY_BUFFER, s_ArrayBufferBinding); // undo possible unexpected changes else if (target == GL_ARRAY_BUFFER) s_ArrayBufferBinding = buffer; // keep track of current GL_ARRAY_BUFFER } void ResetTrackedState() { if (s_OriginalBindBuffer) { s_ArrayBufferBinding = 0; } } void InstallBindBufferWrapper(gl::BindBufferFunc& bindBuffer) { // install glBindBuffer shim if (bindBuffer != s_OriginalBindBuffer) { s_OriginalBindBuffer = bindBuffer; bindBuffer = &BindBufferWrapper; } ResetTrackedState(); } } // namespace BuggyBindElementArrayBufferWorkaround } // namespace ApiGLES * gGL = NULL; const GLuint ApiGLES::kInvalidValue = static_cast<GLuint>(-1); ApiGLES::ApiGLES() : ApiFuncGLES() , m_Translate(new TranslateGLES) , translate(*m_Translate) , m_CurrentProgramBinding(0) , m_CurrentProgramHasTessellation(false) , m_CurrentVertexArrayBinding() , m_DefaultVertexArrayName() , m_CurrentDefaultVertexArrayEnabled(0) , m_CurrentCullMode(kCullOff) , m_CurrentPatchVertices(0) , m_CurrentCapEnabled(0) , m_CurrentPolygonModeWire(false) , m_CurrentTextureUnit(0) # if SUPPORT_THREADS , m_Thread(Thread::GetCurrentThreadID()) # endif , m_Caching(false) { this->m_CurrentSamplerBindings.fill(0); this->m_CurrentFramebufferBindings.fill(gl::FramebufferHandle()); this->m_CurrentBufferBindings.fill(0); this->m_CurrentUniformBufferBindings.fill(0); this->m_CurrentTransformBufferBindings.fill(0); this->m_CurrentStorageBufferBindings.fill(0); this->m_CurrentAtomicCounterBufferBindings.fill(0); } ApiGLES::~ApiGLES() { delete m_Translate; m_Translate = NULL; } void ApiGLES::Init(GfxDeviceLevelGL &deviceLevel) { // Set the current API gGL = this; // Caps are init by InitCaps but we need to initialize the featureLevel before calling Load which load OpenGL functions because it checks for extensions using the featureLevel //Assert(GetGraphicsCaps().gles.featureLevel == kGfxLevelUninitialized); GetGraphicsCaps().gles.featureLevel = deviceLevel; // The order of these functions matters // Load the OpenGL API pointers this->Load(deviceLevel); // Initialize the capabilities supported by the current platform gles::InitCaps(this, &GetGraphicsCaps(), deviceLevel); // Initialize the translation to OpenGL enums depending on the platform capability this->m_Translate->Init(GetGraphicsCaps(), deviceLevel); if (GetGraphicsCaps().gles.buggyBindElementArrayBuffer) BuggyBindElementArrayBufferWorkaround::InstallBindBufferWrapper(this->glBindBuffer); // Try to create framebuffer objects to figure out the effective support texture formats gles::InitRenderTextureFormatSupport(this, &GetGraphicsCaps()); # if UNITY_ANDROID UpdateTextureFormatSupportETC2(this, deviceLevel); # endif } void ApiGLES::Dispatch(UInt32 threadGroupsX, UInt32 threadGroupsY, UInt32 threadGroupsZ) { //GLES_CHECK(this, -1); GLES_CALL(this, glDispatchCompute, threadGroupsX, threadGroupsY, threadGroupsZ); } void ApiGLES::DispatchIndirect(UInt32 indirect) { //GLES_CHECK(this, -1); GLES_CALL(this, glDispatchComputeIndirect, (GLintptr)indirect); } void ApiGLES::DrawArrays(GfxPrimitiveType topology, UInt32 firstVertex, UInt32 vertexCount, UInt32 instanceCount) { GLES_CHECK(this, -1); GLES_ASSERT(this, topology >= kPrimitiveTypeFirst && topology <= kPrimitiveTypeLast, "Invalid 'topology' value"); GLES_ASSERT(this, (GetGraphicsCaps().hasInstancing && instanceCount > 1) || instanceCount <= 1, "Requested an instanced draw but instanced draws are not supported"); GLES_ASSERT(this, this->debug.ProgramStatus(), "The current state can't execute the bound GLSL program"); const GLenum translatedTopology = m_CurrentProgramHasTessellation ? GL_PATCHES : this->translate.Topology(topology); if (GetGraphicsCaps().hasInstancing && instanceCount > 1) GLES_CALL(this, glDrawArraysInstanced, translatedTopology, firstVertex, vertexCount, instanceCount); else GLES_CALL(this, glDrawArrays, translatedTopology, firstVertex, vertexCount); } void ApiGLES::DrawElements(GfxPrimitiveType topology, const void * indicesOrOffset, UInt32 indexCount, UInt32 baseVertex, UInt32 instanceCount) { GLES_CHECK(this, -1); GLES_ASSERT(this, topology >= kPrimitiveTypeFirst && topology <= kPrimitiveTypeLast, "Invalid 'topology' value"); GLES_ASSERT(this, (GetGraphicsCaps().hasInstancing && instanceCount > 1) || instanceCount <= 1, "Requested an instanced draw but instanced draws are not supported"); GLES_ASSERT(this, (GetGraphicsCaps().gles.hasDrawBaseVertex && baseVertex > 0) || baseVertex <= 0, "Requested a base vertex draw but it is not supported"); GLES_ASSERT(this, this->debug.ProgramStatus(), "The current state can't execute the bound GLSL program"); const GLenum translatedTopology = m_CurrentProgramHasTessellation ? GL_PATCHES : this->translate.Topology(topology); if (GetGraphicsCaps().gles.hasDrawBaseVertex && baseVertex > 0) { if (GetGraphicsCaps().hasInstancing && instanceCount > 1) GLES_CALL(this, glDrawElementsInstancedBaseVertex, translatedTopology, indexCount, GL_UNSIGNED_SHORT, indicesOrOffset, instanceCount, baseVertex); else GLES_CALL(this, glDrawElementsBaseVertex, translatedTopology, indexCount, GL_UNSIGNED_SHORT, indicesOrOffset, baseVertex); } else if (GetGraphicsCaps().hasInstancing && instanceCount > 1) GLES_CALL(this, glDrawElementsInstanced, translatedTopology, indexCount, GL_UNSIGNED_SHORT, indicesOrOffset, instanceCount); else GLES_CALL(this, glDrawElements, translatedTopology, indexCount, GL_UNSIGNED_SHORT, indicesOrOffset); } void ApiGLES::DrawCapture(GfxPrimitiveType topology, UInt32 VertexCount) { GLES_CHECK(this, -1); GLES_ASSERT(this, topology >= kPrimitiveTypeFirst && topology <= kPrimitiveTypeLast, "Invalid 'topology' value"); GLES_ASSERT(this, this->debug.ProgramStatus(), "The current state can't execute the bound GLSL program"); GLES_CALL(this, glBeginTransformFeedback, this->translate.Topology(topology)); this->DrawArrays(topology, 0, VertexCount, 1); GLES_CALL(this, glEndTransformFeedback); } void ApiGLES::DrawIndirect(GfxPrimitiveType topology, UInt32 bufferOffset) { GLES_CHECK(this, -1); GLES_ASSERT(this, topology >= kPrimitiveTypeFirst && topology <= kPrimitiveTypeLast, "Invalid 'DrawParam' topology"); GLES_ASSERT(this, GetGraphicsCaps().gles.hasIndirectDraw, "Indirect draw is not supported"); GLES_ASSERT(this, this->debug.ProgramStatus(), "The current state can't execute the bound GLSL program"); GLES_CALL(this, glDrawArraysIndirect, this->translate.Topology(topology), (void*)(intptr_t)bufferOffset); } void ApiGLES::Clear(GLbitfield flags, const ColorRGBAf& color, bool onlyColorAlpha, float depth, int stencil) { GLES_CHECK(this, -1); if (flags == 0) return; if (onlyColorAlpha) GLES_CALL(this, glColorMask, false, false, false, true); if (flags & GL_COLOR_BUFFER_BIT) GLES_CALL(this, glClearColor, color.r, color.g, color.b, color.a); if (flags & GL_DEPTH_BUFFER_BIT) { if (GetGraphicsCaps().gles.hasClearBufferFloat) GLES_CALL(this, glClearDepthf, depth); else GLES_CALL(this, glClearDepth, depth); } if (flags & GL_STENCIL_BUFFER_BIT) GLES_CALL(this, glClearStencil, stencil); GLES_CALL(this, glClear, flags); if (onlyColorAlpha) GLES_CALL(this, glColorMask, true, true, true, true); } GLuint ApiGLES::CreateShader(gl::ShaderStage stage, const char* source) { GLES_CHECK(this, -1); GLES_ASSERT(this, source, "'source' is null, pass a valid GLSL shader source"); GLuint shaderName = 0; GLES_CALL_RET(this, shaderName, glCreateShader, this->translate.GetShaderStage(stage)); GLES_ASSERT(this, shaderName, "Shader object failed to be created"); GLES_CALL(this, glShaderSource, shaderName, 1, &source, NULL); // We compile but we don't wait to the return allowing the drivers to thread the compilation GLES_CALL(this, glCompileShader, shaderName); GLES_CHECK(this, shaderName); return shaderName; } void ApiGLES::LinkProgram(GLuint programName) { GLES_CHECK(this, programName); GLES_ASSERT(this, programName > 0, "'programName' is not a valid program object"); GLES_CALL(this, glLinkProgram, programName); } bool ApiGLES::CheckProgram(GLuint & programName) { GLES_CHECK(this, programName); GLES_ASSERT(this, programName > 0, "'program' is not a valid program object"); GLint status = 0; GLES_CALL(this, glGetProgramiv, programName, GL_LINK_STATUS, &status); if (status == GL_TRUE) return true; // Success! // An compilation error happened GLint infoLogLength = 0; GLES_CALL(this, glGetProgramiv, programName, GL_INFO_LOG_LENGTH, &infoLogLength); if (infoLogLength) { std::vector<char> infoLogBuffer(infoLogLength); GLES_CALL(this, glGetProgramInfoLog, programName, infoLogLength, NULL, &infoLogBuffer[0]); } this->DeleteProgram(programName); return false; // Link error } GLuint ApiGLES::CreateProgram() { GLES_CHECK(this, -1); GLuint programName = 0; GLES_CALL_RET(this, programName, glCreateProgram); GLES_CHECK(this, programName); return programName; } GLuint ApiGLES::CreateGraphicsProgram(GLuint vertexShader, GLuint controlShader, GLuint evaluationShader, GLuint geometryShader, GLuint fragmentShader) { GLES_CHECK(this, -1); GLuint programName = 0; GLES_CALL_RET(this, programName, glCreateProgram); if (g_GraphicsCapsGLES->hasBinaryShaderRetrievableHint) GLES_CALL(this, glProgramParameteri, programName, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE); if (vertexShader) GLES_CALL(this, glAttachShader, programName, vertexShader); if (controlShader) GLES_CALL(this, glAttachShader, programName, controlShader); if (evaluationShader) GLES_CALL(this, glAttachShader, programName, evaluationShader); if (geometryShader) GLES_CALL(this, glAttachShader, programName, geometryShader); if (fragmentShader) GLES_CALL(this, glAttachShader, programName, fragmentShader); GLES_CHECK(this, programName); return programName; } GLuint ApiGLES::CreateComputeProgram(GLuint shaderName) { GLES_CHECK(this, -1); GLuint programName = 0; GLES_CALL_RET(this, programName, glCreateProgram); GLES_CALL(this, glAttachShader, programName, shaderName); this->LinkProgram(programName); GLES_CHECK(this, programName); return programName; } void ApiGLES::DeleteProgram(GLuint & programName) { GLES_CHECK(this, programName); // GLES_ASSERT(this, programName, "Trying to delete an invalid program object"); if (!programName || programName == kInvalidValue) return; if (this->m_CurrentProgramBinding == programName) this->BindProgram(0); GLES_CALL(this, glDeleteProgram, programName); programName = kInvalidValue; } GLenum ApiGLES::BindMemoryBuffer(GLuint bufferName, gl::BufferTarget _target) { GLES_CHECK(this, bufferName); GLES_ASSERT(this, bufferName, "'buffer' object hasn't being created already"); // On WebGL and Mali, we need to always use the buffer target used when creating the buffer object. gl::BufferTarget target = GetGraphicsCaps().gles.useActualBufferTargetForUploads ? _target : GetGraphicsCaps().gles.memoryBufferTargetConst; const GLenum translatedTarget = this->translate.GetBufferTarget(target); if (m_Caching && this->m_CurrentBufferBindings[target] == bufferName) return translatedTarget; this->m_CurrentBufferBindings[target] = bufferName; GLES_CALL(this, glBindBuffer, translatedTarget, bufferName); return translatedTarget; } void ApiGLES::UnbindMemoryBuffer(gl::BufferTarget _target) { GLES_CHECK(this, 0); GLES_ASSERT(this, GetGraphicsCaps().gles.buggyBindBuffer, "This function is just a wordaround code for drivers (iOS) and should not be called otherwise."); // On WebGL and Mali, we need to always use the buffer target used when creating the buffer object. gl::BufferTarget target = GetGraphicsCaps().gles.useActualBufferTargetForUploads ? _target : GetGraphicsCaps().gles.memoryBufferTargetConst; this->m_CurrentBufferBindings[target] = 0; GLES_CALL(this, glBindBuffer, this->translate.GetBufferTarget(target), 0); } void ApiGLES::BindReadBuffer(GLuint bufferName) { GLES_CHECK(this, bufferName); GLES_ASSERT(this, GetGraphicsCaps().gles.hasBufferCopy, "Buffer copy not supported"); GLES_ASSERT(this, this->debug.BufferBindings(), "The context has been modified outside of ApiGLES. States tracking is lost."); if (m_Caching && this->m_CurrentBufferBindings[gl::kCopyReadBuffer] == bufferName) return; this->m_CurrentBufferBindings[gl::kCopyReadBuffer] = bufferName; GLES_CALL(this, glBindBuffer, GL_COPY_READ_BUFFER, bufferName); } void ApiGLES::BindElementArrayBuffer(GLuint bufferName) { GLES_CHECK(this, bufferName); GLES_ASSERT(this, this->debug.BufferBindings(), "The context has been modified outside of ApiGLES. States tracking is lost."); if (m_Caching && this->m_CurrentBufferBindings[gl::kElementArrayBuffer] == bufferName) return; # if UNITY_WEBGL if (bufferName == 0) // Cannot set buffer to 0 on webgl return; # endif this->m_CurrentBufferBindings[gl::kElementArrayBuffer] = bufferName; GLES_CALL(this, glBindBuffer, GL_ELEMENT_ARRAY_BUFFER, bufferName); // Carry on an old and uncommented craft from the previous API overload code... but do we need that? g_DeviceStateGLES->transformDirtyFlags |= TransformState::kWorldViewProjDirty; } void ApiGLES::BindArrayBuffer(GLuint bufferName) { GLES_CHECK(this, bufferName); GLES_ASSERT(this, this->debug.BufferBindings(), "The context has been modified outside of ApiGLES. States tracking is lost."); if (m_Caching && this->m_CurrentBufferBindings[gl::kArrayBuffer] == bufferName) return; # if UNITY_WEBGL if (bufferName == 0) // Cannot set buffer to 0 on webgl return; # endif this->m_CurrentBufferBindings[gl::kArrayBuffer] = bufferName; GLES_CALL(this, glBindBuffer, GL_ARRAY_BUFFER, bufferName); } void ApiGLES::BindDrawIndirectBuffer(GLuint bufferName) { GLES_CHECK(this, bufferName); GLES_ASSERT(this, this->debug.BufferBindings(), "The context has been modified outside of ApiGLES. States tracking is lost."); if (m_Caching && this->m_CurrentBufferBindings[gl::kDrawIndirectBuffer] == bufferName) return; this->m_CurrentBufferBindings[gl::kDrawIndirectBuffer] = bufferName; GLES_CALL(this, glBindBuffer, GL_DRAW_INDIRECT_BUFFER, bufferName); } void ApiGLES::BindDispatchIndirectBuffer(GLuint buffer) { GLES_CHECK(this, buffer); if (m_Caching && this->m_CurrentBufferBindings[gl::kDispatchIndirectBuffer] == buffer) return; this->m_CurrentBufferBindings[gl::kDispatchIndirectBuffer] = buffer; GLES_CALL(this, glBindBuffer, GL_DISPATCH_INDIRECT_BUFFER, buffer); } void ApiGLES::BindUniformBuffer(GLuint index, GLuint bufferName) { GLES_CHECK(this, bufferName); GLES_ASSERT(this, index < GetGraphicsCaps().gles.maxUniformBufferBindings, "Unsupported uniform buffer binding"); if (m_Caching && this->m_CurrentUniformBufferBindings[index] == bufferName) return; this->m_CurrentUniformBufferBindings[index] = bufferName; GLES_CALL(this, glBindBufferBase, GL_UNIFORM_BUFFER, index, bufferName); } void ApiGLES::BindTransformFeedbackBuffer(GLuint index, GLuint bufferName) { GLES_CHECK(this, bufferName); GLES_ASSERT(this, index < GetGraphicsCaps().gles.maxTransformFeedbackBufferBindings, "Unsupported transform feedback buffer binding"); if (m_Caching && this->m_CurrentTransformBufferBindings[index] == bufferName) return; this->m_CurrentTransformBufferBindings[index] = bufferName; GLES_CALL(this, glBindBufferBase, GL_TRANSFORM_FEEDBACK_BUFFER, index, bufferName); } void ApiGLES::BindShaderStorageBuffer(GLuint index, GLuint bufferName) { GLES_CHECK(this, bufferName); GLES_ASSERT(this, index < GetGraphicsCaps().gles.maxShaderStorageBufferBindings, "Unsupported shader storage buffer binding"); if (m_Caching && this->m_CurrentStorageBufferBindings[index] == bufferName) return; this->m_CurrentStorageBufferBindings[index] = bufferName; GLES_CALL(this, glBindBufferBase, GL_SHADER_STORAGE_BUFFER, index, bufferName); } void ApiGLES::BindAtomicCounterBuffer(GLuint index, GLuint bufferName) { GLES_CHECK(this, bufferName); GLES_ASSERT(this, index < GetGraphicsCaps().gles.maxAtomicCounterBufferBindings, "Unsupported atomic counter buffer binding"); if (m_Caching && this->m_CurrentAtomicCounterBufferBindings[index] == bufferName) return; this->m_CurrentAtomicCounterBufferBindings[index] = bufferName; GLES_CALL(this, glBindBufferBase, GL_ATOMIC_COUNTER_BUFFER, index, bufferName); } GLuint ApiGLES::CreateBuffer(gl::BufferTarget target, GLsizeiptr size, const GLvoid* data, GLenum usage) { GLES_CHECK(this, -1); GLES_ASSERT(this, target >= gl::kBufferTargetFirst && target <= gl::kBufferTargetLast, "Invalid target parameter"); GLuint bufferName = 0; if (CAN_HAVE_DIRECT_STATE_ACCESS && GetGraphicsCaps().gles.hasDirectStateAccess) GLES_CALL(this, glCreateBuffers, 1, &bufferName); else GLES_CALL(this, glGenBuffers, 1, &bufferName); if (CAN_HAVE_DIRECT_STATE_ACCESS && GetGraphicsCaps().gles.hasDirectStateAccess) { GLES_CALL(this, glNamedBufferData, bufferName, size, data, usage); } else { const GLenum memoryTarget = this->BindMemoryBuffer(bufferName, target); GLES_CALL(this, glBufferData, memoryTarget, size, data, usage); } GLES_CHECK(this, bufferName); return bufferName; } void ApiGLES::DeleteBuffer(GLuint & bufferName) { GLES_CHECK(this, bufferName); if (!bufferName || bufferName == kInvalidValue) return; // Reset the buffer caching for cases where with delete a buffer which name get reallocated right after. if (this->m_CurrentBufferBindings[gl::kArrayBuffer] == bufferName) this->BindArrayBuffer(0); if (this->m_CurrentBufferBindings[gl::kElementArrayBuffer] == bufferName) this->BindElementArrayBuffer(0); if (GetGraphicsCaps().gles.hasBufferQuery && this->m_CurrentBufferBindings[gl::kQueryBuffer] == bufferName) { this->glBindBuffer(GL_QUERY_BUFFER, 0); this->m_CurrentBufferBindings[gl::kQueryBuffer] = 0; } if (GetGraphicsCaps().gles.hasIndirectParameter && this->m_CurrentBufferBindings[gl::kParameterBuffer] == bufferName) { this->glBindBuffer(GL_PARAMETER_BUFFER_ARB, 0); this->m_CurrentBufferBindings[gl::kParameterBuffer] = 0; } if (GetGraphicsCaps().gles.hasBufferCopy) { if (this->m_CurrentBufferBindings[gl::kCopyReadBuffer] == bufferName) { this->glBindBuffer(GL_COPY_READ_BUFFER, 0); this->m_CurrentBufferBindings[gl::kCopyReadBuffer] = 0; } if (this->m_CurrentBufferBindings[gl::kCopyWriteBuffer] == bufferName) { this->glBindBuffer(GL_COPY_WRITE_BUFFER, 0); this->m_CurrentBufferBindings[gl::kCopyWriteBuffer] = 0; } } if (GetGraphicsCaps().gles.hasIndirectDraw && this->m_CurrentBufferBindings[gl::kDrawIndirectBuffer] == bufferName) { this->glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0); this->m_CurrentBufferBindings[gl::kDrawIndirectBuffer] = 0; } for (std::size_t i = 0; i < m_CurrentUniformBufferBindings.size(); ++i) { if (m_CurrentUniformBufferBindings[i] != bufferName) continue; this->BindUniformBuffer(i, 0); } for (std::size_t i = 0; i < m_CurrentTransformBufferBindings.size(); ++i) { if (m_CurrentTransformBufferBindings[i] != bufferName) continue; this->BindTransformFeedbackBuffer(i, 0); } for (std::size_t i = 0; i < m_CurrentStorageBufferBindings.size(); ++i) { if (m_CurrentStorageBufferBindings[i] != bufferName) continue; this->BindShaderStorageBuffer(i, 0); } for (std::size_t i = 0; i < m_CurrentAtomicCounterBufferBindings.size(); ++i) { if (m_CurrentAtomicCounterBufferBindings[i] != bufferName) continue; this->BindAtomicCounterBuffer(i, 0); } // Now we can delete the buffer object GLES_CALL(this, glDeleteBuffers, 1, &bufferName); bufferName = kInvalidValue; } GLuint ApiGLES::RecreateBuffer(GLuint bufferName, gl::BufferTarget target, GLsizeiptr size, const GLvoid* data, GLenum usage) { GLES_CHECK(this, bufferName); GLES_ASSERT(this, bufferName, "'buffer' object hasn't being created already"); GLES_ASSERT(this, this->debug.BufferBindings(), "The context has been modified outside of ApiGLES. States tracking is lost."); if (CAN_HAVE_DIRECT_STATE_ACCESS && GetGraphicsCaps().gles.hasDirectStateAccess) { GLES_CALL(this, glNamedBufferData, bufferName, size, data, usage); } else { const GLenum memoryTarget = gGL->BindMemoryBuffer(bufferName, target); GLES_CALL(this, glBufferData, memoryTarget, size, data, usage); if (GetGraphicsCaps().gles.buggyBindBuffer) gGL->UnbindMemoryBuffer(target); } return bufferName; } void ApiGLES::UploadBufferSubData(GLuint bufferName, gl::BufferTarget target, GLintptr offset, GLsizeiptr size, const GLvoid* data) { GLES_CHECK(this, bufferName); GLES_ASSERT(this, bufferName, "'buffer' object hasn't being created already"); GLES_ASSERT(this, this->debug.BufferBindings(), "The context has been modified outside of ApiGLES. States tracking is lost."); if (CAN_HAVE_DIRECT_STATE_ACCESS && GetGraphicsCaps().gles.hasDirectStateAccess) { GLES_CALL(this, glNamedBufferSubData, bufferName, offset, size, data); } else { const GLenum memoryTarget = gGL->BindMemoryBuffer(bufferName, target); GLES_CALL(this, glBufferSubData, memoryTarget, offset, size, data); if (GetGraphicsCaps().gles.buggyBindBuffer) gGL->UnbindMemoryBuffer(target); } } void* ApiGLES::MapBuffer(GLuint bufferName, gl::BufferTarget target, GLintptr offset, GLsizeiptr length, GLbitfield access) { GLES_CHECK(this, bufferName); GLES_ASSERT(this, GetGraphicsCaps().gles.hasMapbufferRange, "Map buffer range is not supported"); GLES_ASSERT(this, this->debug.BufferBindings(), "The context has been modified outside of ApiGLES. States tracking is lost."); void* ptr = NULL; if (CAN_HAVE_DIRECT_STATE_ACCESS && GetGraphicsCaps().gles.hasDirectStateAccess) { GLES_CALL_RET(this, ptr, glMapNamedBufferRange, bufferName, offset, length, access); } else { const GLenum memoryTarget = gGL->BindMemoryBuffer(bufferName, target); GLES_CALL_RET(this, ptr, glMapBufferRange, memoryTarget, offset, length, access); if (GetGraphicsCaps().gles.buggyBindBuffer) gGL->UnbindMemoryBuffer(target); } return ptr; } void ApiGLES::UnmapBuffer(GLuint bufferName, gl::BufferTarget target) { GLES_CHECK(this, bufferName); GLES_ASSERT(this, GetGraphicsCaps().gles.hasMapbufferRange, "Map buffer range is not supported"); GLES_ASSERT(this, this->debug.BufferBindings(), "The context has been modified outside of ApiGLES. States tracking is lost."); if (CAN_HAVE_DIRECT_STATE_ACCESS && GetGraphicsCaps().gles.hasDirectStateAccess) { GLES_CALL(this, glUnmapNamedBuffer, bufferName); } else { const GLenum memoryTarget = gGL->BindMemoryBuffer(bufferName, target); GLES_CALL(this, glUnmapBuffer, memoryTarget); if (GetGraphicsCaps().gles.buggyBindBuffer) gGL->UnbindMemoryBuffer(target); } } void ApiGLES::FlushBuffer(GLuint bufferName, gl::BufferTarget target, GLintptr offset, GLsizeiptr length) { GLES_CHECK(this, bufferName); GLES_ASSERT(this, GetGraphicsCaps().gles.hasMapbufferRange, "Map buffer range is not supported"); GLES_ASSERT(this, this->debug.BufferBindings(), "The context has been modified outside of ApiGLES. States tracking is lost."); if (CAN_HAVE_DIRECT_STATE_ACCESS && GetGraphicsCaps().gles.hasDirectStateAccess) { GLES_CALL(this, glFlushMappedNamedBufferRange, bufferName, offset, length); } else { const GLenum memoryTarget = gGL->BindMemoryBuffer(bufferName, target); GLES_CALL(this, glFlushMappedBufferRange, memoryTarget, offset, length); if (GetGraphicsCaps().gles.buggyBindBuffer) gGL->UnbindMemoryBuffer(target); } } void ApiGLES::CopyBufferSubData(GLuint srcBuffer, GLuint dstBuffer, GLintptr srcOffset, GLintptr dstOffset, GLsizeiptr size) { GLES_CHECK(this, dstBuffer); GLES_ASSERT(this, GetGraphicsCaps().gles.hasBufferCopy, "Buffer copy is not supported"); GLES_ASSERT(this, this->debug.BufferBindings(), "The context has been modified outside of ApiGLES. States tracking is lost."); gGL->BindMemoryBuffer(dstBuffer, gl::kCopyWriteBuffer); gGL->BindReadBuffer(srcBuffer); GLES_CALL(this, glCopyBufferSubData, GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, srcOffset, dstOffset, size); } void ApiGLES::ClearBuffer(GLuint bufferName, gl::BufferTarget target) { GLES_CHECK(this, bufferName); GLES_ASSERT(this, GetGraphicsCaps().gles.hasBufferClear, "Buffer clear is not supported"); GLES_ASSERT(this, this->debug.BufferBindings(), "The context has been modified outside of ApiGLES. States tracking is lost."); if (CAN_HAVE_DIRECT_STATE_ACCESS && GetGraphicsCaps().gles.hasDirectStateAccess) { GLuint zeroData = 0; GLES_CALL(this, glClearNamedBufferData, bufferName, GL_R32UI, GL_RED, GL_UNSIGNED_INT, &zeroData); } else { GLuint zeroData = 0; const GLenum memoryTarget = gGL->BindMemoryBuffer(bufferName, target); GLES_CALL(this, glClearBufferData, memoryTarget, GL_R32UI, GL_RED, GL_UNSIGNED_INT, &zeroData); if (GetGraphicsCaps().gles.buggyBindBuffer) gGL->UnbindMemoryBuffer(target); } } void ApiGLES::ClearBufferSubData(GLuint bufferName, gl::BufferTarget target, GLintptr offset, GLsizeiptr size) { GLES_CHECK(this, bufferName); GLES_ASSERT(this, GetGraphicsCaps().gles.hasMapbufferRange, "buffer mapping is not supported"); GLES_ASSERT(this, this->debug.BufferBindings(), "The context has been modified outside of ApiGLES. States tracking is lost."); GLuint zeroData = 0; if (CAN_HAVE_DIRECT_STATE_ACCESS && GetGraphicsCaps().gles.hasDirectStateAccess) { GLES_CALL(this, glClearNamedBufferSubData, bufferName, GL_R32UI, offset, size, GL_RED, GL_UNSIGNED_INT, &zeroData); } else if (GetGraphicsCaps().gles.hasBufferClear) { const GLenum memoryTarget = gGL->BindMemoryBuffer(bufferName, target); GLES_CALL(this, glClearBufferSubData, memoryTarget, GL_R32UI, offset, size, GL_RED, GL_UNSIGNED_INT, &zeroData); if (GetGraphicsCaps().gles.buggyBindBuffer) gGL->UnbindMemoryBuffer(target); } else if (GetGraphicsCaps().gles.hasMapbufferRange) { UInt32* pointer = static_cast<UInt32*>(this->MapBuffer(bufferName, target, offset, size, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT)); for (std::size_t i = 0, n = (size - offset) / sizeof(UInt32); i < n; ++i) *(pointer + i) = zeroData; this->UnmapBuffer(bufferName, target); } else { GLES_ASSERT(this, 0, "Unsupported GfxDeviceLevel"); } } gl::VertexArrayHandle ApiGLES::CreateVertexArray() { //GLES_ASSERT(this, GetGraphicsCaps().gles.hasVertexArrayObject, "Vertex array objects are not supported"); GLuint VertexArrayName = 0; GLES_CALL(this, glGenVertexArrays, 1, &VertexArrayName); return gl::VertexArrayHandle(VertexArrayName); } void ApiGLES::DeleteVertexArray(gl::VertexArrayHandle& vertexArrayName) { GLES_CHECK(this, vertexArrayName); GLES_ASSERT(this, GetGraphicsCaps().gles.hasVertexArrayObject, "Vertex array objects are not supported"); GLuint vaName = GLES_OBJECT_NAME(vertexArrayName); GLES_CALL(this, glDeleteVertexArrays, 1, &vaName); vertexArrayName = gl::VertexArrayHandle(); } void ApiGLES::BindVertexArray(gl::VertexArrayHandle vertexArrayName) { GLES_CHECK(this, vertexArrayName); GLES_ASSERT(this, GetGraphicsCaps().gles.hasVertexArrayObject, "Vertex Array Objects are not supported"); if (m_Caching && this->m_CurrentVertexArrayBinding == vertexArrayName) return; this->m_CurrentVertexArrayBinding = vertexArrayName; GLES_CALL(this, glBindVertexArray, GLES_OBJECT_NAME(vertexArrayName)); } bool ApiGLES::IsVertexArray(gl::VertexArrayHandle vertexArrayName) { GLboolean isVertexArray = 0; GLES_CHECK(this, vertexArrayName); GLES_CALL_RET(this, isVertexArray, glIsVertexArray, GLES_OBJECT_NAME(vertexArrayName)); return (0 != isVertexArray); } void ApiGLES::EnableVertexArrayAttrib(GLuint attribIndex, GLuint bufferName, gl::VertexArrayAttribKind Kind, GLint size, VertexChannelFormat format, GLsizei stride, const GLvoid* offset) { GLES_CHECK(this, attribIndex); GLES_ASSERT(this, m_CurrentVertexArrayBinding == m_DefaultVertexArrayName, "VertexArrayAttribPointer can only be called on a default vertex array object by Unity design"); GLES_ASSERT(this, attribIndex < GetGraphicsCaps().gles.maxAttributes, "Too many attributes used"); GLES_ASSERT(this, size > 0 && size <= 4, "Invalid number of attribute components"); // Enable vertex attribute if (!m_Caching || !(m_CurrentDefaultVertexArrayEnabled & (1 << attribIndex))) { GLES_CALL(this, glEnableVertexAttribArray, attribIndex); m_CurrentDefaultVertexArrayEnabled |= (1 << attribIndex); } // Setup the vertex attribute VertexArray vertexArray(*this, bufferName, size, format, stride, offset, Kind); if (m_Caching && CompareMemory(vertexArray, m_CurrentDefaultVertexArray[attribIndex])) return; m_CurrentDefaultVertexArray[attribIndex] = vertexArray; const GLenum type = this->translate.VertexType(format); GLES_ASSERT(this, bufferName != 0, "An array buffer must be bound to setup a vertex attribute"); this->BindArrayBuffer(bufferName); switch (Kind) { case gl::kVertexArrayAttribSNorm: case gl::kVertexArrayAttribSNormNormalize: GLES_CALL(this, glVertexAttribPointer, attribIndex, size, type, Kind == gl::kVertexArrayAttribSNormNormalize ? GL_TRUE : GL_FALSE, stride, offset); break; case gl::kVertexArrayAttribInteger: GLES_CALL(this, glVertexAttribIPointer, attribIndex, size, type, stride, offset); break; case gl::kVertexArrayAttribLong: GLES_CALL(this, glVertexAttribLPointer, attribIndex, size, type, stride, offset); break; } } void ApiGLES::DisableVertexArrayAttrib(GLuint attribIndex) { GLES_CHECK(this, attribIndex); GLES_ASSERT(this, m_CurrentVertexArrayBinding == m_DefaultVertexArrayName, "VertexArrayAttribPointer can only be called on a default vertex array object by Unity design"); GLES_ASSERT(this, attribIndex < GetGraphicsCaps().gles.maxAttributes, "Too many attributes used"); if (m_Caching && !(m_CurrentDefaultVertexArrayEnabled & (1 << attribIndex))) return; m_CurrentDefaultVertexArrayEnabled &= ~(1 << attribIndex); GLES_CALL(this, glDisableVertexAttribArray, attribIndex); } void ApiGLES::SetPatchVertices(int count) { GLES_CHECK(this, -1); GLES_ASSERT(this, GetGraphicsCaps().gles.hasTessellationShader, "Tessellation is not supported"); if (m_Caching && m_CurrentPatchVertices == count) return; m_CurrentPatchVertices = count; GLES_CALL(this, glPatchParameteri, GL_PATCH_VERTICES, static_cast<GLint>(count)); } void ApiGLES::Enable(gl::EnabledCap cap) { GLES_CHECK(this, -1); GLES_ASSERT(this, (cap == gl::kTextureCubeMapSeamless && GetGraphicsCaps().gles.hasSeamlessCubemapEnable) || (cap != gl::kTextureCubeMapSeamless), "OPENGL ERROR: gl::kTextureCubeMapSeamless is not supported"); const UInt64 flag = (static_cast<UInt64>(1) << cap); if (m_Caching && m_CurrentCapEnabled & flag) return; m_CurrentCapEnabled |= flag; GLES_CALL(this, glEnable, this->translate.Enable(cap)); } void ApiGLES::Disable(gl::EnabledCap cap) { GLES_CHECK(this, -1); GLES_ASSERT(this, (cap == gl::kTextureCubeMapSeamless && GetGraphicsCaps().gles.hasSeamlessCubemapEnable) || (cap != gl::kTextureCubeMapSeamless), "OPENGL ERROR: gl::kTextureCubeMapSeamless is not supported"); const UInt64 flag = (static_cast<UInt64>(1) << cap); if (m_Caching && !(m_CurrentCapEnabled & flag)) return; m_CurrentCapEnabled &= ~flag; GLES_CALL(this, glDisable, this->translate.Enable(cap)); } bool ApiGLES::IsEnabled(gl::EnabledCap cap) const { return m_CurrentCapEnabled & (static_cast<UInt64>(1) << cap) ? true : false; } void ApiGLES::SetPolygonMode(bool wire) { GLES_CHECK(this, -1); if (!GetGraphicsCaps().gles.hasWireframe) return; if (m_Caching && m_CurrentPolygonModeWire == wire) return; this->m_CurrentPolygonModeWire = wire; if (wire) { this->Enable(gl::kPolygonOffsetLine); GLES_CALL(this, glPolygonMode, GL_FRONT_AND_BACK, GL_LINE); } else { this->Disable(gl::kPolygonOffsetLine); GLES_CALL(this, glPolygonMode, GL_FRONT_AND_BACK, GL_FILL); } } void ApiGLES::SetCullMode(const ::CullMode cullMode) { GLES_CHECK(this, -1); GLES_ASSERT(this, cullMode != kCullUnknown, "Invalid cull mode"); GLES_ASSERT(this, !m_Caching || this->debug.CullMode(), "OPENGL ERROR: The OpenGL context has been modified outside of ApiGLES. States tracking is lost."); if (m_Caching && m_CurrentCullMode == cullMode) return; this->m_CurrentCullMode = cullMode; switch (cullMode) { case kCullOff: this->Disable(gl::kCullFace); break; case kCullFront: GLES_CALL(this, glCullFace, GL_FRONT); this->Enable(gl::kCullFace); break; case kCullBack: GLES_CALL(this, glCullFace, GL_BACK); this->Enable(gl::kCullFace); break; default: GLES_ASSERT(this, 0, "Unkown cull mode"); } } gl::QueryHandle ApiGLES::CreateQuery() { GLES_CHECK(this, ApiGLES::kInvalidValue); GLES_ASSERT(this, GetGraphicsCaps().hasTimerQuery, "Timer query is not supported"); GLuint queryName = 0; GLES_CALL(this, glGenQueries, 1, &queryName); GLES_CHECK(this, queryName); return gl::QueryHandle(queryName); } void ApiGLES::DeleteQuery(gl::QueryHandle & query) { GLES_CHECK(this, GLES_OBJECT_NAME(query)); GLES_ASSERT(this, GetGraphicsCaps().hasTimerQuery, "Timer query is not supported"); GLuint const queryName = GLES_OBJECT_NAME(query); GLES_CALL(this, glDeleteQueries, 1, &queryName); query = gl::QueryHandle::kInvalidValue; } void ApiGLES::QueryTimeStamp(gl::QueryHandle query) { GLES_CHECK(this, GLES_OBJECT_NAME(query)); GLES_ASSERT(this, GetGraphicsCaps().hasTimerQuery, "Timer query is not supported"); GLES_CALL(this, glQueryCounter, GLES_OBJECT_NAME(query), GL_TIMESTAMP); } GLuint64 ApiGLES::Query(gl::QueryHandle query, gl::QueryResult queryResult) { GLES_CHECK(this, GLES_OBJECT_NAME(query)); GLES_ASSERT(this, GetGraphicsCaps().hasTimerQuery, "Timer query is not supported"); GLuint64 result = 0; GLES_CALL(this, glGetQueryObjectui64v, GLES_OBJECT_NAME(query), queryResult, &result); return result; } GLint ApiGLES::Get(GLenum cap) const { GLint result = 0; GLES_CALL(this, glGetIntegerv, cap, &result); return result; } bool ApiGLES::QueryExtension(const char * extension) const { GLES_CHECK(this, -1); // WebGL 2.0 does not seem to support GL_NUM_EXTENSIONS if (IsGfxLevelES2(GetGraphicsCaps().gles.featureLevel)) { const char* extensions = reinterpret_cast<const char*>(this->glGetString(GL_EXTENSIONS)); if (!extensions) return false; const char* match = strstr(extensions, extension); if (!match) return false; // we need an exact match, extensions string is a list of extensions separated by spaces, e.g. "GL_EXT_draw_buffers" should not match "GL_EXT_draw_buffers_indexed" const char* end = match + strlen(extension); return *end == ' ' || *end == '\0'; } else { const GLint numExtensions = this->Get(GL_NUM_EXTENSIONS); for (GLint i = 0; i < numExtensions; ++i) { const char* Extension = reinterpret_cast<const char*>(this->glGetStringi(GL_EXTENSIONS, i)); if (!strcmp(extension, Extension)) return true; } return false; } } std::string ApiGLES::GetExtensionString() const { GLES_CHECK(this, -1); std::string extensionString; // WebGL 2.0 does not seem to support GL_NUM_EXTENSIONS if (IsGfxLevelES2(GetGraphicsCaps().gles.featureLevel)) { const GLubyte* string = 0; GLES_CALL_RET(this, string, glGetString, GL_EXTENSIONS); extensionString = reinterpret_cast<const char*>(string); } else { const GLint numExtensions = this->Get(GL_NUM_EXTENSIONS); for (GLint i = 0; i < numExtensions; ++i) { const GLubyte* string = 0; GLES_CALL_RET(this, string, glGetStringi, GL_EXTENSIONS, i); extensionString += std::string(" ") + reinterpret_cast<const char*>(string); } } return extensionString; } const char* ApiGLES::GetDriverString(gl::DriverQuery Query) const { GLES_CHECK(this, -1); const GLenum translatedQuery = GL_VENDOR + Query; // GL_VENDOR, GL_RENDERER and GL_VERSION are contiguous values, query is a zero based enum const GLubyte* stringPointer = 0; GLES_CALL_RET(this, stringPointer, glGetString, translatedQuery); return reinterpret_cast<const char*>(stringPointer); } void ApiGLES::Submit(gl::SubmitMode mode) { switch (mode) { case gl::SUBMIT_FINISH: GLES_CALL(this, glFinish); return; case gl::SUBMIT_FLUSH: GLES_CALL(this, glFlush); return; default: GLES_ASSERT(this, 0, "Unsupported submot mode"); } } bool ApiGLES::Verify() const { GLES_CHECK(this, -1); GLES_ASSERT(this, this->debug.Verify(), "The OpenGL context has been modified outside of ApiGLES. States tracking is lost."); typedef std::pair<bool, bool> Enable; struct IsEnabled { Enable operator()(const ApiGLES & api, const gl::EnabledCap & capUnity) const { return Enable( api.glIsEnabled(api.translate.Enable(capUnity)) == GL_TRUE, (api.m_CurrentCapEnabled & (static_cast<UInt64>(1) << capUnity)) != 0); } } isEnabled; bool check = true; if (GetGraphicsCaps().gles.hasDebugOutput) { const Enable & debugSync = isEnabled(*this, gl::kDebugOutputSynchronous); if (GetGraphicsCaps().gles.hasDebugKHR) { const Enable & debug = isEnabled(*this, gl::kDebugOutput); } } if (IsGfxLevelCore(GetGraphicsCaps().gles.featureLevel)) { const Enable & colorLogicOp = isEnabled(*this, gl::kColorLogicOp); const Enable & depthClamp = isEnabled(*this, gl::kDepthClamp); const Enable & framebufferSRGB = isEnabled(*this, gl::kFramebufferSRGB); const Enable & lineSmooth = isEnabled(*this, gl::kLineSmooth); const Enable & multisample = isEnabled(*this, gl::kMultisample); const Enable & polygonOffsetLine = isEnabled(*this, gl::kPolygonOffsetLine); const Enable & polygonOffsetPoint = isEnabled(*this, gl::kPolygonOffsetpoint); const Enable & polygonSmooth = isEnabled(*this, gl::kPolygonSmooth); const Enable & primitiveRestart = isEnabled(*this, gl::kPrimitiveRestart); const Enable & sampleAlphaToOne = isEnabled(*this, gl::kSampleAlphaToOne); const Enable & sampleShading = isEnabled(*this, gl::kSampleShading); const Enable & textureCubeMapSeamless = isEnabled(*this, gl::kTextureCubeMapSeamless); const Enable & programPointSize = isEnabled(*this, gl::kProgramPointSize); } if (IsGfxLevelES(GetGraphicsCaps().gles.featureLevel, kGfxLevelES31) || IsGfxLevelCore(GetGraphicsCaps().gles.featureLevel, kGfxLevelCore40)) { const Enable & sampleMask = isEnabled(*this, gl::kSampleMask); } const Enable & blend = isEnabled(*this, gl::kBlend); const Enable & cullFace = isEnabled(*this, gl::kCullFace); const Enable & depthTest = isEnabled(*this, gl::kDepthTest); const Enable & dither = isEnabled(*this, gl::kDither); const Enable & polygonOffsetFill = isEnabled(*this, gl::kPolygonOffsetFill); const Enable & sampleAlphaToCoverage = isEnabled(*this, gl::kSampleAlphaToCoverage); const Enable & sampleCoverage = isEnabled(*this, gl::kSampleCoverage); const Enable & scissorTest = isEnabled(*this, gl::kScissorTest); const Enable & stencilTest = isEnabled(*this, gl::kStencilTest); return check; } ApiGLES::VertexArray::VertexArray() : m_Offset(0) , m_Stride(0) , m_Buffer(0) , m_Bitfield(0) {} ApiGLES::VertexArray::VertexArray(const ApiGLES & api, GLuint buffer, GLint size, VertexChannelFormat format, GLsizei stride, const GLvoid* offset, gl::VertexArrayAttribKind kind) : m_Offset(offset) , m_Stride(stride) , m_Buffer(buffer) , m_Bitfield(0) { this->m_Bitfield = api.translate.VertexArrayKindBitfield(kind) | api.translate.VertexArraySizeBitfield(size) | api.translate.VertexArrayTypeBitfield(format); }
[ "akheyun@gmail.com" ]
akheyun@gmail.com
cd53bae4d9ea63bc540a6b48a70ae266f1adeca8
947e2d199cdd0adb5f34befb17e639c9e0cc8867
/按键流程分析/InputReader.cpp
5bb64831c76058ed57f7c908d521cf554277db0e
[]
no_license
qfkongyan/AndroidFramework
9b11a9d273c820d2db23cc8fa158e38d554e40da
3cd1c042b13f0048b8bd59ae8092cc6f81a94738
refs/heads/master
2022-12-14T07:22:39.986361
2020-09-14T13:37:05
2020-09-14T13:37:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
268,279
cpp
/* * Copyright (C) 2010 The Android Open Source Project * * 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. */ #define LOG_TAG "InputReader" //#define LOG_NDEBUG 0 // Log debug messages for each raw event received from the EventHub. #define DEBUG_RAW_EVENTS 0 // Log debug messages about touch screen filtering hacks. #define DEBUG_HACKS 0 // Log debug messages about virtual key processing. #define DEBUG_VIRTUAL_KEYS 0 // Log debug messages about pointers. #define DEBUG_POINTERS 0 // Log debug messages about pointer assignment calculations. #define DEBUG_POINTER_ASSIGNMENT 0 // Log debug messages about gesture detection. #define DEBUG_GESTURES 0 // Log debug messages about the vibrator. #define DEBUG_VIBRATOR 0 #include "InputReader.h" #include <cutils/log.h> #include <cutils/properties.h> #include <input/Keyboard.h> #include <input/VirtualKeyMap.h> #include <stddef.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <limits.h> #include <math.h> #include <fcntl.h> #define INDENT " " #define INDENT2 " " #define INDENT3 " " #define INDENT4 " " #define INDENT5 " " namespace android { // --- Constants --- // Maximum number of slots supported when using the slot-based Multitouch Protocol B. static const size_t MAX_SLOTS = 32; static char g_dmode_str[32]; static char g_daxis_str[32]; // --- Static Functions --- template<typename T> inline static T abs(const T& value) { return value < 0 ? - value : value; } template<typename T> inline static T min(const T& a, const T& b) { return a < b ? a : b; } template<typename T> inline static void swap(T& a, T& b) { T temp = a; a = b; b = temp; } inline static float avg(float x, float y) { return (x + y) / 2; } inline static float distance(float x1, float y1, float x2, float y2) { return hypotf(x1 - x2, y1 - y2); } inline static int32_t signExtendNybble(int32_t value) { return value >= 8 ? value - 16 : value; } static inline const char* toString(bool value) { return value ? "true" : "false"; } static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation, const int32_t map[][4], size_t mapSize) { if (orientation != DISPLAY_ORIENTATION_0) { for (size_t i = 0; i < mapSize; i++) { if (value == map[i][0]) { return map[i][orientation]; } } } return value; } static const int32_t keyCodeRotationMap[][4] = { // key codes enumerated counter-clockwise with the original (unrotated) key first // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT }, { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN }, { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT }, { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP }, }; static const size_t keyCodeRotationMapSize = sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]); static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) { return rotateValueUsingRotationMap(keyCode, orientation, keyCodeRotationMap, keyCodeRotationMapSize); } static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) { float temp; switch (orientation) { case DISPLAY_ORIENTATION_90: temp = *deltaX; *deltaX = *deltaY; *deltaY = -temp; break; case DISPLAY_ORIENTATION_180: *deltaX = -*deltaX; *deltaY = -*deltaY; break; case DISPLAY_ORIENTATION_270: temp = *deltaX; *deltaX = -*deltaY; *deltaY = temp; break; } } static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) { return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0; } // Returns true if the pointer should be reported as being down given the specified // button states. This determines whether the event is reported as a touch event. static bool isPointerDown(int32_t buttonState) { return buttonState & (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY | AMOTION_EVENT_BUTTON_TERTIARY); } static float calculateCommonVector(float a, float b) { if (a > 0 && b > 0) { return a < b ? a : b; } else if (a < 0 && b < 0) { return a > b ? a : b; } else { return 0; } } static void synthesizeButtonKey(InputReaderContext* context, int32_t action, nsecs_t when, int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState, int32_t buttonState, int32_t keyCode) { if ( (action == AKEY_EVENT_ACTION_DOWN && !(lastButtonState & buttonState) && (currentButtonState & buttonState)) || (action == AKEY_EVENT_ACTION_UP && (lastButtonState & buttonState) && !(currentButtonState & buttonState))) { NotifyKeyArgs args(when, deviceId, source, policyFlags, action, 0, keyCode, 0, context->getGlobalMetaState(), when); context->getListener()->notifyKey(&args); } } static void synthesizeButtonKeys(InputReaderContext* context, int32_t action, nsecs_t when, int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) { synthesizeButtonKey(context, action, when, deviceId, source, policyFlags, lastButtonState, currentButtonState, AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK); synthesizeButtonKey(context, action, when, deviceId, source, policyFlags, lastButtonState, currentButtonState, AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD); } // --- InputReaderConfiguration --- bool InputReaderConfiguration::getDisplayInfo(bool external, DisplayViewport* outViewport) const { const DisplayViewport& viewport = external ? mExternalDisplay : mInternalDisplay; if (viewport.displayId >= 0) { *outViewport = viewport; return true; } return false; } void InputReaderConfiguration::setDisplayInfo(bool external, const DisplayViewport& viewport) { DisplayViewport& v = external ? mExternalDisplay : mInternalDisplay; v = viewport; } // --- InputReader --- InputReader::InputReader(const sp<EventHubInterface>& eventHub, const sp<InputReaderPolicyInterface>& policy, const sp<InputListenerInterface>& listener) : mContext(this), mEventHub(eventHub), mPolicy(policy), mGlobalMetaState(0), mGeneration(1), mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX), mConfigurationChangesToRefresh(0) { mQueuedListener = new QueuedInputListener(listener); { // acquire lock AutoMutex _l(mLock); refreshConfigurationLocked(0); updateGlobalMetaStateLocked(); } // release lock } InputReader::~InputReader() { for (size_t i = 0; i < mDevices.size(); i++) { delete mDevices.valueAt(i); } } void InputReader::loopOnce() { int32_t oldGeneration; int32_t timeoutMillis; bool inputDevicesChanged = false; Vector<InputDeviceInfo> inputDevices; { // acquire lock AutoMutex _l(mLock); oldGeneration = mGeneration; timeoutMillis = -1; uint32_t changes = mConfigurationChangesToRefresh; if (changes) { mConfigurationChangesToRefresh = 0; timeoutMillis = 0; refreshConfigurationLocked(changes); } else if (mNextTimeout != LLONG_MAX) { nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC); timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout); } } // release lock size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE); { // acquire lock AutoMutex _l(mLock); mReaderIsAliveCondition.broadcast(); if (count) { processEventsLocked(mEventBuffer, count); } if (mNextTimeout != LLONG_MAX) { nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC); if (now >= mNextTimeout) { #if DEBUG_RAW_EVENTS ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f); #endif mNextTimeout = LLONG_MAX; timeoutExpiredLocked(now); } } if (oldGeneration != mGeneration) { inputDevicesChanged = true; getInputDevicesLocked(inputDevices); } } // release lock // Send out a message that the describes the changed input devices. if (inputDevicesChanged) { mPolicy->notifyInputDevicesChanged(inputDevices); } // Flush queued events out to the listener. // This must happen outside of the lock because the listener could potentially call // back into the InputReader's methods, such as getScanCodeState, or become blocked // on another thread similarly waiting to acquire the InputReader lock thereby // resulting in a deadlock. This situation is actually quite plausible because the // listener is actually the input dispatcher, which calls into the window manager, // which occasionally calls into the input reader. mQueuedListener->flush(); } void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) { for (const RawEvent* rawEvent = rawEvents; count;) { int32_t type = rawEvent->type; size_t batchSize = 1; if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) { int32_t deviceId = rawEvent->deviceId; while (batchSize < count) { if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT || rawEvent[batchSize].deviceId != deviceId) { break; } batchSize += 1; } #if DEBUG_RAW_EVENTS ALOGD("BatchSize: %d Count: %d", batchSize, count); #endif processEventsForDeviceLocked(deviceId, rawEvent, batchSize); } else { switch (rawEvent->type) { case EventHubInterface::DEVICE_ADDED: addDeviceLocked(rawEvent->when, rawEvent->deviceId); break; case EventHubInterface::DEVICE_REMOVED: removeDeviceLocked(rawEvent->when, rawEvent->deviceId); break; case EventHubInterface::FINISHED_DEVICE_SCAN: handleConfigurationChangedLocked(rawEvent->when); break; default: ALOG_ASSERT(false); // can't happen break; } } count -= batchSize; rawEvent += batchSize; } } void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) { ssize_t deviceIndex = mDevices.indexOfKey(deviceId); if (deviceIndex >= 0) { ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId); return; } InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId); uint32_t classes = mEventHub->getDeviceClasses(deviceId); int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId); InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes); device->configure(when, &mConfig, 0); device->reset(when); if (device->isIgnored()) { ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId, identifier.name.string()); } else { ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId, identifier.name.string(), device->getSources()); } mDevices.add(deviceId, device); bumpGenerationLocked(); } void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) { InputDevice* device = NULL; ssize_t deviceIndex = mDevices.indexOfKey(deviceId); if (deviceIndex < 0) { ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId); return; } device = mDevices.valueAt(deviceIndex); mDevices.removeItemsAt(deviceIndex, 1); bumpGenerationLocked(); if (device->isIgnored()) { ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)", device->getId(), device->getName().string()); } else { ALOGI("Device removed: id=%d, name='%s', sources=0x%08x", device->getId(), device->getName().string(), device->getSources()); } device->reset(when); delete device; } InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) { InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(), controllerNumber, identifier, classes); // External devices. if (classes & INPUT_DEVICE_CLASS_EXTERNAL) { device->setExternal(true); } // Switch-like devices. if (classes & INPUT_DEVICE_CLASS_SWITCH) { device->addMapper(new SwitchInputMapper(device)); } // Vibrator-like devices. if (classes & INPUT_DEVICE_CLASS_VIBRATOR) { device->addMapper(new VibratorInputMapper(device)); } // Keyboard-like devices. uint32_t keyboardSource = 0; int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC; if (classes & INPUT_DEVICE_CLASS_KEYBOARD) { keyboardSource |= AINPUT_SOURCE_KEYBOARD; } if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) { keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC; } if (classes & INPUT_DEVICE_CLASS_DPAD) { keyboardSource |= AINPUT_SOURCE_DPAD; } if (classes & INPUT_DEVICE_CLASS_GAMEPAD) { keyboardSource |= AINPUT_SOURCE_GAMEPAD; } if (keyboardSource != 0) { device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType)); } // Cursor-like devices. if (classes & INPUT_DEVICE_CLASS_CURSOR) { device->addMapper(new CursorInputMapper(device)); } // Touchscreens and touchpad devices. if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) { device->addMapper(new MultiTouchInputMapper(device)); } else if (classes & INPUT_DEVICE_CLASS_TOUCH) { device->addMapper(new SingleTouchInputMapper(device)); } // Joystick-like devices. if (classes & INPUT_DEVICE_CLASS_JOYSTICK) { device->addMapper(new JoystickInputMapper(device)); } return device; } void InputReader::processEventsForDeviceLocked(int32_t deviceId, const RawEvent* rawEvents, size_t count) { ssize_t deviceIndex = mDevices.indexOfKey(deviceId); if (deviceIndex < 0) { ALOGW("Discarding event for unknown deviceId %d.", deviceId); return; } InputDevice* device = mDevices.valueAt(deviceIndex); if (device->isIgnored()) { //ALOGD("Discarding event for ignored deviceId %d.", deviceId); return; } device->process(rawEvents, count); } void InputReader::timeoutExpiredLocked(nsecs_t when) { for (size_t i = 0; i < mDevices.size(); i++) { InputDevice* device = mDevices.valueAt(i); if (!device->isIgnored()) { device->timeoutExpired(when); } } } void InputReader::handleConfigurationChangedLocked(nsecs_t when) { // Reset global meta state because it depends on the list of all configured devices. updateGlobalMetaStateLocked(); // Enqueue configuration changed. NotifyConfigurationChangedArgs args(when); mQueuedListener->notifyConfigurationChanged(&args); } void InputReader::refreshConfigurationLocked(uint32_t changes) { mPolicy->getReaderConfiguration(&mConfig); mEventHub->setExcludedDevices(mConfig.excludedDeviceNames); if (changes) { ALOGI("Reconfiguring input devices. changes=0x%08x", changes); nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC); if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) { mEventHub->requestReopenDevices(); } else { for (size_t i = 0; i < mDevices.size(); i++) { InputDevice* device = mDevices.valueAt(i); device->configure(now, &mConfig, changes); } } } } void InputReader::updateGlobalMetaStateLocked() { mGlobalMetaState = 0; for (size_t i = 0; i < mDevices.size(); i++) { InputDevice* device = mDevices.valueAt(i); mGlobalMetaState |= device->getMetaState(); } } int32_t InputReader::getGlobalMetaStateLocked() { return mGlobalMetaState; } void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) { mDisableVirtualKeysTimeout = time; } bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now, InputDevice* device, int32_t keyCode, int32_t scanCode) { if (now < mDisableVirtualKeysTimeout) { ALOGI("Dropping virtual key from device %s because virtual keys are " "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d", device->getName().string(), (mDisableVirtualKeysTimeout - now) * 0.000001, keyCode, scanCode); return true; } else { return false; } } void InputReader::fadePointerLocked() { for (size_t i = 0; i < mDevices.size(); i++) { InputDevice* device = mDevices.valueAt(i); device->fadePointer(); } } void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) { if (when < mNextTimeout) { mNextTimeout = when; mEventHub->wake(); } } int32_t InputReader::bumpGenerationLocked() { return ++mGeneration; } void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) { AutoMutex _l(mLock); getInputDevicesLocked(outInputDevices); } void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) { outInputDevices.clear(); size_t numDevices = mDevices.size(); for (size_t i = 0; i < numDevices; i++) { InputDevice* device = mDevices.valueAt(i); if (!device->isIgnored()) { outInputDevices.push(); device->getDeviceInfo(&outInputDevices.editTop()); } } } int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask, int32_t keyCode) { AutoMutex _l(mLock); return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState); } int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask, int32_t scanCode) { AutoMutex _l(mLock); return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState); } int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) { AutoMutex _l(mLock); return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState); } int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) { int32_t result = AKEY_STATE_UNKNOWN; if (deviceId >= 0) { ssize_t deviceIndex = mDevices.indexOfKey(deviceId); if (deviceIndex >= 0) { InputDevice* device = mDevices.valueAt(deviceIndex); if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) { result = (device->*getStateFunc)(sourceMask, code); } } } else { size_t numDevices = mDevices.size(); for (size_t i = 0; i < numDevices; i++) { InputDevice* device = mDevices.valueAt(i); if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) { // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that // value. Otherwise, return AKEY_STATE_UP as long as one device reports it. int32_t currentResult = (device->*getStateFunc)(sourceMask, code); if (currentResult >= AKEY_STATE_DOWN) { return currentResult; } else if (currentResult == AKEY_STATE_UP) { result = currentResult; } } } } return result; } bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask, size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) { AutoMutex _l(mLock); memset(outFlags, 0, numCodes); return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags); } bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask, size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) { bool result = false; if (deviceId >= 0) { ssize_t deviceIndex = mDevices.indexOfKey(deviceId); if (deviceIndex >= 0) { InputDevice* device = mDevices.valueAt(deviceIndex); if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) { result = device->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags); } } } else { size_t numDevices = mDevices.size(); for (size_t i = 0; i < numDevices; i++) { InputDevice* device = mDevices.valueAt(i); if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) { result |= device->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags); } } } return result; } void InputReader::requestRefreshConfiguration(uint32_t changes) { AutoMutex _l(mLock); if (changes) { bool needWake = !mConfigurationChangesToRefresh; mConfigurationChangesToRefresh |= changes; if (needWake) { mEventHub->wake(); } } } void InputReader::setTvOutStatus(bool enabled){ AutoMutex _l(mLock); ALOGI("InputReader::setTvOutStatus %d",enabled); size_t numDevices = mDevices.size(); for (size_t i = 0; i < numDevices; i++) { InputDevice* device = mDevices.valueAt(i); if (!device->isIgnored()) { device->setTvOutStatus(enabled); } } } void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize, ssize_t repeat, int32_t token) { AutoMutex _l(mLock); ssize_t deviceIndex = mDevices.indexOfKey(deviceId); if (deviceIndex >= 0) { InputDevice* device = mDevices.valueAt(deviceIndex); device->vibrate(pattern, patternSize, repeat, token); } } void InputReader::cancelVibrate(int32_t deviceId, int32_t token) { AutoMutex _l(mLock); ssize_t deviceIndex = mDevices.indexOfKey(deviceId); if (deviceIndex >= 0) { InputDevice* device = mDevices.valueAt(deviceIndex); device->cancelVibrate(token); } } void InputReader::dump(String8& dump) { AutoMutex _l(mLock); mEventHub->dump(dump); dump.append("\n"); dump.append("Input Reader State:\n"); for (size_t i = 0; i < mDevices.size(); i++) { mDevices.valueAt(i)->dump(dump); } dump.append(INDENT "Configuration:\n"); dump.append(INDENT2 "ExcludedDeviceNames: ["); for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) { if (i != 0) { dump.append(", "); } dump.append(mConfig.excludedDeviceNames.itemAt(i).string()); } dump.append("]\n"); dump.appendFormat(INDENT2 "VirtualKeyQuietTime: %0.1fms\n", mConfig.virtualKeyQuietTime * 0.000001f); dump.appendFormat(INDENT2 "PointerVelocityControlParameters: " "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n", mConfig.pointerVelocityControlParameters.scale, mConfig.pointerVelocityControlParameters.lowThreshold, mConfig.pointerVelocityControlParameters.highThreshold, mConfig.pointerVelocityControlParameters.acceleration); dump.appendFormat(INDENT2 "WheelVelocityControlParameters: " "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n", mConfig.wheelVelocityControlParameters.scale, mConfig.wheelVelocityControlParameters.lowThreshold, mConfig.wheelVelocityControlParameters.highThreshold, mConfig.wheelVelocityControlParameters.acceleration); dump.appendFormat(INDENT2 "PointerGesture:\n"); dump.appendFormat(INDENT3 "Enabled: %s\n", toString(mConfig.pointerGesturesEnabled)); dump.appendFormat(INDENT3 "QuietInterval: %0.1fms\n", mConfig.pointerGestureQuietInterval * 0.000001f); dump.appendFormat(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n", mConfig.pointerGestureDragMinSwitchSpeed); dump.appendFormat(INDENT3 "TapInterval: %0.1fms\n", mConfig.pointerGestureTapInterval * 0.000001f); dump.appendFormat(INDENT3 "TapDragInterval: %0.1fms\n", mConfig.pointerGestureTapDragInterval * 0.000001f); dump.appendFormat(INDENT3 "TapSlop: %0.1fpx\n", mConfig.pointerGestureTapSlop); dump.appendFormat(INDENT3 "MultitouchSettleInterval: %0.1fms\n", mConfig.pointerGestureMultitouchSettleInterval * 0.000001f); dump.appendFormat(INDENT3 "MultitouchMinDistance: %0.1fpx\n", mConfig.pointerGestureMultitouchMinDistance); dump.appendFormat(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n", mConfig.pointerGestureSwipeTransitionAngleCosine); dump.appendFormat(INDENT3 "SwipeMaxWidthRatio: %0.1f\n", mConfig.pointerGestureSwipeMaxWidthRatio); dump.appendFormat(INDENT3 "MovementSpeedRatio: %0.1f\n", mConfig.pointerGestureMovementSpeedRatio); dump.appendFormat(INDENT3 "ZoomSpeedRatio: %0.1f\n", mConfig.pointerGestureZoomSpeedRatio); } void InputReader::monitor() { // Acquire and release the lock to ensure that the reader has not deadlocked. mLock.lock(); mEventHub->wake(); mReaderIsAliveCondition.wait(mLock); mLock.unlock(); // Check the EventHub mEventHub->monitor(); } // --- InputReader::ContextImpl --- InputReader::ContextImpl::ContextImpl(InputReader* reader) : mReader(reader) { } void InputReader::ContextImpl::updateGlobalMetaState() { // lock is already held by the input loop mReader->updateGlobalMetaStateLocked(); } int32_t InputReader::ContextImpl::getGlobalMetaState() { // lock is already held by the input loop return mReader->getGlobalMetaStateLocked(); } void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) { // lock is already held by the input loop mReader->disableVirtualKeysUntilLocked(time); } bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now, InputDevice* device, int32_t keyCode, int32_t scanCode) { // lock is already held by the input loop return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode); } void InputReader::ContextImpl::fadePointer() { // lock is already held by the input loop mReader->fadePointerLocked(); } void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) { // lock is already held by the input loop mReader->requestTimeoutAtTimeLocked(when); } int32_t InputReader::ContextImpl::bumpGeneration() { // lock is already held by the input loop return mReader->bumpGenerationLocked(); } InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() { return mReader->mPolicy.get(); } InputListenerInterface* InputReader::ContextImpl::getListener() { return mReader->mQueuedListener.get(); } EventHubInterface* InputReader::ContextImpl::getEventHub() { return mReader->mEventHub.get(); } // --- InputReaderThread --- InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) : Thread(/*canCallJava*/ true), mReader(reader) { } InputReaderThread::~InputReaderThread() { } bool InputReaderThread::threadLoop() { mReader->loopOnce(); return true; } // --- InputDevice --- InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation, int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) : mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber), mIdentifier(identifier), mClasses(classes), mSources(0), mIsExternal(false), mDropUntilNextSync(false) { } InputDevice::~InputDevice() { size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { delete mMappers[i]; } mMappers.clear(); } void InputDevice::dump(String8& dump) { InputDeviceInfo deviceInfo; getDeviceInfo(& deviceInfo); dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(), deviceInfo.getDisplayName().string()); dump.appendFormat(INDENT2 "Generation: %d\n", mGeneration); dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal)); dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources()); dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType()); const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges(); if (!ranges.isEmpty()) { dump.append(INDENT2 "Motion Ranges:\n"); for (size_t i = 0; i < ranges.size(); i++) { const InputDeviceInfo::MotionRange& range = ranges.itemAt(i); const char* label = getAxisLabel(range.axis); char name[32]; if (label) { strncpy(name, label, sizeof(name)); name[sizeof(name) - 1] = '\0'; } else { snprintf(name, sizeof(name), "%d", range.axis); } dump.appendFormat(INDENT3 "%s: source=0x%08x, " "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n", name, range.source, range.min, range.max, range.flat, range.fuzz, range.resolution); } } size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; mapper->dump(dump); } } void InputDevice::addMapper(InputMapper* mapper) { mMappers.add(mapper); } void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) { mSources = 0; if (!isIgnored()) { if (!changes) { // first time only mContext->getEventHub()->getConfiguration(mId, &mConfiguration); } if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) { if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) { sp<KeyCharacterMap> keyboardLayout = mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier.descriptor); if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) { bumpGeneration(); } } } if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) { if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) { String8 alias = mContext->getPolicy()->getDeviceAlias(mIdentifier); if (mAlias != alias) { mAlias = alias; bumpGeneration(); } } } size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; mapper->configure(when, config, changes); mSources |= mapper->getSources(); } } } void InputDevice::reset(nsecs_t when) { size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; mapper->reset(when); } mContext->updateGlobalMetaState(); notifyReset(when); } void InputDevice::process(const RawEvent* rawEvents, size_t count) { // Process all of the events in order for each mapper. // We cannot simply ask each mapper to process them in bulk because mappers may // have side-effects that must be interleaved. For example, joystick movement events and // gamepad button presses are handled by different mappers but they should be dispatched // in the order received. size_t numMappers = mMappers.size(); for (const RawEvent* rawEvent = rawEvents; count--; rawEvent++) { #if DEBUG_RAW_EVENTS ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%lld", rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value, rawEvent->when); #endif if (mDropUntilNextSync) { if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) { mDropUntilNextSync = false; #if DEBUG_RAW_EVENTS ALOGD("Recovered from input event buffer overrun."); #endif } else { #if DEBUG_RAW_EVENTS ALOGD("Dropped input event while waiting for next input sync."); #endif } } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) { ALOGI("Detected input event buffer overrun for device %s.", getName().string()); mDropUntilNextSync = true; reset(rawEvent->when); } else { for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; mapper->process(rawEvent); } } } } void InputDevice::timeoutExpired(nsecs_t when) { size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; mapper->timeoutExpired(when); } } void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) { outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias, mIsExternal); size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; mapper->populateDeviceInfo(outDeviceInfo); } } int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) { return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState); } int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { return getState(sourceMask, scanCode, & InputMapper::getScanCodeState); } int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) { return getState(sourceMask, switchCode, & InputMapper::getSwitchState); } int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) { int32_t result = AKEY_STATE_UNKNOWN; size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; if (sourcesMatchMask(mapper->getSources(), sourceMask)) { // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it. int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code); if (currentResult >= AKEY_STATE_DOWN) { return currentResult; } else if (currentResult == AKEY_STATE_UP) { result = currentResult; } } } return result; } bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) { bool result = false; size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; if (sourcesMatchMask(mapper->getSources(), sourceMask)) { result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags); } } return result; } void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat, int32_t token) { size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; mapper->vibrate(pattern, patternSize, repeat, token); } } void InputDevice::cancelVibrate(int32_t token) { size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; mapper->cancelVibrate(token); } } int32_t InputDevice::getMetaState() { int32_t result = 0; size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; result |= mapper->getMetaState(); } return result; } void InputDevice::fadePointer() { size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; mapper->fadePointer(); } } void InputDevice::bumpGeneration() { mGeneration = mContext->bumpGeneration(); } void InputDevice::notifyReset(nsecs_t when) { NotifyDeviceResetArgs args(when, mId); mContext->getListener()->notifyDeviceReset(&args); } void InputDevice::setTvOutStatus(bool enabled){ size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; mapper->setTvOutStatus(enabled); } } // --- CursorButtonAccumulator --- CursorButtonAccumulator::CursorButtonAccumulator() { clearButtons(); } void CursorButtonAccumulator::reset(InputDevice* device) { mBtnLeft = device->isKeyPressed(BTN_LEFT); mBtnRight = device->isKeyPressed(BTN_RIGHT); mBtnMiddle = device->isKeyPressed(BTN_MIDDLE); mBtnBack = device->isKeyPressed(BTN_BACK); mBtnSide = device->isKeyPressed(BTN_SIDE); mBtnForward = device->isKeyPressed(BTN_FORWARD); mBtnExtra = device->isKeyPressed(BTN_EXTRA); mBtnTask = device->isKeyPressed(BTN_TASK); } void CursorButtonAccumulator::clearButtons() { mBtnLeft = 0; mBtnRight = 0; mBtnMiddle = 0; mBtnBack = 0; mBtnSide = 0; mBtnForward = 0; mBtnExtra = 0; mBtnTask = 0; } void CursorButtonAccumulator::process(const RawEvent* rawEvent) { if (rawEvent->type == EV_KEY) { switch (rawEvent->code) { case BTN_LEFT: mBtnLeft = rawEvent->value; break; case BTN_RIGHT: mBtnRight = rawEvent->value; break; case BTN_MIDDLE: mBtnMiddle = rawEvent->value; break; case BTN_BACK: mBtnBack = rawEvent->value; break; case BTN_SIDE: mBtnSide = rawEvent->value; break; case BTN_FORWARD: mBtnForward = rawEvent->value; break; case BTN_EXTRA: mBtnExtra = rawEvent->value; break; case BTN_TASK: mBtnTask = rawEvent->value; break; } } } uint32_t CursorButtonAccumulator::getButtonState() const { uint32_t result = 0; if (mBtnLeft) { result |= AMOTION_EVENT_BUTTON_PRIMARY; } if (mBtnRight) { //result |= AMOTION_EVENT_BUTTON_SECONDARY; result |= AMOTION_EVENT_BUTTON_BACK; } if (mBtnMiddle) { result |= AMOTION_EVENT_BUTTON_TERTIARY; } if (mBtnBack || mBtnSide) { result |= AMOTION_EVENT_BUTTON_BACK; } if (mBtnForward || mBtnExtra) { result |= AMOTION_EVENT_BUTTON_FORWARD; } return result; } // --- CursorMotionAccumulator --- CursorMotionAccumulator::CursorMotionAccumulator() { clearRelativeAxes(); } void CursorMotionAccumulator::reset(InputDevice* device) { clearRelativeAxes(); } void CursorMotionAccumulator::clearRelativeAxes() { mRelX = 0; mRelY = 0; } void CursorMotionAccumulator::process(const RawEvent* rawEvent) { if (rawEvent->type == EV_REL) { switch (rawEvent->code) { case REL_X: mRelX = rawEvent->value; break; case REL_Y: mRelY = rawEvent->value; break; } } } void CursorMotionAccumulator::finishSync() { clearRelativeAxes(); } // --- CursorScrollAccumulator --- CursorScrollAccumulator::CursorScrollAccumulator() : mHaveRelWheel(false), mHaveRelHWheel(false) { clearRelativeAxes(); } void CursorScrollAccumulator::configure(InputDevice* device) { mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL); mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL); } void CursorScrollAccumulator::reset(InputDevice* device) { clearRelativeAxes(); } void CursorScrollAccumulator::clearRelativeAxes() { mRelWheel = 0; mRelHWheel = 0; } void CursorScrollAccumulator::process(const RawEvent* rawEvent) { if (rawEvent->type == EV_REL) { switch (rawEvent->code) { case REL_WHEEL: mRelWheel = rawEvent->value; break; case REL_HWHEEL: mRelHWheel = rawEvent->value; break; } } } void CursorScrollAccumulator::finishSync() { clearRelativeAxes(); } // --- TouchButtonAccumulator --- TouchButtonAccumulator::TouchButtonAccumulator() : mHaveBtnTouch(false), mHaveStylus(false) { clearButtons(); } void TouchButtonAccumulator::configure(InputDevice* device) { mHaveBtnTouch = device->hasKey(BTN_TOUCH); mHaveStylus = device->hasKey(BTN_TOOL_PEN) || device->hasKey(BTN_TOOL_RUBBER) || device->hasKey(BTN_TOOL_BRUSH) || device->hasKey(BTN_TOOL_PENCIL) || device->hasKey(BTN_TOOL_AIRBRUSH); } void TouchButtonAccumulator::reset(InputDevice* device) { mBtnTouch = device->isKeyPressed(BTN_TOUCH); mBtnStylus = device->isKeyPressed(BTN_STYLUS); mBtnStylus2 = device->isKeyPressed(BTN_STYLUS); mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER); mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN); mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER); mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH); mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL); mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH); mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE); mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS); mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP); mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP); mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP); } void TouchButtonAccumulator::clearButtons() { mBtnTouch = 0; mBtnStylus = 0; mBtnStylus2 = 0; mBtnToolFinger = 0; mBtnToolPen = 0; mBtnToolRubber = 0; mBtnToolBrush = 0; mBtnToolPencil = 0; mBtnToolAirbrush = 0; mBtnToolMouse = 0; mBtnToolLens = 0; mBtnToolDoubleTap = 0; mBtnToolTripleTap = 0; mBtnToolQuadTap = 0; } void TouchButtonAccumulator::process(const RawEvent* rawEvent) { if (rawEvent->type == EV_KEY) { switch (rawEvent->code) { case BTN_TOUCH: mBtnTouch = rawEvent->value; break; case BTN_STYLUS: mBtnStylus = rawEvent->value; break; case BTN_STYLUS2: mBtnStylus2 = rawEvent->value; break; case BTN_TOOL_FINGER: mBtnToolFinger = rawEvent->value; break; case BTN_TOOL_PEN: mBtnToolPen = rawEvent->value; break; case BTN_TOOL_RUBBER: mBtnToolRubber = rawEvent->value; break; case BTN_TOOL_BRUSH: mBtnToolBrush = rawEvent->value; break; case BTN_TOOL_PENCIL: mBtnToolPencil = rawEvent->value; break; case BTN_TOOL_AIRBRUSH: mBtnToolAirbrush = rawEvent->value; break; case BTN_TOOL_MOUSE: mBtnToolMouse = rawEvent->value; break; case BTN_TOOL_LENS: mBtnToolLens = rawEvent->value; break; case BTN_TOOL_DOUBLETAP: mBtnToolDoubleTap = rawEvent->value; break; case BTN_TOOL_TRIPLETAP: mBtnToolTripleTap = rawEvent->value; break; case BTN_TOOL_QUADTAP: mBtnToolQuadTap = rawEvent->value; break; } } } uint32_t TouchButtonAccumulator::getButtonState() const { uint32_t result = 0; if (mBtnStylus) { result |= AMOTION_EVENT_BUTTON_SECONDARY; } if (mBtnStylus2) { result |= AMOTION_EVENT_BUTTON_TERTIARY; } return result; } int32_t TouchButtonAccumulator::getToolType() const { if (mBtnToolMouse || mBtnToolLens) { return AMOTION_EVENT_TOOL_TYPE_MOUSE; } if (mBtnToolRubber) { return AMOTION_EVENT_TOOL_TYPE_ERASER; } if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) { return AMOTION_EVENT_TOOL_TYPE_STYLUS; } if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) { return AMOTION_EVENT_TOOL_TYPE_FINGER; } return AMOTION_EVENT_TOOL_TYPE_UNKNOWN; } bool TouchButtonAccumulator::isToolActive() const { return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush || mBtnToolMouse || mBtnToolLens || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap; } bool TouchButtonAccumulator::isHovering() const { return mHaveBtnTouch && !mBtnTouch; } bool TouchButtonAccumulator::hasStylus() const { return mHaveStylus; } // --- RawPointerAxes --- RawPointerAxes::RawPointerAxes() { clear(); } void RawPointerAxes::clear() { x.clear(); y.clear(); pressure.clear(); touchMajor.clear(); touchMinor.clear(); toolMajor.clear(); toolMinor.clear(); orientation.clear(); distance.clear(); tiltX.clear(); tiltY.clear(); trackingId.clear(); slot.clear(); } // --- RawPointerData --- RawPointerData::RawPointerData() { clear(); } void RawPointerData::clear() { pointerCount = 0; clearIdBits(); } void RawPointerData::copyFrom(const RawPointerData& other) { pointerCount = other.pointerCount; hoveringIdBits = other.hoveringIdBits; touchingIdBits = other.touchingIdBits; for (uint32_t i = 0; i < pointerCount; i++) { pointers[i] = other.pointers[i]; int id = pointers[i].id; idToIndex[id] = other.idToIndex[id]; } } void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const { float x = 0, y = 0; uint32_t count = touchingIdBits.count(); if (count) { for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) { uint32_t id = idBits.clearFirstMarkedBit(); const Pointer& pointer = pointerForId(id); x += pointer.x; y += pointer.y; } x /= count; y /= count; } *outX = x; *outY = y; } // --- CookedPointerData --- CookedPointerData::CookedPointerData() { clear(); } void CookedPointerData::clear() { pointerCount = 0; hoveringIdBits.clear(); touchingIdBits.clear(); } void CookedPointerData::copyFrom(const CookedPointerData& other) { pointerCount = other.pointerCount; hoveringIdBits = other.hoveringIdBits; touchingIdBits = other.touchingIdBits; for (uint32_t i = 0; i < pointerCount; i++) { pointerProperties[i].copyFrom(other.pointerProperties[i]); pointerCoords[i].copyFrom(other.pointerCoords[i]); int id = pointerProperties[i].id; idToIndex[id] = other.idToIndex[id]; } } // --- SingleTouchMotionAccumulator --- SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() { clearAbsoluteAxes(); } void SingleTouchMotionAccumulator::reset(InputDevice* device) { mAbsX = device->getAbsoluteAxisValue(ABS_X); mAbsY = device->getAbsoluteAxisValue(ABS_Y); mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE); mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH); mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE); mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X); mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y); } void SingleTouchMotionAccumulator::clearAbsoluteAxes() { mAbsX = 0; mAbsY = 0; mAbsPressure = 0; mAbsToolWidth = 0; mAbsDistance = 0; mAbsTiltX = 0; mAbsTiltY = 0; } void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) { if (rawEvent->type == EV_ABS) { switch (rawEvent->code) { case ABS_X: mAbsX = rawEvent->value; break; case ABS_Y: mAbsY = rawEvent->value; break; case ABS_PRESSURE: mAbsPressure = rawEvent->value; break; case ABS_TOOL_WIDTH: mAbsToolWidth = rawEvent->value; break; case ABS_DISTANCE: mAbsDistance = rawEvent->value; break; case ABS_TILT_X: mAbsTiltX = rawEvent->value; break; case ABS_TILT_Y: mAbsTiltY = rawEvent->value; break; } } } // --- MultiTouchMotionAccumulator --- MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() : mCurrentSlot(-1), mSlots(NULL), mSlotCount(0), mUsingSlotsProtocol(false), mHaveStylus(false) { } MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() { delete[] mSlots; } void MultiTouchMotionAccumulator::configure(InputDevice* device, size_t slotCount, bool usingSlotsProtocol) { mSlotCount = slotCount; mUsingSlotsProtocol = usingSlotsProtocol; mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE); delete[] mSlots; mSlots = new Slot[slotCount]; } void MultiTouchMotionAccumulator::reset(InputDevice* device) { // Unfortunately there is no way to read the initial contents of the slots. // So when we reset the accumulator, we must assume they are all zeroes. if (mUsingSlotsProtocol) { // Query the driver for the current slot index and use it as the initial slot // before we start reading events from the device. It is possible that the // current slot index will not be the same as it was when the first event was // written into the evdev buffer, which means the input mapper could start // out of sync with the initial state of the events in the evdev buffer. // In the extremely unlikely case that this happens, the data from // two slots will be confused until the next ABS_MT_SLOT event is received. // This can cause the touch point to "jump", but at least there will be // no stuck touches. int32_t initialSlot; status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(), ABS_MT_SLOT, &initialSlot); if (status) { ALOGD("Could not retrieve current multitouch slot index. status=%d", status); initialSlot = -1; } clearSlots(initialSlot); } else { clearSlots(-1); } } void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) { if (mSlots) { for (size_t i = 0; i < mSlotCount; i++) { mSlots[i].clear(); } } mCurrentSlot = initialSlot; } void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) { if (rawEvent->type == EV_ABS) { bool newSlot = false; if (mUsingSlotsProtocol) { if (rawEvent->code == ABS_MT_SLOT) { mCurrentSlot = rawEvent->value; newSlot = true; } } else if (mCurrentSlot < 0) { mCurrentSlot = 0; } if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) { #if DEBUG_POINTERS if (newSlot) { ALOGW("MultiTouch device emitted invalid slot index %d but it " "should be between 0 and %d; ignoring this slot.", mCurrentSlot, mSlotCount - 1); } #endif } else { Slot* slot = &mSlots[mCurrentSlot]; switch (rawEvent->code) { case ABS_MT_POSITION_X: slot->mInUse = true; slot->mAbsMTPositionX = rawEvent->value; break; case ABS_MT_POSITION_Y: slot->mInUse = true; slot->mAbsMTPositionY = rawEvent->value; break; case ABS_MT_TOUCH_MAJOR: slot->mInUse = true; slot->mAbsMTTouchMajor = rawEvent->value; break; case ABS_MT_TOUCH_MINOR: slot->mInUse = true; slot->mAbsMTTouchMinor = rawEvent->value; slot->mHaveAbsMTTouchMinor = true; break; case ABS_MT_WIDTH_MAJOR: slot->mInUse = true; slot->mAbsMTWidthMajor = rawEvent->value; break; case ABS_MT_WIDTH_MINOR: slot->mInUse = true; slot->mAbsMTWidthMinor = rawEvent->value; slot->mHaveAbsMTWidthMinor = true; break; case ABS_MT_ORIENTATION: slot->mInUse = true; slot->mAbsMTOrientation = rawEvent->value; break; case ABS_MT_TRACKING_ID: if (mUsingSlotsProtocol && rawEvent->value < 0) { // The slot is no longer in use but it retains its previous contents, // which may be reused for subsequent touches. slot->mInUse = false; } else { slot->mInUse = true; slot->mAbsMTTrackingId = rawEvent->value; } break; case ABS_MT_PRESSURE: slot->mInUse = true; slot->mAbsMTPressure = rawEvent->value; break; case ABS_MT_DISTANCE: slot->mInUse = true; slot->mAbsMTDistance = rawEvent->value; break; case ABS_MT_TOOL_TYPE: slot->mInUse = true; slot->mAbsMTToolType = rawEvent->value; slot->mHaveAbsMTToolType = true; break; } } } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) { // MultiTouch Sync: The driver has returned all data for *one* of the pointers. mCurrentSlot += 1; } } void MultiTouchMotionAccumulator::finishSync() { if (!mUsingSlotsProtocol) { clearSlots(-1); } } bool MultiTouchMotionAccumulator::hasStylus() const { return mHaveStylus; } // --- MultiTouchMotionAccumulator::Slot --- MultiTouchMotionAccumulator::Slot::Slot() { clear(); } void MultiTouchMotionAccumulator::Slot::clear() { mInUse = false; mHaveAbsMTTouchMinor = false; mHaveAbsMTWidthMinor = false; mHaveAbsMTToolType = false; mAbsMTPositionX = 0; mAbsMTPositionY = 0; mAbsMTTouchMajor = 0; mAbsMTTouchMinor = 0; mAbsMTWidthMajor = 0; mAbsMTWidthMinor = 0; mAbsMTOrientation = 0; mAbsMTTrackingId = -1; mAbsMTPressure = 0; mAbsMTDistance = 0; mAbsMTToolType = 0; } int32_t MultiTouchMotionAccumulator::Slot::getToolType() const { if (mHaveAbsMTToolType) { switch (mAbsMTToolType) { case MT_TOOL_FINGER: return AMOTION_EVENT_TOOL_TYPE_FINGER; case MT_TOOL_PEN: return AMOTION_EVENT_TOOL_TYPE_STYLUS; } } return AMOTION_EVENT_TOOL_TYPE_UNKNOWN; } // --- InputMapper --- InputMapper::InputMapper(InputDevice* device) : mDevice(device), mContext(device->getContext()) { } InputMapper::~InputMapper() { } void InputMapper::populateDeviceInfo(InputDeviceInfo* info) { info->addSource(getSources()); } void InputMapper::dump(String8& dump) { } void InputMapper::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) { } void InputMapper::reset(nsecs_t when) { } void InputMapper::timeoutExpired(nsecs_t when) { } int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) { return AKEY_STATE_UNKNOWN; } int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { return AKEY_STATE_UNKNOWN; } int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) { return AKEY_STATE_UNKNOWN; } bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) { return false; } void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat, int32_t token) { } void InputMapper::cancelVibrate(int32_t token) { } int32_t InputMapper::getMetaState() { return 0; } void InputMapper::fadePointer() { } void InputMapper::setTvOutStatus(bool enabled){ } status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) { return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo); } void InputMapper::bumpGeneration() { mDevice->bumpGeneration(); } void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump, const RawAbsoluteAxisInfo& axis, const char* name) { if (axis.valid) { dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n", name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution); } else { dump.appendFormat(INDENT4 "%s: unknown range\n", name); } } // --- SwitchInputMapper --- SwitchInputMapper::SwitchInputMapper(InputDevice* device) : InputMapper(device), mUpdatedSwitchValues(0), mUpdatedSwitchMask(0) { } SwitchInputMapper::~SwitchInputMapper() { } uint32_t SwitchInputMapper::getSources() { return AINPUT_SOURCE_SWITCH; } void SwitchInputMapper::process(const RawEvent* rawEvent) { switch (rawEvent->type) { case EV_SW: processSwitch(rawEvent->code, rawEvent->value); break; case EV_SYN: if (rawEvent->code == SYN_REPORT) { sync(rawEvent->when); } } } void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) { if (switchCode >= 0 && switchCode < 32) { if (switchValue) { mUpdatedSwitchValues |= 1 << switchCode; } mUpdatedSwitchMask |= 1 << switchCode; } } void SwitchInputMapper::sync(nsecs_t when) { if (mUpdatedSwitchMask) { NotifySwitchArgs args(when, 0, mUpdatedSwitchValues, mUpdatedSwitchMask); getListener()->notifySwitch(&args); mUpdatedSwitchValues = 0; mUpdatedSwitchMask = 0; } } int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) { return getEventHub()->getSwitchState(getDeviceId(), switchCode); } // --- VibratorInputMapper --- VibratorInputMapper::VibratorInputMapper(InputDevice* device) : InputMapper(device), mVibrating(false) { } VibratorInputMapper::~VibratorInputMapper() { } uint32_t VibratorInputMapper::getSources() { return 0; } void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) { InputMapper::populateDeviceInfo(info); info->setVibrator(true); } void VibratorInputMapper::process(const RawEvent* rawEvent) { // TODO: Handle FF_STATUS, although it does not seem to be widely supported. } void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat, int32_t token) { #if DEBUG_VIBRATOR String8 patternStr; for (size_t i = 0; i < patternSize; i++) { if (i != 0) { patternStr.append(", "); } patternStr.appendFormat("%lld", pattern[i]); } ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%ld, token=%d", getDeviceId(), patternStr.string(), repeat, token); #endif mVibrating = true; memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t)); mPatternSize = patternSize; mRepeat = repeat; mToken = token; mIndex = -1; nextStep(); } void VibratorInputMapper::cancelVibrate(int32_t token) { #if DEBUG_VIBRATOR ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token); #endif if (mVibrating && mToken == token) { stopVibrating(); } } void VibratorInputMapper::timeoutExpired(nsecs_t when) { if (mVibrating) { if (when >= mNextStepTime) { nextStep(); } else { getContext()->requestTimeoutAtTime(mNextStepTime); } } } void VibratorInputMapper::nextStep() { mIndex += 1; if (size_t(mIndex) >= mPatternSize) { if (mRepeat < 0) { // We are done. stopVibrating(); return; } mIndex = mRepeat; } bool vibratorOn = mIndex & 1; nsecs_t duration = mPattern[mIndex]; if (vibratorOn) { #if DEBUG_VIBRATOR ALOGD("nextStep: sending vibrate deviceId=%d, duration=%lld", getDeviceId(), duration); #endif getEventHub()->vibrate(getDeviceId(), duration); } else { #if DEBUG_VIBRATOR ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId()); #endif getEventHub()->cancelVibrate(getDeviceId()); } nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC); mNextStepTime = now + duration; getContext()->requestTimeoutAtTime(mNextStepTime); #if DEBUG_VIBRATOR ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f); #endif } void VibratorInputMapper::stopVibrating() { mVibrating = false; #if DEBUG_VIBRATOR ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId()); #endif getEventHub()->cancelVibrate(getDeviceId()); } void VibratorInputMapper::dump(String8& dump) { dump.append(INDENT2 "Vibrator Input Mapper:\n"); dump.appendFormat(INDENT3 "Vibrating: %s\n", toString(mVibrating)); } // --- KeyboardInputMapper --- KeyboardInputMapper::KeyboardInputMapper(InputDevice* device, uint32_t source, int32_t keyboardType) : InputMapper(device), mSource(source), mKeyboardType(keyboardType) { } KeyboardInputMapper::~KeyboardInputMapper() { } uint32_t KeyboardInputMapper::getSources() { return mSource; } void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) { InputMapper::populateDeviceInfo(info); info->setKeyboardType(mKeyboardType); info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId())); } void KeyboardInputMapper::dump(String8& dump) { dump.append(INDENT2 "Keyboard Input Mapper:\n"); dumpParameters(dump); dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType); dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation); dump.appendFormat(INDENT3 "KeyDowns: %d keys currently down\n", mKeyDowns.size()); dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mMetaState); dump.appendFormat(INDENT3 "DownTime: %lld\n", mDownTime); } void KeyboardInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) { InputMapper::configure(when, config, changes); if (!changes) { // first time only // Configure basic parameters. configureParameters(); } if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) { DisplayViewport v; if (config->getDisplayInfo(false /*external*/, &v)) { mOrientation = v.orientation; } else { mOrientation = DISPLAY_ORIENTATION_0; } } else { mOrientation = DISPLAY_ORIENTATION_0; } } } void KeyboardInputMapper::configureParameters() { mParameters.orientationAware = false; getDevice()->getConfiguration().tryGetProperty(String8("keyboard.orientationAware"), mParameters.orientationAware); mParameters.hasAssociatedDisplay = false; if (mParameters.orientationAware) { mParameters.hasAssociatedDisplay = true; } } void KeyboardInputMapper::dumpParameters(String8& dump) { dump.append(INDENT3 "Parameters:\n"); dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n", toString(mParameters.hasAssociatedDisplay)); dump.appendFormat(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware)); } void KeyboardInputMapper::reset(nsecs_t when) { mMetaState = AMETA_NONE; mDownTime = 0; mKeyDowns.clear(); mCurrentHidUsage = 0; resetLedState(); InputMapper::reset(when); } void KeyboardInputMapper::process(const RawEvent* rawEvent) { switch (rawEvent->type) { case EV_KEY: { int32_t scanCode = rawEvent->code; int32_t usageCode = mCurrentHidUsage; char value[PROPERTY_VALUE_MAX] = {0}; mCurrentHidUsage = 0; if (isKeyboardOrGamepadKey(scanCode)) { int32_t keyCode; uint32_t flags; if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, &keyCode, &flags)) { keyCode = AKEYCODE_UNKNOWN; flags = 0; } //for unicom,convert ENTER to DPAD_CENTER,since the ENTER will not be processed // in some apks. //property_get("sys.proj.type", value, "ott"); //if (!strncmp(value,"unicom",6)) if (keyCode == AKEYCODE_ENTER) { //add by ysten liuxl,fix can not write sn bug 20180922 property_get("sys.dragon.enter.start", value, "false"); if (strncmp(value,"true",4)) { keyCode = AKEYCODE_DPAD_CENTER; ALOGD("convert ENTER to DPAD_CENTER"); } } processKey(rawEvent->when, rawEvent->value != 0, keyCode, scanCode, flags); } break; } case EV_MSC: { if (rawEvent->code == MSC_SCAN) { mCurrentHidUsage = rawEvent->value; } break; } case EV_SYN: { if (rawEvent->code == SYN_REPORT) { mCurrentHidUsage = 0; } } } } bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) { return scanCode < BTN_MOUSE || scanCode >= KEY_OK || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE) || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI); } void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t keyCode, int32_t scanCode, uint32_t policyFlags) { if (down) { // Rotate key codes according to orientation if needed. if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) { keyCode = rotateKeyCode(keyCode, mOrientation); } // Add key down. ssize_t keyDownIndex = findKeyDown(scanCode); if (keyDownIndex >= 0) { // key repeat, be sure to use same keycode as before in case of rotation keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode; } else { // key down if ((policyFlags & POLICY_FLAG_VIRTUAL) && mContext->shouldDropVirtualKey(when, getDevice(), keyCode, scanCode)) { return; } mKeyDowns.push(); KeyDown& keyDown = mKeyDowns.editTop(); keyDown.keyCode = keyCode; keyDown.scanCode = scanCode; } mDownTime = when; } else { // Remove key down. ssize_t keyDownIndex = findKeyDown(scanCode); if (keyDownIndex >= 0) { // key up, be sure to use same keycode as before in case of rotation keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode; mKeyDowns.removeAt(size_t(keyDownIndex)); } else { // key was not actually down ALOGI("Dropping key up from device %s because the key was not down. " "keyCode=%d, scanCode=%d", getDeviceName().string(), keyCode, scanCode); return; } } int32_t oldMetaState = mMetaState; int32_t newMetaState = updateMetaState(keyCode, down, oldMetaState); bool metaStateChanged = oldMetaState != newMetaState; if (metaStateChanged) { mMetaState = newMetaState; updateLedState(false); } nsecs_t downTime = mDownTime; // Key down on external an keyboard should wake the device. // We don't do this for internal keyboards to prevent them from waking up in your pocket. // For internal keyboards, the key layout file should specify the policy flags for // each wake key individually. // TODO: Use the input device configuration to control this behavior more finely. char value[PROPERTY_VALUE_MAX]; property_get("ro.platform.has.mbxuimode", value, "false"); if(strcmp(value, "true") != 0) { if (down && getDevice()->isExternal() && !(policyFlags & (POLICY_FLAG_WAKE | POLICY_FLAG_WAKE_DROPPED))) { policyFlags |= POLICY_FLAG_WAKE_DROPPED; } } if (metaStateChanged) { getContext()->updateGlobalMetaState(); } if (down && !isMetaKey(keyCode)) { getContext()->fadePointer(); } NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP, AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, newMetaState, downTime); getListener()->notifyKey(&args); } ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) { size_t n = mKeyDowns.size(); for (size_t i = 0; i < n; i++) { if (mKeyDowns[i].scanCode == scanCode) { return i; } } return -1; } int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) { return getEventHub()->getKeyCodeState(getDeviceId(), keyCode); } int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { return getEventHub()->getScanCodeState(getDeviceId(), scanCode); } bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) { return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags); } int32_t KeyboardInputMapper::getMetaState() { return mMetaState; } void KeyboardInputMapper::resetLedState() { initializeLedState(mCapsLockLedState, LED_CAPSL); initializeLedState(mNumLockLedState, LED_NUML); initializeLedState(mScrollLockLedState, LED_SCROLLL); updateLedState(true); } void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) { ledState.avail = getEventHub()->hasLed(getDeviceId(), led); ledState.on = false; } void KeyboardInputMapper::updateLedState(bool reset) { updateLedStateForModifier(mCapsLockLedState, LED_CAPSL, AMETA_CAPS_LOCK_ON, reset); updateLedStateForModifier(mNumLockLedState, LED_NUML, AMETA_NUM_LOCK_ON, reset); updateLedStateForModifier(mScrollLockLedState, LED_SCROLLL, AMETA_SCROLL_LOCK_ON, reset); } void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState, int32_t led, int32_t modifier, bool reset) { if (ledState.avail) { bool desiredState = (mMetaState & modifier) != 0; if (reset || ledState.on != desiredState) { getEventHub()->setLedState(getDeviceId(), led, desiredState); ledState.on = desiredState; } } } // --- CursorInputMapper --- CursorInputMapper::CursorInputMapper(InputDevice* device) : InputMapper(device) { } CursorInputMapper::~CursorInputMapper() { } uint32_t CursorInputMapper::getSources() { return mSource; } void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) { InputMapper::populateDeviceInfo(info); if (mParameters.mode == Parameters::MODE_POINTER) { float minX, minY, maxX, maxY; if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) { info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f); info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f); } } else { info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f); info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f); } info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f); if (mCursorScrollAccumulator.haveRelativeVWheel()) { info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f); } if (mCursorScrollAccumulator.haveRelativeHWheel()) { info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f); } } void CursorInputMapper::dump(String8& dump) { dump.append(INDENT2 "Cursor Input Mapper:\n"); dumpParameters(dump); dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale); dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale); dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision); dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision); dump.appendFormat(INDENT3 "HaveVWheel: %s\n", toString(mCursorScrollAccumulator.haveRelativeVWheel())); dump.appendFormat(INDENT3 "HaveHWheel: %s\n", toString(mCursorScrollAccumulator.haveRelativeHWheel())); dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale); dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale); dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation); dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mButtonState); dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState))); dump.appendFormat(INDENT3 "DownTime: %lld\n", mDownTime); } void CursorInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) { InputMapper::configure(when, config, changes); if (!changes) { // first time only mEnabled = config->cursorEnabled; mCursorScrollAccumulator.configure(getDevice()); // Configure basic parameters. configureParameters(); // Configure device mode. switch (mParameters.mode) { case Parameters::MODE_POINTER: mSource = AINPUT_SOURCE_MOUSE; mXPrecision = 1.0f; mYPrecision = 1.0f; mXScale = 1.0f; mYScale = 1.0f; mPointerController = getPolicy()->obtainPointerController(getDeviceId()); break; case Parameters::MODE_NAVIGATION: mSource = AINPUT_SOURCE_TRACKBALL; mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD; mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD; mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD; mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD; break; } mVWheelScale = 1.0f; mHWheelScale = 1.0f; } if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) { mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters); mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters); mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters); } if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) { DisplayViewport v; if (config->getDisplayInfo(false /*external*/, &v)) { mOrientation = v.orientation; } else { mOrientation = DISPLAY_ORIENTATION_0; } } else { mOrientation = DISPLAY_ORIENTATION_0; } bumpGeneration(); } if (changes & InputReaderConfiguration::CHANGE_CURSOR_INPUT_STATUS) { mEnabled = config->cursorEnabled; } } void CursorInputMapper::configureParameters() { mParameters.mode = Parameters::MODE_POINTER; String8 cursorModeString; if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) { if (cursorModeString == "navigation") { mParameters.mode = Parameters::MODE_NAVIGATION; } else if (cursorModeString != "pointer" && cursorModeString != "default") { ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string()); } } mParameters.orientationAware = false; getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"), mParameters.orientationAware); mParameters.hasAssociatedDisplay = false; if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) { mParameters.hasAssociatedDisplay = true; } } void CursorInputMapper::dumpParameters(String8& dump) { dump.append(INDENT3 "Parameters:\n"); dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n", toString(mParameters.hasAssociatedDisplay)); switch (mParameters.mode) { case Parameters::MODE_POINTER: dump.append(INDENT4 "Mode: pointer\n"); break; case Parameters::MODE_NAVIGATION: dump.append(INDENT4 "Mode: navigation\n"); break; default: ALOG_ASSERT(false); } dump.appendFormat(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware)); } void CursorInputMapper::reset(nsecs_t when) { mButtonState = 0; mDownTime = 0; mPointerVelocityControl.reset(); mWheelXVelocityControl.reset(); mWheelYVelocityControl.reset(); mCursorButtonAccumulator.reset(getDevice()); mCursorMotionAccumulator.reset(getDevice()); mCursorScrollAccumulator.reset(getDevice()); InputMapper::reset(when); } void CursorInputMapper::process(const RawEvent* rawEvent) { mCursorButtonAccumulator.process(rawEvent); mCursorMotionAccumulator.process(rawEvent); mCursorScrollAccumulator.process(rawEvent); if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) { sync(rawEvent->when); } } void CursorInputMapper::sync(nsecs_t when) { int32_t lastButtonState = mButtonState; int32_t currentButtonState = mCursorButtonAccumulator.getButtonState(); mButtonState = currentButtonState; bool wasDown = isPointerDown(lastButtonState); bool down = isPointerDown(currentButtonState); bool downChanged; if (!wasDown && down) { mDownTime = when; downChanged = true; } else if (wasDown && !down) { downChanged = true; } else { downChanged = false; } nsecs_t downTime = mDownTime; bool buttonsChanged = currentButtonState != lastButtonState; bool buttonsPressed = currentButtonState & ~lastButtonState; float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale; float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale; bool moved = deltaX != 0 || deltaY != 0; // Rotate delta according to orientation if needed. if (mParameters.orientationAware && mParameters.hasAssociatedDisplay && (deltaX != 0.0f || deltaY != 0.0f)) { rotateDelta(mOrientation, &deltaX, &deltaY); } // Move the pointer. PointerProperties pointerProperties; pointerProperties.clear(); pointerProperties.id = 0; pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE; PointerCoords pointerCoords; pointerCoords.clear(); float vscroll = mCursorScrollAccumulator.getRelativeVWheel(); float hscroll = mCursorScrollAccumulator.getRelativeHWheel(); bool scrolled = vscroll != 0 || hscroll != 0; mWheelYVelocityControl.move(when, NULL, &vscroll); mWheelXVelocityControl.move(when, &hscroll, NULL); mPointerVelocityControl.move(when, &deltaX, &deltaY); int32_t displayId; if (mPointerController != NULL) { if (moved || scrolled || buttonsChanged) { mPointerController->setPresentation( PointerControllerInterface::PRESENTATION_POINTER); if (moved) { mPointerController->move(deltaX, deltaY); } if (buttonsChanged) { mPointerController->setButtonState(currentButtonState); } mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE); } float x, y; mPointerController->getPosition(&x, &y); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); displayId = ADISPLAY_ID_DEFAULT; } else { pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY); displayId = ADISPLAY_ID_NONE; } pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f); // Moving an external trackball or mouse should wake the device. // We don't do this for internal cursor devices to prevent them from waking up // the device in your pocket. // TODO: Use the input device configuration to control this behavior more finely. uint32_t policyFlags = 0; char value[PROPERTY_VALUE_MAX]; property_get("ro.platform.has.mbxuimode", value, "false"); if(strcmp(value, "true") != 0) { if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) { policyFlags |= POLICY_FLAG_WAKE_DROPPED; } } // Synthesize key down from buttons if needed. synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource, policyFlags, lastButtonState, currentButtonState); // Send motion event. if (downChanged || moved || scrolled || buttonsChanged) { int32_t metaState = mContext->getGlobalMetaState(); int32_t motionEventAction; if (downChanged) { motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP; } else if (down || mPointerController == NULL) { motionEventAction = AMOTION_EVENT_ACTION_MOVE; } else { motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE; } NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, motionEventAction, 0, metaState, currentButtonState, 0, displayId, 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime); getListener()->notifyMotion(&args); // Send hover move after UP to tell the application that the mouse is hovering now. if (motionEventAction == AMOTION_EVENT_ACTION_UP && mPointerController != NULL) { NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE, displayId, 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime); getListener()->notifyMotion(&hoverArgs); } // Send scroll events. if (scrolled) { pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll); NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE, displayId, 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime); getListener()->notifyMotion(&scrollArgs); } } // Synthesize key up from buttons if needed. synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource, policyFlags, lastButtonState, currentButtonState); mCursorMotionAccumulator.finishSync(); mCursorScrollAccumulator.finishSync(); } int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) { return getEventHub()->getScanCodeState(getDeviceId(), scanCode); } else { return AKEY_STATE_UNKNOWN; } } void CursorInputMapper::fadePointer() { if (mPointerController != NULL) { mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); } } // --- TouchInputMapper --- TouchInputMapper::TouchInputMapper(InputDevice* device) : InputMapper(device), mSource(0), mDeviceMode(DEVICE_MODE_DISABLED), mTvOutStatus(false), mPadmouseStatus(false),mHdimiCfgChange(false), mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0), mSurfaceOrientation(DISPLAY_ORIENTATION_0) { mHWRotation = DISPLAY_ORIENTATION_0; } TouchInputMapper::~TouchInputMapper() { } uint32_t TouchInputMapper::getSources() { return mSource; } void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) { InputMapper::populateDeviceInfo(info); if (mDeviceMode != DEVICE_MODE_DISABLED) { info->addMotionRange(mOrientedRanges.x); info->addMotionRange(mOrientedRanges.y); info->addMotionRange(mOrientedRanges.pressure); if (mOrientedRanges.haveSize) { info->addMotionRange(mOrientedRanges.size); } if (mOrientedRanges.haveTouchSize) { info->addMotionRange(mOrientedRanges.touchMajor); info->addMotionRange(mOrientedRanges.touchMinor); } if (mOrientedRanges.haveToolSize) { info->addMotionRange(mOrientedRanges.toolMajor); info->addMotionRange(mOrientedRanges.toolMinor); } if (mOrientedRanges.haveOrientation) { info->addMotionRange(mOrientedRanges.orientation); } if (mOrientedRanges.haveDistance) { info->addMotionRange(mOrientedRanges.distance); } if (mOrientedRanges.haveTilt) { info->addMotionRange(mOrientedRanges.tilt); } if (mCursorScrollAccumulator.haveRelativeVWheel()) { info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f); } if (mCursorScrollAccumulator.haveRelativeHWheel()) { info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f); } if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) { const InputDeviceInfo::MotionRange& x = mOrientedRanges.x; const InputDeviceInfo::MotionRange& y = mOrientedRanges.y; info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat, x.fuzz, x.resolution); info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat, y.fuzz, y.resolution); info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat, x.fuzz, x.resolution); info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat, y.fuzz, y.resolution); } info->setButtonUnderPad(mParameters.hasButtonUnderPad); } } void TouchInputMapper::dump(String8& dump) { dump.append(INDENT2 "Touch Input Mapper:\n"); dumpParameters(dump); dumpVirtualKeys(dump); dumpRawPointerAxes(dump); dumpCalibration(dump); dumpSurface(dump); dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n"); dump.appendFormat(INDENT4 "XTranslate: %0.3f\n", mXTranslate); dump.appendFormat(INDENT4 "YTranslate: %0.3f\n", mYTranslate); dump.appendFormat(INDENT4 "XScale: %0.3f\n", mXScale); dump.appendFormat(INDENT4 "YScale: %0.3f\n", mYScale); dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mXPrecision); dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mYPrecision); dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale); dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mPressureScale); dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mSizeScale); dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale); dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale); dump.appendFormat(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt)); dump.appendFormat(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter); dump.appendFormat(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale); dump.appendFormat(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter); dump.appendFormat(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale); dump.appendFormat(INDENT3 "Last Button State: 0x%08x\n", mLastButtonState); dump.appendFormat(INDENT3 "Last Raw Touch: pointerCount=%d\n", mLastRawPointerData.pointerCount); for (uint32_t i = 0; i < mLastRawPointerData.pointerCount; i++) { const RawPointerData::Pointer& pointer = mLastRawPointerData.pointers[i]; dump.appendFormat(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, " "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, " "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, " "toolType=%d, isHovering=%s\n", i, pointer.id, pointer.x, pointer.y, pointer.pressure, pointer.touchMajor, pointer.touchMinor, pointer.toolMajor, pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance, pointer.toolType, toString(pointer.isHovering)); } dump.appendFormat(INDENT3 "Last Cooked Touch: pointerCount=%d\n", mLastCookedPointerData.pointerCount); for (uint32_t i = 0; i < mLastCookedPointerData.pointerCount; i++) { const PointerProperties& pointerProperties = mLastCookedPointerData.pointerProperties[i]; const PointerCoords& pointerCoords = mLastCookedPointerData.pointerCoords[i]; dump.appendFormat(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, " "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, " "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, " "toolType=%d, isHovering=%s\n", i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(), pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE), pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR), pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR), pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR), pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR), pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION), pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT), pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE), pointerProperties.toolType, toString(mLastCookedPointerData.isHovering(i))); } if (mDeviceMode == DEVICE_MODE_POINTER) { dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n"); dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale); dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale); dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale); dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale); dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth); } } void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) { InputMapper::configure(when, config, changes); mConfig = *config; if (!changes) { // first time only // Configure basic parameters. configureParameters(); // Configure common accumulators. mCursorScrollAccumulator.configure(getDevice()); mTouchButtonAccumulator.configure(getDevice()); // Configure absolute axis information. configureRawPointerAxes(); // Prepare input device calibration. parseCalibration(); resolveCalibration(); } if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) { // Update pointer speed. mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters); mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters); mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters); } bool resetNeeded = false; if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT | InputReaderConfiguration::CHANGE_SHOW_TOUCHES))) { // Configure device sources, surface dimensions, orientation and // scaling factors. configureSurface(when, &resetNeeded); } if (changes && resetNeeded) { // Send reset, unless this is the first time the device has been configured, // in which case the reader will call reset itself after all mappers are ready. getDevice()->notifyReset(when); } } void TouchInputMapper::configureParameters() { // Use the pointer presentation mode for devices that do not support distinct // multitouch. The spot-based presentation relies on being able to accurately // locate two or more fingers on the touch pad. mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT) ? Parameters::GESTURE_MODE_POINTER : Parameters::GESTURE_MODE_SPOTS; String8 gestureModeString; if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"), gestureModeString)) { if (gestureModeString == "pointer") { mParameters.gestureMode = Parameters::GESTURE_MODE_POINTER; } else if (gestureModeString == "spots") { mParameters.gestureMode = Parameters::GESTURE_MODE_SPOTS; } else if (gestureModeString != "default") { ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string()); } } if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) { // The device is a touch screen. mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN; } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) { // The device is a pointing device like a track pad. mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER; } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X) || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) { // The device is a cursor device with a touch pad attached. // By default don't use the touch pad to move the pointer. mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD; } else { // The device is a touch pad of unknown purpose. mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER; } mParameters.hasButtonUnderPad= getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD); String8 deviceTypeString; if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"), deviceTypeString)) { if (deviceTypeString == "touchScreen") { mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN; } else if (deviceTypeString == "touchPad") { mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD; } else if (deviceTypeString == "touchNavigation") { mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION; } else if (deviceTypeString == "pointer") { mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER; } else if (deviceTypeString != "default") { ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string()); } } mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN; getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"), mParameters.orientationAware); mParameters.hasAssociatedDisplay = false; mParameters.associatedDisplayIsExternal = false; if (mParameters.orientationAware || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) { mParameters.hasAssociatedDisplay = true; mParameters.associatedDisplayIsExternal = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN && getDevice()->isExternal(); } } void TouchInputMapper::dumpParameters(String8& dump) { dump.append(INDENT3 "Parameters:\n"); switch (mParameters.gestureMode) { case Parameters::GESTURE_MODE_POINTER: dump.append(INDENT4 "GestureMode: pointer\n"); break; case Parameters::GESTURE_MODE_SPOTS: dump.append(INDENT4 "GestureMode: spots\n"); break; default: assert(false); } switch (mParameters.deviceType) { case Parameters::DEVICE_TYPE_TOUCH_SCREEN: dump.append(INDENT4 "DeviceType: touchScreen\n"); break; case Parameters::DEVICE_TYPE_TOUCH_PAD: dump.append(INDENT4 "DeviceType: touchPad\n"); break; case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION: dump.append(INDENT4 "DeviceType: touchNavigation\n"); break; case Parameters::DEVICE_TYPE_POINTER: dump.append(INDENT4 "DeviceType: pointer\n"); break; default: ALOG_ASSERT(false); } dump.appendFormat(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s\n", toString(mParameters.hasAssociatedDisplay), toString(mParameters.associatedDisplayIsExternal)); dump.appendFormat(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware)); } void TouchInputMapper::configureRawPointerAxes() { mRawPointerAxes.clear(); } void TouchInputMapper::dumpRawPointerAxes(String8& dump) { dump.append(INDENT3 "Raw Touch Axes:\n"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot"); } void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) { int32_t oldDeviceMode = mDeviceMode; // Determine device mode. if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER && mConfig.pointerGesturesEnabled) { if(mHdimiCfgChange){ mSource = AINPUT_SOURCE_TOUCHSCREEN; mHdimiCfgChange = false; }else{ mSource = AINPUT_SOURCE_MOUSE; } mDeviceMode = DEVICE_MODE_POINTER; if (hasStylus()) { mSource |= AINPUT_SOURCE_STYLUS; } } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN && mParameters.hasAssociatedDisplay) { mSource = AINPUT_SOURCE_TOUCHSCREEN; mDeviceMode = DEVICE_MODE_DIRECT; if (hasStylus()) { mSource |= AINPUT_SOURCE_STYLUS; } } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) { mSource = AINPUT_SOURCE_TOUCH_NAVIGATION; mDeviceMode = DEVICE_MODE_NAVIGATION; } else { mSource = AINPUT_SOURCE_TOUCHPAD; mDeviceMode = DEVICE_MODE_UNSCALED; } // Ensure we have valid X and Y axes. if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) { ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! " "The device will be inoperable.", getDeviceName().string()); mDeviceMode = DEVICE_MODE_DISABLED; return; } // Raw width and height in the natural orientation. int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1; int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1; // Get associated display dimensions. DisplayViewport newViewport; if (mParameters.hasAssociatedDisplay) { if (!mConfig.getDisplayInfo(mParameters.associatedDisplayIsExternal, &newViewport)) { ALOGI(INDENT "Touch device '%s' could not query the properties of its associated " "display. The device will be inoperable until the display size " "becomes available.", getDeviceName().string()); mDeviceMode = DEVICE_MODE_DISABLED; return; } char property[PROPERTY_VALUE_MAX]; if (property_get("ro.sf.hwrotation", property, NULL) > 0 && 180 == atoi(property)) { if(!mPadmouseStatus){ mHWRotation = DISPLAY_ORIENTATION_180; } else{ mHWRotation = DISPLAY_ORIENTATION_0; newViewport.orientation = (newViewport.orientation + DISPLAY_ORIENTATION_180)%4; } } } else { newViewport.setNonDisplayViewport(rawWidth, rawHeight); } bool viewportChanged = mViewport != newViewport; if (viewportChanged) { mViewport = newViewport; if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) { // Convert rotated viewport to natural surface coordinates. int32_t naturalLogicalWidth, naturalLogicalHeight; int32_t naturalPhysicalWidth, naturalPhysicalHeight; int32_t naturalPhysicalLeft, naturalPhysicalTop; int32_t naturalDeviceWidth, naturalDeviceHeight; switch (mViewport.orientation) { case DISPLAY_ORIENTATION_90: naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop; naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft; naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop; naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft; naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom; naturalPhysicalTop = mViewport.physicalLeft; naturalDeviceWidth = mViewport.deviceHeight; naturalDeviceHeight = mViewport.deviceWidth; break; case DISPLAY_ORIENTATION_180: naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft; naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop; naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft; naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop; naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight; naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom; naturalDeviceWidth = mViewport.deviceWidth; naturalDeviceHeight = mViewport.deviceHeight; break; case DISPLAY_ORIENTATION_270: naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop; naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft; naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop; naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft; naturalPhysicalLeft = mViewport.physicalTop; naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight; naturalDeviceWidth = mViewport.deviceHeight; naturalDeviceHeight = mViewport.deviceWidth; break; case DISPLAY_ORIENTATION_0: default: naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft; naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop; naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft; naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop; naturalPhysicalLeft = mViewport.physicalLeft; naturalPhysicalTop = mViewport.physicalTop; naturalDeviceWidth = mViewport.deviceWidth; naturalDeviceHeight = mViewport.deviceHeight; break; } mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth; mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight; mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth; mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight; mSurfaceOrientation = mParameters.orientationAware ? mViewport.orientation : DISPLAY_ORIENTATION_0; } else { mSurfaceWidth = rawWidth; mSurfaceHeight = rawHeight; mSurfaceLeft = 0; mSurfaceTop = 0; mSurfaceOrientation = DISPLAY_ORIENTATION_0; } } // If moving between pointer modes, need to reset some state. bool deviceModeChanged = mDeviceMode != oldDeviceMode; if (deviceModeChanged) { mOrientedRanges.clear(); } // Create pointer controller if needed. if (mDeviceMode == DEVICE_MODE_POINTER || (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) { if (mPointerController == NULL) { mPointerController = getPolicy()->obtainPointerController(getDeviceId()); } } else { mPointerController.clear(); } if (viewportChanged || deviceModeChanged) { ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, " "display id %d", getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight, mSurfaceOrientation, mDeviceMode, mViewport.displayId); // Configure X and Y factors. mXScale = float(mSurfaceWidth) / rawWidth; mYScale = float(mSurfaceHeight) / rawHeight; mXTranslate = -mSurfaceLeft; mYTranslate = -mSurfaceTop; mXPrecision = 1.0f / mXScale; mYPrecision = 1.0f / mYScale; mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X; mOrientedRanges.x.source = mSource; mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y; mOrientedRanges.y.source = mSource; configureVirtualKeys(); // Scale factor for terms that are not oriented in a particular axis. // If the pixels are square then xScale == yScale otherwise we fake it // by choosing an average. mGeometricScale = avg(mXScale, mYScale); // Size of diagonal axis. float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight); // Size factors. if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) { if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) { mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue; } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) { mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue; } else { mSizeScale = 0.0f; } mOrientedRanges.haveTouchSize = true; mOrientedRanges.haveToolSize = true; mOrientedRanges.haveSize = true; mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR; mOrientedRanges.touchMajor.source = mSource; mOrientedRanges.touchMajor.min = 0; mOrientedRanges.touchMajor.max = diagonalSize; mOrientedRanges.touchMajor.flat = 0; mOrientedRanges.touchMajor.fuzz = 0; mOrientedRanges.touchMajor.resolution = 0; mOrientedRanges.touchMinor = mOrientedRanges.touchMajor; mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR; mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR; mOrientedRanges.toolMajor.source = mSource; mOrientedRanges.toolMajor.min = 0; mOrientedRanges.toolMajor.max = diagonalSize; mOrientedRanges.toolMajor.flat = 0; mOrientedRanges.toolMajor.fuzz = 0; mOrientedRanges.toolMajor.resolution = 0; mOrientedRanges.toolMinor = mOrientedRanges.toolMajor; mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR; mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE; mOrientedRanges.size.source = mSource; mOrientedRanges.size.min = 0; mOrientedRanges.size.max = 1.0; mOrientedRanges.size.flat = 0; mOrientedRanges.size.fuzz = 0; mOrientedRanges.size.resolution = 0; } else { mSizeScale = 0.0f; } // Pressure factors. mPressureScale = 0; if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL || mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) { if (mCalibration.havePressureScale) { mPressureScale = mCalibration.pressureScale; } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) { mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue; } } mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE; mOrientedRanges.pressure.source = mSource; mOrientedRanges.pressure.min = 0; mOrientedRanges.pressure.max = 1.0; mOrientedRanges.pressure.flat = 0; mOrientedRanges.pressure.fuzz = 0; mOrientedRanges.pressure.resolution = 0; // Tilt mTiltXCenter = 0; mTiltXScale = 0; mTiltYCenter = 0; mTiltYScale = 0; mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid; if (mHaveTilt) { mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue); mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue); mTiltXScale = M_PI / 180; mTiltYScale = M_PI / 180; mOrientedRanges.haveTilt = true; mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT; mOrientedRanges.tilt.source = mSource; mOrientedRanges.tilt.min = 0; mOrientedRanges.tilt.max = M_PI_2; mOrientedRanges.tilt.flat = 0; mOrientedRanges.tilt.fuzz = 0; mOrientedRanges.tilt.resolution = 0; } // Orientation mOrientationScale = 0; if (mHaveTilt) { mOrientedRanges.haveOrientation = true; mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION; mOrientedRanges.orientation.source = mSource; mOrientedRanges.orientation.min = -M_PI; mOrientedRanges.orientation.max = M_PI; mOrientedRanges.orientation.flat = 0; mOrientedRanges.orientation.fuzz = 0; mOrientedRanges.orientation.resolution = 0; } else if (mCalibration.orientationCalibration != Calibration::ORIENTATION_CALIBRATION_NONE) { if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) { if (mRawPointerAxes.orientation.valid) { if (mRawPointerAxes.orientation.maxValue > 0) { mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue; } else if (mRawPointerAxes.orientation.minValue < 0) { mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue; } else { mOrientationScale = 0; } } } mOrientedRanges.haveOrientation = true; mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION; mOrientedRanges.orientation.source = mSource; mOrientedRanges.orientation.min = -M_PI_2; mOrientedRanges.orientation.max = M_PI_2; mOrientedRanges.orientation.flat = 0; mOrientedRanges.orientation.fuzz = 0; mOrientedRanges.orientation.resolution = 0; } // Distance mDistanceScale = 0; if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) { if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_SCALED) { if (mCalibration.haveDistanceScale) { mDistanceScale = mCalibration.distanceScale; } else { mDistanceScale = 1.0f; } } mOrientedRanges.haveDistance = true; mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE; mOrientedRanges.distance.source = mSource; mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale; mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale; mOrientedRanges.distance.flat = 0; mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale; mOrientedRanges.distance.resolution = 0; } // Compute oriented precision, scales and ranges. // Note that the maximum value reported is an inclusive maximum value so it is one // unit less than the total width or height of surface. int32_t adjustedorientation = (mSurfaceOrientation + mHWRotation) % 4; switch (adjustedorientation) { case DISPLAY_ORIENTATION_90: case DISPLAY_ORIENTATION_270: mOrientedXPrecision = mYPrecision; mOrientedYPrecision = mXPrecision; mOrientedRanges.x.min = mYTranslate; mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1; mOrientedRanges.x.flat = 0; mOrientedRanges.x.fuzz = 0; mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale; mOrientedRanges.y.min = mXTranslate; mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1; mOrientedRanges.y.flat = 0; mOrientedRanges.y.fuzz = 0; mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale; break; default: mOrientedXPrecision = mXPrecision; mOrientedYPrecision = mYPrecision; mOrientedRanges.x.min = mXTranslate; mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1; mOrientedRanges.x.flat = 0; mOrientedRanges.x.fuzz = 0; mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale; mOrientedRanges.y.min = mYTranslate; mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1; mOrientedRanges.y.flat = 0; mOrientedRanges.y.fuzz = 0; mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale; break; } if (mDeviceMode == DEVICE_MODE_POINTER) { // Compute pointer gesture detection parameters. float rawDiagonal = hypotf(rawWidth, rawHeight); float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight); // Scale movements such that one whole swipe of the touch pad covers a // given area relative to the diagonal size of the display when no acceleration // is applied. // Assume that the touch pad has a square aspect ratio such that movements in // X and Y of the same number of raw units cover the same physical distance. mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal; mPointerYMovementScale = mPointerXMovementScale; // Scale zooms to cover a smaller range of the display than movements do. // This value determines the area around the pointer that is affected by freeform // pointer gestures. mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal; mPointerYZoomScale = mPointerXZoomScale; // Max width between pointers to detect a swipe gesture is more than some fraction // of the diagonal axis of the touch pad. Touches that are wider than this are // translated into freeform gestures. mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal; // Abort current pointer usages because the state has changed. abortPointerUsage(when, 0 /*policyFlags*/); } // Inform the dispatcher about the changes. *outResetNeeded = true; bumpGeneration(); } } void TouchInputMapper::dumpSurface(String8& dump) { dump.appendFormat(INDENT3 "Viewport: displayId=%d, orientation=%d, " "logicalFrame=[%d, %d, %d, %d], " "physicalFrame=[%d, %d, %d, %d], " "deviceSize=[%d, %d]\n", mViewport.displayId, mViewport.orientation, mViewport.logicalLeft, mViewport.logicalTop, mViewport.logicalRight, mViewport.logicalBottom, mViewport.physicalLeft, mViewport.physicalTop, mViewport.physicalRight, mViewport.physicalBottom, mViewport.deviceWidth, mViewport.deviceHeight); dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth); dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight); dump.appendFormat(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft); dump.appendFormat(INDENT3 "SurfaceTop: %d\n", mSurfaceTop); dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation); } void TouchInputMapper::configureVirtualKeys() { Vector<VirtualKeyDefinition> virtualKeyDefinitions; getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions); mVirtualKeys.clear(); if (virtualKeyDefinitions.size() == 0) { return; } mVirtualKeys.setCapacity(virtualKeyDefinitions.size()); int32_t touchScreenLeft = mRawPointerAxes.x.minValue; int32_t touchScreenTop = mRawPointerAxes.y.minValue; int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1; int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1; for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) { const VirtualKeyDefinition& virtualKeyDefinition = virtualKeyDefinitions[i]; mVirtualKeys.add(); VirtualKey& virtualKey = mVirtualKeys.editTop(); virtualKey.scanCode = virtualKeyDefinition.scanCode; int32_t keyCode; uint32_t flags; if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, &keyCode, &flags)) { ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode); mVirtualKeys.pop(); // drop the key continue; } virtualKey.keyCode = keyCode; virtualKey.flags = flags; // convert the key definition's display coordinates into touch coordinates for a hit box int32_t halfWidth = virtualKeyDefinition.width / 2; int32_t halfHeight = virtualKeyDefinition.height / 2; virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mSurfaceWidth + touchScreenLeft; virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mSurfaceWidth + touchScreenLeft; virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight / mSurfaceHeight + touchScreenTop; virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight / mSurfaceHeight + touchScreenTop; } } void TouchInputMapper::dumpVirtualKeys(String8& dump) { if (!mVirtualKeys.isEmpty()) { dump.append(INDENT3 "Virtual Keys:\n"); for (size_t i = 0; i < mVirtualKeys.size(); i++) { const VirtualKey& virtualKey = mVirtualKeys.itemAt(i); dump.appendFormat(INDENT4 "%d: scanCode=%d, keyCode=%d, " "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n", i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft, virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom); } } } void TouchInputMapper::parseCalibration() { const PropertyMap& in = getDevice()->getConfiguration(); Calibration& out = mCalibration; // Size out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT; String8 sizeCalibrationString; if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) { if (sizeCalibrationString == "none") { out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE; } else if (sizeCalibrationString == "geometric") { out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC; } else if (sizeCalibrationString == "diameter") { out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER; } else if (sizeCalibrationString == "box") { out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX; } else if (sizeCalibrationString == "area") { out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA; } else if (sizeCalibrationString != "default") { ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string()); } } out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale); out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias); out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed); // Pressure out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT; String8 pressureCalibrationString; if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) { if (pressureCalibrationString == "none") { out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE; } else if (pressureCalibrationString == "physical") { out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL; } else if (pressureCalibrationString == "amplitude") { out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE; } else if (pressureCalibrationString != "default") { ALOGW("Invalid value for touch.pressure.calibration: '%s'", pressureCalibrationString.string()); } } out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale); // Orientation out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT; String8 orientationCalibrationString; if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) { if (orientationCalibrationString == "none") { out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE; } else if (orientationCalibrationString == "interpolated") { out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED; } else if (orientationCalibrationString == "vector") { out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR; } else if (orientationCalibrationString != "default") { ALOGW("Invalid value for touch.orientation.calibration: '%s'", orientationCalibrationString.string()); } } // Distance out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT; String8 distanceCalibrationString; if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) { if (distanceCalibrationString == "none") { out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE; } else if (distanceCalibrationString == "scaled") { out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED; } else if (distanceCalibrationString != "default") { ALOGW("Invalid value for touch.distance.calibration: '%s'", distanceCalibrationString.string()); } } out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale); out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT; String8 coverageCalibrationString; if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) { if (coverageCalibrationString == "none") { out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE; } else if (coverageCalibrationString == "box") { out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX; } else if (coverageCalibrationString != "default") { ALOGW("Invalid value for touch.coverage.calibration: '%s'", coverageCalibrationString.string()); } } } void TouchInputMapper::resolveCalibration() { // Size if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) { if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) { mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC; } } else { mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE; } // Pressure if (mRawPointerAxes.pressure.valid) { if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) { mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL; } } else { mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE; } // Orientation if (mRawPointerAxes.orientation.valid) { if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) { mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED; } } else { mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE; } // Distance if (mRawPointerAxes.distance.valid) { if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) { mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED; } } else { mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE; } // Coverage if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) { mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE; } } void TouchInputMapper::dumpCalibration(String8& dump) { dump.append(INDENT3 "Calibration:\n"); // Size switch (mCalibration.sizeCalibration) { case Calibration::SIZE_CALIBRATION_NONE: dump.append(INDENT4 "touch.size.calibration: none\n"); break; case Calibration::SIZE_CALIBRATION_GEOMETRIC: dump.append(INDENT4 "touch.size.calibration: geometric\n"); break; case Calibration::SIZE_CALIBRATION_DIAMETER: dump.append(INDENT4 "touch.size.calibration: diameter\n"); break; case Calibration::SIZE_CALIBRATION_BOX: dump.append(INDENT4 "touch.size.calibration: box\n"); break; case Calibration::SIZE_CALIBRATION_AREA: dump.append(INDENT4 "touch.size.calibration: area\n"); break; default: ALOG_ASSERT(false); } if (mCalibration.haveSizeScale) { dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale); } if (mCalibration.haveSizeBias) { dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias); } if (mCalibration.haveSizeIsSummed) { dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n", toString(mCalibration.sizeIsSummed)); } // Pressure switch (mCalibration.pressureCalibration) { case Calibration::PRESSURE_CALIBRATION_NONE: dump.append(INDENT4 "touch.pressure.calibration: none\n"); break; case Calibration::PRESSURE_CALIBRATION_PHYSICAL: dump.append(INDENT4 "touch.pressure.calibration: physical\n"); break; case Calibration::PRESSURE_CALIBRATION_AMPLITUDE: dump.append(INDENT4 "touch.pressure.calibration: amplitude\n"); break; default: ALOG_ASSERT(false); } if (mCalibration.havePressureScale) { dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale); } // Orientation switch (mCalibration.orientationCalibration) { case Calibration::ORIENTATION_CALIBRATION_NONE: dump.append(INDENT4 "touch.orientation.calibration: none\n"); break; case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED: dump.append(INDENT4 "touch.orientation.calibration: interpolated\n"); break; case Calibration::ORIENTATION_CALIBRATION_VECTOR: dump.append(INDENT4 "touch.orientation.calibration: vector\n"); break; default: ALOG_ASSERT(false); } // Distance switch (mCalibration.distanceCalibration) { case Calibration::DISTANCE_CALIBRATION_NONE: dump.append(INDENT4 "touch.distance.calibration: none\n"); break; case Calibration::DISTANCE_CALIBRATION_SCALED: dump.append(INDENT4 "touch.distance.calibration: scaled\n"); break; default: ALOG_ASSERT(false); } if (mCalibration.haveDistanceScale) { dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale); } switch (mCalibration.coverageCalibration) { case Calibration::COVERAGE_CALIBRATION_NONE: dump.append(INDENT4 "touch.coverage.calibration: none\n"); break; case Calibration::COVERAGE_CALIBRATION_BOX: dump.append(INDENT4 "touch.coverage.calibration: box\n"); break; default: ALOG_ASSERT(false); } } void TouchInputMapper::reset(nsecs_t when) { mCursorButtonAccumulator.reset(getDevice()); mCursorScrollAccumulator.reset(getDevice()); mTouchButtonAccumulator.reset(getDevice()); mPointerVelocityControl.reset(); mWheelXVelocityControl.reset(); mWheelYVelocityControl.reset(); mCurrentRawPointerData.clear(); mLastRawPointerData.clear(); mCurrentCookedPointerData.clear(); mLastCookedPointerData.clear(); mCurrentButtonState = 0; mLastButtonState = 0; mCurrentRawVScroll = 0; mCurrentRawHScroll = 0; mCurrentFingerIdBits.clear(); mLastFingerIdBits.clear(); mCurrentStylusIdBits.clear(); mLastStylusIdBits.clear(); mCurrentMouseIdBits.clear(); mLastMouseIdBits.clear(); mPointerUsage = POINTER_USAGE_NONE; mSentHoverEnter = false; mDownTime = 0; mCurrentVirtualKey.down = false; mPointerGesture.reset(); mPointerSimple.reset(); if (mPointerController != NULL) { mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); mPointerController->clearSpots(); } InputMapper::reset(when); } void TouchInputMapper::process(const RawEvent* rawEvent) { mCursorButtonAccumulator.process(rawEvent); mCursorScrollAccumulator.process(rawEvent); mTouchButtonAccumulator.process(rawEvent); if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) { sync(rawEvent->when); } } void TouchInputMapper::sync(nsecs_t when) { // Sync button state. mCurrentButtonState = mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState(); // Sync scroll state. mCurrentRawVScroll = mCursorScrollAccumulator.getRelativeVWheel(); mCurrentRawHScroll = mCursorScrollAccumulator.getRelativeHWheel(); mCursorScrollAccumulator.finishSync(); // Sync touch state. bool havePointerIds = true; mCurrentRawPointerData.clear(); syncTouch(when, &havePointerIds); #if DEBUG_RAW_EVENTS if (!havePointerIds) { ALOGD("syncTouch: pointerCount %d -> %d, no pointer ids", mLastRawPointerData.pointerCount, mCurrentRawPointerData.pointerCount); } else { ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, " "hovering ids 0x%08x -> 0x%08x", mLastRawPointerData.pointerCount, mCurrentRawPointerData.pointerCount, mLastRawPointerData.touchingIdBits.value, mCurrentRawPointerData.touchingIdBits.value, mLastRawPointerData.hoveringIdBits.value, mCurrentRawPointerData.hoveringIdBits.value); } #endif // Reset state that we will compute below. mCurrentFingerIdBits.clear(); mCurrentStylusIdBits.clear(); mCurrentMouseIdBits.clear(); mCurrentCookedPointerData.clear(); if (mDeviceMode == DEVICE_MODE_DISABLED) { // Drop all input if the device is disabled. mCurrentRawPointerData.clear(); mCurrentButtonState = 0; } else { // Preprocess pointer data. if (!havePointerIds) { assignPointerIds(); } // Handle policy on initial down or hover events. uint32_t policyFlags = 0; bool initialDown = mLastRawPointerData.pointerCount == 0 && mCurrentRawPointerData.pointerCount != 0; bool buttonsPressed = mCurrentButtonState & ~mLastButtonState; if (initialDown || buttonsPressed) { // If this is a touch screen, hide the pointer on an initial down. if (mDeviceMode == DEVICE_MODE_DIRECT) { getContext()->fadePointer(); } // Initial downs on external touch devices should wake the device. // We don't do this for internal touch screens to prevent them from waking // up in your pocket. // TODO: Use the input device configuration to control this behavior more finely. if (getDevice()->isExternal()) { policyFlags |= POLICY_FLAG_WAKE_DROPPED; } } // Synthesize key down from raw buttons if needed. synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource, policyFlags, mLastButtonState, mCurrentButtonState); // Consume raw off-screen touches before cooking pointer data. // If touches are consumed, subsequent code will not receive any pointer data. if (consumeRawTouches(when, policyFlags)) { mCurrentRawPointerData.clear(); } // Cook pointer data. This call populates the mCurrentCookedPointerData structure // with cooked pointer data that has the same ids and indices as the raw data. // The following code can use either the raw or cooked data, as needed. cookPointerData(); // Dispatch the touches either directly or by translation through a pointer on screen. if (mDeviceMode == DEVICE_MODE_POINTER) { for (BitSet32 idBits(mCurrentRawPointerData.touchingIdBits); !idBits.isEmpty(); ) { uint32_t id = idBits.clearFirstMarkedBit(); const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id); if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) { mCurrentStylusIdBits.markBit(id); } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) { mCurrentFingerIdBits.markBit(id); } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) { mCurrentMouseIdBits.markBit(id); } } for (BitSet32 idBits(mCurrentRawPointerData.hoveringIdBits); !idBits.isEmpty(); ) { uint32_t id = idBits.clearFirstMarkedBit(); const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id); if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) { mCurrentStylusIdBits.markBit(id); } } // Stylus takes precedence over all tools, then mouse, then finger. PointerUsage pointerUsage = mPointerUsage; if (!mCurrentStylusIdBits.isEmpty()) { mCurrentMouseIdBits.clear(); mCurrentFingerIdBits.clear(); pointerUsage = POINTER_USAGE_STYLUS; } else if (!mCurrentMouseIdBits.isEmpty()) { mCurrentFingerIdBits.clear(); pointerUsage = POINTER_USAGE_MOUSE; } else if (!mCurrentFingerIdBits.isEmpty() || isPointerDown(mCurrentButtonState)) { pointerUsage = POINTER_USAGE_GESTURES; } dispatchPointerUsage(when, policyFlags, pointerUsage); } else { if (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches && mPointerController != NULL) { mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT); mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); mPointerController->setButtonState(mCurrentButtonState); mPointerController->setSpots(mCurrentCookedPointerData.pointerCoords, mCurrentCookedPointerData.idToIndex, mCurrentCookedPointerData.touchingIdBits); } dispatchHoverExit(when, policyFlags); dispatchTouches(when, policyFlags); dispatchHoverEnterAndMove(when, policyFlags); } // Synthesize key up from raw buttons if needed. synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource, policyFlags, mLastButtonState, mCurrentButtonState); } // Copy current touch to last touch in preparation for the next cycle. mLastRawPointerData.copyFrom(mCurrentRawPointerData); mLastCookedPointerData.copyFrom(mCurrentCookedPointerData); mLastButtonState = mCurrentButtonState; mLastFingerIdBits = mCurrentFingerIdBits; mLastStylusIdBits = mCurrentStylusIdBits; mLastMouseIdBits = mCurrentMouseIdBits; // Clear some transient state. mCurrentRawVScroll = 0; mCurrentRawHScroll = 0; } void TouchInputMapper::timeoutExpired(nsecs_t when) { if (mDeviceMode == DEVICE_MODE_POINTER) { if (mPointerUsage == POINTER_USAGE_GESTURES) { dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/); } } } bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) { // Check for release of a virtual key. if (mCurrentVirtualKey.down) { if (mCurrentRawPointerData.touchingIdBits.isEmpty()) { // Pointer went up while virtual key was down. mCurrentVirtualKey.down = false; if (!mCurrentVirtualKey.ignored) { #if DEBUG_VIRTUAL_KEYS ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode); #endif dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP, AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY); } return true; } if (mCurrentRawPointerData.touchingIdBits.count() == 1) { uint32_t id = mCurrentRawPointerData.touchingIdBits.firstMarkedBit(); const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id); const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y); if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) { // Pointer is still within the space of the virtual key. return true; } } // Pointer left virtual key area or another pointer also went down. // Send key cancellation but do not consume the touch yet. // This is useful when the user swipes through from the virtual key area // into the main display surface. mCurrentVirtualKey.down = false; if (!mCurrentVirtualKey.ignored) { #if DEBUG_VIRTUAL_KEYS ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode); #endif dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP, AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY | AKEY_EVENT_FLAG_CANCELED); } } if (mLastRawPointerData.touchingIdBits.isEmpty() && !mCurrentRawPointerData.touchingIdBits.isEmpty()) { // Pointer just went down. Check for virtual key press or off-screen touches. uint32_t id = mCurrentRawPointerData.touchingIdBits.firstMarkedBit(); const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id); if (!isPointInsideSurface(pointer.x, pointer.y)) { // If exactly one pointer went down, check for virtual key hit. // Otherwise we will drop the entire stroke. if (mCurrentRawPointerData.touchingIdBits.count() == 1) { const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y); if (virtualKey) { mCurrentVirtualKey.down = true; mCurrentVirtualKey.downTime = when; mCurrentVirtualKey.keyCode = virtualKey->keyCode; mCurrentVirtualKey.scanCode = virtualKey->scanCode; mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey( when, getDevice(), virtualKey->keyCode, virtualKey->scanCode); if (!mCurrentVirtualKey.ignored) { #if DEBUG_VIRTUAL_KEYS ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode); #endif dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_DOWN, AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY); } } } return true; } } // Disable all virtual key touches that happen within a short time interval of the // most recent touch within the screen area. The idea is to filter out stray // virtual key presses when interacting with the touch screen. // // Problems we're trying to solve: // // 1. While scrolling a list or dragging the window shade, the user swipes down into a // virtual key area that is implemented by a separate touch panel and accidentally // triggers a virtual key. // // 2. While typing in the on screen keyboard, the user taps slightly outside the screen // area and accidentally triggers a virtual key. This often happens when virtual keys // are layed out below the screen near to where the on screen keyboard's space bar // is displayed. if (mConfig.virtualKeyQuietTime > 0 && !mCurrentRawPointerData.touchingIdBits.isEmpty()) { mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime); } return false; } void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags, int32_t keyEventAction, int32_t keyEventFlags) { int32_t keyCode = mCurrentVirtualKey.keyCode; int32_t scanCode = mCurrentVirtualKey.scanCode; nsecs_t downTime = mCurrentVirtualKey.downTime; int32_t metaState = mContext->getGlobalMetaState(); policyFlags |= POLICY_FLAG_VIRTUAL; NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime); getListener()->notifyKey(&args); } void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) { BitSet32 currentIdBits = mCurrentCookedPointerData.touchingIdBits; BitSet32 lastIdBits = mLastCookedPointerData.touchingIdBits; int32_t metaState = getContext()->getGlobalMetaState(); int32_t buttonState = mCurrentButtonState; if (currentIdBits == lastIdBits) { if (!currentIdBits.isEmpty()) { // No pointer id changes so this is a move event. // The listener takes care of batching moves so we don't have to deal with that here. dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, mCurrentCookedPointerData.pointerProperties, mCurrentCookedPointerData.pointerCoords, mCurrentCookedPointerData.idToIndex, currentIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime); } } else { // There may be pointers going up and pointers going down and pointers moving // all at the same time. BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value); BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value); BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value); BitSet32 dispatchedIdBits(lastIdBits.value); // Update last coordinates of pointers that have moved so that we observe the new // pointer positions at the same time as other pointers that have just gone up. bool moveNeeded = updateMovedPointers( mCurrentCookedPointerData.pointerProperties, mCurrentCookedPointerData.pointerCoords, mCurrentCookedPointerData.idToIndex, mLastCookedPointerData.pointerProperties, mLastCookedPointerData.pointerCoords, mLastCookedPointerData.idToIndex, moveIdBits); if (buttonState != mLastButtonState) { moveNeeded = true; } // Dispatch pointer up events. while (!upIdBits.isEmpty()) { uint32_t upId = upIdBits.clearFirstMarkedBit(); dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, metaState, buttonState, 0, mLastCookedPointerData.pointerProperties, mLastCookedPointerData.pointerCoords, mLastCookedPointerData.idToIndex, dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime); dispatchedIdBits.clearBit(upId); } // Dispatch move events if any of the remaining pointers moved from their old locations. // Although applications receive new locations as part of individual pointer up // events, they do not generally handle them except when presented in a move event. if (moveNeeded) { ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value); dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, 0, mCurrentCookedPointerData.pointerProperties, mCurrentCookedPointerData.pointerCoords, mCurrentCookedPointerData.idToIndex, dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime); } // Dispatch pointer down events using the new pointer locations. while (!downIdBits.isEmpty()) { uint32_t downId = downIdBits.clearFirstMarkedBit(); dispatchedIdBits.markBit(downId); if (dispatchedIdBits.count() == 1) { // First pointer is going down. Set down time. mDownTime = when; } dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, buttonState, 0, mCurrentCookedPointerData.pointerProperties, mCurrentCookedPointerData.pointerCoords, mCurrentCookedPointerData.idToIndex, dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime); } } } void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) { if (mSentHoverEnter && (mCurrentCookedPointerData.hoveringIdBits.isEmpty() || !mCurrentCookedPointerData.touchingIdBits.isEmpty())) { int32_t metaState = getContext()->getGlobalMetaState(); dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, metaState, mLastButtonState, 0, mLastCookedPointerData.pointerProperties, mLastCookedPointerData.pointerCoords, mLastCookedPointerData.idToIndex, mLastCookedPointerData.hoveringIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime); mSentHoverEnter = false; } } void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) { if (mCurrentCookedPointerData.touchingIdBits.isEmpty() && !mCurrentCookedPointerData.hoveringIdBits.isEmpty()) { int32_t metaState = getContext()->getGlobalMetaState(); if (!mSentHoverEnter) { dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, metaState, mCurrentButtonState, 0, mCurrentCookedPointerData.pointerProperties, mCurrentCookedPointerData.pointerCoords, mCurrentCookedPointerData.idToIndex, mCurrentCookedPointerData.hoveringIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime); mSentHoverEnter = true; } dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, mCurrentButtonState, 0, mCurrentCookedPointerData.pointerProperties, mCurrentCookedPointerData.pointerCoords, mCurrentCookedPointerData.idToIndex, mCurrentCookedPointerData.hoveringIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime); } } void TouchInputMapper::cookPointerData() { uint32_t currentPointerCount = mCurrentRawPointerData.pointerCount; mCurrentCookedPointerData.clear(); mCurrentCookedPointerData.pointerCount = currentPointerCount; mCurrentCookedPointerData.hoveringIdBits = mCurrentRawPointerData.hoveringIdBits; mCurrentCookedPointerData.touchingIdBits = mCurrentRawPointerData.touchingIdBits; // Walk through the the active pointers and map device coordinates onto // surface coordinates and adjust for display orientation. for (uint32_t i = 0; i < currentPointerCount; i++) { const RawPointerData::Pointer& in = mCurrentRawPointerData.pointers[i]; // Size float touchMajor, touchMinor, toolMajor, toolMinor, size; switch (mCalibration.sizeCalibration) { case Calibration::SIZE_CALIBRATION_GEOMETRIC: case Calibration::SIZE_CALIBRATION_DIAMETER: case Calibration::SIZE_CALIBRATION_BOX: case Calibration::SIZE_CALIBRATION_AREA: if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) { touchMajor = in.touchMajor; touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor; toolMajor = in.toolMajor; toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor; size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor) : in.touchMajor; } else if (mRawPointerAxes.touchMajor.valid) { toolMajor = touchMajor = in.touchMajor; toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor; size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor) : in.touchMajor; } else if (mRawPointerAxes.toolMajor.valid) { touchMajor = toolMajor = in.toolMajor; touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor; size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor) : in.toolMajor; } else { ALOG_ASSERT(false, "No touch or tool axes. " "Size calibration should have been resolved to NONE."); touchMajor = 0; touchMinor = 0; toolMajor = 0; toolMinor = 0; size = 0; } if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) { uint32_t touchingCount = mCurrentRawPointerData.touchingIdBits.count(); if (touchingCount > 1) { touchMajor /= touchingCount; touchMinor /= touchingCount; toolMajor /= touchingCount; toolMinor /= touchingCount; size /= touchingCount; } } if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) { touchMajor *= mGeometricScale; touchMinor *= mGeometricScale; toolMajor *= mGeometricScale; toolMinor *= mGeometricScale; } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) { touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0; touchMinor = touchMajor; toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0; toolMinor = toolMajor; } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) { touchMinor = touchMajor; toolMinor = toolMajor; } mCalibration.applySizeScaleAndBias(&touchMajor); mCalibration.applySizeScaleAndBias(&touchMinor); mCalibration.applySizeScaleAndBias(&toolMajor); mCalibration.applySizeScaleAndBias(&toolMinor); size *= mSizeScale; break; default: touchMajor = 0; touchMinor = 0; toolMajor = 0; toolMinor = 0; size = 0; break; } // Pressure float pressure; switch (mCalibration.pressureCalibration) { case Calibration::PRESSURE_CALIBRATION_PHYSICAL: case Calibration::PRESSURE_CALIBRATION_AMPLITUDE: pressure = in.pressure * mPressureScale; break; default: pressure = in.isHovering ? 0 : 1; break; } // Tilt and Orientation float tilt; float orientation; if (mHaveTilt) { float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale; float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale; orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)); tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle)); } else { tilt = 0; switch (mCalibration.orientationCalibration) { case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED: orientation = in.orientation * mOrientationScale; break; case Calibration::ORIENTATION_CALIBRATION_VECTOR: { int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4); int32_t c2 = signExtendNybble(in.orientation & 0x0f); if (c1 != 0 || c2 != 0) { orientation = atan2f(c1, c2) * 0.5f; float confidence = hypotf(c1, c2); float scale = 1.0f + confidence / 16.0f; touchMajor *= scale; touchMinor /= scale; toolMajor *= scale; toolMinor /= scale; } else { orientation = 0; } break; } default: orientation = 0; } } // Distance float distance; switch (mCalibration.distanceCalibration) { case Calibration::DISTANCE_CALIBRATION_SCALED: distance = in.distance * mDistanceScale; break; default: distance = 0; } // Coverage int32_t rawLeft, rawTop, rawRight, rawBottom; switch (mCalibration.coverageCalibration) { case Calibration::COVERAGE_CALIBRATION_BOX: rawLeft = (in.toolMinor & 0xffff0000) >> 16; rawRight = in.toolMinor & 0x0000ffff; rawBottom = in.toolMajor & 0x0000ffff; rawTop = (in.toolMajor & 0xffff0000) >> 16; break; default: rawLeft = rawTop = rawRight = rawBottom = 0; break; } // X, Y, and the bounding box for coverage information // Adjust coords for surface orientation. float x, y, left, top, right, bottom; int32_t adjustedorientation = (mSurfaceOrientation + mHWRotation) % 4; switch (adjustedorientation) { case DISPLAY_ORIENTATION_90: x = float(in.y - mRawPointerAxes.y.minValue) * mYScale + mYTranslate; y = float(mRawPointerAxes.x.maxValue - in.x) * mXScale + mXTranslate; left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate; right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate; bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate; top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate; orientation -= M_PI_2; if (orientation < mOrientedRanges.orientation.min) { orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min); } break; case DISPLAY_ORIENTATION_180: x = float(mRawPointerAxes.x.maxValue - in.x) * mXScale + mXTranslate; y = float(mRawPointerAxes.y.maxValue - in.y) * mYScale + mYTranslate; left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate; right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate; bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate; top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate; orientation -= M_PI; if (orientation < mOrientedRanges.orientation.min) { orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min); } break; case DISPLAY_ORIENTATION_270: x = float(mRawPointerAxes.y.maxValue - in.y) * mYScale + mYTranslate; y = float(in.x - mRawPointerAxes.x.minValue) * mXScale + mXTranslate; left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate; right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate; bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate; top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate; orientation += M_PI_2; if (orientation > mOrientedRanges.orientation.max) { orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min); } break; default: x = float(in.x - mRawPointerAxes.x.minValue) * mXScale + mXTranslate; y = float(in.y - mRawPointerAxes.y.minValue) * mYScale + mYTranslate; left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate; right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate; bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate; top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate; break; } // Write output coords. PointerCoords& out = mCurrentCookedPointerData.pointerCoords[i]; out.clear(); out.setAxisValue(AMOTION_EVENT_AXIS_X, x); out.setAxisValue(AMOTION_EVENT_AXIS_Y, y); out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure); out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size); out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor); out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor); out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation); out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt); out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance); if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) { out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left); out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top); out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right); out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom); } else { out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor); out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor); } // Write output properties. PointerProperties& properties = mCurrentCookedPointerData.pointerProperties[i]; uint32_t id = in.id; properties.clear(); properties.id = id; properties.toolType = in.toolType; // Write id index. mCurrentCookedPointerData.idToIndex[id] = i; } } void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags, PointerUsage pointerUsage) { if (pointerUsage != mPointerUsage) { abortPointerUsage(when, policyFlags); mPointerUsage = pointerUsage; } switch (mPointerUsage) { case POINTER_USAGE_GESTURES: dispatchPointerGestures(when, policyFlags, false /*isTimeout*/); break; case POINTER_USAGE_STYLUS: dispatchPointerStylus(when, policyFlags); break; case POINTER_USAGE_MOUSE: dispatchPointerMouse(when, policyFlags); break; default: break; } } void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) { switch (mPointerUsage) { case POINTER_USAGE_GESTURES: abortPointerGestures(when, policyFlags); break; case POINTER_USAGE_STYLUS: abortPointerStylus(when, policyFlags); break; case POINTER_USAGE_MOUSE: abortPointerMouse(when, policyFlags); break; default: break; } mPointerUsage = POINTER_USAGE_NONE; } void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout) { // Update current gesture coordinates. bool cancelPreviousGesture, finishPreviousGesture; bool sendEvents = preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout); if (!sendEvents) { return; } if (finishPreviousGesture) { cancelPreviousGesture = false; } // Update the pointer presentation and spots. if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) { mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT); if (finishPreviousGesture || cancelPreviousGesture) { mPointerController->clearSpots(); } mPointerController->setSpots(mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex, mPointerGesture.currentGestureIdBits); } else { mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER); } // Show or hide the pointer if needed. switch (mPointerGesture.currentGestureMode) { case PointerGesture::NEUTRAL: case PointerGesture::QUIET: if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS && (mPointerGesture.lastGestureMode == PointerGesture::SWIPE || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)) { // Remind the user of where the pointer is after finishing a gesture with spots. mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL); } break; case PointerGesture::TAP: case PointerGesture::TAP_DRAG: case PointerGesture::BUTTON_CLICK_OR_DRAG: case PointerGesture::HOVER: case PointerGesture::PRESS: // Unfade the pointer when the current gesture manipulates the // area directly under the pointer. mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE); break; case PointerGesture::SWIPE: case PointerGesture::FREEFORM: // Fade the pointer when the current gesture manipulates a different // area and there are spots to guide the user experience. if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) { mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); } else { mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE); } break; } // Send events! int32_t metaState = getContext()->getGlobalMetaState(); int32_t buttonState = mCurrentButtonState; // Update last coordinates of pointers that have moved so that we observe the new // pointer positions at the same time as other pointers that have just gone up. bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG || mPointerGesture.currentGestureMode == PointerGesture::PRESS || mPointerGesture.currentGestureMode == PointerGesture::SWIPE || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM; bool moveNeeded = false; if (down && !cancelPreviousGesture && !finishPreviousGesture && !mPointerGesture.lastGestureIdBits.isEmpty() && !mPointerGesture.currentGestureIdBits.isEmpty()) { BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value & mPointerGesture.lastGestureIdBits.value); moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties, mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex, mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex, movedGestureIdBits); if (buttonState != mLastButtonState) { moveNeeded = true; } } // Send motion events for all pointers that went up or were canceled. BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits); if (!dispatchedGestureIdBits.isEmpty()) { if (cancelPreviousGesture) { dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0, mPointerGesture.downTime); dispatchedGestureIdBits.clear(); } else { BitSet32 upGestureIdBits; if (finishPreviousGesture) { upGestureIdBits = dispatchedGestureIdBits; } else { upGestureIdBits.value = dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value; } while (!upGestureIdBits.isEmpty()) { uint32_t id = upGestureIdBits.clearFirstMarkedBit(); dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0, 0, mPointerGesture.downTime); dispatchedGestureIdBits.clearBit(id); } } } // Send motion events for all pointers that moved. if (moveNeeded) { dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.currentGestureProperties, mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0, mPointerGesture.downTime); } // Send motion events for all pointers that went down. if (down) { BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value & ~dispatchedGestureIdBits.value); while (!downGestureIdBits.isEmpty()) { uint32_t id = downGestureIdBits.clearFirstMarkedBit(); dispatchedGestureIdBits.markBit(id); if (dispatchedGestureIdBits.count() == 1) { mPointerGesture.downTime = when; } dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, buttonState, 0, mPointerGesture.currentGestureProperties, mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0, 0, mPointerGesture.downTime); } } // Send motion events for hover. if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) { dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.currentGestureProperties, mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex, mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime); } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) { // Synthesize a hover move event after all pointers go up to indicate that // the pointer is hovering again even if the user is not currently touching // the touch pad. This ensures that a view will receive a fresh hover enter // event after a tap. float x, y; mPointerController->getPosition(&x, &y); PointerProperties pointerProperties; pointerProperties.clear(); pointerProperties.id = 0; pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER; PointerCoords pointerCoords; pointerCoords.clear(); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, mViewport.displayId, 1, &pointerProperties, &pointerCoords, 0, 0, mPointerGesture.downTime); getListener()->notifyMotion(&args); } // Update state. mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode; if (!down) { mPointerGesture.lastGestureIdBits.clear(); } else { mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits; for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) { uint32_t id = idBits.clearFirstMarkedBit(); uint32_t index = mPointerGesture.currentGestureIdToIndex[id]; mPointerGesture.lastGestureProperties[index].copyFrom( mPointerGesture.currentGestureProperties[index]); mPointerGesture.lastGestureCoords[index].copyFrom( mPointerGesture.currentGestureCoords[index]); mPointerGesture.lastGestureIdToIndex[id] = index; } } } void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) { // Cancel previously dispatches pointers. if (!mPointerGesture.lastGestureIdBits.isEmpty()) { int32_t metaState = getContext()->getGlobalMetaState(); int32_t buttonState = mCurrentButtonState; dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1, 0, 0, mPointerGesture.downTime); } // Reset the current pointer gesture. mPointerGesture.reset(); mPointerVelocityControl.reset(); // Remove any current spots. if (mPointerController != NULL) { mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); mPointerController->clearSpots(); } } bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) { *outCancelPreviousGesture = false; *outFinishPreviousGesture = false; // Handle TAP timeout. if (isTimeout) { #if DEBUG_GESTURES ALOGD("Gestures: Processing timeout"); #endif if (mPointerGesture.lastGestureMode == PointerGesture::TAP) { if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) { // The tap/drag timeout has not yet expired. getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval); } else { // The tap is finished. #if DEBUG_GESTURES ALOGD("Gestures: TAP finished"); #endif *outFinishPreviousGesture = true; mPointerGesture.activeGestureId = -1; mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL; mPointerGesture.currentGestureIdBits.clear(); mPointerVelocityControl.reset(); return true; } } // We did not handle this timeout. return false; } const uint32_t currentFingerCount = mCurrentFingerIdBits.count(); const uint32_t lastFingerCount = mLastFingerIdBits.count(); // Update the velocity tracker. { VelocityTracker::Position positions[MAX_POINTERS]; uint32_t count = 0; for (BitSet32 idBits(mCurrentFingerIdBits); !idBits.isEmpty(); count++) { uint32_t id = idBits.clearFirstMarkedBit(); const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id); positions[count].x = pointer.x * mPointerXMovementScale; positions[count].y = pointer.y * mPointerYMovementScale; } mPointerGesture.velocityTracker.addMovement(when, mCurrentFingerIdBits, positions); } // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning // to NEUTRAL, then we should not generate tap event. if (mPointerGesture.lastGestureMode != PointerGesture::HOVER && mPointerGesture.lastGestureMode != PointerGesture::TAP && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) { mPointerGesture.resetTap(); } // Pick a new active touch id if needed. // Choose an arbitrary pointer that just went down, if there is one. // Otherwise choose an arbitrary remaining pointer. // This guarantees we always have an active touch id when there is at least one pointer. // We keep the same active touch id for as long as possible. bool activeTouchChanged = false; int32_t lastActiveTouchId = mPointerGesture.activeTouchId; int32_t activeTouchId = lastActiveTouchId; if (activeTouchId < 0) { if (!mCurrentFingerIdBits.isEmpty()) { activeTouchChanged = true; activeTouchId = mPointerGesture.activeTouchId = mCurrentFingerIdBits.firstMarkedBit(); mPointerGesture.firstTouchTime = when; } } else if (!mCurrentFingerIdBits.hasBit(activeTouchId)) { activeTouchChanged = true; if (!mCurrentFingerIdBits.isEmpty()) { activeTouchId = mPointerGesture.activeTouchId = mCurrentFingerIdBits.firstMarkedBit(); } else { activeTouchId = mPointerGesture.activeTouchId = -1; } } // Determine whether we are in quiet time. bool isQuietTime = false; if (activeTouchId < 0) { mPointerGesture.resetQuietTime(); } else { isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval; if (!isQuietTime) { if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS || mPointerGesture.lastGestureMode == PointerGesture::SWIPE || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) && currentFingerCount < 2) { // Enter quiet time when exiting swipe or freeform state. // This is to prevent accidentally entering the hover state and flinging the // pointer when finishing a swipe and there is still one pointer left onscreen. isQuietTime = true; } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG && currentFingerCount >= 2 && !isPointerDown(mCurrentButtonState)) { // Enter quiet time when releasing the button and there are still two or more // fingers down. This may indicate that one finger was used to press the button // but it has not gone up yet. isQuietTime = true; } if (isQuietTime) { mPointerGesture.quietTime = when; } } } // Switch states based on button and pointer state. if (isQuietTime) { // Case 1: Quiet time. (QUIET) #if DEBUG_GESTURES ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f); #endif if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) { *outFinishPreviousGesture = true; } mPointerGesture.activeGestureId = -1; mPointerGesture.currentGestureMode = PointerGesture::QUIET; mPointerGesture.currentGestureIdBits.clear(); mPointerVelocityControl.reset(); } else if (isPointerDown(mCurrentButtonState)) { // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG) // The pointer follows the active touch point. // Emit DOWN, MOVE, UP events at the pointer location. // // Only the active touch matters; other fingers are ignored. This policy helps // to handle the case where the user places a second finger on the touch pad // to apply the necessary force to depress an integrated button below the surface. // We don't want the second finger to be delivered to applications. // // For this to work well, we need to make sure to track the pointer that is really // active. If the user first puts one finger down to click then adds another // finger to drag then the active pointer should switch to the finger that is // being dragged. #if DEBUG_GESTURES ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, " "currentFingerCount=%d", activeTouchId, currentFingerCount); #endif // Reset state when just starting. if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) { *outFinishPreviousGesture = true; mPointerGesture.activeGestureId = 0; } // Switch pointers if needed. // Find the fastest pointer and follow it. if (activeTouchId >= 0 && currentFingerCount > 1) { int32_t bestId = -1; float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed; for (BitSet32 idBits(mCurrentFingerIdBits); !idBits.isEmpty(); ) { uint32_t id = idBits.clearFirstMarkedBit(); float vx, vy; if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) { float speed = hypotf(vx, vy); if (speed > bestSpeed) { bestId = id; bestSpeed = speed; } } } if (bestId >= 0 && bestId != activeTouchId) { mPointerGesture.activeTouchId = activeTouchId = bestId; activeTouchChanged = true; #if DEBUG_GESTURES ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, " "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed); #endif } } if (activeTouchId >= 0 && mLastFingerIdBits.hasBit(activeTouchId)) { const RawPointerData::Pointer& currentPointer = mCurrentRawPointerData.pointerForId(activeTouchId); const RawPointerData::Pointer& lastPointer = mLastRawPointerData.pointerForId(activeTouchId); float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale; float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale; rotateDelta(mSurfaceOrientation, &deltaX, &deltaY); mPointerVelocityControl.move(when, &deltaX, &deltaY); // Move the pointer using a relative motion. // When using spots, the click will occur at the position of the anchor // spot and all other spots will move there. mPointerController->move(deltaX, deltaY); } else { mPointerVelocityControl.reset(); } float x, y; mPointerController->getPosition(&x, &y); mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG; mPointerGesture.currentGestureIdBits.clear(); mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId); mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0; mPointerGesture.currentGestureProperties[0].clear(); mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId; mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER; mPointerGesture.currentGestureCoords[0].clear(); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f); } else if (currentFingerCount == 0) { // Case 3. No fingers down and button is not pressed. (NEUTRAL) if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) { *outFinishPreviousGesture = true; } // Watch for taps coming out of HOVER or TAP_DRAG mode. // Checking for taps after TAP_DRAG allows us to detect double-taps. bool tapped = false; if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) && lastFingerCount == 1) { if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) { float x, y; mPointerController->getPosition(&x, &y); if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) { #if DEBUG_GESTURES ALOGD("Gestures: TAP"); #endif mPointerGesture.tapUpTime = when; getContext()->requestTimeoutAtTime(when + mConfig.pointerGestureTapDragInterval); mPointerGesture.activeGestureId = 0; mPointerGesture.currentGestureMode = PointerGesture::TAP; mPointerGesture.currentGestureIdBits.clear(); mPointerGesture.currentGestureIdBits.markBit( mPointerGesture.activeGestureId); mPointerGesture.currentGestureIdToIndex[ mPointerGesture.activeGestureId] = 0; mPointerGesture.currentGestureProperties[0].clear(); mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId; mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER; mPointerGesture.currentGestureCoords[0].clear(); mPointerGesture.currentGestureCoords[0].setAxisValue( AMOTION_EVENT_AXIS_X, mPointerGesture.tapX); mPointerGesture.currentGestureCoords[0].setAxisValue( AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY); mPointerGesture.currentGestureCoords[0].setAxisValue( AMOTION_EVENT_AXIS_PRESSURE, 1.0f); tapped = true; } else { #if DEBUG_GESTURES ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX, y - mPointerGesture.tapY); #endif } } else { #if DEBUG_GESTURES if (mPointerGesture.tapDownTime != LLONG_MIN) { ALOGD("Gestures: Not a TAP, %0.3fms since down", (when - mPointerGesture.tapDownTime) * 0.000001f); } else { ALOGD("Gestures: Not a TAP, incompatible mode transitions"); } #endif } } mPointerVelocityControl.reset(); if (!tapped) { #if DEBUG_GESTURES ALOGD("Gestures: NEUTRAL"); #endif mPointerGesture.activeGestureId = -1; mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL; mPointerGesture.currentGestureIdBits.clear(); } } else if (currentFingerCount == 1) { // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG) // The pointer follows the active touch point. // When in HOVER, emit HOVER_MOVE events at the pointer location. // When in TAP_DRAG, emit MOVE events at the pointer location. ALOG_ASSERT(activeTouchId >= 0); mPointerGesture.currentGestureMode = PointerGesture::HOVER; if (mPointerGesture.lastGestureMode == PointerGesture::TAP) { if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) { float x, y; mPointerController->getPosition(&x, &y); if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) { mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG; } else { #if DEBUG_GESTURES ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX, y - mPointerGesture.tapY); #endif } } else { #if DEBUG_GESTURES ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up", (when - mPointerGesture.tapUpTime) * 0.000001f); #endif } } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) { mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG; } if (mLastFingerIdBits.hasBit(activeTouchId)) { const RawPointerData::Pointer& currentPointer = mCurrentRawPointerData.pointerForId(activeTouchId); const RawPointerData::Pointer& lastPointer = mLastRawPointerData.pointerForId(activeTouchId); float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale; float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale; rotateDelta(mSurfaceOrientation, &deltaX, &deltaY); mPointerVelocityControl.move(when, &deltaX, &deltaY); // Move the pointer using a relative motion. // When using spots, the hover or drag will occur at the position of the anchor spot. mPointerController->move(deltaX, deltaY); } else { mPointerVelocityControl.reset(); } bool down; if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) { #if DEBUG_GESTURES ALOGD("Gestures: TAP_DRAG"); #endif down = true; } else { #if DEBUG_GESTURES ALOGD("Gestures: HOVER"); #endif if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) { *outFinishPreviousGesture = true; } mPointerGesture.activeGestureId = 0; down = false; } float x, y; mPointerController->getPosition(&x, &y); mPointerGesture.currentGestureIdBits.clear(); mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId); mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0; mPointerGesture.currentGestureProperties[0].clear(); mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId; mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER; mPointerGesture.currentGestureCoords[0].clear(); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f); if (lastFingerCount == 0 && currentFingerCount != 0) { mPointerGesture.resetTap(); mPointerGesture.tapDownTime = when; mPointerGesture.tapX = x; mPointerGesture.tapY = y; } } else { // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM) // We need to provide feedback for each finger that goes down so we cannot wait // for the fingers to move before deciding what to do. // // The ambiguous case is deciding what to do when there are two fingers down but they // have not moved enough to determine whether they are part of a drag or part of a // freeform gesture, or just a press or long-press at the pointer location. // // When there are two fingers we start with the PRESS hypothesis and we generate a // down at the pointer location. // // When the two fingers move enough or when additional fingers are added, we make // a decision to transition into SWIPE or FREEFORM mode accordingly. ALOG_ASSERT(activeTouchId >= 0); bool settled = when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval; if (mPointerGesture.lastGestureMode != PointerGesture::PRESS && mPointerGesture.lastGestureMode != PointerGesture::SWIPE && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) { *outFinishPreviousGesture = true; } else if (!settled && currentFingerCount > lastFingerCount) { // Additional pointers have gone down but not yet settled. // Reset the gesture. #if DEBUG_GESTURES ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, " "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval - when) * 0.000001f); #endif *outCancelPreviousGesture = true; } else { // Continue previous gesture. mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode; } if (*outFinishPreviousGesture || *outCancelPreviousGesture) { mPointerGesture.currentGestureMode = PointerGesture::PRESS; mPointerGesture.activeGestureId = 0; mPointerGesture.referenceIdBits.clear(); mPointerVelocityControl.reset(); // Use the centroid and pointer location as the reference points for the gesture. #if DEBUG_GESTURES ALOGD("Gestures: Using centroid as reference for MULTITOUCH, " "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval - when) * 0.000001f); #endif mCurrentRawPointerData.getCentroidOfTouchingPointers( &mPointerGesture.referenceTouchX, &mPointerGesture.referenceTouchY); mPointerController->getPosition(&mPointerGesture.referenceGestureX, &mPointerGesture.referenceGestureY); } // Clear the reference deltas for fingers not yet included in the reference calculation. for (BitSet32 idBits(mCurrentFingerIdBits.value & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) { uint32_t id = idBits.clearFirstMarkedBit(); mPointerGesture.referenceDeltas[id].dx = 0; mPointerGesture.referenceDeltas[id].dy = 0; } mPointerGesture.referenceIdBits = mCurrentFingerIdBits; // Add delta for all fingers and calculate a common movement delta. float commonDeltaX = 0, commonDeltaY = 0; BitSet32 commonIdBits(mLastFingerIdBits.value & mCurrentFingerIdBits.value); for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) { bool first = (idBits == commonIdBits); uint32_t id = idBits.clearFirstMarkedBit(); const RawPointerData::Pointer& cpd = mCurrentRawPointerData.pointerForId(id); const RawPointerData::Pointer& lpd = mLastRawPointerData.pointerForId(id); PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id]; delta.dx += cpd.x - lpd.x; delta.dy += cpd.y - lpd.y; if (first) { commonDeltaX = delta.dx; commonDeltaY = delta.dy; } else { commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx); commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy); } } // Consider transitions from PRESS to SWIPE or MULTITOUCH. if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) { float dist[MAX_POINTER_ID + 1]; int32_t distOverThreshold = 0; for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) { uint32_t id = idBits.clearFirstMarkedBit(); PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id]; dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale); if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) { distOverThreshold += 1; } } // Only transition when at least two pointers have moved further than // the minimum distance threshold. if (distOverThreshold >= 2) { if (currentFingerCount > 2) { // There are more than two pointers, switch to FREEFORM. #if DEBUG_GESTURES ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2", currentFingerCount); #endif *outCancelPreviousGesture = true; mPointerGesture.currentGestureMode = PointerGesture::FREEFORM; } else { // There are exactly two pointers. BitSet32 idBits(mCurrentFingerIdBits); uint32_t id1 = idBits.clearFirstMarkedBit(); uint32_t id2 = idBits.firstMarkedBit(); const RawPointerData::Pointer& p1 = mCurrentRawPointerData.pointerForId(id1); const RawPointerData::Pointer& p2 = mCurrentRawPointerData.pointerForId(id2); float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y); if (mutualDistance > mPointerGestureMaxSwipeWidth) { // There are two pointers but they are too far apart for a SWIPE, // switch to FREEFORM. #if DEBUG_GESTURES ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f", mutualDistance, mPointerGestureMaxSwipeWidth); #endif *outCancelPreviousGesture = true; mPointerGesture.currentGestureMode = PointerGesture::FREEFORM; } else { // There are two pointers. Wait for both pointers to start moving // before deciding whether this is a SWIPE or FREEFORM gesture. float dist1 = dist[id1]; float dist2 = dist[id2]; if (dist1 >= mConfig.pointerGestureMultitouchMinDistance && dist2 >= mConfig.pointerGestureMultitouchMinDistance) { // Calculate the dot product of the displacement vectors. // When the vectors are oriented in approximately the same direction, // the angle betweeen them is near zero and the cosine of the angle // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2). PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1]; PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2]; float dx1 = delta1.dx * mPointerXZoomScale; float dy1 = delta1.dy * mPointerYZoomScale; float dx2 = delta2.dx * mPointerXZoomScale; float dy2 = delta2.dy * mPointerYZoomScale; float dot = dx1 * dx2 + dy1 * dy2; float cosine = dot / (dist1 * dist2); // denominator always > 0 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) { // Pointers are moving in the same direction. Switch to SWIPE. #if DEBUG_GESTURES ALOGD("Gestures: PRESS transitioned to SWIPE, " "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, " "cosine %0.3f >= %0.3f", dist1, mConfig.pointerGestureMultitouchMinDistance, dist2, mConfig.pointerGestureMultitouchMinDistance, cosine, mConfig.pointerGestureSwipeTransitionAngleCosine); #endif mPointerGesture.currentGestureMode = PointerGesture::SWIPE; } else { // Pointers are moving in different directions. Switch to FREEFORM. #if DEBUG_GESTURES ALOGD("Gestures: PRESS transitioned to FREEFORM, " "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, " "cosine %0.3f < %0.3f", dist1, mConfig.pointerGestureMultitouchMinDistance, dist2, mConfig.pointerGestureMultitouchMinDistance, cosine, mConfig.pointerGestureSwipeTransitionAngleCosine); #endif *outCancelPreviousGesture = true; mPointerGesture.currentGestureMode = PointerGesture::FREEFORM; } } } } } } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) { // Switch from SWIPE to FREEFORM if additional pointers go down. // Cancel previous gesture. if (currentFingerCount > 2) { #if DEBUG_GESTURES ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2", currentFingerCount); #endif *outCancelPreviousGesture = true; mPointerGesture.currentGestureMode = PointerGesture::FREEFORM; } } // Move the reference points based on the overall group motion of the fingers // except in PRESS mode while waiting for a transition to occur. if (mPointerGesture.currentGestureMode != PointerGesture::PRESS && (commonDeltaX || commonDeltaY)) { for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) { uint32_t id = idBits.clearFirstMarkedBit(); PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id]; delta.dx = 0; delta.dy = 0; } mPointerGesture.referenceTouchX += commonDeltaX; mPointerGesture.referenceTouchY += commonDeltaY; commonDeltaX *= mPointerXMovementScale; commonDeltaY *= mPointerYMovementScale; rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY); mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY); mPointerGesture.referenceGestureX += commonDeltaX; mPointerGesture.referenceGestureY += commonDeltaY; } // Report gestures. if (mPointerGesture.currentGestureMode == PointerGesture::PRESS || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) { // PRESS or SWIPE mode. #if DEBUG_GESTURES ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d," "activeGestureId=%d, currentTouchPointerCount=%d", activeTouchId, mPointerGesture.activeGestureId, currentFingerCount); #endif ALOG_ASSERT(mPointerGesture.activeGestureId >= 0); mPointerGesture.currentGestureIdBits.clear(); mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId); mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0; mPointerGesture.currentGestureProperties[0].clear(); mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId; mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER; mPointerGesture.currentGestureCoords[0].clear(); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f); } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) { // FREEFORM mode. #if DEBUG_GESTURES ALOGD("Gestures: FREEFORM activeTouchId=%d," "activeGestureId=%d, currentTouchPointerCount=%d", activeTouchId, mPointerGesture.activeGestureId, currentFingerCount); #endif ALOG_ASSERT(mPointerGesture.activeGestureId >= 0); mPointerGesture.currentGestureIdBits.clear(); BitSet32 mappedTouchIdBits; BitSet32 usedGestureIdBits; if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) { // Initially, assign the active gesture id to the active touch point // if there is one. No other touch id bits are mapped yet. if (!*outCancelPreviousGesture) { mappedTouchIdBits.markBit(activeTouchId); usedGestureIdBits.markBit(mPointerGesture.activeGestureId); mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] = mPointerGesture.activeGestureId; } else { mPointerGesture.activeGestureId = -1; } } else { // Otherwise, assume we mapped all touches from the previous frame. // Reuse all mappings that are still applicable. mappedTouchIdBits.value = mLastFingerIdBits.value & mCurrentFingerIdBits.value; usedGestureIdBits = mPointerGesture.lastGestureIdBits; // Check whether we need to choose a new active gesture id because the // current went went up. for (BitSet32 upTouchIdBits(mLastFingerIdBits.value & ~mCurrentFingerIdBits.value); !upTouchIdBits.isEmpty(); ) { uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit(); uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId]; if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) { mPointerGesture.activeGestureId = -1; break; } } } #if DEBUG_GESTURES ALOGD("Gestures: FREEFORM follow up " "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, " "activeGestureId=%d", mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId); #endif BitSet32 idBits(mCurrentFingerIdBits); for (uint32_t i = 0; i < currentFingerCount; i++) { uint32_t touchId = idBits.clearFirstMarkedBit(); uint32_t gestureId; if (!mappedTouchIdBits.hasBit(touchId)) { gestureId = usedGestureIdBits.markFirstUnmarkedBit(); mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId; #if DEBUG_GESTURES ALOGD("Gestures: FREEFORM " "new mapping for touch id %d -> gesture id %d", touchId, gestureId); #endif } else { gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId]; #if DEBUG_GESTURES ALOGD("Gestures: FREEFORM " "existing mapping for touch id %d -> gesture id %d", touchId, gestureId); #endif } mPointerGesture.currentGestureIdBits.markBit(gestureId); mPointerGesture.currentGestureIdToIndex[gestureId] = i; const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(touchId); float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale; float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale; rotateDelta(mSurfaceOrientation, &deltaX, &deltaY); mPointerGesture.currentGestureProperties[i].clear(); mPointerGesture.currentGestureProperties[i].id = gestureId; mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER; mPointerGesture.currentGestureCoords[i].clear(); mPointerGesture.currentGestureCoords[i].setAxisValue( AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX); mPointerGesture.currentGestureCoords[i].setAxisValue( AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY); mPointerGesture.currentGestureCoords[i].setAxisValue( AMOTION_EVENT_AXIS_PRESSURE, 1.0f); } if (mPointerGesture.activeGestureId < 0) { mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit(); #if DEBUG_GESTURES ALOGD("Gestures: FREEFORM new " "activeGestureId=%d", mPointerGesture.activeGestureId); #endif } } } mPointerController->setButtonState(mCurrentButtonState); #if DEBUG_GESTURES ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, " "currentGestureMode=%d, currentGestureIdBits=0x%08x, " "lastGestureMode=%d, lastGestureIdBits=0x%08x", toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture), mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value, mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value); for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) { uint32_t id = idBits.clearFirstMarkedBit(); uint32_t index = mPointerGesture.currentGestureIdToIndex[id]; const PointerProperties& properties = mPointerGesture.currentGestureProperties[index]; const PointerCoords& coords = mPointerGesture.currentGestureCoords[index]; ALOGD(" currentGesture[%d]: index=%d, toolType=%d, " "x=%0.3f, y=%0.3f, pressure=%0.3f", id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X), coords.getAxisValue(AMOTION_EVENT_AXIS_Y), coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)); } for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) { uint32_t id = idBits.clearFirstMarkedBit(); uint32_t index = mPointerGesture.lastGestureIdToIndex[id]; const PointerProperties& properties = mPointerGesture.lastGestureProperties[index]; const PointerCoords& coords = mPointerGesture.lastGestureCoords[index]; ALOGD(" lastGesture[%d]: index=%d, toolType=%d, " "x=%0.3f, y=%0.3f, pressure=%0.3f", id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X), coords.getAxisValue(AMOTION_EVENT_AXIS_Y), coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)); } #endif return true; } void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) { mPointerSimple.currentCoords.clear(); mPointerSimple.currentProperties.clear(); bool down, hovering; if (!mCurrentStylusIdBits.isEmpty()) { uint32_t id = mCurrentStylusIdBits.firstMarkedBit(); uint32_t index = mCurrentCookedPointerData.idToIndex[id]; float x = mCurrentCookedPointerData.pointerCoords[index].getX(); float y = mCurrentCookedPointerData.pointerCoords[index].getY(); mPointerController->setPosition(x, y); hovering = mCurrentCookedPointerData.hoveringIdBits.hasBit(id); down = !hovering; mPointerController->getPosition(&x, &y); mPointerSimple.currentCoords.copyFrom(mCurrentCookedPointerData.pointerCoords[index]); mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x); mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); mPointerSimple.currentProperties.id = 0; mPointerSimple.currentProperties.toolType = mCurrentCookedPointerData.pointerProperties[index].toolType; } else { down = false; hovering = false; } dispatchPointerSimple(when, policyFlags, down, hovering); } void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) { abortPointerSimple(when, policyFlags); } void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) { mPointerSimple.currentCoords.clear(); mPointerSimple.currentProperties.clear(); bool down, hovering; if (!mCurrentMouseIdBits.isEmpty()) { uint32_t id = mCurrentMouseIdBits.firstMarkedBit(); uint32_t currentIndex = mCurrentRawPointerData.idToIndex[id]; if (mLastMouseIdBits.hasBit(id)) { uint32_t lastIndex = mCurrentRawPointerData.idToIndex[id]; float deltaX = (mCurrentRawPointerData.pointers[currentIndex].x - mLastRawPointerData.pointers[lastIndex].x) * mPointerXMovementScale; float deltaY = (mCurrentRawPointerData.pointers[currentIndex].y - mLastRawPointerData.pointers[lastIndex].y) * mPointerYMovementScale; rotateDelta(mSurfaceOrientation, &deltaX, &deltaY); mPointerVelocityControl.move(when, &deltaX, &deltaY); mPointerController->move(deltaX, deltaY); } else { mPointerVelocityControl.reset(); } down = isPointerDown(mCurrentButtonState); hovering = !down; float x, y; mPointerController->getPosition(&x, &y); mPointerSimple.currentCoords.copyFrom( mCurrentCookedPointerData.pointerCoords[currentIndex]); mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x); mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, hovering ? 0.0f : 1.0f); mPointerSimple.currentProperties.id = 0; mPointerSimple.currentProperties.toolType = mCurrentCookedPointerData.pointerProperties[currentIndex].toolType; } else { mPointerVelocityControl.reset(); down = false; hovering = false; } dispatchPointerSimple(when, policyFlags, down, hovering); } void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) { abortPointerSimple(when, policyFlags); mPointerVelocityControl.reset(); } void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down, bool hovering) { int32_t metaState = getContext()->getGlobalMetaState(); if (mPointerController != NULL) { if (down || hovering) { mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER); mPointerController->clearSpots(); mPointerController->setButtonState(mCurrentButtonState); mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE); } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) { mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); } } if (mPointerSimple.down && !down) { mPointerSimple.down = false; // Send up. NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_UP, 0, metaState, mLastButtonState, 0, mViewport.displayId, 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime); getListener()->notifyMotion(&args); } if (mPointerSimple.hovering && !hovering) { mPointerSimple.hovering = false; // Send hover exit. NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, metaState, mLastButtonState, 0, mViewport.displayId, 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime); getListener()->notifyMotion(&args); } if (down) { if (!mPointerSimple.down) { mPointerSimple.down = true; mPointerSimple.downTime = when; // Send down. NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, metaState, mCurrentButtonState, 0, mViewport.displayId, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime); getListener()->notifyMotion(&args); } // Send move. NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, metaState, mCurrentButtonState, 0, mViewport.displayId, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime); getListener()->notifyMotion(&args); } if (hovering) { if (!mPointerSimple.hovering) { mPointerSimple.hovering = true; // Send hover enter. NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, metaState, mCurrentButtonState, 0, mViewport.displayId, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime); getListener()->notifyMotion(&args); } // Send hover move. NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, mCurrentButtonState, 0, mViewport.displayId, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime); getListener()->notifyMotion(&args); } if (mCurrentRawVScroll || mCurrentRawHScroll) { float vscroll = mCurrentRawVScroll; float hscroll = mCurrentRawHScroll; mWheelYVelocityControl.move(when, NULL, &vscroll); mWheelXVelocityControl.move(when, &hscroll, NULL); // Send scroll. PointerCoords pointerCoords; pointerCoords.copyFrom(mPointerSimple.currentCoords); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll); NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, metaState, mCurrentButtonState, 0, mViewport.displayId, 1, &mPointerSimple.currentProperties, &pointerCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime); getListener()->notifyMotion(&args); } // Save state. if (down || hovering) { mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords); mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties); } else { mPointerSimple.reset(); } } void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) { mPointerSimple.currentCoords.clear(); mPointerSimple.currentProperties.clear(); dispatchPointerSimple(when, policyFlags, false, false); } void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source, int32_t action, int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags, const PointerProperties* properties, const PointerCoords* coords, const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime) { PointerCoords pointerCoords[MAX_POINTERS]; PointerProperties pointerProperties[MAX_POINTERS]; uint32_t pointerCount = 0; while (!idBits.isEmpty()) { uint32_t id = idBits.clearFirstMarkedBit(); uint32_t index = idToIndex[id]; pointerProperties[pointerCount].copyFrom(properties[index]); pointerCoords[pointerCount].copyFrom(coords[index]); if (changedId >= 0 && id == uint32_t(changedId)) { action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; } pointerCount += 1; } ALOG_ASSERT(pointerCount != 0); if (changedId >= 0 && pointerCount == 1) { // Replace initial down and final up action. // We can compare the action without masking off the changed pointer index // because we know the index is 0. if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) { action = AMOTION_EVENT_ACTION_DOWN; } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) { action = AMOTION_EVENT_ACTION_UP; } else { // Can't happen. ALOG_ASSERT(false); } } NotifyMotionArgs args(when, getDeviceId(), source, policyFlags, action, flags, metaState, buttonState, edgeFlags, mViewport.displayId, pointerCount, pointerProperties, pointerCoords, xPrecision, yPrecision, downTime); // resize touch coords for (dual_display && freescale_disabled) // rw.vout.scale: off/freescale_disabled, on/freescale_enabled char prop_dual[PROPERTY_VALUE_MAX]; if (!mPadmouseStatus && property_get("ro.vout.dualdisplay2", prop_dual, "false") && (strcmp(prop_dual, "true") == 0) && (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP || action == AMOTION_EVENT_ACTION_MOVE)) { bool resize_touch = false; if (strncmp(g_dmode_str, "panel", 5) != 0) { char prop[PROPERTY_VALUE_MAX]; if (property_get("rw.vout.scale", prop, "on") && strcmp(prop, "off") == 0) { resize_touch = true; } } if (resize_touch) { int x = 0, y = 0, w = 0, h = 0; if(sscanf(g_daxis_str, "%d %d %d %d", &x,&y,&w,&h) > 0) { int ww = w, hh = h; if (strncmp(g_dmode_str, "1080p", 5) == 0) { ww = 1920; hh = 1080; } else if (strncmp(g_dmode_str, "720p", 4) == 0) { ww = 1280; hh = 720; } else if (strncmp(g_dmode_str, "480p", 4) == 0) { ww = 720; hh = 480; } if (ww >= w) x = (ww - w) / 2; if (hh >= h) y = (hh - h) / 2; for (uint32_t i = 0; i < args.pointerCount; i++) { float coords_x = args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X); float coords_y = args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y); if (ww >= w && hh >= h) { //1024*600 < 1280*720 coords_x = coords_x*(w + 2*x)/w; coords_y = coords_y*(h + 2*y)/h; coords_x = (coords_x - x)*(w + 2*x)/w; coords_y = (coords_y - y)*(h + 2*y)/h; coords_x = coords_x*w/(w + 2*x); coords_y = coords_y*h/(h + 2*y); } else if (ww >= w && hh < h) { //1024*768 > 1280*720 coords_x = coords_x*(w + 2*x)/w; coords_y = coords_y*hh/h; coords_x = (coords_x - x)*(w + 2*x)/w; coords_y = (coords_y - 0)*hh/h; coords_x = coords_x*w/(w + 2*x); coords_y = coords_y*h/hh; } else { //1024*600 > 720*480 coords_x = coords_x*ww/w; coords_y = coords_y*hh/h; coords_x = (coords_x - 0)*ww/w; coords_y = (coords_y - 0)*hh/h; coords_x = coords_x*w/ww; coords_y = coords_y*h/hh; } args.pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, coords_x); args.pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, coords_y); } } } } getListener()->notifyMotion(&args); } bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties, const PointerCoords* inCoords, const uint32_t* inIdToIndex, PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex, BitSet32 idBits) const { bool changed = false; while (!idBits.isEmpty()) { uint32_t id = idBits.clearFirstMarkedBit(); uint32_t inIndex = inIdToIndex[id]; uint32_t outIndex = outIdToIndex[id]; const PointerProperties& curInProperties = inProperties[inIndex]; const PointerCoords& curInCoords = inCoords[inIndex]; PointerProperties& curOutProperties = outProperties[outIndex]; PointerCoords& curOutCoords = outCoords[outIndex]; if (curInProperties != curOutProperties) { curOutProperties.copyFrom(curInProperties); changed = true; } if (curInCoords != curOutCoords) { curOutCoords.copyFrom(curInCoords); changed = true; } } return changed; } void TouchInputMapper::fadePointer() { if (mPointerController != NULL) { mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); } } void TouchInputMapper::setTvOutStatus(bool enabled){ bool padmouseStatus = mPadmouseStatus; if( mTvOutStatus != enabled){ mTvOutStatus = enabled; String8 padmouseString; if(mTvOutStatus){ if ( !getDevice()->getConfiguration().tryGetProperty(String8("touch.tvout.padmouse"), padmouseString) || padmouseString == "true" ) { //mouse style: pointer or spot mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER; padmouseStatus = true; mHdimiCfgChange = true; ALOGW(" tvout touch screen set to padmouse mode "); } } else if(mPadmouseStatus){ configureParameters(); padmouseStatus = false; } if(mPadmouseStatus != padmouseStatus){ mPadmouseStatus = padmouseStatus; nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC); bool outReset = true; configureSurface(now, &outReset); reset(now); } } // dual display char prop_dual[PROPERTY_VALUE_MAX]; if (property_get("ro.vout.dualdisplay2", prop_dual, "false") && (strcmp(prop_dual, "true") == 0)) { int fd_dmode = -1; memset(g_dmode_str,0,32); if((fd_dmode = open("/sys/class/display/mode", O_RDONLY)) >= 0) { int ret_len = read(fd_dmode, g_dmode_str, sizeof(g_dmode_str)); close(fd_dmode); } else { ALOGE("open /sys/class/display/mode."); } int fd_daxis = -1; memset(g_daxis_str,0,32); if((fd_daxis = open("/sys/class/display/axis", O_RDONLY)) >= 0) { int ret_len = read(fd_daxis, g_daxis_str, sizeof(g_daxis_str)); close(fd_daxis); } else { ALOGE("open /sys/class/display/mode."); } } } bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) { return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue; } const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit( int32_t x, int32_t y) { size_t numVirtualKeys = mVirtualKeys.size(); for (size_t i = 0; i < numVirtualKeys; i++) { const VirtualKey& virtualKey = mVirtualKeys[i]; #if DEBUG_VIRTUAL_KEYS ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, " "left=%d, top=%d, right=%d, bottom=%d", x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom); #endif if (virtualKey.isHit(x, y)) { return & virtualKey; } } return NULL; } void TouchInputMapper::assignPointerIds() { uint32_t currentPointerCount = mCurrentRawPointerData.pointerCount; uint32_t lastPointerCount = mLastRawPointerData.pointerCount; mCurrentRawPointerData.clearIdBits(); if (currentPointerCount == 0) { // No pointers to assign. return; } if (lastPointerCount == 0) { // All pointers are new. for (uint32_t i = 0; i < currentPointerCount; i++) { uint32_t id = i; mCurrentRawPointerData.pointers[i].id = id; mCurrentRawPointerData.idToIndex[id] = i; mCurrentRawPointerData.markIdBit(id, mCurrentRawPointerData.isHovering(i)); } return; } if (currentPointerCount == 1 && lastPointerCount == 1 && mCurrentRawPointerData.pointers[0].toolType == mLastRawPointerData.pointers[0].toolType) { uint32_t id; if (!mCurrentRawPointerData.isHovering(0) && !mLastRawPointerData.hoveringIdBits.isEmpty()) { // 1 finger released and touching again. Should be safe to // reset to id 0. id = 0; } else { // Only one pointer and no change in count so it must have the same id as before. id = mLastRawPointerData.pointers[0].id; } mCurrentRawPointerData.pointers[0].id = id; mCurrentRawPointerData.idToIndex[id] = 0; mCurrentRawPointerData.markIdBit(id, mCurrentRawPointerData.isHovering(0)); return; } // General case. // We build a heap of squared euclidean distances between current and last pointers // associated with the current and last pointer indices. Then, we find the best // match (by distance) for each current pointer. // The pointers must have the same tool type but it is possible for them to // transition from hovering to touching or vice-versa while retaining the same id. PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS]; uint32_t heapSize = 0; for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount; currentPointerIndex++) { for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount; lastPointerIndex++) { const RawPointerData::Pointer& currentPointer = mCurrentRawPointerData.pointers[currentPointerIndex]; const RawPointerData::Pointer& lastPointer = mLastRawPointerData.pointers[lastPointerIndex]; if (currentPointer.toolType == lastPointer.toolType) { int64_t deltaX = currentPointer.x - lastPointer.x; int64_t deltaY = currentPointer.y - lastPointer.y; uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY); // Insert new element into the heap (sift up). heap[heapSize].currentPointerIndex = currentPointerIndex; heap[heapSize].lastPointerIndex = lastPointerIndex; heap[heapSize].distance = distance; heapSize += 1; } } } // Heapify for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) { startIndex -= 1; for (uint32_t parentIndex = startIndex; ;) { uint32_t childIndex = parentIndex * 2 + 1; if (childIndex >= heapSize) { break; } if (childIndex + 1 < heapSize && heap[childIndex + 1].distance < heap[childIndex].distance) { childIndex += 1; } if (heap[parentIndex].distance <= heap[childIndex].distance) { break; } swap(heap[parentIndex], heap[childIndex]); parentIndex = childIndex; } } #if DEBUG_POINTER_ASSIGNMENT ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize); for (size_t i = 0; i < heapSize; i++) { ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld", i, heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance); } #endif // Pull matches out by increasing order of distance. // To avoid reassigning pointers that have already been matched, the loop keeps track // of which last and current pointers have been matched using the matchedXXXBits variables. // It also tracks the used pointer id bits. BitSet32 matchedLastBits(0); BitSet32 matchedCurrentBits(0); BitSet32 usedIdBits(0); bool first = true; for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) { while (heapSize > 0) { if (first) { // The first time through the loop, we just consume the root element of // the heap (the one with smallest distance). first = false; } else { // Previous iterations consumed the root element of the heap. // Pop root element off of the heap (sift down). heap[0] = heap[heapSize]; for (uint32_t parentIndex = 0; ;) { uint32_t childIndex = parentIndex * 2 + 1; if (childIndex >= heapSize) { break; } if (childIndex + 1 < heapSize && heap[childIndex + 1].distance < heap[childIndex].distance) { childIndex += 1; } if (heap[parentIndex].distance <= heap[childIndex].distance) { break; } swap(heap[parentIndex], heap[childIndex]); parentIndex = childIndex; } #if DEBUG_POINTER_ASSIGNMENT ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize); for (size_t i = 0; i < heapSize; i++) { ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld", i, heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance); } #endif } heapSize -= 1; uint32_t currentPointerIndex = heap[0].currentPointerIndex; if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched uint32_t lastPointerIndex = heap[0].lastPointerIndex; if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched matchedCurrentBits.markBit(currentPointerIndex); matchedLastBits.markBit(lastPointerIndex); uint32_t id = mLastRawPointerData.pointers[lastPointerIndex].id; mCurrentRawPointerData.pointers[currentPointerIndex].id = id; mCurrentRawPointerData.idToIndex[id] = currentPointerIndex; mCurrentRawPointerData.markIdBit(id, mCurrentRawPointerData.isHovering(currentPointerIndex)); usedIdBits.markBit(id); #if DEBUG_POINTER_ASSIGNMENT ALOGD("assignPointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld", lastPointerIndex, currentPointerIndex, id, heap[0].distance); #endif break; } } // Assign fresh ids to pointers that were not matched in the process. for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) { uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit(); uint32_t id = usedIdBits.markFirstUnmarkedBit(); mCurrentRawPointerData.pointers[currentPointerIndex].id = id; mCurrentRawPointerData.idToIndex[id] = currentPointerIndex; mCurrentRawPointerData.markIdBit(id, mCurrentRawPointerData.isHovering(currentPointerIndex)); #if DEBUG_POINTER_ASSIGNMENT ALOGD("assignPointerIds - assigned: cur=%d, id=%d", currentPointerIndex, id); #endif } } int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) { if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) { return AKEY_STATE_VIRTUAL; } size_t numVirtualKeys = mVirtualKeys.size(); for (size_t i = 0; i < numVirtualKeys; i++) { const VirtualKey& virtualKey = mVirtualKeys[i]; if (virtualKey.keyCode == keyCode) { return AKEY_STATE_UP; } } return AKEY_STATE_UNKNOWN; } int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) { return AKEY_STATE_VIRTUAL; } size_t numVirtualKeys = mVirtualKeys.size(); for (size_t i = 0; i < numVirtualKeys; i++) { const VirtualKey& virtualKey = mVirtualKeys[i]; if (virtualKey.scanCode == scanCode) { return AKEY_STATE_UP; } } return AKEY_STATE_UNKNOWN; } bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) { size_t numVirtualKeys = mVirtualKeys.size(); for (size_t i = 0; i < numVirtualKeys; i++) { const VirtualKey& virtualKey = mVirtualKeys[i]; for (size_t i = 0; i < numCodes; i++) { if (virtualKey.keyCode == keyCodes[i]) { outFlags[i] = 1; } } } return true; } // --- SingleTouchInputMapper --- SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) : TouchInputMapper(device) { } SingleTouchInputMapper::~SingleTouchInputMapper() { } void SingleTouchInputMapper::reset(nsecs_t when) { mSingleTouchMotionAccumulator.reset(getDevice()); TouchInputMapper::reset(when); } void SingleTouchInputMapper::process(const RawEvent* rawEvent) { TouchInputMapper::process(rawEvent); mSingleTouchMotionAccumulator.process(rawEvent); } void SingleTouchInputMapper::syncTouch(nsecs_t when, bool* outHavePointerIds) { if (mTouchButtonAccumulator.isToolActive()) { mCurrentRawPointerData.pointerCount = 1; mCurrentRawPointerData.idToIndex[0] = 0; bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE && (mTouchButtonAccumulator.isHovering() || (mRawPointerAxes.pressure.valid && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0)); mCurrentRawPointerData.markIdBit(0, isHovering); RawPointerData::Pointer& outPointer = mCurrentRawPointerData.pointers[0]; outPointer.id = 0; outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX(); outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY(); outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure(); outPointer.touchMajor = 0; outPointer.touchMinor = 0; outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth(); outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth(); outPointer.orientation = 0; outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance(); outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX(); outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY(); outPointer.toolType = mTouchButtonAccumulator.getToolType(); if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) { outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER; } outPointer.isHovering = isHovering; } } void SingleTouchInputMapper::configureRawPointerAxes() { TouchInputMapper::configureRawPointerAxes(); getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x); getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y); getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure); getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor); getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance); getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX); getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY); } bool SingleTouchInputMapper::hasStylus() const { return mTouchButtonAccumulator.hasStylus(); } // --- MultiTouchInputMapper --- MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) : TouchInputMapper(device) { } MultiTouchInputMapper::~MultiTouchInputMapper() { } void MultiTouchInputMapper::reset(nsecs_t when) { mMultiTouchMotionAccumulator.reset(getDevice()); mPointerIdBits.clear(); TouchInputMapper::reset(when); } void MultiTouchInputMapper::process(const RawEvent* rawEvent) { TouchInputMapper::process(rawEvent); mMultiTouchMotionAccumulator.process(rawEvent); } void MultiTouchInputMapper::syncTouch(nsecs_t when, bool* outHavePointerIds) { size_t inCount = mMultiTouchMotionAccumulator.getSlotCount(); size_t outCount = 0; BitSet32 newPointerIdBits; for (size_t inIndex = 0; inIndex < inCount; inIndex++) { const MultiTouchMotionAccumulator::Slot* inSlot = mMultiTouchMotionAccumulator.getSlot(inIndex); if (!inSlot->isInUse()) { continue; } if (outCount >= MAX_POINTERS) { #if DEBUG_POINTERS ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; " "ignoring the rest.", getDeviceName().string(), MAX_POINTERS); #endif break; // too many fingers! } RawPointerData::Pointer& outPointer = mCurrentRawPointerData.pointers[outCount]; outPointer.x = inSlot->getX(); outPointer.y = inSlot->getY(); outPointer.pressure = inSlot->getPressure(); outPointer.touchMajor = inSlot->getTouchMajor(); outPointer.touchMinor = inSlot->getTouchMinor(); outPointer.toolMajor = inSlot->getToolMajor(); outPointer.toolMinor = inSlot->getToolMinor(); outPointer.orientation = inSlot->getOrientation(); outPointer.distance = inSlot->getDistance(); outPointer.tiltX = 0; outPointer.tiltY = 0; outPointer.toolType = inSlot->getToolType(); if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) { outPointer.toolType = mTouchButtonAccumulator.getToolType(); if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) { outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER; } } bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE && (mTouchButtonAccumulator.isHovering() || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0)); outPointer.isHovering = isHovering; // Assign pointer id using tracking id if available. if (*outHavePointerIds) { int32_t trackingId = inSlot->getTrackingId(); int32_t id = -1; if (trackingId >= 0) { for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) { uint32_t n = idBits.clearFirstMarkedBit(); if (mPointerTrackingIdMap[n] == trackingId) { id = n; } } if (id < 0 && !mPointerIdBits.isFull()) { id = mPointerIdBits.markFirstUnmarkedBit(); mPointerTrackingIdMap[id] = trackingId; } } if (id < 0) { *outHavePointerIds = false; mCurrentRawPointerData.clearIdBits(); newPointerIdBits.clear(); } else { outPointer.id = id; mCurrentRawPointerData.idToIndex[id] = outCount; mCurrentRawPointerData.markIdBit(id, isHovering); newPointerIdBits.markBit(id); } } outCount += 1; } mCurrentRawPointerData.pointerCount = outCount; mPointerIdBits = newPointerIdBits; mMultiTouchMotionAccumulator.finishSync(); } void MultiTouchInputMapper::configureRawPointerAxes() { TouchInputMapper::configureRawPointerAxes(); getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x); getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y); getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor); getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor); getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor); getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor); getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation); getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure); getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance); getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId); getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot); if (mRawPointerAxes.trackingId.valid && mRawPointerAxes.slot.valid && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) { size_t slotCount = mRawPointerAxes.slot.maxValue + 1; if (slotCount > MAX_SLOTS) { ALOGW("MultiTouch Device %s reported %d slots but the framework " "only supports a maximum of %d slots at this time.", getDeviceName().string(), slotCount, MAX_SLOTS); slotCount = MAX_SLOTS; } mMultiTouchMotionAccumulator.configure(getDevice(), slotCount, true /*usingSlotsProtocol*/); } else { mMultiTouchMotionAccumulator.configure(getDevice(), MAX_POINTERS, false /*usingSlotsProtocol*/); } } bool MultiTouchInputMapper::hasStylus() const { return mMultiTouchMotionAccumulator.hasStylus() || mTouchButtonAccumulator.hasStylus(); } // --- JoystickInputMapper --- JoystickInputMapper::JoystickInputMapper(InputDevice* device) : InputMapper(device) { } JoystickInputMapper::~JoystickInputMapper() { } uint32_t JoystickInputMapper::getSources() { return AINPUT_SOURCE_JOYSTICK; } void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) { InputMapper::populateDeviceInfo(info); for (size_t i = 0; i < mAxes.size(); i++) { const Axis& axis = mAxes.valueAt(i); addMotionRange(axis.axisInfo.axis, axis, info); if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) { addMotionRange(axis.axisInfo.highAxis, axis, info); } } } void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis, InputDeviceInfo* info) { info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK, axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution); /* In order to ease the transition for developers from using the old axes * to the newer, more semantically correct axes, we'll continue to register * the old axes as duplicates of their corresponding new ones. */ int32_t compatAxis = getCompatAxis(axisId); if (compatAxis >= 0) { info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK, axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution); } } /* A mapping from axes the joystick actually has to the axes that should be * artificially created for compatibility purposes. * Returns -1 if no compatibility axis is needed. */ int32_t JoystickInputMapper::getCompatAxis(int32_t axis) { switch(axis) { case AMOTION_EVENT_AXIS_LTRIGGER: return AMOTION_EVENT_AXIS_BRAKE; case AMOTION_EVENT_AXIS_RTRIGGER: return AMOTION_EVENT_AXIS_GAS; } return -1; } void JoystickInputMapper::dump(String8& dump) { dump.append(INDENT2 "Joystick Input Mapper:\n"); dump.append(INDENT3 "Axes:\n"); size_t numAxes = mAxes.size(); for (size_t i = 0; i < numAxes; i++) { const Axis& axis = mAxes.valueAt(i); const char* label = getAxisLabel(axis.axisInfo.axis); if (label) { dump.appendFormat(INDENT4 "%s", label); } else { dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis); } if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) { label = getAxisLabel(axis.axisInfo.highAxis); if (label) { dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue); } else { dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis, axis.axisInfo.splitValue); } } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) { dump.append(" (invert)"); } dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n", axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution); dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, " "highScale=%0.5f, highOffset=%0.5f\n", axis.scale, axis.offset, axis.highScale, axis.highOffset); dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, " "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n", mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue, axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution); } } void JoystickInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) { InputMapper::configure(when, config, changes); if (!changes) { // first time only // Collect all axes. for (int32_t abs = 0; abs <= ABS_MAX; abs++) { if (!(getAbsAxisUsage(abs, getDevice()->getClasses()) & INPUT_DEVICE_CLASS_JOYSTICK)) { continue; // axis must be claimed by a different device } RawAbsoluteAxisInfo rawAxisInfo; getAbsoluteAxisInfo(abs, &rawAxisInfo); if (rawAxisInfo.valid) { // Map axis. AxisInfo axisInfo; bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo); if (!explicitlyMapped) { // Axis is not explicitly mapped, will choose a generic axis later. axisInfo.mode = AxisInfo::MODE_NORMAL; axisInfo.axis = -1; } // Apply flat override. int32_t rawFlat = axisInfo.flatOverride < 0 ? rawAxisInfo.flat : axisInfo.flatOverride; // Calculate scaling factors and limits. Axis axis; if (axisInfo.mode == AxisInfo::MODE_SPLIT) { float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue); float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue); axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, scale, 0.0f, highScale, 0.0f, 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale, rawAxisInfo.resolution * scale); } else if (isCenteredAxis(axisInfo.axis)) { float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue); float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale; axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, scale, offset, scale, offset, -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale, rawAxisInfo.resolution * scale); } else { float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue); axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, scale, 0.0f, scale, 0.0f, 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale, rawAxisInfo.resolution * scale); } // To eliminate noise while the joystick is at rest, filter out small variations // in axis values up front. axis.filter = axis.flat * 0.25f; mAxes.add(abs, axis); } } // If there are too many axes, start dropping them. // Prefer to keep explicitly mapped axes. if (mAxes.size() > PointerCoords::MAX_AXES) { ALOGI("Joystick '%s' has %d axes but the framework only supports a maximum of %d.", getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES); pruneAxes(true); pruneAxes(false); } // Assign generic axis ids to remaining axes. int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1; size_t numAxes = mAxes.size(); for (size_t i = 0; i < numAxes; i++) { Axis& axis = mAxes.editValueAt(i); if (axis.axisInfo.axis < 0) { while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16 && haveAxis(nextGenericAxisId)) { nextGenericAxisId += 1; } if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) { axis.axisInfo.axis = nextGenericAxisId; nextGenericAxisId += 1; } else { ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids " "have already been assigned to other axes.", getDeviceName().string(), mAxes.keyAt(i)); mAxes.removeItemsAt(i--); numAxes -= 1; } } } } } bool JoystickInputMapper::haveAxis(int32_t axisId) { size_t numAxes = mAxes.size(); for (size_t i = 0; i < numAxes; i++) { const Axis& axis = mAxes.valueAt(i); if (axis.axisInfo.axis == axisId || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT && axis.axisInfo.highAxis == axisId)) { return true; } } return false; } void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) { size_t i = mAxes.size(); while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) { if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) { continue; } ALOGI("Discarding joystick '%s' axis %d because there are too many axes.", getDeviceName().string(), mAxes.keyAt(i)); mAxes.removeItemsAt(i); } } bool JoystickInputMapper::isCenteredAxis(int32_t axis) { switch (axis) { case AMOTION_EVENT_AXIS_X: case AMOTION_EVENT_AXIS_Y: case AMOTION_EVENT_AXIS_Z: case AMOTION_EVENT_AXIS_RX: case AMOTION_EVENT_AXIS_RY: case AMOTION_EVENT_AXIS_RZ: case AMOTION_EVENT_AXIS_HAT_X: case AMOTION_EVENT_AXIS_HAT_Y: case AMOTION_EVENT_AXIS_ORIENTATION: case AMOTION_EVENT_AXIS_RUDDER: case AMOTION_EVENT_AXIS_WHEEL: return true; default: return false; } } void JoystickInputMapper::reset(nsecs_t when) { // Recenter all axes. size_t numAxes = mAxes.size(); for (size_t i = 0; i < numAxes; i++) { Axis& axis = mAxes.editValueAt(i); axis.resetValue(); } InputMapper::reset(when); } void JoystickInputMapper::process(const RawEvent* rawEvent) { switch (rawEvent->type) { case EV_ABS: { ssize_t index = mAxes.indexOfKey(rawEvent->code); if (index >= 0) { Axis& axis = mAxes.editValueAt(index); float newValue, highNewValue; switch (axis.axisInfo.mode) { case AxisInfo::MODE_INVERT: newValue = (axis.rawAxisInfo.maxValue - rawEvent->value) * axis.scale + axis.offset; highNewValue = 0.0f; break; case AxisInfo::MODE_SPLIT: if (rawEvent->value < axis.axisInfo.splitValue) { newValue = (axis.axisInfo.splitValue - rawEvent->value) * axis.scale + axis.offset; highNewValue = 0.0f; } else if (rawEvent->value > axis.axisInfo.splitValue) { newValue = 0.0f; highNewValue = (rawEvent->value - axis.axisInfo.splitValue) * axis.highScale + axis.highOffset; } else { newValue = 0.0f; highNewValue = 0.0f; } break; default: newValue = rawEvent->value * axis.scale + axis.offset; highNewValue = 0.0f; break; } axis.newValue = newValue; axis.highNewValue = highNewValue; } break; } case EV_SYN: switch (rawEvent->code) { case SYN_REPORT: sync(rawEvent->when, false /*force*/); break; } break; } } void JoystickInputMapper::sync(nsecs_t when, bool force) { if (!filterAxes(force)) { return; } int32_t metaState = mContext->getGlobalMetaState(); int32_t buttonState = 0; PointerProperties pointerProperties; pointerProperties.clear(); pointerProperties.id = 0; pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN; PointerCoords pointerCoords; pointerCoords.clear(); size_t numAxes = mAxes.size(); for (size_t i = 0; i < numAxes; i++) { const Axis& axis = mAxes.valueAt(i); setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue); if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) { setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis, axis.highCurrentValue); } } // Moving a joystick axis should not wake the device because joysticks can // be fairly noisy even when not in use. On the other hand, pushing a gamepad // button will likely wake the device. // TODO: Use the input device configuration to control this behavior more finely. uint32_t policyFlags = 0; NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, ADISPLAY_ID_NONE, 1, &pointerProperties, &pointerCoords, 0, 0, 0); getListener()->notifyMotion(&args); } void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords, int32_t axis, float value) { pointerCoords->setAxisValue(axis, value); /* In order to ease the transition for developers from using the old axes * to the newer, more semantically correct axes, we'll continue to produce * values for the old axes as mirrors of the value of their corresponding * new axes. */ int32_t compatAxis = getCompatAxis(axis); if (compatAxis >= 0) { pointerCoords->setAxisValue(compatAxis, value); } } bool JoystickInputMapper::filterAxes(bool force) { bool atLeastOneSignificantChange = force; size_t numAxes = mAxes.size(); for (size_t i = 0; i < numAxes; i++) { Axis& axis = mAxes.editValueAt(i); if (force || hasValueChangedSignificantly(axis.filter, axis.newValue, axis.currentValue, axis.min, axis.max)) { axis.currentValue = axis.newValue; atLeastOneSignificantChange = true; } if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) { if (force || hasValueChangedSignificantly(axis.filter, axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) { axis.highCurrentValue = axis.highNewValue; atLeastOneSignificantChange = true; } } } return atLeastOneSignificantChange; } bool JoystickInputMapper::hasValueChangedSignificantly( float filter, float newValue, float currentValue, float min, float max) { if (newValue != currentValue) { // Filter out small changes in value unless the value is converging on the axis // bounds or center point. This is intended to reduce the amount of information // sent to applications by particularly noisy joysticks (such as PS3). if (fabs(newValue - currentValue) > filter || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min) || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max) || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) { return true; } } return false; } bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange( float filter, float newValue, float currentValue, float thresholdValue) { float newDistance = fabs(newValue - thresholdValue); if (newDistance < filter) { float oldDistance = fabs(currentValue - thresholdValue); if (newDistance < oldDistance) { return true; } } return false; } } // namespace android
[ "wl5201314_@126.com" ]
wl5201314_@126.com
cccf48f490f421ac49b75c17882585a4ac773adf
6a47b5f04c74ed475b632e6561a675135e3baa80
/test/mock/core/consensus/grandpa/voting_round_mock.hpp
95491367d64505b9e253114c5311c213513d4665
[ "Apache-2.0" ]
permissive
DiamondNetwork/kagome
3f89afcc7432c7047b2ce2a3ef6bf7a6ee878423
c018130a5595eeb69e439ea4695c7b7db1c7ee43
refs/heads/master
2023-08-05T01:19:31.739959
2021-10-08T14:01:45
2021-10-08T14:01:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,847
hpp
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef KAGOME_CONSENSUS_GRANDPA_VOTINGROUNDMOCK #define KAGOME_CONSENSUS_GRANDPA_VOTINGROUNDMOCK #include "consensus/grandpa/voting_round.hpp" #include <gmock/gmock.h> namespace kagome::consensus::grandpa { class VotingRoundMock : public VotingRound { public: MOCK_CONST_METHOD0(roundNumber, RoundNumber()); MOCK_CONST_METHOD0(voterSetId, MembershipCounter()); MOCK_CONST_METHOD0(completable, bool()); MOCK_CONST_METHOD0(finalizable, bool()); MOCK_CONST_METHOD0(lastFinalizedBlock, BlockInfo()); MOCK_METHOD0(bestPrevoteCandidate, BlockInfo()); MOCK_METHOD0(bestPrecommitCandidate, BlockInfo()); MOCK_METHOD0(bestFinalCandidate, BlockInfo()); MOCK_CONST_METHOD0(finalizedBlock, boost::optional<BlockInfo>()); MOCK_CONST_METHOD0(state, MovableRoundState()); MOCK_METHOD0(play, void()); MOCK_METHOD0(end, void()); MOCK_METHOD0(doProposal, void()); MOCK_METHOD0(doPrevote, void()); MOCK_METHOD0(doPrecommit, void()); MOCK_METHOD0(doFinalize, void()); MOCK_METHOD1(doCatchUpRequest, void(const libp2p::peer::PeerId &)); MOCK_METHOD1(doCatchUpResponse, void(const libp2p::peer::PeerId &)); MOCK_METHOD2(onProposal, void(const SignedMessage &, Propagation)); MOCK_METHOD2(onPrevote, bool(const SignedMessage &, Propagation)); MOCK_METHOD2(onPrecommit, bool(const SignedMessage &, Propagation)); MOCK_METHOD2(update, void(bool, bool)); MOCK_METHOD2(applyJustification, outcome::result<void>(const BlockInfo &, const GrandpaJustification &)); MOCK_METHOD0(attemptToFinalizeRound, void()); }; } // namespace kagome::consensus::grandpa #endif // KAGOME_CONSENSUS_GRANDPA_VOTINGROUNDMOCK
[ "noreply@github.com" ]
DiamondNetwork.noreply@github.com
aa3cd6fdd4626ba635625988403aabc85c8d84b5
5bbeacc09bcb942112cb506f3bfce3ef4269e9b0
/ElliotEngine/src/ElliotEngineView.h
f3651cfd6775c27848e53c8d9dceef8d6235345b
[]
no_license
schaed/finance
cf62f898cf31e8c0060a57a3bed06d1acea44ca9
64a2d91f01f6abf39b9d1399e47a1f16a529fe41
refs/heads/master
2021-01-13T03:14:15.898981
2017-05-25T14:34:15
2017-05-25T14:34:15
77,621,789
0
3
null
null
null
null
UTF-8
C++
false
false
4,051
h
// ElliotEngineView.h : interface of the CElliotEngineView class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_ELLIOTENGINEVIEW_H__6022A139_5151_45DC_95EB_202FEBC1912E__INCLUDED_) #define AFX_ELLIOTENGINEVIEW_H__6022A139_5151_45DC_95EB_202FEBC1912E__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "FinanceChart.h" #include "./ChartDirector/mfcdemo/mfcdemo/ChartViewer.h" class CElliotEngineView : public CFormView { protected: // create from serialization only CElliotEngineView(); DECLARE_DYNCREATE(CElliotEngineView) public: //{{AFX_DATA(CElliotEngineView) enum { IDD = IDC_STATIC2 }; CButton m_ShowMonowaves; CScrollBar m_ChartScrollBar; CScrollBar m_WaveScroll; CEdit m_MovAvg2; CEdit m_MovAvg1; CButton m_MinorVGrid; CButton m_MajorVGrid; CButton m_LogScale; CButton m_HGrid; CButton m_Volume; CComboBox m_Indicator4; CComboBox m_Indicator3; CComboBox m_Indicator2; CComboBox m_Indicator1; CComboBox m_ChartType; CComboBox m_ChartSize; CComboBox m_Band; CComboBox m_AvgType2; CComboBox m_AvgType1; CComboBox m_TimeRange; CChartViewer m_Chart; //}}AFX_DATA // Attributes public: CElliotEngineDoc* GetDocument(); // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CElliotEngineView) public: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support virtual void OnInitialUpdate(); // called first time after construct virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnPrint(CDC* pDC, CPrintInfo* pInfo); //}}AFX_VIRTUAL // Implementation public: virtual ~CElliotEngineView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: //Start date of the data points (excluding extra leading points) double m_startDate; //End date of the data points. double m_endDate; //The resolution of the data points (in sec) int m_resolution; //The timeStamps of the data points. It can include data points that are before the //startDate (extra leading points) to facilitate moving averages computation. int m_noOfPoints; int m_leadingExtraPoints; int m_offsetIntoRawArrays; int m_noOfRawPoints; double *m_timeStamps; double *m_volData; //The volume values. double *m_highData; //The high values. double *m_lowData; //The low values. double *m_openData; //The open values. double *m_closeData; //The close values. int m_avgPeriod1; int m_avgPeriod2; virtual void ReloadRawData(); virtual void GetData(int requestedDuration, int requestedExtraPoints); virtual void UpdateChart(CChartViewer *viewer); // Generated message map functions protected: //{{AFX_MSG(CElliotEngineView) afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnSelectChange(); afx_msg void OnTextChange(); afx_msg void OnSelchangeChartsize(); afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnResolutionChange(); //}}AFX_MSG DECLARE_MESSAGE_MAP() int DrawWave(const ETime& startDate, double startPrice, const ETime& endDate, double endPrice, double* pts); int AddMonoWaves(XYChart* pMainChart); }; #ifndef _DEBUG // debug version in ElliotEngineView.cpp inline CElliotEngineDoc* CElliotEngineView::GetDocument() { return (CElliotEngineDoc*)m_pDocument; } #endif ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_ELLIOTENGINEVIEW_H__6022A139_5151_45DC_95EB_202FEBC1912E__INCLUDED_)
[ "schae@cern.ch" ]
schae@cern.ch
8af99273daa74669ab403ad115c8de1c9536af78
64bd2dbc0d2c8f794905e3c0c613d78f0648eefc
/Cpp/SDK/OnlineSubsystem_functions.cpp
9029d704aa120b6cfb0bb84cfc22c3472c36c7a9
[]
no_license
zanzo420/SoT-Insider-SDK
37232fa74866031dd655413837813635e93f3692
874cd4f4f8af0c58667c4f7c871d2a60609983d3
refs/heads/main
2023-06-18T15:48:54.547869
2021-07-19T06:02:00
2021-07-19T06:02:00
387,354,587
1
2
null
null
null
null
UTF-8
C++
false
false
1,816
cpp
// Name: SoT Insider, Version: 1.103.4306.0 #include "../pch.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- // Function OnlineSubsystem.TurnBasedMatchInterface.OnMatchReceivedTurn // (Event, Public, BlueprintEvent) // Parameters: // struct FString Match (Parm, ZeroConstructor, HasGetValueTypeHash) // bool bDidBecomeActive (Parm, ZeroConstructor, IsPlainOldData, NoDestructor) void UTurnBasedMatchInterface::OnMatchReceivedTurn(const struct FString& Match, bool bDidBecomeActive) { static auto fn = UObject::FindObject<UFunction>("Function OnlineSubsystem.TurnBasedMatchInterface.OnMatchReceivedTurn"); UTurnBasedMatchInterface_OnMatchReceivedTurn_Params params; params.Match = Match; params.bDidBecomeActive = bDidBecomeActive; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function OnlineSubsystem.TurnBasedMatchInterface.OnMatchEnded // (Event, Public, BlueprintEvent) // Parameters: // struct FString Match (Parm, ZeroConstructor, HasGetValueTypeHash) void UTurnBasedMatchInterface::OnMatchEnded(const struct FString& Match) { static auto fn = UObject::FindObject<UFunction>("Function OnlineSubsystem.TurnBasedMatchInterface.OnMatchEnded"); UTurnBasedMatchInterface_OnMatchEnded_Params params; params.Match = Match; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
44590293364cce2f65278bb659654bd3a991cebe
32411cce4a91a3a4b693b963af77fcb83b3c0764
/src/gruppe3/src/laser.cpp
1f322b2fad74245b624353b9ad81a410e867643e
[]
no_license
IchBinZeyuan/Robotic_CPP
2d1279898ab7e348a3d2dca7bd08626f56c9c562
099592490b583c39cece3b7c7abd1a85e3b74063
refs/heads/master
2020-05-02T07:04:19.241923
2019-03-26T19:44:58
2019-03-26T19:44:58
177,808,938
0
1
null
null
null
null
UTF-8
C++
false
false
1,178
cpp
#include <ros/ros.h> #include <iostream> #include <sensor_msgs/LaserScan.h> using namespace std; double datalaser[360] = {0} ; //void AutoExp::processLaserScan(const sensor_msgs::LaserScan::ConstPtr& scan){ //ROS_INFO("laser messages:",scan->ranges[]); //} //int main(int argc,char** argv) //{ //ros::init(argc,argv,"ladar"); //ros::NodeHandle nh; //ros::Subscriber sub = nh.subscribe<sensor_msgs/LaserScan>("/scan",10,&AutoExp::processLaserScan,this); //ros::spin(); //return 0; //} void get_laser_callback(const sensor_msgs::LaserScan &laser){ //count << "ROS Ladar Data"<<endl; //count << "Front:"<<laser.ranges[719] << endl; //count << "----------------------"<< endl; //double datalaser[360] = {0} ; int i = 0 ; while ( i<360){ datalaser[i] = laser.ranges[i] ; i++; } //ROS_INFO_STREAM("Front:"<<datalaser[2]); } int main (int argc, char **argv) { ros::init(argc,argv,"laser"); ros::NodeHandle n ; ros::Subscriber laser_sub = n.subscribe("/lidarscan",1000,get_laser_callback); //ROS_INFO_STREAM("Front:"<<datalaser[2]); ros::Rate rate(10); int i = 0; while(ros::ok()){ ROS_INFO_STREAM("Front:"<<datalaser[200]); ros::spinOnce(); rate.sleep(); i++; } return 0; }
[ "zeyuan.zhang@tum.de" ]
zeyuan.zhang@tum.de
73d6f0566dd9864b3423a486eae3bba868582991
1dd825971ed4ec0193445dc9ed72d10618715106
/examples/extended/polarisation/Pol01/src/StepMaxMessenger.cc
6a1c8aca373acdc93d2b880e393e8510731ad2e4
[]
no_license
gfh16/Geant4
4d442e5946eefc855436f4df444c245af7d3aa81
d4cc6c37106ff519a77df16f8574b2fe4ad9d607
refs/heads/master
2021-06-25T22:32:21.104339
2020-11-02T13:12:01
2020-11-02T13:12:01
158,790,658
0
0
null
null
null
null
UTF-8
C++
false
false
2,991
cc
// // ******************************************************************** // * License and Disclaimer * // * * // * The Geant4 software is copyright of the Copyright Holders of * // * the Geant4 Collaboration. It is provided under the terms and * // * conditions of the Geant4 Software License, included in the file * // * LICENSE and available at http://cern.ch/geant4/license . These * // * include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GEANT4 collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the Geant4 Software license. * // ******************************************************************** // /// \file polarisation/Pol01/src/StepMaxMessenger.cc /// \brief Implementation of the StepMaxMessenger class // // $Id$ // //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... #include "StepMaxMessenger.hh" #include "StepMax.hh" #include "G4UIcmdWithADoubleAndUnit.hh" //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... StepMaxMessenger::StepMaxMessenger(StepMax* stepMax) : G4UImessenger(), fStepMax(stepMax), fStepMaxCmd(0) { fStepMaxCmd = new G4UIcmdWithADoubleAndUnit("/testem/stepMax",this); fStepMaxCmd->SetGuidance("Set max allowed step length"); fStepMaxCmd->SetParameterName("mxStep",false); fStepMaxCmd->SetRange("mxStep>0."); fStepMaxCmd->SetUnitCategory("Length"); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... StepMaxMessenger::~StepMaxMessenger() { delete fStepMaxCmd; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void StepMaxMessenger::SetNewValue(G4UIcommand* command, G4String newValue) { if (command == fStepMaxCmd) { fStepMax->SetMaxStep(fStepMaxCmd->GetNewDoubleValue(newValue));} } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
[ "gfh16@mails.tsinghua.edu.cn" ]
gfh16@mails.tsinghua.edu.cn
43134827e35602e8ae1f49eeed13910cd9028cbe
f82aa8969f093aeccc55d0724da3605185a29ae4
/templates/examples/videoexample.cpp
4a398b6e511a918f8b4aa26c8d720269c8b19da6
[]
no_license
EricMiddleton1/CPRE575-HW3
d78d0579377972357c5ec6704a45f0c7604173b2
e9fcef27e132b62ec8e141dce080907e75d41b3a
refs/heads/master
2021-03-19T17:30:06.717523
2018-02-22T09:13:08
2018-02-22T09:13:08
122,440,611
0
0
null
null
null
null
UTF-8
C++
false
false
1,638
cpp
// Headers #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/opencv.hpp> #include <iostream> using namespace cv; int main(int argc, char* argv[]) { // Load input video // If your video is in a different source folder than your code, // make sure you specify the directory correctly! VideoCapture input_cap("../../input/part1a/input1a1.avi"); // Check validity of target file if(!input_cap.isOpened()) { std::cout << "Input video not found." << std::endl; return -1; } // Set up target output video /* usage: VideoWriter(filename, encoding, framerate, Size) * in our case, cv_cap_prop_* means "get property of capture" * we want our output to have the same properties as the input! */ VideoWriter output_cap("helloworld.avi", input_cap.get(CV_CAP_PROP_FOURCC), input_cap.get(CV_CAP_PROP_FPS), Size(input_cap.get(CV_CAP_PROP_FRAME_WIDTH), input_cap.get(CV_CAP_PROP_FRAME_HEIGHT))); // Again, check validity of target output file if(!output_cap.isOpened()) { std::cout << "Could not create output file." << std::endl; return -1; } // Loop to read from input one frame at a time, write text on frame, and // copy to output video Mat frame; while(input_cap.read(frame)) { putText(frame, "Hello World!", Point(0, 50), FONT_HERSHEY_PLAIN, 1.0, Scalar(255, 255, 255)); output_cap.write(frame); } // free the capture objects from memory input_cap.release(); output_cap.release(); return 1; }
[ "ericm@iastate.edu" ]
ericm@iastate.edu
be2c5d334b998cd2228c105cdbbfea0578cd2d5b
5586d98bf5f5d3336d5ec427eaa3a2b7c6f6d9da
/Practice/lab1.cpp
bcb9a74627772df5a58aa890a2ee54ee57f99235
[]
no_license
maybeabhishek/PDC_Lab
b09a00f3b25586601084861c42bac545e87843c1
eefb0d15b5344dceb5c089e0eb8f7829155aa0a0
refs/heads/master
2022-03-29T16:09:50.853593
2019-12-24T18:48:12
2019-12-24T18:48:12
198,183,784
1
0
null
null
null
null
UTF-8
C++
false
false
992
cpp
#include<iostream> #include<omp.h> using namespace std; int main(){ int num = omp_get_max_threads(); cout<<"Num threads: "<<num<<endl; int n = 400; double a[n][n], b[n][n], c[n][n]; int i,j,k; double wtime = omp_get_wtime(); srand(time(0)); #pragma omp shared(a,b,c,n) private(i,j,k) { #pragma omp for for( i = 0; i<n;i++){ for( j=0; j<n; j++){ a[i][j] = rand()%100; } } #pragma omp for for( i = 0; i<n;i++){ for( j=0; j<n; j++){ b[i][j] = rand()%100; } } #pragma omp for schedule(static) for( i =0; i<n; i++){ for( j = 0; j<n; j++){ c[i][j] = 0.0; for(k=0; k<n; k++){ c[i][j] += a[i][k] + b[k][j]; } } } } wtime = omp_get_wtime() - wtime; cout<<endl<<"Time taken: "<<wtime<<endl; return 0; }
[ "abhishek.satapathy01@gmail.com" ]
abhishek.satapathy01@gmail.com
4af6534731eb3b414a2a55422c4c9012c768eb34
045ad86b79d87f501cfd8252ecd8cc3c1ac960dd
/DDS/Policy/QosPolicyBase.h
46c582f7f146b30c98205ca4fd62c7c5c7389f02
[ "MIT" ]
permissive
intact-software-systems/cpp-software-patterns
9513e4d988342d88c100e4d85a0e58a3dbd9909e
e463fc7eeba4946b365b5f0b2eecf3da0f4c895b
refs/heads/master
2020-04-08T08:22:25.073672
2018-11-26T14:19:49
2018-11-26T14:19:49
159,176,259
1
0
null
null
null
null
UTF-8
C++
false
false
3,151
h
/* * QosPolicy.h * * Created on: 10. july 2012 * Author: KVik */ #ifndef DDS_QosPolicy_QosPolicyBase_h_IsIncluded #define DDS_QosPolicy_QosPolicyBase_h_IsIncluded #include"DDS/CommonDefines.h" #include"DDS/Policy/PolicyKind.h" #include"DDS/Export.h" namespace DDS { namespace Policy { /** * @brief * * This class is the abstract root for all the QoS policies. * * It provides the basic mechanism for an application to specify quality of service parameters. It has an attribute name that * is used to identify uniquely each QoS policy. All concrete QosPolicy classes derive from this root and include a value * whose type depends on the concrete QoS policy. * * The type of a QosPolicy value may be atomic, such as an integer or float, or compound (a structure). Compound types are * used whenever multiple parameters must be set coherently to define a consistent value for a QosPolicy. * * Each Entity can be configured with a list of QosPolicy. However, any Entity cannot support any QosPolicy. For instance, * a DomainParticipant supports different QosPolicy than a Topic or a Publisher. * * QosPolicy can be set when the Entity is created, or modified with the set_qos method. Each QosPolicy in the list is * treated independently from the others. This approach has the advantage of being very extensible. However, there may be * cases where several policies are in conflict. Consistency checking is performed each time the policies are modified via the * set_qos operation. * * When a policy is changed after being set to a given value, it is not required that the new value be applied instantaneously; * the Service is allowed to apply it after a transition phase. In addition, some QosPolicy have immutable semantics * meaning that they can only be specified either at Entity creation time or else prior to calling the enable operation on the * Entity. * * Section 7.1.3, Supported QoS, on page 96 provides the list of all QosPolicy, their meaning, characteristics and possible * values, as well as the concrete Entity to which they apply. */ #define DEFINE_POLICY_TRAITS(NAME, ID, RXO, CHANGEABLE) \ virtual const std::string& GetPolicyName() const { \ static std::string the_name = #NAME; \ return the_name; \ } \ virtual uint32_t GetPolicyId() const { \ static uint32_t id = ID; \ return id; \ } \ virtual DDS::Policy::RequestedOfferedKind::Type GetRxO() const { \ static DDS::Policy::RequestedOfferedKind::Type rxo = RXO; \ return rxo; \ } \ virtual bool IsChangeable() const { \ static bool changeable = CHANGEABLE; \ return changeable; \ } class DLL_STATE QosPolicyBase : public NetworkLib::NetObjectBase { public: QosPolicyBase() { } virtual ~QosPolicyBase() { } virtual const std::string& GetPolicyName() const = 0; virtual uint32_t GetPolicyId() const = 0; virtual bool IsChangeable() const = 0; virtual DDS::Policy::RequestedOfferedKind::Type GetRxO() const = 0; }; }} #endif
[ "intact.software.systems@gmail.com" ]
intact.software.systems@gmail.com
98f14a305ef75ed6f3303bf0106d8fde28800cf1
98066229ed99c9c1f92fdf8915ab6a11fb8cf60f
/source/response.cpp
fa27221379bd2ea4ba3f9586bfe21484cd9762a8
[]
no_license
NickRegistered/webServer-select
4313faa3516946d5c4a2633e2a139be47014bb50
249a117c3aa80a1ae8e148450f797a3d8b78dec3
refs/heads/master
2020-05-03T20:19:16.746382
2019-04-07T02:04:10
2019-04-07T02:04:10
178,800,364
3
1
null
null
null
null
UTF-8
C++
false
false
2,498
cpp
#include "response.h" using namespace std; const map<string, string> ExtnToType = { { ".gif","image/gif\r\n" },{ ".mp3","audio/mp3\r\n" } , { ".ogg","application/ogg\r\n" },{ ".mp4","audio/mp4\r\n" } , { ".webm","video/webm\r\n" },{ ".html","text/html\r\n" }, {".ico","application/x-ico\r\n"},{ "","text/html\r\n" } }; const char* page404 = "<html><body><h1 style=\"text-align:center\">404 NotFound</h1></body></html>"; Response::Response(char* req) { int i = 0; for (;req[i] != ' ';++i) { Method[i] = req[i]; }Method[i++] = '\0';//添加结束符并跳过空格 int j = 0, k = 0; int flag = 0; for (;req[i] != ' ';++i, ++j) { URL[j] = req[i]; if (URL[j] == '/') URL[j] = '\\';//将请求中的'/'换作'\\' Extn[k] = req[i]; if (req[i] == '.')flag = 1; k += flag; }URL[j] = '\0', Extn[k] = '\0'; //如果请求根目录 if (strcmp(URL, "\\") == 0) {//默认发送html strcat(URL, "index.html"); }; } void Response::ResponseHeader(const char *filename,char* buff) { buff[0] = '\0'; FILE *fin = fopen(filename, "rb"); if (!fin) { Stat[0] = '\0'; strcat(Stat, "HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\nContent-Length: 73\r\n\r\n");//文件打开失败,写入状态信息404 strcat(buff, Stat); strcat(buff,page404);//直接写入404页面 return; } else { Stat[0] = '\0'; strcat(Stat,"HTTP/1.1 200 OK\r\n"); auto itor = ExtnToType.find(Extn); CntType[0] = '\0'; strcat(CntType, "Content-Type: "); strcat(CntType, (itor->second).c_str()); fseek(fin, 0, SEEK_END); int size = ftell(fin); fclose(fin); char num[7],tempc; int i; for (i = 0;size > 0;++i) { num[i] = size % 10 + '0'; size /= 10; }num[i--] = '\0';//添加结束符,将i指向最后一个数字 for (int j = 0;j < i;++j, --i) { tempc = num[j]; num[j] = num[i]; num[i] = tempc; } CntLen[0] = '\0'; strcat(CntLen, "Content-Length: "); strcat(CntLen, num); strcat(CntLen,"\r\n\r\n");//结束一行,结束报文 strcat(buff, Stat); strcat(buff, CntType); strcat(buff, CntLen); return; } }
[ "36127069+NickRegistered@users.noreply.github.com" ]
36127069+NickRegistered@users.noreply.github.com
ceea9ac8fd76a3d13cc8cec5831a2eed6853f85f
815ba6cc98dedf268cf66ef0a5207cfc4d3f5eb9
/mca-2.0.3/mcapi/src/mcapi_trans/mcapi_trans_sm/Fragments/mcapi_trans_smt_initialize_abl.cpp
6a4cb2a09d3222e50379304478f796b61cfc5291
[]
no_license
ke4harper/MxAPI
65b0c1fca9e58dd4670d1752c7f2a1d8f9ba78a7
fc4e2e4037cfb41360f0d0974f3142ba948d9bd7
refs/heads/master
2023-04-03T07:09:04.452807
2023-03-14T21:23:35
2023-03-14T21:23:35
185,410,427
1
0
null
2022-09-29T23:45:15
2019-05-07T13:43:25
C
UTF-8
C++
false
false
4,818
cpp
/* Copyright (c) 2012, ABB, 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 ABB, 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Node attributes { int i = 0; mcapi_node_attributes_t na = { { { 0 } } }; mcapi_uint_t attribute1 = 0; mcapi_uint_t attribute2 = 0; status = MCAPI_SUCCESS; assert(mcapi_trans_node_init_attributes(&na,&status)); assert(MCAPI_SUCCESS == status); // status not used for(i = 0; i < MAX_NUM_ATTRIBUTES; i++) { assert(MCAPI_FALSE == na.entries[i].valid); } attribute1 = MCAPI_NODE_ATTR_TYPE_REGULAR; mcapi_trans_node_set_attribute(&na,MCAPI_NODE_ATTR_TYPE,&attribute1,sizeof(mcapi_uint_t),&status); // Attribute has to fit in size of pointer (void*) assert(MCAPI_SUCCESS == status); assert(MCAPI_NODE_ATTR_TYPE_REGULAR == na.entries[MCAPI_NODE_ATTR_TYPE].attribute_d.type); assert(mcapi_trans_initialize(domain,node,&na,MCAPI_TRUE)); assert(mcapi_trans_whoami(&node,&n_index,&domain,&d_index)); assert(mcapi_db->domains[d_index].nodes[n_index].valid); // Attribute valid property not used assert(sizeof(mcapi_uint_t) == mcapi_db->domains[d_index].nodes[n_index].attributes.entries[MCAPI_NODE_ATTR_TYPE].bytes); assert(MCAPI_NODE_ATTR_TYPE_REGULAR == mcapi_db->domains[d_index].nodes[n_index].attributes.entries[MCAPI_NODE_ATTR_TYPE].attribute_d.type); mcapi_trans_node_get_attribute(domain,node,MCAPI_NODE_ATTR_TYPE,&attribute2,sizeof(mcapi_uint_t),&status); assert(MCAPI_SUCCESS == status); assert(attribute2 == attribute1); assert(mcapi_trans_finalize()); } // Runtime initialization { // One node assert(mcapi_trans_node_init_attributes(&node_attrs,&status)); assert(mcapi_trans_initialize(domain,node,&node_attrs,MCAPI_FALSE)); assert(!mcapi_db->domains[0].nodes[0].valid); assert(mcapi_trans_access_database_pre(global_rwl,MCAPI_TRUE)); mcapi_trans_start_have_lock(); assert(mcapi_trans_access_database_post(global_rwl,MCAPI_TRUE)); assert(mcapi_db->domains[0].nodes[0].valid); assert(domain == mcapi_db->domains[0].domain_id); assert(MCAPI_TRUE == mcapi_db->domains[0].valid); assert(1 == mcapi_db->domains[0].num_nodes); assert(node == mcapi_db->domains[0].nodes[0].node_num); assert(MCAPI_TRUE == mcapi_db->domains[0].nodes[0].valid); #if !(__unix__) assert(GetCurrentProcessId() == mcapi_db->domains[0].nodes[0].pid); assert((pthread_t)GetCurrentThreadId() == mcapi_db->domains[0].nodes[0].tid); #else assert(getpid() == mcapi_db->domains[0].nodes[0].pid); assert(pthread_self() == mcapi_db->domains[0].nodes[0].tid); #endif // (__unix__) assert(mcapi_trans_initialized()); assert(!mcapi_trans_initialize(domain,node,&node_attrs,MCAPI_TRUE)); // Error to initialize duplicate node on same thread assert(!mcapi_db->domains[0].nodes[0].rundown); assert(mcapi_trans_finalize()); assert(mcapi_trans_initialize(domain,node,&node_attrs,MCAPI_TRUE)); assert(!mcapi_db->domains[0].nodes[0].rundown); assert(mcapi_trans_access_database_pre(global_rwl,MCAPI_TRUE)); mcapi_trans_rundown_have_lock(); assert(mcapi_trans_access_database_post(global_rwl,MCAPI_TRUE)); assert(mcapi_db->domains[0].nodes[0].rundown); assert(mcapi_trans_finalize()); }
[ "keharper@wt.net" ]
keharper@wt.net
22588425b27fc86a53fd743533098c88593f3751
5d4753b7e463827c9540e982108de22f62435c3f
/cc/subtle/prf/streaming_prf_wrapper_test.cc
875d6747aa9d648fd878eb35d10f03ed8d0ccecf
[ "Apache-2.0" ]
permissive
thaidn/tink
8c9b65e3f3914eb54d70847c9f56853afd051dd3
2a75c1c3e4ef6aa1b6e29700bf5946b725276c95
refs/heads/master
2021-07-25T02:02:59.839232
2021-02-10T17:21:31
2021-02-10T17:22:01
337,815,957
2
0
Apache-2.0
2021-02-10T18:28:20
2021-02-10T18:28:20
null
UTF-8
C++
false
false
4,640
cc
// 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 "tink/subtle/prf/streaming_prf_wrapper.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/str_cat.h" #include "tink/util/input_stream_util.h" #include "tink/util/istream_input_stream.h" #include "tink/util/test_matchers.h" #include "tink/util/test_util.h" #include "proto/tink.pb.h" namespace crypto { namespace tink { namespace { using ::crypto::tink::test::IsOk; using ::crypto::tink::test::StatusIs; using ::google::crypto::tink::KeysetInfo; using ::google::crypto::tink::KeyStatusType; using ::google::crypto::tink::OutputPrefixType; using ::testing::Eq; using ::testing::HasSubstr; class DummyStreamingPrf : public StreamingPrf { public: explicit DummyStreamingPrf(absl::string_view name) : name_(name) {} std::unique_ptr<InputStream> ComputePrf( absl::string_view input) const override { return absl::make_unique<crypto::tink::util::IstreamInputStream>( absl::make_unique<std::stringstream>( absl::StrCat(name_.length(), ":", name_, input))); } private: std::string name_; }; TEST(AeadSetWrapperTest, WrapNullptr) { StreamingPrfWrapper wrapper; EXPECT_THAT(wrapper.Wrap(nullptr).status(), StatusIs(util::error::INVALID_ARGUMENT, HasSubstr("non-NULL"))); } TEST(KeysetDeriverWrapperTest, WrapEmpty) { EXPECT_THAT( StreamingPrfWrapper() .Wrap(absl::make_unique<PrimitiveSet<StreamingPrf>>()) .status(), StatusIs(util::error::INVALID_ARGUMENT, HasSubstr("exactly one key"))); } TEST(KeysetDeriverWrapperTest, WrapSingle) { auto prf_set = absl::make_unique<PrimitiveSet<StreamingPrf>>(); KeysetInfo::KeyInfo key_info; key_info.set_key_id(1234); key_info.set_status(KeyStatusType::ENABLED); key_info.set_output_prefix_type(OutputPrefixType::RAW); auto entry_or = prf_set->AddPrimitive( absl::make_unique<DummyStreamingPrf>("single_key"), key_info); ASSERT_THAT(entry_or.status(), IsOk()); EXPECT_THAT(prf_set->set_primary(entry_or.ValueOrDie()), IsOk()); auto wrapped_prf = StreamingPrfWrapper().Wrap(std::move(prf_set)); ASSERT_THAT(wrapped_prf.status(), IsOk()); auto prf_output = ReadBytesFromStream( 23, wrapped_prf.ValueOrDie()->ComputePrf("input_text").get()); ASSERT_THAT(prf_output.status(), IsOk()); EXPECT_THAT(prf_output.ValueOrDie(), Eq("10:single_keyinput_text")); } TEST(KeysetDeriverWrapperTest, WrapNonRaw) { auto prf_set = absl::make_unique<PrimitiveSet<StreamingPrf>>(); KeysetInfo::KeyInfo key_info; key_info.set_key_id(1234); key_info.set_status(KeyStatusType::ENABLED); key_info.set_output_prefix_type(OutputPrefixType::TINK); auto entry_or = prf_set->AddPrimitive( absl::make_unique<DummyStreamingPrf>("single_key"), key_info); ASSERT_THAT(entry_or.status(), IsOk()); EXPECT_THAT(prf_set->set_primary(entry_or.ValueOrDie()), IsOk()); EXPECT_THAT(StreamingPrfWrapper().Wrap(std::move(prf_set)).status(), StatusIs(util::error::INVALID_ARGUMENT, HasSubstr("output_prefix_type"))); } TEST(KeysetDeriverWrapperTest, WrapMultiple) { auto prf_set = absl::make_unique<PrimitiveSet<StreamingPrf>>(); KeysetInfo::KeyInfo key_info; key_info.set_key_id(1234); key_info.set_status(KeyStatusType::ENABLED); key_info.set_output_prefix_type(OutputPrefixType::RAW); auto entry_or = prf_set->AddPrimitive( absl::make_unique<DummyStreamingPrf>("single_key"), key_info); ASSERT_THAT(entry_or.status(), IsOk()); EXPECT_THAT(prf_set->set_primary(entry_or.ValueOrDie()), IsOk()); key_info.set_key_id(2345); EXPECT_THAT( prf_set ->AddPrimitive(absl::make_unique<DummyStreamingPrf>("second_key"), key_info) .status(), IsOk()); EXPECT_THAT(StreamingPrfWrapper().Wrap(std::move(prf_set)).status(), StatusIs(util::error::INVALID_ARGUMENT, HasSubstr("given set has 2 keys"))); } } // namespace } // namespace tink } // namespace crypto
[ "copybara-worker@google.com" ]
copybara-worker@google.com
8e3f2e3ab5b71a5bbc66053b5302ce944161c804
3943f4014015ae49a2c6c3c7018afd1d2119a7ed
/final_output/output_myrecur_abs_1_cp/laguerre_formula_0.9_1.1/3-6.cpp
06fb0675062f122b5c4dc02db7a92807b07d57df
[]
no_license
Cathy272272272/practicum
9fa7bfcccc23d4e40af9b647d9d98f5ada37aecf
e13ab8aa5cf5c037245b677453e14b586b10736d
refs/heads/master
2020-05-23T10:10:15.111847
2019-06-08T00:23:57
2019-06-08T00:23:57
186,689,468
0
0
null
null
null
null
UTF-8
C++
false
false
2,852
cpp
#include <iostream> #include <stdio.h> #include <assert.h> #include <math.h> extern "C" { #include "quadmath.h" } #ifndef IFT #define IFT float #endif #ifndef OFT #define OFT __float128 #endif //#include <cmath> using namespace std; //static const int k = 3; template <class T> T n_factorial(T n){ if ( n == 0 ) return 1; return n*n_factorial(n-1); } template <class T> T my_pow(T x, unsigned n){ if ( n == 0 ) return T(1.0); return x * my_pow(x, n-1); } template <class T> T my_hermite(unsigned n, T x){ if (n == 0 ) return T(1); T res(0); T cnt = n - 2*(n/2); T n_start = n_factorial(cnt); T m_start = n_factorial(n/2); T n_multiply = n_factorial(n); T neg_one = my_pow(-1, n/2); T x_start = my_pow(2*x, cnt); for ( unsigned i = n/2; i > 0; i-- ){ res += neg_one * x_start / m_start / n_start; neg_one *= (-1); x_start *= 4*x*x; m_start /= i; n_start *= (cnt+1) *(cnt+2); cnt += 2; } res += neg_one * x_start / m_start / n_start; return n_multiply * res; } template <class T> T my_laguerre(unsigned n, T x){ if (n == 0 ) return 1.0; T n_multiple = 1; T k_multiple = 1; T x_multiple = 1.0; T neg = 1.0; T res = 1.0; for ( unsigned i = 1; i <= n; i++ ){ x_multiple *= x; k_multiple *= i; n_multiple *= (n-i+1); neg *= (-1); res += neg * n_multiple / k_multiple / k_multiple * x_multiple; } return res; } template <class T> T my_legendre(unsigned n, T x){ if (n == 0 ) return 1.0; T x_half = 1.0; T n_minus_multiple = n_factorial(T(n)); T n_plus_multiple = n_minus_multiple; T k_multiple = 1; T res = 1.0; for ( unsigned i = 1; i <= n; i++ ){ n_minus_multiple /= (n-i+1); n_plus_multiple *= (n+i); k_multiple *= i; x_half *= ((x - 1.0) / 2); res += n_plus_multiple / n_minus_multiple / k_multiple / k_multiple * x_half; } return res; } int main (int argc, char *argv[]) { assert(argc == 3); char *iname = argv[1]; char *oname = argv[2]; FILE *ifile = fopen(iname, "r"); FILE *ofile = fopen(oname, "w"); assert(ifile != NULL && ofile != NULL); fseek(ifile, 0, SEEK_END); unsigned long fsize = ftell(ifile); assert(fsize == (sizeof(IFT) * 1)); fseek(ifile, 0, SEEK_SET); IFT in_x; fread(&in_x, sizeof(IFT), 1, ifile); FT rel = 0; FT x = in_x; #ifdef ORIG rel = my_laguerre(6, x + 0.0); #else rel = ( ( ( x*pow(x,3) ) * ( ( ( x*x ) *0.001389 ) + ( ( x*-0.05 ) +0.625 ) ) ) +log( ( ( exp(1.0)*pow(exp(-3.333333),pow(x,3)) ) *pow(exp(x), ( ( x*7.5 ) -6.0 ) ) ) ) ) ; #endif OFT outv = rel; fwrite(&outv, sizeof(OFT), 1, ofile); fclose(ifile); fclose(ofile); return 0; }
[ "cathyxu@Cathys-MacBook-Pro.local" ]
cathyxu@Cathys-MacBook-Pro.local
c227fd87bad21b3935bdbc6acdf59f7ab7350b41
1d68c8a01ed498a99d4797f8c845b89d4bfe92c0
/VK9-Library/CVertexDeclaration9.h
d7fdba2c283135fedb83e4800056123160f84e4c
[ "Zlib" ]
permissive
lorendias/VK9
4edd16f4defaa470e208f2e9bf7237463e86c6a1
c788b63ac307dcae5891cf19b0a11a40a0e96d82
refs/heads/master
2020-05-09T19:20:58.189090
2019-04-14T03:19:11
2019-04-14T03:19:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,582
h
#pragma once /* Copyright(c) 2016-2019 Christopher Joseph Dean Schaefer This software is provided 'as-is', without any express or implied warranty.In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions : 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software.If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <vulkan/vulkan.hpp> #include <vulkan/vk_sdk_platform.h> #include "d3d9.h" #include <vector> class CDevice9; vk::Format ConvertDeclType(D3DDECLTYPE input) noexcept; uint32_t GetTextureCount(DWORD fvf) noexcept; class CVertexDeclaration9 : public IDirect3DVertexDeclaration9 { public: CVertexDeclaration9(CDevice9* device,const D3DVERTEXELEMENT9* pVertexElements); CVertexDeclaration9(CDevice9* device, DWORD fvf); ~CVertexDeclaration9(); //Reference Counting ULONG mReferenceCount = 1; ULONG mPrivateReferenceCount = 0; ULONG PrivateAddRef(void); ULONG PrivateRelease(void); //Creation Parameters std::vector<D3DVERTEXELEMENT9> mVertexElements; DWORD mFVF = 0; //Misc uint32_t mPositionSize = 3; BOOL mIsTransformed = 0; BOOL mHasPosition=0; BOOL mHasBlendWeight = 0; BOOL mHasBlendIndices = 0; BOOL mHasNormal = 0; BOOL mHasPSize = 0; size_t mTextureCount = 0; BOOL mHasTangent = 0; BOOL mHasBinormal = 0; BOOL mHasTessfactor = 0; BOOL mHasPositionT = 0; BOOL mHasColor1=0; BOOL mHasColor2=0; BOOL mHasFog = 0; BOOL mHasDepth = 0; BOOL mHasSample = 0; std::vector<vk::VertexInputAttributeDescription> mVertexInputAttributeDescription; private: CDevice9* mDevice; public: //IUnknown virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid,void **ppv); virtual ULONG STDMETHODCALLTYPE AddRef(void); virtual ULONG STDMETHODCALLTYPE Release(void); //IDirect3DVertexDeclaration9 virtual HRESULT STDMETHODCALLTYPE GetDeclaration(D3DVERTEXELEMENT9* pDecl, UINT* pNumElements); virtual HRESULT STDMETHODCALLTYPE GetDevice(IDirect3DDevice9** ppDevice); };
[ "disks86@gmail.com" ]
disks86@gmail.com
8301e048f1a2c75efe7cd5747e94a4ffcec1c3dd
276f0b31f669b3e1e36b7e2f332c4df86aec800d
/Mateusz Machaj Connect Four Source Code/Connect Four/Game Classes/Game.h
2f9122d52e6f9cba3ae7d40c703ac402f1a95d1d
[]
no_license
mateuszmachaj/Code-Foo
c06b5c5f821ca29224fa778cf97e0ae2e44eb23d
9b4279581f580b4b625b4cc362caf48a9e858f37
refs/heads/master
2021-01-13T02:29:52.554462
2012-05-01T04:25:10
2012-05-01T04:25:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,005
h
#pragma once #include "../Framework/Graphics.h" #include "../Framework/Input.h" #include "../Framework/Audio.h" // Sprite structure typedef struct { // sprite details float width; float height; // sprite position float posX; float posY; bool visible; }Sprite; class Game { public: Game(); int Update(); void Render(); void setUp(bool multiGame, bool newGame); bool InitGame(); void Shutdown(); private: int field[6][7]; int playerPieces[7][6]; int aiPieces[7][6]; int playerTurn; int selection; Sprite redPieces[21]; Sprite bluePieces[21]; LPDIRECT3DTEXTURE9 redPiece; LPDIRECT3DTEXTURE9 bluePiece; LPDIRECT3DTEXTURE9 board; LPDIRECT3DTEXTURE9 title; int redCount; int blueCount; bool pieceFall; bool humanOp; int playerScore[2]; int aiScore[2]; CSound *music; CSound *move; CSound *hit; int aiSeletion(); bool winCheck(int pieces[7][6], int input); void updateField(int field[6][7], int pieces[7][6], int playerTurn); bool drawCheck(); };
[ "mateuszmachaj@yahoo.com" ]
mateuszmachaj@yahoo.com
716ead90c8053dff43b2b8e2d754ee1137dbe2b2
1ab9ced624ad3518554548b7bed92a13c5d05faa
/Solutions/Daily Temperatures.cpp
a4f8a7b922222122c9c2ef10e30eabe2329cdd5c
[]
no_license
shehab-ashraf/Problem_Solving
361674efde765b705402d1971cf0206e604d92c7
2cb4d241bcc885251fdaf2757f3f0738b08f521f
refs/heads/master
2023-07-02T19:25:04.780816
2021-07-30T22:30:01
2021-07-30T22:30:01
381,096,647
0
0
null
null
null
null
UTF-8
C++
false
false
474
cpp
// O(n) time | O(n) space class Solution { public: vector<int> dailyTemperatures(vector<int>& temperatures) { stack<int> st; vector<int> ans(temperatures.size(),0); for(int i = 0 ; i < temperatures.size() ; i++){ while(!st.empty() && temperatures[st.top()] < temperatures[i]){ ans[st.top()] = i-st.top(); st.pop(); } st.push(i); } return ans; } };
[ "ashrafshehab377@gmail.com" ]
ashrafshehab377@gmail.com
0a9fcc33c4a2939430b6d0a810d4ac09375e73b8
087dea2f7147663ba90a213f59b70ddd59f6aec4
/main/stltest/bind2nd2.cpp
4949eb68852cab1062e669d946aa6f4a64a893a6
[ "MIT" ]
permissive
stormbrew/stir
b5c3bcaf7c7e8c3a95dd45bf1642c83b6291a408
2d39364bfceb87106daa2338f9dfe6362a811347
refs/heads/master
2022-05-24T17:52:26.908960
2022-04-28T03:39:42
2022-04-28T03:39:42
1,130,258
0
0
null
null
null
null
UTF-8
C++
false
false
469
cpp
#ifndef SINGLE // An adapted ObjectSpace example for use with SGI STL #include <iostream> #include <algorithm> #include <functional> #ifdef MAIN #define bind2nd2_test main #endif #endif int bind2nd2_test(int, char**) { std::cout<<"Results of bind2nd2_test:"<<std::endl; int array [3] = { 1, 2, 3 }; std::replace_if(array, array + 3, std::bind2nd(std::greater<int>(), 2), 4); for(int i = 0; i < 3; i++) std::cout << array[i] << std::endl; return 0; }
[ "megan@stormbrew.ca" ]
megan@stormbrew.ca
b1773c2ec4e1fb80e2e3dbd5904ecfd5627d91b2
94847d787dfe5695eeaa5e0bfd65eb11b6d4e6ef
/include/rllib/util/Vector3.hpp
ed28eb98ad8604a8ab5197fbd8ebe399436e4c06
[ "MIT" ]
permissive
loriswit/rllib
70bc3161e998d71355536a977f1ce74fdb172ec0
a09a73f8ac353db76454007b2ec95bf438c0fc1a
refs/heads/main
2021-06-15T19:12:58.385115
2021-02-07T17:44:39
2021-02-07T17:44:39
144,877,014
1
0
null
null
null
null
UTF-8
C++
false
false
1,212
hpp
#ifndef RLLIB_VECTOR3_HPP #define RLLIB_VECTOR3_HPP #include <ostream> namespace rl { /** * Structure representing a three-dimensional vector. * * @tparam T The type of the vector components */ template<typename T> struct RL_API Vector3 { /** * The horizontal component of the vector. */ T x; /** * The vertical component of the vector. */ T y; /** * The depth component of the vector. */ T z; /** * Creates a 3D vector. * * @param X The horizontal component of the vector * @param Y The vertical component of the vector * @param Z The depth component of the vector */ constexpr Vector3(T X = 0, T Y = 0, T Z = 0); }; /** * Writes the 3D vector components into a stream. * * @tparam T The type of the vector components * @param stream The stream object * @param vector The 3D vector object * @return The current stream */ template<typename T> std::ostream & operator<<(std::ostream & stream, const Vector3<T> & vector); /** * Type representing a 3D vector with float components. */ using Vector3f = Vector3<float>; #include "Vector3.inl" } // namespace rl #endif //RLLIB_VECTOR3_HPP
[ "loris.wit@gmail.com" ]
loris.wit@gmail.com
1bf6158d4778df4d204abe2699364432bdb10209
e1adcd0173cf849867144a511c029b8f5529b711
/ros_ws/install/include/baxter_maintenance_msgs/UpdateSource.h
01db0d7739d138f6ee9fb041e903ba16298fbf1d
[]
no_license
adubredu/cartbot_arm_subsystem
20a6e0c7bacc28dc0486160c6e25fede49f013f2
3e451272ddaf720bc7bd24da2ad5201b27248f1c
refs/heads/master
2022-01-04T23:01:25.061143
2019-05-14T16:45:02
2019-05-14T16:45:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,794
h
// Generated by gencpp from file baxter_maintenance_msgs/UpdateSource.msg // DO NOT EDIT! #ifndef BAXTER_MAINTENANCE_MSGS_MESSAGE_UPDATESOURCE_H #define BAXTER_MAINTENANCE_MSGS_MESSAGE_UPDATESOURCE_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace baxter_maintenance_msgs { template <class ContainerAllocator> struct UpdateSource_ { typedef UpdateSource_<ContainerAllocator> Type; UpdateSource_() : devname() , filename() , version() , uuid() { } UpdateSource_(const ContainerAllocator& _alloc) : devname(_alloc) , filename(_alloc) , version(_alloc) , uuid(_alloc) { (void)_alloc; } typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _devname_type; _devname_type devname; typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _filename_type; _filename_type filename; typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _version_type; _version_type version; typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _uuid_type; _uuid_type uuid; typedef boost::shared_ptr< ::baxter_maintenance_msgs::UpdateSource_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::baxter_maintenance_msgs::UpdateSource_<ContainerAllocator> const> ConstPtr; }; // struct UpdateSource_ typedef ::baxter_maintenance_msgs::UpdateSource_<std::allocator<void> > UpdateSource; typedef boost::shared_ptr< ::baxter_maintenance_msgs::UpdateSource > UpdateSourcePtr; typedef boost::shared_ptr< ::baxter_maintenance_msgs::UpdateSource const> UpdateSourceConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::baxter_maintenance_msgs::UpdateSource_<ContainerAllocator> & v) { ros::message_operations::Printer< ::baxter_maintenance_msgs::UpdateSource_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace baxter_maintenance_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'baxter_maintenance_msgs': ['/home/bill/bill_ros/ros_ws/src/baxter_common/baxter_maintenance_msgs/msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::baxter_maintenance_msgs::UpdateSource_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::baxter_maintenance_msgs::UpdateSource_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::baxter_maintenance_msgs::UpdateSource_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::baxter_maintenance_msgs::UpdateSource_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::baxter_maintenance_msgs::UpdateSource_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::baxter_maintenance_msgs::UpdateSource_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::baxter_maintenance_msgs::UpdateSource_<ContainerAllocator> > { static const char* value() { return "88ad69e3ed4d619e167c9d83e6d9310f"; } static const char* value(const ::baxter_maintenance_msgs::UpdateSource_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x88ad69e3ed4d619eULL; static const uint64_t static_value2 = 0x167c9d83e6d9310fULL; }; template<class ContainerAllocator> struct DataType< ::baxter_maintenance_msgs::UpdateSource_<ContainerAllocator> > { static const char* value() { return "baxter_maintenance_msgs/UpdateSource"; } static const char* value(const ::baxter_maintenance_msgs::UpdateSource_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::baxter_maintenance_msgs::UpdateSource_<ContainerAllocator> > { static const char* value() { return "string devname\n\ string filename\n\ string version\n\ string uuid\n\ "; } static const char* value(const ::baxter_maintenance_msgs::UpdateSource_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::baxter_maintenance_msgs::UpdateSource_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.devname); stream.next(m.filename); stream.next(m.version); stream.next(m.uuid); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct UpdateSource_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::baxter_maintenance_msgs::UpdateSource_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::baxter_maintenance_msgs::UpdateSource_<ContainerAllocator>& v) { s << indent << "devname: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.devname); s << indent << "filename: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.filename); s << indent << "version: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.version); s << indent << "uuid: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.uuid); } }; } // namespace message_operations } // namespace ros #endif // BAXTER_MAINTENANCE_MSGS_MESSAGE_UPDATESOURCE_H
[ "alphonsusbq436@gmail.com" ]
alphonsusbq436@gmail.com
11da73a7609b400d1f32fffc741d4bf3fea24596
107dd749c9886d781894e5238d9c2419f7952649
/src/qt/bitcoingui.h
483fa2b75e701a13a46e904982aad166dee03137
[ "MIT" ]
permissive
Coin4Trade/Coin4Trade
ae58e76e09ed5a0cb62def5b91efd848cd77a284
fb5c4b7580212cd7e3daacd93fabf1be4d20ff7c
refs/heads/master
2023-08-23T22:42:33.681882
2021-10-02T20:58:21
2021-10-02T20:58:21
281,785,399
1
0
null
null
null
null
UTF-8
C++
false
false
9,416
h
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2017-2018 The PIVX developers // Copyright (c) 2020 The C4T developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_BITCOINGUI_H #define BITCOIN_QT_BITCOINGUI_H #if defined(HAVE_CONFIG_H) #include "config/C4T-config.h" #endif #include "amount.h" #include <QLabel> #include <QMainWindow> #include <QMap> #include <QMenu> #include <QPoint> #include <QPushButton> #include <QSystemTrayIcon> class ClientModel; class NetworkStyle; class Notificator; class OptionsModel; class BlockExplorer; class RPCConsole; class SendCoinsRecipient; class UnitDisplayStatusBarControl; class WalletFrame; class WalletModel; class MasternodeList; class CWallet; QT_BEGIN_NAMESPACE class QAction; class QProgressBar; class QProgressDialog; QT_END_NAMESPACE /** Bitcoin GUI main class. This class represents the main window of the Bitcoin UI. It communicates with both the client and wallet models to give the user an up-to-date view of the current core state. */ class BitcoinGUI : public QMainWindow { Q_OBJECT public: static const QString DEFAULT_WALLET; explicit BitcoinGUI(const NetworkStyle* networkStyle, QWidget* parent = 0); ~BitcoinGUI(); /** Set the client model. The client model represents the part of the core that communicates with the P2P network, and is wallet-agnostic. */ void setClientModel(ClientModel* clientModel); #ifdef ENABLE_WALLET /** Set the wallet model. The wallet model represents a bitcoin wallet, and offers access to the list of transactions, address book and sending functionality. */ bool addWallet(const QString& name, WalletModel* walletModel); bool setCurrentWallet(const QString& name); void removeAllWallets(); #endif // ENABLE_WALLET bool enableWallet; bool fMultiSend = false; protected: void changeEvent(QEvent* e); void closeEvent(QCloseEvent* event); void dragEnterEvent(QDragEnterEvent* event); void dropEvent(QDropEvent* event); bool eventFilter(QObject* object, QEvent* event); private: ClientModel* clientModel; WalletFrame* walletFrame; UnitDisplayStatusBarControl* unitDisplayControl; QLabel* labelStakingIcon; QPushButton* labelAutoMintIcon; QPushButton* labelEncryptionIcon; QLabel* labelTorIcon; QPushButton* labelConnectionsIcon; QLabel* labelBlocksIcon; QLabel* progressBarLabel; QProgressBar* progressBar; QProgressDialog* progressDialog; QMenuBar* appMenuBar; QAction* overviewAction; QAction* historyAction; QAction* masternodeAction; QAction* quitAction; QAction* sendCoinsAction; QAction* usedSendingAddressesAction; QAction* usedReceivingAddressesAction; QAction* signMessageAction; QAction* verifyMessageAction; QAction* bip38ToolAction; QAction* multisigCreateAction; QAction* multisigSpendAction; QAction* multisigSignAction; QAction* aboutAction; QAction* receiveCoinsAction; QAction* optionsAction; QAction* toggleHideAction; QAction* encryptWalletAction; QAction* backupWalletAction; QAction* changePassphraseAction; QAction* unlockWalletAction; QAction* lockWalletAction; QAction* aboutQtAction; QAction* openInfoAction; QAction* openRPCConsoleAction; QAction* openNetworkAction; QAction* openPeersAction; QAction* openRepairAction; QAction* openConfEditorAction; QAction* openMNConfEditorAction; QAction* showBackupsAction; QAction* openAction; QAction* openBlockExplorerAction; QAction* showHelpMessageAction; QAction* multiSendAction; QSystemTrayIcon* trayIcon; QMenu* trayIconMenu; Notificator* notificator; RPCConsole* rpcConsole; BlockExplorer* explorerWindow; /** Keep track of previous number of blocks, to detect progress */ int prevBlocks; int spinnerFrame; /** Create the main UI actions. */ void createActions(const NetworkStyle* networkStyle); /** Create the menu bar and sub-menus. */ void createMenuBar(); /** Create the toolbars */ void createToolBars(); /** Create system tray icon and notification */ void createTrayIcon(const NetworkStyle* networkStyle); /** Create system tray menu (or setup the dock menu) */ void createTrayIconMenu(); /** Enable or disable all wallet-related actions */ void setWalletActionsEnabled(bool enabled); /** Connect core signals to GUI client */ void subscribeToCoreSignals(); /** Disconnect core signals from GUI client */ void unsubscribeFromCoreSignals(); signals: /** Signal raised when a URI was entered or dragged to the GUI */ void receivedURI(const QString& uri); /** Restart handling */ void requestedRestart(QStringList args); public slots: /** Set number of connections shown in the UI */ void setNumConnections(int count); /** Set number of blocks shown in the UI */ void setNumBlocks(int count); /** Get restart command-line parameters and request restart */ void handleRestart(QStringList args); /** Notify the user of an event from the core network or transaction handling code. @param[in] title the message box / notification title @param[in] message the displayed text @param[in] style modality and style definitions (icon and used buttons - buttons only for message boxes) @see CClientUIInterface::MessageBoxFlags @param[in] ret pointer to a bool that will be modified to whether Ok was clicked (modal only) */ void message(const QString& title, const QString& message, unsigned int style, bool* ret = NULL); #ifdef ENABLE_WALLET void setStakingStatus(); /** Set the encryption status as shown in the UI. @param[in] status current encryption status @see WalletModel::EncryptionStatus */ void setEncryptionStatus(int status); bool handlePaymentRequest(const SendCoinsRecipient& recipient); /** Show incoming transaction notification for new transactions. */ void incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address); #endif // ENABLE_WALLET private: /** Set the Tor-enabled icon as shown in the UI. */ void updateTorIcon(); private slots: #ifdef ENABLE_WALLET /** Switch to overview (home) page */ void gotoOverviewPage(); /** Switch to history (transactions) page */ void gotoHistoryPage(); /** Switch to Explorer Page */ void gotoBlockExplorerPage(); /** Switch to masternode page */ void gotoMasternodePage(); /** Switch to receive coins page */ void gotoReceiveCoinsPage(); /** Switch to send coins page */ void gotoSendCoinsPage(QString addr = ""); /** Show Sign/Verify Message dialog and switch to sign message tab */ void gotoSignMessageTab(QString addr = ""); /** Show Sign/Verify Message dialog and switch to verify message tab */ void gotoVerifyMessageTab(QString addr = ""); /** Show MultiSend Dialog */ void gotoMultiSendDialog(); /** Show MultiSig Dialog */ void gotoMultisigCreate(); void gotoMultisigSpend(); void gotoMultisigSign(); /** Show BIP 38 tool - default to Encryption tab */ void gotoBip38Tool(); /** Show open dialog */ void openClicked(); #endif // ENABLE_WALLET /** Show configuration dialog */ void optionsClicked(); /** Show about dialog */ void aboutClicked(); /** Show help message dialog */ void showHelpMessageClicked(); #ifndef Q_OS_MAC /** Handle tray icon clicked */ void trayIconActivated(QSystemTrayIcon::ActivationReason reason); #endif /** Show window if hidden, unminimize when minimized, rise when obscured or show if hidden and fToggleHidden is true */ void showNormalIfMinimized(bool fToggleHidden = false); /** Simply calls showNormalIfMinimized(true) for use in SLOT() macro */ void toggleHidden(); /** called by a timer to check if fRequestShutdown has been set **/ void detectShutdown(); /** Show progress dialog e.g. for verifychain */ void showProgress(const QString& title, int nProgress); }; class UnitDisplayStatusBarControl : public QLabel { Q_OBJECT public: explicit UnitDisplayStatusBarControl(); /** Lets the control know about the Options Model (and its signals) */ void setOptionsModel(OptionsModel* optionsModel); protected: /** So that it responds to left-button clicks */ void mousePressEvent(QMouseEvent* event); private: OptionsModel* optionsModel; QMenu* menu; /** Shows context menu with Display Unit options by the mouse coordinates */ void onDisplayUnitsClicked(const QPoint& point); /** Creates context menu, its actions, and wires up all the relevant signals for mouse events. */ void createContextMenu(); private slots: /** When Display Units are changed on OptionsModel it will refresh the display text of the control on the status bar */ void updateDisplayUnit(int newUnits); /** Tells underlying optionsModel to update its current display unit. */ void onMenuSelection(QAction* action); }; #endif // BITCOIN_QT_BITCOINGUI_H
[ "68502813+Coin4Trade@users.noreply.github.com" ]
68502813+Coin4Trade@users.noreply.github.com
0dd68be4b85d753fe732558602078b139e87ed0e
6fe17c32ba5bb492e276e13128c516a3f85f01ff
/New folder/stones on the table.cpp
385fd81f1bbde63893ea12f81cdf4a3b3416c12c
[ "Apache-2.0" ]
permissive
YaminArafat/Codeforces
35c5c527c8edd51c7f591bfe6474060934241d86
3d72ba0b5c9408a8e2491b25b5b643e9f9be728b
refs/heads/master
2023-08-17T03:12:04.596632
2021-10-06T14:49:29
2021-10-06T14:49:29
351,042,898
0
0
null
null
null
null
UTF-8
C++
false
false
326
cpp
#include <bits/stdc++.h> using namespace std; int main() { int n,i,x=0; scanf("%d",&n); char str[n+1]; for (i=0 ; i<n; i++) { cin>>str[i]; } str[i]='\0'; for(i=0;i<n-1;i++) { if(str[i]==str[i+1]) { x++; } } cout<<x<<endl; return 0; }
[ "yaminarafat032@gmail.com" ]
yaminarafat032@gmail.com
af878b71446af13a25c84154d07c56691cfb77d4
d4876d852d32d64391f4eaf67b38a461a219cf73
/src/GameCuaTao/Castlevania/Models/Weapons/Whip.cpp
dbd1ef7f96eb2fa5d63547c912f9c3d5a207cbcc
[]
no_license
ngb0511/Castlevania
1894988743bfcd622e4eb01d13329cffaf31c91a
c2c8a33fcbe9c67cb22b0fe15fbe65b313f0b8aa
refs/heads/master
2022-03-21T03:16:26.013207
2019-10-15T12:55:57
2019-10-15T12:55:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,261
cpp
#include "Direct2DGame/MathHelper.h" #include "Whip.h" #include "../Settings.h" #include "WhipFlashingRenderingSystem.h" #include "../../Utilities/AudioManager.h" using namespace Castlevania; const auto HITPOINTS = std::map<int, int> { { 1, 1 }, { 2, 2 }, { 3, 2 }, }; Whip::Whip() : GameObject{ ObjectId::Whip } { level = 1; } int Whip::GetLevel() { return level; } void Whip::SetLevel(int level) { this->level = MathHelper::Clamp(level, 1, WHIP_MAX_LEVEL); } int Whip::GetAttack() { return HITPOINTS.at(level); } void Whip::SetAttack(int attack) { } GameObject *Whip::GetOwner() { return owner; } void Whip::SetOwner(GameObject *owner) { this->owner = owner; } void Whip::SetFacing(Facing facing) { GameObject::SetFacing(facing); SendMessageToSystems(FACING_CHANGED); } void Whip::LoadContent(ContentManager &content) { GameObject::LoadContent(content); Withdraw(); } void Whip::Unleash() { // Collision detection will be turn on when whip is on the attack frame // body.Enabled(true); SendMessageToSystems(WHIP_UNLEASHED); AudioManager::Play(SE_USING_WEAPON); } void Whip::Withdraw() { body.Enabled(false); SendMessageToSystems(WEAPON_WITHDRAWN); } void Whip::Upgrade() { level = MathHelper::Min(++level, WHIP_MAX_LEVEL); }
[ "near.huscarl@gmail.com" ]
near.huscarl@gmail.com
81c1afc23b0bf8396ccb7cfb078d27d5c4e40585
e17f365bf6d40cc0325ed0dc6ec1c5ecd9132b99
/arduino/libraries/EZKey/EZKey.cpp
440783316bb0a99c8709a7d18096ef0f37f97c34
[ "MIT" ]
permissive
wyolum/VPD
70740230807ba4c74eb1455507ff60149c91d618
52baa1d7046b004015e4c9d727df13d7cfa4bf23
refs/heads/master
2016-09-05T08:44:23.418769
2015-05-24T13:56:39
2015-05-24T13:56:39
35,377,369
1
0
null
null
null
null
UTF-8
C++
false
false
537
cpp
#include "EZKey.h" void keyCommand(SoftwareSerial BT, uint8_t modifiers, uint8_t keycode1, uint8_t keycode2, uint8_t keycode3, uint8_t keycode4, uint8_t keycode5, uint8_t keycode6) { BT.write(0xFD); // our command BT.write(modifiers); // modifier! BT.write((byte)0x00); // 0x00 BT.write(keycode1); // key code #1 BT.write(keycode2); // key code #2 BT.write(keycode3); // key code #3 BT.write(keycode4); // key code #4 BT.write(keycode5); // key code #5 BT.write(keycode6); // key code #6 }
[ "wyojustin@gmail.com" ]
wyojustin@gmail.com
132408885f75e8a40b0f4ea9c497342073d408b6
e94caa5e0894eb25ff09ad75aa104e484d9f0582
/data/s30l/mp2/cp_corrected/20/AB/cc-pVQZ/2_ghosts/cbas_mp2/restart.cc
6dd50a8da7a2af525c343189c32bacc56e590290
[]
no_license
bdnguye2/divergence_mbpt_noncovalent
d74e5d755497509026e4ac0213ed66f3ca296908
f29b8c75ba2f1c281a9b81979d2a66d2fd48e09c
refs/heads/master
2022-04-14T14:09:08.951134
2020-04-04T10:49:03
2020-04-04T10:49:03
240,377,466
0
0
null
null
null
null
UTF-8
C++
false
false
444
cc
$chkbas= 1570771.54340576 $nucrep= 505.009748775714 $chkaux= 13179617163.0805 $chkupro= 1.00000000000000 $chkipro= 2.00000000000000 $chklasrep= 1.00000000000000 $chkisy6= 4.00000000000000 $chkmos= 2036.89531322081 $chkCCVPQ_ISQR= 52880.6863318043 $chkbqia= 55.1374803240782 $chkr0_MP2= 0.00000000000000 $energy_MP2= -389.004999792089 $sccss= 1.00000000000000 $sccos= 1.00000000000000 $end
[ "bdnguye2@uci.edu" ]
bdnguye2@uci.edu
bcf16128971fb4c7345db6e518ead319194cef9e
f442bfabec358023bfdb5d2f25158e2e13e26227
/Homework 1/homework1/staff.h
d9bd42dc916f1c4106d3f7bf7b68f48b2102ed38
[]
no_license
snchvz/CS202
203797e74c90db7ee5ebc8b471e1413c526a4741
abbf296f4e60e1164579791426a3e147932090ff
refs/heads/master
2020-04-17T15:48:48.723959
2019-01-20T22:07:09
2019-01-20T22:07:09
166,714,380
1
0
null
null
null
null
UTF-8
C++
false
false
567
h
/* Andrew Sanchez File name: Staff.h Date: 4/19/17 Description: initialize class Staff percentage: 100% */ #ifndef STAFF_H #define STAFF_H #include <iostream> #include <string> #include <vector> #include "Employee.h" using namespace std; class Staff { private: vector<Employee> members; int find(string n); //returns position of n in members or -1 if not found public: Staff(){} void add_employee(Employee e); // better: const Employee & void raise_salary(string n, int percent); void print(); }; #endif
[ "noreply@github.com" ]
snchvz.noreply@github.com
889e592fd4c76f9c96705afbbb3ea6f8719a23bb
b2b10f8ba5b3a2b023fe3dbfb9fe9900c111a8e7
/common/columnlistview/haiku/ColumnListView.cpp
37ee3eee3dc67a0abc1549d96878b323dd92dd35
[ "BSD-3-Clause" ]
permissive
HaikuArchives/IMKit
0759451f29a15502838e9102c0c4566a436fd9c0
9c80ad110de77481717d855f503d3de6ce65e4d8
refs/heads/master
2021-01-19T03:14:00.562465
2009-11-27T16:17:29
2009-11-27T16:17:29
12,183,169
1
0
null
null
null
null
UTF-8
C++
false
false
117,906
cpp
/* Open Tracker License Terms and Conditions Copyright (c) 1991-2000, Be Incorporated. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice applies to all licensees and 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 TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL BE INCORPORATED BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Be Incorporated shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Be Incorporated. Tracker(TM), Be(R), BeOS(R), and BeIA(TM) are trademarks or registered trademarks of Be Incorporated in the United States and other countries. Other brand product names are registered trademarks or trademarks of their respective holders. All rights reserved. */ /******************************************************************************* / / File: ColumnListView.cpp / / Description: Experimental multi-column list view. / / Copyright 2000+, Be Incorporated, All Rights Reserved / By Jeff Bush / *******************************************************************************/ #include "ColumnListView.h" #include <typeinfo> #include <stdio.h> #include <stdlib.h> #include <Application.h> #include <Bitmap.h> #include <ControlLook.h> #include <Cursor.h> #include <Debug.h> #include <GraphicsDefs.h> #include <LayoutUtils.h> #include <MenuItem.h> #include <PopUpMenu.h> #include <Region.h> #include <ScrollBar.h> #include <String.h> #include <Window.h> #include "ColorTools.h" #include "ObjectList.h" #define DOUBLE_BUFFERED_COLUMN_RESIZE 1 #define SMART_REDRAW 1 #define DRAG_TITLE_OUTLINE 1 #define CONSTRAIN_CLIPPING_REGION 1 #define LOWER_SCROLLBAR 0 namespace BPrivate { static const unsigned char kResizeCursorData[] = { 16, 1, 8, 8, 0x03, 0xc0, 0x02, 0x40, 0x02, 0x40, 0x02, 0x40, 0x1a, 0x58, 0x2a, 0x54, 0x4a, 0x52, 0x8a, 0x51, 0x8a, 0x51, 0x4a, 0x52, 0x2a, 0x54, 0x1a, 0x58, 0x02, 0x40, 0x02, 0x40, 0x02, 0x40, 0x03, 0xc0, 0x03, 0xc0, 0x03, 0xc0, 0x03, 0xc0, 0x03, 0xc0, 0x1b, 0xd8, 0x3b, 0xdc, 0x7b, 0xde, 0xfb, 0xdf, 0xfb, 0xdf, 0x7b, 0xde, 0x3b, 0xdc, 0x1b, 0xd8, 0x03, 0xc0, 0x03, 0xc0, 0x03, 0xc0, 0x03, 0xc0 }; static const unsigned char kMaxResizeCursorData[] = { 16, 1, 8, 8, 0x03, 0xc0, 0x02, 0x40, 0x02, 0x40, 0x02, 0x40, 0x1a, 0x40, 0x2a, 0x40, 0x4a, 0x40, 0x8a, 0x40, 0x8a, 0x40, 0x4a, 0x40, 0x2a, 0x40, 0x1a, 0x40, 0x02, 0x40, 0x02, 0x40, 0x02, 0x40, 0x03, 0xc0, 0x03, 0xc0, 0x03, 0xc0, 0x03, 0xc0, 0x03, 0xc0, 0x1b, 0xc0, 0x3b, 0xc0, 0x7b, 0xc0, 0xfb, 0xc0, 0xfb, 0xc0, 0x7b, 0xc0, 0x3b, 0xc0, 0x1b, 0xc0, 0x03, 0xc0, 0x03, 0xc0, 0x03, 0xc0, 0x03, 0xc0 }; static const unsigned char kMinResizeCursorData[] = { 16, 1, 8, 8, 0x03, 0xc0, 0x02, 0x40, 0x02, 0x40, 0x02, 0x40, 0x02, 0x58, 0x02, 0x54, 0x02, 0x52, 0x02, 0x51, 0x02, 0x51, 0x02, 0x52, 0x02, 0x54, 0x02, 0x58, 0x02, 0x40, 0x02, 0x40, 0x02, 0x40, 0x03, 0xc0, 0x03, 0xc0, 0x03, 0xc0, 0x03, 0xc0, 0x03, 0xc0, 0x03, 0xd8, 0x03, 0xdc, 0x03, 0xde, 0x03, 0xdf, 0x03, 0xdf, 0x03, 0xde, 0x03, 0xdc, 0x03, 0xd8, 0x03, 0xc0, 0x03, 0xc0, 0x03, 0xc0, 0x03, 0xc0 }; static const unsigned char kColumnMoveCursorData[] = { 16, 1, 8, 8, 0x01, 0x80, 0x02, 0x40, 0x04, 0x20, 0x08, 0x10, 0x1e, 0x78, 0x2a, 0x54, 0x4e, 0x72, 0x80, 0x01, 0x80, 0x01, 0x4e, 0x72, 0x2a, 0x54, 0x1e, 0x78, 0x08, 0x10, 0x04, 0x20, 0x02, 0x40, 0x01, 0x80, 0x01, 0x80, 0x03, 0xc0, 0x07, 0xe0, 0x0f, 0xf0, 0x1f, 0xf8, 0x3b, 0xdc, 0x7f, 0xfe, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xfe, 0x3b, 0xdc, 0x1f, 0xf8, 0x0f, 0xf0, 0x07, 0xe0, 0x03, 0xc0, 0x01, 0x80 }; static const unsigned char kDownSortArrow8x8[] = { 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0xff, 0xff, 0xff, 0xff }; static const unsigned char kUpSortArrow8x8[] = { 0xff, 0xff, 0xff, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff }; static const unsigned char kDownSortArrow8x8Invert[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x1f, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0xff, 0xff, 0xff, 0xff }; static const unsigned char kUpSortArrow8x8Invert[] = { 0xff, 0xff, 0xff, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x1f, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; static const float kTintedLineTint = 0.7 * B_NO_TINT + 0.3 * B_DARKEN_1_TINT; static const float kTitleHeight = 16.0; static const float kLatchWidth = 15.0; static const rgb_color kColor[B_COLOR_TOTAL] = { {236, 236, 236, 255}, // B_COLOR_BACKGROUND { 0, 0, 0, 255}, // B_COLOR_TEXT {148, 148, 148, 255}, // B_COLOR_ROW_DIVIDER {190, 190, 190, 255}, // B_COLOR_SELECTION { 0, 0, 0, 255}, // B_COLOR_SELECTION_TEXT {200, 200, 200, 255}, // B_COLOR_NON_FOCUS_SELECTION {180, 180, 180, 180}, // B_COLOR_EDIT_BACKGROUND { 0, 0, 0, 255}, // B_COLOR_EDIT_TEXT {215, 215, 215, 255}, // B_COLOR_HEADER_BACKGROUND { 0, 0, 0, 255}, // B_COLOR_HEADER_TEXT { 0, 0, 0, 255}, // B_COLOR_SEPARATOR_LINE { 0, 0, 0, 255}, // B_COLOR_SEPARATOR_BORDER }; static const int32 kMaxDepth = 1024; static const float kLeftMargin = kLatchWidth; static const float kRightMargin = kLatchWidth; static const float kOutlineLevelIndent = kLatchWidth; static const float kColumnResizeAreaWidth = 10.0; static const float kRowDragSensitivity = 5.0; static const float kDoubleClickMoveSensitivity = 4.0; static const float kSortIndicatorWidth = 9.0; static const float kDropHighlightLineHeight = 2.0; static const uint32 kToggleColumn = 'BTCL'; class BRowContainer : public BObjectList<BRow> { }; class TitleView : public BView { typedef BView _inherited; public: TitleView(BRect frame, OutlineView* outlineView, BList* visibleColumns, BList* sortColumns, BColumnListView* masterView, uint32 resizingMode); virtual ~TitleView(); void ColumnAdded(BColumn* column); void ColumnResized(BColumn* column, float oldWidth); void SetColumnVisible(BColumn* column, bool visible); virtual void Draw(BRect updateRect); virtual void ScrollTo(BPoint where); virtual void MessageReceived(BMessage* message); virtual void MouseDown(BPoint where); virtual void MouseMoved(BPoint where, uint32 transit, const BMessage* dragMessage); virtual void MouseUp(BPoint where); virtual void FrameResized(float width, float height); void MoveColumn(BColumn* column, int32 index); void SetColumnFlags(column_flags flags); void SetEditMode(bool state) { fEditMode = state; } private: void GetTitleRect(BColumn* column, BRect* _rect); int32 FindColumn(BPoint where, float* _leftEdge); void FixScrollBar(bool scrollToFit); void DragSelectedColumn(BPoint where); void ResizeSelectedColumn(BPoint where, bool preferred = false); void ComputeDragBoundries(BColumn* column, BPoint where); void DrawTitle(BView* view, BRect frame, BColumn* column, bool depressed); float _VirtualWidth() const; OutlineView* fOutlineView; BList* fColumns; BList* fSortColumns; // float fColumnsWidth; BRect fVisibleRect; #if DOUBLE_BUFFERED_COLUMN_RESIZE BBitmap* fDrawBuffer; BView* fDrawBufferView; #endif enum { INACTIVE, RESIZING_COLUMN, PRESSING_COLUMN, DRAG_COLUMN_INSIDE_TITLE, DRAG_COLUMN_OUTSIDE_TITLE } fCurrentState; BPopUpMenu* fColumnPop; BColumnListView* fMasterView; bool fEditMode; int32 fColumnFlags; // State information for resizing/dragging BColumn* fSelectedColumn; BRect fSelectedColumnRect; bool fResizingFirstColumn; BPoint fClickPoint; // offset within cell float fLeftDragBoundry; float fRightDragBoundry; BPoint fCurrentDragPosition; BBitmap* fUpSortArrow; BBitmap* fDownSortArrow; BCursor* fResizeCursor; BCursor* fMinResizeCursor; BCursor* fMaxResizeCursor; BCursor* fColumnMoveCursor; }; class OutlineView : public BView { typedef BView _inherited; public: OutlineView(BRect, BList* visibleColumns, BList* sortColumns, BColumnListView* listView); virtual ~OutlineView(); virtual void Draw(BRect); const BRect& VisibleRect() const; void RedrawColumn(BColumn* column, float leftEdge, bool isFirstColumn); void StartSorting(); float GetColumnPreferredWidth(BColumn* column); void AddRow(BRow*, int32 index, BRow* TheRow); BRow* CurrentSelection(BRow* lastSelected) const; void ToggleFocusRowSelection(bool selectRange); void ToggleFocusRowOpen(); void ChangeFocusRow(bool up, bool updateSelection, bool addToCurrentSelection); void MoveFocusToVisibleRect(); void ExpandOrCollapse(BRow* parent, bool expand); void RemoveRow(BRow*); BRowContainer* RowList(); void UpdateRow(BRow*); bool FindParent(BRow* row, BRow** _parent, bool* _isVisible); int32 IndexOf(BRow* row); void Deselect(BRow*); void AddToSelection(BRow*); void DeselectAll(); BRow* FocusRow() const; void SetFocusRow(BRow* row, bool select); BRow* FindRow(float ypos, int32* _indent, float* _top); bool FindRect(const BRow* row, BRect* _rect); void ScrollTo(const BRow* row); void Clear(); void SetSelectionMode(list_view_type type); list_view_type SelectionMode() const; void SetMouseTrackingEnabled(bool); void FixScrollBar(bool scrollToFit); void SetEditMode(bool state) { fEditMode = state; } virtual void FrameResized(float width, float height); virtual void ScrollTo(BPoint where); virtual void MouseDown(BPoint where); virtual void MouseMoved(BPoint where, uint32 transit, const BMessage* dragMessage); virtual void MouseUp(BPoint where); virtual void MessageReceived(BMessage* message); private: bool SortList(BRowContainer* list, bool isVisible); static int32 DeepSortThreadEntry(void* outlineView); void DeepSort(); void SelectRange(BRow* start, BRow* end); int32 CompareRows(BRow* row1, BRow* row2); void AddSorted(BRowContainer* list, BRow* row); void RecursiveDeleteRows(BRowContainer* list, bool owner); void InvalidateCachedPositions(); bool FindVisibleRect(BRow* row, BRect* _rect); BList* fColumns; BList* fSortColumns; float fItemsHeight; BRowContainer fRows; BRect fVisibleRect; #if DOUBLE_BUFFERED_COLUMN_RESIZE BBitmap* fDrawBuffer; BView* fDrawBufferView; #endif BRow* fFocusRow; BRect fFocusRowRect; BRow* fRollOverRow; BRow fSelectionListDummyHead; BRow* fLastSelectedItem; BRow* fFirstSelectedItem; thread_id fSortThread; int32 fNumSorted; bool fSortCancelled; enum CurrentState { INACTIVE, LATCH_CLICKED, ROW_CLICKED, DRAGGING_ROWS }; CurrentState fCurrentState; BColumnListView* fMasterView; list_view_type fSelectionMode; bool fTrackMouse; BField* fCurrentField; BRow* fCurrentRow; BColumn* fCurrentColumn; bool fMouseDown; BRect fFieldRect; int32 fCurrentCode; bool fEditMode; // State information for mouse/keyboard interaction BPoint fClickPoint; bool fDragging; int32 fClickCount; BRow* fTargetRow; float fTargetRowTop; BRect fLatchRect; float fDropHighlightY; friend class RecursiveOutlineIterator; }; class RecursiveOutlineIterator { public: RecursiveOutlineIterator( BRowContainer* container, bool openBranchesOnly = true); BRow* CurrentRow() const; int32 CurrentLevel() const; void GoToNext(); private: struct { BRowContainer* fRowSet; int32 fIndex; int32 fDepth; } fStack[kMaxDepth]; int32 fStackIndex; BRowContainer* fCurrentList; int32 fCurrentListIndex; int32 fCurrentListDepth; bool fOpenBranchesOnly; }; } // namespace BPrivate using namespace BPrivate; BField::BField() { } BField::~BField() { } // #pragma mark - void BColumn::MouseMoved(BColumnListView* /*parent*/, BRow* /*row*/, BField* /*field*/, BRect /*field_rect*/, BPoint/*point*/, uint32 /*buttons*/, int32 /*code*/) { } void BColumn::MouseDown(BColumnListView* /*parent*/, BRow* /*row*/, BField* /*field*/, BRect /*field_rect*/, BPoint /*point*/, uint32 /*buttons*/) { } void BColumn::MouseUp(BColumnListView* /*parent*/, BRow* /*row*/, BField* /*field*/) { } // #pragma mark - BRow::BRow(float height) : fChildList(NULL), fIsExpanded(false), fHeight(height), fNextSelected(NULL), fPrevSelected(NULL), fParent(NULL), fList(NULL) { } BRow::~BRow() { while (true) { BField* field = (BField*) fFields.RemoveItem(0L); if (field == 0) break; delete field; } } bool BRow::HasLatch() const { return fChildList != 0; } int32 BRow::CountFields() const { return fFields.CountItems(); } BField* BRow::GetField(int32 index) { return (BField*)fFields.ItemAt(index); } const BField* BRow::GetField(int32 index) const { return (const BField*)fFields.ItemAt(index); } void BRow::SetField(BField* field, int32 logicalFieldIndex) { if (fFields.ItemAt(logicalFieldIndex) != 0) delete (BField*)fFields.RemoveItem(logicalFieldIndex); if (NULL != fList) { ValidateField(field, logicalFieldIndex); BRect inv; fList->GetRowRect(this, &inv); fList->Invalidate(inv); } fFields.AddItem(field, logicalFieldIndex); } float BRow::Height() const { return fHeight; } bool BRow::IsExpanded() const { return fIsExpanded; } void BRow::ValidateFields() const { for (int32 i = 0; i < CountFields(); i++) ValidateField(GetField(i), i); } void BRow::ValidateField(const BField* field, int32 logicalFieldIndex) const { // The Fields may be moved by the user, but the logicalFieldIndexes // do not change, so we need to map them over when checking the // Field types. BColumn* col = NULL; int32 items = fList->CountColumns(); for (int32 i = 0 ; i < items; ++i) { col = fList->ColumnAt(i); if( col->LogicalFieldNum() == logicalFieldIndex ) break; } if (NULL == col) { BString dbmessage("\n\n\tThe parent BColumnListView does not have " "\n\ta BColumn at the logical field index "); dbmessage << logicalFieldIndex << ".\n\n"; printf(dbmessage.String()); } else { if (!col->AcceptsField(field)) { BString dbmessage("\n\n\tThe BColumn of type "); dbmessage << typeid(*col).name() << "\n\tat logical field index " << logicalFieldIndex << "\n\tdoes not support the " "field type " << typeid(*field).name() << ".\n\n"; debugger(dbmessage.String()); } } } // #pragma mark - BColumn::BColumn(float width, float minWidth, float maxWidth, alignment align) : fWidth(width), fMinWidth(minWidth), fMaxWidth(maxWidth), fVisible(true), fList(0), fShowHeading(true), fAlignment(align) { } BColumn::~BColumn() { } float BColumn::Width() const { return fWidth; } void BColumn::SetWidth(float width) { fWidth = width; } float BColumn::MinWidth() const { return fMinWidth; } float BColumn::MaxWidth() const { return fMaxWidth; } void BColumn::DrawTitle(BRect, BView*) { } void BColumn::DrawField(BField*, BRect, BView*) { } int BColumn::CompareFields(BField*, BField*) { return 0; } void BColumn::GetColumnName(BString* into) const { *into = "(Unnamed)"; } float BColumn::GetPreferredWidth(BField* field, BView* parent) const { return fWidth; } bool BColumn::IsVisible() const { return fVisible; } void BColumn::SetVisible(bool visible) { if (fList && (fVisible != visible)) fList->SetColumnVisible(this, visible); } bool BColumn::ShowHeading() const { return fShowHeading; } void BColumn::SetShowHeading(bool state) { fShowHeading = state; } alignment BColumn::Alignment() const { return fAlignment; } void BColumn::SetAlignment(alignment align) { fAlignment = align; } bool BColumn::WantsEvents() const { return fWantsEvents; } void BColumn::SetWantsEvents(bool state) { fWantsEvents = state; } int32 BColumn::LogicalFieldNum() const { return fFieldID; } bool BColumn::AcceptsField(const BField*) const { return true; } // #pragma mark - BColumnListView::BColumnListView(BRect rect, const char* name, uint32 resizingMode, uint32 flags, border_style border, bool showHorizontalScrollbar) : BView(rect, name, resizingMode, flags | B_WILL_DRAW | B_FRAME_EVENTS | B_FULL_UPDATE_ON_RESIZE), fStatusView(NULL), fSelectionMessage(NULL), fSortingEnabled(true), fLatchWidth(kLatchWidth), fBorderStyle(border) { _Init(showHorizontalScrollbar); } BColumnListView::BColumnListView(const char* name, uint32 flags, border_style border, bool showHorizontalScrollbar) : BView(name, flags | B_WILL_DRAW | B_FRAME_EVENTS | B_FULL_UPDATE_ON_RESIZE), fStatusView(NULL), fSelectionMessage(NULL), fSortingEnabled(true), fLatchWidth(kLatchWidth), fBorderStyle(border) { _Init(showHorizontalScrollbar); } BColumnListView::~BColumnListView() { while (BColumn* column = (BColumn*)fColumns.RemoveItem(0L)) delete column; } bool BColumnListView::InitiateDrag(BPoint, bool) { return false; } void BColumnListView::MessageDropped(BMessage*, BPoint) { } void BColumnListView::ExpandOrCollapse(BRow* row, bool Open) { fOutlineView->ExpandOrCollapse(row, Open); } status_t BColumnListView::Invoke(BMessage* message) { if (message == 0) message = Message(); return BInvoker::Invoke(message); } void BColumnListView::ItemInvoked() { Invoke(); } void BColumnListView::SetInvocationMessage(BMessage* message) { SetMessage(message); } BMessage* BColumnListView::InvocationMessage() const { return Message(); } uint32 BColumnListView::InvocationCommand() const { return Command(); } BRow* BColumnListView::FocusRow() const { return fOutlineView->FocusRow(); } void BColumnListView::SetFocusRow(int32 Index, bool Select) { SetFocusRow(RowAt(Index), Select); } void BColumnListView::SetFocusRow(BRow* row, bool Select) { fOutlineView->SetFocusRow(row, Select); } void BColumnListView::SetMouseTrackingEnabled(bool Enabled) { fOutlineView->SetMouseTrackingEnabled(Enabled); } list_view_type BColumnListView::SelectionMode() const { return fOutlineView->SelectionMode(); } void BColumnListView::Deselect(BRow* row) { fOutlineView->Deselect(row); } void BColumnListView::AddToSelection(BRow* row) { fOutlineView->AddToSelection(row); } void BColumnListView::DeselectAll() { fOutlineView->DeselectAll(); } BRow* BColumnListView::CurrentSelection(BRow* lastSelected) const { return fOutlineView->CurrentSelection(lastSelected); } void BColumnListView::SelectionChanged() { if (fSelectionMessage) Invoke(fSelectionMessage); } void BColumnListView::SetSelectionMessage(BMessage* message) { if (fSelectionMessage == message) return; delete fSelectionMessage; fSelectionMessage = message; } BMessage* BColumnListView::SelectionMessage() { return fSelectionMessage; } uint32 BColumnListView::SelectionCommand() const { if (fSelectionMessage) return fSelectionMessage->what; return 0; } void BColumnListView::SetSelectionMode(list_view_type mode) { fOutlineView->SetSelectionMode(mode); } void BColumnListView::SetSortingEnabled(bool enabled) { fSortingEnabled = enabled; fSortColumns.MakeEmpty(); fTitleView->Invalidate(); // Erase sort indicators } bool BColumnListView::SortingEnabled() const { return fSortingEnabled; } void BColumnListView::SetSortColumn(BColumn* column, bool add, bool ascending) { if (!SortingEnabled()) return; if (!add) fSortColumns.MakeEmpty(); if (!fSortColumns.HasItem(column)) fSortColumns.AddItem(column); column->fSortAscending = ascending; fTitleView->Invalidate(); fOutlineView->StartSorting(); } void BColumnListView::ClearSortColumns() { fSortColumns.MakeEmpty(); fTitleView->Invalidate(); // Erase sort indicators } void BColumnListView::AddStatusView(BView* view) { BRect bounds = Bounds(); float width = view->Bounds().Width(); if (width > bounds.Width() / 2) width = bounds.Width() / 2; fStatusView = view; Window()->BeginViewTransaction(); fHorizontalScrollBar->ResizeBy(-(width + 1), 0); fHorizontalScrollBar->MoveBy((width + 1), 0); AddChild(view); BRect viewRect(bounds); viewRect.right = width; viewRect.top = viewRect.bottom - B_H_SCROLL_BAR_HEIGHT; if (fBorderStyle == B_PLAIN_BORDER) viewRect.OffsetBy(1, -1); else if (fBorderStyle == B_FANCY_BORDER) viewRect.OffsetBy(2, -2); view->SetResizingMode(B_FOLLOW_LEFT | B_FOLLOW_BOTTOM); view->ResizeTo(viewRect.Width(), viewRect.Height()); view->MoveTo(viewRect.left, viewRect.top); Window()->EndViewTransaction(); } BView* BColumnListView::RemoveStatusView() { if (fStatusView) { float width = fStatusView->Bounds().Width(); Window()->BeginViewTransaction(); fStatusView->RemoveSelf(); fHorizontalScrollBar->MoveBy(-width, 0); fHorizontalScrollBar->ResizeBy(width, 0); Window()->EndViewTransaction(); } BView* view = fStatusView; fStatusView = 0; return view; } void BColumnListView::AddColumn(BColumn* column, int32 logicalFieldIndex) { ASSERT(column != NULL); column->fList = this; column->fFieldID = logicalFieldIndex; // sanity check. If there is already a field with this ID, remove it. for (int32 index = 0; index < fColumns.CountItems(); index++) { BColumn* existingColumn = (BColumn*) fColumns.ItemAt(index); if (existingColumn && existingColumn->fFieldID == logicalFieldIndex) { RemoveColumn(existingColumn); break; } } if (column->Width() < column->MinWidth()) column->SetWidth(column->MinWidth()); else if (column->Width() > column->MaxWidth()) column->SetWidth(column->MaxWidth()); fColumns.AddItem((void*) column); fTitleView->ColumnAdded(column); } void BColumnListView::MoveColumn(BColumn* column, int32 index) { ASSERT(column != NULL); fTitleView->MoveColumn(column, index); } void BColumnListView::RemoveColumn(BColumn* column) { if (fColumns.HasItem(column)) { SetColumnVisible(column, false); if (Window() != NULL) Window()->UpdateIfNeeded(); fColumns.RemoveItem(column); } } int32 BColumnListView::CountColumns() const { return fColumns.CountItems(); } BColumn* BColumnListView::ColumnAt(int32 field) const { return (BColumn*) fColumns.ItemAt(field); } void BColumnListView::SetColumnVisible(BColumn* column, bool visible) { fTitleView->SetColumnVisible(column, visible); } void BColumnListView::SetColumnVisible(int32 index, bool isVisible) { BColumn* column = ColumnAt(index); if (column) column->SetVisible(isVisible); } bool BColumnListView::IsColumnVisible(int32 index) const { BColumn* column = ColumnAt(index); if (column) return column->IsVisible(); return false; } void BColumnListView::SetColumnFlags(column_flags flags) { fTitleView->SetColumnFlags(flags); } void BColumnListView::ResizeColumnToPreferred(int32 index) { BColumn* column = ColumnAt(index); if (column == NULL) return; // get the preferred column width float width = fOutlineView->GetColumnPreferredWidth(column); // set it float oldWidth = column->Width(); column->SetWidth(width); fTitleView->ColumnResized(column, oldWidth); fOutlineView->Invalidate(); } void BColumnListView::ResizeAllColumnsToPreferred() { int32 count = CountColumns(); for (int32 i = 0; i < count; i++) ResizeColumnToPreferred(i); } const BRow* BColumnListView::RowAt(int32 Index, BRow* parentRow) const { if (parentRow == 0) return fOutlineView->RowList()->ItemAt(Index); return parentRow->fChildList ? parentRow->fChildList->ItemAt(Index) : NULL; } BRow* BColumnListView::RowAt(int32 Index, BRow* parentRow) { if (parentRow == 0) return fOutlineView->RowList()->ItemAt(Index); return parentRow->fChildList ? parentRow->fChildList->ItemAt(Index) : 0; } const BRow* BColumnListView::RowAt(BPoint point) const { float top; int32 indent; return fOutlineView->FindRow(point.y, &indent, &top); } BRow* BColumnListView::RowAt(BPoint point) { float top; int32 indent; return fOutlineView->FindRow(point.y, &indent, &top); } bool BColumnListView::GetRowRect(const BRow* row, BRect* outRect) const { return fOutlineView->FindRect(row, outRect); } bool BColumnListView::FindParent(BRow* row, BRow** _parent, bool* _isVisible) const { return fOutlineView->FindParent(row, _parent, _isVisible); } int32 BColumnListView::IndexOf(BRow* row) { return fOutlineView->IndexOf(row); } int32 BColumnListView::CountRows(BRow* parentRow) const { if (parentRow == 0) return fOutlineView->RowList()->CountItems(); if (parentRow->fChildList) return parentRow->fChildList->CountItems(); else return 0; } void BColumnListView::AddRow(BRow* row, BRow* parentRow) { AddRow(row, -1, parentRow); } void BColumnListView::AddRow(BRow* row, int32 index, BRow* parentRow) { row->fChildList = 0; row->fList = this; row->ValidateFields(); fOutlineView->AddRow(row, index, parentRow); } void BColumnListView::RemoveRow(BRow* row) { fOutlineView->RemoveRow(row); row->fList = NULL; } void BColumnListView::UpdateRow(BRow* row) { fOutlineView->UpdateRow(row); } void BColumnListView::ScrollTo(const BRow* row) { fOutlineView->ScrollTo(row); } void BColumnListView::ScrollTo(BPoint point) { fOutlineView->ScrollTo(point); } void BColumnListView::Clear() { fOutlineView->Clear(); } void BColumnListView::SetFont(const BFont* font, uint32 mask) { // This method is deprecated. fOutlineView->SetFont(font, mask); fTitleView->SetFont(font, mask); } void BColumnListView::SetFont(ColumnListViewFont font_num, const BFont* font, uint32 mask) { switch (font_num) { case B_FONT_ROW: fOutlineView->SetFont(font, mask); break; case B_FONT_HEADER: fTitleView->SetFont(font, mask); break; default: ASSERT(false); break; } } void BColumnListView::GetFont(ColumnListViewFont font_num, BFont* font) const { switch (font_num) { case B_FONT_ROW: fOutlineView->GetFont(font); break; case B_FONT_HEADER: fTitleView->GetFont(font); break; default: ASSERT(false); break; } } void BColumnListView::SetColor(ColumnListViewColor color_num, const rgb_color color) { if ((int)color_num < 0) { ASSERT(false); color_num = (ColumnListViewColor) 0; } if ((int)color_num >= (int)B_COLOR_TOTAL) { ASSERT(false); color_num = (ColumnListViewColor) (B_COLOR_TOTAL - 1); } fColorList[color_num] = color; } rgb_color BColumnListView::Color(ColumnListViewColor color_num) const { if ((int)color_num < 0) { ASSERT(false); color_num = (ColumnListViewColor) 0; } if ((int)color_num >= (int)B_COLOR_TOTAL) { ASSERT(false); color_num = (ColumnListViewColor) (B_COLOR_TOTAL - 1); } return fColorList[color_num]; } void BColumnListView::SetHighColor(rgb_color color) { BView::SetHighColor(color); // fOutlineView->Invalidate(); // Redraw things with the new color // Note that this will currently cause // an infinite loop, refreshing over and over. // A better solution is needed. } void BColumnListView::SetSelectionColor(rgb_color color) { fColorList[B_COLOR_SELECTION] = color; } void BColumnListView::SetBackgroundColor(rgb_color color) { fColorList[B_COLOR_BACKGROUND] = color; fOutlineView->Invalidate(); // Repaint with new color } void BColumnListView::SetEditColor(rgb_color color) { fColorList[B_COLOR_EDIT_BACKGROUND] = color; } const rgb_color BColumnListView::SelectionColor() const { return fColorList[B_COLOR_SELECTION]; } const rgb_color BColumnListView::BackgroundColor() const { return fColorList[B_COLOR_BACKGROUND]; } const rgb_color BColumnListView::EditColor() const { return fColorList[B_COLOR_EDIT_BACKGROUND]; } BPoint BColumnListView::SuggestTextPosition(const BRow* row, const BColumn* inColumn) const { BRect rect; GetRowRect(row, &rect); if (inColumn) { float leftEdge = MAX(kLeftMargin, LatchWidth()); for (int index = 0; index < fColumns.CountItems(); index++) { BColumn* column = (BColumn*) fColumns.ItemAt(index); if (!column->IsVisible()) continue; if (column == inColumn) { rect.left = leftEdge; rect.right = rect.left + column->Width(); break; } leftEdge += column->Width() + 1; } } font_height fh; fOutlineView->GetFontHeight(&fh); float baseline = floor(rect.top + fh.ascent + (rect.Height()+1-(fh.ascent+fh.descent))/2); return BPoint(rect.left + 8, baseline); } void BColumnListView::SetLatchWidth(float width) { fLatchWidth = width; Invalidate(); } float BColumnListView::LatchWidth() const { return fLatchWidth; } void BColumnListView::DrawLatch(BView* view, BRect rect, LatchType position, BRow*) { const int32 rectInset = 4; view->SetHighColor(0, 0, 0); // Make Square int32 sideLen = rect.IntegerWidth(); if (sideLen > rect.IntegerHeight()) sideLen = rect.IntegerHeight(); // Make Center int32 halfWidth = rect.IntegerWidth() / 2; int32 halfHeight = rect.IntegerHeight() / 2; int32 halfSide = sideLen / 2; float left = rect.left + halfWidth - halfSide; float top = rect.top + halfHeight - halfSide; BRect itemRect(left, top, left + sideLen, top + sideLen); // Why it is a pixel high? I don't know. itemRect.OffsetBy(0, -1); itemRect.InsetBy(rectInset, rectInset); // Make it an odd number of pixels wide, the latch looks better this way if ((itemRect.IntegerWidth() % 2) == 1) { itemRect.right += 1; itemRect.bottom += 1; } switch (position) { case B_OPEN_LATCH: view->StrokeRect(itemRect); view->StrokeLine( BPoint(itemRect.left + 2, (itemRect.top + itemRect.bottom) / 2), BPoint(itemRect.right - 2, (itemRect.top + itemRect.bottom) / 2)); break; case B_PRESSED_LATCH: view->StrokeRect(itemRect); view->StrokeLine( BPoint(itemRect.left + 2, (itemRect.top + itemRect.bottom) / 2), BPoint(itemRect.right - 2, (itemRect.top + itemRect.bottom) / 2)); view->StrokeLine( BPoint((itemRect.left + itemRect.right) / 2, itemRect.top + 2), BPoint((itemRect.left + itemRect.right) / 2, itemRect.bottom - 2)); view->InvertRect(itemRect); break; case B_CLOSED_LATCH: view->StrokeRect(itemRect); view->StrokeLine( BPoint(itemRect.left + 2, (itemRect.top + itemRect.bottom) / 2), BPoint(itemRect.right - 2, (itemRect.top + itemRect.bottom) / 2)); view->StrokeLine( BPoint((itemRect.left + itemRect.right) / 2, itemRect.top + 2), BPoint((itemRect.left + itemRect.right) / 2, itemRect.bottom - 2)); break; case B_NO_LATCH: // No drawing break; } } void BColumnListView::MakeFocus(bool isFocus) { if (fBorderStyle != B_NO_BORDER) { // Redraw focus marks around view Invalidate(); fHorizontalScrollBar->SetBorderHighlighted(isFocus); fVerticalScrollBar->SetBorderHighlighted(isFocus); } BView::MakeFocus(isFocus); } void BColumnListView::MessageReceived(BMessage* message) { // Propagate mouse wheel messages down to child, so that it can // scroll. Note we have done so, so we don't go into infinite // recursion if this comes back up here. if (message->what == B_MOUSE_WHEEL_CHANGED) { bool handled; if (message->FindBool("be:clvhandled", &handled) != B_OK) { message->AddBool("be:clvhandled", true); fOutlineView->MessageReceived(message); return; } } BView::MessageReceived(message); } void BColumnListView::KeyDown(const char* bytes, int32 numBytes) { char c = bytes[0]; switch (c) { case B_RIGHT_ARROW: case B_LEFT_ARROW: { float minVal, maxVal; fHorizontalScrollBar->GetRange(&minVal, &maxVal); float smallStep, largeStep; fHorizontalScrollBar->GetSteps(&smallStep, &largeStep); float oldVal = fHorizontalScrollBar->Value(); float newVal = oldVal; if (c == B_LEFT_ARROW) newVal -= smallStep; else if (c == B_RIGHT_ARROW) newVal += smallStep; if (newVal < minVal) newVal = minVal; else if (newVal > maxVal) newVal = maxVal; fHorizontalScrollBar->SetValue(newVal); break; } case B_DOWN_ARROW: fOutlineView->ChangeFocusRow(false, (modifiers() & B_CONTROL_KEY) == 0, (modifiers() & B_SHIFT_KEY) != 0); break; case B_UP_ARROW: fOutlineView->ChangeFocusRow(true, (modifiers() & B_CONTROL_KEY) == 0, (modifiers() & B_SHIFT_KEY) != 0); break; case B_PAGE_UP: case B_PAGE_DOWN: { float minValue, maxValue; fVerticalScrollBar->GetRange(&minValue, &maxValue); float smallStep, largeStep; fVerticalScrollBar->GetSteps(&smallStep, &largeStep); float currentValue = fVerticalScrollBar->Value(); float newValue = currentValue; if (c == B_PAGE_UP) newValue -= largeStep; else newValue += largeStep; if (newValue > maxValue) newValue = maxValue; else if (newValue < minValue) newValue = minValue; fVerticalScrollBar->SetValue(newValue); // Option + pgup or pgdn scrolls and changes the selection. if (modifiers() & B_OPTION_KEY) fOutlineView->MoveFocusToVisibleRect(); break; } case B_ENTER: Invoke(); break; case B_SPACE: fOutlineView->ToggleFocusRowSelection( (modifiers() & B_SHIFT_KEY) != 0); break; case '+': fOutlineView->ToggleFocusRowOpen(); break; default: BView::KeyDown(bytes, numBytes); } } void BColumnListView::AttachedToWindow() { if (!Messenger().IsValid()) SetTarget(Window()); if (SortingEnabled()) fOutlineView->StartSorting(); } void BColumnListView::WindowActivated(bool active) { fOutlineView->Invalidate(); // Focus and selection appearance changes with focus Invalidate(); // Redraw focus marks around view BView::WindowActivated(active); } void BColumnListView::Draw(BRect updateRect) { BRect rect = Bounds(); if (be_control_look != NULL) { uint32 flags = 0; if (IsFocus() && Window()->IsActive()) flags |= BControlLook::B_FOCUSED; rgb_color base = ui_color(B_PANEL_BACKGROUND_COLOR); BRect verticalScrollBarFrame; if (!fVerticalScrollBar->IsHidden()) verticalScrollBarFrame = fVerticalScrollBar->Frame(); BRect horizontalScrollBarFrame; if (!fHorizontalScrollBar->IsHidden()) horizontalScrollBarFrame = fHorizontalScrollBar->Frame(); if (fBorderStyle == B_NO_BORDER) { // We still draw the left/top border, but not focused. // The scrollbars cannot be displayed without frame and // it looks bad to have no frame only along the left/top // side. rgb_color borderColor = tint_color(base, B_DARKEN_2_TINT); SetHighColor(borderColor); StrokeLine(BPoint(rect.left, rect.bottom), BPoint(rect.left, rect.top)); StrokeLine(BPoint(rect.left + 1, rect.top), BPoint(rect.right, rect.top)); } be_control_look->DrawScrollViewFrame(this, rect, updateRect, verticalScrollBarFrame, horizontalScrollBarFrame, base, fBorderStyle, flags); return; } BRect cornerRect(rect.right - B_V_SCROLL_BAR_WIDTH, rect.bottom - B_H_SCROLL_BAR_HEIGHT, rect.right, rect.bottom); if (fBorderStyle == B_PLAIN_BORDER) { BView::SetHighColor(0, 0, 0); StrokeRect(rect); cornerRect.OffsetBy(-1, -1); } else if (fBorderStyle == B_FANCY_BORDER) { bool isFocus = IsFocus() && Window()->IsActive(); if (isFocus) { // TODO: Need to find focus color programatically BView::SetHighColor(0, 0, 190); } else BView::SetHighColor(255, 255, 255); StrokeRect(rect); if (!isFocus) BView::SetHighColor(184, 184, 184); else BView::SetHighColor(152, 152, 152); rect.InsetBy(1,1); StrokeRect(rect); cornerRect.OffsetBy(-2, -2); } BView::SetHighColor(ui_color(B_PANEL_BACKGROUND_COLOR)); // fills lower right rect between scroll bars FillRect(cornerRect); } void BColumnListView::SaveState(BMessage* msg) { msg->MakeEmpty(); for (int32 i = 0; BColumn* col = (BColumn*)fColumns.ItemAt(i); i++) { msg->AddInt32("ID",col->fFieldID); msg->AddFloat("width", col->fWidth); msg->AddBool("visible", col->fVisible); } msg->AddBool("sortingenabled", fSortingEnabled); if (fSortingEnabled) { for (int32 i = 0; BColumn* col = (BColumn*)fSortColumns.ItemAt(i); i++) { msg->AddInt32("sortID", col->fFieldID); msg->AddBool("sortascending", col->fSortAscending); } } } void BColumnListView::LoadState(BMessage* msg) { int32 id; for (int i = 0; msg->FindInt32("ID", i, &id) == B_OK; i++) { for (int j = 0; BColumn* column = (BColumn*)fColumns.ItemAt(j); j++) { if (column->fFieldID == id) { // move this column to position 'i' and set its attributes MoveColumn(column, i); float width; if (msg->FindFloat("width", i, &width) == B_OK) column->SetWidth(width); bool visible; if (msg->FindBool("visible", i, &visible) == B_OK) column->SetVisible(visible); } } } bool b; if (msg->FindBool("sortingenabled", &b) == B_OK) { SetSortingEnabled(b); for (int k = 0; msg->FindInt32("sortID", k, &id) == B_OK; k++) { for (int j = 0; BColumn* column = (BColumn*)fColumns.ItemAt(j); j++) { if (column->fFieldID == id) { // add this column to the sort list bool value; if (msg->FindBool("sortascending", k, &value) == B_OK) SetSortColumn(column, true, value); } } } } } void BColumnListView::SetEditMode(bool state) { fOutlineView->SetEditMode(state); fTitleView->SetEditMode(state); } void BColumnListView::Refresh() { if (LockLooper()) { Invalidate(); fOutlineView->FixScrollBar (true); fOutlineView->Invalidate(); Window()->UpdateIfNeeded(); UnlockLooper(); } } BSize BColumnListView::MinSize() { BSize size; size.width = 100; size.height = kTitleHeight + 4 * B_H_SCROLL_BAR_HEIGHT; if (!fHorizontalScrollBar->IsHidden()) size.height += fHorizontalScrollBar->Frame().Height() + 1; // TODO: Take border size into account return BLayoutUtils::ComposeSize(ExplicitMinSize(), size); } BSize BColumnListView::PreferredSize() { BSize size = MinSize(); size.height += ceilf(be_plain_font->Size()) * 20; int32 count = CountColumns(); if (count > 0) { // return MinSize().width if there are no columns. size.width = 40.0f; for (int32 i = 0; i < count; i++) { BColumn* column = ColumnAt(i); if (column != NULL) size.width += fOutlineView->GetColumnPreferredWidth(column); } } return BLayoutUtils::ComposeSize(ExplicitPreferredSize(), size); } BSize BColumnListView::MaxSize() { BSize size(B_SIZE_UNLIMITED, B_SIZE_UNLIMITED); return BLayoutUtils::ComposeSize(ExplicitMaxSize(), size); } void BColumnListView::InvalidateLayout(bool descendants) { BView::InvalidateLayout(descendants); } void BColumnListView::DoLayout() { if (!(Flags() & B_SUPPORTS_LAYOUT)) return; BRect titleRect; BRect outlineRect; BRect vScrollBarRect; BRect hScrollBarRect; _GetChildViewRects(Bounds(), !fHorizontalScrollBar->IsHidden(), titleRect, outlineRect, vScrollBarRect, hScrollBarRect); fTitleView->MoveTo(titleRect.LeftTop()); fTitleView->ResizeTo(titleRect.Width(), titleRect.Height()); fOutlineView->MoveTo(outlineRect.LeftTop()); fOutlineView->ResizeTo(outlineRect.Width(), outlineRect.Height()); fVerticalScrollBar->MoveTo(vScrollBarRect.LeftTop()); fVerticalScrollBar->ResizeTo(vScrollBarRect.Width(), vScrollBarRect.Height()); fHorizontalScrollBar->MoveTo(hScrollBarRect.LeftTop()); fHorizontalScrollBar->ResizeTo(hScrollBarRect.Width(), hScrollBarRect.Height()); fOutlineView->FixScrollBar(true); } void BColumnListView::_Init(bool showHorizontalScrollbar) { SetViewColor(B_TRANSPARENT_32_BIT); BRect bounds(Bounds()); if (bounds.Width() <= 0) bounds.right = 100; if (bounds.Height() <= 0) bounds.bottom = 100; for (int i = 0; i < (int)B_COLOR_TOTAL; i++) fColorList[i] = kColor[i]; BRect titleRect; BRect outlineRect; BRect vScrollBarRect; BRect hScrollBarRect; _GetChildViewRects(bounds, showHorizontalScrollbar, titleRect, outlineRect, vScrollBarRect, hScrollBarRect); fOutlineView = new OutlineView(outlineRect, &fColumns, &fSortColumns, this); AddChild(fOutlineView); fTitleView = new TitleView(titleRect, fOutlineView, &fColumns, &fSortColumns, this, B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP); AddChild(fTitleView); fVerticalScrollBar = new BScrollBar(vScrollBarRect, "vertical_scroll_bar", fOutlineView, 0.0, bounds.Height(), B_VERTICAL); AddChild(fVerticalScrollBar); fHorizontalScrollBar = new BScrollBar(hScrollBarRect, "horizontal_scroll_bar", fTitleView, 0.0, bounds.Width(), B_HORIZONTAL); AddChild(fHorizontalScrollBar); if (!showHorizontalScrollbar) fHorizontalScrollBar->Hide(); fOutlineView->FixScrollBar(true); } void BColumnListView::_GetChildViewRects(const BRect& bounds, bool showHorizontalScrollbar, BRect& titleRect, BRect& outlineRect, BRect& vScrollBarRect, BRect& hScrollBarRect) { titleRect = bounds; titleRect.bottom = titleRect.top + kTitleHeight; #if !LOWER_SCROLLBAR titleRect.right -= B_V_SCROLL_BAR_WIDTH; #endif outlineRect = bounds; outlineRect.top = titleRect.bottom + 1.0; outlineRect.right -= B_V_SCROLL_BAR_WIDTH; if (showHorizontalScrollbar) outlineRect.bottom -= B_H_SCROLL_BAR_HEIGHT; vScrollBarRect = bounds; #if LOWER_SCROLLBAR vScrollBarRect.top += kTitleHeight; #endif vScrollBarRect.left = vScrollBarRect.right - B_V_SCROLL_BAR_WIDTH; if (showHorizontalScrollbar) vScrollBarRect.bottom -= B_H_SCROLL_BAR_HEIGHT; hScrollBarRect = bounds; hScrollBarRect.top = hScrollBarRect.bottom - B_H_SCROLL_BAR_HEIGHT; hScrollBarRect.right -= B_V_SCROLL_BAR_WIDTH; // Adjust stuff so the border will fit. if (fBorderStyle == B_PLAIN_BORDER || fBorderStyle == B_NO_BORDER) { titleRect.InsetBy(1, 0); titleRect.OffsetBy(0, 1); outlineRect.InsetBy(1, 1); } else if (fBorderStyle == B_FANCY_BORDER) { titleRect.InsetBy(2, 0); titleRect.OffsetBy(0, 2); outlineRect.InsetBy(2, 2); vScrollBarRect.OffsetBy(-1, 0); #if LOWER_SCROLLBAR vScrollBarRect.top += 2; vScrollBarRect.bottom -= 1; #else vScrollBarRect.InsetBy(0, 1); #endif hScrollBarRect.OffsetBy(0, -1); hScrollBarRect.InsetBy(1, 0); } } // #pragma mark - TitleView::TitleView(BRect rect, OutlineView* horizontalSlave, BList* visibleColumns, BList* sortColumns, BColumnListView* listView, uint32 resizingMode) : BView(rect, "title_view", resizingMode, B_WILL_DRAW | B_FRAME_EVENTS), fOutlineView(horizontalSlave), fColumns(visibleColumns), fSortColumns(sortColumns), // fColumnsWidth(0), fVisibleRect(rect.OffsetToCopy(0, 0)), fCurrentState(INACTIVE), fColumnPop(NULL), fMasterView(listView), fEditMode(false), fColumnFlags(B_ALLOW_COLUMN_MOVE | B_ALLOW_COLUMN_RESIZE | B_ALLOW_COLUMN_POPUP | B_ALLOW_COLUMN_REMOVE) { SetViewColor(B_TRANSPARENT_COLOR); #if DOUBLE_BUFFERED_COLUMN_RESIZE // xxx this needs to be smart about the size of the backbuffer. BRect doubleBufferRect(0, 0, 600, 35); fDrawBuffer = new BBitmap(doubleBufferRect, B_RGB32, true); fDrawBufferView = new BView(doubleBufferRect, "double_buffer_view", B_FOLLOW_ALL_SIDES, 0); fDrawBuffer->Lock(); fDrawBuffer->AddChild(fDrawBufferView); fDrawBuffer->Unlock(); #endif fUpSortArrow = new BBitmap(BRect(0, 0, 7, 7), B_CMAP8); fDownSortArrow = new BBitmap(BRect(0, 0, 7, 7), B_CMAP8); fUpSortArrow->SetBits((const void*) kUpSortArrow8x8, 64, 0, B_CMAP8); fDownSortArrow->SetBits((const void*) kDownSortArrow8x8, 64, 0, B_CMAP8); fResizeCursor = new BCursor(kResizeCursorData); fMinResizeCursor = new BCursor(kMinResizeCursorData); fMaxResizeCursor = new BCursor(kMaxResizeCursorData); fColumnMoveCursor = new BCursor(kColumnMoveCursorData); FixScrollBar(true); } TitleView::~TitleView() { delete fColumnPop; fColumnPop = NULL; #if DOUBLE_BUFFERED_COLUMN_RESIZE delete fDrawBuffer; #endif delete fUpSortArrow; delete fDownSortArrow; delete fResizeCursor; delete fMaxResizeCursor; delete fMinResizeCursor; delete fColumnMoveCursor; } void TitleView::ColumnAdded(BColumn* column) { // fColumnsWidth += column->Width(); FixScrollBar(false); Invalidate(); } void TitleView::ColumnResized(BColumn* column, float oldWidth) { // fColumnsWidth += column->Width() - oldWidth; FixScrollBar(false); Invalidate(); } void TitleView::SetColumnVisible(BColumn* column, bool visible) { if (column->fVisible == visible) return; // If setting it visible, do this first so we can find its position // to invalidate. If hiding it, do it last. if (visible) column->fVisible = visible; BRect titleInvalid; GetTitleRect(column, &titleInvalid); // Now really set the visibility column->fVisible = visible; // if (visible) // fColumnsWidth += column->Width(); // else // fColumnsWidth -= column->Width(); BRect outlineInvalid(fOutlineView->VisibleRect()); outlineInvalid.left = titleInvalid.left; titleInvalid.right = outlineInvalid.right; Invalidate(titleInvalid); fOutlineView->Invalidate(outlineInvalid); } void TitleView::GetTitleRect(BColumn* findColumn, BRect* _rect) { float leftEdge = MAX(kLeftMargin, fMasterView->LatchWidth()); int32 numColumns = fColumns->CountItems(); for (int index = 0; index < numColumns; index++) { BColumn* column = (BColumn*) fColumns->ItemAt(index); if (!column->IsVisible()) continue; if (column == findColumn) { _rect->Set(leftEdge, 0, leftEdge + column->Width(), fVisibleRect.bottom); return; } leftEdge += column->Width() + 1; } TRESPASS(); } int32 TitleView::FindColumn(BPoint position, float* _leftEdge) { float leftEdge = MAX(kLeftMargin, fMasterView->LatchWidth()); int32 numColumns = fColumns->CountItems(); for (int index = 0; index < numColumns; index++) { BColumn* column = (BColumn*) fColumns->ItemAt(index); if (!column->IsVisible()) continue; if (leftEdge > position.x) break; if (position.x >= leftEdge && position.x <= leftEdge + column->Width()) { *_leftEdge = leftEdge; return index; } leftEdge += column->Width() + 1; } return 0; } void TitleView::FixScrollBar(bool scrollToFit) { BScrollBar* hScrollBar = ScrollBar(B_HORIZONTAL); if (hScrollBar == NULL) return; float virtualWidth = _VirtualWidth(); if (virtualWidth > fVisibleRect.Width()) { hScrollBar->SetProportion(fVisibleRect.Width() / virtualWidth); // Perform the little trick if the user is scrolled over too far. // See OutlineView::FixScrollBar for a more in depth explanation float maxScrollBarValue = virtualWidth - fVisibleRect.Width(); if (scrollToFit || hScrollBar->Value() <= maxScrollBarValue) { hScrollBar->SetRange(0.0, maxScrollBarValue); hScrollBar->SetSteps(50, fVisibleRect.Width()); } } else if (hScrollBar->Value() == 0.0) { // disable scroll bar. hScrollBar->SetRange(0.0, 0.0); } } void TitleView::DragSelectedColumn(BPoint position) { float invalidLeft = fSelectedColumnRect.left; float invalidRight = fSelectedColumnRect.right; float leftEdge; int32 columnIndex = FindColumn(position, &leftEdge); fSelectedColumnRect.OffsetTo(leftEdge, 0); MoveColumn(fSelectedColumn, columnIndex); fSelectedColumn->fVisible = true; ComputeDragBoundries(fSelectedColumn, position); // Redraw the new column position GetTitleRect(fSelectedColumn, &fSelectedColumnRect); invalidLeft = MIN(fSelectedColumnRect.left, invalidLeft); invalidRight = MAX(fSelectedColumnRect.right, invalidRight); Invalidate(BRect(invalidLeft, 0, invalidRight, fVisibleRect.bottom)); fOutlineView->Invalidate(BRect(invalidLeft, 0, invalidRight, fOutlineView->VisibleRect().bottom)); DrawTitle(this, fSelectedColumnRect, fSelectedColumn, true); } void TitleView::MoveColumn(BColumn* column, int32 index) { fColumns->RemoveItem((void*) column); if (-1 == index) { // Re-add the column at the end of the list. fColumns->AddItem((void*) column); } else { fColumns->AddItem((void*) column, index); } } void TitleView::SetColumnFlags(column_flags flags) { fColumnFlags = flags; } void TitleView::ResizeSelectedColumn(BPoint position, bool preferred) { float minWidth = fSelectedColumn->MinWidth(); float maxWidth = fSelectedColumn->MaxWidth(); float oldWidth = fSelectedColumn->Width(); float originalEdge = fSelectedColumnRect.left + oldWidth; if (preferred) { float width = fOutlineView->GetColumnPreferredWidth(fSelectedColumn); fSelectedColumn->SetWidth(width); } else if (position.x > fSelectedColumnRect.left + maxWidth) fSelectedColumn->SetWidth(maxWidth); else if (position.x < fSelectedColumnRect.left + minWidth) fSelectedColumn->SetWidth(minWidth); else fSelectedColumn->SetWidth(position.x - fSelectedColumnRect.left - 1); float dX = fSelectedColumnRect.left + fSelectedColumn->Width() - originalEdge; if (dX != 0) { float columnHeight = fVisibleRect.Height(); BRect originalRect(originalEdge, 0, 1000000.0, columnHeight); BRect movedRect(originalRect); movedRect.OffsetBy(dX, 0); // Update the size of the title column BRect sourceRect(0, 0, fSelectedColumn->Width(), columnHeight); BRect destRect(sourceRect); destRect.OffsetBy(fSelectedColumnRect.left, 0); #if DOUBLE_BUFFERED_COLUMN_RESIZE fDrawBuffer->Lock(); DrawTitle(fDrawBufferView, sourceRect, fSelectedColumn, false); fDrawBufferView->Sync(); fDrawBuffer->Unlock(); CopyBits(originalRect, movedRect); DrawBitmap(fDrawBuffer, sourceRect, destRect); #else CopyBits(originalRect, movedRect); DrawTitle(this, destRect, fSelectedColumn, false); #endif // Update the body view BRect slaveSize = fOutlineView->VisibleRect(); BRect slaveSource(originalRect); slaveSource.bottom = slaveSize.bottom; BRect slaveDest(movedRect); slaveDest.bottom = slaveSize.bottom; fOutlineView->CopyBits(slaveSource, slaveDest); fOutlineView->RedrawColumn(fSelectedColumn, fSelectedColumnRect.left, fResizingFirstColumn); // fColumnsWidth += dX; // Update the cursor if (fSelectedColumn->Width() == minWidth) SetViewCursor(fMinResizeCursor, true); else if (fSelectedColumn->Width() == maxWidth) SetViewCursor(fMaxResizeCursor, true); else SetViewCursor(fResizeCursor, true); ColumnResized(fSelectedColumn, oldWidth); } } void TitleView::ComputeDragBoundries(BColumn* findColumn, BPoint) { float previousColumnLeftEdge = -1000000.0; float nextColumnRightEdge = 1000000.0; bool foundColumn = false; float leftEdge = MAX(kLeftMargin, fMasterView->LatchWidth()); int32 numColumns = fColumns->CountItems(); for (int index = 0; index < numColumns; index++) { BColumn* column = (BColumn*) fColumns->ItemAt(index); if (!column->IsVisible()) continue; if (column == findColumn) { foundColumn = true; continue; } if (foundColumn) { nextColumnRightEdge = leftEdge + column->Width(); break; } else previousColumnLeftEdge = leftEdge; leftEdge += column->Width() + 1; } float rightEdge = leftEdge + findColumn->Width(); fLeftDragBoundry = MIN(previousColumnLeftEdge + findColumn->Width(), leftEdge); fRightDragBoundry = MAX(nextColumnRightEdge, rightEdge); } void TitleView::DrawTitle(BView* view, BRect rect, BColumn* column, bool depressed) { BRect drawRect; rgb_color borderColor = mix_color( fMasterView->Color(B_COLOR_HEADER_BACKGROUND), make_color(0, 0, 0), 128); rgb_color backgroundColor; rgb_color bevelHigh; rgb_color bevelLow; // Want exterior borders to overlap. if (be_control_look == NULL) { rect.right += 1; drawRect = rect; drawRect.InsetBy(2, 2); if (depressed) { backgroundColor = mix_color( fMasterView->Color(B_COLOR_HEADER_BACKGROUND), make_color(0, 0, 0), 64); bevelHigh = mix_color(backgroundColor, make_color(0, 0, 0), 64); bevelLow = mix_color(backgroundColor, make_color(255, 255, 255), 128); drawRect.left++; drawRect.top++; } else { backgroundColor = fMasterView->Color(B_COLOR_HEADER_BACKGROUND); bevelHigh = mix_color(backgroundColor, make_color(255, 255, 255), 192); bevelLow = mix_color(backgroundColor, make_color(0, 0, 0), 64); drawRect.bottom--; drawRect.right--; } } else { drawRect = rect; } font_height fh; GetFontHeight(&fh); float baseline = floor(drawRect.top + fh.ascent + (drawRect.Height() + 1 - (fh.ascent + fh.descent)) / 2); if (be_control_look != NULL) { BRect bgRect = rect; rgb_color base = ui_color(B_PANEL_BACKGROUND_COLOR); view->SetHighColor(tint_color(base, B_DARKEN_2_TINT)); view->StrokeLine(bgRect.LeftBottom(), bgRect.RightBottom()); bgRect.bottom--; bgRect.right--; if (depressed) base = tint_color(base, B_DARKEN_1_TINT); be_control_look->DrawButtonBackground(view, bgRect, rect, base, 0, BControlLook::B_TOP_BORDER | BControlLook::B_BOTTOM_BORDER); view->SetHighColor(tint_color(ui_color(B_PANEL_BACKGROUND_COLOR), B_DARKEN_2_TINT)); view->StrokeLine(rect.RightTop(), rect.RightBottom()); } else { view->SetHighColor(borderColor); view->StrokeRect(rect); view->BeginLineArray(4); view->AddLine(BPoint(rect.left + 1, rect.top + 1), BPoint(rect.right - 1, rect.top + 1), bevelHigh); view->AddLine(BPoint(rect.left + 1, rect.top + 1), BPoint(rect.left + 1, rect.bottom - 1), bevelHigh); view->AddLine(BPoint(rect.right - 1, rect.top + 1), BPoint(rect.right - 1, rect.bottom - 1), bevelLow); view->AddLine(BPoint(rect.left + 2, rect.bottom-1), BPoint(rect.right - 1, rect.bottom - 1), bevelLow); view->EndLineArray(); view->SetHighColor(backgroundColor); view->SetLowColor(backgroundColor); view->FillRect(rect.InsetByCopy(2, 2)); } // If no column given, nothing else to draw. if (!column) return; view->SetHighColor(fMasterView->Color(B_COLOR_HEADER_TEXT)); BFont font; GetFont(&font); view->SetFont(&font); int sortIndex = fSortColumns->IndexOf(column); if (sortIndex >= 0) { // Draw sort notation. BPoint upperLeft(drawRect.right - kSortIndicatorWidth, baseline); if (fSortColumns->CountItems() > 1) { char str[256]; sprintf(str, "%d", sortIndex + 1); const float w = view->StringWidth(str); upperLeft.x -= w; view->SetDrawingMode(B_OP_COPY); view->MovePenTo(BPoint(upperLeft.x + kSortIndicatorWidth, baseline)); view->DrawString(str); } float bmh = fDownSortArrow->Bounds().Height()+1; view->SetDrawingMode(B_OP_OVER); if (column->fSortAscending) { BPoint leftTop(upperLeft.x, drawRect.top + (drawRect.IntegerHeight() - fDownSortArrow->Bounds().IntegerHeight()) / 2); view->DrawBitmapAsync(fDownSortArrow, leftTop); } else { BPoint leftTop(upperLeft.x, drawRect.top + (drawRect.IntegerHeight() - fUpSortArrow->Bounds().IntegerHeight()) / 2); view->DrawBitmapAsync(fUpSortArrow, leftTop); } upperLeft.y = baseline - bmh + floor((fh.ascent + fh.descent - bmh) / 2); if (upperLeft.y < drawRect.top) upperLeft.y = drawRect.top; // Adjust title stuff for sort indicator drawRect.right = upperLeft.x - 2; } if (drawRect.right > drawRect.left) { #if CONSTRAIN_CLIPPING_REGION BRegion clipRegion(drawRect); view->PushState(); view->ConstrainClippingRegion(&clipRegion); #endif view->MovePenTo(BPoint(drawRect.left + 8, baseline)); view->SetDrawingMode(B_OP_OVER); view->SetHighColor(fMasterView->Color(B_COLOR_HEADER_TEXT)); column->DrawTitle(drawRect, view); #if CONSTRAIN_CLIPPING_REGION view->PopState(); #endif } } float TitleView::_VirtualWidth() const { float width = 0.0f; int32 count = fColumns->CountItems(); for (int32 i = 0; i < count; i++) { BColumn* column = reinterpret_cast<BColumn*>(fColumns->ItemAt(i)); width += column->Width(); } return width + MAX(kLeftMargin, fMasterView->LatchWidth()) + kRightMargin * 2; } void TitleView::Draw(BRect invalidRect) { float columnLeftEdge = MAX(kLeftMargin, fMasterView->LatchWidth()); for (int32 columnIndex = 0; columnIndex < fColumns->CountItems(); columnIndex++) { BColumn* column = (BColumn*) fColumns->ItemAt(columnIndex); if (!column->IsVisible()) continue; if (columnLeftEdge > invalidRect.right) break; if (columnLeftEdge + column->Width() >= invalidRect.left) { BRect titleRect(columnLeftEdge, 0, columnLeftEdge + column->Width(), fVisibleRect.Height()); DrawTitle(this, titleRect, column, (fCurrentState == DRAG_COLUMN_INSIDE_TITLE && fSelectedColumn == column)); } columnLeftEdge += column->Width() + 1; } // Bevels for right title margin if (columnLeftEdge <= invalidRect.right) { BRect titleRect(columnLeftEdge, 0, Bounds().right + 2, fVisibleRect.Height()); DrawTitle(this, titleRect, NULL, false); } // Bevels for left title margin if (invalidRect.left < MAX(kLeftMargin, fMasterView->LatchWidth())) { BRect titleRect(0, 0, MAX(kLeftMargin, fMasterView->LatchWidth()) - 1, fVisibleRect.Height()); DrawTitle(this, titleRect, NULL, false); } #if DRAG_TITLE_OUTLINE // (Internal) Column Drag Indicator if (fCurrentState == DRAG_COLUMN_INSIDE_TITLE) { BRect dragRect(fSelectedColumnRect); dragRect.OffsetTo(fCurrentDragPosition.x - fClickPoint.x, 0); if (dragRect.Intersects(invalidRect)) { SetHighColor(0, 0, 255); StrokeRect(dragRect); } } #endif } void TitleView::ScrollTo(BPoint position) { fOutlineView->ScrollBy(position.x - fVisibleRect.left, 0); fVisibleRect.OffsetTo(position.x, position.y); // Perform the little trick if the user is scrolled over too far. // See OutlineView::ScrollTo for a more in depth explanation float maxScrollBarValue = _VirtualWidth() - fVisibleRect.Width(); BScrollBar* hScrollBar = ScrollBar(B_HORIZONTAL); float min, max; hScrollBar->GetRange(&min, &max); if (max != maxScrollBarValue && position.x > maxScrollBarValue) FixScrollBar(true); _inherited::ScrollTo(position); } void TitleView::MessageReceived(BMessage* message) { if (message->what == kToggleColumn) { int32 num; if (message->FindInt32("be:field_num", &num) == B_OK) { for (int index = 0; index < fColumns->CountItems(); index++) { BColumn* column = (BColumn*) fColumns->ItemAt(index); if (!column) continue; if (column->LogicalFieldNum() == num) column->SetVisible(!column->IsVisible()); } } return; } else { BView::MessageReceived(message); } } void TitleView::MouseDown(BPoint position) { if(fEditMode) return; int32 buttons = 1; Window()->CurrentMessage()->FindInt32("buttons", &buttons); if (buttons == B_SECONDARY_MOUSE_BUTTON && (fColumnFlags & B_ALLOW_COLUMN_POPUP)) { // Right mouse button -- bring up menu to show/hide columns. if (!fColumnPop) fColumnPop = new BPopUpMenu("Columns", false, false); fColumnPop->RemoveItems(0, fColumnPop->CountItems(), true); BMessenger me(this); for (int index = 0; index < fColumns->CountItems(); index++) { BColumn* column = (BColumn*) fColumns->ItemAt(index); if (!column) continue; BString name; column->GetColumnName(&name); BMessage* msg = new BMessage(kToggleColumn); msg->AddInt32("be:field_num", column->LogicalFieldNum()); BMenuItem* it = new BMenuItem(name.String(), msg); it->SetMarked(column->IsVisible()); it->SetTarget(me); fColumnPop->AddItem(it); } BPoint screenPosition = ConvertToScreen(position); BRect sticky(screenPosition, screenPosition); sticky.InsetBy(-5, -5); fColumnPop->Go(ConvertToScreen(position), true, false, sticky, true); return; } fResizingFirstColumn = true; float leftEdge = MAX(kLeftMargin, fMasterView->LatchWidth()); for (int index = 0; index < fColumns->CountItems(); index++) { BColumn* column = (BColumn*) fColumns->ItemAt(index); if (!column->IsVisible()) continue; if (leftEdge > position.x + kColumnResizeAreaWidth / 2) break; // Check for resizing a column float rightEdge = leftEdge + column->Width(); if (column->ShowHeading()) { if (position.x > rightEdge - kColumnResizeAreaWidth / 2 && position.x < rightEdge + kColumnResizeAreaWidth / 2 && column->MaxWidth() > column->MinWidth() && (fColumnFlags & B_ALLOW_COLUMN_RESIZE)) { int32 clicks = 0; Window()->CurrentMessage()->FindInt32("clicks", &clicks); if (clicks == 2) { ResizeSelectedColumn(position, true); fCurrentState = INACTIVE; break; } fCurrentState = RESIZING_COLUMN; fSelectedColumn = column; fSelectedColumnRect.Set(leftEdge, 0, rightEdge, fVisibleRect.Height()); fClickPoint = BPoint(position.x - rightEdge - 1, position.y - fSelectedColumnRect.top); SetMouseEventMask(B_POINTER_EVENTS, B_LOCK_WINDOW_FOCUS | B_NO_POINTER_HISTORY); break; } fResizingFirstColumn = false; // Check for clicking on a column. if (position.x > leftEdge && position.x < rightEdge) { fCurrentState = PRESSING_COLUMN; fSelectedColumn = column; fSelectedColumnRect.Set(leftEdge, 0, rightEdge, fVisibleRect.Height()); DrawTitle(this, fSelectedColumnRect, fSelectedColumn, true); fClickPoint = BPoint(position.x - fSelectedColumnRect.left, position.y - fSelectedColumnRect.top); SetMouseEventMask(B_POINTER_EVENTS, B_LOCK_WINDOW_FOCUS | B_NO_POINTER_HISTORY); break; } } leftEdge = rightEdge + 1; } } void TitleView::MouseMoved(BPoint position, uint32 transit, const BMessage* dragMessage) { if (fEditMode) return; // Handle column manipulation switch (fCurrentState) { case RESIZING_COLUMN: ResizeSelectedColumn(position - BPoint(fClickPoint.x, 0)); break; case PRESSING_COLUMN: { if (abs((int32)(position.x - (fClickPoint.x + fSelectedColumnRect.left))) > kColumnResizeAreaWidth || abs((int32)(position.y - (fClickPoint.y + fSelectedColumnRect.top))) > kColumnResizeAreaWidth) { // User has moved the mouse more than the tolerable amount, // initiate a drag. if (transit == B_INSIDE_VIEW || transit == B_ENTERED_VIEW) { if(fColumnFlags & B_ALLOW_COLUMN_MOVE) { fCurrentState = DRAG_COLUMN_INSIDE_TITLE; ComputeDragBoundries(fSelectedColumn, position); SetViewCursor(fColumnMoveCursor, true); #if DRAG_TITLE_OUTLINE BRect invalidRect(fSelectedColumnRect); invalidRect.OffsetTo(position.x - fClickPoint.x, 0); fCurrentDragPosition = position; Invalidate(invalidRect); #endif } } else { if(fColumnFlags & B_ALLOW_COLUMN_REMOVE) { // Dragged outside view fCurrentState = DRAG_COLUMN_OUTSIDE_TITLE; fSelectedColumn->SetVisible(false); BRect dragRect(fSelectedColumnRect); // There is a race condition where the mouse may have // moved by the time we get to handle this message. // If the user drags a column very quickly, this // results in the annoying bug where the cursor is // outside of the rectangle that is being dragged // around. Call GetMouse with the checkQueue flag set // to false so we can get the most recent position of // the mouse. This minimizes this problem (although // it is currently not possible to completely eliminate // it). uint32 buttons; GetMouse(&position, &buttons, false); dragRect.OffsetTo(position.x - fClickPoint.x, position.y - dragRect.Height() / 2); BeginRectTracking(dragRect, B_TRACK_WHOLE_RECT); } } } break; } case DRAG_COLUMN_INSIDE_TITLE: { if (transit == B_EXITED_VIEW && (fColumnFlags & B_ALLOW_COLUMN_REMOVE)) { // Dragged outside view fCurrentState = DRAG_COLUMN_OUTSIDE_TITLE; fSelectedColumn->SetVisible(false); BRect dragRect(fSelectedColumnRect); // See explanation above. uint32 buttons; GetMouse(&position, &buttons, false); dragRect.OffsetTo(position.x - fClickPoint.x, position.y - fClickPoint.y); BeginRectTracking(dragRect, B_TRACK_WHOLE_RECT); } else if (position.x < fLeftDragBoundry || position.x > fRightDragBoundry) { DragSelectedColumn(position - BPoint(fClickPoint.x, 0)); } #if DRAG_TITLE_OUTLINE // Set up the invalid rect to include the rect for the previous // position of the drag rect, as well as the new one. BRect invalidRect(fSelectedColumnRect); invalidRect.OffsetTo(fCurrentDragPosition.x - fClickPoint.x, 0); if (position.x < fCurrentDragPosition.x) invalidRect.left -= fCurrentDragPosition.x - position.x; else invalidRect.right += position.x - fCurrentDragPosition.x; fCurrentDragPosition = position; Invalidate(invalidRect); #endif break; } case DRAG_COLUMN_OUTSIDE_TITLE: if (transit == B_ENTERED_VIEW) { // Drag back into view EndRectTracking(); fCurrentState = DRAG_COLUMN_INSIDE_TITLE; fSelectedColumn->SetVisible(true); DragSelectedColumn(position - BPoint(fClickPoint.x, 0)); } break; case INACTIVE: // Check for cursor changes if we are over the resize area for // a column. BColumn* resizeColumn = 0; float leftEdge = MAX(kLeftMargin, fMasterView->LatchWidth()); for (int index = 0; index < fColumns->CountItems(); index++) { BColumn* column = (BColumn*) fColumns->ItemAt(index); if (!column->IsVisible()) continue; if (leftEdge > position.x + kColumnResizeAreaWidth / 2) break; float rightEdge = leftEdge + column->Width(); if (position.x > rightEdge - kColumnResizeAreaWidth / 2 && position.x < rightEdge + kColumnResizeAreaWidth / 2 && column->MaxWidth() > column->MinWidth()) { resizeColumn = column; break; } leftEdge = rightEdge + 1; } // Update the cursor if (resizeColumn) { if (resizeColumn->Width() == resizeColumn->MinWidth()) SetViewCursor(fMinResizeCursor, true); else if (resizeColumn->Width() == resizeColumn->MaxWidth()) SetViewCursor(fMaxResizeCursor, true); else SetViewCursor(fResizeCursor, true); } else SetViewCursor(B_CURSOR_SYSTEM_DEFAULT, true); break; } } void TitleView::MouseUp(BPoint position) { if (fEditMode) return; switch (fCurrentState) { case RESIZING_COLUMN: ResizeSelectedColumn(position - BPoint(fClickPoint.x, 0)); fCurrentState = INACTIVE; FixScrollBar(false); break; case PRESSING_COLUMN: { if (fMasterView->SortingEnabled()) { if (fSortColumns->HasItem(fSelectedColumn)) { if ((modifiers() & B_CONTROL_KEY) == 0 && fSortColumns->CountItems() > 1) { fSortColumns->MakeEmpty(); fSortColumns->AddItem(fSelectedColumn); } fSelectedColumn->fSortAscending = !fSelectedColumn->fSortAscending; } else { if ((modifiers() & B_CONTROL_KEY) == 0) fSortColumns->MakeEmpty(); fSortColumns->AddItem(fSelectedColumn); fSelectedColumn->fSortAscending = true; } fOutlineView->StartSorting(); } fCurrentState = INACTIVE; Invalidate(); break; } case DRAG_COLUMN_INSIDE_TITLE: fCurrentState = INACTIVE; #if DRAG_TITLE_OUTLINE Invalidate(); // xxx Can make this smaller #else Invalidate(fSelectedColumnRect); #endif SetViewCursor(B_CURSOR_SYSTEM_DEFAULT, true); break; case DRAG_COLUMN_OUTSIDE_TITLE: fCurrentState = INACTIVE; EndRectTracking(); SetViewCursor(B_CURSOR_SYSTEM_DEFAULT, true); break; default: ; } } void TitleView::FrameResized(float width, float height) { fVisibleRect.right = fVisibleRect.left + width; fVisibleRect.bottom = fVisibleRect.top + height; FixScrollBar(true); } // #pragma mark - OutlineView::OutlineView(BRect rect, BList* visibleColumns, BList* sortColumns, BColumnListView* listView) : BView(rect, "outline_view", B_FOLLOW_ALL_SIDES, B_WILL_DRAW | B_FRAME_EVENTS), fColumns(visibleColumns), fSortColumns(sortColumns), fItemsHeight(0.0), fVisibleRect(rect.OffsetToCopy(0, 0)), fFocusRow(0), fRollOverRow(0), fLastSelectedItem(0), fFirstSelectedItem(0), fSortThread(B_BAD_THREAD_ID), fCurrentState(INACTIVE), fMasterView(listView), fSelectionMode(B_MULTIPLE_SELECTION_LIST), fTrackMouse(false), fCurrentField(0), fCurrentRow(0), fCurrentColumn(0), fMouseDown(false), fCurrentCode(B_OUTSIDE_VIEW), fEditMode(false), fDragging(false), fClickCount(0), fDropHighlightY(-1) { SetViewColor(B_TRANSPARENT_COLOR); #if DOUBLE_BUFFERED_COLUMN_RESIZE // TODO: This needs to be smart about the size of the buffer. // Also, the buffer can be shared with the title's buffer. BRect doubleBufferRect(0, 0, 600, 35); fDrawBuffer = new BBitmap(doubleBufferRect, B_RGB32, true); fDrawBufferView = new BView(doubleBufferRect, "double_buffer_view", B_FOLLOW_ALL_SIDES, 0); fDrawBuffer->Lock(); fDrawBuffer->AddChild(fDrawBufferView); fDrawBuffer->Unlock(); #endif FixScrollBar(true); fSelectionListDummyHead.fNextSelected = &fSelectionListDummyHead; fSelectionListDummyHead.fPrevSelected = &fSelectionListDummyHead; } OutlineView::~OutlineView() { #if DOUBLE_BUFFERED_COLUMN_RESIZE delete fDrawBuffer; #endif Clear(); } void OutlineView::Clear() { DeselectAll(); // Make sure selection list doesn't point to deleted rows! RecursiveDeleteRows(&fRows, false); Invalidate(); fItemsHeight = 0.0; FixScrollBar(true); } void OutlineView::SetSelectionMode(list_view_type mode) { DeselectAll(); fSelectionMode = mode; } list_view_type OutlineView::SelectionMode() const { return fSelectionMode; } void OutlineView::Deselect(BRow* row) { if (row == NULL) return; if (row->fNextSelected != 0) { row->fNextSelected->fPrevSelected = row->fPrevSelected; row->fPrevSelected->fNextSelected = row->fNextSelected; row->fNextSelected = 0; row->fPrevSelected = 0; Invalidate(); } } void OutlineView::AddToSelection(BRow* row) { if (row == NULL) return; if (row->fNextSelected == 0) { if (fSelectionMode == B_SINGLE_SELECTION_LIST) DeselectAll(); row->fNextSelected = fSelectionListDummyHead.fNextSelected; row->fPrevSelected = &fSelectionListDummyHead; row->fNextSelected->fPrevSelected = row; row->fPrevSelected->fNextSelected = row; BRect invalidRect; if (FindVisibleRect(row, &invalidRect)) Invalidate(invalidRect); } } void OutlineView::RecursiveDeleteRows(BRowContainer* list, bool isOwner) { if (list == NULL) return; while (true) { BRow* row = list->RemoveItemAt(0L); if (row == 0) break; if (row->fChildList) RecursiveDeleteRows(row->fChildList, true); delete row; } if (isOwner) delete list; } void OutlineView::RedrawColumn(BColumn* column, float leftEdge, bool isFirstColumn) { // TODO: Remove code duplication (private function which takes a view // pointer, pass "this" in non-double buffered mode)! // Watch out for sourceRect versus destRect though! if (!column) return; font_height fh; GetFontHeight(&fh); float line = 0.0; bool tintedLine = true; for (RecursiveOutlineIterator iterator(&fRows); iterator.CurrentRow(); line += iterator.CurrentRow()->Height() + 1, iterator.GoToNext()) { BRow* row = iterator.CurrentRow(); float rowHeight = row->Height(); if (line > fVisibleRect.bottom) break; tintedLine = !tintedLine; if (line + rowHeight >= fVisibleRect.top) { #if DOUBLE_BUFFERED_COLUMN_RESIZE BRect sourceRect(0, 0, column->Width(), rowHeight); #endif BRect destRect(leftEdge, line, leftEdge + column->Width(), line + rowHeight); rgb_color highColor; rgb_color lowColor; if (row->fNextSelected != 0) { if (fEditMode) { highColor = fMasterView->Color(B_COLOR_EDIT_BACKGROUND); lowColor = fMasterView->Color(B_COLOR_EDIT_BACKGROUND); } else { highColor = fMasterView->Color(B_COLOR_SELECTION); lowColor = fMasterView->Color(B_COLOR_SELECTION); } } else { highColor = fMasterView->Color(B_COLOR_BACKGROUND); lowColor = fMasterView->Color(B_COLOR_BACKGROUND); } if (tintedLine) lowColor = tint_color(lowColor, kTintedLineTint); #if DOUBLE_BUFFERED_COLUMN_RESIZE fDrawBuffer->Lock(); fDrawBufferView->SetHighColor(highColor); fDrawBufferView->SetLowColor(lowColor); BFont font; GetFont(&font); fDrawBufferView->SetFont(&font); fDrawBufferView->FillRect(sourceRect, B_SOLID_LOW); if (isFirstColumn) { // If this is the first column, double buffer drawing the latch // too. destRect.left += iterator.CurrentLevel() * kOutlineLevelIndent - fMasterView->LatchWidth(); sourceRect.left += iterator.CurrentLevel() * kOutlineLevelIndent - fMasterView->LatchWidth(); LatchType pos = B_NO_LATCH; if (row->HasLatch()) pos = row->fIsExpanded ? B_OPEN_LATCH : B_CLOSED_LATCH; BRect latchRect(sourceRect); latchRect.right = latchRect.left + fMasterView->LatchWidth(); fMasterView->DrawLatch(fDrawBufferView, latchRect, pos, row); } BField* field = row->GetField(column->fFieldID); if (field) { BRect fieldRect(sourceRect); if (isFirstColumn) fieldRect.left += fMasterView->LatchWidth(); #if CONSTRAIN_CLIPPING_REGION BRegion clipRegion(fieldRect); fDrawBufferView->PushState(); fDrawBufferView->ConstrainClippingRegion(&clipRegion); #endif fDrawBufferView->SetHighColor(fMasterView->Color( row->fNextSelected ? B_COLOR_SELECTION_TEXT : B_COLOR_TEXT)); float baseline = floor(fieldRect.top + fh.ascent + (fieldRect.Height() + 1 - (fh.ascent+fh.descent)) / 2); fDrawBufferView->MovePenTo(fieldRect.left + 8, baseline); column->DrawField(field, fieldRect, fDrawBufferView); #if CONSTRAIN_CLIPPING_REGION fDrawBufferView->PopState(); #endif } if (fFocusRow == row && !fEditMode && fMasterView->IsFocus() && Window()->IsActive()) { fDrawBufferView->SetHighColor(fMasterView->Color( B_COLOR_ROW_DIVIDER)); fDrawBufferView->StrokeRect(BRect(-1, sourceRect.top, 10000.0, sourceRect.bottom)); } fDrawBufferView->Sync(); fDrawBuffer->Unlock(); SetDrawingMode(B_OP_COPY); DrawBitmap(fDrawBuffer, sourceRect, destRect); #else SetHighColor(highColor); SetLowColor(lowColor); FillRect(destRect, B_SOLID_LOW); BField* field = row->GetField(column->fFieldID); if (field) { #if CONSTRAIN_CLIPPING_REGION BRegion clipRegion(destRect); PushState(); ConstrainClippingRegion(&clipRegion); #endif SetHighColor(fMasterView->Color(row->fNextSelected ? B_COLOR_SELECTION_TEXT : B_COLOR_TEXT)); float baseline = floor(destRect.top + fh.ascent + (destRect.Height() + 1 - (fh.ascent + fh.descent)) / 2); MovePenTo(destRect.left + 8, baseline); column->DrawField(field, destRect, this); #if CONSTRAIN_CLIPPING_REGION PopState(); #endif } if (fFocusRow == row && !fEditMode && fMasterView->IsFocus() && Window()->IsActive()) { SetHighColor(fMasterView->Color(B_COLOR_ROW_DIVIDER)); StrokeRect(BRect(0, destRect.top, 10000.0, destRect.bottom)); } #endif } } } void OutlineView::Draw(BRect invalidBounds) { #if SMART_REDRAW BRegion invalidRegion; GetClippingRegion(&invalidRegion); #endif font_height fh; GetFontHeight(&fh); float line = 0.0; bool tintedLine = true; int32 numColumns = fColumns->CountItems(); for (RecursiveOutlineIterator iterator(&fRows); iterator.CurrentRow(); iterator.GoToNext()) { BRow* row = iterator.CurrentRow(); if (line > invalidBounds.bottom) break; tintedLine = !tintedLine; float rowHeight = row->Height(); if (line > invalidBounds.top - rowHeight) { bool isFirstColumn = true; float fieldLeftEdge = MAX(kLeftMargin, fMasterView->LatchWidth()); // setup background color rgb_color lowColor; if (row->fNextSelected != 0) { if (Window()->IsActive()) { if (fEditMode) lowColor = fMasterView->Color(B_COLOR_EDIT_BACKGROUND); else lowColor = fMasterView->Color(B_COLOR_SELECTION); } else lowColor = fMasterView->Color(B_COLOR_NON_FOCUS_SELECTION); } else lowColor = fMasterView->Color(B_COLOR_BACKGROUND); if (tintedLine) lowColor = tint_color(lowColor, kTintedLineTint); for (int columnIndex = 0; columnIndex < numColumns; columnIndex++) { BColumn* column = (BColumn*) fColumns->ItemAt(columnIndex); if (!column->IsVisible()) continue; if (!isFirstColumn && fieldLeftEdge > invalidBounds.right) break; if (fieldLeftEdge + column->Width() >= invalidBounds.left) { BRect fullRect(fieldLeftEdge, line, fieldLeftEdge + column->Width(), line + rowHeight); bool clippedFirstColumn = false; // This happens when a column is indented past the // beginning of the next column. SetHighColor(lowColor); BRect destRect(fullRect); if (isFirstColumn) { fullRect.left -= fMasterView->LatchWidth(); destRect.left += iterator.CurrentLevel() * kOutlineLevelIndent; if (destRect.left >= destRect.right) { // clipped FillRect(BRect(0, line, fieldLeftEdge + column->Width(), line + rowHeight)); clippedFirstColumn = true; } FillRect(BRect(0, line, MAX(kLeftMargin, fMasterView->LatchWidth()), line + row->Height())); } #if SMART_REDRAW if (!clippedFirstColumn && invalidRegion.Intersects(fullRect)) { #else if (!clippedFirstColumn) { #endif FillRect(fullRect); // Using color set above // Draw the latch widget if it has one. if (isFirstColumn) { if (row == fTargetRow && fCurrentState == LATCH_CLICKED) { // Note that this only occurs if the user is // holding down a latch while items are added // in the background. BPoint pos; uint32 buttons; GetMouse(&pos, &buttons); if (fLatchRect.Contains(pos)) { fMasterView->DrawLatch(this, fLatchRect, B_PRESSED_LATCH, fTargetRow); } else { fMasterView->DrawLatch(this, fLatchRect, row->fIsExpanded ? B_OPEN_LATCH : B_CLOSED_LATCH, fTargetRow); } } else { LatchType pos = B_NO_LATCH; if (row->HasLatch()) pos = row->fIsExpanded ? B_OPEN_LATCH : B_CLOSED_LATCH; fMasterView->DrawLatch(this, BRect(destRect.left - fMasterView->LatchWidth(), destRect.top, destRect.left, destRect.bottom), pos, row); } } SetHighColor(fMasterView->HighColor()); // The master view just holds the high color for us. SetLowColor(lowColor); BField* field = row->GetField(column->fFieldID); if (field) { #if CONSTRAIN_CLIPPING_REGION BRegion clipRegion(destRect); PushState(); ConstrainClippingRegion(&clipRegion); #endif SetHighColor(fMasterView->Color( row->fNextSelected ? B_COLOR_SELECTION_TEXT : B_COLOR_TEXT)); float baseline = floor(destRect.top + fh.ascent + (destRect.Height() + 1 - (fh.ascent+fh.descent)) / 2); MovePenTo(destRect.left + 8, baseline); column->DrawField(field, destRect, this); #if CONSTRAIN_CLIPPING_REGION PopState(); #endif } } } isFirstColumn = false; fieldLeftEdge += column->Width() + 1; } if (fieldLeftEdge <= invalidBounds.right) { SetHighColor(lowColor); FillRect(BRect(fieldLeftEdge, line, invalidBounds.right, line + rowHeight)); } } // indicate the keyboard focus row if (fFocusRow == row && !fEditMode && fMasterView->IsFocus() && Window()->IsActive()) { SetHighColor(fMasterView->Color(B_COLOR_ROW_DIVIDER)); StrokeRect(BRect(0, line, 10000.0, line + rowHeight)); } line += rowHeight + 1; } if (line <= invalidBounds.bottom) { // fill background below last item SetHighColor(fMasterView->Color(B_COLOR_BACKGROUND)); FillRect(BRect(invalidBounds.left, line, invalidBounds.right, invalidBounds.bottom)); } // Draw the drop target line if (fDropHighlightY != -1) { InvertRect(BRect(0, fDropHighlightY - kDropHighlightLineHeight / 2, 1000000, fDropHighlightY + kDropHighlightLineHeight / 2)); } } BRow* OutlineView::FindRow(float ypos, int32* _rowIndent, float* _top) { if (_rowIndent && _top) { float line = 0.0; for (RecursiveOutlineIterator iterator(&fRows); iterator.CurrentRow(); iterator.GoToNext()) { BRow* row = iterator.CurrentRow(); if (line > ypos) break; float rowHeight = row->Height(); if (ypos <= line + rowHeight) { *_top = line; *_rowIndent = iterator.CurrentLevel(); return row; } line += rowHeight + 1; } } return NULL; } void OutlineView::SetMouseTrackingEnabled(bool enabled) { fTrackMouse = enabled; if (!enabled && fDropHighlightY != -1) { // Erase the old target line InvertRect(BRect(0, fDropHighlightY - kDropHighlightLineHeight / 2, 1000000, fDropHighlightY + kDropHighlightLineHeight / 2)); fDropHighlightY = -1; } } // // Note that this interaction is not totally safe. If items are added to // the list in the background, the widget rect will be incorrect, possibly // resulting in drawing glitches. The code that adds items needs to be a little smarter // about invalidating state. // void OutlineView::MouseDown(BPoint position) { if (!fEditMode) fMasterView->MakeFocus(true); // Check to see if the user is clicking on a widget to open a section // of the list. bool reset_click_count = false; int32 indent; float rowTop; BRow* row = FindRow(position.y, &indent, &rowTop); if (row != NULL) { // Update fCurrentField bool handle_field = false; BField* new_field = 0; BRow* new_row = 0; BColumn* new_column = 0; BRect new_rect; if (position.y >= 0) { if (position.x >= 0) { float x = 0; for (int32 c = 0; c < fMasterView->CountColumns(); c++) { new_column = fMasterView->ColumnAt(c); if (!new_column->IsVisible()) continue; if ((MAX(kLeftMargin, fMasterView->LatchWidth()) + x) + new_column->Width() >= position.x) { if (new_column->WantsEvents()) { new_field = row->GetField(c); new_row = row; FindRect(new_row,&new_rect); new_rect.left = MAX(kLeftMargin, fMasterView->LatchWidth()) + x; new_rect.right = new_rect.left + new_column->Width() - 1; handle_field = true; } break; } x += new_column->Width(); } } } // Handle mouse down if (handle_field) { fMouseDown = true; fFieldRect = new_rect; fCurrentColumn = new_column; fCurrentRow = new_row; fCurrentField = new_field; fCurrentCode = B_INSIDE_VIEW; fCurrentColumn->MouseDown(fMasterView, fCurrentRow, fCurrentField, fFieldRect, position, 1); } if (!fEditMode) { fTargetRow = row; fTargetRowTop = rowTop; FindVisibleRect(fFocusRow, &fFocusRowRect); float leftWidgetBoundry = indent * kOutlineLevelIndent + MAX(kLeftMargin, fMasterView->LatchWidth()) - fMasterView->LatchWidth(); fLatchRect.Set(leftWidgetBoundry, rowTop, leftWidgetBoundry + fMasterView->LatchWidth(), rowTop + row->Height()); if (fLatchRect.Contains(position) && row->HasLatch()) { fCurrentState = LATCH_CLICKED; if (fTargetRow->fNextSelected != 0) SetHighColor(fMasterView->Color(B_COLOR_SELECTION)); else SetHighColor(fMasterView->Color(B_COLOR_BACKGROUND)); FillRect(fLatchRect); if (fLatchRect.Contains(position)) { fMasterView->DrawLatch(this, fLatchRect, B_PRESSED_LATCH, row); } else { fMasterView->DrawLatch(this, fLatchRect, fTargetRow->fIsExpanded ? B_OPEN_LATCH : B_CLOSED_LATCH, row); } } else { Invalidate(fFocusRowRect); fFocusRow = fTargetRow; FindVisibleRect(fFocusRow, &fFocusRowRect); ASSERT(fTargetRow != 0); if ((modifiers() & B_CONTROL_KEY) == 0) DeselectAll(); if ((modifiers() & B_SHIFT_KEY) != 0 && fFirstSelectedItem != 0 && fSelectionMode == B_MULTIPLE_SELECTION_LIST) { SelectRange(fFirstSelectedItem, fTargetRow); } else { if (fTargetRow->fNextSelected != 0) { // Unselect row fTargetRow->fNextSelected->fPrevSelected = fTargetRow->fPrevSelected; fTargetRow->fPrevSelected->fNextSelected = fTargetRow->fNextSelected; fTargetRow->fPrevSelected = 0; fTargetRow->fNextSelected = 0; fFirstSelectedItem = NULL; } else { // Select row if (fSelectionMode == B_SINGLE_SELECTION_LIST) DeselectAll(); fTargetRow->fNextSelected = fSelectionListDummyHead.fNextSelected; fTargetRow->fPrevSelected = &fSelectionListDummyHead; fTargetRow->fNextSelected->fPrevSelected = fTargetRow; fTargetRow->fPrevSelected->fNextSelected = fTargetRow; fFirstSelectedItem = fTargetRow; } Invalidate(BRect(fVisibleRect.left, fTargetRowTop, fVisibleRect.right, fTargetRowTop + fTargetRow->Height())); } fCurrentState = ROW_CLICKED; if (fLastSelectedItem != fTargetRow) reset_click_count = true; fLastSelectedItem = fTargetRow; fMasterView->SelectionChanged(); } } SetMouseEventMask(B_POINTER_EVENTS, B_LOCK_WINDOW_FOCUS | B_NO_POINTER_HISTORY); } else if (fFocusRow != 0) { // User clicked in open space, unhighlight focus row. FindVisibleRect(fFocusRow, &fFocusRowRect); fFocusRow = 0; Invalidate(fFocusRowRect); } // We stash the click counts here because the 'clicks' field // is not in the CurrentMessage() when MouseUp is called... ;( if (reset_click_count) fClickCount = 1; else Window()->CurrentMessage()->FindInt32("clicks", &fClickCount); fClickPoint = position; } void OutlineView::MouseMoved(BPoint position, uint32 /*transit*/, const BMessage* /*dragMessage*/) { if (!fMouseDown) { // Update fCurrentField bool handle_field = false; BField* new_field = 0; BRow* new_row = 0; BColumn* new_column = 0; BRect new_rect(0,0,0,0); if (position.y >=0 ) { float top; int32 indent; BRow* row = FindRow(position.y, &indent, &top); if (row && position.x >=0 ) { float x=0; for (int32 c=0;c<fMasterView->CountColumns();c++) { new_column = fMasterView->ColumnAt(c); if (!new_column->IsVisible()) continue; if ((MAX(kLeftMargin, fMasterView->LatchWidth()) + x) + new_column->Width() > position.x) { if(new_column->WantsEvents()) { new_field = row->GetField(c); new_row = row; FindRect(new_row,&new_rect); new_rect.left = MAX(kLeftMargin, fMasterView->LatchWidth()) + x; new_rect.right = new_rect.left + new_column->Width() - 1; handle_field = true; } break; } x += new_column->Width(); } } } // Handle mouse moved if (handle_field) { if (new_field != fCurrentField) { if (fCurrentField) { fCurrentColumn->MouseMoved(fMasterView, fCurrentRow, fCurrentField, fFieldRect, position, 0, fCurrentCode = B_EXITED_VIEW); } fCurrentColumn = new_column; fCurrentRow = new_row; fCurrentField = new_field; fFieldRect = new_rect; if (fCurrentField) { fCurrentColumn->MouseMoved(fMasterView, fCurrentRow, fCurrentField, fFieldRect, position, 0, fCurrentCode = B_ENTERED_VIEW); } } else { if (fCurrentField) { fCurrentColumn->MouseMoved(fMasterView, fCurrentRow, fCurrentField, fFieldRect, position, 0, fCurrentCode = B_INSIDE_VIEW); } } } else { if (fCurrentField) { fCurrentColumn->MouseMoved(fMasterView, fCurrentRow, fCurrentField, fFieldRect, position, 0, fCurrentCode = B_EXITED_VIEW); fCurrentField = 0; fCurrentColumn = 0; fCurrentRow = 0; } } } else { if (fCurrentField) { if (fFieldRect.Contains(position)) { if (fCurrentCode == B_OUTSIDE_VIEW || fCurrentCode == B_EXITED_VIEW) { fCurrentColumn->MouseMoved(fMasterView, fCurrentRow, fCurrentField, fFieldRect, position, 1, fCurrentCode = B_ENTERED_VIEW); } else { fCurrentColumn->MouseMoved(fMasterView, fCurrentRow, fCurrentField, fFieldRect, position, 1, fCurrentCode = B_INSIDE_VIEW); } } else { if (fCurrentCode == B_INSIDE_VIEW || fCurrentCode == B_ENTERED_VIEW) { fCurrentColumn->MouseMoved(fMasterView, fCurrentRow, fCurrentField, fFieldRect, position, 1, fCurrentCode = B_EXITED_VIEW); } else { fCurrentColumn->MouseMoved(fMasterView, fCurrentRow, fCurrentField, fFieldRect, position, 1, fCurrentCode = B_OUTSIDE_VIEW); } } } } if (!fEditMode) { switch (fCurrentState) { case LATCH_CLICKED: if (fTargetRow->fNextSelected != 0) SetHighColor(fMasterView->Color(B_COLOR_SELECTION)); else SetHighColor(fMasterView->Color(B_COLOR_BACKGROUND)); FillRect(fLatchRect); if (fLatchRect.Contains(position)) { fMasterView->DrawLatch(this, fLatchRect, B_PRESSED_LATCH, fTargetRow); } else { fMasterView->DrawLatch(this, fLatchRect, fTargetRow->fIsExpanded ? B_OPEN_LATCH : B_CLOSED_LATCH, fTargetRow); } break; case ROW_CLICKED: if (abs((int)(position.x - fClickPoint.x)) > kRowDragSensitivity || abs((int)(position.y - fClickPoint.y)) > kRowDragSensitivity) { fCurrentState = DRAGGING_ROWS; fMasterView->InitiateDrag(fClickPoint, fTargetRow->fNextSelected != 0); } break; case DRAGGING_ROWS: #if 0 // falls through... #else if (fTrackMouse /*&& message*/) { if (fVisibleRect.Contains(position)) { float top; int32 indent; BRow* target = FindRow(position.y, &indent, &top); if (target) SetFocusRow(target, true); } } break; #endif default: { if (fTrackMouse /*&& message*/) { // Draw a highlight line... if (fVisibleRect.Contains(position)) { float top; int32 indent; BRow* target = FindRow(position.y, &indent, &top); if (target == fRollOverRow) break; if (fRollOverRow) { BRect rect; FindRect(fRollOverRow, &rect); Invalidate(rect); } fRollOverRow = target; #if 0 SetFocusRow(fRollOverRow,false); #else PushState(); SetDrawingMode(B_OP_BLEND); SetHighColor(255, 255, 255, 255); BRect rect; FindRect(fRollOverRow, &rect); rect.bottom -= 1.0; FillRect(rect); PopState(); #endif } else { if (fRollOverRow) { BRect rect; FindRect(fRollOverRow, &rect); Invalidate(rect); fRollOverRow = NULL; } } } } } } } void OutlineView::MouseUp(BPoint position) { if (fCurrentField) { fCurrentColumn->MouseUp(fMasterView, fCurrentRow, fCurrentField); fMouseDown = false; } if (fEditMode) return; switch (fCurrentState) { case LATCH_CLICKED: if (fLatchRect.Contains(position)) { fMasterView->ExpandOrCollapse(fTargetRow, !fTargetRow->fIsExpanded); } Invalidate(fLatchRect); fCurrentState = INACTIVE; break; case ROW_CLICKED: if (fClickCount > 1 && abs((int)fClickPoint.x - (int)position.x) < kDoubleClickMoveSensitivity && abs((int)fClickPoint.y - (int)position.y) < kDoubleClickMoveSensitivity) { fMasterView->ItemInvoked(); } fCurrentState = INACTIVE; break; case DRAGGING_ROWS: fCurrentState = INACTIVE; // Falls through default: if (fDropHighlightY != -1) { InvertRect(BRect(0, fDropHighlightY - kDropHighlightLineHeight / 2, 1000000, fDropHighlightY + kDropHighlightLineHeight / 2)); // Erase the old target line fDropHighlightY = -1; } } } void OutlineView::MessageReceived(BMessage* message) { if (message->WasDropped()) { fMasterView->MessageDropped(message, ConvertFromScreen(message->DropPoint())); } else { BView::MessageReceived(message); } } void OutlineView::ChangeFocusRow(bool up, bool updateSelection, bool addToCurrentSelection) { int32 indent; float top; float newRowPos = 0; float verticalScroll = 0; if (fFocusRow) { // A row currently has the focus, get information about it newRowPos = fFocusRowRect.top + (up ? -4 : fFocusRow->Height() + 4); if (newRowPos < fVisibleRect.top + 20) verticalScroll = newRowPos - 20; else if (newRowPos > fVisibleRect.bottom - 20) verticalScroll = newRowPos - fVisibleRect.Height() + 20; } else newRowPos = fVisibleRect.top + 2; // no row is currently focused, set this to the top of the window // so we will select the first visible item in the list. BRow* newRow = FindRow(newRowPos, &indent, &top); if (newRow) { if (fFocusRow) { fFocusRowRect.right = 10000; Invalidate(fFocusRowRect); } fFocusRow = newRow; fFocusRowRect.top = top; fFocusRowRect.left = 0; fFocusRowRect.right = 10000; fFocusRowRect.bottom = fFocusRowRect.top + fFocusRow->Height(); Invalidate(fFocusRowRect); if (updateSelection) { if (!addToCurrentSelection || fSelectionMode == B_SINGLE_SELECTION_LIST) { DeselectAll(); } if (fFocusRow->fNextSelected == 0) { fFocusRow->fNextSelected = fSelectionListDummyHead.fNextSelected; fFocusRow->fPrevSelected = &fSelectionListDummyHead; fFocusRow->fNextSelected->fPrevSelected = fFocusRow; fFocusRow->fPrevSelected->fNextSelected = fFocusRow; } fLastSelectedItem = fFocusRow; } } else Invalidate(fFocusRowRect); if (verticalScroll != 0) { BScrollBar* vScrollBar = ScrollBar(B_VERTICAL); float min, max; vScrollBar->GetRange(&min, &max); if (verticalScroll < min) verticalScroll = min; else if (verticalScroll > max) verticalScroll = max; vScrollBar->SetValue(verticalScroll); } if (newRow && updateSelection) fMasterView->SelectionChanged(); } void OutlineView::MoveFocusToVisibleRect() { fFocusRow = 0; ChangeFocusRow(true, true, false); } BRow* OutlineView::CurrentSelection(BRow* lastSelected) const { BRow* row; if (lastSelected == 0) row = fSelectionListDummyHead.fNextSelected; else row = lastSelected->fNextSelected; if (row == &fSelectionListDummyHead) row = 0; return row; } void OutlineView::ToggleFocusRowSelection(bool selectRange) { if (fFocusRow == 0) return; if (selectRange && fSelectionMode == B_MULTIPLE_SELECTION_LIST) SelectRange(fLastSelectedItem, fFocusRow); else { if (fFocusRow->fNextSelected != 0) { // Unselect row fFocusRow->fNextSelected->fPrevSelected = fFocusRow->fPrevSelected; fFocusRow->fPrevSelected->fNextSelected = fFocusRow->fNextSelected; fFocusRow->fPrevSelected = 0; fFocusRow->fNextSelected = 0; } else { // Select row if (fSelectionMode == B_SINGLE_SELECTION_LIST) DeselectAll(); fFocusRow->fNextSelected = fSelectionListDummyHead.fNextSelected; fFocusRow->fPrevSelected = &fSelectionListDummyHead; fFocusRow->fNextSelected->fPrevSelected = fFocusRow; fFocusRow->fPrevSelected->fNextSelected = fFocusRow; } } fLastSelectedItem = fFocusRow; fMasterView->SelectionChanged(); Invalidate(fFocusRowRect); } void OutlineView::ToggleFocusRowOpen() { if (fFocusRow) fMasterView->ExpandOrCollapse(fFocusRow, !fFocusRow->fIsExpanded); } void OutlineView::ExpandOrCollapse(BRow* parentRow, bool expand) { // TODO: Could use CopyBits here to speed things up. if (parentRow == NULL) return; if (parentRow->fIsExpanded == expand) return; parentRow->fIsExpanded = expand; BRect parentRect; if (FindRect(parentRow, &parentRect)) { // Determine my new height float subTreeHeight = 0.0; if (parentRow->fIsExpanded) for (RecursiveOutlineIterator iterator(parentRow->fChildList); iterator.CurrentRow(); iterator.GoToNext() ) { subTreeHeight += iterator.CurrentRow()->Height()+1; } else for (RecursiveOutlineIterator iterator(parentRow->fChildList); iterator.CurrentRow(); iterator.GoToNext() ) { subTreeHeight -= iterator.CurrentRow()->Height()+1; } fItemsHeight += subTreeHeight; // Adjust focus row if necessary. if (FindRect(fFocusRow, &fFocusRowRect) == false) { // focus row is in a subtree that has collapsed, // move it up to the parent. fFocusRow = parentRow; FindRect(fFocusRow, &fFocusRowRect); } Invalidate(BRect(0, parentRect.top, fVisibleRect.right, fVisibleRect.bottom)); FixScrollBar(false); } } void OutlineView::RemoveRow(BRow* row) { if (row == NULL) return; BRow* parentRow; bool parentIsVisible; float subTreeHeight = row->Height(); if (FindParent(row, &parentRow, &parentIsVisible)) { // adjust height if (parentIsVisible && (parentRow == 0 || parentRow->fIsExpanded)) { if (row->fIsExpanded) { for (RecursiveOutlineIterator iterator(row->fChildList); iterator.CurrentRow(); iterator.GoToNext()) subTreeHeight += iterator.CurrentRow()->Height(); } } } if (parentRow) { if (parentRow->fIsExpanded) fItemsHeight -= subTreeHeight + 1; } else { fItemsHeight -= subTreeHeight + 1; } FixScrollBar(false); if (parentRow) parentRow->fChildList->RemoveItem(row); else fRows.RemoveItem(row); if (parentRow != 0 && parentRow->fChildList->CountItems() == 0) { delete parentRow->fChildList; parentRow->fChildList = 0; if (parentIsVisible) Invalidate(); // xxx crude way of redrawing latch } if (parentIsVisible && (parentRow == 0 || parentRow->fIsExpanded)) Invalidate(); // xxx make me smarter. // Adjust focus row if necessary. if (fFocusRow && FindRect(fFocusRow, &fFocusRowRect) == false) { // focus row is in a subtree that is gone, move it up to the parent. fFocusRow = parentRow; if (fFocusRow) FindRect(fFocusRow, &fFocusRowRect); } // Remove this from the selection if necessary if (row->fNextSelected != 0) { row->fNextSelected->fPrevSelected = row->fPrevSelected; row->fPrevSelected->fNextSelected = row->fNextSelected; row->fPrevSelected = 0; row->fNextSelected = 0; fMasterView->SelectionChanged(); } fCurrentColumn = 0; fCurrentRow = 0; fCurrentField = 0; } BRowContainer* OutlineView::RowList() { return &fRows; } void OutlineView::UpdateRow(BRow* row) { if (row) { // Determine if this row has changed its sort order BRow* parentRow = NULL; bool parentIsVisible = false; FindParent(row, &parentRow, &parentIsVisible); BRowContainer* list = (parentRow == NULL) ? &fRows : parentRow->fChildList; if(list) { int32 rowIndex = list->IndexOf(row); ASSERT(rowIndex >= 0); ASSERT(list->ItemAt(rowIndex) == row); bool rowMoved = false; if (rowIndex > 0 && CompareRows(list->ItemAt(rowIndex - 1), row) > 0) rowMoved = true; if (rowIndex < list->CountItems() - 1 && CompareRows(list->ItemAt(rowIndex + 1), row) < 0) rowMoved = true; if (rowMoved) { // Sort location of this row has changed. // Remove and re-add in the right spot SortList(list, parentIsVisible && (parentRow == NULL || parentRow->fIsExpanded)); } else if (parentIsVisible && (parentRow == NULL || parentRow->fIsExpanded)) { BRect invalidRect; if (FindVisibleRect(row, &invalidRect)) Invalidate(invalidRect); } } } } void OutlineView::AddRow(BRow* row, int32 Index, BRow* parentRow) { if (!row) return; row->fParent = parentRow; if (fMasterView->SortingEnabled()) { // Ignore index here. if (parentRow) { if (parentRow->fChildList == NULL) parentRow->fChildList = new BRowContainer; AddSorted(parentRow->fChildList, row); } else AddSorted(&fRows, row); } else { // Note, a -1 index implies add to end if sorting is not enabled if (parentRow) { if (parentRow->fChildList == 0) parentRow->fChildList = new BRowContainer; if (Index < 0 || Index > parentRow->fChildList->CountItems()) parentRow->fChildList->AddItem(row); else parentRow->fChildList->AddItem(row, Index); } else { if (Index < 0 || Index >= fRows.CountItems()) fRows.AddItem(row); else fRows.AddItem(row, Index); } } if (parentRow == 0 || parentRow->fIsExpanded) fItemsHeight += row->Height() + 1; FixScrollBar(false); BRect newRowRect; bool newRowIsInOpenBranch = FindRect(row, &newRowRect); if (fFocusRow && fFocusRowRect.top > newRowRect.bottom) { // The focus row has moved. Invalidate(fFocusRowRect); FindRect(fFocusRow, &fFocusRowRect); Invalidate(fFocusRowRect); } if (newRowIsInOpenBranch) { if (fCurrentState == INACTIVE) { if (newRowRect.bottom < fVisibleRect.top) { // The new row is totally above the current viewport, move // everything down and redraw the first line. BRect source(fVisibleRect); BRect dest(fVisibleRect); source.bottom -= row->Height() + 1; dest.top += row->Height() + 1; CopyBits(source, dest); Invalidate(BRect(fVisibleRect.left, fVisibleRect.top, fVisibleRect.right, fVisibleRect.top + newRowRect.Height())); } else if (newRowRect.top < fVisibleRect.bottom) { // New item is somewhere in the current region. Scroll everything // beneath it down and invalidate just the new row rect. BRect source(fVisibleRect.left, newRowRect.top, fVisibleRect.right, fVisibleRect.bottom - newRowRect.Height()); BRect dest(source); dest.OffsetBy(0, newRowRect.Height() + 1); CopyBits(source, dest); Invalidate(newRowRect); } // otherwise, this is below the currently visible region } else { // Adding the item may have caused the item that the user is currently // selected to move. This would cause annoying drawing and interaction // bugs, as the position of that item is cached. If this happens, resize // the scroll bar, then scroll back so the selected item is in view. BRect targetRect; if (FindRect(fTargetRow, &targetRect)) { float delta = targetRect.top - fTargetRowTop; if (delta != 0) { // This causes a jump because ScrollBy will copy a chunk of the view. // Since the actual contents of the view have been offset, we don't // want this, we just want to change the virtual origin of the window. // Constrain the clipping region so everything is clipped out so no // copy occurs. // // xxx this currently doesn't work if the scroll bars aren't enabled. // everything will still move anyway. A minor annoyance. BRegion emptyRegion; ConstrainClippingRegion(&emptyRegion); PushState(); ScrollBy(0, delta); PopState(); ConstrainClippingRegion(NULL); fTargetRowTop += delta; fClickPoint.y += delta; fLatchRect.OffsetBy(0, delta); } } } } // If the parent was previously childless, it will need to have a latch // drawn. BRect parentRect; if (parentRow && parentRow->fChildList->CountItems() == 1 && FindVisibleRect(parentRow, &parentRect)) Invalidate(parentRect); } void OutlineView::FixScrollBar(bool scrollToFit) { BScrollBar* vScrollBar = ScrollBar(B_VERTICAL); if (vScrollBar) { if (fItemsHeight > fVisibleRect.Height()) { float maxScrollBarValue = fItemsHeight - fVisibleRect.Height(); vScrollBar->SetProportion(fVisibleRect.Height() / fItemsHeight); // If the user is scrolled down too far when makes the range smaller, the list // will jump suddenly, which is undesirable. In this case, don't fix the scroll // bar here. In ScrollTo, it checks to see if this has occured, and will // fix the scroll bars sneakily if the user has scrolled up far enough. if (scrollToFit || vScrollBar->Value() <= maxScrollBarValue) { vScrollBar->SetRange(0.0, maxScrollBarValue); vScrollBar->SetSteps(20.0, fVisibleRect.Height()); } } else if (vScrollBar->Value() == 0.0) vScrollBar->SetRange(0.0, 0.0); // disable scroll bar. } } void OutlineView::AddSorted(BRowContainer* list, BRow* row) { if (list && row) { // Find general vicinity with binary search. int32 lower = 0; int32 upper = list->CountItems()-1; while( lower < upper ) { int32 middle = lower + (upper-lower+1)/2; int32 cmp = CompareRows(row, list->ItemAt(middle)); if( cmp < 0 ) upper = middle-1; else if( cmp > 0 ) lower = middle+1; else lower = upper = middle; } // At this point, 'upper' and 'lower' at the last found item. // Arbitrarily use 'upper' and determine the final insertion // point -- either before or after this item. if( upper < 0 ) upper = 0; else if( upper < list->CountItems() ) { if( CompareRows(row, list->ItemAt(upper)) > 0 ) upper++; } if (upper >= list->CountItems()) list->AddItem(row); // Adding to end. else list->AddItem(row, upper); // Insert } } int32 OutlineView::CompareRows(BRow* row1, BRow* row2) { int32 itemCount (fSortColumns->CountItems()); if (row1 && row2) { for (int32 index = 0; index < itemCount; index++) { BColumn* column = (BColumn*) fSortColumns->ItemAt(index); int comp = 0; BField* field1 = (BField*) row1->GetField(column->fFieldID); BField* field2 = (BField*) row2->GetField(column->fFieldID); if (field1 && field2) comp = column->CompareFields(field1, field2); if (!column->fSortAscending) comp = -comp; if (comp != 0) return comp; } } return 0; } void OutlineView::FrameResized(float width, float height) { fVisibleRect.right = fVisibleRect.left + width; fVisibleRect.bottom = fVisibleRect.top + height; FixScrollBar(true); _inherited::FrameResized(width, height); } void OutlineView::ScrollTo(BPoint position) { fVisibleRect.OffsetTo(position.x, position.y); // In FixScrollBar, we might not have been able to change the size of // the scroll bar because the user was scrolled down too far. Take // this opportunity to sneak it in if we can. BScrollBar* vScrollBar = ScrollBar(B_VERTICAL); float maxScrollBarValue = fItemsHeight - fVisibleRect.Height(); float min, max; vScrollBar->GetRange(&min, &max); if (max != maxScrollBarValue && position.y > maxScrollBarValue) FixScrollBar(true); _inherited::ScrollTo(position); } const BRect& OutlineView::VisibleRect() const { return fVisibleRect; } bool OutlineView::FindVisibleRect(BRow* row, BRect* _rect) { if (row && _rect) { float line = 0.0; for (RecursiveOutlineIterator iterator(&fRows); iterator.CurrentRow(); iterator.GoToNext()) { if (line > fVisibleRect.bottom) break; if (iterator.CurrentRow() == row) { _rect->Set(fVisibleRect.left, line, fVisibleRect.right, line + row->Height()); return true; } line += iterator.CurrentRow()->Height() + 1; } } return false; } bool OutlineView::FindRect(const BRow* row, BRect* _rect) { float line = 0.0; for (RecursiveOutlineIterator iterator(&fRows); iterator.CurrentRow(); iterator.GoToNext()) { if (iterator.CurrentRow() == row) { _rect->Set(fVisibleRect.left, line, fVisibleRect.right, line + row->Height()); return true; } line += iterator.CurrentRow()->Height() + 1; } return false; } void OutlineView::ScrollTo(const BRow* row) { BRect rect; if (FindRect(row, &rect)) { BRect bounds = Bounds(); if (rect.top < bounds.top) ScrollTo(BPoint(bounds.left, rect.top)); else if (rect.bottom > bounds.bottom) ScrollBy(0, rect.bottom - bounds.bottom); } } void OutlineView::DeselectAll() { // Invalidate all selected rows float line = 0.0; for (RecursiveOutlineIterator iterator(&fRows); iterator.CurrentRow(); iterator.GoToNext()) { if (line > fVisibleRect.bottom) break; BRow* row = iterator.CurrentRow(); if (line + row->Height() > fVisibleRect.top) { if (row->fNextSelected != 0) Invalidate(BRect(fVisibleRect.left, line, fVisibleRect.right, line + row->Height())); } line += row->Height() + 1; } // Set items not selected while (fSelectionListDummyHead.fNextSelected != &fSelectionListDummyHead) { BRow* row = fSelectionListDummyHead.fNextSelected; row->fNextSelected->fPrevSelected = row->fPrevSelected; row->fPrevSelected->fNextSelected = row->fNextSelected; row->fNextSelected = 0; row->fPrevSelected = 0; } } BRow* OutlineView::FocusRow() const { return fFocusRow; } void OutlineView::SetFocusRow(BRow* row, bool Select) { if (row) { if (Select) AddToSelection(row); if (fFocusRow == row) return; Invalidate(fFocusRowRect); // invalidate previous fTargetRow = fFocusRow = row; FindVisibleRect(fFocusRow, &fFocusRowRect); Invalidate(fFocusRowRect); // invalidate current fFocusRowRect.right = 10000; fMasterView->SelectionChanged(); } } bool OutlineView::SortList(BRowContainer* list, bool isVisible) { if (list) { // Shellsort BRow** items = (BRow**) list->AsBList()->Items(); int32 numItems = list->CountItems(); int h; for (h = 1; h < numItems / 9; h = 3 * h + 1) ; for (;h > 0; h /= 3) { for (int step = h; step < numItems; step++) { BRow* temp = items[step]; int i; for (i = step - h; i >= 0; i -= h) { if (CompareRows(temp, items[i]) < 0) items[i + h] = items[i]; else break; } items[i + h] = temp; } } if (isVisible) { Invalidate(); InvalidateCachedPositions(); int lockCount = Window()->CountLocks(); for (int i = 0; i < lockCount; i++) Window()->Unlock(); while (lockCount--) if (!Window()->Lock()) return false; // Window is gone... } } return true; } int32 OutlineView::DeepSortThreadEntry(void* _outlineView) { ((OutlineView*) _outlineView)->DeepSort(); return 0; } void OutlineView::DeepSort() { struct stack_entry { bool isVisible; BRowContainer* list; int32 listIndex; } stack[kMaxDepth]; int32 stackTop = 0; stack[stackTop].list = &fRows; stack[stackTop].isVisible = true; stack[stackTop].listIndex = 0; fNumSorted = 0; if (Window()->Lock() == false) return; bool doneSorting = false; while (!doneSorting && !fSortCancelled) { stack_entry* currentEntry = &stack[stackTop]; // xxx Can make the invalidate area smaller by finding the rect for the // parent item and using that as the top of the invalid rect. bool haveLock = SortList(currentEntry->list, currentEntry->isVisible); if (!haveLock) return ; // window is gone. // Fix focus rect. InvalidateCachedPositions(); if (fCurrentState != INACTIVE) fCurrentState = INACTIVE; // sorry... // next list. bool foundNextList = false; while (!foundNextList && !fSortCancelled) { for (int32 index = currentEntry->listIndex; index < currentEntry->list->CountItems(); index++) { BRow* parentRow = currentEntry->list->ItemAt(index); BRowContainer* childList = parentRow->fChildList; if (childList != 0) { currentEntry->listIndex = index + 1; stackTop++; ASSERT(stackTop < kMaxDepth); stack[stackTop].listIndex = 0; stack[stackTop].list = childList; stack[stackTop].isVisible = (currentEntry->isVisible && parentRow->fIsExpanded); foundNextList = true; break; } } if (!foundNextList) { // back up if (--stackTop < 0) { doneSorting = true; break; } currentEntry = &stack[stackTop]; } } } Window()->Unlock(); } void OutlineView::StartSorting() { // If this view is not yet attached to a window, don't start a sort thread! if (Window() == NULL) return; if (fSortThread != B_BAD_THREAD_ID) { thread_info tinfo; if (get_thread_info(fSortThread, &tinfo) == B_OK) { // Unlock window so this won't deadlock (sort thread is probably // waiting to lock window). int lockCount = Window()->CountLocks(); for (int i = 0; i < lockCount; i++) Window()->Unlock(); fSortCancelled = true; int32 status; wait_for_thread(fSortThread, &status); while (lockCount--) if (!Window()->Lock()) return ; // Window is gone... } } fSortCancelled = false; fSortThread = spawn_thread(DeepSortThreadEntry, "sort_thread", B_NORMAL_PRIORITY, this); resume_thread(fSortThread); } void OutlineView::SelectRange(BRow* start, BRow* end) { if (!start || !end) return; if (start == end) // start is always selected when this is called return; RecursiveOutlineIterator iterator(&fRows, false); while (iterator.CurrentRow() != 0) { if (iterator.CurrentRow() == end) { // reverse selection, swap to fix special case BRow* temp = start; start = end; end = temp; break; } else if (iterator.CurrentRow() == start) break; iterator.GoToNext(); } while (true) { BRow* row = iterator.CurrentRow(); if (row) { if (row->fNextSelected == 0) { row->fNextSelected = fSelectionListDummyHead.fNextSelected; row->fPrevSelected = &fSelectionListDummyHead; row->fNextSelected->fPrevSelected = row; row->fPrevSelected->fNextSelected = row; } } else break; if (row == end) break; iterator.GoToNext(); } Invalidate(); // xxx make invalidation smaller } bool OutlineView::FindParent(BRow* row, BRow** outParent, bool* out_parentIsVisible) { bool result = false; if (row && outParent) { *outParent = row->fParent; // Walk up the parent chain to determine if this row is visible bool isVisible = true; for (BRow* currentRow = row->fParent; currentRow; currentRow = currentRow->fParent) { if (!currentRow->fIsExpanded) { isVisible = false; break; } } if (out_parentIsVisible) *out_parentIsVisible = isVisible; result = (NULL != *outParent); } return result; } int32 OutlineView::IndexOf(BRow* row) { if (row) { if (row->fParent == 0) return fRows.IndexOf(row); ASSERT(row->fParent->fChildList); return row->fParent->fChildList->IndexOf(row); } return B_ERROR; } void OutlineView::InvalidateCachedPositions() { if (fFocusRow) FindRect(fFocusRow, &fFocusRowRect); } float OutlineView::GetColumnPreferredWidth(BColumn* column) { float preferred = 0.0; for (RecursiveOutlineIterator iterator(&fRows); iterator.CurrentRow(); iterator.GoToNext()) { BRow* row = iterator.CurrentRow(); BField* field = row->GetField(column->fFieldID); if (field) { float width = column->GetPreferredWidth(field, this); if (preferred < width) preferred = width; } } // Constrain to preferred width. This makes the method do a little // more than asked, but it's for convenience. if (preferred < column->MinWidth()) preferred = column->MinWidth(); else if (preferred > column->MaxWidth()) preferred = column->MaxWidth(); return preferred; } // #pragma mark - RecursiveOutlineIterator::RecursiveOutlineIterator(BRowContainer* list, bool openBranchesOnly) : fStackIndex(0), fCurrentListIndex(0), fCurrentListDepth(0), fOpenBranchesOnly(openBranchesOnly) { if (list == 0 || list->CountItems() == 0) fCurrentList = 0; else fCurrentList = list; } BRow* RecursiveOutlineIterator::CurrentRow() const { if (fCurrentList == 0) return 0; return fCurrentList->ItemAt(fCurrentListIndex); } void RecursiveOutlineIterator::GoToNext() { if (fCurrentList == 0) return; if (fCurrentListIndex < 0 || fCurrentListIndex >= fCurrentList->CountItems()) { fCurrentList = 0; return; } BRow* currentRow = fCurrentList->ItemAt(fCurrentListIndex); if(currentRow) { if (currentRow->fChildList && (currentRow->fIsExpanded || !fOpenBranchesOnly) && currentRow->fChildList->CountItems() > 0) { // Visit child. // Put current list on the stack if it needs to be revisited. if (fCurrentListIndex < fCurrentList->CountItems() - 1) { fStack[fStackIndex].fRowSet = fCurrentList; fStack[fStackIndex].fIndex = fCurrentListIndex + 1; fStack[fStackIndex].fDepth = fCurrentListDepth; fStackIndex++; } fCurrentList = currentRow->fChildList; fCurrentListIndex = 0; fCurrentListDepth++; } else if (fCurrentListIndex < fCurrentList->CountItems() - 1) fCurrentListIndex++; // next item in current list else if (--fStackIndex >= 0) { fCurrentList = fStack[fStackIndex].fRowSet; fCurrentListIndex = fStack[fStackIndex].fIndex; fCurrentListDepth = fStack[fStackIndex].fDepth; } else fCurrentList = 0; } } int32 RecursiveOutlineIterator::CurrentLevel() const { return fCurrentListDepth; }
[ "plfiorini@8f1b5804-98cd-0310-9b8b-c217470a4c7c" ]
plfiorini@8f1b5804-98cd-0310-9b8b-c217470a4c7c
528fab0165064c94b8656aae326d9ff93590b227
f98e981fc25fc883c1550613a6c70ba1ccb0115d
/lib/dra818v.cpp
c4a1cfd0773472e003eb1cbfc795413d8718a2f8
[]
no_license
invictus1123/ssiRadio
f25d2b77e901d6777b27a593cf9a897441864ebe
03de7244843e8f6091d20921697a9fc483748ade
refs/heads/master
2020-05-22T01:20:48.508329
2017-01-09T06:01:53
2017-01-09T06:01:53
65,703,918
0
0
null
null
null
null
UTF-8
C++
false
false
4,501
cpp
#include "dra818v.h" DRA818V::DRA818V(uint8_t PTT, uint8_t audioOut, uint8_t mic, uint8_t draTX, uint8_t draRX) { pttPin = PTT; pttDelay = PTT_DELAY; audioOutPin = audioOut; micPin = mic; #if USE_HW_SERIAL== true radioSerial = &Serial1; #else radioSerial = new SoftwareSerial(draTX,draRX); #endif } void DRA818V::init() { // #if USE_HW_SERIAL==true pinMode(pttPin,OUTPUT); pinMode(micPin,OUTPUT); char incomingByte; radioSerial->begin(SOFT_SERIAL_BAUD); if(!Serial) { Serial.begin(SOFT_SERIAL_BAUD); } digitalWrite(pttPin,LOW); delay(200); Serial.println("asdf"); radioSerial->print("AT+DMOCONNECT\r\n"); digitalWrite(pttPin,HIGH); delay(200); if(DEBUG) { String messageRx = ""; while (radioSerial->available() > 0) { incomingByte = radioSerial->read(); messageRx = messageRx + incomingByte; } if(messageRx!="") { Serial.print("UART received: "); Serial.println(messageRx); } } digitalWrite(pttPin,LOW); delay(200); configSettings(); digitalWrite(pttPin,HIGH); delay(200); if(DEBUG) { String messageRx = ""; while (radioSerial->available() > 0) { incomingByte = radioSerial->read(); messageRx = messageRx + incomingByte; } if(messageRx!="") { Serial.print("UART received: "); Serial.println(messageRx); } } // #else // pinMode(pttPin,OUTPUT); // pinMode(micPin,OUTPUT); // char incomingByte; // radioSerial.begin(SOFT_SERIAL_BAUD); // if(!Serial) { // Serial.begin(SOFT_SERIAL_BAUD); // } // digitalWrite(pttPin,LOW); // delay(200); // Serial.println("asdf"); // radioSerial.print("AT+DMOCONNECT\r\n"); // digitalWrite(pttPin,HIGH); // delay(200); // if(DEBUG) { // String messageRx = ""; // while (radioSerial.available() > 0) { // incomingByte = radioSerial.read(); // messageRx = messageRx + incomingByte; // } // if(messageRx!="") { // Serial.print("UART received: "); // Serial.println(messageRx); // } // } // digitalWrite(pttPin,LOW); // delay(200); // configSettings(); // digitalWrite(pttPin,HIGH); // delay(200); // if(DEBUG) { // String messageRx = ""; // while (radioSerial.available() > 0) { // incomingByte = radioSerial.read(); // messageRx = messageRx + incomingByte; // } // if(messageRx!="") { // Serial.print("UART received: "); // Serial.println(messageRx); // } // } // #endif } void DRA818V::setPTTDelay(uint16_t delayMs) { pttDelay = delayMs; } void DRA818V::configSettings() { // #if USE_HW_SERIAL == true digitalWrite(pttPin,HIGH); delay(500); digitalWrite(pttPin,LOW); radioSerial->print("AT+DMOSETGROUP="); radioSerial->print(CHANNEL_SCAN_BW,1); radioSerial->print(","); radioSerial->print(APRS_NA_FTX,4); radioSerial->print(","); radioSerial->print(APRS_NA_FRX,4); radioSerial->print(","); radioSerial->print(TX_CTCSS); radioSerial->print(","); radioSerial->print(squelch); radioSerial->print(","); radioSerial->print(RX_CTCSS); radioSerial->print("\r\n"); delay(500); digitalWrite(pttPin,HIGH); delay(500); // digitalWrite(pttPin,LOW); // radioSerial->print("AT+SETFILTER=1,0,0\r\n"); // digitalWrite(pttPin,HIGH); // #else // digitalWrite(pttPin,HIGH); // delay(500); // digitalWrite(pttPin,LOW); // radioSerial.print("AT+DMOSETGROUP="); // radioSerial.print(CHANNEL_SCAN_BW,1); // radioSerial.print(","); // radioSerial.print(APRS_NA_FTX,4); // radioSerial.print(","); // radioSerial.print(APRS_NA_FRX,4); // radioSerial.print(","); // radioSerial.print(TX_CTCSS); // radioSerial.print(","); // radioSerial.print(squelch); // radioSerial.print(","); // radioSerial.print(RX_CTCSS); // radioSerial.print("\r\n"); // delay(500); // digitalWrite(pttPin,HIGH); // delay(500); // digitalWrite(pttPin,LOW); // radioSerial.print("AT+SETFILTER=1,0,0\r\n"); // digitalWrite(pttPin,HIGH); // #endif }
[ "noreply@github.com" ]
invictus1123.noreply@github.com
44496751581b6f2b80791871729c24c53d5c64e3
de35ee3cb9e95affb2971ca96d3d67d2cb89d3fe
/src/Game.h
bb080cd3cbbacff8071bc34ddab19871e0a0dc47
[]
no_license
ratanraj/triangle
45d8d655579db8b603314593212ffbe9188b0cd3
a263ed7ee7389be2ff71a5e6ce2a2767a8d7c4b7
refs/heads/master
2020-12-20T18:49:26.338201
2020-01-25T17:29:43
2020-01-25T17:29:43
236,176,383
0
0
null
null
null
null
UTF-8
C++
false
false
543
h
// // Created by ratanraj on 25/01/20. // #ifndef TRIANGLE_GAME_H #define TRIANGLE_GAME_H #include <iostream> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> class Game { private: bool isRunning; SDL_Window *window; int cnt = 0; public: Game(); ~Game(); void init(const char *title, int xpos, int ypos, int width, int height, bool fullscreen); void handleEvents(); void update(); void render(); void clean(); bool running(); static SDL_Renderer *renderer; }; #endif //TRIANGLE_GAME_H
[ "ratanraj.r@gmail.com" ]
ratanraj.r@gmail.com
243365f568677d6f2311811a20efb11b75c580fd
5f2f9dcb47bb810cf55291825ab2be3028a201a5
/HNU/2015 暑期培训训练赛之八 1004/main2.cpp
7302a98eb36fad4a79fc480a0320e926713e8c4a
[]
no_license
Linfanty/ACM-ICPC
19480155d6e461b728147cfd299e8bce8930f303
2d23ef8013df4eb55dc27aa8f7149420a1b5d3a7
refs/heads/master
2021-01-24T00:24:39.585748
2017-08-27T08:27:32
2017-08-27T08:27:32
122,764,304
1
0
null
2018-02-24T17:48:03
2018-02-24T17:48:03
null
UTF-8
C++
false
false
531
cpp
/* * this code is made by crazyacking * Verdict: Accepted * Submission Date: 2015-08-16-21.49 * Time: 0MS * Memory: 137KB */ #include <queue> #include <cstdio> #include <set> #include <string> #include <stack> #include <cmath> #include <climits> #include <map> #include <cstdlib> #include <iostream> #include <vector> #include <algorithm> #include <cstring> #define LL long long #define ULL unsigned long long using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); return 0; } /* */
[ "11301655@qq.com" ]
11301655@qq.com
205ad586f27ce5575493985251c76edeef916cd1
08d7df69e27d359f30110a3438b891e2a14cac35
/include/snek/ast/position.hpp
f25167d8b7c4176d5ebfb4e8eeb6492fbad3695c
[ "BSD-2-Clause" ]
permissive
RauliL/snek
c06e4553e8260d38187a1013d58465b71babeee4
ad530c0485addaf71fd01469860b83a16d16bf9d
refs/heads/master
2021-06-07T00:23:55.729775
2021-06-03T15:04:19
2021-06-03T15:04:19
291,930,396
0
0
BSD-2-Clause
2020-09-15T16:54:17
2020-09-01T07:40:01
C++
UTF-8
C++
false
false
2,141
hpp
/* * Copyright (c) 2020, Rauli Laine * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <iostream> #include <optional> #include <string> #include <peelo/unicode/encoding/utf8.hpp> namespace snek::ast { struct Position { std::u32string file; int line; int column; }; inline std::ostream& operator<<(std::ostream& os, const Position& position) { using peelo::unicode::encoding::utf8::encode; if (!position.file.empty()) { os << encode(position.file) << ':'; } if (position.line > 0) { os << position.line << ':'; if (position.column > 0) { os << position.column << ':'; } } return os; } inline std::ostream& operator<<(std::ostream& os, const std::optional<Position>& position) { return position ? os << *position : os; } }
[ "rauli.laine@iki.fi" ]
rauli.laine@iki.fi
a1e7d1781673d8224587d0bc836808e2e55466c0
3e1ac5a6f5473c93fb9d4174ced2e721a7c1ff4c
/build/iOS/Preview/include/Fuse.Internal.CacheRef-2.h
ce5b60c3dcb5b0eac560458bc1ffe1f4669d3f79
[]
no_license
dream-plus/DreamPlus_popup
49d42d313e9cf1c9bd5ffa01a42d4b7c2cf0c929
76bb86b1f2e36a513effbc4bc055efae78331746
refs/heads/master
2020-04-28T20:47:24.361319
2019-05-13T12:04:14
2019-05-13T12:04:14
175,556,703
0
1
null
null
null
null
UTF-8
C++
false
false
1,839
h
// This file was generated based on /usr/local/share/uno/Packages/Fuse.Common/1.9.0/Internal/Cache.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.IDisposable.h> #include <Uno.Object.h> namespace g{namespace Fuse{namespace Internal{struct Cache;}}} namespace g{namespace Fuse{namespace Internal{struct CacheRef;}}} namespace g{namespace Uno{namespace Collections{struct LinkedListNode;}}} namespace g{ namespace Fuse{ namespace Internal{ // internal sealed class CacheRef<TKey, TValue> :152 // { struct CacheRef_type : uType { ::g::Uno::IDisposable interface0; }; CacheRef_type* CacheRef_typeof(); void CacheRef__ctor__fn(CacheRef* __this, ::g::Fuse::Internal::Cache* parent, void* key, uObject* value); void CacheRef__Dispose_fn(CacheRef* __this); void CacheRef__New1_fn(uType* __type, ::g::Fuse::Internal::Cache* parent, void* key, uObject* value, CacheRef** __retval); void CacheRef__Release_fn(CacheRef* __this); void CacheRef__Retain_fn(CacheRef* __this); struct CacheRef : uObject { uStrong< ::g::Fuse::Internal::Cache*> _parent; uTField Key() { return __type->Field(this, 1); } uStrong<uObject*> Value; int32_t _refCount; uStrong<uObject*> _refCountMutex; uStrong< ::g::Uno::Collections::LinkedListNode*> _unusedListNode; template<class TKey> void ctor_(::g::Fuse::Internal::Cache* parent, TKey key, uObject* value) { CacheRef__ctor__fn(this, parent, uConstrain(__type->T(0), key), value); } void Dispose(); void Release(); void Retain(); template<class TKey> static CacheRef* New1(uType* __type, ::g::Fuse::Internal::Cache* parent, TKey key, uObject* value) { CacheRef* __retval; return CacheRef__New1_fn(__type, parent, uConstrain(__type->T(0), key), value, &__retval), __retval; } }; // } }}} // ::g::Fuse::Internal
[ "cowodbs156@gmail.com" ]
cowodbs156@gmail.com
f2b96fe3cce8de49105796a4e25830df341131d6
fec81bfe0453c5646e00c5d69874a71c579a103d
/blazetest/src/mathtest/operations/dmatsmatsub/UHbUCb.cpp
bbe5ce937dc99f5427d41e501de214028caf4914
[ "BSD-3-Clause" ]
permissive
parsa/blaze
801b0f619a53f8c07454b80d0a665ac0a3cf561d
6ce2d5d8951e9b367aad87cc55ac835b054b5964
refs/heads/master
2022-09-19T15:46:44.108364
2022-07-30T04:47:03
2022-07-30T04:47:03
105,918,096
52
7
null
null
null
null
UTF-8
C++
false
false
4,190
cpp
//================================================================================================= /*! // \file src/mathtest/operations/dmatsmatsub/UHbUCb.cpp // \brief Source file for the UHbUCb dense matrix/sparse matrix subtraction math test // // Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group 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. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/CompressedMatrix.h> #include <blaze/math/HybridMatrix.h> #include <blaze/math/UpperMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/operations/dmatsmatsub/OperationTest.h> #include <blazetest/system/MathTest.h> #ifdef BLAZE_USE_HPX_THREADS # include <hpx/hpx_main.hpp> #endif //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'UHbUCb'..." << std::endl; using blazetest::mathtest::TypeB; try { // Matrix type definitions using UHb = blaze::UpperMatrix< blaze::HybridMatrix<TypeB,128UL,128UL> >; using UCb = blaze::UpperMatrix< blaze::CompressedMatrix<TypeB> >; // Creator type definitions using CUHb = blazetest::Creator<UHb>; using CUCb = blazetest::Creator<UCb>; // Running tests with small matrices for( size_t i=0UL; i<=6UL; ++i ) { for( size_t j=0UL; j<=UCb::maxNonZeros( i ); ++j ) { RUN_DMATSMATSUB_OPERATION_TEST( CUHb( i ), CUCb( i, j ) ); } } // Running tests with large matrices RUN_DMATSMATSUB_OPERATION_TEST( CUHb( 67UL ), CUCb( 67UL, 7UL ) ); RUN_DMATSMATSUB_OPERATION_TEST( CUHb( 128UL ), CUCb( 128UL, 16UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during dense matrix/sparse matrix subtraction:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
cad8586476cab3d1e1e4da1d1c1b646d1689aee1
526332cee7ef8b68854512f590943db7cb574ca1
/src/tools.cpp
5bedf695016c53571bd0bb182b42f2c89cd4ce81
[]
no_license
yabdelhadi/CarND-Extended-Kalman-Filter-Project
d5c6032f6780d108d69b8edbfe4fe81a3320e79e
6bbab213914f64aabbc631be71f39a3dca6660ed
refs/heads/master
2021-05-09T17:02:04.305030
2018-01-27T03:36:59
2018-01-27T03:36:59
119,127,882
0
0
null
null
null
null
UTF-8
C++
false
false
2,074
cpp
#include <iostream> #include "tools.h" using Eigen::VectorXd; using Eigen::MatrixXd; using std::vector; Tools::Tools() {} Tools::~Tools() {} VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations, const vector<VectorXd> &ground_truth) { /** TODO: * Calculate the RMSE here. */ VectorXd rmse(4); rmse << 0, 0, 0, 0; // check the validity of the following inputs: // * the estimation vector size should not be zero // * the estimation vector size should equal ground truth vector size if (estimations.size() != ground_truth.size() || estimations.size() == 0) { cout << "Invalid estimation or ground_truth data" << endl; return rmse; } //accumulate squared residuals for (unsigned int i = 0; i < estimations.size(); ++i) { VectorXd residual = estimations[i] - ground_truth[i]; //coefficient-wise multiplication residual = residual.array()*residual.array(); rmse += residual; } //calculate the mean rmse = rmse / estimations.size(); //calculate the squared root rmse = rmse.array().sqrt(); //cout << "RMSE" << "\n"; //cout << "X: " << rmse[0] << "\n"; //cout << "Y: " << rmse[1] << "\n"; //cout << "VX: " << rmse[2] << "\n"; //cout << "VY: " << rmse[3] << "\n"; //return the result return rmse; } MatrixXd Tools::CalculateJacobian(const VectorXd& x_state) { /** TODO: * Calculate a Jacobian here. */ MatrixXd Hj(3, 4); //recover state parameters float px = x_state(0); float py = x_state(1); float vx = x_state(2); float vy = x_state(3); //pre-compute a set of terms to avoid repeated calculation float c1 = px * px + py * py; float c2 = sqrt(c1); float c3 = (c1*c2); //check division by zero if (fabs(c1) < 0.0001) { cout << "CalculateJacobian () - Error - Division by Zero" << endl; return Hj; } //compute the Jacobian matrix Hj << (px / c2), (py / c2), 0, 0, -(py / c1), (px / c1), 0, 0, py*(vx*py - vy * px) / c3, px*(px*vy - py * vx) / c3, px / c2, py / c2; return Hj; }
[ "noreply@github.com" ]
yabdelhadi.noreply@github.com
cfefaf4cdf63b5692c396e21d7902d8a138910a3
ae68403fba102765271c28ad47a9cf17650f5623
/ch16/DebugDelete.h
dd9444d78872157010ea36db18365feec887fab6
[]
no_license
yangcnju/cpp_primer_5
a3b0a903f81b5b281053adc01b5a1a66704819c0
81152ad4277405082613f29de6fb89a6176e4fa4
refs/heads/master
2021-01-01T19:06:22.280063
2015-11-20T03:05:42
2015-11-20T03:05:42
40,577,238
0
0
null
null
null
null
UTF-8
C++
false
false
372
h
#ifndef _DebugDelete_h #define _DebugDelete_h #include <iostream> // function-obj class that calls delete on a given ptr class DebugDelete { public: DebugDelete(std::ostream &s = std::cerr) : os(s) {} template <typename T> void operator()(T *p) const { os << "deleting unique_ptr" << std::endl; delete p; } private: std::ostream &os; }; // class DebugDelete #endif
[ "yangcnju@gmail.com" ]
yangcnju@gmail.com
bb366dd7995357dcb2fe21bff61c83d1e3037f46
3fcc27c255db2da950af5b9b08c7e4cceea2ef75
/src/rpcwallet.cpp
3a7cd1b2664f0b871c8937a1c20e732b288775de
[ "MIT" ]
permissive
legendcoin/legendcoin
dfda212512f9c31b335cb9f169241c9cdfa93f34
5eeb4ef47dacece3a314d4944217b36a1f2e71c1
refs/heads/master
2021-01-10T20:49:46.572694
2014-05-14T09:52:43
2014-05-14T09:52:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
55,117
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> #include "wallet.h" #include "walletdb.h" #include "bitcoinrpc.h" #include "init.h" #include "base58.h" using namespace std; using namespace boost; using namespace boost::assign; using namespace json_spirit; int64 nWalletUnlockTime; static CCriticalSection cs_nWalletUnlockTime; std::string HelpRequiringPassphrase() { return pwalletMain && pwalletMain->IsCrypted() ? "\nrequires wallet passphrase to be set with walletpassphrase first" : ""; } void EnsureWalletIsUnlocked() { if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); } void WalletTxToJSON(const CWalletTx& wtx, Object& entry) { int confirms = wtx.GetDepthInMainChain(); entry.push_back(Pair("confirmations", confirms)); if (wtx.IsCoinBase()) entry.push_back(Pair("generated", true)); if (confirms > 0) { entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex())); entry.push_back(Pair("blockindex", wtx.nIndex)); entry.push_back(Pair("blocktime", (boost::int64_t)(mapBlockIndex[wtx.hashBlock]->nTime))); } entry.push_back(Pair("txid", wtx.GetHash().GetHex())); entry.push_back(Pair("normtxid", wtx.GetNormalizedHash().GetHex())); entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime())); entry.push_back(Pair("timereceived", (boost::int64_t)wtx.nTimeReceived)); BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue) entry.push_back(Pair(item.first, item.second)); } string AccountFromValue(const Value& value) { string strAccount = value.get_str(); if (strAccount == "*") throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name"); return strAccount; } Value getinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getinfo\n" "Returns an object containing various state info."); proxyType proxy; GetProxy(NET_IPV4, proxy); Object obj; obj.push_back(Pair("version", (int)CLIENT_VERSION)); obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION)); if (pwalletMain) { obj.push_back(Pair("walletversion", pwalletMain->GetVersion())); obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance()))); } obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("timeoffset", (boost::int64_t)GetTimeOffset())); obj.push_back(Pair("connections", (int)vNodes.size())); obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string()))); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("testnet", fTestNet)); if (pwalletMain) { obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime())); obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize())); } obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee))); obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue))); if (pwalletMain && pwalletMain->IsCrypted()) obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime)); obj.push_back(Pair("errors", GetWarnings("statusbar"))); return obj; } Value getnewaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnewaddress [account]\n" "Returns a new Legendcoin address for receiving payments. " "If [account] is specified (recommended), it is added to the address book " "so payments received with the address will be credited to [account]."); // Parse the account first so we don't generate a key if there's an error string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked()) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBookName(keyID, strAccount); return CBitcoinAddress(keyID).ToString(); } CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false) { CWalletDB walletdb(pwalletMain->strWalletFile); CAccount account; walletdb.ReadAccount(strAccount, account); bool bKeyUsed = false; // Check if the current key has been used if (account.vchPubKey.IsValid()) { CScript scriptPubKey; scriptPubKey.SetDestination(account.vchPubKey.GetID()); for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid(); ++it) { const CWalletTx& wtx = (*it).second; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) bKeyUsed = true; } } // Generate a new key if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) { if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount); walletdb.WriteAccount(strAccount, account); } return CBitcoinAddress(account.vchPubKey.GetID()); } Value getaccountaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccountaddress <account>\n" "Returns the current Legendcoin address for receiving payments to this account."); // Parse the account first so we don't generate a key if there's an error string strAccount = AccountFromValue(params[0]); Value ret; ret = GetAccountAddress(strAccount).ToString(); return ret; } Value setaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setaccount <legendcoinaddress> <account>\n" "Sets the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Legendcoin address"); string strAccount; if (params.size() > 1) strAccount = AccountFromValue(params[1]); // Detect when changing the account of an address that is the 'unused current key' of another account: if (pwalletMain->mapAddressBook.count(address.Get())) { string strOldAccount = pwalletMain->mapAddressBook[address.Get()]; if (address == GetAccountAddress(strOldAccount)) GetAccountAddress(strOldAccount, true); } pwalletMain->SetAddressBookName(address.Get(), strAccount); return Value::null; } Value getaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccount <legendcoinaddress>\n" "Returns the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Legendcoin address"); string strAccount; map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get()); if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty()) strAccount = (*mi).second; return strAccount; } Value getaddressesbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaddressesbyaccount <account>\n" "Returns the list of addresses for the given account."); string strAccount = AccountFromValue(params[0]); // Find all addresses that have the given account Array ret; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strName = item.second; if (strName == strAccount) ret.push_back(address.ToString()); } return ret; } Value setmininput(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "setmininput <amount>\n" "<amount> is a real and is rounded to the nearest 0.00000001"); // Amount int64 nAmount = 0; if (params[0].get_real() != 0.0) nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts nMinimumInputValue = nAmount; return true; } Value sendtoaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendtoaddress <legendcoinaddress> <amount> [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.00000001" + HelpRequiringPassphrase()); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Legendcoin address"); // Amount int64 nAmount = AmountFromValue(params[1]); // Wallet comments CWalletTx wtx; if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty()) wtx.mapValue["comment"] = params[2].get_str(); if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["to"] = params[3].get_str(); if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); return wtx.GetHash().GetHex(); } Value listaddressgroupings(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listaddressgroupings\n" "Lists groups of addresses which have had their common ownership\n" "made public by common use as inputs or as the resulting change\n" "in past transactions"); Array jsonGroupings; map<CTxDestination, int64> balances = pwalletMain->GetAddressBalances(); BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings()) { Array jsonGrouping; BOOST_FOREACH(CTxDestination address, grouping) { Array addressInfo; addressInfo.push_back(CBitcoinAddress(address).ToString()); addressInfo.push_back(ValueFromAmount(balances[address])); { LOCK(pwalletMain->cs_wallet); if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end()) addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second); } jsonGrouping.push_back(addressInfo); } jsonGroupings.push_back(jsonGrouping); } return jsonGroupings; } Value signmessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "signmessage <legendcoinaddress> <message>\n" "Sign a message with the private key of an address"); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); string strMessage = params[1].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); CKey key; if (!pwalletMain->GetKey(keyID, key)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available"); CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; vector<unsigned char> vchSig; if (!key.SignCompact(ss.GetHash(), vchSig)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed"); return EncodeBase64(&vchSig[0], vchSig.size()); } Value verifymessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 3) throw runtime_error( "verifymessage <legendcoinaddress> <signature> <message>\n" "Verify a signed message"); string strAddress = params[0].get_str(); string strSign = params[1].get_str(); string strMessage = params[2].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); bool fInvalid = false; vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid); if (fInvalid) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding"); CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; CPubKey pubkey; if (!pubkey.RecoverCompact(ss.GetHash(), vchSig)) return false; return (pubkey.GetID() == keyID); } Value getreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaddress <legendcoinaddress> [minconf=1]\n" "Returns the total amount received by <legendcoinaddress> in transactions with at least [minconf] confirmations."); // Bitcoin address CBitcoinAddress address = CBitcoinAddress(params[0].get_str()); CScript scriptPubKey; if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Legendcoin address"); scriptPubKey.SetDestination(address.Get()); if (!IsMine(*pwalletMain,scriptPubKey)) return (double)0.0; // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Tally int64 nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !wtx.IsFinal()) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } return ValueFromAmount(nAmount); } void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook) { const CTxDestination& address = item.first; const string& strName = item.second; if (strName == strAccount) setAddress.insert(address); } } Value getreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaccount <account> [minconf=1]\n" "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations."); // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Get the set of pub keys assigned to account string strAccount = AccountFromValue(params[0]); set<CTxDestination> setAddress; GetAccountAddresses(strAccount, setAddress); // Tally int64 nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !wtx.IsFinal()) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address)) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } } return (double)nAmount / (double)COIN; } int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth) { int64 nBalance = 0; // Tally wallet transactions for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsFinal()) continue; int64 nReceived, nSent, nFee; wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee); if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth) nBalance += nReceived; nBalance -= nSent + nFee; } // Tally internal accounting entries nBalance += walletdb.GetAccountCreditDebit(strAccount); return nBalance; } int64 GetAccountBalance(const string& strAccount, int nMinDepth) { CWalletDB walletdb(pwalletMain->strWalletFile); return GetAccountBalance(walletdb, strAccount, nMinDepth); } Value getbalance(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getbalance [account] [minconf=1]\n" "If [account] is not specified, returns the server's total available balance.\n" "If [account] is specified, returns the balance in the account."); if (params.size() == 0) return ValueFromAmount(pwalletMain->GetBalance()); int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); if (params[0].get_str() == "*") { // Calculate total balance a different way from GetBalance() // (GetBalance() sums up all unspent TxOuts) // getbalance and getbalance '*' 0 should return the same number int64 nBalance = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsConfirmed()) continue; int64 allFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount); if (wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived) nBalance += r.second; } BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listSent) nBalance -= r.second; nBalance -= allFee; } return ValueFromAmount(nBalance); } string strAccount = AccountFromValue(params[0]); int64 nBalance = GetAccountBalance(strAccount, nMinDepth); return ValueFromAmount(nBalance); } Value movecmd(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 5) throw runtime_error( "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n" "Move from one account in your wallet to another."); string strFrom = AccountFromValue(params[0]); string strTo = AccountFromValue(params[1]); int64 nAmount = AmountFromValue(params[2]); if (params.size() > 3) // unused parameter, used to be nMinDepth, keep type-checking it though (void)params[3].get_int(); string strComment; if (params.size() > 4) strComment = params[4].get_str(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!walletdb.TxnBegin()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); int64 nNow = GetAdjustedTime(); // Debit CAccountingEntry debit; debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); debit.strAccount = strFrom; debit.nCreditDebit = -nAmount; debit.nTime = nNow; debit.strOtherAccount = strTo; debit.strComment = strComment; walletdb.WriteAccountingEntry(debit); // Credit CAccountingEntry credit; credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); credit.strAccount = strTo; credit.nCreditDebit = nAmount; credit.nTime = nNow; credit.strOtherAccount = strFrom; credit.strComment = strComment; walletdb.WriteAccountingEntry(credit); if (!walletdb.TxnCommit()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); return true; } Value sendfrom(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 6) throw runtime_error( "sendfrom <fromaccount> <tolegendcoinaddress> <amount> [minconf=1] [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.00000001" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); CBitcoinAddress address(params[1].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Legendcoin address"); int64 nAmount = AmountFromValue(params[2]); int nMinDepth = 1; if (params.size() > 3) nMinDepth = params[3].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty()) wtx.mapValue["comment"] = params[4].get_str(); if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty()) wtx.mapValue["to"] = params[5].get_str(); EnsureWalletIsUnlocked(); // Check funds int64 nBalance = GetAccountBalance(strAccount, nMinDepth); if (nAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); return wtx.GetHash().GetHex(); } Value sendmany(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n" "amounts are double-precision floating point numbers" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); Object sendTo = params[1].get_obj(); int nMinDepth = 1; if (params.size() > 2) nMinDepth = params[2].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["comment"] = params[3].get_str(); set<CBitcoinAddress> setAddress; vector<pair<CScript, int64> > vecSend; int64 totalAmount = 0; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Legendcoin address: ")+s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64 nAmount = AmountFromValue(s.value_); totalAmount += nAmount; vecSend.push_back(make_pair(scriptPubKey, nAmount)); } EnsureWalletIsUnlocked(); // Check funds int64 nBalance = GetAccountBalance(strAccount, nMinDepth); if (totalAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send CReserveKey keyChange(pwalletMain); int64 nFeeRequired = 0; string strFailReason; bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, strFailReason); if (!fCreated) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason); if (!pwalletMain->CommitTransaction(wtx, keyChange)) throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed"); return wtx.GetHash().GetHex(); } // // Used by addmultisigaddress / createmultisig: // static CScript _createmultisig(const Array& params) { int nRequired = params[0].get_int(); const Array& keys = params[1].get_array(); // Gather public keys if (nRequired < 1) throw runtime_error("a multisignature address must require at least one key to redeem"); if ((int)keys.size() < nRequired) throw runtime_error( strprintf("not enough keys supplied " "(got %"PRIszu" keys, but need at least %d to redeem)", keys.size(), nRequired)); std::vector<CPubKey> pubkeys; pubkeys.resize(keys.size()); for (unsigned int i = 0; i < keys.size(); i++) { const std::string& ks = keys[i].get_str(); // Case 1: Legendcoin address and we have full public key: CBitcoinAddress address(ks); if (pwalletMain && address.IsValid()) { CKeyID keyID; if (!address.GetKeyID(keyID)) throw runtime_error( strprintf("%s does not refer to a key",ks.c_str())); CPubKey vchPubKey; if (!pwalletMain->GetPubKey(keyID, vchPubKey)) throw runtime_error( strprintf("no full public key for address %s",ks.c_str())); if (!vchPubKey.IsFullyValid()) throw runtime_error(" Invalid public key: "+ks); pubkeys[i] = vchPubKey; } // Case 2: hex public key else if (IsHex(ks)) { CPubKey vchPubKey(ParseHex(ks)); if (!vchPubKey.IsFullyValid()) throw runtime_error(" Invalid public key: "+ks); pubkeys[i] = vchPubKey; } else { throw runtime_error(" Invalid public key: "+ks); } } CScript result; result.SetMultisig(nRequired, pubkeys); return result; } Value addmultisigaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) { string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n" "Add a nrequired-to-sign multisignature address to the wallet\"\n" "each key is a Legendcoin address or hex-encoded public key\n" "If [account] is specified, assign address to [account]."; throw runtime_error(msg); } string strAccount; if (params.size() > 2) strAccount = AccountFromValue(params[2]); // Construct using pay-to-script-hash: CScript inner = _createmultisig(params); CScriptID innerID = inner.GetID(); pwalletMain->AddCScript(inner); pwalletMain->SetAddressBookName(innerID, strAccount); return CBitcoinAddress(innerID).ToString(); } Value createmultisig(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 2) { string msg = "createmultisig <nrequired> <'[\"key\",\"key\"]'>\n" "Creates a multi-signature address and returns a json object\n" "with keys:\n" "address : legendcoin address\n" "redeemScript : hex-encoded redemption script"; throw runtime_error(msg); } // Construct using pay-to-script-hash: CScript inner = _createmultisig(params); CScriptID innerID = inner.GetID(); CBitcoinAddress address(innerID); Object result; result.push_back(Pair("address", address.ToString())); result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end()))); return result; } struct tallyitem { int64 nAmount; int nConf; vector<uint256> txids; tallyitem() { nAmount = 0; nConf = std::numeric_limits<int>::max(); } }; Value ListReceived(const Array& params, bool fByAccounts) { // Minimum confirmations int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); // Whether to include empty accounts bool fIncludeEmpty = false; if (params.size() > 1) fIncludeEmpty = params[1].get_bool(); // Tally map<CBitcoinAddress, tallyitem> mapTally; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !wtx.IsFinal()) continue; int nDepth = wtx.GetDepthInMainChain(); if (nDepth < nMinDepth) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address)) continue; tallyitem& item = mapTally[address]; item.nAmount += txout.nValue; item.nConf = min(item.nConf, nDepth); item.txids.push_back(wtx.GetHash()); } } // Reply Array ret; map<string, tallyitem> mapAccountTally; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strAccount = item.second; map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address); if (it == mapTally.end() && !fIncludeEmpty) continue; int64 nAmount = 0; int nConf = std::numeric_limits<int>::max(); if (it != mapTally.end()) { nAmount = (*it).second.nAmount; nConf = (*it).second.nConf; } if (fByAccounts) { tallyitem& item = mapAccountTally[strAccount]; item.nAmount += nAmount; item.nConf = min(item.nConf, nConf); } else { Object obj; obj.push_back(Pair("address", address.ToString())); obj.push_back(Pair("account", strAccount)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); Array transactions; if (it != mapTally.end()) { BOOST_FOREACH(const uint256& item, (*it).second.txids) { transactions.push_back(item.GetHex()); } } obj.push_back(Pair("txids", transactions)); ret.push_back(obj); } } if (fByAccounts) { for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) { int64 nAmount = (*it).second.nAmount; int nConf = (*it).second.nConf; Object obj; obj.push_back(Pair("account", (*it).first)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } return ret; } Value listreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaddress [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include addresses that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"address\" : receiving address\n" " \"account\" : the account of the receiving address\n" " \"amount\" : total amount received by the address\n" " \"confirmations\" : number of confirmations of the most recent transaction included\n" " \"txids\" : list of transactions with outputs to the address\n"); return ListReceived(params, false); } Value listreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaccount [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include accounts that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"account\" : the account of the receiving addresses\n" " \"amount\" : total amount received by addresses with this account\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); return ListReceived(params, true); } static void MaybePushAddress(Object & entry, const CTxDestination &dest) { CBitcoinAddress addr; if (addr.Set(dest)) entry.push_back(Pair("address", addr.ToString())); } void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret) { int64 nFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount); bool fAllAccounts = (strAccount == string("*")); // Sent if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent) { Object entry; entry.push_back(Pair("account", strSentAccount)); MaybePushAddress(entry, s.first); entry.push_back(Pair("category", "send")); entry.push_back(Pair("amount", ValueFromAmount(-s.second))); entry.push_back(Pair("fee", ValueFromAmount(-nFee))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } // Received if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived) { string account; if (pwalletMain->mapAddressBook.count(r.first)) account = pwalletMain->mapAddressBook[r.first]; if (fAllAccounts || (account == strAccount)) { Object entry; entry.push_back(Pair("account", account)); MaybePushAddress(entry, r.first); if (wtx.IsCoinBase()) { if (wtx.GetDepthInMainChain() < 1) entry.push_back(Pair("category", "orphan")); else if (wtx.GetBlocksToMaturity() > 0) entry.push_back(Pair("category", "immature")); else entry.push_back(Pair("category", "generate")); } else { entry.push_back(Pair("category", "receive")); } entry.push_back(Pair("amount", ValueFromAmount(r.second))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } } } void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret) { bool fAllAccounts = (strAccount == string("*")); if (fAllAccounts || acentry.strAccount == strAccount) { Object entry; entry.push_back(Pair("account", acentry.strAccount)); entry.push_back(Pair("category", "move")); entry.push_back(Pair("time", (boost::int64_t)acentry.nTime)); entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit))); entry.push_back(Pair("otheraccount", acentry.strOtherAccount)); entry.push_back(Pair("comment", acentry.strComment)); ret.push_back(entry); } } Value listtransactions(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listtransactions [account] [count=10] [from=0]\n" "Returns up to [count] most recent transactions skipping the first [from] transactions for account [account]."); string strAccount = "*"; if (params.size() > 0) strAccount = params[0].get_str(); int nCount = 10; if (params.size() > 1) nCount = params[1].get_int(); int nFrom = 0; if (params.size() > 2) nFrom = params[2].get_int(); if (nCount < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count"); if (nFrom < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from"); Array ret; std::list<CAccountingEntry> acentries; CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount); // iterate backwards until we have nCount items to return: for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx != 0) ListTransactions(*pwtx, strAccount, 0, true, ret); CAccountingEntry *const pacentry = (*it).second.second; if (pacentry != 0) AcentryToJSON(*pacentry, strAccount, ret); if ((int)ret.size() >= (nCount+nFrom)) break; } // ret is newest to oldest if (nFrom > (int)ret.size()) nFrom = ret.size(); if ((nFrom + nCount) > (int)ret.size()) nCount = ret.size() - nFrom; Array::iterator first = ret.begin(); std::advance(first, nFrom); Array::iterator last = ret.begin(); std::advance(last, nFrom+nCount); if (last != ret.end()) ret.erase(last, ret.end()); if (first != ret.begin()) ret.erase(ret.begin(), first); std::reverse(ret.begin(), ret.end()); // Return oldest to newest return ret; } Value listaccounts(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "listaccounts [minconf=1]\n" "Returns Object that has account names as keys, account balances as values."); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); map<string, int64> mapAccountBalances; BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) { if (IsMine(*pwalletMain, entry.first)) // This address belongs to me mapAccountBalances[entry.second] = 0; } for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; int64 nFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount); mapAccountBalances[strSentAccount] -= nFee; BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent) mapAccountBalances[strSentAccount] -= s.second; if (wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived) if (pwalletMain->mapAddressBook.count(r.first)) mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second; else mapAccountBalances[""] += r.second; } } list<CAccountingEntry> acentries; CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries); BOOST_FOREACH(const CAccountingEntry& entry, acentries) mapAccountBalances[entry.strAccount] += entry.nCreditDebit; Object ret; BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) { ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second))); } return ret; } Value listsinceblock(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listsinceblock [blockhash] [target-confirmations]\n" "Get all transactions in blocks since block [blockhash], or all transactions if omitted"); CBlockIndex *pindex = NULL; int target_confirms = 1; if (params.size() > 0) { uint256 blockId = 0; blockId.SetHex(params[0].get_str()); pindex = CBlockLocator(blockId).GetBlockIndex(); } if (params.size() > 1) { target_confirms = params[1].get_int(); if (target_confirms < 1) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); } int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1; Array transactions; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++) { CWalletTx tx = (*it).second; if (depth == -1 || tx.GetDepthInMainChain() < depth) ListTransactions(tx, "*", 0, true, transactions); } uint256 lastblock; if (target_confirms == 1) { lastblock = hashBestChain; } else { int target_height = pindexBest->nHeight + 1 - target_confirms; CBlockIndex *block; for (block = pindexBest; block && block->nHeight > target_height; block = block->pprev) { } lastblock = block ? block->GetBlockHash() : 0; } Object ret; ret.push_back(Pair("transactions", transactions)); ret.push_back(Pair("lastblock", lastblock.GetHex())); return ret; } Value gettransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "gettransaction <txid>\n" "Get detailed information about in-wallet transaction <txid>"); uint256 hash; hash.SetHex(params[0].get_str()); Object entry; if (!pwalletMain->mapWallet.count(hash)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id"); const CWalletTx& wtx = pwalletMain->mapWallet[hash]; int64 nCredit = wtx.GetCredit(); int64 nDebit = wtx.GetDebit(); int64 nNet = nCredit - nDebit; int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0); entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee))); if (wtx.IsFromMe()) entry.push_back(Pair("fee", ValueFromAmount(nFee))); WalletTxToJSON(wtx, entry); Array details; ListTransactions(wtx, "*", 0, false, details); entry.push_back(Pair("details", details)); return entry; } Value backupwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "backupwallet <destination>\n" "Safely copies wallet.dat to destination, which can be a directory or a path with filename."); string strDest = params[0].get_str(); if (!BackupWallet(*pwalletMain, strDest)) throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!"); return Value::null; } Value keypoolrefill(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "keypoolrefill\n" "Fills the keypool." + HelpRequiringPassphrase()); EnsureWalletIsUnlocked(); pwalletMain->TopUpKeyPool(); if (pwalletMain->GetKeyPoolSize() < GetArg("-keypool", 100)) throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool."); return Value::null; } void ThreadTopUpKeyPool(void* parg) { // Make this thread recognisable as the key-topping-up thread RenameThread("bitcoin-key-top"); pwalletMain->TopUpKeyPool(); } void ThreadCleanWalletPassphrase(void* parg) { // Make this thread recognisable as the wallet relocking thread RenameThread("bitcoin-lock-wa"); int64 nMyWakeTime = GetTimeMillis() + *((int64*)parg) * 1000; ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); if (nWalletUnlockTime == 0) { nWalletUnlockTime = nMyWakeTime; do { if (nWalletUnlockTime==0) break; int64 nToSleep = nWalletUnlockTime - GetTimeMillis(); if (nToSleep <= 0) break; LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); MilliSleep(nToSleep); ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); } while(1); if (nWalletUnlockTime) { nWalletUnlockTime = 0; pwalletMain->Lock(); } } else { if (nWalletUnlockTime < nMyWakeTime) nWalletUnlockTime = nMyWakeTime; } LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); delete (int64*)parg; } Value walletpassphrase(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrase <passphrase> <timeout>\n" "Stores the wallet decryption key in memory for <timeout> seconds."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called."); if (!pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked."); // Note that the walletpassphrase is stored in params[0] which is not mlock()ed SecureString strWalletPass; strWalletPass.reserve(100); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() > 0) { if (!pwalletMain->Unlock(strWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); } else throw runtime_error( "walletpassphrase <passphrase> <timeout>\n" "Stores the wallet decryption key in memory for <timeout> seconds."); NewThread(ThreadTopUpKeyPool, NULL); int64* pnSleepTime = new int64(params[1].get_int64()); NewThread(ThreadCleanWalletPassphrase, pnSleepTime); return Value::null; } Value walletpassphrasechange(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called."); // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strOldWalletPass; strOldWalletPass.reserve(100); strOldWalletPass = params[0].get_str().c_str(); SecureString strNewWalletPass; strNewWalletPass.reserve(100); strNewWalletPass = params[1].get_str().c_str(); if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); return Value::null; } Value walletlock(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0)) throw runtime_error( "walletlock\n" "Removes the wallet encryption key from memory, locking the wallet.\n" "After calling this method, you will need to call walletpassphrase again\n" "before being able to call any methods which require the wallet to be unlocked."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called."); { LOCK(cs_nWalletUnlockTime); pwalletMain->Lock(); nWalletUnlockTime = 0; } return Value::null; } Value encryptwallet(const Array& params, bool fHelp) { if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1)) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (fHelp) return true; if (pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called."); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() < 1) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (!pwalletMain->EncryptWallet(strWalletPass)) throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet."); // BDB seems to have a bad habit of writing old data into // slack space in .dat files; that is bad if the old data is // unencrypted private keys. So: StartShutdown(); return "wallet encrypted; Legendcoin server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup."; } class DescribeAddressVisitor : public boost::static_visitor<Object> { public: Object operator()(const CNoDestination &dest) const { return Object(); } Object operator()(const CKeyID &keyID) const { Object obj; CPubKey vchPubKey; pwalletMain->GetPubKey(keyID, vchPubKey); obj.push_back(Pair("isscript", false)); obj.push_back(Pair("pubkey", HexStr(vchPubKey))); obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed())); return obj; } Object operator()(const CScriptID &scriptID) const { Object obj; obj.push_back(Pair("isscript", true)); CScript subscript; pwalletMain->GetCScript(scriptID, subscript); std::vector<CTxDestination> addresses; txnouttype whichType; int nRequired; ExtractDestinations(subscript, whichType, addresses, nRequired); obj.push_back(Pair("script", GetTxnOutputType(whichType))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); obj.push_back(Pair("addresses", a)); if (whichType == TX_MULTISIG) obj.push_back(Pair("sigsrequired", nRequired)); return obj; } }; Value validateaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "validateaddress <legendcoinaddress>\n" "Return information about <legendcoinaddress>."); CBitcoinAddress address(params[0].get_str()); bool isValid = address.IsValid(); Object ret; ret.push_back(Pair("isvalid", isValid)); if (isValid) { CTxDestination dest = address.Get(); string currentAddress = address.ToString(); ret.push_back(Pair("address", currentAddress)); bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false; ret.push_back(Pair("ismine", fMine)); if (fMine) { Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest); ret.insert(ret.end(), detail.begin(), detail.end()); } if (pwalletMain && pwalletMain->mapAddressBook.count(dest)) ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest])); } return ret; } Value lockunspent(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "lockunspent unlock? [array-of-Objects]\n" "Updates list of temporarily unspendable outputs."); if (params.size() == 1) RPCTypeCheck(params, list_of(bool_type)); else RPCTypeCheck(params, list_of(bool_type)(array_type)); bool fUnlock = params[0].get_bool(); if (params.size() == 1) { if (fUnlock) pwalletMain->UnlockAllCoins(); return true; } Array outputs = params[1].get_array(); BOOST_FOREACH(Value& output, outputs) { if (output.type() != obj_type) throw JSONRPCError(-8, "Invalid parameter, expected object"); const Object& o = output.get_obj(); RPCTypeCheck(o, map_list_of("txid", str_type)("vout", int_type)); string txid = find_value(o, "txid").get_str(); if (!IsHex(txid)) throw JSONRPCError(-8, "Invalid parameter, expected hex txid"); int nOutput = find_value(o, "vout").get_int(); if (nOutput < 0) throw JSONRPCError(-8, "Invalid parameter, vout must be positive"); COutPoint outpt(uint256(txid), nOutput); if (fUnlock) pwalletMain->UnlockCoin(outpt); else pwalletMain->LockCoin(outpt); } return true; } Value listlockunspent(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "listlockunspent\n" "Returns list of temporarily unspendable outputs."); vector<COutPoint> vOutpts; pwalletMain->ListLockedCoins(vOutpts); Array ret; BOOST_FOREACH(COutPoint &outpt, vOutpts) { Object o; o.push_back(Pair("txid", outpt.hash.GetHex())); o.push_back(Pair("vout", (int)outpt.n)); ret.push_back(o); } return ret; }
[ "sunchaoqun@126.com" ]
sunchaoqun@126.com
afeeb5ef42f822403b4fd9048a2be1c94dc1ed50
ab01f5ba3e2130f1160a5fa51f7a993c7aa8d14f
/Projects/IMeteorite/Meteorite.h
cc101e616ef13d1ed49f053932d04e68531e18e4
[]
no_license
HinsSyr/Shoot-Game
b6400ae8239d02a5e7bf1f838b29de3b0297aac2
7415791f069b6bbee5913c51256c18a31600a4bb
refs/heads/master
2023-03-02T00:35:11.171213
2021-02-08T01:15:07
2021-02-08T01:15:07
336,927,469
0
0
null
null
null
null
UTF-8
C++
false
false
2,545
h
#ifndef METEORITE_H #define METEORITE_H /////////////////////////////////////////////////////////////////////// // Meteorite.h Meteorite object // // // // ver 1.0 // // Author: Bo Qiu Master in Computer Engineering, // // Syracuse University // // (315) 278-2362, qb86880301@gmail.com // /////////////////////////////////////////////////////////////////////// /* * Package Operations: * ------------------- * - This package contains a Meteorite class that implements IMeteorite * interface. It also contains a Factory class that creates instances * of Meteorite. * * Required Files: * --------------- * IMeteorite.h * Simple2D.h * * Maintenance History * ------------------- * ver 1.0 : 05 Dec 2020 * - first release */ #include "IMeteorite.h" #include "../../Extern/Simple2D/Includes/Simple2D.h" #include <iostream> namespace Simple2D { class Meteorite : public IMeteorite { public: Meteorite(int &tp, int& minSp, int& maxSp, float &sps); ~Meteorite(); virtual void drawMeteorite() override; virtual float getPosx() override; virtual float getPosy() override; virtual void movement() override; virtual int getDesx() override; virtual int getDesy() override; virtual int getHeight() override; virtual int getWidth() override; virtual void increHitCount(int count) override; virtual int getHitCount() override; virtual int getMaxHit() override; virtual void increMaxHit(int count) override; virtual void setSpeed(int &minSp, int &maxSp) override; virtual int getMaxSpeed() override; virtual int getMinSpeed() override; virtual void setSpeedScale(float &scale) override; private: void getSize(); void randomPos(); //meteorites born in random places int getRandomNumber(int a, int b); //get random number from [A,B] Simple2D::Image* pImageMeteorite = nullptr; float posX, posY, speedScale; int speed, scale, rotate, desX, desY, speedX, speedY, minSpeed, maxSpeed, countHits, maxHits; int* pWidth, * pHeight; bool goUp; }; class MeteoriteFactory { public: static IMeteorite* createMeteorite(int &tp, int& minSp, int& maxSp, float &sps) { Meteorite* rtn = new Meteorite(tp,minSp,maxSp,sps); return rtn; } }; } #endif
[ "bqiu03@syr.edu" ]
bqiu03@syr.edu
18aa0c2584ee9c9addc69129d37c52442bdc8f68
c53bbbdb65378437e05ef1e0de0041684e1797cb
/CONTRIB/LLVM/src/lib/Support/ManagedStatic.cpp
9868207b14ff2733ba7c8ea75b81ec6a98b7abe4
[ "Spencer-94", "BSD-3-Clause", "Apache-2.0" ]
permissive
Maeiky/CpcdosOS2.1-1
b4d087b85f137f44fc34a521ebede3a5fc1d6c59
95910f2fe0cfeda592d6c47d8fa29f380b2b4d08
refs/heads/main
2023-03-26T08:39:40.606756
2021-03-16T05:57:00
2021-03-16T05:57:00
345,801,854
0
0
Apache-2.0
2021-03-08T21:36:06
2021-03-08T21:36:06
null
UTF-8
C++
false
false
2,683
cpp
//===-- ManagedStatic.cpp - Static Global wrapper -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the ManagedStatic class and llvm_shutdown(). // //===----------------------------------------------------------------------===// #include "llvm/Support/ManagedStatic.h" #include "llvm/Config/config.h" #include "llvm/Support/Atomic.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Mutex.h" #include "llvm/Support/MutexGuard.h" #include <cassert> using namespace llvm; static const ManagedStaticBase *StaticList = nullptr; static sys::Mutex& getManagedStaticMutex() { // We need to use a function local static here, since this can get called // during a static constructor and we need to guarantee that it's initialized // correctly. static sys::Mutex ManagedStaticMutex; return ManagedStaticMutex; } void ManagedStaticBase::RegisterManagedStatic(void *(*Creator)(), void (*Deleter)(void*)) const { assert(Creator); if (llvm_is_multithreaded()) { MutexGuard Lock(getManagedStaticMutex()); if (!Ptr) { void* tmp = Creator(); TsanHappensBefore(this); sys::MemoryFence(); // This write is racy against the first read in the ManagedStatic // accessors. The race is benign because it does a second read after a // memory fence, at which point it isn't possible to get a partial value. TsanIgnoreWritesBegin(); Ptr = tmp; TsanIgnoreWritesEnd(); DeleterFn = Deleter; // Add to list of managed statics. Next = StaticList; StaticList = this; } } else { assert(!Ptr && !DeleterFn && !Next && "Partially initialized ManagedStatic!?"); Ptr = Creator(); DeleterFn = Deleter; // Add to list of managed statics. Next = StaticList; StaticList = this; } } void ManagedStaticBase::destroy() const { assert(DeleterFn && "ManagedStatic not initialized correctly!"); assert(StaticList == this && "Not destroyed in reverse order of construction?"); // Unlink from list. StaticList = Next; Next = nullptr; // Destroy memory. DeleterFn(Ptr); // Cleanup. Ptr = nullptr; DeleterFn = nullptr; } /// llvm_shutdown - Deallocate and destroy all ManagedStatic variables. void llvm::llvm_shutdown() { MutexGuard Lock(getManagedStaticMutex()); while (StaticList) StaticList->destroy(); }
[ "cpcdososx@gmail.com" ]
cpcdososx@gmail.com
e2b1bd304976789735eb1ec74676e74907ab870f
309e9e43f6c105f686a5991d355f201423b6f20e
/old study/c++/c_++ yuanma/appliance/light.h
71df3d0b4fecd81b6e049e96c7c82120db70e83c
[]
no_license
jikal/mystudy
d1e106725154730de0567fe4d7a7efa857b09682
ff51292c3fcb93d354c279e2c5222bc17b874966
refs/heads/master
2020-05-30T09:36:55.439089
2015-06-30T02:58:22
2015-06-30T02:58:22
35,258,479
0
0
null
null
null
null
UTF-8
C++
false
false
257
h
#ifndef _LIGHT_H_ #define _LIGHT_H_ #include "appliance.h" #define WHITE 1 #define GREEN 2 class Light : public Appliance{ public: Light(int price, int color); ~Light(); void on(); void off(); string toString(); private: int m_color; }; #endif
[ "zhk@ubuntu.(none)" ]
zhk@ubuntu.(none)
9bd21eec6afbc87007020e6dc7253210fd7602cf
d4bfae1b7aba456a355487e98c50dfd415ccb9ba
/media/filters/decrypting_demuxer_stream.cc
bc35d5bd109c40db26380e75932b9629161fa39f
[ "BSD-3-Clause" ]
permissive
mindaptiv/chromium
d123e4e215ef4c82518a6d08a9c4211433ae3715
a93319b2237f37862989129eeecf87304ab4ff0c
refs/heads/master
2023-05-19T22:48:12.614549
2016-08-23T02:56:57
2016-08-23T02:56:57
66,865,429
1
1
null
2016-08-29T17:35:46
2016-08-29T17:35:45
null
UTF-8
C++
false
false
12,383
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/filters/decrypting_demuxer_stream.h" #include "base/bind.h" #include "base/callback_helpers.h" #include "base/location.h" #include "base/logging.h" #include "base/single_thread_task_runner.h" #include "media/base/bind_to_current_loop.h" #include "media/base/decoder_buffer.h" #include "media/base/media_log.h" #include "media/base/media_util.h" namespace media { static bool IsStreamValidAndEncrypted(DemuxerStream* stream) { return ((stream->type() == DemuxerStream::AUDIO && stream->audio_decoder_config().IsValidConfig() && stream->audio_decoder_config().is_encrypted()) || (stream->type() == DemuxerStream::VIDEO && stream->video_decoder_config().IsValidConfig() && stream->video_decoder_config().is_encrypted())); } DecryptingDemuxerStream::DecryptingDemuxerStream( const scoped_refptr<base::SingleThreadTaskRunner>& task_runner, const scoped_refptr<MediaLog>& media_log, const base::Closure& waiting_for_decryption_key_cb) : task_runner_(task_runner), media_log_(media_log), state_(kUninitialized), waiting_for_decryption_key_cb_(waiting_for_decryption_key_cb), demuxer_stream_(NULL), decryptor_(NULL), key_added_while_decrypt_pending_(false), weak_factory_(this) {} std::string DecryptingDemuxerStream::GetDisplayName() const { return "DecryptingDemuxerStream"; } void DecryptingDemuxerStream::Initialize(DemuxerStream* stream, CdmContext* cdm_context, const PipelineStatusCB& status_cb) { DVLOG(2) << __FUNCTION__; DCHECK(task_runner_->BelongsToCurrentThread()); DCHECK_EQ(state_, kUninitialized) << state_; DCHECK(stream); DCHECK(cdm_context); DCHECK(!demuxer_stream_); weak_this_ = weak_factory_.GetWeakPtr(); demuxer_stream_ = stream; init_cb_ = BindToCurrentLoop(status_cb); InitializeDecoderConfig(); if (!cdm_context->GetDecryptor()) { MEDIA_LOG(DEBUG, media_log_) << GetDisplayName() << ": no decryptor"; state_ = kUninitialized; base::ResetAndReturn(&init_cb_).Run(DECODER_ERROR_NOT_SUPPORTED); return; } decryptor_ = cdm_context->GetDecryptor(); decryptor_->RegisterNewKeyCB( GetDecryptorStreamType(), BindToCurrentLoop( base::Bind(&DecryptingDemuxerStream::OnKeyAdded, weak_this_))); state_ = kIdle; base::ResetAndReturn(&init_cb_).Run(PIPELINE_OK); } void DecryptingDemuxerStream::Read(const ReadCB& read_cb) { DVLOG(3) << __FUNCTION__; DCHECK(task_runner_->BelongsToCurrentThread()); DCHECK_EQ(state_, kIdle) << state_; DCHECK(!read_cb.is_null()); CHECK(read_cb_.is_null()) << "Overlapping reads are not supported."; read_cb_ = BindToCurrentLoop(read_cb); state_ = kPendingDemuxerRead; demuxer_stream_->Read( base::Bind(&DecryptingDemuxerStream::DecryptBuffer, weak_this_)); } void DecryptingDemuxerStream::Reset(const base::Closure& closure) { DVLOG(2) << __FUNCTION__ << " - state: " << state_; DCHECK(task_runner_->BelongsToCurrentThread()); DCHECK(state_ != kUninitialized) << state_; DCHECK(reset_cb_.is_null()); reset_cb_ = BindToCurrentLoop(closure); decryptor_->CancelDecrypt(GetDecryptorStreamType()); // Reset() cannot complete if the read callback is still pending. // Defer the resetting process in this case. The |reset_cb_| will be fired // after the read callback is fired - see DoDecryptBuffer() and // DoDeliverBuffer(). if (state_ == kPendingDemuxerRead || state_ == kPendingDecrypt) { DCHECK(!read_cb_.is_null()); return; } if (state_ == kWaitingForKey) { DCHECK(!read_cb_.is_null()); pending_buffer_to_decrypt_ = NULL; base::ResetAndReturn(&read_cb_).Run(kAborted, NULL); } DCHECK(read_cb_.is_null()); DoReset(); } AudioDecoderConfig DecryptingDemuxerStream::audio_decoder_config() { DCHECK(state_ != kUninitialized) << state_; CHECK_EQ(demuxer_stream_->type(), AUDIO); return audio_config_; } VideoDecoderConfig DecryptingDemuxerStream::video_decoder_config() { DCHECK(state_ != kUninitialized) << state_; CHECK_EQ(demuxer_stream_->type(), VIDEO); return video_config_; } DemuxerStream::Type DecryptingDemuxerStream::type() const { DCHECK(state_ != kUninitialized) << state_; return demuxer_stream_->type(); } DemuxerStream::Liveness DecryptingDemuxerStream::liveness() const { DCHECK(state_ != kUninitialized) << state_; return demuxer_stream_->liveness(); } void DecryptingDemuxerStream::EnableBitstreamConverter() { demuxer_stream_->EnableBitstreamConverter(); } bool DecryptingDemuxerStream::SupportsConfigChanges() { return demuxer_stream_->SupportsConfigChanges(); } VideoRotation DecryptingDemuxerStream::video_rotation() { return demuxer_stream_->video_rotation(); } bool DecryptingDemuxerStream::enabled() const { return demuxer_stream_->enabled(); } void DecryptingDemuxerStream::set_enabled(bool enabled, base::TimeDelta timestamp) { demuxer_stream_->set_enabled(enabled, timestamp); } void DecryptingDemuxerStream::SetStreamRestartedCB( const StreamRestartedCB& cb) { demuxer_stream_->SetStreamRestartedCB(cb); } DecryptingDemuxerStream::~DecryptingDemuxerStream() { DVLOG(2) << __FUNCTION__ << " : state_ = " << state_; DCHECK(task_runner_->BelongsToCurrentThread()); if (state_ == kUninitialized) return; if (decryptor_) { decryptor_->CancelDecrypt(GetDecryptorStreamType()); decryptor_ = NULL; } if (!init_cb_.is_null()) base::ResetAndReturn(&init_cb_).Run(PIPELINE_ERROR_ABORT); if (!read_cb_.is_null()) base::ResetAndReturn(&read_cb_).Run(kAborted, NULL); if (!reset_cb_.is_null()) base::ResetAndReturn(&reset_cb_).Run(); pending_buffer_to_decrypt_ = NULL; } void DecryptingDemuxerStream::DecryptBuffer( DemuxerStream::Status status, const scoped_refptr<DecoderBuffer>& buffer) { DVLOG(3) << __FUNCTION__; DCHECK(task_runner_->BelongsToCurrentThread()); DCHECK_EQ(state_, kPendingDemuxerRead) << state_; DCHECK(!read_cb_.is_null()); DCHECK_EQ(buffer.get() != NULL, status == kOk) << status; // Even when |!reset_cb_.is_null()|, we need to pass |kConfigChanged| back to // the caller so that the downstream decoder can be properly reinitialized. if (status == kConfigChanged) { DVLOG(2) << "DoDecryptBuffer() - kConfigChanged."; DCHECK_EQ(demuxer_stream_->type() == AUDIO, audio_config_.IsValidConfig()); DCHECK_EQ(demuxer_stream_->type() == VIDEO, video_config_.IsValidConfig()); // Update the decoder config, which the decoder will use when it is notified // of kConfigChanged. InitializeDecoderConfig(); state_ = kIdle; base::ResetAndReturn(&read_cb_).Run(kConfigChanged, NULL); if (!reset_cb_.is_null()) DoReset(); return; } if (!reset_cb_.is_null()) { base::ResetAndReturn(&read_cb_).Run(kAborted, NULL); DoReset(); return; } if (status == kAborted) { DVLOG(2) << "DoDecryptBuffer() - kAborted."; state_ = kIdle; base::ResetAndReturn(&read_cb_).Run(kAborted, NULL); return; } if (buffer->end_of_stream()) { DVLOG(2) << "DoDecryptBuffer() - EOS buffer."; state_ = kIdle; base::ResetAndReturn(&read_cb_).Run(status, buffer); return; } DCHECK(buffer->decrypt_config()); // An empty iv string signals that the frame is unencrypted. if (buffer->decrypt_config()->iv().empty()) { DVLOG(2) << "DoDecryptBuffer() - clear buffer."; scoped_refptr<DecoderBuffer> decrypted = DecoderBuffer::CopyFrom( buffer->data(), buffer->data_size()); decrypted->set_timestamp(buffer->timestamp()); decrypted->set_duration(buffer->duration()); if (buffer->is_key_frame()) decrypted->set_is_key_frame(true); state_ = kIdle; base::ResetAndReturn(&read_cb_).Run(kOk, decrypted); return; } pending_buffer_to_decrypt_ = buffer; state_ = kPendingDecrypt; DecryptPendingBuffer(); } void DecryptingDemuxerStream::DecryptPendingBuffer() { DCHECK(task_runner_->BelongsToCurrentThread()); DCHECK_EQ(state_, kPendingDecrypt) << state_; decryptor_->Decrypt( GetDecryptorStreamType(), pending_buffer_to_decrypt_, BindToCurrentLoop( base::Bind(&DecryptingDemuxerStream::DeliverBuffer, weak_this_))); } void DecryptingDemuxerStream::DeliverBuffer( Decryptor::Status status, const scoped_refptr<DecoderBuffer>& decrypted_buffer) { DVLOG(3) << __FUNCTION__ << " - status: " << status; DCHECK(task_runner_->BelongsToCurrentThread()); DCHECK_EQ(state_, kPendingDecrypt) << state_; DCHECK_NE(status, Decryptor::kNeedMoreData); DCHECK(!read_cb_.is_null()); DCHECK(pending_buffer_to_decrypt_.get()); bool need_to_try_again_if_nokey = key_added_while_decrypt_pending_; key_added_while_decrypt_pending_ = false; if (!reset_cb_.is_null()) { pending_buffer_to_decrypt_ = NULL; base::ResetAndReturn(&read_cb_).Run(kAborted, NULL); DoReset(); return; } DCHECK_EQ(status == Decryptor::kSuccess, decrypted_buffer.get() != NULL); if (status == Decryptor::kError) { DVLOG(2) << "DoDeliverBuffer() - kError"; MEDIA_LOG(ERROR, media_log_) << GetDisplayName() << ": decrypt error"; pending_buffer_to_decrypt_ = NULL; state_ = kIdle; base::ResetAndReturn(&read_cb_).Run(kAborted, NULL); return; } if (status == Decryptor::kNoKey) { DVLOG(2) << "DoDeliverBuffer() - kNoKey"; MEDIA_LOG(DEBUG, media_log_) << GetDisplayName() << ": no key"; if (need_to_try_again_if_nokey) { // The |state_| is still kPendingDecrypt. DecryptPendingBuffer(); return; } state_ = kWaitingForKey; waiting_for_decryption_key_cb_.Run(); return; } DCHECK_EQ(status, Decryptor::kSuccess); // Copy the key frame flag from the encrypted to decrypted buffer, assuming // that the decryptor initialized the flag to false. if (pending_buffer_to_decrypt_->is_key_frame()) decrypted_buffer->set_is_key_frame(true); pending_buffer_to_decrypt_ = NULL; state_ = kIdle; base::ResetAndReturn(&read_cb_).Run(kOk, decrypted_buffer); } void DecryptingDemuxerStream::OnKeyAdded() { DCHECK(task_runner_->BelongsToCurrentThread()); if (state_ == kPendingDecrypt) { key_added_while_decrypt_pending_ = true; return; } if (state_ == kWaitingForKey) { state_ = kPendingDecrypt; DecryptPendingBuffer(); } } void DecryptingDemuxerStream::DoReset() { DCHECK(state_ != kUninitialized); DCHECK(init_cb_.is_null()); DCHECK(read_cb_.is_null()); state_ = kIdle; base::ResetAndReturn(&reset_cb_).Run(); } Decryptor::StreamType DecryptingDemuxerStream::GetDecryptorStreamType() const { if (demuxer_stream_->type() == AUDIO) return Decryptor::kAudio; DCHECK_EQ(demuxer_stream_->type(), VIDEO); return Decryptor::kVideo; } void DecryptingDemuxerStream::InitializeDecoderConfig() { // The decoder selector or upstream demuxer make sure the stream is valid and // potentially encrypted. DCHECK(IsStreamValidAndEncrypted(demuxer_stream_)); switch (demuxer_stream_->type()) { case AUDIO: { AudioDecoderConfig input_audio_config = demuxer_stream_->audio_decoder_config(); audio_config_.Initialize( input_audio_config.codec(), input_audio_config.sample_format(), input_audio_config.channel_layout(), input_audio_config.samples_per_second(), input_audio_config.extra_data(), Unencrypted(), input_audio_config.seek_preroll(), input_audio_config.codec_delay()); break; } case VIDEO: { VideoDecoderConfig input_video_config = demuxer_stream_->video_decoder_config(); video_config_.Initialize( input_video_config.codec(), input_video_config.profile(), input_video_config.format(), input_video_config.color_space(), input_video_config.coded_size(), input_video_config.visible_rect(), input_video_config.natural_size(), input_video_config.extra_data(), Unencrypted()); break; } default: NOTREACHED(); return; } } } // namespace media
[ "serg.zhukovsky@gmail.com" ]
serg.zhukovsky@gmail.com
75c86ef28b23bc232f55ba04c982ebc7f691e34f
2c0d2a9c349365c27e7e7dd980c607c48d58c234
/s1257.cpp
c08fbaf0bebea562435291a2c5daa9fa6991fb4f
[]
no_license
h77h7/sw_expert_academy
3598d229ab7e7675d216a7a22fb9db2a6b94724b
efd0141301ce6bbd65856dc33845a11b1eb90dea
refs/heads/main
2023-06-03T11:48:46.539845
2021-06-08T06:43:38
2021-06-08T06:43:38
353,582,837
0
0
null
null
null
null
UTF-8
C++
false
false
1,752
cpp
//K번째 문자열 #include <iostream> #include <stdio.h> using namespace std; const int MAX = 400; int arrLen = 0; char arr[MAX] = { 0, }; int str_cmp(int idx1, int idx2) { while (idx1 < arrLen && idx2 < arrLen && arr[idx1] == arr[idx2]) { idx1++; idx2++; } return (arr[idx1] - arr[idx2]); } int str_cmp_(int idx1, int idx2) { //공통 접두어 길이 찾기 int cnt = 0; while (idx1 < arrLen && idx2 < arrLen && arr[idx1] == arr[idx2]) { cnt++; idx1++; idx2++; } return cnt; } void quicksort(int* a, int begin, int end) { if (begin < end) { int pivot = a[begin]; int i = begin; int j = end; while (i <= j) { while (i <= end && str_cmp(a[i], pivot) <= 0) i++; while (j >= begin && str_cmp(a[j], pivot) > 0) j--; if (i < j) { swap(a[i], a[j]); } } swap(a[begin], a[j]); quicksort(a, begin, j - 1); quicksort(a, j + 1, end); } } int main() { cin.tie(NULL); int tc; cin >> tc; for (int t = 1; t <= tc; t++) { int K; cin >> K; scanf(" %s", arr); int A[400] = { 0, }; int arrIdx = 0; while (arr[arrIdx]) { A[arrIdx] = arrIdx; arrIdx++; } arrLen = arrIdx; quicksort(A, 0, arrIdx - 1); int LCP[MAX] = { 0, }; for (int i = 1; i < arrLen; i++) { LCP[i] = str_cmp_(A[i - 1], A[i]); } cout << "#" << t << " "; int cnt = 0; int start_idx = -1; int end_idx = -1; for (int i = 0; i < arrLen; i++) { int curCnt = 0; curCnt += (arrLen - A[i] - LCP[i]); if (K > cnt && K <= cnt + curCnt) { start_idx = A[i]; end_idx = A[i] + K - cnt + LCP[i]; break; } cnt += curCnt; } if (start_idx < 0) { cout << "none\n"; } else { for (int i = start_idx; i < end_idx; i++) { cout << arr[i]; } cout << endl; } } }
[ "noreply@github.com" ]
h77h7.noreply@github.com
04c0a8bbc1eb6d8a834a02fee0d51bf070fba784
ef3fa8e089c53422db4a5bbff9721268976bae53
/cases/mixerVessel2D/150/uniform/time
08677b802582989a4172a79f1f321292383cac84
[]
no_license
will214/CFDcourse
6b22f00a86f5ac83378e059074eb907e288693f2
37bd665013d77095f85ea4e6bc464caa11f91db1
refs/heads/master
2021-05-09T18:51:12.192394
2016-11-20T10:02:50
2016-11-20T10:02:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
968
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 4.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "150/uniform"; object time; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value 150; name "150"; index 150; deltaT 1; deltaT0 1; // ************************************************************************* //
[ "victormavi_1995@hotmail.com" ]
victormavi_1995@hotmail.com
e669675136ccb263e0d7f18eed8ab42d4ec7c9a2
84827d73992a00aa28a6baabf6ff660af55657db
/1.0/code/interface/AndroidQQDecryptSDK.hpp
f32962424645cf052e364569df523b8c951f30ea
[]
no_license
mogeku/mytest
6b167c503330740df7f0127878e3a045539db981
cd3e474aaada674991c4d40761e9be9db77abd2f
refs/heads/main
2023-01-09T23:26:07.936899
2020-11-10T10:24:04
2020-11-10T10:24:04
310,562,755
0
0
null
null
null
null
UTF-8
C++
false
false
1,447
hpp
// The following ifdef block is the standard way of creating macros which make exporting // from a DLL simpler. All files within this DLL are compiled with the ANDROIDQQDECRYPTSDK_EXPORTS // symbol defined on the command line. This symbol should not be defined on any project // that uses this DLL. This way any other project whose source files include this file see // ANDROIDQQDECRYPTSDK_API functions as being imported from a DLL, whereas this DLL sees symbols // defined with this macro as being exported. #ifndef _ANDROIDQQDECRYPTSDK_H #define _ANDROIDQQDECRYPTSDK_H #ifdef _WIN32 #ifdef ANDROIDQQDECRYPTSDK_EXPORTS #define ANDROIDQQDECRYPTSDK_API __declspec(dllexport) #else #define ANDROIDQQDECRYPTSDK_API __declspec(dllimport) #endif #else #ifdef ANDROIDQQDECRYPTSDK_EXPORTS #define ANDROIDQQDECRYPTSDK_API extern "C" __attribute__((visibility ("default"))) #else #define ANDROIDQQDECRYPTSDK_API extern "C" #endif #endif enum PhoneType { HUAWEI = 0, XIAOMI, }; enum QQDecryptErrorType { ERROR_NO, ERROR_INVALID_PARAM = 2000, ERROR_PATH_NOT_EXIST, ERROR_UNKNOW_PHONE_TYPE, ERROR_PATH_NOT_DIR, ERROR_DATABASE_COPY_FAILED, ERROR_GET_TABLE_FIELD_FAILED, ERROR_SEARCH_KEY_FAILED, }; ANDROIDQQDECRYPTSDK_API int InitAndroidQQDecryptSDK(); ANDROIDQQDECRYPTSDK_API int DecryptAndroidQQDB(PhoneType phone_type, const char* backup_folder, const char* decrypted_folder); ANDROIDQQDECRYPTSDK_API void StopAndroidQQDBDecrypt(); #endif
[ "local@email.com" ]
local@email.com
52211ec7167cbe4534272b0dfe158ab6edae8c5d
89016fcda83d19cf880a3671e7923d69b8cb7c39
/spriterengine/global/settings.h
8ec7bd60521f147648da2e3de563344d2f2c7538
[ "Zlib" ]
permissive
lucidspriter/SpriterPlusPlus
9f83e68cd81295642dd3814ab800cd92967ee6c0
8fb550e1633036b42acd1cce0e05cfe60a3041c0
refs/heads/master
2023-08-10T10:29:03.386422
2021-02-17T22:13:10
2021-02-17T22:13:10
45,448,363
97
55
NOASSERTION
2023-07-23T13:17:31
2015-11-03T07:09:45
C++
UTF-8
C++
false
false
875
h
#ifndef SETTINGS_H #define SETTINGS_H #include <iostream> #include <string> namespace SpriterEngine { typedef void(*ErrorFunctionPointer)(const std::string &errorMessage); class Settings { public: static bool renderDebugBoxes; static bool renderDebugPoints; static bool renderDebugBones; static bool enableDebugBones; static void simpleError(const std::string &errorMessage); static void nullError(const std::string &errorMessage); static void error(const std::string &errorMessage); static void setErrorFunction(ErrorFunctionPointer errorFunction); static void suppressErrorOutput(bool suppress = true); static bool reverseYOnLoad; static bool reversePivotYOnLoad; static bool reverseAngleOnLoad; private: static ErrorFunctionPointer errFunction; static ErrorFunctionPointer previousErrorFunction; }; } #endif // SETTINGS_H
[ "lucid@brashmonkey.com" ]
lucid@brashmonkey.com
45cd2f2228f37422e3a3ad9ffe0f1bfaa4124892
4bad7578931dd47c38dc283aec7eb961be6e1f30
/tests/core_tests/v2_tests.h
76a3b24728e4221a8a750a92818b212e4c9b96fd
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
cyberstormdotmu/electroneum-classic
d034453071a3c9fa37f494c212e3ffc6d0effc9b
494bd2b5f9d9d759c10568e0326dde1737cefad6
refs/heads/master
2020-04-01T06:25:43.262217
2018-10-17T04:16:13
2018-10-17T04:16:13
152,947,188
0
0
null
2018-10-14T06:47:32
2018-10-14T06:47:32
null
UTF-8
C++
false
false
5,069
h
// Copyrights(c) 2018, The Electroneum Classic Project // Copyrights(c) 2017-2018, The Electroneum Project // Copyrights(c) 2014-2017, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #pragma once #include "chaingen.h" struct gen_v2_tx_validation_base : public test_chain_unit_base { gen_v2_tx_validation_base() : m_invalid_tx_index(0) , m_invalid_block_index(0) { REGISTER_CALLBACK_METHOD(gen_v2_tx_validation_base, mark_invalid_tx); REGISTER_CALLBACK_METHOD(gen_v2_tx_validation_base, mark_invalid_block); } bool check_tx_verification_context(const cryptonote::tx_verification_context& tvc, bool tx_added, size_t event_idx, const cryptonote::transaction& /*tx*/) { if (m_invalid_tx_index == event_idx) return tvc.m_verifivation_failed; else return !tvc.m_verifivation_failed && tx_added; } bool check_block_verification_context(const cryptonote::block_verification_context& bvc, size_t event_idx, const cryptonote::block& /*block*/) { if (m_invalid_block_index == event_idx) return bvc.m_verifivation_failed; else return !bvc.m_verifivation_failed; } bool mark_invalid_block(cryptonote::core& /*c*/, size_t ev_index, const std::vector<test_event_entry>& /*events*/) { m_invalid_block_index = ev_index + 1; return true; } bool mark_invalid_tx(cryptonote::core& /*c*/, size_t ev_index, const std::vector<test_event_entry>& /*events*/) { m_invalid_tx_index = ev_index + 1; return true; } bool generate_with(std::vector<test_event_entry>& events, const int *out_idx, int mixin, uint64_t amount_paid, bool valid) const; private: size_t m_invalid_tx_index; size_t m_invalid_block_index; }; template<> struct get_test_options<gen_v2_tx_validation_base> { const std::pair<uint8_t, uint64_t> hard_forks[3] = {std::make_pair(1, 0), std::make_pair(2, 1), std::make_pair(0, 0)}; const cryptonote::test_options test_options = { hard_forks }; }; struct gen_v2_tx_mixable_0_mixin : public gen_v2_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; template<> struct get_test_options<gen_v2_tx_mixable_0_mixin>: public get_test_options<gen_v2_tx_validation_base> {}; struct gen_v2_tx_mixable_low_mixin : public gen_v2_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; template<> struct get_test_options<gen_v2_tx_mixable_low_mixin>: public get_test_options<gen_v2_tx_validation_base> {}; struct gen_v2_tx_unmixable_only : public gen_v2_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; template<> struct get_test_options<gen_v2_tx_unmixable_only>: public get_test_options<gen_v2_tx_validation_base> {}; struct gen_v2_tx_unmixable_one : public gen_v2_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; template<> struct get_test_options<gen_v2_tx_unmixable_one>: public get_test_options<gen_v2_tx_validation_base> {}; struct gen_v2_tx_unmixable_two : public gen_v2_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; template<> struct get_test_options<gen_v2_tx_unmixable_two>: public get_test_options<gen_v2_tx_validation_base> {}; struct gen_v2_tx_dust : public gen_v2_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; template<> struct get_test_options<gen_v2_tx_dust>: public get_test_options<gen_v2_tx_validation_base> {};
[ "vans_163@yahoo.com" ]
vans_163@yahoo.com
e4897687d6455ae0e5b051345063725b9547303a
6a69d57c782e0b1b993e876ad4ca2927a5f2e863
/vendor/samsung/common/packages/apps/SBrowser/src/ui/views/controls/button/image_button.h
5d71ec42fc17647aaf9f23a6f205679f35e69d53
[ "BSD-3-Clause" ]
permissive
duki994/G900H-Platform-XXU1BOA7
c8411ef51f5f01defa96b3381f15ea741aa5bce2
4f9307e6ef21893c9a791c96a500dfad36e3b202
refs/heads/master
2020-05-16T20:57:07.585212
2015-05-11T11:03:16
2015-05-11T11:03:16
35,418,464
2
1
null
null
null
null
UTF-8
C++
false
false
5,566
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_BUTTON_IMAGE_BUTTON_H_ #define UI_VIEWS_CONTROLS_BUTTON_IMAGE_BUTTON_H_ #include "base/gtest_prod_util.h" #include "base/memory/scoped_ptr.h" #include "ui/base/layout.h" #include "ui/gfx/image/image_skia.h" #include "ui/views/controls/button/custom_button.h" namespace views { class Painter; // An image button. // Note that this type of button is not focusable by default and will not be // part of the focus chain. Call SetFocusable(true) to make it part of the // focus chain. class VIEWS_EXPORT ImageButton : public CustomButton { public: static const char kViewClassName[]; enum HorizontalAlignment { ALIGN_LEFT = 0, ALIGN_CENTER, ALIGN_RIGHT }; enum VerticalAlignment { ALIGN_TOP = 0, ALIGN_MIDDLE, ALIGN_BOTTOM }; explicit ImageButton(ButtonListener* listener); virtual ~ImageButton(); // Returns the image for a given |state|. virtual const gfx::ImageSkia& GetImage(ButtonState state) const; // Set the image the button should use for the provided state. virtual void SetImage(ButtonState state, const gfx::ImageSkia* image); // Set the background details. void SetBackground(SkColor color, const gfx::ImageSkia* image, const gfx::ImageSkia* mask); // Sets how the image is laid out within the button's bounds. void SetImageAlignment(HorizontalAlignment h_align, VerticalAlignment v_align); void SetFocusPainter(scoped_ptr<Painter> focus_painter); // Sets preferred size, so it could be correctly positioned in layout even if // it is NULL. void SetPreferredSize(const gfx::Size& preferred_size) { preferred_size_ = preferred_size; } // Whether we should draw our images resources horizontally flipped. void SetDrawImageMirrored(bool mirrored) { draw_image_mirrored_ = mirrored; } // Overridden from View: virtual gfx::Size GetPreferredSize() OVERRIDE; virtual const char* GetClassName() const OVERRIDE; virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE; protected: // Overridden from View: virtual void OnFocus() OVERRIDE; virtual void OnBlur() OVERRIDE; // Returns the image to paint. This is invoked from paint and returns a value // from images. virtual gfx::ImageSkia GetImageToPaint(); // Updates button background for |scale_factor|. void UpdateButtonBackground(ui::ScaleFactor scale_factor); Painter* focus_painter() { return focus_painter_.get(); } // The images used to render the different states of this button. gfx::ImageSkia images_[STATE_COUNT]; gfx::ImageSkia background_image_; private: FRIEND_TEST_ALL_PREFIXES(ImageButtonTest, Basics); FRIEND_TEST_ALL_PREFIXES(ImageButtonTest, ImagePositionWithBorder); FRIEND_TEST_ALL_PREFIXES(ImageButtonTest, LeftAlignedMirrored); FRIEND_TEST_ALL_PREFIXES(ImageButtonTest, RightAlignedMirrored); // Returns the correct position of the image for painting. gfx::Point ComputeImagePaintPosition(const gfx::ImageSkia& image); // Image alignment. HorizontalAlignment h_alignment_; VerticalAlignment v_alignment_; gfx::Size preferred_size_; // Whether we draw our resources horizontally flipped. This can happen in the // linux titlebar, where image resources were designed to be flipped so a // small curved corner in the close button designed to fit into the frame // resources. bool draw_image_mirrored_; scoped_ptr<Painter> focus_painter_; DISALLOW_COPY_AND_ASSIGN(ImageButton); }; //////////////////////////////////////////////////////////////////////////////// // // ToggleImageButton // // A toggle-able ImageButton. It swaps out its graphics when toggled. // //////////////////////////////////////////////////////////////////////////////// class VIEWS_EXPORT ToggleImageButton : public ImageButton { public: explicit ToggleImageButton(ButtonListener* listener); virtual ~ToggleImageButton(); // Change the toggled state. void SetToggled(bool toggled); // Like ImageButton::SetImage(), but to set the graphics used for the // "has been toggled" state. Must be called for each button state // before the button is toggled. void SetToggledImage(ButtonState state, const gfx::ImageSkia* image); // Set the tooltip text displayed when the button is toggled. void SetToggledTooltipText(const base::string16& tooltip); // Overridden from ImageButton: virtual const gfx::ImageSkia& GetImage(ButtonState state) const OVERRIDE; virtual void SetImage(ButtonState state, const gfx::ImageSkia* image) OVERRIDE; // Overridden from View: virtual bool GetTooltipText(const gfx::Point& p, base::string16* tooltip) const OVERRIDE; virtual void GetAccessibleState(ui::AccessibleViewState* state) OVERRIDE; private: // The parent class's images_ member is used for the current images, // and this array is used to hold the alternative images. // We swap between the two when toggling. gfx::ImageSkia alternate_images_[STATE_COUNT]; // True if the button is currently toggled. bool toggled_; // The parent class's tooltip_text_ is displayed when not toggled, and // this one is shown when toggled. base::string16 toggled_tooltip_text_; DISALLOW_COPY_AND_ASSIGN(ToggleImageButton); }; } // namespace views #endif // UI_VIEWS_CONTROLS_BUTTON_IMAGE_BUTTON_H_
[ "duki994@gmail.com" ]
duki994@gmail.com
c2f76efc3bc25c376acece49eb70ac0c1c618eb2
6e017be8782f3978f2bb235ef2d90dff16409e65
/Dev_class11Brofiler_handout/Motor2D/j1Scene.cpp
5e817ccabb642c29917cd38d847796cde3a4223c
[]
no_license
joseppi/Dev-Class
03fb4c2fde3cbd1628c9a24aca3cdf6646d51507
e12693f6a5e8f1786b33402e589e4498b3dfe124
refs/heads/master
2018-09-27T02:19:03.000505
2018-06-07T10:54:34
2018-06-07T10:54:34
112,933,525
0
0
null
null
null
null
UTF-8
C++
false
false
3,414
cpp
#include "p2Defs.h" #include "p2Log.h" #include "j1App.h" #include "j1Input.h" #include "j1Textures.h" #include "j1Audio.h" #include "j1Render.h" #include "j1Window.h" #include "j1Map.h" #include "j1PathFinding.h" #include "j1Scene.h" j1Scene::j1Scene() : j1Module() { name.create("scene"); } // Destructor j1Scene::~j1Scene() {} // Called before render is available bool j1Scene::Awake() { LOG("Loading Scene"); bool ret = true; return ret; } // Called before the first frame bool j1Scene::Start() { if(App->map->Load("iso_walk.tmx") == true) { int w, h; uchar* data = NULL; if(App->map->CreateWalkabilityMap(w, h, &data)) App->pathfinding->SetMap(w, h, data); RELEASE_ARRAY(data); } debug_tex = App->tex->Load("maps/path2.png"); return true; } // Called each loop iteration bool j1Scene::PreUpdate() { BROFILER_CATEGORY("PreUpdate Scene", Profiler::Color::Yellow); // debug pathfing ------------------ static iPoint origin; static bool origin_selected = false; int x, y; App->input->GetMousePosition(x, y); iPoint p = App->render->ScreenToWorld(x, y); p = App->map->WorldToMap(p.x, p.y); if(App->input->GetMouseButtonDown(SDL_BUTTON_LEFT) == KEY_DOWN) { if(origin_selected == true) { App->pathfinding->CreatePath(origin, p); origin_selected = false; } else { origin = p; origin_selected = true; } } return true; } // Called each loop iteration bool j1Scene::Update(float dt) { BROFILER_CATEGORY("Update Scene", Profiler::Color::Orange); if(App->input->GetKey(SDL_SCANCODE_L) == KEY_DOWN) App->LoadGame("save_game.xml"); if(App->input->GetKey(SDL_SCANCODE_S) == KEY_DOWN) App->SaveGame("save_game.xml"); if(App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT) App->render->camera.y += floor(200.0f * dt); if(App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT) App->render->camera.y -= floor(200.0f * dt); if(App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT) App->render->camera.x += floor(200.0f * dt); if(App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT) App->render->camera.x -= floor(200.0f * dt); App->map->Draw(); int x, y; App->input->GetMousePosition(x, y); iPoint map_coordinates = App->map->WorldToMap(x - App->render->camera.x, y - App->render->camera.y); p2SString title("Map:%dx%d Tiles:%dx%d Tilesets:%d Tile:%d,%d", App->map->data.width, App->map->data.height, App->map->data.tile_width, App->map->data.tile_height, App->map->data.tilesets.count(), map_coordinates.x, map_coordinates.y); //App->win->SetTitle(title.GetString()); // Debug pathfinding ------------------------------ //int x, y; App->input->GetMousePosition(x, y); iPoint p = App->render->ScreenToWorld(x, y); p = App->map->WorldToMap(p.x, p.y); p = App->map->MapToWorld(p.x, p.y); App->render->Blit(debug_tex, p.x, p.y); const p2DynArray<iPoint>* path = App->pathfinding->GetLastPath(); for(uint i = 0; i < path->Count(); ++i) { iPoint pos = App->map->MapToWorld(path->At(i)->x, path->At(i)->y); App->render->Blit(debug_tex, pos.x, pos.y); } return true; } // Called each loop iteration bool j1Scene::PostUpdate() { BROFILER_CATEGORY("PostUpdate Scene", Profiler::Color::MistyRose); bool ret = true; if(App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN) ret = false; return ret; } // Called before quitting bool j1Scene::CleanUp() { LOG("Freeing scene"); return true; }
[ "josep.pi.serra@gmail.com" ]
josep.pi.serra@gmail.com
5f05584b9468a039ee59c83807d43557e34b3ef6
aab5af1da9e52c9f49d8d063868da0a0a929f085
/inputValidation.hpp
2c576fae9aaa325a3f63b64ed2fc76604494c480
[]
no_license
mcopland/home-invasion
47a1fb470f574aea3a4683e93598d7d2b7ef8907
3dcf1a8b27a367caab4a0483e3faf08d3f3715ce
refs/heads/master
2021-08-19T20:22:06.448986
2020-07-24T22:56:26
2020-07-24T22:56:26
207,384,800
0
0
null
null
null
null
UTF-8
C++
false
false
812
hpp
/******************************************************************************* ** Program: homeInvasion ** File: inputValidation.hpp ** ----------------------------------------------------------------------------- ** This is the inputValidation class specification (header) file. There are ** functions to validate yes or no questions, ints, floats, and strings for use ** throughout the program. *******************************************************************************/ #ifndef INPUTVALIDATION_HPP #define INPUTVALIDATION_HPP #include <ios> // <streamsize> #include <iostream> #include <limits> // numeric_limits #include <string> bool getYesNo(std::string); float getValidFloat(std::string prompt); int getValidInt(int min, int max); long getValidLong(long min, long max); #endif
[ "mcopland@users.noreply.github.com" ]
mcopland@users.noreply.github.com
1b9c983f3a69410d0321641d8935ff4d1dc11745
9f35bea3c50668a4205c04373da95195e20e5427
/ash/assistant/assistant_web_ui_controller.cc
fe627906dc6b3ccfbc67192a73cdb36f74bc4a0b
[ "BSD-3-Clause" ]
permissive
foolcodemonkey/chromium
5958fb37df91f92235fa8cf2a6e4a834c88f44aa
c155654fdaeda578cebc218d47f036debd4d634f
refs/heads/master
2023-02-21T00:56:13.446660
2020-01-07T05:12:51
2020-01-07T05:12:51
232,250,603
1
0
BSD-3-Clause
2020-01-07T05:38:18
2020-01-07T05:38:18
null
UTF-8
C++
false
false
4,976
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/assistant/assistant_web_ui_controller.h" #include "ash/assistant/assistant_controller.h" #include "ash/assistant/ui/assistant_web_container_view.h" #include "ash/assistant/util/deep_link_util.h" #include "ash/multi_user/multi_user_window_manager_impl.h" #include "ash/session/session_controller_impl.h" #include "ash/shell.h" #include "chromeos/services/assistant/public/features.h" #include "ui/aura/client/aura_constants.h" #include "ui/events/event_observer.h" #include "ui/views/event_monitor.h" namespace ash { // ----------------------------------------------------------------------------- // AssistantWebContainerEventObserver: class AssistantWebContainerEventObserver : public ui::EventObserver { public: AssistantWebContainerEventObserver(AssistantWebUiController* owner, views::Widget* widget) : owner_(owner), widget_(widget), event_monitor_( views::EventMonitor::CreateWindowMonitor(this, widget->GetNativeWindow(), {ui::ET_KEY_PRESSED})) {} ~AssistantWebContainerEventObserver() override = default; // ui::EventObserver: void OnEvent(const ui::Event& event) override { DCHECK(event.type() == ui::ET_KEY_PRESSED); const ui::KeyEvent& key_event = static_cast<const ui::KeyEvent&>(event); switch (key_event.key_code()) { case ui::VKEY_BROWSER_BACK: owner_->OnBackButtonPressed(); break; case ui::VKEY_W: if (!key_event.IsControlDown()) break; event_monitor_.reset(); widget_->Close(); break; default: // No action necessary. break; } } private: AssistantWebUiController* owner_ = nullptr; views::Widget* widget_ = nullptr; std::unique_ptr<views::EventMonitor> event_monitor_; DISALLOW_COPY_AND_ASSIGN(AssistantWebContainerEventObserver); }; // ----------------------------------------------------------------------------- // AssistantWebUiController: AssistantWebUiController::AssistantWebUiController( AssistantController* assistant_controller) : assistant_controller_(assistant_controller) { DCHECK(chromeos::assistant::features::IsAssistantWebContainerEnabled()); assistant_controller_->AddObserver(this); } AssistantWebUiController::~AssistantWebUiController() { assistant_controller_->RemoveObserver(this); } void AssistantWebUiController::OnWidgetDestroying(views::Widget* widget) { ResetWebContainerView(); } void AssistantWebUiController::OnAssistantControllerDestroying() { if (!web_container_view_) return; // The view should not outlive the controller. web_container_view_->GetWidget()->CloseNow(); DCHECK_EQ(nullptr, web_container_view_); } void AssistantWebUiController::OnDeepLinkReceived( assistant::util::DeepLinkType type, const std::map<std::string, std::string>& params) { if (!assistant::util::IsWebDeepLinkType(type, params)) return; ShowUi(); // Open the url associated w/ the deep link. web_container_view_->OpenUrl( assistant::util::GetWebUrl(type, params).value()); } void AssistantWebUiController::ShowUi() { if (!web_container_view_) CreateWebContainerView(); web_container_view_->GetWidget()->Show(); } void AssistantWebUiController::OnBackButtonPressed() { DCHECK(web_container_view_); web_container_view_->OnBackButtonPressed(); } AssistantWebContainerView* AssistantWebUiController::GetViewForTest() { return web_container_view_; } void AssistantWebUiController::CreateWebContainerView() { DCHECK(!web_container_view_); web_container_view_ = new AssistantWebContainerView( assistant_controller_->view_delegate(), &view_delegate_); auto* widget = web_container_view_->GetWidget(); widget->AddObserver(this); event_observer_ = std::make_unique<AssistantWebContainerEventObserver>(this, widget); // Associate the window for Assistant Web UI with the active user in order to // not leak across user sessions. auto* window_manager = MultiUserWindowManagerImpl::Get(); if (!window_manager) return; const UserSession* active_user_session = Shell::Get()->session_controller()->GetUserSession(0); if (!active_user_session) return; auto* native_window = widget->GetNativeWindow(); native_window->SetProperty(aura::client::kCreatedByUserGesture, true); window_manager->SetWindowOwner(native_window, active_user_session->user_info.account_id); } void AssistantWebUiController::ResetWebContainerView() { DCHECK(web_container_view_); event_observer_.reset(); web_container_view_->GetWidget()->RemoveObserver(this); web_container_view_ = nullptr; } } // namespace ash
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
c7bf8ef392302de54ca6cd1ea6bedeb80926ab4f
0e4f37b4dd9754203ea3cfe61d24c4db900ff1b1
/ch14 Augmenting Data Structures/IntervalTree_test.cpp
9728fc8e42671df24ef0a2ea77172bb11fceb1dc
[]
no_license
HongfeiXu/LearnCLRS
1c8eacb6ed7396c061e00444629224c8f5c07116
403a6da7ea89ac61642557b013df48de7ab04909
refs/heads/master
2021-01-10T23:01:48.120537
2018-04-11T14:21:58
2018-04-11T14:21:58
70,452,998
2
0
null
null
null
null
WINDOWS-1252
C++
false
false
4,168
cpp
/*************************************************************************** * @file IntervalTree_test.cpp * @author Alex.Xu * @mail icevmj@gmail.com * @date 7.6 2017 * @remark Test the functionality of IntervalTree template * @platform visual studio 2013, windows 10 ***************************************************************************/ #include <iostream> #include <string> #include <vector> #include <ctime> #include "myUtility.h" // RandomizeInPlace() #include "IntervalTree.h" using ch14_2::IntervalTree; // overload operator<<, so we can use OutputVec to print the infomation of *pNode std::ostream& ch14_2::operator<< (std::ostream &os, const IntervalTree<int, std::string>::IntervalNode * pNode) { os << "key: "<<pNode->key << " interval: (" << pNode->interval.first << "," << pNode->interval.second << ")" << " value: " << pNode->value << " max:" << pNode->max; return os; } void ch14_2::IntervalTree_test() { std::srand(unsigned(time(0))); IntervalTree<int, std::string> intervalTree; std::vector<IntervalTree<int, std::string>::IntervalNode *> ptr_vec(8); ptr_vec[0] = new IntervalTree<int, std::string>::IntervalNode(std::make_pair(0,3), "Cat"); ptr_vec[1] = new IntervalTree<int, std::string>::IntervalNode(std::make_pair(5,8), "Razor"); ptr_vec[2] = new IntervalTree<int, std::string>::IntervalNode(std::make_pair(6,10), "Grass"); ptr_vec[3] = new IntervalTree<int, std::string>::IntervalNode(std::make_pair(8,9), "Sun"); ptr_vec[4] = new IntervalTree<int, std::string>::IntervalNode(std::make_pair(15,23), "Apple"); ptr_vec[5] = new IntervalTree<int, std::string>::IntervalNode(std::make_pair(16,21), "Dog"); ptr_vec[6] = new IntervalTree<int, std::string>::IntervalNode(std::make_pair(17,19), "Knife"); ptr_vec[7] = new IntervalTree<int, std::string>::IntervalNode(std::make_pair(25,30), "Shark"); std::cout << "Initial nodes:" << std::endl; OutputVec(ptr_vec, std::cout, '\n'); //RandomizeInPlace(ptr_vec); //std::cout << "After Randomized:" << std::endl; //OutputVec(ptr_vec, std::cout, ' '); for (auto &item : ptr_vec) intervalTree.insert(item); std::cout << "inorderTreeWalk:" << std::endl; intervalTree.inorderTreeWalk(std::cout); std::cout << "Tree: "; intervalTree.printTree(std::cout); std::cout << std::endl; std::cout << "deleteNodeHasKey 8" << std::endl; // if there are many nodes have key 8, only delete the node inseted firstly. intervalTree.deleteNodeHasKey(8); std::cout << "inorderTreeWalk:" << std::endl; intervalTree.inorderTreeWalk(std::cout); std::cout << "Tree: "; intervalTree.printTree(std::cout); std::cout << std::endl; // test intervalSearch std::pair<int, int> interval_a(8, 9); IntervalTree<int, std::string>::IntervalNode * pInterval_a = intervalTree.intervalSearch(interval_a); std::cout << pInterval_a << std::endl; return; } /* Initial nodes: key: 0 interval: (0,3) value: Cat max:0 key: 5 interval: (5,8) value: Razor max:0 key: 6 interval: (6,10) value: Grass max:0 key: 8 interval: (8,9) value: Sun max:0 key: 15 interval: (15,23) value: Apple max:0 key: 16 interval: (16,21) value: Dog max:0 key: 17 interval: (17,19) value: Knife max:0 key: 25 interval: (25,30) value: Shark max:0 inorderTreeWalk: key: 0 interval: (0,3) value:Cat max:3 BLACK key: 5 interval: (5,8) value:Razor max:10 RED key: 6 interval: (6,10) value:Grass max:10 BLACK key: 8 interval: (8,9) value:Sun max:30 BLACK key: 15 interval: (15,23) value:Apple max:23 BLACK key: 16 interval: (16,21) value:Dog max:30 RED key: 17 interval: (17,19) value:Knife max:30 BLACK key: 25 interval: (25,30) value:Shark max:30 RED Tree: 8(5(0,6),16(15,17(,25))) deleteNodeHasKey 8 inorderTreeWalk: key: 0 interval: (0,3) value:Cat max:3 BLACK key: 5 interval: (5,8) value:Razor max:10 RED key: 6 interval: (6,10) value:Grass max:10 BLACK key: 15 interval: (15,23) value:Apple max:30 BLACK key: 16 interval: (16,21) value:Dog max:21 BLACK key: 17 interval: (17,19) value:Knife max:30 RED key: 25 interval: (25,30) value:Shark max:30 BLACK Tree: 15(5(0,6),17(16,25)) key: 5 interval: (5,8) value: Razor max:10 Çë°´ÈÎÒâ¼ü¼ÌÐø. . . */
[ "icevmj@gmail.com" ]
icevmj@gmail.com
add8c74707964611e16d7c21d04f9d8f8a933f36
bdb9af8381619e483ef1a9e5cbe1c1fc408a0bf9
/tools/grpc/cpp/gobgp_api_client.cc
938b9f0e5a8255ca267f4794853d88313f1afd11
[ "Apache-2.0" ]
permissive
gitter-badger/gobgp
06bc9396cd9f684aedf96e04a67bca2bb93349e8
e41e86f9d1d1d23c90219efd7c93aec7f01510c6
refs/heads/master
2021-01-18T10:33:54.814163
2015-09-03T11:40:55
2015-09-04T05:51:49
41,905,487
0
0
null
2015-09-04T08:31:01
2015-09-04T08:31:01
null
UTF-8
C++
false
false
1,663
cc
#include <iostream> #include <memory> #include <sstream> #include <string> #include <grpc/grpc.h> #include <grpc++/channel.h> #include <grpc++/client_context.h> #include <grpc++/create_channel.h> #include <grpc++/security/credentials.h> #include "gobgp_api_client.grpc.pb.h" using grpc::Channel; using grpc::ClientContext; using grpc::Status; using api::Grpc; class GrpcClient { public: GrpcClient(std::shared_ptr<Channel> channel) : stub_(Grpc::NewStub(channel)) {} std::string GetAllNeighbor(std::string neighbor_ip) { api::Arguments request; request.set_rf(4); request.set_name(neighbor_ip); ClientContext context; api::Peer peer; grpc::Status status = stub_->GetNeighbor(&context, request, &peer); if (status.ok()) { api::PeerConf peer_conf = peer.conf(); api::PeerInfo peer_info = peer.info(); std::stringstream buffer; buffer << "Peer AS: " << peer_conf.remote_as() << "\n" << "Peer router id: " << peer_conf.id() << "\n" << "Peer flops: " << peer_info.flops() << "\n" << "BGP state: " << peer_info.bgp_state(); return buffer.str(); } else { return "Something wrong"; } } private: std::unique_ptr<Grpc::Stub> stub_; }; int main(int argc, char** argv) { GrpcClient gobgp_client(grpc::CreateChannel("localhost:8080", grpc::InsecureCredentials())); std::string reply = gobgp_client.GetAllNeighbor("213.133.111.200"); std::cout << "We received: " << reply << std::endl; return 0; }
[ "fujita.tomonori@lab.ntt.co.jp" ]
fujita.tomonori@lab.ntt.co.jp
d51bcc14984b55b544b69af2d5810dca24ea36b3
c13fe33b9ccf0e6857388405ef791071aa753c0f
/mythread.cpp
295791a01ac4914d0dc8b0d6985e7d231a317443
[]
no_license
Cirnoo/game-server
8b1c8b1fdff4b92c42812e2de2ff5d825abed675
b4970692fd980240e58543454f127c1713a8e2ae
refs/heads/master
2020-04-01T22:55:29.567920
2018-11-17T16:35:27
2018-11-17T16:35:27
153,732,972
0
0
null
null
null
null
UTF-8
C++
false
false
266
cpp
#include "mythread.h" #include <QTcpSocket> #include <QMetaType> MyThread::MyThread() { qRegisterMetaType<DATA_PACKAGE>("DATA_PACKAGE"); } void MyThread::Reply(QTcpSocket * socket, const DATA_PACKAGE &pack) { socket->write((char *)&pack,sizeof (pack)); }
[ "42065449+Cirno0@users.noreply.github.com" ]
42065449+Cirno0@users.noreply.github.com
92a0f299fe1f364e129d42f4650b39e87b29f4c7
8f7c8beaa2fca1907fb4796538ea77b4ecddc300
/chrome/installer/zucchini/disassembler_win32.h
0241257c082d0c9e63373019cbaa047822399929
[ "BSD-3-Clause" ]
permissive
lgsvl/chromium-src
8f88f6ae2066d5f81fa363f1d80433ec826e3474
5a6b4051e48b069d3eacbfad56eda3ea55526aee
refs/heads/ozone-wayland-62.0.3202.94
2023-03-14T10:58:30.213573
2017-10-26T19:27:03
2017-11-17T09:42:56
108,161,483
8
4
null
2017-12-19T22:53:32
2017-10-24T17:34:08
null
UTF-8
C++
false
false
3,832
h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_INSTALLER_ZUCCHINI_DISASSEMBLER_WIN32_H_ #define CHROME_INSTALLER_ZUCCHINI_DISASSEMBLER_WIN32_H_ #include <stddef.h> #include <stdint.h> #include <memory> #include <string> #include <utility> #include <vector> #include "base/macros.h" #include "chrome/installer/zucchini/address_translator.h" #include "chrome/installer/zucchini/buffer_view.h" #include "chrome/installer/zucchini/disassembler.h" #include "chrome/installer/zucchini/image_utils.h" #include "chrome/installer/zucchini/type_win_pe.h" namespace zucchini { class Rel32FinderX86; class Rel32FinderX64; struct Win32X86Traits { static constexpr ExecutableType kExeType = kExeTypeWin32X86; enum : uint16_t { kMagic = 0x10B }; enum : uint16_t { kRelocType = 3 }; enum : offset_t { kVAWidth = 4 }; static const char kExeTypeString[]; using ImageOptionalHeader = pe::ImageOptionalHeader; using RelFinder = Rel32FinderX86; using Address = uint32_t; }; struct Win32X64Traits { static constexpr ExecutableType kExeType = kExeTypeWin32X64; enum : uint16_t { kMagic = 0x20B }; enum : uint16_t { kRelocType = 10 }; enum : offset_t { kVAWidth = 8 }; static const char kExeTypeString[]; using ImageOptionalHeader = pe::ImageOptionalHeader64; using RelFinder = Rel32FinderX64; using Address = uint64_t; }; template <class Traits> class DisassemblerWin32 : public Disassembler { public: enum ReferenceType : uint8_t { kRel32, kTypeCount }; // Applies quick checks to determine whether |image| *may* point to the start // of an executable. Returns true iff the check passes. static bool QuickDetect(ConstBufferView image); // Main instantiator and initializer. static std::unique_ptr<DisassemblerWin32> Make(ConstBufferView image); DisassemblerWin32(); ~DisassemblerWin32() override; // Disassembler: ExecutableType GetExeType() const override; std::string GetExeTypeString() const override; std::vector<ReferenceGroup> MakeReferenceGroups() const override; // Functions that return reader / writer for references. std::unique_ptr<ReferenceReader> MakeReadRel32(offset_t lower, offset_t upper); std::unique_ptr<ReferenceWriter> MakeWriteRel32(MutableBufferView image); private: // Disassembler: bool Parse(ConstBufferView image) override; // Parses the file header. Returns true iff successful. bool ParseHeader(); // Parsers to extract references. These are lazily called, and return whether // parsing was successful (failures are non-fatal). bool ParseAndStoreRel32(); // PE-specific translation utilities. rva_t AddressToRva(typename Traits::Address address) const; typename Traits::Address RvaToAddress(rva_t rva) const; // In-memory copy of sections. std::vector<pe::ImageSectionHeader> sections_; // Image base address to translate between RVA and VA. typename Traits::Address image_base_ = 0; // Translator between offsets and RVAs. AddressTranslator translator_; // Reference storage. std::vector<offset_t> rel32_locations_; // Initialization states of reference storage, used for lazy initialization. // TODO(huangs): Investigate whether lazy initialization is useful for memory // reduction. This is a carryover from Courgette. To be sure we should run // experiment after Zucchini is able to do ensemble patching. bool has_parsed_rel32_ = false; DISALLOW_COPY_AND_ASSIGN(DisassemblerWin32); }; using DisassemblerWin32X86 = DisassemblerWin32<Win32X86Traits>; using DisassemblerWin32X64 = DisassemblerWin32<Win32X64Traits>; } // namespace zucchini #endif // CHROME_INSTALLER_ZUCCHINI_DISASSEMBLER_WIN32_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
817a1e920ec10374737864a4c0d8602b44fbd624
180492f944459ac416476603f601407e9c4c6988
/NeoGUI/Connector.h
22cd1e1666b232c92f43f28a216f95e01cce6149
[]
no_license
bratao/NeoLoader
3a05068f104fa82c853a3ccf8bcc079c5a61a527
7885abdb71dc98ef1b45273faaad699eda82c57b
refs/heads/master
2021-01-15T08:48:06.483422
2015-04-02T18:04:54
2015-04-02T18:04:54
35,004,681
0
1
null
2015-05-03T23:33:38
2015-05-03T23:33:38
null
UTF-8
C++
false
false
1,321
h
#pragma once #if QT_VERSION < 0x050000 #include <QtGui> #else #include <QWidget> #include <QHBoxLayout> #include <QTreeWidget> #include <QFormLayout> #include <QLineEdit> #include <QCheckBox> #include <QPushButton> #include <QSplitter> #include <QHeaderView> #include <QApplication> #include <QMessageBox> #include <QInputDialog> #include <QCloseEvent> #include <QComboBox> #include <QStackedLayout> #include <QDialogButtonBox> #endif #include "Common/Dialog.h" class CConnector : public QDialogEx { Q_OBJECT public: CConnector(QWidget *pMainWindow = 0); ~CConnector(); private slots: void OnModeChanged(int Index); void OnConnect(); void OnClicked(QAbstractButton* pButton); protected: void timerEvent(QTimerEvent *e); void closeEvent(QCloseEvent *e); void Load(); void Apply(); int m_uTimerID; int m_Mode; private: QFormLayout* m_pMainLayout; QLabel* m_pLabel; QComboBox* m_pMode; QLineEdit* m_pPassword; QLineEdit* m_pPipeName; QLineEdit* m_pHostPort; QLineEdit* m_pHostName; QComboBox* m_pAutoConnect; /*QPushButton* m_pServiceBtn; QLineEdit* m_pServiceName;*/ //QPushButton* m_pStartBtn; QPushButton* m_pConnectBtn; QDialogButtonBox* m_pButtonBox; };
[ "xanatosdavid@gmail.com" ]
xanatosdavid@gmail.com
ba075a5618803e90bb72c0c15f910c2bf2e61c85
ccfbf5a9ee9c00282c200945bbe36b387eb38b19
/UVA Solutions/uva 674.cpp
10a42902b8480662d2d5e0567e6f904a72b67b95
[]
no_license
sakiib/OnlineJudge-Solutions
e070d4b255d036cdefaf087e9f75b69db708406c
b024352aa99efe548b48ef74c492cb69c1fa89f9
refs/heads/master
2023-01-07T20:57:04.259395
2020-11-16T08:41:27
2020-11-16T08:41:27
288,191,980
0
0
null
null
null
null
UTF-8
C++
false
false
644
cpp
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; int Coin[] = {1, 5, 10, 20, 25}; int dp[7][7493]; int makeCoin(int I, int H){ if(I >= 5){ if(!H)return 1; else return 0; } if(dp[I][H] != -1)return dp[I][H]; int Way1 = 0, Way2 = 0; if(H-Coin[I] >= 0)Way1 = makeCoin(I, H-Coin[I]); Way2 = makeCoin(I+1, H); cout << Way1 << " " << Way2 << " I = " << I << " H = " << H << endl; return dp[I][H] = Way1+Way2; } int main(){ int N; memset(dp, -1, sizeof(dp)); while(cin >> N){ cout << makeCoin(0, N) << endl; } return 0; }
[ "sakibalamin162@gmail.com" ]
sakibalamin162@gmail.com
35a37ab15b20f5c99aa417b860e2e1a79f98b9c3
ec68c973b7cd3821dd70ed6787497a0f808e18e1
/Cpp/SDK/BP_RandomMapActor_classes.h
0ae829b86b9867a57c06c1a26ae73215a86770a4
[]
no_license
Hengle/zRemnant-SDK
05be5801567a8cf67e8b03c50010f590d4e2599d
be2d99fb54f44a09ca52abc5f898e665964a24cb
refs/heads/main
2023-07-16T04:44:43.113226
2021-08-27T14:26:40
2021-08-27T14:26:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
783
h
#pragma once // Name: Remnant, Version: 1.0 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_RandomMapActor.BP_RandomMapActor_C // 0x0000 class ABP_RandomMapActor_C : public AActor { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_RandomMapActor.BP_RandomMapActor_C"); return ptr; } void Init(); void ReceiveBeginPlay(); void SetRandomSeed(); void ExecuteUbergraph_BP_RandomMapActor(); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
84ae28000560b6103020accf566949083b972462
9aaa39f200ee6a14d7d432ef6a3ee9795163ebed
/Algorithm/C++/009. Palindrome Number.cpp
1061308f3faa138c3eb9b5a655dc81263f8c010c
[]
no_license
WuLC/LeetCode
47e1c351852d86c64595a083e7818ecde4131cb3
ee79d3437cf47b26a4bca0ec798dc54d7b623453
refs/heads/master
2023-07-07T18:29:29.110931
2023-07-02T04:31:00
2023-07-02T04:31:00
54,354,616
29
16
null
null
null
null
UTF-8
C++
false
false
928
cpp
/* * Created on Thu Apr 19 2018 14:41:13 * Author: WuLC * EMail: liangchaowu5@gmail.com */ // method 1, convert number to string class Solution { public: bool isPalindrome(int x) { string s = std::to_string(x); int left = 0, right = s.length()-1; while(left < right) { if (s[left] != s[right]) return false; left++; right--; } return true; } }; // method 2,no need to convert number to string // follow the method of reversing a number class Solution { public: bool isPalindrome(int x) { if (x<0 || (x>0 && x%10==0)) return false; int sum = 0; while(x>sum) { sum = sum*10+x%10; x/=10; } return x==sum || x==sum/10; } };
[ "liangchaowu5@gmail.com" ]
liangchaowu5@gmail.com
bc8a31f28ed687ebbb33bd15d10d3f3373154da8
f40a9ea8fcc5cf34e132181aed9076978161dc45
/mba/cpp/include/readers/common.h
7eaa467bc5160e02751dcd431d6960fa25ca85ca
[]
no_license
azeroman/Livingstone-2
7cb7373e58457ab09f979a966eed2ae043285dee
c422a8264900860ff6255c676e254004766486ec
refs/heads/master
2022-04-12T20:35:36.050943
2020-04-08T14:58:50
2020-04-08T14:58:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,727
h
/*** *** See the file "mba/disclaimers-and-notices-L2.txt" for *** information on usage and redistribution of this file, *** and for a DISCLAIMER OF ALL WARRANTIES. ***/ /* $Id: common.h,v 1.17 2004/02/18 23:50:16 lbrown Exp $ */ #ifndef COMMON_H #define COMMON_H #define L2_READER_MAGIC "L211" #include <livingstone/L2_assert.h> /** * Return array[i], checking that i < size. * The template ensures we can't use this as an l-value. * Gcc-3.0 requires both templates in order to work with either * passing in T const * const * or T**. */ template <class T> const T *bounds_check_access(unsigned i, unsigned size, const T *const * array, const char *name) { L2_assert(i<size, L2_bounds_error, (MBA_string(name)+" array", i, size)); return array[i]; } template <class T> const T *bounds_check_access(unsigned i, unsigned size, T *const * array, const char *name) { L2_assert(i<size, L2_bounds_error, (MBA_string(name)+" array", i, size)); return array[i]; } /** * Similarly, except array is only T**, and return is T* * We don't need to worry about the consts. */ template <class T> T *bounds_check_access_friend(unsigned i, unsigned size, T ** array, const char *name) { L2_assert(i<size, L2_bounds_error, (MBA_string(name)+" array", i, size)); return array[i]; } /*************************************************************************** Several of the methods only need to be virtual if we have the debug versions of the objects. ***************************************************************************/ #ifdef ENABLE_L2_DEBUG_SECTIONS # define l2_virtual virtual #else # define l2_virtual #endif #endif
[ "kbshah1998@outlook.com" ]
kbshah1998@outlook.com
3ba0853664f970541666c81e085fecaf601f430b
92e67b30497ffd29d3400e88aa553bbd12518fe9
/assignment2/part6/Re=110/12.5/p
d4fc3a93bef16e746100e42729eab6138aa9df9f
[]
no_license
henryrossiter/OpenFOAM
8b89de8feb4d4c7f9ad4894b2ef550508792ce5c
c54b80dbf0548b34760b4fdc0dc4fb2facfdf657
refs/heads/master
2022-11-18T10:05:15.963117
2020-06-28T15:24:54
2020-06-28T15:24:54
241,991,470
0
0
null
null
null
null
UTF-8
C++
false
false
20,094
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "12.5"; object p; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -2 0 0 0 0]; internalField nonuniform List<scalar> 2000 ( 0.0336571 0.0371535 0.0392559 0.0423602 0.0471211 0.0536115 0.0613989 0.0698262 0.0782675 0.0864584 0.0358873 0.0388906 0.0405405 0.0428691 0.0465651 0.0518905 0.0586208 0.0662324 0.0741274 0.081996 0.0380545 0.0405732 0.0418639 0.0436037 0.0464481 0.0507575 0.0564719 0.0632125 0.0704536 0.0778572 0.0401796 0.0422155 0.0432207 0.0445336 0.0467381 0.0502168 0.0550157 0.0608839 0.0673933 0.0741893 0.0422827 0.0438356 0.0446188 0.0456453 0.0474101 0.0502633 0.0542974 0.0593534 0.0651029 0.0711649 0.0443778 0.0454534 0.0460772 0.0469428 0.0484514 0.0508874 0.054341 0.0587036 0.0637223 0.0689475 0.0464626 0.0470806 0.0476143 0.0484365 0.0498554 0.0520729 0.0551457 0.0589813 0.0633577 0.067674 0.0485079 0.0487079 0.049231 0.050124 0.0516045 0.0537867 0.0566782 0.0601864 0.0640715 0.0674729 0.0504478 0.0502984 0.0508954 0.0519696 0.0536494 0.0559603 0.0588568 0.0622529 0.0658713 0.0684593 0.0521848 0.0517796 0.0525322 0.0538881 0.055887 0.05847 0.0615358 0.0650125 0.0686674 0.071024 0.102475 0.119266 0.12978 0.136949 0.141881 0.145656 0.148066 0.14997 0.150817 0.151394 0.0981505 0.115546 0.126175 0.133442 0.138452 0.142323 0.14482 0.146802 0.147715 0.148326 0.093966 0.11191 0.12258 0.129979 0.135071 0.139035 0.141626 0.143683 0.14466 0.145306 0.0900863 0.108394 0.119018 0.126582 0.131754 0.135803 0.13849 0.140615 0.141654 0.142333 0.0867567 0.105062 0.11554 0.123282 0.128511 0.132641 0.135425 0.137605 0.138693 0.139396 0.0841683 0.101872 0.112158 0.120085 0.125342 0.129553 0.132431 0.13466 0.135784 0.136504 0.082529 0.0988789 0.108997 0.117029 0.122269 0.12656 0.129526 0.131783 0.132915 0.133628 0.0816756 0.0958257 0.106013 0.114059 0.119271 0.123641 0.126696 0.128985 0.130122 0.130819 0.0818428 0.0931341 0.103458 0.11125 0.116422 0.120855 0.12398 0.126247 0.127325 0.127957 0.081204 0.0900802 0.100817 0.108415 0.113607 0.118071 0.121305 0.123618 0.124704 0.125294 0.0880799 0.0882393 0.0963484 0.102529 0.107663 0.11206 0.115159 0.116966 0.117576 0.11784 0.0934872 0.0900745 0.0932539 0.0959844 0.0991109 0.102062 0.104675 0.107106 0.108873 0.11018 0.0893516 0.0879193 0.0886617 0.0897362 0.0919035 0.0942553 0.0960687 0.0976025 0.0992483 0.100456 0.0777365 0.0792725 0.0805242 0.0817366 0.0837039 0.0859021 0.0878906 0.0892818 0.0904838 0.0912534 0.0644466 0.067514 0.0701096 0.0729688 0.0757247 0.0776252 0.0788837 0.0799796 0.0809222 0.0816657 0.051789 0.0558134 0.0589013 0.0622624 0.0656382 0.0684135 0.0699977 0.0708977 0.0716024 0.0722231 0.0396444 0.0439021 0.0475513 0.0513756 0.0548612 0.0575058 0.059226 0.0601554 0.0606346 0.0609164 0.0273512 0.0313155 0.0349643 0.0388246 0.0424141 0.0450174 0.0467391 0.0477848 0.0483339 0.048494 0.0154132 0.018652 0.0217215 0.0247125 0.0276147 0.0298842 0.0312459 0.0319474 0.0323583 0.0325851 0.00183696 0.0050897 0.00738762 0.00893608 0.0103858 0.0117441 0.012634 0.0130189 0.0131798 0.0133455 0.0843276 0.0915544 0.0838786 0.0709122 0.0581221 0.0461572 0.0355604 0.0240848 0.0138562 -0.000395019 0.0865209 0.0909065 0.0810793 0.0674802 0.0550259 0.0435477 0.0335159 0.0224968 0.0132226 -0.00104594 0.0901766 0.0885424 0.0772084 0.0637726 0.0519408 0.0410628 0.0316126 0.0211321 0.0126236 -0.0015789 0.090247 0.0848998 0.0728734 0.0600008 0.0488491 0.0386104 0.0297166 0.0198377 0.0120058 -0.00204909 0.0882009 0.0806198 0.0682583 0.0561714 0.0457722 0.0362085 0.0278659 0.0186463 0.0114016 -0.00240599 0.0841519 0.0758339 0.0635566 0.0523467 0.0427271 0.0338553 0.0260607 0.0175355 0.0108281 -0.00262483 0.0787659 0.0706502 0.0589181 0.0485862 0.0397326 0.03156 0.024317 0.0164932 0.0103211 -0.00221157 0.0728036 0.0652584 0.0544297 0.0449512 0.0368222 0.0293432 0.0226546 0.0155074 0.00982747 -0.0011522 0.0668588 0.0599154 0.0501522 0.0414933 0.0340393 0.0272359 0.0211008 0.0145883 0.00927552 -0.000118582 0.061332 0.0548686 0.0461377 0.0382502 0.0314288 0.0252716 0.0196837 0.0137782 0.00874941 0.000691593 0.056451 0.0502951 0.0424272 0.0352451 0.0290252 0.0234767 0.0184222 0.0130742 0.00828965 0.0012666 0.0523093 0.0463121 0.0390745 0.0325092 0.0268598 0.0218789 0.0173281 0.0124706 0.00790292 0.00164257 0.0489329 0.0429914 0.0361533 0.0300844 0.024967 0.0205177 0.0164108 0.011967 0.00758317 0.00186954 0.0463046 0.0403532 0.0337063 0.0279871 0.0233924 0.0194021 0.0156761 0.0115667 0.00732469 0.00199788 0.0443635 0.0383594 0.0317315 0.0262242 0.0221813 0.0185156 0.0151189 0.0112668 0.00712387 0.00206839 0.0429797 0.0369106 0.0302166 0.0250443 0.0210922 0.0178536 0.0147135 0.0110602 0.00697557 0.00210837 0.042021 0.0359653 0.0292543 0.0241301 0.0203318 0.0173974 0.0144082 0.0109233 0.00687163 0.00213254 0.0416464 0.0357439 0.0287416 0.0235521 0.0198504 0.0171311 0.0144396 0.0108417 0.0067908 0.00214792 0.0419665 0.0362089 0.0287906 0.0233027 0.0195838 0.0170278 0.014318 0.0108346 0.00674086 0.00215711 0.0409157 0.0362595 0.0292371 0.0235409 0.0196249 0.0171156 0.0143659 0.0109072 0.00671734 0.00215772 0.0334824 0.0337366 0.0310385 0.0264585 0.0217318 0.0176373 0.0143573 0.0107542 0.00667122 0.00222248 0.0400106 0.0291663 0.0241423 0.0214017 0.0187371 0.0162378 0.0135477 0.0101349 0.00615463 0.00200819 0.0456421 0.0385194 0.0318254 0.0268918 0.0218773 0.0179488 0.0142155 0.0104233 0.00627801 0.0021052 0.0466911 0.0384841 0.0315056 0.0264787 0.0217831 0.0179994 0.0142499 0.0103611 0.00638668 0.00228505 0.0498632 0.0417067 0.0345754 0.0286883 0.023456 0.0192765 0.0148588 0.0107558 0.00674677 0.00263593 0.0514653 0.043245 0.0361149 0.0301938 0.0248517 0.0201232 0.0153182 0.0112013 0.00725154 0.0031231 0.0538637 0.0453388 0.0378019 0.0315653 0.0260287 0.0208241 0.0159045 0.0117291 0.00772473 0.00352554 0.0557301 0.0469051 0.0394652 0.0331208 0.0271073 0.0214962 0.0164813 0.0120519 0.00824154 0.00404371 0.0570426 0.0491176 0.0414282 0.0343568 0.0279692 0.0222616 0.0169618 0.0125309 0.00899702 0.00443462 0.0584549 0.0498685 0.0421047 0.0350093 0.0285291 0.0226686 0.0173088 0.0128851 0.00899911 0.00401291 0.0527937 0.0550946 0.0533767 0.0533573 0.0559014 0.0572778 0.0598625 0.0625936 0.0626517 0.0649764 0.055999 0.0589275 0.0564133 0.0564531 0.0587291 0.0599881 0.0629168 0.0658986 0.0666657 0.0688284 0.059239 0.0599587 0.0580381 0.0592917 0.0616217 0.063068 0.0665103 0.0697703 0.0722921 0.074394 0.0623579 0.061253 0.0594632 0.0617608 0.0642986 0.0661892 0.0700096 0.0735443 0.0773569 0.0797805 0.0652556 0.0632564 0.0614972 0.0642561 0.0669228 0.0693167 0.0733749 0.077097 0.0814609 0.0843096 0.0680299 0.0653714 0.0639904 0.0669888 0.069715 0.072551 0.076774 0.0806103 0.0850501 0.0881748 0.0707661 0.0673681 0.0665657 0.069883 0.0727543 0.0759685 0.0803299 0.084281 0.0886604 0.0918803 0.0735381 0.0693586 0.0690857 0.0728266 0.0760124 0.0795769 0.0840738 0.0881933 0.0925857 0.0958233 0.0764294 0.0714532 0.0715967 0.0758059 0.0794513 0.0833441 0.0879918 0.0923386 0.0968812 0.100161 0.0795185 0.073691 0.0741586 0.0788658 0.083064 0.0872301 0.0920678 0.096672 0.101482 0.104867 0.0828251 0.0760863 0.0767983 0.0820445 0.0868629 0.0911993 0.0963003 0.101157 0.106318 0.109855 0.0863758 0.0786703 0.0795473 0.0853442 0.0908436 0.0952287 0.100687 0.105782 0.111353 0.115054 0.0904584 0.0815157 0.0824797 0.0887202 0.0949679 0.0993228 0.105228 0.11059 0.11659 0.120449 0.0952317 0.0846884 0.0857022 0.0921001 0.0991796 0.103493 0.109913 0.115637 0.122028 0.126043 0.100543 0.088224 0.0892685 0.0954845 0.103414 0.107769 0.114823 0.120923 0.127687 0.131874 0.106274 0.0921574 0.0931652 0.0989422 0.107567 0.112276 0.119876 0.126356 0.133535 0.137941 0.112267 0.096493 0.097297 0.102595 0.111531 0.117124 0.125038 0.131936 0.139608 0.144288 0.118335 0.101181 0.101502 0.106466 0.115454 0.121931 0.130138 0.137548 0.145822 0.150878 0.124735 0.106451 0.105568 0.110648 0.119421 0.126715 0.135253 0.143316 0.152252 0.157763 0.130868 0.112148 0.109453 0.114447 0.122937 0.130936 0.139902 0.148785 0.158609 0.16485 0.140925 0.130528 0.123957 0.126918 0.133784 0.142825 0.152815 0.163665 0.175197 0.182872 0.155336 0.1502 0.146998 0.149657 0.156516 0.166633 0.178702 0.192526 0.206815 0.216659 0.174466 0.173684 0.173162 0.176989 0.184731 0.195927 0.210018 0.226866 0.24384 0.255173 0.192446 0.195918 0.200061 0.206559 0.216688 0.230253 0.247012 0.267024 0.286456 0.298364 0.208487 0.215156 0.223167 0.233731 0.2476 0.264836 0.284922 0.30787 0.329343 0.342234 0.22182 0.230828 0.242025 0.256186 0.273764 0.294843 0.318184 0.34313 0.365772 0.37863 0.231545 0.242482 0.255999 0.272707 0.292833 0.316559 0.342121 0.367744 0.390353 0.403359 0.239312 0.251304 0.266374 0.284939 0.306775 0.33198 0.358788 0.384441 0.40562 0.415317 0.241933 0.255038 0.271383 0.291353 0.314277 0.340543 0.368336 0.393607 0.412704 0.423049 0.246286 0.259849 0.27674 0.297201 0.321215 0.348334 0.376807 0.404597 0.425994 0.41907 0.148046 0.158852 0.174511 0.190106 0.204723 0.21704 0.226059 0.233373 0.235587 0.239507 0.151787 0.163008 0.177435 0.191468 0.204909 0.216247 0.224543 0.231321 0.233242 0.237043 0.155311 0.167851 0.181731 0.194544 0.206574 0.216545 0.223792 0.229675 0.231315 0.23481 0.157488 0.17053 0.184092 0.196311 0.207438 0.216445 0.222908 0.228056 0.229558 0.232564 0.159162 0.172074 0.185168 0.196943 0.207471 0.215844 0.221791 0.226417 0.227859 0.230357 0.160701 0.173481 0.186034 0.19729 0.207248 0.21509 0.220626 0.224835 0.226229 0.228294 0.161974 0.174799 0.186925 0.19767 0.207052 0.214384 0.219535 0.223365 0.224704 0.226422 0.162904 0.175854 0.187695 0.198019 0.20688 0.213743 0.218535 0.222016 0.223304 0.224737 0.163549 0.176634 0.188273 0.19826 0.206677 0.213135 0.21761 0.220779 0.222029 0.22321 0.163999 0.177213 0.188697 0.198399 0.206437 0.212552 0.216752 0.219646 0.220881 0.22181 0.164327 0.177648 0.189017 0.198469 0.206182 0.212002 0.215966 0.21862 0.219829 0.220545 0.164527 0.177927 0.189246 0.198486 0.205923 0.211495 0.215255 0.217703 0.218865 0.219405 0.164542 0.178012 0.189371 0.198446 0.205667 0.211033 0.214619 0.216886 0.217996 0.218381 0.164352 0.177911 0.189401 0.198355 0.205417 0.210615 0.214055 0.21616 0.217224 0.217468 0.163971 0.177667 0.189348 0.198221 0.205179 0.210244 0.21356 0.21552 0.216538 0.216667 0.163366 0.177314 0.189207 0.198054 0.204954 0.209916 0.213135 0.214961 0.215918 0.215977 0.162517 0.17691 0.188969 0.197864 0.20474 0.209632 0.212776 0.214478 0.215353 0.215419 0.161189 0.176419 0.18859 0.197648 0.204528 0.209388 0.212477 0.214062 0.214799 0.214992 0.159531 0.175968 0.188148 0.197418 0.204327 0.209185 0.212236 0.213722 0.214299 0.214747 0.156783 0.174914 0.18738 0.197009 0.204052 0.208971 0.212022 0.213412 0.213686 0.214643 0.152032 0.17298 0.186058 0.19638 0.203707 0.208741 0.211862 0.213364 0.213374 0.214846 0.163079 0.179191 0.189938 0.199192 0.205442 0.209755 0.212285 0.213574 0.21363 0.214689 0.172008 0.185262 0.194699 0.202531 0.207618 0.211058 0.212835 0.213762 0.213838 0.214403 0.177798 0.189382 0.198214 0.204838 0.20912 0.211811 0.213043 0.213832 0.214356 0.215084 0.181838 0.192326 0.200511 0.206046 0.209575 0.211582 0.212554 0.213666 0.215314 0.217939 0.184818 0.194453 0.201809 0.206193 0.20875 0.210191 0.211328 0.213678 0.218462 0.226327 0.186652 0.195778 0.202035 0.204762 0.205682 0.206539 0.208487 0.213878 0.225564 0.245641 0.188407 0.196945 0.202088 0.203194 0.202922 0.20362 0.206902 0.218649 0.244923 0.291643 0.188642 0.196267 0.198773 0.196879 0.195219 0.196675 0.206679 0.230845 0.283963 0.378324 0.191894 0.201963 0.206783 0.206146 0.206538 0.215619 0.236485 0.280382 0.370486 0.521657 0.140175 0.151835 0.160889 0.167931 0.17289 0.177025 0.179153 0.18137 0.181781 0.184088 0.136668 0.148702 0.157709 0.164798 0.169772 0.174062 0.176149 0.17844 0.178835 0.180753 0.134709 0.14713 0.156169 0.162892 0.167518 0.171505 0.173392 0.175553 0.175891 0.177416 0.131781 0.144659 0.153777 0.160619 0.165035 0.16877 0.170541 0.172559 0.17287 0.174062 0.128154 0.141398 0.150635 0.157597 0.162121 0.165741 0.167498 0.169436 0.169762 0.170711 0.124261 0.137905 0.147286 0.154236 0.158928 0.162534 0.164327 0.166229 0.166604 0.167389 0.120159 0.134333 0.143909 0.150843 0.155568 0.159264 0.161098 0.162984 0.163428 0.164106 0.115846 0.130652 0.140472 0.147439 0.152173 0.155849 0.157903 0.159721 0.160254 0.160865 0.111392 0.126872 0.136953 0.143982 0.148762 0.152424 0.154635 0.156466 0.157088 0.157666 0.1069 0.123052 0.133377 0.140474 0.145328 0.149026 0.151344 0.153196 0.153948 0.154509 0.0535983 0.0530518 0.0540261 0.0557394 0.0581488 0.0611195 0.0644988 0.0682317 0.0724173 0.0767082 0.0545626 0.0540029 0.0552367 0.0573419 0.0602036 0.0636118 0.0673456 0.0712488 0.0752227 0.0790386 0.0549652 0.0545358 0.0560351 0.0585126 0.0618068 0.06563 0.0696933 0.0737387 0.0774127 0.0803967 0.0547451 0.0545976 0.0563428 0.0591282 0.062778 0.0669117 0.0711954 0.0752921 0.0787258 0.0808042 0.0539047 0.0541955 0.0561612 0.0591559 0.0630631 0.0673211 0.0716267 0.075576 0.0787357 0.0801852 0.0525024 0.0533893 0.055567 0.0587336 0.0626583 0.0668815 0.0709883 0.0745692 0.0773254 0.0784462 0.050628 0.0522649 0.0546535 0.0579117 0.0617542 0.0657417 0.0694446 0.0724917 0.0746859 0.075605 0.0483754 0.0509018 0.0535063 0.0567959 0.0604551 0.0640552 0.0672065 0.069624 0.0711804 0.0718327 0.0458386 0.0493367 0.0521632 0.0554381 0.0588357 0.0619557 0.0644874 0.0662475 0.0671964 0.067464 0.0430698 0.0475835 0.0506222 0.0538543 0.056959 0.0595807 0.0615092 0.062658 0.0630845 0.0629152 0.0401066 0.0456208 0.0488628 0.0520656 0.054913 0.0570957 0.0585059 0.0591448 0.0591441 0.0585699 0.0370298 0.0435013 0.0469544 0.0501819 0.0528564 0.0547045 0.0557092 0.0559508 0.055603 0.0546944 0.0339356 0.0412611 0.0449811 0.0483406 0.050963 0.0525981 0.0533081 0.0532459 0.0526068 0.0514316 0.0309649 0.0389943 0.043107 0.0467373 0.0494276 0.0509535 0.0514519 0.0511431 0.0502379 0.0488418 0.0282979 0.0368583 0.0415479 0.0455824 0.048427 0.049908 0.0502413 0.04971 0.0485417 0.046943 0.0261336 0.0350677 0.0405321 0.045067 0.0481019 0.0495554 0.049731 0.0489741 0.0475339 0.0457189 0.0246707 0.0338764 0.0402702 0.0453447 0.048558 0.0499596 0.0499439 0.0489169 0.047153 0.0450466 0.0240981 0.0335438 0.0409333 0.046525 0.0498752 0.0511887 0.0509329 0.0495364 0.0472648 0.044623 0.0245893 0.0342928 0.0426401 0.048666 0.0521011 0.053324 0.0528484 0.0510375 0.048036 0.0444016 0.0262965 0.036283 0.0454471 0.0517629 0.055215 0.0563797 0.05583 0.0538417 0.0503756 0.0461895 0.029366 0.0396092 0.0493532 0.0557528 0.0591056 0.0601902 0.0596778 0.057939 0.0552141 0.0528206 0.0339901 0.044314 0.054316 0.0605391 0.0636184 0.0644892 0.0638739 0.0622191 0.0600402 0.0583526 0.0401675 0.0503296 0.0602543 0.0660067 0.0686213 0.0691307 0.0682743 0.0665291 0.0644104 0.0626345 0.0478621 0.057572 0.0670529 0.0720446 0.0739939 0.073982 0.0727414 0.0707412 0.0684276 0.0663697 0.056988 0.0659775 0.0745227 0.0785306 0.0796415 0.0789689 0.0772206 0.0748349 0.0721978 0.0698155 0.0674361 0.0752866 0.0825454 0.0853581 0.0854925 0.0840518 0.0817063 0.078857 0.0758421 0.0731258 0.0790119 0.0852371 0.0909834 0.092437 0.0914963 0.089217 0.086219 0.0828638 0.079447 0.0763956 0.0913589 0.09568 0.0996933 0.0996831 0.0976153 0.0944665 0.0907972 0.086927 0.0831076 0.0797223 0.104151 0.10639 0.108526 0.107012 0.103814 0.0998059 0.0954821 0.0911199 0.0869237 0.0832129 0.116985 0.117097 0.117323 0.114332 0.11005 0.105233 0.100306 0.0955058 0.0909851 0.0869676 0.129392 0.127516 0.125919 0.121544 0.116271 0.110732 0.105284 0.100124 0.0953492 0.0910476 0.141291 0.13745 0.134147 0.128529 0.122397 0.116258 0.110399 0.104979 0.100028 0.0954678 0.152317 0.146653 0.141846 0.135175 0.128351 0.121758 0.115622 0.110061 0.105029 0.100277 0.162133 0.154891 0.148844 0.141351 0.134027 0.127148 0.120879 0.115315 0.110341 0.105522 0.170444 0.161947 0.154976 0.14692 0.139307 0.132319 0.126074 0.120649 0.115876 0.111147 0.176996 0.167628 0.160087 0.151748 0.144068 0.137154 0.131087 0.125943 0.121522 0.116952 0.181582 0.171772 0.164041 0.155712 0.148189 0.141531 0.135792 0.131057 0.127085 0.122812 0.184054 0.174258 0.16673 0.158706 0.151566 0.14534 0.140071 0.135863 0.132459 0.12857 0.184329 0.175008 0.168078 0.160651 0.15411 0.148491 0.14382 0.140222 0.137488 0.134156 0.182392 0.173999 0.168048 0.161496 0.155753 0.150891 0.146918 0.143939 0.141953 0.139696 0.178295 0.171254 0.166641 0.161229 0.156482 0.152557 0.149484 0.147292 0.146128 0.146159 0.172119 0.166836 0.163888 0.159841 0.156226 0.153295 0.151097 0.149575 0.14886 0.149379 0.164085 0.160881 0.159867 0.157371 0.154994 0.153098 0.151787 0.15098 0.15072 0.151497 0.154469 0.153575 0.154706 0.153913 0.152873 0.152069 0.151686 0.151684 0.152041 0.153125 0.143588 0.145143 0.148568 0.149604 0.149989 0.150336 0.150917 0.151764 0.152843 0.154367 0.131791 0.135841 0.141648 0.144604 0.146485 0.148032 0.149606 0.151313 0.153145 0.15521 0.11944 0.125943 0.134144 0.139077 0.142503 0.145287 0.147871 0.150434 0.153009 0.155645 0.106898 0.115715 0.126252 0.133177 0.138175 0.142212 0.14581 0.149217 0.152511 0.155712 0.0945084 0.105402 0.118152 0.127043 0.133611 0.1389 0.143505 0.147735 0.151721 0.155478 0.0826032 0.0952033 0.109995 0.120787 0.128902 0.135425 0.141016 0.146045 0.150694 0.155 0.0716211 0.0853103 0.101923 0.114496 0.12411 0.131836 0.138386 0.144185 0.149466 0.154314 0.0614461 0.0757757 0.0940392 0.108251 0.119299 0.128178 0.135648 0.142181 0.148056 0.153425 0.052154 0.0670045 0.0863852 0.102111 0.114509 0.124473 0.132815 0.140042 0.146468 0.152324 0.0439064 0.0590152 0.0790965 0.0961353 0.109752 0.12072 0.129881 0.137763 0.144695 0.150995 0.0367859 0.0518076 0.0722793 0.0903451 0.105026 0.116913 0.126833 0.135331 0.142731 0.149412 0.0308175 0.0454626 0.0659545 0.0847521 0.100317 0.113035 0.12364 0.132716 0.140572 0.147514 0.025991 0.0400424 0.0601482 0.0793704 0.0956335 0.109052 0.120265 0.12986 0.138208 0.14523 0.0222685 0.0355695 0.0548983 0.0742157 0.090971 0.104954 0.116683 0.126697 0.135329 0.142862 0.019591 0.0320383 0.0502404 0.0693101 0.0863254 0.100724 0.11287 0.123252 0.132141 0.139935 0.0178846 0.0294208 0.0462041 0.0646862 0.081711 0.0963611 0.108809 0.119507 0.128663 0.136374 0.0170579 0.0276665 0.0428114 0.0603842 0.0771565 0.0918753 0.104465 0.115277 0.124574 0.131823 0.0169587 0.0266821 0.0400685 0.0564486 0.0727036 0.0873041 0.0999058 0.110678 0.119931 0.127447 0.017533 0.0263983 0.0379793 0.0529295 0.0684151 0.0827248 0.0952766 0.106066 0.115393 0.123336 0.0186819 0.026718 0.036529 0.0498757 0.0643644 0.0782182 0.090659 0.10151 0.110971 0.119178 0.020284 0.0275289 0.0356833 0.0473259 0.0606177 0.073839 0.0860566 0.0969145 0.106468 0.114831 0.0222204 0.0287191 0.0353857 0.0452996 0.0572296 0.0696327 0.0814768 0.0922365 0.101814 0.110292 0.0243813 0.0301838 0.0355604 0.0437955 0.0542499 0.0656592 0.0769689 0.0875151 0.097047 0.105597 0.0266704 0.0318287 0.0361193 0.0427933 0.0517235 0.0619933 0.0726109 0.0828215 0.0922285 0.100794 0.0290092 0.0335713 0.0369704 0.0422536 0.0496845 0.0587158 0.0684966 0.0782413 0.0874317 0.095948 0.0313461 0.0353534 0.038031 0.0421219 0.0481455 0.0558969 0.064722 0.07387 0.0827421 0.0911391 ) ; boundaryField { inlet { type zeroGradient; } outlet { type fixedValue; value uniform 0; } cylinder { type zeroGradient; } top { type symmetryPlane; } bottom { type symmetryPlane; } defaultFaces { type empty; } } // ************************************************************************* //
[ "henry.rossiter@utexas.edu" ]
henry.rossiter@utexas.edu
eddd44313e6274eeb0acac7ff02b8121405143a2
b34cd2fb7a9e361fe1deb0170e3df323ec33259f
/Applications/ChiaMarketDataFeedClient/Include/ChiaMarketDataFeedClient/ChiaMdProtocolClient.hpp
79e338cd94ddcf9fa10332d3f5e997b550d703bf
[]
no_license
lineCode/nexus
c4479879dba1fbd11573c129f15b7b3c2156463e
aea7e2cbcf96a113f58eed947138b76e09b8fccb
refs/heads/master
2022-04-19T01:10:22.139995
2020-04-16T23:07:23
2020-04-16T23:07:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,468
hpp
#ifndef NEXUS_CHIAMDPROTOCOLCLIENT_HPP #define NEXUS_CHIAMDPROTOCOLCLIENT_HPP #include <string> #include <Beam/IO/NotConnectedException.hpp> #include <Beam/IO/OpenState.hpp> #include <Beam/Pointers/Dereference.hpp> #include <Beam/Pointers/LocalPtr.hpp> #include <boost/noncopyable.hpp> #include <boost/throw_exception.hpp> #include "ChiaMarketDataFeedClient/ChiaMessage.hpp" namespace Nexus { namespace MarketDataService { /*! \class ChiaMdProtocolClient \brief Parses packets from the CHIA market data feed. \tparam ChannelType The type of Channel receiving data. */ template<typename ChannelType> class ChiaMdProtocolClient : private boost::noncopyable { public: //! The type of Channel receiving data. using Channel = Beam::GetTryDereferenceType<ChannelType>; //! Constructs a ChiaMdProtocolClient. /*! \param channel Initializes the Channel receiving data. \param username The username. \param password The password. */ template<typename ChannelForward> ChiaMdProtocolClient(ChannelForward&& channel, std::string username, std::string password); //! Constructs a ChiaMdProtocolClient. /*! \param channel Initializes the Channel receiving data. \param username The username. \param password The password. \param session The session ID. \param sequence The sequence of the next expected message. */ template<typename ChannelForward> ChiaMdProtocolClient(ChannelForward&& channel, std::string username, std::string password, std::string session, std::uint32_t sequence); ~ChiaMdProtocolClient(); //! Reads the next message. ChiaMessage Read(); //! Reads the next message. /*! \param sequenceNumber The message's sequence number. */ ChiaMessage Read(Beam::Out<std::uint32_t> sequenceNumber); //! Reads the next message. /*! \param sequenceNumber The message's sequence number. */ Beam::IO::SharedBuffer ReadBuffer( Beam::Out<std::uint32_t> sequenceNumber); void Open(); void Close(); private: Beam::GetOptionalLocalPtr<ChannelType> m_channel; std::string m_username; std::string m_password; std::string m_session; std::uint32_t m_sequence; std::uint32_t m_nextSequence; Beam::IO::SharedBuffer m_message; Beam::IO::SharedBuffer m_buffer; Beam::IO::OpenState m_openState; void Shutdown(); Beam::IO::SharedBuffer ReadBuffer(); void Append(const std::string& value, int size, Beam::Out<Beam::IO::SharedBuffer> buffer); void Append(int value, int size, Beam::Out<Beam::IO::SharedBuffer> buffer); void Append(std::uint32_t value, int size, Beam::Out<Beam::IO::SharedBuffer> buffer); }; template<typename ChannelType> template<typename ChannelForward> ChiaMdProtocolClient<ChannelType>::ChiaMdProtocolClient( ChannelForward&& channel, std::string username, std::string password) : ChiaMdProtocolClient{std::forward<ChannelForward>(channel), std::move(username), std::move(password), "", 0} {} template<typename ChannelType> template<typename ChannelForward> ChiaMdProtocolClient<ChannelType>::ChiaMdProtocolClient( ChannelForward&& channel, std::string username, std::string password, std::string session, std::uint32_t sequence) : m_channel{std::forward<ChannelForward>(channel)}, m_username{std::move(username)}, m_password{std::move(password)}, m_session{std::move(session)}, m_sequence{sequence} {} template<typename ChannelType> ChiaMdProtocolClient<ChannelType>::~ChiaMdProtocolClient() { Close(); } template<typename ChannelType> ChiaMessage ChiaMdProtocolClient<ChannelType>::Read() { std::uint32_t sequence; return Read(Beam::Store(sequence)); } template<typename ChannelType> ChiaMessage ChiaMdProtocolClient<ChannelType>::Read( Beam::Out<std::uint32_t> sequenceNumber) { while(true) { m_message = ReadBuffer(); if(!m_message.IsEmpty() && m_message.GetData()[0] == 'S') { auto message = ChiaMessage::Parse(m_message.GetData() + 1, m_message.GetSize() - 2); *sequenceNumber = m_nextSequence; ++m_nextSequence; return message; } } } template<typename ChannelType> Beam::IO::SharedBuffer ChiaMdProtocolClient<ChannelType>::ReadBuffer( Beam::Out<std::uint32_t> sequenceNumber) { while(true) { auto buffer = ReadBuffer(); if(!buffer.IsEmpty() && buffer.GetData()[0] == 'S') { buffer.ShrinkFront(1); buffer.Shrink(2); *sequenceNumber = m_nextSequence; ++m_nextSequence; return buffer; } } } template<typename ChannelType> void ChiaMdProtocolClient<ChannelType>::Open() { const auto USERNAME_LENGTH = 6; const auto PASSWORD_LENGTH = 10; const auto SESSION_LENGTH = 10; const auto SEQUENCE_OFFSET = 11; const auto SEQUENCE_LENGTH = 10; if(m_openState.SetOpening()) { return; } try { m_channel->GetConnection().Open(); Beam::IO::SharedBuffer loginBuffer; Append("L", 1, Beam::Store(loginBuffer)); Append(m_username, USERNAME_LENGTH, Beam::Store(loginBuffer)); Append(m_password, PASSWORD_LENGTH, Beam::Store(loginBuffer)); Append(m_session, SESSION_LENGTH, Beam::Store(loginBuffer)); Append(m_sequence, SEQUENCE_LENGTH, Beam::Store(loginBuffer)); loginBuffer.Append('\x0A'); m_channel->GetWriter().Write(loginBuffer); auto response = ReadBuffer(); if(response.GetSize() < SEQUENCE_OFFSET + SEQUENCE_LENGTH || response.GetData()[0] != 'A') { BOOST_THROW_EXCEPTION(Beam::IO::ConnectException{"Invalid response."}); } auto cursor = &(response.GetData()[SEQUENCE_OFFSET]); m_nextSequence = static_cast<std::uint32_t>(ChiaMessage::ParseNumeric( SEQUENCE_LENGTH, Beam::Store(cursor))); } catch(const std::exception&) { m_openState.SetOpenFailure(); Shutdown(); } m_openState.SetOpen(); } template<typename ChannelType> void ChiaMdProtocolClient<ChannelType>::Close() { if(m_openState.SetClosing()) { return; } Shutdown(); } template<typename ChannelType> void ChiaMdProtocolClient<ChannelType>::Shutdown() { m_channel->GetConnection().Close(); m_openState.SetClosed(); } template<typename ChannelType> Beam::IO::SharedBuffer ChiaMdProtocolClient<ChannelType>::ReadBuffer() { const auto READ_SIZE = 1024; while(true) { auto delimiter = std::find(m_buffer.GetData(), m_buffer.GetData() + m_buffer.GetSize(), '\x0A'); if(delimiter == m_buffer.GetData() + m_buffer.GetSize()) { m_channel->GetReader().Read(Beam::Store(m_buffer), READ_SIZE); } else if(delimiter == m_buffer.GetData() + m_buffer.GetSize()) { auto buffer = std::move(m_buffer); m_buffer.Reset(); return buffer; } else { auto size = delimiter - m_buffer.GetData(); Beam::IO::SharedBuffer buffer{m_buffer.GetData(), static_cast<std::size_t>(size)}; m_buffer.ShrinkFront(size + 1); return buffer; } } } template<typename ChannelType> void ChiaMdProtocolClient<ChannelType>::Append(const std::string& value, int size, Beam::Out<Beam::IO::SharedBuffer> buffer) { buffer->Append(value.c_str(), value.size()); for(int i = 0; i < size - static_cast<int>(value.size()); ++i) { buffer->Append(' '); } } template<typename ChannelType> void ChiaMdProtocolClient<ChannelType>::Append(int value, int size, Beam::Out<Beam::IO::SharedBuffer> buffer) { auto stringValue = std::to_string(value); for(int i = 0; i < size - static_cast<int>(stringValue.size()); ++i) { buffer->Append(' '); } buffer->Append(stringValue.c_str(), stringValue.size()); } template<typename ChannelType> void ChiaMdProtocolClient<ChannelType>::Append(std::uint32_t value, int size, Beam::Out<Beam::IO::SharedBuffer> buffer) { auto stringValue = std::to_string(value); for(int i = 0; i < size - static_cast<int>(stringValue.size()); ++i) { buffer->Append(' '); } buffer->Append(stringValue.c_str(), stringValue.size()); } } } #endif
[ "kamal@eidolonsystems.com" ]
kamal@eidolonsystems.com
334410342f21d7015da0ee58b08c9923ab1171cf
c6b483cc2d7bc9eb6dc5c08ae92aa55ff9b3a994
/hazelcast/include/hazelcast/util/Comparator.h
4345b0bf2911757cd6803a1dc73321c91ea60e48
[ "Apache-2.0" ]
permissive
oguzdemir/hazelcast-cpp-client
ebffc7137a3a14b9fc5d96e1a1b0eac8aac1e60f
95c4687634a8ac4886d0a9b9b4c17622225261f0
refs/heads/master
2021-01-21T02:53:05.197319
2016-08-24T21:08:14
2016-08-24T21:08:14
63,674,978
0
0
null
2016-07-19T08:16:24
2016-07-19T08:16:23
null
UTF-8
C++
false
false
1,238
h
/* * Copyright (c) 2008-2015, Hazelcast, Inc. 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. */ // // Created by ihsan demir on 14 Apr 2016. #ifndef HAZELCAST_UTIL_COMPARATOR_ #define HAZELCAST_UTIL_COMPARATOR_ #include "hazelcast/util/HazelcastDll.h" namespace hazelcast { namespace util { template <typename T> class Comparator { public: /** * @lhs First value to compare * @rhs Second value to compare * @return Returns < 0 if lhs is less, >0 if lhs is greater, else returns 0. */ virtual int compare(const T &lhs, const T &rhs) const = 0; }; } } #endif //HAZELCAST_UTIL_COMPARATOR_
[ "ihsan@hazelcast.com" ]
ihsan@hazelcast.com
899cf420ecb8531f47b155a42fef0df93aed0d9e
9a488a219a4f73086dc704c163d0c4b23aabfc1f
/tags/Release-0_9_15/src/FbTk/Button.cc
e2ba7b5e5a7c1a0b19c8caeebffe40df17382548
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
BackupTheBerlios/fluxbox-svn
47b8844b562f56d02b211fd4323c2a761b473d5b
3ac62418ccf8ffaddbf3c181f28d2f652543f83f
refs/heads/master
2016-09-05T14:55:27.249504
2007-12-14T23:27:57
2007-12-14T23:27:57
40,667,038
0
0
null
null
null
null
UTF-8
C++
false
false
4,356
cc
// Button.cc for FbTk - fluxbox toolkit // Copyright (c) 2002 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org) // // 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. // $Id$ #include "Button.hh" #include "Command.hh" #include "EventManager.hh" #include "App.hh" namespace FbTk { Button::Button(int screen_num, int x, int y, unsigned int width, unsigned int height): FbWindow(screen_num, x, y, width, height, ExposureMask | ButtonPressMask | ButtonReleaseMask), m_background_pm(0), m_pressed_pm(0), m_pressed_color(), m_gc(DefaultGC(FbTk::App::instance()->display(), screen_num)), m_pressed(false) { // add this to eventmanager FbTk::EventManager::instance()->add(*this, *this); } Button::Button(const FbWindow &parent, int x, int y, unsigned int width, unsigned int height): FbWindow(parent, x, y, width, height, ExposureMask | ButtonPressMask | ButtonReleaseMask), m_background_pm(0), m_pressed_pm(0), m_pressed_color(), m_gc(DefaultGC(FbTk::App::instance()->display(), screenNumber())), m_pressed(false) { // add this to eventmanager FbTk::EventManager::instance()->add(*this, *this); } Button::~Button() { } void Button::setOnClick(RefCount<Command> &cmd, int button) { // we only handle buttons 1 to 5 if (button > 5 || button == 0) return; //set on click command for the button m_onclick[button - 1] = cmd; } void Button::setPressedPixmap(Pixmap pm) { m_pressed_pm = pm; } void Button::setPressedColor(const FbTk::Color &color) { m_pressed_pm = None; m_pressed_color = color; } void Button::setBackgroundColor(const Color &color) { m_background_pm = 0; // we're using background color now m_background_color = color; FbTk::FbWindow::setBackgroundColor(color); } void Button::setBackgroundPixmap(Pixmap pm) { m_background_pm = pm; FbTk::FbWindow::setBackgroundPixmap(pm); } void Button::buttonPressEvent(XButtonEvent &event) { bool update = false; if (m_pressed_pm != 0) { update = true; FbTk::FbWindow::setBackgroundPixmap(m_pressed_pm); } else if (m_pressed_color.isAllocated()) { update = true; FbTk::FbWindow::setBackgroundColor(m_pressed_color); } m_pressed = true; if (update) { clear(); } } void Button::buttonReleaseEvent(XButtonEvent &event) { m_pressed = false; bool update = false; if (m_background_pm) { if (m_pressed_pm != 0) { update = true; setBackgroundPixmap(m_background_pm); } } else if (m_pressed_color.isAllocated()) { update = true; setBackgroundColor(m_background_color); } if (update) clear(); // clear background // finaly, execute command (this must be done last since this object might be deleted by the command) if (event.button > 0 && event.button <= 5 && event.x > 0 && event.x < static_cast<signed>(width()) && event.y > 0 && event.y < static_cast<signed>(height()) && m_onclick[event.button -1].get() != 0) m_onclick[event.button - 1]->execute(); } void Button::exposeEvent(XExposeEvent &event) { clearArea(event.x, event.y, event.width, event.height); } }; // end namespace FbTk
[ "simonb@54ec5f11-9ae8-0310-9a2b-99d706b22625" ]
simonb@54ec5f11-9ae8-0310-9a2b-99d706b22625