text
string
size
int64
token_count
int64
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/permissions/permission_util.h" #include "build/build_config.h" #include "base/feature_list.h" #include "base/logging.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/permissions/permission_uma_util.h" #include "chrome/common/chrome_features.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "content/public/browser/permission_type.h" using content::PermissionType; std::size_t PermissionTypeHash::operator()( const content::PermissionType& type) const { return static_cast<size_t>(type); } // The returned strings must match the RAPPOR metrics in rappor.xml, // and any Field Trial configs for the Permissions kill switch e.g. // Permissions.Action.Geolocation etc.. std::string PermissionUtil::GetPermissionString( content::PermissionType permission) { switch (permission) { case content::PermissionType::GEOLOCATION: return "Geolocation"; case content::PermissionType::NOTIFICATIONS: return "Notifications"; case content::PermissionType::MIDI_SYSEX: return "MidiSysEx"; case content::PermissionType::PUSH_MESSAGING: return "PushMessaging"; case content::PermissionType::DURABLE_STORAGE: return "DurableStorage"; case content::PermissionType::PROTECTED_MEDIA_IDENTIFIER: return "ProtectedMediaIdentifier"; case content::PermissionType::AUDIO_CAPTURE: return "AudioCapture"; case content::PermissionType::VIDEO_CAPTURE: return "VideoCapture"; case content::PermissionType::MIDI: return "Midi"; case content::PermissionType::BACKGROUND_SYNC: return "BackgroundSync"; case content::PermissionType::FLASH: return "Flash"; case content::PermissionType::NUM: break; } NOTREACHED(); return std::string(); } PermissionRequestType PermissionUtil::GetRequestType( content::PermissionType type) { switch (type) { case content::PermissionType::GEOLOCATION: return PermissionRequestType::PERMISSION_GEOLOCATION; case content::PermissionType::NOTIFICATIONS: return PermissionRequestType::PERMISSION_NOTIFICATIONS; case content::PermissionType::MIDI_SYSEX: return PermissionRequestType::PERMISSION_MIDI_SYSEX; case content::PermissionType::PUSH_MESSAGING: return PermissionRequestType::PERMISSION_PUSH_MESSAGING; case content::PermissionType::PROTECTED_MEDIA_IDENTIFIER: return PermissionRequestType::PERMISSION_PROTECTED_MEDIA_IDENTIFIER; case content::PermissionType::FLASH: return PermissionRequestType::PERMISSION_FLASH; default: NOTREACHED(); return PermissionRequestType::UNKNOWN; } } PermissionRequestGestureType PermissionUtil::GetGestureType(bool user_gesture) { return user_gesture ? PermissionRequestGestureType::GESTURE : PermissionRequestGestureType::NO_GESTURE; } bool PermissionUtil::GetPermissionType(ContentSettingsType type, PermissionType* out) { if (type == CONTENT_SETTINGS_TYPE_GEOLOCATION) { *out = PermissionType::GEOLOCATION; } else if (type == CONTENT_SETTINGS_TYPE_NOTIFICATIONS) { *out = PermissionType::NOTIFICATIONS; } else if (type == CONTENT_SETTINGS_TYPE_MIDI_SYSEX) { *out = PermissionType::MIDI_SYSEX; } else if (type == CONTENT_SETTINGS_TYPE_DURABLE_STORAGE) { *out = PermissionType::DURABLE_STORAGE; } else if (type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA) { *out = PermissionType::VIDEO_CAPTURE; } else if (type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC) { *out = PermissionType::AUDIO_CAPTURE; } else if (type == CONTENT_SETTINGS_TYPE_BACKGROUND_SYNC) { *out = PermissionType::BACKGROUND_SYNC; #if defined(OS_ANDROID) || defined(OS_CHROMEOS) } else if (type == CONTENT_SETTINGS_TYPE_PROTECTED_MEDIA_IDENTIFIER) { *out = PermissionType::PROTECTED_MEDIA_IDENTIFIER; #endif } else { return false; } return true; } bool PermissionUtil::ShouldShowPersistenceToggle() { return base::FeatureList::IsEnabled( features::kDisplayPersistenceToggleInPermissionPrompts); } PermissionUtil::ScopedRevocationReporter::ScopedRevocationReporter( Profile* profile, const GURL& primary_url, const GURL& secondary_url, ContentSettingsType content_type, PermissionSourceUI source_ui) : profile_(profile), primary_url_(primary_url), secondary_url_(secondary_url), content_type_(content_type), source_ui_(source_ui) { if (!primary_url_.is_valid() || (!secondary_url_.is_valid() && !secondary_url_.is_empty())) { is_initially_allowed_ = false; return; } HostContentSettingsMap* settings_map = HostContentSettingsMapFactory::GetForProfile(profile_); ContentSetting initial_content_setting = settings_map->GetContentSetting( primary_url_, secondary_url_, content_type_, std::string()); is_initially_allowed_ = initial_content_setting == CONTENT_SETTING_ALLOW; } PermissionUtil::ScopedRevocationReporter::ScopedRevocationReporter( Profile* profile, const ContentSettingsPattern& primary_pattern, const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, PermissionSourceUI source_ui) : ScopedRevocationReporter( profile, GURL(primary_pattern.ToString()), GURL((secondary_pattern == ContentSettingsPattern::Wildcard()) ? primary_pattern.ToString() : secondary_pattern.ToString()), content_type, source_ui) {} PermissionUtil::ScopedRevocationReporter::~ScopedRevocationReporter() { if (!is_initially_allowed_) return; HostContentSettingsMap* settings_map = HostContentSettingsMapFactory::GetForProfile(profile_); ContentSetting final_content_setting = settings_map->GetContentSetting( primary_url_, secondary_url_, content_type_, std::string()); if (final_content_setting != CONTENT_SETTING_ALLOW) { PermissionType permission_type; if (PermissionUtil::GetPermissionType(content_type_, &permission_type)) { PermissionUmaUtil::PermissionRevoked(permission_type, source_ui_, primary_url_, profile_); } } }
6,462
2,028
/* * * Filename: proj2_2_6.cpp * * Author: Haibo Hao * Email : haohaibo@ncic.ac.cn * Description: --- * Create: 2017-04-08 22:16:41 * Last Modified: 2017-04-08 22:51:35 **/ #include <iostream> int main() { std::cout << "a multi-line " "string literal " "using concatenation" << std::endl; std::cou\ t << "hi" << std::endl; // multiline string literal std::cout << "a multi-line \ string literal \ using a backslash" << std::endl; return 0; }
538
218
#pragma once #ifndef POINT_PLANE_HPP #define POINT_PLANE_HPP #include <physics/Plane.hpp> namespace slaggy { class PointPlane : public Plane { public: glm::vec3 position = glm::vec3(0); float distance() const override; }; } #endif
243
107
#include "Cycle.h" /// <summary> /// 문제 /// 두 자연수 N과 P를 가지고 다음 과정을 거쳐서 나오는 숫자들을 차례대로 출력해보자. /// 처음 출력하는 숫자는 N이고, 두 번째 이후 출력하는 숫자들은 N을 곱하고 P로 나눈 나머지를 구하는 과정을 반복하여 구한다. /// 즉, 먼저 N에 N을 곱하고, 이 수를 P로 나눈 나머지를 두 번째에 출력한다. /// 다음에는 이 나머지에 N을 곱하고 P로 나눈 나머지를 출력한다. /// 다음에는 이 나머지에 N을 곱한 후 P로 나눈 나머지를 출력한다. /// 이 과정을 계속 반복해보면 출력되는 숫자들에는 반복되는 부분이 있다. /// /// 예를 들어서, N = 67, P = 31인 경우를 생각해보자. /// 처음 출력되는 숫자는 67이고, 두 번째로 출력되는 숫자는 67×67 = 4489를 31로 나눈 나머지 25이다. /// 다음에는 25×67 = 1675를 31로 나눈 나머지 1, 다음에는 1×67 = 67을 31로 나눈 나머지 5가 차례대로 출력된다. /// 다음에는 5×67 = 335를 31로 나눈 나머지 25가 출력되는데, /// 이 수는 이미 이전에 출력된 수이다.이 과정을 그림으로 보이면 다음과 같다. /// /// 즉 이 과정을 반복하면, 처음 67을 제외하면 3개의 숫자 25, 1, 5가 계속 무한히 반복되게 된다. /// 또 다른 예로, N = 9, P = 3을 가지고 시작하면, 9×9 = 81이고 3으로 나눈 나머지는 0이며, /// 0×9 = 0이고 3으로 나눈 나머지도 0이기 때문에 처음 9를 제외하면 0이 무한히 반복되게 된다. /// /// N과 P를 입력받아 위와 같이 정의된 연산을 수행하였을 때, /// 반복되는 부분에 포함된 서로 다른 숫자의 개수를 구하는 프로그램을 작성하시오. /// /// 입력 형식 /// 첫째 줄에 처음 시작하는 N과 P가 공백을 사이에 두고 주어진다. 단, 1≤N≤1,000, 2≤P≤97이다. /// /// 출력 형식 /// 첫째 줄에 반복되는 부분에 포함된 서로 다른 숫자의 개수를 출력한다. /// /// 입력 예 /// 입력 예 /// 67 31 /// 96 61 /// /// 출력 예 /// 출력 예 /// 3 /// 60 /// /// http://www.jungol.co.kr/bbs/board.php?bo_table=pbank&wr_id=1828&sca=2080 /// </summary> void Cycle::Code() { int n, p; std::cin >> n >> p; vector<int> numbers; std::cout << GetCycleNumberCount(n, p, n, numbers); } int Cycle::GetCycleNumberCount(int n, int p, int curNumber, vector<int>& numbers) { auto cycleBeg = std::find(numbers.begin(), numbers.end(), curNumber); if (std::find(numbers.begin(), numbers.end(), curNumber) != numbers.end()) { int count{ 0 }; while (cycleBeg != numbers.end()) { count++; cycleBeg++; } return count; } numbers.push_back(curNumber); return GetCycleNumberCount(n, p, (curNumber * n) % p, numbers); }
1,800
1,670
#include "vm-object-scanner.h" #include "vm-objects.h" namespace mio { void ObjectScanner::Scan(HeapObject *ob, Callback callback) { if (!ob) { return; } callback(ob); if (traced_objects_.find(ob) != traced_objects_.end()) { return; } traced_objects_.insert(ob); switch (ob->GetKind()) { case HeapObject::kString: break; case HeapObject::kError: { auto err = ob->AsError(); Scan(err->GetLinkedError(), callback); Scan(err->GetFileName(), callback); Scan(err->GetMessage(), callback); } break; case HeapObject::kUnion: { auto uni = ob->AsUnion(); Scan(uni->GetTypeInfo(), callback); if (uni->GetTypeInfo()->IsObject()) { Scan(uni->GetObject(), callback); } } break; case HeapObject::kUpValue: { auto upval = ob->AsUpValue(); if (upval->IsObjectValue()) { Scan(upval->GetObject(), callback); } } break; case HeapObject::kClosure: { auto fn = ob->AsClosure(); Scan(fn->GetName(), callback); if (fn->IsOpen()) { return; } Scan(fn->GetFunction(), callback); auto buf = fn->GetUpValuesBuf(); for (int i = 0; i < buf.n; ++i) { auto val = buf.z[i].val; Scan(val, callback); if (val->IsObjectValue()) { Scan(val->GetObject(), callback); } } } break; case HeapObject::kGeneratedFunction: { auto fn = ob->AsGeneratedFunction(); Scan(fn->GetName(), callback); auto buf = fn->GetConstantObjectBuf(); for (int i = 0; i < buf.n; ++i) { Scan(buf.z[i], callback); } } break; case HeapObject::kNativeFunction: { auto fn = ob->AsNativeFunction(); Scan(fn->GetName(), callback); Scan(fn->GetSignature(), callback); } break; case HeapObject::kSlice: { auto slice = ob->AsSlice(); Scan(slice->GetVector(), callback); } break; case HeapObject::kVector: { auto vector = ob->AsVector(); Scan(vector->GetElement(), callback); if (vector->GetElement()->IsObject()) { for (int i = 0; i < vector->GetSize(); ++i) { Scan(vector->GetObject(i), callback); } } } break; case HeapObject::kHashMap: { auto map = ob->AsHashMap(); Scan(map->GetKey(), callback); Scan(map->GetValue(), callback); if (map->GetKey()->IsPrimitive() && map->GetValue()->IsPrimitive()) { break; } for (int i = 0; i < map->GetSlotSize(); ++i) { auto node = map->GetSlot(i)->head; while (node) { if (map->GetKey()->IsObject()) { Scan(*static_cast<HeapObject **>(node->GetKey()), callback); } if (map->GetValue()->IsObject()) { Scan(*static_cast<HeapObject **>(node->GetValue()), callback); } node = node->GetNext(); } } } break; case HeapObject::kReflectionVoid: case HeapObject::kReflectionRef: case HeapObject::kReflectionString: case HeapObject::kReflectionError: case HeapObject::kReflectionFloating: case HeapObject::kReflectionIntegral: case HeapObject::kReflectionUnion: case HeapObject::kReflectionExternal: break; case HeapObject::kReflectionArray: { auto type = ob->AsReflectionArray(); Scan(type->GetElement(), callback); } break; case HeapObject::kReflectionMap: { auto type = ob->AsReflectionMap(); Scan(type->GetKey(), callback); Scan(type->GetValue(), callback); } break; case HeapObject::kReflectionFunction: { auto type = ob->AsReflectionFunction(); Scan(type->GetReturn(), callback); for (int i = 0; i < type->GetNumberOfParameters(); ++i) { Scan(type->GetParamter(i), callback); } } break; default: DLOG(FATAL) << "kind not be supported. " << ob->GetKind(); break; } } } // namespace mio
4,648
1,321
GetStatusBar ().SetPaneAnimation (nStatusAnimation, m_imlStatusAnimation); GetStatusBar ().SetPaneText (nStatusAnimation, _T("")); GetStatusBar ().SetPaneWidth (nStatusAnimation, 16);
186
61
#include "class_3.h" #include "class_2.h" #include "class_6.h" #include "class_9.h" #include "class_5.h" #include "class_3.h" #include <lib_32/class_0.h> #include <lib_3/class_6.h> #include <lib_27/class_4.h> #include <lib_47/class_2.h> #include <lib_29/class_8.h> class_3::class_3() {} class_3::~class_3() {}
311
157
/****************************************************************************** * Copyright 2018 The Apollo 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 "modules/drivers/radar/racobit_radar/protocol/radar_state_201.h" #include "glog/logging.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/common/canbus_consts.h" namespace apollo { namespace drivers { namespace racobit_radar { using apollo::drivers::canbus::Byte; RadarState201::RadarState201() {} const uint32_t RadarState201::ID = 0x201; void RadarState201::Parse(const std::uint8_t* bytes, int32_t length, RacobitRadar* racobit_radar) const { auto state = racobit_radar->mutable_radar_state(); state->set_max_distance(max_dist(bytes, length)); state->set_output_type(output_type(bytes, length)); state->set_rcs_threshold(rcs_threshold(bytes, length)); state->set_radar_power(radar_power(bytes, length)); state->set_send_quality(send_quality(bytes, length)); state->set_send_ext_info(send_ext_info(bytes, length)); } int RadarState201::max_dist(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 1); uint32_t x = t0.get_byte(0, 8); Byte t1(bytes + 2); uint32_t t = t1.get_byte(6, 2); x <<= 2; x |= t; int ret = x * 2; return ret; } int RadarState201::radar_power(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 3); uint32_t x = t0.get_byte(0, 2); Byte t1(bytes + 4); uint32_t t = t1.get_byte(7, 1); x <<= 1; x |= t; int ret = x; return ret; } OutputType RadarState201::output_type(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); uint32_t x = t0.get_byte(2, 2); switch (x) { case 0x0: return OUTPUT_TYPE_NONE; case 0x1: return OUTPUT_TYPE_OBJECTS; case 0x2: return OUTPUT_TYPE_CLUSTERS; default: return OUTPUT_TYPE_ERROR; } } RcsThreshold RadarState201::rcs_threshold(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 7); uint32_t x = t0.get_byte(2, 3); switch (x) { case 0x0: return RCS_THRESHOLD_STANDARD; case 0x1: return RCS_THRESHOLD_HIGH_SENSITIVITY; default: return RCS_THRESHOLD_ERROR; } } bool RadarState201::send_quality(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); uint32_t x = t0.get_byte(4, 1); bool ret = (x == 0x1); return ret; } bool RadarState201::send_ext_info(const std::uint8_t* bytes, int32_t length) const { Byte t0(bytes + 5); uint32_t x = t0.get_byte(5, 1); bool ret = (x == 0x1); return ret; } } // namespace racobit_radar } // namespace drivers } // namespace apollo
3,488
1,327
#include<cstdio> #include<cstring> #include<vector> using namespace std; const int maxv = 1111; vector<int> G[maxv]; bool vis[maxv] = {false}; int currentPoint; //当前需要删除的顶点号 void dfs(int v){ if(v == currentPoint){ //当遍历到已删除结点v时,返回 return; } vis[v] = true; for (int i = 0; i < G[v].size(); i++){ if(vis[G[v][i]] == false){ dfs(G[v][i]); } } } int main(){ int n, m, k, a, b; int block; //连通块数目 scanf("%d%d%d", &n, &m, &k); for (int i = 0; i < m; i++){ scanf("%d%d", &a, &b); G[a].push_back(b); G[b].push_back(a); } for (int query = 0; query < k; query++){ scanf("%d", &currentPoint); memset(vis, false, sizeof(vis)); //初始化vis数组为false block = 0; for (int i = 1; i <= n ; i++) //枚举每个顶点 { if(i != currentPoint && vis[i] == false){ dfs(i); //遍历顶点i所在的连通块 block++; //连通块个数加1 } } printf("%d\n", block - 1); //需要添加的边数等于连通块个数减1 } }
1,064
491
/* * Copyright 2007-2021 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * 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. * * 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 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Client.hxx" #include "Error.hxx" #include "Parser.hxx" #include "pool/pool.hxx" #include "istream/Sink.hxx" #include "istream/UnusedPtr.hxx" #include "istream/istream_null.hxx" #include "stopwatch.hxx" #include "http/ResponseHandler.hxx" #include "memory/fb_pool.hxx" #include "memory/SliceFifoBuffer.hxx" #include "util/Cancellable.hxx" #include "util/DestructObserver.hxx" #include "util/Exception.hxx" #include <string.h> #include <stdlib.h> class CGIClient final : Istream, IstreamSink, Cancellable, DestructAnchor { const StopwatchPtr stopwatch; SliceFifoBuffer buffer; CGIParser parser; /** * This flag is true while cgi_parse_headers() is calling * HttpResponseHandler::InvokeResponse(). In this case, * istream_read(cgi->input) is already up in the stack, and must * not be called again. */ bool in_response_callback; bool had_input, had_output; HttpResponseHandler &handler; public: CGIClient(struct pool &_pool, StopwatchPtr &&_stopwatch, UnusedIstreamPtr _input, HttpResponseHandler &_handler, CancellablePointer &cancel_ptr); /** * @return false if the connection has been closed */ bool ReturnResponse(); /** * Feed data into the input buffer and continue parsing response * headers from it. After this function returns, the response may * have been delivered to the response handler, and the caller should * post the rest of the specified buffer to the response body stream. * * Caller must hold pool reference. * * @return the number of bytes consumed from the specified buffer * (moved to the input buffer), 0 if the object has been closed */ size_t FeedHeaders(const void *data, size_t length); /** * Call FeedHeaders() in a loop, to parse as much as possible. * * Caller must hold pool reference. */ size_t FeedHeadersLoop(const char *data, size_t length); /** * Caller must hold pool reference. */ size_t FeedHeadersCheck(const char *data, size_t length); size_t FeedBody(const char *data, size_t length); /* virtual methods from class Cancellable */ void Cancel() noexcept override; /* virtual methods from class Istream */ void _SetDirect(FdTypeMask mask) noexcept override { Istream::_SetDirect(mask); input.SetDirect(mask); } off_t _GetAvailable(bool partial) noexcept override; void _Read() noexcept override; /* virtual methods from class IstreamHandler */ size_t OnData(const void *data, size_t length) noexcept override; ssize_t OnDirect(FdType type, int fd, size_t max_length) noexcept override; void OnEof() noexcept override; void OnError(std::exception_ptr ep) noexcept override; }; inline bool CGIClient::ReturnResponse() { http_status_t status = parser.GetStatus(); auto headers = std::move(parser).GetHeaders(); if (http_status_is_empty(status)) { /* this response does not have a response body, as indicated by the HTTP status code */ stopwatch.RecordEvent("empty"); auto &_handler = handler; Destroy(); _handler.InvokeResponse(status, std::move(headers), UnusedIstreamPtr()); return false; } else if (parser.IsEOF()) { /* the response body is empty */ stopwatch.RecordEvent("empty"); auto &_handler = handler; Destroy(); _handler.InvokeResponse(status, std::move(headers), istream_null_new(GetPool())); return false; } else { stopwatch.RecordEvent("headers"); const DestructObserver destructed(*this); in_response_callback = true; handler.InvokeResponse(status, std::move(headers), UnusedIstreamPtr(this)); if (destructed) return false; in_response_callback = false; return true; } } inline size_t CGIClient::FeedHeaders(const void *data, size_t length) try { assert(!parser.AreHeadersFinished()); auto w = buffer.Write(); assert(!w.empty()); if (length > w.size) length = w.size; memcpy(w.data, data, length); buffer.Append(length); switch (parser.FeedHeaders(GetPool(), buffer)) { case Completion::DONE: /* the DONE status can only be triggered by new data that was just received; therefore, the amount of data still in the buffer (= response body) must be smaller */ assert(buffer.GetAvailable() < length); if (!ReturnResponse()) return 0; /* don't consider data still in the buffer (= response body) as "consumed"; the caller will attempt to submit it to the response body handler */ return length - buffer.GetAvailable(); case Completion::MORE: return length; case Completion::CLOSED: /* unreachable */ assert(false); return 0; } /* unreachable */ assert(false); return 0; } catch (...) { auto &_handler = handler; Destroy(); _handler.InvokeError(std::current_exception()); return 0; } inline size_t CGIClient::FeedHeadersLoop(const char *data, size_t length) { assert(length > 0); assert(!parser.AreHeadersFinished()); const DestructObserver destructed(*this); size_t consumed = 0; do { size_t nbytes = FeedHeaders(data + consumed, length - consumed); if (nbytes == 0) break; consumed += nbytes; } while (consumed < length && !parser.AreHeadersFinished()); if (destructed) return 0; return consumed; } inline size_t CGIClient::FeedHeadersCheck(const char *data, size_t length) { size_t nbytes = FeedHeadersLoop(data, length); assert(nbytes == 0 || input.IsDefined()); assert(nbytes == 0 || !parser.AreHeadersFinished() || !parser.IsEOF()); return nbytes; } inline size_t CGIClient::FeedBody(const char *data, size_t length) { if (parser.IsTooMuch(length)) { stopwatch.RecordEvent("malformed"); DestroyError(std::make_exception_ptr(CgiError("too much data from CGI script"))); return 0; } had_output = true; size_t nbytes = InvokeData(data, length); if (nbytes > 0 && parser.BodyConsumed(nbytes)) { stopwatch.RecordEvent("end"); DestroyEof(); return 0; } return nbytes; } /* * input handler * */ size_t CGIClient::OnData(const void *data, size_t length) noexcept { assert(input.IsDefined()); had_input = true; if (!parser.AreHeadersFinished()) { size_t nbytes = FeedHeadersCheck((const char *)data, length); if (nbytes > 0 && nbytes < length && parser.AreHeadersFinished()) { /* the headers are finished; now begin sending the response body */ const DestructObserver destructed(*this); size_t nbytes2 = FeedBody((const char *)data + nbytes, length - nbytes); if (nbytes2 > 0) /* more data was consumed */ nbytes += nbytes2; else if (destructed) /* the connection was closed, must return 0 */ nbytes = 0; } return nbytes; } else { return FeedBody((const char *)data, length); } } ssize_t CGIClient::OnDirect(FdType type, int fd, size_t max_length) noexcept { assert(parser.AreHeadersFinished()); had_input = true; had_output = true; if (parser.KnownLength() && (off_t)max_length > parser.GetAvailable()) max_length = (size_t)parser.GetAvailable(); ssize_t nbytes = InvokeDirect(type, fd, max_length); if (nbytes > 0 && parser.BodyConsumed(nbytes)) { stopwatch.RecordEvent("end"); DestroyEof(); return ISTREAM_RESULT_CLOSED; } return nbytes; } void CGIClient::OnEof() noexcept { input.Clear(); if (!parser.AreHeadersFinished()) { stopwatch.RecordEvent("malformed"); assert(!HasHandler()); auto &_handler = handler; Destroy(); _handler.InvokeError(std::make_exception_ptr(CgiError("premature end of headers from CGI script"))); } else if (parser.DoesRequireMore()) { stopwatch.RecordEvent("malformed"); DestroyError(std::make_exception_ptr(CgiError("premature end of response body from CGI script"))); } else { stopwatch.RecordEvent("end"); DestroyEof(); } } void CGIClient::OnError(std::exception_ptr ep) noexcept { stopwatch.RecordEvent("error"); input.Clear(); if (!parser.AreHeadersFinished()) { /* the response hasn't been sent yet: notify the response handler */ assert(!HasHandler()); auto &_handler = handler; Destroy(); _handler.InvokeError(NestException(ep, std::runtime_error("CGI request body failed"))); } else { /* response has been sent: abort only the output stream */ DestroyError(ep); } } /* * istream implementation * */ off_t CGIClient::_GetAvailable(bool partial) noexcept { if (parser.KnownLength()) return parser.GetAvailable(); if (!input.IsDefined()) return 0; if (in_response_callback) /* this condition catches the case in cgi_parse_headers(): HttpResponseHandler::InvokeResponse() might recursively call istream_read(input) */ return (off_t)-1; return input.GetAvailable(partial); } void CGIClient::_Read() noexcept { if (input.IsDefined()) { /* this condition catches the case in cgi_parse_headers(): HttpResponseHandler::InvokeResponse() might recursively call input.Read() */ if (in_response_callback) { return; } const DestructObserver destructed(*this); had_output = false; do { had_input = false; input.Read(); } while (!destructed && input.IsDefined() && had_input && !had_output); } } /* * async operation * */ void CGIClient::Cancel() noexcept { assert(input.IsDefined()); Destroy(); } /* * constructor * */ inline CGIClient::CGIClient(struct pool &_pool, StopwatchPtr &&_stopwatch, UnusedIstreamPtr _input, HttpResponseHandler &_handler, CancellablePointer &cancel_ptr) :Istream(_pool), IstreamSink(std::move(_input)), stopwatch(std::move(_stopwatch)), buffer(fb_pool_get()), handler(_handler) { cancel_ptr = *this; input.Read(); } void cgi_client_new(struct pool &pool, StopwatchPtr stopwatch, UnusedIstreamPtr input, HttpResponseHandler &handler, CancellablePointer &cancel_ptr) { NewFromPool<CGIClient>(pool, pool, std::move(stopwatch), std::move(input), handler, cancel_ptr); }
11,238
4,003
struct _DFS_TEST_LINK { LPWSTR Name; LPWSTR RemainingName; ULONG NumberReplicas; ULONG ReplicaIndex[10]; } DfsTestLinks[] = { { L"\\\\BlahBlah\\DfsRoot\\FirstLevel", L"", 2, 1, 2 }, { L"\\\\BlahBlah\\DfsRoot\\FirstLevel\\a\\b\\c", L"a\\b\\c", 2, 1, 2 }, { L"\\\\BlahBlah\\DfsRoot\\FirstLevel\\x\\y", L"x\\y", 2, 1, 2 }, { L"\\\\BlahBlah\\DfsRoot\\FirstLevel\\test\\me\\once", L"test\\me\\once", 2, 1, 2 }, { L"\\\\BlahBlah\\DfsRoot\\SecondLevel\\This", L"", 2, 3, 4, }, { L"\\\\BlahBlah\\DfsRoot\\SecondLevel\\This\\one\\two\\three", L"one\\two\\three", 2, 3, 4, }, { L"\\\\BlahBlah\\DfsRoot\\SecondLevel\\This\\Not\\Again", L"Not\\Again", 2, 3, 4, }, { L"\\\\BlahBlah\\DfsRoot\\SecondLevel\\This\\a\\b\\c", L"a\\b\\c", 2, 3, 4, }, { L"\\\\BlahBlah\\DfsRoot\\ThirdLevel\\This\\That", L"", 3, 5, 6, 7, }, { L"\\\\BlahBlah\\DfsRoot\\ThirdLevel\\This\\That\\a\\b\\c", L"a\\b\\c", 3, 5, 6, 7, }, { L"\\\\BlahBlah\\DfsRoot\\ThirdLevel\\This\\That\\m\\n\\o", L"m\\n\\o", 3, 5, 6, 7, }, { L"\\\\BlahBlah\\DfsRoot\\FourLevel\\This\\That\\a", L"", 3, 8, 9, 10, }, { L"\\\\BlahBlah\\DfsRoot\\FourLevel\\This\\That\\a\\aaa\\aaa\\aaa", L"aaa\\aaa\\aaa", 3, 8, 9, 10, }, { L"\\\\BlahBlah\\DfsRoot\\FourLevel\\This\\That\\a\\bbb\\bbb", L"bbb\\bbb", 3, 8, 9, 10, }, { L"\\\\BlahBlah\\DfsRoot\\FiveLevel\\This\\That\\a\\b", L"", 3, 11, 12, 13, }, { L"\\\\BlahBlah\\DfsRoot\\SixLevel\\This\\That\\a\\b\\c", L"", 3, 14, 15, 16, }, { L"\\\\BlahBlah\\DfsRoot\\SevenLevel\\This\\That\\a\\b\\c\\d", L"", 3, 17, 18, 19, }, { L"\\\\BlahBlah\\DfsRoot\\EightLevel\\This\\That\\a\\b\\c\\d\\e", L"", 3, 20, 21, 22, }, { L"\\\\BlahBlah\\DfsRoot\\TestLevel\\This\\That", L"", 2, 23, 24, }, { L"\\\\BlahBlah\\DfsRoot\\Test1Level\\This\\That", L"", 2, 25, 26, }, }; LPWSTR Targets[] = { L"", L"\\\\scratch\\scratch\\uday\\a", L"\\\\scratch\\scratch\\uday\\b" L"\\\\scratch\\scratch\\uday\\c", L"\\\\scratch\\scratch\\uday\\d", L"\\\\scratch\\scratch\\uday\\e", L"\\\\scratch\\scratch\\uday\\f", L"\\\\scratch\\scratch\\uday\\g", L"\\\\scratch\\scratch\\uday\\h", L"\\\\scratch\\scratch\\uday\\i", L"\\\\scratch\\scratch\\uday\\j", L"\\\\scratch\\scratch\\uday\\k", L"\\\\scratch\\scratch\\uday\\l", L"\\\\scratch\\scratch\\uday\\m", L"\\\\scratch\\scratch\\uday\\n", L"\\\\scratch\\scratch\\uday\\o", L"\\\\scratch\\scratch\\uday\\p", L"\\\\scratch\\scratch\\uday\\q", L"\\\\scratch\\scratch\\uday\\r", L"\\\\scratch\\scratch\\uday\\s", L"\\\\scratch\\scratch\\uday\\t", L"\\\\scratch\\scratch\\uday\\u", L"\\\\scratch\\scratch\\uday\\v", L"\\\\scratch\\scratch\\uday\\w", L"\\\\scratch\\scratch\\uday\\x", L"\\\\scratch\\scratch\\uday\\y", L"\\\\scratch\\scratch\\uday\\z" };
4,126
1,692
// license:BSD-3-Clause // copyright-holders:Ernesto Corvi /*************************************************************************** Sprite/tile priority is quite complex in this game: it is handled both internally to the CUS29 chip, and externally to it. The bg tilemap is always behind everything. The CUS29 mixes two 8-bit inputs, one from sprites and one from the fg tilemap. 0xff is the transparent color. CUS29 also takes a PRI input, telling which of the two color inputs has priority. Additionally, sprite pixels of color >= 0xf0 always have priority. The priority bit comes from the tilemap RAM, but through an additional filter: sprite pixels of color < 0x80 act as a "cookie cut" mask, handled externally, which overload the PRI bit, making the sprite always have priority. The external RAM that holds this mask contains the OR of all sprite pixels drawn at a certain position, therefore when sprites overlap, it is sufficient for one of them to have color < 0x80 to promote priority of the frontmost sprite. This is used to draw the light in round 19. The CUS29 outputs an 8-bit pixel color, but only the bottom 7 bits are externally checked to determine whether it is transparent or not; therefore, both 0xff and 0x7f are transparent. This is again used to draw the light in round 19, because sprite color 0x7f will erase the tilemap and force it to be transparent. ***************************************************************************/ #include "emu.h" #include "includes/pacland.h" /*************************************************************************** Convert the color PROMs. Pacland has one 1024x8 and one 1024x4 palette PROM; and three 1024x8 lookup table PROMs (sprites, bg tiles, fg tiles). The palette has 1024 colors, but it is bank switched (4 banks) and only 256 colors are visible at a time. So, instead of creating a static palette, we modify it when the bank switching takes place. The color PROMs are connected to the RGB output this way: bit 7 -- 220 ohm resistor -- GREEN -- 470 ohm resistor -- GREEN -- 1 kohm resistor -- GREEN -- 2.2kohm resistor -- GREEN -- 220 ohm resistor -- RED -- 470 ohm resistor -- RED -- 1 kohm resistor -- RED bit 0 -- 2.2kohm resistor -- RED bit 3 -- 220 ohm resistor -- BLUE -- 470 ohm resistor -- BLUE -- 1 kohm resistor -- BLUE bit 0 -- 2.2kohm resistor -- BLUE ***************************************************************************/ void pacland_state::switch_palette() { int i; const uint8_t *color_prom = m_color_prom + 256 * m_palette_bank; for (i = 0;i < 256;i++) { int bit0,bit1,bit2,bit3; int r,g,b; bit0 = (color_prom[0] >> 0) & 0x01; bit1 = (color_prom[0] >> 1) & 0x01; bit2 = (color_prom[0] >> 2) & 0x01; bit3 = (color_prom[0] >> 3) & 0x01; r = 0x0e * bit0 + 0x1f * bit1 + 0x43 * bit2 + 0x8f * bit3; bit0 = (color_prom[0] >> 4) & 0x01; bit1 = (color_prom[0] >> 5) & 0x01; bit2 = (color_prom[0] >> 6) & 0x01; bit3 = (color_prom[0] >> 7) & 0x01; g = 0x0e * bit0 + 0x1f * bit1 + 0x43 * bit2 + 0x8f * bit3; bit0 = (color_prom[1024] >> 0) & 0x01; bit1 = (color_prom[1024] >> 1) & 0x01; bit2 = (color_prom[1024] >> 2) & 0x01; bit3 = (color_prom[1024] >> 3) & 0x01; b = 0x0e * bit0 + 0x1f * bit1 + 0x43 * bit2 + 0x8f * bit3; color_prom++; m_palette->set_indirect_color(i,rgb_t(r,g,b)); } } PALETTE_INIT_MEMBER(pacland_state, pacland) { const uint8_t *color_prom = memregion("proms")->base(); int i; m_color_prom = color_prom; /* we'll need this later */ /* skip the palette data, it will be initialized later */ color_prom += 2 * 0x400; /* color_prom now points to the beginning of the lookup table */ for (i = 0;i < 0x400;i++) palette.set_pen_indirect(m_gfxdecode->gfx(0)->colorbase() + i, *color_prom++); /* Background */ for (i = 0;i < 0x400;i++) palette.set_pen_indirect(m_gfxdecode->gfx(1)->colorbase() + i, *color_prom++); /* Sprites */ for (i = 0;i < 0x400;i++) palette.set_pen_indirect(m_gfxdecode->gfx(2)->colorbase() + i, *color_prom++); m_palette_bank = 0; switch_palette(); /* precalculate transparency masks for sprites */ m_transmask[0] = std::make_unique<uint32_t[]>(64); m_transmask[1] = std::make_unique<uint32_t[]>(64); m_transmask[2] = std::make_unique<uint32_t[]>(64); for (i = 0; i < 64; i++) { int palentry; /* start with no transparency */ m_transmask[0][i] = m_transmask[1][i] = m_transmask[2][i] = 0; /* iterate over all palette entries except the last one */ for (palentry = 0; palentry < 0x100; palentry++) { uint32_t mask = palette.transpen_mask(*m_gfxdecode->gfx(2), i, palentry); /* transmask[0] is a mask that is used to draw only high priority sprite pixels; thus, pens $00-$7F are opaque, and others are transparent */ if (palentry >= 0x80) m_transmask[0][i] |= mask; /* transmask[1] is a normal drawing masking with palette entries $7F and $FF transparent */ if ((palentry & 0x7f) == 0x7f) m_transmask[1][i] |= mask; /* transmask[2] is a mask of the topmost priority sprite pixels; thus pens $F0-$FE are opaque, and others are transparent */ if (palentry < 0xf0 || palentry == 0xff) m_transmask[2][i] |= mask; } } } /*************************************************************************** Callbacks for the TileMap code ***************************************************************************/ TILE_GET_INFO_MEMBER(pacland_state::get_bg_tile_info) { int offs = tile_index * 2; int attr = m_videoram2[offs + 1]; int code = m_videoram2[offs] + ((attr & 0x01) << 8); int color = ((attr & 0x3e) >> 1) + ((code & 0x1c0) >> 1); int flags = TILE_FLIPYX(attr >> 6); SET_TILE_INFO_MEMBER(1, code, color, flags); } TILE_GET_INFO_MEMBER(pacland_state::get_fg_tile_info) { int offs = tile_index * 2; int attr = m_videoram[offs + 1]; int code = m_videoram[offs] + ((attr & 0x01) << 8); int color = ((attr & 0x1e) >> 1) + ((code & 0x1e0) >> 1); int flags = TILE_FLIPYX(attr >> 6); tileinfo.category = (attr & 0x20) ? 1 : 0; tileinfo.group = color; SET_TILE_INFO_MEMBER(0, code, color, flags); } /*************************************************************************** Start the video hardware emulation. ***************************************************************************/ void pacland_state::video_start() { m_screen->register_screen_bitmap(m_sprite_bitmap); m_screen->register_screen_bitmap(m_fg_bitmap); m_fg_bitmap.fill(0xffff); m_bg_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(FUNC(pacland_state::get_bg_tile_info),this),TILEMAP_SCAN_ROWS,8,8,64,32); m_fg_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(FUNC(pacland_state::get_fg_tile_info),this),TILEMAP_SCAN_ROWS,8,8,64,32); m_bg_tilemap->set_scrolldx(3, 340); m_fg_tilemap->set_scrolldx(0, 336); /* scrolling portion needs an additional offset when flipped */ m_fg_tilemap->set_scroll_rows(32); /* create one group per color code; for each group, set the transparency mask to correspond to the pens that are 0x7f or 0xff */ assert(m_gfxdecode->gfx(0)->colors() <= TILEMAP_NUM_GROUPS); for (int color = 0; color < m_gfxdecode->gfx(0)->colors(); color++) { uint32_t mask = m_palette->transpen_mask(*m_gfxdecode->gfx(0), color, 0x7f); mask |= m_palette->transpen_mask(*m_gfxdecode->gfx(0), color, 0xff); m_fg_tilemap->set_transmask(color, mask, 0); } membank("bank1")->configure_entries(0, 8, memregion("maincpu")->base() + 0x10000, 0x2000); save_item(NAME(m_palette_bank)); save_item(NAME(m_scroll0)); save_item(NAME(m_scroll1)); } /*************************************************************************** Memory handlers ***************************************************************************/ WRITE8_MEMBER(pacland_state::videoram_w) { m_videoram[offset] = data; m_fg_tilemap->mark_tile_dirty(offset / 2); } WRITE8_MEMBER(pacland_state::videoram2_w) { m_videoram2[offset] = data; m_bg_tilemap->mark_tile_dirty(offset / 2); } WRITE8_MEMBER(pacland_state::scroll0_w) { m_scroll0 = data + 256 * offset; } WRITE8_MEMBER(pacland_state::scroll1_w) { m_scroll1 = data + 256 * offset; } WRITE8_MEMBER(pacland_state::bankswitch_w) { membank("bank1")->set_entry(data & 0x07); // pbc = data & 0x20; if (m_palette_bank != ((data & 0x18) >> 3)) { m_palette_bank = (data & 0x18) >> 3; switch_palette(); } } /*************************************************************************** Display refresh ***************************************************************************/ /* the sprite generator IC is the same as Mappy */ void pacland_state::draw_sprites(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect, int flip, int whichmask) { uint8_t *spriteram = m_spriteram + 0x780; uint8_t *spriteram_2 = spriteram + 0x800; uint8_t *spriteram_3 = spriteram_2 + 0x800; for (int offs = 0;offs < 0x80;offs += 2) { static const int gfx_offs[2][2] = { { 0, 1 }, { 2, 3 } }; int sprite = spriteram[offs] + ((spriteram_3[offs] & 0x80) << 1); int color = spriteram[offs+1] & 0x3f; int sx = (spriteram_2[offs+1]) + 0x100*(spriteram_3[offs+1] & 1) - 47; int sy = 256 - spriteram_2[offs] + 9; int flipx = (spriteram_3[offs] & 0x01); int flipy = (spriteram_3[offs] & 0x02) >> 1; int sizex = (spriteram_3[offs] & 0x04) >> 2; int sizey = (spriteram_3[offs] & 0x08) >> 3; int x,y; sprite &= ~sizex; sprite &= ~(sizey << 1); if (flip) { flipx ^= 1; flipy ^= 1; } sy -= 16 * sizey; sy = (sy & 0xff) - 32; // fix wraparound for (y = 0;y <= sizey;y++) { for (x = 0;x <= sizex;x++) { if (whichmask != 0) m_gfxdecode->gfx(2)->transmask(bitmap,cliprect, sprite + gfx_offs[y ^ (sizey * flipy)][x ^ (sizex * flipx)], color, flipx,flipy, sx + 16*x,sy + 16*y,m_transmask[whichmask][color]); else m_gfxdecode->gfx(2)->prio_transmask(bitmap,cliprect, sprite + gfx_offs[y ^ (sizey * flipy)][x ^ (sizex * flipx)], color, flipx,flipy, sx + 16*x,sy + 16*y, screen.priority(),0,m_transmask[whichmask][color]); } } } } void pacland_state::draw_fg(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect, int priority ) { /* draw tilemap transparently over it; this will leave invalid pens (0xffff) anywhere where the fg_tilemap should be transparent; note that we assume the fg_bitmap has been pre-erased to 0xffff */ m_fg_tilemap->draw(screen, m_fg_bitmap, cliprect, priority, 0); /* now copy the fg_bitmap to the destination wherever the sprite pixel allows */ for (int y = cliprect.min_y; y <= cliprect.max_y; y++) { const uint8_t *pri = &screen.priority().pix8(y); uint16_t *src = &m_fg_bitmap.pix16(y); uint16_t *dst = &bitmap.pix16(y); /* only copy if the priority bitmap is 0 (no high priority sprite) and the source pixel is not the invalid pen; also clear to 0xffff when finished */ for (int x = cliprect.min_x; x <= cliprect.max_x; x++) { uint16_t pix = src[x]; if (pix != 0xffff) { src[x] = 0xffff; if (pri[x] == 0) dst[x] = pix; } } } } uint32_t pacland_state::screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) { int flip = flip_screen(); for (int row = 5; row < 29; row++) m_fg_tilemap->set_scrollx(row, m_scroll0 - (flip ? 7 : 0)); m_bg_tilemap->set_scrollx(0, m_scroll1); /* draw high priority sprite pixels, setting priority bitmap to non-zero wherever there is a high-priority pixel; note that we draw to the bitmap which is safe because the bg_tilemap draw will overwrite everything */ screen.priority().fill(0x00, cliprect); draw_sprites(screen, bitmap, cliprect, flip, 0); /* draw background */ m_bg_tilemap->draw(screen, bitmap, cliprect, 0, 0); /* draw low priority fg tiles */ draw_fg(screen, bitmap, cliprect, 0); /* draw sprites with regular transparency */ draw_sprites(screen, bitmap, cliprect, flip, 1); /* draw high priority fg tiles */ draw_fg(screen, bitmap, cliprect, 1); /* draw sprite pixels with colortable values >= 0xf0, which have priority over all fg tiles */ m_sprite_bitmap.fill(0, cliprect); draw_sprites(screen, m_sprite_bitmap, cliprect, flip, 2); for (int y = cliprect.min_y; y <= cliprect.max_y; y++) { uint16_t *src = &m_sprite_bitmap.pix16(y); uint16_t *dst = &bitmap.pix16(y); for (int x = cliprect.min_x; x <= cliprect.max_x; x++) { uint16_t pix = src[x]; if (pix != 0 && dst[x] < 0x800) dst[x] = pix; } } return 0; }
12,683
5,452
// Copyright 2012 Google 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. #include "syzygy/pdb/mutators/add_named_stream_mutator.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "syzygy/core/unittest_util.h" #include "syzygy/pdb/pdb_byte_stream.h" #include "syzygy/pdb/pdb_reader.h" #include "syzygy/pdb/unittest_util.h" namespace pdb { namespace mutators { namespace { using testing::_; using testing::Invoke; using testing::Ref; using testing::Return; using testing::StrictMock; class MockAddNamedStreamMutator : public AddNamedStreamMutatorImpl<MockAddNamedStreamMutator> { public: static const char kMutatorName[]; MOCK_METHOD1(AddNamedStreams, bool(const PdbFile& pdb_file)); bool AddFooStream(const PdbFile& pdb_file) { scoped_refptr<PdbByteStream> stream(new PdbByteStream()); EXPECT_TRUE(stream->Init(reinterpret_cast<const uint8*>(kMutatorName), ::strlen(kMutatorName))); added_stream_ = stream; EXPECT_TRUE(SetNamedStream("foo", stream.get())); return true; } bool GetAndReplaceFooStream(const PdbFile& pdb_file) { scoped_refptr<PdbStream> foo = GetNamedStream("foo"); EXPECT_TRUE(foo.get() != NULL); scoped_refptr<PdbByteStream> stream(new PdbByteStream()); EXPECT_TRUE(stream->Init(foo)); added_stream_ = stream; EXPECT_FALSE(SetNamedStream("foo", stream.get())); return true; } scoped_refptr<PdbStream> added_stream_; }; const char MockAddNamedStreamMutator::kMutatorName[] = "MockAddNamedStreamMutator"; class AddNamedStreamMutatorTest : public testing::Test { public: virtual void SetUp() OVERRIDE { testing::Test::SetUp(); } void ReadActualPdb() { base::FilePath pdb_path = testing::GetSrcRelativePath(testing::kTestPdbFilePath); PdbReader pdb_reader; EXPECT_TRUE(pdb_reader.Read(pdb_path, &pdb_file_)); } void CheckFooStreamAdded() { // Read the named stream map and ensure the stream was properly added. PdbInfoHeader70 header = {}; NameStreamMap name_stream_map; ASSERT_TRUE(pdb::ReadHeaderInfoStream(pdb_file_, &header, &name_stream_map)); ASSERT_TRUE(name_stream_map.count("foo")); size_t stream_id = name_stream_map["foo"]; ASSERT_GT(pdb_file_.StreamCount(), stream_id); scoped_refptr<PdbStream> stream(pdb_file_.GetStream(stream_id)); ASSERT_EQ(mutator_.added_stream_.get(), stream.get()); } StrictMock<MockAddNamedStreamMutator> mutator_; PdbFile pdb_file_; }; } // namespace TEST_F(AddNamedStreamMutatorTest, FailsWithNoHeaderInfoStream) { EXPECT_FALSE(mutator_.MutatePdb(&pdb_file_)); } TEST_F(AddNamedStreamMutatorTest, FailsIfAddNamedStreamsFails) { ASSERT_NO_FATAL_FAILURE(testing::InitMockPdbFile(&pdb_file_)); EXPECT_CALL(mutator_, AddNamedStreams(Ref(pdb_file_))).Times(1). WillOnce(Return(false)); EXPECT_FALSE(mutator_.MutatePdb(&pdb_file_)); } TEST_F(AddNamedStreamMutatorTest, SucceedsWithNoInsertion) { ASSERT_NO_FATAL_FAILURE(testing::InitMockPdbFile(&pdb_file_)); EXPECT_CALL(mutator_, AddNamedStreams(Ref(pdb_file_))).Times(1). WillOnce(Return(true)); EXPECT_TRUE(mutator_.MutatePdb(&pdb_file_)); } TEST_F(AddNamedStreamMutatorTest, SucceedsWithInsertionAndReplacement) { ASSERT_NO_FATAL_FAILURE(testing::InitMockPdbFile(&pdb_file_)); EXPECT_CALL(mutator_, AddNamedStreams(Ref(pdb_file_))).Times(1). WillOnce(Invoke(&mutator_, &MockAddNamedStreamMutator::AddFooStream)); EXPECT_TRUE(mutator_.MutatePdb(&pdb_file_)); ASSERT_NO_FATAL_FAILURE(CheckFooStreamAdded()); EXPECT_CALL(mutator_, AddNamedStreams(Ref(pdb_file_))).Times(1). WillOnce(Invoke(&mutator_, &MockAddNamedStreamMutator::GetAndReplaceFooStream)); EXPECT_TRUE(mutator_.MutatePdb(&pdb_file_)); ASSERT_NO_FATAL_FAILURE(CheckFooStreamAdded()); } } // namespace mutators } // namespace pdb
4,455
1,629
#define SASS_SOURCE_MAP #include <vector> #ifndef SASS_MAPPING #include "mapping.hpp" #endif #ifndef SASS_AST #include "ast.hpp" #endif #ifndef SASSS_BASE64VLQ #include "base64vlq.hpp" #endif namespace Sass { using std::vector; struct Context; class SourceMap { public: vector<string> files; SourceMap(const string& file); void new_line(); void remove_line(); void update_column(const string& str); void update_column(); void add_mapping(AST_Node* node); string generate_source_map(Context* ctx); private: string serialize_mappings(); vector<Mapping> mappings; Position current_position; string file; Base64VLQ base64vlq; }; }
738
271
#if defined(KOKKOSKERNELS_INST_FLOAT) TEST_F( TestCategory, batched_scalar_team_gemm_nt_nt_float_float ) { typedef ::Test::ParamTag<Trans::NoTranspose,Trans::NoTranspose> param_tag_type; typedef Algo::Gemm::Blocked algo_tag_type; test_batched_gemm<TestExecSpace,float,float,param_tag_type,algo_tag_type>(); } TEST_F( TestCategory, batched_scalar_team_gemm_t_nt_float_float ) { typedef ::Test::ParamTag<Trans::Transpose,Trans::NoTranspose> param_tag_type; typedef Algo::Gemm::Blocked algo_tag_type; test_batched_gemm<TestExecSpace,float,float,param_tag_type,algo_tag_type>(); } TEST_F( TestCategory, batched_scalar_team_gemm_nt_t_float_float ) { typedef ::Test::ParamTag<Trans::NoTranspose,Trans::Transpose> param_tag_type; typedef Algo::Gemm::Blocked algo_tag_type; test_batched_gemm<TestExecSpace,float,float,param_tag_type,algo_tag_type>(); } TEST_F( TestCategory, batched_scalar_team_gemm_t_t_float_float ) { typedef ::Test::ParamTag<Trans::Transpose,Trans::Transpose> param_tag_type; typedef Algo::Gemm::Blocked algo_tag_type; test_batched_gemm<TestExecSpace,float,float,param_tag_type,algo_tag_type>(); } #endif #if defined(KOKKOSKERNELS_INST_DOUBLE) TEST_F( TestCategory, batched_scalar_team_gemm_nt_nt_double_double ) { typedef ::Test::ParamTag<Trans::NoTranspose,Trans::NoTranspose> param_tag_type; typedef Algo::Gemm::Blocked algo_tag_type; test_batched_gemm<TestExecSpace,double,double,param_tag_type,algo_tag_type>(); } TEST_F( TestCategory, batched_scalar_team_gemm_t_nt_double_double ) { typedef ::Test::ParamTag<Trans::Transpose,Trans::NoTranspose> param_tag_type; typedef Algo::Gemm::Blocked algo_tag_type; test_batched_gemm<TestExecSpace,double,double,param_tag_type,algo_tag_type>(); } TEST_F( TestCategory, batched_scalar_team_gemm_nt_t_double_double ) { typedef ::Test::ParamTag<Trans::NoTranspose,Trans::Transpose> param_tag_type; typedef Algo::Gemm::Blocked algo_tag_type; test_batched_gemm<TestExecSpace,double,double,param_tag_type,algo_tag_type>(); } TEST_F( TestCategory, batched_scalar_team_gemm_t_t_double_double ) { typedef ::Test::ParamTag<Trans::Transpose,Trans::Transpose> param_tag_type; typedef Algo::Gemm::Blocked algo_tag_type; test_batched_gemm<TestExecSpace,double,double,param_tag_type,algo_tag_type>(); } #endif
2,302
893
// construction/destruction: template<class TSig, class TPar> rsLinkwitzRileyCrossOver<TSig, TPar>::rsLinkwitzRileyCrossOver(int newMaxButterworthOrder) : lowpass1(newMaxButterworthOrder/2) , lowpass2(newMaxButterworthOrder/2) , sumAllpass(newMaxButterworthOrder/2) { rsAssert( newMaxButterworthOrder >= 1 ); // filter of zero or negative order? no such thing! maxButterworthOrder = newMaxButterworthOrder; sampleRate = 44100.0; crossoverFrequency = 1000.0; butterworthOrder = rsMin(2, maxButterworthOrder); updateFilterCoefficients(); } // setup: template<class TSig, class TPar> void rsLinkwitzRileyCrossOver<TSig, TPar>::setSampleRate(TPar newSampleRate) { if( newSampleRate > 0.0 && newSampleRate != sampleRate ) { sampleRate = newSampleRate; updateFilterCoefficients(); } } template<class TSig, class TPar> void rsLinkwitzRileyCrossOver<TSig, TPar>::setCrossoverFrequency(TPar newCrossoverFrequency) { if( newCrossoverFrequency <= 20000.0 ) crossoverFrequency = newCrossoverFrequency; updateFilterCoefficients(); } template<class TSig, class TPar> void rsLinkwitzRileyCrossOver<TSig, TPar>::setSlope(int newSlope) { rsAssert( newSlope%12 == 0 && newSlope >= 12 ); // slope must be a multiple of 12 dB/oct setButterworthOrder(newSlope/12); } template<class TSig, class TPar> void rsLinkwitzRileyCrossOver<TSig, TPar>::setButterworthOrder(int newOrder) { if( newOrder >= 1 && newOrder <= maxButterworthOrder ) butterworthOrder = newOrder; updateFilterCoefficients(); } // inquiry: template<class TSig, class TPar> void rsLinkwitzRileyCrossOver<TSig, TPar>::getLowpassMagnitudeResponse(TPar* frequencies, TPar* magnitudes, int numBins, bool inDecibels, bool accumulate) { if( accumulate == false ) { if( inDecibels == true ) rsArrayTools::fillWithValue(magnitudes, numBins, TPar(0)); else rsArrayTools::fillWithValue(magnitudes, numBins, TPar(1)); } lowpass1.getMagnitudeResponse(frequencies, sampleRate, magnitudes, numBins, true, true); lowpass2.getMagnitudeResponse(frequencies, sampleRate, magnitudes, numBins, true, true); } template<class TSig, class TPar> void rsLinkwitzRileyCrossOver<TSig, TPar>::getLowpassFrequencyResponse(TPar* frequencies, Complex* H, int numBins, bool accumulate) { if( accumulate == false ) rsArrayTools::fillWithValue(H, numBins, Complex(1.0)); TPar* w = new TPar[numBins]; rsArrayTools::copy(frequencies, w, numBins); rsArrayTools::scale(w, w, numBins, TPar(2*PI)/sampleRate); lowpass1.getFrequencyResponse(w, H, numBins, rsFilterAnalyzer<TPar>::MULTIPLICATIVE_ACCUMULATION); lowpass2.getFrequencyResponse(w, H, numBins, rsFilterAnalyzer<TPar>::MULTIPLICATIVE_ACCUMULATION); delete[] w; } template<class TSig, class TPar> void rsLinkwitzRileyCrossOver<TSig, TPar>::getHighpassMagnitudeResponse(TPar* frequencies, TPar* magnitudes, int numBins, bool inDecibels, bool accumulate) { Complex* H = new Complex[numBins]; getHighpassFrequencyResponse(frequencies, H, numBins, false); if( accumulate == true ) { if( inDecibels == true ) { for(int k=0; k<numBins; k++) magnitudes[k] += rsAmpToDb(abs(H[k])); } else { for(int k=0; k<numBins; k++) magnitudes[k] *= abs(H[k]); }} else { if( inDecibels == true ) { for(int k=0; k<numBins; k++) magnitudes[k] = rsAmpToDb(abs(H[k])); } else { for(int k=0; k<numBins; k++) magnitudes[k] = abs(H[k]); }} delete[] H; } template<class TSig, class TPar> void rsLinkwitzRileyCrossOver<TSig, TPar>::getHighpassFrequencyResponse(TPar* frequencies, Complex* H, int numBins, bool accumulate) { TPar* w = new TPar[numBins]; rsArrayTools::copy(frequencies, w, numBins); rsArrayTools::scale(w, w, numBins, TPar(2*PI)/sampleRate); Complex *tmpLowpass = new Complex[numBins]; getLowpassFrequencyResponse(frequencies, tmpLowpass, numBins, false); Complex *tmpAllpass = new Complex[numBins]; sumAllpass.getFrequencyResponse(w, tmpAllpass, numBins); if( accumulate == false ) rsArrayTools::subtract(tmpAllpass, tmpLowpass, H, numBins); else { rsArrayTools::subtract(tmpAllpass, tmpLowpass, tmpAllpass, numBins); // tmpAllpass is now the highpass-response rsArrayTools::multiply(H, tmpAllpass, H, numBins); } delete[] tmpLowpass; delete[] tmpAllpass; delete[] w; } // others: template<class TSig, class TPar> void rsLinkwitzRileyCrossOver<TSig, TPar>::resetBuffers() { lowpass1.reset(); lowpass2.reset(); sumAllpass.reset(); } template<class TSig, class TPar> void rsLinkwitzRileyCrossOver<TSig, TPar>::updateFilterCoefficients() { // create and set up a filter-designer object: rsInfiniteImpulseResponseDesigner<TPar> designer; designer.setSampleRate(sampleRate); designer.setApproximationMethod(rsPrototypeDesigner<TPar>::BUTTERWORTH); designer.setPrototypeOrder(butterworthOrder); designer.setFrequency(crossoverFrequency); // \todo keep this object around as a member to avoid unnecessary re-calculations of the // prototype poles // design the lowpasses: designer.setMode(rsInfiniteImpulseResponseDesigner<TPar>::LOWPASS); lowpass1.setOrder(butterworthOrder); designer.getBiquadCascadeCoefficients(lowpass1.getAddressB0(), lowpass1.getAddressB1(), lowpass1.getAddressB2(), lowpass1.getAddressA1(), lowpass1.getAddressA2() ); lowpass2.copySettingsFrom(&lowpass1); // obtain the allpass: sumAllpass.copySettingsFrom(&lowpass1); sumAllpass.turnIntoAllpass(); }
5,528
2,066
/* A group of Xtreme soldiers are fighting a tough war but are unfortunately trapped within the enemy territory. But don't worry, they managed to find NN hideouts along a long battle line. The hideouts are numbered 11 to NN. Initially there are S_iS ​i ​​ soldiers at hideout ii. There is a safe rendezvous location. Each hideout has one path to the rendezvous location. However, since the enemies are heavily patrolling the area, that path between the rendezvous location and hideout ii cannot be taken unless the weather around hideout ii is foggy. You are planning a rescue mission to safely evacuate these soldiers in the next DD days. You are able to forecast that on day ii, the hideouts numbered L_i, L_i+1, ...R_{i}L ​i ​​ ,L ​i ​​ +1,...R ​i ​​ will have foggy weather, and will be able to gather at the rendevouz location. You will send a vehicle that can evacuate V_iV ​i ​​ soldiers. The remaining soldiers must go back to the hideouts. The soldiers do not necessarily need to go back to the hideout where they came from. Instead, they can go to any hideout with a number between L_iL ​i ​​ and R_iR ​i ​​ . Each hideout may have an arbitrary number of soldiers at any time, including zero. If you coordinate the movements of the soldiers carefully, what is the maximum total number of soldiers you can evacuate? Standard input There is a single integer NN on the first line, the number of hideouts. The second line has NN integer. The ii-th integer is S_iS ​i ​​ . The next line has a single integer DD, the number of days. Each of the next DD lines has three integers L_iL ​i ​​ , R_iR ​i ​​ , and V_iV ​i ​​ . They indicate that on day ii hideouts L_i, L_i+1, ... R_iL ​i ​​ ,L ​i ​​ +1,...R ​i ​​ will have foggy weather, and you will send a vehicle to the rendezvous location that can evacuate V_iV ​i ​​ soldiers from these hideouts. Standard output Output the maximum total number of soldiers you can evacuate. Constraints and notes 1 \leq N \leq 10^51≤N≤10 ​5 ​​ 0 \leq S_i \leq 10^40≤S ​i ​​ ≤10 ​4 ​​ 1 \leq D \leq 5\,0001≤D≤5000 1 \leq L_i \leq R_i \leq N1≤L ​i ​​ ≤R ​i ​​ ≤N 1 \leq V_i \leq 10^91≤V ​i ​​ ≤10 ​9 ​​ For 30\%30% of the test data, D \leq 50D≤50 and N \leq 50N≤50. For 60\%60% of the test data, D \leq 50D≤50. Input Output Explanation 4 5 4 3 2 4 1 2 4 1 1 3 2 4 1 3 3 4 12 At the beginning, the number of soldiers at the hideouts are [5, 4, 3, 2][5,4,3,2]. On day 11, there are 99 soldiers from hideout 11 and 22 that can be evacuated. The vehicle takes 44, and the 33 of the 55 remaining soldiers can go to hideout 11 to wait for the vehicle on day 22. The other 22 remaining soldiers go to hideout 22. The number of soldiers at the hideouts are therefore [3, 2, 3, 2][3,2,3,2]. After day 22, the numbers become [0, 2, 3, 2][0,2,3,2]. On day 33, we can evacuate one solder from hideout 22, and let the other soldier there go to hideout 33. The numbers of soldiers at the hideouts become [0, 0, 4, 2][0,0,4,2]. On the last day, the 44 soldiers at hideout 33 will be evacuated. 3 7 8 7 6 1 2 1 2 3 1 3 3 9 2 3 1 1 2 1 1 1 9 22 At the beginning, we have [7, 8, 7][7,8,7] soldiers. In the first two days, two soldiers can be evacuated, and at the same time all soldiers can move to hideout 33, getting [0, 0, 20][0,0,20] by the end of day 22. On day 33 we can evacuate 99 soldiers, getting [0, 0, 11][0,0,11]. Then on day 44 and 55 two soldiers can be evacuated, and at the same time all soldiers can move to hideout 11, getting [9, 0, 0][9,0,0]. On the last day all the remaining soldiers can be evacuated. */ #include <bits/stdc++.h> using namespace std; typedef long long int ll; int main(){ int n; cin >> n; vector<int> soldierCount; for (int i = 0; i < n; i++){ int x; cin >> x; soldierCount.push_back(x); } int d; cin >> d; vector<int> left; vector<int> right; vector<int> rescueLimit; int res = 0; for (int i = 0; i < d; i++){ int l, r, v; cin >> l >> r >> v; left.push_back(l); right.push_back(r); rescueLimit.push_back(v); res += v; } res -= rescueLimit[0]; int maxRescued = soldierCount[left[0]-1]; for (int i = left[0]-1; i < right[0]; i++){ maxRescued = maxRescued < soldierCount[i]? soldierCount[i]:maxRescued; } int rescuedFirst = rescueLimit[0] < maxRescued? rescueLimit[0]:maxRescued; res += rescuedFirst; cout << res; return 0; }
4,473
1,701
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- * vim: sw=2 ts=8 et : */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "VRManagerChild.h" #include "VRManagerParent.h" #include "VRDeviceProxy.h" #include "VRDeviceProxyOrientationFallBack.h" #include "mozilla/StaticPtr.h" #include "mozilla/layers/CompositorParent.h" // for CompositorParent #include "mozilla/dom/Navigator.h" namespace mozilla { namespace gfx { static StaticRefPtr<VRManagerChild> sVRManagerChildSingleton; static StaticRefPtr<VRManagerParent> sVRManagerParentSingleton; void ReleaseVRManagerParentSingleton() { sVRManagerParentSingleton = nullptr; } VRManagerChild::VRManagerChild() { MOZ_COUNT_CTOR(VRManagerChild); MOZ_ASSERT(NS_IsMainThread()); } VRManagerChild::~VRManagerChild() { MOZ_ASSERT(NS_IsMainThread()); MOZ_COUNT_DTOR(VRManagerChild); Transport* trans = GetTransport(); if (trans) { MOZ_ASSERT(XRE_GetIOMessageLoop()); XRE_GetIOMessageLoop()->PostTask(FROM_HERE, new DeleteTask<Transport>(trans)); } } /*static*/ VRManagerChild* VRManagerChild::Get() { MOZ_ASSERT(sVRManagerChildSingleton); return sVRManagerChildSingleton; } /*static*/ VRManagerChild* VRManagerChild::StartUpInChildProcess(Transport* aTransport, ProcessId aOtherPid) { MOZ_ASSERT(NS_IsMainThread()); // There's only one VRManager per child process. MOZ_ASSERT(!sVRManagerChildSingleton); RefPtr<VRManagerChild> child(new VRManagerChild()); if (!child->Open(aTransport, aOtherPid, XRE_GetIOMessageLoop(), ipc::ChildSide)) { NS_RUNTIMEABORT("Couldn't Open() Compositor channel."); return nullptr; } sVRManagerChildSingleton = child; return sVRManagerChildSingleton; } /*static*/ void VRManagerChild::StartUpSameProcess() { NS_ASSERTION(NS_IsMainThread(), "Should be on the main Thread!"); if (sVRManagerChildSingleton == nullptr) { sVRManagerChildSingleton = new VRManagerChild(); sVRManagerParentSingleton = VRManagerParent::CreateSameProcess(); sVRManagerChildSingleton->Open(sVRManagerParentSingleton->GetIPCChannel(), mozilla::layers::CompositorParent::CompositorLoop(), mozilla::ipc::ChildSide); } } /*static*/ void VRManagerChild::ShutDown() { MOZ_ASSERT(NS_IsMainThread()); if (sVRManagerChildSingleton) { sVRManagerChildSingleton->Destroy(); sVRManagerChildSingleton = nullptr; } } /*static*/ void VRManagerChild::DeferredDestroy(RefPtr<VRManagerChild> aVRManagerChild) { aVRManagerChild->Close(); } void VRManagerChild::Destroy() { // This must not be called from the destructor! MOZ_ASSERT(mRefCnt != 0); // Keep ourselves alive until everything has been shut down RefPtr<VRManagerChild> selfRef = this; // The DeferredDestroyVRManager task takes ownership of // the VRManagerChild and will release it when it runs. MessageLoop::current()->PostTask(FROM_HERE, NewRunnableFunction(DeferredDestroy, selfRef)); } bool VRManagerChild::RecvUpdateDeviceInfo(nsTArray<VRDeviceUpdate>&& aDeviceUpdates) { // mDevices could be a hashed container for more scalability, but not worth // it now as we expect < 10 entries. nsTArray<RefPtr<VRDeviceProxy> > devices; for (auto& deviceUpdate: aDeviceUpdates) { bool isNewDevice = true; for (auto& device: mDevices) { if (device->GetDeviceInfo().GetDeviceID() == deviceUpdate.mDeviceInfo.GetDeviceID()) { device->UpdateDeviceInfo(deviceUpdate); devices.AppendElement(device); isNewDevice = false; break; } } if (isNewDevice) { if (deviceUpdate.mDeviceInfo.GetUseMainThreadOrientation()) { devices.AppendElement(new VRDeviceProxyOrientationFallBack(deviceUpdate)); } else { devices.AppendElement(new VRDeviceProxy(deviceUpdate)); } } } mDevices = devices; for (auto& nav: mNavigatorCallbacks) { nav->NotifyVRDevicesUpdated(); } mNavigatorCallbacks.Clear(); return true; } bool VRManagerChild::RecvUpdateDeviceSensors(nsTArray<VRSensorUpdate>&& aDeviceSensorUpdates) { // mDevices could be a hashed container for more scalability, but not worth // it now as we expect < 10 entries. for (auto& sensorUpdate: aDeviceSensorUpdates) { for (auto& device: mDevices) { if (device->GetDeviceInfo().GetDeviceID() == sensorUpdate.mDeviceID) { device->UpdateSensorState(sensorUpdate.mSensorState); break; } } } return true; } bool VRManagerChild::GetVRDevices(nsTArray<RefPtr<VRDeviceProxy> >& aDevices) { aDevices = mDevices; return true; } bool VRManagerChild::RefreshVRDevicesWithCallback(dom::Navigator* aNavigator) { bool success = SendRefreshDevices(); if (success) { mNavigatorCallbacks.AppendElement(aNavigator); } return success; } } // namespace gfx } // namespace mozilla
5,094
1,711
/* GUIDO Library Copyright (C) 2003--2006 Grame This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Grame Research Laboratory, 11, cours de Verdun Gensoul 69002 Lyon - France research@grame.fr */ ///////////////////////////////////////////////////////////////// /// /// MacOS X Quartz 2D implementation of VGDevice. /// /// perfs (G3-350): Bach-Inv1.gmn: parse: 240ms, draw: 670ms ///////////////////////////////////////////////////////////////// #include <iostream> using namespace std; #include "GMemoryDeviceOSX.h" // -------------------------------------------------------------- GMemoryDeviceOSX::GMemoryDeviceOSX( int inWidth, int inHeight, VGSystem* sys ) :GDeviceOSX(inWidth, inHeight, sys), mOffscreen(0) { mContext = CreateBitmapContext(inWidth, inHeight); Init(); } // -------------------------------------------------------------- GMemoryDeviceOSX::~GMemoryDeviceOSX() { if (mContext) ::CGContextRelease(mContext); delete [] (char *)mOffscreen; } // -------------------------------------------------------------- void GMemoryDeviceOSX::PutImage (CGImageRef img) { size_t h = CGImageGetHeight (img); size_t w = CGImageGetWidth (img); NotifySize (w, h); CGRect rect = ::CGRectMake (0, 0, w, h); ::CGContextSaveGState (mContext); ::CGContextTranslateCTM (mContext, 0, h); ::CGContextScaleCTM (mContext, 1.0f, -1.0f); ::CGContextDrawImage (mContext, rect, img); ::CGContextRestoreGState (mContext); } // -------------------------------------------------------------- void GMemoryDeviceOSX::NotifySize( int inWidth, int inHeight ) { // pixmap is updated only if input size differs from actual if ((mPhysicalWidth != inWidth) || (mPhysicalHeight != inHeight)) { // delete previous bitmap ::CGContextRelease(mContext); // allocates a new one mContext = CreateBitmapContext(inWidth, inHeight); // update attributes each time mPhysicalWidth = inWidth; mPhysicalHeight = inHeight; // Update context Init(); } } // -------------------------------------------------------------- void* GMemoryDeviceOSX::GetBitMapPixels() const { return ::CGBitmapContextGetData(mContext); } // -------------------------------------------------------------- CGContextRef GMemoryDeviceOSX::CreateBitmapContext(int inWidth, int inHeight) { const int componentsPerPixel = 4; const int bitsPerComponent = 8; const int bytesPerRow = inWidth * componentsPerPixel; if (mOffscreen) delete [] (char *)mOffscreen; mOffscreen = new char[inHeight * bytesPerRow]; if (mOffscreen == NULL) return NULL; CGContextRef context = ::CGBitmapContextCreate( mOffscreen, (size_t)inWidth, (size_t)inHeight, bitsPerComponent, bytesPerRow, mColorSpace, kCGImageAlphaPremultipliedLast); if (context == NULL) { delete [] (char *)mOffscreen; mOffscreen = 0; } return context; }
3,056
1,061
/* * Copyright (C) 2010 Apple Inc. All rights reserved. * Copyright (C) 2017 Sony Interactive Entertainment Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "WebPage.h" #include "EditorState.h" #include "WebEvent.h" #include "WebFrame.h" #include "WebPageProxyMessages.h" #include "WebProcess.h" #include <WebCore/BackForwardController.h> #include <WebCore/Editor.h> #include <WebCore/EventHandler.h> #include <WebCore/EventNames.h> #include <WebCore/FocusController.h> #include <WebCore/Frame.h> #include <WebCore/FrameView.h> #include <WebCore/KeyboardEvent.h> #include <WebCore/NotImplemented.h> #include <WebCore/Page.h> #include <WebCore/PlatformKeyboardEvent.h> #include <WebCore/Settings.h> #include <WebCore/SharedBuffer.h> #include <WebCore/UserAgent.h> #include <WebCore/WindowsKeyboardCodes.h> using namespace WebCore; namespace WebKit { void WebPage::platformInitialize() { } void WebPage::platformDetach() { } void WebPage::platformEditorState(Frame& frame, EditorState& result, IncludePostLayoutDataHint shouldIncludePostLayoutData) const { } bool WebPage::performDefaultBehaviorForKeyEvent(const WebKeyboardEvent& keyboardEvent) { if (keyboardEvent.type() != WebEvent::KeyDown && keyboardEvent.type() != WebEvent::RawKeyDown) return false; switch (keyboardEvent.windowsVirtualKeyCode()) { case VK_SPACE: scroll(m_page.get(), keyboardEvent.shiftKey() ? ScrollUp : ScrollDown, ScrollByPage); break; case VK_LEFT: scroll(m_page.get(), ScrollLeft, ScrollByLine); break; case VK_RIGHT: scroll(m_page.get(), ScrollRight, ScrollByLine); break; case VK_UP: scroll(m_page.get(), ScrollUp, ScrollByLine); break; case VK_DOWN: scroll(m_page.get(), ScrollDown, ScrollByLine); break; case VK_HOME: scroll(m_page.get(), ScrollUp, ScrollByDocument); break; case VK_END: scroll(m_page.get(), ScrollDown, ScrollByDocument); break; case VK_PRIOR: scroll(m_page.get(), ScrollUp, ScrollByPage); break; case VK_NEXT: scroll(m_page.get(), ScrollDown, ScrollByPage); break; default: return false; } return true; } bool WebPage::platformCanHandleRequest(const ResourceRequest&) { notImplemented(); return false; } String WebPage::platformUserAgent(const URL& url) const { if (url.isNull() || !m_page->settings().needsSiteSpecificQuirks()) return String(); return WebCore::standardUserAgentForURL(url); } static const unsigned CtrlKey = 1 << 0; static const unsigned AltKey = 1 << 1; static const unsigned ShiftKey = 1 << 2; struct KeyDownEntry { unsigned virtualKey; unsigned modifiers; const char* name; }; struct KeyPressEntry { unsigned charCode; unsigned modifiers; const char* name; }; static const KeyDownEntry keyDownEntries[] = { { VK_LEFT, 0, "MoveLeft" }, { VK_LEFT, ShiftKey, "MoveLeftAndModifySelection" }, { VK_LEFT, CtrlKey, "MoveWordLeft" }, { VK_LEFT, CtrlKey | ShiftKey, "MoveWordLeftAndModifySelection" }, { VK_RIGHT, 0, "MoveRight" }, { VK_RIGHT, ShiftKey, "MoveRightAndModifySelection" }, { VK_RIGHT, CtrlKey, "MoveWordRight" }, { VK_RIGHT, CtrlKey | ShiftKey, "MoveWordRightAndModifySelection" }, { VK_UP, 0, "MoveUp" }, { VK_UP, ShiftKey, "MoveUpAndModifySelection" }, { VK_PRIOR, ShiftKey, "MovePageUpAndModifySelection" }, { VK_DOWN, 0, "MoveDown" }, { VK_DOWN, ShiftKey, "MoveDownAndModifySelection" }, { VK_NEXT, ShiftKey, "MovePageDownAndModifySelection" }, { VK_PRIOR, 0, "MovePageUp" }, { VK_NEXT, 0, "MovePageDown" }, { VK_HOME, 0, "MoveToBeginningOfLine" }, { VK_HOME, ShiftKey, "MoveToBeginningOfLineAndModifySelection" }, { VK_HOME, CtrlKey, "MoveToBeginningOfDocument" }, { VK_HOME, CtrlKey | ShiftKey, "MoveToBeginningOfDocumentAndModifySelection" }, { VK_END, 0, "MoveToEndOfLine" }, { VK_END, ShiftKey, "MoveToEndOfLineAndModifySelection" }, { VK_END, CtrlKey, "MoveToEndOfDocument" }, { VK_END, CtrlKey | ShiftKey, "MoveToEndOfDocumentAndModifySelection" }, { VK_BACK, 0, "DeleteBackward" }, { VK_BACK, ShiftKey, "DeleteBackward" }, { VK_DELETE, 0, "DeleteForward" }, { VK_BACK, CtrlKey, "DeleteWordBackward" }, { VK_DELETE, CtrlKey, "DeleteWordForward" }, { 'B', CtrlKey, "ToggleBold" }, { 'I', CtrlKey, "ToggleItalic" }, { VK_ESCAPE, 0, "Cancel" }, { VK_OEM_PERIOD, CtrlKey, "Cancel" }, { VK_TAB, 0, "InsertTab" }, { VK_TAB, ShiftKey, "InsertBacktab" }, { VK_RETURN, 0, "InsertNewline" }, { VK_RETURN, CtrlKey, "InsertNewline" }, { VK_RETURN, AltKey, "InsertNewline" }, { VK_RETURN, ShiftKey, "InsertNewline" }, { VK_RETURN, AltKey | ShiftKey, "InsertNewline" }, // It's not quite clear whether clipboard shortcuts and Undo/Redo should be handled // in the application or in WebKit. We chose WebKit. { 'C', CtrlKey, "Copy" }, { 'V', CtrlKey, "Paste" }, { 'X', CtrlKey, "Cut" }, { 'A', CtrlKey, "SelectAll" }, { VK_INSERT, CtrlKey, "Copy" }, { VK_DELETE, ShiftKey, "Cut" }, { VK_INSERT, ShiftKey, "Paste" }, { 'Z', CtrlKey, "Undo" }, { 'Z', CtrlKey | ShiftKey, "Redo" }, }; static const KeyPressEntry keyPressEntries[] = { { '\t', 0, "InsertTab" }, { '\t', ShiftKey, "InsertBacktab" }, { '\r', 0, "InsertNewline" }, { '\r', CtrlKey, "InsertNewline" }, { '\r', AltKey, "InsertNewline" }, { '\r', ShiftKey, "InsertNewline" }, { '\r', AltKey | ShiftKey, "InsertNewline" }, }; const char* WebPage::interpretKeyEvent(const WebCore::KeyboardEvent* evt) { ASSERT(evt->type() == eventNames().keydownEvent || evt->type() == eventNames().keypressEvent); static HashMap<int, const char*>* keyDownCommandsMap = 0; static HashMap<int, const char*>* keyPressCommandsMap = 0; if (!keyDownCommandsMap) { keyDownCommandsMap = new HashMap<int, const char*>; keyPressCommandsMap = new HashMap<int, const char*>; for (size_t i = 0; i < WTF_ARRAY_LENGTH(keyDownEntries); ++i) keyDownCommandsMap->set(keyDownEntries[i].modifiers << 16 | keyDownEntries[i].virtualKey, keyDownEntries[i].name); for (size_t i = 0; i < WTF_ARRAY_LENGTH(keyPressEntries); ++i) keyPressCommandsMap->set(keyPressEntries[i].modifiers << 16 | keyPressEntries[i].charCode, keyPressEntries[i].name); } unsigned modifiers = 0; if (evt->shiftKey()) modifiers |= ShiftKey; if (evt->altKey()) modifiers |= AltKey; if (evt->ctrlKey()) modifiers |= CtrlKey; if (evt->type() == eventNames().keydownEvent) { int mapKey = modifiers << 16 | evt->keyCode(); return mapKey ? keyDownCommandsMap->get(mapKey) : 0; } int mapKey = modifiers << 16 | evt->charCode(); return mapKey ? keyPressCommandsMap->get(mapKey) : 0; } bool WebPage::handleEditingKeyboardEvent(WebCore::KeyboardEvent* event) { auto* frame = downcast<Node>(event->target())->document().frame(); ASSERT(frame); auto* keyEvent = event->underlyingPlatformEvent(); if (!keyEvent || keyEvent->isSystemKey()) // Do not treat this as text input if it's a system key event. return false; auto command = frame->editor().command(interpretKeyEvent(event)); if (keyEvent->type() == PlatformEvent::RawKeyDown) { // WebKit doesn't have enough information about mode to decide // how commands that just insert text if executed via Editor // should be treated, so we leave it upon WebCore to either // handle them immediately (e.g. Tab that changes focus) or // let a keypress event be generated (e.g. Tab that inserts a // Tab character, or Enter). return !command.isTextInsertion() && command.execute(event); } if (command.execute(event)) return true; // Don't insert null or control characters as they can result in unexpected behaviour. if (event->charCode() < ' ') return false; return frame->editor().insertText(keyEvent->text(), event); } } // namespace WebKit
10,214
3,441
#include "mid_exceptions.h" jclass jRuntimeException_class; void safeThrowJavaException(JNIEnv *env, jclass exceptionCls, const char *msg) { if (!env->ExceptionCheck()) { env->ThrowNew(exceptionCls, msg); } }
227
76
// Copyright 2014, Additive Regularization of Topic Models. #include "artm/core/node_controller.h" #include "glog/logging.h" #include "artm/core/node_controller_service_impl.h" #include "artm/core/exceptions.h" #include "artm/core/helpers.h" #include "artm/core/zmq_context.h" namespace artm { namespace core { NodeController::NodeController(int id, const NodeControllerConfig& config) : node_controller_id_(id), config_(std::make_shared<NodeControllerConfig>(NodeControllerConfig(config))), service_endpoint_(nullptr), node_controller_service_impl_() { service_endpoint_.reset(new ServiceEndpoint(config.create_endpoint(), impl())); } NodeController::~NodeController() { } int NodeController::id() const { return node_controller_id_; } NodeController::ServiceEndpoint::~ServiceEndpoint() { application_->terminate(); thread_.join(); } NodeController::ServiceEndpoint::ServiceEndpoint(const std::string& endpoint, NodeControllerServiceImpl* impl) : endpoint_(endpoint), application_(nullptr), impl_(impl), thread_() { rpcz::application::options options(3); options.zeromq_context = ZmqContext::singleton().get(); application_.reset(new rpcz::application(options)); boost::thread t(&NodeController::ServiceEndpoint::ThreadFunction, this); thread_.swap(t); } void NodeController::ServiceEndpoint::ThreadFunction() { try { Helpers::SetThreadName(-1, "NodeController"); LOG(INFO) << "Establishing NodeControllerService on " << endpoint(); rpcz::server server(*application_); server.register_service(impl_); server.bind(endpoint()); application_->run(); LOG(INFO) << "NodeControllerService on " << endpoint() << " is stopped."; } catch(...) { LOG(FATAL) << "Fatal exception in NodeController::ServiceEndpoint::ThreadFunction() function"; return; } } } // namespace core } // namespace artm
1,933
569
# include "oolua_tests_pch.h" # include "oolua.h" # include "common_cppunit_headers.h" # include "expose_static_and_c_functions.h" # include "expose_hierarchy.h" int returns_stack_count(lua_State* vm) { int top = lua_gettop(vm); OOLUA::push(vm, top); return 1; } int stack_top_type(lua_State* vm) { int top = lua_type(vm, -1); OOLUA::push(vm, top); return 1; } namespace { int static_func_base_return(0); int static_func_derived_return(1); } // namespace int staticFunction_pushes0(lua_State* vm) { OOLUA::push(vm, static_func_base_return); return 1; } int staticFunction_pushes1(lua_State* vm) { OOLUA::push(vm, static_func_derived_return); return 1; } struct DerivedClassHasStaticFunction : public ClassHasStaticFunction { }; OOLUA_PROXY(DerivedClassHasStaticFunction, ClassHasStaticFunction) OOLUA_PROXY_END OOLUA_EXPORT_NO_FUNCTIONS(DerivedClassHasStaticFunction) class StaticFunction : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(StaticFunction); CPPUNIT_TEST(staticFunc_functionIsRegisteredUsingScript_callReturnsTrue); CPPUNIT_TEST(staticFunc_functionIsRegisteredUsingOOLua_callReturnsTrue); CPPUNIT_TEST(staticFunc_generatedProxy_callReturnsTrue); CPPUNIT_TEST(cFunctionAddedToClassTable_calledWithObjectInstaceAndReturnsStackCountOnEntry_returnEqualsZero); CPPUNIT_TEST(cFunctionAddedToClassTable_calledAsStaticFunctionAndReturnsStackCountOnEntry_returnEqualsZero); CPPUNIT_TEST(cFunctionAddedToClassTable_calledOnObjectInstaceWithFloatParamReturnsStackTypeOfTop_returnEqualsNumber); CPPUNIT_TEST(cFunctionAddedToClassTable_calledAsStaticFunctionWithFloatParamReturnsStackTypeOfTop_returnEqualsNumber); CPPUNIT_TEST(cFunctionAddedToClassTable_calledOnObjectInstaceWithFloatParamReturnsOneTypeOnStack_SecondReturnIsNil); CPPUNIT_TEST(cFunctionAddedToClassTable_calledProxyStaticWithObjectInstaceAndInputInt_returnEqualsInput); CPPUNIT_TEST(staticFunction_addedToBaseCalledInDerived_callReturnsTrue); CPPUNIT_TEST(staticFunction_addedToBaseOverriddenInDerived_callsDerivedVersion); CPPUNIT_TEST(staticFunction_addedToBaseInLuaAndCalledFromDerivedClassName_callReturnsTrue); CPPUNIT_TEST(staticData_addedOnBaseInLuaOnBase_calledOnDerived_callReturnsTrue); CPPUNIT_TEST(staticData_addedOnBaseInLuaOnBase_calledOnDerived_resultIsSetValue); #if OOLUA_STORE_LAST_ERROR == 1 CPPUNIT_TEST(staticFunc_functionIsUnregistered_callReturnsFalse); #endif #if OOLUA_USE_EXCEPTIONS == 1 CPPUNIT_TEST(staticFunc_functionIsUnregistered_throwsRuntimeError); #endif CPPUNIT_TEST_SUITE_END(); OOLUA::Script* m_lua; public: void setUp() { m_lua = new OOLUA::Script; m_lua->register_class<ClassHasStaticFunction>(); } void tearDown() { delete m_lua; } void staticFunc_functionIsRegisteredUsingScript_callReturnsTrue() { m_lua->register_class_static<ClassHasStaticFunction>("static_function" , &oolua_ClassHasStaticFunction_static_function); m_lua->run_chunk("foo = function() " "ClassHasStaticFunction.static_function() " "end "); bool result = m_lua->call("foo"); CPPUNIT_ASSERT_EQUAL(true, result); } void staticFunc_functionIsRegisteredUsingOOLua_callReturnsTrue() { OOLUA::register_class_static<ClassHasStaticFunction>(*m_lua , "static_function" , &oolua_ClassHasStaticFunction_static_function); m_lua->run_chunk("foo = function() " "ClassHasStaticFunction.static_function() " "end "); bool result = m_lua->call("foo"); CPPUNIT_ASSERT_EQUAL(true, result); } void staticFunc_generatedProxy_callReturnsTrue() { OOLUA::register_class_static<ClassHasStaticFunction>(*m_lua , "static_function" , &oolua_ClassHasStaticFunction_static_function); m_lua->run_chunk("foo = function() " "ClassHasStaticFunction.static_function() " "end "); bool result = m_lua->call("foo"); CPPUNIT_ASSERT_EQUAL(true, result); } void cFunctionAddedToClassTable_calledWithObjectInstaceAndReturnsStackCountOnEntry_returnEqualsZero() { OOLUA::register_class_static<ClassHasStaticFunction>(*m_lua , "stack_count" , &returns_stack_count); m_lua->run_chunk("foo = function(obj) " "return obj.stack_count() " "end "); ClassHasStaticFunction stack; ClassHasStaticFunction* obj = &stack; m_lua->call("foo", obj); int result(-1); OOLUA::pull(*m_lua, result); CPPUNIT_ASSERT_EQUAL(int(0), result); //NOLINT(readability/casting) } void cFunctionAddedToClassTable_calledAsStaticFunctionAndReturnsStackCountOnEntry_returnEqualsZero() { OOLUA::register_class_static<ClassHasStaticFunction>(*m_lua , "stack_count" , &returns_stack_count); m_lua->run_chunk("foo = function() " "return ClassHasStaticFunction.stack_count() " "end "); m_lua->call("foo"); int result(-1); OOLUA::pull(*m_lua, result); CPPUNIT_ASSERT_EQUAL(int(0), result); //NOLINT(readability/casting) } void cFunctionAddedToClassTable_calledOnObjectInstaceWithFloatParamReturnsStackTypeOfTop_returnEqualsNumber() { OOLUA::register_class_static<ClassHasStaticFunction>(*m_lua , "stack_top_type" , &stack_top_type); m_lua->run_chunk("foo = function(obj) " "return obj.stack_top_type(1.0) " "end "); ClassHasStaticFunction stack; ClassHasStaticFunction* obj = &stack; m_lua->call("foo", obj); int result(-1); OOLUA::pull(*m_lua, result); CPPUNIT_ASSERT_EQUAL(int(LUA_TNUMBER), result); //NOLINT(readability/casting) } void cFunctionAddedToClassTable_calledAsStaticFunctionWithFloatParamReturnsStackTypeOfTop_returnEqualsNumber() { OOLUA::register_class_static<ClassHasStaticFunction>(*m_lua , "stack_top_type" , &stack_top_type); m_lua->run_chunk("foo = function() " "return ClassHasStaticFunction.stack_top_type(1.0) " "end "); m_lua->call("foo"); int result(-1); OOLUA::pull(*m_lua, result); CPPUNIT_ASSERT_EQUAL(int(LUA_TNUMBER), result); //NOLINT(readability/casting) } void cFunctionAddedToClassTable_calledOnObjectInstaceWithFloatParamReturnsOneTypeOnStack_SecondReturnIsNil() { OOLUA::register_class_static<ClassHasStaticFunction>(*m_lua , "stack_top_type" , &stack_top_type); m_lua->run_chunk("foo = function(obj) " "a,b =obj.stack_top_type(1.0) " "assert(b == nil) " "end "); ClassHasStaticFunction stack; ClassHasStaticFunction* obj = &stack; bool result =m_lua->call("foo", obj); CPPUNIT_ASSERT_EQUAL(true, result); } void cFunctionAddedToClassTable_calledProxyStaticWithObjectInstaceAndInputInt_returnEqualsInput() { /*[ClassStaticFunctionUsage]*/ m_lua->register_class_static<ClassHasStaticFunction>("returns_input", &OOLUA::Proxy_class<ClassHasStaticFunction>::returns_input); m_lua->run_chunk("foo = function(obj, input) " "return obj.returns_input(input) " "end "); /*[ClassStaticFunctionUsage]*/ ClassHasStaticFunction stack; ClassHasStaticFunction* obj = &stack; int input = 1; m_lua->call("foo", obj, input); int result(-1); OOLUA::pull(*m_lua, result); CPPUNIT_ASSERT_EQUAL(input, result); } void staticFunction_registeredInBaseCalledInDerived_resultReturnsTrue() { OOLUA::register_class<DerivedClassHasStaticFunction>(*m_lua); m_lua->register_class_static<ClassHasStaticFunction>("stack_count" , &returns_stack_count); m_lua->run_chunk("foo = function(obj) " "return obj.stack_count() " "end "); DerivedClassHasStaticFunction derived; DerivedClassHasStaticFunction* dp = &derived; bool result = m_lua->call("foo", dp); CPPUNIT_ASSERT_EQUAL(result, true); } void staticFunction_addedToBaseCalledInDerived_callReturnsTrue() { OOLUA::register_class<DerivedFromTwoAbstractBasesAndAbstract3>(*m_lua); m_lua->register_class_static<Abstract3>("stack_count", &returns_stack_count); m_lua->run_chunk("foo = function(obj) " "return obj.stack_count() " "end "); DerivedFromTwoAbstractBasesAndAbstract3 derived; bool result = m_lua->call("foo", &derived); CPPUNIT_ASSERT_EQUAL(result, true); } void staticFunction_addedToBaseOverriddenInDerived_callsDerivedVersion() { OOLUA::register_class<DerivedFromTwoAbstractBasesAndAbstract3>(*m_lua); m_lua->register_class_static<Abstract3>("static_func", &staticFunction_pushes0); m_lua->register_class_static<DerivedFromTwoAbstractBasesAndAbstract3>("static_func", &staticFunction_pushes1); m_lua->run_chunk("foo = function(obj) " "return obj.static_func() " "end "); DerivedFromTwoAbstractBasesAndAbstract3 derived; m_lua->call("foo", &derived); int result; OOLUA::pull(*m_lua, result); CPPUNIT_ASSERT_EQUAL(static_func_derived_return, result); } void staticFunction_addedToBaseInLuaAndCalledFromDerivedClassName_callReturnsTrue() { OOLUA::register_class<DerivedFromTwoAbstractBasesAndAbstract3>(*m_lua); m_lua->run_chunk("function Abstract3:lua_func() return 1 end "); m_lua->run_chunk("foo = function() " "return DerivedFromTwoAbstractBasesAndAbstract3.lua_func() " "end "); bool result = m_lua->call("foo"); CPPUNIT_ASSERT_EQUAL(result, true); } void staticData_addedOnBaseInLuaOnBase_calledOnDerived_callReturnsTrue() { OOLUA::register_class<DerivedFromTwoAbstractBasesAndAbstract3>(*m_lua); m_lua->run_chunk("Abstract3[\"static_data\"] = 1 "); m_lua->run_chunk("foo = function() " "return DerivedFromTwoAbstractBasesAndAbstract3.static_data " "end "); bool result = m_lua->call("foo"); CPPUNIT_ASSERT_EQUAL(result, true); } void staticData_addedOnBaseInLuaOnBase_calledOnDerived_resultIsSetValue() { OOLUA::register_class<DerivedFromTwoAbstractBasesAndAbstract3>(*m_lua); m_lua->run_chunk("Abstract3[\"static_data\"] = 1 "); m_lua->run_chunk("foo = function() " "return DerivedFromTwoAbstractBasesAndAbstract3.static_data " "end "); m_lua->call("foo"); int result; OOLUA::pull(*m_lua, result); CPPUNIT_ASSERT_EQUAL(int(1), result); //NOLINT(readability/casting) } #if OOLUA_STORE_LAST_ERROR == 1 void staticFunc_functionIsUnregistered_callReturnsFalse() { m_lua->run_chunk("foo = function() " "ClassHasStaticFunction.static_function() " "end "); bool result = m_lua->call("foo"); CPPUNIT_ASSERT_EQUAL(false, result); } #endif #if OOLUA_USE_EXCEPTIONS == 1 void staticFunc_functionIsUnregistered_throwsRuntimeError() { m_lua->run_chunk("foo = function() " "ClassHasStaticFunction.static_function() " "end "); CPPUNIT_ASSERT_THROW(m_lua->call("foo"), OOLUA::Runtime_error); } #endif }; CPPUNIT_TEST_SUITE_REGISTRATION(StaticFunction);
10,739
4,387
/****************************** Header ******************************\ Class Name: EncoderItem inherits InputComponent File Name: EncoderItem.cpp Summary: Abstraction for the WPIlib Encoder that extends to include some helper and control methods. Project: BroncBotzFRC2019 Copyright (c) BroncBotz. All rights reserved. Author(s): Dylan Watson Email: dylantrwatson@gmail.com \********************************************************************/ #include "EncoderItem.h" using namespace Components; EncoderItem::EncoderItem() {} EncoderItem::EncoderItem(string _name, int _aChannel, int _bChannel, bool _reversed, bool Real) : InputComponent(_name){ aChannel = _aChannel; bChannel = _bChannel; reversed = _reversed; encoder = new Encoder(aChannel, bChannel, reversed); FromTable(Real); Offset = OutputTable->GetNumber(name, 0); { Log::General("Using Table values"); OutputTable->PutNumber(name, 0); OutputTable->PutBoolean(name + "-Reset", true); } Type = InputType::Independent; } EncoderItem::EncoderItem(string _name, NativeComponent *Connected) : InputComponent(_name) { Type = InputType::Data_Driven; LinkedComponent = Connected; } void EncoderItem::Reset() { if(Type == InputType::Independent) { encoder->Reset(); OutputTable->PutBoolean(name + "-Reset", true); } else { if(LinkedComponent != nullptr) LinkedComponent->ResetData(); else Log::Error("Encoder " + name + " tracking nullptr!"); } } double EncoderItem::Get() { if(Type == InputType::Independent) { double input = (UseTable ? OutputTable->GetNumber(name, 0) : (double)encoder->Get()); return input - Offset; } else { if(LinkedComponent != nullptr) return LinkedComponent->GetData(); else { Log::Error("Encoder " + name + " tracking nullptr!"); return 0; } } } string EncoderItem::GetName() { return name; } void EncoderItem::DeleteComponent() { delete encoder; delete this; } void EncoderItem::UpdateComponent() { if (!UseTable && Type == InputType::Independent) { OutputTable->PutNumber(name, EncoderItem::Get()); } } EncoderItem::~EncoderItem() {}
2,103
733
/* \file tb2randomgen.hpp * \brief Random WCSP generator. */ #ifndef TB2RANDOMGEN_H_ #define TB2RANDOMGEN_H_ #include "core/tb2wcsp.hpp" class naryRandom { public: WCSP& wcsp; naryRandom(WCSP* wcspin, int seed = 0) : wcsp(*wcspin) { mysrand(seed); } ~naryRandom() {} int n, m; bool connected(); void generateGlobalCtr(vector<int>& indexs, string globalname, Cost costMin = SMALL_COST, Cost costMax = MEDIUM_COST); void generateNaryCtr(vector<int>& indexs, long nogoods, Cost costMin = SMALL_COST, Cost costMax = MEDIUM_COST); void generateTernCtr(int i, int j, int k, long p, Cost costMin = SMALL_COST, Cost costMax = MEDIUM_COST); void generateBinCtr(int i, int j, long p, Cost costMin = SMALL_COST, Cost costMax = MEDIUM_COST); void generateSubModularBinCtr(int i, int j, Cost costMin = SMALL_COST, Cost costMax = MEDIUM_COST); void Input(int in_n, int in_m, vector<int>& p, bool forceSubModular = false, string globalname = ""); void ini(vector<int>& index, int arity); long toIndex(vector<int>& index); int inc(vector<int>& index, int i); bool inc(vector<int>& index); }; #endif /*TB2RANDOMGEN_H_*/ /* Local Variables: */ /* c-basic-offset: 4 */ /* tab-width: 4 */ /* indent-tabs-mode: nil */ /* c-default-style: "k&r" */ /* End: */
1,332
531
#include <iostream> #include <vector> #include <math.h> #include <string> #include "Input_Reader.h" #include "Materials.h" #include "Fem_Quadrature.h" #include "Quadrule_New.h" #include "Cell_Data.h" #include "Angular_Quadrature.h" #include "Time_Data.h" #include "Intensity_Data.h" #include "Intensity_Moment_Data.h" #include "Temperature_Data.h" #include "L2_Error_Calculator.h" #include "Dark_Arts_Exception.h" /** Goal of this unit test is to verify that L2 error estimate is zero when the analytic solution is within the DFEM trial space */ int main(int argc, char** argv) { int val = 0; const double tol = 1.0E-12; Input_Reader input_reader; try { input_reader.read_xml(argv[1]); } catch(const Dark_Arts_Exception& da_exception ) { da_exception.message() ; val = -1; } Quadrule_New quad_fun; Fem_Quadrature fem_quadrature( input_reader , quad_fun); Cell_Data cell_data( input_reader ); Angular_Quadrature angular_quadrature( input_reader , quad_fun ); /// Create a Materials object that contains all opacity, heat capacity, and source objects Materials materials( input_reader, fem_quadrature , cell_data, angular_quadrature ); Time_Data time_data(input_reader); Temperature_Data t_old(fem_quadrature, input_reader, cell_data); Intensity_Data i_old(cell_data, angular_quadrature, fem_quadrature, materials,input_reader); Intensity_Moment_Data phi(cell_data,angular_quadrature,fem_quadrature,i_old); try{ L2_Error_Calculator l2_error_calculator(angular_quadrature,fem_quadrature, cell_data, input_reader); const double t_eval = time_data.get_t_start(); double temperature_err = l2_error_calculator.calculate_l2_error(t_eval , t_old); double phi_err = l2_error_calculator.calculate_l2_error(t_eval , phi); std::cout << "Phi L2 err: " << phi_err << std::endl; std::cout << "Temperature L2 err: " << temperature_err << std::endl; if(fabs(phi_err) > tol) throw Dark_Arts_Exception(SUPPORT_OBJECT , "Not calculating phi zero err"); if(fabs(temperature_err) > tol) throw Dark_Arts_Exception(SUPPORT_OBJECT , "Not calculating temperature zero err"); temperature_err = l2_error_calculator.calculate_cell_avg_error(t_eval , t_old); phi_err = l2_error_calculator.calculate_cell_avg_error(t_eval , phi); std::cout << "Phi avg err: " << phi_err << std::endl; std::cout << "Temperature avg err: " << temperature_err << std::endl; if(fabs(phi_err) > tol) throw Dark_Arts_Exception(SUPPORT_OBJECT , "Not calculating phi zero err"); if(fabs(temperature_err) > tol) throw Dark_Arts_Exception(SUPPORT_OBJECT , "Not calculating temperature zero err"); } catch(const Dark_Arts_Exception& da) { val = -1; da.testing_message(); } return val; }
2,960
1,095
#ifndef CPPURSES_WIDGET_WIDGETS_LINE_EDIT_HPP #define CPPURSES_WIDGET_WIDGETS_LINE_EDIT_HPP #include <functional> #include <string> #include <signals/signals.hpp> #include <cppurses/painter/color.hpp> #include <cppurses/painter/glyph.hpp> #include <cppurses/painter/glyph_string.hpp> #include <cppurses/system/events/key.hpp> #include <cppurses/system/events/mouse.hpp> #include <cppurses/widget/widgets/textbox.hpp> namespace cppurses { struct Point; // TODO input_mask option, which shows outline of acceptable text in ghost color // ex) phone #| (___)___-____ // ip address| ___.___.___.___ // ref: webtoolkit.eu/widgets/forms/line_text-editor /// Text input box with input validator and Signal emitted on Enter Key press. /** Initial text is in ghost color and cleared on initial focus. Height is fixed * at 1. */ // TODO change to class Field. class Line_edit : public Textbox { public: /// Construct a Line_edit object with \p initial_text in ghost color. explicit Line_edit(Glyph_string initial_text = ""); /// Set the input validator, allowing or disallowing specific char types. /** The default validator always returns true, allowing all chars. Invalid * character input will result in no input being given to the Line_edit. */ void set_validator(std::function<bool(char)> validator); /// Set whether the text is cleared from the Line_edit on Enter Key press. /** This is disabled by default. */ void clear_on_enter(bool enable = true); /// Set whether the Line_edit has veilded output, doesn't alter the content. /** Disabled by default, uses '*' to veil by default. */ auto veil_text(bool enable = true) -> void; /// Set Glyph used to obscure the display. auto set_veil(const Glyph& veil) -> void { veil_ = veil; this->update(); } /// Set whether the Line_edit has an underline. /** Disabled by default. The entire length of the box is underlined if * enabled. */ void underline(bool enabled = true); /// Set color of the initial text, before focus has been given to this. void set_ghost_color(Color c); /// Emitted on Enter Key press, sends along the current contents. sig::Signal<void(std::string)> edit_finished; protected: bool key_press_event(const Key::State& keyboard) override; bool mouse_press_event(const Mouse::State& mouse) override; bool focus_in_event() override; auto paint_event() -> bool override; private: bool clear_on_enter_{false}; bool on_initial_{true}; bool is_veiled_{false}; Glyph veil_{L'*'}; std::function<bool(char)> validator_{[](char) { return true; }}; }; } // namespace cppurses #endif // CPPURSES_WIDGET_WIDGETS_LINE_EDIT_HPP
2,751
872
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_X11INPUT_DEVICE_OPTIONAL_ID_FWD_HPP_INCLUDED #define SGE_X11INPUT_DEVICE_OPTIONAL_ID_FWD_HPP_INCLUDED #include <sge/x11input/device/id.hpp> #include <fcppt/optional/object_fwd.hpp> namespace sge { namespace x11input { namespace device { typedef fcppt::optional::object<sge::x11input::device::id> optional_id; } } } #endif
560
245
/* * Copyright (C) 2012 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. */ #include "disassembler.h" #include <iostream> #include "base/logging.h" #include "disassembler_arm.h" #include "disassembler_mips.h" #include "disassembler_x86.h" namespace art { Disassembler* Disassembler::Create(InstructionSet instruction_set) { if (instruction_set == kArm || instruction_set == kThumb2) { return new arm::DisassemblerArm(); } else if (instruction_set == kMips) { return new mips::DisassemblerMips(); } else if (instruction_set == kX86) { return new x86::DisassemblerX86(); } else { UNIMPLEMENTED(FATAL) << "no disassembler for " << instruction_set; return NULL; } } } // namespace art
1,262
422
#include "../../head.h" class SolutionWrongAnswer { public: std::vector<int> findSubstring(std::string const & s, std::vector<std::string> const & words) { std::vector<int> res; int cnt = words.size(); int wordLen = 0; std::unordered_map<string, int> visited; for (std::string const & word : words) { visited[word]++; wordLen = word.size(); } int start = 0; for (int index = 0; index < s.size() - wordLen; index++) { std::string cur = s.substr(index, wordLen); visited[cur]--; if (visited[cur] >= 0) { cnt++; } else { cnt = 0; visited[cur]++; for (; start < index - wordLen; start += wordLen) { std::string preCur = s.substr(start, wordLen); visited[preCur]++; } } if (cnt == words.size()) { res.emplace(start); cnt = 0; visited[cur]++; for (; start < index - wordLen; start += wordLen) { std::string preCur = s.substr(start, wordLen); visited[preCur]++; } } } return res; } }; class Solution { public: std::vector<int> findSubstring(std::string const & s, std::vector<std::string> const & words) { // plagiarizing from https://leetcode.com/problems/substring-with-concatenation-of-all-words/discuss/13658/Easy-Two-Map-Solution-(C%2B%2BJava) std::vector<int> indexes; if (words.empty() || s.empty()) { return indexes; } std::unordered_map<std::string, int> counts; for (string word : words) { counts[word]++; } int n = s.length(), num = words.size(), len = words[0].length(); for (int i = 0; i < n - num * len + 1; i++) { std::unordered_map<string, int> seen; int j = 0; for (; j < num; j++) { std::string word = s.substr(i + j * len, len); if (counts.find(word) != counts.end()) { seen[word]++; if (seen[word] > counts[word]) break; } else { break; } } if (j == num) { indexes.push_back(i); } } return indexes; } }; // using sliding window to reduce repeat computation class SolutionBetterRunTime { public: std::vector<int> findSubstring(std::string const & s, std::vector<std::string> const & words) { if (s.size() == 0 || words.size() == 0) { return vector<int>(); } int n = s.size(), m = words.size(), wz = words[0].size(); int len = m * wz; size_t ghash = 0; for (int i = 0; i < words.size(); i++) { ghash += std::hash<std::string>{}(words[i]); // construct a hash object and call the operator(); } std::vector<int> ans; for (int i = 0; i < wz; i++) { size_t thash = 0, cnt = 0; for (int j = i; j + wz <= n; j += wz) { if (++cnt < m) { thash += std::hash<std::string_view>{}(std::string_view(&s[j], wz)); continue; } if (cnt > m) { thash -= std::hash<std::string_view>{}(std::string_view(&s[j - len], wz)); } thash += std::hash<std::string_view>{}(std::string_view(&s[j], wz)); if (thash == ghash) { ans.push_back(j - len + wz); } } } return ans; } std::vector<int> findSubstringEasyUnderstand(std::string const & s, std::vector<std::string> const & words) { if (s.size() == 0 || words.size() == 0) { return vector<int>(); } int n = s.size(), m = words.size(), wz = words[0].size(); int len = m * wz; size_t ghash = 0; for (int i = 0; i < words.size(); i++) { ghash += std::hash<std::string>{}(words[i]); // construct a hash object and call the operator(); } std::vector<int> ans; for (int i = 0; i < wz; i++) { size_t thash = 0, cnt = 0; for (int j = i; j + wz <= n; j += wz) { // cnt++, we didn't add the new word into thash cnt++; thash += std::hash<std::string_view>{}(std::string_view(&s[j], wz)); if (cnt < m) { continue; } if (cnt > m) { // remove the left word thash -= std::hash<std::string_view>{}(std::string_view(&s[j - len], wz)); } if (thash == ghash) { ans.push_back(j - len + wz); } } } return ans; } }; class Solution { public: // travel all the words combinations to maintain a window // there are wl(word len) times travel // each time, n/wl words, mostly 2 times travel for each word // one left side of the window, the other right side of the window // so, time complexity O(wl * 2 * N/wl) = O(2N) std::vector<int> findSubstring(std::string const & S, std::vector<std::string> const & L) { std::vector<int> ans; int n = S.size(), cnt = L.size(); if (n <= 0 || cnt <= 0) return ans; // init word occurence std::unordered_map<std::string, int> dict; for (int i = 0; i < cnt; ++i) { dict[L[i]]++; } // travel all sub string combinations int wl = L[0].size(); for (int i = 0; i < wl; ++i) { int left = i, count = 0; std::unordered_map<std::string, int> tdict; for (int j = i; j <= n - wl; j += wl) { std::string str = S.substr(j, wl); // a valid word, accumulate results if (dict.count(str)) { tdict[str]++; if (tdict[str] <= dict[str]) { count++; } else { // a more word, advance the window left side possiablly while (tdict[str] > dict[str]) { string str1 = S.substr(left, wl); tdict[str1]--; if (tdict[str1] < dict[str1]) { count--; } left += wl; } } // come to a result if (count == cnt) { ans.push_back(left); // advance one word tdict[S.substr(left, wl)]--; count--; left += wl; } } else { // not a valid word, reset all vars tdict.clear(); count = 0; left = j + wl; } } } return ans; } };
7,281
2,163
// Sphere #include<bits/stdc++.h> #include<graphics.h> void draw_points(int x, int y, int x_centre, int y_centre) { putpixel(x + x_centre ,-y + y_centre,WHITE); putpixel(y + x_centre ,x + y_centre,WHITE); putpixel(-y + x_centre ,x + y_centre,WHITE); putpixel(x + x_centre,y + y_centre,WHITE); putpixel(-x + x_centre,y + y_centre,WHITE); putpixel(x + x_centre,-y + y_centre,WHITE); putpixel(-x + x_centre,-y + y_centre,WHITE); putpixel(y + x_centre, x + y_centre,WHITE); putpixel(-y + x_centre, x + y_centre,WHITE); putpixel(y + x_centre, -x + y_centre,WHITE); putpixel(-y + x_centre, -x + y_centre,WHITE); } void my_circle(int x_centre, int y_centre, int r) { //First Point int x = 0, y = r; putpixel(x + x_centre, y + y_centre,WHITE); putpixel(y + y_centre, x + x_centre,WHITE); putpixel(x + x_centre, -y + y_centre,WHITE); putpixel(-y + y_centre, x + x_centre,WHITE); int p = 1 - r; while(x <= y) { if(p < 0) { x++; draw_points(x, y, x_centre, y_centre); p = p + 2*x + 1; } else { x++; y--; draw_points(x, y, x_centre, y_centre); p=p + 2*x + 1 - 2*y; } } float phi; float theta; float i,j; for(phi = -1.57; phi<=0; phi += 0.1) { for(theta = -3.14; theta<=3.14; theta += 0.2) { x = r * cos(phi) * cos(theta); y = r * cos(phi) * sin(theta); draw_points(0, y, x_centre, y_centre); p = 1 - r; while(x <= y) { x++; if (p < 0) { p += 2*x + 1; draw_points(x, y, x_centre, y_centre); } else { y--; p += 2*x + 1 - 2*y; draw_points(x, y, x_centre, y_centre); } } } } } int main() { int gd = DETECT, gm; initgraph(&gd, &gm, NULL); my_circle(200, 200, 120); delay(500000); closegraph(); return 0; }
2,181
927
// Copyright (c) 2020 The Console 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 "console/animation.h" #include "color/named_color.h" #include "gtest/gtest.h" namespace console { namespace { class TestAnimation : public TextAnimation { public: typedef std::function<bool()> ShouldUpdateCallback; typedef std::function<void()> DoUpdateCallback; void set_should_update_callback(ShouldUpdateCallback should_update_callback) { should_update_callback_ = should_update_callback; } void set_do_update_callback(DoUpdateCallback do_update_callback) { do_update_callback_ = do_update_callback; } bool ShouldUpdate() override { if (!should_update_callback_) return true; return should_update_callback_(); } void DoUpdate() override { if (do_update_callback_) do_update_callback_(); } void set_end() { ended_ = true; } private: ShouldUpdateCallback should_update_callback_; DoUpdateCallback do_update_callback_; }; } // namespace #define SETUP_CALLBACKS(animation) \ bool started = false; \ bool ended = false; \ size_t will_update = 0; \ size_t did_update = 0; \ animation.set_on_animation_start([&started]() { started = true; }); \ animation.set_on_animation_end([&ended]() { ended = true; }); \ animation.set_on_animation_will_update( \ [&will_update](size_t) { will_update++; }); \ animation.set_on_animation_did_update([&did_update](size_t) { did_update++; }) TEST(AnimationTest, Callback) { TestAnimation animation; SETUP_CALLBACKS(animation); size_t count = 0; animation.set_do_update_callback([&count, &animation]() { count++; if (count == 5) { animation.set_end(); } }); animation.Update(); EXPECT_TRUE(started); EXPECT_FALSE(ended); EXPECT_EQ(will_update, 1); EXPECT_EQ(did_update, 1); for (size_t i = 0; i < 4; ++i) { animation.Update(); EXPECT_EQ(will_update, 2 + i); EXPECT_EQ(did_update, 2 + i); } EXPECT_TRUE(ended); } TEST(FlowTextAnimationTest, Callback) { { FlowTextAnimation animation; SETUP_CALLBACKS(animation); animation.set_text("Hello World\n"); animation.Update(); EXPECT_FALSE(started); EXPECT_FALSE(ended); EXPECT_EQ(will_update, 0); EXPECT_EQ(did_update, 0); } { FlowTextAnimation animation; SETUP_CALLBACKS(animation); animation.set_colors({color::kBlack, color::kGray, color::kWhite}); animation.Update(); EXPECT_FALSE(started); EXPECT_FALSE(ended); EXPECT_EQ(will_update, 0); EXPECT_EQ(did_update, 0); } { FlowTextAnimation animation; SETUP_CALLBACKS(animation); animation.set_text("Hello World\n"); animation.set_colors({color::kBlack, color::kGray, color::kWhite}); for (size_t i = 0; i < animation.text().length(); ++i) { animation.Update(); EXPECT_TRUE(started); if (i == animation.text().length() - 1) { EXPECT_TRUE(ended); } else { EXPECT_FALSE(ended); } } } { FlowTextAnimation animation; SETUP_CALLBACKS(animation); animation.set_text("Hello World\n"); animation.set_colors({color::kBlack, color::kGray, color::kWhite}); animation.set_repeat(true); for (size_t i = 0; i < animation.text().length(); ++i) { animation.Update(); EXPECT_TRUE(started); EXPECT_FALSE(ended); } } } TEST(NeonTextAnimationTest, Callback) { { NeonTextAnimation animation; SETUP_CALLBACKS(animation); animation.set_text("Hello World\n"); animation.Update(); EXPECT_FALSE(started); EXPECT_FALSE(ended); EXPECT_EQ(will_update, 0); EXPECT_EQ(did_update, 0); } { NeonTextAnimation animation; SETUP_CALLBACKS(animation); animation.set_colors({color::kBlack, color::kGray, color::kWhite}); animation.Update(); EXPECT_FALSE(started); EXPECT_FALSE(ended); EXPECT_EQ(will_update, 0); EXPECT_EQ(did_update, 0); } { NeonTextAnimation animation; SETUP_CALLBACKS(animation); animation.set_text("Hello World\n"); animation.set_colors({color::kBlack, color::kGray, color::kWhite}); for (size_t i = 0; i < animation.colors().size(); ++i) { animation.Update(); EXPECT_TRUE(started); if (i == animation.colors().size() - 1) { EXPECT_TRUE(ended); } else { EXPECT_FALSE(ended); } } } { NeonTextAnimation animation; SETUP_CALLBACKS(animation); animation.set_text("Hello World\n"); animation.set_colors({color::kBlack, color::kGray, color::kWhite}); animation.set_repeat(true); for (size_t i = 0; i < animation.colors().size(); ++i) { animation.Update(); EXPECT_TRUE(started); EXPECT_FALSE(ended); } } } TEST(KaraokeTextAnimationTest, Callback) { { KaraokeTextAnimation animation; SETUP_CALLBACKS(animation); animation.Update(); EXPECT_FALSE(started); EXPECT_FALSE(ended); EXPECT_EQ(will_update, 0); EXPECT_EQ(did_update, 0); } { KaraokeTextAnimation animation; SETUP_CALLBACKS(animation); animation.set_text("Hello World\n"); animation.set_color(color::kBlack); for (size_t i = 0; i < animation.text().length(); ++i) { animation.Update(); EXPECT_TRUE(started); if (i == animation.text().length() - 1) { EXPECT_TRUE(ended); } else { EXPECT_FALSE(ended); } } } { KaraokeTextAnimation animation; SETUP_CALLBACKS(animation); animation.set_text("Hello World\n"); animation.set_color(color::kBlack); animation.set_repeat(true); for (size_t i = 0; i < animation.text().length(); ++i) { animation.Update(); EXPECT_TRUE(started); EXPECT_FALSE(ended); } } } TEST(RadarTextAnimationTest, Callback) { { RadarTextAnimation animation; SETUP_CALLBACKS(animation); animation.set_text("Hello World\n"); animation.Update(); EXPECT_FALSE(started); EXPECT_FALSE(ended); EXPECT_EQ(will_update, 0); EXPECT_EQ(did_update, 0); } { RadarTextAnimation animation; SETUP_CALLBACKS(animation); animation.set_colors({color::kBlack, color::kGray, color::kWhite}); animation.Update(); EXPECT_FALSE(started); EXPECT_FALSE(ended); EXPECT_EQ(will_update, 0); EXPECT_EQ(did_update, 0); } { RadarTextAnimation animation; SETUP_CALLBACKS(animation); animation.set_text("Hello World\n"); animation.set_colors({color::kBlack, color::kGray, color::kWhite}); for (size_t i = 0; i < animation.text().length(); ++i) { animation.Update(); EXPECT_TRUE(started); if (i == animation.text().length() - 1) { EXPECT_TRUE(ended); } else { EXPECT_FALSE(ended); } } } { RadarTextAnimation animation; SETUP_CALLBACKS(animation); animation.set_text("Hello World\n"); animation.set_colors({color::kBlack, color::kGray, color::kWhite}); animation.set_repeat(true); for (size_t i = 0; i < animation.text().length(); ++i) { animation.Update(); EXPECT_TRUE(started); EXPECT_FALSE(ended); } } } } // namespace console
7,502
2,620
/* * mptPathString.cpp * ----------------- * Purpose: Wrapper class around the platform-native representation of path names. Should be the only type that is used to store path names. * Notes : Currently none. * Authors: OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #include "mptPathString.h" #include "misc_util.h" #if MPT_OS_WINDOWS #include <windows.h> #endif OPENMPT_NAMESPACE_BEGIN #if MPT_OS_WINDOWS namespace mpt { RawPathString PathString::AsNativePrefixed() const //------------------------------------------------ { if(path.length() <= MAX_PATH || path.substr(0, 4) == L"\\\\?\\") { // Path is short enough or already in prefixed form return path; } const RawPathString absPath = mpt::GetAbsolutePath(path).AsNative(); if(absPath.substr(0, 2) == L"\\\\") { // Path is a network share: \\server\foo.bar -> \\?\UNC\server\foo.bar return L"\\\\?\\UNC" + absPath.substr(1); } else { // Regular file: C:\foo.bar -> \\?\C:\foo.bar return L"\\\\?\\" + absPath; } } int PathString::CompareNoCase(const PathString & a, const PathString & b) //----------------------------------------------------------------------- { return lstrcmpiW(a.ToWide().c_str(), b.ToWide().c_str()); } } // namespace mpt #endif // MPT_OS_WINDOWS #if defined(MODPLUG_TRACKER) && MPT_OS_WINDOWS namespace mpt { void PathString::SplitPath(PathString *drive, PathString *dir, PathString *fname, PathString *ext) const //------------------------------------------------------------------------------------------------------ { wchar_t tempDrive[_MAX_DRIVE]; wchar_t tempDir[_MAX_DIR]; wchar_t tempFname[_MAX_FNAME]; wchar_t tempExt[_MAX_EXT]; _wsplitpath(path.c_str(), tempDrive, tempDir, tempFname, tempExt); if(drive) *drive = mpt::PathString::FromNative(tempDrive); if(dir) *dir = mpt::PathString::FromNative(tempDir); if(fname) *fname = mpt::PathString::FromNative(tempFname); if(ext) *ext = mpt::PathString::FromNative(tempExt); } PathString PathString::GetDrive() const //------------------------------------- { PathString drive; SplitPath(&drive, nullptr, nullptr, nullptr); return drive; } PathString PathString::GetDir() const //----------------------------------- { PathString dir; SplitPath(nullptr, &dir, nullptr, nullptr); return dir; } PathString PathString::GetPath() const //------------------------------------ { PathString drive, dir; SplitPath(&drive, &dir, nullptr, nullptr); return drive + dir; } PathString PathString::GetFileName() const //---------------------------------------- { PathString fname; SplitPath(nullptr, nullptr, &fname, nullptr); return fname; } PathString PathString::GetFileExt() const //--------------------------------------- { PathString ext; SplitPath(nullptr, nullptr, nullptr, &ext); return ext; } PathString PathString::GetFullFileName() const //-------------------------------------------- { PathString name, ext; SplitPath(nullptr, nullptr, &name, &ext); return name + ext; } PathString PathString::ReplaceExt(const mpt::PathString &newExt) const //-------------------------------------------------------------------- { return GetDrive() + GetDir() + GetFileName() + newExt; } PathString PathString::SanitizeComponent() const //---------------------------------------------- { PathString result = *this; SanitizeFilename(result); return result; } // Convert an absolute path to a path that's relative to "&relativeTo". PathString PathString::AbsolutePathToRelative(const PathString &relativeTo) const //------------------------------------------------------------------------------- { mpt::PathString result = path; if(path.empty()) { return result; } if(!_wcsnicmp(relativeTo.AsNative().c_str(), AsNative().c_str(), relativeTo.AsNative().length())) { // Path is OpenMPT's directory or a sub directory ("C:\OpenMPT\Somepath" => ".\Somepath") result = MPT_PATHSTRING(".\\"); // ".\" result += mpt::PathString::FromNative(AsNative().substr(relativeTo.AsNative().length())); } else if(!_wcsnicmp(relativeTo.AsNative().c_str(), AsNative().c_str(), 2)) { // Path is on the same drive as OpenMPT ("C:\Somepath" => "\Somepath") result = mpt::PathString::FromNative(AsNative().substr(2)); } return result; } // Convert a path that is relative to "&relativeTo" to an absolute path. PathString PathString::RelativePathToAbsolute(const PathString &relativeTo) const //------------------------------------------------------------------------------- { mpt::PathString result = path; if(path.empty()) { return result; } if(AsNative().length() >= 2 && AsNative().at(0) == L'\\' && AsNative().at(1) != L'\\') { // Path is on the same drive as OpenMPT ("\Somepath\" => "C:\Somepath\"), but ignore network paths starting with "\\" result = mpt::PathString::FromNative(relativeTo.AsNative().substr(0, 2)); result += path; } else if(AsNative().length() >= 2 && AsNative().substr(0, 2) == L".\\") { // Path is OpenMPT's directory or a sub directory (".\Somepath\" => "C:\OpenMPT\Somepath\") result = relativeTo; // "C:\OpenMPT\" result += mpt::PathString::FromNative(AsNative().substr(2)); } return result; } #if MPT_OS_WINDOWS #if defined(_MFC_VER) mpt::PathString PathString::TunnelOutofCString(const CString &path) //----------------------------------------------------------------- { #ifdef UNICODE return mpt::PathString::FromWide(path.GetString()); #else // Since MFC code can call into our code from a lot of places, we cannot assume // that filenames we get from MFC are always encoded in our hacked UTF8-in-CString encoding. // Instead, we use a rough heuristic: if the string is parseable as UTF8, we assume it is. // This fails for CP_ACP strings, that are also valid UTF8. That's the trade-off here. if(mpt::IsUTF8(path.GetString())) { // utf8 return mpt::PathString::FromUTF8(path.GetString()); } else { // ANSI return mpt::PathString::FromWide(mpt::ToWide(path)); } #endif } CString PathString::TunnelIntoCString(const mpt::PathString &path) //---------------------------------------------------------------- { #ifdef UNICODE return path.ToWide().c_str(); #else return path.ToUTF8().c_str(); #endif } #endif // MFC #endif // MPT_OS_WINDOWS } // namespace mpt #endif // MODPLUG_TRACKER && MPT_OS_WINDOWS namespace mpt { #if MPT_OS_WINDOWS mpt::PathString GetAbsolutePath(const mpt::PathString &path) //---------------------------------------------------------- { DWORD size = GetFullPathNameW(path.AsNative().c_str(), 0, nullptr, nullptr); if(size == 0) { return path; } std::vector<WCHAR> fullPathName(size, L'\0'); if(GetFullPathNameW(path.AsNative().c_str(), size, &fullPathName[0], nullptr) == 0) { return path; } return mpt::PathString::FromNative(&fullPathName[0]); } #ifdef MODPLUG_TRACKER bool DeleteWholeDirectoryTree(mpt::PathString path) { if(path.AsNative().empty()) { return false; } if(!path.FileOrDirectoryExists()) { return true; } if(!path.IsDirectory()) { return false; } path.EnsureTrailingSlash(); HANDLE hFind = NULL; WIN32_FIND_DATAW wfd; MemsetZero(wfd); hFind = FindFirstFileW((path + MPT_PATHSTRING("*.*")).AsNative().c_str(), &wfd); if(hFind != NULL && hFind != INVALID_HANDLE_VALUE) { do { mpt::PathString filename = mpt::PathString::FromNative(wfd.cFileName); if(filename != MPT_PATHSTRING(".") && filename != MPT_PATHSTRING("..")) { filename = path + filename; if(filename.IsDirectory()) { if(!DeleteWholeDirectoryTree(filename)) { return false; } } else if(filename.IsFile()) { if(DeleteFileW(filename.AsNative().c_str()) == 0) { return false; } } } } while(FindNextFileW(hFind, &wfd)); FindClose(hFind); } if(RemoveDirectoryW(path.AsNative().c_str()) == 0) { return false; } return true; } #endif // MODPLUG_TRACKER #endif // MPT_OS_WINDOWS #if defined(MPT_ENABLE_TEMPFILE) #if MPT_OS_WINDOWS mpt::PathString GetTempDirectory() //-------------------------------- { DWORD size = GetTempPathW(0, nullptr); if(size) { std::vector<WCHAR> tempPath(size + 1); if(GetTempPathW(size + 1, &tempPath[0])) { return mpt::PathString::FromNative(&tempPath[0]); } } // use app directory as fallback return mpt::GetAppPath(); } mpt::PathString CreateTempFileName(const mpt::PathString &fileNamePrefix, const mpt::PathString &fileNameExtension) //----------------------------------------------------------------------------------------------------------------- { mpt::PathString filename = mpt::GetTempDirectory(); filename += (!fileNamePrefix.empty() ? fileNamePrefix + MPT_PATHSTRING("_") : mpt::PathString()); filename += mpt::PathString::FromUnicode(mpt::UUID::GenerateLocalUseOnly().ToUString()); filename += (!fileNameExtension.empty() ? MPT_PATHSTRING(".") + fileNameExtension : mpt::PathString()); return filename; } TempFileGuard::TempFileGuard(const mpt::PathString &filename) : filename(filename) { return; } mpt::PathString TempFileGuard::GetFilename() const { return filename; } TempFileGuard::~TempFileGuard() { if(!filename.empty()) { DeleteFileW(filename.AsNative().c_str()); } } #ifdef MODPLUG_TRACKER TempDirGuard::TempDirGuard(const mpt::PathString &dirname_) : dirname(dirname_.WithTrailingSlash()) { if(dirname.empty()) { return; } if(::CreateDirectoryW(dirname.AsNative().c_str(), NULL) == 0) { // fail dirname = mpt::PathString(); } } mpt::PathString TempDirGuard::GetDirname() const { return dirname; } TempDirGuard::~TempDirGuard() { if(!dirname.empty()) { DeleteWholeDirectoryTree(dirname); } } #endif // MODPLUG_TRACKER #endif // MPT_OS_WINDOWS #endif // MPT_ENABLE_TEMPFILE } // namespace mpt #if defined(MODPLUG_TRACKER) static inline char SanitizeFilenameChar(char c) //--------------------------------------------- { if( c == '\\' || c == '\"' || c == '/' || c == ':' || c == '?' || c == '<' || c == '>' || c == '|' || c == '*') { c = '_'; } return c; } static inline wchar_t SanitizeFilenameChar(wchar_t c) //--------------------------------------------------- { if( c == L'\\' || c == L'\"' || c == L'/' || c == L':' || c == L'?' || c == L'<' || c == L'>' || c == L'|' || c == L'*') { c = L'_'; } return c; } void SanitizeFilename(mpt::PathString &filename) //---------------------------------------------- { mpt::RawPathString tmp = filename.AsNative(); for(mpt::RawPathString::iterator it = tmp.begin(); it != tmp.end(); ++it) { *it = SanitizeFilenameChar(*it); } filename = mpt::PathString::FromNative(tmp); } void SanitizeFilename(char *beg, char *end) //----------------------------------------- { for(char *it = beg; it != end; ++it) { *it = SanitizeFilenameChar(*it); } } void SanitizeFilename(wchar_t *beg, wchar_t *end) //----------------------------------------------- { for(wchar_t *it = beg; it != end; ++it) { *it = SanitizeFilenameChar(*it); } } void SanitizeFilename(std::string &str) //------------------------------------- { for(size_t i = 0; i < str.length(); i++) { str[i] = SanitizeFilenameChar(str[i]); } } void SanitizeFilename(std::wstring &str) //-------------------------------------- { for(size_t i = 0; i < str.length(); i++) { str[i] = SanitizeFilenameChar(str[i]); } } #if defined(_MFC_VER) void SanitizeFilename(CString &str) //--------------------------------- { for(int i = 0; i < str.GetLength(); i++) { str.SetAt(i, SanitizeFilenameChar(str.GetAt(i))); } } #endif // MFC #endif // MODPLUG_TRACKER #if defined(MODPLUG_TRACKER) mpt::PathString FileType::AsFilterString(FlagSet<FileTypeFormat> format) const //---------------------------------------------------------------------------- { mpt::PathString filter; if(GetShortName().empty() || GetExtensions().empty()) { return filter; } if(!GetDescription().empty()) { filter += mpt::PathString::FromUnicode(GetDescription()); } else { filter += mpt::PathString::FromUnicode(GetShortName()); } const std::vector<mpt::PathString> extensions = GetExtensions(); if(format[FileTypeFormatShowExtensions]) { filter += MPT_PATHSTRING(" ("); bool first = true; for(std::vector<mpt::PathString>::const_iterator it = extensions.begin(); it != extensions.end(); ++it) { if(first) { first = false; } else { filter += MPT_PATHSTRING(","); } filter += MPT_PATHSTRING("*."); filter += (*it); } filter += MPT_PATHSTRING(")"); } filter += MPT_PATHSTRING("|"); { bool first = true; for(std::vector<mpt::PathString>::const_iterator it = extensions.begin(); it != extensions.end(); ++it) { if(first) { first = false; } else { filter += MPT_PATHSTRING(";"); } filter += MPT_PATHSTRING("*."); filter += (*it); } } filter += MPT_PATHSTRING("|"); return filter; } mpt::PathString FileType::AsFilterOnlyString() const //-------------------------------------------------- { mpt::PathString filter; const std::vector<mpt::PathString> extensions = GetExtensions(); { bool first = true; for(std::vector<mpt::PathString>::const_iterator it = extensions.begin(); it != extensions.end(); ++it) { if(first) { first = false; } else { filter += MPT_PATHSTRING(";"); } filter += MPT_PATHSTRING("*."); filter += (*it); } } return filter; } mpt::PathString ToFilterString(const FileType &fileType, FlagSet<FileTypeFormat> format) //-------------------------------------------------------------------------------------- { return fileType.AsFilterString(format); } mpt::PathString ToFilterString(const std::vector<FileType> &fileTypes, FlagSet<FileTypeFormat> format) //---------------------------------------------------------------------------------------------------- { mpt::PathString filter; for(std::vector<FileType>::const_iterator it = fileTypes.begin(); it != fileTypes.end(); ++it) { filter += it->AsFilterString(format); } return filter; } mpt::PathString ToFilterOnlyString(const FileType &fileType, bool prependSemicolonWhenNotEmpty) //--------------------------------------------------------------------------------------------- { mpt::PathString filter = fileType.AsFilterOnlyString(); return filter.empty() ? filter : (prependSemicolonWhenNotEmpty ? MPT_PATHSTRING(";") : MPT_PATHSTRING("")) + filter; } mpt::PathString ToFilterOnlyString(const std::vector<FileType> &fileTypes, bool prependSemicolonWhenNotEmpty) //----------------------------------------------------------------------------------------------------------- { mpt::PathString filter; for(std::vector<FileType>::const_iterator it = fileTypes.begin(); it != fileTypes.end(); ++it) { filter += it->AsFilterOnlyString(); } return filter.empty() ? filter : (prependSemicolonWhenNotEmpty ? MPT_PATHSTRING(";") : MPT_PATHSTRING("")) + filter; } #endif // MODPLUG_TRACKER OPENMPT_NAMESPACE_END
15,008
5,376
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Antonio Recuero // ============================================================================= // // Unit test for ANCF beam element (continuum-based). This unit test uses published // data to verify the implementation of the internal forces of the ANCFbeamelement. // For more information, refer to Nachbagauer, Gruber, and Gerstmayr, "Structural and // continuum mechanics approaches for a 3D shear deformable ANCF beam finite element: // Application to static and linearized dynamic examples", Journal of Computational // and Nonlinear Dynamics, April 2013, Vol. 8/021004. Table 1 therein. // ============================================================================= #include <cstdio> #include <cmath> #include <iomanip> #include "chrono/physics/ChSystemNSC.h" #include "chrono/solver/ChSolverMINRES.h" #include "chrono/fea/ChElementBeamANCF.h" #include "chrono/fea/ChMesh.h" #ifdef CHRONO_MKL #include "chrono_mkl/ChSolverMKL.h" #endif bool use_mkl = true; const double u_y_Ref = 8.091623235e-4; const double u_x_Ref = 1.944145290e-7; const double rel_Tol = 1e-7; using namespace chrono; using namespace chrono::fea; int main(int argc, char* argv[]) { // Create a Chrono::Engine physical system ChSystemNSC my_system; // Create a mesh, that is a container for groups of elements and // their referenced nodes. auto my_mesh = chrono_types::make_shared<ChMesh>(); my_system.Set_G_acc(ChVector<>(0, -9.81, 0.0)); const double beam_h = 0.5; // Beam height (y) const double beam_w = 0.1; // Beam width (z) const double beam_l = 2.0; // Beam length unsigned int NElem = 4; // Number of finite elements double rho = 2000.0; // Beam material density const double E_mod = 2.07e11; // Beam modulus of elasticity const double nu_rat = 0.3; // Beam material Poisson ratio const double k1 = 10 * (1 + nu_rat) / (12 + 11 * nu_rat); // Timoshenko coefficient const double k2 = k1; // Timoshenko coefficient auto m_beamMaterial = chrono_types::make_shared<ChMaterialBeamANCF>(rho, E_mod, nu_rat, k1, k2); // Create the end nodes auto hnodeancf1 = chrono_types::make_shared<ChNodeFEAxyzDD>(ChVector<>(0, 0, 0.0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1)); auto hnodeancf2 = chrono_types::make_shared<ChNodeFEAxyzDD>(ChVector<>(beam_l / 4, 0, 0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1)); auto hnodeancf3 = chrono_types::make_shared<ChNodeFEAxyzDD>(ChVector<>(beam_l / 2, 0, 0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1)); auto hnodeancf4 = chrono_types::make_shared<ChNodeFEAxyzDD>(ChVector<>(3.0 * beam_l / 4, 0, 0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1)); auto hnodeancf5 = chrono_types::make_shared<ChNodeFEAxyzDD>(ChVector<>(beam_l, 0, 0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1)); // Create the middle nodes auto hnodeancfm1 = chrono_types::make_shared<ChNodeFEAxyzDD>(ChVector<>(beam_l / 8, 0, 0.0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1)); auto hnodeancfm2 = chrono_types::make_shared<ChNodeFEAxyzDD>(ChVector<>(3 * beam_l / 8, 0, 0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1)); auto hnodeancfm3 = chrono_types::make_shared<ChNodeFEAxyzDD>(ChVector<>(5 * beam_l / 8, 0, 0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1)); auto hnodeancfm4 = chrono_types::make_shared<ChNodeFEAxyzDD>(ChVector<>(7 * beam_l / 8, 0, 0), ChVector<>(0, 1, 0), ChVector<>(0, 0, 1)); hnodeancf1->SetFixed(true); // Fix ALL coordinates of first (clamped) node my_mesh->AddNode(hnodeancf1); my_mesh->AddNode(hnodeancf2); my_mesh->AddNode(hnodeancf3); my_mesh->AddNode(hnodeancf4); my_mesh->AddNode(hnodeancf5); my_mesh->AddNode(hnodeancfm1); my_mesh->AddNode(hnodeancfm2); my_mesh->AddNode(hnodeancfm3); my_mesh->AddNode(hnodeancfm4); // Create the element 1 auto belementancf1 = chrono_types::make_shared<ChElementBeamANCF>(); belementancf1->SetNodes(hnodeancf1, hnodeancf2, hnodeancfm1); belementancf1->SetDimensions(beam_l / 4, beam_h, beam_w); belementancf1->SetMaterial(m_beamMaterial); belementancf1->SetAlphaDamp(0.0004); belementancf1->SetGravityOn(false); belementancf1->SetStrainFormulation(ChElementBeamANCF::StrainFormulation::CMPoisson); // Neglect Poisson effect my_mesh->AddElement(belementancf1); // Create the element 2 auto belementancf2 = chrono_types::make_shared<ChElementBeamANCF>(); belementancf2->SetNodes(hnodeancf2, hnodeancf3, hnodeancfm2); belementancf2->SetDimensions(beam_l / 4, beam_h, beam_w); belementancf2->SetMaterial(m_beamMaterial); belementancf2->SetAlphaDamp(0.0004); belementancf2->SetGravityOn(false); belementancf2->SetStrainFormulation(ChElementBeamANCF::StrainFormulation::CMPoisson); // Neglect Poisson effect my_mesh->AddElement(belementancf2); // Create the element 3 auto belementancf3 = chrono_types::make_shared<ChElementBeamANCF>(); belementancf3->SetNodes(hnodeancf3, hnodeancf4, hnodeancfm3); belementancf3->SetDimensions(beam_l / 4, beam_h, beam_w); belementancf3->SetMaterial(m_beamMaterial); belementancf3->SetAlphaDamp(0.0004); belementancf3->SetGravityOn(false); belementancf3->SetStrainFormulation(ChElementBeamANCF::StrainFormulation::CMPoisson); // Neglect Poisson effect my_mesh->AddElement(belementancf3); // Create the element 4 auto belementancf4 = chrono_types::make_shared<ChElementBeamANCF>(); belementancf4->SetNodes(hnodeancf4, hnodeancf5, hnodeancfm4); belementancf4->SetDimensions(beam_l / 4, beam_h, beam_w); belementancf4->SetMaterial(m_beamMaterial); belementancf4->SetAlphaDamp(0.0004); belementancf4->SetGravityOn(false); belementancf4->SetStrainFormulation(ChElementBeamANCF::StrainFormulation::CMPoisson); // Neglect Poisson effect my_mesh->AddElement(belementancf4); // Cancel automatic gravity my_mesh->SetAutomaticGravity(false); // Remember to add the mesh to the system my_system.Add(my_mesh); #ifndef CHRONO_MKL use_mkl = false; #endif // Setup solver if (use_mkl) { #ifdef CHRONO_MKL auto mkl_solver = chrono_types::make_shared<ChSolverMKL<>>(); mkl_solver->SetSparsityPatternLock(false); mkl_solver->SetVerbose(false); my_system.SetSolver(mkl_solver); #endif } else { my_system.SetSolverType(ChSolver::Type::MINRES); auto msolver = std::static_pointer_cast<ChSolverMINRES>(my_system.GetSolver()); msolver->SetDiagonalPreconditioning(true); my_system.SetSolverWarmStarting(true); my_system.SetMaxItersSolverSpeed(100); my_system.SetMaxItersSolverStab(100); my_system.SetTolForce(1e-14); } // Setup integrator my_system.SetTimestepperType(ChTimestepper::Type::HHT); auto mystepper = std::static_pointer_cast<ChTimestepperHHT>(my_system.GetTimestepper()); mystepper->SetAlpha(-0.2); mystepper->SetMaxiters(10); mystepper->SetAbsTolerances(1e-10); mystepper->SetMode(ChTimestepperHHT::POSITION); mystepper->SetScaling(false); mystepper->SetVerbose(true); mystepper->SetModifiedNewton(false); // Mark completion of system construction my_system.SetupInitial(); unsigned int num_steps = 50; double time_Step = 0.01; std::cout << std::fixed << std::setprecision(12); for (unsigned int it = 0; it < num_steps; it++) { //std::cout << "Position of the tip: " << hnodeancf5->GetPos().y() << " m. \n"; //std::cout << "Long. Position of the tip: " << hnodeancf5->GetPos().x() << " m. \n"; //std::cout << "Lat. Position of the tip: " << hnodeancf5->GetPos().z() << " m. \n"; hnodeancf5->SetForce(ChVector<>(0, -5e5 * std::pow(0.5, 3), 0)); my_system.DoStepDynamics(time_Step); } double error_y = (hnodeancf5->GetPos().y() + u_y_Ref) / u_y_Ref; double error_x = (hnodeancf5->GetPos().x() + u_x_Ref - 2.0) / u_x_Ref; if (ChMax(error_x, error_y) > rel_Tol) { return 1; } std::cout << "Position of the tip: " << hnodeancf5->GetPos().y() << " m. \n"; std::cout << "Long. Position of the tip: " << hnodeancf5->GetPos().x() << " m. \n"; std::cout << "Lat. Position of the tip: " << hnodeancf5->GetPos().z() << " m. \n"; return 0; }
8,963
3,408
// XPLMTestHarness.cpp : Defines the exported functions for the DLL application. // #include "stdafx.h" #include "XPLMTestHarness.h" #include "XPLMScenery.h" #include "XPLMGraphics.h" #include <map> #include <tuple> #include <vector> #include <string> #include <algorithm> #include <iostream> #include <Shlwapi.h> using std::map; using std::tuple; using std::make_tuple; using std::string; using std::vector; using std::remove; static int idSource; # define strcp(dest, str) strcpy_s(dest, strlen(str) + 1, str) // NOTE: The data type naming conventions in this file match those used in the X-Plane API. // E.g., int is 'i' and int array is 'iv'. But I defined 'data' as 'bv' (byte vector) instead // of 'b' like X-Plane does b/c resolving that inconsistency made writing the macros easier. template <typename T> struct dataref { dataref(const string n, const T& v) : id(++idSource), name(n), value(v) { } dataref(const dataref& other) : id(other.id), name(other.name), value(other.value) { } int id; string name; T value; operator XPLMDataRef () { return reinterpret_cast<XPLMDataRef>(static_cast<uintptr_t>(id)); } bool operator == (XPLMDataRef id) { return static_cast<XPLMDataRef>(*this) == id; } }; struct command { command(const string n, CommandCallback cb) : id(++idSource), name(n), callback(cb) { } command(const command& other) : id(other.id), name(other.name), callback(other.callback) { } int id; string name; CommandCallback callback; operator XPLMCommandRef () { return reinterpret_cast<XPLMCommandRef>(static_cast<uintptr_t>(id)); } }; struct flightloop { flightloop(const XPLMFlightLoop_f fl, float i) : flightLoop(fl), interval(i) { } flightloop(const flightloop& other) : flightLoop(other.flightLoop), interval(other.interval) { } XPLMFlightLoop_f flightLoop; float interval; bool deleted = false; }; struct drawcallback { drawcallback(const XPLMDrawCallback_f dc, const XPLMDrawingPhase phase, int wb) : drawCallback(dc), drawingPhase(phase), wantsBefore(wb) { } XPLMDrawCallback_f drawCallback; XPLMDrawingPhase drawingPhase; int wantsBefore; bool deleted = false; }; template <typename T> using datarefmap = map<string, dataref<T>>; static datarefmap<int> iData; static datarefmap<vector<int>> ivData; static datarefmap<float> fData; static datarefmap<vector<float>> fvData; static datarefmap<double> dData; static datarefmap<vector<BYTE>> bvData; using commandmap = map<string, command>; static commandmap configuredCommands; static map<XPLMFlightLoop_f, flightloop> registeredFlightLoops; static map<tuple<XPLMDrawCallback_f, XPLMDrawingPhase, int>, drawcallback> registeredDrawCallbacks; template <typename T> void SetDataRef(const string name, const T& value, datarefmap<T>& container) { auto it = container.find(name); if (it == container.end()) container.emplace(name, dataref<T>(name, value)); else it->second.value = value; } template <typename T> dataref<T>* FindDataRef(XPLMDataRef id, datarefmap<T>& container) { for (auto i = container.begin(), end = container.end(); i != end; ++i) { if (i->second == id) return &i->second; } return nullptr; } command* FindCommand(XPLMCommandRef id, commandmap& container) { for (auto i = container.begin(), end = container.end(); i != end; ++i) { if (i->second == id) return &i->second; } return nullptr; } bool GetEntrypointExecutableAbsolutePath(std::string& entrypointExecutable) { CHAR path[MAX_PATH]; GetModuleFileNameA(NULL, path, sizeof(path)); entrypointExecutable = path; return true; } #define DEFINE_DATA_SET(code, type) \ XPLM_API void XPHarnessSetDataRef##code (const char* dataRefName, type data) { SetDataRef(dataRefName, data, code##Data); } #define DEFINE_DATA_SET_VECTOR(code, type) \ XPLM_API void XPHarnessSetDataRef##code##v (const char* dataRefName, type* data, int size) { SetDataRef(dataRefName, vector<type>(data, data + size), code##vData); } DEFINE_DATA_SET(i, int) DEFINE_DATA_SET_VECTOR(i, int) DEFINE_DATA_SET(f, float) DEFINE_DATA_SET_VECTOR(f, float) DEFINE_DATA_SET(d, double) DEFINE_DATA_SET_VECTOR(b, BYTE) XPLM_API XPLMPluginID XPLMGetMyID(void) { return 1; } XPLM_API void XPLMDebugString( const char * inString) { std::cout << inString; } XPLM_API void XPLMEnableFeature( const char * inFeature, int inEnable) { // Not implemented. } XPLM_API void XPLMGetPluginInfo( XPLMPluginID inPlugin, char * outName, /* Can be NULL */ char * outFilePath, /* Can be NULL */ char * outSignature, /* Can be NULL */ char * outDescription) /* Can be NULL */ { if (outName) strcp(outName, "XPLMTestHarness"); if (outFilePath) { std::string hostPath; GetEntrypointExecutableAbsolutePath(hostPath); strcp(outFilePath, hostPath.c_str()); } if (outSignature) strcp(outSignature, "1234"); if (outDescription) strcp(outDescription, "Info provided by the test harness for XPNet, which simulates the X-Plane API."); } XPLM_API XPLMDataRef XPLMFindDataRef( const char * inDataRefName) { # define TryReturnDataRef(name, container) { auto it = container.find(name); if (it != container.end()) return it->second; } TryReturnDataRef(inDataRefName, iData); TryReturnDataRef(inDataRefName, ivData); TryReturnDataRef(inDataRefName, fData); TryReturnDataRef(inDataRefName, fvData); TryReturnDataRef(inDataRefName, dData); TryReturnDataRef(inDataRefName, bvData); return nullptr; } XPLM_API XPLMDataTypeID XPLMGetDataRefTypes( XPLMDataRef inDataRef) { XPLMDataTypeID types = 0; if (FindDataRef(inDataRef, iData)) types |= xplmType_Int; if (FindDataRef(inDataRef, ivData)) types |= xplmType_IntArray; if (FindDataRef(inDataRef, fData)) types |= xplmType_Float; if (FindDataRef(inDataRef, fvData)) types |= xplmType_FloatArray; if (FindDataRef(inDataRef, dData)) types |= xplmType_Double; if (FindDataRef(inDataRef, bvData)) types |= xplmType_Data; return types; } XPLM_API int XPLMGetDatai( XPLMDataRef inDataRef) { auto d = FindDataRef(inDataRef, iData); return d ? d->value : 0; } XPLM_API void XPLMSetDatai( XPLMDataRef inDataRef, int inValue) { auto d = FindDataRef(inDataRef, iData); if (!d) return; // Dataref isn't defined, can't set it. d->value = inValue; } XPLM_API float XPLMGetDataf( XPLMDataRef inDataRef) { auto d = FindDataRef(inDataRef, fData); return d ? d->value : 0; } XPLM_API void XPLMSetDataf( XPLMDataRef inDataRef, float inValue) { auto d = FindDataRef(inDataRef, fData); if (!d) return; // Dataref isn't defined, can't set it. d->value = inValue; } XPLM_API double XPLMGetDatad( XPLMDataRef inDataRef) { auto d = FindDataRef(inDataRef, dData); return d ? d->value : 0; } XPLM_API void XPLMSetDatad( XPLMDataRef inDataRef, double inValue) { auto d = FindDataRef(inDataRef, dData); if (!d) return; // Dataref isn't defined, can't set it. d->value = inValue; } XPLM_API int XPLMGetDatavi( XPLMDataRef inDataRef, int * outValues, /* Can be NULL */ int inOffset, int inMax) { auto d = FindDataRef(inDataRef, ivData); if (!d) return 0; if (outValues) std::copy_n(d->value.begin(), min(d->value.size(), inMax), outValues + inOffset); return static_cast<int>(d->value.size()); } XPLM_API void XPLMSetDatavi( XPLMDataRef inDataRef, int * inValues, int inoffset, int inCount) { auto d = FindDataRef(inDataRef, ivData); if (!d) return; // Dataref isn't defined, can't set it. d->value = vector<int>(inValues + inoffset, inValues + inoffset + inCount); } XPLM_API int XPLMGetDatavf( XPLMDataRef inDataRef, float * outValues, /* Can be NULL */ int inOffset, int inMax) { auto d = FindDataRef(inDataRef, fvData); if (!d) return 0; if (outValues) std::copy_n(d->value.begin(), min(d->value.size(), inMax), outValues + inOffset); return static_cast<int>(d->value.size()); } XPLM_API void XPLMSetDatavf( XPLMDataRef inDataRef, float * inValues, int inoffset, int inCount) { auto d = FindDataRef(inDataRef, fvData); if (!d) return; // Dataref isn't defined, can't set it. d->value = vector<float>(inValues + inoffset, inValues + inoffset + inCount); } XPLM_API int XPLMGetDatab( XPLMDataRef inDataRef, void * outValue, /* Can be NULL */ int inOffset, int inMaxBytes) { auto d = FindDataRef(inDataRef, bvData); if (!d) return 0; if (outValue) std::copy_n(d->value.begin(), min(d->value.size(), inMaxBytes), reinterpret_cast<BYTE*>(outValue) + inOffset); return static_cast<int>(d->value.size()); } XPLM_API void XPLMSetDatab( XPLMDataRef inDataRef, void * inValue, int inOffset, int inLength) { auto d = FindDataRef(inDataRef, bvData); if (!d) return; // Dataref isn't defined, can't set it. BYTE* inValueBytes = reinterpret_cast<BYTE*>(inValue); d->value = vector<BYTE>(inValueBytes + inOffset, inValueBytes + inOffset + inLength); } XPLM_API void XPHarnessSetCommandCallback(const char* commandName, CommandCallback cb) { configuredCommands.emplace(commandName, command(commandName, cb)); } XPLM_API XPLMCommandRef XPLMFindCommand( const char * inName) { auto it = configuredCommands.find(inName); if (it != configuredCommands.end()) return it->second; return nullptr; } XPLM_API void XPLMCommandBegin( XPLMCommandRef inCommand) { auto c = FindCommand(inCommand, configuredCommands); if (!c) return; // Command isn't defined, can't invoke it. c->callback(CommandPhase_Begin); } XPLM_API void XPLMCommandEnd( XPLMCommandRef inCommand) { auto c = FindCommand(inCommand, configuredCommands); if (!c) return; // Command isn't defined, can't invoke it. c->callback(CommandPhase_End); } XPLM_API void XPLMCommandOnce( XPLMCommandRef inCommand) { auto c = FindCommand(inCommand, configuredCommands); if (!c) return; // Command isn't defined, can't invoke it. c->callback(CommandPhase_Once); } XPLM_API float XPLMGetElapsedTime(void) { return 4242.0f; } XPLM_API int XPLMGetCycleNumber(void) { return 84848484; } XPLM_API void XPLMRegisterFlightLoopCallback( XPLMFlightLoop_f inFlightLoop, float inInterval, void * inRefcon) { registeredFlightLoops.emplace(inFlightLoop, flightloop(inFlightLoop, inInterval)); } XPLM_API void XPLMUnregisterFlightLoopCallback( XPLMFlightLoop_f inFlightLoop, void * inRefcon) { auto cb = registeredFlightLoops.find(inFlightLoop); cb->second.deleted = true; } XPLM_API void XPLMSetFlightLoopCallbackInterval( XPLMFlightLoop_f inFlightLoop, float inInterval, int inRelativeToNow, void * inRefcon) { // ENHANCE: Implement. } XPLM_API XPLMFlightLoopID XPLMCreateFlightLoop( XPLMCreateFlightLoop_t * inParams) { // Not implemented b/c we don't use it in XPNet. return nullptr; } XPLM_API void XPLMDestroyFlightLoop( XPLMFlightLoopID inFlightLoopID) { // Not implemented b/c we don't use it in XPNet. } XPLM_API void XPLMScheduleFlightLoop( XPLMFlightLoopID inFlightLoopID, float inInterval, int inRelativeToNow) { // Not implemented b/c we don't use it in XPNet. } XPLM_API int XPLMRegisterDrawCallback( XPLMDrawCallback_f inCallback, XPLMDrawingPhase inPhase, int inWantsBefore, void * inRefcon) { registeredDrawCallbacks.emplace(make_tuple(inCallback, inPhase, inWantsBefore), drawcallback(inCallback, inPhase, inWantsBefore)); return 1; } XPLM_API int XPLMUnregisterDrawCallback( XPLMDrawCallback_f inCallback, XPLMDrawingPhase inPhase, int inWantsBefore, void * inRefcon) { auto cb = registeredDrawCallbacks.find(make_tuple(inCallback, inPhase, inWantsBefore)); cb->second.deleted = true; return 1; } XPLM_API XPLMProbeRef XPLMCreateProbe( XPLMProbeType inProbeType) { std::cout << "XPLMTestHarness: Created probe of type " << inProbeType << std::endl; return reinterpret_cast<XPLMProbeRef>(static_cast<uintptr_t>(43)); } XPLM_API void XPLMDestroyProbe( XPLMProbeRef inProbe) { std::cout << "XPLMTestHarness: Destroyed probe with reference " << inProbe << std::endl; } XPLM_API XPLMProbeResult XPLMProbeTerrainXYZ( XPLMProbeRef inProbe, float inX, float inY, float inZ, XPLMProbeInfo_t * outInfo) { std::cout << "XPLMTestHarness: Invoked XPLMProbeTerrainXYZ with X " << inX << ", Y " << inY << ", Z " << inZ << std::endl; outInfo->locationX = inX; outInfo->locationY = 42; outInfo->locationZ = inZ; return xplm_ProbeHitTerrain; } XPLM_API XPLMObjectRef XPLMLoadObject( const char * inPath) { return reinterpret_cast<XPLMObjectRef>(static_cast<uintptr_t>(42)); } XPLM_API void XPLMLoadObjectAsync( const char * inPath, XPLMObjectLoaded_f inCallback, void * inRefcon) { inCallback(reinterpret_cast<XPLMObjectRef>(static_cast<uintptr_t>(42)), nullptr); } XPLM_API void XPLMDrawObjects( XPLMObjectRef inObject, int inCount, XPLMDrawInfo_t * inLocations, int lighting, int earth_relative) { std::cout << "XPLMTestHarness: Drawing object " << inObject << std::endl; } XPLM_API void XPLMUnloadObject( XPLMObjectRef inObject) { std::cout << "XPLMTestHarness: Unloading object " << inObject << std::endl; } XPLM_API int XPLMLookupObjects( const char * inPath, float inLatitude, float inLongitude, XPLMLibraryEnumerator_f enumerator, void * ref) { std::string fullPath ("/realpath/"); fullPath.append(inPath); enumerator(fullPath.c_str(), ref); return 1; } XPLM_API void XPLMWorldToLocal( double inLatitude, double inLongitude, double inAltitude, double * outX, double * outY, double * outZ) { std::cout << "XPLMTestHarness: Invoked XPLMWorldToLocal with lat " << inLatitude << ", lon " << inLongitude << ", alt " << inAltitude << std::endl; *outX = inLongitude; *outY = inAltitude; *outZ = inLatitude; } XPLM_API void XPLMLocalToWorld( double inX, double inY, double inZ, double * outLatitude, double * outLongitude, double * outAltitude) { std::cout << "XPLMTestHarness: Invoked XPLMLocalToWorld with X " << inX << ", Y " << inY << ", Z " << inZ << std::endl; *outLongitude = inX; *outAltitude = inY; *outLatitude = inZ; } XPLM_API void XPHarnessInvokeFlightLoop(float elapsedSinceLastCall, float elapsedTimeSinceLastFlightLoop, int counter) { // Before invoking clean up all the unregistered flight loops. auto it = registeredFlightLoops.begin(); while (it != registeredFlightLoops.end()) { if (it->second.deleted) it = registeredFlightLoops.erase(it); else ++it; } for (auto p = registeredFlightLoops.begin(); p != registeredFlightLoops.end(); ++p) p->first(elapsedSinceLastCall, elapsedTimeSinceLastFlightLoop, counter, nullptr); } XPLM_API void XPHarnessInvokeDrawCallback() { // Before invoking clean up all the unregistered draw callbacks. auto it = registeredFlightLoops.begin(); while (it != registeredFlightLoops.end()) { if (it->second.deleted) it = registeredFlightLoops.erase(it); else ++it; } for (auto p = registeredDrawCallbacks.begin(); p != registeredDrawCallbacks.end(); ++p) p->second.drawCallback(p->second.drawingPhase, p->second.wantsBefore, nullptr); }
16,676
6,108
// Problem: https://leetcode.com/problems/sum-root-to-leaf-numbers/ #include "utils.h" namespace sum_root_to_leaf_numbers { struct TreeNode { int val; TreeNode* left; TreeNode* right; }; class Solution { public: // Note: Each node value must be within [0, 9]. Overflow of the sum is // not detected. // // Time: O(n), Space: O(h), Recursion depth <= h + 2 // n - number of nodes, h - height of the tree // int run(TreeNode* root) { return calculateSum(root).value; } private: struct Sum { int value; int multiplier; }; Sum calculateSum(TreeNode* root) const { if (!root) return {0, 0}; if (root->val < 0 || root->val > 9) throw std::runtime_error("Node value must be within [0, 9]"); Sum sum_left = calculateSum(root->left); Sum sum_right = calculateSum(root->right); Sum result; result.multiplier = std::max(sum_left.multiplier * 10 + sum_right.multiplier * 10, 1); result.value = sum_left.value + sum_right.value + root->val * result.multiplier; return result; } }; int main() { ASSERT( Solution().run(nullptr) == 0 ); ASSERT( Solution().run(TemporaryTree<TreeNode>(new TreeNode{0})) == 0 ); ASSERT( Solution().run(TemporaryTree<TreeNode>(new TreeNode{1})) == 1 ); ASSERT( Solution().run(TemporaryTree<TreeNode>(new TreeNode{9})) == 9 ); ASSERT( Solution().run( TemporaryTree<TreeNode>( new TreeNode{0, new TreeNode{1}, nullptr } )) == 1 ); ASSERT( Solution().run( TemporaryTree<TreeNode>( new TreeNode{0, new TreeNode{0, new TreeNode{1}, nullptr }, nullptr } )) == 1 ); ASSERT( Solution().run( TemporaryTree<TreeNode>( new TreeNode{1, new TreeNode{0}, nullptr } )) == 10 ); ASSERT( Solution().run( TemporaryTree<TreeNode>( new TreeNode{1, nullptr, new TreeNode{0} } )) == 10 ); ASSERT( Solution().run( TemporaryTree<TreeNode>( new TreeNode{1, new TreeNode{9}, nullptr } )) == 19 ); ASSERT( Solution().run( TemporaryTree<TreeNode>( new TreeNode{1, new TreeNode{9}, new TreeNode{1} } )) == 30 ); ASSERT( Solution().run( TemporaryTree<TreeNode>( new TreeNode{1, new TreeNode{9}, new TreeNode{9} } )) == 38 ); ASSERT( Solution().run( TemporaryTree<TreeNode>( new TreeNode{1, new TreeNode{2, new TreeNode{4}, new TreeNode{5} }, new TreeNode{3, new TreeNode{6}, new TreeNode{7} }, } )) == 522 ); ASSERT( Solution().run( TemporaryTree<TreeNode>( new TreeNode{1, new TreeNode{2, new TreeNode{4, new TreeNode{1, nullptr, new TreeNode{0, new TreeNode{1}, nullptr } }, nullptr }, new TreeNode{5, nullptr, new TreeNode{9} } }, new TreeNode{3, new TreeNode{6, new TreeNode{0}, new TreeNode{1} }, new TreeNode{7, new TreeNode{2}, nullptr } }, } )) == 129453 ); return 0; } }
4,205
1,213
#include "ast_field.hpp" #include "ast_constexpr.hpp" #include "ast_ref.hpp" #include "ast_conv.hpp" #include "ast/ast_util.hpp" #include "symbol/qual_type.hpp" #include "symbol/symbol_lookup.hpp" #include "parsercontext.hpp" #include "driver.hpp" #include "tx_error.hpp" TxFieldValueNode* make_compound_symbol_expression( const TxLocation& ploc, const std::string& compoundName ) { TxIdentifier ci( compoundName ); TxFieldValueNode* node = nullptr; for ( auto it = ci.segments_cbegin(); it != ci.segments_cend(); it++ ) { node = new TxFieldValueNode( ploc, node, new TxIdentifierNode( ploc, *it ) ); } return node; } int get_reinterpretation_degree( TxExpressionNode* originalExpr, const TxActualType *requiredType ) { auto originalType = originalExpr->resolve_type( TXR_FULL_RESOLUTION ); if ( *originalType == *requiredType ) { //std::cerr << "Types equal: " << originalType << " == " << requiredType << std::endl; return 0; } // TODO: check if provided type is narrower than the expected type if ( auto_converts_to( originalExpr, requiredType ) ) return 2; #ifndef NO_IMPLICIT_REF_DEREF if ( requiredType->get_type_class() == TXTC_REFERENCE ) { if ( auto expRefTargetType = requiredType->target_type() ) { if ( originalType->is_a( *expRefTargetType ) ) { if ( !expRefTargetType.is_modifiable() ) return 3; // expression will be auto-wrapped with a reference-to node } } } if ( originalType->get_type_class() == TXTC_REFERENCE ) { if ( auto provRefTargetType = originalType->target_type() ) { if ( provRefTargetType->auto_converts_to( *requiredType ) ) { return 3; // expression will be wrapped with a dereference node } } } #endif return -1; // does not match } static const TxFieldDeclaration* inner_resolve_field( const TxExpressionNode* origin, TxEntitySymbol* entitySymbol, const std::vector<TxExpressionNode*>* arguments, bool printCandidates ) { if ( !arguments ) { if ( entitySymbol->field_count() == 1 ) return entitySymbol->get_first_field_decl(); if ( entitySymbol->field_count() > 1 ) LOG_DEBUG( origin->LOGGER(), entitySymbol << " must be resolved using type parameters but none provided from " << origin ); return nullptr; } if ( entitySymbol->field_count() == 0 ) return nullptr; const TxFieldDeclaration* closestDecl = nullptr; uint64_t closestReint = UINT64_MAX; for ( auto fieldCandidateI = entitySymbol->fields_cbegin(); fieldCandidateI != entitySymbol->fields_cend(); fieldCandidateI++ ) { const TxFieldDeclaration* fieldDecl = ( *fieldCandidateI ); if ( !( fieldDecl->get_decl_flags() & TXD_EXPERROR ) ) { auto field = fieldDecl->get_definer()->resolve_field(); // first screen the fields that are of function type and take the correct number of arguments: if ( field->qtype()->get_type_class() == TXTC_FUNCTION ) { auto fieldType = field->qtype().type(); auto candArgTypes = fieldType->argument_types(); const TxActualType* arrayArgElemType = fieldType->vararg_elem_type(); if ( printCandidates ) CINFO( origin, " Candidate: " << field->get_unique_full_name() << " : " << fieldType->func_signature_str() ); if ( arrayArgElemType ) { // var-arg tail parameter accepts zero or more arguments if ( arguments->size() < candArgTypes.size() - 1 ) continue; // mismatching number of function args } else if ( auto fixedArrayArgType = fieldType->fixed_array_arg_type() ) { // fixed array parameter accepts matching number of arguments auto lenExpr = fixedArrayArgType->capacity(); auto len = eval_unsigned_int_constant( lenExpr ); if ( !( arguments->size() == 1 || arguments->size() == len ) ) continue; // mismatching number of function args arrayArgElemType = fixedArrayArgType->element_type().type(); } else if ( arguments->size() != candArgTypes.size() ) { continue; // mismatching number of function args } { // next check that the argument types match, and how close they match: uint16_t reint[4] = { 0, 0, 0, 0 }; for ( unsigned i = 0; i < arguments->size(); i++ ) { TxExpressionNode* argNode = arguments->at( i ); const TxActualType* argDef = ( arrayArgElemType && i >= candArgTypes.size() - 1 ? arrayArgElemType : candArgTypes.at( i ) ); int degree = get_reinterpretation_degree( argNode, argDef ); if ( degree < 0 ) { if ( arrayArgElemType && i == candArgTypes.size() - 1 && candArgTypes.size() == arguments->size() ) { // if last provided arg is an array of the correct type, match it against the var-arg tail if present //std::cerr << " cand-arg: " << candArgTypes.at( i ) << " prov-arg: " << argType << std::endl; degree = get_reinterpretation_degree( argNode, candArgTypes.at( i ) ); if ( degree < 0 ) goto NEXT_CANDIDATE; } else { //entitySymbol->LOGGER()->info("Argument mismatch, can't convert\n\tFrom: %80s\n\tTo: %80s", // argType->str(true).c_str(), argDef->str(true).c_str()); goto NEXT_CANDIDATE; } } reint[degree]++; } //origin->LOGGER()->trace( "Arguments match for %s: %-32s: %d, %d, %d, %d", field->str().c_str(), field->get_type()->str().c_str(), // reint[0], reint[1], reint[2], reint[3] ); uint64_t candReint = ( ( (uint64_t) reint[3] ) << 48 | ( (uint64_t) reint[2] ) << 32 | ( (uint64_t) reint[1] ) << 16 | reint[0] ); if ( candReint <= closestReint ) { if ( candReint == closestReint ) { // Note, multiple functions with the exact same signature is checked elsewhere. // If arguments for multiple "equal" top candidates are matched via reinterpretation, we just pick the first one found. // TODO: Pick the narrowest match, not the first found match //CWARNING(origin, "Ambiguous function call to " << entitySymbol->get_full_name() << ": " // << field->get_type() << ", multiple signatures match equally well " // << "[ " << reint[0] << ", " << reint[1] << ", " << reint[2] << ", " << reint[3] << " ]"); } else { closestDecl = *fieldCandidateI; closestReint = candReint; } } } } } NEXT_CANDIDATE: ; } if ( closestDecl ) { return closestDecl; } LOG_DEBUG( origin->LOGGER(), "Arguments do not match any overloaded candidate of " << entitySymbol ); return nullptr; } /** Attempts to resolve an identified entity symbol, that is potentially overloaded, * to a specific field by matching with the provided arguments' types. * The closest matching, valid field is picked. If no field matched, NULL is returned. * If a field was matched, and implicit conversions were needed for any arguments, * those conversions are inserted for those arguments within this call. * * All included fields that have the matching number of arguments and compatible argument types are candidates. * Candidate selection is done by counting the number and degree of argument reinterpretations necessary to match it. * (A single 2nd degree reinterpretation is "further away" than many 1st degree reinterpretations.) * * Degrees of reinterpretation (to be thought of as degrees of "distance"): * 0: Argument and receiver have the exact same type * 1: Argument and receiver have equivalent types (according to narrowing/widening type rules) * 2: Argument can be implicitly converted to the receiver's type (e.g. Int -> Long) * 3: Argument can be transformed via implicit operation to the receiver's type (e.g. implicit referencing) * * Generate compiler error and throws resolution exception if unsuccessful. */ static const TxFieldDeclaration* resolve_field( const TxExpressionNode* origin, TxEntitySymbol* entitySymbol, const std::vector<TxExpressionNode*>* arguments ) { if ( auto fieldDecl = inner_resolve_field( origin, entitySymbol, arguments, false ) ) { return fieldDecl; } else if ( arguments ) { // ensure arguments are resolved (doing it here ensures sensible signatures in error messages) for ( auto argNode : *arguments ) argNode->resolve_type( TXR_FULL_RESOLUTION ); // we expand the CERR_THROWRES macro here so that we can print the candidates before throwing the exception: std::stringstream msg; msg << entitySymbol->get_full_name() << " has no matching function for args: "; if ( arguments->empty() ) msg << "()"; else msg << "( " << join( attempt_typevec( arguments ), ", " ) << " )"; cerror(origin, msg.str()); inner_resolve_field( origin, entitySymbol, arguments, true ); throw resolution_error( origin, msg.str() ); // CERR_THROWRES( origin, entitySymbol->get_full_name() << " has no matching function for args: " // << "(" << join( attempt_typevec( arguments ), ", ") << ")" ); } else CERR_THROWRES( origin, entitySymbol->get_full_name() << " could not be resolved to a distinct field: " << entitySymbol->get_full_name() ); } const TxFieldDeclaration* resolve_constructor( TxExpressionNode* origin, const TxActualType* allocType, const std::vector<TxExpressionNode*>* appliedFuncArgs ) { // constructors aren't inherited, except for certain empty and VALUE derivations: auto constructionType = allocType->get_construction_type(); auto constrMember = lookup_member( origin->context().scope(), constructionType->get_declaration()->get_symbol(), CONSTR_IDENT ); if ( auto constructorSymbol = dynamic_cast<TxEntitySymbol*>( constrMember ) ) { auto constructorDecl = resolve_field( origin, constructorSymbol, appliedFuncArgs ); //std::cerr << "Resolved constructor " << constructorDecl << ": " << constructorDecl->get_definer()->qualtype() << " at " << origin << std::endl; ASSERT( constructorDecl->get_decl_flags() & ( TXD_CONSTRUCTOR | TXD_INITIALIZER ), "field named " CONSTR_IDENT " is not flagged as TXD_CONSTRUCTOR or TXD_INITIALIZER: " << constructorDecl->str() ); return constructorDecl; } CERR_THROWRES( origin, "No constructor '" << CONSTR_IDENT << "' found in type " << allocType ); } TxScopeSymbol* TxFieldValueNode::resolve_symbol() { if (this->symbol) return this->symbol; TxScopeSymbol* vantageScope = this->context().scope(); if ( this->baseExpr ) { // baseExpr may or may not refer to a type (e.g. modules don't) auto baseType = this->baseExpr->resolve_type( TXR_FULL_RESOLUTION ); if ( baseType->get_type_class() == TXTC_VOID ) { if ( auto baseFieldExpr = dynamic_cast<TxFieldValueNode*>( this->baseExpr ) ) { // base is a non-entity symbol this->symbol = lookup_member( vantageScope, baseFieldExpr->resolve_symbol(), this->symbolName->ident() ); } else CERR_THROWRES( this, "Base expression of field member operator '.' has no type." ); } else { if ( baseType->get_type_class() == TXTC_REFERENCE ) { if ( auto baseValExpr = dynamic_cast<TxExpressionNode*>( this->baseExpr )) { // implicit dereferencing ('^') operation: baseType = baseType->target_type(); //std::cerr << "Adding implicit '^' to: " << this->baseExpr << " six=" << six << std::endl; auto derefNode = new TxReferenceDerefNode( this->baseExpr->ploc, baseValExpr ); this->baseExpr = derefNode; inserted_node( derefNode, this, "deref" ); } } // base is a type or value expression this->symbol = lookup_inherited_member( vantageScope, baseType.type(), this->symbolName->ident() ); } } else { this->symbol = search_name( vantageScope, this->symbolName->ident() ); } return this->symbol; } const TxEntityDeclaration* TxFieldValueNode::resolve_decl() { if ( this->declaration ) return this->declaration; // if ( get_node_id() == 6442 ) // std::cerr << "HERE " << this << std::endl; if ( auto symb = this->resolve_symbol() ) { if ( auto entitySymbol = dynamic_cast<TxEntitySymbol*>( symb ) ) { // if symbol can be resolved to actual field, then do so if ( entitySymbol->field_count() ) { this->declaration = resolve_field( this, entitySymbol, this->appliedFuncArgs ); this->ploc.parserCtx->driver().add_reachable( this->declaration->get_definer() ); return this->declaration; } // if symbol is a type, and arguments are applied, and they match a constructor, then resolve to that constructor if ( auto typeDecl = entitySymbol->get_type_decl() ) { this->ploc.parserCtx->driver().add_reachable( typeDecl->get_definer() ); if ( this->appliedFuncArgs ) { auto allocType = typeDecl->get_definer()->resolve_type( TXR_FULL_RESOLUTION ); // find the constructor (note, constructors aren't inherited, except for certain empty and VALUE derivations): this->declaration = resolve_constructor( this, allocType.type(), this->appliedFuncArgs ); if ( this->declaration != typeDecl ) this->ploc.parserCtx->driver().add_reachable( this->declaration->get_definer() ); this->constructedType = allocType.type(); return this->declaration; } else { // resolve this symbol to its type this->declaration = typeDecl; return this->declaration; } } CERR_THROWRES( this, "Symbol " << entitySymbol << " could not be resolved to a distinct type or field: " << this->get_full_identifier() ); } else { //not an error, symbol is not an entity but valid //CERROR(this, "Symbol is not a field or type: " << this->get_full_identifier()); return nullptr; } } else { if ( this->baseExpr ) CERR_THROWRES( this, "Unknown symbol '" << this->get_full_identifier() << "' (base expression type is " << this->baseExpr->qtype() << ")" ); else CERR_THROWRES( this, "Unknown symbol '" << this->get_full_identifier() << "'" ); } // function returns or throws resolution exception before this ASSERT( false, "unexpected execution point in " << this ); return nullptr; } TxQualType TxFieldValueNode::define_type( TxTypeResLevel typeResLevel ) { // if ( get_node_id() = =6442 ) // std::cerr << "HERE " << this << std::endl; if ( auto decl = this->resolve_decl() ) { if ( auto fieldDecl = dynamic_cast<const TxFieldDeclaration*>( decl ) ) { this->_field = fieldDecl->get_definer()->resolve_field(); if ( fieldDecl->get_storage() == TXS_INSTANCE || fieldDecl->get_storage() == TXS_INSTANCEMETHOD ) { if ( !( fieldDecl->get_decl_flags() & ( TXD_CONSTRUCTOR | TXD_INITIALIZER | TXD_GENPARAM | TXD_GENBINDING ) ) ) { if ( this->baseExpr ) { if ( auto baseSymbolNode = dynamic_cast<TxFieldValueNode*>( this->baseExpr ) ) { if ( !baseSymbolNode->field() ) { CERR_THROWRES( this, "Instance member field referenced without instance base: " << this->get_full_identifier() ); } } } else { CERR_THROWRES( this, "Instance member field referenced without instance base: " << this->get_full_identifier() ); } } } return this->_field->qtype(); } else return decl->get_definer()->resolve_type( typeResLevel ); } // Symbol is not a field or type, return Void as placeholder type return TxQualType( this->registry().get_builtin_type( TXBT_VOID ) ); } bool TxFieldValueNode::is_value() const { ASSERT( this->is_context_set(), "can't call is_value() before declaration pass is run for " << this ); return this->_field; } const TxExpressionNode* TxFieldValueNode::get_data_graph_origin_expr() const { if ( auto baseValExpr = dynamic_cast<TxExpressionNode*>( this->baseExpr ) ) { if ( auto fieldBase = dynamic_cast<TxFieldValueNode*>( baseValExpr ) ) { if ( !fieldBase->field() ) return nullptr; // baseExpr identifies a namespace } return baseValExpr; } return nullptr; } TxFieldStorage TxFieldValueNode::get_storage() const { if ( this->_field->get_storage() == TXS_VIRTUAL && !this->baseExpr ) return TXS_STATIC; return this->_field->get_storage(); } bool TxFieldValueNode::is_statically_constant() const { // if (get_node_id()==2893) // std::cerr << "is_statically_constant() in " << this << std::endl; if ( this->_field ) { // A field is statically constant if it is unmodifiable, isn't virtual, and has a statically constant initializer or base expression auto storage = this->get_storage(); if ( auto initExpr = this->_field->get_declaration()->get_definer()->get_init_expression() ) { if ( storage == TXS_VIRTUAL || storage == TXS_INSTANCEMETHOD ) return false; return ( !this->_field->qtype().is_modifiable() && initExpr->is_statically_constant() ); } else if ( storage == TXS_INSTANCE ) { if ( auto baseValExpr = dynamic_cast<TxExpressionNode*>( this->baseExpr ) ) { return baseValExpr->is_statically_constant(); } } // FUTURE: allow a virtual field lookup, with a constant base expression, to behave as a static field lookup (i.e. non-polymorphic) // FUTURE: support getting instance method lambda object of statically constant objects return false; } else if ( this->symbol ) { return true; } else return false; } void TxNamedFieldNode::verification_pass() const { // if ( !dynamic_cast<const TxFieldValueNode*>( this->parent() ) ) { if ( auto declaration = this->exprNode->get_declaration() ) if ( !dynamic_cast<const TxFieldDeclaration*>( declaration ) ) CERROR( this, "'" << this->exprNode->get_full_identifier() << "' resolved to a type, not a field: " << declaration ); // } } void TxFieldAssigneeNode::verification_pass() const { if ( auto declaration = this->fieldNode->get_declaration() ) { if ( auto fieldDecl = dynamic_cast<const TxFieldDeclaration*>( declaration ) ) { if ( fieldDecl->get_storage() == TXS_NOSTORAGE ) CERROR( this, "Assignee '" << fieldNode->symbolName << "' is not an L-value / has no storage." ); } else CERROR( this, "'" << this->fieldNode->get_full_identifier() << "' resolved to a type, not a field: " << declaration ); } }
20,996
5,833
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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. * *=========================================================================*/ #ifndef itkSceneSpatialObject_hxx #define itkSceneSpatialObject_hxx #include "itkSceneSpatialObject.h" #include <algorithm> namespace itk { /** Constructor */ template< unsigned int TSpaceDimension > SceneSpatialObject< TSpaceDimension > ::SceneSpatialObject() : m_ParentId(0) {} /** Destructor */ template< unsigned int TSpaceDimension > SceneSpatialObject< TSpaceDimension > ::~SceneSpatialObject() {} /** Add a spatial object to the SceneSpatialObject */ template< unsigned int TSpaceDimension > void SceneSpatialObject< TSpaceDimension > ::AddSpatialObject(SpatialObject< TSpaceDimension > *pointer) { m_Objects.push_back(pointer); this->Modified(); } /** Remove a spatial object from the SceneSpatialObject */ template< unsigned int TSpaceDimension > void SceneSpatialObject< TSpaceDimension > ::RemoveSpatialObject(SpatialObject< TSpaceDimension > *pointer) { typename ObjectListType::iterator it; it = std::find(m_Objects.begin(), m_Objects.end(), pointer); if ( it != m_Objects.end() ) { if ( *it == pointer ) { m_Objects.erase(it); this->Modified(); } } else { //throw an exception object to let user know that // he tried to remove an object // which is not in the list of the children. } } /** Return the modification time of the SceneSpatialObject */ template< unsigned int TSpaceDimension > ModifiedTimeType SceneSpatialObject< TSpaceDimension > ::GetMTime(void) const { typename ObjectListType::const_iterator it = m_Objects.begin(); typename ObjectListType::const_iterator itEnd = m_Objects.end(); ModifiedTimeType latestTime = Superclass::GetMTime(); ModifiedTimeType localTime; while ( it != itEnd ) { localTime = ( *it )->GetMTime(); if ( localTime > latestTime ) { latestTime = localTime; } it++; } return latestTime; } /** Returns a new list of objects in the scene */ template< unsigned int TSpaceDimension > typename SceneSpatialObject< TSpaceDimension >::ObjectListType * SceneSpatialObject< TSpaceDimension > ::GetObjects(unsigned int depth, char *name) { ObjectListType *newList = new ObjectListType; typename ObjectListType::const_iterator it = m_Objects.begin(); typename ObjectListType::const_iterator itEnd = m_Objects.end(); while ( it != itEnd ) { if ( name == ITK_NULLPTR || strstr(typeid( **it ).name(), name) ) { newList->push_back(*it); } if ( depth > 0 ) { typedef typename SpatialObject< TSpaceDimension >::ChildrenListType ChildListType; ChildListType *childList = dynamic_cast< SpatialObject< TSpaceDimension > * >( ( *it ).GetPointer() )-> GetChildren(depth - 1, name); typename ChildListType::const_iterator cIt = childList->begin(); typename ChildListType::const_iterator cItEnd = childList->end(); while ( cIt != cItEnd ) { newList->push_back( dynamic_cast< ObjectType * >( ( *cIt ).GetPointer() ) ); cIt++; } delete childList; } it++; } return newList; } /** Set the children list */ template< unsigned int TSpaceDimension > void SceneSpatialObject< TSpaceDimension > ::SetObjects(ObjectListType & children) { m_Objects = children; } /** Return the number of objects in the SceneSpatialObject */ template< unsigned int TSpaceDimension > unsigned int SceneSpatialObject< TSpaceDimension > ::GetNumberOfObjects(unsigned int depth, char *name) { typename ObjectListType::const_iterator it = m_Objects.begin(); typename ObjectListType::const_iterator itEnd = m_Objects.end(); unsigned int cnt = 0; while ( it != itEnd ) { if ( name == ITK_NULLPTR || strstr(typeid( **it ).name(), name) ) { cnt++; } it++; } it = m_Objects.begin(); itEnd = m_Objects.end(); if ( depth > 0 ) { while ( it != itEnd ) { cnt += ( dynamic_cast< SpatialObject< TSpaceDimension > * >( ( *it ).GetPointer() ) )-> GetNumberOfChildren(depth - 1, name); it++; } } return cnt; } /** Print the object */ template< unsigned int TSpaceDimension > void SceneSpatialObject< TSpaceDimension > ::PrintSelf(std::ostream & os, Indent indent) const { os << indent << "Number of objects: " << m_Objects.size() << std::endl; os << indent << "List of objects: "; typename ObjectListType::const_iterator it = m_Objects.begin(); typename ObjectListType::const_iterator itEnd = m_Objects.end(); while ( it != itEnd ) { os << "[" << ( *it ) << "] "; it++; } os << std::endl; Superclass::PrintSelf(os, indent); } /** Return a SpatialObject in the SceneSpatialObject * given a parent ID */ template< unsigned int TSpaceDimension > SpatialObject< TSpaceDimension > * SceneSpatialObject< TSpaceDimension > ::GetObjectById(int Id) { typename ObjectListType::iterator it = m_Objects.begin(); typename ObjectListType::iterator itEnd = m_Objects.end(); typedef typename SpatialObjectType::ChildrenListType ChildListType; ChildListType *cList; typename ChildListType::iterator cIt; typename ChildListType::iterator cItEnd; while ( it != itEnd ) { if ( ( *it )->GetId() == Id ) { return *it; } else { //cList = (dynamic_cast<SpatialObject<TSpaceDimension> *>(*it))-> // GetChildren(SpatialObjectType::MaximumDepth); cList = ( *it )->GetChildren(SpatialObjectType::MaximumDepth); cIt = cList->begin(); cItEnd = cList->end(); while ( cIt != cItEnd ) { if ( ( *cIt )->GetId() == Id ) { SpatialObject< TSpaceDimension > *tmp; tmp = *cIt; delete cList; return tmp; } cIt++; } delete cList; } it++; } return ITK_NULLPTR; } template< unsigned int TSpaceDimension > bool SceneSpatialObject< TSpaceDimension > ::FixHierarchy(void) { typename ObjectListType::iterator it = m_Objects.begin(); typename ObjectListType::iterator oldIt; typename ObjectListType::iterator itEnd = m_Objects.end(); bool ret = true; while ( it != itEnd ) { const int parentId = ( *it )->GetParentId(); if ( parentId >= 0 ) { SpatialObject< TSpaceDimension > *parentObject = static_cast< SpatialObject< TSpaceDimension > * > ( this->GetObjectById(parentId) ); if ( parentObject == ITK_NULLPTR ) { ret = false; ++it; } else { parentObject->AddSpatialObject( dynamic_cast< SpatialObject< TSpaceDimension > * > ( ( *it ).GetPointer() ) ); oldIt = it; ++it; m_Objects.erase(oldIt); } } else { ++it; } } return ret; } /** Check if the parent objects have a defined ID */ template< unsigned int TSpaceDimension > bool SceneSpatialObject< TSpaceDimension > ::CheckIdValidity(void) { typename ObjectListType::iterator it = m_Objects.begin(); typename ObjectListType::iterator itEnd = m_Objects.end(); bool ret = true; while ( it != itEnd ) { // For every object in the scene we check the ID validity typename ObjectType::ChildrenListType * children = ( *it )->GetChildren(); typename ObjectType::ChildrenListType::const_iterator itChild = children->begin(); while ( itChild != children->end() ) { if ( ( *itChild )->HasParent() ) { if ( ( *itChild )->GetParent()->GetId() < 0 ) { delete children; return false; } } itChild++; } delete children; it++; } return ret; } template< unsigned int TSpaceDimension > void SceneSpatialObject< TSpaceDimension > ::FixIdValidity(void) { typename ObjectListType::iterator it = m_Objects.begin(); typename ObjectListType::iterator itEnd = m_Objects.end(); while ( it != itEnd ) { // For every object in the scene we check the ID validity typename ObjectType::ChildrenListType * children = ( *it )->GetChildren(); typename ObjectType::ChildrenListType::iterator itChild = children->begin(); while ( itChild != children->end() ) { if ( ( *itChild )->HasParent() ) { if ( ( *itChild )->GetParent()->GetId() < 0 ) { ( *itChild )->GetParent()->SetId( this->GetNextAvailableId() ); } } itChild++; } delete children; it++; } } /** Return the next available Id. For speed reason the MaxID+1 is returned */ template< unsigned int TSpaceDimension > int SceneSpatialObject< TSpaceDimension > ::GetNextAvailableId() { int Id = 0; typename ObjectListType::iterator it = m_Objects.begin(); typename ObjectListType::iterator itEnd = m_Objects.end(); while ( it != itEnd ) { typename ObjectType::ChildrenListType * children = ( *it )->GetChildren(); typename ObjectType::ChildrenListType::iterator itChild = children->begin(); while ( itChild != children->end() ) { if ( ( *itChild )->GetId() >= Id ) { Id = ( *itChild )->GetId() + 1; } itChild++; } delete children; it++; } return Id; } /** Clear function : Remove all the objects in the scene */ template< unsigned int TSpaceDimension > void SceneSpatialObject< TSpaceDimension > ::Clear() { m_Objects.clear(); this->Modified(); } } // end of namespace itk #endif
10,659
3,404
/* * encode.hpp * * Copyright (c) 2018, Ueda Laboratory LMNtal Group * <lmntal@ueda.info.waseda.ac.jp> 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 Ueda Laboratory LMNtal 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 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SLIM_VERIFIER_MEM_ENCODE_ENCODER_HPP #define SLIM_VERIFIER_MEM_ENCODE_ENCODER_HPP #include "../visitlog.h" #include "binstr.hpp" #include "vm/vm.h" #include <algorithm> #include <vector> namespace slim { namespace verifier { namespace mem_encode { class encoder { void write_mem_atoms(LmnMembraneRef mem, BinStrCursor &bsp, VisitLogRef visited) { if (!bsp.is_valid()) return; auto v = symbol_atom_range(mem); write_mols(v.begin(), v.end(), bsp, visited); } /* write_atomsの膜バージョン. * ここで書き込む計算する分子には膜のみが含まれている */ void write_mems(LmnMembraneRef mem, BinStrCursor &bsp, VisitLogRef visited) { BinStrCursor last_valid_bsp; CheckpointRef last_valid_checkpoint = nullptr; if (!bsp.is_valid()) return; bool last_valid = false; for (auto m = mem->mem_child_head(); m; m = m->mem_next()) { if (visited->get_mem(m, NULL)) continue; BinStrCursor new_bsptr = bsp; visited->set_checkpoint(); write_mem(m, 0, -1, -1, new_bsptr, visited, TRUE); if (new_bsptr.is_valid()) { /* mからたどった分子が書き込みに成功したので、last_validに記憶する */ if (last_valid) { delete last_valid_checkpoint; } last_valid_bsp = new_bsptr; last_valid_checkpoint = visited->pop_checkpoint(); last_valid = true; } else { visited->revert_checkpoint(); } } if (last_valid) { /* 書き込みに成功した分子をログに記録して、次の分子に進む */ visited->push_checkpoint(last_valid_checkpoint); write_mems(mem, last_valid_bsp, visited); if (last_valid_bsp.is_valid()) { bsp = last_valid_bsp; visited->commit_checkpoint(); } else { visited->revert_checkpoint(); } } } /* 膜memの全てのアトムのバイナリストリングを書き込む. * 辿ってきたアトムfrom_atomとそのアトムの属性attrとこちらからのリンク番号fromを受け取る. */ void write_mem(LmnMembraneRef mem, LmnAtomRef from_atom, LmnLinkAttr attr, int from, BinStrCursor &bsp, VisitLogRef visited, BOOL is_id) { LmnWord n_visited; if (!bsp.is_valid()) return; /* 訪問済み */ if (visited->get_mem(mem, &n_visited)) { bsp.push_visited_mem(n_visited); if (from_atom) { /* 引き続きアトムをたどる */ write_mol(from_atom, attr, from, bsp, visited, is_id); } return; } visited->put_mem(mem); bsp.push_start_mem(mem->NAME_ID()); if (!bsp.is_valid()) return; if (from_atom) { write_mol(from_atom, attr, from, bsp, visited, is_id); } /* アトム・膜・ルールセットの順に書込み */ if (is_id) { /* 膜に対して一意なIDとなるバイナリストリングへエンコードする場合 */ write_mem_atoms(mem, bsp, visited); write_mems(mem, bsp, visited); } else { /* 単なるバイナリストリングへエンコードする場合 */ dump_mem_atoms(mem, bsp, visited); dump_mems(mem, bsp, visited); /* 膜memに存在するデータアトムを起点にしたinside * proxyアトムをちゃんと書き込んでおく */ auto ent = mem->get_atomlist(LMN_IN_PROXY_FUNCTOR); if (ent) { for (auto in : *ent) { if (!LMN_ATTR_IS_DATA(in->get_attr(1)) || visited->get_atom(in, NULL)) { continue; } /* -------------------------+ * [DATA ATOM]-0--1-[in]-0--|--0-[out]-1--.. * -------------------------+ */ bsp.push_escape_mem_data(in->get_link(1), in->get_attr(1), visited); auto out = (LmnSymbolAtomRef)in->get_link(0); write_mol(out->get_link(1), out->get_attr(1), LMN_ATTR_GET_VALUE(out->get_attr(1)), bsp, visited, is_id); }; } } write_rulesets(mem, bsp); bsp.push_end_mem(); } /* アトムatomをバイナリストリングへ書き込む * 入力: * アトムatomと, atomのリンク属性attr, * アトムatomへ辿ってきた際に辿ったリンクと接続するリンク番号from, * エンコード領域bsp, 訪問管理visited, * is_idは計算するバイナリストリングがmem_idならば真 */ void write_mol(LmnAtomRef atom, LmnLinkAttr attr, int from, BinStrCursor &bsp, VisitLogRef visited, BOOL is_id) { LmnWord n_visited; if (!bsp.is_valid()) return; /* データアトムの場合 */ if (LMN_ATTR_IS_DATA(attr)) { bsp.push_data_atom(atom, attr, visited); return; } auto satom = reinterpret_cast<LmnSymbolAtomRef>(atom); auto f = satom->get_functor(); if (f == LMN_OUT_PROXY_FUNCTOR) { /* outside proxyの場合, inside proxy側の膜をwrite_memで書き込む */ auto in = (LmnSymbolAtomRef)satom->get_link(0); auto in_mem = LMN_PROXY_GET_MEM(in); if (visited->get_atom(in, NULL)) { visited->put_atom(in); } write_mem(in_mem, in->get_link(1), in->get_attr(1), LMN_ATTR_GET_VALUE(in->get_attr(1)), bsp, visited, is_id); } else if (f == LMN_IN_PROXY_FUNCTOR) { /* inside proxyの場合, 親膜へ抜ける旨を示すタグTAG_ESCAPE_MEMを書き込む. * その後, outside proxyから分子のトレース(write_mol)を引き続き実行する */ auto out = (LmnSymbolAtomRef)satom->get_link(0); bsp.push_escape_mem(); if (visited->get_atom(satom, NULL)) { visited->put_atom(satom); } write_mol(out->get_link(1), out->get_attr(1), LMN_ATTR_GET_VALUE(out->get_attr(1)), bsp, visited, is_id); } else if (!visited->get_atom(satom, &n_visited)) { /* 未訪問のシンボルアトムの場合 */ visited->put_atom(satom); bsp.push_atom(satom); if (!bsp.is_valid()) return; auto arity = LMN_FUNCTOR_GET_LINK_NUM(f); for (auto i_arg = 0; i_arg < arity; i_arg++) { if (i_arg == from) { /* 辿ってきたリンクに接続 */ bsp.push_from(); continue; } write_mol(satom->get_link(i_arg), satom->get_attr(i_arg), LMN_ATTR_GET_VALUE(satom->get_attr(i_arg)), bsp, visited, is_id); } } else { /* 訪問済のシンボルアトムの場合 */ bsp.push_visited_atom(n_visited, from); } } /* atomsに含まれるアトムを起点とする未訪問分子を、バイナリストリングが 最小となるように書き込む */ template <class Iterator> void write_mols(Iterator begin, Iterator end, BinStrCursor &bsp, VisitLogRef visited) { BinStrCursor last_valid_bsp; Iterator last_valid_it = end; int first_func = 0; CheckpointRef last_valid_checkpoint = nullptr; if (!bsp.is_valid()) return; /* atoms中の未訪問のアトムを起点とする分子を、それぞれ試みる */ for (auto it = begin; it != end; ++it) { LmnSymbolAtomRef atom = *it; if (LMN_IS_HL(atom)) continue; /* 最適化: 最小のファンクタ以外は試す必要なし */ if (last_valid_it != end && atom->get_functor() != first_func) break; if (visited->get_atom(atom, NULL)) continue; BinStrCursor new_bsptr = bsp; visited->set_checkpoint(); write_mol(atom, LMN_ATTR_MAKE_LINK(0), -1, new_bsptr, visited, TRUE); if (new_bsptr.is_valid()) { /* atomからたどった分子が書き込みに成功したので、last_validに記憶する */ if (last_valid_it == end) { first_func = atom->get_functor(); } else { delete last_valid_checkpoint; } last_valid_bsp = new_bsptr; last_valid_checkpoint = visited->pop_checkpoint(); last_valid_it = it; } else { visited->revert_checkpoint(); } } if (last_valid_it != end) { /* 書き込みに成功した分子をログに記録して、次の分子に進む */ auto t = *last_valid_it; *last_valid_it = 0; visited->push_checkpoint(last_valid_checkpoint); write_mols(begin, end, last_valid_bsp, visited); *last_valid_it = t; if (last_valid_bsp.is_valid()) { bsp = last_valid_bsp; visited->commit_checkpoint(); } else { visited->revert_checkpoint(); } } } void write_rulesets(LmnMembraneRef mem, BinStrCursor &bsp) { /* ルールセットがルールセットIDでソートされていることに基づいたコード */ auto n = mem->ruleset_num(); if (n == 0) return; bool has_uniq = FALSE; /* TODO: uniqルールセットが存在するか否かを検査するためだけに * O(ルールセット数)かかってしまうため. * ルールの移動や複製を行うプログラムで非効率 */ for (auto i = 0; i < n; i++) { if (lmn_mem_get_ruleset(mem, i)->has_unique()) { has_uniq = TRUE; break; } } if (!has_uniq) { bsp.push_start_rulesets(n); for (auto i = 0; i < n; i++) { bsp.push_ruleset(lmn_mem_get_ruleset(mem, i)); } } else { bsp.push_ruleset_uniq(mem, n); } } /* 膜memに存在する全てのアトムをファンクタIDの降順の列で求め, * 求めた列をdump_molsする */ void dump_mem_atoms(LmnMembraneRef mem, BinStrCursor &bsp, VisitLogRef visited) { dump_mols(symbol_atom_range(mem), bsp, visited); } /* アトム列atomsから, visitedに未登録のアトムに対し, write_molを行う * つまり, mhash同様に, 各アトムを起点とした分子単位でエンコードを行っている */ template <typename Container> void dump_mols(const Container &atoms, BinStrCursor &bsp, VisitLogRef visited) { /* atoms中の未訪問のアトムを起点とする分子を、それぞれ試みる */ for (auto atom : atoms) { if (visited->get_atom(atom, NULL) || LMN_IS_HL(atom)) continue; write_mol((LmnAtomRef)atom, LMN_ATTR_MAKE_LINK(0), -1, bsp, visited, FALSE); } } /* 膜中心の計算単位. 未訪問の子膜Xに対して, 子膜の分子を書き込み, * dump_memsへ再起する 兄弟膜は子膜内のプロセスを全て書き込んでから訪問される */ void dump_mems(LmnMembraneRef mem, BinStrCursor &bsp, VisitLogRef visited) { for (auto m = mem->mem_child_head(); m; m = m->mem_next()) { if (!visited->get_mem(m, NULL)) { write_mem(m, 0, -1, -1, bsp, visited, FALSE); } } } public: static LmnBinStr *encode(LmnMembraneRef mem, unsigned int tbl_size = 0 /* hint */) { encoder e(mem, false, tbl_size); auto visited = &e.visit_log; auto &bs = e.binstr; auto &bsp = e.cur; e.write_mem_atoms(mem, *bsp, visited); e.write_mems(mem, *bsp, visited); e.write_rulesets(mem, *bsp); return e.binary_string(); } static LmnBinStr *dump(LmnMembraneRef mem, unsigned long tbl_size = 0 /* hint */) { encoder e(mem, true, tbl_size); auto visitlog = &e.visit_log; auto &bs = e.binstr; auto &bsp = e.cur; e.dump_mem_atoms(mem, *bsp, visitlog); /* 1. アトムから */ e.dump_mems(mem, *bsp, visitlog); /* 2. 子膜から */ e.write_rulesets(mem, *bsp); /* 3. 最後にルール */ return e.binary_string(); } private: LmnMembraneRef root_mem; VisitLog visit_log; BinStr binstr; std::unique_ptr<BinStrCursor> cur; public: encoder(LmnMembraneRef mem, bool direct, unsigned int tbl_size = 0) : root_mem(mem), visit_log() { cur = direct ? binstr.head_direct() : binstr.head(); visit_log.init_with_size(tbl_size); } LmnBinStr *binary_string() { return binstr.to_lmn_binstr(); } }; } // namespace mem_encode } // namespace verifier } // namespace slim #endif /* SLIM_VERIFIER_MEM_ENCODE_ENCODER_HPP */
12,450
5,430
/***************************************************************** * Copyright (c) 2005 Héctor Daniel Guajardo, Tim de Jong * * * * All rights reserved. * * Distributed under the terms of the MIT License. * *****************************************************************/ #ifndef STRING_LIST_H #include "StringList.h" #endif /** * Constructor, creates the BList. */ StringList::StringList() : BList() { } /** * Destructor */ StringList::~StringList() { } /** * Redefined to return BString * . * @param index * @return <code> NULL </code> if the index is out of range. * Otherwise returs the BString at index. * @see BString::ItemAt */ BString* StringList::ItemAt(int32 index) { return (BString*) BList::ItemAt(index); } /** * Redefined to return BString * . * @param index * @return <code> NULL </code> if the index is out of range. * Otherwise returs the BString at index. * @see BString::RemoveItem */ BString& StringList::operator[](int index) { return (BString&) *ItemAt(index); } /** * To access the BString at the index given. * Be sure that the BString at index exists before calling this. * In case it does not it would return a reference to NULL. * @param index * @return <code> NULL </code> if the index is out of range. * Otherwise returs the BString at index. * @see BString::ItemAt */ BString* StringList::RemoveItem(int32 index) { return (BString*) BList::RemoveItem(index); } /** * Deletes the BStrings held by list. Not the list itself. * @param list */ void StringList::deleteStrings(StringList *list) { BString *anItem; while((anItem = list->RemoveItem((long)0))) delete anItem; }
1,726
564
//Copyright (c) 2016 Artem A. Mavrin and other contributors #pragma once //#include "DialogueSystemPrivatePCH.h" #include "QuestBook.h" FQuest UQuestBook::GetQuest(int32 ID) { FQuest Result; for (auto& elem : Quests) { if (elem.ID == ID) { Result = elem; break; } } return Result; } void UQuestBook::IncreaseLastID() { LastID++; } void UQuestBook::SetUniqueID() { IncreaseLastID(); for (auto& elem : Quests) { if (elem.ID == 0) { elem.ID = LastID; elem.QuestBook = this; break; } } }
567
263
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "wfa/virtual_people/common/field_filter/utils/field_util.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "common_cpp/testing/common_matchers.h" #include "common_cpp/testing/status_macros.h" #include "common_cpp/testing/status_matchers.h" #include "gmock/gmock.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" #include "google/protobuf/text_format.h" #include "gtest/gtest.h" #include "wfa/virtual_people/common/field_filter/test/test.pb.h" namespace wfa_virtual_people { namespace { using ::google::protobuf::FieldDescriptor; using ::google::protobuf::Message; using ::testing::FieldsAre; using ::wfa::EqualsProto; using ::wfa::IsOk; using ::wfa::IsOkAndHolds; using ::wfa::StatusIs; using ::wfa_virtual_people::test::TestProto; using ::wfa_virtual_people::test::TestProtoB; TEST(FieldUtilTest, GetFieldAndValue) { TestProto test_proto_1, test_proto_2; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( a { b { int32_value: 1 int64_value: 1 uint32_value: 1 uint64_value: 1 float_value: 1.0 double_value: 1.0 bool_value: true enum_value: TEST_ENUM_1 string_value: "string1" } } )pb", &test_proto_1)); ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( a { b { int32_value: 2 int64_value: 2 uint32_value: 2 uint64_value: 2 float_value: 2.0 double_value: 2.0 bool_value: false enum_value: TEST_ENUM_2 string_value: "string2" } } )pb", &test_proto_2)); // Test int32. absl::StatusOr<std::vector<const google::protobuf::FieldDescriptor*>> field_descriptors = GetFieldFromProto(test_proto_1.GetDescriptor(), "a.b.int32_value"); EXPECT_THAT(field_descriptors, IsOk()); EXPECT_THAT(GetValueFromProto<int32_t>(test_proto_2, *field_descriptors), FieldsAre(true, 2)); // Test int64. field_descriptors = GetFieldFromProto(test_proto_1.GetDescriptor(), "a.b.int64_value"); EXPECT_THAT(field_descriptors, IsOk()); EXPECT_THAT(GetValueFromProto<int64_t>(test_proto_2, *field_descriptors), FieldsAre(true, 2)); // Test uint32. field_descriptors = GetFieldFromProto(test_proto_1.GetDescriptor(), "a.b.uint32_value"); EXPECT_THAT(field_descriptors, IsOk()); EXPECT_THAT(GetValueFromProto<uint32_t>(test_proto_2, *field_descriptors), FieldsAre(true, 2)); // Test uint64. field_descriptors = GetFieldFromProto(test_proto_1.GetDescriptor(), "a.b.uint64_value"); EXPECT_THAT(field_descriptors, IsOk()); EXPECT_THAT(GetValueFromProto<uint64_t>(test_proto_2, *field_descriptors), FieldsAre(true, 2)); // Test float. field_descriptors = GetFieldFromProto(test_proto_1.GetDescriptor(), "a.b.float_value"); EXPECT_THAT(field_descriptors, IsOk()); EXPECT_THAT(GetValueFromProto<float>(test_proto_2, *field_descriptors), FieldsAre(true, 2.0)); // Test double. field_descriptors = GetFieldFromProto(test_proto_1.GetDescriptor(), "a.b.double_value"); EXPECT_THAT(field_descriptors, IsOk()); EXPECT_THAT(GetValueFromProto<double>(test_proto_2, *field_descriptors), FieldsAre(true, 2.0)); // Test bool. field_descriptors = GetFieldFromProto(test_proto_1.GetDescriptor(), "a.b.bool_value"); EXPECT_THAT(field_descriptors, IsOk()); EXPECT_THAT(GetValueFromProto<bool>(test_proto_2, *field_descriptors), FieldsAre(true, false)); // Test enum. field_descriptors = GetFieldFromProto(test_proto_1.GetDescriptor(), "a.b.enum_value"); EXPECT_THAT(field_descriptors, IsOk()); ProtoFieldValue<const google::protobuf::EnumValueDescriptor*> enum_value = GetValueFromProto<const google::protobuf::EnumValueDescriptor*>( test_proto_2, *field_descriptors); EXPECT_TRUE(enum_value.is_set); EXPECT_EQ(enum_value.value->number(), 2); // Test string. field_descriptors = GetFieldFromProto(test_proto_1.GetDescriptor(), "a.b.string_value"); EXPECT_THAT(field_descriptors, IsOk()); EXPECT_THAT( GetValueFromProto<const std::string&>(test_proto_2, *field_descriptors), FieldsAre(true, "string2")); // Test Message. field_descriptors = GetFieldFromProto(test_proto_1.GetDescriptor(), "a.b"); EXPECT_THAT(field_descriptors, IsOk()); EXPECT_THAT(GetValueFromProto<const google::protobuf::Message&>( test_proto_2, *field_descriptors), FieldsAre(true, EqualsProto(test_proto_2.a().b()))); } TEST(FieldUtilTest, GetValueForUnsetField) { TestProto test_proto; // Test int32. absl::StatusOr<std::vector<const google::protobuf::FieldDescriptor*>> field_descriptors = GetFieldFromProto(TestProto().GetDescriptor(), "a.b.int32_value"); EXPECT_THAT(field_descriptors, IsOk()); EXPECT_THAT(GetValueFromProto<int32_t>(test_proto, *field_descriptors), FieldsAre(false, 0)); // Test int64. field_descriptors = GetFieldFromProto(TestProto().GetDescriptor(), "a.b.int64_value"); EXPECT_THAT(field_descriptors, IsOk()); EXPECT_THAT(GetValueFromProto<int64_t>(test_proto, *field_descriptors), FieldsAre(false, 0)); // Test uint32. field_descriptors = GetFieldFromProto(TestProto().GetDescriptor(), "a.b.uint32_value"); EXPECT_THAT(field_descriptors, IsOk()); EXPECT_THAT(GetValueFromProto<uint32_t>(test_proto, *field_descriptors), FieldsAre(false, 0)); // Test uint64. field_descriptors = GetFieldFromProto(TestProto().GetDescriptor(), "a.b.uint64_value"); EXPECT_THAT(field_descriptors, IsOk()); EXPECT_THAT(GetValueFromProto<uint64_t>(test_proto, *field_descriptors), FieldsAre(false, 0)); // Test float. field_descriptors = GetFieldFromProto(TestProto().GetDescriptor(), "a.b.float_value"); EXPECT_THAT(field_descriptors, IsOk()); EXPECT_THAT(GetValueFromProto<float>(test_proto, *field_descriptors), FieldsAre(false, 0)); // Test double. field_descriptors = GetFieldFromProto(TestProto().GetDescriptor(), "a.b.double_value"); EXPECT_THAT(field_descriptors, IsOk()); EXPECT_THAT(GetValueFromProto<double>(test_proto, *field_descriptors), FieldsAre(false, 0)); // Test bool. field_descriptors = GetFieldFromProto(TestProto().GetDescriptor(), "a.b.bool_value"); EXPECT_THAT(field_descriptors, IsOk()); EXPECT_THAT(GetValueFromProto<bool>(test_proto, *field_descriptors), FieldsAre(false, false)); // Test enum. field_descriptors = GetFieldFromProto(TestProto().GetDescriptor(), "a.b.enum_value"); EXPECT_THAT(field_descriptors, IsOk()); ProtoFieldValue<const google::protobuf::EnumValueDescriptor*> enum_value = GetValueFromProto<const google::protobuf::EnumValueDescriptor*>( test_proto, *field_descriptors); EXPECT_FALSE(enum_value.is_set); EXPECT_EQ(enum_value.value->number(), 0); // Test string. field_descriptors = GetFieldFromProto(TestProto().GetDescriptor(), "a.b.string_value"); EXPECT_THAT(field_descriptors, IsOk()); EXPECT_THAT( GetValueFromProto<const std::string&>(test_proto, *field_descriptors), FieldsAre(false, "")); // Test Message. field_descriptors = GetFieldFromProto(TestProto().GetDescriptor(), "a.b"); EXPECT_THAT(field_descriptors, IsOk()); EXPECT_THAT(GetValueFromProto<const google::protobuf::Message&>( test_proto, *field_descriptors), FieldsAre(false, EqualsProto(TestProtoB()))); } TEST(FieldUtilTest, GetFieldAndSetValue) { TestProtoB test_b_proto; ASSERT_TRUE( google::protobuf::TextFormat::ParseFromString(R"pb( int32_value: 1 int64_value: 1 uint32_value: 1 uint64_value: 1 float_value: 1.0 double_value: 1.0 bool_value: true enum_value: TEST_ENUM_1 string_value: "string1" )pb", &test_b_proto)); std::vector<const google::protobuf::FieldDescriptor*> field_descriptors; // Test int32. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProtoB().GetDescriptor(), "int32_value")); SetValueToProto<int32_t>(test_b_proto, field_descriptors, 2); // Test int64. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProtoB().GetDescriptor(), "int64_value")); SetValueToProto<int64_t>(test_b_proto, field_descriptors, 2); // Test uint32. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProtoB().GetDescriptor(), "uint32_value")); SetValueToProto<uint32_t>(test_b_proto, field_descriptors, 2); // Test uint64. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProtoB().GetDescriptor(), "uint64_value")); SetValueToProto<uint64_t>(test_b_proto, field_descriptors, 2); // Test float. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProtoB().GetDescriptor(), "float_value")); SetValueToProto<float>(test_b_proto, field_descriptors, 2.0); // Test double. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProtoB().GetDescriptor(), "double_value")); SetValueToProto<double>(test_b_proto, field_descriptors, 2.0); // Test bool. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProtoB().GetDescriptor(), "bool_value")); SetValueToProto<bool>(test_b_proto, field_descriptors, false); // Test enum. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProtoB().GetDescriptor(), "enum_value")); SetValueToProto<const google::protobuf::EnumValueDescriptor*>( test_b_proto, field_descriptors, field_descriptors.back()->enum_type()->FindValueByNumber(2)); // Test string. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProtoB().GetDescriptor(), "string_value")); SetValueToProto<const std::string&>(test_b_proto, field_descriptors, "string2"); TestProtoB expected_test_b_proto; ASSERT_TRUE( google::protobuf::TextFormat::ParseFromString(R"pb( int32_value: 2 int64_value: 2 uint32_value: 2 uint64_value: 2 float_value: 2.0 double_value: 2.0 bool_value: false enum_value: TEST_ENUM_2 string_value: "string2" )pb", &expected_test_b_proto)); EXPECT_THAT(test_b_proto, EqualsProto(expected_test_b_proto)); } TEST(FieldUtilTest, GetFieldAndSetNestedValue) { TestProto test_proto; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( a { b { int32_value: 1 int64_value: 1 uint32_value: 1 uint64_value: 1 float_value: 1.0 double_value: 1.0 bool_value: true enum_value: TEST_ENUM_1 string_value: "string1" } } )pb", &test_proto)); std::vector<const google::protobuf::FieldDescriptor*> field_descriptors; // Test int32. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.int32_value")); SetValueToProto<int32_t>(test_proto, field_descriptors, 2); // Test int64. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.int64_value")); SetValueToProto<int64_t>(test_proto, field_descriptors, 2); // Test uint32. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.uint32_value")); SetValueToProto<uint32_t>(test_proto, field_descriptors, 2); // Test uint64. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.uint64_value")); SetValueToProto<uint64_t>(test_proto, field_descriptors, 2); // Test float. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.float_value")); SetValueToProto<float>(test_proto, field_descriptors, 2.0); // Test double. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.double_value")); SetValueToProto<double>(test_proto, field_descriptors, 2.0); // Test bool. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.bool_value")); SetValueToProto<bool>(test_proto, field_descriptors, false); // Test enum. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.enum_value")); SetValueToProto<const google::protobuf::EnumValueDescriptor*>( test_proto, field_descriptors, field_descriptors.back()->enum_type()->FindValueByNumber(2)); // Test string. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.string_value")); SetValueToProto<const std::string&>(test_proto, field_descriptors, "string2"); TestProto expected_test_proto; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( a { b { int32_value: 2 int64_value: 2 uint32_value: 2 uint64_value: 2 float_value: 2.0 double_value: 2.0 bool_value: false enum_value: TEST_ENUM_2 string_value: "string2" } } )pb", &expected_test_proto)); EXPECT_THAT(test_proto, EqualsProto(expected_test_proto)); } TEST(FieldUtilTest, GetFieldAndSetValueForUnsetParentMessage) { TestProto test_proto; std::vector<const google::protobuf::FieldDescriptor*> field_descriptors; // Test int32. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.int32_value")); SetValueToProto<int32_t>(test_proto, field_descriptors, 2); // Test int64. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.int64_value")); SetValueToProto<int64_t>(test_proto, field_descriptors, 2); // Test uint32. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.uint32_value")); SetValueToProto<uint32_t>(test_proto, field_descriptors, 2); // Test uint64. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.uint64_value")); SetValueToProto<uint64_t>(test_proto, field_descriptors, 2); // Test float. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.float_value")); SetValueToProto<float>(test_proto, field_descriptors, 2.0); // Test double. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.double_value")); SetValueToProto<double>(test_proto, field_descriptors, 2.0); // Test bool. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.bool_value")); SetValueToProto<bool>(test_proto, field_descriptors, false); // Test enum. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.enum_value")); SetValueToProto<const google::protobuf::EnumValueDescriptor*>( test_proto, field_descriptors, field_descriptors.back()->enum_type()->FindValueByNumber(2)); // Test string. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.string_value")); SetValueToProto<const std::string&>(test_proto, field_descriptors, "string2"); TestProto expected_test_proto; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( a { b { int32_value: 2 int64_value: 2 uint32_value: 2 uint64_value: 2 float_value: 2.0 double_value: 2.0 bool_value: false enum_value: TEST_ENUM_2 string_value: "string2" } } )pb", &expected_test_proto)); EXPECT_THAT(test_proto, EqualsProto(expected_test_proto)); } TEST(FieldUtilTest, InvalidFieldName) { TestProto test_proto; ASSERT_TRUE( google::protobuf::TextFormat::ParseFromString(R"pb( a { b { int64_value: 1 } } )pb", &test_proto)); absl::StatusOr<std::vector<const google::protobuf::FieldDescriptor*>> field_descriptors = GetFieldFromProto(test_proto.GetDescriptor(), "a.c"); EXPECT_THAT(field_descriptors.status(), StatusIs(absl::StatusCode::kInvalidArgument, "")); } TEST(FieldUtilTest, InvalidSubmessageName) { TestProto test_proto; ASSERT_TRUE( google::protobuf::TextFormat::ParseFromString(R"pb( a { b { int64_value: 1 } } )pb", &test_proto)); absl::StatusOr<std::vector<const google::protobuf::FieldDescriptor*>> field_descriptors = GetFieldFromProto(test_proto.GetDescriptor(), "a.b.int64_value.c"); EXPECT_THAT(field_descriptors.status(), StatusIs(absl::StatusCode::kInvalidArgument, "")); } TEST(FieldUtilTest, TestGetParentMessage) { ASSERT_OK_AND_ASSIGN( std::vector<const google::protobuf::FieldDescriptor*> field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.int32_value")); TestProto test_proto; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( a { b { int32_value: 1 int64_value: 1 uint32_value: 1 uint64_value: 1 float_value: 1.0 double_value: 1.0 bool_value: true enum_value: TEST_ENUM_1 string_value: "string1" int32_values: 1 int32_values: 2 } } )pb", &test_proto)); EXPECT_THAT(GetParentMessageFromProto(test_proto, field_descriptors), EqualsProto(test_proto.a().b())); } TEST(FieldUtilTest, DisallowRepeatedField) { // Any repeated field in the path except the last field is disallowed. EXPECT_THAT(GetFieldFromProto(TestProto().GetDescriptor(), "repeated_proto_a.b.int32_value") .status(), StatusIs(absl::StatusCode::kInvalidArgument, "")); // Any repeated field in the path except the last field is disallowed. EXPECT_THAT(GetFieldFromProto(TestProto().GetDescriptor(), "repeated_proto_a.b.int32_value", /* allow_repeated = */ true) .status(), StatusIs(absl::StatusCode::kInvalidArgument, "")); // Last field is disallowed to be repeated if @allow_repeated is set to false. EXPECT_THAT(GetFieldFromProto(TestProto().GetDescriptor(), "a.b.int32_values") .status(), StatusIs(absl::StatusCode::kInvalidArgument, "")); } TEST(FieldUtilTest, TestAllowRepeatedAndGetParentMessage) { ASSERT_OK_AND_ASSIGN( std::vector<const google::protobuf::FieldDescriptor*> field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.int32_values", /* allow_repeated = */ true)); TestProto test_proto; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( a { b { int32_value: 1 int64_value: 1 uint32_value: 1 uint64_value: 1 float_value: 1.0 double_value: 1.0 bool_value: true enum_value: TEST_ENUM_1 string_value: "string1" int32_values: 1 int32_values: 2 } } )pb", &test_proto)); EXPECT_THAT(GetParentMessageFromProto(test_proto, field_descriptors), EqualsProto(test_proto.a().b())); } TEST(FieldUtilTest, TestGetParentMessageParentNotSet) { ASSERT_OK_AND_ASSIGN( std::vector<const google::protobuf::FieldDescriptor*> field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.int32_value")); TestProto test_proto; EXPECT_THAT(GetParentMessageFromProto(test_proto, field_descriptors), EqualsProto(test_proto.a().b())); } TEST(FieldUtilTest, GetSizeOfRepeatedProto) { TestProto test_proto; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( a { b { int32_values: 1 int32_values: 1 } } )pb", &test_proto)); ASSERT_OK_AND_ASSIGN( std::vector<const google::protobuf::FieldDescriptor*> field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.int32_values", /*allow_repeated = */ true)); EXPECT_EQ(GetSizeOfRepeatedProto(test_proto, field_descriptors), 2); } TEST(FieldUtilTest, GetSizeOfRepeatedProtoEmptyField) { TestProto test_proto; ASSERT_OK_AND_ASSIGN( std::vector<const google::protobuf::FieldDescriptor*> field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.int32_values", /*allow_repeated = */ true)); EXPECT_EQ(GetSizeOfRepeatedProto(test_proto, field_descriptors), 0); } TEST(FieldUtilTest, GetRepeatedFieldAndValue) { TestProto test_proto; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString( R"pb( a { b { int32_values: 1 int32_values: 2 int64_values: 1 int64_values: 2 uint32_values: 1 uint32_values: 2 uint64_values: 1 uint64_values: 2 float_values: 1.0 float_values: 2.0 double_values: 1.0 double_values: 2.0 bool_values: true bool_values: false enum_values: TEST_ENUM_1 enum_values: TEST_ENUM_2 string_values: "string1" string_values: "string2" } } repeated_proto_a { b { int32_value: 1 } } repeated_proto_a { b { int32_value: 2 } } )pb", &test_proto)); std::vector<const google::protobuf::FieldDescriptor*> field_descriptors; // Test int32. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.int32_values", /*allow_repeated = */ true)); EXPECT_EQ( GetValueFromRepeatedProto<int32_t>(test_proto, field_descriptors, 1), 2); // Test int64. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.int64_values", /*allow_repeated = */ true)); EXPECT_EQ( GetValueFromRepeatedProto<int64_t>(test_proto, field_descriptors, 1), 2); // Test uint32. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.uint32_values", /*allow_repeated = */ true)); EXPECT_EQ( GetValueFromRepeatedProto<uint32_t>(test_proto, field_descriptors, 1), 2); // Test uint64. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.uint64_values", /*allow_repeated = */ true)); EXPECT_EQ( GetValueFromRepeatedProto<uint64_t>(test_proto, field_descriptors, 1), 2); // Test float. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.float_values", /*allow_repeated = */ true)); EXPECT_EQ(GetValueFromRepeatedProto<float>(test_proto, field_descriptors, 1), 2.0); // Test double. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.double_values", /*allow_repeated = */ true)); EXPECT_EQ(GetValueFromRepeatedProto<double>(test_proto, field_descriptors, 1), 2.0); // Test bool. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.bool_values", /*allow_repeated = */ true)); EXPECT_FALSE( GetValueFromRepeatedProto<bool>(test_proto, field_descriptors, 1)); // Test enum. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.enum_values", /*allow_repeated = */ true)); EXPECT_EQ( GetValueFromRepeatedProto<const google::protobuf::EnumValueDescriptor*>( test_proto, field_descriptors, 1) ->number(), 2); // Test string. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "a.b.string_values", /*allow_repeated = */ true)); EXPECT_EQ(GetValueFromRepeatedProto<const std::string&>(test_proto, field_descriptors, 1), "string2"); // Test Message. ASSERT_OK_AND_ASSIGN( field_descriptors, GetFieldFromProto(TestProto().GetDescriptor(), "repeated_proto_a", /*allow_repeated = */ true)); EXPECT_THAT(GetValueFromRepeatedProto<const google::protobuf::Message&>( test_proto, field_descriptors, 1), EqualsProto(test_proto.repeated_proto_a(1))); } } // namespace } // namespace wfa_virtual_people
27,459
9,381
#include "BrowserService.h" #include "BrowserService-marshaller.h" #include "MeeGoPluginAPI.h" static guint signals[LAST_SIGNAL] = { 0 }; G_DEFINE_TYPE(BrowserService, browser_service, G_TYPE_OBJECT); static void browser_service_init(BrowserService* bs) { //g_debug("browser_service_init"); } static void browser_service_class_init(BrowserServiceClass* klass) { //g_debug("browser_service_class_init"); signals[URL_VISITED_SIGNAL] = g_signal_new("url_visited", G_OBJECT_CLASS_TYPE(klass), (GSignalFlags)(G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED), 0, NULL, NULL, browser_service_marshal_VOID__INT64_STRING_STRING_STRING, G_TYPE_NONE, 4, G_TYPE_INT64, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING); signals[URL_REMOVED_SIGNAL] = g_signal_new("url_removed", G_OBJECT_CLASS_TYPE(klass), (GSignalFlags)(G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED), 0, NULL, NULL, g_cclosure_marshal_VOID__STRING, G_TYPE_NONE, 1, G_TYPE_STRING); signals[BOOKMARK_UPDATED_SIGNAL] = g_signal_new("bookmark_updated", G_OBJECT_CLASS_TYPE(klass), (GSignalFlags)(G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED), 0, NULL, NULL, browser_service_marshal_VOID__INT64_STRING_STRING_STRING, G_TYPE_NONE, 4, G_TYPE_INT64, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING); signals[BOOKMARK_REMOVED_SIGNAL] = g_signal_new("bookmark_removed", G_OBJECT_CLASS_TYPE(klass), (GSignalFlags)(G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED), 0, NULL, NULL, browser_service_marshal_VOID__INT64, G_TYPE_NONE, 1, G_TYPE_INT64); signals[FAVICON_UPDATED_SIGNAL] = g_signal_new("favicon_updated", G_OBJECT_CLASS_TYPE(klass), (GSignalFlags)(G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED), 0, NULL, NULL, g_cclosure_marshal_VOID__STRING, G_TYPE_NONE, 1, G_TYPE_STRING); signals[THUMBNAIL_UPDATED_SIGNAL] = g_signal_new("thumbnail_updated", G_OBJECT_CLASS_TYPE(klass), (GSignalFlags)(G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED), 0, NULL, NULL, g_cclosure_marshal_VOID__STRING, G_TYPE_NONE, 1, G_TYPE_STRING); signals[TAB_INFO_UPDATED_SIGNAL] = g_signal_new("tab_info_updated", G_OBJECT_CLASS_TYPE(klass), (GSignalFlags)(G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED), 0, NULL, NULL, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); signals[TAB_LIST_UPDATED_SIGNAL] = g_signal_new("tab_list_updated", G_OBJECT_CLASS_TYPE(klass), (GSignalFlags)(G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED), 0, NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); signals[BROWSER_LAUNCHED_SIGNAL] = g_signal_new("browser_launched", G_OBJECT_CLASS_TYPE(klass), (GSignalFlags)(G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED), 0, NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); signals[BROWSER_CLOSED_SIGNAL] = g_signal_new("browser_closed", G_OBJECT_CLASS_TYPE(klass), (GSignalFlags)(G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED), 0, NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); } BrowserService* browser_service_new(gpointer data) { BrowserService* obj = (BrowserService*)g_object_new(BROWSER_SERVICE_TYPE, NULL); obj->provider = data; return obj; } void browser_service_destroy(BrowserService* bs) { if(bs) g_object_unref(bs); } // // Browser service DBUS API implementation // gboolean browser_service_view_item(BrowserService* self, const char* url) { DBG("browser_service_view_item: %s", url); MeeGoPluginAPI* plugin = static_cast<MeeGoPluginAPI*>(self->provider); if(plugin) plugin->openWebPage(url); return TRUE; } gboolean browser_service_remove_bookmark(BrowserService* self, const char* id) { DBG("browser_service_remove_bookmark"); MeeGoPluginAPI* plugin = static_cast<MeeGoPluginAPI*>(self->provider); if(plugin) plugin->removeBookmarkByExtension(id); return TRUE; } gboolean browser_service_remove_url(BrowserService* self, const char* url) { DBG("browser_service_remove_url"); MeeGoPluginAPI* plugin = static_cast<MeeGoPluginAPI*>(self->provider); if(plugin) plugin->removeUrlByExtension(url); return TRUE; } gboolean browser_service_update_current_tab(BrowserService * self) { DBG("browser_service_close_tab"); MeeGoPluginAPI* plugin = static_cast<MeeGoPluginAPI*>(self->provider); if(plugin) plugin->updateCurrentTab(); return TRUE; } gboolean browser_service_refresh_tab_list(BrowserService* self) { DBG("browser_service_refresh_tab_list"); MeeGoPluginAPI* plugin = static_cast<MeeGoPluginAPI*>(self->provider); if(plugin) plugin->refreshTabList(); return TRUE; } gboolean browser_service_show_browser(BrowserService * self, const char * mode, const char * target) { DBG("browser_service_close_tab"); MeeGoPluginAPI* plugin = static_cast<MeeGoPluginAPI*>(self->provider); if(plugin) plugin->showBrowser(mode, target); return TRUE; } gboolean browser_service_close_tab(BrowserService * self, int index) { DBG("browser_service_close_tab"); MeeGoPluginAPI* plugin = static_cast<MeeGoPluginAPI*>(self->provider); if(plugin) plugin->closeTab(index); return TRUE; } gboolean browser_service_get_current_tab_index(BrowserService *self, int * index) { DBG("browser_service_close_tab"); MeeGoPluginAPI* plugin = static_cast<MeeGoPluginAPI*>(self->provider); if(plugin) *index = plugin->getCurrentTabIndex(); return TRUE; }
5,548
2,301
/* * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * Copyright (c) 2009 Helge Bahmann * Copyright (c) 2012 Tim Blechmann * Copyright (c) 2013 - 2014 Andrey Semashev */ /*! * \file atomic/detail/caps_gcc_x86.hpp * * This header defines feature capabilities macros */ #ifndef BOOST_ATOMIC_DETAIL_CAPS_GCC_X86_HPP_INCLUDED_ #define BOOST_ATOMIC_DETAIL_CAPS_GCC_X86_HPP_INCLUDED_ #include <boost/atomic/detail/config.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif #if defined(__i386__) &&\ (\ defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8) ||\ defined(__i586__) || defined(__i686__) || defined(__pentium4__) || defined(__nocona__) || defined(__core2__) || defined(__corei7__) ||\ defined(__k6__) || defined(__athlon__) || defined(__k8__) || defined(__amdfam10__) || defined(__bdver1__) || defined(__bdver2__) || defined(__bdver3__) || defined(__btver1__) || defined(__btver2__)\ ) #define BOOST_ATOMIC_DETAIL_X86_HAS_CMPXCHG8B 1 #endif #if defined(__x86_64__) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16) #define BOOST_ATOMIC_DETAIL_X86_HAS_CMPXCHG16B 1 #endif #define BOOST_ATOMIC_INT8_LOCK_FREE 2 #define BOOST_ATOMIC_INT16_LOCK_FREE 2 #define BOOST_ATOMIC_INT32_LOCK_FREE 2 #if defined(__x86_64__) || defined(BOOST_ATOMIC_DETAIL_X86_HAS_CMPXCHG8B) #define BOOST_ATOMIC_INT64_LOCK_FREE 2 #endif #if defined(BOOST_ATOMIC_DETAIL_X86_HAS_CMPXCHG16B) && (defined(BOOST_HAS_INT128) || !defined(BOOST_NO_ALIGNMENT)) #define BOOST_ATOMIC_INT128_LOCK_FREE 2 #endif #define BOOST_ATOMIC_POINTER_LOCK_FREE 2 #define BOOST_ATOMIC_THREAD_FENCE 2 #define BOOST_ATOMIC_SIGNAL_FENCE 2 #endif // BOOST_ATOMIC_DETAIL_CAPS_GCC_X86_HPP_INCLUDED_
1,793
847
/* ARPACK++ v1.2 2/18/2000 c++ interface to ARPACK code. MODULE ANSymShf.cc Example program that illustrates how to solve a real nonsymmetric standard eigenvalue problem in shift and invert mode using the AREig function. 1) Problem description: In this example we try to solve A*x = x*lambda in shift and invert mode, where A is derived from 2-D Brusselator Wave Model. The shift is a real number. 2) Data structure used to represent matrix A: {nnzA, irowA, pcolA, valA}: matrix A data in CSC format. 3) Library called by this example: The SuperLU package is called by AREig to solve some linear systems involving (A-sigma*I). This is needed to implement the shift and invert strategy. 4) Included header files: File Contents ----------- -------------------------------------------- lnmatrxa.h BrusselatorMatrix, a function that generates matrix A in CSC format. areig.h The AREig function definition. ansymsol.h The Solution function. 5) ARPACK Authors: Richard Lehoucq Kristyn Maschhoff Danny Sorensen Chao Yang Dept. of Computational & Applied Mathematics Rice University Houston, Texas */ #include "lnmatrxa.h" #include "areig.h" #include "ansymsol.h" int main() { // Defining variables; int n; // Dimension of the problem. int nconv; // Number of "converged" eigenvalues. int nnz; // Number of nonzero elements in A. int* irow; // pointer to an array that stores the row // indices of the nonzeros in A. int* pcol; // pointer to an array of pointers to the // beginning of each column of A in vector A. double* A; // pointer to an array that stores the // nonzero elements of A. double EigValR[101]; // Real part of the eigenvalues. double EigValI[101]; // Imaginary part of the eigenvalues. double EigVec[1201]; // Eigenvectors stored sequentially. // Creating a double precision matrix. n = 200; BrusselatorMatrix(1.0, 0.004, 0.008, 2.0, 5.45, n, nnz, A, irow, pcol); // Finding the four eigenvalues nearest to 0.0 and the // related eigenvectors. nconv = AREig(EigValR, EigValI, EigVec, n, nnz, A, irow, pcol, 0.0, 4); // Printing solution. Solution(nconv, n, nnz, A, irow, pcol, EigValR, EigValI, EigVec); } // main.
2,541
823
#include <iostream> using namespace std; int main(void) { int r, c, a, b; cin >> r >> c >> a >> b; for (int i = 0; i < r; i++) { for (int k = 0; k < a; k++) { for (int j = 0; j < c; j++) { if ((i + j) % 2 == 0) for (int si = 0; si < b; si++) cout << "X"; else for (int si = 0; si < b; si++) cout << "."; } cout << '\n'; } } }
379
217
/* * Copyright (C) 2011 Ericsson AB. All rights reserved. * Copyright (C) 2012 Google Inc. All rights reserved. * Copyright (C) 2013-2016 Apple Inc. All rights reserved. * Copyright (C) 2013 Nokia Corporation and/or its subsidiary(-ies). * * 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 Ericsson nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "UserMediaRequest.h" #if ENABLE(MEDIA_STREAM) #include "Document.h" #include "DocumentLoader.h" #include "JSMediaStream.h" #include "JSOverconstrainedError.h" #include "Logging.h" #include "MainFrame.h" #include "MediaConstraints.h" #include "RealtimeMediaSourceCenter.h" #include "Settings.h" #include "UserMediaController.h" namespace WebCore { ExceptionOr<void> UserMediaRequest::start(Document& document, MediaConstraints&& audioConstraints, MediaConstraints&& videoConstraints, DOMPromiseDeferred<IDLInterface<MediaStream>>&& promise) { auto* userMedia = UserMediaController::from(document.page()); if (!userMedia) return Exception { NotSupportedError }; // FIXME: Why is it better to return an exception here instead of rejecting the promise as we do just below? if (!audioConstraints.isValid && !videoConstraints.isValid) { promise.reject(TypeError); return { }; } adoptRef(*new UserMediaRequest(document, *userMedia, WTFMove(audioConstraints), WTFMove(videoConstraints), WTFMove(promise)))->start(); return { }; } UserMediaRequest::UserMediaRequest(Document& document, UserMediaController& controller, MediaConstraints&& audioConstraints, MediaConstraints&& videoConstraints, DOMPromiseDeferred<IDLInterface<MediaStream>>&& promise) : ContextDestructionObserver(&document) , m_audioConstraints(WTFMove(audioConstraints)) , m_videoConstraints(WTFMove(videoConstraints)) , m_controller(&controller) , m_promise(WTFMove(promise)) { } UserMediaRequest::~UserMediaRequest() { } SecurityOrigin* UserMediaRequest::userMediaDocumentOrigin() const { if (!m_scriptExecutionContext) return nullptr; return m_scriptExecutionContext->securityOrigin(); } SecurityOrigin* UserMediaRequest::topLevelDocumentOrigin() const { if (!m_scriptExecutionContext) return nullptr; return &m_scriptExecutionContext->topOrigin(); } static bool isSecure(DocumentLoader& documentLoader) { auto& response = documentLoader.response(); return response.url().protocolIs("https") && response.certificateInfo() && !response.certificateInfo()->containsNonRootSHA1SignedCertificate(); } static bool canCallGetUserMedia(Document& document, String& errorMessage) { bool requiresSecureConnection = document.settings().mediaCaptureRequiresSecureConnection(); if (requiresSecureConnection && !isSecure(*document.loader())) { errorMessage = "Trying to call getUserMedia from an insecure document."; return false; } auto& topDocument = document.topDocument(); if (&document != &topDocument) { auto& topOrigin = topDocument.topOrigin(); if (!document.securityOrigin().isSameSchemeHostPort(topOrigin)) { errorMessage = "Trying to call getUserMedia from a document with a different security origin than its top-level frame."; return false; } for (auto* ancestorDocument = document.parentDocument(); ancestorDocument != &topDocument; ancestorDocument = ancestorDocument->parentDocument()) { if (requiresSecureConnection && !isSecure(*ancestorDocument->loader())) { errorMessage = "Trying to call getUserMedia from a document with an insecure parent frame."; return false; } if (!ancestorDocument->securityOrigin().isSameSchemeHostPort(topOrigin)) { errorMessage = "Trying to call getUserMedia from a document with a different security origin than its top-level frame."; return false; } } } return true; } void UserMediaRequest::start() { if (!m_scriptExecutionContext || !m_controller) { deny(MediaAccessDenialReason::OtherFailure, emptyString()); return; } Document& document = downcast<Document>(*m_scriptExecutionContext); // 10.2 - 6.3 Optionally, e.g., based on a previously-established user preference, for security reasons, // or due to platform limitations, jump to the step labeled Permission Failure below. String errorMessage; if (!canCallGetUserMedia(document, errorMessage)) { deny(MediaAccessDenialReason::PermissionDenied, emptyString()); document.domWindow()->printErrorMessage(errorMessage); return; } m_controller->requestUserMediaAccess(*this); } void UserMediaRequest::allow(String&& audioDeviceUID, String&& videoDeviceUID, String&& deviceIdentifierHashSalt) { RELEASE_LOG(MediaStream, "UserMediaRequest::allow %s %s", audioDeviceUID.utf8().data(), videoDeviceUID.utf8().data()); m_allowedAudioDeviceUID = WTFMove(audioDeviceUID); m_allowedVideoDeviceUID = WTFMove(videoDeviceUID); RefPtr<UserMediaRequest> protectedThis = this; RealtimeMediaSourceCenter::NewMediaStreamHandler callback = [this, protectedThis = WTFMove(protectedThis)](RefPtr<MediaStreamPrivate>&& privateStream) mutable { if (!m_scriptExecutionContext) return; if (!privateStream) { deny(MediaAccessDenialReason::HardwareError, emptyString()); return; } privateStream->monitorOrientation(downcast<Document>(m_scriptExecutionContext)->orientationNotifier()); auto stream = MediaStream::create(*m_scriptExecutionContext, privateStream.releaseNonNull()); if (stream->getTracks().isEmpty()) { deny(MediaAccessDenialReason::HardwareError, emptyString()); return; } stream->startProducingData(); m_promise.resolve(stream); }; m_audioConstraints.deviceIDHashSalt = deviceIdentifierHashSalt; m_videoConstraints.deviceIDHashSalt = WTFMove(deviceIdentifierHashSalt); RealtimeMediaSourceCenter::singleton().createMediaStream(WTFMove(callback), m_allowedAudioDeviceUID, m_allowedVideoDeviceUID, &m_audioConstraints, &m_videoConstraints); if (!m_scriptExecutionContext) return; #if ENABLE(WEB_RTC) auto* page = downcast<Document>(*m_scriptExecutionContext).page(); if (page) page->rtcController().disableICECandidateFiltering(); #endif } void UserMediaRequest::deny(MediaAccessDenialReason reason, const String& invalidConstraint) { if (!m_scriptExecutionContext) return; switch (reason) { case MediaAccessDenialReason::NoConstraints: RELEASE_LOG(MediaStream, "UserMediaRequest::deny - no constraints"); m_promise.reject(TypeError); break; case MediaAccessDenialReason::UserMediaDisabled: RELEASE_LOG(MediaStream, "UserMediaRequest::deny - user media disabled"); m_promise.reject(SecurityError); break; case MediaAccessDenialReason::NoCaptureDevices: RELEASE_LOG(MediaStream, "UserMediaRequest::deny - no capture devices"); m_promise.reject(NotFoundError); break; case MediaAccessDenialReason::InvalidConstraint: RELEASE_LOG(MediaStream, "UserMediaRequest::deny - invalid constraint - %s", invalidConstraint.utf8().data()); m_promise.rejectType<IDLInterface<OverconstrainedError>>(OverconstrainedError::create(invalidConstraint, ASCIILiteral("Invalid constraint")).get()); break; case MediaAccessDenialReason::HardwareError: RELEASE_LOG(MediaStream, "UserMediaRequest::deny - hardware error"); m_promise.reject(NotReadableError); break; case MediaAccessDenialReason::OtherFailure: RELEASE_LOG(MediaStream, "UserMediaRequest::deny - other failure"); m_promise.reject(AbortError); break; case MediaAccessDenialReason::PermissionDenied: RELEASE_LOG(MediaStream, "UserMediaRequest::deny - permission denied"); m_promise.reject(NotAllowedError); break; } } void UserMediaRequest::contextDestroyed() { ContextDestructionObserver::contextDestroyed(); Ref<UserMediaRequest> protectedThis(*this); if (m_controller) { m_controller->cancelUserMediaAccessRequest(*this); m_controller = nullptr; } } Document* UserMediaRequest::document() const { return downcast<Document>(m_scriptExecutionContext); } } // namespace WebCore #endif // ENABLE(MEDIA_STREAM)
9,978
2,882
#include <cassert> #include <vector> #include <algorithm> #include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #include <string> #include <cstring> using namespace std; bool is_taxi(const string &s) { char c = s[0]; for (int i=0; i<(int)s.size(); ++i) { if (s[i]!='-' && s[i]!=c) { return false; } } return true; } bool is_pizza(const string &s) { char c = s[0]; for (int i=1; i<(int)s.size(); ++i) { if (s[i] == '-') continue; if (s[i] >= c) { return false; } c = s[i]; } return true; } int main() { int n; cin >> n; vector<string> names; vector<int> taxi, pizza, girls; int T=-1, P=-1, G=-1; for (int i=0; i<n; ++i) { int sz; string s; cin >> sz >> s; names.push_back(s); int t=0, p=0, g=0; for (int j=0; j<sz; ++j) { cin >> s; assert(s.size() == 8); if (is_taxi(s)) { ++t; } else if (is_pizza(s)) { ++p; } else { ++g; } } T = max(T, t); taxi.push_back(t); P = max(P, p); pizza.push_back(p); G = max(G, g); girls.push_back(g); } cout << "If you want to call a taxi, you should call: "; int cnt = 0; for (int i=0; i<n; ++i) { if (taxi[i] == T) { if (cnt > 0) { cout << ", "; } ++cnt; cout << names[i]; } } cout << ".\n"; cout << "If you want to order a pizza, you should call: "; cnt = 0; for (int i=0; i<n; ++i) { if (pizza[i] == P) { if (cnt > 0) { cout << ", "; } ++cnt; cout << names[i]; } } cout << ".\n"; cout << "If you want to go to a cafe with a wonderful girl, you should call: "; cnt = 0; for (int i=0; i<n; ++i) { if (girls[i] == G) { if (cnt > 0) { cout << ", "; } ++cnt; cout << names[i]; } } cout << ".\n"; return 0; }
2,223
836
#include <Arduino.h> #include "mockup.h" bool i2c_init(void) { return true; } bool i2c_start(uint8_t addr) { return true; } bool i2c_start_wait(uint8_t addr) { return true; } bool i2c_rep_start(uint8_t addr) { return true; } bool i2c_write(uint8_t data) { return true; } byte i2c_read(bool last) { return 0xA1; } void i2c_stop() { }
353
179
#include "Account.h" void Account::read(const QJsonObject& json) { AccountId = json["AccountId"].toInt(); RegistrationDateTime = QDateTime::fromString(json["RegistrationDateTime"].toString(), Qt::DateFormat::ISODate); LoginDateTime = QDateTime::fromString(json["LoginDateTime"].toString(), Qt::DateFormat::ISODate); Nickname = json["Nickname"].toString(); DialogsIds.clear(); QJsonArray dialogs = json["DialogsIds"].toArray(); for (auto i : dialogs) { DialogsIds.append(i.toInt()); } } void Account::write(QJsonObject& json) const { json["AccountId"] = AccountId; json["RegistrationDateTime"] = RegistrationDateTime.toOffsetFromUtc(QDateTime::currentDateTime().offsetFromUtc()).toString(Qt::ISODateWithMs); json["LoginDateTime"] = LoginDateTime.toOffsetFromUtc(QDateTime::currentDateTime().offsetFromUtc()).toString(Qt::ISODateWithMs); json["Nickname"] = Nickname; QJsonArray ar; for (auto id : DialogsIds) { ar.append(id); } json["DialogsIds"] = ar; } //void Account::SetAccountId(int id) //{ // AccountId = id; //} //int Account::GetAccountId() //{ // return AccountId; //} //void Account::SetNickname(QString name) //{ // Nickname = name; //} //QString Account::GetNickname() //{ // return Nickname; //} //void Account::SetRegistrationDateTime(QDateTime date) //{ // RegistrationDateTime = date; //} //QDateTime Account::GetRegistrationDateTime() //{ // return RegistrationDateTime; //} //void Account::SetLoginDateTime(QDateTime date) //{ // LoginDateTime = date; //} //QDateTime Account::GetLoginDateTime() //{ // return LoginDateTime; //} ////void Account::SetDialogsIds(QVector<int> v) ////{ //// DialogsIds = v; ////} //QVector<int> Account::GetDialogsIds() //{ // return DialogsIds; //}
1,735
604
#ifndef VEC3_H #define VEC3_H #include <math.h> #include <set> #include <utility> #include <string> class Vec3 { public: float x_, y_, z_; // Constructor Vec3(void) : x_(0.0f), y_(0.0f), z_(0.0f){}; Vec3(float x, float y, float z) : x_(x), y_(y), z_(z){}; // Operators Vec3 operator+(const Vec3 &o_v3) { return Vec3(x_ + o_v3.x_, y_ + o_v3.y_, z_ + o_v3.z_); }; Vec3 operator-(const Vec3 &o_v3) { return Vec3(x_ - o_v3.x_, y_ - o_v3.y_, z_ - o_v3.z_); }; Vec3 operator*(const Vec3 &o_v3) { return Vec3(x_ * o_v3.x_, y_ * o_v3.y_, z_ * o_v3.z_); }; Vec3 operator/(const Vec3 &o_v3) { return Vec3(x_ / o_v3.x_, y_ / o_v3.y_, z_ / o_v3.z_); }; Vec3 operator+(const float &f) { return Vec3(x_ + f, y_ + f, z_ + f); }; Vec3 operator-(const float &f) { return Vec3(x_ - f, y_ - f, z_ - f); }; Vec3 operator*(const float &f) { return Vec3(x_ * f, y_ * f, z_ * f); }; Vec3 operator/(const float &f) { return Vec3(x_ / f, y_ / f, z_ / f); }; bool operator==(const Vec3 &b) const { return (x_ == b.x_) && (y_ == b.y_) && (z_ == b.z_); } Vec3 &operator+=(const Vec3 &o_v3) { x_ += o_v3.x_; y_ += o_v3.y_; z_ += o_v3.z_; return *this; }; Vec3 &operator-=(const Vec3 &o_v3) { x_ -= o_v3.x_; y_ -= o_v3.y_; z_ -= o_v3.z_; return *this; }; Vec3 &operator*=(const Vec3 &o_v3) { x_ *= o_v3.x_; y_ *= o_v3.y_; z_ *= o_v3.z_; return *this; }; Vec3 &operator/=(const Vec3 &o_v3) { x_ /= o_v3.x_; y_ /= o_v3.y_; z_ /= o_v3.z_; return *this; }; Vec3 &operator+=(const float &f) { x_ += f; y_ += f; z_ += f; return *this; }; Vec3 &operator-=(const float &f) { x_ -= f; y_ -= f; z_ -= f; return *this; }; Vec3 &operator*=(const float &f) { x_ *= f; y_ *= f; z_ *= f; return *this; }; Vec3 &operator/=(const float &f) { x_ /= f; y_ /= f; z_ /= f; return *this; }; // 1. Normalize vector void Normalize() { float len = sqrt(pow(x_, 2) + pow(y_, 2) + pow(z_, 2)); x_ /= len; y_ /= len; z_ /= len; }; // 2. Calculate Cross Product static Vec3 Cross(Vec3 v3_1, Vec3 v3_2) { float x = v3_1.y_ * v3_2.z_ - v3_1.z_ * v3_2.y_; float y = v3_1.z_ * v3_2.x_ - v3_1.x_ * v3_2.z_; float z = v3_1.x_ * v3_2.y_ - v3_1.y_ * v3_2.x_; return Vec3(x, y, z); }; // 3. Calculate Dot Product static float Dot(Vec3 v3_1, Vec3 v3_2) { return (v3_1.x_ * v3_2.x_) + (v3_1.y_ * v3_2.y_) + (v3_1.z_ * v3_2.z_); }; // 3. Return Absolute Value static float Abs(Vec3 v3) { return sqrt(Vec3::Dot(v3, v3)); }; // 4. Return Distance static float Distance(Vec3 v3_1, Vec3 v3_2) { return sqrt(pow(v3_1.x_ - v3_2.x_, 2) + pow(v3_1.y_ - v3_2.y_, 2) + pow(v3_1.z_ - v3_2.z_, 2)); }; // 5. Calcuclate Angle between vector direction static float Angle(Vec3 v3_1, Vec3 v3_2) { return acos(Vec3::Dot(v3_1, v3_2) / (Vec3::Abs(v3_1) * Vec3::Abs(v3_2))); }; // 6.5 check the given position is between xz plane static bool BetweenXZ(float min_x, float max_x, float min_z, float max_z, Vec3 pos) { return (pos.x_ >= min_x) && (pos.x_ <= max_x) && (pos.z_ >= min_z) && (pos.z_ <= max_z); } // compare operator bool operator<(const Vec3 &cvec) const { if (x_ != cvec.x_) return x_ < cvec.x_; else if (y_ != cvec.y_) return y_ < cvec.y_; else return z_ < cvec.z_; } static void ReorderEdges(Vec3 txPos, std::vector<Vec3> &edges) { txPos.y_ = 0.0f; std::set<std::pair<float, Vec3> > ordered_edges; for (Vec3 edge : edges) { Vec3 edge_on_plane = edge; edge_on_plane.y_ = 0.0f; float distance = Vec3::Distance(txPos, edge_on_plane); ordered_edges.insert({distance, edge}); } std::vector<Vec3> new_edges; for (std::pair<float, Vec3> pair_edge : ordered_edges) new_edges.push_back(pair_edge.second); edges = new_edges; ordered_edges.clear(); } std::string GetString() const { return "(" + std::to_string(x_) + ", " + std::to_string(y_) + ", " + std::to_string(z_) + ")"; } }; struct Vec3Hasher { std::size_t operator()(const Vec3 &v) const { return ((std::hash<float>()(v.x_) ^ (std::hash<float>()(v.y_) << 1)) >> 1) ^ (std::hash<float>()(v.z_) << 1); } }; #endif //VEC3_H
4,975
2,158
// Copyright (c) 2020 [Your Name]. All rights reserved. #define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> #include <bayes/classifier.h> #include <bayes/image.h> using namespace bayes; // TODO(you): Remove this unnecessary test case. TEST_CASE("Sanity Check", "[addition]") { REQUIRE(1 + 1 == 2); } TEST_CASE("Count number of shaded pixels in image", "[image-function]") { string image_name = "data/sampleimages"; string label_name = "data/samplelabels"; Image *image; image = new Image(image_name, label_name); int num_of_shaded_pixels = image->CalcNumOfShadedPixels(); delete image; REQUIRE(num_of_shaded_pixels == 148); } TEST_CASE("Count of pixels works", "[image-function]") { string image_name = "data/sampleimages"; string label_name = "data/samplelabels"; Image *image; image = new Image(image_name, label_name); int num_of_shaded_pixels = image->CalcNumOfShadedPixels(); delete image; REQUIRE(num_of_shaded_pixels == 148); } TEST_CASE("Multiple counts of shaded pixels (3 images)", "[image-function]") { string image_name = "data/sampleimages"; string label_name = "data/samplelabels"; Image *image; image = new Image(image_name, label_name); int num_of_shaded_pixels = image->CalcNumOfShadedPixels(); // int num_of_shaded_pixels_2 = image2->CalcNumOfShadedPixels(); delete image; REQUIRE(num_of_shaded_pixels == 148); }
1,383
519
#ifndef SHIFT_PROTO_TYPES_HPP #define SHIFT_PROTO_TYPES_HPP #include <cstddef> #include <cstdint> #include <stdexcept> #include <type_traits> #include <utility> #include <memory> #include <variant> #include <vector> #include <string> #include <unordered_map> #include <utility> #include <shift/core/boost_disable_warnings.hpp> #include <boost/lexical_cast.hpp> #include <shift/core/boost_restore_warnings.hpp> #include <shift/core/exception.hpp> namespace shift::proto { using parse_error_line = boost::error_info<struct parse_error_line_tag, std::size_t>; using parse_error_column = boost::error_info<struct parse_error_column_tag, std::size_t>; using parse_error_source = boost::error_info<struct parse_error_source_tag, std::string>; using parse_error_message = boost::error_info<struct parse_error_message_tag, std::string>; /// An exception type thrown if the parser reports an error. struct parse_error : virtual core::runtime_error { }; /// Enumeration of supported built-in types. enum class built_in_type : unsigned char { undefined, boolean, char8, char16, char32, int8, uint8, int16, uint16, int32, uint32, int64, uint64, float32, float64, string, datetime, raw_ptr, unique_ptr, shared_ptr, weak_ptr, group_ptr, tuple, array, list, vector, set, matrix, map, variant, bitfield }; struct alias; struct type_reference; struct enumerator; struct enumeration; struct field; struct message; struct interface; struct service; struct namescope; using type = std::variant<namescope, alias, enumeration, message, interface, service>; using attribute_value = std::variant<std::string, std::uint64_t>; using attribute = std::pair<std::string, attribute_value>; using attribute_pair = std::pair<std::string, attribute_value>; using attribute_map = std::unordered_map<std::string, attribute_value>; using namescope_path = std::vector<std::string>; using type_path = std::vector<std::string>; using type_variant = std::variant<built_in_type, const alias*, const enumeration*, const message*>; using template_argument = std::variant<type_reference, int>; using template_arguments = std::vector<template_argument>; } #endif
2,202
760
/* * Academic License - for use in teaching, academic research, and meeting * course requirements at degree granting institutions only. Not for * government, commercial, or other organizational use. * File: recip.c * * MATLAB Coder version : 3.4 * C/C++ source code generated on : 14-May-2018 23:15:09 */ /* Include Files */ #include "rt_nonfinite.h" #include "butterBandpassOnly.h" #include "recip.h" /* Function Definitions */ /* * Arguments : const creal_T y * Return Type : creal_T */ creal_T recip(const creal_T y) { creal_T z; double brm; double bim; double d; brm = fabs(y.re); bim = fabs(y.im); if (y.im == 0.0) { z.re = 1.0 / y.re; z.im = 0.0; } else if (y.re == 0.0) { z.re = 0.0; z.im = -1.0 / y.im; } else if (brm > bim) { bim = y.im / y.re; d = y.re + bim * y.im; z.re = 1.0 / d; z.im = -bim / d; } else if (brm == bim) { bim = 0.5; if (y.re < 0.0) { bim = -0.5; } d = 0.5; if (y.im < 0.0) { d = -0.5; } z.re = bim / brm; z.im = -d / brm; } else { bim = y.re / y.im; d = y.im + bim * y.re; z.re = bim / d; z.im = -1.0 / d; } return z; } /* * File trailer for recip.c * * [EOF] */
1,250
590
#include <cstdlib> #include <vector> #include "recently_used_list.h" // A utility function to create a new Queue Node. The queue Node // will store the given 'pageNumber' QNode* newQNode(unsigned pageNumber) { // Allocate memory and assign 'pageNumber' QNode* temp = (QNode*)malloc(sizeof(QNode)); temp->pageNumber = pageNumber; // Initialize prev and next as NULL temp->prev = temp->next = NULL; return temp; } // A utility function to create an empty Queue. // The queue can have at most 'numberOfFrames' nodes Queue* createQueue(int numberOfFrames) { Queue* queue = (Queue*)malloc(sizeof(Queue)); // The queue is empty queue->count = 0; queue->front = queue->rear = NULL; // Number of frames that can be stored in memory queue->numberOfFrames = numberOfFrames; return queue; } // A utility function to create an empty Hash of given capacity Hash* createHash(int capacity) { // Allocate memory for hash Hash* hash = (Hash*)malloc(sizeof(Hash)); hash->capacity = capacity; // Create an array of pointers for refering queue nodes hash->array = (QNode**)malloc(hash->capacity * sizeof(QNode*)); // Initialize all hash entries as empty int i; for (i = 0; i < hash->capacity; ++i) hash->array[i] = NULL; return hash; } // A function to check if there is slot available in memory int AreAllFramesFull(Queue* queue) { return queue->count == queue->numberOfFrames; } // A utility function to check if queue is empty int isQueueEmpty(Queue* queue) { return queue->rear == NULL; } // A utility function to delete a frame from queue void deQueue(Queue* queue) { if (isQueueEmpty(queue)) return; // If this is the only node in list, then change front if (queue->front == queue->rear) queue->front = NULL; // Change rear and remove the previous rear QNode* temp = queue->rear; queue->rear = queue->rear->prev; if (queue->rear) queue->rear->next = NULL; free(temp); // decrement the number of full frames by 1 queue->count--; } // A function to add a page with given 'pageNumber' to both queue // and hash void Enqueue(Queue* queue, Hash* hash, unsigned pageNumber) { // If all frames are full, remove the page at the rear if (AreAllFramesFull(queue)) { // remove page from hash hash->array[queue->rear->pageNumber] = NULL; deQueue(queue); } // Create a new node with given page number, // And add the new node to the front of queue QNode* temp = newQNode(pageNumber); temp->next = queue->front; // If queue is empty, change both front and rear pointers if (isQueueEmpty(queue)) queue->rear = queue->front = temp; else // Else change the front { queue->front->prev = temp; queue->front = temp; } // Add page entry to hash also hash->array[pageNumber] = temp; // increment number of full frames queue->count++; } // This function is called when a page with given 'pageNumber' is referenced // from cache (or memory). There are two cases: // 1. Frame is not there in memory, we bring it in memory and add to the front // of queue // 2. Frame is there in memory, we move the frame to front of queue void LookupPage(Queue* queue, Hash* hash, unsigned pageNumber) { QNode* reqPage = hash->array[pageNumber]; // the page is not in cache, bring it if (reqPage == NULL) Enqueue(queue, hash, pageNumber); // page is there and not at front, change pointer else if (reqPage != queue->front) { // Unlink rquested page from its current location // in queue. reqPage->prev->next = reqPage->next; if (reqPage->next) reqPage->next->prev = reqPage->prev; // If the requested page is rear, then change rear // as this node will be moved to front if (reqPage == queue->rear) { queue->rear = reqPage->prev; queue->rear->next = NULL; } // Put the requested page before current front reqPage->next = queue->front; reqPage->prev = NULL; // Change prev of current front reqPage->next->prev = reqPage; // Change front to the requested page queue->front = reqPage; } } void currentPageOrder(Queue* q, int pages[], int max) { QNode* current = q->front; int i = 0; while (current != NULL && i < max) { pages[i] = current->pageNumber; current = current->next; i++; } } std::vector<int>* currentPages(Queue* q) { QNode* current = q->front; int i = 0; std::vector<int>* result = new std::vector<int>(); while (current != NULL && i < q->count) { result->push_back(current->pageNumber); current = current->next; i++; } return result; }
4,896
1,480
#include <bits/stdc++.h> #define ll long long using namespace std; int main(void) { ll int N, W, answer=-1; cin>>N>>W; ll int w[N+1]; ll int v[N+1]; w[0]=0; v[0]=0; for(ll int i=1; i<=N; i++) cin>>w[i]>>v[i]; ll int dp[N+1][W+1]; for(ll int j=0; j<=W; j++) dp[0][j]=0; for(ll int k=0; k<=N; k++) dp[k][0]=0; for(ll int item=1; item<=N; item++) { for(ll int weight=1; weight<=W; weight++) { if(w[item]>weight) dp[item][weight]=dp[item-1][weight]; else dp[item][weight]=max(v[item]+dp[item-1][weight-w[item]],dp[item-1][weight]); } } cout<<dp[N][W]<<"\n"; //cout<<answer<<"\n"; return 0; }
643
353
// COMPMSGD.CPP // #include "stdafx.h" #include <afxcmn.h> #include <QCUtils.h> #include "resource.h" #include "rs.h" #include "helpxdlg.h" #include "doc.h" #include "cursor.h" #include "fileutil.h" #include "summary.h" #include "msgdoc.h" #include "compmsgd.h" #include "mdichild.h" #include "CompMessageFrame.h" #include "font.h" #include "bmpcombo.h" #include "3dformv.h" #include "header.h" // for MIME.H #include "mime.h" // for TextReader class #include "headervw.h" #include "msgframe.h" #include "tocdoc.h" #include "utils.h" #include "guiutils.h" #include "address.h" #include "eudora.h" #include "progress.h" #include "sendmail.h" #include "changeq.h" #include "mainfrm.h" #include "filtersd.h" #include "tocview.h" #include "SaveAsDialog.h" #include "msgutils.h" #include "pop.h" #include "password.h" #include "persona.h" #include "msgopts.h" #include "PgMsgView.h" #include "PgCompMsgView.h" #include "Text2Html.h" #include "ems-wglu.h" #include "trnslate.h" #include "helpcntx.h" #include "utils.h" #include "nickdoc.h" #include "QCWorkerSocket.h" #include "NewMbox.h" #include "QCProtocol.h" #include "QCCommandActions.h" #include "QCCommandStack.h" #include "QCPluginCommand.h" #include "QCMailboxCommand.h" #include "QCMailboxDirector.h" #include "QCRecipientCommand.h" #include "QCRecipientDirector.h" #include "QCStationeryCommand.h" #include "QCStationeryDirector.h" #include "QCPersonalityCommand.h" #include "QCPersonalityDirector.h" #include "QCPluginCommand.h" #include "QCPluginDirector.h" #include "Automation.h" #include "AutoCompleteSearcher.h" #include "QCSharewareManager.h" #define DIM( a ) ( sizeof( a ) / sizeof( a[0] ) ) extern CString EudoraDir; extern QCCommandStack g_theCommandStack; extern QCMailboxDirector g_theMailboxDirector; extern QCRecipientDirector g_theRecipientDirector; extern QCStationeryDirector g_theStationeryDirector; extern QCPersonalityDirector g_thePersonalityDirector; extern QCPluginDirector g_thePluginDirector; #ifdef _DEBUG #undef THIS_FILE #ifndef DEBUG_NEW #define DEBUG_NEW new(__FILE__, __LINE__) #endif static char BASED_CODE THIS_FILE[] = __FILE__; #define new DEBUG_NEW #endif ///////////////////////////////////////////////////////////////////////////// // CCompMessageDoc IMPLEMENT_DYNCREATE(CCompMessageDoc, CMessageDoc) CCompMessageDoc::CCompMessageDoc() : m_FindHeaderIndex(-1) // negative value indicates that no Find actions have been executed { m_HasBeenSaved = FALSE; m_StationeryApplied = FALSE; m_MessageId = ""; // not really required, but... m_bIsStationery = FALSE; } BOOL CCompMessageDoc::InitializeNew ( const char* To, const char* From, const char* Subject, const char* Cc, const char* Bcc, const char* Attachments, const char* Body, const char* ECHeaders ) { m_Headers[HEADER_TO] = To; m_Headers[HEADER_FROM] = From? From : GetReturnAddress(); m_Headers[HEADER_SUBJECT] = Subject; m_Headers[HEADER_CC] = Cc; m_Headers[HEADER_BCC] = Bcc; m_Headers[HEADER_ATTACHMENTS] = Attachments; m_HeadersInvalidFlag[HEADER_TO] = FALSE; m_HeadersInvalidFlag[HEADER_FROM] = FALSE; m_HeadersInvalidFlag[HEADER_SUBJECT] = FALSE; m_HeadersInvalidFlag[HEADER_CC] = FALSE; m_HeadersInvalidFlag[HEADER_BCC] = FALSE; m_HeadersInvalidFlag[HEADER_ATTACHMENTS] = FALSE; SetText(Body); AssignMessageId(); // each message gets a unique id m_NextAutoSaveTime = time(NULL); //get the Creation time stamp m_ExtraHeaders.Format("%s<%s>\r\n", (LPCTSTR)CRString(IDS_HEADER_MESSAGE_ID), (LPCTSTR)m_MessageId); m_QCMessage.Init(m_MessageId, m_Text, FALSE); if ( ECHeaders ) { m_QCMessage.InitMap( ECHeaders ); m_QCMessage.NukeCIDs(); } // Take out attachments that are not found if (!IsHeaderEmpty(HEADER_ATTACHMENTS)) { BOOL MissingFile = FALSE; char* a = m_Headers[HEADER_ATTACHMENTS].GetBuffer(m_Headers[HEADER_ATTACHMENTS].GetLength()); char* semi; BOOL foundSemi = FALSE; while(strlen(a) > 0) //while (1) { if ( semi = strchr(a, ';') ) { *semi = 0; foundSemi = TRUE; } char* filename = a; while (*filename == ' ' || *filename == '\t') filename++; if (!::FileExistsMT(filename)) { MissingFile = TRUE; if (foundSemi) strcpy(a, semi + 1); else break; } else { if (foundSemi) { *semi = ';'; a = semi + 1; } else break; } foundSemi = FALSE; } m_Headers[HEADER_ATTACHMENTS].ReleaseBuffer(); if (MissingFile) ErrorDialog(IDS_ERR_MISSING_ATTACHMENT); } m_Sum = new CSummary; CTocDoc* OutToc; if (!m_Sum || !(OutToc = GetOutToc())) return (FALSE); OutToc->AddSum(m_Sum); if (!IsHeaderEmpty(HEADER_TO)) { char buf[128]; strncpy(buf, GetHeaderLine(HEADER_TO), sizeof(buf)); buf[sizeof(buf) - 1] = 0; m_Sum->SetFrom(GetRealName(buf)); } m_Sum->SetSubject(GetHeaderLine(HEADER_SUBJECT)); m_Sum->m_State = MS_UNSENDABLE; ReallySetTitle(m_Sum->MakeTitle()); if (GetIniShort(IDS_INI_SEND_MIME)) m_Sum->SetFlag(MSF_MIME); if (GetIniShort(IDS_INI_SEND_UUENCODE)) m_Sum->SetFlag(MSF_UUENCODE); if (GetIniShort(IDS_INI_USE_QP)) m_Sum->SetFlag(MSF_QUOTED_PRINTABLE); if (GetIniShort(IDS_INI_WORD_WRAP)) m_Sum->SetFlag(MSF_WORD_WRAP); if (GetIniShort(IDS_INI_TABS_IN_BODY)) m_Sum->SetFlag(MSF_TABS_IN_BODY); if (GetIniShort(IDS_INI_KEEP_COPIES)) m_Sum->SetFlag(MSF_KEEP_COPIES); if (GetIniShort(IDS_INI_TEXT_AS_DOC)) m_Sum->SetFlag(MSF_TEXT_AS_DOC); switch (IsFancy(Body)) { case IS_FLOWED: m_Sum->SetFlagEx(MSFEX_FLOWED); break; case IS_HTML: m_Sum->SetFlagEx(MSFEX_HTML); // fall through case IS_RICH: m_Sum->SetFlag(MSF_XRICH); break; } RemoveIniFromCache(IDS_INI_DEFAULT_TRANSLATOR); CString defINITrans = GetIniString(IDS_INI_DEFAULT_TRANSLATOR); CString defFlaggedTrans; ((CEudoraApp *)AfxGetApp())->GetTranslators()->GetDefOutTransString(defFlaggedTrans); if (!defINITrans.IsEmpty() && !defFlaggedTrans.IsEmpty()) defINITrans += ','; defINITrans += defFlaggedTrans; if (!defINITrans.IsEmpty()) { defINITrans = "<" + defINITrans; defINITrans += ">"; m_Sum->SetTranslators(defINITrans, TRUE); } return (TRUE); } BOOL CCompMessageDoc::OnNewDocument() { if (!CMessageDoc::OnNewDocument()) return (FALSE); return (TRUE); } CCompMessageDoc::~CCompMessageDoc() { if ( m_bIsStationery ) { CTocDoc* OutToc = GetOutToc(); CSummary* Sum = m_Sum; if (Sum) { // Remove the link between the message doc and the summary because otherwise // deleting the summary (done in RemoveSum()) will cause the message doc to // be deleted. And look where we are? The destructor of the message doc! // That's a double delete, my friend, and that will make you crash and burn! m_Sum = NULL; OutToc->RemoveSum(Sum); } } } void CCompMessageDoc::SetTitle(const char* pszTitle) { if (!m_bIsStationery) { // The title should only have to be set once. This prevents screen flicker when saving. if (m_strTitle.IsEmpty()) CDocument::SetTitle(pszTitle); } else { CString title; int filenameStart = m_strPathName.ReverseFind(SLASH); if (filenameStart > 0) { //Strip the Path title = m_strPathName.Right(m_strPathName.GetLength() - filenameStart - 1); //Strip the Extension if ( title.ReverseFind('.') > 0 ) title = title.Left(title.GetLength() - 4); } else title = CRString(IDS_UNTITLED); title += " - "; title += CRString(IDR_STATIONERY); CDocument::SetTitle(title); } } // BADSTUFF: this routine has been badly hacked to "know" about Paige message // views, but still return a CCompMessageView. Hopefully this will die before // I have to check-in this module, but ya never know. CView* CCompMessageDoc::GetView() { // Note: this routine is symptomatic of a general architectural problem // with our "design". A document should not care about the types of // views that are attached to it. POSITION pos = GetFirstViewPosition(); while ( pos ) { CView* pCV = GetNextView( pos ); VERIFY( pCV ); BOOL isCV = pCV->IsKindOf( RUNTIME_CLASS(PgMsgView) ); if ( isCV ) return pCV; } return NULL; } CView* CCompMessageDoc::GetCompView() { //This routine currently only returns the PgCompMsgView //Don't try to use this to get a *preview* View POSITION pos = GetFirstViewPosition(); while ( pos ) { CView* pCV = GetNextView( pos ); VERIFY( pCV ); //BOOL isHV = pCV->IsKindOf( RUNTIME_CLASS(CHeaderView) ); BOOL isCV = pCV->IsKindOf( RUNTIME_CLASS(PgCompMsgView) ); //if ( !isHV ) if ( isCV ) return pCV; } return NULL; } CHeaderView* CCompMessageDoc::GetHeaderView() { // Note: this routine is symptomatic of a general architectural problem // with our "design". A document should not care about the types of // views that are attached to it. POSITION pos = GetFirstViewPosition(); while ( pos ) { CView* pHV = GetNextView( pos ); VERIFY( pHV ); BOOL isHV = pHV->IsKindOf( RUNTIME_CLASS(CHeaderView) ); if ( isHV ) return (CHeaderView*) pHV; } return NULL; } BOOL CCompMessageDoc::AddAttachment( const char* Filename ) { VERIFY( Filename ); CHeaderView* pHV = GetHeaderView(); pHV->AddAttachment( Filename ); return TRUE; } BOOL CCompMessageDoc::SaveModified() { if (m_bIsStationery) { if ( IsModified() ) { //Hasn't ever been saved before if ( m_strPathName.Compare("A") == 0 ) { CRString prompt(IDS_SAVE_STATIONERY_CHANGES); switch (AfxMessageBox(prompt, MB_YESNOCANCEL)) { case IDCANCEL: return (FALSE); case IDYES: OnFileSaveAsStationery(); //If the user chose cancel in the SaveAs dlg, dont' close the window if ( m_strPathName.Compare("A") == 0 ) return (FALSE); break; case IDNO: SetModifiedFlag(FALSE); break; } } else { //Resave/Update the document?? CString prompt; AfxFormatString1(prompt, IDS_SAVE_CHANGES, m_strPathName); switch (AfxMessageBox(prompt, MB_YESNOCANCEL)) { case IDCANCEL: return (FALSE); // don't continue case IDYES: { JJFile theFile; if (FAILED(theFile.Open( m_strPathName, O_CREAT | O_TRUNC | O_WRONLY))) return (FALSE); CMessageDoc::OnFileSave(); WriteAsText( &theFile, TRUE ); // If so, either Save or Update, as appropriate //if (!DoSave(m_strPathName)) // return (FALSE); // don't continue } break; case IDNO: // If we get here, it may be the case that the user hit // No when asked to save the changes. If this is so, then the modified // flag needs to be cleared so the save prompt doesn't come up again. SetModifiedFlag(FALSE); //return (FALSE); break; default: ASSERT(FALSE); return (FALSE); // don't continue } } } //Except for the case of cancel, close the window and //remove the summary from the Out Toc //CTocDoc* OutToc = GetOutToc(); OnCloseDocument(); //if ( !m_Sum || !(OutToc) ) // OutToc->RemoveSum(m_Sum); //Closed and deleted from the outbox, so don't continuue //OnMessageDelete(); return FALSE; } //For other comp messages if (IsModified()) { if (CMessageDoc::SaveModified() == FALSE) return (FALSE); if (m_HasBeenSaved == FALSE) { // // If we get this far, then the user has chosen to trash this // message. So, now we need to check whether there are any // MAPI attachments. If the user's MAPI settings are such // deleting MAPI attachments is allowed, then blow away each // MAPI attachment file. // if (m_Sum->IsMAPI()) { GetText(); // make sure body is read up CString attachments(GetHeaderLine(HEADER_ATTACHMENTS)); if (! attachments.IsEmpty()) { char attachments_dir[_MAX_PATH + 1]; GetIniString(IDS_INI_AUTO_RECEIVE_DIR, attachments_dir, sizeof(attachments_dir)); if (attachments_dir[0] == '\0') wsprintf(attachments_dir,"%s%s", (const char *) EudoraDir, (const char *) CRString(IDS_ATTACH_FOLDER)); const int ATTACHMENTS_DIR_LEN = strlen(attachments_dir); int idx; while ((idx = attachments.Find(';')) != -1) { // // If the attachment file is in the Eudora attachments // directory, then delete the file. // CString attachment(attachments.Left(idx)); if (strnicmp(attachments_dir, attachment, ATTACHMENTS_DIR_LEN) == 0) ::FileRemoveMT(attachment); // // Removed processed attachment filename by shifting string. // attachments = attachments.Right(attachments.GetLength() - (idx + 1)); } // // Delete the last file in the list, if it is in the Eudora // attachments directory. // if (! attachments.IsEmpty()) { if (strnicmp(attachments_dir, attachments, ATTACHMENTS_DIR_LEN) == 0) ::FileRemoveMT(attachments); } } } // what he said, but for the .msg command line stuff if ( m_Sum->IsAutoAttached() ) { // extract the attachment filename CString AttachStr(GetHeaderLine(HEADER_ATTACHMENTS)); char* Attach = AttachStr.GetBuffer(AttachStr.GetLength()); while (Attach && *Attach) { char *t = strchr(Attach, ';'); if (t) { *t++ = 0; if (*t == ' ') t++; } // expects a fully-qualified filename ::FileRemoveMT( Attach ); Attach = t; } } } } return (TRUE); } ///////////////////////////////////////////////////////////////////////////// // CSendStylesDialog dialog class CSendStylesDialog : public CDialog { // Construction public: CSendStylesDialog(CWnd* pParent = NULL); // standard constructor virtual BOOL OnInitDialog(); // Dialog Data //{{AFX_DATA(CSendStylesDialog) enum { IDD = IDD_SENDING_STYLES }; CButton m_SendPlainAndStyled; CButton m_WarnCheckbox; CButton m_SendStyled; CButton m_SendPlain; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CSendStylesDialog) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CSendStylesDialog) afx_msg void OnSendPlain(); afx_msg void OnSendPlainAndStyled(); afx_msg void OnSendStyled(); afx_msg void OnButtonPress(UINT ButtonID); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// // CSendStylesDialog dialog CSendStylesDialog::CSendStylesDialog(CWnd* pParent /*=NULL*/) : CDialog(CSendStylesDialog::IDD, pParent) { //{{AFX_DATA_INIT(CSendStylesDialog) //}}AFX_DATA_INIT // We better not be creating this dialog if the warning is off ASSERT(GetIniShort(IDS_INI_WARN_QUEUE_STYLED_TEXT)); } BOOL CSendStylesDialog::OnInitDialog() { if (!CDialog::OnInitDialog()) return FALSE; if (GetIniShort(IDS_INI_SEND_PLAIN_ONLY)) { m_SendPlain.SetFocus(); SetDefID(IDC_SEND_PLAIN); } else if (GetIniShort(IDS_INI_SEND_STYLED_ONLY)) { m_SendStyled.SetFocus(); SetDefID(IDC_SEND_STYLED); } else { // This better be set if the above two aren't ASSERT(GetIniShort(IDS_INI_SEND_PLAIN_AND_STYLED)); m_SendPlainAndStyled.SetFocus(); SetDefID(IDC_SEND_PLAIN_AND_STYLED); } // We set the focus, so return FALSE return FALSE; } void CSendStylesDialog::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CSendStylesDialog) DDX_Control(pDX, IDC_SEND_PLAIN_AND_STYLED, m_SendPlainAndStyled); DDX_Control(pDX, IDC_WARN_CHECKBOX, m_WarnCheckbox); DDX_Control(pDX, IDC_SEND_STYLED, m_SendStyled); DDX_Control(pDX, IDC_SEND_PLAIN, m_SendPlain); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CSendStylesDialog, CDialog) //{{AFX_MSG_MAP(CSendStylesDialog) ON_COMMAND_EX(IDC_SEND_PLAIN, OnButtonPress) ON_COMMAND_EX(IDC_SEND_STYLED, OnButtonPress) ON_COMMAND_EX(IDC_SEND_PLAIN_AND_STYLED, OnButtonPress) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CSendStylesDialog message handlers void CSendStylesDialog::OnButtonPress(UINT ButtonID) { if (m_WarnCheckbox.GetCheck()) { // A little verbose, but it prevents a setting from being turned off, then on again, // which would cause a default setting to be written to the .INI file switch (ButtonID) { case IDC_SEND_PLAIN: SetIniShort(IDS_INI_SEND_PLAIN_ONLY, TRUE); SetIniShort(IDS_INI_SEND_STYLED_ONLY, FALSE); SetIniShort(IDS_INI_SEND_PLAIN_AND_STYLED, FALSE); break; case IDC_SEND_STYLED: SetIniShort(IDS_INI_SEND_PLAIN_ONLY, FALSE); SetIniShort(IDS_INI_SEND_STYLED_ONLY, TRUE); SetIniShort(IDS_INI_SEND_PLAIN_AND_STYLED, FALSE); break; case IDC_SEND_PLAIN_AND_STYLED: SetIniShort(IDS_INI_SEND_PLAIN_ONLY, FALSE); SetIniShort(IDS_INI_SEND_STYLED_ONLY, FALSE); SetIniShort(IDS_INI_SEND_PLAIN_AND_STYLED, TRUE); break; default: // This better not happpen ASSERT(0); break; } SetIniShort(IDS_INI_WARN_QUEUE_STYLED_TEXT, FALSE); } EndDialog(ButtonID); } // BadRecipient // // Tells whether or not there is a problem with a particular // recipient or there are no recipients at all. // BOOL CCompMessageDoc::BadRecipient() { char* Expanded; BOOL bIsEmpty = TRUE; Expanded = ExpandAliases(GetHeaderLine(HEADER_TO), TRUE, TRUE, TRUE, TRUE); if (!Expanded) return TRUE; bIsEmpty = bIsEmpty && !*Expanded; delete [] Expanded; Expanded = ExpandAliases(GetHeaderLine(HEADER_CC), TRUE, TRUE, TRUE, TRUE); if (!Expanded) return TRUE; // Can't send with just Cc: recipient, so don't update bIsEmpty delete [] Expanded; Expanded = ExpandAliases(GetHeaderLine(HEADER_BCC), TRUE, TRUE, TRUE, TRUE); if (!Expanded) return TRUE; bIsEmpty = bIsEmpty && !*Expanded; delete [] Expanded; if (bIsEmpty) { if (!gbAutomationCall) { // BOG: this is a hack for queueing through MAPI; it really ain't // the way to go in the long run, but... AfxGetMainWnd()->SetForegroundWindow(); // EndHack ErrorDialog(IDS_ERR_COMP_NEED_RCPT); } return TRUE; } return FALSE; } BOOL CCompMessageDoc::Queue(BOOL autoSend /*= FALSE*/) { // BADSTUFF CView* View = GetView(); if ( !m_Sum || m_Sum->CantEdit() ) { ASSERT( FALSE ); return FALSE; } // Spell check if necessary if ( View && !autoSend && GetIniShort( IDS_INI_SPELL_ON_QUEUE ) ) { QCProtocol* pProtocol = QCProtocol::QueryProtocol( QCP_SPELL, ( CObject* )View ); if( pProtocol == NULL ) return FALSE; int ret = pProtocol->CheckSpelling( TRUE ); if ( ret == IDCANCEL ) return FALSE; if ( ret < 0 ) { if ( GetIniShort( IDS_INI_SPELL_ON_QUEUE_WARN ) ) { if ( !gbAutomationCall ) { if ( WarnDialog( IDS_INI_SPELL_ON_QUEUE_WARN, IDS_WARN_SPELL_ON_QUEUE_FAIL ) != IDOK ) return FALSE; } } } } if (BadRecipient()) return (FALSE); const char* Subject = GetHeaderLine(HEADER_SUBJECT); if (!autoSend && GetIniShort(IDS_INI_WARN_QUEUE_NO_SUBJECT) && (!Subject || !*Subject)) { if (!gbAutomationCall) { if (WarnDialog(IDS_INI_WARN_QUEUE_NO_SUBJECT, IDS_WARN_QUEUE_NO_SUBJECT) != IDOK) return (FALSE); } } const char* Attachments = GetHeaderLine(HEADER_ATTACHMENTS); if (!autoSend && GetIniShort(IDS_INI_WARN_QUEUE_BIG_MESSAGE) ) { long EstSize = ::SafeStrlenMT(GetText()); // 9/16 Changed from GetBody()); if ( Attachments && *Attachments ) { // add the size of the attachments while (1) { const char* End = strchr(Attachments, ';'); char Filename[_MAX_PATH + 1]; if (!End) End = Attachments + strlen(Attachments); while (*Attachments == ' ') Attachments++; int Length = End - Attachments; strncpy(Filename, Attachments, Length); Filename[Length] = 0; if (*Filename) { CString fc(Filename); char* FilenameCopy = fc.GetBuffer(fc.GetLength() + 1); CFileStatus Status; if (!CFile::GetStatus(FilenameCopy, Status)) { ErrorDialog(IDS_ERR_OPEN_ATTACH, Filename); return (FALSE); } EstSize += ((Status.m_size * 4L) / 3L); } if (!*End) break; Attachments = End + 1; } } long BigSize = GetIniLong(IDS_INI_WARN_QUEUE_BIG_MESSAGE_SIZE) * 1024L; if (!gbAutomationCall) { if (EstSize > BigSize && WarnDialog(IDS_INI_WARN_QUEUE_BIG_MESSAGE, IDS_WARN_QUEUE_BIG_MESSAGE, (EstSize / 1024L)) != IDOK) { return (FALSE); } } } // Here we're going to look through the recipient headers and check them for names we can add to // Our AutoCompleter History list. We've previously turned on an expanded flag if the header has // undergone expansion. This is important because if you type a nickname and it's expanded the // names that were expanded out are not something you've typed and therefore shouldn't be added // to a list of "Typing Shortcuts" CHeaderView* pHView = GetHeaderView(); CHeaderField* pHField = NULL; // We grab the addresses from each header and then put // them in the list if they should be put there. /* if (pHView) { CString addresses = ""; pHField = pHView->GetHeaderCtrl(HEADER_TO); if (pHField && pHField->GetExpanded() == false) {// We have a candidate for name grabbing. addresses += pHField->GetText(); addresses += ", "; pHField = NULL; } pHField = pHView->GetHeaderCtrl(HEADER_CC); if (pHField && pHField->GetExpanded() == false) {// We have a candidate for name grabbing. addresses += pHField->GetText(); addresses += ", "; pHField = NULL; } pHField = pHView->GetHeaderCtrl(HEADER_BCC); if (pHField && pHField->GetExpanded() == false) {// We have a candidate for name grabbing. addresses += pHField->GetText(); } bool done = false; while (!done) { CString oneaddress; int length = addresses.Find(','); if (length == -1) { done = true; if (addresses.GetLength() == 0) break; oneaddress = addresses; } else { oneaddress = addresses.Left(length); addresses = addresses.Right(addresses.GetLength() - (length+1)); } oneaddress.TrimLeft(); oneaddress.TrimRight(); char *nameToAdd = oneaddress.GetBuffer(0); if (g_AutoCompleter) g_AutoCompleter->Add(nameToAdd); oneaddress.ReleaseBuffer(); } } */ // Copy the text in the headers from the control to the document // if (View && IsModified()) // View->SaveHeaders(); // if (IsModified() && !OnSaveDocument(NULL)) if(!OnSaveDocument(NULL)) return (FALSE); // Here's the scoop behind the MSFEX_SEND_PLAIN and MSFEX_SEND_STYLED flags: // // If both the message and the signature contain no styles, then both // flags are unset. If there are some styles present, then the two flags // tell which versions to send. So a flag being set means that there are // some styles in the message, and that particular version (plain or styled) // of the message should be sent. // // If we've saved a message with styles only because it has excerpts, then the MSFEX_SEND_PLAIN flag // will be set (and MSFEX_SEND_STYLED won't be set) so that we wind up just sending plain text. const BOOL bBodyExcerptOnly = (m_Sum->GetFlagsEx() & MSFEX_SEND_PLAIN) && !(m_Sum->GetFlagsEx() & MSFEX_SEND_STYLED); BOOL bSendStyles = FALSE; if (m_Sum->IsXRich() && !bBodyExcerptOnly) bSendStyles = TRUE; else { // If only the signature has styles, then IDS_INI_STYLED_SIG controls whether // or not a styled signature should get sent with styles or just plain. char* Sig = NULL; if (GetIniShort(IDS_INI_SEND_STYLED_SIG) && (Sig = GetSignature(this, FALSE)) && IsFancy(Sig) >= IS_RICH) { bSendStyles = TRUE; } delete [] Sig; } if (!bSendStyles) { if (!bBodyExcerptOnly) { m_Sum->UnsetFlagEx(MSFEX_SEND_PLAIN); m_Sum->UnsetFlagEx(MSFEX_SEND_STYLED); } } else { if (!autoSend && GetIniShort(IDS_INI_WARN_QUEUE_STYLED_TEXT)) { // Let user tell us what to send CSendStylesDialog dlg; switch (dlg.DoModal()) { case IDCANCEL: return (FALSE); case IDC_SEND_PLAIN: m_Sum->SetFlagEx(MSFEX_SEND_PLAIN); m_Sum->UnsetFlagEx(MSFEX_SEND_STYLED); break; case IDC_SEND_STYLED: m_Sum->UnsetFlagEx(MSFEX_SEND_PLAIN); m_Sum->SetFlagEx(MSFEX_SEND_STYLED); break; case IDC_SEND_PLAIN_AND_STYLED: m_Sum->SetFlagEx(MSFEX_SEND_PLAIN); m_Sum->SetFlagEx(MSFEX_SEND_STYLED); break; default: // Should never get here... ASSERT(0); } } else { // Use setting to determine what to send if (GetIniShort(IDS_INI_SEND_PLAIN_AND_STYLED)) { m_Sum->SetFlagEx(MSFEX_SEND_PLAIN); m_Sum->SetFlagEx(MSFEX_SEND_STYLED); } else if (GetIniShort(IDS_INI_SEND_STYLED_ONLY)) { m_Sum->UnsetFlagEx(MSFEX_SEND_PLAIN); m_Sum->SetFlagEx(MSFEX_SEND_STYLED); } else { m_Sum->SetFlagEx(MSFEX_SEND_PLAIN); m_Sum->UnsetFlagEx(MSFEX_SEND_STYLED); } } } if (!m_Sum->GetTranslators().IsEmpty()) { CTranslatorManager* trans = ((CEudoraApp *)AfxGetApp())->GetTranslators(); if ( !trans->CanXLateMessageOut(this, EMSF_Q4_TRANSMISSION | EMSF_Q4_COMPLETION) ) return (FALSE); // // Do we have any OnCompletion translators? // If so, go ahead and translate the message now. // if (GetIniShort(IDS_INI_ALLOW_COMPLETION_PLUGINS) && trans->CanXLateMessageOut(this, EMSF_Q4_COMPLETION ) ) { char cooked[_MAX_PATH]; HRESULT hr = OnCompletionTranslate(cooked); if ( FAILED(hr) ) return (FALSE); // // Delete attachments from header and attach newly // translated file (.msg). Clear Body as well. // m_Sum->SetFlagEx(MSFEX_MIME_ATTACHED); m_Sum->SetFlagEx(MSFEX_AUTO_ATTACHED); AddAttachment(cooked); SetHeaderLine(HEADER_ATTACHMENTS, cooked); m_Sum->SetTranslators(""); QCProtocol* pProtocol = QCProtocol::QueryProtocol( QCP_TRANSLATE, ( CObject* )GetView() ); if( pProtocol == NULL ) return FALSE; pProtocol->SetAllText("", FALSE); if (!OnSaveDocument(NULL)) return (FALSE); // make read only } } // No need to do this anymore because saving the message sets the date/time // of the summary. That's because the Date: header should contain the last // date/time the message was edited, not when it was queued/sent. // // //If msg could not be sent, then it is queued with the current time again. // //Since the send code changes the time zone minutes, we need to reset it. // m_Sum->m_Seconds = time(NULL); // m_Sum->m_TimeZoneMinutes = 0; // m_Sum->FormatDate(); m_Sum->SetState(MS_QUEUED); // Close up message window if (m_Sum->m_FrameWnd) { // Close the window, but don't destroy the document because // we're going to need it later when we send the message m_bAutoDelete = FALSE; OnCloseDocument(); m_bAutoDelete = TRUE; } SetQueueStatus(); return (TRUE); } HRESULT CCompMessageDoc::OnCompletionTranslate(char* cookedMsg) { HRESULT hr; char* ptr; int err; // // Create an object to encode the message and send its // MIME parts to the spool file. // QCSMTPMessage SendMsg(this); CString raw = GetTmpFileNameMT(); hr = SendMsg.Start(raw); if ( FAILED(hr) ) goto fail; // hr = SendMsg.WriteHeaders(); // if ( FAILED(hr) ) goto fail; // // Save MIME encoded body to temp file // hr= SendMsg.WriteBody(); if ( FAILED(hr) ) goto fail; hr = SendMsg.End(); // Translate it and store it in new file called COOKED. // char cooked[_MAX_PATH]; *cooked = 0; err = GetTransMan()->XLateMessageOut(EMSF_Q4_TRANSMISSION | EMSF_Q4_COMPLETION | EMSF_WHOLE_MESSAGE | EMSF_REQUIRES_MIME | EMSF_GENERATES_MIME, this, raw, cooked); DeleteFile(raw); if ( err != EMSR_OK ) { DeleteFile(cooked); CloseProgress(); return E_FAIL; } // // Rename the file from .tmp to .msg // strcpy(cookedMsg,cooked); strlwr(cookedMsg); ptr = strstr(cookedMsg,".tmp"); if (ptr) { strcpy(ptr,".msg"); hr = ::FileRenameMT(cooked,cookedMsg); } CloseProgress(); return hr; fail: HRESULT hr2; hr2 = SendMsg.End(); // what to do about return value here... DeleteFile(raw); CloseProgress(); return hr; } const char* CCompMessageDoc::SetHeaderLine(int i, const char* NewText) { CHeaderView* View = NULL; if ( i == HEADER_CURRENT ) { View = GetHeaderView(); if (View) i = View->GetCurrentHeader(); if ( i < 0 || i >= MaxHeaders ) return NULL; } ASSERT(i >= 0 && i < MaxHeaders); if ( i < NumHeaders ) { if (View == NULL) View = GetHeaderView(); if (View) View->SetText(i, NewText); } return (m_Headers[i] = NewText); } const char* CCompMessageDoc::GetHeaderLine( int i ) { CHeaderView* pHView = NULL; if ( i == HEADER_CURRENT ) { pHView = GetHeaderView(); if (pHView) i = pHView->GetCurrentHeader(); } if ( i >= 0 && i < MaxHeaders ) { if ( i < NumHeaders ) { if ( pHView == NULL ) pHView = GetHeaderView(); if ( pHView ) { m_Headers[i] = pHView->GetText( i ); } } return ( m_Headers[i] ); } ASSERT( 0 ); return NULL; } BOOL CCompMessageDoc::IsHeaderEmpty(int i) { const char* Header = GetHeaderLine(i); return (Header && *Header? FALSE : TRUE); } void CCompMessageDoc::SetHeaderAsInvalid(int nHeader, BOOL bInvalid) { m_HeadersInvalidFlag[nHeader] = bInvalid; } BOOL CCompMessageDoc::Read() { UINT uLen; if (!CMessageDoc::Read()) return (FALSE); // // m_ExtraHeaders is an additive variable so let's clean it out just // in case some residue is left. The reason for this is because PgMsgView // chooses to nullify m_text to conserve memory. // m_ExtraHeaders=""; // get the Translation X-Header char *Trans = HeaderContents(IDS_TRANS_XHEADER, m_Text); if (Trans) { m_Sum->SetTranslators(Trans); delete []Trans; } // get the Signature X-Header char *sigstr = HeaderContents(IDS_SIGNATURE_XHEADER, m_Text); if (sigstr) { char *cp = sigstr; if (*cp == '<' && *(cp + strlen(cp) - 1) == '>') { cp++; *(cp + strlen(cp) - 1) = '\0'; m_Sum->m_SigSelected = m_Sum->m_SigHdr = cp; } delete[] sigstr; } // get the Persona X-Header char *Persona = HeaderContents(IDS_PERSONA_XHEADER, m_Text); if (Persona) { char *cp = Persona; if (*cp == '<' && *(cp + strlen(cp) - 1) == '>') { cp++; *(cp + strlen(cp) - 1) = '\0'; m_Sum->SetPersona( cp ); } delete [] Persona; } // get the Precedence Header char *prec = HeaderContents(IDS_PRECEDENCE_HEADER, m_Text); if (prec) { m_Sum->SetPrecedence(prec); delete [] prec; } // Go through the message and parcel out each item char* t = m_Text; while (t && *t != '\r' && *t != '\n' && *t) { char * start = t; char * end; BOOL bConsumed = FALSE; // strip "\r\n" if ( end = strchr( t, '\n') ) { if ( end[ -1 ] == '\r') end[ -1 ] = '\0'; end[0] = '\0'; } else { // // What we have here is a corrupted message that doesn't // have a CR/LF to terminate the current line of the message. // Bail the header processing loop, placing a canned // blurb into the message body stating that the message is // corrupted. // ASSERT( FALSE ); // every line should have a delimiter delete [] m_Text; CRString corrupted(IDS_ERR_CORRUPTED_MESSAGE); m_Text = new char[corrupted.GetLength() + 1]; if (m_Text) strcpy(m_Text, corrupted); t = NULL; break; } char* colon = strchr( t, ':' ); if ( colon ) { // Check if this is a header we use? int i = FindRStringIndexI(IDS_HEADER_TO, IDS_HEADER_REFERENCES, t, colon - t); // If found, fill in the value for display. if (i >= 0) { // Get the value for the header if (*++colon == ' ') colon++; m_Headers[i] = colon; bConsumed = TRUE; } } while ( ! bConsumed ) // will only run once { bConsumed = TRUE; char ours[ 80 ]; QCLoadString( IDS_TRANS_XHEADER, ours, sizeof( ours ) ); if ( strstr( start, ours ) == start ) continue; QCLoadString( IDS_SIGNATURE_XHEADER, ours, sizeof( ours ) ); if ( strstr( start, ours ) == start ) continue; QCLoadString( IDS_PERSONA_XHEADER, ours, sizeof( ours ) ); if ( strstr( start, ours ) == start ) continue; QCLoadString( IDS_PRECEDENCE_HEADER, ours, sizeof( ours ) ); if ( strstr( start, ours ) == start ) continue; // save extra headers if (! m_ExtraHeaders.IsEmpty() ) m_ExtraHeaders += "\r\n"; m_ExtraHeaders += start; } // go on to next header t = end + 1; } // delimit the extra headers if (! m_ExtraHeaders.IsEmpty() ) m_ExtraHeaders += "\r\n"; // default From: if need be if ( m_Headers[ HEADER_FROM ].IsEmpty() ) { m_Headers[ HEADER_FROM ] = GetReturnAddress(); } #ifndef unix int hasLF = 1; #else int hasLF = 0; #endif // find the begining of the body which start with a \n // step over it so the body start at the first line if (t && (t = strchr(t + hasLF, '\n'))) strcpy(m_Text, t + 1); // strip off the trailing \r\n we added on save if ( ( uLen = strlen( m_Text ) ) >= 2 ) { if( ( m_Text[ uLen - 1 ] == '\n' ) && ( m_Text[ uLen - 2 ] == '\r' ) ) { // truncate it at the \r\n m_Text[ uLen - 2 ] = '\0'; } } m_HasBeenSaved = TRUE; //Reset these flags only if they haven't been set yet..they should never be set to TRUE m_HeadersInvalidFlag[HEADER_FROM] = FALSE; m_HeadersInvalidFlag[HEADER_SUBJECT] = FALSE; m_HeadersInvalidFlag[HEADER_ATTACHMENTS] = FALSE; return (TRUE); } // Write BOOL CCompMessageDoc::Write() { return (Write((JJFile*)NULL)); } BOOL CCompMessageDoc::Write(JJFile* out) { char* mes = NULL; int CreatedJJFile = FALSE; CTocDoc *OutToc = GetOutToc(); if (!OutToc) return (FALSE); m_Sum->m_TheToc = OutToc; // Save the flags if (!out) { CHeaderView* pHView = GetHeaderView(); // BADSTUFF - Here we just hacked it to use our Paige derived view. This // sucks just as bad; we need to use protocols to solve this view- // dependancy stuff. CView* View = GetView(); if ( View && pHView ) { pHView->SaveToDoc(); ((PgMsgView*)View)->SaveInfo(); if (!IsHeaderEmpty(HEADER_ATTACHMENTS)) m_Sum->SetFlag(MSF_HAS_ATTACHMENT); else m_Sum->UnsetFlag(MSF_HAS_ATTACHMENT); OutToc->SetModifiedFlag(); } } // Let's not waste time and disk space, shall we if (!out && m_HasBeenSaved && !IsModified()) return (TRUE); else OutToc->SetModifiedFlag(); while (1) { char buf[256]; if (!out) { out = new JJFile; CreatedJJFile = TRUE; if (FAILED(out->Open(OutToc->MBFilename(), O_APPEND | O_RDWR))) break; } // Get the offset of the start of the message long Start = 0; out->Tell(&Start); ASSERT(Start >= 0); // Write From line CTime Time(CTime::GetCurrentTime()); if (Time.GetTime() < 0) Time = 0; CString FromString = ::FormatTimeMT(Time.GetTime(), GetIniString(IDS_FROM_CTIME_FORMAT)); if (FAILED(out->PutLine(FromString))) break; // Write out headers int i = 0; for (; i < MaxHeaders; i++) { if (FAILED(out->Put(CRString(IDS_HEADER_TO + i))) || FAILED(out->Put(" "))) break; char* t = m_Headers[i].GetBuffer(m_Headers[i].GetLength()); char* HL = t; char* n = t; while (n && (*n == ' ' || *n == '\t')) n++; for (; n && *n; n++) { if (*n == '\n') *t++ = ' '; else if (*n != '\r') *t++ = *n; } if (t) { *t = 0; if (FAILED(out->Put(HL))) break; } if (FAILED(out->PutLine())) break; m_Headers[i].ReleaseBuffer(); } // Did something go wrong? if (i != MaxHeaders) break; // Add any extra headers if ( ! m_ExtraHeaders.IsEmpty() ) { if (FAILED(out->Put(m_ExtraHeaders))) break; } // Put the Translator Header CString TransString; CString Tltrs = m_Sum->GetTranslators(); if (!Tltrs.IsEmpty()) { TransString.Format(CRString(IDS_TRANS_XHEADER_FORMAT),(const char *)Tltrs); if (FAILED(out->PutLine(TransString))) break; } // Put the Signature Header CString SigString = m_Sum->m_SigSelected; if (!SigString.IsEmpty()) { CString szTemp; szTemp.Format(CRString(IDS_SIGNATURE_XHEADER_FORMAT),(const char *)SigString); if (FAILED(out->PutLine(szTemp))) break; m_Sum->m_SigHdr = m_Sum->m_SigSelected; } // Put the Persona Header CString PersonaString; CString Persona = m_Sum->GetPersona(); if (!Persona.IsEmpty()) { PersonaString.Format(CRString(IDS_PERSONA_XHEADER_FORMAT),(const char *)Persona); if (FAILED(out->PutLine(PersonaString))) break; } // Put the Precedence Header CString PrecString; CString Precedence = m_Sum->GetPrecedence(); if (!Precedence.IsEmpty()) { PrecString.Format(CRString(IDS_PRECEDENCE_HEADER_FORMAT),(const char *)Precedence); if (FAILED(out->PutLine(PrecString))) break; } // BOG: write the "embedded object headers"; these don't go out // over the wire. CString eoHeaders; m_QCMessage.GetEmbeddedObjectHeaders( eoHeaders ); if ( !eoHeaders.IsEmpty() ) { if (FAILED(out->Put(eoHeaders) < 0)) break; if (FAILED(out->PutLine())) break; } // Separate Header section from the Body of the message if (FAILED(out->PutLine())) break; if (!m_Text) break; //If we add space or quote at the beginning of lines starting //with "From ", then we should read the body text again. Else, the //send code just calls GetFullMessage which detects m_text is already //loaded up. But we just wrote some spaces or >s into the mbx file, //but haven't changed m_text itself. BOOL bNeedReRead = FALSE; char* Text = m_Text; do { long len = strcspn(Text, "\n"); if (Text[len] == '\n') len++; // Quote From lines //For html msgs we add a space since spaces at the beginning of the line //are collapsed anyway on display //For all other msg types we quote the from line if ( m_Sum->IsHTML() ) { if ( Text[0] == 'F' && Text[1] == 'r' && Text[2] == 'o' && Text[3] == 'm' && Text[4] == ' ' ) { if (FAILED(out->Put(' '))) break; bNeedReRead = TRUE; } } else if ( IsFromLine(Text) ) { if ( FAILED(out->Put(' '))) break; bNeedReRead = TRUE; } if (FAILED(out->Put(Text, len))) break; Text += len; } while (*Text); // Did something go wrong? if (*Text) break; // add the body separator if (FAILED(out->PutLine())) break; // Update the message summary CSummary::m_lBegin = Start; out->Seek(Start); m_Sum->SetFrom(NULL); m_Sum->SetSubject(NULL); // m_Sum->SetDate(NULL); // Save State and Date since Build() changes it short state = m_Sum->m_State; strcpy(buf, m_Sum->m_Date); m_Sum->m_TheToc->m_DelSpace += m_Sum->m_Length; m_Sum->m_TheToc->m_MesSpace -= m_Sum->m_Length; m_Sum->Build(out); m_Sum->m_TheToc->m_MesSpace += m_Sum->m_Length; m_Sum->m_TheToc->m_TotalSpace += m_Sum->m_Length; m_Sum->SetState( (char)state); m_Sum->SetDate(time(NULL) + (GetGMTOffset() * 60)); if (m_Sum->IsQueued() == FALSE) { m_Sum->SetState(!IsHeaderEmpty(HEADER_TO) || !IsHeaderEmpty(HEADER_BCC)? MS_SENDABLE : MS_UNSENDABLE); } // Possibly change the title info ReallySetTitle(m_Sum->MakeTitle()); if (CreatedJJFile) { out->Close(); OutToc->Write(); if (m_HasBeenSaved) OutToc->m_NeedsCompact = TRUE; else m_HasBeenSaved = TRUE; SetModifiedFlag(FALSE); delete out; } if (bNeedReRead) { delete [] m_Text; m_Text = NULL; } return (TRUE); } if (out && CreatedJJFile) delete out; return (FALSE); } //////////////////////////////////////////////////////////////////////// // FindFirst [public, virtual] // // Implementation of pure virtual defined in base class. //////////////////////////////////////////////////////////////////////// BOOL CCompMessageDoc::FindFirst(const CString& searchStr, BOOL matchCase, BOOL wholeWord, BOOL bOpenWnd /* = TRUE */) { m_FindHeaderIndex = 0; // force search to start at first header m_FindIndex = 0; // force search to start at top of message BOOL result = FALSE; // // Make copies of the search string and the actual message text. // Yes, it's inefficient to ALWAYS make copies, but since most // searches are case-insensitive, we'll probably end up making a // copy anyway. We need these local copies so that we can call // MakeLower() and strlwr() on them. // CString search_str(searchStr); // // Force message data to be read up from file. // GetText(); // // Kick off the search, first looking through each header in turn. // If there is no match in a header, then continue the search in // the message body. // for (int i = m_FindHeaderIndex; i <= 6; i++) { // // Get the text to scan in this pass, searching from the last // find position. // CString msg_text; if (i < 6) msg_text = (char *) GetHeaderLine(i); else { msg_text = (char *) GetText(); // // Strip text-enriched formatting codes, if any. // /* fix if (m_Sum->IsXRich()) { TextReader reader; const OLD_LENGTH = msg_text.GetLength(); char* p_msgtext = msg_text.GetBuffer(OLD_LENGTH + 4); int new_length = reader.StripRich(p_msgtext, OLD_LENGTH, TRUE); ASSERT(new_length < OLD_LENGTH); p_msgtext[new_length] = '\0'; msg_text.ReleaseBuffer(new_length); } */ } const char* p_msgtext = msg_text; if (! matchCase) { msg_text.MakeLower(); search_str.MakeLower(); } ASSERT(m_FindIndex >= 0); if (m_FindIndex > 0) { ASSERT(m_FindIndex < long(msg_text.GetLength())); p_msgtext += m_FindIndex; } // // Do the search... // char* p_match = strstr(p_msgtext, search_str); if (p_match) { // // Got a hit. // result = TRUE; m_FindIndex += p_match - p_msgtext; ASSERT(m_FindIndex >= 0); if (!bOpenWnd) return (TRUE); // // Open the message window, if necessary, making it the active MDI child. // ASSERT(m_Sum != NULL); ASSERT(m_Sum->IsComp()); m_DidFindOpenView = (GetFirstViewPosition() == NULL); m_Sum->Display(); // // Get the one and only comp message window for this document. // CView* p_compmsgv = GetCompView(); if (NULL == p_compmsgv) { ASSERT(0); m_FindIndex = -1; return FALSE; } // // 32-bit implementation. FORNOW, should call a generic // "get header view" function here whenever BOGDON gets // around to writing one. // CCompMessageFrame* p_frame = (CCompMessageFrame *) p_compmsgv->GetParentFrame(); ASSERT(p_frame && p_frame->IsKindOf(RUNTIME_CLASS(CCompMessageFrame))); CHeaderView* p_hdrview = p_frame->GetHeaderView(); ASSERT(p_hdrview && p_hdrview->IsKindOf(RUNTIME_CLASS(CHeaderView))); ASSERT(m_FindHeaderIndex >= 0); if (m_FindHeaderIndex < 6) { // // Got a hit in the header, so we need to grab the // proper edit control and tell the edit control // exactly where to do the selection. // CHeaderField* p_editctrl = p_hdrview->GetHeaderCtrl(m_FindHeaderIndex); if (p_editctrl != NULL) { // // We need to set the active view ourselves // so that the keyboard focus ends up where // we want it. FORNOW, this is probably // overkill since the comp message view // splitter comes up with the CHeaderView pane // as the active view by default. // p_frame->SetActiveView(p_hdrview, TRUE); // // The following call is a very special hack // to fool the CFormView-derived object to set // the focus where we want it and not where it // thinks it wants it. // p_hdrview->SetFocusToHeader(m_FindHeaderIndex); FindSetSel32(/* p_compmsgv,*/ p_hdrview, p_editctrl, int(m_FindIndex), int(m_FindIndex + search_str.GetLength())); // p_editctrl->SetSel(m_FindIndex, m_FindIndex + search_str.GetLength(), FALSE); m_FindIndex++; } } else { QCProtocol* pProtocol = QCProtocol::QueryProtocol( QCP_FIND, p_compmsgv ); if( ( pProtocol == NULL ) || ( pProtocol->DoFindFirst( searchStr, matchCase, wholeWord, TRUE ) == FALSE ) ) { return FALSE; } result = TRUE; } break; } else { // // No match in this header, so try next header, if any. // m_FindHeaderIndex++; m_FindIndex = 0; } } // // Set index so that subsequent FindNext() calls don't choke on // the fact that there is no view for this doc. // if (! result) { m_FindHeaderIndex = -1; m_FindIndex = -1; } return result; } //////////////////////////////////////////////////////////////////////// // FindNext [public, virtual] // // Implementation of pure virtual defined in base class. //////////////////////////////////////////////////////////////////////// BOOL CCompMessageDoc::FindNext(const CString& searchStr, BOOL matchCase, BOOL wholeWord) { // // Check for previous Find action, redirecting to FindFirst() if // there was no previous Find. // if (m_FindHeaderIndex < 0) return FindFirst(searchStr, matchCase, wholeWord); // // Get the one and only comp message window for this document. // CView* p_compmsgv = GetCompView(); if (NULL == p_compmsgv) { ASSERT(0); m_FindIndex = -1; return FALSE; } BOOL result = FALSE; // returned if (6 == m_FindHeaderIndex) { // // Special case for 32-bit implementation. If we had a // previous hit in the message body, we just need to delegate // to QCProtocol to find the next hit, if any. // QCProtocol* pProtocol = QCProtocol::QueryProtocol( QCP_FIND, p_compmsgv ); m_Sum->Display(); if( ( pProtocol == NULL ) || ( pProtocol->DoFindNext( searchStr, matchCase, wholeWord, TRUE ) == FALSE ) ) { return FALSE; } result=TRUE; } else { // // Run a loop to scan remaining header controls, if any, plus the // actual message text, starting where we left off from last time. // Make copies of the search string and the actual message text. // Yes, it's inefficient to ALWAYS make copies, but since most // searches are case-insensitive, we'll probably end up making a // copy anyway. We need these local copies so that we can call // MakeLower() and strlwr() on them. // CString search_str(searchStr); // // Kick off the search, first looking through each header in turn. // If there is no match in a header, then continue the search in // the message body. // for (int i = m_FindHeaderIndex; i <= 6; i++) { // // Get the text to scan in this pass, searching from the last // find position. // CString msg_text; if (i < 6) msg_text = (char *) GetHeaderLine(i); else { msg_text = (char *) GetText(); // // Strip text-enriched formatting codes, if any. // /* fix if (m_Sum->IsXRich()) { TextReader reader; const OLD_LENGTH = msg_text.GetLength(); char* p_msgtext = msg_text.GetBuffer(OLD_LENGTH + 4); int new_length = reader.StripRich(p_msgtext, OLD_LENGTH, TRUE); ASSERT(new_length < OLD_LENGTH); p_msgtext[new_length] = '\0'; msg_text.ReleaseBuffer(new_length); } */ } const char* p_msgtext = msg_text; if (! matchCase) { msg_text.MakeLower(); search_str.MakeLower(); } ASSERT(m_FindIndex >= 0); if (m_FindIndex > 0) { ASSERT(m_FindIndex < long(msg_text.GetLength())); p_msgtext += m_FindIndex; } // // Do the search... // char* p_match = strstr(p_msgtext, search_str); if (p_match) { // // Found a match! // m_FindIndex += p_match - p_msgtext; // save position for next time ASSERT(m_FindIndex >= 0); m_Sum->Display(); // already open, but make it the active child window // // 32-bit implementation. FORNOW, should call a generic // "get header view" method here someday. // CCompMessageFrame* p_frame = (CCompMessageFrame *) p_compmsgv->GetParentFrame(); ASSERT(p_frame && p_frame->IsKindOf(RUNTIME_CLASS(CCompMessageFrame))); CHeaderView* p_hdrview = p_frame->GetHeaderView(); ASSERT(p_hdrview && p_hdrview->IsKindOf(RUNTIME_CLASS(CHeaderView))); ASSERT(m_FindHeaderIndex >= 0); if (m_FindHeaderIndex < 6) { // // Got a hit in the header, so we need to grab the // proper edit control and do the selection ourselves. // CHeaderField* p_editctrl = p_hdrview->GetHeaderCtrl(m_FindHeaderIndex); if (p_editctrl != NULL) { // // We need to set the active view ourselves // so that the keyboard focus ends up where // we want it. // p_frame->SetActiveView(p_hdrview, TRUE); // // The following call is a very special hack to // fool the CFormView-derived object to set the // focus where we want it and not where it thinks // it wants it. // p_hdrview->SetFocusToHeader(m_FindHeaderIndex); FindSetSel32(/* p_compmsgv,*/ p_hdrview, p_editctrl, int(m_FindIndex), int(m_FindIndex + search_str.GetLength())); // p_editctrl->SetSel(m_FindIndex, m_FindIndex + search_str.GetLength(), FALSE); m_FindIndex++; result = TRUE; } } else { // // Got a hit in the body, so first deselect // everything in the headers, then perform // ANOTHER search in the body using the built-in // QCProtocol method. // FindSetSel32(/*p_compmsgv, */p_hdrview, NULL, -1, -1); QCProtocol* pProtocol = QCProtocol::QueryProtocol( QCP_FIND, p_compmsgv ); if( ( pProtocol == NULL ) || ( pProtocol->DoFindFirst( searchStr, matchCase, wholeWord, TRUE ) == FALSE ) ) { return FALSE; } result = TRUE; } break; } else { // // No match in this header, so try next header, if any. // m_FindHeaderIndex++; m_FindIndex = 0; } } } // // Set indices so that subsequent FindNext() calls don't choke on // the fact that there is no view for this doc. // if (! result) { m_FindHeaderIndex = -1; m_FindIndex = -1; } return result; } //////////////////////////////////////////////////////////////////////// // FindAgain [public, virtual] // // Implementation of pure virtual defined in base class. //////////////////////////////////////////////////////////////////////// BOOL CCompMessageDoc::FindAgain(const CString& searchStr, BOOL matchCase, BOOL wholeWord) { if (m_FindHeaderIndex < 0) { // // This is an unusual, but legal, case where the user didn't find // a hit last time we searched in an open message. // return FindFirst(searchStr, matchCase, wholeWord); } if (FindNext(searchStr, matchCase, wholeWord)) return TRUE; return FindFirst(searchStr, matchCase, wholeWord); } //////////////////////////////////////////////////////////////////////// // FindSetSel32 [protected] // // Helper function for the 32-bit Find Engine which knows how to do the // selection correctly for the split comp message window. The // problem is that you must clear any existing selection from all // of the edit controls before you can set a new selection. Otherwise, // you end up with multiple, disjoint selections on the screen. // //////////////////////////////////////////////////////////////////////// void CCompMessageDoc::FindSetSel32( // CCompMessageView* pCompMessageView, //(i) lower rich edit view pane (required) CHeaderView* pHeaderView, //(i) upper form view pane (required) CEdit* pEditCtrl, //(i) header control containing text to be selected (optional) int startIndex, //(i) starting offset for pEditCtrl (optional) int endIndex) //(i) ending offst for pEditCtrl (optional) { if (/*NULL == pCompMessageView ||*/ NULL == pHeaderView) { ASSERT(0); // caller blew it return; } // // The actual type returned by GetHeaderCtrl() is actually // CHeaderField, which is a derivation of CEdit. Also, the type // returned by GetBodyCntl() is actually CCompBody, which is also // a derivation of CEdit. However, we don't need any special // subclassed edit control behavior, so force a generic CEdit. // // FORNOW, the 32-bit header doesn't support an Attachments header // line. // for (int i = 0; i <= 5; i++) { if (i < 5) { CEdit* p_edit = (CEdit *) pHeaderView->GetHeaderCtrl(i); if (p_edit != NULL) { ASSERT(p_edit->IsKindOf(RUNTIME_CLASS(CEdit))); p_edit->SetSel(0, 0); // deselect all } } // else // { // pCompMessageView->GetEditCtrl().SetSel(0, 0); // } } // // Finally, select the stuff that we were interested in the first // place. If the caller didn't provide an edit control, don't // panic -- that means they just wanted to deselect everything in // the header, presumably because we're about to select something // in the body. // if (pEditCtrl) { ASSERT(pEditCtrl->IsKindOf(RUNTIME_CLASS(CEdit))); pEditCtrl->SetFocus(); pEditCtrl->SetSel(startIndex, endIndex, FALSE); } } BEGIN_MESSAGE_MAP(CCompMessageDoc, CMessageDoc) //{{AFX_MSG_MAP(CCompMessageDoc) ON_UPDATE_COMMAND_UI(ID_MESSAGE_CHANGEQUEUEING, OnUpdateChangeQueueing) ON_COMMAND(ID_MESSAGE_CHANGEQUEUEING, OnChangeQueueing) ON_UPDATE_COMMAND_UI(ID_MESSAGE_STATUS_SENDABLE, OnUpdateStatusSendable) ON_UPDATE_COMMAND_UI(ID_MESSAGE_STATUS_QUEUED, OnUpdateStatusQueued) ON_UPDATE_COMMAND_UI(ID_MESSAGE_STATUS_TIME_QUEUED, OnUpdateStatusTimedQueue) ON_UPDATE_COMMAND_UI(ID_MESSAGE_STATUS_SENT, OnUpdateStatusSent) ON_UPDATE_COMMAND_UI(ID_MESSAGE_STATUS_UNSENT, OnUpdateStatusUnsent) ON_COMMAND(ID_FILE_PRINT, OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, OnFilePrintPreview) ON_COMMAND(ID_FILE_SAVE, OnFileSave) ON_UPDATE_COMMAND_UI(ID_FILE_SAVE_AS, OnUpdateFileSaveAs) ON_COMMAND(ID_FILE_SAVE_AS, OnFileSaveAs) ON_COMMAND(ID_FILE_SAVE_AS_STATIONERY, OnFileSaveAsStationery) ON_COMMAND(ID_MESSAGE_SENDIMMEDIATELY, OnSend) // ON_COMMAND(ID_MESSAGE_ATTACHFILE, OnAttachFile) ON_COMMAND(ID_MESSAGE_DELETE, OnMessageDelete) ON_UPDATE_COMMAND_UI(ID_MESSAGE_ATTACHFILE, OnCanModify) //}}AFX_MSG_MAP ON_COMMAND_EX(ID_MESSAGE_STATUS_SENDABLE, OnStatus) ON_COMMAND_EX(ID_MESSAGE_STATUS_QUEUED, OnStatus) ON_COMMAND_EX(ID_MESSAGE_STATUS_TIME_QUEUED, OnStatus) ON_COMMAND_EX(ID_MESSAGE_STATUS_SENT, OnStatus) ON_COMMAND_EX(ID_MESSAGE_STATUS_UNSENT, OnStatus) ON_COMMAND( ID_FCC_NEW_MBOX_IN_ROOT, OnFCCNewInRoot ) ON_COMMAND_EX_RANGE( QC_FIRST_COMMAND_ID, QC_LAST_COMMAND_ID, OnDynamicCommand ) ON_UPDATE_COMMAND_UI_RANGE( QC_FIRST_COMMAND_ID, QC_LAST_COMMAND_ID, OnUpdateDynamicCommand ) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CCompMessageDoc commands void CCompMessageDoc::OnUpdateChangeQueueing(CCmdUI* pCmdUI) { pCmdUI->Enable(m_Sum->IsSendable()); } void CCompMessageDoc::OnChangeQueueing() { if (!m_Sum || m_Sum->CantEdit()) ASSERT(FALSE); else { CChangeQueueing dlg(m_Sum->m_State == MS_TIME_QUEUED? m_Sum->m_Seconds : 0); if (dlg.DoModal() == IDOK) { dlg.ChangeSummary(m_Sum); if (FlushQueue) SendQueuedMessages(); } } } void CCompMessageDoc::OnUpdateStatusSendable(CCmdUI* pCmdUI) { BOOL Enable = FALSE; if (m_Sum) { switch (m_Sum->m_State) { case MS_SENDABLE: case MS_QUEUED: case MS_TIME_QUEUED: Enable = TRUE; break; } } pCmdUI->Enable(Enable); } void CCompMessageDoc::OnUpdateStatusQueued(CCmdUI* pCmdUI) { BOOL Enable = FALSE; if (m_Sum) { switch (m_Sum->m_State) { case MS_QUEUED: case MS_SENDABLE: case MS_TIME_QUEUED: Enable = TRUE; break; } } pCmdUI->Enable(Enable); } void CCompMessageDoc::OnUpdateStatusTimedQueue(CCmdUI* pCmdUI) { BOOL Enable = FALSE; if (m_Sum) { switch (m_Sum->m_State) { case MS_TIME_QUEUED: case MS_SENDABLE: case MS_QUEUED: Enable = TRUE; break; } } pCmdUI->Enable(Enable); } void CCompMessageDoc::OnUpdateStatusSent(CCmdUI* pCmdUI) { BOOL Enable = FALSE; if (m_Sum) { switch (m_Sum->m_State) { case MS_SENT: case MS_UNSENT: Enable = TRUE; break; } } pCmdUI->Enable(Enable); } void CCompMessageDoc::OnUpdateStatusUnsent(CCmdUI* pCmdUI) { BOOL Enable = FALSE; if (m_Sum) { switch (m_Sum->m_State) { case MS_UNSENT: case MS_SENT: Enable = TRUE; break; } } pCmdUI->Enable(Enable); } BOOL CCompMessageDoc::OnStatus(UINT StatusMenuID) { if (!m_Sum) return (FALSE); int NewStatus = m_Sum->m_State; switch (StatusMenuID) { case ID_MESSAGE_STATUS_SENDABLE: NewStatus = MS_SENDABLE; break; case ID_MESSAGE_STATUS_QUEUED: NewStatus = MS_QUEUED; break; case ID_MESSAGE_STATUS_TIME_QUEUED: NewStatus = MS_TIME_QUEUED; break; case ID_MESSAGE_STATUS_SENT: NewStatus = MS_SENT; break; case ID_MESSAGE_STATUS_UNSENT: NewStatus = MS_UNSENT; break; default: ASSERT(FALSE); break; } m_Sum->SetState(char(NewStatus)); SetQueueStatus(); return (TRUE); } // hack city void CCompMessageDoc::OnFilePrint() { CView* pRchView = GetView(); pRchView->SendMessage( WM_COMMAND, ID_FILE_PRINT ); } void CCompMessageDoc::OnFilePrintPreview() { CView* pRchView = GetView(); pRchView->SendMessage( WM_COMMAND, ID_FILE_PRINT_PREVIEW ); } // this stuff supports processing multiple documents via one MessageOptions setting static BOOL bInGroup; static BOOL bFirstInGroup; static CString csGroupPersona; static CString csGroupStationery; void StartGroup( void ) { // Obsolete? SD 7/13/99 bInGroup = TRUE; // Obsolete? SD 7/13/99 bFirstInGroup = TRUE; } void EndGroup( void ) { // Obsolete? SD 7/13/99 bInGroup = FALSE; // Obsolete? SD 7/13/99 bFirstInGroup = FALSE; } /* As far as I can tell, every message Eudora ever sends is created by this method. For sure, New Message, Reply, Reply All, Reply With, Forward, Redirect, and all the XXX To equiv's go through here. I've added Stationery and Persona. The precedence that all this stuff gets applied to the new message is as follows (lowest to highest); 1) To, From, Subject, Cc, Bcc, Attachments, Body 2) Default Stationery - if no explicit Stationery is specified and the Personality (including Dominant) has a default Stationery, it's applied. 3) Explicit Stationery - if specified, is applied instead of (2). 4) Default Personality - If no explicit Personality is specified, the Stationery's Personality will be used. If no Stationery was applied the Dominant personality will be used. The Personality is used to determine the From line, Signature, and how the message is sent. 5) Explicit Personality - if specified, is used instead of (4) to determine From line, Signature, and how the message is sent. Note that applying Stationery can change the effective Personality. Hence if a Personality's default Stationery was created by a different Personality... User input supplied via the Message Options dialog rules over parameters. Prophecy - Someday Dominant and Persona.IsEmpty() are not going to be equivilent. We will be revisiting this... */ CCompMessageDoc* NewCompDocument ( const char* To /*= NULL*/, const char* From /*= NULL*/, const char* Subject /*= NULL*/, const char* Cc /*= NULL*/, const char* Bcc /*= NULL*/, const char* Attachments /*= NULL*/, const char* Body /*= NULL*/, const char* Stationery /*= NULL*/, const char* Persona /*= NULL*/, const char ResponseType /*= 0*/, const char* ECHeaders /* = NULL*/ ) { CCompMessageDoc* NewCompDoc = NULL; #ifdef COMMERCIAL CString csStationery = Stationery; CString csPersona = Persona; CString csStatPersona; CString csCurPersona = g_Personalities.GetCurrent(); #if 0 // BOG: this is the old Shift-* sets the stationary/personality feature, // which has now gone back to Shift-Reply == ReplyAll. Woohoo! if ( ( Stationery == NULL ) && ShiftDown()) { CMessageOptions dlg; QCStationeryCommand* pCommand; // char statname[ 80 ]; // GetStatItemName( csStationery, statname, sizeof( statname) ); dlg.m_Persona = csPersona; pCommand = g_theStationeryDirector.FindByPathname( csStationery ); if( pCommand ) { dlg.m_Stationery = pCommand->GetName(); } int result = dlg.DoModal(); if ( result == IDCANCEL ) return NewCompDoc; if ( result == IDOK ) { csPersona = dlg.m_Persona; csStationery = dlg.m_Stationery; } } #endif // check for groups of documents if ( bFirstInGroup ) { csGroupPersona = csPersona; csGroupStationery = csStationery; bFirstInGroup = FALSE; } if ( bInGroup ) { csPersona = csGroupPersona; csStationery = csGroupStationery; } // make sure we get the right persona's default stationery if ( ! csPersona.IsEmpty() && g_Personalities.IsA( csPersona ) ) g_Personalities.SetCurrent( csPersona ); #endif // COMMERCIAL // create the new doc with the defaults NewCompDoc = (CCompMessageDoc*)NewChildDocument(CompMessageTemplate); if (NewCompDoc) NewCompDoc->InitializeNew(To, From, Subject, Cc, Bcc, Attachments, Body, ECHeaders); else return (NewCompDoc); // error creating document //No need for Persona and stationery in 4.1 Light #ifdef COMMERCIAL // Do not apply stationery if redirecting // or if call is from Automation if ((MS_REDIRECT != ResponseType) || gbAutomationCall) { // determine which (if any) stationery to apply if ( csStationery.IsEmpty() ) { const char * defaultStat = GetIniString(IDS_INI_STATIONERY); if (defaultStat && *defaultStat) csStationery = defaultStat; } // apply the stationery (may specify a personality) if ( ! csStationery.IsEmpty() ) { CString szFileName; // csStationery might be fully qualified already if ( strchr( csStationery, '\\' ) ) { szFileName = csStationery; } else { QCStationeryCommand* pCommand; pCommand = g_theStationeryDirector.Find( csStationery ); if( pCommand ) { szFileName = pCommand->GetPathname(); } } if( ( szFileName != "" ) && ::FileExistsMT( szFileName ) ) { CCompStationeryDoc NewStatDoc; NewStatDoc.Read( szFileName); NewCompDoc->ApplyStationery( &NewStatDoc ); // look for a personality change if ( NewStatDoc.m_Sum != NULL ) { csStatPersona = NewStatDoc.m_Sum->GetPersona(); } } //ReallySetTitle(); } } // // determine which personality we really want to use according to // Keith's Rule: Stationery Rules(tm) when it comes to personality. // //FORNOW if ( csPersona.IsEmpty() ) //FORNOW { if ( ! csStatPersona.IsEmpty() && g_Personalities.IsA( csStatPersona ) ) { // use the stationery's persona csPersona = csStatPersona; g_Personalities.SetCurrent( csPersona ); } //FORNOW } // Add personality overrides NewCompDoc->ApplyPersona( csPersona ); g_Personalities.SetCurrent( csCurPersona ); // go back to default persona #else //for Light 4.1 - don't know whethere we really need to apply persona, but anyways :) // Add personality overrides NewCompDoc->ApplyPersona( Persona ); #endif // COMMERCIAL return (NewCompDoc); } CCompMessageDoc* NewCompDocumentWith(const char * fileName) { char StrippedFileName[MAX_PATH + 1]; int len; strcpy(StrippedFileName, *fileName == '"'? fileName + 1 : fileName); len = strlen(StrippedFileName); if (StrippedFileName[len - 1] == '"') StrippedFileName[len - 1] = 0; // Make sure the file is there if (::FileExistsMT(StrippedFileName)) { // ( To, From, Subject, Cc, Bcc, Attachments, Body, Stationery, Persona ) CCompMessageDoc* NewCompDoc = NewCompDocument( "", "", "", "", "", "", "", StrippedFileName, "" ); return (NewCompDoc); } return (NULL); } CCompMessageDoc* NewCompDocumentAs(const CString& strPersona) { // Make sure the persona exists if (g_Personalities.IsA(strPersona)) { // ( To, From, Subject, Cc, Bcc, Attachments, Body, Stationery, Persona ) CCompMessageDoc* pNewCompDoc = NewCompDocument("", "", "", "", "", "", "", "", strPersona); return pNewCompDoc; } ASSERT(0); return NULL; } BOOL CCompMessageDoc::ApplyStationery(CCompStationeryDoc *statDoc) { CCompMessageDoc* msgdoc = (CCompMessageDoc *)m_Sum->GetMessageDoc(); for (int i = 0; i < NumHeaders; i++) { char sepChar = 0; switch(i) { case HEADER_FROM: //don't use this break; case HEADER_SUBJECT: { CString newSubject; CString oldString = GetHeaderLine(i); const char *subHdr = statDoc->GetHeaderLine(i); if (subHdr && *subHdr) { if (oldString.IsEmpty()) SetHeaderLine(HEADER_SUBJECT,subHdr); else { newSubject.Format(CRString(IDS_SUBJECT_CHANGE),subHdr, ( const char* )oldString); SetHeaderLine(HEADER_SUBJECT,newSubject); } } else SetHeaderLine(HEADER_SUBJECT,oldString); } break; case HEADER_TO: case HEADER_CC: case HEADER_BCC: sepChar = ','; case HEADER_ATTACHMENTS: { CString oldString = GetHeaderLine(i); const char *statHdr = statDoc->GetHeaderLine(i); if (statHdr && *statHdr && strcmp(statHdr, " ")) { if (!oldString.IsEmpty()) { if (sepChar) { oldString += sepChar; oldString += " "; } oldString += statHdr; SetHeaderLine(i,oldString); } else SetHeaderLine(i,statHdr); } } break; } } // Add A Line if (m_Text && *m_Text) CatText("\r\n"); //Applying Plain Stat to a styled msg causes linebreaks to disappear if (statDoc->m_Sum) { if ((this->m_Sum->IsXRich()) || (this->m_Sum->IsHTML())) { if ((statDoc->m_Sum->IsXRich()) || (statDoc->m_Sum->IsHTML())) CatText(statDoc->GetText()); else { CString szHtmlOn = "<" + CRString(IDS_MIME_HTML) + ">"; CString szHtmlOff = "</" + CRString(IDS_MIME_HTML) + ">"; CString statText = Text2Html(statDoc->GetText(), TRUE, TRUE); CatText(szHtmlOn); CatText(statText); CatText(szHtmlOff); } } else CatText(statDoc->GetText()); } else CatText(statDoc->GetText()); // 9/16 changed from GetBody() m_QCMessage.Init(CCompMessageDoc::m_MessageId, CCompMessageDoc::m_Text, FALSE); // Do we have summary info? if (statDoc->m_Sum) { BOOL bAddRich = m_Sum->IsXRich(); BOOL bAddHTML = m_Sum->IsHTML(); // copy the stationary flags m_Sum->CopyFlags( statDoc->m_Sum ); if ( bAddRich ) m_Sum->SetFlag( MSF_XRICH ); if ( bAddHTML ) m_Sum->SetFlagEx( MSFEX_HTML ); m_Sum->SetPriority(statDoc->m_Sum->m_Priority); m_Sum->SetTranslators(statDoc->m_Sum->GetTranslators(), TRUE); m_Sum->SetSignature(statDoc->m_Sum->m_SigHdr); m_Sum->SetPersona( statDoc->m_Sum->GetPersona() ); } m_strPathName.Empty(); CCompMessageDoc::m_strPathName = statDoc->m_strPathName; m_StationeryApplied = TRUE; return (TRUE); } // Format the From line for redirect void CCompMessageDoc::SetupRedirect( const char * oldFrom /* = NULL */ ) { const char* Return = GetReturnAddress(); if (!IsRedirect()) m_RedirectFrom = oldFrom ? oldFrom : GetHeaderLine(HEADER_FROM); char *NewFrom = new char[m_RedirectFrom.GetLength() + ::SafeStrlenMT(Return) + 100]; sprintf(NewFrom, CRString(IDS_REDIRECT_FORMAT), (const char *)m_RedirectFrom, Return); SetHeaderLine(HEADER_FROM,NewFrom); delete [] NewFrom; } // From: and signature are always based of Persona BOOL CCompMessageDoc::ApplyPersona( CString Persona ) { if ( ! Persona.IsEmpty() && ! g_Personalities.IsA( Persona ) ) return FALSE; CRString DomDude( IDS_DOMINANT ); if ( Persona == DomDude ) Persona.Empty(); // we prefer the "" over "<Dominant>" CString CurPersona = g_Personalities.GetCurrent(); if ( Persona != CurPersona ) g_Personalities.SetCurrent( Persona ); m_Sum->SetPersona( Persona ); #ifdef COMMERCIAL // IDS_INI_SIGNATURE_NAME must be the same string as IDS_INI_PERSONA_SIGNATURE char szEntry[ 80 ]; // emulate 2.2 behavior if ( ! m_StationeryApplied && GetIniShort( IDS_INI_USE_SIGNATURE ) ) { // look for ini entry and default to "Standard" if none found char szKey[ 64 ]; QCLoadString( IDS_INI_SIGNATURE_NAME, szKey, sizeof( szKey ) ); g_Personalities.GetProfileString( Persona, szKey, "NotThereAtAll", szEntry, sizeof( szEntry ) ); if ( strcmp( szEntry, "NotThereAtAll" ) == 0 ) { CRString csStandard( IDS_STANDARD_SIGNATURE ); strcpy( szEntry, csStandard ); } } else { GetIniString( IDS_INI_SIGNATURE_NAME, szEntry, sizeof( szEntry ) ); } // Stationery signatures normally rule... // If we are editing a stationery and change the persona, then we want the //persona's signature BOOL bStationeryRules = GetIniShort( IDS_INI_SIGNATURE_PRECEDENCE ); if ( IsStationery() || ! m_StationeryApplied || ( m_StationeryApplied && !bStationeryRules ) ) { //If the personality had no default signature, we want to set the signature to <none> //Note the signature could be Empty or "No Default", Set signature handles all cases m_Sum->SetSignature( szEntry ); } #else if ( GetIniShort( IDS_INI_USE_SIGNATURE ) ) { CRString csStandard( IDS_STANDARD_SIGNATURE ); CRString csNone( IDS_SIGNATURE_NONE); CRString csAlternate( IDS_ALTERNATE_SIGNATURE32); CString strSig = GetIniString( IDS_INI_SIGNATURE_NAME); if(strSig == csStandard) m_Sum->SetSignature( csStandard ); else if(strSig == csAlternate) m_Sum->SetSignature( csAlternate ); } #endif //COMMERCIAL // fix up the From: line if (IsRedirect()) SetupRedirect(); else SetHeaderLine( HEADER_FROM, GetReturnAddress() ); // restore current persona if we changed it if ( ( Persona != CurPersona ) ) g_Personalities.SetCurrent( CurPersona ); return TRUE; } void CCompMessageDoc::ReadEudoraInfo(CString &sEudoraIniV2) { char buf[_MAX_PATH+1]; CString EudoraFile; GetIniString(IDS_INI_AUTO_RECEIVE_DIR, buf, sizeof(buf)); if (buf[0] == '\0') EudoraFile = EudoraDir + CRString(IDS_ATTACH_FOLDER) + "\\" + CRString(IDS_REGISTER_EUDORA_COPY); else EudoraFile = CString(buf) + "\\" + CRString(IDS_REGISTER_EUDORA_COPY); wsprintf(buf, "%s", EudoraFile); // Let's get the new INI file JJFile *pNewFile = new JJFile; if (!pNewFile) return; if (FAILED(pNewFile->Open(buf, O_CREAT | O_WRONLY))) { delete pNewFile; pNewFile = NULL; return; } // Let's get the Eudora INI file JJFile *pINIFile = new JJFile; if (!pINIFile) return; if (FAILED(pINIFile->Open((const char*)INIPath, O_RDONLY))) { delete pINIFile; pINIFile = NULL; return; } CString sLine; CString sPassword; sPassword = CRString(IDS_INI_SAVE_PASSWORD_TEXT); CString sDialUpPassword; sDialUpPassword = CRString(IDS_INI_SAVE_DIALUP_PASSWORD_TEXT); long lNumBytesRead = 0; do { char* pszLine = sLine.GetBuffer(1024); HRESULT hrGet = pINIFile->GetLine(pszLine, 1024, &lNumBytesRead); sLine.ReleaseBuffer(); if (SUCCEEDED(hrGet) && (lNumBytesRead > 0)) { if ((sLine.Find(sPassword) == -1) && (sLine.Find(sDialUpPassword) == -1)) pNewFile->PutLine(sLine); sLine.Empty(); } } while (lNumBytesRead > 0); if (lNumBytesRead != -1) sEudoraIniV2 = EudoraFile; pINIFile->Close(); pNewFile->Close(); delete pNewFile; delete pINIFile; } void CCompMessageDoc::ReadSystemInfo(CString &sAttach, CString &sBody) { CString sEudoraIniV2; ReadEudoraInfo(sEudoraIniV2); // Attach Eudora_C.Ini if (!sEudoraIniV2.IsEmpty()) { if (sAttach.IsEmpty() == FALSE) { if (';' != sAttach[sAttach.GetLength() - 1]) sAttach += "; "; else if (' ' != sAttach[sAttach.GetLength() - 1]) sAttach += ' '; } sAttach += sEudoraIniV2 + ";"; } CString sPlatform; CString sVersion; CString sProcessor; CString sMachineType; CString sTotalPhys; CString sTotalVirtual; ReadPlatform(sPlatform, sVersion, sMachineType, sProcessor, sTotalPhys, sTotalVirtual); int i=0; CString sWinsock; if(QCWinSockLibMT::LoadWSLibrary()) { WORD wVersionRequested = MAKEWORD(1, 1); WSADATA wsaData; for (i = 0; i < sizeof(wsaData.szDescription); i++) wsaData.szDescription[i] = 0; if (QCWinSockLibMT::WSAStartup(wVersionRequested, &wsaData) == 0) { sWinsock = wsaData.szDescription; QCWinSockLibMT::WSACleanup(); } } sBody.Format(GetIniString(IDS_REGISTER_BODY2), (LPCTSTR)sPlatform, (LPCTSTR)sMachineType, (LPCTSTR)sVersion, (LPCTSTR)sProcessor, (LPCTSTR)sTotalPhys, (LPCTSTR)sTotalVirtual, (LPCTSTR)CRString(IDS_VERSION), GetIniString(IDS_INI_REG_NUMBER), (LPCTSTR)sWinsock); } void CCompMessageDoc::ReadPlatform(CString &sPlatform, CString &sVer, CString &sMachineType, CString &sProcessor, CString &sTotalPhys, CString &sTotalVirtual) { sVer.Format("%lu.%02lu.%04u", GetMajorVersion(), GetMinorVersion(), LOWORD(GetBuildNumber())); if (IsWinNT()) sPlatform.Format(GetIniString(IDS_REGISTER_WINNT), (LPCTSTR)sVer); else if (IsWin98()) sPlatform.Format(GetIniString(IDS_REGISTER_WIN98), (LPCTSTR)sVer); else if (IsWin95()) sPlatform.Format(GetIniString(IDS_REGISTER_WIN95), (LPCTSTR)sVer); else if (IsWin32s()) sPlatform.Format(GetIniString(IDS_REGISTER_WIN32S), (LPCTSTR)sVer); char stemp[20]={0}; SYSTEM_INFO sinf; GetSystemInfo(&sinf); switch(sinf.wProcessorArchitecture) { case PROCESSOR_ARCHITECTURE_INTEL: sMachineType = CRString(IDS_REGISTER_PROCESS_INTEL); switch(sinf.wProcessorLevel) { case 3: sProcessor = "80386"; break; case 4: sProcessor = "80486"; break; case 5: sProcessor = "Pentium"; break; case 6: sProcessor = "Pentium II"; break; default: sProcessor = CString(ultoa(sinf.dwProcessorType, stemp, 10)); } break; case PROCESSOR_ARCHITECTURE_MIPS: sMachineType = CRString(IDS_REGISTER_PROCESS_MIPS); sProcessor = CString(ultoa(sinf.dwProcessorType, stemp, 10)) + " " + CString(itoa(sinf.wProcessorLevel, stemp, 10)); break; case PROCESSOR_ARCHITECTURE_ALPHA: sMachineType = CRString(IDS_REGISTER_PROCESS_ALPHA); sProcessor = CString(ultoa(sinf.dwProcessorType, stemp, 10)) + " " + CString(itoa(sinf.wProcessorLevel, stemp, 10)); break; case PROCESSOR_ARCHITECTURE_PPC: sMachineType = CRString(IDS_REGISTER_PROCESS_PPC); switch(sinf.wProcessorLevel) { case 1: sProcessor = "601"; break; case 3: sProcessor = "603"; break; case 4: sProcessor = "604"; break; case 6: sProcessor = "603+"; break; case 9: sProcessor = "604+"; break; case 20: sProcessor = "620"; break; default: sProcessor = sMachineType; break; } break; default: sMachineType = CRString(IDS_REGISTER_PROCESS_UNKNOWN); sProcessor = sMachineType; } MEMORYSTATUS mst; mst.dwLength = sizeof(MEMORYSTATUS); GlobalMemoryStatus(&mst); sTotalPhys.Format("%lu Kb", (mst.dwTotalPhys / 1024L)); sTotalVirtual.Format("%lu Kb", (mst.dwTotalVirtual / 1024L)); } int QueueStatus = QS_NONE_QUEUED; // SetQueueStatus // // Sets the QueueStatus flag to it's correct state. // void SetQueueStatus() { CTocDoc* OutToc = GetOutToc(); unsigned long nextSendTime = 0; if (!OutToc) return; time_t Now = time(NULL); time_t Later = Now + 12 * 60L * 60L; // 12 hours from now POSITION pos = OutToc->m_Sums.GetHeadPosition(); QueueStatus = QS_NONE_QUEUED; while (pos) { CSummary* Sum = OutToc->m_Sums.GetNext(pos); if (Sum->IsQueued() && !Sum->m_FrameWnd) { time_t SumLocalSeconds = Sum->m_Seconds + Sum->m_TimeZoneMinutes * 60; if (Sum->m_State == MS_QUEUED || SumLocalSeconds <= Now) QueueStatus |= QS_READY_TO_BE_SENT; else if (SumLocalSeconds <= Later) QueueStatus |= QS_DELAYED_WITHIN_12; else QueueStatus |= QS_DELAYED_MORE_THAN_12; if (Sum->m_State == MS_TIME_QUEUED && Sum->GetDate()[0] != 0) { if (!nextSendTime || nextSendTime > (unsigned long)SumLocalSeconds) nextSendTime = SumLocalSeconds; } } } // Set time so mail will be sent when the time comes ((CEudoraApp *)AfxGetApp())->SetNextSendMail(nextSendTime); // Minimize icon may have to change to reflect queued message status ((CMainFrame*)AfxGetMainWnd())->SetIcon(); } /* SendQueuedResult SendOne(CSummary* Sum,SendQueuedResult InResult, CFilterActions *filt) { CTocDoc* OutToc = GetOutToc(); CCompMessageDoc* doc; QCMailboxCommand* pCommand; BOOL CreatedDoc = FALSE; if (Sum->m_FrameWnd) { doc = (CCompMessageDoc*)Sum->m_FrameWnd->GetActiveDocument(); if (doc->IsModified()) { switch (AlertDialog(IDD_SEND_CHANGED, Sum->MakeTitle())) { case IDC_DONT_SEND: return (InResult); case IDOK: if (doc->OnSaveDocument(NULL) == FALSE) return (InResult); break; case IDC_SEND_ORIGINAL: // Get old contents back doc->SetModifiedFlag(FALSE); if (((CMessageDoc*)doc)->Read() == FALSE) return (InResult); break; } } doc->Queue(TRUE); } //FORNOW doc = (CCompMessageDoc*)Sum->GetMessageDoc(); if (!(doc = (CCompMessageDoc *) Sum->FindMessageDoc())) { CreatedDoc = TRUE; doc = (CCompMessageDoc *) Sum->GetMessageDoc(); } if (!doc || !doc->GetText()) return (InResult); ASSERT_KINDOF(CCompMessageDoc, doc); // save the BCC line for processessing char *OldLine = (char *)::SafeStrdupMT(doc->GetHeaderLine(HEADER_BCC)); if (SendMessage(doc) == 1) { Sum->SetState(MS_SENT); SetIniShort(IDS_INI_SUCCESSFUL_SEND, 1); if (OutToc->GetView()) OutToc->GetView()->UpdateWindow(); //FCC Stuff if (OldLine) { int len = ::SafeStrlenMT(OldLine); CString sOldLine(OldLine); CString sMbox; BOOL endOfLine=FALSE; int ch=131; int beginPos=0; int endPos=0; BOOL bFound=FALSE; CString sTemp; CString sPath; CString sName; while (!endOfLine) { ch = 131; beginPos = sOldLine.Find(char(ch)); if (beginPos == -1) { endOfLine=TRUE; continue; } beginPos++; ch = sOldLine[beginPos]; beginPos++; sOldLine = sOldLine.Mid(beginPos); endPos = sOldLine.Find(','); if (endPos == -1) { endOfLine=TRUE; sMbox = sOldLine; } else { sMbox = sOldLine.Mid(0, endPos); } pCommand = g_theMailboxDirector.FindByNamedPath( sMbox ); if( pCommand != NULL ) { OutToc->Xfer( GetToc( pCommand->GetPathname(), pCommand->GetName(), FALSE, FALSE), Sum, FALSE, TRUE); } else { char sText[256]; sprintf(sText, CRString(IDS_FCC_LOST_MBOX), sMbox); AfxMessageBox(sText); } } delete [] OldLine; } if ( !(filt->FilterOne(Sum, WTA_OUTGOING) & FA_TRANSFER ) && !Sum->KeepCopies()) { OutToc->Xfer(GetTrashToc(), Sum, TRUE); } OutToc->SetModifiedFlag(); //FORNOW delete doc; if (CreatedDoc) { Sum->NukeMessageDocIfUnused(); doc = NULL; } } else { //FORNOW delete doc; if (CreatedDoc) { Sum->NukeMessageDocIfUnused(); doc = NULL; } // If there wasn't something wrong with the message, then there // was a problem with the network, so quit sending if (Sum->m_State != MS_UNSENDABLE) return (SQR_MAJOR_ERROR); // Otherwise, this message is amiss, so display it, and continue sending Sum->Display(); return (SQR_UNSENT_MESSAGE); } return (InResult); } */ BOOL FlushQueue = FALSE; //extern CPOP* gPOP; // SendQueuedMessages // // Send all messages that are currently queued. If any fail, bring the window // back so the user has a chance to edit the contents. // SendQueuedResult SendQueuedMessages(int WhichToSend /*= QS_READY_TO_BE_SENT*/, BOOL bMultiPersona /*= TRUE*/) { /* static SendQueuedResult Result; BOOL CreatedNetConnection = (NetConnection == NULL); time_t Now = time(NULL); time_t Later = Now + 12 * 60L * 60L; // 12 hours from now int NumToSend = 0; */ // Plugins want to know what that we're about to send ((CEudoraApp *)AfxGetApp())->GetTranslators()->IdleEveryone(0, EMIDLE_PRE_SEND); #ifdef THREADED if ( SUCCEEDED(SendQueuedMessages2(WhichToSend, bMultiPersona, TRUE))) return SQR_ALL_OK; else return SQR_MAJOR_ERROR; #endif } /* char Server[128]; POSITION pos; CSummary* Sum; Result = SQR_ALL_OK; // assume the best in case... // If no messages meet the sending criteria, then we're done // This wont let expired messages be sent i //if (QueueStatus < WhichToSend) // get out'a here if there aren't any queued messages if (QueueStatus <= QS_NONE_QUEUED) return (SQR_ALL_OK); CTocDoc* OutToc = GetOutToc(); if (!OutToc) return (Result); // Count how many messages to send for (pos = OutToc->m_Sums.GetHeadPosition(); pos; ) { Sum = OutToc->m_Sums.GetNext(pos); if (Sum->m_State == MS_QUEUED || (Sum->m_State == MS_TIME_QUEUED && (Sum->m_Seconds <= Now || Sum->m_Seconds <= Later && WhichToSend <= QS_DELAYED_WITHIN_12 || WhichToSend == QS_DELAYED_MORE_THAN_12))) { NumToSend++; } } if (!NumToSend) return (SQR_ALL_OK); CString homie = g_Personalities.GetCurrent(); LPSTR lpPersonalities = g_Personalities.List(); lpPersonalities += strlen( lpPersonalities ) + 1; //Skip <Dominant> CString Persona = ""; //Still always start with the Default personality do { if ( bMultiPersona ) g_Personalities.SetCurrent( Persona ); else Persona = homie; // send mail for the current persona if (!gPOP) { // If we haven't created the POP object yet, and we're sending via POP or we // have to validate the POP password, then check mail via the POP object methods if (GetIniShort(IDS_INI_USE_POP_SEND) || (GetIniShort(IDS_REQUIRE_POP_LOGIN_TO_SEND) && POPPassword.IsEmpty())) { GetMail(kCheckPassword | kNetworkBit | kPOPBit | kLogonBit | kSendMailBit); return (Result); } } else if (GetIniShort(IDS_REQUIRE_POP_LOGIN_TO_SEND) && POPPassword.IsEmpty()) { // If we did log on to the POP server, but the password failed and it's // required to send mail, then just get out of here return (SQR_MAJOR_ERROR); } GetIniString(IDS_INI_SMTP_SERVER, Server, sizeof(Server)); ::TrimWhitespaceMT(Server); char* s; if (!*Server && (s = strrchr(GetIniString(IDS_INI_POP_ACCOUNT), '@'))) strcpy(Server, s + 1); // If the server name is Hesiod, StartSMTP queries the Hesiod server for the // users POP server. The users SMTP Hesiod server is ignored at this time. CFilterActions filt; // are there any messages for this server? NumToSend = 0; for (pos = OutToc->m_Sums.GetHeadPosition(); pos; ) { Sum = OutToc->m_Sums.GetNext(pos); if ( Sum->GetPersona() == Persona ) { if (Sum->m_State == MS_QUEUED || (Sum->m_State == MS_TIME_QUEUED && (Sum->m_Seconds <= Now || Sum->m_Seconds <= Later && WhichToSend <= QS_DELAYED_WITHIN_12 || WhichToSend == QS_DELAYED_MORE_THAN_12))) { NumToSend++; } } } if (NumToSend) { if ( StartSMTP(Server) >= 0 && DoSMTPIntro() >= 0 && filt.StartFiltering() ) { CountdownProgress(CRString(IDS_SMTP_MESSAGES_LEFT), NumToSend); Result = SQR_ALL_OK; for (pos = OutToc->m_Sums.GetHeadPosition(); pos && NumToSend && Result != SQR_MAJOR_ERROR; ) { Sum = OutToc->m_Sums.GetNext(pos); if ( Sum->GetPersona() == Persona ) { if (Sum->m_State == MS_QUEUED || (Sum->m_State == MS_TIME_QUEUED && (Sum->m_Seconds <= Now || Sum->m_Seconds <= Later && WhichToSend <= QS_DELAYED_WITHIN_12 || WhichToSend == QS_DELAYED_MORE_THAN_12))) { CFilterActions *fptr = NULL; fptr = &filt; Result = SendOne(Sum, Result, fptr); NumToSend--; DecrementCountdownProgress(); } } } } FlushQueue = FALSE; EndSMTP(Result == SQR_MAJOR_ERROR); if (OutToc->IsModified()) OutToc->Write(); SetQueueStatus(); filt.EndFiltering(); } // advance to next personality Persona = lpPersonalities; lpPersonalities += strlen( lpPersonalities ) + 1; } while ( bMultiPersona && ! Persona.IsEmpty() ); g_Personalities.SetCurrent( homie ); if ( NetConnection ) { if (CreatedNetConnection && GetIniShort(IDS_INI_AUTO_CONNECTION)) { delete NetConnection; NetConnection = NULL; } else NetConnection->NukeCursor(); } if (OutToc->GetView()) OutToc->GetView()->m_SumListBox.SetRedraw(TRUE); if (CreatedNetConnection) CloseProgress(); return (Result); } */ IMPLEMENT_DYNCREATE(CCompStationeryDoc, CCompMessageDoc) CCompStationeryDoc::CCompStationeryDoc() { m_File = NULL; } CCompStationeryDoc::~CCompStationeryDoc() { delete m_Sum; delete m_File; } BOOL CCompStationeryDoc::Read(const char *Filename) { if (!::FileExistsMT(Filename)) return (FALSE); m_File = new JJFile(); if (NULL == m_File) return FALSE; if (FAILED(m_File->Open(Filename, O_RDONLY))) { delete m_File; m_File = NULL; return FALSE; } const unsigned int MaxLength = 62 * 1024L; m_Text = new char[MaxLength + 1]; m_BufSize = MaxLength; if (!m_Text) { m_BufSize = 0; return FALSE; } memset(m_Text,0,MaxLength); m_File->Read(m_Text, MaxLength); // get the Translation X-Header char *Trans = HeaderContents(IDS_TRANS_XHEADER, m_Text); // get the Signature X-Header char *cp; char *sigstr = HeaderContents(IDS_SIGNATURE_XHEADER, m_Text); if (sigstr) { cp = sigstr; if (*cp == '<' && *(cp + strlen(cp) - 1) == '>') { cp++; *(cp + strlen(cp) - 1) = '\0'; } } // get the Persona X-Header char *cpPersona; char *Persona = HeaderContents(IDS_PERSONA_XHEADER, m_Text); if (Persona) { char * cp = Persona; if (*cp == '<' && *(cp + strlen(cp) - 1) == '>') { cp++; *(cp + strlen(cp) - 1) = '\0'; } cpPersona = cp; } // Go through the message and parcel out each item char* t = m_Text; while (t && *t != '\r' && *t != '\n' && *t) { char* colon = strchr(t, ':'); if (!colon) { t = strchr(t, '\n'); if (t) t++; continue; } // Check if this is a header we use? int i = FindRStringIndexI(IDS_HEADER_TO, IDS_STATIONERY_TOC_HEADER, t, colon - t); // Get the value for the header if (!(t = strchr(colon, '\n'))) continue; if (t[-1] == '\r') t[-1] = 0; *t++ = '\0'; if (*++colon == ' ') colon++; // If found, fill in the value for display. Otherwise, // move onto the next header. if (i >= 0 && i < MaxHeaders && i != (IDS_HEADER_IN_REPLY_TO - IDS_HEADER_TO) && i != (IDS_HEADER_REFERENCES - IDS_HEADER_TO) ) { m_Headers[i] = colon; } else if (i == MaxHeaders) { m_Sum = new CSummary; WORD flgVal = WORD(atoi(colon)); m_Sum->SetFlag(flgVal); char *c = strchr(colon, ' '); if (c) { colon = c; short prior = short(atoi(colon)); m_Sum->m_Priority = prior; if (Trans) { m_Sum->SetTranslators(Trans, TRUE); delete Trans; } if (sigstr) { m_Sum->m_SigSelected = m_Sum->m_SigHdr = cp; delete [] sigstr; } if (Persona) { m_Sum->SetPersona( cpPersona ); delete Persona; } } } } #ifndef unix int hasLF = 1; #else int hasLF = 0; #endif // find the begining of the body which start with a \n // step over it so the body start at the first line if (t && (t = strchr(t + hasLF, '\n'))) strcpy(m_Text, t + 1); //Best place to stuff in the Pathname m_strPathName.Empty(); m_strPathName = Filename; m_HasBeenSaved = TRUE; return (TRUE); } CSummary* NewMessageFromFile(const char *fileName) { CTocDoc * OutToc = NULL; JJFile * in = NULL; JJFile * out = NULL; JJFile * tmp = NULL; CSummary * theSum = NULL; CRString MIMEVersionHeader( IDS_MIME_HEADER_VERSION ); CRString AttachHeader( IDS_HEADER_ATTACHMENTS ); CRString ToHeader( IDS_HEADER_TO ); CRString CCHeader( IDS_HEADER_CC ); CRString BCCHeader( IDS_HEADER_BCC ); CString AttachString; CString FromString; CTime Time(CTime::GetCurrentTime()); long lStartLoc; long lEndLoc; long lInSize; long lBodySize; char * t; BOOL bMimeEncoded = FALSE; const unsigned int BufLength = 62 * 1024L; char * pBuf = new char[ BufLength + 1 ]; if ( ! pBuf ) goto done; OutToc = GetOutToc(); if (!OutToc) goto done; in = new JJFile; if (!in) goto done; if (FAILED(in->Open(fileName, O_RDWR))) // does a O_BINARY open goto done; out = new JJFile; if (!out) goto done; if (FAILED(out->Open(OutToc->MBFilename(), O_APPEND | O_RDWR))) goto done; // Get the offset of the start of the message out->Tell(&lStartLoc); ASSERT(lStartLoc >= 0); // Write From line if (Time.GetTime() < 0) Time = 0; FromString = ::FormatTimeMT(Time.GetTime(), GetIniString(IDS_FROM_CTIME_FORMAT)); if (FAILED(out->PutLine(FromString))) goto done; // get in filesize in->Seek( 0L, SEEK_END ); in->Tell(&lInSize); ASSERT(lInSize >= 0); in->Seek( 0L, SEEK_SET ); // Write out headers pBuf[ BufLength ] = '\0'; if ( FAILED(in->Read( pBuf, BufLength )) ) goto done; t = pBuf; while (t && *t != '\r' && *t != '\n' && *t) { // Check if this is a MIME-Version header? char * end = strchr(t, '\n'); if ( end ) { if (end[-1] == '\r') // don't duplicate \r or \n end[-1] = '\0'; end[0] = '\0'; if ( strnicmp( t, MIMEVersionHeader, strlen( MIMEVersionHeader ) ) == 0 ) bMimeEncoded = TRUE; if ( strnicmp( t, AttachHeader, strlen( AttachHeader ) ) == 0 ) AttachString = t; else if( GetIniShort(IDS_INI_AUTO_EXPAND_NICKNAMES) && ( strnicmp( t, ToHeader, strlen( ToHeader ) ) == 0 || strnicmp( t, CCHeader, strlen( CCHeader ) ) == 0 || strnicmp( t, BCCHeader, strlen( BCCHeader ) ) == 0 ) ) { char* ExpandedText, *colon; if ( (colon = strstr(t, ": ")) == 0) goto done; if (*(colon + 2)) { ExpandedText = ExpandAliases(colon + 2, TRUE, FALSE, FALSE); if (ExpandedText) { if ( FAILED( out->Put( t, (colon + 2) - t ) ) ) goto done; if ( FAILED( out->PutLine( ExpandedText, strlen( ExpandedText ) ) ) ) goto done; delete [] ExpandedText; } else if ( FAILED( out->PutLine( t, strlen( t ) ) ) ) goto done; } else if ( FAILED( out->PutLine( t, strlen( t ) ) ) ) goto done; } else if ( FAILED( out->PutLine( t, strlen( t ) ) ) ) goto done; t = end + 1; } else ASSERT( FALSE ); // I expect to find new lines } lBodySize = lInSize - ( t - pBuf ); // handle body if ( bMimeEncoded ) { // if MIME-Version detected write the body to a temp file CString tmpname = ::GetTmpFileNameMT( "rr" ); tmp = new JJFile; if (!tmp) goto done; if (FAILED(tmp->Open(tmpname, O_CREAT | O_TRUNC | O_RDWR))) // does a O_BINARY open goto done; // save the body filename in X-Attachments char buf[ 512 ]; sprintf( buf, "%s %s;", (const char*)AttachHeader, (const char*)tmpname ); if ( FAILED( out->PutLine( buf, strlen( buf ) ) ) ) goto done; if ( FAILED( out->PutLine( "\r\n", 2 ) ) ) goto done; // delimit header // t now points to the header/body separator (blank-line) while ( lBodySize ) { long bytes = BufLength - ( t - pBuf ); if ( lBodySize < bytes ) bytes = lBodySize; if ( FAILED(tmp->Put( t, bytes )) ) goto done; lBodySize -= bytes; if ( lBodySize ) { t = pBuf; if ( FAILED(in->Read( pBuf, BufLength )) ) goto done; } } tmp->Flush(); tmp->Close(); } else { // use original messages X-Attachment specifier if ( ! AttachString.IsEmpty() ) if ( FAILED( out->PutLine( AttachString, AttachString.GetLength() ) ) ) goto done; // not MIME-encode so write body to the OutToc (not to exceed 62K) long bytes = BufLength - ( t - pBuf ); if ( lBodySize < bytes ) bytes = lBodySize; if( FAILED(out->Put( t, bytes )) ) goto done; } // Get the offset of the end of the message out->Tell(&lEndLoc); ASSERT(lEndLoc >= 0); out->Seek( lStartLoc ); // prepare for CSummary::Build() OutToc->Write(); // init the CSummary object theSum = new CSummary; theSum->m_TheToc = OutToc; CSummary::m_lBegin = lStartLoc; theSum->Build( out, TRUE ); theSum->SetState( MS_QUEUED ); if (GetIniShort(IDS_INI_KEEP_COPIES)) theSum->SetFlag( MSF_KEEP_COPIES ); if (bMimeEncoded) theSum->SetFlagEx( MSFEX_AUTO_ATTACHED ); // add the summary to the out mailbox OutToc->AddSum( theSum ); SetQueueStatus(); done: delete in; delete out; delete tmp; delete [] pBuf; return theSum; } void CCompMessageDoc::OnMessageDelete() { CSummary* Sum = m_Sum; CTocDoc* Toc = Sum->m_TheToc; // If we haven't done anything to this message, then just get rid of it if (!IsModified() && !m_HasBeenSaved) { OnCloseDocument(); Toc->RemoveSum(Sum); } else { if (Sum->CantEdit() == FALSE) { if (Sum->IsQueued() && GetIniShort(IDS_INI_WARN_DELETE_QUEUED) && WarnDialog(IDS_INI_WARN_DELETE_QUEUED, IDS_WARN_DELETE_QUEUED) != IDOK) { return; } else if ((Sum->IsSendable() || Sum->m_State == MS_UNSENDABLE) && GetIniShort(IDS_INI_WARN_DELETE_UNSENT) && WarnDialog(IDS_INI_WARN_DELETE_UNSENT, IDS_WARN_DELETE_UNSENT) != IDOK) { return; } } if ( (IsModified() == FALSE) || (SaveModified()) ) Toc->Xfer(GetTrashToc(), Sum); } } void CCompMessageDoc::OnSend() { if (m_Sum && m_Sum->CantEdit() == FALSE) { if (ShiftDown()) OnChangeQueueing(); else { Queue(); SetQueueStatus(); if (GetIniShort(IDS_INI_IMMEDIATE_SEND)) SendQueuedMessages(); } } } void CCompMessageDoc::OnCanModify(CCmdUI* pCmdUI) { if(m_Sum != NULL) pCmdUI->Enable(m_Sum->CantEdit() == FALSE); } void CCompMessageDoc::OnFileSave() { CMessageDoc::OnFileSave(); if (m_bIsStationery) { //MsgDoc initializes it to "A", so if it hasn't been //saved before call the SaveAs function if ( m_strPathName.Compare("A") == 0 ) { OnFileSaveAsStationery(); return; } JJFile theFile; if (FAILED(theFile.Open( m_strPathName, O_CREAT | O_TRUNC | O_WRONLY))) return; WriteAsText( &theFile, TRUE ); } } void CCompMessageDoc::OnFileSaveAs() { char szName[_MAX_PATH + 1]; CString szPathName; JJFile theFile; if( m_Sum == NULL ) { return; } strcpy( szName, m_Sum->m_Subject ); ::StripIllegalMT( szName, EudoraDir ); if( !::LongFileSupportMT( EudoraDir ) ) { szName[8] = 0; } CSaveAsDialog theDlg( szName, TRUE, //TRUE, FALSE, CRString( IDS_TEXT_EXTENSION ), CRString( IDS_TXT_HTML_FILE_FILTER ), NULL ); if ( theDlg.DoModal() != IDOK ) { return; } // // Hack alert! Under the 32-bit Version 4 shell, the OnOK() // method of dialog doesn't get called! Therefore, this is a // hack workaround to manually update these INI settings // outside of the dialog class. Whatta hack. // if (IsVersion4()) { SetIniShort(IDS_INI_INCLUDE_HEADERS, ( short ) theDlg.m_Inc ); SetIniShort(IDS_INI_GUESS_PARAGRAPHS, ( short ) theDlg.m_Guess); } szPathName = theDlg.GetPathName(); //bIsStationery = theDlg.m_IsStat; // determine whether or not this is stationery by the file extension //if ( !bIsStationery && // ( szPathName.Right( 3 ).CompareNoCase( CRString( IDS_STATIONERY_EXTENSION ) ) == 0 ) ) //{ // bIsStationery = TRUE; //} if (FAILED(theFile.Open( szPathName, O_CREAT | O_TRUNC | O_WRONLY))) return; //WriteAsText( &theFile, bIsStationery ); SaveAsFile(&theFile, szPathName); } BOOL CCompMessageDoc::SaveAsFile( JJFile *theFile, CString szPathName) { if ( !theFile || szPathName.IsEmpty() ) return (FALSE); CView* pView= GetCompView(); QCProtocol* view = QCProtocol::QueryProtocol( QCP_GET_MESSAGE, ( CObject* )pView ); if (!view) return (FALSE); CString msg; if ( (szPathName.Right( 3 ).CompareNoCase( CRString( IDS_HTM_EXTENSION) ) == 0 ) || (szPathName.Right( 4 ).CompareNoCase( CRString( IDS_HTML_EXTENSION) ) == 0 ) ) view->GetMessageAsHTML(msg, GetIniShort( IDS_INI_INCLUDE_HEADERS )); else { view->GetMessageAsText(msg, GetIniShort( IDS_INI_INCLUDE_HEADERS )); if ( GetIniShort( IDS_INI_GUESS_PARAGRAPHS ) ) { char* CopyText = ::SafeStrdupMT( msg ); if (FAILED(theFile->Put( UnwrapText( CopyText )))) { delete CopyText; return (FALSE); } else { delete CopyText; return (TRUE); } } } if ( FAILED( theFile->Put( msg ) ) ) { ASSERT( 0 ); return (FALSE); } return (TRUE); } void CCompMessageDoc::OnUpdateFileSaveAs(CCmdUI* pCmdUI) { pCmdUI->Enable(TRUE); } long CCompMessageDoc::DoContextMenu( CWnd* pCaller, WPARAM wParam, // HWND of window receiving WM_CONTEXTMENU message LPARAM lParam) // WM_CONTEXTMENU screen coordinates { CPoint ptScreen(LOWORD(lParam), HIWORD(lParam)); // Get the CMenu that contains all the context popups CMenu popupMenus; HMENU hMenu = QCLoadMenu(IDR_CONTEXT_POPUPS); if ( ! hMenu || !popupMenus.Attach(hMenu) ) return FALSE; CMenu* pTempPopupMenu = popupMenus.GetSubMenu(MP_POPUP_COMP_MSG); if (pTempPopupMenu != NULL) { // // Since the popup menu we get from GetSubMenu() is a pointer // to a temporary object, let's make a local copy of the // object so that we have explicit control over its lifetime. // // Note that we edit the context menu on-the-fly in order to // add a number of "user-defined" context menus, display the edited // context menu, then remove the added "user-defined" context menus. // // This all works because we add the sub-menus in a certain order, // and then remove them in exactly the reverse order. Be careful // if you make changes to the processing order here. // CMenu tempPopupMenu; tempPopupMenu.Attach(pTempPopupMenu->GetSafeHmenu()); // // Insert the Attach (plug-ins) sub-menu. // CMenu theAttachMenu; theAttachMenu.CreatePopupMenu(); g_thePluginDirector.NewMessageCommands( CA_ATTACH_PLUGIN, &theAttachMenu ); ::WrapMenu( theAttachMenu.GetSafeHmenu() ); tempPopupMenu.InsertMenu( MP_ATTACH_PLUGINS, MF_BYPOSITION | MF_POPUP, (UINT) theAttachMenu.GetSafeHmenu(), CRString(IDS_ATTACH_MENU_TEXT)); // // Insert the Insert Recipient sub-menu. // CMenu theRecipientMenu; theRecipientMenu.CreatePopupMenu(); g_theRecipientDirector.NewMessageCommands( CA_INSERT_RECIPIENT, &theRecipientMenu ); ::WrapMenu( theRecipientMenu.GetSafeHmenu() ); tempPopupMenu.InsertMenu( MP_INSERT_RECIP, MF_BYPOSITION | MF_POPUP, (UINT) theRecipientMenu.GetSafeHmenu(), CRString(IDS_INSERT_RECIPIENT)); CMenu theFCCMenu; // Shareware: Only allow FCC in FULL FEATURE version. if (UsingFullFeatureSet()) { // FULL FEATURE mode // // Insert the FCC sub-menu. This includes a fixed "New..." // mailbox command ID in the root of the FCC sub-menu, just // after the In/Out/Trash items. // theFCCMenu.CreatePopupMenu(); g_theMailboxDirector.NewMessageCommands( CA_INSERT_FCC, &theFCCMenu, CA_FCC_NEW ); theFCCMenu.InsertMenu( 3, MF_BYPOSITION, ID_FCC_NEW_MBOX_IN_ROOT, CRString( IDS_MAILBOX_NEW ) ); theFCCMenu.InsertMenu( 3, MF_BYPOSITION | MF_SEPARATOR ); ::WrapMenu( theFCCMenu.GetSafeHmenu() ); tempPopupMenu.InsertMenu( MP_INSERT_RECIP, MF_BYPOSITION | MF_POPUP, (UINT) theFCCMenu.GetSafeHmenu(), CRString( IDS_FCC ) ); } #ifdef COMMERCIAL // // Insert the Change Persona sub-menu // CMenu theChangePersonaMenu; theChangePersonaMenu.CreatePopupMenu(); g_thePersonalityDirector.NewMessageCommands( CA_CHANGE_PERSONA, &theChangePersonaMenu ); ::WrapMenu( theChangePersonaMenu.GetSafeHmenu() ); int nChangePersonaPosition = tempPopupMenu.GetMenuItemCount() - 1; tempPopupMenu.InsertMenu( nChangePersonaPosition, MF_BYPOSITION | MF_POPUP, (UINT) theChangePersonaMenu.GetSafeHmenu(), CRString( IDS_CHANGE_PERSONA ) ); #endif // COMMERCIAL // // Insert the Message Plug-Ins sub-menu. // CMenu theMessagePluginsMenu; theMessagePluginsMenu.CreatePopupMenu(); g_thePluginDirector.NewMessageCommands( CA_TRANSLATE_PLUGIN, &theMessagePluginsMenu ); int nMessagePluginsPosition = tempPopupMenu.GetMenuItemCount(); ::WrapMenu( theMessagePluginsMenu.GetSafeHmenu() ); tempPopupMenu.InsertMenu( nMessagePluginsPosition, MF_BYPOSITION | MF_POPUP, (UINT) theMessagePluginsMenu.GetSafeHmenu(), CRString(IDS_MESSAGE_PLUGINS)); CContextMenu::MatchCoordinatesToWindow(HWND(wParam), ptScreen); tempPopupMenu.TrackPopupMenu(0, ptScreen.x, ptScreen.y, AfxGetMainWnd()); // // Remove the Message Plug-Ins sub-menu. // g_thePluginDirector.RemoveMessageCommands( CA_TRANSLATE_PLUGIN, &theMessagePluginsMenu ); tempPopupMenu.RemoveMenu( nMessagePluginsPosition, MF_BYPOSITION ); #ifdef COMMERCIAL // // Remove the Change Persona sub-menu. // g_thePersonalityDirector.RemoveMessageCommands( CA_CHANGE_PERSONA, &theChangePersonaMenu ); tempPopupMenu.RemoveMenu( nChangePersonaPosition, MF_BYPOSITION); #endif // COMMERCIAL // Shareware: Only allow FCC in FULL FEATURE version. if (UsingFullFeatureSet()) { // FULL FEATURE mode // // Remove the FCC sub-menu. // g_theMailboxDirector.RemoveMessageCommands( CA_INSERT_FCC, &theFCCMenu ); g_theMailboxDirector.RemoveMessageCommands( CA_FCC_NEW, &theFCCMenu ); tempPopupMenu.RemoveMenu(MP_INSERT_RECIP, MF_BYPOSITION); } // // Remove the Insert Recipient sub-menu. // g_theRecipientDirector.RemoveMessageCommands( CA_INSERT_RECIPIENT, &theRecipientMenu ); tempPopupMenu.RemoveMenu(MP_INSERT_RECIP, MF_BYPOSITION); // // Remove the Attach (plug-ins) sub-menu. // g_thePluginDirector.RemoveMessageCommands(CA_ATTACH_PLUGIN, &theAttachMenu); tempPopupMenu.RemoveMenu(MP_ATTACH_PLUGINS, MF_BYPOSITION); VERIFY(tempPopupMenu.Detach()); } return TRUE; } void CCompMessageDoc::InsertFCCInBCC(QCMailboxCommand* pCommand) { // Shareware: Only allow FCC in FULL FEATURE version. if (UsingFullFeatureSet()) { // FULL FEATURE mode CString szNewBCC; char* pBCCString; if( pCommand == NULL ) { ASSERT( 0 ); return; } szNewBCC = g_theMailboxDirector.BuildNamedPath( pCommand ); szNewBCC = "\x83\\" + szNewBCC; pBCCString = ( char* ) GetHeaderLine(HEADER_BCC); if( ::SafeStrlenMT( pBCCString ) ) { szNewBCC = "," + szNewBCC; szNewBCC = pBCCString + szNewBCC; } SetHeaderLine( HEADER_BCC, szNewBCC ); SetModifiedFlag( TRUE ); } else { ASSERT(0); // No FCC in REDUCED FEATURE mode } } void CCompMessageDoc::OnFCCNewInRoot() { // Shareware: Only allow FCC in FULL FEATURE version. if (UsingFullFeatureSet()) { // FULL FEATURE mode QCMailboxCommand* pCommand = NULL; pCommand = g_theMailboxDirector.CreateTargetMailbox( NULL, FALSE ); if( pCommand ) { ASSERT_KINDOF( QCMailboxCommand, pCommand ); ASSERT( pCommand->GetType() == MBT_REGULAR ); InsertFCCInBCC( pCommand ); } } else { ASSERT(0); // FCC not allowed in REDUCED FEATURE mode } } //////////////////////////////////////////////////////////////////////// // OnDynamicCommand [protected] // // Handles commands specific to a comp message. Generic stuff like // the Transfer commands are handled in the base class CMessageDoc. //////////////////////////////////////////////////////////////////////// BOOL CCompMessageDoc::OnDynamicCommand(UINT uID) { QCCommandObject* pCommand; COMMAND_ACTION_TYPE theAction; CString szTo; struct TRANSLATE_DATA theData; if( ! g_theCommandStack.GetCommand( ( WORD ) uID, &pCommand, &theAction ) ) { return FALSE; } if( ( pCommand == NULL ) || !theAction ) { return FALSE; } if( theAction == CA_FCC_NEW ) { // Shareware: Only allow FCC in FULL FEATURE version. if (UsingFullFeatureSet()) { // FULL FEATURE mode ASSERT_KINDOF( QCMailboxCommand, pCommand ); pCommand = g_theMailboxDirector.CreateTargetMailbox( ( QCMailboxCommand* ) pCommand, FALSE ); if( pCommand ) { ASSERT_KINDOF( QCMailboxCommand, pCommand ); ASSERT( ( ( QCMailboxCommand* ) pCommand)->GetType() == MBT_REGULAR ); theAction = CA_INSERT_FCC; } else { return TRUE; } } else { // REDUCED FEATURE mode ASSERT(0); // Should not get here -- FCC disabled in REDUCED FEATURE mode return FALSE; } } if( theAction == CA_INSERT_FCC ) { // Shareware: Only allow FCC in FULL FEATURE version. if (UsingFullFeatureSet()) { // FULL FEATURE mode ASSERT_KINDOF( QCMailboxCommand, pCommand ); InsertFCCInBCC( ( QCMailboxCommand* ) pCommand ); return TRUE; } else { // REDUCED FEATURE mode ASSERT(0); // Should not get here -- FCC disabled in REDUCED FEATURE mode return FALSE; } } if( theAction == CA_ATTACH_PLUGIN ) { pCommand->Execute( theAction, this ); return TRUE; } if( theAction == CA_TRANSLATE_PLUGIN ) { if( ( theData.m_pView = GetView() ) != NULL ) { QCProtocol* pProtocol = QCProtocol::QueryProtocol( QCP_TRANSLATE, ( CObject* )theData.m_pView); if( pProtocol == NULL ) return FALSE; theData.m_pProtocol = pProtocol; theData.m_bBuildAddresses = TRUE; pCommand->Execute( theAction, &theData ); return TRUE; } } if ( theAction == CA_CHANGE_PERSONA ) { ASSERT_KINDOF( QCPersonalityCommand, pCommand ); if ( ApplyPersona( ((QCPersonalityCommand *) pCommand)->GetName() ) ) { SetModifiedFlag( TRUE ); } else { ASSERT(0); // bogus persona name } return TRUE; } if ( (theAction == CA_TRANSFER_NEW ) || (theAction == CA_TRANSFER_TO ) ) { // // Normally, the CMessageDoc base class handles the Transfer commands. // However, Transfer is not applicable to stationery, so bounce // those here. // if (m_bIsStationery) { ASSERT(0); // theoretically shouldn't get here due to CmdUI return TRUE; } } if ( theAction == CA_FORWARD_TO ) { VERIFY(m_Sum != NULL); pCommand->Execute( theAction, m_Sum ); return TRUE; } return CMessageDoc::OnDynamicCommand( uID ); } //////////////////////////////////////////////////////////////////////// // OnUpdateDynamicCommand [protected] // // Handles commands specific to a comp message. Generic stuff like // the Transfer commands are handled in the base class CMessageDoc. //////////////////////////////////////////////////////////////////////// void CCompMessageDoc::OnUpdateDynamicCommand( CCmdUI* pCmdUI) { QCCommandObject* pCommand; COMMAND_ACTION_TYPE theAction; if( pCmdUI->m_pSubMenu == NULL ) { if( g_theCommandStack.Lookup( ( WORD ) ( pCmdUI->m_nID ), &pCommand, &theAction ) ) { if( theAction == CA_CHANGE_PERSONA ) { QCPersonalityCommand* pPC = DYNAMIC_DOWNCAST(QCPersonalityCommand, pCommand); BOOL bPersonaMatch = FALSE; if (pPC && m_Sum) { LPCTSTR ThisPersona = m_Sum->GetPersona(); LPCTSTR CommandPersona = pPC->GetName(); if (stricmp(ThisPersona, CommandPersona) == 0 || (!*ThisPersona && stricmp(CommandPersona, CRString(IDS_DOMINANT)) == 0)) { bPersonaMatch = TRUE; } } pCmdUI->SetRadio( bPersonaMatch ); pCmdUI->Enable( TRUE ); return; } if( ( theAction == CA_FCC_NEW ) || ( theAction == CA_ATTACH_PLUGIN ) || ( ( theAction == CA_TRANSLATE_PLUGIN ) && ( GetView() != NULL ) ) || ( theAction == CA_INSERT_FCC ) || ( theAction == CA_FORWARD_TO ) ) { pCmdUI->Enable( TRUE ); return; } if ( ( theAction == CA_TRANSFER_NEW ) || ( theAction == CA_TRANSFER_TO ) ) { // // In the CMessageDoc base class, Transfer commands // are always enabled. Therefore, we need to override // that for stationery. // if ( m_bIsStationery ) { pCmdUI->Enable(FALSE); return; } } } } CMessageDoc::OnUpdateDynamicCommand(pCmdUI); } BOOL CCompMessageDoc::WriteAsText( JJFile* pFile, BOOL bIsStationery ) { char* szBody; if( m_Sum == NULL ) { return FALSE; } // GetText() makes sure message is read up and returns body szBody = GetText(); if( bIsStationery || GetIniShort( IDS_INI_INCLUDE_HEADERS ) ) { for (int i = 0; i < MaxHeaders; i++) { if (FAILED(pFile->Put(CRString(IDS_HEADER_TO + i))) || FAILED(pFile->Put(" ")) || FAILED(pFile->Put(GetHeaderLine(i))) || FAILED(pFile->Put("\r\n"))) { return FALSE; } } // add a header for toc stuff if( bIsStationery ) { CString tocFlags; tocFlags.Format(CRString(IDS_STATIONERY_TOC_HEADER_FORMAT),m_Sum->GetFlags(), m_Sum->m_Priority); pFile->Put(tocFlags); pFile->Put("\r\n"); // Put the Translator Header CString TransString; CString Tltrs = m_Sum->GetTranslators(); if (!Tltrs.IsEmpty()) { TransString.Format(CRString(IDS_TRANS_XHEADER_FORMAT),(const char *)Tltrs); pFile->Put(TransString); pFile->Put("\r\n"); } // Put the Signature Header CString SigString = m_Sum->m_SigSelected; if (!SigString.IsEmpty()) { SigString.Format(CRString(IDS_SIGNATURE_XHEADER_FORMAT),(const char *)( m_Sum->m_SigSelected ) ); pFile->Put(SigString); pFile->Put("\r\n"); m_Sum->m_SigHdr = m_Sum->m_SigSelected; } // Put the Persona Header CString PersonaString; CString Persona = m_Sum->GetPersona(); if (!Persona.IsEmpty()) { PersonaString.Format(CRString(IDS_PERSONA_XHEADER_FORMAT),(const char *)Persona); pFile->Put(PersonaString); pFile->Put("\r\n"); } } if( FAILED(pFile->Put("\r\n")) ) { return FALSE; } } if ( !bIsStationery && GetIniShort( IDS_INI_GUESS_PARAGRAPHS ) ) { char* CopyText = ::SafeStrdupMT( szBody ); BOOL Status = TRUE; if (FAILED(pFile->Put( UnwrapText( CopyText )))) Status = FALSE; delete CopyText; return Status; } //((PgMsgView*)GetView())->SaveInfo(); //szBody = CMessageDoc::GetText(); if ( FAILED(pFile->Put( szBody )) ) return FALSE; return TRUE; } void CCompMessageDoc::OnFileSaveAsStationery() { char szName[_MAX_PATH + 1]; CString szPathName; JJFile theFile; if( m_Sum == NULL ) { return; } strcpy( szName, m_Sum->m_Subject ); ::StripIllegalMT( szName, EudoraDir ); if( !::LongFileSupportMT( EudoraDir ) ) { szName[8] = 0; } CString statDir = EudoraDir; if (::LongFileSupportMT(EudoraDir)) statDir += CRString(IDS_STATIONERY_FOLDER); else statDir += CRString(IDS_STATIONERY_FOLDER16); CString defExt = CRString(IDS_STATIONERY_EXTENSION); CString dlgTitle = CRString(IDS_SAVE_AS_STATIONERY_TITLE); CFileDialog theDlg( FALSE, CRString(IDS_STATIONERY_EXTENSION), szName, OFN_HIDEREADONLY | OFN_NOREADONLYRETURN | OFN_OVERWRITEPROMPT | OFN_EXTENSIONDIFFERENT , CRString( IDS_STATIONERY_FILE_FILTER ), AfxGetMainWnd() ); theDlg.m_ofn.lpstrInitialDir = statDir; theDlg.m_ofn.lpstrDefExt = LPCTSTR(defExt); theDlg.m_ofn.lpstrTitle = LPCTSTR(dlgTitle); if (theDlg.DoModal() == IDOK) { szPathName = theDlg.GetPathName(); CString dir = szPathName; //CString fileTitle = theDlg.GetFileTitle(); //Append .sta even if the user entered a different extension //CString ext = theDlg.GetFileExt(); //if (ext.Compare(CRString(IDS_STATIONERY_EXTENSION)) != 0) //{ // fileTitle += "." + ext; // szPathName += ("." + CRString(IDS_STATIONERY_EXTENSION)); //} int s = szPathName.ReverseFind(SLASH); if (s > 0) dir = szPathName.Left( s ); if (dir.CompareNoCase(statDir) == 0 ) { if ( ! theDlg.GetFileExt().Compare(CRString(IDS_STATIONERY_EXTENSION)) ) { QCStationeryCommand* pCommand; pCommand = g_theStationeryDirector.AddCommand( theDlg.GetFileTitle() ); //if( pCommand ) // pCommand->Execute( CA_NEW ); } } if (FAILED(theFile.Open( szPathName, O_CREAT | O_TRUNC | O_WRONLY))) return; CMessageDoc::OnFileSave(); WriteAsText( &theFile, TRUE ); m_strPathName = theDlg.GetPathName(); SetTitle(m_strPathName); } } BOOL CCompMessageDoc::GetMessageHeaders(CString& hdrs) { //This is for PaigeStuff. //Will be changing it back to use \r\n instead of just \n, so that the //current WriteAsText function can use this piece of code hdrs.Empty(); for (int i = 0; i < MaxHeaders; i++) { hdrs += ( CRString(IDS_HEADER_TO + i) + " " + GetHeaderLine(i) + "\n" ); } // add extra header for the stationery stuff if( m_bIsStationery ) { //Put the Stationery Header CString tocFlags; tocFlags.Format(CRString(IDS_STATIONERY_TOC_HEADER_FORMAT),m_Sum->GetFlags(), m_Sum->m_Priority); hdrs += (tocFlags + "\n"); // Put the Translator Header CString TransString; CString Tltrs = m_Sum->GetTranslators(); if (!Tltrs.IsEmpty()) { TransString.Format(CRString(IDS_TRANS_XHEADER_FORMAT),(const char *)Tltrs); hdrs += ( TransString + "\n" ); } // Put the Signature Header CString SigString = m_Sum->m_SigSelected; if (!SigString.IsEmpty()) { SigString.Format(CRString(IDS_SIGNATURE_XHEADER_FORMAT),(const char *)( m_Sum->m_SigSelected ) ); hdrs += ( SigString + "\n" ); m_Sum->m_SigHdr = m_Sum->m_SigSelected; } // Put the Persona Header CString PersonaString; CString Persona = m_Sum->GetPersona(); if (!Persona.IsEmpty()) { PersonaString.Format(CRString(IDS_PERSONA_XHEADER_FORMAT),(const char *)Persona); hdrs += (PersonaString + "\n"); } } hdrs += "\n" ; return ( TRUE ); }
113,625
49,333
/* * Copyright (C) 2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ using namespace NEO; template <> bool HwInfoConfigHw<IGFX_XE_HP_SDV>::isMaxThreadsForWorkgroupWARequired(const HardwareInfo &hwInfo) const { const auto &hwInfoConfig = *HwInfoConfig::get(hwInfo.platform.eProductFamily); uint32_t stepping = hwInfoConfig.getSteppingFromHwRevId(hwInfo); return REVISION_B > stepping; } template <> uint32_t HwInfoConfigHw<IGFX_XE_HP_SDV>::getHwRevIdFromStepping(uint32_t stepping, const HardwareInfo &hwInfo) const { switch (stepping) { case REVISION_A0: return 0x0; case REVISION_A1: return 0x1; case REVISION_B: return 0x4; } return CommonConstants::invalidStepping; } template <> uint32_t HwInfoConfigHw<IGFX_XE_HP_SDV>::getSteppingFromHwRevId(const HardwareInfo &hwInfo) const { switch (hwInfo.platform.usRevId) { case 0x0: return REVISION_A0; case 0x1: return REVISION_A1; case 0x4: return REVISION_B; } return CommonConstants::invalidStepping; } template <> void HwInfoConfigHw<IGFX_XE_HP_SDV>::adjustSamplerState(void *sampler, const HardwareInfo &hwInfo) { using SAMPLER_STATE = typename XeHpFamily::SAMPLER_STATE; auto samplerState = reinterpret_cast<SAMPLER_STATE *>(sampler); if (DebugManager.flags.ForceSamplerLowFilteringPrecision.get()) { samplerState->setLowQualityFilter(SAMPLER_STATE::LOW_QUALITY_FILTER_ENABLE); } }
1,487
574
#include "grammar.h" #include "simCFG.h" Grammar grammar; Symbol start; // 初始化语法 void initGrammar() { Symbol next_symbol, non_terminal_new, non_terminal_old; Rule rule; while (cin >> next_symbol) { // for each symbol if (next_symbol == "->") { // 若为生成符号 // 上个读取的符号为非终结符 non_terminal_new = rule.back(); if (isTerminal(non_terminal_new)) { cout << "WARNING: INVALID GRAMMAR! terminal deriving symbols." << endl; } rule.pop_back(); if (!rule.empty()) { addRule(non_terminal_old, rule); } if (grammar.empty()) { // 若语法为空 start = non_terminal_new; // 当前非终结符为起始符号 cout << "Note: Start Symbol (" + start + ")" << endl; } non_terminal_old = non_terminal_new; // 更新非终结符 } else if (next_symbol == "|") { // 保持当前非终结符不变 // 将上条规则加入语法 if (!rule.empty()) addRule(non_terminal_old, rule); } else if (next_symbol == "null") { // 若为ε if (!rule.empty()) cout << "WARNING: symbols exist before a null production." << endl; rule.clear(); // 清空rule addRule(non_terminal_old, rule); // 将空规则加入语法 } else { // 若为其他符号 rule.push_back(next_symbol); } } if (!rule.empty()) { addRule(non_terminal_old, rule); } delDuplicatedRules(); } // 添加产生式 void addRule(Symbol nonterminal, Rule &rule) { grammar[nonterminal].push_back(rule); rule.clear(); } // 判断是否为终结符 bool isTerminal(Symbol symbol) { if (isupper(symbol[0])) // 若首字母为大写 return false; else return true; } // 获取符号类型 void getSymbolType(Symbols &nonterminals, Symbols &terminals, Symbols &deriving) { terminals.clear(); nonterminals.clear(); deriving.clear(); for (RuleSet &ruleset : grammar) { // this cannot be modified ruleset.first Symbol derivingsymbol = ruleset.first; // get the symbol on the RHS of rules deriving.insert(derivingsymbol); Rules &rules = ruleset.second; // get the set of rules derived by the deriving symbol if (isTerminal(derivingsymbol)) { // if deriving symbol is a terminal INVALID terminals.insert(derivingsymbol); cout << "WARNING: getterminals(): Deriving Symbol (" + derivingsymbol + ") is a terminal. " << endl; } else nonterminals.insert(derivingsymbol); // Add it as terminal for (Rule &rule : rules) for (Symbol symbol : rule) // for each rule if (isTerminal(symbol)) // check for terminals terminals.insert(symbol); else nonterminals.insert(symbol); } } // 打印语法 void printGrammar() { Symbols nonterminals, terminals, deriving; getSymbolType(nonterminals, terminals, deriving); // Print the description of grammar cout << "Start Symbol : " << start << endl; cout << "Terminals : "; printSymbols(terminals); cout << "Non-Terminals : "; printSymbols(nonterminals); cout << "Deriving Symbols : "; printSymbols(deriving); // usefull in debugging cout << "Rules : " << endl; int count = 1; // to display with rule number just to keep track of count // get maz size of deriving symbol .. int maxsize = 0; // for the formating for aesthetics for (RuleSet &ruleset : grammar) { Symbol derivingsymbol = ruleset.first; if (derivingsymbol.size() > maxsize) maxsize = derivingsymbol.size(); } for (RuleSet &ruleset : grammar) { Symbol derivingsymbol = ruleset.first; // get the symbol on the RHS of rules Rules &rules = ruleset.second; // get the set of rules derived by the deriving symbol if (rules.size() == 0) { // if no rule cout << "WARNING: Unneccessary deriving symbol (" << derivingsymbol << ")" << endl; } for (Rule &rule : rules) { cout << setw(4) << count << ". " << setw(maxsize); // print count printRule(derivingsymbol, rule); // print rule count++; // increment count } } } void printRule(Symbol nonterminal, Rule rule) { cout << nonterminal << " -> "; if (rule.empty()) // null production cout << "--null--"; for (Symbol symbol : rule) cout << " " << symbol << " "; cout << endl; } void printSymbols(Symbols symbols) { cout << "(" << symbols.size() << ")"; for (Symbol terminal : symbols) cout << " " << terminal << " "; cout << endl; }
5,140
1,615
#include "Camera.h" #define _USE_MATH_DEFINES #include <cmath> #include <Windows.h> using namespace DirectX; Camera::Camera() { } Camera::~Camera() { } void Camera::operator = (const Camera& camera) { memcpy(this, &camera, sizeof(Camera)); } bool Camera::operator ==(const Camera& camera) { return XMVector3Equal(m_position, camera.m_position) && XMVector3Equal(m_direction, camera.m_direction) && XMVector3Equal(m_up, camera.m_up) && m_fovRad == camera.m_fovRad; } void Camera::SnapUpToAxis() { static constexpr XMFLOAT3 xpos(1, 0, 0); static constexpr XMFLOAT3 xneg(-1, 0, 0); static constexpr XMFLOAT3 ypos(0, 1, 0); static constexpr XMFLOAT3 yneg(0, -1, 0); static constexpr XMFLOAT3 zpos(0,0, 1); static constexpr XMFLOAT3 zneg(0,0, -1); XMFLOAT3 up; DirectX::XMStoreFloat3(&up, m_up); if (fabs(up.x) > fabs(up.y) && fabs(up.x) > fabs(up.z)) m_up = XMLoadFloat3(up.x > 0 ? &xpos : &xneg); else if (fabs(up.y) > fabs(up.x) && fabs(up.y) > fabs(up.z)) m_up = XMLoadFloat3(up.y > 0 ? &ypos : &yneg); else if (fabs(up.z) > fabs(up.y) && fabs(up.z) > fabs(up.y)) m_up = XMLoadFloat3(up.z > 0 ? &zpos : &zneg); } void Camera::ComputeCameraParams(float aspectRatio, XMVECTOR& cameraU, XMVECTOR& cameraV, XMVECTOR& cameraW) const { cameraW = m_direction; cameraU = DirectX::XMVector3Normalize(DirectX::XMVector3Cross(cameraW, m_up)); cameraV = DirectX::XMVector3Normalize(DirectX::XMVector3Cross(cameraW, cameraU)); float f = (float)tan(m_fovRad * 0.5f); cameraU *= f; cameraV *= f; if (aspectRatio > 1.0f) cameraU *= aspectRatio; else cameraV /= aspectRatio; } static inline bool IsKeyDown(int keyCode) { return GetAsyncKeyState(keyCode) & 0x8000; } void ControllableCamera::Update(float secondsSinceLastUpdate) { POINT newMousePos; GetCursorPos(&newMousePos); unsigned char keyState[256]; GetKeyboardState(keyState); if (IsKeyDown(VK_RBUTTON)) { DirectX::XMFLOAT3 dir; XMStoreFloat3(&dir, m_direction); float rotY = -m_rotSpeed * (newMousePos.y - m_lastMousePosY); float rotX = -m_rotSpeed * (newMousePos.x - m_lastMousePosX); float scaledMoveSpeed = m_moveSpeed; if (IsKeyDown(VK_SHIFT)) scaledMoveSpeed *= m_moveSpeedSpeedupFactor; float forward = (IsKeyDown(VK_UP) || IsKeyDown('W')) ? 1.0f : 0.0f; float back = (IsKeyDown(VK_DOWN) || IsKeyDown('S')) ? 1.0f : 0.0f; float left = (IsKeyDown(VK_LEFT) || IsKeyDown('A')) ? 1.0f : 0.0f; float right = (IsKeyDown(VK_RIGHT) || IsKeyDown('D')) ? 1.0f : 0.0f; auto cameraLeft = XMVector3Cross(m_direction, m_up); auto rotateUpDown = XMQuaternionRotationAxis(cameraLeft, rotY); auto rotateLeftRight = XMQuaternionRotationAxis(m_up, rotX); //m_up = XMVector3Rotate(m_up, rotateUpDown); m_direction = XMVector3Rotate(m_direction, rotateUpDown); m_direction = XMVector3Rotate(m_direction, rotateLeftRight); m_position = m_position + ((forward - back) * m_direction + (right - left) * cameraLeft) * scaledMoveSpeed * secondsSinceLastUpdate; } m_lastMousePosX = newMousePos.x; m_lastMousePosY = newMousePos.y; }
3,311
1,340
#include <cstdio> #include <Imgui/imgui.h> #include "CUDA/CUDAContext.h" #include "Pathtracer/Pathtracer.h" #include "Input.h" #include "Window.h" #include "Util/Util.h" #include "Util/Random.h" #include "Util/PerfTest.h" #include "Util/ScopeTimer.h" extern "C" { _declspec(dllexport) unsigned NvOptimusEnablement = true; } // Forces NVIDIA driver to be used // Index of frame to take screen capture on static constexpr int capture_frame_index = -1; static constexpr bool exit_after_capture = true; static Window window; static Pathtracer pathtracer; static PerfTest perf_test; #define FRAMETIME_HISTORY_LENGTH 100 struct Timing { Uint64 now; Uint64 last; double inv_perf_freq; double delta_time; double second; int frames_this_second; int fps; double avg; double min; double max; double history[FRAMETIME_HISTORY_LENGTH]; int frame_index ; } static timing; static void capture_screen(const Window & window, const char * file_name) { ScopeTimer timer("Screenshot"); int pack_alignment; glGetIntegerv(GL_PACK_ALIGNMENT, &pack_alignment); int window_pitch = Math::divide_round_up(window.width * 3, pack_alignment) * pack_alignment; unsigned char * data = new unsigned char[window_pitch * window.height]; unsigned char * temp = new unsigned char[window_pitch]; window.read_frame_buffer(data); // Flip image vertically for (int j = 0; j < window.height / 2; j++) { unsigned char * row_top = data + j * window_pitch; unsigned char * row_bottom = data + (window.height - j - 1) * window_pitch; memcpy(temp, row_top, window_pitch); memcpy(row_top, row_bottom, window_pitch); memcpy(row_bottom, temp, window_pitch); } // Remove pack alignment for (int j = 1; j < window.height; j++) { memmove(data + j * window.width * 3, data + j * window_pitch, window.width * 3); } Util::export_ppm(file_name, window.width, window.height, data); delete [] temp; delete [] data; } static void window_resize(unsigned frame_buffer_handle, int width, int height) { pathtracer.resize_free(); pathtracer.resize_init(frame_buffer_handle, width, height); }; static void calc_timing(); static void draw_gui(); int main(int argument_count, char ** arguments) { const char * scene_filename = DATA_PATH("Sponza/scene.xml"); const char * sky_filename = DATA_PATH("Sky_Probes/sky_15.hdr"); if (argument_count > 1) { scene_filename = arguments[1]; } { ScopeTimer timer("Initialization"); window.init("Pathtracer"); window.resize_handler = &window_resize; CUDAContext::init(); pathtracer.init(scene_filename, sky_filename, window.frame_buffer_handle); perf_test.init(&pathtracer, false, scene_filename); Random::init(1337); } timing.inv_perf_freq = 1.0 / double(SDL_GetPerformanceFrequency()); timing.last = SDL_GetPerformanceCounter(); // Game loop while (!window.is_closed) { perf_test.frame_begin(); pathtracer.update((float)timing.delta_time); pathtracer.render(); window.render_framebuffer(); if (Input::is_key_pressed(SDL_SCANCODE_P) || timing.frame_index == capture_frame_index) { char screenshot_name[32]; sprintf_s(screenshot_name, "screenshot_%i.ppm", timing.frame_index); capture_screen(window, screenshot_name); if (timing.frame_index == capture_frame_index && exit_after_capture) break; } calc_timing(); draw_gui(); if (ImGui::IsMouseClicked(0) && !ImGui::GetIO().WantCaptureMouse) { int mouse_x, mouse_y; Input::mouse_position(&mouse_x, &mouse_y); pathtracer.set_pixel_query(mouse_x, mouse_y); } if (Input::is_key_released(SDL_SCANCODE_F5)) { ScopeTimer timer("Hot Reload"); pathtracer.cuda_free(); pathtracer.cuda_init(window.frame_buffer_handle, window.width, window.height); } if (perf_test.frame_end((float)timing.delta_time)) break; Input::update(); // Save Keyboard State of this frame before SDL_PumpEvents window.swap(); } CUDAContext::free(); window.free(); return EXIT_SUCCESS; } static void calc_timing() { // Calculate delta time timing.now = SDL_GetPerformanceCounter(); timing.delta_time = double(timing.now - timing.last) * timing.inv_perf_freq; timing.last = timing.now; // Calculate average of last frames timing.history[timing.frame_index++ % FRAMETIME_HISTORY_LENGTH] = timing.delta_time; int count = timing.frame_index < FRAMETIME_HISTORY_LENGTH ? timing.frame_index : FRAMETIME_HISTORY_LENGTH; timing.avg = 0.0; timing.min = INFINITY; timing.max = 0.0; for (int i = 0; i < count; i++) { timing.avg += timing.history[i]; timing.min = fmin(timing.min, timing.history[i]); timing.max = fmax(timing.max, timing.history[i]); } timing.avg /= double(count); // Calculate fps timing.frames_this_second++; timing.second += timing.delta_time; while (timing.second >= 1.0) { timing.second -= 1.0; timing.fps = timing.frames_this_second; timing.frames_this_second = 0; } } static void draw_gui() { window.gui_begin(); if (ImGui::Begin("Pathtracer")) { if (ImGui::CollapsingHeader("Performance", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::Text("Frame: %i - Index: %i", timing.frame_index, pathtracer.frames_accumulated); ImGui::Text("Delta: %.2f ms", 1000.0f * timing.delta_time); ImGui::Text("Avg: %.2f ms", 1000.0f * timing.avg); ImGui::Text("Min: %.2f ms", 1000.0f * timing.min); ImGui::Text("Max: %.2f ms", 1000.0f * timing.max); ImGui::Text("FPS: %i", timing.fps); ImGui::BeginChild("Performance Region", ImVec2(0, 150), true); struct EventTiming { CUDAEvent::Desc desc; float timing; }; int event_timing_count = pathtracer.event_pool.num_used - 1; EventTiming * event_timings = new EventTiming[event_timing_count]; for (int i = 0; i < event_timing_count; i++) { event_timings[i].desc = pathtracer.event_pool.pool[i].desc; event_timings[i].timing = CUDAEvent::time_elapsed_between( pathtracer.event_pool.pool[i], pathtracer.event_pool.pool[i + 1] ); } std::stable_sort(event_timings, event_timings + event_timing_count, [](const EventTiming & a, const EventTiming & b) { if (a.desc.display_order == b.desc.display_order) { return strcmp(a.desc.category, b.desc.category) < 0; } return a.desc.display_order < b.desc.display_order; }); bool category_changed = true; int padding; // Display Profile timings per category for (int i = 0; i < event_timing_count; i++) { if (category_changed) { padding = 0; // Sum the times of all events in the new Category so it can be displayed in the header float time_sum = 0.0f; int j; for (j = i; j < event_timing_count; j++) { int length = strlen(event_timings[j].desc.name); if (length > padding) padding = length; time_sum += event_timings[j].timing; if (j < event_timing_count - 1 && strcmp(event_timings[j].desc.category, event_timings[j + 1].desc.category) != 0) break; } bool category_visible = ImGui::TreeNode(event_timings[i].desc.category, "%s: %.2f ms", event_timings[i].desc.category, time_sum); if (!category_visible) { // Skip ahead to next category i = j; continue; } } // Add up all timings with the same name float timing = 0.0f; while (true) { timing += event_timings[i].timing; if (i == event_timing_count - 1 || strcmp(event_timings[i].desc.name, event_timings[i+1].desc.name) != 0) break; i++; }; ImGui::Text("%s: %*.2f ms", event_timings[i].desc.name, 5 + padding - strlen(event_timings[i].desc.name), timing); if (i == event_timing_count - 1) { ImGui::TreePop(); break; } category_changed = strcmp(event_timings[i].desc.category, event_timings[i + 1].desc.category); if (category_changed) { ImGui::TreePop(); } } ImGui::EndChild(); delete [] event_timings; } if (ImGui::CollapsingHeader("Settings", ImGuiTreeNodeFlags_DefaultOpen)) { bool invalidated_settings = false; invalidated_settings |= ImGui::SliderInt("Num Bounces", &pathtracer.settings.num_bounces, 0, MAX_BOUNCES); float fov = Math::rad_to_deg(pathtracer.scene.camera.fov); if (ImGui::SliderFloat("FOV", &fov, 0.0f, 179.0f)) { pathtracer.scene.camera.set_fov(Math::deg_to_rad(fov)); pathtracer.invalidated_camera = true; } pathtracer.invalidated_camera |= ImGui::SliderFloat("Aperture", &pathtracer.scene.camera.aperture_radius, 0.0f, 1.0f); pathtracer.invalidated_camera |= ImGui::SliderFloat("Focus", &pathtracer.scene.camera.focal_distance, 0.001f, 50.0f); invalidated_settings |= ImGui::Checkbox("NEE", &pathtracer.settings.enable_next_event_estimation); invalidated_settings |= ImGui::Checkbox("MIS", &pathtracer.settings.enable_multiple_importance_sampling); invalidated_settings |= ImGui::Checkbox("Update Scene", &pathtracer.settings.enable_scene_update); if (ImGui::Checkbox("SVGF", &pathtracer.settings.enable_svgf)) { if (pathtracer.settings.enable_svgf) { pathtracer.svgf_init(); } else { pathtracer.svgf_free(); } invalidated_settings = true; } invalidated_settings |= ImGui::Checkbox("Spatial Variance", &pathtracer.settings.enable_spatial_variance); invalidated_settings |= ImGui::Checkbox("TAA", &pathtracer.settings.enable_taa); invalidated_settings |= ImGui::Checkbox("Modulate Albedo", &pathtracer.settings.modulate_albedo); invalidated_settings |= ImGui::Combo("Reconstruction Filter", reinterpret_cast<int *>(&pathtracer.settings.reconstruction_filter), "Box\0Gaussian\0"); invalidated_settings |= ImGui::SliderInt("A Trous iterations", &pathtracer.settings.atrous_iterations, 0, MAX_ATROUS_ITERATIONS); invalidated_settings |= ImGui::SliderFloat("Alpha colour", &pathtracer.settings.alpha_colour, 0.0f, 1.0f); invalidated_settings |= ImGui::SliderFloat("Alpha moment", &pathtracer.settings.alpha_moment, 0.0f, 1.0f); pathtracer.invalidated_settings = invalidated_settings; } } ImGui::End(); if (ImGui::Begin("Scene")) { if (ImGui::CollapsingHeader("Properties", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::Text("Has Diffuse: %s", pathtracer.scene.has_diffuse ? "True" : "False"); ImGui::Text("Has Dielectric: %s", pathtracer.scene.has_dielectric ? "True" : "False"); ImGui::Text("Has Glossy: %s", pathtracer.scene.has_glossy ? "True" : "False"); ImGui::Text("Has Lights: %s", pathtracer.scene.has_lights ? "True" : "False"); } if (ImGui::IsMouseClicked(1)) { // Deselect current object pathtracer.pixel_query.pixel_index = INVALID; pathtracer.pixel_query.mesh_id = INVALID; pathtracer.pixel_query.triangle_id = INVALID; pathtracer.pixel_query.material_id = INVALID; } if (ImGui::CollapsingHeader("Meshes", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::BeginChild("Meshes", ImVec2(0, 200), true); for (int m = 0; m < pathtracer.scene.meshes.size(); m++) { const Mesh & mesh = pathtracer.scene.meshes[m]; bool is_selected = pathtracer.pixel_query.mesh_id == m; ImGui::PushID(m); if (ImGui::Selectable(mesh.name, &is_selected)) { pathtracer.pixel_query.mesh_id = m; pathtracer.pixel_query.triangle_id = INVALID; pathtracer.pixel_query.material_id = mesh.material_handle.handle; } ImGui::PopID(); } ImGui::EndChild(); } if (pathtracer.pixel_query.mesh_id != INVALID) { Mesh & mesh = pathtracer.scene.meshes[pathtracer.pixel_query.mesh_id]; if (ImGui::CollapsingHeader("Mesh", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::TextUnformatted(mesh.name); bool mesh_changed = false; mesh_changed |= ImGui::DragFloat3("Position", &mesh.position.x); static bool dragging = false; if (ImGui::DragFloat3("Rotation", &mesh.euler_angles.x)) { mesh.euler_angles.x = Math::wrap(mesh.euler_angles.x, 0.0f, 360.0f); mesh.euler_angles.y = Math::wrap(mesh.euler_angles.y, 0.0f, 360.0f); mesh.euler_angles.z = Math::wrap(mesh.euler_angles.z, 0.0f, 360.0f); if (!dragging) { mesh.euler_angles = Quaternion::to_euler(mesh.rotation); mesh.euler_angles.x = Math::rad_to_deg(mesh.euler_angles.x); mesh.euler_angles.y = Math::rad_to_deg(mesh.euler_angles.y); mesh.euler_angles.z = Math::rad_to_deg(mesh.euler_angles.z); dragging = true; } mesh.rotation = Quaternion::from_euler(Math::deg_to_rad(mesh.euler_angles.x), Math::deg_to_rad(mesh.euler_angles.y), Math::deg_to_rad(mesh.euler_angles.z)); mesh_changed = true; } mesh_changed |= ImGui::DragFloat("Scale", &mesh.scale, 0.1f, 0.0f, INFINITY); if (mesh_changed) pathtracer.invalidated_scene = true; } ImDrawList * draw_list = ImGui::GetBackgroundDrawList(); Vector4 aabb_corners[8] = { Vector4(mesh.aabb.min.x, mesh.aabb.min.y, mesh.aabb.min.z, 1.0f), Vector4(mesh.aabb.max.x, mesh.aabb.min.y, mesh.aabb.min.z, 1.0f), Vector4(mesh.aabb.max.x, mesh.aabb.min.y, mesh.aabb.max.z, 1.0f), Vector4(mesh.aabb.min.x, mesh.aabb.min.y, mesh.aabb.max.z, 1.0f), Vector4(mesh.aabb.min.x, mesh.aabb.max.y, mesh.aabb.min.z, 1.0f), Vector4(mesh.aabb.max.x, mesh.aabb.max.y, mesh.aabb.min.z, 1.0f), Vector4(mesh.aabb.max.x, mesh.aabb.max.y, mesh.aabb.max.z, 1.0f), Vector4(mesh.aabb.min.x, mesh.aabb.max.y, mesh.aabb.max.z, 1.0f) }; // Transform from world space to homogeneous clip space for (int i = 0; i < 8; i++) { aabb_corners[i] = Matrix4::transform(pathtracer.scene.camera.view_projection, aabb_corners[i]); } auto draw_line_clipped = [draw_list](Vector4 a, Vector4 b, ImColor colour, float thickness = 1.0f) { if (a.z < pathtracer.scene.camera.near && b.z < pathtracer.scene.camera.near) return; // Clip against near plane only if (a.z < pathtracer.scene.camera.near) a = Math::lerp(a, b, Math::inv_lerp(pathtracer.scene.camera.near, a.z, b.z)); if (b.z < pathtracer.scene.camera.near) b = Math::lerp(a, b, Math::inv_lerp(pathtracer.scene.camera.near, a.z, b.z)); // Clip space to NDC to Window coordinates ImVec2 a_window = { (0.5f + 0.5f * a.x / a.w) * window.width, (0.5f - 0.5f * a.y / a.w) * window.height }; ImVec2 b_window = { (0.5f + 0.5f * b.x / b.w) * window.width, (0.5f - 0.5f * b.y / b.w) * window.height }; draw_list->AddLine(a_window, b_window, colour, thickness); }; ImColor aabb_colour = ImColor(0.2f, 0.8f, 0.2f); draw_line_clipped(aabb_corners[0], aabb_corners[1], aabb_colour); draw_line_clipped(aabb_corners[1], aabb_corners[2], aabb_colour); draw_line_clipped(aabb_corners[2], aabb_corners[3], aabb_colour); draw_line_clipped(aabb_corners[3], aabb_corners[0], aabb_colour); draw_line_clipped(aabb_corners[4], aabb_corners[5], aabb_colour); draw_line_clipped(aabb_corners[5], aabb_corners[6], aabb_colour); draw_line_clipped(aabb_corners[6], aabb_corners[7], aabb_colour); draw_line_clipped(aabb_corners[7], aabb_corners[4], aabb_colour); draw_line_clipped(aabb_corners[0], aabb_corners[4], aabb_colour); draw_line_clipped(aabb_corners[1], aabb_corners[5], aabb_colour); draw_line_clipped(aabb_corners[2], aabb_corners[6], aabb_colour); draw_line_clipped(aabb_corners[3], aabb_corners[7], aabb_colour); if (pathtracer.pixel_query.triangle_id != INVALID) { const MeshData & mesh_data = pathtracer.scene.asset_manager.get_mesh_data(mesh.mesh_data_handle); int index = mesh_data.bvh.indices[pathtracer.pixel_query.triangle_id - pathtracer.mesh_data_triangle_offsets[mesh.mesh_data_handle.handle]]; const Triangle & triangle = mesh_data.triangles[index]; ImGui::Text("Distance: %f", Vector3::length(triangle.get_center() - pathtracer.scene.camera.position)); Vector4 triangle_positions[3] = { Vector4(triangle.position_0.x, triangle.position_0.y, triangle.position_0.z, 1.0f), Vector4(triangle.position_1.x, triangle.position_1.y, triangle.position_1.z, 1.0f), Vector4(triangle.position_2.x, triangle.position_2.y, triangle.position_2.z, 1.0f) }; Vector4 triangle_normals[3] = { Vector4(triangle.normal_0.x, triangle.normal_0.y, triangle.normal_0.z, 0.0f), Vector4(triangle.normal_1.x, triangle.normal_1.y, triangle.normal_1.z, 0.0f), Vector4(triangle.normal_2.x, triangle.normal_2.y, triangle.normal_2.z, 0.0f) }; for (int i = 0; i < 3; i++) { triangle_positions[i] = Matrix4::transform(pathtracer.scene.camera.view_projection * mesh.transform, triangle_positions[i]); triangle_normals [i] = Matrix4::transform(pathtracer.scene.camera.view_projection * mesh.transform, triangle_normals [i]); } ImColor triangle_colour = ImColor(0.8f, 0.2f, 0.8f); draw_line_clipped(triangle_positions[0], triangle_positions[1], triangle_colour); draw_line_clipped(triangle_positions[1], triangle_positions[2], triangle_colour); draw_line_clipped(triangle_positions[2], triangle_positions[0], triangle_colour); ImColor normal_colour = ImColor(0.2f, 0.5f, 0.8f); draw_line_clipped(triangle_positions[0], triangle_positions[0] + 0.1f * triangle_normals[0], normal_colour); draw_line_clipped(triangle_positions[1], triangle_positions[1] + 0.1f * triangle_normals[1], normal_colour); draw_line_clipped(triangle_positions[2], triangle_positions[2] + 0.1f * triangle_normals[2], normal_colour); } } if (pathtracer.pixel_query.material_id != INVALID) { Material & material = pathtracer.scene.asset_manager.get_material(MaterialHandle { pathtracer.pixel_query.material_id }); if (ImGui::CollapsingHeader("Material", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::Text("Name: %s", material.name); bool material_changed = false; int material_type = int(material.type); if (ImGui::Combo("Type", &material_type, "Light\0Diffuse\0Dielectric\0Glossy\0")) { material.type = Material::Type(material_type); material_changed = true; } switch (material.type) { case Material::Type::LIGHT: { material_changed |= ImGui::DragFloat3("Emission", &material.emission.x, 0.1f, 0.0f, INFINITY); break; } case Material::Type::DIFFUSE: { material_changed |= ImGui::SliderFloat3("Diffuse", &material.diffuse.x, 0.0f, 1.0f); material_changed |= ImGui::SliderInt ("Texture", &material.texture_id.handle, -1, pathtracer.scene.asset_manager.textures.size() - 1); break; } case Material::Type::DIELECTRIC: { material_changed |= ImGui::SliderFloat3("Transmittance", &material.transmittance.x, 0.0f, 1.0f); material_changed |= ImGui::SliderFloat ("IOR", &material.index_of_refraction, 1.0f, 5.0f); break; } case Material::Type::GLOSSY: { material_changed |= ImGui::SliderFloat3("Diffuse", &material.diffuse.x, 0.0f, 1.0f); material_changed |= ImGui::SliderInt ("Texture", &material.texture_id.handle, -1, pathtracer.scene.asset_manager.textures.size() - 1); material_changed |= ImGui::SliderFloat ("IOR", &material.index_of_refraction, 1.0f, 5.0f); material_changed |= ImGui::SliderFloat ("Roughness", &material.linear_roughness, 0.0f, 1.0f); break; } default: abort(); } if (material_changed) pathtracer.invalidated_materials = true; } } } ImGui::End(); window.gui_end(); }
19,399
8,500
#pragma once #include "gmLogicCvBase.hpp" namespace gm { namespace Logic { namespace Cv { class Sum : public Base { public: struct ID { static constexpr auto input = "input"; static constexpr auto output = "sum"; }; static Register<Sum> Register; using Access = Enable::ImageTypes < Enable::Dimension<2>, Enable::Scalar<unsigned char, unsigned short, char, short, float, double>, Enable::Rgb<unsigned char, unsigned short, char, short> >; Sum() : Base("Sum") { this->add(new Slot::Input<Data::Image>(ID::input, Access::MakeConstraints(), Data::Required)); this->add(new Slot::Output<Data::Vector>(ID::output)); } auto run() -> void override { auto output = this->getOutput<Data::Vector>(ID::output); for (auto it : this->inputIterator()) { auto out = cv::sum(Image::ToCv(it.image())); output->addVector(new Data::Vector(out[0], out[1], out[2], out[3])); } } }; } } }
1,418
354
#include "gtest_color.h" namespace { class ColorHdrTest : public ::testing::Test { public: ColorHdrTest() : col1_(5.0f, 5.0f, 5.0f), col2_(2.5f, 3.3f, 2.5f) {} nc::ColorHdr col1_; nc::ColorHdr col2_; }; const float red = 0.25f; const float green = 0.5f; const float blue = 0.75f; TEST_F(ColorHdrTest, DefaultConstructor) { const nc::ColorHdr color; printColor("Constructing a new color with the default white constructor: ", color); ASSERT_FLOAT_EQ(color.data()[0], 1.0f); ASSERT_FLOAT_EQ(color.data()[1], 1.0f); ASSERT_FLOAT_EQ(color.data()[2], 1.0f); } TEST_F(ColorHdrTest, ConstructFromThreeComponents) { const nc::ColorHdr color(red, green, blue); printColor("Constructing a new color from three components: ", color); ASSERT_FLOAT_EQ(color.data()[0], red); ASSERT_FLOAT_EQ(color.data()[1], green); ASSERT_FLOAT_EQ(color.data()[2], blue); } TEST_F(ColorHdrTest, ConstructFromArray) { const float vec[nc::ColorHdr::NumChannels] = { red, green, blue }; const nc::ColorHdr color(vec); printColor("Constructing a new color from an array: ", color); ASSERT_FLOAT_EQ(color.data()[0], vec[0]); ASSERT_FLOAT_EQ(color.data()[1], vec[1]); ASSERT_FLOAT_EQ(color.data()[2], vec[2]); } TEST_F(ColorHdrTest, ConstructFromClampedFloatColor) { nc::ColorHdr color(nc::Colorf::Black); printColor("Constructing a new color from a float one: ", color); ASSERT_FLOAT_EQ(color.r(), 0.0f); ASSERT_FLOAT_EQ(color.g(), 0.0f); ASSERT_FLOAT_EQ(color.b(), 0.0f); } TEST_F(ColorHdrTest, Getters) { const nc::ColorHdr color(red, green, blue); printColor("Constructing a new color and testing its getters: ", color); ASSERT_FLOAT_EQ(color.r(), red); ASSERT_FLOAT_EQ(color.g(), green); ASSERT_FLOAT_EQ(color.b(), blue); } TEST_F(ColorHdrTest, SetThreeComponents) { nc::ColorHdr color; color.set(red, green, blue); printColor("Constructing a new color and setting three components: ", color); ASSERT_FLOAT_EQ(color.r(), red); ASSERT_FLOAT_EQ(color.g(), green); ASSERT_FLOAT_EQ(color.b(), blue); } TEST_F(ColorHdrTest, SetArray) { const float vec[nc::ColorHdr::NumChannels] = { red, green, blue }; nc::ColorHdr color; color.setVec(vec); printColor("Constructing a new color and setting components from an array: ", color); ASSERT_FLOAT_EQ(color.data()[0], vec[0]); ASSERT_FLOAT_EQ(color.data()[1], vec[1]); ASSERT_FLOAT_EQ(color.data()[2], vec[2]); } TEST_F(ColorHdrTest, Clamp) { nc::ColorHdr color(-1.0f, -1.0f, -1.0f); color.clamp(); printColor("Constructing a new color and clamping its channels: ", color); ASSERT_FLOAT_EQ(color.r(), 0.0f); ASSERT_FLOAT_EQ(color.g(), 0.0f); ASSERT_FLOAT_EQ(color.b(), 0.0f); } TEST_F(ColorHdrTest, Clamped) { nc::ColorHdr color(-1.0f, -1.0f, -1.0f); const nc::ColorHdr newColor = color.clamped(); printColor("Constructing a new color by clamping another one: ", newColor); ASSERT_FLOAT_EQ(newColor.r(), 0.0f); ASSERT_FLOAT_EQ(newColor.g(), 0.0f); ASSERT_FLOAT_EQ(newColor.b(), 0.0f); } TEST_F(ColorHdrTest, AssignNonFloatColor) { nc::ColorHdr color; color = nc::Colorf::Black; printColor("Assigning a new color from a float one: ", color); ASSERT_FLOAT_EQ(color.r(), 0.0f); ASSERT_FLOAT_EQ(color.g(), 0.0f); ASSERT_FLOAT_EQ(color.b(), 0.0f); } TEST_F(ColorHdrTest, EqualityOperatorAfterConversion) { const nc::Color color1 = nc::Color(nc::Colorf(nc::ColorHdr::Red)); const nc::Color color2 = nc::Color(nc::Colorf(nc::ColorHdr::Red)); ASSERT(color1 == color2); } TEST_F(ColorHdrTest, AdditionInPlace) { const nc::ColorHdr oldCol1 = col1_; printColor("color1: ", col1_); printColor("color2: ", col2_); printColor("Adding the second color to the first: ", col1_ += col2_); ASSERT_EQ(col1_.r(), oldCol1.r() + col2_.r()); ASSERT_EQ(col1_.g(), oldCol1.g() + col2_.g()); ASSERT_EQ(col1_.b(), oldCol1.b() + col2_.b()); } TEST_F(ColorHdrTest, SubtractionInPlace) { const nc::ColorHdr oldCol1 = col1_; printColor("color1: ", col1_); printColor("color2: ", col2_); printColor("Subtracting the second color from the first: ", col1_ -= col2_); ASSERT_EQ(col1_.r(), oldCol1.r() - col2_.r()); ASSERT_EQ(col1_.g(), oldCol1.g() - col2_.g()); ASSERT_EQ(col1_.b(), oldCol1.b() - col2_.b()); } TEST_F(ColorHdrTest, MultiplicationInPlace) { const nc::ColorHdr oldCol1 = col1_; printColor("color1: ", col1_); printColor("color2: ", col2_); printColor("Multiplying the first color by the second: ", col1_ *= col2_); ASSERT_FLOAT_EQ(col1_.r(), oldCol1.r() * col2_.r()); ASSERT_FLOAT_EQ(col1_.g(), oldCol1.g() * col2_.g()); ASSERT_FLOAT_EQ(col1_.b(), oldCol1.b() * col2_.b()); } TEST_F(ColorHdrTest, MultiplyScalarInPlace) { const float scalar = 0.5f; const nc::ColorHdr oldCol1 = col1_; printColor("color1: ", col1_); printf("Multiplying the first color by the scalar %.2f: ", scalar); printColor(col1_ *= scalar); ASSERT_FLOAT_EQ(col1_.r(), oldCol1.r() * scalar); ASSERT_FLOAT_EQ(col1_.g(), oldCol1.g() * scalar); ASSERT_FLOAT_EQ(col1_.b(), oldCol1.b() * scalar); } TEST_F(ColorHdrTest, Addition) { printColor("color1: ", col1_); printColor("color2: ", col2_); const nc::ColorHdr add = col1_ + col2_; printColor("Color addition: ", add); ASSERT_EQ(add.r(), col1_.r() + col2_.r()); ASSERT_EQ(add.g(), col1_.g() + col2_.g()); ASSERT_EQ(add.b(), col1_.b() + col2_.b()); } TEST_F(ColorHdrTest, Subtraction) { printColor("color1: ", col1_); printColor("color2: ", col2_); const nc::ColorHdr sub = col1_ - col2_; printColor("Color subtraction: ", sub); ASSERT_EQ(sub.r(), col1_.r() - col2_.r()); ASSERT_EQ(sub.g(), col1_.g() - col2_.g()); ASSERT_EQ(sub.b(), col1_.b() - col2_.b()); } TEST_F(ColorHdrTest, Multiplication) { printColor("color1: ", col1_); printColor("color2: ", col2_); const nc::ColorHdr mul = col1_ * col2_; printColor("Color multiplication: ", mul); ASSERT_FLOAT_EQ(mul.r(), col1_.r() * col2_.r()); ASSERT_FLOAT_EQ(mul.g(), col1_.g() * col2_.g()); ASSERT_FLOAT_EQ(mul.b(), col1_.b() * col2_.b()); } TEST_F(ColorHdrTest, MultiplyScalar) { const float scalar = 0.5f; printColor("color1: ", col1_); const nc::ColorHdr mul = col1_ * scalar; printf("Multiplication by scalar %.2f: ", scalar); printColor(mul); ASSERT_FLOAT_EQ(mul.r(), col1_.r() * scalar); ASSERT_FLOAT_EQ(mul.g(), col1_.g() * scalar); ASSERT_FLOAT_EQ(mul.b(), col1_.b() * scalar); } }
6,320
2,782
#include"datarecorder.h" #if _MSC_VER >= 1600 #pragma execution_character_set("utf-8") #endif Datarecorder::Datarecorder(EventEngine *eventengine) :connectStatus(false) { my_logger = spdlog::rotating_logger_mt("Datarecorder", "logs/datarecorder.txt", 1048576 * 10, 3); my_logger->flush_on(spdlog::level::info); this->eventengine = eventengine; this->ctpgateway = new Ctpmd(eventengine); eventengine->regEvent(EVENT_LOG, std::bind(&Datarecorder::showLog, this, std::placeholders::_1)); eventengine->regEvent(EVENT_TICK, std::bind(&Datarecorder::onTick, this, std::placeholders::_1)); eventengine->regEvent(EVENT_TIMER, std::bind(&Datarecorder::onDailybar, this)); eventengine->regEvent(EVENT_TIMER, std::bind(&Datarecorder::autoConnect, this)); mongoc_init(); this->uri = mongoc_uri_new("mongodb://localhost/"); // 创建客户端池 this->pool = mongoc_client_pool_new(uri); std::vector<std::string>ninetoeleven = { "bu", "rb", "hc", "ru" }; this->ninetoeleven.insert(ninetoeleven.begin(), ninetoeleven.end()); //9点到11点的合约列表 std::vector<std::string>ninetohalfeleven = { "p", "j", "m", "y", "a", "b", "jm", "i", "SR", "CF", "RM", "MA", "ZC", "FG", "OI", "CY" }; this->ninetohalfeleven.insert(ninetohalfeleven.begin(), ninetohalfeleven.end()); //9点到11点半的合约 std::vector<std::string>ninetoone = { "cu", "al", "zn", "pb", "sn", "ni" }; this->ninetoone.insert(ninetoone.begin(), ninetoone.end()); //9点到1点的合约列表 std::vector<std::string>ninetohalftwo = { "ag", "au" }; this->ninetohalftwo.insert(ninetohalftwo.begin(), ninetohalftwo.end()); //9点到2点半的合约 std::vector<std::string>treasury_futures = { "TF" }; this->treasury_futures.insert(treasury_futures.begin(), treasury_futures.end()); //国债到下午三点十五分 } Datarecorder::~Datarecorder() { this->ctpgateway->close(); delete this->ctpgateway; mongoc_client_pool_destroy(this->pool); mongoc_uri_destroy(this->uri); mongoc_cleanup(); } void Datarecorder::readSymbols() { if (Utils::checkExist("./CTPGateway")) { std::fstream file("./CTPGateway/symbols.txt", std::ios::in); if (file.is_open()) { std::string line; while (getline(file, line)) { this->conf_symbols.insert(line); } } else { this->writeLog("/CTPGateway/symbols.txt不存在,无法读取合约列表"); } file.close(); } else { this->writeLog("CTPGateway目录不存在,无法读取合约列表"); } for (std::set<std::string>::iterator iter = this->conf_symbols.begin(); iter != this->conf_symbols.end(); ++iter) { this->barHourmap[*iter] = 99; this->barMinutemap[*iter] = 99; std::cout << Utils::UTF8_2_GBK("开始订阅合约:") << *iter << std::endl; this->ctpgateway->subscribe(*iter);//订阅一个合约 } } inline void Datarecorder::writeLog(const std::string& msg) const { std::shared_ptr<Event_Log>e = std::make_shared<Event_Log>(); e->msg = msg; e->gatewayname = "ctp"; e->logTime = Utils::getCurrentDateTime(); this->eventengine->put(e); } inline void Datarecorder::showLog(std::shared_ptr<Event>e) { std::unique_lock<std::mutex>lck(log_mutex); std::shared_ptr<Event_Log>elog = std::static_pointer_cast<Event_Log>(e); std::cout << Utils::UTF8_2_GBK("时间:") << elog->logTime << Utils::UTF8_2_GBK("接口:") << Utils::UTF8_2_GBK(elog->gatewayname) << Utils::UTF8_2_GBK("消息:") << Utils::UTF8_2_GBK(elog->msg) << std::endl; if (elog->msg == "行情服务器登录完成") { this->readSymbols();//开始订阅合约 this->writeLog("开始获取合约并订阅"); } } void Datarecorder::autoConnect() { //判断一下当前时间是不是在早上3点到8点50之间 auto nowtime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());//获取当前的系统时间 if (((nowtime > Utils::timeTotime_t(2, 30, 0)) && (nowtime < Utils::timeTotime_t(8, 58, 0))) || ((nowtime > Utils::timeTotime_t(15, 16, 0)) && (nowtime < Utils::timeTotime_t(20, 58, 0)))) { if (this->connectStatus == true) { this->connectStatus = false; this->writeLog("CTP接口主动(断开连接)"); this->ctpgateway->close(); } } else { if (this->connectStatus == false) { if (Utils::getWeekDay(Utils::getCurrentDate()) != 6 && Utils::getWeekDay(Utils::getCurrentDate()) != 7) { this->connectStatus = true; this->writeLog("CTP接口主动(开始连接)"); this->ctpgateway->connect(); } } } } void Datarecorder::onTick(std::shared_ptr<Event>e) { std::shared_ptr<Event_Tick> Tick = std::static_pointer_cast<Event_Tick>(e); //过滤CTP的时间*************************************************************************************************************************** auto ticktime_t = Tick->getTime_t(); auto systemtime_t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());//获取当前的系统时间 std::string symbolHead = Utils::regexSymbol(Tick->symbol); this->dailyBarmap[Tick->symbol] = Tick;//每次更新 this->insertTicktoDb("CTPTickDb", Tick->symbol, Tick); if (Tick->getMinute() != this->barMinutemap.at(Tick->symbol) || Tick->getHour() != this->barHourmap.at(Tick->symbol)) { if (!((this->barHourmap.at(Tick->symbol) == 11 && this->barMinutemap.at(Tick->symbol) == 30) || (this->barHourmap.at(Tick->symbol) == 10 && this->barMinutemap.at(Tick->symbol) == 15))) { //剔除10点15分11点半下午3点的一根TICK合成出来的K线 if (this->ninetoeleven.find(symbolHead) != this->ninetoeleven.end()) { if (this->barHourmap.at(Tick->symbol) == 23) { this->barHourmap.at(Tick->symbol) = 99; this->barmap.erase(Tick->symbol); return; } } else if (this->ninetohalfeleven.find(symbolHead) != this->ninetohalfeleven.end()) { if ((this->barHourmap.at(Tick->symbol) == 23 && this->barMinutemap.at(Tick->symbol) == 30) || (this->barHourmap.at(Tick->symbol) == 15 && this->barMinutemap.at(Tick->symbol) == 00)) { this->barHourmap.at(Tick->symbol) = 99; this->barMinutemap.at(Tick->symbol) = 99; this->barmap.erase(Tick->symbol); return; } } else if (this->ninetoone.find(symbolHead) != this->ninetoone.end()) { if ((this->barHourmap.at(Tick->symbol) == 1) || (this->barHourmap.at(Tick->symbol) == 15 && this->barMinutemap.at(Tick->symbol) == 00)) { this->barHourmap.at(Tick->symbol) = 99; this->barmap.erase(Tick->symbol); return; } } else if (this->ninetohalftwo.find(symbolHead) != this->ninetohalftwo.end()) { if ((this->barHourmap.at(Tick->symbol) == 2 && this->barMinutemap.at(Tick->symbol) == 30) || (this->barHourmap.at(Tick->symbol) == 15 && this->barMinutemap.at(Tick->symbol) == 00)) { this->barHourmap.at(Tick->symbol) = 99; this->barMinutemap.at(Tick->symbol) = 99; this->barmap.erase(Tick->symbol); return; } } else if (this->treasury_futures.find(symbolHead) != this->treasury_futures.end()) { if (this->barHourmap.at(Tick->symbol) == 15 && this->barMinutemap.at(Tick->symbol) == 15) { this->barHourmap.at(Tick->symbol) = 99; this->barMinutemap.at(Tick->symbol) = 99; this->barmap.erase(Tick->symbol); return; } } if (this->barmap.find(Tick->symbol) != this->barmap.end()) { if (this->barHourmap.at(Tick->symbol) == 15 && this->barMinutemap.at(Tick->symbol) == 00) { if (this->treasury_futures.find(symbolHead) == this->treasury_futures.end()) { this->barHourmap.at(Tick->symbol) = 99; this->barMinutemap.at(Tick->symbol) = 99; this->barmap.erase(Tick->symbol); return; } else { onBar(this->barmap.at(Tick->symbol)); } } else { onBar(this->barmap.at(Tick->symbol)); } } } jsstructs::BarData bar; bar.symbol = Tick->symbol; bar.exchange = Tick->exchange; bar.open = Tick->lastprice; bar.high = Tick->lastprice; bar.low = Tick->lastprice; bar.close = Tick->lastprice; bar.openPrice = Tick->openPrice;//今日开 bar.highPrice = Tick->highPrice;//今日高 bar.lowPrice = Tick->lowPrice;//今日低 bar.preClosePrice = Tick->preClosePrice;//昨收 bar.upperLimit = Tick->upperLimit;//涨停 bar.lowerLimit = Tick->lowerLimit;//跌停 bar.volume = Tick->volume; bar.openInterest = Tick->openInterest; bar.date = Tick->date; bar.time = Tick->time; bar.setUnixDatetime(); this->barmap[Tick->symbol] = bar; this->barMinutemap[Tick->symbol] = Tick->getMinute(); this->barHourmap[Tick->symbol] = Tick->getHour(); } else { this->barmap[Tick->symbol].high = std::max(this->barmap[Tick->symbol].high, Tick->lastprice); this->barmap[Tick->symbol].low = std::min(this->barmap[Tick->symbol].low, Tick->lastprice); this->barmap[Tick->symbol].close = Tick->lastprice; this->barmap[Tick->symbol].highPrice = Tick->highPrice; this->barmap[Tick->symbol].lowPrice = Tick->lowPrice; this->barmap[Tick->symbol].openInterest = Tick->openInterest; this->barmap[Tick->symbol].volume += Tick->volume; } } void Datarecorder::onBar(const jsstructs::BarData &bar) { std::unique_lock<std::mutex>lck(bar_mutex); std::vector<std::string>time_milliseconds = Utils::split(bar.time, "."); if (time_milliseconds.size() == 2) { std::string lastmilliseconds = time_milliseconds.back() + "00"; long long id = std::stoll(std::to_string(bar.getTime_t()) + lastmilliseconds); if (this->lastBarIdmap.find(bar.symbol) != this->lastBarIdmap.end()) { if (this->lastBarIdmap.at(bar.symbol) == id) { this->writeLog(bar.symbol + "bar级别收到了重复的时间戳" + std::to_string(id)); return; } } mongoc_client_t *client = mongoc_client_pool_pop(this->pool); mongoc_collection_t *collection = mongoc_client_get_collection(client, "CTPMinuteDb", bar.symbol.c_str()); bson_error_t error; bson_t *doc = bson_new(); this->lastBarIdmap[bar.symbol] = id; BSON_APPEND_INT64(doc, "_id", id); BSON_APPEND_UTF8(doc, "exchange", bar.exchange.c_str()); BSON_APPEND_UTF8(doc, "symbol", bar.symbol.c_str()); BSON_APPEND_DOUBLE(doc, "open", bar.open); BSON_APPEND_DOUBLE(doc, "high", bar.high); BSON_APPEND_DOUBLE(doc, "low", bar.low); BSON_APPEND_DOUBLE(doc, "close", bar.close); BSON_APPEND_DOUBLE(doc, "volume", bar.volume); BSON_APPEND_DATE_TIME(doc, "datetime", id); BSON_APPEND_UTF8(doc, "date", bar.date.c_str()); BSON_APPEND_UTF8(doc, "time", bar.time.c_str()); BSON_APPEND_DOUBLE(doc, "openInterest", bar.openInterest); BSON_APPEND_DOUBLE(doc, "openPrice", bar.openPrice); BSON_APPEND_DOUBLE(doc, "highPrice", bar.highPrice); BSON_APPEND_DOUBLE(doc, "lowPrice", bar.lowPrice); BSON_APPEND_DOUBLE(doc, "preClosePrice", bar.preClosePrice); BSON_APPEND_DOUBLE(doc, "upperLimit", bar.upperLimit); BSON_APPEND_DOUBLE(doc, "lowerLimit", bar.lowerLimit); // 将bson文档插入到集合 if (!mongoc_collection_insert(collection, MONGOC_INSERT_NONE, doc, NULL, &error)) { this->writeLog("mongoc Bar insert failed"); } bson_destroy(doc); mongoc_collection_destroy(collection); mongoc_client_pool_push(this->pool, client); this->writeLog("合约:" + bar.symbol + "开" + std::to_string(bar.open) + "高" + std::to_string(bar.high) + "低" + std::to_string(bar.low) + "收" + std::to_string(bar.close)); } } void Datarecorder::onDailybar() { std::unique_lock<std::mutex>lck(dailyBarmtx); auto nowtime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); auto close_time_begin = Utils::timeTotime_t(15, 0, 0); auto close_time_end = Utils::timeTotime_t(15, 10, 0); if ((nowtime > close_time_begin) && (nowtime < close_time_end)) { if (!this->dailyBarmap.empty()) { //遍历一遍 for (std::map<std::string, std::shared_ptr<Event_Tick>>::iterator it = this->dailyBarmap.begin(); it != this->dailyBarmap.end(); ++it) { mongoc_client_t *client = mongoc_client_pool_pop(this->pool); mongoc_collection_t *collection = mongoc_client_get_collection(client, "CTPDailyDb", it->second->symbol.c_str()); bson_error_t error; bson_t *doc = bson_new(); auto milliseconds = Utils::getMilliseconds(); std::string lastmilliseconds = milliseconds.substr(milliseconds.size() - 3); long long id = std::stoll(std::to_string(it->second->getTime_t()) + lastmilliseconds); BSON_APPEND_INT64(doc, "_id", id); BSON_APPEND_DOUBLE(doc, "open", it->second->openPrice); BSON_APPEND_DOUBLE(doc, "high", it->second->highPrice); BSON_APPEND_DOUBLE(doc, "low", it->second->lowPrice); BSON_APPEND_DOUBLE(doc, "close", it->second->lastprice); BSON_APPEND_UTF8(doc, "symbol", it->second->symbol.c_str()); BSON_APPEND_UTF8(doc, "exchange", it->second->exchange.c_str()); BSON_APPEND_UTF8(doc, "date", it->second->date.c_str()); BSON_APPEND_UTF8(doc, "time", it->second->time.c_str()); BSON_APPEND_DOUBLE(doc, "openInterest", it->second->openInterest); BSON_APPEND_DOUBLE(doc, "volume", it->second->volume); BSON_APPEND_DATE_TIME(doc, "datetime", id); // 将bson文档插入到集合 if (!mongoc_collection_insert(collection, MONGOC_INSERT_NONE, doc, NULL, &error)) { this->writeLog("mongoc insert dailybar failed"); } bson_destroy(doc); mongoc_collection_destroy(collection); mongoc_client_pool_push(this->pool, client); } } this->dailyBarmap.clear();//清空 } } void Datarecorder::insertTicktoDb(const std::string &dbname, const std::string &symbol, std::shared_ptr<Event_Tick> tick) { std::unique_lock<std::mutex>lck(tick_mutex); std::vector<std::string>time_milliseconds = Utils::split(tick->time, "."); if (time_milliseconds.size() == 2) { std::string lastmilliseconds = time_milliseconds.back() + "00"; long long id = std::stoll(std::to_string(tick->getTime_t()) + lastmilliseconds); if (this->lastTickIdmap.find(symbol) != this->lastTickIdmap.end()) { if (this->lastTickIdmap.at(symbol) == id) { this->writeLog(symbol + "收到了重复的时间戳" + std::to_string(id)); return; } } mongoc_client_t *client = mongoc_client_pool_pop(this->pool); mongoc_collection_t *collection = mongoc_client_get_collection(client, dbname.c_str(), symbol.c_str()); bson_error_t error; bson_t *doc = bson_new(); this->lastTickIdmap[symbol] = id; BSON_APPEND_INT64(doc, "_id", id); BSON_APPEND_DOUBLE(doc, "bidVolume5", tick->bidvolume5); BSON_APPEND_DOUBLE(doc, "bidVolume4", tick->bidvolume4); BSON_APPEND_DOUBLE(doc, "bidVolume3", tick->bidvolume3); BSON_APPEND_DOUBLE(doc, "bidVolume2", tick->bidvolume2); BSON_APPEND_DOUBLE(doc, "bidVolume1", tick->bidvolume1); BSON_APPEND_DOUBLE(doc, "askVolume1", tick->askvolume1); BSON_APPEND_DOUBLE(doc, "askVolume2", tick->askvolume2); BSON_APPEND_DOUBLE(doc, "askVolume3", tick->askvolume3); BSON_APPEND_DOUBLE(doc, "askVolume4", tick->askvolume4); BSON_APPEND_DOUBLE(doc, "askVolume5", tick->askvolume5); BSON_APPEND_DOUBLE(doc, "askPrice5", tick->askprice5); BSON_APPEND_DOUBLE(doc, "askPrice4", tick->askprice4); BSON_APPEND_DOUBLE(doc, "askPrice3", tick->askprice3); BSON_APPEND_DOUBLE(doc, "askPrice2", tick->askprice2); BSON_APPEND_DOUBLE(doc, "askPrice1", tick->askprice1); BSON_APPEND_DOUBLE(doc, "bidPrice5", tick->bidprice5); BSON_APPEND_DOUBLE(doc, "bidPrice4", tick->bidprice4); BSON_APPEND_DOUBLE(doc, "bidPrice3", tick->bidprice3); BSON_APPEND_DOUBLE(doc, "bidPrice2", tick->bidprice2); BSON_APPEND_DOUBLE(doc, "bidPrice1", tick->bidprice1); BSON_APPEND_DOUBLE(doc, "lastPrice", tick->lastprice); BSON_APPEND_DOUBLE(doc, "volume", tick->volume); BSON_APPEND_DOUBLE(doc, "openInterest", tick->openInterest); BSON_APPEND_DOUBLE(doc, "lowerLimit", tick->lowerLimit); BSON_APPEND_DOUBLE(doc, "upperLimit", tick->upperLimit); BSON_APPEND_UTF8(doc, "exchange", tick->exchange.c_str()); BSON_APPEND_UTF8(doc, "symbol", tick->symbol.c_str()); BSON_APPEND_DATE_TIME(doc, "datetime", id); BSON_APPEND_UTF8(doc, "date", tick->date.c_str()); BSON_APPEND_UTF8(doc, "time", tick->time.c_str()); // 将bson文档插入到集合 if (!mongoc_collection_insert(collection, MONGOC_INSERT_NONE, doc, NULL, &error)) { this->writeLog("mongoc insert failed"); fprintf(stderr, "Count failed: %s\n", error.message); } bson_destroy(doc); mongoc_collection_destroy(collection); mongoc_client_pool_push(this->pool, client); } else { my_logger->error("insert Tick DB failed symbol:{} date:{} time:{} ", tick->symbol, tick->date, tick->time); } }
16,282
7,299
class GVAR(dynamicOwnerNoSyncToolbox): GVAR(dynamicToolboxPicture) { class Controls: Controls { class Title: Title {}; class Value: Value { columns = 5; strings[] = { "\a3\3DEN\Data\Displays\Display3DEN\PanelRight\side_custom_ca.paa", "\a3\3DEN\Data\Displays\Display3DEN\PanelRight\side_west_ca.paa", "\a3\3DEN\Data\Displays\Display3DEN\PanelRight\side_east_ca.paa", "\a3\3DEN\Data\Displays\Display3DEN\PanelRight\side_guer_ca.paa", "\a3\3DEN\Data\Displays\Display3DEN\PanelRight\side_civ_ca.paa" }; tooltips[] = { CSTRING(dynamicOwnerToolbox_all), "BLUFOR", "OPFOR", "INDEP", "CIV" }; values[] = {0, 1, 2, 3, 4}; }; class GVAR(description): GVAR(description) {}; }; };
943
315
#include "../include/dsfs.hh" #include "../include/clientHelper.h" DSFS* DSFS::_instance = NULL; DSFS* DSFS::Instance() { if(_instance == NULL) { _instance = new DSFS(); } return _instance; } DSFS::DSFS() { } DSFS::~DSFS() { } void DSFS::AbsPath(char dest[PATH_MAX], const char *path) { log_msg("dsfs_AbsPath: rootdir = \"%s\", path = \"%s\", destination = \"%s\"\n", _root, path, dest); strcpy(dest, _root); strncat(dest, path, PATH_MAX); } void DSFS::setRootDir(const char *path) { _root = path; } int DSFS::Getattr(const char *path, struct stat *statbuf) { char fullPath[ PATH_MAX ]; AbsPath( fullPath, path ); log_msg("\ndsfs_Getattr(path=\"%s\", statbuf=%s)\n", path, *statbuf); GetAttrClient client( grpc::CreateChannel( "localhost:50051", grpc::InsecureChannelCredentials() ) ); GetAttrRequest request; GetAttrResponse response; request.set_name(fullPath); try { response = client.GetAttr(request); Attr attributes = response.attr(); FSstatus status = response.status(); statbuf->st_dev = attributes.dev(); statbuf->st_ino = attributes.ino(); statbuf->st_mode = attributes.mode(); statbuf->st_nlink = attributes.nlink(); Owner owner = attributes.owner(); statbuf->st_uid = owner.uid(); statbuf->st_gid = owner.gid(); statbuf->st_rdev = attributes.rdev(); statbuf->st_size = attributes.size(); statbuf->st_blksize = attributes.blksize(); statbuf->st_blocks = attributes.blocks(); statbuf->st_atime = attributes.atime(); statbuf->st_mtime = attributes.mtime(); statbuf->st_ctime = attributes.ctime(); if (status.retcode() == 0) { log_msg("Return Code: %d\n", status.retcode()); return 0; } else { log_msg("Return Code: %d\n", status.retcode()); errno = status.retcode(); return errno; } } catch ( std::string errorMsg ) { std::cout << errorMsg << std::endl; return -1; } } int DSFS::Mknod(const char *path, mode_t mode, dev_t dev) { char fullPath[PATH_MAX]; AbsPath(fullPath, path); log_msg("dsfs_Mknod(path=%s, mode=%d, dev=%d)\n", path, mode, dev); MknodClient client( grpc::CreateChannel( "localhost:50051", grpc::InsecureChannelCredentials() ) ); MknodRequest request; request.set_name(fullPath); request.set_mode(mode); request.set_dev(dev); try { MknodResponse response = client.Mknod(request); FSstatus status = response.status(); if (status.retcode() == 0) { log_msg("Return Code: %d\n", status.retcode()); return 0; } else { errno = status.retcode(); log_msg("Return Code: %d\n", status.retcode()); return errno; } } catch ( std::string errorMsg ) { std::cout << errorMsg << std::endl; return -1; } } int DSFS::Mkdir(const char *path, mode_t mode) { char fullPath[PATH_MAX]; AbsPath(fullPath, path); log_msg("dsfs_Mkdir(path=%s, mode=%d)\n", path, mode); MkdirClient client( grpc::CreateChannel( "localhost:50051", grpc::InsecureChannelCredentials() ) ); MkdirRequest request; MkdirResponse response; request.set_name(fullPath); request.set_mode(mode); try { response = client.Mkdir(request); FSstatus status = response.status(); if (status.retcode() == 0) { log_msg("Return Code: %d\n", status.retcode()); return 0; } else { errno = status.retcode(); log_msg("Return Code: %d\n", status.retcode()); return errno; } } catch ( std::string errorMsg ) { std::cout << errorMsg << std::endl; return -1; } } int DSFS::Unlink(const char *path) { char fullPath[PATH_MAX]; AbsPath(fullPath, path); log_msg("dsfs_Unlink(path=%s)\n", path); UnlinkClient client( grpc::CreateChannel( "localhost:50051", grpc::InsecureChannelCredentials() ) ); UnlinkRequest request; request.set_name(fullPath); try { UnlinkResponse response = client.Unlink(request); FSstatus status = response.status(); if (status.retcode() == 0) { log_msg("Return Code: %d\n", status.retcode()); return 0; } else { errno = status.retcode(); log_msg("Return Code: %d\n", status.retcode()); return errno; } } catch ( std::string errorMsg ) { std::cout << errorMsg << std::endl; return -1; } } int DSFS::Rmdir(const char *path) { char fullPath[PATH_MAX]; AbsPath(fullPath, path); log_msg("dsfs_Rmdir(path=%s)\n", path); RmdirClient client( grpc::CreateChannel( "localhost:50051", grpc::InsecureChannelCredentials() ) ); RmdirRequest request; request.set_name(fullPath); try { RmdirResponse response = client.Rmdir(request); FSstatus status = response.status(); if (status.retcode() == 0) { log_msg("Return Code: %d\n", status.retcode()); return 0; } else { errno = status.retcode(); log_msg("Return Code: %d\n", status.retcode()); return errno; } } catch ( std::string errorMsg ) { std::cout << errorMsg << std::endl; return -1; } } int DSFS::Rename(const char *path, const char *newpath) { char fullPath[PATH_MAX], newFullPath[PATH_MAX]; AbsPath(fullPath, path); AbsPath(newFullPath, newpath); log_msg("dsfs_Rename(path=\"%s\", newpath=\"%s\")\n", path, newpath); RenameClient client( grpc::CreateChannel( "localhost:50051", grpc::InsecureChannelCredentials() ) ); RenameRequest request; request.set_oldname(fullPath); request.set_newname(newFullPath); try { RenameResponse response = client.Rename(request); FSstatus status = response.status(); if (status.retcode() == 0) { log_msg("Return Code: %d\n", status.retcode()); return 0; } else { errno = status.retcode(); log_msg("Return Code: %d\n", status.retcode()); return errno; } } catch ( std::string errorMsg ) { std::cout << errorMsg << std::endl; return -1; } } int DSFS::Chmod(const char *path, mode_t mode) { char fullPath[PATH_MAX]; AbsPath(fullPath, path); log_msg("dsfs_Chmod(path=%s, mode=%d)\n", path, mode); ChmodClient client( grpc::CreateChannel( "localhost:50051", grpc::InsecureChannelCredentials() ) ); ChmodRequest request; request.set_name( fullPath ); request.set_mode( mode ); try { ChmodResponse response = client.Chmod( request ); FSstatus status = response.status(); if ( status.retcode() == 0 ) { log_msg("Return Code: %d\n", status.retcode()); return 0; } else { errno = status.retcode(); log_msg("Return Code: %d\n", status.retcode()); return errno; } } catch ( std::string errorMsg ) { std::cout << errorMsg << std::endl; return -1; } } int DSFS::Chown(const char *path, uid_t uid, gid_t gid) { char fullPath[PATH_MAX]; AbsPath(fullPath, path); log_msg("dsfs_Chown(path=%s, uid=%d, gid=%d)\n", path, (int)uid, (int)gid); ChownClient client( grpc::CreateChannel( "localhost:50051", grpc::InsecureChannelCredentials() ) ); ChownRequest request; request.set_name( fullPath ); request.set_uid( uid ); request.set_gid( gid ); try { ChownResponse response = client.Chown( request ); FSstatus status = response.status(); if ( status.retcode() == 0 ) { log_msg("Return Code: %d\n", status.retcode()); return 0; } else { errno = status.retcode(); log_msg("Return Code: %d\n", status.retcode()); return errno; } } catch ( std::string errorMsg ) { std::cout << errorMsg << std::endl; return -1; } } int DSFS::Truncate(const char *path, off_t newSize) { char fullPath[PATH_MAX]; AbsPath(fullPath, path); log_msg("dsfs_Truncate(path=%s, newSize=%d)\n", path, (int)newSize); TruncateClient client( grpc::CreateChannel( "localhost:50051", grpc::InsecureChannelCredentials() ) ); TruncateRequest request; request.set_name( fullPath ); request.set_size( newSize ); try { TruncateResponse response = client.Truncate( request ); FSstatus status = response.status(); if ( status.retcode() == 0 ) { log_msg("Return Code: %d\n", status.retcode()); return 0; } else { errno = status.retcode(); log_msg("Return Code: %d\n", status.retcode()); return errno; } } catch ( std::string errorMsg ) { std::cout << errorMsg << std::endl; return -1; } } int DSFS::Access(const char *path, int mask) { char fullPath[PATH_MAX]; AbsPath(fullPath, path); log_msg("dsfs_Access(path=%s, mask=%d)\n", path, mask); AccessClient client( grpc::CreateChannel( "localhost:50051", grpc::InsecureChannelCredentials() ) ); AccessRequest request; request.set_name( fullPath ); request.set_mode( mask ); try { AccessResponse response = client.Access( request ); FSstatus status = response.status(); if ( status.retcode() == 0 ) { log_msg("Return Code: %d\n", status.retcode()); return 0; } else { errno = status.retcode(); log_msg("Return Code: %d\n", status.retcode()); return errno; } } catch ( std::string errorMsg ) { std::cout << errorMsg << std::endl; return -1; } } int DSFS::Open(const char *path, struct fuse_file_info *fileInfo) { char fullPath[ PATH_MAX ]; AbsPath( fullPath, path ); log_msg("dsfs_Open(path=%s, fileHandle=%d, flags=%d)\n", path, (int)fileInfo->fh, (int)fileInfo->flags); // RPC request prep OpenClient client( grpc::CreateChannel( "localhost:50051", grpc::InsecureChannelCredentials() ) ); OpenRequest request; request.set_name( fullPath ); request.set_flags( fileInfo->flags ); try { OpenResponse response = client.Open( request ); fileInfo->fh = response.filehandle(); FSstatus status = response.status(); if ( status.retcode() == 0 ) { log_msg("Return Code: %d\n", status.retcode()); return 0; } else { errno = status.retcode(); log_msg("Return Code: %d\n", status.retcode()); return errno; } } catch ( std::string errorMsg ) { std::cout << errorMsg << std::endl; return -1; } } int DSFS::Read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo) { log_msg("dsfs_Read(path=%s, size=%d, offset=%d, fileHandle=%d, flags=%d)\n", path, (int)size, (int)offset, (int)fileInfo->fh, (int)fileInfo->flags); // RPC request prep ReadClient client( grpc::CreateChannel( "localhost:50051", grpc::InsecureChannelCredentials() ) ); ReadRequest request; request.set_filehandle( fileInfo->fh ); request.set_size( size ); request.set_offset( offset ); try { // RPC call ReadResponse response = client.Read( request ); FSstatus status = response.status(); if ( status.retcode() == 0 ) { int byteRead = response.dataread(); if ( byteRead > 0 ) memcpy( buf, response.data().c_str(), byteRead ); log_msg("Return Code: %d\n", status.retcode()); return byteRead; } else { errno = status.retcode(); log_msg("Return Code: %d\n", status.retcode()); return errno; } } catch ( std::string errorMsg ) { std::cout << errorMsg << std::endl; return -1; } } int DSFS::Write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo) { log_msg("dsfs_Write(path=%s, size=%d, offset=%d, fileHandle=%d, flags=%d)\n", path, (int)size, (int)offset, (int)fileInfo->fh, (int)fileInfo->flags); std::string data( buf, size ); // RPC request prep WriteClient client( grpc::CreateChannel( "localhost:50051", grpc::InsecureChannelCredentials() ) ); WriteRequest request; request.set_filehandle( fileInfo->fh ); request.set_data( data ); request.set_size( size ); request.set_offset( offset ); try { // RPC call WriteResponse response = client.Write( request ); FSstatus status = response.status(); if ( status.retcode() == 0 ) { // update local buffer, if fh is not in map, it will be added this way dataBuffer[ fileInfo->fh ].append( buf, size ); log_msg("Return Code: %d\n", status.retcode()); return size; } else { errno = status.retcode(); log_msg("Return Code: %d\n", status.retcode()); return errno; } } catch ( std::string errorMsg ) { std::cout << errorMsg << std::endl; return -1; } } int DSFS::Release(const char *path, struct fuse_file_info *fileInfo) { log_msg("dsfs_Release(path=%s)\n", path); ReleaseClient client( grpc::CreateChannel( "localhost:50051", grpc::InsecureChannelCredentials() ) ); ReleaseRequest request; request.set_filehandle(fileInfo->fh); try { ReleaseResponse response = client.Release(request); FSstatus status = response.status(); if (status.retcode() == 0) { log_msg("Return Code: %d\n", status.retcode()); return 0; } else { errno = status.retcode(); log_msg("Return Code: %d\n", status.retcode()); return errno; } } catch ( std::string errorMsg ) { std::cout << errorMsg << std::endl; return -1; } } int DSFS::Fsync(const char *path, int datasync, struct fuse_file_info *fi) { log_msg("dsfs_Fsync(path=%s, fileHandle=%d, datasync=%d\n", path, (int) fi->fh, datasync); FsyncClient client( grpc::CreateChannel( "localhost:50051", grpc::InsecureChannelCredentials() ) ); FsyncRequest request; request.set_filehandle( fi->fh ); try { FsyncResponse response = client.Fsync( request ); FSstatus status = response.status(); if (status.retcode() == 0) { // Data successfully on disk, we can remove stuff from local buffer log_msg("Return Code: %d\n", status.retcode()); dataBuffer.erase( fi->fh ); return 0; } else { errno = status.retcode(); log_msg("Return Code: %d\n", status.retcode()); return errno; } } catch ( std::string errorMsg ) { std::cout << errorMsg << std::endl; return -1; } } //Extended attributes not implemented for RPC calls. int DSFS::Setxattr(const char *path, const char *name, const char *value, size_t size, int flags) { log_msg("dsfs_Setxattr(path=%s, name=%s, value=%s, size=%d, flags=%d\n", path, name, value, (int)size, flags); return 0; } int DSFS::Getxattr(const char *path, const char *name, char *value, size_t size) { log_msg("dsfs_Getxattr(path=%s, name=%s, size=%d)\n", path, name, (int)size); return 0; } int DSFS::Listxattr(const char *path, char *list, size_t size) { log_msg("dsfs_Listxattr(path=%s, list=%s, size=%d)\n", path, list, (int)size); return 0; } int DSFS::Removexattr(const char *path, const char *name) { log_msg("dsfs_Removexattr(path=%s, name=%s)\n", path, name); return 0; } int DSFS::Readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fileInfo) { char fullPath[PATH_MAX]; AbsPath(fullPath, path); log_msg("dsfs_Readdir(path=%s, offset=%d)\n", path, (int)offset); std::shared_ptr<Channel> channel = grpc::CreateChannel( "localhost:50051", grpc::InsecureChannelCredentials() ); OpenDirClient client( channel); OpenDirRequest request; OpenDirResponse response; request.set_name(fullPath); try { response = client.Opendir(request); FSstatus status = response.status(); if ( status.retcode() == 0 ) { for(int i=0; i< response.dirs_size(); i++) { struct stat st; memset(&st, 0, sizeof(st)); DirEntry dir = response.dirs(i); st.st_ino = dir.ino(); st.st_mode = dir.mode() << 12; if (filler(buf, (dir.name()).c_str(), &st, 0) != 0) break; } log_msg("Return Code: %d\n", status.retcode()); return 0; } else { errno = status.retcode(); log_msg("Return Code: %d\n", status.retcode()); return errno; } } catch ( std::string errorMsg ) { std::cout << errorMsg << std::endl; return -1; } } int DSFS::Releasedir(const char *path, struct fuse_file_info *fileInfo) { log_msg("dsfs_Releasedir(path=%s)\n", path); ReleasedirClient client( grpc::CreateChannel( "localhost:50051", grpc::InsecureChannelCredentials() ) ); ReleasedirRequest request; request.set_filehandle(fileInfo->fh); try { ReleasedirResponse response = client.Releasedir(request); FSstatus status = response.status(); if (status.retcode() == 0) { log_msg("Return Code: %d\n", status.retcode()); return 0; } else { errno = status.retcode(); log_msg("Return Code: %d\n", status.retcode()); return errno; } } catch ( std::string errorMsg ) { std::cout << errorMsg << std::endl; return -1; } } int DSFS::Init(struct fuse_conn_info *conn) { log_msg("\ndsfs_init()\n"); log_conn(conn); log_fuse_context(fuse_get_context()); return 0; } /*int DSFS::Flush(const char *path, struct fuse_file_info *fileInfo) { printf("flush(path=%s)\n", path); //noop because we don't maintain our own buffers return 0; }*/
18,564
6,173
#include <cstdio> #include <iostream> #include <cmath> using namespace std; int MRR[1000001]; int ARR[1000001]; int main() { int N; scanf("%d", &N); for (int i = 0; i < N; i++) { int v; scanf("%d", &v); if (v >= 0) ARR[v] = 1; else MRR[abs(v)] = 1; } for (int i = 1000000; i >= 0; i--) if (ARR[i] == 1) printf("%d\n", i); for (int i = 1; i < 1000001; i++) if (MRR[i] == 1) printf("%d\n", -i); return 0; }
421
236
#include "cose/cose.h" #include "cose/cose_configure.h" #include "cose_int.h" #include "cose_crypto.h" #include <assert.h> #ifdef __MBED__ #include <string.h> #else #include <memory.h> #endif #include <stdbool.h> #ifdef COSE_C_USE_OPENSSL #include <openssl/evp.h> #include <openssl/aes.h> #include <openssl/cmac.h> #include <openssl/hmac.h> #include <openssl/ecdsa.h> #include <openssl/ecdh.h> #include <openssl/rand.h> #include <openssl/bn.h> /*******************************************/ #define Safe_OPENSSL(handleName, freeFunction) \ class Safe_##handleName { \ handleName *h; \ \ public: \ Safe_##handleName() { h = nullptr; } \ Safe_##handleName(handleName *hIn) { h = hIn; } \ ~Safe_##handleName() { freeFunction(h); } \ handleName *Set(handleName *hIn) \ { \ if (h != nullptr) { \ freeFunction(h); \ } \ h = hIn; \ if (hIn != nullptr) { \ handleName##_up_ref(hIn); \ } \ return hIn; \ } \ bool IsNull() { return h == NULL; } \ operator handleName *() { return h; } \ handleName *operator=(handleName *pIn) \ { \ Set(pIn); \ return pIn; \ } \ handleName *Transfer(Safe_##handleName *hIn) \ { \ if (h != nullptr) { \ freeFunction(h); \ } \ h = hIn->h; \ hIn->h = nullptr; \ return h; \ } \ handleName *operator=(Safe_##handleName hIn) \ { \ Set(hIn.h); \ return h; \ } \ handleName *Release() \ { \ handleName *h2 = h; \ h = nullptr; \ return h2; \ } \ }; Safe_OPENSSL(EC_KEY, EC_KEY_free); Safe_OPENSSL(EVP_PKEY, EVP_PKEY_free); /**********************************************/ bool AES_CCM_Decrypt(COSE_Enveloped *pcose, int TSize, int LSize, const byte *pbKey, size_t cbKey, const byte *pbCrypto, size_t cbCrypto, const byte *pbAuthData, size_t cbAuthData, cose_errback *perr) { EVP_CIPHER_CTX *ctx; int cbOut; byte *rgbOut = nullptr; size_t NSize = 15 - (LSize / 8); int outl = 0; byte rgbIV[15] = {0}; const cn_cbor *pIV = nullptr; const EVP_CIPHER *cipher; #ifdef USE_CBOR_CONTEXT cn_cbor_context *context = &pcose->m_message.m_allocContext; #endif ctx = EVP_CIPHER_CTX_new(); CHECK_CONDITION(ctx != nullptr, COSE_ERR_OUT_OF_MEMORY); // Setup the IV/Nonce and put it into the message pIV = _COSE_map_get_int( &pcose->m_message, COSE_Header_IV, COSE_BOTH, nullptr); if ((pIV == nullptr) || (pIV->type != CN_CBOR_BYTES)) { if (perr != nullptr) { perr->err = COSE_ERR_INVALID_PARAMETER; } errorReturn: if (rgbOut != nullptr) { COSE_FREE(rgbOut, context); } EVP_CIPHER_CTX_free(ctx); return false; } CHECK_CONDITION(pIV->length == NSize, COSE_ERR_INVALID_PARAMETER); memcpy(rgbIV, pIV->v.str, pIV->length); // Setup and run the OpenSSL code switch (cbKey) { case 128 / 8: cipher = EVP_aes_128_ccm(); break; case 192 / 8: cipher = EVP_aes_192_ccm(); break; case 256 / 8: cipher = EVP_aes_256_ccm(); break; default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); break; } CHECK_CONDITION(EVP_DecryptInit_ex(ctx, cipher, nullptr, nullptr, nullptr), COSE_ERR_DECRYPT_FAILED); TSize /= 8; // Comes in in bits not bytes. CHECK_CONDITION( EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_L, (LSize / 8), 0), COSE_ERR_DECRYPT_FAILED); // CHECK_CONDITION(EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_CCM_SET_IVLEN, NSize, // 0), COSE_ERR_DECRYPT_FAILED); CHECK_CONDITION(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_TAG, TSize, (void *)&pbCrypto[cbCrypto - TSize]), COSE_ERR_DECRYPT_FAILED); CHECK_CONDITION(EVP_DecryptInit_ex(ctx, 0, nullptr, pbKey, rgbIV), COSE_ERR_DECRYPT_FAILED); CHECK_CONDITION( EVP_DecryptUpdate(ctx, nullptr, &cbOut, nullptr, (int)cbCrypto - TSize), COSE_ERR_DECRYPT_FAILED); cbOut = (int)cbCrypto - TSize; rgbOut = (byte *)COSE_CALLOC(cbOut, 1, context); CHECK_CONDITION(rgbOut != nullptr, COSE_ERR_OUT_OF_MEMORY); CHECK_CONDITION( EVP_DecryptUpdate(ctx, nullptr, &outl, pbAuthData, (int)cbAuthData), COSE_ERR_DECRYPT_FAILED); CHECK_CONDITION( EVP_DecryptUpdate(ctx, rgbOut, &cbOut, pbCrypto, (int)cbCrypto - TSize), COSE_ERR_DECRYPT_FAILED); EVP_CIPHER_CTX_free(ctx); pcose->pbContent = rgbOut; pcose->cbContent = cbOut; return true; } bool AES_CCM_Encrypt(COSE_Enveloped *pcose, int TSize, int LSize, const byte *pbKey, size_t cbKey, const byte *pbAuthData, size_t cbAuthData, cose_errback *perr) { EVP_CIPHER_CTX *ctx; int cbOut; byte *rgbOut = nullptr; size_t NSize = 15 - (LSize / 8); int outl = 0; const cn_cbor *cbor_iv = nullptr; cn_cbor *cbor_iv_t = nullptr; #ifdef USE_CBOR_CONTEXT cn_cbor_context *context = &pcose->m_message.m_allocContext; #endif cn_cbor *cnTmp = nullptr; const EVP_CIPHER *cipher; byte rgbIV[16]; byte *pbIV = nullptr; cn_cbor_errback cbor_error; ctx = EVP_CIPHER_CTX_new(); CHECK_CONDITION(nullptr != ctx, COSE_ERR_OUT_OF_MEMORY); switch (cbKey * 8) { case 128: cipher = EVP_aes_128_ccm(); break; case 192: cipher = EVP_aes_192_ccm(); break; case 256: cipher = EVP_aes_256_ccm(); break; default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); } // Setup the IV/Nonce and put it into the message cbor_iv = _COSE_map_get_int(&pcose->m_message, COSE_Header_IV, COSE_BOTH, perr); if (cbor_iv == nullptr) { pbIV = (byte *)COSE_CALLOC(NSize, 1, context); CHECK_CONDITION(pbIV != nullptr, COSE_ERR_OUT_OF_MEMORY); rand_bytes(pbIV, NSize); memcpy(rgbIV, pbIV, NSize); cbor_iv_t = cn_cbor_data_create2( pbIV, NSize, 0, CBOR_CONTEXT_PARAM_COMMA & cbor_error); CHECK_CONDITION_CBOR(cbor_iv_t != nullptr, cbor_error); pbIV = nullptr; if (!_COSE_map_put(&pcose->m_message, COSE_Header_IV, cbor_iv_t, COSE_UNPROTECT_ONLY, perr)) { goto errorReturn; } cbor_iv_t = nullptr; } else { CHECK_CONDITION( cbor_iv->type == CN_CBOR_BYTES, COSE_ERR_INVALID_PARAMETER); CHECK_CONDITION(cbor_iv->length == NSize, COSE_ERR_INVALID_PARAMETER); memcpy(rgbIV, cbor_iv->v.str, cbor_iv->length); } // Setup and run the OpenSSL code CHECK_CONDITION(EVP_EncryptInit_ex(ctx, cipher, nullptr, nullptr, nullptr), COSE_ERR_CRYPTO_FAIL); TSize /= 8; // Comes in in bits not bytes. CHECK_CONDITION( EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_L, (LSize / 8), 0), COSE_ERR_CRYPTO_FAIL); // CHECK_CONDITION(EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_CCM_SET_IVLEN, NSize, // 0), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION( EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_TAG, TSize, nullptr), COSE_ERR_CRYPTO_FAIL); // Say we are doing an 8 byte tag CHECK_CONDITION(EVP_EncryptInit_ex(ctx, 0, nullptr, pbKey, rgbIV), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION(EVP_EncryptUpdate(ctx, 0, &cbOut, 0, (int)pcose->cbContent), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION( EVP_EncryptUpdate(ctx, nullptr, &outl, pbAuthData, (int)cbAuthData), COSE_ERR_CRYPTO_FAIL); rgbOut = (byte *)COSE_CALLOC(cbOut + TSize, 1, context); CHECK_CONDITION(rgbOut != nullptr, COSE_ERR_OUT_OF_MEMORY); CHECK_CONDITION(EVP_EncryptUpdate(ctx, rgbOut, &cbOut, pcose->pbContent, (int)pcose->cbContent), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION( EVP_EncryptFinal_ex(ctx, &rgbOut[cbOut], &cbOut), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_GET_TAG, TSize, &rgbOut[pcose->cbContent]), COSE_ERR_CRYPTO_FAIL); cnTmp = cn_cbor_data_create2(rgbOut, (int)pcose->cbContent + TSize, 0, CBOR_CONTEXT_PARAM_COMMA nullptr); CHECK_CONDITION(cnTmp != nullptr, COSE_ERR_CBOR); rgbOut = nullptr; CHECK_CONDITION(_COSE_array_replace(&pcose->m_message, cnTmp, INDEX_BODY, CBOR_CONTEXT_PARAM_COMMA nullptr), COSE_ERR_CBOR); cnTmp = nullptr; EVP_CIPHER_CTX_free(ctx); return true; errorReturn: if (pbIV != nullptr) { COSE_FREE(pbIV, context); } if (cbor_iv_t != nullptr) { COSE_FREE(cbor_iv_t, context); } if (rgbOut != nullptr) { COSE_FREE(rgbOut, context); } if (cnTmp != nullptr) { COSE_FREE(cnTmp, context); } EVP_CIPHER_CTX_free(ctx); return false; } bool AES_GCM_Decrypt(COSE_Enveloped *pcose, const byte *pbKey, size_t cbKey, const byte *pbCrypto, size_t cbCrypto, const byte *pbAuthData, size_t cbAuthData, cose_errback *perr) { EVP_CIPHER_CTX *ctx; int cbOut; byte *rgbOut = nullptr; int outl = 0; byte rgbIV[15] = {0}; const cn_cbor *pIV = nullptr; const EVP_CIPHER *cipher; #ifdef USE_CBOR_CONTEXT cn_cbor_context *context = &pcose->m_message.m_allocContext; #endif int TSize = 128 / 8; ctx = EVP_CIPHER_CTX_new(); CHECK_CONDITION(nullptr != ctx, COSE_ERR_OUT_OF_MEMORY); // Setup the IV/Nonce and put it into the message pIV = _COSE_map_get_int( &pcose->m_message, COSE_Header_IV, COSE_BOTH, nullptr); if ((pIV == nullptr) || (pIV->type != CN_CBOR_BYTES)) { if (perr != nullptr) { perr->err = COSE_ERR_INVALID_PARAMETER; } errorReturn: if (rgbOut != nullptr) { COSE_FREE(rgbOut, context); } EVP_CIPHER_CTX_free(ctx); return false; } CHECK_CONDITION(pIV->length == 96 / 8, COSE_ERR_INVALID_PARAMETER); memcpy(rgbIV, pIV->v.str, pIV->length); // Setup and run the OpenSSL code switch (cbKey) { case 128 / 8: cipher = EVP_aes_128_gcm(); break; case 192 / 8: cipher = EVP_aes_192_gcm(); break; case 256 / 8: cipher = EVP_aes_256_gcm(); break; default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); break; } // Do the setup for OpenSSL CHECK_CONDITION(EVP_DecryptInit_ex(ctx, cipher, nullptr, nullptr, nullptr), COSE_ERR_DECRYPT_FAILED); CHECK_CONDITION(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_TAG, TSize, (void *)&pbCrypto[cbCrypto - TSize]), COSE_ERR_DECRYPT_FAILED); CHECK_CONDITION(EVP_DecryptInit_ex(ctx, 0, nullptr, pbKey, rgbIV), COSE_ERR_DECRYPT_FAILED); // Pus in the AAD CHECK_CONDITION( EVP_DecryptUpdate(ctx, nullptr, &outl, pbAuthData, (int)cbAuthData), COSE_ERR_DECRYPT_FAILED); // cbOut = (int)cbCrypto - TSize; rgbOut = (byte *)COSE_CALLOC(cbOut, 1, context); CHECK_CONDITION(rgbOut != nullptr, COSE_ERR_OUT_OF_MEMORY); // Process content CHECK_CONDITION( EVP_DecryptUpdate(ctx, rgbOut, &cbOut, pbCrypto, (int)cbCrypto - TSize), COSE_ERR_DECRYPT_FAILED); // Process Tag CHECK_CONDITION(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, TSize, (byte *)pbCrypto + cbCrypto - TSize), COSE_ERR_DECRYPT_FAILED); // Check the result CHECK_CONDITION( EVP_DecryptFinal(ctx, rgbOut + cbOut, &cbOut), COSE_ERR_DECRYPT_FAILED); EVP_CIPHER_CTX_free(ctx); pcose->pbContent = rgbOut; pcose->cbContent = cbOut; return true; } bool AES_GCM_Encrypt(COSE_Enveloped *pcose, const byte *pbKey, size_t cbKey, const byte *pbAuthData, size_t cbAuthData, cose_errback *perr) { EVP_CIPHER_CTX *ctx; int cbOut; byte *rgbOut = nullptr; int outl = 0; byte rgbIV[16] = {0}; byte *pbIV = nullptr; const cn_cbor *cbor_iv = nullptr; cn_cbor *cbor_iv_t = nullptr; const EVP_CIPHER *cipher; #ifdef USE_CBOR_CONTEXT cn_cbor_context *context = &pcose->m_message.m_allocContext; #endif cn_cbor_errback cbor_error; if (false) { errorReturn: if (pbIV != nullptr) { COSE_FREE(pbIV, context); } if (cbor_iv_t != nullptr) { CN_CBOR_FREE(cbor_iv_t, context); } if (rgbOut != nullptr) { COSE_FREE(rgbOut, context); } EVP_CIPHER_CTX_free(ctx); return false; } // Make it first so we can clean it up ctx = EVP_CIPHER_CTX_new(); CHECK_CONDITION(nullptr != ctx, COSE_ERR_OUT_OF_MEMORY); // Setup the IV/Nonce and put it into the message cbor_iv = _COSE_map_get_int(&pcose->m_message, COSE_Header_IV, COSE_BOTH, perr); if (cbor_iv == nullptr) { pbIV = (byte *)COSE_CALLOC(96, 1, context); CHECK_CONDITION(pbIV != nullptr, COSE_ERR_OUT_OF_MEMORY); rand_bytes(pbIV, 96 / 8); memcpy(rgbIV, pbIV, 96 / 8); cbor_iv_t = cn_cbor_data_create2( pbIV, 96 / 8, 0, CBOR_CONTEXT_PARAM_COMMA & cbor_error); CHECK_CONDITION_CBOR(cbor_iv_t != nullptr, cbor_error); pbIV = nullptr; if (!_COSE_map_put(&pcose->m_message, COSE_Header_IV, cbor_iv_t, COSE_UNPROTECT_ONLY, perr)) { goto errorReturn; } cbor_iv_t = nullptr; } else { CHECK_CONDITION( cbor_iv->type == CN_CBOR_BYTES, COSE_ERR_INVALID_PARAMETER); CHECK_CONDITION(cbor_iv->length == 96 / 8, COSE_ERR_INVALID_PARAMETER); memcpy(rgbIV, cbor_iv->v.str, cbor_iv->length); } switch (cbKey * 8) { case 128: cipher = EVP_aes_128_gcm(); break; case 192: cipher = EVP_aes_192_gcm(); break; case 256: cipher = EVP_aes_256_gcm(); break; default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); break; } // Setup and run the OpenSSL code CHECK_CONDITION(EVP_EncryptInit_ex(ctx, cipher, nullptr, nullptr, nullptr), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION(EVP_EncryptInit_ex(ctx, 0, nullptr, pbKey, rgbIV), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION( EVP_EncryptUpdate(ctx, nullptr, &outl, pbAuthData, (int)cbAuthData), COSE_ERR_CRYPTO_FAIL); rgbOut = (byte *)COSE_CALLOC(pcose->cbContent + 128 / 8, 1, context); CHECK_CONDITION(rgbOut != nullptr, COSE_ERR_OUT_OF_MEMORY); CHECK_CONDITION(EVP_EncryptUpdate(ctx, rgbOut, &cbOut, pcose->pbContent, (int)pcose->cbContent), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION( EVP_EncryptFinal_ex(ctx, &rgbOut[cbOut], &cbOut), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 128 / 8, &rgbOut[pcose->cbContent]), COSE_ERR_CRYPTO_FAIL); cn_cbor *cnTmp = cn_cbor_data_create2(rgbOut, (int)pcose->cbContent + 128 / 8, 0, CBOR_CONTEXT_PARAM_COMMA nullptr); CHECK_CONDITION(cnTmp != nullptr, COSE_ERR_CBOR); rgbOut = nullptr; CHECK_CONDITION(_COSE_array_replace(&pcose->m_message, cnTmp, INDEX_BODY, CBOR_CONTEXT_PARAM_COMMA nullptr), COSE_ERR_CBOR); EVP_CIPHER_CTX_free(ctx); if (pbIV != nullptr) { COSE_FREE(pbIV, context); } return true; } bool AES_CBC_MAC_Create(COSE_MacMessage *pcose, int TSize, const byte *pbKey, size_t cbKey, const byte *pbAuthData, size_t cbAuthData, cose_errback *perr) { const EVP_CIPHER *pcipher = nullptr; EVP_CIPHER_CTX *ctx; int cbOut; byte rgbIV[16] = {0}; byte *rgbOut = nullptr; bool f = false; unsigned int i; cn_cbor *cn = nullptr; #ifdef USE_CBOR_CONTEXT cn_cbor_context *context = &pcose->m_message.m_allocContext; #endif ctx = EVP_CIPHER_CTX_new(); CHECK_CONDITION(nullptr != ctx, COSE_ERR_OUT_OF_MEMORY); rgbOut = (byte *)COSE_CALLOC(16, 1, context); CHECK_CONDITION(rgbOut != nullptr, COSE_ERR_OUT_OF_MEMORY); switch (cbKey * 8) { case 128: pcipher = EVP_aes_128_cbc(); break; case 256: pcipher = EVP_aes_256_cbc(); break; default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); } // Setup and run the OpenSSL code CHECK_CONDITION(EVP_EncryptInit_ex(ctx, pcipher, nullptr, pbKey, rgbIV), COSE_ERR_CRYPTO_FAIL); for (i = 0; i < (unsigned int)cbAuthData / 16; i++) { CHECK_CONDITION( EVP_EncryptUpdate(ctx, rgbOut, &cbOut, pbAuthData + (i * 16), 16), COSE_ERR_CRYPTO_FAIL); } if (cbAuthData % 16 != 0) { CHECK_CONDITION(EVP_EncryptUpdate(ctx, rgbOut, &cbOut, pbAuthData + (i * 16), cbAuthData % 16), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION(EVP_EncryptUpdate( ctx, rgbOut, &cbOut, rgbIV, 16 - (cbAuthData % 16)), COSE_ERR_CRYPTO_FAIL); } cn = cn_cbor_data_create2( rgbOut, TSize / 8, 0, CBOR_CONTEXT_PARAM_COMMA nullptr); CHECK_CONDITION(cn != nullptr, COSE_ERR_OUT_OF_MEMORY); rgbOut = nullptr; CHECK_CONDITION(_COSE_array_replace(&pcose->m_message, cn, INDEX_MAC_TAG, CBOR_CONTEXT_PARAM_COMMA nullptr), COSE_ERR_CBOR); cn = nullptr; EVP_CIPHER_CTX_free(ctx); return !f; errorReturn: if (rgbOut != nullptr) { COSE_FREE(rgbOut, context); } if (cn != nullptr) { CN_CBOR_FREE(cn, context); } EVP_CIPHER_CTX_free(ctx); return false; } bool AES_CBC_MAC_Validate(COSE_MacMessage *pcose, int TSize, const byte *pbKey, size_t cbKey, const byte *pbAuthData, size_t cbAuthData, cose_errback *perr) { const EVP_CIPHER *pcipher = nullptr; EVP_CIPHER_CTX *ctx = nullptr; int cbOut; byte rgbIV[16] = {0}; byte rgbTag[16] = {0}; bool f = false; unsigned int i; if (false) { errorReturn: EVP_CIPHER_CTX_free(ctx); return false; } switch (cbKey * 8) { case 128: pcipher = EVP_aes_128_cbc(); break; case 256: pcipher = EVP_aes_256_cbc(); break; default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); } // Setup and run the OpenSSL code ctx = EVP_CIPHER_CTX_new(); CHECK_CONDITION(nullptr != ctx, COSE_ERR_OUT_OF_MEMORY); CHECK_CONDITION(EVP_EncryptInit_ex(ctx, pcipher, nullptr, pbKey, rgbIV), COSE_ERR_CRYPTO_FAIL); TSize /= 8; for (i = 0; i < (unsigned int)cbAuthData / 16; i++) { CHECK_CONDITION( EVP_EncryptUpdate(ctx, rgbTag, &cbOut, pbAuthData + (i * 16), 16), COSE_ERR_CRYPTO_FAIL); } if (cbAuthData % 16 != 0) { CHECK_CONDITION(EVP_EncryptUpdate(ctx, rgbTag, &cbOut, pbAuthData + (i * 16), cbAuthData % 16), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION(EVP_EncryptUpdate( ctx, rgbTag, &cbOut, rgbIV, 16 - (cbAuthData % 16)), COSE_ERR_CRYPTO_FAIL); } cn_cbor *cn = _COSE_arrayget_int(&pcose->m_message, INDEX_MAC_TAG); CHECK_CONDITION(cn != nullptr, COSE_ERR_CBOR); for (i = 0; i < (unsigned int)TSize; i++) { f |= (cn->v.bytes[i] != rgbTag[i]); } EVP_CIPHER_CTX_free(ctx); return !f; } #if 0 // We are doing CBC-MAC not CMAC at this time bool AES_CMAC_Validate(COSE_MacMessage * pcose, int KeySize, int TagSize, const byte * pbAuthData, int cbAuthData, cose_errback * perr) { CMAC_CTX * pctx = nullptr; const EVP_CIPHER * pcipher = nullptr; byte * rgbOut = nullptr; size_t cbOut; bool f = false; unsigned int i; #ifdef USE_CBOR_CONTEXT cn_cbor_context * context = &pcose->m_message.m_allocContext; #endif pctx = CMAC_CTX_new(); switch (KeySize) { case 128: pcipher = EVP_aes_128_cbc(); break; case 256: pcipher = EVP_aes_256_cbc(); break; default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); break; } rgbOut = COSE_CALLOC(128/8, 1, context); CHECK_CONDITION(rgbOut != nullptr, COSE_ERR_OUT_OF_MEMORY); CHECK_CONDITION(CMAC_Init(pctx, pcose->pbKey, pcose->cbKey, pcipher, nullptr /*impl*/) == 1, COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION(CMAC_Update(pctx, pbAuthData, cbAuthData), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION(CMAC_Final(pctx, rgbOut, &cbOut), COSE_ERR_CRYPTO_FAIL); cn_cbor * cn = _COSE_arrayget_int(&pcose->m_message, INDEX_MAC_TAG); CHECK_CONDITION(cn != nullptr, COSE_ERR_CBOR); for (i = 0; i < (unsigned int)TagSize / 8; i++) f |= (cn->v.bytes[i] != rgbOut[i]); COSE_FREE(rgbOut, context); CMAC_CTX_cleanup(pctx); CMAC_CTX_free(pctx); return !f; errorReturn: COSE_FREE(rgbOut, context); CMAC_CTX_cleanup(pctx); CMAC_CTX_free(pctx); return false; } #endif bool HKDF_AES_Expand(COSE *pcose, size_t cbitKey, const byte *pbPRK, size_t cbPRK, const byte *pbInfo, size_t cbInfo, byte *pbOutput, size_t cbOutput, cose_errback *perr) { const EVP_CIPHER *pcipher = nullptr; EVP_CIPHER_CTX *ctx; int cbOut; byte rgbIV[16] = {0}; byte bCount = 1; size_t ib; byte rgbDigest[128 / 8]; int cbDigest = 0; byte rgbOut[16]; UNUSED(pcose); ctx = EVP_CIPHER_CTX_new(); CHECK_CONDITION(nullptr != ctx, COSE_ERR_OUT_OF_MEMORY); switch (cbitKey) { case 128: pcipher = EVP_aes_128_cbc(); break; case 256: pcipher = EVP_aes_256_cbc(); break; default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); } CHECK_CONDITION(cbPRK == cbitKey / 8, COSE_ERR_INVALID_PARAMETER); // Setup and run the OpenSSL code for (ib = 0; ib < cbOutput; ib += 16, bCount += 1) { size_t ib2; CHECK_CONDITION(EVP_EncryptInit_ex(ctx, pcipher, nullptr, pbPRK, rgbIV), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION( EVP_EncryptUpdate(ctx, rgbOut, &cbOut, rgbDigest, cbDigest), COSE_ERR_CRYPTO_FAIL); for (ib2 = 0; ib2 < cbInfo; ib2 += 16) { CHECK_CONDITION(EVP_EncryptUpdate(ctx, rgbOut, &cbOut, pbInfo + ib2, (int)COSE_MIN(16, cbInfo - ib2)), COSE_ERR_CRYPTO_FAIL); } CHECK_CONDITION(EVP_EncryptUpdate(ctx, rgbOut, &cbOut, &bCount, 1), COSE_ERR_CRYPTO_FAIL); if ((cbInfo + 1) % 16 != 0) { CHECK_CONDITION(EVP_EncryptUpdate(ctx, rgbOut, &cbOut, rgbIV, (int)16 - (cbInfo + 1) % 16), COSE_ERR_CRYPTO_FAIL); } memcpy(rgbDigest, rgbOut, cbOut); cbDigest = cbOut; memcpy(pbOutput + ib, rgbDigest, COSE_MIN(16, cbOutput - ib)); } EVP_CIPHER_CTX_free(ctx); return true; errorReturn: EVP_CIPHER_CTX_free(ctx); return false; } bool HKDF_Extract(COSE *pcose, const byte *pbKey, size_t cbKey, size_t cbitDigest, byte *rgbDigest, size_t *pcbDigest, CBOR_CONTEXT_COMMA cose_errback *perr) { #ifdef USE_CBOR_CONTEXT UNUSED(context); #endif byte rgbSalt[EVP_MAX_MD_SIZE] = {0}; int cbSalt; cn_cbor *cnSalt; HMAC_CTX *ctx; const EVP_MD *pmd = nullptr; unsigned int cbDigest; ctx = HMAC_CTX_new(); CHECK_CONDITION(nullptr != ctx, COSE_ERR_OUT_OF_MEMORY); if (0) { errorReturn: HMAC_CTX_free(ctx); return false; } switch (cbitDigest) { case 256: pmd = EVP_sha256(); cbSalt = 256 / 8; break; case 384: pmd = EVP_sha384(); cbSalt = 384 / 8; break; case 512: pmd = EVP_sha512(); cbSalt = 512 / 8; break; default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); break; } cnSalt = _COSE_map_get_int(pcose, COSE_Header_HKDF_salt, COSE_BOTH, perr); if (cnSalt != nullptr) { CHECK_CONDITION(HMAC_Init_ex(ctx, cnSalt->v.bytes, (int)cnSalt->length, pmd, nullptr), COSE_ERR_CRYPTO_FAIL); } else { CHECK_CONDITION(HMAC_Init_ex(ctx, rgbSalt, cbSalt, pmd, nullptr), COSE_ERR_CRYPTO_FAIL); } CHECK_CONDITION(HMAC_Update(ctx, pbKey, (int)cbKey), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION( HMAC_Final(ctx, rgbDigest, &cbDigest), COSE_ERR_CRYPTO_FAIL); *pcbDigest = cbDigest; HMAC_CTX_free(ctx); return true; } bool HKDF_Expand(COSE *pcose, size_t cbitDigest, const byte *pbPRK, size_t cbPRK, const byte *pbInfo, size_t cbInfo, byte *pbOutput, size_t cbOutput, cose_errback *perr) { HMAC_CTX *ctx; const EVP_MD *pmd = nullptr; size_t ib; unsigned int cbDigest = 0; byte rgbDigest[EVP_MAX_MD_SIZE]; byte bCount = 1; UNUSED(pcose); ctx = HMAC_CTX_new(); CHECK_CONDITION(ctx != nullptr, COSE_ERR_OUT_OF_MEMORY); if (0) { errorReturn: HMAC_CTX_free(ctx); return false; } switch (cbitDigest) { case 256: pmd = EVP_sha256(); break; case 384: pmd = EVP_sha384(); break; case 512: pmd = EVP_sha512(); break; default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); break; } for (ib = 0; ib < cbOutput; ib += cbDigest, bCount += 1) { CHECK_CONDITION(HMAC_Init_ex(ctx, pbPRK, (int)cbPRK, pmd, nullptr), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION( HMAC_Update(ctx, rgbDigest, cbDigest), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION(HMAC_Update(ctx, pbInfo, cbInfo), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION(HMAC_Update(ctx, &bCount, 1), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION( HMAC_Final(ctx, rgbDigest, &cbDigest), COSE_ERR_CRYPTO_FAIL); memcpy(pbOutput + ib, rgbDigest, COSE_MIN(cbDigest, cbOutput - ib)); } HMAC_CTX_free(ctx); return true; } bool HMAC_Create(COSE_MacMessage *pcose, int HSize, int TSize, const byte *pbKey, size_t cbKey, const byte *pbAuthData, size_t cbAuthData, cose_errback *perr) { HMAC_CTX *ctx; const EVP_MD *pmd = nullptr; byte *rgbOut = nullptr; unsigned int cbOut; cn_cbor *cbor = nullptr; #ifdef USE_CBOR_CONTEXT cn_cbor_context *context = &pcose->m_message.m_allocContext; #endif ctx = HMAC_CTX_new(); CHECK_CONDITION(nullptr != ctx, COSE_ERR_OUT_OF_MEMORY); if (0) { errorReturn: COSE_FREE(rgbOut, context); if (cbor != nullptr) { COSE_FREE(cbor, context); } HMAC_CTX_free(ctx); return false; } switch (HSize) { case 256: pmd = EVP_sha256(); break; case 384: pmd = EVP_sha384(); break; case 512: pmd = EVP_sha512(); break; default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); break; } rgbOut = (byte *)COSE_CALLOC(EVP_MAX_MD_SIZE, 1, context); CHECK_CONDITION(rgbOut != nullptr, COSE_ERR_OUT_OF_MEMORY); CHECK_CONDITION(HMAC_Init_ex(ctx, pbKey, (int)cbKey, pmd, nullptr), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION( HMAC_Update(ctx, pbAuthData, cbAuthData), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION(HMAC_Final(ctx, rgbOut, &cbOut), COSE_ERR_CRYPTO_FAIL); cbor = cn_cbor_data_create2( rgbOut, TSize / 8, 0, CBOR_CONTEXT_PARAM_COMMA nullptr); CHECK_CONDITION(cbor != nullptr, COSE_ERR_OUT_OF_MEMORY); CHECK_CONDITION(_COSE_array_replace(&pcose->m_message, cbor, INDEX_MAC_TAG, CBOR_CONTEXT_PARAM_COMMA nullptr), COSE_ERR_CBOR); HMAC_CTX_free(ctx); return true; } bool HMAC_Validate(COSE_MacMessage *pcose, int HSize, int TSize, const byte *pbKey, size_t cbKey, const byte *pbAuthData, size_t cbAuthData, cose_errback *perr) { HMAC_CTX *ctx = nullptr; const EVP_MD *pmd = nullptr; byte *rgbOut = nullptr; unsigned int cbOut = 0; bool f = false; #ifdef USE_CBOR_CONTEXT cn_cbor_context *context = &pcose->m_message.m_allocContext; #endif if (false) { errorReturn: if (rgbOut != nullptr) { COSE_FREE(rgbOut, context); } HMAC_CTX_free(ctx); return false; } ctx = HMAC_CTX_new(); CHECK_CONDITION(ctx != nullptr, COSE_ERR_OUT_OF_MEMORY); switch (HSize) { case 256: pmd = EVP_sha256(); break; case 384: pmd = EVP_sha384(); break; case 512: pmd = EVP_sha512(); break; default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); break; } rgbOut = (byte *)COSE_CALLOC(EVP_MAX_MD_SIZE, 1, context); CHECK_CONDITION(rgbOut != nullptr, COSE_ERR_OUT_OF_MEMORY); CHECK_CONDITION(HMAC_Init_ex(ctx, pbKey, (int)cbKey, pmd, nullptr), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION( HMAC_Update(ctx, pbAuthData, cbAuthData), COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION(HMAC_Final(ctx, rgbOut, &cbOut), COSE_ERR_CRYPTO_FAIL); cn_cbor *cn = _COSE_arrayget_int(&pcose->m_message, INDEX_MAC_TAG); CHECK_CONDITION(cn != nullptr, COSE_ERR_CBOR); if (cn->length > cbOut) { f = false; } else { for (unsigned int i = 0; i < (unsigned int)TSize / 8; i++) { f |= (cn->v.bytes[i] != rgbOut[i]); } } COSE_FREE(rgbOut, context); HMAC_CTX_free(ctx); return !f; } #define COSE_Key_EC_Curve -1 #define COSE_Key_EC_X -2 #define COSE_Key_EC_Y -3 #define COSE_Key_EC_d -4 EVP_PKEY *EVP_FromKey(COSE_KEY *pKey, CBOR_CONTEXT_COMMA cose_errback *perr) { if (pKey->m_opensslKey != nullptr) { return pKey->m_opensslKey; } if (false) { errorReturn: return nullptr; } cn_cbor *keyType = cn_cbor_mapget_int(pKey->m_cborKey, COSE_Key_Type); CHECK_CONDITION(keyType != NULL && keyType->type == CN_CBOR_UINT, COSE_ERR_INVALID_PARAMETER); switch (keyType->v.uint) { case COSE_Key_Type_EC2: { int cbSize; Safe_EC_KEY ecKey = ECKey_From(pKey, &cbSize, perr); CHECK_CONDITION(ecKey != nullptr, perr->err); Safe_EVP_PKEY evpKey = EVP_PKEY_new(); CHECK_CONDITION(evpKey != nullptr, COSE_ERR_OUT_OF_MEMORY); CHECK_CONDITION( EVP_PKEY_set1_EC_KEY(evpKey, ecKey) == 1, COSE_ERR_CRYPTO_FAIL); pKey->m_opensslKey = evpKey; EVP_PKEY_up_ref(pKey->m_opensslKey); return evpKey.Release(); } case COSE_Key_Type_OKP: { int type; cn_cbor *p = cn_cbor_mapget_int(pKey->m_cborKey, COSE_Key_OPK_Curve); CHECK_CONDITION(p != nullptr, COSE_ERR_INVALID_PARAMETER); switch (p->v.uint) { case COSE_Curve_Ed25519: type = EVP_PKEY_ED25519; break; case COSE_Curve_Ed448: type = EVP_PKEY_ED448; break; case COSE_Curve_X25519: type = EVP_PKEY_X25519; break; case COSE_Curve_X448: type = EVP_PKEY_X448; break; default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); } Safe_EVP_PKEY evpKey; p = cn_cbor_mapget_int(pKey->m_cborKey, COSE_Key_EC_d); if (p != nullptr) { evpKey = EVP_PKEY_new_raw_private_key( type, nullptr, p->v.bytes, p->length); CHECK_CONDITION(evpKey != nullptr, COSE_ERR_CRYPTO_FAIL); } else { p = cn_cbor_mapget_int(pKey->m_cborKey, COSE_Key_OPK_X); CHECK_CONDITION(p != nullptr, COSE_ERR_INVALID_PARAMETER); evpKey = EVP_PKEY_new_raw_public_key( type, nullptr, p->v.bytes, p->length); } pKey->m_opensslKey = evpKey; EVP_PKEY_up_ref(pKey->m_opensslKey); return evpKey.Release(); } default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); } } EC_KEY *ECKey_From(COSE_KEY *pKey, int *cbGroup, cose_errback *perr) { if (false) { errorReturn: return nullptr; } if (pKey->m_opensslKey != nullptr) { Safe_EC_KEY pKeyNew = EVP_PKEY_get1_EC_KEY(pKey->m_opensslKey); CHECK_CONDITION(pKeyNew != nullptr, COSE_ERR_INVALID_PARAMETER); int gid = EC_GROUP_get_curve_name(EC_KEY_get0_group(pKeyNew)); switch (gid) { case NID_X9_62_prime256v1: *cbGroup = 256 / 8; break; case NID_secp384r1: *cbGroup = 384 / 8; break; case NID_secp521r1: *cbGroup = (521 + 7) / 8; break; default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); } return pKeyNew.Release(); } byte rgbKey[512 + 1]; int cbKey; const cn_cbor *p; int nidGroup = -1; EC_POINT *pPoint = nullptr; Safe_EC_KEY pNewKey = EC_KEY_new(); CHECK_CONDITION(pNewKey != nullptr, COSE_ERR_OUT_OF_MEMORY); p = cn_cbor_mapget_int(pKey->m_cborKey, COSE_Key_EC_Curve); CHECK_CONDITION(p != nullptr, COSE_ERR_INVALID_PARAMETER); switch (p->v.sint) { case 1: // P-256 nidGroup = NID_X9_62_prime256v1; *cbGroup = 256 / 8; break; case 2: // P-384 nidGroup = NID_secp384r1; *cbGroup = 384 / 8; break; case 3: // P-521 nidGroup = NID_secp521r1; *cbGroup = (521 + 7) / 8; break; default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); } EC_GROUP *ecgroup = EC_GROUP_new_by_curve_name(nidGroup); CHECK_CONDITION(ecgroup != nullptr, COSE_ERR_INVALID_PARAMETER); CHECK_CONDITION( EC_KEY_set_group(pNewKey, ecgroup) == 1, COSE_ERR_CRYPTO_FAIL); p = cn_cbor_mapget_int(pKey->m_cborKey, COSE_Key_EC_X); CHECK_CONDITION((p != nullptr) && (p->type == CN_CBOR_BYTES), COSE_ERR_INVALID_PARAMETER); CHECK_CONDITION(p->length == (size_t)*cbGroup, COSE_ERR_INVALID_PARAMETER); memcpy(rgbKey + 1, p->v.str, p->length); p = cn_cbor_mapget_int(pKey->m_cborKey, COSE_Key_EC_Y); CHECK_CONDITION(p != nullptr, COSE_ERR_INVALID_PARAMETER); if (p->type == CN_CBOR_BYTES) { rgbKey[0] = POINT_CONVERSION_UNCOMPRESSED; cbKey = (*cbGroup * 2) + 1; CHECK_CONDITION( p->length == (size_t)*cbGroup, COSE_ERR_INVALID_PARAMETER); memcpy(rgbKey + p->length + 1, p->v.str, p->length); } else if (p->type == CN_CBOR_TRUE) { cbKey = (*cbGroup) + 1; rgbKey[0] = POINT_CONVERSION_COMPRESSED + 1; } else if (p->type == CN_CBOR_FALSE) { cbKey = (*cbGroup) + 1; rgbKey[0] = POINT_CONVERSION_COMPRESSED; } else { FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); } pPoint = EC_POINT_new(ecgroup); CHECK_CONDITION(pPoint != nullptr, COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION( EC_POINT_oct2point(ecgroup, pPoint, rgbKey, cbKey, nullptr) == 1, COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION( EC_KEY_set_public_key(pNewKey, pPoint) == 1, COSE_ERR_CRYPTO_FAIL); p = cn_cbor_mapget_int(pKey->m_cborKey, COSE_Key_EC_d); if (p != nullptr) { BIGNUM *pbn = BN_bin2bn(p->v.bytes, (int)p->length, nullptr); CHECK_CONDITION(pbn != nullptr, COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION( EC_KEY_set_private_key(pNewKey, pbn) == 1, COSE_ERR_CRYPTO_FAIL); } pKey->m_opensslKey = EVP_PKEY_new(); CHECK_CONDITION(pKey->m_opensslKey != nullptr, COSE_ERR_OUT_OF_MEMORY); CHECK_CONDITION(EVP_PKEY_set1_EC_KEY(pKey->m_opensslKey, pNewKey) == 1, COSE_ERR_CRYPTO_FAIL); return pNewKey.Release(); } cn_cbor *EC_ToCBOR(const EC_KEY *pKey, bool fUseCompressed, CBOR_CONTEXT_COMMA cose_errback *perr) { cn_cbor *pkey = nullptr; int cose_group; cn_cbor *p = nullptr; cn_cbor_errback cbor_error; byte *pbPoint = nullptr; size_t cbSize; byte *pbOut = nullptr; size_t cbX; const EC_POINT *pPoint = nullptr; const EC_GROUP *pgroup = EC_KEY_get0_group(pKey); CHECK_CONDITION(pgroup != nullptr, COSE_ERR_INVALID_PARAMETER); switch (EC_GROUP_get_curve_name(pgroup)) { case NID_X9_62_prime256v1: cose_group = 1; break; case NID_secp384r1: cose_group = 2; break; case NID_secp521r1: cose_group = 3; break; default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); } pkey = cn_cbor_map_create(CBOR_CONTEXT_PARAM_COMMA & cbor_error); CHECK_CONDITION_CBOR(pkey != nullptr, cbor_error); p = cn_cbor_int_create(cose_group, CBOR_CONTEXT_PARAM_COMMA & cbor_error); CHECK_CONDITION_CBOR(p != nullptr, cbor_error); CHECK_CONDITION_CBOR(cn_cbor_mapput_int(pkey, COSE_Key_EC_Curve, p, CBOR_CONTEXT_PARAM_COMMA & cbor_error), cbor_error); p = nullptr; pPoint = EC_KEY_get0_public_key(pKey); CHECK_CONDITION(pPoint != nullptr, COSE_ERR_INVALID_PARAMETER); if (fUseCompressed) { cbSize = EC_POINT_point2oct( pgroup, pPoint, POINT_CONVERSION_COMPRESSED, nullptr, 0, nullptr); CHECK_CONDITION(cbSize > 0, COSE_ERR_CRYPTO_FAIL); pbPoint = (byte *)COSE_CALLOC(cbSize, 1, context); CHECK_CONDITION(pbPoint != nullptr, COSE_ERR_OUT_OF_MEMORY); CHECK_CONDITION( EC_POINT_point2oct(pgroup, pPoint, POINT_CONVERSION_COMPRESSED, pbPoint, cbSize, nullptr) == cbSize, COSE_ERR_CRYPTO_FAIL); cbX = cbSize - 1; } else { cbSize = EC_POINT_point2oct( pgroup, pPoint, POINT_CONVERSION_UNCOMPRESSED, nullptr, 0, nullptr); CHECK_CONDITION(cbSize > 0, COSE_ERR_CRYPTO_FAIL); pbPoint = (byte *)COSE_CALLOC(cbSize, 1, context); CHECK_CONDITION(pbPoint != nullptr, COSE_ERR_OUT_OF_MEMORY); CHECK_CONDITION( EC_POINT_point2oct(pgroup, pPoint, POINT_CONVERSION_UNCOMPRESSED, pbPoint, cbSize, nullptr) == cbSize, COSE_ERR_CRYPTO_FAIL); cbX = cbSize / 2; } pbOut = (byte *)COSE_CALLOC((int)(cbX), 1, context); CHECK_CONDITION(pbOut != nullptr, COSE_ERR_OUT_OF_MEMORY); memcpy(pbOut, pbPoint + 1, (int)(cbX)); p = cn_cbor_data_create2( pbOut, (int)(cbX), 0, CBOR_CONTEXT_PARAM_COMMA & cbor_error); CHECK_CONDITION_CBOR(p != nullptr, cbor_error); pbOut = nullptr; CHECK_CONDITION_CBOR(cn_cbor_mapput_int(pkey, COSE_Key_EC_X, p, CBOR_CONTEXT_PARAM_COMMA & cbor_error), cbor_error); p = nullptr; if (fUseCompressed) { p = cn_cbor_bool_create( pbPoint[0] & 1, CBOR_CONTEXT_PARAM_COMMA & cbor_error); CHECK_CONDITION_CBOR(p != nullptr, cbor_error); CHECK_CONDITION_CBOR(cn_cbor_mapput_int(pkey, COSE_Key_EC_Y, p, CBOR_CONTEXT_PARAM_COMMA & cbor_error), cbor_error); p = nullptr; } else { pbOut = (byte *)COSE_CALLOC((int)(cbX), 1, context); CHECK_CONDITION(pbOut != nullptr, COSE_ERR_OUT_OF_MEMORY); memcpy(pbOut, pbPoint + cbSize / 2 + 1, (int)(cbX)); p = cn_cbor_data_create2( pbOut, (int)(cbX), 0, CBOR_CONTEXT_PARAM_COMMA & cbor_error); CHECK_CONDITION_CBOR(p != nullptr, cbor_error); pbOut = nullptr; CHECK_CONDITION_CBOR(cn_cbor_mapput_int(pkey, COSE_Key_EC_Y, p, CBOR_CONTEXT_PARAM_COMMA & cbor_error), cbor_error); p = nullptr; } p = cn_cbor_int_create( COSE_Key_Type_EC2, CBOR_CONTEXT_PARAM_COMMA & cbor_error); CHECK_CONDITION_CBOR(p != nullptr, cbor_error); CHECK_CONDITION_CBOR(cn_cbor_mapput_int(pkey, COSE_Key_Type, p, CBOR_CONTEXT_PARAM_COMMA & cbor_error), cbor_error); p = nullptr; returnHere: if (pbPoint != nullptr) { COSE_FREE(pbPoint, context); } if (pbOut != nullptr) { COSE_FREE(pbOut, context); } if (p != nullptr) { CN_CBOR_FREE(p, context); } return pkey; errorReturn: CN_CBOR_FREE(pkey, context); pkey = nullptr; goto returnHere; } cn_cbor *EVP_ToCBOR(EVP_PKEY *pKey, bool fCompressPoints, CBOR_CONTEXT_COMMA cose_errback *perr) { cn_cbor_errback cborErr; int type = EVP_PKEY_base_id(pKey); switch (type) { case EVP_PKEY_EC: return EC_ToCBOR(EVP_PKEY_get1_EC_KEY(pKey), fCompressPoints, CBOR_CONTEXT_PARAM_COMMA perr); case EVP_PKEY_X25519: case EVP_PKEY_X448: { cn_cbor *pkey = nullptr; cn_cbor *temp = nullptr; unsigned char *pbKey = nullptr; if (false) { errorReturn: if (pkey != nullptr) { CN_CBOR_FREE(pkey, context); } if (temp != nullptr) { CN_CBOR_FREE(temp, context); } if (pbKey != nullptr) { COSE_FREE(pbKey, context); } return nullptr; } pkey = cn_cbor_map_create(CBOR_CONTEXT_PARAM_COMMA & cborErr); CHECK_CONDITION_CBOR(pkey != nullptr, cborErr); temp = cn_cbor_int_create( COSE_Key_Type_OKP, CBOR_CONTEXT_PARAM_COMMA & cborErr); CHECK_CONDITION_CBOR(temp != nullptr, cborErr); CHECK_CONDITION_CBOR(cn_cbor_mapput_int(pkey, COSE_Key_Type, temp, CBOR_CONTEXT_PARAM_COMMA & cborErr), cborErr); temp = nullptr; temp = cn_cbor_int_create( type == EVP_PKEY_X25519 ? COSE_Curve_X25519 : COSE_Curve_X448, CBOR_CONTEXT_PARAM_COMMA & cborErr); CHECK_CONDITION_CBOR(temp != nullptr, cborErr); CHECK_CONDITION_CBOR(cn_cbor_mapput_int(pkey, COSE_Key_OPK_Curve, temp, CBOR_CONTEXT_PARAM_COMMA & cborErr), cborErr); temp = nullptr; size_t cbKey; CHECK_CONDITION( EVP_PKEY_get_raw_public_key(pKey, nullptr, &cbKey) == 1, COSE_ERR_CRYPTO_FAIL); pbKey = (unsigned char *)COSE_CALLOC(cbKey, 1, context); CHECK_CONDITION(pbKey != nullptr, COSE_ERR_OUT_OF_MEMORY); CHECK_CONDITION( EVP_PKEY_get_raw_public_key(pKey, pbKey, &cbKey) == 1, COSE_ERR_CRYPTO_FAIL); temp = cn_cbor_data_create2( pbKey, cbKey, 0, CBOR_CONTEXT_PARAM_COMMA & cborErr); CHECK_CONDITION(temp != nullptr, COSE_ERR_OUT_OF_MEMORY); pbKey = nullptr; CHECK_CONDITION_CBOR(cn_cbor_mapput_int(pkey, COSE_Key_OPK_X, temp, CBOR_CONTEXT_PARAM_COMMA & cborErr), cborErr); temp = nullptr; return pkey; } break; default: perr->err = COSE_ERR_INVALID_PARAMETER; return nullptr; } } #if false COSE_KEY *EC_FromKey(EC_KEY *pKey, bool fUseCompressed, CBOR_CONTEXT_COMMA cose_errback *perr) { COSE_KEY *coseKey = nullptr; cn_cbor *pkey = EC_ToCBOR(pKey, fUseCompressed, CBOR_CONTEXT_PARAM_COMMA perr); if (pkey == nullptr) { return nullptr; } Safe_EVP_PKEY evpKey = EVP_PKEY_new(); CHECK_CONDITION(evpKey != nullptr, COSE_ERR_OUT_OF_MEMORY); CHECK_CONDITION(EVP_PKEY_set1_EC_KEY(evpKey, pKey) == 1, COSE_ERR_CRYPTO_FAIL); coseKey = (COSE_KEY *)COSE_KEY_FromEVP(evpKey, pkey, CBOR_CONTEXT_PARAM_COMMA perr); CHECK_CONDITION(coseKey != nullptr, COSE_ERR_OUT_OF_MEMORY); pkey = nullptr; returnHere: if (pkey != nullptr) { CN_CBOR_FREE(pkey, context); } return coseKey; errorReturn: goto returnHere; } #endif bool ECDSA_Sign(COSE *pSigner, int index, COSE_KEY *pKey, int cbitDigest, const byte *rgbToSign, size_t cbToSign, cose_errback *perr) { EC_KEY *eckey = nullptr; byte rgbDigest[EVP_MAX_MD_SIZE]; unsigned int cbDigest = sizeof(rgbDigest); byte *pbSig = nullptr; const EVP_MD *digest; #ifdef USE_CBOR_CONTEXT cn_cbor_context *context = &pSigner->m_allocContext; #endif cn_cbor *p = nullptr; ECDSA_SIG *psig = nullptr; cn_cbor_errback cbor_error; int cbR; byte rgbSig[66]; int cb; eckey = ECKey_From(pKey, &cbR, perr); if (eckey == nullptr) { errorReturn: if (pbSig != nullptr) { COSE_FREE(pbSig, context); } if (p != nullptr) { CN_CBOR_FREE(p, context); } if (eckey != nullptr) { EC_KEY_free(eckey); } return false; } switch (cbitDigest) { case 256: digest = EVP_sha256(); break; case 512: digest = EVP_sha512(); break; case 384: digest = EVP_sha384(); break; default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); } EVP_Digest(rgbToSign, cbToSign, rgbDigest, &cbDigest, digest, nullptr); psig = ECDSA_do_sign(rgbDigest, cbDigest, eckey); CHECK_CONDITION(psig != nullptr, COSE_ERR_CRYPTO_FAIL); pbSig = (byte *)COSE_CALLOC(cbR, 2, context); CHECK_CONDITION(pbSig != nullptr, COSE_ERR_OUT_OF_MEMORY); const BIGNUM *r; const BIGNUM *s; ECDSA_SIG_get0(psig, &r, &s); cb = BN_bn2bin(r, rgbSig); CHECK_CONDITION(cb <= cbR, COSE_ERR_INVALID_PARAMETER); memcpy(pbSig + cbR - cb, rgbSig, cb); cb = BN_bn2bin(s, rgbSig); CHECK_CONDITION(cb <= cbR, COSE_ERR_INVALID_PARAMETER); memcpy(pbSig + 2 * cbR - cb, rgbSig, cb); p = cn_cbor_data_create2( pbSig, cbR * 2, 0, CBOR_CONTEXT_PARAM_COMMA & cbor_error); CHECK_CONDITION_CBOR(p != nullptr, cbor_error); CHECK_CONDITION(_COSE_array_replace( pSigner, p, index, CBOR_CONTEXT_PARAM_COMMA nullptr), COSE_ERR_CBOR); pbSig = nullptr; if (eckey != nullptr) { EC_KEY_free(eckey); } return true; } bool ECDSA_Verify(COSE *pSigner, int index, COSE_KEY *pKey, int cbitDigest, const byte *rgbToSign, size_t cbToSign, cose_errback *perr) { EC_KEY *eckey = nullptr; byte rgbDigest[EVP_MAX_MD_SIZE]; unsigned int cbDigest = sizeof(rgbDigest); const EVP_MD *digest; #ifdef USE_CBOR_CONTEXT cn_cbor_context *context = &pSigner->m_allocContext; #endif cn_cbor *p = nullptr; ECDSA_SIG *sig = nullptr; int cbR; cn_cbor *pSig; size_t cbSignature; BIGNUM *r, *s; eckey = ECKey_From(pKey, &cbR, perr); if (eckey == nullptr) { errorReturn: if (p != nullptr) { CN_CBOR_FREE(p, context); } if (eckey != nullptr) { EC_KEY_free(eckey); } if (sig != nullptr) { ECDSA_SIG_free(sig); } return false; } switch (cbitDigest) { case 256: digest = EVP_sha256(); break; case 512: digest = EVP_sha512(); break; case 384: digest = EVP_sha384(); break; default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); } EVP_Digest(rgbToSign, cbToSign, rgbDigest, &cbDigest, digest, nullptr); pSig = _COSE_arrayget_int(pSigner, index); CHECK_CONDITION(pSig != nullptr, COSE_ERR_INVALID_PARAMETER); cbSignature = pSig->length; CHECK_CONDITION(cbSignature / 2 == (size_t)cbR, COSE_ERR_INVALID_PARAMETER); r = BN_bin2bn(pSig->v.bytes, (int)cbSignature / 2, nullptr); CHECK_CONDITION(nullptr != r, COSE_ERR_OUT_OF_MEMORY); s = BN_bin2bn( pSig->v.bytes + cbSignature / 2, (int)cbSignature / 2, nullptr); CHECK_CONDITION(nullptr != s, COSE_ERR_OUT_OF_MEMORY); sig = ECDSA_SIG_new(); CHECK_CONDITION(sig != nullptr, COSE_ERR_OUT_OF_MEMORY); ECDSA_SIG_set0(sig, r, s); CHECK_CONDITION(ECDSA_do_verify(rgbDigest, cbDigest, sig, eckey) == 1, COSE_ERR_CRYPTO_FAIL); if (eckey != nullptr) { EC_KEY_free(eckey); } if (sig != nullptr) { ECDSA_SIG_free(sig); } return true; } #ifdef USE_EDDSA bool EdDSA_Sign(COSE *pSigner, int index, COSE_KEY *pKeyIn, const byte *rgbToSign, size_t cbToSign, cose_errback *perr) { #ifdef USE_CBOR_CONTEXT cn_cbor_context *context = &pSigner->m_allocContext; #endif cn_cbor *p; cn_cbor_errback cbor_error; EVP_PKEY_CTX *keyCtx = nullptr; EVP_MD_CTX *mdCtx = nullptr; Safe_EVP_PKEY pkey; byte *pbSig = nullptr; int cbSig; p = cn_cbor_mapget_int(pKeyIn->m_cborKey, COSE_Key_OPK_Curve); if (p == nullptr) { errorReturn: if (mdCtx != nullptr) { EVP_MD_CTX_free(mdCtx); } if (keyCtx != nullptr) { EVP_PKEY_CTX_free(keyCtx); } if (pbSig != nullptr) { COSE_FREE(pbSig, context); } return false; } int type; switch (p->v.uint) { case COSE_Curve_Ed25519: type = EVP_PKEY_ED25519; cbSig = 32 * 2; break; case COSE_Curve_Ed448: type = EVP_PKEY_ED448; cbSig = 64 * 2; break; default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); } pkey = EVP_FromKey(pKeyIn, CBOR_CONTEXT_PARAM_COMMA perr); if (pkey == nullptr) { goto errorReturn; } keyCtx = EVP_PKEY_CTX_new_id(type, nullptr); CHECK_CONDITION(keyCtx != nullptr, COSE_ERR_OUT_OF_MEMORY); mdCtx = EVP_MD_CTX_new(); CHECK_CONDITION(mdCtx != nullptr, COSE_ERR_OUT_OF_MEMORY); CHECK_CONDITION( EVP_DigestSignInit(mdCtx, &keyCtx, nullptr, nullptr, pkey) == 1, COSE_ERR_CRYPTO_FAIL); keyCtx = nullptr; pbSig = (byte *)COSE_CALLOC(cbSig, 1, context); CHECK_CONDITION(pbSig != nullptr, COSE_ERR_OUT_OF_MEMORY); size_t cb2 = cbSig; CHECK_CONDITION( EVP_DigestSign(mdCtx, pbSig, &cb2, rgbToSign, cbToSign) == 1, COSE_ERR_CRYPTO_FAIL); p = cn_cbor_data_create2( pbSig, (int)cb2, 0, CBOR_CONTEXT_PARAM_COMMA & cbor_error); CHECK_CONDITION(p != nullptr, COSE_ERR_OUT_OF_MEMORY); pbSig = nullptr; CHECK_CONDITION(_COSE_array_replace( pSigner, p, index, CBOR_CONTEXT_PARAM_COMMA nullptr), COSE_ERR_CBOR); if (mdCtx != nullptr) { EVP_MD_CTX_free(mdCtx); } if (keyCtx != nullptr) { EVP_PKEY_CTX_free(keyCtx); } if (pbSig != nullptr) { COSE_FREE(pbSig, context); } return true; } bool EdDSA_Verify(COSE *pSigner, int index, COSE_KEY *pKey, const byte *rgbToSign, size_t cbToSign, cose_errback *perr) { #ifdef USE_CBOR_CONTEXT cn_cbor_context *context = &pSigner->m_allocContext; #endif cn_cbor *pSig; Safe_EVP_PKEY pkey = nullptr; EVP_MD_CTX *pmdCtx = nullptr; cn_cbor *p = cn_cbor_mapget_int(pKey->m_cborKey, COSE_Key_OPK_Curve); if (p == nullptr) { errorReturn: if (pmdCtx != nullptr) { EVP_MD_CTX_free(pmdCtx); } return false; } int type; switch (p->v.uint) { case COSE_Curve_Ed25519: type = EVP_PKEY_ED25519; break; case COSE_Curve_Ed448: type = EVP_PKEY_ED448; break; default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); } pkey = EVP_FromKey(pKey, CBOR_CONTEXT_PARAM_COMMA perr); if (pkey == nullptr) { goto errorReturn; } pSig = _COSE_arrayget_int(pSigner, index); CHECK_CONDITION(pSig != nullptr, COSE_ERR_INVALID_PARAMETER); pmdCtx = EVP_MD_CTX_new(); EVP_PKEY_CTX *keyCtx = EVP_PKEY_CTX_new_id(type, nullptr); CHECK_CONDITION( EVP_DigestVerifyInit(pmdCtx, &keyCtx, nullptr, nullptr, pkey) == 1, COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION(EVP_DigestVerify(pmdCtx, pSig->v.bytes, pSig->length, rgbToSign, cbToSign) == 1, COSE_ERR_CRYPTO_FAIL); if (pmdCtx != nullptr) { EVP_MD_CTX_free(pmdCtx); } return true; } #endif bool AES_KW_Decrypt(COSE_Enveloped *pcose, const byte *pbKeyIn, size_t cbitKey, const byte *pbCipherText, size_t cbCipherText, byte *pbKeyOut, size_t *pcbKeyOut, cose_errback *perr) { byte rgbOut[512 / 8]; AES_KEY key; UNUSED(pcose); CHECK_CONDITION(AES_set_decrypt_key(pbKeyIn, (int)cbitKey, &key) == 0, COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION( AES_unwrap_key(&key, nullptr, rgbOut, pbCipherText, (int)cbCipherText), COSE_ERR_CRYPTO_FAIL); memcpy(pbKeyOut, rgbOut, cbCipherText - 8); *pcbKeyOut = (int)(cbCipherText - 8); return true; errorReturn: return false; } bool AES_KW_Encrypt(COSE_RecipientInfo *pcose, const byte *pbKeyIn, int cbitKey, const byte *pbContent, int cbContent, cose_errback *perr) { byte *pbOut = nullptr; AES_KEY key; #ifdef USE_CBOR_CONTEXT cn_cbor_context *context = &pcose->m_encrypt.m_message.m_allocContext; #endif cn_cbor *cnTmp = nullptr; pbOut = (byte *)COSE_CALLOC(cbContent + 8, 1, context); CHECK_CONDITION(pbOut != nullptr, COSE_ERR_OUT_OF_MEMORY); CHECK_CONDITION( AES_set_encrypt_key(pbKeyIn, cbitKey, &key) == 0, COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION(AES_wrap_key(&key, nullptr, pbOut, pbContent, cbContent), COSE_ERR_CRYPTO_FAIL); cnTmp = cn_cbor_data_create2( pbOut, (int)cbContent + 8, 0, CBOR_CONTEXT_PARAM_COMMA nullptr); CHECK_CONDITION(cnTmp != nullptr, COSE_ERR_CBOR); pbOut = nullptr; CHECK_CONDITION(_COSE_array_replace(&pcose->m_encrypt.m_message, cnTmp, INDEX_BODY, CBOR_CONTEXT_PARAM_COMMA nullptr), COSE_ERR_CBOR); cnTmp = nullptr; return true; errorReturn: COSE_FREE(cnTmp, context); if (pbOut != nullptr) { COSE_FREE(pbOut, context); } return false; } void rand_bytes(byte *pb, size_t cb) { RAND_bytes(pb, (int)cb); } /*! * * @param[in] pRecipent Pointer to the message object * @param[in] ppKeyPrivate Address of key with private portion * @param[in] pKeyPublic Address of the key w/o a private portion * @param[in/out] ppbSecret pointer to buffer to hold the computed secret * @param[in/out] pcbSecret size of the computed secret * @param[in] context cbor allocation context structure * @param[out] perr location to return error information * @returns success of the function */ bool ECDH_ComputeSecret(COSE *pRecipient, COSE_KEY **ppKeyPrivate, COSE_KEY *pKeyPublic, byte **ppbSecret, size_t *pcbSecret, CBOR_CONTEXT_COMMA cose_errback *perr) { EVP_PKEY *evpPublic = nullptr; EVP_PKEY *evpPrivate = nullptr; EVP_PKEY_CTX *ctx = nullptr; if (false) { errorReturn: if (ctx != nullptr) { EVP_PKEY_CTX_free(ctx); } if (evpPublic != nullptr) { EVP_PKEY_free(evpPublic); } return false; } evpPublic = EVP_FromKey(pKeyPublic, CBOR_CONTEXT_PARAM_COMMA perr); if (evpPublic == nullptr) { goto errorReturn; } bool fCompressPoints = true; if (*ppKeyPrivate == nullptr) { // Generate an ephemeral key for the key agreement. int type = EVP_PKEY_base_id(evpPublic); cn_cbor *pCompress = _COSE_map_get_int( pRecipient, COSE_Header_UseCompressedECDH, COSE_DONT_SEND, perr); if (pCompress == nullptr) { fCompressPoints = true; } else { fCompressPoints = (pCompress->type == CN_CBOR_TRUE); } switch (type) { case EVP_PKEY_EC: { EC_KEY *peckeyPrivate = EC_KEY_new(); EC_KEY *peckeyPublic = EVP_PKEY_get0_EC_KEY(evpPublic); EC_KEY_set_group( peckeyPrivate, EC_KEY_get0_group(peckeyPublic)); CHECK_CONDITION(EC_KEY_generate_key(peckeyPrivate) == 1, COSE_ERR_CRYPTO_FAIL); evpPrivate = EVP_PKEY_new(); EVP_PKEY_set1_EC_KEY(evpPrivate, peckeyPrivate); } break; case EVP_PKEY_X25519: case EVP_PKEY_X448: { EVP_PKEY_CTX *ctx2 = EVP_PKEY_CTX_new_id(type, nullptr); CHECK_CONDITION(ctx2 != nullptr, COSE_ERR_OUT_OF_MEMORY); // CHECK_CONDITION( // EVP_PKEY_paramgen_init(ctx2) == 1, COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION( EVP_PKEY_keygen_init(ctx2) == 1, COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION( EVP_PKEY_keygen(ctx2, &evpPrivate), COSE_ERR_CRYPTO_FAIL); } break; default: FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER); } cn_cbor *pcborPrivate = EVP_ToCBOR( evpPrivate, fCompressPoints, CBOR_CONTEXT_PARAM_COMMA perr); if (pcborPrivate == nullptr) { goto errorReturn; } COSE_KEY *pPrivateKey = (COSE_KEY *)COSE_KEY_FromEVP( evpPrivate, pcborPrivate, CBOR_CONTEXT_PARAM_COMMA perr); if (pPrivateKey == nullptr) { CN_CBOR_FREE(pcborPrivate, context); goto errorReturn; } *ppKeyPrivate = pPrivateKey; } else { // Use the passed in sender key evpPrivate = EVP_FromKey(*ppKeyPrivate, CBOR_CONTEXT_PARAM_COMMA perr); if (evpPrivate == nullptr) { goto errorReturn; } } ctx = EVP_PKEY_CTX_new(evpPrivate, nullptr); CHECK_CONDITION(ctx != nullptr, COSE_ERR_OUT_OF_MEMORY); CHECK_CONDITION(EVP_PKEY_derive_init(ctx) > 0, COSE_ERR_CRYPTO_FAIL); CHECK_CONDITION( EVP_PKEY_derive_set_peer(ctx, evpPublic) > 0, COSE_ERR_CRYPTO_FAIL); size_t skeylen; CHECK_CONDITION( EVP_PKEY_derive(ctx, nullptr, &skeylen) > 0, COSE_ERR_CRYPTO_FAIL); byte *skey = static_cast<byte *>(COSE_CALLOC(skeylen, 1, context)); CHECK_CONDITION(skey != nullptr, COSE_ERR_OUT_OF_MEMORY); CHECK_CONDITION( EVP_PKEY_derive(ctx, skey, &skeylen) > 0, COSE_ERR_CRYPTO_FAIL); if (ctx != nullptr) { EVP_PKEY_CTX_free(ctx); } *ppbSecret = skey; *pcbSecret = skeylen; return true; } #endif // COSE_C_USE_OPENSSL
52,483
26,241
// Generated from /POI/java/org/apache/poi/sl/usermodel/SlideShowFactory.java #include <org/apache/poi/sl/usermodel/SlideShowFactory.hpp> #include <java/io/File.hpp> #include <java/io/FileNotFoundException.hpp> #include <java/io/IOException.hpp> #include <java/io/InputStream.hpp> #include <java/io/Serializable.hpp> #include <java/lang/ArrayStoreException.hpp> #include <java/lang/Boolean.hpp> #include <java/lang/Class.hpp> #include <java/lang/ClassCastException.hpp> #include <java/lang/ClassLoader.hpp> #include <java/lang/Exception.hpp> #include <java/lang/IllegalArgumentException.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/Object.hpp> #include <java/lang/RuntimeException.hpp> #include <java/lang/String.hpp> #include <java/lang/Thread.hpp> #include <java/lang/Throwable.hpp> #include <java/lang/reflect/AnnotatedElement.hpp> #include <java/lang/reflect/GenericDeclaration.hpp> #include <java/lang/reflect/InvocationTargetException.hpp> #include <java/lang/reflect/Method.hpp> #include <java/lang/reflect/Type.hpp> #include <org/apache/poi/EncryptedDocumentException.hpp> #include <org/apache/poi/OldFileFormatException.hpp> #include <org/apache/poi/hssf/record/crypto/Biff8EncryptionKey.hpp> #include <org/apache/poi/poifs/crypt/Decryptor.hpp> #include <org/apache/poi/poifs/filesystem/DirectoryNode.hpp> #include <org/apache/poi/poifs/filesystem/DocumentFactoryHelper.hpp> #include <org/apache/poi/poifs/filesystem/FileMagic.hpp> #include <org/apache/poi/poifs/filesystem/NPOIFSFileSystem.hpp> #include <org/apache/poi/poifs/filesystem/OfficeXmlFileException.hpp> #include <org/apache/poi/sl/usermodel/SlideShow.hpp> #include <org/apache/poi/util/IOUtils.hpp> #include <SubArray.hpp> #include <ObjectArray.hpp> template<typename ComponentType, typename... Bases> struct SubArray; namespace java { namespace io { typedef ::SubArray< ::java::io::Serializable, ::java::lang::ObjectArray > SerializableArray; } // io namespace lang { namespace reflect { typedef ::SubArray< ::java::lang::reflect::AnnotatedElement, ::java::lang::ObjectArray > AnnotatedElementArray; typedef ::SubArray< ::java::lang::reflect::GenericDeclaration, ::java::lang::ObjectArray, AnnotatedElementArray > GenericDeclarationArray; typedef ::SubArray< ::java::lang::reflect::Type, ::java::lang::ObjectArray > TypeArray; } // reflect typedef ::SubArray< ::java::lang::Class, ObjectArray, ::java::io::SerializableArray, ::java::lang::reflect::GenericDeclarationArray, ::java::lang::reflect::TypeArray, ::java::lang::reflect::AnnotatedElementArray > ClassArray; } // lang } // java template<typename T, typename U> static T java_cast(U* u) { if(!u) return static_cast<T>(nullptr); auto t = dynamic_cast<T>(u); if(!t) throw new ::java::lang::ClassCastException(); return t; } template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } namespace { template<typename F> struct finally_ { finally_(F f) : f(f), moved(false) { } finally_(finally_ &&x) : f(x.f), moved(false) { x.moved = true; } ~finally_() { if(!moved) f(); } private: finally_(const finally_&); finally_& operator=(const finally_&); F f; bool moved; }; template<typename F> finally_<F> finally(F f) { return finally_<F>(f); } } poi::sl::usermodel::SlideShowFactory::SlideShowFactory(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::sl::usermodel::SlideShowFactory::SlideShowFactory() : SlideShowFactory(*static_cast< ::default_init_tag* >(0)) { ctor(); } poi::sl::usermodel::SlideShow* poi::sl::usermodel::SlideShowFactory::create(::poi::poifs::filesystem::NPOIFSFileSystem* fs) /* throws(IOException) */ { clinit(); return create(fs, static_cast< ::java::lang::String* >(nullptr)); } poi::sl::usermodel::SlideShow* poi::sl::usermodel::SlideShowFactory::create(::poi::poifs::filesystem::NPOIFSFileSystem* fs, ::java::lang::String* password) /* throws(IOException) */ { clinit(); auto root = npc(fs)->getRoot(); if(npc(root)->hasEntry(::poi::poifs::crypt::Decryptor::DEFAULT_POIFS_ENTRY())) { ::java::io::InputStream* stream = nullptr; { auto finally0 = finally([&] { ::poi::util::IOUtils::closeQuietly(stream); }); { stream = ::poi::poifs::filesystem::DocumentFactoryHelper::getDecryptedStream(fs, password); return createXSLFSlideShow(new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(stream)})); } } } auto passwordSet = false; if(password != nullptr) { ::poi::hssf::record::crypto::Biff8EncryptionKey::setCurrentUserPassword(password); passwordSet = true; } { auto finally1 = finally([&] { if(passwordSet) { ::poi::hssf::record::crypto::Biff8EncryptionKey::setCurrentUserPassword(nullptr); } }); { return createHSLFSlideShow(new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(fs)})); } } } poi::sl::usermodel::SlideShow* poi::sl::usermodel::SlideShowFactory::create(::java::io::InputStream* inp) /* throws(IOException, EncryptedDocumentException) */ { clinit(); return create(inp, static_cast< ::java::lang::String* >(nullptr)); } poi::sl::usermodel::SlideShow* poi::sl::usermodel::SlideShowFactory::create(::java::io::InputStream* inp, ::java::lang::String* password) /* throws(IOException, EncryptedDocumentException) */ { clinit(); auto is = ::poi::poifs::filesystem::FileMagic::prepareToCheckMagic(inp); auto fm = ::poi::poifs::filesystem::FileMagic::valueOf(is); { ::poi::poifs::filesystem::NPOIFSFileSystem* fs; { auto v = fm; if((v == ::poi::poifs::filesystem::FileMagic::OLE2)) { auto fs = new ::poi::poifs::filesystem::NPOIFSFileSystem(is); return create(fs, password); } if((v == ::poi::poifs::filesystem::FileMagic::OOXML)) { return createXSLFSlideShow(new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(is)})); } if((((v != ::poi::poifs::filesystem::FileMagic::OLE2) && (v != ::poi::poifs::filesystem::FileMagic::OOXML)))) { throw new ::java::lang::IllegalArgumentException(u"Your InputStream was neither an OLE2 stream, nor an OOXML stream"_j); } end_switch0:; } } } poi::sl::usermodel::SlideShow* poi::sl::usermodel::SlideShowFactory::create(::java::io::File* file) /* throws(IOException, EncryptedDocumentException) */ { clinit(); return create(file, static_cast< ::java::lang::String* >(nullptr)); } poi::sl::usermodel::SlideShow* poi::sl::usermodel::SlideShowFactory::create(::java::io::File* file, ::java::lang::String* password) /* throws(IOException, EncryptedDocumentException) */ { clinit(); return create(file, password, false); } poi::sl::usermodel::SlideShow* poi::sl::usermodel::SlideShowFactory::create(::java::io::File* file, ::java::lang::String* password, bool readOnly) /* throws(IOException, EncryptedDocumentException) */ { clinit(); if(!npc(file)->exists()) { throw new ::java::io::FileNotFoundException(npc(file)->toString()); } ::poi::poifs::filesystem::NPOIFSFileSystem* fs = nullptr; try { fs = new ::poi::poifs::filesystem::NPOIFSFileSystem(file, readOnly); return create(fs, password); } catch (::poi::poifs::filesystem::OfficeXmlFileException* e) { ::poi::util::IOUtils::closeQuietly(fs); return createXSLFSlideShow(new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(file), static_cast< ::java::lang::Object* >(::java::lang::Boolean::valueOf(readOnly))})); } catch (::java::lang::RuntimeException* e) { ::poi::util::IOUtils::closeQuietly(fs); throw e; } } poi::sl::usermodel::SlideShow* poi::sl::usermodel::SlideShowFactory::createHSLFSlideShow(::java::lang::ObjectArray*/*...*/ args) /* throws(IOException, EncryptedDocumentException) */ { clinit(); return createSlideShow(u"org.apache.poi.hslf.usermodel.HSLFSlideShowFactory"_j, args); } poi::sl::usermodel::SlideShow* poi::sl::usermodel::SlideShowFactory::createXSLFSlideShow(::java::lang::ObjectArray*/*...*/ args) /* throws(IOException, EncryptedDocumentException) */ { clinit(); return createSlideShow(u"org.apache.poi.xslf.usermodel.XSLFSlideShowFactory"_j, args); } poi::sl::usermodel::SlideShow* poi::sl::usermodel::SlideShowFactory::createSlideShow(::java::lang::String* factoryClass, ::java::lang::ObjectArray* args) /* throws(IOException, EncryptedDocumentException) */ { clinit(); try { auto clazz = npc(npc(::java::lang::Thread::currentThread())->getContextClassLoader())->loadClass(factoryClass); auto argsClz = new ::java::lang::ClassArray(npc(args)->length); auto i = int32_t(0); for(auto o : *npc(args)) { auto c = npc(o)->getClass(); if(npc(::java::lang::Boolean::class_())->isAssignableFrom(c)) { c = ::java::lang::Boolean::TYPE(); } else if(npc(::java::io::InputStream::class_())->isAssignableFrom(c)) { c = ::java::io::InputStream::class_(); } argsClz->set(i++, c); } auto m = npc(clazz)->getMethod(u"createSlideShow"_j, argsClz); return java_cast< SlideShow* >(npc(m)->invoke(nullptr, args)); } catch (::java::lang::reflect::InvocationTargetException* e) { auto t = npc(e)->getCause(); if(dynamic_cast< ::java::io::IOException* >(t) != nullptr) { throw java_cast< ::java::io::IOException* >(t); } else if(dynamic_cast< ::poi::EncryptedDocumentException* >(t) != nullptr) { throw java_cast< ::poi::EncryptedDocumentException* >(t); } else if(dynamic_cast< ::poi::OldFileFormatException* >(t) != nullptr) { throw java_cast< ::poi::OldFileFormatException* >(t); } else { throw new ::java::io::IOException(t); } } catch (::java::lang::Exception* e) { throw new ::java::io::IOException(static_cast< ::java::lang::Throwable* >(e)); } } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::sl::usermodel::SlideShowFactory::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.sl.usermodel.SlideShowFactory", 44); return c; } java::lang::Class* poi::sl::usermodel::SlideShowFactory::getClass0() { return class_(); }
10,756
3,613
#ifndef _BASE_ #define _BASE_ class Base { public: virtual int fcn(); }; class D1 : public Base { public: int fcn(int); virtual void f2(); }; class D2 : public D1 { public: int fcn(int); int fcn(); void f2(); }; #endif
247
103
//----------------------------------------------------------------------------- // Created on: 11 June 2013 //----------------------------------------------------------------------------- // Copyright (c) 2013-present, Sergey Slyadnev // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the copyright holder(s) nor the // names of all 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 AUTHORS 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. //----------------------------------------------------------------------------- // Windows includes #include <windows.h> // Own include #include <asiTestEngine_Launcher.h> // asiTestEngine includes #include <asiTestEngine_DescriptionProc.h> #include <asiTestEngine_ReportRenderer.h> #include <asiTestEngine_ReportStyleFactory.h> // asiAlgo includes #include <asiAlgo_TimeStamp.h> #include <asiAlgo_Utils.h> // STD includes #include <fstream> //! Adds the passed Test Case Launcher to the internal collection. //! \param CaseLauncher [in] Test Case Launcher to add. //! \return this for subsequent streaming. asiTestEngine_Launcher& asiTestEngine_Launcher::operator<<(const Handle(asiTestEngine_CaseLauncherAPI)& CaseLauncher) { m_launchers.push_back(CaseLauncher); return *this; } //! Launches all managed Test Cases. //! \param out [in, optional] output stream. //! \return true if all Cases have succeeded, false -- otherwise. bool asiTestEngine_Launcher::Launch(std::ostream* out) const { /* ============================== * Launch Test Cases one by one * ============================== */ bool isOk = true; int numTotal = 0, numFailed = 0; for ( int l = 0; l < (int) m_launchers.size(); ++l ) { const Handle(asiTestEngine_CaseLauncherAPI)& CaseLauncher = m_launchers.at(l); const bool nextOk = CaseLauncher->Launch(); // Put message to output stream if ( out ) { *out << "\tCase " << CaseLauncher->CaseID() << ": " << (nextOk ? "Ok" : "Failed"); *out << "; (Total / Failed) = (" << CaseLauncher->NumberOfExecuted() << " / " << CaseLauncher->NumberOfFailed() << ")\n"; } numTotal += CaseLauncher->NumberOfExecuted(); numFailed += CaseLauncher->NumberOfFailed(); if ( !nextOk && isOk ) isOk = false; } if ( out ) { *out << "\t***\n"; *out << "\tTotal executed: " << numTotal << "\n"; *out << "\tTotal failed: " << numFailed << "\n"; } /* ================ * Prepare report * ================ */ if ( out ) *out << "\t***\n"; if ( this->generateReport(out) ) { if ( out ) *out << "\tReport generation succeeded\n"; } else { if ( out ) *out << "\tReport generation failed (!!!)\n"; } return isOk; } //! Generates HTML report for the Test Cases identified by the managed //! Launchers. //! \param out [in] output stream. //! \return true in case of success, false -- otherwise. bool asiTestEngine_Launcher::generateReport(std::ostream* out) const { /* =========================== * Render header information * =========================== */ Handle(asiTestEngine_ReportRenderer) Rdr = new asiTestEngine_ReportRenderer; // Global style for HTML body asiTestEngine_ReportStyle BodyStyle; BodyStyle.SetFontFamily("Verdana"); // Global style for TD elements asiTestEngine_ReportStyle CellStyle; CellStyle.SetFontSize(11); // Global style for header cells asiTestEngine_ReportStyle HCellStyle; HCellStyle.SetBgColor( asiTestEngine_ReportStyle::Color(215, 215, 200) ); // Global style for TD elements for "good" results asiTestEngine_ReportStyle GoodCellStyle; GoodCellStyle.SetBgColor( asiTestEngine_ReportStyle::Color(180, 220, 25) ); // Global style for TD elements for "bad" results asiTestEngine_ReportStyle BadCellStyle; BadCellStyle.SetBgColor( asiTestEngine_ReportStyle::Color(255, 0, 0) ); // Global style for tables asiTestEngine_ReportStyle TableStyle; TableStyle.SetBorder(1); TableStyle.SetPadding(5); // Generate HTML heading section Rdr->AddDoctype() ->StartHtml() ->StartHeader() ->AddMeta() ->StartStyle() ->AddClass("body_class", BodyStyle) ->AddClass("table_class", TableStyle) ->AddClass("cell_class", CellStyle) ->AddClass("good_cell_class", GoodCellStyle) ->AddClass("bad_cell_class", BadCellStyle) ->AddClass("header_cell_class", HCellStyle) ->EndStyle() ->EndHeader() ->StartBody("body_class"); // Generate table header Rdr->StartTable("table_class") ->StartTableRow() ->StartColSpanTableHCell(2, "table_class cell_class") ->AddText(asiTestEngine_Macro_TEST) ->EndTableHCell() ->StartTableHCell("table_class cell_class") ->AddText(asiTestEngine_Macro_RESULT) ->EndTableHCell() ->EndTableRow(); /* ======================================= * Render information per each Test Case * ======================================= */ // Iterate over Test Cases for ( int l = 0; l < (int) m_launchers.size(); ++l ) { const Handle(asiTestEngine_CaseLauncherAPI)& CaseLauncher = m_launchers.at(l); // Local summary const int nTotal = CaseLauncher->NumberOfExecuted(); const int nFailed = CaseLauncher->NumberOfFailed(); const double passedPercent = (double) (nTotal-nFailed)/nTotal*100.0; // Get filename for description std::string descGroupDir = CaseLauncher->CaseDescriptionDir(); std::string descFilename = CaseLauncher->CaseDescriptionFn() + asiTestEngine_Macro_DOT + asiTestEngine_Macro_DESCR_EXT; std::string descDir = asiAlgo_Utils::Str::Slashed( asiAlgo_Utils::Env::AsiTestDescr() ) + descGroupDir; // Description processing tool std::string title; std::vector<std::string> overviewBlocks, detailBlocks; // if ( !asiTestEngine_DescriptionProc::Process(descDir, descFilename, CaseLauncher->Variables(), CaseLauncher->CaseID(), nTotal, title, overviewBlocks, detailBlocks) ) { if ( out ) *out << "\tFailed to read description from \"" << descFilename.c_str() << "\"\n"; return false; } // Render header for Test Case Rdr->StartTableRow() ->StartTableHCell("table_class cell_class header_cell_class") ->AddText( CaseLauncher->CaseID() ) ->EndTableHCell() ->StartTableHCell("table_class cell_class header_cell_class") ->AddText(title) ->EndTableHCell(); // Finish row with local statistics Rdr->StartTableHCell( (nFailed == 0) ? "table_class cell_class good_cell_class" : "table_class cell_class bad_cell_class" ); Rdr->AddText(passedPercent)->AddText("%")->EndTableHCell(); Rdr->EndTableRow(); // Check number of OVERVIEW blocks if ( (int) overviewBlocks.size() < nTotal ) { if ( out ) *out << "\tNot enough OVERVIEW blocks in \"" << descFilename.c_str() << "\"\n"; return false; } // Add rows for Test Functions for ( int f = 0; f < nTotal; ++f ) { // Prepare global ID of Test Function std::string GID = asiAlgo_Utils::Str::ToString( CaseLauncher->CaseID() ) + asiTestEngine_Macro_COLON + asiAlgo_Utils::Str::ToString(f+1); // Add table row Rdr->StartTableRow() ->StartTableCell("table_class cell_class")->AddText(GID)->EndTableCell() ->StartTableCell("table_class cell_class") ->AddText( overviewBlocks[f] ); // Add section for details if ( ( (int) detailBlocks.size() >= (f+1) ) && detailBlocks[f].length() ) { const std::string& details = detailBlocks[f]; Rdr->BreakRow()->BreakRow() ->AddText("<i>Details:</i>") ->AddText("<div style='border: 1px dotted rgb(100, 100, 100); " "font-size: 11; background-color: rgb(250, 245, 160); " "padding: 5px; margin: 5px;'>") ->AddText(details) ->AddText("</div>"); } // Finish description cell Rdr->EndTableCell(); // Result of Test Function if ( CaseLauncher->IsPassed(f) ) Rdr->StartTableCell("table_class cell_class good_cell_class")->AddText(asiTestEngine_Macro_OK); else Rdr->StartTableCell("table_class cell_class bad_cell_class")->AddText(asiTestEngine_Macro_FAILED); // Finish row Rdr->EndTableCell()->EndTableRow(); } } // Finish table Rdr->EndTable(); /* =============== * Render footer * =============== */ Rdr->EndBody()->EndHtml(); /* ========================== * Prepare filesystem stuff * ========================== */ std::string dirName = std::string("ut_") + this->uniqueDirName(); if ( out ) *out << "\tTemporary directory: " << dirName.c_str() << "\n"; // Prepare full name of the temporary directory std::string fullDirName = asiAlgo_Utils::Str::Slashed( asiAlgo_Utils::Env::AsiTestDumping() ) + dirName; // TODO: for Windows only (!!!) // Create directory if ( !CreateDirectory(fullDirName.c_str(), NULL) ) { if ( out ) *out << "\tFailed to create directory: " << fullDirName.c_str() << "\n"; return false; } // Filename for HTML report std::string filename = asiAlgo_Utils::Str::Slashed(fullDirName) + asiTestEngine_Macro_REPORT_FN + asiTestEngine_Macro_DOT + asiTestEngine_Macro_REPORT_EXT; // Create file for HTML report std::ofstream file; file.open(filename.c_str(), std::ios::out | std::ios::trunc); if ( !file.is_open() ) { if ( out ) *out << "Cannot open file " << filename.c_str() << " for writing" << "\n"; return false; } // Dump rendered information to file file << Rdr->Flush(); // Release file file.close(); return true; } //! Generates unique name for the directory containing all results for //! current test session. The used format is as follows: //! <pre> //! ut_{week-day}_{month}_{day}_{{hour}{min}{sec}}_{year} //! //! E.g: //! //! ut_Sat_Dec_07_190744_2013 //! //! </pre> //! \return generated unique name. std::string asiTestEngine_Launcher::uniqueDirName() const { Handle(asiAlgo_TimeStamp) TS = asiAlgo_TimeStampTool::Generate(); return TS->ToString(false, true); }
11,980
3,812
#include <iostream> #include <typeinfo> using namespace std; auto AutoFunctionFromReturn(int parameter)->int // 这里需要加 { return parameter; } int main() { auto value = AutoFunctionFromReturn(1); cout << value << endl; return 0; }
236
84
#include <karm-test/macros.h> #include "../vec.h" template <typename V> Error test_vec(Driver &_driver) { describe$("constructor") { it$("should be empty when created") { V v; expectEq$(v.len(), 0uz); expectEq$(v.cap(), 0uz); } it$("should be copyable") { V v = {1, 2, 3}; V v2 = v; expectEq$(v2.len(), 3uz); expectEq$(v2.cap(), 3uz); expectEq$(v2.at(0), 1); expectEq$(v2.at(1), 2); expectEq$(v2.at(2), 3); } it$("should be moveable") { V v = {1, 2, 3}; V v2 = std::move(v); expectEq$(v2.len(), 3uz); expectEq$(v2.cap(), 3uz); expectEq$(v2.at(0), 1); expectEq$(v2.at(1), 2); expectEq$(v2.at(2), 3); } it$("should be empty when created with capacity") { V v(10); expectEq$(v.len(), 0uz); expectEq$(v.cap(), 10uz); } it$("should be empty when created with an empty initializer list") { V v = {}; expectEq$(v.len(), 0uz); expectEq$(v.cap(), 0uz); } it$("should contain the elements of the initializer list") { V v = {1, 2, 3}; expectEq$(v.len(), 3uz); expectEq$(v.cap(), 3uz); expectEq$(v.at(0), 1); expectEq$(v.at(1), 2); expectEq$(v.at(2), 3); } } describe$("insert") { it$("should insert at the end") { V v = {1, 2, 3}; v.insert(3, 4); expectEq$(v.len(), 4uz); expectEq$(v.cap(), 4uz); expectEq$(v.at(0), 1); expectEq$(v.at(1), 2); expectEq$(v.at(2), 3); expectEq$(v.at(3), 4); } it$("should insert at the beginning") { V v = {1, 2, 3}; v.insert(0, 0); expectEq$(v.len(), 4uz); expectEq$(v.cap(), 4uz); expectEq$(v.at(0), 0); expectEq$(v.at(1), 1); expectEq$(v.at(2), 2); expectEq$(v.at(3), 3); } it$("should insert at the middle") { V v = {1, 2, 3}; v.insert(1, 0); expectEq$(v.len(), 4uz); expectEq$(v.cap(), 4uz); expectEq$(v.at(0), 1); expectEq$(v.at(1), 0); expectEq$(v.at(2), 2); expectEq$(v.at(3), 3); } it$("should insert at the end when the vector is full") { V v = {1, 2, 3}; v.insert(3, 4); v.insert(4, 5); expectEq$(v.len(), 5uz); expectEq$(v.cap(), 5uz); expectEq$(v.at(0), 1); expectEq$(v.at(1), 2); expectEq$(v.at(2), 3); expectEq$(v.at(3), 4); expectEq$(v.at(4), 5); } } describe$("pushBack") { it$("should increase the length and capacity") { V v; size_t oldCap = v.cap(); v.pushBack(1); v.pushBack(2); v.pushBack(3); expectEq$(v.len(), 3uz); expectGteq$(v.cap(), v.len()); expectGt$(v.cap(), oldCap); expectEq$(v.at(0), 1); expectEq$(v.at(1), 2); expectEq$(v.at(2), 3); } it$("should not increase the capacity when the capacity is sufficient") { V v(10); size_t oldCap = v.cap(); v.pushBack(1); v.pushBack(2); v.pushBack(3); expectEq$(v.len(), 3uz); expectEq$(v.cap(), oldCap); expectEq$(v.at(0), 1); expectEq$(v.at(1), 2); expectEq$(v.at(2), 3); } it$("let elements be popped") { V v = {1, 2, 3}; v.pushBack(4); auto popped = v.popBack(); expectEq$(v.len(), 3uz); expectEq$(v.at(0), 1); expectEq$(v.at(1), 2); expectEq$(v.at(2), 3); expectEq$(popped, 4); } it$("let element be peeked") { V v = {1, 2}; v.pushBack(3); auto peeked = v.peekBack(); expectEq$(v.len(), 3uz); expectEq$(v.at(0), 1); expectEq$(v.at(1), 2); expectEq$(v.at(2), 3); expectEq$(peeked, 3); } } describe$("pushFront") { it$("should increase the length and capacity") { V v; size_t oldCap = v.cap(); v.pushFront(1); v.pushFront(2); v.pushFront(3); expectEq$(v.len(), 3uz); expectGteq$(v.cap(), v.len()); expectGt$(v.cap(), oldCap); expectEq$(v.at(0), 3); expectEq$(v.at(1), 2); expectEq$(v.at(2), 1); } it$("should not increase the capacity when the capacity is sufficient") { V v(10); size_t oldCap = v.cap(); v.pushFront(1); v.pushFront(2); v.pushFront(3); expectEq$(v.len(), 3uz); expectEq$(v.cap(), oldCap); expectEq$(v.at(0), 3); expectEq$(v.at(1), 2); expectEq$(v.at(2), 1); } it$("let elements be popped") { V v = {1, 2, 3}; v.pushFront(4); auto popped = v.popFront(); expectEq$(v.len(), 3uz); expectEq$(v.at(0), 1); expectEq$(v.at(1), 2); expectEq$(v.at(2), 3); expectEq$(popped, 4); } it$("let element be peeked") { V v = {1, 2}; v.pushFront(3); auto peeked = v.peekFront(); expectEq$(v.len(), 3uz); expectEq$(v.at(0), 3); expectEq$(v.at(1), 1); expectEq$(v.at(2), 2); expectEq$(peeked, 3); } } return OK; } test$("Vec") { try$(test_vec<Vec<int>>(_driver)); return OK; } test$("InlineVec") { try$((test_vec<InlineVec<int, 10>>(_driver))); return OK; }
6,185
2,224
#include "folderviewstyleditemdelegate.h" #include <QStyleOptionViewItem> #include <QModelIndex> #include <QDebug> #include <QPainter> #include <QApplication> #include "folderview.h" #include "default_settings.h" namespace Farman { FolderViewStyledItemDelegate::FolderViewStyledItemDelegate(QObject *parent/* = Q_NULLPTR*/) : QStyledItemDelegate(parent) , m_cursorWidth(DEFAULT_CURSOR_WIDTH) , m_activeColor(DEFAULT_COLOR_SETTINGS["folderView_cursor"]) , m_inactiveColor(DEFAULT_COLOR_SETTINGS["folderView_cursor_inactive"]) { makePen(); } void FolderViewStyledItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItem opt = option; opt.state &= ~QStyle::State_Selected; // FolderModel の TextColorRole・BackgroundRole の Brush を使用するため、ここでは Selected を無効にする opt.state &= ~QStyle::State_HasFocus; // カーソル位置の枠を表示しないようにするため、ここでは Has_Focus を無効にする(Windows用) QStyledItemDelegate::paint(painter, opt, index); FolderView* parent = qobject_cast<FolderView*>(this->parent()); if(parent != Q_NULLPTR) { if(parent->currentIndex().row() == index.row()) { // カーソル位置をアンダーラインで表示 painter->save(); painter->setPen((option.state & QStyle::State_Active) ? m_activeCursorPen : m_inactiveCursorPen); painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight()); painter->restore(); } } } void FolderViewStyledItemDelegate::setCursorAppearance(int width, const QColor& activeColor, const QColor& inactiveColor) { m_cursorWidth = width; m_activeColor = activeColor; m_inactiveColor = inactiveColor; makePen(); } void FolderViewStyledItemDelegate::makePen() { m_activeCursorPen = QPen(m_activeColor, static_cast<qreal>(m_cursorWidth)); m_inactiveCursorPen = QPen(m_inactiveColor, static_cast<qreal>(m_cursorWidth)); } } // namespace Farman
1,986
715
//%Header { /***************************************************************************** * * File: src/Media/MediaJoystick.cpp * * Copyright: Andy Southgate 2002-2007, 2020 * * 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. * ****************************************************************************/ //%Header } QTCqGGve2ziFnEL2Ljyj9A /* * $Id: MediaJoystick.cpp,v 1.2 2006/07/21 10:52:06 southa Exp $ * $Log: MediaJoystick.cpp,v $ * Revision 1.2 2006/07/21 10:52:06 southa * win32 build fixes * * Revision 1.1 2006/07/11 19:49:04 southa * Control menu * */ #include "MediaJoystick.h" #include "MediaSDL.h" MUSHCORE_SINGLETON_INSTANCE(MediaJoystick); using namespace Mushware; using namespace std; MediaJoystick::MediaJoystick() { MediaSDL::Sgl().InitJoystick(); SDL_JoystickEventState(SDL_ENABLE); U32 numSticks = SDL_NumJoysticks(); m_sticks.resize(numSticks); for (U32 i=0; i<numSticks; ++i) { m_sticks[i] = SDL_JoystickOpen(i); SDL_JoystickID stickId = SDL_JoystickInstanceID(m_sticks[i]); if (m_sticks[i] != NULL) { MushcoreLog::Sgl().InfoLog() << "Opening joystick " << i << endl; MushcoreLog::Sgl().InfoLog() << "- Name : " << SDL_JoystickName(m_sticks[i]) << endl; MushcoreLog::Sgl().InfoLog() << "- Axes : " << SDL_JoystickNumAxes(m_sticks[i]) << endl; MushcoreLog::Sgl().InfoLog() << "- Buttons : " << SDL_JoystickNumButtons(m_sticks[i]) << endl; MushcoreLog::Sgl().InfoLog() << "- Balls : " << SDL_JoystickNumBalls(m_sticks[i]) << endl; MushcoreLog::Sgl().InfoLog() << "- Hats : " << SDL_JoystickNumHats(m_sticks[i]) << endl; } } } MediaJoystick::~MediaJoystick() { #ifndef WIN32 // Windows doesn't like this for (U32 i=0; i<m_sticks.size(); ++i) { if (SDL_JoystickOpened(i)) { SDL_JoystickClose(m_sticks[i]); } } #endif MediaSDL::Sgl().QuitJoystick(); } Mushware::U32 MediaJoystick::NumJoysticks(void) { return SDL_NumJoysticks(); }
3,134
1,186
/* ______ ______ __ __ __ ______ __ __ /\___ \ /\ ___\ /\ "-.\ \ /\ \ /\__ _\ /\ \_\ \ \/_/ /__ \ \ __\ \ \ \-. \ \ \ \ \/_/\ \/ \ \ __ \ /\_____\ \ \_____\ \ \_\" \_\ \ \_\ \ \_\ \ \_\ \_\ \/_____/ \/_____/ \/_/ \/_/ \/_/ \/_/ \/_/\/_/ ZEditor.hpp Created by Adrian Sanchez on 18/01/21. Copyright © 2019 Pervasive Sense. All rights reserved. This file is part of Zenith. Zenith 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 3 of the License, or (at your option) any later version. Zenith 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 Zenith. If not, see <https://www.gnu.org/licenses/>. */ #pragma once // Includes #include "ZScene.hpp" // Forward Declarations class ZEditorEntity; class ZMenuBar; class ZEvent; class ZResourceHandle; class ZResourceLoadedEvent; class ZUIPanel; class ZCamera; class ZEditorTool; // Definitions const std::string EDITOR_CONFIG_PATH = "/conf.zof"; const std::string EDITOR_OBJECT_TEMPLATES_PATH = "/object_templates.zof"; struct ZEditorConfig { glm::vec4 sizeLimits{ 0.f }; ZUITheme theme; }; class ZEditorScene : public ZScene { public: ZEditorScene() : ZScene("EditorScene"), editorOpen_(true) { } void Initialize() override; void Update(double deltaTime) override; void CleanUp() override; ZGameObjectMap& ObjectTemplates() { return gameObjectTemplates_; } ZUIElementMap& UITemplates() { return uiElementTemplates_; } ZEditorConfig& Config() { return config_; } ZGameObjectMap& SelectedObjects() { return selectedObjects_; } std::shared_ptr<ZGameObject> EditorCamera() { return editorCamera_; } ZSceneSnapshot& LastSceneSnapshot() { return lastSceneSnapshot_; } std::shared_ptr<ZScene> ActiveProjectScene() { return activeProjectScene_; } void SetSceneSnapshot(ZSceneSnapshot& snapshot) { lastSceneSnapshot_ = snapshot; } void SetActiveProjectScene(const std::shared_ptr<ZScene>& activeScene); void AddTool(const std::shared_ptr<ZEditorTool>& tool, const std::shared_ptr<ZUIPanel>& layoutRegion); std::shared_ptr<ZCamera> CreateCamera(); std::shared_ptr<ZUIPanel> CreateVerticalRegion(const ZRect& rect, std::shared_ptr<ZUIPanel> parent = nullptr); std::shared_ptr<ZUIPanel> CreateHorizontalRegion(const ZRect& rect, std::shared_ptr<ZUIPanel> parent = nullptr); private: ZGameObjectMap gameObjectTemplates_; ZUIElementMap uiElementTemplates_; ZEditorConfig config_; bool editorOpen_; ZGameObjectMap selectedObjects_; std::shared_ptr<ZGameObject> editorCamera_; std::shared_ptr<ZUIPanel> topPanel_; std::shared_ptr<ZUIPanel> leftPanel_; std::shared_ptr<ZUIPanel> centerPanel_; std::shared_ptr<ZUIPanel> rightPanel_; std::shared_ptr<ZUIPanel> bottomPanel_; std::vector<std::shared_ptr<ZEditorEntity>> entities_; ZSceneSnapshot lastSceneSnapshot_; std::shared_ptr<ZScene> activeProjectScene_; void SetupLayoutPanels(); void SetupInitialTools(); void Configure(std::shared_ptr<ZOFTree> objectTree); void Configure(ZEditorConfig config); void LoadObjectTemplates(std::shared_ptr<ZOFTree> objectTree); void HandleResourceLoaded(const std::shared_ptr<ZResourceLoadedEvent>& event); };
3,998
1,227
#include "module.h" #include <web/httpd/kernel/http.h> #include <web/httpd/kernel/errors.h> #include <web/httpd/kernel/module.h> #include <web/httpd/kernel/config.h> #include <web/httpd/kernel/rewind.h> #include <web/httpd/kernel/concat.h> #include <web/httpd/kernel/regexp.h> #include <web/httpd/kernel/precharge.h> #include <util/generic/ptr.h> #include <util/generic/vector.h> #include "optvalue.h" using namespace NSrvKernel; using namespace NModRegexp; MODULE(regexp) { class TItem: public TRefCounted<TItem>, public TModuleParams, public IConfig::IFunc { public: inline TItem(const Stroka& name, const TModuleParams& mp) : TModuleParams(mp) , Name_(name) , CaseInsensitive_(OV_DEFAULT) , Surround_(OV_DEFAULT) , Priority_(1.0) { if (IsDefault()) { Regexp_ = ".*"; } Config->ForEach(this); if (!Slave_) { ythrow TConfigParseError() << "no module configured"; } if (!Regexp_) { ythrow TConfigParseError() << "no regexp configured"; } if (IsDefault()) { Priority_ = -1.0; } } inline bool IsDefault() const throw () { return Name_ == "default"; } inline float Priority() const throw () { return Priority_; } START_PARSE { ON_KEY ("priority", Priority_) { return; } ON_KEY("match", Regexp_) { return; } if (key == "case_insensitive") { CaseInsensitive_ = OptionValue(value->AsBool()); return; } if (key == "surround") { Surround_ = OptionValue(value->AsBool()); return; } { Slave_.Reset(Loader->MustLoad(key, Copy(value->AsSubConfig())).Release()); return; } } END_PARSE inline const TFsm& Fsm() const throw () { return *Fsm_; } inline IModule* Slave() const throw () { return Slave_.Get(); } inline void PrintStats(TOutputStream& out) { out << "<" << Name_ << ">"; Slave_->PrintStats(out); out << "</" << Name_ << ">"; } inline void InitFsm(bool defaultCaseInsensitive, bool defaultSurround) { TFsm::TOptions options; options.SetCaseInsensitive(CalcOptionValue(CaseInsensitive_, defaultCaseInsensitive)); options.SetSurround(CalcOptionValue(Surround_, defaultSurround)); Fsm_.Reset(new TFsm(Regexp_, options)); } private: const Stroka Name_; Stroka Regexp_; EOptionValue CaseInsensitive_; EOptionValue Surround_; THolder<TFsm> Fsm_; THolder<IModule> Slave_; float Priority_; }; typedef TIntrusivePtr<TItem> TItemRef; struct THdrChooser { THdrChooser(const TFsm* fsm) : R(fsm) , Header(0) { } inline void operator() (THeader* hdr) { if (Header) { return; } TMatcher m(*R); if (Match(m, hdr->Key).Final()) { Header = hdr; } } const TFsm* R; THeader* Header; }; public: inline TModule(const TModuleParams& mp) : TModuleParams(mp) , Fsm_(TFsm::False()) , CaseInsensitive_(false) , Surround_(false) , Default_(0) { Config->ForEach(this); if (Items_.empty()) { ythrow TConfigParseError() << "no modules configured"; } InitFsm(); } START_PARSE { Stroka header; ON_KEY("http_header", header) { FsmHeader_.Reset(new TFsm(header, TFsm::TOptions().SetCaseInsensitive(true))); return; } if (key == "case_insensitive") { CaseInsensitive_ = value->AsBool(); return; } if (key == "surround") { Surround_ = value->AsBool(); return; } { Items_.push_back(new TItem(key, Copy(value->AsSubConfig()))); return; } } END_PARSE virtual void DoRun(const TConnDescr& descr) { IModule* slave = NULL; if (!FsmHeader_) { slave = SelectHandle(descr.Request->Request()); } else { THdrChooser chooser(FsmHeader_.Get()); descr.Request->ForEachHeader(chooser); if (chooser.Header) { slave = SelectHandle(chooser.Header->Value); } else { TChunkList tmp; slave = SelectHandle(tmp); } } if (!slave) { ythrow THttpError(404) << "no module for request handling"; } slave->Run(descr); } inline IModule* SelectHandle(const TChunkList& data) { TMatcher m(Fsm_); if (Match(m, data).Final()) { TMatcher::TMatchedRegexps mr = m.MatchedRegexps(); const TItem* item = 0; for (const size_t* numIt = mr.first; numIt != mr.second; ++numIt) { const size_t num = *numIt; if (num < Items_.size()) { const TItem* next = Items_[num].Get(); if (!item || (next->Priority() > item->Priority())) { item = next; } } } if (item) { return item->Slave(); } } return Default(); } inline IModule* Default() const throw () { if (Default_) { return Default_->Slave(); } return 0; } virtual void DoStats(TOutputStream& out) { for (TItems::const_iterator it = Items_.begin(); it != Items_.end(); ++it) { (*it)->PrintStats(out); } } private: inline void InitFsm() { for (TItems::iterator pItem = Items_.begin(); pItem != Items_.end(); ++pItem) { const TItemRef& item = *pItem; if (item->IsDefault()) { Default_ = item.Get(); } item->InitFsm(CaseInsensitive_, Surround_); if (pItem == Items_.begin()) { Fsm_ = item->Fsm(); } else { Fsm_ = Fsm_ | item->Fsm(); } } } private: typedef yvector<TItemRef> TItems; TItems Items_; TFsm Fsm_; THolder<TFsm> FsmHeader_; bool CaseInsensitive_; bool Surround_; TItem* Default_; }; IModuleHandle* NModRegexp::Handle() { return TModule::ModuleHandle(); }
6,886
2,088
/**************************************************************************************/ /* */ /* Visualization Library */ /* http://visualizationlibrary.org */ /* */ /* Copyright (c) 2005-2020, Michele Bosi */ /* 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. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */ /* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ /* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */ /* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ /* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */ /* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */ /* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* */ /**************************************************************************************/ #include <vlGraphics/PolygonSimplifier.hpp> #include <vlGraphics/DoubleVertexRemover.hpp> #include <vlCore/Time.hpp> #include <vlCore/Log.hpp> #include <vlCore/Say.hpp> #include <set> using namespace vl; //----------------------------------------------------------------------------- namespace { class VertexPtrWrapper { public: VertexPtrWrapper(PolygonSimplifier::Vertex* ptr=NULL): mVertex(ptr) {} bool operator==(const VertexPtrWrapper& other) const { return mVertex == other.mVertex; } bool operator!=(const VertexPtrWrapper& other) const { return mVertex == other.mVertex; } bool operator<(const VertexPtrWrapper& other) const { if ( mVertex->collapseCost() != other.mVertex->collapseCost() ) return mVertex->collapseCost() < other.mVertex->collapseCost(); else return mVertex < other.mVertex; } PolygonSimplifier::Vertex* mVertex; }; } //----------------------------------------------------------------------------- void PolygonSimplifier::simplify() { if (!mInput) { Log::error("PolygonSimplifier::simplify() : no input Geometry specified.\n"); return; } // we don't support vertex attributes of any kind yet #ifndef NDEBUG bool problem = false; for( int i = VA_Position + 1; i < VA_MaxAttribCount; ++i ) problem |= mInput->vertexAttribArray(i) != NULL; if (problem) Log::warning("PolygonSimplifier::simplify() simplifies only the position array of a Geometry, the other attibutes will be discarded.\n"); #endif Time timer; timer.start(); if ( removeDoubles() ) { DoubleVertexRemover remover; remover.removeDoubles( mInput.get() ); } std::vector<fvec3> verts; std::vector<int> indices; indices.reserve(1000); // merge all triangles in a single DrawElementsUInt ref<DrawElementsUInt> pint = new DrawElementsUInt(PT_TRIANGLES, 1); for( size_t i=0; i<mInput->drawCalls().size(); ++i ) { DrawCall* prim = mInput->drawCalls().at(i); for(TriangleIterator trit = prim->triangleIterator(); trit.hasNext(); trit.next()) { indices.push_back( trit.a() ); indices.push_back( trit.b() ); indices.push_back( trit.c() ); } } if (indices.empty()) { Log::warning("PolygonSimplifier::simplify() : no triangles found in input Geometry.\n"); return; } ArrayAbstract* posarr = mInput->vertexArray(); if (!posarr) { Log::warning("PolygonSimplifier::simplify() : no vertices found in input Geometry.\n"); return; } // fill vertices verts.resize( posarr->size() ); for( size_t i=0; i< posarr->size(); ++i ) verts[i] = (fvec3)posarr->getAsVec3(i); if (verts.empty()) { Log::warning("PolygonSimplifier::simplify() : no vertices found in input Geometry.\n"); return; } simplify(verts, indices); if (verbose()) Log::print( Say("PolygonSimplifier::simplify() done in %.3ns\n") << timer.elapsed() ); } //----------------------------------------------------------------------------- void PolygonSimplifier::simplify(const std::vector<fvec3>& in_verts, const std::vector<int>& in_tris) { if (verbose()) Log::print("PolygonSimplifier::simplify() starting ... \n"); Time timer; timer.start(); // sort simplification targets 1.0 -> 0.0 std::sort(mTargets.begin(), mTargets.end()); std::reverse(mTargets.begin(), mTargets.end()); mSimplifiedVertices.clear(); mSimplifiedTriangles.clear(); mProtectedVerts.clear(); mTriangleLump.clear(); mVertexLump.clear(); // mic fixme: this is the one taking time. // preallocate vertices and triangles in one chunk mTriangleLump.resize(in_tris.size()/3); mVertexLump.resize(in_verts.size()); int polys_before = (int)in_tris.size() / 3; int verts_before = (int)in_verts.size(); mSimplifiedTriangles.resize( in_tris.size() / 3 ); mSimplifiedVertices.resize( in_verts.size() ); #define SHUFFLE_VERTICES 0 #if SHUFFLE_VERTICES std::vector<Vertex*> vertex_pool; vertex_pool.resize( in_verts.size() ); for(int i=0; i<(int)mVertexLump.size(); ++i) vertex_pool[i] = &mVertexLump[i]; // shuffle the vertices for(int i=0; i<(int)vertex_pool.size(); ++i) { int a = int( (float)rand() / (RAND_MAX+1) * vertex_pool.size() ); int b = int( (float)rand() / (RAND_MAX+1) * vertex_pool.size() ); Vertex* tmp = vertex_pool[a]; vertex_pool[a] = vertex_pool[b]; vertex_pool[b] = tmp; } #endif // initialize vertices for(int ivert=0; ivert<(int)in_verts.size(); ++ivert) { #if SHUFFLE_VERTICES mSimplifiedVertices[ivert] = vertex_pool[ivert]; #else mSimplifiedVertices[ivert] = &mVertexLump[ivert]; #endif mSimplifiedVertices[ivert]->mPosition = in_verts[ivert]; // so that the user knows which vertex is which and can regenerate per-vertex // information like textures coordinates, colors etc. mSimplifiedVertices[ivert]->mOriginalIndex = ivert; // unprotect the vertex mSimplifiedVertices[ivert]->mProtected = false; // reserve the memory for quicker allocation mSimplifiedVertices[ivert]->mIncidentTriangles.reserve(12); mSimplifiedVertices[ivert]->mAdjacentVerts.reserve(12); } // initialize triangles for(int idx=0, itri=0; idx<(int)in_tris.size(); idx+=3, ++itri) { mSimplifiedTriangles[itri] = &mTriangleLump[itri]; mSimplifiedTriangles[itri]->mVertices[0] = mSimplifiedVertices[ in_tris[idx+0] ]; mSimplifiedTriangles[itri]->mVertices[1] = mSimplifiedVertices[ in_tris[idx+1] ]; mSimplifiedTriangles[itri]->mVertices[2] = mSimplifiedVertices[ in_tris[idx+2] ]; } // compute vertex/vertex and vertex/triangle connectivity for(int itri=0; itri<(int)mSimplifiedTriangles.size(); ++itri) { // add this triangle to all its vertices mSimplifiedTriangles[itri]->mVertices[0]->mIncidentTriangles.push_back( mSimplifiedTriangles[itri] ); mSimplifiedTriangles[itri]->mVertices[1]->mIncidentTriangles.push_back( mSimplifiedTriangles[itri] ); mSimplifiedTriangles[itri]->mVertices[2]->mIncidentTriangles.push_back( mSimplifiedTriangles[itri] ); // add adjacent vertices mSimplifiedTriangles[itri]->mVertices[0]->addAdjacentVertex( mSimplifiedTriangles[itri]->mVertices[1] ); // vertex 0 mSimplifiedTriangles[itri]->mVertices[0]->addAdjacentVertex( mSimplifiedTriangles[itri]->mVertices[2] ); mSimplifiedTriangles[itri]->mVertices[1]->addAdjacentVertex( mSimplifiedTriangles[itri]->mVertices[0] ); // vertex 1 mSimplifiedTriangles[itri]->mVertices[1]->addAdjacentVertex( mSimplifiedTriangles[itri]->mVertices[2] ); mSimplifiedTriangles[itri]->mVertices[2]->addAdjacentVertex( mSimplifiedTriangles[itri]->mVertices[0] ); // vertex 2 mSimplifiedTriangles[itri]->mVertices[2]->addAdjacentVertex( mSimplifiedTriangles[itri]->mVertices[1] ); // compute normal mSimplifiedTriangles[itri]->computeNormal(); // error QErr qerr = mSimplifiedTriangles[itri]->computeQErr(); mSimplifiedTriangles[itri]->mVertices[0]->addQErr(qerr); mSimplifiedTriangles[itri]->mVertices[1]->addQErr(qerr); mSimplifiedTriangles[itri]->mVertices[2]->addQErr(qerr); } // - remove vertices without triangles // - compute edge penalties // - initialize the collapse info of each vertex for( int ivert=(int)mSimplifiedVertices.size(); ivert--; ) { if ( mSimplifiedVertices[ivert]->incidentTrianglesCount() == 0 ) mSimplifiedVertices.erase( mSimplifiedVertices.begin() + ivert ); else { mSimplifiedVertices[ivert]->computeEdgePenalty(); computeCollapseInfo( mSimplifiedVertices[ivert] ); } } // sets the protected vertices for(int i=0; i<(int)mProtectedVerts.size(); ++i) { VL_CHECK(mProtectedVerts[i] < (int)mSimplifiedVertices.size() ) mSimplifiedVertices[ mProtectedVerts[i] ]->mProtected = true; } if (verbose()) Log::print(Say("database setup = %.3n\n") << timer.elapsed() ); std::set<VertexPtrWrapper> vertex_set; for(int ivert=0; ivert<(int)mSimplifiedVertices.size(); ++ivert) if ( !mSimplifiedVertices[ivert]->mProtected ) vertex_set.insert( mSimplifiedVertices[ivert] ); if (verbose()) Log::print(Say("heap setup = %.3n\n") << timer.elapsed() ); // loop through the simplification targets for(size_t itarget=0, remove_order=0; itarget<mTargets.size(); ++itarget) { const int target_vertex_count = mTargets[itarget]; if (target_vertex_count < 3) { Log::print(Say("Invalid target_vertex_count = %n\n") << target_vertex_count); return; } timer.start(1); std::vector< PolygonSimplifier::Vertex* > adj_verts; for( ; (int)vertex_set.size()>target_vertex_count; ++remove_order ) { std::set<VertexPtrWrapper>::iterator it = vertex_set.begin(); PolygonSimplifier::Vertex* v = it->mVertex; v->mRemoveOrder = (int)remove_order; vertex_set.erase(it); // remove the adjacent vertices to v and v->collapseVert() adj_verts.clear(); for(int i=0; i<v->adjacentVerticesCount(); ++i) { VL_CHECK( v != v->adjacentVertex(i) ) VL_CHECK( !v->adjacentVertex(i)->mAlreadyProcessed ) adj_verts.push_back( v->adjacentVertex(i) ); adj_verts.back()->mAlreadyProcessed = true; vertex_set.erase( v->adjacentVertex(i) ); } for(int i=0; i<v->collapseVertex()->adjacentVerticesCount(); ++i) { if ( !v->collapseVertex()->adjacentVertex(i)->mAlreadyProcessed ) { adj_verts.push_back( v->collapseVertex()->adjacentVertex(i) ); vertex_set.erase( v->collapseVertex()->adjacentVertex(i) ); } } VL_CHECK(!v->removed()) VL_CHECK(v->collapseVertex()) VL_CHECK(!v->collapseVertex()->removed()) collapse( v ); // reinsert the adj_verts if not removed // NOTE: v->collapseVertex() might have been also removed for( int i=(int)adj_verts.size(); i--; ) { adj_verts[i]->mAlreadyProcessed = false; if ( adj_verts[i]->removed() ) continue; computeCollapseInfo( adj_verts[i] ); VL_CHECK( adj_verts[i]->checkTriangles() ) VL_CHECK( adj_verts[i]->collapseVertex() != v ) VL_CHECK( !adj_verts[i]->collapseVertex()->removed() ) vertex_set.insert( adj_verts[i] ); } } if (verbose()) Log::print(Say("simplification = %.3ns (%.3ns)\n") << timer.elapsed() << timer.elapsed(1) ); outputSimplifiedGeometry(); } if (verbose() && !output().empty()) { float elapsed = (float)timer.elapsed(); int polys_after = output().back()->drawCalls().at(0)->countTriangles(); int verts_after = output().back()->vertexArray() ? (int)output().back()->vertexArray()->size() : 0; Log::print(Say("POLYS: %n -> %n, %.2n%%, %.1nT/s\n") << polys_before << polys_after << 100.0f*verts_after/verts_before << (polys_before - polys_after)/elapsed ); Log::print(Say("VERTS: %n -> %n, %.2n%%, %.1nV/s\n") << verts_before << verts_after << 100.0f*verts_after/verts_before << (verts_before - verts_after)/elapsed ); } } //----------------------------------------------------------------------------- void PolygonSimplifier::outputSimplifiedGeometry() { // count vertices required size_t vert_count = 0; for(int i=0; i<(int)mSimplifiedVertices.size(); ++i) vert_count += mSimplifiedVertices[i]->mRemoved ? 0 : 1; // regenerate vertex buffer & generate indices for index buffer ref<ArrayFloat3> arr_f3 = new ArrayFloat3; arr_f3->resize(vert_count); for(int i=0, vert_index=0; i<(int)mSimplifiedVertices.size(); ++i) { if (!mSimplifiedVertices[i]->mRemoved) { arr_f3->at(vert_index) = mSimplifiedVertices[i]->mPosition; mSimplifiedVertices[i]->mSimplifiedIndex = vert_index++; } } // count indices required size_t index_count = 0; for(size_t i=0; i<mSimplifiedTriangles.size(); ++i) index_count += mSimplifiedTriangles[i]->mRemoved ? 0 : 3; // regenerate index buffer ref<DrawElementsUInt> de = new DrawElementsUInt(PT_TRIANGLES); de->indexBuffer()->resize(index_count); DrawElementsUInt::index_type* ptr = de->indexBuffer()->begin(); for(size_t i=0; i<mSimplifiedTriangles.size(); ++i) { if(!mSimplifiedTriangles[i]->mRemoved) { VL_CHECK( !mSimplifiedTriangles[i]->mVertices[0]->mRemoved ) VL_CHECK( !mSimplifiedTriangles[i]->mVertices[1]->mRemoved ) VL_CHECK( !mSimplifiedTriangles[i]->mVertices[2]->mRemoved ) ptr[0] = mSimplifiedTriangles[i]->mVertices[0]->mSimplifiedIndex; ptr[1] = mSimplifiedTriangles[i]->mVertices[1]->mSimplifiedIndex; ptr[2] = mSimplifiedTriangles[i]->mVertices[2]->mSimplifiedIndex; ptr+=3; } } VL_CHECK(ptr == de->indexBuffer()->end()); // output geometry mOutput.push_back( new Geometry ); mOutput.back()->setVertexArray( arr_f3.get() ); mOutput.back()->drawCalls().push_back( de.get() ); } //----------------------------------------------------------------------------- void PolygonSimplifier::clearTrianglesAndVertices() { mSimplifiedVertices.clear(); mSimplifiedTriangles.clear(); mProtectedVerts.clear(); mTriangleLump.clear(); mVertexLump.clear(); } //-----------------------------------------------------------------------------
16,373
5,657
// Serializable Map Boost Test - SerializableMapBT.hpp (Wrapper) #ifndef SERIALIZABLE_MAP_BT_HPP #define SERIALIZABLE_MAP_BT_HPP #include "DBHandlerHelper.cpp" namespace DB { namespace TEST { template <typename MAP_TYPE > class SerializableMapBT : public boost::noncopyable { protected: SERVICES::DBHandler &m_dbHandlerInstance; MAP_TYPE *m_map; virtual int getFirstRunIdIfExist(void) const; virtual size_t getSizeOfRunTable(void) const; public: SerializableMapBT(void); virtual ~SerializableMapBT(void); }; template <typename MAP_TYPE > SerializableMapBT<MAP_TYPE>::SerializableMapBT() : m_dbHandlerInstance(DBHandlerHelper::getInstanceForTestsDemand()), m_map(new MAP_TYPE(DBHandlerHelper::getInstanceForTestsDemand())) { } template <typename MAP_TYPE > SerializableMapBT<MAP_TYPE>::~SerializableMapBT() { delete m_map; } template <typename MAP_TYPE > int SerializableMapBT<MAP_TYPE>::getFirstRunIdIfExist() const { std::string l_sqlQuerry = "SELECT * FROM runDataFunction();"; pqxx::result l_runDbResults = m_dbHandlerInstance.querry(l_sqlQuerry); size_t l_sizeResultQuerry = l_runDbResults.size(); if(l_sizeResultQuerry) { pqxx::result::const_iterator row = l_runDbResults.begin(); int l_runId = row["run_id"].as<int>(); return l_runId; } return -1; } template <typename MAP_TYPE > size_t SerializableMapBT<MAP_TYPE>::getSizeOfRunTable() const { std::string l_sqlQuerry = "SELECT * FROM runDataFunction();"; pqxx::result l_runDbResults = m_dbHandlerInstance.querry(l_sqlQuerry); return l_runDbResults.size(); } } // namespace TEST } // namespace DB #endif // SERIALIZABLE_MAP_BT_HPP
1,753
622
// -*- mode: c++; c-file-style: "k&r"; c-basic-offset: 4 -*- // vim: set ts=4 sw=4: /*********************************************************************** * * store/common/backend/versionstore.cc: * Timestamped version store * * Copyright 2015 Irene Zhang <iyzhang@cs.washington.edu> * * 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 "versionstore.h" using namespace std; VersionedKVStore::VersionedKVStore() { } VersionedKVStore::~VersionedKVStore() { } bool VersionedKVStore::inStore(const string &key) { return store.find(key) != store.end() && store[key].size() > 0; } bool VersionedKVStore::getValue(const string &key, const Timestamp &t, set<Version>::iterator &it) { Version v(t); it = store[key].upper_bound(v); // if there is no valid version at this timestamp if (it == store[key].begin()) { return false; } it--; return true; } /* Returns the most recent value and timestamp for given key. * Error if key does not exist. */ bool VersionedKVStore::Get(const string &key, Version &value) { // check for existence of key in store if (inStore(key)) { value = *(store[key].rbegin()); return true; } return false; } /* Returns the value valid at given timestamp. * Error if key did not exist at the timestamp. */ bool VersionedKVStore::Get(const string &key, const Timestamp &t, Version &value) { if (t == MAX_TIMESTAMP) { return Get(key, value); } if (inStore(key)) { set<Version>::iterator it; if (getValue(key, t, it) && it->GetInterval().End() >= t) { value = *it; return true; } } return false; } bool VersionedKVStore::GetRange(const string &key, const Timestamp &t, Interval &range) { if (inStore(key)) { set<Version>::iterator it; if (getValue(key, t, it)) { range = it->GetInterval(); return true; } } return false; } void VersionedKVStore::Put(const string &key, const string &value, const Timestamp &t) { // Key does not exist. Create a list and an entry. Put(key, Version(t, value)); } void VersionedKVStore::Put(const string &key, const Version &v) { // Key does not exist. Create a list and an entry. if (store.find(key) != store.end()) { if (v.GetTimestamp() == 0) { store.erase(key); } else { set<Version>::iterator it = --(store[key].end()); if (v.GetInterval().Start() < it->GetInterval().End()) { Version v1 = *it; store[key].erase(it); v1.SetEnd(v.GetInterval().Start()); store[key].insert(v1); } } } store[key].insert(v); } /* * Commit a read by updating the timestamp of the latest read txn for * the version of the key that the txn read. */ void VersionedKVStore::CommitGet(const string &key, const Timestamp &readTime, const Timestamp &commit) { set<Version>::iterator it; if (getValue(key, readTime, it)) { if (commit < it->GetInterval().End()) { Version v1 = *it; store[key].erase(it); v1.SetEnd(commit); store[key].insert(v1); } } } void VersionedKVStore::Remove(const string &key) { auto it = store.find(key); if (it != store.end()) { store.erase(it); } } bool VersionedKVStore::GetLastRead(const string &key, Timestamp &lastRead) { if (inStore(key)) { Version v = *(store[key].rbegin()); if (v.GetInterval().End() != MAX_TIMESTAMP) { lastRead = v.GetInterval().End(); return true; } } return false; } /* * Get the latest read for the write valid at timestamp t */ bool VersionedKVStore::GetLastRead(const string &key, const Timestamp &t, Timestamp &lastRead) { if (inStore(key)) { set<Version>::iterator it; if (getValue(key, t, it)) { Version v = *it; // figure out if anyone has read this version before if (v.GetInterval().End() != MAX_TIMESTAMP) { lastRead = v.GetInterval().End(); return true; } } } return false; }
5,461
1,739
// Autogenerated from CppHeaderCreator on 7/27/2020 3:09:49 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: System.Runtime.Remoting.Channels.CrossAppDomainSink #include "System/Runtime/Remoting/Channels/CrossAppDomainSink.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Runtime::Remoting::Messaging namespace System::Runtime::Remoting::Messaging { // Forward declaring type: CADMethodReturnMessage class CADMethodReturnMessage; } // Completed forward declares // Type namespace: System.Runtime.Remoting.Channels namespace System::Runtime::Remoting::Channels { // Autogenerated type: System.Runtime.Remoting.Channels.CrossAppDomainSink/ProcessMessageRes struct CrossAppDomainSink::ProcessMessageRes : public System::ValueType { public: // public System.Byte[] arrResponse // Offset: 0x0 ::Array<uint8_t>* arrResponse; // public System.Runtime.Remoting.Messaging.CADMethodReturnMessage cadMrm // Offset: 0x8 System::Runtime::Remoting::Messaging::CADMethodReturnMessage* cadMrm; // Creating value type constructor for type: ProcessMessageRes ProcessMessageRes(::Array<uint8_t>* arrResponse_ = {}, System::Runtime::Remoting::Messaging::CADMethodReturnMessage* cadMrm_ = {}) : arrResponse{arrResponse_}, cadMrm{cadMrm_} {} }; // System.Runtime.Remoting.Channels.CrossAppDomainSink/ProcessMessageRes } DEFINE_IL2CPP_ARG_TYPE(System::Runtime::Remoting::Channels::CrossAppDomainSink::ProcessMessageRes, "System.Runtime.Remoting.Channels", "CrossAppDomainSink/ProcessMessageRes"); #pragma pack(pop)
1,835
563
#ifndef GDBPLZ_EXPRESSION_HPP_F452FB1B00034F0B81FC533F15A5B280 #define GDBPLZ_EXPRESSION_HPP_F452FB1B00034F0B81FC533F15A5B280 #include <memory> namespace gdbplz { class expression { virtual ~expression() {} virtual std::unique_ptr<expression> freeze() = 0; }; } #endif
278
151
/******************************************************************** created: 2013/10/13 filename: OptimizedIndexGenerator.cc author: Crazii purpose: *********************************************************************/ #include <BladePCH.h> #include "OptimizedIndexGenerator.h" #include <interface/public/graphics/IGraphicsResourceManager.h> #include "../TerrainBufferManager.h" namespace Blade { ////////////////////////////////////////////////////////////////////////// TerrainIndexGroup* OptimizedIndexGenerator::createTileIndexBuffer() { size_t BlockSize = TerrainConfigManager::getSingleton().getTerrainBlockSize(); size_t MaxLod = TerrainConfigManager::getSingleton().getMaxLODLevel(); size_t CurLod = TerrainConfigManager::getSingleton().getLODLevel(); IGraphicsResourceManager* GResMan = TerrainConfigManager::getSingleton().getBatchCombiner()->getResourceManager(); IGraphicsBuffer::USAGE GBU = TerrainConfigManager::getSingleton().getBatchCombiner()->getIndexBufferUsage(); size_t MaxBlockIndexCount = 0; TerrainIndexGroup* group = BLADE_NEW TerrainIndexGroup(); group->mBuffers.resize(MaxLod+1, TerrainIndexGroup::DiffBufferList()); mMaxIndexCount.resize(MaxLod+1); size_t IndexCount = BlockSize*BlockSize*3; uint32 IndexStride = 1; const size_t Size = BlockSize + 1; const size_t VertexCount = (Size)*(Size); //get index type IIndexBuffer::EIndexType indexType = IndexBufferHelper::calcIndexType(VertexCount); for( size_t i = 0; i <= CurLod; ++i ) { TerrainIndexGroup::DiffBufferList& LevelBuffer = group->mBuffers[i]; // 2 triangles if( i == MaxLod ) { assert( IndexCount == 3 ); HIBUFFER& indexbuffer = LevelBuffer[0]; size_t count = IndexCount*2; mMaxIndexCount[i] = count; void* ibData = BLADE_TMP_ALLOC(IndexBufferHelper::calcIndexSize(indexType)*count); IndexBufferHelper ibuffer(ibData, indexType); uint32 p1 = (uint32)(BlockSize*Size); uint32 p2 = p1+(uint32)BlockSize; uint32 p3 = (uint32)BlockSize; // 0 p3 // +-------+ // | \ | // | \ | // | \ | // | \ | // | \ | // +-------+ // p1 p2 ibuffer[0] = 0; ibuffer[1] = p1; ibuffer[2] = p2; ibuffer[3] = 0; ibuffer[4] = p2; ibuffer[5] = p3; indexbuffer = GResMan->createIndexBuffer(ibData, indexType, count, GBU); BLADE_TMP_FREE(ibData); for( index_t j = 1; j < 16; ++j) LevelBuffer[j] = LevelBuffer[0]; } else { //build difference adaptive buffer for( index_t diffIdx = 0; diffIdx < 16; ++diffIdx ) { // level default buffer HIBUFFER& indexbuffer = LevelBuffer[diffIdx]; LODDiff diff = LODDiff::generateLODDifference((LOD_DI)diffIdx); size_t diffCount = diff.getDiffSideCount(); //add additional index for extra LOD triangles size_t CurIndexCount = IndexCount + diffCount*3*( (BlockSize/IndexStride)/2 ); if( CurIndexCount > MaxBlockIndexCount ) MaxBlockIndexCount = CurIndexCount; if( CurIndexCount > mMaxIndexCount[i] ) mMaxIndexCount[i] = CurIndexCount; //TotalIndexCount = CurIndexCount; void* ibData = BLADE_TMP_ALLOC(IndexBufferHelper::calcIndexSize(indexType) * CurIndexCount); IndexBufferHelper ibuffer(ibData, indexType); index_t IndexSub = 0; const uint32 RowStride = (uint32)Size*IndexStride*2; const uint32 ColStride = IndexStride*2; const uint32 RowCount = (uint32)(BlockSize/IndexStride)/2; const uint32 ColCount = (uint32)(BlockSize/IndexStride)/2; uint32 RowA = 0; uint32 RowB = RowStride/2; uint32 RowC = RowStride; uint32 Col0 = 0; uint32 Col1 = IndexStride; uint32 Col2 = IndexStride*2; // for( uint32 z = 0; z < RowCount; ++z) { for( uint32 x = 0; x < ColCount; ++x) { // x x+1 // 0 1 2 //A +-------+ // | \ /| // | \ / | //B | + | // | / \ | // | / \ | //C +-------+ if( diff.hasLevelDifference() ) { assert( i != MaxLod ); assert( BlockSize/IndexStride > 1 ); } if( diff.isUpDiff() && z == 0 ) { //add one triangle //0A,1B,1A ibuffer[IndexSub++] = RowA + Col0; ibuffer[IndexSub++] = RowB + Col1; ibuffer[IndexSub++] = RowA + Col1; //1A,1B,2A ibuffer[IndexSub++] = RowA + Col1; ibuffer[IndexSub++] = RowB + Col1; ibuffer[IndexSub++] = RowA + Col2; } else { //0A,1B,2A ibuffer[IndexSub++] = RowA + Col0; ibuffer[IndexSub++] = RowB + Col1; ibuffer[IndexSub++] = RowA + Col2; } if( diff.isLeftDiff() && x == 0 ) { //0A,0B,1B ibuffer[IndexSub++] = RowA + Col0; ibuffer[IndexSub++] = RowB + Col0; ibuffer[IndexSub++] = RowB + Col1; //0B,0C,1B ibuffer[IndexSub++] = RowB + Col0; ibuffer[IndexSub++] = RowC + Col0; ibuffer[IndexSub++] = RowB + Col1; } else { //0A,0C,1B ibuffer[IndexSub++] = RowA + Col0; ibuffer[IndexSub++] = RowC + Col0; ibuffer[IndexSub++] = RowB + Col1; } if( diff.isDownDiff() && z == RowCount -1 ) { //1B,0C,1C ibuffer[IndexSub++] = RowB + Col1; ibuffer[IndexSub++] = RowC + Col0; ibuffer[IndexSub++] = RowC + Col1; //1B,1C,2C ibuffer[IndexSub++] = RowB + Col1; ibuffer[IndexSub++] = RowC + Col1; ibuffer[IndexSub++] = RowC + Col2; } else { //1B,0C,2C ibuffer[IndexSub++] = RowB + Col1; ibuffer[IndexSub++] = RowC + Col0; ibuffer[IndexSub++] = RowC + Col2; } if( diff.isRightDiff() && x == ColCount -1 ) { //2A,1B,2B ibuffer[IndexSub++] = RowA + Col2; ibuffer[IndexSub++] = RowB + Col1; ibuffer[IndexSub++] = RowB + Col2; //1B,2C,2B ibuffer[IndexSub++] = RowB + Col1; ibuffer[IndexSub++] = RowC + Col2; ibuffer[IndexSub++] = RowB + Col2; } else { //2A,1B,2C ibuffer[IndexSub++] = RowA + Col2; ibuffer[IndexSub++] = RowB + Col1; ibuffer[IndexSub++] = RowC + Col2; } Col0 += ColStride; Col1 += ColStride; Col2 += ColStride; } //clear col index Col0 = 0; Col1 = IndexStride; Col2 = IndexStride*2; //move to next row RowA += RowStride; RowB += RowStride; RowC += RowStride; }//for each block assert( IndexSub == CurIndexCount ); indexbuffer = GResMan->createIndexBuffer(ibData, indexType, CurIndexCount, GBU); BLADE_TMP_FREE(ibData); }// for each diff level }////build difference adaptive buffer IndexCount /= 4; IndexStride *= 2; }//for each LOD level // TERRAIN_INFO info = TerrainConfigManager::getSingleton().getTerrainInfo(); info.mMaxBlockIndexCount = MaxBlockIndexCount; TerrainConfigManager::getSingleton().updateGlobalTerrainInfo(info); return group; } ////////////////////////////////////////////////////////////////////////// TerrainQueryIndexGroup* OptimizedIndexGenerator::createBlockQueryIndexBuffer() { size_t BlockSize = TerrainConfigManager::getSingleton().getTerrainBlockSize(); size_t MaxLod = TerrainConfigManager::getSingleton().getMaxLODLevel(); //size_t CurLod = TerrainConfigManager::getSingleton().getLODLevel(); IGraphicsResourceManager* GResMan = IGraphicsResourceManager::getOtherSingletonPtr(BTString("Software")); TerrainQueryIndexGroup* group = BLADE_NEW TerrainQueryIndexGroup(MaxLod); group->mBuffers.resize(MaxLod+1,TerrainIndexGroup::DiffBufferList()); size_t IndexCount = BlockSize*BlockSize*3; uint32 IndexStride = 1; const size_t Size = BlockSize + 1; const size_t VertexCount = (Size)*(Size); //get index type IIndexBuffer::EIndexType indexType = IndexBufferHelper::calcIndexType(VertexCount); //the top 2 level is simple and could use the Hardware index buffer instead, //so we don't build query buffer for the highest 2 levels for( size_t i = 0; i < MaxLod; ++i ) { TerrainIndexGroup::DiffBufferList& LevelBuffer = group->mBuffers[i]; //build difference adaptive buffer for( index_t diffIdx = 0; diffIdx < 16; ++diffIdx ) { // level default buffer HIBUFFER& indexbuffer = LevelBuffer[diffIdx]; LODDiff diff = LODDiff::generateLODDifference((LOD_DI)diffIdx); size_t diffCount = diff.getDiffSideCount(); //add additional index for extra LOD triangles size_t CurIndexCount = IndexCount + diffCount*3*( (BlockSize/IndexStride)/2 ); void* ibData = BLADE_TMP_ALLOC(IndexBufferHelper::calcIndexSize(indexType) * CurIndexCount); IndexBufferHelper ibuffer(ibData, indexType); const uint32 RowStride = (uint32)Size*IndexStride*2; const uint32 ColStride = IndexStride*2; const uint32 RowCount = (uint32)(BlockSize/IndexStride)/2; const uint32 ColCount = (uint32)(BlockSize/IndexStride)/2; SQueryIndexData data(ibuffer); data.LODLevel = i; data.ColCount = ColCount; data.RowCount = RowCount; data.RowStride = RowStride; data.ColStride = ColStride; data.Diff = diff; data.DiffIndex = (LOD_DI)diffIdx; data.IndexCount = 0; #ifdef DEBUG_DEPTH this->buildQueryIndex(MaxLod-i,0,0,RowCount,group->mQueryQuads[i],data); #else this->buildQueryIndex(0,0,RowCount,group->mQueryQuads[i],data); #endif assert( data.IndexCount == CurIndexCount ); indexbuffer = GResMan->createIndexBuffer(ibData, indexType, CurIndexCount, IGraphicsBuffer::GBU_STATIC); BLADE_TMP_FREE(ibData); }////build difference adaptive buffer IndexCount /= 4; IndexStride *= 2; }//for each LOD level //manual build for max LOD { TerrainIndexGroup::DiffBufferList& LevelBuffer = group->mBuffers[MaxLod]; HIBUFFER& indexbuffer = LevelBuffer[0]; void* ibData = BLADE_TMP_ALLOC(IndexBufferHelper::calcIndexSize(indexType) * 6); IndexBufferHelper ibuffer(ibData , indexType); uint32 p1 = (uint32)(BlockSize*Size); uint32 p2 = p1+(uint32)BlockSize; uint32 p3 = (uint32)BlockSize; // 0 p3 // +-------+ // | \ | // | \ | // | \ | // | \ | // | \ | // +-------+ // p1 p2 ibuffer[0] = 0; ibuffer[1] = p1; ibuffer[2] = p2; ibuffer[3] = 0; ibuffer[4] = p2; ibuffer[5] = p3; indexbuffer = GResMan->createIndexBuffer(ibData, indexType, 6, IGraphicsBuffer::GBU_STATIC); BLADE_TMP_FREE(ibData); for( index_t i = 1; i < 16; ++i) LevelBuffer[i] = LevelBuffer[0]; for( index_t diffIdx = 0; diffIdx < 16; ++diffIdx ) { group->mQueryQuads[MaxLod]->mIndicesByLODDiff[diffIdx].mStartIndex = 0; group->mQueryQuads[MaxLod]->mIndicesByLODDiff[diffIdx].mTriangleCount = 2; } } return group; } ////////////////////////////////////////////////////////////////////////// TerrainFixedIndexGroup* OptimizedIndexGenerator::createFixedIndexBuffer() { TerrainConfigManager& tcm = TerrainConfigManager::getSingleton(); ILODComparator* cmp = this; size_t flatLOD = tcm.getFlatLODLevel(); size_t cliffLOD = tcm.getCliffLODLevel(); size_t LODs[] = { cliffLOD, flatLOD, }; size_t BlockSize = tcm.getTerrainBlockSize(); const size_t Size = BlockSize + 1; const size_t VertexCount = (Size)*(Size); IIndexBuffer::EIndexType indexType = IndexBufferHelper::calcIndexType(VertexCount); IGraphicsResourceManager* GResMan = tcm.getBatchCombiner()->getResourceManager(); IGraphicsBuffer::USAGE GBU = TerrainConfigManager::getSingleton().getBatchCombiner()->getIndexBufferUsage(); TerrainFixedIndexGroup* group = BLADE_NEW TerrainFixedIndexGroup(); index_t curLOD = tcm.getLODLevel(); index_t maxLOD = tcm.getMaxLODLevel(); for (size_t i = 0; i < countOf(LODs); ++i) { index_t LOD = LODs[i]; assert(LOD > 0 && LOD <= curLOD); TerrainFixedIndexGroup::LODBuffer& buffer = (LOD == tcm.getCliffLODLevel()) ? group->mCliffBuffer : group->mFlatBuffer; size_t maxDiff = (size_t)std::max(std::abs(int(0 - LOD)), std::abs(int(curLOD - LOD))); size_t IndexCount = BlockSize * BlockSize * 3; uint32 IndexStride = 1u << std::min(LOD, tcm.getMaxLODLevel()-1); //max LOD is 2 triangle2 that cannot break, use max LOD-1 uint32 diffCount = (uint32)(4u * maxDiff); //4 sides size_t maxIndexCount = IndexCount + diffCount * 3 * ((BlockSize / IndexStride) / 2); for (index_t l = 0; l <= curLOD; ++l) { for (index_t t = 0; t <= curLOD; ++t) { for (index_t r = 0; r <= curLOD; ++r) { for (index_t b = 0; b <= curLOD; ++b) { indexdiff_t ldiff = cmp->compareLOD(l, LOD); indexdiff_t tdiff = cmp->compareLOD(t, LOD); indexdiff_t rdiff = cmp->compareLOD(r, LOD); indexdiff_t bdiff = cmp->compareLOD(b, LOD); FixedLODDiff diff((int8)ldiff, (int8)tdiff, (int8)rdiff, (int8)bdiff); if (!diff.isValid()) continue; HIBUFFER& indexBuffer = buffer[diff]; if (LOD == flatLOD) { if (LOD == maxLOD) { if (ldiff > 0) ldiff -= 1; if (tdiff > 0) tdiff -= 1; if (rdiff > 0) rdiff -= 1; if (bdiff > 0) bdiff -= 1; } if (ldiff == -1) ldiff = 0; if (tdiff == -1) tdiff = 0; if (rdiff == -1) rdiff = 0; if (bdiff == -1) bdiff = 0; diff = FixedLODDiff((int8)ldiff, (int8)tdiff, (int8)rdiff, (int8)bdiff); } TempBuffer tempIBuffer; tempIBuffer.reserve(maxIndexCount); //reserve enough space IndexBufferHelper ibuffer(tempIBuffer.getData(), indexType); const uint32 RowStride = (uint32)Size*IndexStride * 2; const uint32 ColStride = IndexStride * 2; const uint32 RowCount = (uint32)(BlockSize / IndexStride) / 2; const uint32 ColCount = (uint32)(BlockSize / IndexStride) / 2; index_t IndexSub = 0; { uint32 RowA = 0; uint32 RowB = RowStride / 2; uint32 RowC = RowStride; uint32 Col0 = 0; uint32 Col1 = ColStride / 2; uint32 Col2 = ColStride; // x x+1 // 0 1 2 //A +-------+ // | \ /| // | \ / | //B | + | // | / \ | // | / \ | //C +-------+ for (uint32 z = 0; z < RowCount; ++z) { for (uint32 x = 0; x < ColCount; ++x) { //0A,1B,2A if ((z != 0 || diff.t == 0) && (x != 0 || diff.l > -1) && (x != ColCount-1 || diff.r > -1) && (z != RowCount-1 || diff.b > -1)) { ibuffer[IndexSub++] = RowA + Col0; ibuffer[IndexSub++] = RowB + Col1; ibuffer[IndexSub++] = RowA + Col2; } //0A,0C,1B if ((x != 0 || diff.l == 0) && (z != 0 || diff.t > -1) && (z != RowCount-1 || diff.b > -1) && (x != ColCount - 1 || diff.r > -1)) { ibuffer[IndexSub++] = RowA + Col0; ibuffer[IndexSub++] = RowC + Col0; ibuffer[IndexSub++] = RowB + Col1; } //1B,0C,2C if ((z != RowCount-1 || diff.b == 0) && (x != 0 || diff.l > -1) && (x != ColCount-1 || diff.r > -1) && (z != 0 || diff.t > -1)) { ibuffer[IndexSub++] = RowB + Col1; ibuffer[IndexSub++] = RowC + Col0; ibuffer[IndexSub++] = RowC + Col2; } //2A,1B,2C if ((x != ColCount - 1 || diff.r == 0) && (z != 0 || diff.t > -1) && (z != RowCount-1 || diff.b > -1) && (x != 0 || diff.l > -1)) { ibuffer[IndexSub++] = RowA + Col2; ibuffer[IndexSub++] = RowB + Col1; ibuffer[IndexSub++] = RowC + Col2; } Col0 += ColStride; Col1 += ColStride; Col2 += ColStride; } //clear col index Col0 = 0; Col1 = IndexStride; Col2 = IndexStride * 2; //move to next row RowA += RowStride; RowB += RowStride; RowC += RowStride; }//for inner triangles } //left side { uint32 leftRowStride = ldiff < 0 ? RowStride << (-ldiff) : RowStride >> (ldiff); if (ldiff >= 1) { uint32 Col0 = 0; uint32 Col1 = ColStride / 2; for (uint32 z = 0; z < RowCount; ++z) { uint32 Row0 = z * RowStride; uint32 Row1 = Row0 + RowStride / 2; for (uint32 z1 = 0; z1 < (1u << ldiff); ++z1) { ibuffer[IndexSub++] = Row0 + z1 * leftRowStride + Col0; ibuffer[IndexSub++] = Row0 + (z1 + 1) * leftRowStride + Col0; ibuffer[IndexSub++] = Row1 + Col1; } } } else if (ldiff <= -1) { uint32 leftRowCount = RowCount >> (-ldiff); if (leftRowCount == 0)//hard fix for max(min detail) LOD level (2 triangles) { leftRowCount = 1; leftRowStride = RowStride*RowCount; } uint32 Col0 = 0; uint32 Col1 = ColStride; for (uint32 n = 0; n < leftRowCount; ++n) { uint32 Row0 = leftRowStride * n; uint32 Row1 = Row0 + leftRowStride/2; uint32 Row2 = Row0 + leftRowStride; for (uint32 z1 = (n == 0 && tdiff <= -1) ? RowStride : Row0; z1 < Row1; z1 += RowStride) { ibuffer[IndexSub++] = Row0 + Col0; ibuffer[IndexSub++] = (z1 + RowStride) + Col1; ibuffer[IndexSub++] = z1 + Col1; } for (uint32 z1 = (n == leftRowCount -1 && bdiff <= -1) ? (RowCount - 1)*RowStride : Row2; z1 > Row1; z1 -= RowStride) { ibuffer[IndexSub++] = Row2 + Col0; ibuffer[IndexSub++] = z1 + Col1; ibuffer[IndexSub++] = (z1 - RowStride) + Col1; } ibuffer[IndexSub++] = Row0 + Col0; ibuffer[IndexSub++] = Row2 + Col0; ibuffer[IndexSub++] = Row1 + Col1; } } } //top side { uint32 topColStride = tdiff < 0 ? ColStride << (-tdiff) : ColStride >> (tdiff); if (tdiff >= 1) { uint32 Row0 = 0; uint32 Row1 = RowStride / 2; for (uint32 x = 0; x < ColCount; ++x) { uint32 Col0 = x * ColStride; uint32 Col1 = Col0 + ColStride / 2; for (uint32 x1 = 0; x1 < (1u << tdiff); ++x1) { ibuffer[IndexSub++] = Row0 + Col0 + x1 * topColStride; ibuffer[IndexSub++] = Row1 + Col1; ibuffer[IndexSub++] = Row0 + Col0 + (x1 + 1) * topColStride; } } } else if (tdiff <= -1) { uint32 topColCount = ColCount >> (-tdiff); if (topColCount == 0)//hard fix for max LOD level (2 triangles) { topColCount = 1; topColStride = ColStride*ColCount; } uint32 Row0 = 0; uint32 Row1 = RowStride; for (uint32 n = 0; n < topColCount; ++n) { uint32 Col0 = n * topColStride; uint32 Col1 = Col0 + topColStride / 2; uint32 Col2 = Col0 + topColStride; for (uint32 x1 = (n == 0 && ldiff <= -1) ? ColStride : Col0; x1 < Col1; x1 += ColStride) { ibuffer[IndexSub++] = Row0 + Col0; ibuffer[IndexSub++] = Row1 + x1; ibuffer[IndexSub++] = Row1 + (x1 + ColStride); } for (uint32 x1 = (n == topColCount-1 && rdiff <= -1) ? (ColCount - 1)*ColStride : Col2; x1 > Col1; x1 -= ColStride) { ibuffer[IndexSub++] = Row0 + Col2; ibuffer[IndexSub++] = Row1 + (x1 - ColStride); ibuffer[IndexSub++] = Row1 + x1; } ibuffer[IndexSub++] = Row0 + Col0; ibuffer[IndexSub++] = Row1 + Col1; ibuffer[IndexSub++] = Row0 + Col2; } } } //right side (triangle winding order diff from left side) { uint32 rightRowStride = rdiff < 0 ? RowStride << (-rdiff) : RowStride >> (rdiff); if (rdiff >= 1) { uint32 Col0 = (ColCount-1) * ColStride + ColStride / 2; uint32 Col1 = Col0 + ColStride / 2; for (uint32 z = 0; z < RowCount; ++z) { uint32 Row0 = z * RowStride; uint32 Row1 = Row0 + RowStride / 2; for (uint32 z1 = 0; z1 < (1u << rdiff); ++z1) { ibuffer[IndexSub++] = Row0 + z1 * rightRowStride + Col1; ibuffer[IndexSub++] = Row1 + Col0; ibuffer[IndexSub++] = Row0 + (z1 + 1) * rightRowStride + Col1; } } } else if (rdiff <= -1) { uint32 rightRowCount = RowCount >> (-rdiff); if (rightRowCount == 0)//hard fix for max LOD level (2 triangles) { rightRowCount = 1; rightRowStride = RowStride*RowCount; } uint32 Col0 = (ColCount - 1) * ColStride; uint32 Col1 = Col0+ColStride; for (uint32 n = 0; n < rightRowCount; ++n) { uint32 Row0 = rightRowStride * n; uint32 Row1 = Row0 + rightRowStride / 2; uint32 Row2 = Row0 + rightRowStride; for (uint32 z1 = (n == 0 && tdiff <= -1) ? RowStride : Row0; z1 < Row1; z1 += RowStride) { ibuffer[IndexSub++] = Row0 + Col1; ibuffer[IndexSub++] = z1 + Col0; ibuffer[IndexSub++] = (z1 + RowStride) + Col0; } for (uint32 z1 = (n == rightRowCount-1 && bdiff <= -1) ? (RowCount - 1)*RowStride : Row2; z1 > Row1; z1 -= RowStride) { ibuffer[IndexSub++] = Row2 + Col1; ibuffer[IndexSub++] = (z1 - RowStride) + Col0; ibuffer[IndexSub++] = z1 + Col0; } ibuffer[IndexSub++] = Row0 + Col1; ibuffer[IndexSub++] = Row1 + Col0; ibuffer[IndexSub++] = Row2 + Col1; } } } //bottom side { uint32 bottomColStride = bdiff < 0 ? ColStride << (-bdiff) : ColStride >> (bdiff); if (bdiff >= 1) { uint32 Row0 = (RowCount - 1) * RowStride + RowStride / 2; uint32 Row1 = Row0 + RowStride/2; for (uint32 x = 0; x < ColCount; ++x) { uint32 Col0 = x * ColStride; uint32 Col1 = Col0 + ColStride / 2; for (uint32 x1 = 0; x1 < (1u << bdiff); ++x1) { ibuffer[IndexSub++] = Row1 + Col0 + x1 * bottomColStride; ibuffer[IndexSub++] = Row1 + Col0 + (x1 + 1) * bottomColStride; ibuffer[IndexSub++] = Row0 + Col1; } } } else if (bdiff <= -1) { uint32 bottomColCount = ColCount >> (-bdiff); if (bottomColCount == 0)//hard fix for max LOD level (2 triangles) { bottomColCount = 1; bottomColStride = ColStride*ColCount; } uint32 Row0 = (RowCount - 1) * RowStride; uint32 Row1 = Row0 + RowStride; for (uint32 n = 0; n < bottomColCount; ++n) { uint32 Col0 = n * bottomColStride; uint32 Col1 = Col0 + bottomColStride / 2; uint32 Col2 = Col0 + bottomColStride; for (uint32 x1 = (n == 0 && ldiff <= -1) ? ColStride : Col0; x1 < Col1; x1 += ColStride) { ibuffer[IndexSub++] = Row1 + Col0; ibuffer[IndexSub++] = Row0 + (x1 + ColStride); ibuffer[IndexSub++] = Row0 + x1; } for (uint32 x1 = (n == bottomColCount-1 && rdiff <= -1) ? (ColCount - 1)*ColStride : Col2; x1 > Col1; x1 -= ColStride) { ibuffer[IndexSub++] = Row1 + Col2; ibuffer[IndexSub++] = Row0 + x1; ibuffer[IndexSub++] = Row0 + (x1 - ColStride); } ibuffer[IndexSub++] = Row1 + Col0; ibuffer[IndexSub++] = Row1 + Col2; ibuffer[IndexSub++] = Row0 + Col1; } } } assert(IndexSub <= maxIndexCount); indexBuffer = GResMan->createIndexBuffer(tempIBuffer.getData(), indexType, IndexSub, GBU); }// } } } } return group; } ////////////////////////////////////////////////////////////////////////// int16 OptimizedIndexGenerator::getLowLODHeight(const int16* tileHeightaMap, size_t& LOD, index_t blockX, index_t blockZ, index_t x, index_t z) const { LOD = 0; if( (x % 2 == 1 || z % 2 == 1) && !(x % 2 == 1 && z % 2 == 1) ) //optimized index has no odd points, skip return 0; const size_t BlockSize = TerrainConfigManager::getSingleton().getTerrainBlockSize(); //const size_t blockPerSide = TerrainConfigManager::getSingleton().getBlocksPerTileSide(); const size_t TileSize = TerrainConfigManager::getSingleton().getTerrainTileSize(); const size_t SourceSize = TileSize + 1; const int16* blockVPos = tileHeightaMap + (blockZ*BlockSize/*+z*/)*SourceSize + blockX*BlockSize/*+x*/; LOD = TerrainConfigManager::getSingleton().getMaxLODLevel()-1; if( (x == 0 || x == BlockSize ) && (z == 0 || z == BlockSize) ) return blockVPos[z*SourceSize+x]; else if(x == BlockSize/2 && z == BlockSize/2) //lowest LOD level: (p0+p2)/2 return ((int32)blockVPos[0] + (int32)blockVPos[BlockSize*SourceSize+BlockSize])/2; size_t quadSize = BlockSize; index_t quadTop = 0; index_t quadBottom = BlockSize; index_t quadLeft = 0; index_t quadRight = BlockSize; bool cornerLeft = true; bool cornerTop = true; while( quadSize > 2 ) { --LOD; assert( (int)LOD >= 0 ); assert( quadSize > 4 || LOD == 0); assert( quadRight - quadLeft == quadSize ); assert( quadBottom - quadTop == quadSize ); // A // +-------+-------+ // | \ /| / | // | \ / | / | // | E+ | / | // | / \ | / | // | / \ | / | // D +-------+ +B // | / \ | // | / \ | // | / \ | // | / \ | // | / \ | // +-------+-------+ // C //top/bottom border center point (A,C) if( x == quadLeft+quadSize/2 && (z == quadTop || z == quadBottom) ) return ((int32)((int32)blockVPos[z*SourceSize+quadLeft] + (int32)blockVPos[z*SourceSize+quadRight]))/2; //left/right border center point (B,D) if( z == quadTop+quadSize/2 && (x == quadLeft || x == quadRight) ) return ((int32)((int32)blockVPos[quadTop*SourceSize+x] + (int32)blockVPos[quadBottom*SourceSize+x]))/2; if( x < quadLeft+quadSize/2 ) { quadRight -= quadSize/2; cornerLeft = true; } else { quadLeft += quadSize/2; cornerLeft = false; } if( z < quadTop+quadSize/2 ) { quadBottom -= quadSize/2; cornerTop = true; } else { quadTop += quadSize/2; cornerTop = false; } //center point of next level quad (E) if( (x == quadLeft+quadSize/4 || x == quadLeft+quadSize/4*3) && (z == quadTop+quadSize/4 || z == quadTop+quadSize/4*3) ) { if( (cornerLeft && cornerTop) || (!cornerLeft && !cornerTop) ) return ((int32)((int32)blockVPos[(z-quadSize/4)*SourceSize+(x-quadSize/4)] + (int32)blockVPos[(z+quadSize/4)*SourceSize+(x+quadSize/4)]))/2; else return ((int32)((int32)blockVPos[(z-quadSize/4)*SourceSize+(x+quadSize/4)] + (int32)blockVPos[(z+quadSize/4)*SourceSize+(x-quadSize/4)]))/2; } quadSize /= 2; } assert(false); return 0; } ////////////////////////////////////////////////////////////////////////// #if BLADE_DEBUG && DEBUG_DEPTH void OptimizedIndexGenerator::buildQueryIndex(size_t depth,size_t x,size_t z,size_t size,QueryIndexQuad* quad,const SQueryIndexData& data) #else void OptimizedIndexGenerator::buildQueryIndex(size_t x,size_t z,size_t size,QueryIndexQuad* quad,const SQueryIndexData& data) #endif { size_t& IndexSub = data.IndexCount; IndexBufferHelper& ib = data.IndexBuffer; assert(quad != NULL ); #if BLADE_DEBUG && DEBUG_DEPTH if( depth == 1 ) //final { //minimal block assert(size == 1 ); #else if( size == 1) { #endif //all null assert(quad->mSubQuad == NULL ); SQueryIndices& indices = quad->mIndicesByLODDiff[data.DiffIndex]; indices.mStartIndex = (uint16)IndexSub; indices.mTriangleCount = 0; uint32 RowA = uint32(z * data.RowStride); uint32 RowB = RowA + data.RowStride/2; uint32 RowC = RowA + data.RowStride; uint32 Col0 = uint32(x * data.ColStride); uint32 Col1 = Col0 + data.ColStride/2; uint32 Col2 = Col0 + data.ColStride; if( data.Diff.isUpDiff() && z == 0 ) { //add one triangle //0A,1B,1A ib[IndexSub++] = RowA + Col0; ib[IndexSub++] = RowB + Col1; ib[IndexSub++] = RowA + Col1; //1A,1B,2A ib[IndexSub++] = RowA + Col1; ib[IndexSub++] = RowB + Col1; ib[IndexSub++] = RowA + Col2; indices.mTriangleCount += 2; } else { //0A,1B,2A ib[IndexSub++] = RowA + Col0; ib[IndexSub++] = RowB + Col1; ib[IndexSub++] = RowA + Col2; indices.mTriangleCount += 1; } if( data.Diff.isLeftDiff() && x == 0 ) { //0A,0B,1B ib[IndexSub++] = RowA + Col0; ib[IndexSub++] = RowB + Col0; ib[IndexSub++] = RowB + Col1; //0B,0C,1B ib[IndexSub++] = RowB + Col0; ib[IndexSub++] = RowC + Col0; ib[IndexSub++] = RowB + Col1; indices.mTriangleCount += 2; } else { //0A,0C,1B ib[IndexSub++] = RowA + Col0; ib[IndexSub++] = RowC + Col0; ib[IndexSub++] = RowB + Col1; indices.mTriangleCount += 1; } if( data.Diff.isDownDiff() && z == data.RowCount -1 ) { //1B,0C,1C ib[IndexSub++] = RowB + Col1; ib[IndexSub++] = RowC + Col0; ib[IndexSub++] = RowC + Col1; //1B,1C,2C ib[IndexSub++] = RowB + Col1; ib[IndexSub++] = RowC + Col1; ib[IndexSub++] = RowC + Col2; indices.mTriangleCount += 2; } else { //1B,0C,2C ib[IndexSub++] = RowB + Col1; ib[IndexSub++] = RowC + Col0; ib[IndexSub++] = RowC + Col2; indices.mTriangleCount += 1; } if( data.Diff.isRightDiff() && x == data.ColCount -1 ) { //2A,1B,2B ib[IndexSub++] = RowA + Col2; ib[IndexSub++] = RowB + Col1; ib[IndexSub++] = RowB + Col2; //1B,2C,2B ib[IndexSub++] = RowB + Col1; ib[IndexSub++] = RowC + Col2; ib[IndexSub++] = RowB + Col2; indices.mTriangleCount += 2; } else { //2A,1B,2C ib[IndexSub++] = RowA + Col2; ib[IndexSub++] = RowB + Col1; ib[IndexSub++] = RowC + Col2; indices.mTriangleCount += 1; } } else { size_t subSize = size/2; #if BLADE_DEBUG && DEBUG_DEPTH buildQueryIndex(depth-1,x ,z ,subSize,quad->mSubQuad[0],data); buildQueryIndex(depth-1,x+subSize ,z ,subSize,quad->mSubQuad[1],data); buildQueryIndex(depth-1,x ,z+subSize ,subSize,quad->mSubQuad[2],data); buildQueryIndex(depth-1,x+subSize ,z+subSize ,subSize,quad->mSubQuad[3],data); #else buildQueryIndex(x ,z ,subSize,&quad->mSubQuad[0],data); buildQueryIndex(x+subSize ,z ,subSize,&quad->mSubQuad[1],data); buildQueryIndex(x ,z+subSize ,subSize,&quad->mSubQuad[2],data); buildQueryIndex(x+subSize ,z+subSize ,subSize,&quad->mSubQuad[3],data); #endif SQueryIndices& indices = quad->mIndicesByLODDiff[data.DiffIndex]; indices.mStartIndex = quad->mSubQuad[0].mIndicesByLODDiff[data.DiffIndex].mStartIndex; indices.mTriangleCount = 0; for(size_t i = 0; i < 4; ++i) indices.mTriangleCount += quad->mSubQuad[i].mIndicesByLODDiff[data.DiffIndex].mTriangleCount; } } }//namespace Blade
31,889
16,528
/* Copyright (c) 2013-2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <utility> #include "util/lazy_list_fn.h" #include "util/sstream.h" #include "util/name_map.h" #include "util/sexpr/option_declarations.h" #include "kernel/for_each_fn.h" #include "kernel/replace_fn.h" #include "kernel/instantiate.h" #include "kernel/abstract.h" #include "kernel/error_msgs.h" #include "kernel/type_checker.h" #include "library/reducible.h" #include "library/unifier.h" #include "library/occurs.h" #include "library/constants.h" #include "library/type_util.h" #include "library/class_instance_resolution.h" #include "library/tactic/expr_to_tactic.h" #include "library/tactic/apply_tactic.h" #ifndef LEAN_DEFAULT_APPLY_CLASS_INSTANCE #define LEAN_DEFAULT_APPLY_CLASS_INSTANCE true #endif namespace lean { static name * g_apply_class_instance = nullptr; bool get_apply_class_instance(options const & opts) { return opts.get_bool(*g_apply_class_instance, LEAN_DEFAULT_APPLY_CLASS_INSTANCE); } /** \brief Given a sequence metas: <tt>(?m_1 ...) (?m_2 ... ) ... (?m_k ...)</tt>, we say ?m_i is "redundant" if it occurs in the type of some ?m_j. This procedure removes from metas any redundant element. */ static void remove_redundant_metas(buffer<expr> & metas) { buffer<expr> mvars; for (expr const & m : metas) mvars.push_back(get_app_fn(m)); unsigned k = 0; for (unsigned i = 0; i < metas.size(); i++) { bool found = false; for (unsigned j = 0; j < metas.size(); j++) { if (j != i) { if (occurs(mvars[i], mlocal_type(mvars[j]))) { found = true; break; } } } if (!found) { metas[k] = metas[i]; k++; } } metas.shrink(k); } enum subgoals_action_kind { IgnoreSubgoals, AddRevSubgoals, AddSubgoals, AddAllSubgoals }; enum add_meta_kind { DoNotAdd, AddDiff, AddAll }; static proof_state_seq apply_tactic_core(environment const & env, io_state const & ios, proof_state const & s, expr const & _e, buffer<constraint> & cs, add_meta_kind add_meta, subgoals_action_kind subgoals_action, optional<unifier_kind> const & uk = optional<unifier_kind>()) { goals const & gs = s.get_goals(); if (empty(gs)) { throw_no_goal_if_enabled(s); return proof_state_seq(); } bool class_inst = get_apply_class_instance(ios.get_options()); std::shared_ptr<type_checker> tc(mk_type_checker(env)); goal g = head(gs); goals tail_gs = tail(gs); expr t = g.get_type(); expr e = _e; auto e_t_cs = tc->infer(e); e_t_cs.second.linearize(cs); expr e_t = e_t_cs.first; buffer<expr> metas; old_local_context ctx; bool initialized_ctx = false; unifier_config cfg(ios.get_options()); if (uk) cfg.m_kind = *uk; if (add_meta != DoNotAdd) { unsigned num_e_t = get_expect_num_args(*tc, e_t); if (add_meta == AddDiff) { unsigned num_t = get_expect_num_args(*tc, t); if (num_t <= num_e_t) num_e_t -= num_t; else num_e_t = 0; } else { lean_assert(add_meta == AddAll); } for (unsigned i = 0; i < num_e_t; i++) { auto e_t_cs = tc->whnf(e_t); e_t_cs.second.linearize(cs); e_t = e_t_cs.first; expr meta; if (class_inst && binding_info(e_t).is_inst_implicit()) { if (!initialized_ctx) { ctx = g.to_local_context(); initialized_ctx = true; } bool use_local_insts = true; bool is_strict = false; auto mc = mk_class_instance_elaborator( env, ios, ctx, optional<name>(), use_local_insts, is_strict, some_expr(head_beta_reduce(binding_domain(e_t))), e.get_tag(), nullptr); meta = mc.first; cs.push_back(mc.second); } else { meta = g.mk_meta(mk_fresh_name(), head_beta_reduce(binding_domain(e_t))); } e = mk_app(e, meta); e_t = instantiate(binding_body(e_t), meta); metas.push_back(meta); } } pair<bool, constraint_seq> dcs = tc->is_def_eq(t, e_t); if (!dcs.first) { throw_tactic_exception_if_enabled(s, [=](formatter const & fmt) { format r = format("invalid 'apply' tactic, failed to unify"); r += pp_indent_expr(fmt, t); r += compose(line(), format("with")); r += pp_indent_expr(fmt, e_t); return r; }); return proof_state_seq(); } dcs.second.linearize(cs); unify_result_seq rseq = unify(env, cs.size(), cs.data(), s.get_subst(), cfg); list<expr> meta_lst = to_list(metas.begin(), metas.end()); return map2<proof_state>(rseq, [=](pair<substitution, constraints> const & p) -> proof_state { substitution const & subst = p.first; constraints const & postponed = p.second; substitution new_subst = subst; expr new_e = new_subst.instantiate_all(e); assign(new_subst, g, new_e); goals new_gs = tail_gs; if (subgoals_action != IgnoreSubgoals) { buffer<expr> metas; for (auto m : meta_lst) { if (!new_subst.is_assigned(get_app_fn(m))) metas.push_back(m); } if (subgoals_action == AddRevSubgoals) { for (unsigned i = 0; i < metas.size(); i++) new_gs = cons(goal(metas[i], new_subst.instantiate_all(tc->infer(metas[i]).first)), new_gs); } else { lean_assert(subgoals_action == AddSubgoals || subgoals_action == AddAllSubgoals); if (subgoals_action == AddSubgoals) remove_redundant_metas(metas); unsigned i = metas.size(); while (i > 0) { --i; new_gs = cons(goal(metas[i], new_subst.instantiate_all(tc->infer(metas[i]).first)), new_gs); } } } return proof_state(s, new_gs, new_subst, postponed); }); } proof_state_seq apply_tactic_core(environment const & env, io_state const & ios, proof_state const & s, expr const & e, constraint_seq const & cs) { buffer<constraint> tmp_cs; cs.linearize(tmp_cs); return apply_tactic_core(env, ios, s, e, tmp_cs, AddDiff, AddSubgoals); } proof_state_seq fapply_tactic_core(environment const & env, io_state const & ios, proof_state const & s, expr const & e, constraint_seq const & cs) { buffer<constraint> tmp_cs; cs.linearize(tmp_cs); return apply_tactic_core(env, ios, s, e, tmp_cs, AddDiff, AddAllSubgoals); } tactic apply_tactic_core(expr const & e, constraint_seq const & cs) { return tactic([=](environment const & env, io_state const & ios, proof_state const & s) { return apply_tactic_core(env, ios, s, e, cs); }); } tactic apply_tactic_core(elaborate_fn const & elab, expr const & e, add_meta_kind add_meta, subgoals_action_kind k) { return tactic([=](environment const & env, io_state const & ios, proof_state const & s) { goals const & gs = s.get_goals(); if (empty(gs)) { throw_no_goal_if_enabled(s); return proof_state_seq(); } goal const & g = head(gs); expr new_e; substitution new_subst; constraints cs_; try { auto ecs = elab(g, ios.get_options(), e, none_expr(), s.get_subst(), false); std::tie(new_e, new_subst, cs_) = ecs; buffer<constraint> cs; to_buffer(cs_, cs); to_buffer(s.get_postponed(), cs); proof_state new_s(s, new_subst, constraints()); return apply_tactic_core(env, ios, new_s, new_e, cs, add_meta, k); } catch (exception &) { if (s.report_failure()) throw; else return proof_state_seq(); } }); } tactic apply_tactic(elaborate_fn const & elab, expr const & e) { return apply_tactic_core(elab, e, AddDiff, AddSubgoals); } tactic fapply_tactic(elaborate_fn const & elab, expr const & e) { return apply_tactic_core(elab, e, AddDiff, AddAllSubgoals); } tactic eapply_tactic(elaborate_fn const & elab, expr const & e) { return apply_tactic_core(elab, e, AddAll, AddSubgoals); } void initialize_apply_tactic() { g_apply_class_instance = new name{"apply", "class_instance"}; register_bool_option(*g_apply_class_instance, LEAN_DEFAULT_APPLY_CLASS_INSTANCE, "(apply tactic) if true apply tactic uses class-instances " "resolution for instance implicit arguments"); register_tac(get_tactic_apply_name(), [](type_checker &, elaborate_fn const & fn, expr const & e, pos_info_provider const *) { check_tactic_expr(app_arg(e), "invalid 'apply' tactic, invalid argument"); return apply_tactic(fn, get_tactic_expr_expr(app_arg(e))); }); register_tac(get_tactic_eapply_name(), [](type_checker &, elaborate_fn const & fn, expr const & e, pos_info_provider const *) { check_tactic_expr(app_arg(e), "invalid 'eapply' tactic, invalid argument"); return eapply_tactic(fn, get_tactic_expr_expr(app_arg(e))); }); register_tac(get_tactic_fapply_name(), [](type_checker &, elaborate_fn const & fn, expr const & e, pos_info_provider const *) { check_tactic_expr(app_arg(e), "invalid 'fapply' tactic, invalid argument"); return fapply_tactic(fn, get_tactic_expr_expr(app_arg(e))); }); } void finalize_apply_tactic() { delete g_apply_class_instance; } }
10,561
3,431
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup() { ofEnableSmoothing(); ofSetCircleResolution(60); red = 100; blue = 100; green = 100; drawPadding = false; gui0 = new ofxUISuperCanvas("SLIDER WIDGETS"); gui0->addSpacer(); gui0->addFPSSlider("FPS SLIDER"); gui0->addSpacer(); gui0->addLabel("NORMAL SLIDER"); gui0->addSlider("RED", 0.0, 255.0, &red); gui0->addSpacer(); gui0->addLabel("MINIMAL SLIDER"); gui0->addMinimalSlider("GREEN", 0.0, 255.0, &green); gui0->addSpacer(); gui0->addLabel("BILABEL SLIDER"); gui0->addBiLabelSlider("BLUE", "LESS BLUE", "MORE BLUE", 0.0, 255.0, &blue); gui0->addSpacer(); gui0->addLabel("VERTICAL SLIDERS"); gui0->addSlider("1", 0.0, 255.0, 100.0, 17, 64); gui0->setWidgetPosition(OFX_UI_WIDGET_POSITION_RIGHT); gui0->addSlider("2", 0.0, 255.0, 150.0, 17, 64); gui0->addSlider("3", 0.0, 255.0, 200.0, 17, 64); gui0->addSlider("4", 0.0, 255.0, 250.0, 17, 64); gui0->addSlider("5", 0.0, 255.0, 250.0, 17, 64); gui0->addSlider("6", 0.0, 255.0, 250.0, 17, 64); gui0->addSlider("7", 0.0, 255.0, 250.0, 17, 64); gui0->addSlider("8", 0.0, 255.0, 250.0, 17, 64); gui0->addSlider("9", 0.0, 255.0, 250.0, 17, 64); gui0->setWidgetPosition(OFX_UI_WIDGET_POSITION_DOWN); gui0->addSpacer(); gui0->addLabel("RANGE SLIDER"); gui0->addRangeSlider("RANGE", 0.0, 255.0, &blue, &green); gui0->addSpacer(); gui0->addLabel("TEMPLATED SLIDERS"); gui0->addIntSlider("INT SLIDER", 0, 100, 50); gui0->addSlider("FLOAT SLIDER", 0.0, 100.0, 50.0); gui0->addDoubleSlider("DOUBLE SLIDER", 0.0, 100.0, 50.0); gui0->addSpacer(); gui0->addLabel("ROTARY SLIDER"); gui0->addRotarySlider("ROTARY", 0.0, 255.0, &red); gui0->autoSizeToFitWidgets(); ofAddListener(gui0->newGUIEvent,this,&ofApp::guiEvent); gui1 = new ofxUISuperCanvas("MORE SLIDERS"); gui1->setPosition(212, 0); gui1->addSpacer(); gui1->addLabel("2D PAD"); gui1->add2DPad("PAD", ofVec2f(-100, 100), ofVec2f(-100, 100), ofVec2f(0, 0)); gui1->addSpacer(); gui1->addLabel("CIRCLE SLIDER"); gui1->addCircleSlider("GREEN", 0.0, 255.0, &green); gui1->addSpacer(); gui1->addLabel("IMAGE SLIDER"); gui1->setGlobalSliderHeight(32); gui1->addImageSlider("IMAGE SLIDER", "slider.png", 0.0, 255.0, &red); gui1->autoSizeToFitWidgets(); ofAddListener(gui1->newGUIEvent,this,&ofApp::guiEvent); ofBackground(red, green, blue); } //-------------------------------------------------------------- void ofApp::update() { } //-------------------------------------------------------------- void ofApp::draw() { ofBackground(red, green, blue, 255); } //-------------------------------------------------------------- void ofApp::guiEvent(ofxUIEventArgs &e) { } //-------------------------------------------------------------- void ofApp::exit() { delete gui0; delete gui1; } //-------------------------------------------------------------- void ofApp::keyPressed(int key) { switch (key) { case 'p': { drawPadding = !drawPadding; gui0->setDrawWidgetPadding(drawPadding); } break; case 'g': { gui0->toggleVisible(); } break; default: break; } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ) { // gui0->getRect()->setHeight(y); } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button) { } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button) { } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button) { } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h) { } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
4,363
1,786
/** * @copyright Copyright (c) 2015 All Right Reserved, B-com http://www.b-com.com/ * * This file is subject to the B<>Com License. * All other rights reserved. * * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A * PARTICULAR PURPOSE. * * @author Loïc Touraine * * @file * @brief description of file * @date 2015-09-18 */ #include <stdio.h> #include "ComponentTemplate.h" // XPCF_ComponentBase #include "ComponentBase.h" XPCF_DEFINE_FACTORY_CREATE_INSTANCE(client::ComponentTemplate); namespace client { ComponentTemplate::ComponentTemplate ():ComponentBase(xpcf::toMap<ComponentTemplate>()) { addInterface<ITemplateInterface>(this); } ComponentTemplate::~ComponentTemplate () { } void ComponentTemplate::unloadComponent () { std::cout<<m_name<<"::"<<"ComponentTemplate::unload () called!"<<std::endl; delete this; return; } }
1,014
374
/* * Copyright (c) 2019 TOYOTA MOTOR CORPORATION * * 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 <unistd.h> #include <cstring> #include "hs-appinfo.h" #include "hs-helper.h" #include "hs-clientmanager.h" #include <stdio.h> // standard input / output functions #include <stdlib.h> #include <string.h> // string function definitions #include <unistd.h> // UNIX standard function definitions #include <fcntl.h> // File control definitions #include <errno.h> // Error number definitions #include <termios.h> // POSIX terminal control definitions #include <pthread.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <time.h> #define RETRY_CNT 10 const char _keyName[] = "name"; const char _keyVersion[] = "version"; const char _keyInstall[] = "install"; const char _keyUninstall[] = "uninstall"; const char _keyOperation[] = "operation"; const char _keyRunnables[] = "runnables"; const char _keyStart[] = "start"; const char _keyApplistChanged[] = "application-list-changed"; HS_AppInfo* HS_AppInfo::me = nullptr; const std::unordered_map<std::string, HS_AppInfo::func_handler> HS_AppInfo::concerned_event_list { {"afm-main/application-list-changed", &HS_AppInfo::updateAppDetailList} }; /** * event hook function * * #### Parameters * - api : the api serving the request * - event : event name * - object : event json object * * #### Return * 0 : continue transfer * 1 : blocked * */ static int eventHandler(afb_api_t api, const char *event, struct json_object *object) { return HS_AppInfo::instance()->onEvent(api, event, object); } /** * get application property function * * #### Parameters * - key : retrieve keyword * * #### Return * retrieved property * */ std::string AppDetail::getProperty(std::string key) const { struct json_object *j_obj; struct json_object *j_detail = json_tokener_parse(this->detail.c_str()); if(json_object_object_get_ex(j_detail, key.c_str(), &j_obj) == 0) { AFB_WARNING("can't find key=%s.", key.c_str()); return std::string(); } return std::string(json_object_get_string(j_obj)); } /** * HS_AppInfo destruction function * * #### Parameters * - Nothing * * #### Return * None * */ HS_AppInfo::~HS_AppInfo() { if(afmmain) delete afmmain; } typedef struct { unsigned char msgRcv[0xFF]; unsigned char iCount; unsigned char isValid; }SERIAL_DATA_QUEUE; pthread_mutex_t mutexsync; pthread_mutex_t mutexSerialSync; pthread_t tid; int fdUSB = 0x00; int icount = 0x00; SERIAL_DATA_QUEUE g_serial_rcv; void printLogMsg(char *msg) { FILE *f = fopen("/home/1001/app-data/agl-service-homescreen/file.txt", "a"); if (f == NULL) { printf("Error opening file!\n"); exit(1); } fprintf(f, "%s\n", msg); fclose(f); } void setSerialRcv(unsigned char *buffer, int icound) { pthread_mutex_lock (&mutexsync); int idx = 0x00; g_serial_rcv.iCount = icound; for(idx = 0x00; idx < icound; idx++) { g_serial_rcv.msgRcv[idx] = buffer[idx]; } g_serial_rcv.isValid = 0x20; pthread_mutex_unlock (&mutexsync); } bool sendHeartBeat() { bool retVal = false; pthread_mutex_lock (&mutexSerialSync); if(fdUSB != 0x00) { char syncByte = 0xA5; if(write (fdUSB, &syncByte, 1) < 0x00) { printLogMsg((char*)"sendHeartBeat, write socket error\n\r"); } else { printLogMsg((char*)"sendHeartBeat successed\n\r"); retVal = true; } } pthread_mutex_unlock (&mutexSerialSync); return retVal; } void printserial() { return; printLogMsg((char*)"printserial"); close(fdUSB);fdUSB = open( "/dev/ttyS0", O_RDWR| O_NOCTTY ); struct termios tty; struct termios tty_old; memset (&tty, 0, sizeof tty); /* Error Handling */ if ( tcgetattr ( fdUSB, &tty ) != 0 ) { //printLogMsg((char*)"Open /dev/ttyS0 failed, fdUSB: %d", fdUSB); printLogMsg((char*)"printserial Open /dev/ttyS0 failed"); return; } printLogMsg((char*)"printserial do serial config"); /* Save old tty parameters */ tty_old = tty; /* Set Baud Rate */ cfsetospeed (&tty, (speed_t)B115200); /* Setting other Port Stuff */ tty.c_cflag &= ~PARENB; // Make 8n1 tty.c_cflag &= ~CSTOPB; tty.c_cflag &= ~CSIZE; tty.c_cflag |= CS8; tty.c_cflag &= ~CRTSCTS; // no flow control tty.c_cc[VMIN] = 1; // read doesn't block tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout tty.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines /* Make raw */ cfmakeraw(&tty); printLogMsg((char*)"printserial flush usb"); /* Flush Port, then applies attributes */ tcflush( fdUSB, TCIFLUSH ); if ( tcsetattr ( fdUSB, TCSANOW, &tty ) != 0) { close(fdUSB); printLogMsg((char*)"printserial flush usb failed"); return; } if(fdUSB != 0x00) { printLogMsg((char*)"printserial writing data to serial"); if(write (fdUSB, "K-Auto hello!\n", strlen("K-Auto hello!\n")) < 0x00) { close(fdUSB); fdUSB = 0x00; return; } } fdUSB = 0x00; } #define UNUSED(x) (void)(x) void* doSomeThing(void *arg) { UNUSED(arg); usleep(10000000);//10s #if 0 int seconds = 0x00; int odo = 12500; int curSpeed = 30; int batteryLev = 60; int signalLightLeft = 0x00; int signalLightRight = 0x01; #endif int listenfd = 0, connfd = 0; struct sockaddr_in serv_addr; char sendBuff[1025]; //time_t ticks; listenfd = socket(AF_INET, SOCK_STREAM, 0); memset(&serv_addr, '0', sizeof(serv_addr)); memset(sendBuff, '0', sizeof(sendBuff)); serv_addr.sin_family = AF_INET; //serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); //serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");//htonl("127.0.0.1"); serv_addr.sin_addr.s_addr = inet_addr("127.192.90.189");//htonl("127.0.0.1"); serv_addr.sin_port = htons(5000); bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); listen(listenfd, 10); connfd = accept(listenfd, (struct sockaddr*)NULL, NULL); while(1) { //usleep(1000000);//1s //printserial(); //continue; //{"odo":12500, "curSpeed":30, "batteryLev":60, signalLightLeft:0, signalLightRight:1} //ticks = time(NULL); #if 0 if((seconds % 3) == 0x00) { odo++; } if((seconds % 1) == 0x00) { curSpeed = (rand() % (70 - 55 + 1)) + 55; } if((seconds % 5) == 0x00 && batteryLev > 0x00) { batteryLev--; } if((seconds % 10) == 0x00) { signalLightLeft = 0x01; signalLightRight = 0x00; } else { signalLightLeft = 0x00; signalLightRight = 0x01; } snprintf(sendBuff, sizeof(sendBuff), "{\"odo\":%d, \"curSpeed\":%d, \"batteryLev\":%d, \"signalLightLeft\":%d, \"signalLightRight\":%d}", odo, curSpeed, batteryLev, signalLightLeft, signalLightRight); if(write(connfd, sendBuff, strlen(sendBuff)) < 0x00) { printLogMsg((char*)"write socket error\n\r"); } seconds++; #endif pthread_mutex_lock (&mutexsync); if(g_serial_rcv.isValid == 0x20) { g_serial_rcv.isValid = 0x00; snprintf(sendBuff, sizeof(sendBuff), "{\"odo\":%d, \"curSpeed\":%d, \"batteryLev\":%d, \"signalLightLeft\":%d, \"signalLightRight\":%d}", g_serial_rcv.msgRcv[3], g_serial_rcv.msgRcv[4], g_serial_rcv.msgRcv[5], g_serial_rcv.msgRcv[6], g_serial_rcv.msgRcv[7]); if(write(connfd, sendBuff, strlen(sendBuff)) < 0x00) { printLogMsg((char*)"write socket error\n\r"); } } pthread_mutex_unlock (&mutexsync); usleep(1000000);//1s } close(connfd); return NULL; } #define MAX_RECEIVING_BUFFER 0xFF //CRC POLYNOMIAL parameter #define CRC_POLYNOMIAL 0x131 #define MESSAGE_HEADER_01 0xA5 #define MESSAGE_HEADER_02 0x5A enum State_enum { CLI_COMMAND_UNKNOWN = 0x00, CLI_COMMAND_HEADER_01 = 0x01, CLI_COMMAND_HEADER_02 = 0x02, CLI_COMMAND_OPTYPE = 0x03, CLI_COMMAND_DATA_LENGTH = 0x04, CLI_COMMAND_DATA = 0x05, CLI_COMMAND_CRC = 0x06, CLI_COMMAND_COMPLETE = 0x07, }; unsigned char m_arru8_receivingbuff[MAX_RECEIVING_BUFFER]; char msgBuffer[0xFF]; int heartBeatCount = 0x00; #define UNUSED(x) (void)(x) int openSerialPort() { int serialfd = 0x00; //serialfd = open( "/dev/ttyS0", O_RDWR| O_NOCTTY | O_NDELAY ); serialfd = open( "/dev/ttyUSB0", O_RDWR| O_NOCTTY | O_NDELAY ); struct termios tty; struct termios tty_old; memset (&tty, 0, sizeof tty); /* Error Handling */ if ( tcgetattr ( serialfd, &tty ) != 0 ) { printLogMsg((char*)"openSerialPort Open /dev/ttyS0 failed"); return 0x00; } tcflush(fdUSB, TCIOFLUSH); /* Save old tty parameters */ tty_old = tty; /* Set Baud Rate */ cfsetospeed (&tty, (speed_t)B115200); /* Setting other Port Stuff */ tty.c_cflag &= ~PARENB; // Make 8n1 tty.c_cflag &= ~CSTOPB; tty.c_cflag &= ~CSIZE; tty.c_cflag |= CS8; tty.c_cflag &= ~CRTSCTS; // no flow control tty.c_cc[VMIN] = 1; // read doesn't block tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout tty.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines /* Make raw */ cfmakeraw(&tty); cfsetispeed(&tty, cfgetospeed(&tty)); /* Flush Port, then applies attributes */ tcflush( fdUSB, TCIFLUSH ); if ( tcsetattr ( fdUSB, TCSANOW, &tty ) != 0) { close(fdUSB); printLogMsg((char*)"openSerialPort tcsetattr failed"); return 0x00; } return serialfd; } void* kAutoSerialComunication(void *arg) { UNUSED(arg); bool isSerialInitSuccessed = false; int m_u8state = CLI_COMMAND_UNKNOWN; unsigned char m_u8receiveCount = 0x00; unsigned char u8datalength = 0x00; static char inChar = 0x00; pthread_mutex_lock (&mutexSerialSync); if(fdUSB != 0x00) { close(fdUSB); } while(isSerialInitSuccessed == false) { fdUSB = openSerialPort(); if(fdUSB != 0x00) { isSerialInitSuccessed = true; } } pthread_mutex_unlock (&mutexSerialSync); m_u8state = CLI_COMMAND_HEADER_01; while(1) { pthread_mutex_lock (&mutexSerialSync); if(read(fdUSB, &inChar, 1) > 0x00) { memset(msgBuffer, 0x00, 0xFF); sprintf((char*)msgBuffer, "Data received: %d, m_u8state: %d\n\r", inChar, m_u8state); printLogMsg((char*)msgBuffer); switch(m_u8state) { case CLI_COMMAND_HEADER_01: { if(inChar == MESSAGE_HEADER_01) { m_u8receiveCount = 0x00; m_arru8_receivingbuff[m_u8receiveCount++] = inChar; m_u8state = CLI_COMMAND_HEADER_02; printLogMsg((char*)"Receive header 1\n\r"); } } break; case CLI_COMMAND_HEADER_02: { if(inChar == MESSAGE_HEADER_02) { m_arru8_receivingbuff[m_u8receiveCount++] = inChar; m_u8state = CLI_COMMAND_DATA_LENGTH; printLogMsg((char*)"Receive header 2\n\r"); } } break; case CLI_COMMAND_DATA_LENGTH: { u8datalength = inChar; m_arru8_receivingbuff[m_u8receiveCount++] = inChar; m_u8state = CLI_COMMAND_DATA; printLogMsg((char*)"Receive data length\n\r"); } break; case CLI_COMMAND_DATA: { if( u8datalength > 0) { m_arru8_receivingbuff[m_u8receiveCount++] = inChar; u8datalength--; printLogMsg((char*)"Receive data ..\n\r"); } if(u8datalength == 0) { m_u8state = CLI_COMMAND_CRC; //printLogMsg((char*)"Receive data complete, switch to CRC\n\r"); } } break; case CLI_COMMAND_CRC: { m_arru8_receivingbuff[m_u8receiveCount++] = inChar; /*complete*/ //msg.deserialize((const char*)m_arru8_receivingbuff, m_u8receiveCount); setSerialRcv((unsigned char *)m_arru8_receivingbuff, m_u8receiveCount); /*reset package*/ m_u8state = CLI_COMMAND_HEADER_01; m_u8receiveCount = 0x00; u8datalength = 0x00; printLogMsg((char*)"Receive CRC, message complete\n\r"); } break; } } pthread_mutex_unlock (&mutexSerialSync); #if 0 usleep(1000);//delay for 1 milisecond if(heartBeatCount++ > 2000)//2 seconds { if(sendHeartBeat() == false) { close(fdUSB); printLogMsg((char*)"Serial write failed, try to open again\n\r"); fdUSB = openSerialPort(); } heartBeatCount = 0x00; } #endif } if(fdUSB != 0x00) { close(fdUSB); } return NULL; } int iCountDelay = 0x00; void* kAutoHeartBeat(void *arg) { UNUSED(arg); while(1) { if(iCountDelay > 1000) { sendHeartBeat(); iCountDelay = 0x00; } usleep(1000);//delay for 1 milisecond iCountDelay++; } return NULL; } /** * get instance * * #### Parameters * - Nothing * * #### Return * HS_AppInfo instance pointer * */ HS_AppInfo* HS_AppInfo::instance(void) { if(me == nullptr) { me = new HS_AppInfo(); pthread_mutex_init(&mutexsync, NULL); pthread_mutex_init(&mutexSerialSync, NULL); pthread_create(&tid, NULL, &doSomeThing, NULL); pthread_create(&tid, NULL, &kAutoSerialComunication, NULL); //pthread_create(&tid, NULL, &kAutoHeartBeat, NULL); } return me; } /** * HS_AppInfo initialize function * * #### Parameters * - api : the api serving the request * * #### Return * 0 : init success * 1 : init fail * */ int HS_AppInfo::init(afb_api_t api) { afmmain = new HS_AfmMainProxy(); if(afmmain == nullptr) { AFB_ERROR("new HS_AfmMainProxy failed"); return -1; } struct json_object* j_runnable = nullptr; int retry = 0; do { if(afmmain->runnables(api, &j_runnable) == 0) { createAppDetailList(j_runnable); json_object_put(j_runnable); break; } ++retry; if(retry == RETRY_CNT) { AFB_ERROR("get runnables list failed"); json_object_put(j_runnable); return -1; } AFB_DEBUG("retry to get runnables list %d", retry); usleep(100000); // 100ms } while(1); for(auto &ref : concerned_event_list) { setEventHook(ref.first.c_str(), eventHandler); } return 0; } /** * onEvent function * * #### Parameters * - api : the api serving the request * - event : event name * - object : event json object * * #### Return * 0 : continue transfer * 1 : blocked */ int HS_AppInfo::onEvent(afb_api_t api, const char *event, struct json_object *object) { int ret = 0; auto ip = concerned_event_list.find(std::string(event)); if(ip != concerned_event_list.end()) { ret = (this->*(ip->second))(api, object); } return ret; } /** * create application detail list function * * #### Parameters * - object : the detail of all applications * * #### Return * None * */ void HS_AppInfo::createAppDetailList(struct json_object *object) { AFB_DEBUG("applist:%s", json_object_to_json_string(object)); if(json_object_get_type(object) == json_type_array) { int array_len = json_object_array_length(object); for (int i = 0; i < array_len; ++i) { struct json_object *obj = json_object_array_get_idx(object, i); addAppDetail(obj); } } else { AFB_ERROR("Apps information input error."); } } /** * update application detail function * * #### Parameters * - object : the detail of all applications * * #### Return * 0 : continue transfer * 1 : blocked * */ int HS_AppInfo::updateAppDetailList(afb_api_t api, struct json_object *object) { AFB_DEBUG("update:%s", json_object_to_json_string(object)); if(json_object_get_type(object) != json_type_object) { AFB_ERROR("input detail object error."); return 1; } struct json_object *obj_oper, *obj_data; if(json_object_object_get_ex(object, _keyOperation, &obj_oper) == 0 || json_object_object_get_ex(object, _keyData, &obj_data) == 0) { AFB_ERROR("can't find key=%s, %s.", _keyOperation, _keyData); return 1; } std::string id = json_object_get_string(obj_data); std::string appid = id2appid(id); if(isPeripheryApp(appid.c_str())) { AFB_INFO( "install/uninstall application is periphery."); return 1; } std::string oper = json_object_get_string(obj_oper); if(oper == _keyInstall) { struct json_object* j_runnable = nullptr; int ret = afmmain->runnables(api, &j_runnable); if(!ret) { struct json_object *j_found = retrieveRunnables(j_runnable, id); if(j_found == nullptr) { AFB_INFO( "installed application isn't runnables."); json_object_put(j_runnable); return 1; } addAppDetail(json_object_get(j_found)); pushAppListChangedEvent(_keyInstall, j_found); } else { AFB_ERROR("get runnalbes failed."); } json_object_put(j_runnable); } else if(oper == _keyUninstall) { std::string appid_checked = checkAppId(appid); if(appid_checked.empty()) { AFB_INFO("uninstalled application isn't in runnables list, appid=%s.", appid.c_str()); return 1; } pushAppListChangedEvent(_keyUninstall, json_object_get(obj_data)); removeAppDetail(appid); } else { AFB_ERROR("operation error."); } return 1; } /** * parse application detail function * * #### Parameters * - object : [IN] the detail of application * - info : [OUT] parsed application detail * * #### Return * the appid of application liked "dashboard" * */ std::string HS_AppInfo::parseAppDetail(struct json_object *object, AppDetail &info) const { struct json_object *name, *id; if(json_object_object_get_ex(object, _keyName, &name) == 0 || json_object_object_get_ex(object, _keyId, &id) == 0) { AFB_ERROR("can't find key=%s, %s.", _keyName, _keyId); return std::string(); } std::string appid = id2appid(json_object_get_string(id)); bool periphery = isPeripheryApp(appid.c_str()); info = { json_object_get_string(name), json_object_get_string(id), json_object_to_json_string(object), periphery }; return appid; } /** * add application detail to list function * * #### Parameters * - object : application detail * * #### Return * None * */ void HS_AppInfo::addAppDetail(struct json_object *object) { AppDetail info; std::string appid = parseAppDetail(object, info); if(appid.empty()) { AFB_ERROR("application id error"); return; } std::lock_guard<std::mutex> lock(this->mtx); appid2name[appid] = info.name; name2appid[info.name] = appid; app_detail_list[appid] = std::move(info); } /** * remove application detail from list function * * #### Parameters * - appid : application id * * #### Return * None * */ void HS_AppInfo::removeAppDetail(std::string appid) { std::lock_guard<std::mutex> lock(this->mtx); auto it = app_detail_list.find(appid); if(it != app_detail_list.end()) { appid2name.erase(appid); name2appid.erase(it->second.name); app_detail_list.erase(it); } else { AFB_WARNING("erase application(%s) wasn't in applist.", appid.c_str()); } } /** * push app_list_changed event function * * #### Parameters * - oper: install/uninstall * - object: event data * * #### Return * None * */ void HS_AppInfo::pushAppListChangedEvent(const char *oper, struct json_object *object) { struct json_object *push_obj = json_object_new_object(); json_object_object_add(push_obj, _keyOperation, json_object_new_string(oper)); json_object_object_add(push_obj, _keyData, object); HS_ClientManager::instance()->pushEvent(_keyApplistChanged, push_obj); } /** * retrieve runnables function * * #### Parameters * - obj_runnables: runnables array * - id: application id * * #### Return * found application detail * */ struct json_object* HS_AppInfo::retrieveRunnables(struct json_object *obj_runnables, std::string id) { struct json_object *j_found = nullptr; if(json_object_get_type(obj_runnables) == json_type_array) { int array_len = json_object_array_length(obj_runnables); for (int i = 0; i < array_len; ++i) { struct json_object *obj = json_object_array_get_idx(obj_runnables, i); struct json_object *j_id; if(json_object_object_get_ex(obj, _keyId, &j_id) == 0) { AFB_WARNING("can't find id."); continue; } if(id == json_object_get_string(j_id)) { j_found = obj; break; } } } else { AFB_ERROR("Apps information input error."); } return j_found; } /** * convert id to appid function * * #### Parameters * - id : the id of application liked "dashboard@0.1" * * #### Return * the appid of application liked "dashboard" * */ std::string HS_AppInfo::id2appid(const std::string &id) const { std::string appid; std::size_t pos = id.find("@"); appid = id.substr(0,pos); return appid; } /** * get runnables list * * #### Parameters * - object : runnables list,json array * * #### Return * None * */ void HS_AppInfo::getRunnables(struct json_object **object) { if(json_object_get_type(*object) != json_type_array) { AFB_ERROR("json type error."); return; } std::lock_guard<std::mutex> lock(this->mtx); for(auto it : app_detail_list) { if(!it.second.periphery) json_object_array_add(*object, json_tokener_parse(it.second.detail.c_str())); } } /** * check appid function * * #### Parameters * - appid : appid liked "dashboard" * * #### Return * success : the correct appid * fail : empty string * */ std::string HS_AppInfo::checkAppId(const std::string &appid) { std::lock_guard<std::mutex> lock(this->mtx); auto it_appid = appid2name.find(appid); if(it_appid != appid2name.end()) return it_appid->first; auto it_name = name2appid.find(appid); if(it_name != name2appid.end()) return it_name->second; return std::string(); } /** * check if application is a runnable periphery application function * * #### Parameters * - appid : appid liked "launcher" * * #### Return * true : periphery * false : not periphery * */ bool HS_AppInfo::isPeripheryApp(const char *appid) const { bool ret = false; for(auto m : periphery_app_list) { if(strcasecmp(appid, m) == 0) { ret = true; break; } } return ret; } /** * get application specific property * * #### Parameters * - appid : appid liked "launcher" * - key : the keyword * * #### Return * application property * */ std::string HS_AppInfo::getAppProperty(const std::string appid, std::string key) const { std::string value = ""; auto it = app_detail_list.find(appid); if(it != app_detail_list.end()) { value = it->second.getProperty(key); } return value; }
25,693
9,265
//////////////////////////////////////////////////////////// // Copyright (c) 2012 Polytech Montpellier // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS // BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////// #ifndef BADGER_BADGER_HPP #define BADGER_BADGER_HPP #include <map> #include <string> #include <vector> #include "Console.hpp" #include "Date.hpp" #include "Time.hpp" #include "SerialStream.hpp" namespace badger { class Badger { public: Badger(); ~Badger(); void run(); private: struct Record { Date date; Time time; std::string data; }; private: template<typename Res, typename... Args> void addCommand(const std::string &name, const std::function<Res(Args...)> &function, bool needSerialPortOpen); void tryToSendCommand(const std::string &command); std::string getReturnCommand(); void sendCommandOnSerial(const std::vector<serial::byte> &command); Record parseRecord(const std::string &str) const; std::vector<Record> get(const Date &date, const Time &begin, const Time &end); std::vector<Record> getAll(); private: void open(const std::string &port); void close(); std::string next(); std::string rollback(); std::string erase(); std::string count(); std::string minMaxDate(); std::string getDateTime(); std::string setDateTime(const Date &date, const Time &time); std::string display(const Date &date, const Time &begin, const Time &end); std::string csv(const Date &date, const Time &begin, const Time &end); void quit(); private: //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// bool m_continuer; plt::Console m_console; // The boolean is for the need of an open serial port std::map<std::string, bool> m_access; serial::serialstream m_serial; }; } // namespace badger #include "Badger.inl" #endif // BADGER_BADGER_HPP
3,719
1,138
#pragma once #include <string> #include <unordered_map> #include "common/encoding_rlp.hpp" #include "common/types.hpp" namespace taraxa::state_api { static constexpr auto BlockNumberNIL = std::numeric_limits<EthBlockNumber>::max(); struct ETHChainConfig { EthBlockNumber homestead_block = 0; EthBlockNumber dao_fork_block = 0; EthBlockNumber eip_150_block = 0; EthBlockNumber eip_158_block = 0; EthBlockNumber byzantium_block = 0; EthBlockNumber constantinople_block = 0; EthBlockNumber petersburg_block = 0; HAS_RLP_FIELDS }; Json::Value enc_json(ETHChainConfig const& obj); void dec_json(Json::Value const& json, ETHChainConfig& obj); using BalanceMap = std::unordered_map<addr_t, u256>; Json::Value enc_json(BalanceMap const& obj); void dec_json(Json::Value const& json, BalanceMap& obj); struct DPOSConfig { u256 eligibility_balance_threshold; EthBlockNumber deposit_delay = 0; EthBlockNumber withdrawal_delay = 0; std::unordered_map<addr_t, BalanceMap> genesis_state; HAS_RLP_FIELDS }; Json::Value enc_json(DPOSConfig const& obj); void dec_json(Json::Value const& json, DPOSConfig& obj); struct ExecutionOptions { bool disable_nonce_check = 0; bool disable_gas_fee = 0; HAS_RLP_FIELDS }; Json::Value enc_json(ExecutionOptions const& obj); void dec_json(Json::Value const& json, ExecutionOptions& obj); struct Config { ETHChainConfig eth_chain_config; bool disable_block_rewards = 0; ExecutionOptions execution_options; BalanceMap genesis_balances; std::optional<DPOSConfig> dpos; HAS_RLP_FIELDS u256 effective_genesis_balance(addr_t const& addr) const; }; Json::Value enc_json(Config const& obj); void dec_json(Json::Value const& json, Config& obj); struct Opts { uint32_t expected_max_trx_per_block = 0; uint8_t max_trie_full_node_levels_to_cache = 0; HAS_RLP_FIELDS }; struct OptsDB { std::string db_path; bool disable_most_recent_trie_value_views = 0; HAS_RLP_FIELDS }; } // namespace taraxa::state_api
1,989
761
 # pragma once # include "Common.hpp" # include "ResultKurachan.hpp" # include <vector> using namespace result; // リザルトシーン // ぱらちゃんを1匹泳がせる。等速直線運動で、スクリーン端で跳ね返る class ResultScene : public MyApp::Scene { private: std::vector<ResultKurachan> parachans { ResultKurachan(Scene::Center(), SMALL, Vec2(100.0, 50.0)), ResultKurachan(Scene::Center() + Vec2(100.0, 0.0), MIDDLE, Vec2(0, 100.0)), ResultKurachan(Scene::Center() + Vec2(-50.0, 50.0), BIG, Vec2(-60.0, 80.0)), ResultKurachan(Scene::Center() + Vec2(-100.0, 100.0), VERY_SMALL, Vec2(50.0, 30.0)), ResultKurachan(Scene::Center() + Vec2(200.0, -50.0), VERY_BIG, Vec2(-20.0, -60.0)) }; Rect m_startButton = Rect(Arg::center = Scene::Center().movedBy(0, 80), 300, 60); Transition m_startTransition = Transition(0.4s, 0.2s); Rect m_goTitleButton = Rect(Arg::center = Scene::Center().movedBy(0, 160), 300, 60); Transition m_goTitleTransition = Transition(0.4s, 0.2s); Rect m_exitButton = Rect(Arg::center = Scene::Center().movedBy(0, 240), 300, 60); Transition m_exitTransition = Transition(0.4s, 0.2s); Rect m_tweetButton = Rect(Arg::center = Scene::Center().movedBy(300, 240), 150, 60); Transition m_tweetTransition = Transition(0.4s, 0.2s); Texture backgroundTexture; int highScore; //今回のプレイ以前のハイスコア int currentScore; public: ResultScene(const InitData& init); void update() override; void draw() const override; void writeHighScore(); void setHighScore(int highScore); int getHighScore(); void updateHighScore(); };
1,517
729
#include <QCoreApplication> #if defined(WIN32) || defined(Q_OS_WIN) # include "win32ioenumerator.h" #else # include "unixioenumerator.h" #endif int main(int argc, char** argv) { QCoreApplication a(argc, argv); #ifdef WIN32 Win32IOEnumerator e; #else UnixIOEnumerator e; #endif e.rescan(); return 0; }
326
139
#include "D2DataTbls.h" //D2Common.0x6FD62EA0 int __fastcall DATATBLS_MapMissilesTxtKeywordToNumber(char* szKey) { if (!_strnicmp(szKey, "min", 32)) { return 0; } else if (!_strnicmp(szKey, "max", 32)) { return 1; } else if (!_strnicmp(szKey, "rand", 32)) { return 2; } else if (!_strnicmp(szKey, "skill", 32)) { return 3; } else if (!_strnicmp(szKey, "miss", 32)) { return 4; } else { return -1; } } //D2Common.0x6FD62F20 //TODO: Find a name int __fastcall sub_6FD62F20(char* szText, int* a2, int a3, int nKeywordNumber) { D2TxtLinkStrc* pLinker = sgptDataTables->pMissileCalcLinker; char szCode[4] = {}; int nRow = 0; if (a3 == 1) { if (nKeywordNumber == 3) { if (sgptDataTables->iSkillCode) { nRow = FOG_GetRowFromTxt(sgptDataTables->iSkillCode, szText, 0); if (nRow >= 0) { *a2 = 1; return nRow; } pLinker = sgptDataTables->pSkillCalcLinker; } } else if (nKeywordNumber == 4) { if (sgptDataTables->pMissilesLinker) { nRow = FOG_GetRowFromTxt(sgptDataTables->pMissilesLinker, szText, 0); if (nRow >= 0) { *a2 = 1; return nRow; } } pLinker = sgptDataTables->pMissileCalcLinker; } } if (szText[0]) { szCode[0] = szText[0]; if (szText[1]) { szCode[1] = szText[1]; if (szText[2]) { szCode[2] = szText[2]; if (szText[3]) { szCode[3] = szText[3]; } else { szCode[3] = ' '; } } else { szCode[2] = ' '; szCode[3] = ' '; } } else { szCode[1] = ' '; szCode[2] = ' '; szCode[3] = ' '; } } else { szCode[0] = ' '; szCode[1] = ' '; szCode[2] = ' '; szCode[3] = ' '; } nRow = FOG_GetLinkIndex(pLinker, *(uint32_t*)szCode, 1); *a2 = 0; return nRow; } //D2Common.0x6FD630F0 void __fastcall DATATBLS_MissileCalcLinker(char* pSrc, void* pRecord, int nOffset, int nPosition, int nTxtRow, int nTxtColumn) { int nBufferSize = 0; char pBuffer[1024] = {}; if (pRecord) { if (pSrc) { nBufferSize = FOG_10254(pSrc, pBuffer, sizeof(pBuffer), DATATBLS_MapMissilesTxtKeywordToNumber, NULL, sub_6FD62F20); if (nBufferSize > 0) { *(uint32_t*)((char*)pRecord + nOffset) = DATATBLS_AppendMemoryBuffer(&sgptDataTables->pMissCode, (int*)&sgptDataTables->nMissCodeSize, &sgptDataTables->nMissCodeSizeEx, pBuffer, nBufferSize); } else { *(uint32_t*)((char*)pRecord + nOffset) = -1; } } else { *(uint32_t*)((char*)pRecord + nOffset) = -1; } } } //D2Common.0x6FD63180 void __fastcall DATATBLS_LoadMissilesTxt(void* pMemPool) { D2BinFieldStrc pTbl[] = { { "Missile", TXTFIELD_NAMETOINDEX, 0, 0, &sgptDataTables->pMissilesLinker }, { "LastCollide", TXTFIELD_BIT, 0, 4, NULL }, { "Explosion", TXTFIELD_BIT, 1, 4, NULL }, { "Pierce", TXTFIELD_BIT, 2, 4, NULL }, { "CanSlow", TXTFIELD_BIT, 3, 4, NULL }, { "CanDestroy", TXTFIELD_BIT, 4, 4, NULL }, { "NoMultiShot", TXTFIELD_BIT, 12, 4, NULL }, { "NoUniqueMod", TXTFIELD_BIT, 13, 4, NULL }, { "ClientSend", TXTFIELD_BIT, 5, 4, NULL }, { "GetHit", TXTFIELD_BIT, 6, 4, NULL }, { "SoftHit", TXTFIELD_BIT, 7, 4, NULL }, { "ApplyMastery", TXTFIELD_BIT, 8, 4, NULL }, { "ReturnFire", TXTFIELD_BIT, 9, 4, NULL }, { "Town", TXTFIELD_BIT, 10, 4, NULL }, { "SrcTown", TXTFIELD_BIT, 11, 4, NULL }, { "pCltDoFunc", TXTFIELD_WORD, 0, 8, NULL }, { "pCltHitFunc", TXTFIELD_WORD, 0, 10, NULL }, { "pSrvDoFunc", TXTFIELD_WORD, 0, 12, NULL }, { "pSrvHitFunc", TXTFIELD_WORD, 0, 14, NULL }, { "pSrvDmgFunc", TXTFIELD_WORD, 0, 16, NULL }, { "Param1", TXTFIELD_DWORD, 0, 56, NULL }, { "Param2", TXTFIELD_DWORD, 0, 60, NULL }, { "Param3", TXTFIELD_DWORD, 0, 64, NULL }, { "Param4", TXTFIELD_DWORD, 0, 68, NULL }, { "Param5", TXTFIELD_DWORD, 0, 72, NULL }, { "SrvCalc1", TXTFIELD_CALCTODWORD, 0, 128, DATATBLS_MissileCalcLinker }, { "CltParam1", TXTFIELD_DWORD, 0, 88, NULL }, { "CltParam2", TXTFIELD_DWORD, 0, 92, NULL }, { "CltParam3", TXTFIELD_DWORD, 0, 96, NULL }, { "CltParam4", TXTFIELD_DWORD, 0, 100, NULL }, { "CltParam5", TXTFIELD_DWORD, 0, 104, NULL }, { "CltCalc1", TXTFIELD_CALCTODWORD, 0, 132, DATATBLS_MissileCalcLinker }, { "sHitPar1", TXTFIELD_DWORD, 0, 76, NULL }, { "sHitPar2", TXTFIELD_DWORD, 0, 80, NULL }, { "sHitPar3", TXTFIELD_DWORD, 0, 84, NULL }, { "SHitCalc1", TXTFIELD_CALCTODWORD, 0, 136, DATATBLS_MissileCalcLinker }, { "cHitPar1", TXTFIELD_DWORD, 0, 108, NULL }, { "cHitPar2", TXTFIELD_DWORD, 0, 112, NULL }, { "cHitPar3", TXTFIELD_DWORD, 0, 116, NULL }, { "CHitCalc1", TXTFIELD_CALCTODWORD, 0, 140, DATATBLS_MissileCalcLinker }, { "dParam1", TXTFIELD_DWORD, 0, 120, NULL }, { "dParam2", TXTFIELD_DWORD, 0, 124, NULL }, { "DmgCalc1", TXTFIELD_CALCTODWORD, 0, 144, DATATBLS_MissileCalcLinker }, { "TravelSound", TXTFIELD_NAMETOWORD, 0, 18, &sgptDataTables->pSoundsLinker }, { "HitSound", TXTFIELD_NAMETOWORD, 0, 20, &sgptDataTables->pSoundsLinker }, { "ProgSound", TXTFIELD_NAMETOWORD, 0, 52, &sgptDataTables->pSoundsLinker }, { "ProgOverlay", TXTFIELD_NAMETOWORD, 0, 54, &sgptDataTables->pOverlayLinker }, { "ExplosionMissile", TXTFIELD_NAMETOWORD, 0, 22, &sgptDataTables->pMissilesLinker }, { "SubMissile1", TXTFIELD_NAMETOWORD, 0, 24, &sgptDataTables->pMissilesLinker }, { "SubMissile2", TXTFIELD_NAMETOWORD, 0, 26, &sgptDataTables->pMissilesLinker }, { "SubMissile3", TXTFIELD_NAMETOWORD, 0, 28, &sgptDataTables->pMissilesLinker }, { "HitSubMissile1", TXTFIELD_NAMETOWORD, 0, 36, &sgptDataTables->pMissilesLinker }, { "HitSubMissile2", TXTFIELD_NAMETOWORD, 0, 38, &sgptDataTables->pMissilesLinker }, { "HitSubMissile3", TXTFIELD_NAMETOWORD, 0, 40, &sgptDataTables->pMissilesLinker }, { "HitSubMissile4", TXTFIELD_NAMETOWORD, 0, 42, &sgptDataTables->pMissilesLinker }, { "CltSubMissile1", TXTFIELD_NAMETOWORD, 0, 30, &sgptDataTables->pMissilesLinker }, { "CltSubMissile2", TXTFIELD_NAMETOWORD, 0, 32, &sgptDataTables->pMissilesLinker }, { "CltSubMissile3", TXTFIELD_NAMETOWORD, 0, 34, &sgptDataTables->pMissilesLinker }, { "CltHitSubMissile1", TXTFIELD_NAMETOWORD, 0, 44, &sgptDataTables->pMissilesLinker }, { "CltHitSubMissile2", TXTFIELD_NAMETOWORD, 0, 46, &sgptDataTables->pMissilesLinker }, { "CltHitSubMissile3", TXTFIELD_NAMETOWORD, 0, 48, &sgptDataTables->pMissilesLinker }, { "CltHitSubMissile4", TXTFIELD_NAMETOWORD, 0, 50, &sgptDataTables->pMissilesLinker }, { "ResultFlags", TXTFIELD_WORD, 0, 172, NULL }, { "HitFlags", TXTFIELD_DWORD2, 0, 168, NULL }, { "HitClass", TXTFIELD_BYTE, 0, 148, NULL }, { "Range", TXTFIELD_WORD, 0, 150, NULL }, { "LevRange", TXTFIELD_WORD, 0, 152, NULL }, { "KnockBack", TXTFIELD_BYTE, 0, 174, NULL }, { "animrate", TXTFIELD_WORD, 0, 160, NULL }, { "xoffset", TXTFIELD_WORD, 0, 162, NULL }, { "yoffset", TXTFIELD_WORD, 0, 164, NULL }, { "zoffset", TXTFIELD_WORD, 0, 166, NULL }, { "MissileSkill", TXTFIELD_BIT, 15, 4, NULL }, { "Skill", TXTFIELD_NAMETOWORD, 0, 404, &sgptDataTables->iSkillCode }, { "MinDamage", TXTFIELD_DWORD, 0, 176, NULL }, { "MinLevDam1", TXTFIELD_DWORD, 0, 184, NULL }, { "MinLevDam2", TXTFIELD_DWORD, 0, 188, NULL }, { "MinLevDam3", TXTFIELD_DWORD, 0, 192, NULL }, { "MinLevDam4", TXTFIELD_DWORD, 0, 196, NULL }, { "MinLevDam5", TXTFIELD_DWORD, 0, 200, NULL }, { "MaxDamage", TXTFIELD_DWORD, 0, 180, NULL }, { "MaxLevDam1", TXTFIELD_DWORD, 0, 204, NULL }, { "MaxLevDam2", TXTFIELD_DWORD, 0, 208, NULL }, { "MaxLevDam3", TXTFIELD_DWORD, 0, 212, NULL }, { "MaxLevDam4", TXTFIELD_DWORD, 0, 216, NULL }, { "MaxLevDam5", TXTFIELD_DWORD, 0, 220, NULL }, { "DmgSymPerCalc", TXTFIELD_CALCTODWORD, 0, 224, DATATBLS_MissileCalcLinker }, { "EType", TXTFIELD_CODETOBYTE, 0, 228, &sgptDataTables->pElemTypesLinker }, { "EMin", TXTFIELD_DWORD, 0, 232, NULL }, { "MinELev1", TXTFIELD_DWORD, 0, 240, NULL }, { "MinELev2", TXTFIELD_DWORD, 0, 244, NULL }, { "MinELev3", TXTFIELD_DWORD, 0, 248, NULL }, { "MinELev4", TXTFIELD_DWORD, 0, 252, NULL }, { "MinELev5", TXTFIELD_DWORD, 0, 256, NULL }, { "EMax", TXTFIELD_DWORD, 0, 236, NULL }, { "MaxELev1", TXTFIELD_DWORD, 0, 260, NULL }, { "MaxELev2", TXTFIELD_DWORD, 0, 264, NULL }, { "MaxELev3", TXTFIELD_DWORD, 0, 268, NULL }, { "MaxELev4", TXTFIELD_DWORD, 0, 272, NULL }, { "MaxELev5", TXTFIELD_DWORD, 0, 276, NULL }, { "EDmgSymPerCalc", TXTFIELD_CALCTODWORD, 0, 280, DATATBLS_MissileCalcLinker }, { "ELen", TXTFIELD_DWORD, 0, 284, NULL }, { "ELevLen1", TXTFIELD_DWORD, 0, 288, NULL }, { "ELevLen2", TXTFIELD_DWORD, 0, 292, NULL }, { "ELevLen3", TXTFIELD_DWORD, 0, 296, NULL }, { "CltSrcTown", TXTFIELD_BYTE, 0, 300, NULL }, { "SrcDamage", TXTFIELD_BYTE, 0, 301, NULL }, { "SrcMissDmg", TXTFIELD_BYTE, 0, 302, NULL }, { "Half2HSrc", TXTFIELD_BIT, 14, 4, NULL }, { "Vel", TXTFIELD_BYTE, 0, 154, NULL }, { "VelLev", TXTFIELD_BYTE, 0, 155, NULL }, { "MaxVel", TXTFIELD_BYTE, 0, 156, NULL }, { "Accel", TXTFIELD_WORD, 0, 158, NULL }, { "Holy", TXTFIELD_BYTE, 0, 303, NULL }, { "Light", TXTFIELD_BYTE, 0, 304, NULL }, { "Flicker", TXTFIELD_BYTE, 0, 305, NULL }, { "Red", TXTFIELD_BYTE, 0, 306, NULL }, { "Green", TXTFIELD_BYTE, 0, 307, NULL }, { "Blue", TXTFIELD_BYTE, 0, 308, NULL }, { "InitSteps", TXTFIELD_BYTE, 0, 309, NULL }, { "Activate", TXTFIELD_BYTE, 0, 310, NULL }, { "LoopAnim", TXTFIELD_BYTE, 0, 311, NULL }, { "CelFile", TXTFIELD_ASCII, 64, 312, NULL }, { "AnimLen", TXTFIELD_BYTE, 0, 376, NULL }, { "RandStart", TXTFIELD_DWORD, 0, 380, NULL }, { "SubLoop", TXTFIELD_BYTE, 0, 384, NULL }, { "SubStart", TXTFIELD_BYTE, 0, 385, NULL }, { "SubStop", TXTFIELD_BYTE, 0, 386, NULL }, { "CollideType", TXTFIELD_BYTE, 0, 387, NULL }, { "CollideKill", TXTFIELD_BYTE, 0, 390, NULL }, { "CollideFriend", TXTFIELD_BYTE, 0, 391, NULL }, { "Collision", TXTFIELD_BYTE, 0, 388, NULL }, { "ClientCol", TXTFIELD_BYTE, 0, 389, NULL }, { "NextHit", TXTFIELD_BYTE, 0, 392, NULL }, { "NextDelay", TXTFIELD_BYTE, 0, 393, NULL }, { "Size", TXTFIELD_BYTE, 0, 394, NULL }, { "ToHit", TXTFIELD_BYTE, 0, 395, NULL }, { "AlwaysExplode", TXTFIELD_BYTE, 0, 396, NULL }, { "Trans", TXTFIELD_BYTE, 0, 397, NULL }, { "Qty", TXTFIELD_BYTE, 0, 398, NULL }, { "SpecialSetup", TXTFIELD_DWORD, 0, 400, NULL }, { "HitShift", TXTFIELD_BYTE, 0, 406, NULL }, { "NumDirections", TXTFIELD_BYTE, 0, 416, NULL }, { "AnimSpeed", TXTFIELD_BYTE, 0, 417, NULL }, { "LocalBlood", TXTFIELD_BYTE, 0, 418, NULL }, { "DamageRate", TXTFIELD_DWORD, 0, 412, NULL }, { "end", TXTFIELD_NONE, 0, 0, NULL }, }; sgptDataTables->pMissilesLinker = (D2TxtLinkStrc*)FOG_AllocLinker(__FILE__, __LINE__); sgptDataTables->pMissilesTxt = (D2MissilesTxt*)DATATBLS_CompileTxt(pMemPool, "missiles", pTbl, &sgptDataTables->nMissilesTxtRecordCount, sizeof(D2MissilesTxt)); for (int i = 0; i < sgptDataTables->nMissilesTxtRecordCount; ++i) { if (sgptDataTables->pMissilesTxt[i].nCollideType > 8) { FOG_WriteToLogFile("Range error in entry %d in table '%s' field '%s'. Value must be between %d and %d.", i, "missiles", "CollideType", 0, 8); } if (sgptDataTables->pMissilesTxt[i].nCollideType < 0) { sgptDataTables->pMissilesTxt[i].nCollideType = 0; } else if (sgptDataTables->pMissilesTxt[i].nCollideType > 8) { sgptDataTables->pMissilesTxt[i].nCollideType = 8; } } DATATBLS_GetBinFileHandle(pMemPool, "misscode", (void**)&sgptDataTables->pMissCode, (int*)&sgptDataTables->nMissCodeSize, &sgptDataTables->nMissCodeSizeEx); } //D2Common.0x6FD64B80 void __fastcall DATATBLS_UnloadMissilesTxt() { if (sgptDataTables->pMissCode) { FOG_FreeServerMemory(NULL, sgptDataTables->pMissCode, __FILE__, __LINE__, 0); sgptDataTables->pMissCode = NULL; } sgptDataTables->nMissCodeSize = 0; sgptDataTables->nMissCodeSizeEx = 0; if (sgptDataTables->pMissilesTxt) { DATATBLS_UnloadBin(sgptDataTables->pMissilesTxt); sgptDataTables->pMissilesTxt = NULL; } if (sgptDataTables->pMissilesLinker) { FOG_FreeLinker(sgptDataTables->pMissilesLinker); sgptDataTables->pMissilesLinker = NULL; } sgptDataTables->nMissilesTxtRecordCount = 0; } //D2Common.0x6FD64BE0 (#10590) int __stdcall DATATBLS_GetMissileVelocityFromMissilesTxt(int nMissileId, int nLevel) { D2MissilesTxt* pMissilesTxtRecord = DATATBLS_GetMissilesTxtRecord(nMissileId); if (pMissilesTxtRecord) { return pMissilesTxtRecord->nVel + nLevel * pMissilesTxtRecord->nVelLev / 8; } return 0; } //Inlined at various places D2MissilesTxt* __fastcall DATATBLS_GetMissilesTxtRecord(int nMissileId) { D2MissilesTxt* pMissilesTxtRecord = NULL; if (nMissileId >= 0 && nMissileId < sgptDataTables->nMissilesTxtRecordCount) { return &sgptDataTables->pMissilesTxt[nMissileId]; } return NULL; }
12,733
6,749
#include "native-test.h" #ifdef BUILD_PYTHON_TESTS #include "py-test.h" #endif
78
36
// Copyright 2021 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/webui/projector_app/projector_xhr_sender.h" #include "ash/webui/projector_app/test/mock_app_client.h" #include "base/bind.h" #include "base/callback.h" #include "base/run_loop.h" #include "base/test/bind.h" #include "base/test/task_environment.h" #include "base/time/time.h" #include "services/network/public/mojom/url_response_head.mojom.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" namespace { const char kTestUserEmail[] = "testuser1@gmail.com"; const base::TimeDelta kExpiryTimeFromNow = base::Minutes(10); constexpr char kValidUrl[] = "https://www.googleapis.com/drive/v3/files/fileID"; constexpr char kValidUrl2[] = "https://translation.googleapis.com/language/translate/v2"; } // namespace namespace chromeos { class ProjectorXhrSenderTest : public testing::Test { public: ProjectorXhrSenderTest() = default; ProjectorXhrSenderTest(const ProjectorXhrSenderTest&) = delete; ProjectorXhrSenderTest& operator=(const ProjectorXhrSenderTest&) = delete; ~ProjectorXhrSenderTest() override = default; // testing::Test: void SetUp() override { sender_ = std::make_unique<ProjectorXhrSender>( mock_app_client_.GetUrlLoaderFactory()); } ProjectorXhrSender* sender() { return sender_.get(); } MockAppClient& mock_app_client() { return mock_app_client_; } private: base::test::SingleThreadTaskEnvironment task_environment_; std::unique_ptr<ProjectorXhrSender> sender_; MockAppClient mock_app_client_; }; TEST_F(ProjectorXhrSenderTest, Success) { base::RunLoop run_loop; const std::string& test_response_body = "{}"; sender()->Send( GURL(kValidUrl), "GET", /*request_body=*/"", /*useCredential=*/false, base::BindOnce( [](const std::string& expected_response_body, base::RepeatingClosure quit_closure, bool success, const std::string& response_body, const std::string& error) { EXPECT_TRUE(success); EXPECT_EQ(expected_response_body, response_body); EXPECT_EQ("", error); quit_closure.Run(); }, test_response_body, run_loop.QuitClosure())); mock_app_client().test_url_loader_factory().AddResponse(kValidUrl, test_response_body); mock_app_client().GrantOAuthTokenFor( kTestUserEmail, /* expiry_time = */ base::Time::Now() + kExpiryTimeFromNow); run_loop.Run(); } TEST_F(ProjectorXhrSenderTest, TwoRequests) { base::RunLoop run_loop; const std::string& test_response_body = "{}"; sender()->Send( GURL(kValidUrl), "GET", /*request_body=*/"", /*useCredential=*/false, base::BindOnce( [](const std::string& expected_response_body, base::RepeatingClosure quit_closure, bool success, const std::string& response_body, const std::string& error) { EXPECT_TRUE(success); EXPECT_EQ(expected_response_body, response_body); EXPECT_EQ("", error); quit_closure.Run(); }, test_response_body, run_loop.QuitClosure())); base::RunLoop run_loop2; const std::string& test_response_body2 = "{data: {}}"; sender()->Send( GURL(kValidUrl2), "GET", /*request_body=*/"", /*useCredential=*/false, base::BindOnce( [](const std::string& expected_response_body, base::RepeatingClosure quit_closure, bool success, const std::string& response_body, const std::string& error) { EXPECT_TRUE(success); EXPECT_EQ(expected_response_body, response_body); EXPECT_EQ("", error); quit_closure.Run(); }, test_response_body2, run_loop2.QuitClosure())); mock_app_client().test_url_loader_factory().AddResponse(kValidUrl, test_response_body); mock_app_client().test_url_loader_factory().AddResponse(kValidUrl2, test_response_body2); mock_app_client().GrantOAuthTokenFor( kTestUserEmail, /* expiry_time = */ base::Time::Now() + kExpiryTimeFromNow); run_loop.Run(); run_loop2.Run(); } TEST_F(ProjectorXhrSenderTest, UseCredentials) { base::RunLoop run_loop; const std::string& test_response_body = "{}"; sender()->Send( GURL(kValidUrl), "GET", /*request_body=*/"", /*useCredential=*/true, base::BindOnce( [](const std::string& expected_response_body, base::RepeatingClosure quit_closure, bool success, const std::string& response_body, const std::string& error) { EXPECT_TRUE(success); EXPECT_EQ(expected_response_body, response_body); EXPECT_EQ("", error); quit_closure.Run(); }, test_response_body, run_loop.QuitClosure())); // Verify that http request is sent without granting OAuth token. mock_app_client().test_url_loader_factory().AddResponse(kValidUrl, test_response_body); run_loop.Run(); } TEST_F(ProjectorXhrSenderTest, NetworkError) { base::RunLoop run_loop; sender()->Send( GURL(kValidUrl), /*method=*/"GET", /*request_body=*/"", /*use_credentials=*/false, base::BindOnce( [](base::RepeatingClosure quit_closure, bool success, const std::string& response_body, const std::string& error) { EXPECT_FALSE(success); EXPECT_EQ("", response_body); EXPECT_EQ("XHR_FETCH_FAILURE", error); quit_closure.Run(); }, run_loop.QuitClosure())); mock_app_client().test_url_loader_factory().AddResponse( GURL(kValidUrl), network::mojom::URLResponseHead::New(), std::string(), network::URLLoaderCompletionStatus(net::HTTP_NOT_FOUND)); mock_app_client().GrantOAuthTokenFor( kTestUserEmail, /* expiry_time = */ base::Time::Now() + kExpiryTimeFromNow); run_loop.Run(); } TEST_F(ProjectorXhrSenderTest, UnsupportedUrl) { base::RunLoop run_loop; sender()->Send( GURL("https://example.com"), /*method=*/"GET", /*request_body=*/"", /*use_credentials=*/false, base::BindOnce( [](base::RepeatingClosure quit_closure, bool success, const std::string& response_body, const std::string& error) { EXPECT_FALSE(success); EXPECT_EQ("", response_body); EXPECT_EQ("UNSUPPORTED_URL", error); quit_closure.Run(); }, run_loop.QuitClosure())); run_loop.Run(); } } // namespace chromeos
6,809
2,162
/* * Software License Agreement (BSD License) * * Copyright (c) 2011-2014, Willow Garage, Inc. * Copyright (c) 2014-2016, Open Source Robotics Foundation * 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 Open Source Robotics Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** \author Jia Pan */ #include "fcl/ccd/interval.h" #include <iostream> namespace fcl { Interval bound(const Interval& i, FCL_REAL v) { Interval res = i; if(v < res.i_[0]) res.i_[0] = v; if(v > res.i_[1]) res.i_[1] = v; return res; } Interval bound(const Interval& i, const Interval& other) { Interval res = i; if(other.i_[0] < res.i_[0]) res.i_[0] = other.i_[0]; if(other.i_[1] > res.i_[1]) res.i_[1] = other.i_[1]; return res; } Interval Interval::operator * (const Interval& other) const { if(other.i_[0] >= 0) { if(i_[0] >= 0) return Interval(i_[0] * other.i_[0], i_[1] * other.i_[1]); if(i_[1] <= 0) return Interval(i_[0] * other.i_[1], i_[1] * other.i_[0]); return Interval(i_[0] * other.i_[1], i_[1] * other.i_[1]); } if(other.i_[1] <= 0) { if(i_[0] >= 0) return Interval(i_[1] * other.i_[0], i_[0] * other.i_[1]); if(i_[1] <= 0) return Interval(i_[1] * other.i_[1], i_[0] * other.i_[0]); return Interval(i_[1] * other.i_[0], i_[0] * other.i_[0]); } if(i_[0] >= 0) return Interval(i_[1] * other.i_[0], i_[1] * other.i_[1]); if(i_[1] <= 0) return Interval(i_[0] * other.i_[1], i_[0] * other.i_[0]); FCL_REAL v00 = i_[0] * other.i_[0]; FCL_REAL v11 = i_[1] * other.i_[1]; if(v00 <= v11) { FCL_REAL v01 = i_[0] * other.i_[1]; FCL_REAL v10 = i_[1] * other.i_[0]; if(v01 < v10) return Interval(v01, v11); return Interval(v10, v11); } FCL_REAL v01 = i_[0] * other.i_[1]; FCL_REAL v10 = i_[1] * other.i_[0]; if(v01 < v10) return Interval(v01, v00); return Interval(v10, v00); } Interval& Interval::operator *= (const Interval& other) { if(other.i_[0] >= 0) { if(i_[0] >= 0) { i_[0] *= other.i_[0]; i_[1] *= other.i_[1]; } else if(i_[1] <= 0) { i_[0] *= other.i_[1]; i_[1] *= other.i_[0]; } else { i_[0] *= other.i_[1]; i_[1] *= other.i_[1]; } return *this; } if(other.i_[1] <= 0) { if(i_[0] >= 0) { FCL_REAL tmp = i_[0]; i_[0] = i_[1] * other.i_[0]; i_[1] = tmp * other.i_[1]; } else if(i_[1] <= 0) { FCL_REAL tmp = i_[0]; i_[0] = i_[1] * other.i_[1]; i_[1] = tmp * other.i_[0]; } else { FCL_REAL tmp = i_[0]; i_[0] = i_[1] * other.i_[0]; i_[1] = tmp * other.i_[0]; } return *this; } if(i_[0] >= 0) { i_[0] = i_[1] * other.i_[0]; i_[1] *= other.i_[1]; return *this; } if(i_[1] <= 0) { i_[1] = i_[0] * other.i_[0]; i_[0] *= other.i_[1]; return *this; } FCL_REAL v00 = i_[0] * other.i_[0]; FCL_REAL v11 = i_[1] * other.i_[1]; if(v00 <= v11) { FCL_REAL v01 = i_[0] * other.i_[1]; FCL_REAL v10 = i_[1] * other.i_[0]; if(v01 < v10) { i_[0] = v01; i_[1] = v11; } else { i_[0] = v10; i_[1] = v11; } return *this; } FCL_REAL v01 = i_[0] * other.i_[1]; FCL_REAL v10 = i_[1] * other.i_[0]; if(v01 < v10) { i_[0] = v01; i_[1] = v00; } else { i_[0] = v10; i_[1] = v00; } return *this; } Interval Interval::operator / (const Interval& other) const { return *this * Interval(1.0 / other.i_[1], 1.0 / other.i_[0]); } Interval& Interval::operator /= (const Interval& other) { *this *= Interval(1.0 / other.i_[1], 1.0 / other.i_[0]); return *this; } void Interval::print() const { std::cout << "[" << i_[0] << ", " << i_[1] << "]" << std::endl; } }
5,224
2,492
// 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. #include "chrome/browser/notifications/notification_platform_bridge_message_center.h" #include "base/bind.h" #include "base/callback.h" #include "base/memory/raw_ptr.h" #include "base/memory/scoped_refptr.h" #include "base/no_destructor.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/notifications/notification_display_service_impl.h" #include "chrome/browser/notifications/notification_ui_manager.h" #include "chrome/browser/notifications/profile_notification.h" #include "chrome/common/notifications/notification_operation.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "ui/message_center/public/cpp/notification.h" namespace { // A NotificationDelegate that passes through click actions to the notification // display service (and on to the appropriate handler). This is a temporary // class to ease the transition from NotificationDelegate to // NotificationHandler. // TODO(estade): also handle other NotificationDelegate actions as needed. class PassThroughDelegate : public message_center::NotificationDelegate { public: PassThroughDelegate(Profile* profile, const message_center::Notification& notification, NotificationHandler::Type notification_type) : profile_(profile), notification_(notification), notification_type_(notification_type) { DCHECK_NE(notification_type, NotificationHandler::Type::TRANSIENT); } PassThroughDelegate(const PassThroughDelegate&) = delete; PassThroughDelegate& operator=(const PassThroughDelegate&) = delete; void SettingsClick() override { NotificationDisplayServiceImpl::GetForProfile(profile_) ->ProcessNotificationOperation( NotificationOperation::kSettings, notification_type_, notification_.origin_url(), notification_.id(), absl::nullopt, absl::nullopt, absl::nullopt /* by_user */); } void DisableNotification() override { NotificationDisplayServiceImpl::GetForProfile(profile_) ->ProcessNotificationOperation( NotificationOperation::kDisablePermission, notification_type_, notification_.origin_url(), notification_.id(), absl::nullopt /* action_index */, absl::nullopt /* reply */, absl::nullopt /* by_user */); } void Close(bool by_user) override { NotificationDisplayServiceImpl::GetForProfile(profile_) ->ProcessNotificationOperation( NotificationOperation::kClose, notification_type_, notification_.origin_url(), notification_.id(), absl::nullopt /* action_index */, absl::nullopt /* reply */, by_user); } void Click(const absl::optional<int>& button_index, const absl::optional<std::u16string>& reply) override { NotificationDisplayServiceImpl::GetForProfile(profile_) ->ProcessNotificationOperation( NotificationOperation::kClick, notification_type_, notification_.origin_url(), notification_.id(), button_index, reply, absl::nullopt /* by_user */); } protected: ~PassThroughDelegate() override = default; private: raw_ptr<Profile> profile_; message_center::Notification notification_; NotificationHandler::Type notification_type_; }; } // namespace // static NotificationPlatformBridgeMessageCenter* NotificationPlatformBridgeMessageCenter::Get() { static base::NoDestructor<NotificationPlatformBridgeMessageCenter> instance; return instance.get(); } NotificationPlatformBridgeMessageCenter:: NotificationPlatformBridgeMessageCenter() = default; NotificationPlatformBridgeMessageCenter:: ~NotificationPlatformBridgeMessageCenter() = default; void NotificationPlatformBridgeMessageCenter::Display( NotificationHandler::Type notification_type, Profile* profile, const message_center::Notification& notification, std::unique_ptr<NotificationCommon::Metadata> /* metadata */) { NotificationUIManager* ui_manager = g_browser_process->notification_ui_manager(); if (!ui_manager) return; // The process is shutting down. if (notification.delegate() || notification_type == NotificationHandler::Type::TRANSIENT) { ui_manager->Add(notification, profile); return; } // If there's no delegate, replace it with a PassThroughDelegate so clicks // go back to the appropriate handler. message_center::Notification notification_with_delegate(notification); notification_with_delegate.set_delegate(base::WrapRefCounted( new PassThroughDelegate(profile, notification, notification_type))); ui_manager->Add(notification_with_delegate, profile); } void NotificationPlatformBridgeMessageCenter::Close( Profile* profile, const std::string& notification_id) { NotificationUIManager* ui_manager = g_browser_process->notification_ui_manager(); if (!ui_manager) return; // the process is shutting down ui_manager->CancelById(notification_id, ProfileNotification::GetProfileID(profile)); } void NotificationPlatformBridgeMessageCenter::GetDisplayed( Profile* profile, GetDisplayedNotificationsCallback callback) const { std::set<std::string> displayed_notifications; NotificationUIManager* ui_manager = g_browser_process->notification_ui_manager(); if (ui_manager) { displayed_notifications = ui_manager->GetAllIdsByProfile( ProfileNotification::GetProfileID(profile)); } content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(std::move(callback), std::move(displayed_notifications), true /* supports_synchronization */)); } void NotificationPlatformBridgeMessageCenter::SetReadyCallback( NotificationBridgeReadyCallback callback) { std::move(callback).Run(true /* success */); } void NotificationPlatformBridgeMessageCenter::DisplayServiceShutDown( Profile* profile) {}
6,142
1,611
#include "lst_timer.h" #include "../http/http_conn.h" time_wheel::time_wheel() : cur_slot(0) { for(int i = 0; i < N; i++){ slots[i] = NULL; } } time_wheel::~time_wheel() { for(int i = 0; i < N; i++){ util_timer* tmp = slots[i]; while(tmp){ slots[i] = tmp -> next; delete tmp; tmp = slots[i]; } } } void time_wheel::add_timer(util_timer *timer) { int ticks = 0; time_t time_gap = timer->expire - time(NULL); if(time_gap < SI) { ticks = 1; } else { ticks = time_gap / SI; } //计算待插入的定时器在时间轮转动多少圈后被触发 int rotation = ticks / N; //计算待插入的定时器应该被插入哪个槽中 int ts = (cur_slot + (ticks % N)) % N; timer->rotation = rotation; timer->time_slot = ts; //如果第ts个槽尚无任何定时器则把新建的定时器插入其中,并将该定时器设置为该槽的头结点 if(!slots[ts]){ slots[ts] = timer; } else{ timer->next = slots[ts]; slots[ts]->prev = timer; slots[ts] = timer; } } void time_wheel::adjust_timer(util_timer *timer) { if (!timer) { return; } int ts = timer->time_slot; if(timer == slots[ts]) { slots[ts] = slots[ts]->next; if(slots[ts]) slots[ts]->prev = NULL; } else{ timer->prev->next = timer->next; if(timer->next) timer->next->prev = timer->prev; } timer -> next = nullptr; timer -> prev = nullptr; add_timer(timer); } void time_wheel::del_timer(util_timer *timer) { if(!timer) return; int ts = timer->time_slot; //slots[ts]是目标定时器所在槽的头结点。如果目标定时器就是该头结点,这需要重置第ts个槽的头结点 if(timer == slots[ts]){ slots[ts] = slots[ts]->next; if(slots[ts]) slots[ts]->prev = NULL; delete timer; } else{ timer->prev->next = timer->next; if(timer->next) timer->next->prev = timer->prev; delete timer; } } void time_wheel::tick() { util_timer* tmp = slots[cur_slot]; while(tmp){ //如果定时器的rotation值大于0,则它在这一轮不起作用 if(tmp -> rotation > 0){ tmp->rotation--; tmp = tmp->next; } //否则,说明定时器已经到期,于是执行定时任务,然后删除该定时器 else{ tmp->cb_func(tmp->user_data); if(tmp == slots[cur_slot]){ slots[cur_slot] = tmp->next; delete tmp; if(slots[cur_slot]){ slots[cur_slot]->prev = NULL; } tmp = slots[cur_slot]; } else{ tmp->prev->next = tmp->next; if(tmp->next){ tmp->next->prev = tmp->prev; } util_timer* tmp2 = tmp->next; delete tmp; tmp = tmp2; } } } cur_slot = ++cur_slot % N; } void Utils::init(int timeslot) { m_TIMESLOT = timeslot; } //对文件描述符设置非阻塞 int Utils::setnonblocking(int fd) { int old_option = fcntl(fd, F_GETFL); int new_option = old_option | O_NONBLOCK; fcntl(fd, F_SETFL, new_option); return old_option; } //将内核事件表注册读事件,ET模式,选择开启EPOLLONESHOT void Utils::addfd(int epollfd, int fd, bool one_shot, int TRIGMode) { epoll_event event; event.data.fd = fd; if (1 == TRIGMode) event.events = EPOLLIN | EPOLLET | EPOLLRDHUP; else event.events = EPOLLIN | EPOLLRDHUP; if (one_shot) event.events |= EPOLLONESHOT; epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event); setnonblocking(fd); } //信号处理函数 void Utils::sig_handler(int sig) { //为保证函数的可重入性,保留原来的errno int save_errno = errno; int msg = sig; send(u_pipefd[1], (char *)&msg, 1, 0); errno = save_errno; } //设置信号函数 void Utils::addsig(int sig, void(handler)(int), bool restart) { struct sigaction sa; memset(&sa, '\0', sizeof(sa)); sa.sa_handler = handler; if (restart) sa.sa_flags |= SA_RESTART; sigfillset(&sa.sa_mask); assert(sigaction(sig, &sa, NULL) != -1); } //定时处理任务,重新定时以不断触发SIGALRM信号 void Utils::timer_handler() { m_timer_lst.tick(); alarm(m_TIMESLOT); } void Utils::show_error(int connfd, const char *info) { send(connfd, info, strlen(info), 0); close(connfd); } int *Utils::u_pipefd = 0; int Utils::u_epollfd = 0; class Utils; void cb_func(client_data *user_data) //回调函数 { epoll_ctl(Utils::u_epollfd, EPOLL_CTL_DEL, user_data->sockfd, 0); assert(user_data); close(user_data->sockfd); http_conn::m_user_count--; }
4,506
1,946
#include "MenuSelection.hpp" MenuSelection::MenuSelection() { open = true; } MenuSelection::~MenuSelection(){} void MenuSelection::notAnimation(){ wantAnimation = false; } void MenuSelection::animation(){ wantAnimation = true; } int MenuSelection::select(sf::RenderWindow* window, std::vector<std::string> &buttonNames){ int qttyButtons = buttonNames.size(); sf::Vector2f buttonSize(window->getSize().x/(qttyButtons+2), window->getSize().y/6); sf::Font font; sf::Texture text; if(!font.loadFromFile("res/fonts/font.otf")){ std::cerr << "Can't find the font file" << std::endl; } open = true; while(open){ sf::Event event; while (window->pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window->close(); break; case sf::Event::KeyPressed: if (event.key.code == sf::Keyboard::Escape) window->close(); break; default: break; } } window->display(); } } void MenuSelection::display(sf::RenderWindow* window, std::string pathImage){ open = true; t.loadFromFile(pathImage); s = sf::Sprite(); s.setTexture(t); s.scale(window->getSize().y/s.getGlobalBounds().height,window->getSize().y/s.getGlobalBounds().height); s.setPosition(window->getSize().x/2 - s.getGlobalBounds().width/2, 0); while(open){ sf::Event event; while (window->pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window->close(); break; case sf::Event::KeyPressed: if (event.key.code == sf::Keyboard::Escape) window->close(); break; case sf::Event::MouseButtonPressed: if (event.mouseButton.button == sf::Mouse::Left) { open = false; } break; default: break; } //ANDROID if(event.type == sf::Event::TouchEnded) open = false; break; } window->clear(); window->draw(s); window->display(); } sf::Clock timer; sf::Sprite dark; sf::Texture text; bool closing = true; text.loadFromFile("res/pics/black.png"); dark.setTexture(text); dark.setOrigin(dark.getLocalBounds().width/2,dark.getLocalBounds().height/2); dark.setPosition(window->getSize().x/2,window->getSize().y/2); float scale = 1/dark.getGlobalBounds().width;; float time = 0; while(closing and wantAnimation){ dark.setScale(scale,scale); time += timer.restart().asSeconds(); if(time > 0.1){ scale *= 1.5; time = 0; } window->clear(); window->draw(s); window->draw(dark); window->display(); if(dark.getGlobalBounds().width > window->getSize().x) closing = false; } //clean events sf::Event e; while (window->pollEvent(e)) { } }
3,614
975
#ifndef PKG_PATH_NOT_A_DIRECTORY_ERROR_HPP #define PKG_PATH_NOT_A_DIRECTORY_ERROR_HPP #include "pkg_error.hpp" #include <string> namespace pkg { class path_not_a_directory_error : public pkg_error { public: path_not_a_directory_error(const std::string &path) throw(); }; } #endif
311
119
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved. /* binary_symmetric.cc Jeremy Barnes, 17 March 2006 Copyright (c) 2006 Jeremy Barnes. All rights reserved. $Source$ Functions to deal with binary symmetric data. */ #include "binary_symmetric.h" #include "training_data.h" #include "training_index.h" #include "mldb/plugins/jml/multi_array_utils.h" using namespace std; namespace ML { bool convert_bin_sym(boost::multi_array<float, 2> & weights, const Training_Data & data, const Feature & predicted, const vector<Feature> & features) { /* If we have a binary symmetric problem, then we reduce the weights down to just one column, since the second column would be the same as the first one. The bin_sym flag is true when all of the label weights will have the same value. This is only generally true in the binary classification case. It will be false when: 1. We learn a stump which updates the weights where */ int nl = data.label_count(predicted); bool bin_sym = false; int nx = weights.shape()[0]; //cerr << "convert_bin_sym" << endl; //cerr << "nl = " << nl << " nx = " << nx << endl; //cerr << "bin_sym: input: weights.shape()[1] = " // << weights.shape()[1] << endl; if (nl == 2) { bin_sym = true; /* Look at all of these features. If any don't have exactly_one true, then we are not binary symmetric. */ for (unsigned i = 0; i < features.size(); ++i) { if (!data.index().only_one(features[i])) { //cerr << "false due to feature " // << data.feature_space()->print(features[i]) // << endl; bin_sym = false; break; } } if (!bin_sym && weights.shape()[1] == 1) { /* Not bin sym for these features... expand them. */ //cerr << "expanding" << endl; boost::multi_array<float, 2> new_weights(boost::extents[nx][2]); for (unsigned x = 0; x < nx; ++x) new_weights[x][0] = new_weights[x][1] = weights[x][0]; swap_multi_arrays(weights, new_weights); } else if (bin_sym && weights.shape()[1] == 2) { for (unsigned x = 0; x < nx; ++x) { bin_sym = true; if (weights[x][0] != weights[x][1]) { bin_sym = false; //cerr << "false due to unequal weights " << endl; break; } } /* If we are binary symmetric, then we can reduce our weights array. */ if (bin_sym) { boost::multi_array<float, 2> new_weights(boost::extents[nx][1]); for (unsigned x = 0; x < nx; ++x) new_weights[x][0] = weights[x][0]; swap_multi_arrays(weights, new_weights); } } } //cerr << "bin_sym: returned " << bin_sym << " weights.shape()[1] = " // << weights.shape()[1] << endl; return bin_sym; } bool is_bin_sym(const boost::multi_array<float, 2> & weights, const Training_Data & data, const Feature & predicted, const vector<Feature> & features) { /* If we have a binary symmetric problem, then we reduce the weights down to just one column, since the second column would be the same as the first one. */ int nl = data.label_count(predicted); bool bin_sym = false; int nx = weights.shape()[0]; //cerr << "is_bin_sym" << endl; //cerr << "nl = " << nl << " nx = " << nx << endl; if (nl == 2) { if (weights.shape()[1] == 1) bin_sym = true; /* Look at all of these features. If any don't have exactly_one true, then we are not binary symmetric. */ for (unsigned i = 0; i < features.size(); ++i) { if (!data.index().only_one(features[i])) { bin_sym = false; break; } } if (bin_sym && weights.shape()[1] == 2) { for (unsigned x = 0; x < nx; ++x) { bin_sym = true; if (weights[x][0] != weights[x][1]) { bin_sym = false; break; } } } } //cerr << "is_bin_sym: returning " << bin_sym << endl; return bin_sym; } } // namespace ML
4,576
1,446