hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
588 values
lang
stringclasses
305 values
max_stars_repo_path
stringlengths
3
363
max_stars_repo_name
stringlengths
5
118
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringdate
2015-01-01 00:00:35
2022-03-31 23:43:49
max_stars_repo_stars_event_max_datetime
stringdate
2015-01-01 12:37:38
2022-03-31 23:59:52
max_issues_repo_path
stringlengths
3
363
max_issues_repo_name
stringlengths
5
118
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
float64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
363
max_forks_repo_name
stringlengths
5
135
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringdate
2015-01-01 00:01:02
2022-03-31 23:27:27
max_forks_repo_forks_event_max_datetime
stringdate
2015-01-03 08:55:07
2022-03-31 23:59:24
content
stringlengths
5
1.05M
avg_line_length
float64
1.13
1.04M
max_line_length
int64
1
1.05M
alphanum_fraction
float64
0
1
6b2aeb98b549b810e0d263d26ba35b9cc18bce36
5,275
h
C
exotations/solvers/exotica_ompl_control_solver/include/exotica_ompl_control_solver/ompl_control_solver.h
maxspahn/exotica
f748a5860939b870ab522a1bd553d2fa0da56f8e
[ "BSD-3-Clause" ]
130
2018-03-12T11:00:55.000Z
2022-02-21T02:41:28.000Z
exotations/solvers/exotica_ompl_control_solver/include/exotica_ompl_control_solver/ompl_control_solver.h
maxspahn/exotica
f748a5860939b870ab522a1bd553d2fa0da56f8e
[ "BSD-3-Clause" ]
349
2017-09-14T00:42:33.000Z
2022-03-29T13:51:04.000Z
exotations/solvers/exotica_ompl_control_solver/include/exotica_ompl_control_solver/ompl_control_solver.h
maxspahn/exotica
f748a5860939b870ab522a1bd553d2fa0da56f8e
[ "BSD-3-Clause" ]
48
2017-10-04T15:50:42.000Z
2022-02-10T05:03:39.000Z
// // Copyright (c) 2019, University of Edinburgh // 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 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 EXOTICA_OMPL_CONTROL_SOLVER_OMPL_CONTROL_SOLVER_H_ #define EXOTICA_OMPL_CONTROL_SOLVER_OMPL_CONTROL_SOLVER_H_ // #include <exotica_core/feedback_motion_solver.h> #include <exotica_core/motion_solver.h> #include <exotica_core/problems/dynamic_time_indexed_shooting_problem.h> #include <exotica_ompl_control_solver/ompl_control_solver_initializer.h> // TODO: Remove unused includes #include <ompl/base/goals/GoalState.h> #include <ompl/base/spaces/SE2StateSpace.h> #include <ompl/control/SimpleSetup.h> #include <ompl/control/SpaceInformation.h> #include <ompl/control/spaces/RealVectorControlSpace.h> namespace ob = ompl::base; namespace oc = ompl::control; typedef std::function<ob::PlannerPtr(const oc::SpaceInformationPtr &si)> ConfiguredPlannerAllocator; namespace exotica { class OMPLStatePropagator : public oc::StatePropagator { public: OMPLStatePropagator( oc::SpaceInformationPtr si, DynamicsSolverPtr dynamics_solver_) : oc::StatePropagator(si), space_(si), dynamics_solver_(dynamics_solver_) {} void propagate( const ob::State *state, const oc::Control *control, const double duration, ob::State *result) const override { double t = 0; space_->copyState(result, state); while (t < duration) { Integrate(result, control, timeStep_); t += timeStep_; } } void setIntegrationTimeStep(double timeStep) { timeStep_ = timeStep; } double getIntegrationTimeStep() const { return timeStep_; } private: double timeStep_ = 0.0; oc::SpaceInformationPtr space_; DynamicsSolverPtr dynamics_solver_; void Integrate(ob::State *ob_x, const oc::Control *oc_u, double dt) const { const int NU = dynamics_solver_->get_num_controls(); const int NX = dynamics_solver_->get_num_positions() + dynamics_solver_->get_num_velocities(); double *x = ob_x->as<ob::RealVectorStateSpace::StateType>()->values; double *u = oc_u->as<oc::RealVectorControlSpace::ControlType>()->values; Eigen::VectorXd eig_x = Eigen::Map<Eigen::VectorXd>(x, NX); Eigen::VectorXd eig_u = Eigen::Map<Eigen::VectorXd>(u, NU); Eigen::VectorXd x_new = dynamics_solver_->Simulate(eig_x, eig_u, dt); std::memcpy(x, x_new.data(), NX * sizeof(double)); } }; class OMPLControlSolver : public MotionSolver { public: ///\brief Solves the problem ///@param solution Returned solution trajectory as a vector of joint configurations. void Solve(Eigen::MatrixXd &solution) override; ///\brief Binds the solver to a specific problem which must be pre-initalised ///@param pointer Shared pointer to the motion planning problem ///@return Successful if the problem is a valid DynamicTimeIndexedProblem void SpecifyProblem(PlanningProblemPtr pointer) override; protected: template <typename PlannerType> static ob::PlannerPtr AllocatePlanner(const oc::SpaceInformationPtr &si) { ob::PlannerPtr planner(new PlannerType(si)); return planner; } DynamicTimeIndexedShootingProblemPtr prob_; ///!< Shared pointer to the planning problem. DynamicsSolverPtr dynamics_solver_; ///!< Shared pointer to the dynamics solver. OMPLControlSolverInitializer init_; std::unique_ptr<oc::SimpleSetup> setup_; std::string algorithm_; ConfiguredPlannerAllocator planner_allocator_; void Setup(); bool isStateValid(const oc::SpaceInformationPtr si, const ob::State *state) { return true; } }; } // namespace exotica #endif // EXOTICA_OMPL_CONTROL_SOLVER_OMPL_CONTROL_SOLVER_H_
36.130137
120
0.726256
07f3fb65d350b547b5a5c856d301b951d423d8f3
1,883
h
C
third_party/retdec-3.2/include/retdec/bin2llvmir/optimizations/value_protect/value_protect.h
Fimbure/icebox-1
0b81992a53e1b410955ca89bdb6f8169d6f2da86
[ "MIT" ]
521
2019-03-29T15:44:08.000Z
2022-03-22T09:46:19.000Z
third_party/retdec-3.2/include/retdec/bin2llvmir/optimizations/value_protect/value_protect.h
Fimbure/icebox-1
0b81992a53e1b410955ca89bdb6f8169d6f2da86
[ "MIT" ]
30
2019-06-04T17:00:49.000Z
2021-09-08T20:44:19.000Z
third_party/retdec-3.2/include/retdec/bin2llvmir/optimizations/value_protect/value_protect.h
Fimbure/icebox-1
0b81992a53e1b410955ca89bdb6f8169d6f2da86
[ "MIT" ]
99
2019-03-29T16:04:13.000Z
2022-03-28T16:59:34.000Z
/** * @file include/retdec/bin2llvmir/optimizations/value_protect/value_protect.h * @brief Protect values from LLVM optimization passes. * @copyright (c) 2017 Avast Software, licensed under the MIT license */ #ifndef RETDEC_BIN2LLVMIR_OPTIMIZATIONS_VALUE_PROTECT_VALUE_PROTECT_H #define RETDEC_BIN2LLVMIR_OPTIMIZATIONS_VALUE_PROTECT_VALUE_PROTECT_H #include <llvm/IR/Function.h> #include <llvm/IR/Module.h> #include <llvm/Pass.h> #include "retdec/bin2llvmir/providers/abi/abi.h" #include "retdec/bin2llvmir/providers/config.h" namespace retdec { namespace bin2llvmir { /** * Generates patterns like this at functions' entry BBs: * \code{.ll} * %1 = call i32 @__decompiler_undefined_function_X() * store i32 %1, i32* XYZ * \endcode * Where XYZ are allocated variables (registers, stacks). * * This is done to protect these variables from aggressive LLVM optimizations. * This way, stacks are not uninitialized, and registers are not equal to * their initialization values. * * Every even run generates these protections. * Every odd run removes them * (partially, see https://github.com/avast-tl/retdec/issues/301). */ class ValueProtect : public llvm::ModulePass { public: static char ID; ValueProtect(); virtual bool runOnModule(llvm::Module& M) override; bool runOnModuleCustom(llvm::Module& M, Config* c, Abi* abi); private: bool run(); void protect(); void protectStack(); void protectRegisters(); void unprotect(); void protectValue( llvm::Value* val, llvm::Type* t, llvm::Instruction* before); llvm::Function* getOrCreateFunction(llvm::Type* t); llvm::Function* createFunction(llvm::Type* t); private: llvm::Module* _module = nullptr; Config* _config = nullptr; Abi* _abi = nullptr; static std::map<llvm::Type*, llvm::Function*> _type2fnc; }; } // namespace bin2llvmir } // namespace retdec #endif
26.9
78
0.734466
1d066bfe1d0a4bc8282845181b267ef47e0c6911
8,523
h
C
Headers/java/util/concurrent/ScheduledExecutorService.h
tcak76/j2objc
bb9415df98c3fdd1e5e3f4b9e27049d0b2e42633
[ "MIT" ]
11
2015-12-10T13:23:54.000Z
2019-04-23T02:41:13.000Z
Headers/java/util/concurrent/ScheduledExecutorService.h
tcak76/j2objc
bb9415df98c3fdd1e5e3f4b9e27049d0b2e42633
[ "MIT" ]
7
2015-11-05T22:45:53.000Z
2017-11-05T14:36:36.000Z
Headers/java/util/concurrent/ScheduledExecutorService.h
tcak76/j2objc
bb9415df98c3fdd1e5e3f4b9e27049d0b2e42633
[ "MIT" ]
40
2015-12-10T07:30:58.000Z
2022-03-15T02:50:10.000Z
// // Generated by the J2ObjC translator. DO NOT EDIT! // source: android/libcore/luni/src/main/java/java/util/concurrent/ScheduledExecutorService.java // #include "../../../J2ObjC_header.h" #pragma push_macro("INCLUDE_ALL_JavaUtilConcurrentScheduledExecutorService") #ifdef RESTRICT_JavaUtilConcurrentScheduledExecutorService #define INCLUDE_ALL_JavaUtilConcurrentScheduledExecutorService 0 #else #define INCLUDE_ALL_JavaUtilConcurrentScheduledExecutorService 1 #endif #undef RESTRICT_JavaUtilConcurrentScheduledExecutorService #pragma clang diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #if !defined (JavaUtilConcurrentScheduledExecutorService_) && (INCLUDE_ALL_JavaUtilConcurrentScheduledExecutorService || defined(INCLUDE_JavaUtilConcurrentScheduledExecutorService)) #define JavaUtilConcurrentScheduledExecutorService_ #define RESTRICT_JavaUtilConcurrentExecutorService 1 #define INCLUDE_JavaUtilConcurrentExecutorService 1 #include "../../../java/util/concurrent/ExecutorService.h" @class JavaUtilConcurrentTimeUnit; @protocol JavaLangRunnable; @protocol JavaUtilConcurrentCallable; @protocol JavaUtilConcurrentScheduledFuture; /*! @brief An <code>ExecutorService</code> that can schedule commands to run after a given delay, or to execute periodically. <p>The <code>schedule</code> methods create tasks with various delays and return a task object that can be used to cancel or check execution. The <code>scheduleAtFixedRate</code> and <code>scheduleWithFixedDelay</code> methods create and execute tasks that run periodically until cancelled. <p>Commands submitted using the <code>Executor.execute(Runnable)</code> and <code>ExecutorService</code> <code>submit</code> methods are scheduled with a requested delay of zero. Zero and negative delays (but not periods) are also allowed in <code>schedule</code> methods, and are treated as requests for immediate execution. <p>All <code>schedule</code> methods accept <em>relative</em> delays and periods as arguments, not absolute times or dates. It is a simple matter to transform an absolute time represented as a <code>java.util.Date</code> to the required form. For example, to schedule at a certain future <code>date</code>, you can use: <code>schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS)</code> . Beware however that expiration of a relative delay need not coincide with the current <code>Date</code> at which the task is enabled due to network time synchronization protocols, clock drift, or other factors. <p>The <code>Executors</code> class provides convenient factory methods for the ScheduledExecutorService implementations provided in this package. <h3>Usage Example</h3> Here is a class with a method that sets up a ScheduledExecutorService to beep every ten seconds for an hour: @code import static java.util.concurrent.TimeUnit.*; class BeeperControl private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); public void beepForAnHour() { final Runnable beeper = new Runnable() { public void run() { System.out.println("beep"); } }; final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS); scheduler.schedule(new Runnable() { public void run() { beeperHandle.cancel(true); } }, 60 * 60, SECONDS); } @endcode @since 1.5 @author Doug Lea */ @protocol JavaUtilConcurrentScheduledExecutorService < JavaUtilConcurrentExecutorService, NSObject, JavaObject > /*! @brief Creates and executes a one-shot action that becomes enabled after the given delay. @param command the task to execute @param delay the time from now to delay execution @param unit the time unit of the delay parameter @return a ScheduledFuture representing pending completion of the task and whose <code>get()</code> method will return <code>null</code> upon completion @throws RejectedExecutionException if the task cannot be scheduled for execution @throws NullPointerException if command is null */ - (id<JavaUtilConcurrentScheduledFuture>)scheduleWithJavaLangRunnable:(id<JavaLangRunnable>)command withLong:(jlong)delay withJavaUtilConcurrentTimeUnit:(JavaUtilConcurrentTimeUnit *)unit; /*! @brief Creates and executes a ScheduledFuture that becomes enabled after the given delay. @param callable the function to execute @param delay the time from now to delay execution @param unit the time unit of the delay parameter @return a ScheduledFuture that can be used to extract result or cancel @throws RejectedExecutionException if the task cannot be scheduled for execution @throws NullPointerException if callable is null */ - (id<JavaUtilConcurrentScheduledFuture>)scheduleWithJavaUtilConcurrentCallable:(id<JavaUtilConcurrentCallable>)callable withLong:(jlong)delay withJavaUtilConcurrentTimeUnit:(JavaUtilConcurrentTimeUnit *)unit; /*! @brief Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after <code>initialDelay</code> then <code>initialDelay+period</code>, then <code>initialDelay + 2 * period</code>, and so on. If any execution of the task encounters an exception, subsequent executions are suppressed. Otherwise, the task will only terminate via cancellation or termination of the executor. If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute. @param command the task to execute @param initialDelay the time to delay first execution @param period the period between successive executions @param unit the time unit of the initialDelay and period parameters @return a ScheduledFuture representing pending completion of the task, and whose <code>get()</code> method will throw an exception upon cancellation @throws RejectedExecutionException if the task cannot be scheduled for execution @throws NullPointerException if command is null @throws IllegalArgumentException if period less than or equal to zero */ - (id<JavaUtilConcurrentScheduledFuture>)scheduleAtFixedRateWithJavaLangRunnable:(id<JavaLangRunnable>)command withLong:(jlong)initialDelay withLong:(jlong)period withJavaUtilConcurrentTimeUnit:(JavaUtilConcurrentTimeUnit *)unit; /*! @brief Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next. If any execution of the task encounters an exception, subsequent executions are suppressed. Otherwise, the task will only terminate via cancellation or termination of the executor. @param command the task to execute @param initialDelay the time to delay first execution @param delay the delay between the termination of one execution and the commencement of the next @param unit the time unit of the initialDelay and delay parameters @return a ScheduledFuture representing pending completion of the task, and whose <code>get()</code> method will throw an exception upon cancellation @throws RejectedExecutionException if the task cannot be scheduled for execution @throws NullPointerException if command is null @throws IllegalArgumentException if delay less than or equal to zero */ - (id<JavaUtilConcurrentScheduledFuture>)scheduleWithFixedDelayWithJavaLangRunnable:(id<JavaLangRunnable>)command withLong:(jlong)initialDelay withLong:(jlong)delay withJavaUtilConcurrentTimeUnit:(JavaUtilConcurrentTimeUnit *)unit; @end J2OBJC_EMPTY_STATIC_INIT(JavaUtilConcurrentScheduledExecutorService) J2OBJC_TYPE_LITERAL_HEADER(JavaUtilConcurrentScheduledExecutorService) #endif #pragma clang diagnostic pop #pragma pop_macro("INCLUDE_ALL_JavaUtilConcurrentScheduledExecutorService")
47.088398
181
0.749032
df68f06159da1bfdda5831d12b1add89525d82f6
44,081
c
C
word2vec.c
Jiajie-Mei/word2vec
69b1e219225a8ef0bc005873c925e3918cd405f4
[ "Apache-2.0" ]
6
2017-07-14T05:39:34.000Z
2020-03-30T08:29:40.000Z
word2vec.c
ccmaymay/word2vec
043dcc4a41d93b89414f85ae65a556c902bc255a
[ "Apache-2.0" ]
null
null
null
word2vec.c
ccmaymay/word2vec
043dcc4a41d93b89414f85ae65a556c902bc255a
[ "Apache-2.0" ]
null
null
null
// Copyright 2013 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. // --------------------------------------------------------------------- // // Word2vec C code commented by Chandler May. Run // // git diff original // // to see the complete set of changes to the original code. // // Preliminaries: // * There are a lot of global variables. They are important. // * a, b, and c are used for loop counters and lots of other things; // it's not uncommon for one of them to be set to one thing and then // re-initialized and used for something completely different. // * Random number generation is through a custom linear congruential // generator. This in particular facilitates decoupled random number // generation across training threads. // // Notation: // * Backticks are used to denote variables (`foo`) // * The skip-gram model learns co-occurrence information between a // word and a fixed-length window of context words on either side of // it. The embedding of the central word is called the "input" // representation and the embeddings of the left and right context // words are "output" representations. This distinction (and // terminology) are quite important for understanding the code so here // is an example, assumping a context window of two words on either // side: // // The quick brown fox jumped over the lazy dog. // ^ ^ ^ ^ ^ // | | | | | // output output input output output // // When looking at the input word "jumped" in this sentence, the // skip-gram with negative sampling (SGNS) model learns that it // co-occurs with "brown" and "fox" and "over" and "the" and does not // co-occur with a selection of negative-sample words (perhaps // "apple", "of", and "slithered"). // // Partial call graph: // // main // | // L- TrainModel // | // |- ReadVocab // | |- ReadWord // | |- AddWordToVocab // | L- SortVocab // | // |- LearnVocabFromTrainFile // | |- ReadWord // | |- AddWordToVocab // | |- SearchVocab // | |- ReduceVocab // | L- SortVocab // | // |- SaveVocab // |- InitNet // |- InitUnigramTable // | // L- TrainModelThread // L- ReadWordIndex // |- ReadWord // L- SearchVocab // // --------------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <pthread.h> // max length of filenames, vocabulary words (including null terminator) #define MAX_STRING 100 // size of pre-computed e^x / (e^x + 1) table #define EXP_TABLE_SIZE 1000 // max exponent x for which to pre-compute e^x / (e^x + 1) #define MAX_EXP 6 // max length (in words) of a sequence of overlapping word contexts or // "sentences" (if there is a sequence of words longer than this not // explicitly broken up into multiple "sentences" in the training data, // it will be broken up into multiple "sentences" of length no longer // than `MAX_SENTENCE_LENGTH` each during training) #define MAX_SENTENCE_LENGTH 1000 // max length of Huffman codes used by hierarchical softmax #define MAX_CODE_LENGTH 40 // Maximum 30 * 0.7 = 21M words in the vocabulary // (where 0.7 is the magical load factor beyond which hash table // performance degrades) const int vocab_hash_size = 30000000; // Negative sampling distribution represented by 1e8-element discrete // sample from smoothed empirical unigram distribution. const int table_size = 1e8; // Set precision of real numbers typedef float real; // Representation of a word in the vocabulary, including (optional, // for hierarchical softmax only) Huffman coding struct vocab_word { long long cn; int *point; char *word, *code, codelen; }; struct vocab_word *vocab; // vocabulary char train_file[MAX_STRING], // training data (text) input file output_file[MAX_STRING], // word vector (or word vector cluster) // (binary/text) output file save_vocab_file[MAX_STRING], // vocabulary (text) output file read_vocab_file[MAX_STRING]; // vocabulary (text) input file int binary = 0, // 0 for text output, 1 for binary cbow = 1, // 0 for skip-gram, 1 for CBOW debug_mode = 2, // 1 for extra terminal output, 2 for // extra extra terminal output window = 5, // context window radius (use `window` // output words on left and `window` // output words on right as context // of central input word) min_count = 5, // min count of words in vocabulary when // pruning to mitigate sparsity num_threads = 12, // number of threads to use for training min_reduce = 1, // initial min count of words to keep in // vocabulary if pruning for space // (will be incremented as necessary) // (do not change) hs = 0, // 1 for hierarchical softmax negative = 5; // number of negative samples to draw // per word int *vocab_hash, // hash table of words to positions in // vocabulary *table; // discrete sample of words used as // negative sampling distribution long long vocab_max_size = 1000, // capacity of vocabulary // (will be incremented as necessary) vocab_size = 0, // number of words in vocabulary // (do not change) layer1_size = 100, // size of embeddings train_words = 0, // number of word tokens in training data // (do not change) word_count_actual = 0, // number of word tokens seen so far // during training, over all // iterations; updated infrequently // (used for terminal output and // learning rate) // (do not change) iter = 5, // number of passes to take through // training data file_size = 0, // size (in bytes) of training data file classes = 0; // number of k-means clusters to learn // of word vectors and write to output // file (0 to write word vectors to // output file, no clustering) real alpha = 0.025, // linear-decay learning rate starting_alpha, // initial learning rate // (do not change; initialized at // beginning of training) sample = 1e-3; // word subsampling threshold real *syn0, // input word embeddings *syn1, // (used by hierarchical softmax) *syn1neg, // output word embeddings *expTable; // precomputed table of // e^x / (e^x + 1) for x in // [-MAX_EXP, MAX_EXP) clock_t start; // start time of training algorithm // Allocate and populate negative-sampling data structure `table`, an // array of `table_size` words distributed approximately according to // the empirical unigram distribution (smoothed by raising all // probabilities to the power of 0.75 and re-normalizing), from `vocab`, // an array of `vocab_size` words represented as `vocab_word` structs. void InitUnigramTable() { int a, i; double train_words_pow = 0; double d1, power = 0.75; // allocate memory table = (int *)malloc(table_size * sizeof(int)); // compute normalizer, `train_words_pow` for (a = 0; a < vocab_size; a++) train_words_pow += pow(vocab[a].cn, power); // initialize vocab position `i` and cumulative probability mass `d1` i = 0; d1 = pow(vocab[i].cn, power) / train_words_pow; for (a = 0; a < table_size; a++) { table[a] = i; if (a / (double)table_size > d1) { i++; d1 += pow(vocab[i].cn, power) / train_words_pow; } if (i >= vocab_size) i = vocab_size - 1; } } // Read a single word from file `fin` into length `MAX_STRING` array // `word`, terminating with a null byte, treating space, tab, and // newline as word boundaries. Ignore carriage returns. If the first // character read (excluding carriage returns) is a newline, set `word` // to "</s>" and return. If a newline is encountered after reading one // or more non-boundary characters, put that newline back into the // stream and leave word as the non-boundary characters up to that point // (so that the next time this function is called the newline will be // read and `word` will be set to "</s>"). If the number of // non-boundary characters is equal to or greater than `MAX_STRING`, // read and ignore the trailing characters. If we reach end of file, // set `eof` to 1. void ReadWord(char *word, FILE *fin, char *eof) { int a = 0, ch; while (1) { ch = fgetc_unlocked(fin); if (ch == EOF) { *eof = 1; break; } if (ch == '\r') continue; // skip carriage returns if ((ch == ' ') || (ch == '\t') || (ch == '\n')) { if (a > 0) { if (ch == '\n') ungetc(ch, fin); break; } if (ch == '\n') { strcpy(word, (char *)"</s>"); return; } else continue; } word[a] = ch; a++; if (a >= MAX_STRING - 1) a--; // Truncate too-long words } word[a] = 0; } // Return hash (integer between 0, inclusive, and `vocab_hash_size`, // exclusive) of `word` int GetWordHash(char *word) { unsigned long long a, hash = 0; for (a = 0; a < strlen(word); a++) hash = hash * 257 + word[a]; hash = hash % vocab_hash_size; return hash; } // Return position of `word` in vocabulary `vocab` using `vocab_hash`, // a linear-probing hash table; if the word is not found, return -1. int SearchVocab(char *word) { // compute initial hash unsigned int hash = GetWordHash(word); while (1) { // return -1 if cell is empty if (vocab_hash[hash] == -1) return -1; // return position at current hash if word is a match if (!strcmp(word, vocab[vocab_hash[hash]].word)) return vocab_hash[hash]; // no match, increment hash hash = (hash + 1) % vocab_hash_size; } return -1; } // Read a word from file `fin` and return its position in vocabulary // `vocab`. If the next thing in the file is a newline, return 0 (the // index of "</s>"). If the word is not in the vocabulary, return -1. // If the end of file is reached, set `eof` to 1 and return -1. TODO: // if the file is not newline-terminated, the last word will be // swallowed (-1 will be returned because we have reached EOF, even if // a word was read). int ReadWordIndex(FILE *fin, char *eof) { char word[MAX_STRING], eof_l = 0; ReadWord(word, fin, &eof_l); if (eof_l) { *eof = 1; return -1; } return SearchVocab(word); } // Add word `word` to first empty slot in vocabulary `vocab`, increment // vocabulary length `vocab_size`, increase `vocab_max_size` by // increments of 1000 (increasing `vocab` allocation) as needed, and set // position of that slot in vocabulary hash table `vocab_hash`. // Return index of `word` in `vocab`. int AddWordToVocab(char *word) { unsigned int hash, length = strlen(word) + 1; if (length > MAX_STRING) length = MAX_STRING; // add word to `vocab` and increment `vocab_size` vocab[vocab_size].word = (char *)calloc(length, sizeof(char)); // TODO: this may blow up if strlen(word) + 1 > MAX_STRING strcpy(vocab[vocab_size].word, word); vocab[vocab_size].cn = 0; vocab_size++; // Reallocate memory if needed if (vocab_size + 2 >= vocab_max_size) { vocab_max_size += 1000; vocab = (struct vocab_word *)realloc(vocab, vocab_max_size * sizeof(struct vocab_word)); } // add word vocabulary position to `vocab_hash` hash = GetWordHash(word); while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; vocab_hash[hash] = vocab_size - 1; return vocab_size - 1; } // Given pointers `a` and `b` to `vocab_word` structs, return 1 if the // stored count `cn` of b is greater than that of a, -1 if less than, // and 0 if equal. (Comparator for a reverse sort by word count.) int VocabCompare(const void *a, const void *b) { long long l = ((struct vocab_word *)b)->cn - ((struct vocab_word *)a)->cn; if (l > 0) return 1; if (l < 0) return -1; return 0; } // Sort vocabulary `vocab` by word count, decreasing, while removing // words that have count less than `min_count`; re-compute `vocab_hash` // accordingly; shrink vocab memory allocation to minimal size. void SortVocab() { int a, size; unsigned int hash; // Sort the vocabulary but keep "</s>" at the first position qsort(&vocab[1], vocab_size - 1, sizeof(struct vocab_word), VocabCompare); // clear `vocab_hash` cells for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; // save initial `vocab_size` (we will decrease `vocab_size` as we // prune infrequent words) size = vocab_size; // initialize total word count train_words = 0; for (a = 0; a < size; a++) { if ((vocab[a].cn < min_count) && (a != 0)) { // word is infrequent and not "</s>", discard it vocab_size--; free(vocab[a].word); } else { // word is frequent or "</s>", add to hash table hash=GetWordHash(vocab[a].word); while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; vocab_hash[hash] = a; train_words += vocab[a].cn; } } // shrink vocab memory allocation to minimal size // TODO: to be safe we should probably update vocab_max_size which // seems to be interpreted as the allocation size vocab = (struct vocab_word *)realloc(vocab, (vocab_size + 1) * sizeof(struct vocab_word)); // Allocate memory for the binary tree construction for (a = 0; a < vocab_size; a++) { vocab[a].code = (char *)calloc(MAX_CODE_LENGTH, sizeof(char)); vocab[a].point = (int *)calloc(MAX_CODE_LENGTH, sizeof(int)); } } // Reduce vocabulary `vocab` size by removing words with count equal to // `min_reduce` or less, in order to make room in hash table (not for // mitigating data sparsity). Increment `min_reduce` by one, so that // this function can be called in a loop until there is enough space. void ReduceVocab() { int a, b = 0; unsigned int hash; for (a = 0; a < vocab_size; a++) if (vocab[a].cn > min_reduce) { vocab[b].cn = vocab[a].cn; vocab[b].word = vocab[a].word; b++; } else free(vocab[a].word); vocab_size = b; for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; // recompute `vocab_hash` as we have removed some items and it may // now be broken for (a = 0; a < vocab_size; a++) { hash = GetWordHash(vocab[a].word); while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; vocab_hash[hash] = a; } fflush(stdout); min_reduce++; } // Create binary Huffman tree from word counts in `vocab`, storing // codes in `vocab`; frequent words will have short uniqe binary codes. // Used by hierarchical softmax. void CreateBinaryTree() { long long a, b, i, min1i, min2i, pos1, pos2, point[MAX_CODE_LENGTH]; char code[MAX_CODE_LENGTH]; long long *count = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long)); long long *binary = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long)); long long *parent_node = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long)); for (a = 0; a < vocab_size; a++) count[a] = vocab[a].cn; for (a = vocab_size; a < vocab_size * 2; a++) count[a] = 1e15; pos1 = vocab_size - 1; pos2 = vocab_size; // Following algorithm constructs the Huffman tree by adding one node at a time for (a = 0; a < vocab_size - 1; a++) { // First, find two smallest nodes 'min1, min2' if (pos1 >= 0) { if (count[pos1] < count[pos2]) { min1i = pos1; pos1--; } else { min1i = pos2; pos2++; } } else { min1i = pos2; pos2++; } if (pos1 >= 0) { if (count[pos1] < count[pos2]) { min2i = pos1; pos1--; } else { min2i = pos2; pos2++; } } else { min2i = pos2; pos2++; } count[vocab_size + a] = count[min1i] + count[min2i]; parent_node[min1i] = vocab_size + a; parent_node[min2i] = vocab_size + a; binary[min2i] = 1; } // Now assign binary code to each vocabulary word for (a = 0; a < vocab_size; a++) { b = a; i = 0; while (1) { code[i] = binary[b]; point[i] = b; i++; b = parent_node[b]; if (b == vocab_size * 2 - 2) break; } vocab[a].codelen = i; vocab[a].point[0] = vocab_size - 2; for (b = 0; b < i; b++) { vocab[a].code[i - b - 1] = code[b]; vocab[a].point[i - b] = point[b] - vocab_size; } } free(count); free(binary); free(parent_node); } // Compute vocabulary `vocab` and corresponding hash table `vocab_hash` // from text in `train_file`. Insert </s> as vocab item 0. Prune vocab // incrementally (as needed to keep number of items below effective hash // table capacity). After reading file, sort vocabulary by word count, // decreasing. void LearnVocabFromTrainFile() { char word[MAX_STRING], eof = 0; FILE *fin; long long a, i, wc = 0; for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; fin = fopen(train_file, "rb"); if (fin == NULL) { printf("ERROR: training data file not found!\n"); exit(1); } vocab_size = 0; AddWordToVocab((char *)"</s>"); while (1) { // TODO: if file is not newline-terminated, last word may be // swallowed ReadWord(word, fin, &eof); if (eof) break; train_words++; wc++; if ((debug_mode > 1) && (wc >= 1000000)) { printf("%lldM%c", train_words / 1000000, 13); fflush(stdout); wc = 0; } i = SearchVocab(word); if (i == -1) { a = AddWordToVocab(word); vocab[a].cn = 1; } else vocab[i].cn++; if (vocab_size > vocab_hash_size * 0.7) ReduceVocab(); } SortVocab(); if (debug_mode > 0) { printf("Vocab size: %lld\n", vocab_size); printf("Words in train file: %lld\n", train_words); } file_size = ftell(fin); fclose(fin); } // Write vocabulary `vocab` to file `save_vocab_file`, one word per // line, with each line containing a word, a space, the word count, and // a newline. void SaveVocab() { long long i; FILE *fo = fopen(save_vocab_file, "wb"); for (i = 0; i < vocab_size; i++) fprintf(fo, "%s %lld\n", vocab[i].word, vocab[i].cn); fclose(fo); } // Read vocabulary from file `read_vocab_file` that has one word per // line, where each line contains a word, a space, the word count, and a // newline. Store vocabulary in `vocab` and update `vocab_hash` // accordingly. After reading, sort vocabulary by word count, // decreasing. void ReadVocab() { long long a, i = 0; char c, eof = 0; char word[MAX_STRING]; FILE *fin = fopen(read_vocab_file, "rb"); if (fin == NULL) { printf("Vocabulary file not found\n"); exit(1); } for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; vocab_size = 0; while (1) { // TODO: if file is not newline-terminated, last word may be // swallowed ReadWord(word, fin, &eof); if (eof) break; a = AddWordToVocab(word); fscanf(fin, "%lld%c", &vocab[a].cn, &c); i++; } SortVocab(); if (debug_mode > 0) { printf("Vocab size: %lld\n", vocab_size); printf("Words in train file: %lld\n", train_words); } fin = fopen(train_file, "rb"); if (fin == NULL) { printf("ERROR: training data file not found!\n"); exit(1); } fseek(fin, 0, SEEK_END); file_size = ftell(fin); fclose(fin); } // Allocate memory for and initialize neural network parameters. Each // array has size `vocab_size` x `layer1_size`. // // syn0: input word embeddings, initialized uniformly on // [-0.5/`layer1_size`, 0.5/`layer1_size`) // syn1: only used by hierarchical softmax; initialized to 0 // syn1neg: output word embeddings; initialized to zero void InitNet() { long long a, b; unsigned long long next_random = 1; a = posix_memalign((void **)&syn0, 128, (long long)vocab_size * layer1_size * sizeof(real)); if (syn0 == NULL) {printf("Memory allocation failed\n"); exit(1);} if (hs) { a = posix_memalign((void **)&syn1, 128, (long long)vocab_size * layer1_size * sizeof(real)); if (syn1 == NULL) {printf("Memory allocation failed\n"); exit(1);} for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++) syn1[a * layer1_size + b] = 0; } if (negative>0) { a = posix_memalign((void **)&syn1neg, 128, (long long)vocab_size * layer1_size * sizeof(real)); if (syn1neg == NULL) {printf("Memory allocation failed\n"); exit(1);} for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++) syn1neg[a * layer1_size + b] = 0; } for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++) { next_random = next_random * (unsigned long long)25214903917 + 11; syn0[a * layer1_size + b] = (((next_random & 0xFFFF) / (real)65536) - 0.5) / layer1_size; } CreateBinaryTree(); } // Given allocated and initialized vocabulary `vocab`, corresponding // hash `vocab_hash`, and neural network parameters `syn0`, `syn1`, and // `syn1neg`, train word2vec model on 1 / `num_threads` fraction of text // in `train_file` (storing learned parameters in `syn0`, `syn1`, and // `syn1neg`). When cast to long long, `id` should be an integer // between 0 (inclusive) and `num_threads` (exclusive) representing // which training thread this is. // // Note main loop is broken down into procedures for hierarchical // softmax versus negative sampling and those for continuous BOW versus // skip-gram; ensure you are looking in the right code block (for your // purposes)! The added comments focus on the SGNS case. void *TrainModelThread(void *id) { long long a, // loop counter among other things b, // offset of dynamic window in max window // (if 0, use all `window` output // words on each side of input word; // otherwise use `window - b` words // on each side) d, // loop counter among other things cw, // (used by CBOW) word, // index of output word in vocabulary last_word, // index of input word in vocabulary sentence_length = 0, // number of words read into the current // sentence sentence_position = 0, // position of current output word in // sentence word_count = 0, // number of words seen so far in this // iteration last_word_count = 0, // number of words seen so far in this // iteration, as of the most recent // update of terminal output and learning // rate l1, // input word row offset in syn0 l2, // output word row offset in syn1, syn1neg c, // loop counter among other things target, // index of output word or negatively-sampled // word in vocabulary label, // switch between output word (1) and // negatively-sampled word (0) local_iter = iter; // iterations over this thread's chunk of the // data set left long long sen[MAX_SENTENCE_LENGTH + 1]; // index of word in vocabulary for // each word in current sentence unsigned long long next_random = (long long)id; // thread-specific RNG state char eof = 0; // 1 if end of file has been reached real f, g; // work space (values of sub-expressions in // gradient computation) clock_t now; // current time during training // allocate memory for gradients real *neu1 = (real *)calloc(layer1_size, sizeof(real)), *neu1e = (real *)calloc(layer1_size, sizeof(real)); FILE *fi = fopen(train_file, "rb"); fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET); // iteratively read a sentence and train (update gradients) over it; // read over all sentences in this thread's chunk of the training // data `iter` times, then break while (1) { // every 10k words, update progress in terminal and update learning // rate if (word_count - last_word_count > 10000) { word_count_actual += word_count - last_word_count; last_word_count = word_count; if ((debug_mode > 1)) { now=clock(); printf("%cAlpha: %f Progress: %.2f%% Words/thread/sec: %.2fk ", 13, alpha, word_count_actual / (real)(iter * train_words + 1) * 100, word_count_actual / ((real)(now - start + 1) / (real)CLOCKS_PER_SEC * 1000)); fflush(stdout); } // linear-decay learning rate (decreases from one toward zero // linearly in number of words seen, but thresholded below // at one ten-thousandth of initial learning rate) // (each word in the data is to be seen `iter` times) alpha = starting_alpha * (1 - word_count_actual / (real)(iter * train_words + 1)); if (alpha < starting_alpha * 0.0001) alpha = starting_alpha * 0.0001; } // if we have finished training on the most recently-read sentence // (or we are just starting training), read a new sentence; // truncate each sentence at `MAX_SENTENCE_LENGTH` words (sentences // longer than that will be broken up into smaller sentences) if (sentence_length == 0) { // iteratively read word and add to sentence while (1) { word = ReadWordIndex(fi, &eof); if (eof) break; // skip OOV if (word == -1) continue; word_count++; // if EOS, we're done reading this sentence if (word == 0) break; // The subsampling randomly discards frequent words while keeping the ranking same if (sample > 0) { // discard w.p. 1 - [ sqrt(t / p_{word}) + t / p_{word} ] // (t is the subsampling threshold `sample`, p_{word} is the // ML estimate of the probability of `word` in a unigram LM // (normalized frequency) // TODO: why is this not merely 1 - sqrt(t / p_{word}) as in // the paper? real ran = (sqrt(vocab[word].cn / (sample * train_words)) + 1) * (sample * train_words) / vocab[word].cn; next_random = next_random * (unsigned long long)25214903917 + 11; if (ran < (next_random & 0xFFFF) / (real)65536) continue; } sen[sentence_length] = word; sentence_length++; // truncate long sentences if (sentence_length >= MAX_SENTENCE_LENGTH) break; } // set output word position to first word in sentence sentence_position = 0; } // if we are at the end of this iteration (sweep over the data), // restart and decrement `local_iter` if (eof || (word_count > train_words / num_threads)) { word_count_actual += word_count - last_word_count; local_iter--; if (local_iter == 0) break; word_count = 0; last_word_count = 0; // signal to read new sentence sentence_length = 0; fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET); continue; } // get index of output word word = sen[sentence_position]; // skip OOV (TODO, checked OOV already when reading sentence?) if (word == -1) continue; // reset gradients to zero for (c = 0; c < layer1_size; c++) neu1[c] = 0; for (c = 0; c < layer1_size; c++) neu1e[c] = 0; // pick dynamic window offset (uniformly at random, between 0 // (inclusive) and max window size `window` (exclusive)) next_random = next_random * (unsigned long long)25214903917 + 11; b = next_random % window; // CBOW if (cbow) { // in -> hidden cw = 0; for (a = b; a < window * 2 + 1 - b; a++) if (a != window) { c = sentence_position - window + a; if (c < 0) continue; if (c >= sentence_length) continue; last_word = sen[c]; if (last_word == -1) continue; for (c = 0; c < layer1_size; c++) neu1[c] += syn0[c + last_word * layer1_size]; cw++; } if (cw) { for (c = 0; c < layer1_size; c++) neu1[c] /= cw; // CBOW HIERARCHICAL SOFTMAX if (hs) for (d = 0; d < vocab[word].codelen; d++) { f = 0; l2 = vocab[word].point[d] * layer1_size; // Propagate hidden -> output for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1[c + l2]; if (f <= -MAX_EXP) continue; else if (f >= MAX_EXP) continue; else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]; // 'g' is the gradient multiplied by the learning rate g = (1 - vocab[word].code[d] - f) * alpha; // Propagate errors output -> hidden for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[c + l2]; // Learn weights hidden -> output for (c = 0; c < layer1_size; c++) syn1[c + l2] += g * neu1[c]; } // CBOW NEGATIVE SAMPLING if (negative > 0) for (d = 0; d < negative + 1; d++) { if (d == 0) { target = word; label = 1; } else { next_random = next_random * (unsigned long long)25214903917 + 11; target = table[(next_random >> 16) % table_size]; if (target == 0) target = next_random % (vocab_size - 1) + 1; if (target == word) continue; label = 0; } l2 = target * layer1_size; f = 0; for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1neg[c + l2]; if (f > MAX_EXP) g = (label - 1) * alpha; else if (f < -MAX_EXP) g = (label - 0) * alpha; else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha; for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2]; for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * neu1[c]; } // hidden -> in for (a = b; a < window * 2 + 1 - b; a++) if (a != window) { c = sentence_position - window + a; if (c < 0) continue; if (c >= sentence_length) continue; last_word = sen[c]; if (last_word == -1) continue; for (c = 0; c < layer1_size; c++) syn0[c + last_word * layer1_size] += neu1e[c]; } } // SKIP-GRAM } else { // loop over offsets within dynamic window // (relative to max window size) for (a = b; a < window * 2 + 1 - b; a++) if (a != window) { // compute position in sentence of input word // (output word pos - max window size + rel offset) c = sentence_position - window + a; // skip if input word position OOB // (note this is our main constraint on word position w.r.t. sentence // bounds) if (c < 0) continue; if (c >= sentence_length) continue; // compute input word index last_word = sen[c]; // skip OOV (TODO checked already, should never fire) if (last_word == -1) continue; // compute input word row offset l1 = last_word * layer1_size; // initialize gradient for input word (work space) for (c = 0; c < layer1_size; c++) neu1e[c] = 0; // SKIP-GRAM HIERARCHICAL SOFTMAX if (hs) for (d = 0; d < vocab[word].codelen; d++) { f = 0; l2 = vocab[word].point[d] * layer1_size; // Propagate hidden -> output for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1[c + l2]; if (f <= -MAX_EXP) continue; else if (f >= MAX_EXP) continue; else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]; // 'g' is the gradient multiplied by the learning rate g = (1 - vocab[word].code[d] - f) * alpha; // Propagate errors output -> hidden for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[c + l2]; // Learn weights hidden -> output for (c = 0; c < layer1_size; c++) syn1[c + l2] += g * syn0[c + l1]; } // SKIP-GRAM NEGATIVE SAMPLING if (negative > 0) for (d = 0; d < negative + 1; d++) { if (d == 0) { // fetch output word target = word; label = 1; } else { // fetch negative-sampled word next_random = next_random * (unsigned long long)25214903917 + 11; target = table[(next_random >> 16) % table_size]; if (target == 0) target = next_random % (vocab_size - 1) + 1; if (target == word) continue; label = 0; } l2 = target * layer1_size; // output/neg-sample word row offset // compute f = < v_{w_I}', v_{w_O} > // (inner product for neg sample) f = 0; for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1neg[c + l2]; // compute gradient coeff g = alpha * (label - 1 / (e^-f + 1)) // (alpha is learning rate, label is 1 for output and 0 for neg) if (f > MAX_EXP) g = (label - 1) * alpha; else if (f < -MAX_EXP) g = (label - 0) * alpha; else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha; // contribute to gradient for input word for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2]; // perform gradient step for output/neg-sample word for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * syn0[c + l1]; } // now that we've taken gradient step for output and all neg sample // words, take gradient step for input word for (c = 0; c < layer1_size; c++) syn0[c + l1] += neu1e[c]; } } // update to next output word; if we are at end of sentence, signal // to read new sentence sentence_position++; if (sentence_position >= sentence_length) { sentence_length = 0; continue; } } // clean up fclose(fi); free(neu1); free(neu1e); pthread_exit(NULL); } // Train word embeddings on text in `train_file` using one or more // threads, either learning vocabulary from that training data (in a // separate pass over the data) or loading the vocabulary from a file // `read_vocab_file`. Optionally save vocabulary to a file // `save_vocab_file`; either save word embeddings to a file // `output_file` or, if `classes` is greater than zero, run k-means // clustering and save those clusters to `output_file`. // // If `output_file` is empty (first byte is null), do not train; this // can be used to learn the vocabulary only from a training text file. void TrainModel() { long a, b, c, d; // loop counters among other things FILE *fo; // output file pthread_t *pt = (pthread_t *)malloc(num_threads * sizeof(pthread_t)); printf("Starting training using file %s\n", train_file); // initialize learning rate starting_alpha = alpha; // read vocab from file or learn from training data if (read_vocab_file[0] != 0) ReadVocab(); else LearnVocabFromTrainFile(); // save vocab to file if (save_vocab_file[0] != 0) SaveVocab(); // if no `output_file` is specified, exit (do not train) if (output_file[0] == 0) return; // initialize network parameters InitNet(); // initialize negative sampling distribution if (negative > 0) InitUnigramTable(); start = clock(); for (a = 0; a < num_threads; a++) pthread_create(&pt[a], NULL, TrainModelThread, (void *)a); for (a = 0; a < num_threads; a++) pthread_join(pt[a], NULL); fo = fopen(output_file, "wb"); if (classes == 0) { // Save the word vectors fprintf(fo, "%lld %lld\n", vocab_size, layer1_size); for (a = 0; a < vocab_size; a++) { fprintf(fo, "%s ", vocab[a].word); if (binary) for (b = 0; b < layer1_size; b++) fwrite(&syn0[a * layer1_size + b], sizeof(real), 1, fo); else for (b = 0; b < layer1_size; b++) fprintf(fo, "%lf ", syn0[a * layer1_size + b]); fprintf(fo, "\n"); } } else { // Run K-means on the word vectors int clcn = classes, iter = 10, closeid; int *centcn = (int *)malloc(classes * sizeof(int)); int *cl = (int *)calloc(vocab_size, sizeof(int)); real closev, x; real *cent = (real *)calloc(classes * layer1_size, sizeof(real)); for (a = 0; a < vocab_size; a++) cl[a] = a % clcn; for (a = 0; a < iter; a++) { for (b = 0; b < clcn * layer1_size; b++) cent[b] = 0; for (b = 0; b < clcn; b++) centcn[b] = 1; for (c = 0; c < vocab_size; c++) { for (d = 0; d < layer1_size; d++) cent[layer1_size * cl[c] + d] += syn0[c * layer1_size + d]; centcn[cl[c]]++; } for (b = 0; b < clcn; b++) { closev = 0; for (c = 0; c < layer1_size; c++) { cent[layer1_size * b + c] /= centcn[b]; closev += cent[layer1_size * b + c] * cent[layer1_size * b + c]; } closev = sqrt(closev); for (c = 0; c < layer1_size; c++) cent[layer1_size * b + c] /= closev; } for (c = 0; c < vocab_size; c++) { closev = -10; closeid = 0; for (d = 0; d < clcn; d++) { x = 0; for (b = 0; b < layer1_size; b++) x += cent[layer1_size * d + b] * syn0[c * layer1_size + b]; if (x > closev) { closev = x; closeid = d; } } cl[c] = closeid; } } // Save the K-means classes for (a = 0; a < vocab_size; a++) fprintf(fo, "%s %d\n", vocab[a].word, cl[a]); free(centcn); free(cent); free(cl); } fclose(fo); } int ArgPos(char *str, int argc, char **argv) { int a; for (a = 1; a < argc; a++) if (!strcmp(str, argv[a])) { if (a == argc - 1) { printf("Argument missing for %s\n", str); exit(1); } return a; } return -1; } int main(int argc, char **argv) { int i; if (argc == 1) { printf("WORD VECTOR estimation toolkit v 0.1c\n\n"); printf("Options:\n"); printf("Parameters for training:\n"); printf("\t-train <file>\n"); printf("\t\tUse text data from <file> to train the model\n"); printf("\t-output <file>\n"); printf("\t\tUse <file> to save the resulting word vectors / word clusters\n"); printf("\t-size <int>\n"); printf("\t\tSet size of word vectors; default is 100\n"); printf("\t-window <int>\n"); printf("\t\tSet max skip length between words; default is 5\n"); printf("\t-sample <float>\n"); printf("\t\tSet threshold for occurrence of words. Those that appear with higher frequency in the training data\n"); printf("\t\twill be randomly down-sampled; default is 1e-3, useful range is (0, 1e-5)\n"); printf("\t-hs <int>\n"); printf("\t\tUse Hierarchical Softmax; default is 0 (not used)\n"); printf("\t-negative <int>\n"); printf("\t\tNumber of negative examples; default is 5, common values are 3 - 10 (0 = not used)\n"); printf("\t-threads <int>\n"); printf("\t\tUse <int> threads (default 12)\n"); printf("\t-iter <int>\n"); printf("\t\tRun more training iterations (default 5)\n"); printf("\t-min-count <int>\n"); printf("\t\tThis will discard words that appear less than <int> times; default is 5\n"); printf("\t-alpha <float>\n"); printf("\t\tSet the starting learning rate; default is 0.025 for skip-gram and 0.05 for CBOW\n"); printf("\t-classes <int>\n"); printf("\t\tOutput word classes rather than word vectors; default number of classes is 0 (vectors are written)\n"); printf("\t-debug <int>\n"); printf("\t\tSet the debug mode (default = 2 = more info during training)\n"); printf("\t-binary <int>\n"); printf("\t\tSave the resulting vectors in binary moded; default is 0 (off)\n"); printf("\t-save-vocab <file>\n"); printf("\t\tThe vocabulary will be saved to <file>\n"); printf("\t-read-vocab <file>\n"); printf("\t\tThe vocabulary will be read from <file>, not constructed from the training data\n"); printf("\t-cbow <int>\n"); printf("\t\tUse the continuous bag of words model; default is 1 (use 0 for skip-gram model)\n"); printf("\nExamples:\n"); printf("./word2vec -train data.txt -output vec.txt -size 200 -window 5 -sample 1e-4 -negative 5 -hs 0 -binary 0 -cbow 1 -iter 3\n\n"); return 0; } output_file[0] = 0; save_vocab_file[0] = 0; read_vocab_file[0] = 0; if ((i = ArgPos((char *)"-size", argc, argv)) > 0) layer1_size = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-train", argc, argv)) > 0) strcpy(train_file, argv[i + 1]); if ((i = ArgPos((char *)"-save-vocab", argc, argv)) > 0) strcpy(save_vocab_file, argv[i + 1]); if ((i = ArgPos((char *)"-read-vocab", argc, argv)) > 0) strcpy(read_vocab_file, argv[i + 1]); if ((i = ArgPos((char *)"-debug", argc, argv)) > 0) debug_mode = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-binary", argc, argv)) > 0) binary = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-cbow", argc, argv)) > 0) cbow = atoi(argv[i + 1]); if (cbow) alpha = 0.05; if ((i = ArgPos((char *)"-alpha", argc, argv)) > 0) alpha = atof(argv[i + 1]); if ((i = ArgPos((char *)"-output", argc, argv)) > 0) strcpy(output_file, argv[i + 1]); if ((i = ArgPos((char *)"-window", argc, argv)) > 0) window = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-sample", argc, argv)) > 0) sample = atof(argv[i + 1]); if ((i = ArgPos((char *)"-hs", argc, argv)) > 0) hs = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-negative", argc, argv)) > 0) negative = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-threads", argc, argv)) > 0) num_threads = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-iter", argc, argv)) > 0) iter = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-min-count", argc, argv)) > 0) min_count = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-classes", argc, argv)) > 0) classes = atoi(argv[i + 1]); vocab = (struct vocab_word *)calloc(vocab_max_size, sizeof(struct vocab_word)); vocab_hash = (int *)calloc(vocab_hash_size, sizeof(int)); // precompute e^x / (e^x + 1) for x in [-MAX_EXP, MAX_EXP) // TODO extra element (+ 1) seems unused? expTable = (real *)malloc((EXP_TABLE_SIZE + 1) * sizeof(real)); for (i = 0; i < EXP_TABLE_SIZE; i++) { // Precompute the exp() table expTable[i] = exp((i / (real)EXP_TABLE_SIZE * 2 - 1) * MAX_EXP); // Precompute f(x) = x / (x + 1) expTable[i] = expTable[i] / (expTable[i] + 1); } TrainModel(); return 0; }
40.740296
138
0.581815
8a31c31fbc6c1a1bae071ceb7e533a2a78f9668b
666
h
C
aws-cpp-sdk-ecs/include/aws/ecs/model/LogDriver.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-ecs/include/aws/ecs/model/LogDriver.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-ecs/include/aws/ecs/model/LogDriver.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/ecs/ECS_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace ECS { namespace Model { enum class LogDriver { NOT_SET, json_file, syslog, journald, gelf, fluentd, awslogs, splunk, awsfirelens }; namespace LogDriverMapper { AWS_ECS_API LogDriver GetLogDriverForName(const Aws::String& name); AWS_ECS_API Aws::String GetNameForLogDriver(LogDriver value); } // namespace LogDriverMapper } // namespace Model } // namespace ECS } // namespace Aws
17.526316
69
0.708709
c046206ffc65a1326a7e053e693fc459c04e7237
309
h
C
HPTextViewTapGestureRecognizerDemo/HPAppDelegate.h
mobilejazz/HPTextViewTapGestureRecognizer
ced9c4bbf3fc0a77048ebeaf0394081b4bd398a4
[ "Apache-2.0" ]
43
2015-01-11T18:35:45.000Z
2021-12-26T06:18:35.000Z
HPTextViewTapGestureRecognizerDemo/HPAppDelegate.h
mobilejazz/HPTextViewTapGestureRecognizer
ced9c4bbf3fc0a77048ebeaf0394081b4bd398a4
[ "Apache-2.0" ]
1
2020-09-21T09:06:02.000Z
2020-09-21T09:06:02.000Z
HPTextViewTapGestureRecognizerDemo/HPAppDelegate.h
mobilejazz/HPTextViewTapGestureRecognizer
ced9c4bbf3fc0a77048ebeaf0394081b4bd398a4
[ "Apache-2.0" ]
13
2015-01-21T06:03:46.000Z
2021-01-30T08:09:44.000Z
// // HPAppDelegate.h // HPTextViewTapGestureRecognizerDemo // // Created by Hermes Pique on 7/8/14. // Copyright (c) 2014 Hermes Pique. All rights reserved. // #import <UIKit/UIKit.h> @interface HPAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
19.3125
62
0.734628
077da3ddc7a96d96081e6b01b6fa53725cabf2a9
357
h
C
ios/Pods/Headers/Public/ABI38_0_0EXCamera/ABI38_0_0EXCameraManager.h
viktor-podzigun/expo
8fa0b005b391412fd4ee6e429646dd7a45892e71
[ "Apache-2.0", "MIT" ]
3
2020-09-06T17:32:53.000Z
2021-05-20T19:04:48.000Z
ios/Pods/Headers/Public/ABI38_0_0EXCamera/ABI38_0_0EXCameraManager.h
viktor-podzigun/expo
8fa0b005b391412fd4ee6e429646dd7a45892e71
[ "Apache-2.0", "MIT" ]
2
2021-09-02T20:34:01.000Z
2021-12-09T04:01:45.000Z
ios/Pods/Headers/Public/ABI38_0_0EXCamera/ABI38_0_0EXCameraManager.h
viktor-podzigun/expo
8fa0b005b391412fd4ee6e429646dd7a45892e71
[ "Apache-2.0", "MIT" ]
1
2021-11-04T12:32:35.000Z
2021-11-04T12:32:35.000Z
#import <AVFoundation/AVFoundation.h> #import <ABI38_0_0UMCore/ABI38_0_0UMViewManager.h> #import <ABI38_0_0UMCore/ABI38_0_0UMExportedModule.h> #import <ABI38_0_0UMCore/ABI38_0_0UMModuleRegistryConsumer.h> #import <ABI38_0_0EXCamera/ABI38_0_0EXCamera.h> @interface ABI38_0_0EXCameraManager : ABI38_0_0UMViewManager <ABI38_0_0UMModuleRegistryConsumer> @end
35.7
96
0.865546
6dad7ee3b22cc25e6509939aa98f16fce942b132
1,734
c
C
kubernetes/unit-test/test_v1_pod_readiness_gate.c
minerba/c
8eb6593e55d0e5d57a2dd3153c15c9645de677bc
[ "Apache-2.0" ]
69
2020-03-17T13:47:05.000Z
2022-03-30T08:25:05.000Z
kubernetes/unit-test/test_v1_pod_readiness_gate.c
minerba/c
8eb6593e55d0e5d57a2dd3153c15c9645de677bc
[ "Apache-2.0" ]
115
2020-03-17T14:53:19.000Z
2022-03-31T11:31:30.000Z
kubernetes/unit-test/test_v1_pod_readiness_gate.c
minerba/c
8eb6593e55d0e5d57a2dd3153c15c9645de677bc
[ "Apache-2.0" ]
28
2020-03-17T13:42:21.000Z
2022-03-19T23:37:16.000Z
#ifndef v1_pod_readiness_gate_TEST #define v1_pod_readiness_gate_TEST // the following is to include only the main from the first c file #ifndef TEST_MAIN #define TEST_MAIN #define v1_pod_readiness_gate_MAIN #endif // TEST_MAIN #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdbool.h> #include "../external/cJSON.h" #include "../model/v1_pod_readiness_gate.h" v1_pod_readiness_gate_t* instantiate_v1_pod_readiness_gate(int include_optional); v1_pod_readiness_gate_t* instantiate_v1_pod_readiness_gate(int include_optional) { v1_pod_readiness_gate_t* v1_pod_readiness_gate = NULL; if (include_optional) { v1_pod_readiness_gate = v1_pod_readiness_gate_create( "0" ); } else { v1_pod_readiness_gate = v1_pod_readiness_gate_create( "0" ); } return v1_pod_readiness_gate; } #ifdef v1_pod_readiness_gate_MAIN void test_v1_pod_readiness_gate(int include_optional) { v1_pod_readiness_gate_t* v1_pod_readiness_gate_1 = instantiate_v1_pod_readiness_gate(include_optional); cJSON* jsonv1_pod_readiness_gate_1 = v1_pod_readiness_gate_convertToJSON(v1_pod_readiness_gate_1); printf("v1_pod_readiness_gate :\n%s\n", cJSON_Print(jsonv1_pod_readiness_gate_1)); v1_pod_readiness_gate_t* v1_pod_readiness_gate_2 = v1_pod_readiness_gate_parseFromJSON(jsonv1_pod_readiness_gate_1); cJSON* jsonv1_pod_readiness_gate_2 = v1_pod_readiness_gate_convertToJSON(v1_pod_readiness_gate_2); printf("repeating v1_pod_readiness_gate:\n%s\n", cJSON_Print(jsonv1_pod_readiness_gate_2)); } int main() { test_v1_pod_readiness_gate(1); test_v1_pod_readiness_gate(0); printf("Hello world \n"); return 0; } #endif // v1_pod_readiness_gate_MAIN #endif // v1_pod_readiness_gate_TEST
29.389831
117
0.809689
ef4b12c2280215aae46a85fd0c704cd922e1ae80
4,654
c
C
lib/common/uds_connect/uds_connect.c
CloudNativeDataPlane/cndp
cc83410b525bd3aacaf72ad12f8d4f4af5b28727
[ "BSD-3-Clause" ]
null
null
null
lib/common/uds_connect/uds_connect.c
CloudNativeDataPlane/cndp
cc83410b525bd3aacaf72ad12f8d4f4af5b28727
[ "BSD-3-Clause" ]
null
null
null
lib/common/uds_connect/uds_connect.c
CloudNativeDataPlane/cndp
cc83410b525bd3aacaf72ad12f8d4f4af5b28727
[ "BSD-3-Clause" ]
null
null
null
/* SPDX-License-Identifier: BSD-3-Clause * Copyright (c) 2021-2022 Intel Corporation */ #include <stdio.h> // for NULL #include <unistd.h> // for gethostname #include <sys/socket.h> // for send, CMSG_DATA #include <bsd/string.h> // for strlcat, strlcpy #include <sched.h> // for sched_yield #include "uds_connect.h" #define MAX_NUM_TRIES 40000 #define HOST_NAME_LEN 32 static int fin_ack(uds_client_t *c, const char *cmd __cne_unused, const char *params __cne_unused) { uds_info_t *uds = c->info; uds->xsk_uds_state = UDS_FIN; return UDS_NO_OUTPUT; } static int set_host_nak(uds_client_t *c, const char *cmd __cne_unused, const char *params __cne_unused) { uds_info_t *uds = c->info; uds->xsk_uds_state = UDS_HOST_NAK; return UDS_NO_OUTPUT; } static int set_host_ok(uds_client_t *c, const char *cmd __cne_unused, const char *params __cne_unused) { uds_info_t *uds = c->info; uds->xsk_uds_state = UDS_HOST_OK; return UDS_NO_OUTPUT; } static int fd_ack(uds_client_t *c, const char *cmd __cne_unused, const char *params __cne_unused) { if (!c || !c->cmsg) goto err; uds_info_t *uds = c->info; if (!uds) goto err; uds->xsk_map_fd = *(int *)CMSG_DATA(c->cmsg); uds->xsk_uds_state = UDS_GOT_FD; err: return UDS_NO_OUTPUT; } static int fd_nak(uds_client_t *c, const char *cmd __cne_unused, const char *params __cne_unused) { uds_info_t *uds = c->info; uds->xsk_uds_state = UDS_FD_NAK; return UDS_NO_OUTPUT; } static int config_busy_poll_ack(uds_client_t *c, const char *cmd __cne_unused, const char *params __cne_unused) { uds_info_t *uds = c->info; uds->xsk_uds_state = UDS_BUSY_POLL_ACK; return UDS_NO_OUTPUT; } static int config_busy_poll_nak(uds_client_t *c, const char *cmd __cne_unused, const char *params __cne_unused) { uds_info_t *uds = c->info; uds->xsk_uds_state = UDS_BUSY_POLL_NAK; return UDS_NO_OUTPUT; } uds_info_t * udsc_handshake(const char *uds_name) { const char *err_msg = NULL; char connect_msg[UDS_MAX_CMD_LEN] = {0}; char hostname[HOST_NAME_LEN] = {0}; int len = 0; int num_of_tries = 0; uds_info_t *info = NULL; const uds_group_t *group = NULL; /* NOTE: currently uds_connect creates an async client * to register protocol commands with and process information * exchanged on the UDS. */ info = uds_connect(uds_name, &err_msg, NULL); if (!info) return NULL; /* get root group */ group = uds_get_group_by_name(info, NULL); if (group == NULL) goto err; info->xsk_uds_state = UDS_CONNECTED; if (uds_register(group, UDS_HOST_OK_MSG, set_host_ok) < 0) goto err; if (uds_register(group, UDS_FD_ACK_MSG, fd_ack) < 0) goto err; if (uds_register(group, UDS_FD_NAK_MSG, fd_nak) < 0) goto err; if (uds_register(group, UDS_FIN_ACK_MSG, fin_ack) < 0) goto err; if (uds_register(group, UDS_HOST_NAK_MSG, set_host_nak) < 0) goto err; if (uds_register(group, UDS_CFG_BUSY_POLL_ACK, config_busy_poll_ack) < 0) goto err; if (uds_register(group, UDS_CFG_BUSY_POLL_NAK, config_busy_poll_nak) < 0) goto err; /* Sending a request of the form "/connect,$hostname" to the UDS * If hostname is correct, /host_ok will be sent by the UDS * and if incorrect, /host_nak is sent by the UDS. */ strlcpy(connect_msg, UDS_CONNECT_MSG, sizeof(connect_msg)); if (gethostname(hostname, sizeof(hostname)) < 0) goto err; strlcat(connect_msg, ",", sizeof(connect_msg)); len = strlcat(connect_msg, hostname, sizeof(connect_msg)); if (send(info->sock, connect_msg, len, 0) <= 0) goto err; do { num_of_tries++; sched_yield(); } while (info->xsk_uds_state != UDS_HOST_OK && num_of_tries < MAX_NUM_TRIES); if (info->xsk_uds_state == UDS_HOST_OK) return info; else if (num_of_tries == MAX_NUM_TRIES) info->xsk_uds_state = UDS_HOST_ERR; err: uds_destroy(info); uds_destroy_group(group); return NULL; } int udsc_close(uds_info_t *info) { int num_of_tries = 0; if (!info) return -1; if (send(info->sock, UDS_FIN_MSG, sizeof(UDS_FIN_MSG) - 1, 0) <= 0) return -1; do { num_of_tries++; sched_yield(); } while (info->xsk_uds_state != UDS_FIN && num_of_tries < MAX_NUM_TRIES); if (num_of_tries == MAX_NUM_TRIES) return -1; return 0; }
24.494737
100
0.645681
8fc4543b6a5f4864d5d39a298aff36cf04df6c37
680
h
C
include/user_sonos_discovery.h
dkonigsberg/wallbox-code
2098ae5c59a51ae26c64a95a7f47df76fa885cfd
[ "BSD-3-Clause" ]
2
2018-01-27T06:26:46.000Z
2019-04-11T18:28:57.000Z
include/user_sonos_discovery.h
dkonigsberg/wallbox-code
2098ae5c59a51ae26c64a95a7f47df76fa885cfd
[ "BSD-3-Clause" ]
null
null
null
include/user_sonos_discovery.h
dkonigsberg/wallbox-code
2098ae5c59a51ae26c64a95a7f47df76fa885cfd
[ "BSD-3-Clause" ]
null
null
null
#ifndef USER_SONOS_DISCOVERY_H #define USER_SONOS_DISCOVERY_H #include "user_sonos_client.h" typedef void (* user_sonos_discovery_callback_t)( const sonos_device *device, void *user_data); void user_sonos_discovery_init(void); void user_sonos_discovery_start(void); void user_sonos_discovery_abort(void); void user_sonos_discovery_set_callback(user_sonos_discovery_callback_t callback, void *user_data); int user_sonos_discovery_get_device_by_uuid(sonos_device *device, const char *uuid); int user_sonos_discovery_get_device_by_name(sonos_device *device, const char *zone_name); bool user_sonos_discovery_json_devices(char **json_data); #endif /* USER_SONOS_DISCOVERY_H */
40
98
0.848529
8929205369babf6f156d04284119934a7ac77ee5
88
h
C
ios/versioned-react-native/ABI39_0_0/Expo/ExpoKit/Core/Api/Reanimated/Nodes/ABI39_0_0READebugNode.h
PhuocNgo1898/expo
341d1714a7e1adda86008a4061e351c7614636b9
[ "Apache-2.0", "MIT" ]
3
2020-09-06T17:32:53.000Z
2021-05-20T19:04:48.000Z
ios/versioned-react-native/ABI39_0_0/Expo/ExpoKit/Core/Api/Reanimated/Nodes/ABI39_0_0READebugNode.h
PhuocNgo1898/expo
341d1714a7e1adda86008a4061e351c7614636b9
[ "Apache-2.0", "MIT" ]
2
2021-09-02T20:34:01.000Z
2021-12-09T04:01:45.000Z
ios/versioned-react-native/ABI39_0_0/Expo/ExpoKit/Core/Api/Reanimated/Nodes/ABI39_0_0READebugNode.h
PhuocNgo1898/expo
341d1714a7e1adda86008a4061e351c7614636b9
[ "Apache-2.0", "MIT" ]
1
2021-11-24T08:07:42.000Z
2021-11-24T08:07:42.000Z
#import "ABI39_0_0REANode.h" @interface ABI39_0_0READebugNode : ABI39_0_0REANode @end
14.666667
51
0.818182
a6b437986849bb0044eec1a3759c855b02c551a8
2,640
h
C
registration/include/dip/registration/icp.h
gregorpm/Depth-Image-Processing
3a23f393aa3460816e81419a677b0c5fbbfc30c0
[ "BSD-3-Clause" ]
51
2015-01-31T03:30:58.000Z
2021-11-10T11:47:59.000Z
registration/include/dip/registration/icp.h
paochiang/dip1
890363305c67845a86ca586c0109e36ef543170f
[ "BSD-3-Clause" ]
null
null
null
registration/include/dip/registration/icp.h
paochiang/dip1
890363305c67845a86ca586c0109e36ef543170f
[ "BSD-3-Clause" ]
32
2015-02-05T00:24:21.000Z
2021-06-28T09:10:17.000Z
/* Copyright (c) 2013-2015, Gregory P. Meyer University of Illinois Board of Trustees 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 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 DIP_REGISTRATION_ICP_H #define DIP_REGISTRATION_ICP_H #include <Eigen/Dense> #include <dip/common/types.h> #include <dip/common/macros.h> namespace dip { class ICP { public: ICP(); ~ICP(); int Run(int max_iterations, int min_correspondences_begin, int min_correspondences_end, float distance_threshold_begin, float distance_threshold_end, float normal_threshold_begin, float normal_threshold_end, float max_rotation, float max_translation, float fx, float fy, float cx, float cy, int src_width, int src_height, int dst_width, int dst_height, Vertices src_vertices, Normals src_normals, Vertices dst_vertices, Normals dst_normals, const Eigen::Matrix4f &previous_transformation, Eigen::Matrix4f &transformation); private: Eigen::Matrix4f ConstructTransform(Eigen::VectorXf &x); float *buffer_[29]; int bytes_; DISALLOW_COPY_AND_ASSIGN(ICP); }; } // namespace dip #endif // DIP_REGISTRATION_ICP_H
38.26087
79
0.751894
ed98a0e9bda7f8f47da6616582216f8140f060b7
1,741
c
C
src/sem_returns.c
miffi/bcc2
d37691e0f05600be068911823dba270ce6f92074
[ "MIT" ]
4
2021-05-10T22:03:13.000Z
2021-05-14T22:19:59.000Z
src/sem_returns.c
miffi/bcc2
d37691e0f05600be068911823dba270ce6f92074
[ "MIT" ]
4
2021-05-16T18:57:09.000Z
2021-05-19T17:03:43.000Z
src/sem_returns.c
miffi/bcc2
d37691e0f05600be068911823dba270ce6f92074
[ "MIT" ]
2
2021-05-07T19:18:18.000Z
2021-05-14T04:23:51.000Z
#include "semantics.h" #include "error.h" enum { RETURN_RIGHT, RETURN_NEVER, RETURN_WRONG, }; /* first_wrong_stmt, and first_wrong_type are set if the function returns * incorrectly */ /* this method will make it easier to identify incorrect returns and properly * fill in error info on the AST later */ static int check_fn(AST *ast, Function *fn, Stmt **first_wrong_stmt, Type **first_wrong_type) { for (size_t i = 0; i < fn->body.stmts.items; i++) { Stmt *stmt = vector_idx(&fn->body.stmts, i); switch (stmt->t) { case STMT_LET: case STMT_EXPR: break; case STMT_RETURN: if (stmt->data.ret == NULL) { if (fn->ret_type->t == TYPE_VOID) { return RETURN_RIGHT; } else { return RETURN_WRONG; } } if (coerce_type(BINOP_ASSIGN, &fn->ret_type, &stmt->data.ret->type, &ast->pool) != NULL) { return RETURN_RIGHT; } else { *first_wrong_stmt = stmt; *first_wrong_type = stmt->data.ret->type; return RETURN_WRONG; } default: log_internal_err("invalid stmt type %d", stmt->t); } } return (fn->ret_type->t == TYPE_VOID) ? RETURN_RIGHT : RETURN_NEVER; } void check_returns(AST *ast) { Stmt *wrong_stmt; Type *wrong_type; for (size_t i = 0; i < ast->fns.items; i++) { Function *fn = vector_idx(&ast->fns, i); switch (check_fn(ast, fn, &wrong_stmt, &wrong_type)) { case RETURN_RIGHT: break; case RETURN_NEVER: log_never_returns(fn->pos); break; case RETURN_WRONG: log_incorrect_return(wrong_stmt->pos, wrong_type, fn->ret_type); break; } } }
26.784615
77
0.588742
54b96c80310dcc8bcc154c9d07e12bf78c0bbf5e
138
h
C
include/Screen.h
jamiesyme/Pong
d1d93543f52b8abff7fc3378065304a04149036a
[ "Unlicense" ]
null
null
null
include/Screen.h
jamiesyme/Pong
d1d93543f52b8abff7fc3378065304a04149036a
[ "Unlicense" ]
null
null
null
include/Screen.h
jamiesyme/Pong
d1d93543f52b8abff7fc3378065304a04149036a
[ "Unlicense" ]
null
null
null
#pragma once class Screen { public: Screen() {} virtual ~Screen() {} virtual void Tick() {} virtual void Draw() {} private: };
9.2
23
0.601449
60b4fb10bcc4c87c7e416d21c838aff320732c5f
137
h
C
mqtt/raw_connect.h
hias222/serial
4b638e4875d8ff7b3aef3c09a80f0142c4dcbf2c
[ "MIT" ]
null
null
null
mqtt/raw_connect.h
hias222/serial
4b638e4875d8ff7b3aef3c09a80f0142c4dcbf2c
[ "MIT" ]
null
null
null
mqtt/raw_connect.h
hias222/serial
4b638e4875d8ff7b3aef3c09a80f0142c4dcbf2c
[ "MIT" ]
null
null
null
#ifndef TEMPERATURE_CONVERSION_H #define TEMPERATURE_CONVERSION_H #include <cstring> #include <mosquitto.h> int raw_connect(); #endif
13.7
32
0.80292
c251dfedd419160b91794ef4d394aecf8dceec4b
1,811
h
C
Assets/header/CQQContactMgr.h
NuolanNuolan/IPAPatch-master
0f1821950c9b26d504c73681673901b8efa1e44c
[ "MIT" ]
5
2017-09-21T06:56:18.000Z
2021-01-02T22:15:23.000Z
Assets/header/CQQContactMgr.h
NuolanNuolan/IPAPatch-master
0f1821950c9b26d504c73681673901b8efa1e44c
[ "MIT" ]
null
null
null
Assets/header/CQQContactMgr.h
NuolanNuolan/IPAPatch-master
0f1821950c9b26d504c73681673901b8efa1e44c
[ "MIT" ]
5
2017-11-14T03:18:42.000Z
2019-12-30T03:09:35.000Z
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Mar 29 2017 23:22:24). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import "MMService.h" #import "IContactProfileMgrExt-Protocol.h" #import "MMService-Protocol.h" #import "MessageObserverDelegate-Protocol.h" @class CQQContactDB, NSMutableDictionary, NSString; @interface CQQContactMgr : MMService <MMService, MessageObserverDelegate, IContactProfileMgrExt> { CQQContactDB *m_oDB; NSMutableDictionary *m_dicContacts; _Bool m_bDataNeedReload; } - (void).cxx_destruct; - (void)MessageReturn:(unsigned int)arg1 MessageInfo:(id)arg2 Event:(unsigned int)arg3; - (void)DidGetQQContactProfile:(id)arg1 withImage:(_Bool)arg2; - (void)onServiceTerminate; - (void)onServiceEnterBackground; - (void)saveContactImageStatus:(id)arg1 Status:(id)arg2 Image:(id)arg3; - (_Bool)syncAllQQContact; - (_Bool)syncContacts:(id)arg1; - (_Bool)syncContact:(id)arg1; - (_Bool)RemoveContactFromChatList:(id)arg1; - (_Bool)setContact:(id)arg1 chatState:(unsigned int)arg2; - (_Bool)addContact:(id)arg1; - (id)getContactByName:(id)arg1; - (id)getAllContactInChatList; - (void)initDB:(id)arg1 lock:(id)arg2; - (_Bool)autoReload; - (void)dealloc; - (id)init; - (void)initTestData; - (void)initTestDataItem:(unsigned int)arg1 name:(id)arg2; - (_Bool)onGetQQContact:(id)arg1 withImage:(_Bool)arg2; - (_Bool)onSyncQQContact:(id)arg1; - (void)internalDeleteContact:(id)arg1; - (void)internalModifyContact:(id)arg1; - (void)internalAddContact:(id)arg1; - (void)removeListen; - (void)initListen; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
31.224138
96
0.756488
fd130b3079eafd3b1065b3f2a3595c3293897e78
1,022
h
C
spirit_simulator/gazebo_scripts/include/estimator_plugin.h
robomechanics/spirit-software
b0a3d8defd3abe06406de6573212bab4a2eb769a
[ "MIT" ]
10
2020-12-17T16:58:55.000Z
2021-11-12T09:31:30.000Z
spirit_simulator/gazebo_scripts/include/estimator_plugin.h
robomechanics/spirit-software
b0a3d8defd3abe06406de6573212bab4a2eb769a
[ "MIT" ]
101
2020-09-02T00:36:25.000Z
2021-12-04T23:40:32.000Z
spirit_simulator/gazebo_scripts/include/estimator_plugin.h
robomechanics/spirit-software
b0a3d8defd3abe06406de6573212bab4a2eb769a
[ "MIT" ]
null
null
null
#ifndef GAZEBO_SPIRIT_ESTIMATOR_PLUGIN #define GAZEBO_SPIRIT_ESTIMATOR_PLUGIN #include <functional> #include <ros/ros.h> #include <gazebo/gazebo.hh> #include <gazebo/physics/physics.hh> #include <gazebo/common/common.hh> #include <gazebo/common/Plugin.hh> #include <gazebo/common/UpdateInfo.hh> #include <ignition/math/Vector3.hh> #include <spirit_msgs/RobotState.h> #include <spirit_utils/math_utils.h> #include <spirit_utils/ros_utils.h> namespace gazebo { class SpiritEstimatorGroundTruth : public ModelPlugin { /// \brief Constructor. public: SpiritEstimatorGroundTruth(); /// \brief Destructor. ~SpiritEstimatorGroundTruth(); void Load(physics::ModelPtr _parent, sdf::ElementPtr _sdf); void OnUpdate(); private: double update_rate_; common::Time last_time_; ros::Publisher ground_truth_state_pub_; physics::ModelPtr model_; event::ConnectionPtr updateConnection_; }; GZ_REGISTER_MODEL_PLUGIN(SpiritEstimatorGroundTruth) } #endif
26.205128
65
0.739726
e6d803b0a595317dda06e793fda722a502956b1e
3,294
h
C
morpho5/datastructures/varray.h
mattsep/morpho
50bb935653c0675b81e9f2d78573cf117971a147
[ "MIT" ]
10
2021-09-18T14:44:14.000Z
2022-03-26T11:41:50.000Z
morpho5/datastructures/varray.h
mattsep/morpho
50bb935653c0675b81e9f2d78573cf117971a147
[ "MIT" ]
79
2021-10-05T17:33:19.000Z
2022-03-31T16:06:10.000Z
morpho5/datastructures/varray.h
mattsep/morpho
50bb935653c0675b81e9f2d78573cf117971a147
[ "MIT" ]
2
2021-10-05T16:56:16.000Z
2021-10-31T19:55:27.000Z
/** @file varray.h * @author T J Atherton * * @brief Dynamically resizing array (varray) data structure */ #ifndef varray_h #define varray_h #include <stdlib.h> #include <stddef.h> #include <stdbool.h> #include "memory.h" /** * Variable array macros */ /** @brief Creates a generic varray containing a specified type. * * @details Varrays only differ by their contents, and so we use macros to * conveniently define types and functions. * To use these: * First, call DECLARE_VARRAY(NAME,TYPE) in your .h file with a selected * name for your varray and the type of thing you want to store in it. * This will define: * 1. A type called varray_NAME (where NAME is the name you gave). * 2. Functions * varray_NAMEinit(v) - Initializes the varray * varray_NAMEadd(v, data[], count) - Adds elements to the varray * varray_NAMEwrite(v, data) - Writes a single element to the varray, returning the index * varray_NAMEclear(v) - Clears the varray, freeing memory * Then, call DEFINE_VARRAY(NAME,TYPE) in your .c file to define the appropriate functions */ #define DECLARE_VARRAY(name, type) \ typedef struct { \ unsigned int count; \ unsigned int capacity; \ type *data; \ } varray_##name; \ \ void varray_##name##init(varray_##name *v); \ bool varray_##name##add(varray_##name *v, type *data, int count); \ bool varray_##name##resize(varray_##name *v, int count); \ int varray_##name##write(varray_##name *v, type data); \ void varray_##name##clear(varray_##name *v); #define DEFINE_VARRAY(name, type) \ void varray_##name##init(varray_##name *v) { \ v->count = 0; \ v->capacity=0; \ v->data=NULL; \ } \ \ bool varray_##name##add(varray_##name *v, type *data, int count) { \ if (v->capacity<v->count + count) { \ unsigned int capacity = varray_powerof2ceiling(v->count + count); \ v->data = (type *) morpho_allocate(v->data, v->capacity * sizeof(type), \ capacity * sizeof(type)); \ v->capacity = capacity; \ }; \ \ if (v->data && data) for (unsigned int i = 0; i < count; i++) { \ v->data[v->count++] = data[i]; \ } \ return (v->data!=NULL); \ } \ \ bool varray_##name##resize(varray_##name *v, int count) { \ if (v->capacity<v->count + count) { \ unsigned int capacity = varray_powerof2ceiling(v->count + count); \ v->data = (type *) morpho_allocate(v->data, v->capacity * sizeof(type), \ capacity * sizeof(type)); \ v->capacity = capacity; \ }; \ return (v->data!=NULL); \ } \ \ int varray_##name##write(varray_##name *v, type data) { \ varray_##name##add(v, &data, 1); \ return v->count-1; \ } \ \ void varray_##name##clear(varray_##name *v) { \ morpho_allocate(v->data, 0, 0); \ varray_##name##init(v); \ } /* ********************************************************************** * Common varray types * ********************************************************************** */ DECLARE_VARRAY(char, char); DECLARE_VARRAY(int, int); DECLARE_VARRAY(double, double); DECLARE_VARRAY(ptrdiff, ptrdiff_t); unsigned int varray_powerof2ceiling(unsigned int n); #endif /* varray_h */
32.613861
100
0.589557
7436cd74f05b1f8c743cdeac3ce51979b86103ea
958
h
C
TestProject/Source/TestProject/Items/Explosive.h
1Gokul/TestProject
e732c65440537252bd02b9b527ac9a084f4ce44c
[ "MIT" ]
3
2020-07-06T19:46:42.000Z
2021-12-06T11:23:17.000Z
TestProject/Source/TestProject/Items/Explosive.h
1Gokul/TestProject
e732c65440537252bd02b9b527ac9a084f4ce44c
[ "MIT" ]
null
null
null
TestProject/Source/TestProject/Items/Explosive.h
1Gokul/TestProject
e732c65440537252bd02b9b527ac9a084f4ce44c
[ "MIT" ]
1
2021-12-06T11:23:48.000Z
2021-12-06T11:23:48.000Z
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Item.h" #include "Explosive.generated.h" /** * */ UCLASS() class TESTPROJECT_API AExplosive : public AItem { GENERATED_BODY() public: AExplosive(); /**Called if an Overlap Event starts. */ void OnOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) override; /** Called when the Overlap Event ends */ void OnOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex) override; protected: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Damage") float Damage; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Damage") TSubclassOf<UDamageType> DamageTypeClass; };
25.891892
114
0.749478
de87110bbd04abd461eba2660c55dd8c00e687c4
1,440
h
C
RGBController.h
ljw980105/RGBFanControllerArduino
f1426f1593b7316fa2d2ad233388048c62f059e5
[ "MIT" ]
null
null
null
RGBController.h
ljw980105/RGBFanControllerArduino
f1426f1593b7316fa2d2ad233388048c62f059e5
[ "MIT" ]
null
null
null
RGBController.h
ljw980105/RGBFanControllerArduino
f1426f1593b7316fa2d2ad233388048c62f059e5
[ "MIT" ]
null
null
null
// // Created by Li on 1/12/2020. // #ifndef RGBFANCONTROLLERARDUINO_RGBCONTROLLER_H #define RGBFANCONTROLLERARDUINO_RGBCONTROLLER_H #include <Arduino.h> #include <EEPROM.h> typedef enum { CONTROL_MODE_STATIC, CONTROL_MODE_RAINBOW } CONTROL_MODE; typedef struct { unsigned int r; unsigned int g; unsigned int b; } RgbColor; typedef struct { unsigned int h; unsigned int s; unsigned char v; } HsvColor; typedef struct { double h; // angle in degrees double s; // a fraction between 0 and 1 double v; // a fraction between 0 and 1 } UnitHsv; typedef struct { double r; // a fraction between 0 and 1 double g; // a fraction between 0 and 1 double b; // a fraction between 0 and 1 } UnitRGB; class RGBController { public: RGBController(int redPin, int greenPin, int bluePin); void setColor(int r, int g, int b); void saveColor(int r, int g, int b); void setSavedColor(); void setRGBColor(RgbColor rgb); void setHSVColor(int h, int s, int v); RgbColor HsvToRgb(HsvColor hsv); HsvColor RgbToHsv(RgbColor rgb); private: int redPin; int greenPin; int bluePin; static HsvColor unitHsvToHSv(UnitHsv hsv); static UnitHsv hsvToUnitHsv(HsvColor hsv); static RgbColor unitRGBtoRGb(UnitRGB rgb); static UnitRGB rgbToUnitRgb(RgbColor rgb); }; #endif //RGBFANCONTROLLERARDUINO_RGBCONTROLLER_H
22.5
57
0.681944
25f7c2df36cb6b18f02efbc3e6085ce95d4b2941
1,436
h
C
engine/audio/audioStreamSource.h
ClayHanson/B4v21-Public-Repo
c812aa7bf2ecb267e02969c85f0c9c2a29be0d28
[ "MIT" ]
1
2020-08-18T19:45:34.000Z
2020-08-18T19:45:34.000Z
engine/audio/audioStreamSource.h
ClayHanson/B4v21-Launcher-Public-Repo
c812aa7bf2ecb267e02969c85f0c9c2a29be0d28
[ "MIT" ]
null
null
null
engine/audio/audioStreamSource.h
ClayHanson/B4v21-Launcher-Public-Repo
c812aa7bf2ecb267e02969c85f0c9c2a29be0d28
[ "MIT" ]
null
null
null
//-------------------------------------------- // audioStreamSource.h // header for streaming audio source // // Kurtis Seebaldt //-------------------------------------------- #ifndef _AUDIOSTREAMSOURCE_H_ #define _AUDIOSTREAMSOURCE_H_ #ifndef _PLATFORM_H_ #include "platform/platform.h" #endif #ifndef _PLATFORMAUDIO_H_ #include "platform/platformAudio.h" #endif #ifndef _PLATFORMAL_H_ #include "platform/platformAL.h" #endif #ifndef _AUDIOBUFFER_H_ #include "audio/audioBuffer.h" #endif #ifndef _RESMANAGER_H_ #include "core/resManager.h" #endif #define NUMBUFFERS 16 class AudioStreamSource { public: //need this because subclasses are deleted through base pointer virtual ~AudioStreamSource() {} virtual bool initStream() = 0; virtual bool updateBuffers() = 0; virtual void freeStream() = 0; virtual F32 getElapsedTime() = 0; virtual F32 getTotalTime() = 0; //void clear(); AUDIOHANDLE mHandle; ALuint mSource; Audio::Description mDescription; AudioSampleEnvironment *mEnvironment; Point3F mPosition; Point3F mDirection; F32 mPitch; F32 mScore; U32 mCullTime; bool bFinishedPlaying; bool bIsValid; #ifdef TORQUE_OS_LINUX void checkPosition(); #endif protected: const char* mFilename; }; #endif // _AUDIOSTREAMSOURCE_H_
22.092308
71
0.626045
1c53b3e84e9ba76632cb4605e0062f6b821a1c9b
4,704
c
C
CoX/CoX_Peripheral/CoX_Peripheral_NUC1xx/acmp/test/suite2/src/xacmptest.c
coocox/cox
c94e4a65417301b76a02108be5a9eeea3663ef70
[ "BSD-3-Clause" ]
58
2015-01-23T11:12:14.000Z
2022-03-23T01:52:14.000Z
CoX/CoX_Peripheral/CoX_Peripheral_NUC1xx/acmp/test/suite2/src/xacmptest.c
eventus17/cox
c94e4a65417301b76a02108be5a9eeea3663ef70
[ "BSD-3-Clause" ]
1
2017-12-30T05:40:50.000Z
2017-12-30T05:40:50.000Z
CoX/CoX_Peripheral/CoX_Peripheral_NUC1xx/acmp/test/suite2/src/xacmptest.c
eventus17/cox
c94e4a65417301b76a02108be5a9eeea3663ef70
[ "BSD-3-Clause" ]
68
2015-01-22T11:03:59.000Z
2022-01-29T14:18:40.000Z
//***************************************************************************** // //! @page xacmp_testcase xacmp register test //! //! File: @ref xacmptest.c //! //! <h2>Description</h2> //! This module implements the test sequence for the xacmp sub component.<br><br> //! - \p Board: NUC140 <br><br> //! - \p Last-Time(about): 0.5s <br><br> //! - \p Phenomenon: Success or failure information will be printed on the UART. <br><br> //! . //! //! <h2>Preconditions</h2> //! The module requires the following options:<br><br> //! - \p Option-define: //! <br>(1)None.<br><br> //! - \p Option-hardware: //! <br>(1)Connect an USB cable to the development board.<br><br> //! - \p Option-OtherModule: //! <br>Connect an COM cable to the development board.<br> //! . //! In case some of the required options are not enabled then some or all tests //! may be skipped or result FAILED.<br> //! //! <h2>Test Cases</h2> //! The module contain those sub tests:<br><br> //! - \subpage test_xacmp_register //! . //! \file xacmptest.c //! \brief xacmp test source file //! \brief xacmp test header file <br> // //***************************************************************************** #include "test.h" #include "xhw_acmp.h" #include "xacmp.h" //***************************************************************************** // //!\page test_xacmp_register test_xacmp_register //! //!<h2>Description</h2> //!Test xacmp register. <br> //! // //***************************************************************************** //***************************************************************************** // //! \brief Comparator 0 Interrupt Handler. //! //! If users want to user the ACMP Interrupt Callback feature, Users should //! promise that the ACMP Handler in the vector table is CMPIntHandler. //! //! \return None. // //***************************************************************************** void CMP_IRQHandler( void ) { TestAssert( 1 == ACMPIntStatus( ACMP_BASE, 0 ), "xacmp API \"ACMPIntStatus()\" error!" ); ACMPIntClear( ACMP_BASE, 0 ); TestEmitToken( 'T' ); } //***************************************************************************** // //! \brief xacmp api comparator interrupt status test. //! //! \return None. // //***************************************************************************** static void Int_Status( void ) { ACMPNegativeSrcSet( ACMP_BASE, 0, ACMP_ASRCN_REF ); ACMPIntEnable( ACMP_BASE, 0 ); xIntEnable( xINT_ACMP0 ); if ( 1 == ACMPIntStatus( ACMP_BASE, 0 ) ) { ACMPIntClear( ACMP_BASE, 0 ); TestAssert( 1 == ACMPIntStatus( ACMP_BASE, 0 ), "xacmp API \"ACMPIntClear()\" error!" ); } ACMPEnable( ACMP_BASE, 0 ); TestAssertQBreak( "T", "xacmp interrupt function error!", 0xFFFFFFFF ); } //***************************************************************************** // //! \brief xacmp001 test execute main body. //! //! \return None. // //***************************************************************************** static void xacmp001Execute( void ) { Int_Status( ); } //***************************************************************************** // //! \brief Get the Test description of xacmp001 register test. //! //! \return the desccription of the xacmp001 test. // //***************************************************************************** static char* xacmp001GetTest( void ) { return "xacmp, 001, xacmp register test"; } //***************************************************************************** // //! \brief something should do before the test execute of xacmp001 test. //! //! \return None. // //***************************************************************************** static void xacmp001Setup( void ) { // // reset acmp // SysCtlPeripheralReset( SYSCTL_PERIPH_ACMP ); // // enable acmp clock // SysCtlPeripheralEnable( SYSCTL_PERIPH_ACMP ); // // config GPIO pin as ACMP function // xSPinTypeACMP( CMP0P, PC6 ); xSPinTypeACMP( CMP0O, PB12 ); } //***************************************************************************** // //! \brief something should do after the test execute of xacmp001 test. //! //! \return None. // //***************************************************************************** static void xacmp001TearDown( void ) { } // // xacmp001 register test case struct. // const tTestCase sTestXacmp001Register = { xacmp001GetTest, xacmp001Setup, xacmp001TearDown, xacmp001Execute }; // // Xgpio test suits. // const tTestCase * const psPatternXacmp[] = { &sTestXacmp001Register, 0 };
26.88
89
0.461522
6ef39493b7a53a0eec93561626391ce7a288183a
1,233
h
C
src/irix-mips.h
loongson-zn/Bitbucket-papi
dcf0ce127719927154f55cb29b643abb604227b8
[ "BSD-3-Clause" ]
null
null
null
src/irix-mips.h
loongson-zn/Bitbucket-papi
dcf0ce127719927154f55cb29b643abb604227b8
[ "BSD-3-Clause" ]
null
null
null
src/irix-mips.h
loongson-zn/Bitbucket-papi
dcf0ce127719927154f55cb29b643abb604227b8
[ "BSD-3-Clause" ]
null
null
null
#ifndef _IRIX_MIPS_H #define _IRIX_MIPS_H #define MAX_COUNTERS HWPERF_EVENTMAX #define MAX_NATIVE_EVENT 32 #define PAPI_MAX_NATIVE_EVENTS MAX_NATIVE_EVENT typedef int hwd_register_t; typedef int hwd_reg_alloc_t; typedef struct hwd_control_state { /* Generation number of the counters */ int generation; /* Native encoding of the default counting domain */ int selector; /* Buffer to pass to the kernel to control the counters */ hwperf_profevctrarg_t counter_cmd; /* Number on each hwcounter */ unsigned num_on_counter[2]; int overflow_event_count; /* Buffer for reading counters */ hwperf_cntr_t cntrs_read; /* Buffer for generating overflow vector */ hwperf_cntr_t cntrs_last_read; } hwd_control_state_t; typedef struct _Context { /* File descriptor controlling the counters; */ int fd; } hwd_context_t; typedef struct { unsigned int ri_fill:16, ri_imp:8, /* implementation id */ ri_majrev:4, /* major revision */ ri_minrev:4; /* minor revision */ } papi_rev_id_t; typedef siginfo_t hwd_siginfo_t; typedef struct sigcontext hwd_ucontext_t; #define GET_OVERFLOW_ADDRESS(ctx) (caddr_t)(((hwd_ucontext_t *)ctx.ucontext)->sc_pc) #endif
26.804348
85
0.733982
207f4647a19694652b88db35f97ced5e6fae9e20
638
h
C
LZBYKLive/LZBYKLive/Modules/Other/Model/DM/LZBYKLoginManger.h
lzbgithubcode/LZBYKLive
b240908c957193f039b6c6476b83a9366624c6de
[ "Apache-2.0" ]
29
2017-03-19T11:08:41.000Z
2022-02-20T13:25:59.000Z
LZBYKLive/LZBYKLive/Modules/Other/Model/DM/LZBYKLoginManger.h
lzbgithubcode/LZBYKLive
b240908c957193f039b6c6476b83a9366624c6de
[ "Apache-2.0" ]
null
null
null
LZBYKLive/LZBYKLive/Modules/Other/Model/DM/LZBYKLoginManger.h
lzbgithubcode/LZBYKLive
b240908c957193f039b6c6476b83a9366624c6de
[ "Apache-2.0" ]
14
2016-08-30T05:36:46.000Z
2021-08-11T02:28:45.000Z
// // LZBYKLoginManger.h // LZBYKLive // // Created by zibin on 16/9/13. // Copyright © 2016年 刘子彬(更多项目源码分享平台“开发者源代码” 微信号:developerCode 作者简介:iOS开发者,喜爱交流分享). All rights reserved. // #import "BaseHttpDataManger.h" @protocol LZBYKLoginMangerDelegate <NSObject> /** * 登陆成功 */ - (void)didLogInSucess; /** * 退出成功 */ - (void)didLogOutSucess; @end @interface LZBYKLoginManger : BaseHttpDataManger /** * 登陆上传数据 * * @param phone 手机号 * @param passWord 密码 * @param compeletion 登陆结果 */ - (void)loginWithUserTel:(NSString *)phone password:(NSString *)passWord compeletion:(void(^)(NSError *error))compeletion; @end
16.789474
122
0.684953
545213dec5dad85de37e9c8753743f605735e6aa
1,846
c
C
zircon/system/utest/vdso-variant/helper/vdso-variant-helper.c
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
3
2020-08-02T04:46:18.000Z
2020-08-07T10:10:53.000Z
zircon/system/utest/vdso-variant/helper/vdso-variant-helper.c
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
zircon/system/utest/vdso-variant/helper/vdso-variant-helper.c
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
1
2020-08-07T10:11:49.000Z
2020-08-07T10:11:49.000Z
// Copyright 2017 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <dirent.h> #include <dlfcn.h> #include <errno.h> #include <fcntl.h> #include <string.h> #include <unistd.h> #include <unittest/unittest.h> #define GOOD_SYMBOL "zx_syscall_test_0" #define BAD_SYMBOL "zx_syscall_test_1" bool vdso_open_test(void) { BEGIN_TEST; int vdso_dir_fd = open("/boot/kernel/vdso", O_RDONLY | O_DIRECTORY); ASSERT_GE(vdso_dir_fd, 0, "open of vdso directory failed"); DIR* dir = fdopendir(dup(vdso_dir_fd)); ASSERT_NONNULL(dir, "fdopendir failed"); const struct dirent* d; int vdso_files_found = 0; while ((d = readdir(dir)) != NULL) { if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, "..")) continue; ++vdso_files_found; // Test that we can open for read. int fd = openat(vdso_dir_fd, d->d_name, O_RDONLY); EXPECT_GE(fd, 0, d->d_name); EXPECT_EQ(close(fd), 0, ""); // Test that we cannot open for write. EXPECT_EQ(openat(vdso_dir_fd, d->d_name, O_RDWR), -1, "opening vDSO file for writing"); EXPECT_EQ(errno, EACCES, "opening vDSO file for writing"); } EXPECT_GT(vdso_files_found, 1, "didn't find vDSO files"); EXPECT_EQ(closedir(dir), 0, ""); EXPECT_EQ(close(vdso_dir_fd), 0, ""); END_TEST; } bool vdso_missing_test_syscall1_test(void) { BEGIN_TEST; void* dso = dlopen("libzircon.so", RTLD_LOCAL | RTLD_NOLOAD); ASSERT_NONNULL(dso, dlerror()); EXPECT_NONNULL(dlsym(dso, GOOD_SYMBOL), dlerror()); EXPECT_NULL(dlsym(dso, BAD_SYMBOL), BAD_SYMBOL " symbol found in vDSO"); EXPECT_EQ(dlclose(dso), 0, ""); END_TEST; } BEGIN_TEST_CASE(vdso_variant_tests) RUN_TEST(vdso_open_test) RUN_TEST(vdso_missing_test_syscall1_test) END_TEST_CASE(vdso_variant_tests)
26.371429
91
0.7026
f5b8649f4c72e61c9699f62ca9ef903b43d093a0
4,017
h
C
src/MathArray.h
gwli/namd
a2ce2a1bfe68350cde94a72d32192ad8f1ffa175
[ "BSD-3-Clause" ]
2
2022-02-18T09:57:57.000Z
2022-02-18T09:58:14.000Z
src/MathArray.h
gwli/namd
a2ce2a1bfe68350cde94a72d32192ad8f1ffa175
[ "BSD-3-Clause" ]
null
null
null
src/MathArray.h
gwli/namd
a2ce2a1bfe68350cde94a72d32192ad8f1ffa175
[ "BSD-3-Clause" ]
1
2020-09-20T23:21:39.000Z
2020-09-20T23:21:39.000Z
/** *** Copyright (c) 1995, 1996, 1997, 1998, 1999, 2000 by *** The Board of Trustees of the University of Illinois. *** All rights reserved. **/ #ifndef MATHARRAY_H #define MATHARRAY_H #include "Array.h" template <class Elem, int Size> class MathArray : public Array<Elem,Size> { public: // constructor MathArray(void) : Array<Elem,Size>(0) { ; } // destructor ~MathArray(void) { ; } // copy constructor MathArray(const Array<Elem,Size> &a2) : Array<Elem,Size>(a2) { ; } // assignment operator MathArray<Elem,Size> & operator= (const Array<Elem,Size> &a2) { Array<Elem,Size>::operator=(a2); return (*this); } // set all elements to a given value (like 0) MathArray(const Elem &v) : Array<Elem,Size>(v) { ; } MathArray<Elem,Size> & operator= (const Elem &v) { Array<Elem,Size>::operator=(v); return (*this); } // bulk mathematical operations MathArray<Elem,Size> & operator+= (const Array<Elem,Size> &a2) { for ( int i = 0; i < Size; ++i ) { this->data[i] += a2.data[i]; } return (*this); } MathArray<Elem,Size> & operator+= (const Elem &v) { for ( int i = 0; i < Size; ++i ) { this->data[i] += v; } return (*this); } MathArray<Elem,Size> & operator-= (const Array<Elem,Size> &a2) { for ( int i = 0; i < Size; ++i ) { this->data[i] -= a2.data[i]; } return (*this); } MathArray<Elem,Size> & operator-= (const Elem &v) { for ( int i = 0; i < Size; ++i ) { this->data[i] -= v; } return (*this); } MathArray<Elem,Size> & operator*= (const Array<Elem,Size> &a2) { for ( int i = 0; i < Size; ++i ) { this->data[i] *= a2.data[i]; } return (*this); } MathArray<Elem,Size> & operator*= (const Elem &v) { for ( int i = 0; i < Size; ++i ) { this->data[i] *= v; } return (*this); } MathArray<Elem,Size> & operator/= (const Array<Elem,Size> &a2) { for ( int i = 0; i < Size; ++i ) { this->data[i] /= a2.data[i]; } return (*this); } MathArray<Elem,Size> & operator/= (const Elem &v) { for ( int i = 0; i < Size; ++i ) { this->data[i] /= v; } return (*this); } friend MathArray<Elem,Size> operator+ ( const Array<Elem,Size> &a1, const Array<Elem,Size> &a2 ) { return (MathArray<Elem,Size>(a1) += a2); } friend MathArray<Elem,Size> operator+ ( const Array<Elem,Size> &a1, const Elem &v2 ) { return (MathArray<Elem,Size>(a1) += v2); } friend MathArray<Elem,Size> operator+ ( const Elem & v1, const Array<Elem,Size> &a2 ) { return (MathArray<Elem,Size>(v1) += a2); } friend MathArray<Elem,Size> operator- ( const Array<Elem,Size> &a1, const Array<Elem,Size> &a2 ) { return (MathArray<Elem,Size>(a1) -= a2); } friend MathArray<Elem,Size> operator- ( const Array<Elem,Size> &a1, const Elem &v2 ) { return (MathArray<Elem,Size>(a1) -= v2); } friend MathArray<Elem,Size> operator- ( const Elem & v1, const Array<Elem,Size> &a2 ) { return (MathArray<Elem,Size>(v1) -= a2); } friend MathArray<Elem,Size> operator* ( const Array<Elem,Size> &a1, const Array<Elem,Size> &a2 ) { return (MathArray<Elem,Size>(a1) *= a2); } friend MathArray<Elem,Size> operator* ( const Array<Elem,Size> &a1, const Elem &v2 ) { return (MathArray<Elem,Size>(a1) *= v2); } friend MathArray<Elem,Size> operator* ( const Elem & v1, const Array<Elem,Size> &a2 ) { return (MathArray<Elem,Size>(v1) *= a2); } friend MathArray<Elem,Size> operator/ ( const Array<Elem,Size> &a1, const Array<Elem,Size> &a2 ) { return (MathArray<Elem,Size>(a1) /= a2); } friend MathArray<Elem,Size> operator/ ( const Array<Elem,Size> &a1, const Elem &v2 ) { return (MathArray<Elem,Size>(a1) /= v2); } friend MathArray<Elem,Size> operator/ ( const Elem & v1, const Array<Elem,Size> &a2 ) { return (MathArray<Elem,Size>(v1) /= a2); } }; #endif
32.658537
75
0.573811
f55485b0f64b19781d08b216441da2f0d0d3a882
264
h
C
MaliQuizLibs/MQlib_Qt/maliquizlib_global.h
hcamara/MaliQuiz
0435030689de8e9acffb8448009e46d18bb110f4
[ "MIT" ]
null
null
null
MaliQuizLibs/MQlib_Qt/maliquizlib_global.h
hcamara/MaliQuiz
0435030689de8e9acffb8448009e46d18bb110f4
[ "MIT" ]
null
null
null
MaliQuizLibs/MQlib_Qt/maliquizlib_global.h
hcamara/MaliQuiz
0435030689de8e9acffb8448009e46d18bb110f4
[ "MIT" ]
null
null
null
#ifndef MALIQUIZLIB_GLOBAL_H #define MALIQUIZLIB_GLOBAL_H #include <QtCore/qglobal.h> #if defined(MALIQUIZLIB_LIBRARY) # define MALIQUIZLIBSHARED_EXPORT Q_DECL_EXPORT #else # define MALIQUIZLIBSHARED_EXPORT Q_DECL_IMPORT #endif #endif // MALIQUIZLIB_GLOBAL_H
20.307692
48
0.837121
e582857660459f0301e3cecf788339dee3ebe7c2
222
c
C
src/interpreter/tests/CFG/old_decompilation/test-function-3.c
tracer-x/tracer
c91fa7dae8f4fd92f9cefa842e2d2a4e67c95a19
[ "RSA-MD" ]
21
2016-08-20T16:44:01.000Z
2019-10-08T12:16:55.000Z
src/interpreter/tests/CFG/old_decompilation/test-function-3.c
tracer-x/TRACER
c91fa7dae8f4fd92f9cefa842e2d2a4e67c95a19
[ "RSA-MD" ]
1
2020-06-16T03:45:51.000Z
2020-06-16T03:45:51.000Z
src/interpreter/tests/CFG/old_decompilation/test-function-3.c
tracer-x/tracer
c91fa7dae8f4fd92f9cefa842e2d2a4e67c95a19
[ "RSA-MD" ]
6
2016-11-27T04:07:40.000Z
2018-04-22T01:54:15.000Z
gint foo(int a, int b) { if(a <= 0) return a+1; else return b+1; } int main() { int i = 0; int sum = 0; while(i <= 10 || sum <= 100) { sum = foo(sum, i); i = foo(i, 1); } return sum; }
11.684211
32
0.436937
bceb69d59c49b0b70b6ac7f2a2551b35422dd5b9
315
h
C
src/examples/04_module/01_bank/customer.h
acc-cosc-1337-fall-2019/acc-cosc-1337-fall-2019-longdangaustincc
c20f551933db8cddada19939695cb1fe153c90ad
[ "MIT" ]
null
null
null
src/examples/04_module/01_bank/customer.h
acc-cosc-1337-fall-2019/acc-cosc-1337-fall-2019-longdangaustincc
c20f551933db8cddada19939695cb1fe153c90ad
[ "MIT" ]
null
null
null
src/examples/04_module/01_bank/customer.h
acc-cosc-1337-fall-2019/acc-cosc-1337-fall-2019-longdangaustincc
c20f551933db8cddada19939695cb1fe153c90ad
[ "MIT" ]
null
null
null
//customer.h #include <iostream> #include <vector> #include "bank_account.h" using std::ostream; using std::vector; class Customer { public: void add_account(BankAccount act); friend ostream & operator << (ostream & out, const Customer & c); private: vector <BankAccount> accounts; int total_balance{ 0 }; };
17.5
66
0.72381
491b28bd985c7d345126e3d27772bd70bc0b9c96
2,960
h
C
unit_tests/os_interface/windows/wddm_tests.h
abhi5658054/compute-runtime
894060de5010874381fc981cf96a722769e65a76
[ "MIT" ]
1
2022-03-04T22:47:19.000Z
2022-03-04T22:47:19.000Z
unit_tests/os_interface/windows/wddm_tests.h
abhi5658054/compute-runtime
894060de5010874381fc981cf96a722769e65a76
[ "MIT" ]
null
null
null
unit_tests/os_interface/windows/wddm_tests.h
abhi5658054/compute-runtime
894060de5010874381fc981cf96a722769e65a76
[ "MIT" ]
null
null
null
/* * Copyright (c) 2017, Intel Corporation * * 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. */ #pragma once #include "unit_tests/os_interface/windows/wddm_fixture.h" #include "runtime/command_stream/preemption.h" #include "test.h" using namespace OCLRT; OsLibrary *setAdapterInfo(const PLATFORM *platform, const GT_SYSTEM_INFO *gtSystemInfo); typedef Test<WddmGmmFixture> WddmTest; typedef Test<WddmInstrumentationGmmFixture> WddmInstrumentationTest; typedef WddmDummyFixture WddmTestSingle; class WddmPreemptionTests : public WddmTest { public: void SetUp() override { WddmTest::SetUp(); const HardwareInfo hwInfo = *platformDevices[0]; memcpy(&hwInfoTest, &hwInfo, sizeof(hwInfoTest)); dbgRestorer = new DebugManagerStateRestore(); } void TearDown() override { if (mockWddm) { delete mockWddm; } delete dbgRestorer; WddmTest::TearDown(); } template <typename GfxFamily> void createAndInitWddm(unsigned int forceReturnPreemptionRegKeyValue) { mockWddm = new WddmMock(); auto regReader = new RegistryReaderMock(); mockWddm->registryReader.reset(regReader); regReader->forceRetValue = forceReturnPreemptionRegKeyValue; PreemptionMode preemptionMode = PreemptionHelper::getDefaultPreemptionMode(hwInfoTest); mockWddm->setPreemptionMode(preemptionMode); mockWddm->init<GfxFamily>(); } WddmMock *mockWddm = nullptr; DebugManagerStateRestore *dbgRestorer = nullptr; HardwareInfo hwInfoTest; }; class WddmGmmMockGdiFixture : public GmmFixture, public WddmFixture { public: virtual void SetUp() { GmmFixture::SetUp(); WddmFixture::SetUp(&gdi); } virtual void TearDown() { WddmFixture::TearDown(); GmmFixture::TearDown(); } MockGdi gdi; }; typedef Test<WddmGmmMockGdiFixture> WddmWithMockGdiTest;
33.636364
95
0.725676
4ced08681678ffa696a3343041742924fd3df8db
387
h
C
4-ElementBufferObject/include/window_manager.h
Sander-Zeeman/GCJourney
65e12168bef0324987e117925c32d584a584e8a1
[ "MIT" ]
null
null
null
4-ElementBufferObject/include/window_manager.h
Sander-Zeeman/GCJourney
65e12168bef0324987e117925c32d584a584e8a1
[ "MIT" ]
null
null
null
4-ElementBufferObject/include/window_manager.h
Sander-Zeeman/GCJourney
65e12168bef0324987e117925c32d584a584e8a1
[ "MIT" ]
null
null
null
#ifndef WINDOW_MANAGER_H #define WINDOW_MANAGER_H #include <GL/glew.h> #include <SDL2/SDL.h> #include <stdint.h> extern uint32_t g_width; extern uint32_t g_height; void glv(int v, const char *msg); void *glp(void *ptr, const char *msg); void updateWindowSize(uint32_t width, uint32_t height); SDL_GLContext prepare(SDL_Window **window); #endif //WINDOW_MANAGER_H
20.368421
56
0.731266
48b3f4f94296d60d68fed0bb0660898f93a5cf6e
907
h
C
src/qif191/QIFDocument/type_t.CPerpendicularityCharacteristicDefinitionType.h
QualityInformationFramework/QIFResourcesEditor
4ff1de9d1dd20d9c43eaa9cc320caeff1c57760e
[ "BSL-1.0" ]
null
null
null
src/qif191/QIFDocument/type_t.CPerpendicularityCharacteristicDefinitionType.h
QualityInformationFramework/QIFResourcesEditor
4ff1de9d1dd20d9c43eaa9cc320caeff1c57760e
[ "BSL-1.0" ]
null
null
null
src/qif191/QIFDocument/type_t.CPerpendicularityCharacteristicDefinitionType.h
QualityInformationFramework/QIFResourcesEditor
4ff1de9d1dd20d9c43eaa9cc320caeff1c57760e
[ "BSL-1.0" ]
null
null
null
#pragma once #include "type_t.COrientationCharacteristicDefinitionBaseType.h" namespace qif191 { namespace t { class CPerpendicularityCharacteristicDefinitionType : public ::qif191::t::COrientationCharacteristicDefinitionBaseType { public: QIF191_EXPORT CPerpendicularityCharacteristicDefinitionType(xercesc::DOMNode* const& init); QIF191_EXPORT CPerpendicularityCharacteristicDefinitionType(CPerpendicularityCharacteristicDefinitionType const& init); void operator=(CPerpendicularityCharacteristicDefinitionType const& other) { m_node = other.m_node; } static altova::meta::ComplexType StaticInfo() { return altova::meta::ComplexType(types + _altova_ti_t_altova_CPerpendicularityCharacteristicDefinitionType); } QIF191_EXPORT void SetXsiType(); }; } // namespace t } // namespace qif191 //#endif // _ALTOVA_INCLUDED_QIFDocument_ALTOVA_t_ALTOVA_CPerpendicularityCharacteristicDefinitionType
31.275862
159
0.842337
48212a7ecf4b1da7b895ffc7586c448177c228dc
4,769
c
C
cQueue.c
arihantdaga/ESPHap
fd11b7c8a7075e2eedcd77aa54fca7c9d92bf67e
[ "MIT" ]
259
2018-12-30T03:40:51.000Z
2022-03-27T17:49:47.000Z
cQueue.c
arihantdaga/ESPHap
fd11b7c8a7075e2eedcd77aa54fca7c9d92bf67e
[ "MIT" ]
104
2020-03-28T18:01:49.000Z
2022-03-23T06:32:43.000Z
cQueue.c
arihantdaga/ESPHap
fd11b7c8a7075e2eedcd77aa54fca7c9d92bf67e
[ "MIT" ]
425
2018-11-26T14:01:22.000Z
2022-03-28T16:44:22.000Z
/*!\file cQueue.c ** \author SMFSW ** \copyright BSD 3-Clause License (c) 2017-2019, SMFSW ** \brief Queue handling library (designed in c on STM32) ** \details Queue handling library (designed in c on STM32) **/ /****************************************************************/ #include "port_x.h" #ifdef ARDUINO8266_SERVER_CPP #include <string.h> #include <stdlib.h> #include "cQueue.h" /****************************************************************/ /*! \brief Increment index ** \details Increment buffer index \b pIdx rolling back to \b start when limit \b end is reached ** \param [in,out] pIdx - pointer to index value ** \param [in] end - counter upper limit value ** \param [in] start - counter lower limit value **/ static inline void __attribute__((nonnull, always_inline)) inc_idx(uint16_t * const pIdx, const uint16_t end, const uint16_t start) { // (*pIdx)++; // *pIdx %= end; if (*pIdx < end - 1) { (*pIdx)++; } else { *pIdx = start; } } /*! \brief Decrement index ** \details Decrement buffer index \b pIdx rolling back to \b end when limit \b start is reached ** \param [in,out] pIdx - pointer to index value ** \param [in] end - counter upper limit value ** \param [in] start - counter lower limit value **/ static inline void __attribute__((nonnull, always_inline)) dec_idx(uint16_t * const pIdx, const uint16_t end, const uint16_t start) { if (*pIdx > start) { (*pIdx)--; } else { *pIdx = end - 1; } } void * __attribute__((nonnull)) q_init(Queue_t * const q, const uint16_t size_rec, const uint16_t nb_recs, const QueueType type, const bool overwrite) { const uint32_t size = nb_recs * size_rec; q->rec_nb = nb_recs; q->rec_sz = size_rec; q->impl = type; q->ovw = overwrite; q_kill(q); // Free existing data (if any) q->queue = (uint8_t *) malloc(size); if (q->queue == NULL) { q->queue_sz = 0; return 0; } // Return here if Queue not allocated else { q->queue_sz = size; } q->init = QUEUE_INITIALIZED; q_flush(q); return q->queue; // return NULL when queue not allocated (beside), Queue address otherwise } void __attribute__((nonnull)) q_kill(Queue_t * const q) { if (q->init == QUEUE_INITIALIZED) { free(q->queue); } // Free existing data (if already initialized) q->init = 0; } void __attribute__((nonnull)) q_flush(Queue_t * const q) { q->in = 0; q->out = 0; q->cnt = 0; } bool __attribute__((nonnull)) q_push(Queue_t * const q, const void * const record) { if ((!q->ovw) && q_isFull(q)) { return false; } uint8_t * const pStart = q->queue + (q->rec_sz * q->in); memcpy(pStart, record, q->rec_sz); inc_idx(&q->in, q->rec_nb, 0); if (!q_isFull(q)) { q->cnt++; } // Increase records count else if (q->ovw) // Queue is full and overwrite is allowed { if (q->impl == FIFO) { inc_idx(&q->out, q->rec_nb, 0); } // as oldest record is overwritten, increment out //else if (q->impl == LIFO) {} // Nothing to do in this case } return true; } bool __attribute__((nonnull)) q_pop(Queue_t * const q, void * const record) { const uint8_t * pStart; if (q_isEmpty(q)) { return false; } // No more records if (q->impl == FIFO) { pStart = q->queue + (q->rec_sz * q->out); inc_idx(&q->out, q->rec_nb, 0); } else if (q->impl == LIFO) { dec_idx(&q->in, q->rec_nb, 0); pStart = q->queue + (q->rec_sz * q->in); } else { return false; } memcpy(record, pStart, q->rec_sz); q->cnt--; // Decrease records count return true; } bool __attribute__((nonnull)) q_peek(const Queue_t * const q, void * const record) { const uint8_t * pStart; if (q_isEmpty(q)) { return false; } // No more records if (q->impl == FIFO) { pStart = q->queue + (q->rec_sz * q->out); // No change on out var as it's just a peek } else if (q->impl == LIFO) { uint16_t rec = q->in; // Temporary var for peek (no change on q->in with dec_idx) dec_idx(&rec, q->rec_nb, 0); pStart = q->queue + (q->rec_sz * rec); } else { return false; } memcpy(record, pStart, q->rec_sz); return true; } bool __attribute__((nonnull)) q_drop(Queue_t * const q) { if (q_isEmpty(q)) { return false; } // No more records if (q->impl == FIFO) { inc_idx(&q->out, q->rec_nb, 0); } else if (q->impl == LIFO) { dec_idx(&q->in, q->rec_nb, 0); } else { return false; } q->cnt--; // Decrease records count return true; } bool __attribute__((nonnull)) q_peekIdx(const Queue_t * const q, void * const record, const uint16_t idx) { const uint8_t * pStart; if (idx + 1 > q_getCount(q)) { return false; } // Index out of range if (q->impl == FIFO) { pStart = q->queue + (q->rec_sz * ((q->out + idx) % q->rec_nb)); } else if (q->impl == LIFO) { pStart = q->queue + (q->rec_sz * idx); } else { return false; } memcpy(record, pStart, q->rec_sz); return true; } #endif
26.943503
150
0.621514
484d33084ff7d931adb5d7fc17b3ebba0774843d
5,165
h
C
src/Native.h
vortex314/akkaCpp
a1d23499cff0e2aa01449a3a6e4193e174596870
[ "MIT" ]
20
2018-12-19T10:34:25.000Z
2022-03-10T07:10:57.000Z
src/Native.h
vortex314/microAkka
a1d23499cff0e2aa01449a3a6e4193e174596870
[ "MIT" ]
null
null
null
src/Native.h
vortex314/microAkka
a1d23499cff0e2aa01449a3a6e4193e174596870
[ "MIT" ]
null
null
null
/* * Native.h * * Created on: Feb 9, 2019 * Author: lieven */ #ifndef SRC_NATIVE_H_ #define SRC_NATIVE_H_ #include <stdint.h> #include <Log.h> template <typename T> class AbstractNativeQueue { public: virtual ~AbstractNativeQueue(){}; virtual int recv(T* item, uint32_t to)=0; virtual int send(T item, uint32_t to)=0; virtual int sendFromIsr(T item)=0; virtual uint32_t messageCount()=0; }; typedef void (*TaskFunction)(void*); class AbstractNativeThread { public: virtual ~AbstractNativeThread(){}; virtual void start()=0; virtual void wait()=0; }; #if defined( __freeRTOS__ ) || defined( ESP_OPEN_RTOS ) || defined(ESP32_IDF) #include <FreeRTOS.h> #include <semphr.h> #include <queue.h> #include <task.h> #include <timers.h> template <typename T> class NativeQueue : public AbstractNativeQueue<T> { QueueHandle_t _queue; public: NativeQueue(uint32_t queueSize); int send(T item,uint32_t msecWait); int recv(T* item,uint32_t msecWait); int sendFromIsr(T item); uint32_t messageCount(); }; typedef void (*TimerCallback)(void*); class NativeTimer { TimerHandle_t _timer; TimerCallback _callbackFunction; void* _callbackArg; bool _autoReload; uint32_t _interval; public: static void freeRTOSCallback(TimerHandle_t handle); NativeTimer(const char* name,bool autoReload , uint32_t interval,void* callbackArg,TimerCallback callbackFunction); ~NativeTimer(); void start(); void stop(); void reset(); void interval(uint32_t v); }; typedef void(*TaskFunction)(void*); class NativeThread { const char* _name; uint32_t _stackSize = 1024; uint32_t _priority = tskIDLE_PRIORITY + 1; TaskFunction _taskFunction; void* _taskArg; TaskHandle_t _task; public: NativeThread(const char* name,uint32_t stackSize,uint32_t priority,void* taskArg,TaskFunction taskFunction); void start(); void wait(); }; #endif #if defined( __linux__ ) || defined(__APPLE__) #ifndef __APPLE__ #include <sys/msg.h> #endif #include <stdint.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <errno.h> //#include <signal.h> #include <time.h> #include <condition_variable> #include <vector> #include <algorithm> #include <Log.h> #include <functional> #include <queue> #include <thread> #include <mutex> #include <condition_variable> template <typename T> class NativeQueue :public AbstractNativeQueue<T> { private: std::queue<T> queue_; std::mutex mutex_; std::condition_variable cond_; public: NativeQueue(uint32_t queueSize) {}; ~NativeQueue() {} ; int recv(T* item, uint32_t to); int send(T item, uint32_t to); int sendFromIsr(T item); uint32_t messageCount(); // Queue()=default; NativeQueue<T>(const NativeQueue<T>& other) = delete; // Queue& operator=(const Queue&) = delete; // disable assignment }; template <typename T> int NativeQueue<T>::recv(T* item, uint32_t to) { std::unique_lock<std::mutex> mlock(mutex_); std::chrono::milliseconds waitTime(to); if (queue_.empty()) { cond_.wait_for(mlock, waitTime); if (queue_.empty()) return ENOENT; } *item = queue_.front(); queue_.pop(); return 0; } template <typename T> int NativeQueue<T>::send(T item, uint32_t to) { std::unique_lock<std::mutex> mlock(mutex_); queue_.push(item); mlock.unlock(); cond_.notify_one(); return 0; } template <typename T> int NativeQueue<T>::sendFromIsr(T item) { return 0; // NOT IMPLEMENTED ON LINUX } template <typename T> uint32_t NativeQueue<T>::messageCount() { return queue_.size() ; } typedef void*(*PthreadFunction)(void*); #define tskIDLE_PRIORITY 0 class NativeThread : public AbstractNativeThread{ std::string _name; uint32_t _stackSize = 1024; uint32_t _priority = tskIDLE_PRIORITY + 1; TaskFunction _taskFunction; void* _taskArg; pthread_t _thread; public: NativeThread(const char* name, uint32_t stackSize, uint32_t priority, void* taskArg, TaskFunction taskFunction); void start(); void wait(); }; //#include <sort> typedef void (*TimerCallback)(void*); typedef std::chrono::milliseconds Interval; typedef std::function<void(void)> Timeout; typedef std::chrono::high_resolution_clock Clock; class NativeTimer { // timer_t _timer; TimerCallback _callbackFunction; void* _callbackArg; bool _autoReload; uint32_t _interval; uint32_t _id; static uint32_t _idCounter; public: std::chrono::high_resolution_clock::time_point _timePoint; NativeTimer(const char* name, bool autoReload, uint32_t interval, void* callbackArg, TimerCallback callbackFunction); ~NativeTimer(); void start(); void stop(); void reset(); void interval(uint32_t v); uint32_t interval(); bool autoReload(); void invoke(); }; //___________________________________________________________________________ // class NativeTimerThread: public NativeThread { // std::unique_ptr<std::thread> m_Thread; std::vector<NativeTimer*> m_Timers; std::mutex m_Mutex; std::condition_variable m_Condition; bool m_Stop; bool m_Sort; public: void run(); static void runStatic(void* th); NativeTimerThread(); ~NativeTimerThread(); void addTimer(NativeTimer* timer); void removeTimer(NativeTimer* timer); }; #endif #endif /* SRC_NATIVE_H_ */
21.701681
116
0.738238
3454c01d06f024c0c1fa6ce7a2dc6535e53c214c
1,248
h
C
src/simplesat/bin_algebra/variable_environment.h
evmaus/ClusterSAT
d26ff539fe9789611e9ecd8ef5c14a19e150105b
[ "Apache-2.0" ]
null
null
null
src/simplesat/bin_algebra/variable_environment.h
evmaus/ClusterSAT
d26ff539fe9789611e9ecd8ef5c14a19e150105b
[ "Apache-2.0" ]
null
null
null
src/simplesat/bin_algebra/variable_environment.h
evmaus/ClusterSAT
d26ff539fe9789611e9ecd8ef5c14a19e150105b
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Google LLC * * 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. */ #ifndef SRC_VARIABLE_ENVIRONMENT_H #define SRC_VARIABLE_ENVIRONMENT_H #include <map> #include <string> namespace simplesat { namespace binary { class VariableEnvironment { public: static VariableEnvironment Empty(); bool Lookup(::std::string variable_name); void Assign(::std::string variable_name, bool value); ::std::map<std::string, bool>::iterator begin() { return variables_.begin(); } ::std::map<std::string, bool>::iterator end() { return variables_.end(); } private: VariableEnvironment(); ::std::map<std::string, bool> variables_; }; } // namespace binary } // namespace simplesat #endif // SRC_VARIABLE_ENVIRONMENT_H
29.714286
80
0.730769
4262d334dffe9ab485bed949d937552a4052fb61
4,785
h
C
Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.h
LB-JakubSkorupka/o3de
e224fc2ee5ec2a12e75a10acae268b7b38ae3a32
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.h
LB-JakubSkorupka/o3de
e224fc2ee5ec2a12e75a10acae268b7b38ae3a32
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorVisibleEntityDataCache.h
LB-JakubSkorupka/o3de
e224fc2ee5ec2a12e75a10acae268b7b38ae3a32
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #include <AzCore/Component/TransformBus.h> #include <AzCore/std/optional.h> #include <AzToolsFramework/API/ComponentEntitySelectionBus.h> #include <AzToolsFramework/ContainerEntity/ContainerEntityNotificationBus.h> #include <AzToolsFramework/FocusMode/FocusModeNotificationBus.h> #include <AzToolsFramework/ToolsComponents/EditorEntityIconComponentBus.h> #include <AzToolsFramework/ToolsComponents/EditorLockComponentBus.h> #include <AzToolsFramework/ToolsComponents/EditorSelectionAccentSystemComponent.h> #include <AzToolsFramework/ToolsComponents/EditorVisibilityBus.h> namespace AzToolsFramework { //! A cache of packed EntityData that can be iterated over efficiently without //! the need to make individual EBus calls class EditorVisibleEntityDataCache : private EditorEntityVisibilityNotificationBus::Router , private EditorEntityLockComponentNotificationBus::Router , private AZ::TransformNotificationBus::Router , private EditorComponentSelectionNotificationsBus::Router , private EntitySelectionEvents::Bus::Router , private EditorEntityIconComponentNotificationBus::Router , private ToolsApplicationNotificationBus::Handler , private ContainerEntityNotificationBus::Handler , private FocusModeNotificationBus::Handler { public: EditorVisibleEntityDataCache(); ~EditorVisibleEntityDataCache(); EditorVisibleEntityDataCache(const EditorVisibleEntityDataCache&) = delete; EditorVisibleEntityDataCache& operator=(const EditorVisibleEntityDataCache&) = delete; EditorVisibleEntityDataCache(EditorVisibleEntityDataCache&&); EditorVisibleEntityDataCache& operator=(EditorVisibleEntityDataCache&&); using ComponentEntityAccentType = Components::EditorSelectionAccentSystemComponent::ComponentEntityAccentType; void CalculateVisibleEntityDatas(const AzFramework::ViewportInfo& viewportInfo); //! EditorVisibleEntityDataCache interface size_t VisibleEntityDataCount() const; AZ::Vector3 GetVisibleEntityPosition(size_t index) const; const AZ::Transform& GetVisibleEntityTransform(size_t index) const; AZ::EntityId GetVisibleEntityId(size_t index) const; ComponentEntityAccentType GetVisibleEntityAccent(size_t index) const; bool IsVisibleEntityLocked(size_t index) const; bool IsVisibleEntityVisible(size_t index) const; bool IsVisibleEntitySelected(size_t index) const; bool IsVisibleEntityIconHidden(size_t index) const; //! Returns true if the entity is individually selectable (none of its ancestors are a closed container entity). //! @note It may still be desirable to be able to 'click' an entity that is a descendant of a closed container //! to select the container itself, not the individual entity. bool IsVisibleEntityIndividuallySelectableInViewport(size_t index) const; AZStd::optional<size_t> GetVisibleEntityIndexFromId(AZ::EntityId entityId) const; void AddEntityIds(const EntityIdList& entityIds); private: // ToolsApplicationNotificationBus overrides ... void AfterUndoRedo() override; // EditorEntityVisibilityNotificationBus overrides ... void OnEntityVisibilityChanged(bool visibility) override; // EditorEntityLockComponentNotificationBus overrides ... void OnEntityLockChanged(bool locked) override; // TransformNotificationBus overrides ... void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override; // EditorComponentSelectionNotificationsBus overrides ... void OnAccentTypeChanged(EntityAccentType accent) override; // EntitySelectionEvents::Bus overrides ... void OnSelected() override; void OnDeselected() override; // EditorEntityIconComponentNotificationBus overrides ... void OnEntityIconChanged(const AZ::Data::AssetId& entityIconAssetId) override; // ContainerEntityNotificationBus overrides ... void OnContainerEntityStatusChanged(AZ::EntityId entityId, bool open) override; // FocusModeNotificationBus overrides ... void OnEditorFocusChanged(AZ::EntityId previousFocusEntityId, AZ::EntityId newFocusEntityId) override; class EditorVisibleEntityDataCacheImpl; AZStd::unique_ptr<EditorVisibleEntityDataCacheImpl> m_impl; //!< Internal representation of entity data cache. }; } // namespace AzToolsFramework
47.85
120
0.758203
51a79793e221d9ee6a9a2a683abb45f66f7d3ba8
9,190
c
C
kernel/drivers/media/video/samsung/jpeg_v2/jpg_opr.c
LoongPenguin/Linux_210
d941ed620798fb9c96b5d06764fb1dcb68057513
[ "Apache-2.0" ]
null
null
null
kernel/drivers/media/video/samsung/jpeg_v2/jpg_opr.c
LoongPenguin/Linux_210
d941ed620798fb9c96b5d06764fb1dcb68057513
[ "Apache-2.0" ]
null
null
null
kernel/drivers/media/video/samsung/jpeg_v2/jpg_opr.c
LoongPenguin/Linux_210
d941ed620798fb9c96b5d06764fb1dcb68057513
[ "Apache-2.0" ]
null
null
null
/* linux/drivers/media/video/samsung/jpeg_v2/jpg_opr.c * * Copyright (c) 2010 Samsung Electronics Co., Ltd. * http://www.samsung.com/ * * Operation for Jpeg encoder/docoder * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/delay.h> #include <linux/io.h> #include "jpg_mem.h" #include "jpg_misc.h" #include "jpg_opr.h" #include "jpg_conf.h" #include "regs-jpeg.h" enum { UNKNOWN, BASELINE = 0xC0, EXTENDED_SEQ = 0xC1, PROGRESSIVE = 0xC2 } jpg_sof_marker; enum jpg_return_status wait_for_interrupt(void) { if (interruptible_sleep_on_timeout(&wait_queue_jpeg, \ INT_TIMEOUT) == 0) { jpg_err("waiting for interrupt is timeout\n"); } return jpg_irq_reason; } enum jpg_return_status decode_jpg(struct s5pc110_jpg_ctx *jpg_ctx, struct jpg_dec_proc_param *dec_param) { int ret; enum sample_mode sample_mode; unsigned int width, height; jpg_dbg("enter decode_jpg function\n"); if (jpg_ctx) reset_jpg(jpg_ctx); else { jpg_err("jpg ctx is NULL\n"); return JPG_FAIL; } /* set jpeg clock register : power on */ writel(readl(s3c_jpeg_base + S3C_JPEG_CLKCON_REG) | (S3C_JPEG_CLKCON_REG_POWER_ON_ACTIVATE), s3c_jpeg_base + S3C_JPEG_CLKCON_REG); /* set jpeg mod register : decode */ writel(readl(s3c_jpeg_base + S3C_JPEG_MOD_REG) | (S3C_JPEG_MOD_REG_PROC_DEC), s3c_jpeg_base + S3C_JPEG_MOD_REG); /* set jpeg interrupt setting register */ writel(readl(s3c_jpeg_base + S3C_JPEG_INTSE_REG) | (S3C_JPEG_INTSE_REG_RSTM_INT_EN | S3C_JPEG_INTSE_REG_DATA_NUM_INT_EN | S3C_JPEG_INTSE_REG_FINAL_MCU_NUM_INT_EN), s3c_jpeg_base + S3C_JPEG_INTSE_REG); /* set jpeg deocde ouput format register */ writel(readl(s3c_jpeg_base + S3C_JPEG_OUTFORM_REG) & ~(S3C_JPEG_OUTFORM_REG_YCBCY420), s3c_jpeg_base + S3C_JPEG_OUTFORM_REG); writel(readl(s3c_jpeg_base + S3C_JPEG_OUTFORM_REG) | (dec_param->out_format << 0), s3c_jpeg_base + S3C_JPEG_OUTFORM_REG); /* set the address of compressed input data */ writel(jpg_ctx->img_data_addr, s3c_jpeg_base + S3C_JPEG_IMGADR_REG); /* set the address of decompressed image */ writel(jpg_ctx->jpg_data_addr, s3c_jpeg_base + S3C_JPEG_JPGADR_REG); /* start decoding */ writel(readl(s3c_jpeg_base + S3C_JPEG_JRSTART_REG) | S3C_JPEG_JRSTART_REG_ENABLE, s3c_jpeg_base + S3C_JPEG_JSTART_REG); ret = wait_for_interrupt(); if (ret != OK_ENC_OR_DEC) { jpg_err("jpg decode error(%d)\n", ret); return JPG_FAIL; } sample_mode = get_sample_type(jpg_ctx); jpg_dbg("sample_mode : %d\n", sample_mode); if (sample_mode == JPG_SAMPLE_UNKNOWN) { jpg_err("jpg has invalid sample_mode\r\n"); return JPG_FAIL; } dec_param->sample_mode = sample_mode; get_xy(jpg_ctx, &width, &height); jpg_dbg("decode size:: width : %d height : %d\n", width, height); dec_param->data_size = get_yuv_size(dec_param->out_format, width, height); dec_param->width = width; dec_param->height = height; return JPG_SUCCESS; } void reset_jpg(struct s5pc110_jpg_ctx *jpg_ctx) { jpg_dbg("s3c_jpeg_base %p\n", s3c_jpeg_base); writel(S3C_JPEG_SW_RESET_REG_ENABLE, s3c_jpeg_base + S3C_JPEG_SW_RESET_REG); do { writel(S3C_JPEG_SW_RESET_REG_ENABLE, s3c_jpeg_base + S3C_JPEG_SW_RESET_REG); } while (((readl(s3c_jpeg_base + S3C_JPEG_SW_RESET_REG)) & S3C_JPEG_SW_RESET_REG_ENABLE) == S3C_JPEG_SW_RESET_REG_ENABLE); } enum sample_mode get_sample_type(struct s5pc110_jpg_ctx *jpg_ctx) { unsigned long jpgMode; enum sample_mode sample_mode = JPG_SAMPLE_UNKNOWN; jpgMode = readl(s3c_jpeg_base + S3C_JPEG_MOD_REG); sample_mode = ((jpgMode & JPG_SMPL_MODE_MASK) == JPG_444) ? JPG_444 : ((jpgMode & JPG_SMPL_MODE_MASK) == JPG_422) ? JPG_422 : ((jpgMode & JPG_SMPL_MODE_MASK) == JPG_420) ? JPG_420 : ((jpgMode & JPG_SMPL_MODE_MASK) == JPG_400) ? JPG_400 : ((jpgMode & JPG_SMPL_MODE_MASK) == JPG_411) ? JPG_411 : JPG_SAMPLE_UNKNOWN; return sample_mode; } void get_xy(struct s5pc110_jpg_ctx *jpg_ctx, unsigned int *x, unsigned int *y) { *x = (readl(s3c_jpeg_base + S3C_JPEG_X_U_REG)<<8)| readl(s3c_jpeg_base + S3C_JPEG_X_L_REG); *y = (readl(s3c_jpeg_base + S3C_JPEG_Y_U_REG)<<8)| readl(s3c_jpeg_base + S3C_JPEG_Y_L_REG); } unsigned int get_yuv_size(enum out_mode out_format, unsigned int width, unsigned int height) { switch (out_format) { case YCBCR_422: if (width % 16 != 0) width += 16 - (width % 16); if (height % 8 != 0) height += 8 - (height % 8); break; case YCBCR_420: if (width % 16 != 0) width += 16 - (width % 16); if (height % 16 != 0) height += 16 - (height % 16); break; case YCBCR_SAMPLE_UNKNOWN: break; } jpg_dbg("get_yuv_size width(%d) height(%d)\n", width, height); switch (out_format) { case YCBCR_422: return width * height * 2; case YCBCR_420: return (width * height) + (width * height >> 1); default: return 0; } } enum jpg_return_status encode_jpg(struct s5pc110_jpg_ctx *jpg_ctx, struct jpg_enc_proc_param *enc_param) { unsigned int i, ret; unsigned int cmd_val; if (enc_param->width <= 0 || enc_param->width > jpg_ctx->limits->max_main_width || enc_param->height <= 0 || enc_param->height > jpg_ctx->limits->max_main_height) { jpg_err("::encoder : width: %d, height: %d\n", enc_param->width, enc_param->height); jpg_err("::encoder : invalid width/height\n"); return JPG_FAIL; } /* SW reset */ if (jpg_ctx) reset_jpg(jpg_ctx); else { jpg_err("::jpg ctx is NULL\n"); return JPG_FAIL; } /* set jpeg clock register : power on */ writel(readl(s3c_jpeg_base + S3C_JPEG_CLKCON_REG) | (S3C_JPEG_CLKCON_REG_POWER_ON_ACTIVATE), s3c_jpeg_base + S3C_JPEG_CLKCON_REG); /* set jpeg mod register : encode */ writel(readl(s3c_jpeg_base + S3C_JPEG_CMOD_REG) | (enc_param->in_format << JPG_MODE_SEL_BIT), s3c_jpeg_base + S3C_JPEG_CMOD_REG); cmd_val = (enc_param->sample_mode == JPG_422) ? (S3C_JPEG_MOD_REG_SUBSAMPLE_422) : (S3C_JPEG_MOD_REG_SUBSAMPLE_420); writel(cmd_val | S3C_JPEG_MOD_REG_PROC_ENC, s3c_jpeg_base + S3C_JPEG_MOD_REG); /* set DRI(Define Restart Interval) */ writel(JPG_RESTART_INTRAVEL, s3c_jpeg_base + S3C_JPEG_DRI_L_REG); writel((JPG_RESTART_INTRAVEL>>8), s3c_jpeg_base + S3C_JPEG_DRI_U_REG); writel(S3C_JPEG_QHTBL_REG_QT_NUM1, s3c_jpeg_base + S3C_JPEG_QTBL_REG); writel(0x00, s3c_jpeg_base + S3C_JPEG_HTBL_REG); /* Horizontal resolution */ writel((enc_param->width>>8), s3c_jpeg_base + S3C_JPEG_X_U_REG); writel(enc_param->width, s3c_jpeg_base + S3C_JPEG_X_L_REG); /* Vertical resolution */ writel((enc_param->height>>8), s3c_jpeg_base + S3C_JPEG_Y_U_REG); writel(enc_param->height, s3c_jpeg_base + S3C_JPEG_Y_L_REG); jpg_dbg("enc_param->enc_type : %d\n", enc_param->enc_type); if (enc_param->enc_type == JPG_MAIN) { jpg_dbg("encode image size width: %d, height: %d\n", enc_param->width, enc_param->height); writel(jpg_ctx->img_data_addr, s3c_jpeg_base + S3C_JPEG_IMGADR_REG); writel(jpg_ctx->jpg_data_addr, s3c_jpeg_base + S3C_JPEG_JPGADR_REG); } else { /* thumbnail encoding */ jpg_dbg("thumb image size width: %d, height: %d\n", enc_param->width, enc_param->height); writel(jpg_ctx->img_thumb_data_addr, s3c_jpeg_base + S3C_JPEG_IMGADR_REG); writel(jpg_ctx->jpg_thumb_data_addr, s3c_jpeg_base + S3C_JPEG_JPGADR_REG); } /* Coefficient value 1~3 for RGB to YCbCr */ writel(COEF1_RGB_2_YUV, s3c_jpeg_base + S3C_JPEG_COEF1_REG); writel(COEF2_RGB_2_YUV, s3c_jpeg_base + S3C_JPEG_COEF2_REG); writel(COEF3_RGB_2_YUV, s3c_jpeg_base + S3C_JPEG_COEF3_REG); /* Quantiazation and Huffman Table setting */ for (i = 0; i < 64; i++) { writel((unsigned int)qtbl_luminance[enc_param->quality][i], s3c_jpeg_base + S3C_JPEG_QTBL0_REG + (i*0x04)); } for (i = 0; i < 64; i++) { writel((unsigned int)qtbl_chrominance[enc_param->quality][i], s3c_jpeg_base + S3C_JPEG_QTBL1_REG + (i*0x04)); } for (i = 0; i < 16; i++) { writel((unsigned int)hdctbl0[i], s3c_jpeg_base + S3C_JPEG_HDCTBL0_REG + (i*0x04)); } for (i = 0; i < 12; i++) { writel((unsigned int)hdctblg0[i], s3c_jpeg_base + S3C_JPEG_HDCTBLG0_REG + (i*0x04)); } for (i = 0; i < 16; i++) { writel((unsigned int)hactbl0[i], s3c_jpeg_base + S3C_JPEG_HACTBL0_REG + (i*0x04)); } for (i = 0; i < 162; i++) { writel((unsigned int)hactblg0[i], s3c_jpeg_base + S3C_JPEG_HACTBLG0_REG + (i*0x04)); } writel(readl(s3c_jpeg_base + S3C_JPEG_INTSE_REG) | (S3C_JPEG_INTSE_REG_RSTM_INT_EN | S3C_JPEG_INTSE_REG_DATA_NUM_INT_EN | S3C_JPEG_INTSE_REG_FINAL_MCU_NUM_INT_EN), s3c_jpeg_base + S3C_JPEG_INTSE_REG); writel(readl(s3c_jpeg_base + S3C_JPEG_JSTART_REG) | S3C_JPEG_JSTART_REG_ENABLE, s3c_jpeg_base + S3C_JPEG_JSTART_REG); ret = wait_for_interrupt(); if (ret != OK_ENC_OR_DEC) { jpg_err("jpeg encoding error(%d)\n", ret); return JPG_FAIL; } enc_param->file_size = readl(s3c_jpeg_base + S3C_JPEG_CNT_U_REG) << 16; enc_param->file_size |= readl(s3c_jpeg_base + S3C_JPEG_CNT_M_REG) << 8; enc_param->file_size |= readl(s3c_jpeg_base + S3C_JPEG_CNT_L_REG); return JPG_SUCCESS; }
28.629283
78
0.722633
61b2531eef17edb07b2b7e6dad78ddfdbefd1ce5
495
h
C
linux/arch/s390/oprofile/op_counter.h
bradchesney79/illacceptanything
4594ae4634fdb5e39263a6423dc255ed46c25208
[ "MIT" ]
55
2019-12-20T03:25:14.000Z
2022-01-16T07:19:47.000Z
linux/arch/s390/oprofile/op_counter.h
bradchesney79/illacceptanything
4594ae4634fdb5e39263a6423dc255ed46c25208
[ "MIT" ]
2
2020-11-02T08:01:00.000Z
2022-03-27T02:59:18.000Z
linux/arch/s390/oprofile/op_counter.h
bradchesney79/illacceptanything
4594ae4634fdb5e39263a6423dc255ed46c25208
[ "MIT" ]
11
2020-08-06T03:59:45.000Z
2022-02-25T02:31:59.000Z
/* * Copyright IBM Corp. 2011 * Author(s): Andreas Krebbel (krebbel@linux.vnet.ibm.com) * * @remark Copyright 2011 OProfile authors */ #ifndef OP_COUNTER_H #define OP_COUNTER_H struct op_counter_config { /* `enabled' maps to the hwsampler_file variable. */ /* `count' maps to the oprofile_hw_interval variable. */ /* `event' and `unit_mask' are unused. */ unsigned long kernel; unsigned long user; }; extern struct op_counter_config counter_config; #endif /* OP_COUNTER_H */
22.5
60
0.719192
b2cda779ca9ca33a7c50fdafac06969807b3b554
20,084
h
C
test/aarch64/traces/sim-sdot-4s-trace-aarch64.h
capablevms/VIXL
769c8e46a09bb077e9a2148b86a2093addce8233
[ "BSD-3-Clause" ]
573
2016-08-31T20:21:20.000Z
2021-08-29T14:01:11.000Z
test/aarch64/traces/sim-sdot-4s-trace-aarch64.h
capablevms/VIXL
769c8e46a09bb077e9a2148b86a2093addce8233
[ "BSD-3-Clause" ]
366
2016-09-02T06:37:43.000Z
2021-08-11T18:38:24.000Z
test/aarch64/traces/sim-sdot-4s-trace-aarch64.h
capablevms/VIXL
769c8e46a09bb077e9a2148b86a2093addce8233
[ "BSD-3-Clause" ]
135
2016-09-01T02:02:58.000Z
2021-08-13T01:25:22.000Z
// Copyright 2015, VIXL authors // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * 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 ARM Limited 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 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. // --------------------------------------------------------------------- // This file is auto generated using tools/generate_simulator_traces.py. // // PLEASE DO NOT EDIT. // --------------------------------------------------------------------- #ifndef VIXL_SIM_SDOT_4S_TRACE_AARCH64_H_ #define VIXL_SIM_SDOT_4S_TRACE_AARCH64_H_ const uint32_t kExpected_NEON_sdot_4S[] = { 0x0000a16f, 0x0000fc07, 0x000064bf, 0x0000002e, 0x0000b678, 0x00007c09, 0x00003d30, 0x00000028, 0x000041c0, 0x00006857, 0x00001cc2, 0x00000022, 0xffffc643, 0x00004441, 0x0000055c, 0x0000001c, 0xffff72c6, 0x00000aba, 0x00000259, 0x00000011, 0xffff4149, 0xfffff4c9, 0x0000014a, 0xffffffd7, 0xffff5580, 0xffffecae, 0x0000003b, 0xffffff4d, 0xffff79cf, 0xffffff05, 0xffffff04, 0xfffffe60, 0xffffad37, 0x00000003, 0xfffffba1, 0xfffffda9, 0xffffd838, 0xffffff05, 0xffffef54, 0xfffffd2e, 0xfffff089, 0xfffffe07, 0xffffd5cc, 0xfffffe28, 0xfffffbf1, 0xfffffa93, 0xffffad39, 0x00000022, 0xfffffe40, 0xffffe26e, 0xffff8ef3, 0x0000031c, 0xffffffc3, 0xffffb9dc, 0xffff82d9, 0x00000316, 0x00000146, 0xffff82c8, 0xffffb5ca, 0x000002ea, 0x0000053f, 0xffff72c7, 0x00000abb, 0x00000277, 0x00001ddf, 0xffff6ea8, 0x000086ac, 0x00000192, 0x000045cb, 0xffffff03, 0x0000846d, 0x000000cf, 0x0000798e, 0x00007d05, 0x00007a9e, 0x00000040, 0x0000b678, 0x00007c09, 0x00003d30, 0x00000028, 0x0000d647, 0x0000fa0f, 0x000027bf, 0x00000026, 0x00006609, 0x0000e587, 0x00001338, 0x00000024, 0xffffe9d8, 0x0000c0bc, 0x00000361, 0x00000027, 0xffff6ea7, 0x000086ab, 0x00000174, 0x0000004f, 0xffff1b76, 0x00004a34, 0x000000df, 0x00000069, 0xffff301f, 0x0000206d, 0x0000004a, 0x0000005a, 0xffff5501, 0x000006f7, 0xffffffa6, 0xffffffe3, 0xffff8ef1, 0x000002fd, 0xfffffe6b, 0xffffff78, 0xffffc4a1, 0x00000103, 0xfffffb1f, 0xfffffe28, 0xffffe85c, 0xffffff09, 0xffffeed7, 0xfffffe26, 0xfffffa66, 0xfffffa9e, 0xffffd83a, 0xffffff24, 0xfffffd89, 0xffffe1ac, 0xffffc4a3, 0x00000122, 0xffffff58, 0xffffb86e, 0xffffb9f4, 0x00000146, 0x00000127, 0xffff7bd5, 0xffffc15f, 0x00000165, 0x00000571, 0xffff414a, 0xfffff4ca, 0x00000168, 0x00001e8c, 0xffff1b77, 0x00004a35, 0x000000fd, 0x000047d7, 0xffff82fd, 0x0000492e, 0x0000008e, 0x00008368, 0xffffff03, 0x00004706, 0x00000032, 0x000041c0, 0x00006857, 0x00001cc2, 0x00000022, 0x00006609, 0x0000e587, 0x00001338, 0x00000024, 0x0000fa0e, 0x0000d6f3, 0x00000adf, 0x00000026, 0x00007c08, 0x0000b77f, 0x000001c2, 0x00000032, 0xffffff02, 0x0000846c, 0x000000b1, 0x0000008d, 0xffff82fc, 0x0000492d, 0x00000070, 0x000000fb, 0xffff70f6, 0x00001fe0, 0x0000002f, 0x00000167, 0xffff744a, 0x000006c3, 0xffffffe4, 0x00000166, 0xffff82d7, 0x000002f7, 0xffffff40, 0x00000147, 0xffffb9f2, 0x00000127, 0xfffffe17, 0xffffff22, 0xffffe22f, 0xffffff57, 0xfffffad1, 0xfffffe24, 0xfffffa20, 0xfffffbd9, 0xfffff08b, 0xfffffe26, 0xfffffd0e, 0xffffe97c, 0xffffe85e, 0xffffff28, 0xfffffe08, 0xffffc59e, 0xffffe231, 0xffffff76, 0xffffff02, 0xffff8f70, 0xffffe4f0, 0xffffffe0, 0xfffffd7c, 0xffff5581, 0xffffecaf, 0x00000059, 0xffffebf1, 0xffff3020, 0x0000206e, 0x00000068, 0xfffff3b7, 0xffff70f7, 0x00001fe1, 0x0000004d, 0x000008ad, 0xffffec27, 0x00001eec, 0x00000024, 0xffffc643, 0x00004441, 0x0000055c, 0x0000001c, 0xffffe9d8, 0x0000c0bc, 0x00000361, 0x00000027, 0x00007c08, 0x0000b77f, 0x000001c2, 0x00000032, 0x0000fc06, 0x0000a282, 0x00000050, 0x00000065, 0x00007d04, 0x00007a9d, 0x00000022, 0x000001ca, 0xffffff02, 0x00004705, 0x00000014, 0x00000336, 0xffffec26, 0x00001eeb, 0x00000006, 0x000004e5, 0xffffc8c5, 0x00000648, 0xfffffff3, 0x0000055f, 0xffffb5c8, 0x000002cb, 0xffffffb1, 0x00000591, 0xffffc15d, 0x00000146, 0xffffff1f, 0xfffffd9c, 0xffffe4ee, 0xffffffc1, 0xfffffe02, 0xfffffba7, 0xfffffc12, 0xfffffd38, 0xfffffbf3, 0xfffffab2, 0xfffffe08, 0xfffff17d, 0xfffffa68, 0xfffffabd, 0xfffffe06, 0xffffd8b7, 0xfffffa22, 0xfffffbf8, 0xfffffe04, 0xffffad38, 0xfffffc14, 0xfffffd57, 0xfffffb87, 0xffff79d0, 0xffffff06, 0xffffff22, 0xffffe42f, 0xffff5502, 0x000006f8, 0xffffffc4, 0xffffc149, 0xffff744b, 0x000006c4, 0x00000002, 0xffffb4ba, 0xffffc8c6, 0x00000649, 0x00000011, 0xffff72c6, 0x00000aba, 0x00000259, 0x00000011, 0xffff6ea7, 0x000086ab, 0x00000174, 0x0000004f, 0xffffff02, 0x0000846c, 0x000000b1, 0x0000008d, 0x00007d04, 0x00007a9d, 0x00000022, 0x000001ca, 0x0000fc06, 0x000064be, 0x00000010, 0x00000a8e, 0x00007c08, 0x00003d2f, 0x0000000a, 0x000012b9, 0x00006856, 0x00001cc1, 0x00000004, 0x00001c1d, 0x00004440, 0x0000055b, 0xfffffffe, 0x00001dff, 0x00000ab9, 0x00000258, 0xfffffff3, 0x00001eac, 0xfffff4c8, 0x00000149, 0xffffffb9, 0xffffec11, 0xffffecad, 0x0000003a, 0xffffff2f, 0xffffe44f, 0xffffff04, 0xffffff03, 0xfffffe42, 0xffffe28d, 0x00000002, 0xfffffba0, 0xfffffd8b, 0xffffe1cb, 0xffffff04, 0xffffef53, 0xfffffd10, 0xffffe99b, 0xfffffe06, 0xffffd5cb, 0xfffffe0a, 0xfffff19c, 0xfffffa92, 0xffffad38, 0x00000004, 0xfffffbbf, 0xffffe26d, 0xffff8ef2, 0x000002fe, 0xfffffe89, 0xffffb9db, 0xffff82d8, 0x000002f8, 0xffffff5e, 0xffff82c7, 0xffffb5c9, 0x000002cc, 0xffffffcf, 0xffff4149, 0xfffff4c9, 0x0000014a, 0xffffffd7, 0xffff1b76, 0x00004a34, 0x000000df, 0x00000069, 0xffff82fc, 0x0000492d, 0x00000070, 0x000000fb, 0xffffff02, 0x00004705, 0x00000014, 0x00000336, 0x00007c08, 0x00003d2f, 0x0000000a, 0x000012b9, 0x0000fa0e, 0x000027be, 0x00000008, 0x000026c6, 0x0000e586, 0x00001337, 0x00000006, 0x00003c38, 0x0000c0bb, 0x00000360, 0x00000009, 0x000045eb, 0x000086aa, 0x00000173, 0x00000031, 0x000047f7, 0x00004a33, 0x000000de, 0x0000004b, 0xfffff3d7, 0x0000206c, 0x00000049, 0x0000003c, 0xffffc169, 0x000006f6, 0xffffffa5, 0xffffffc5, 0xffffb9fb, 0x000002fc, 0xfffffe6a, 0xffffff5a, 0xffffb88d, 0x00000102, 0xfffffb1e, 0xfffffe0a, 0xffffc5bd, 0xffffff08, 0xffffeed6, 0xfffffe08, 0xffffd8d6, 0xfffffa9d, 0xffffd839, 0xffffff06, 0xffffef72, 0xffffe1ab, 0xffffc4a2, 0x00000104, 0xfffffb3d, 0xffffb86d, 0xffffb9f3, 0x00000128, 0xfffffe35, 0xffff7bd4, 0xffffc15e, 0x00000147, 0xffffff3d, 0xffff5580, 0xffffecae, 0x0000003b, 0xffffff4d, 0xffff301f, 0x0000206d, 0x0000004a, 0x0000005a, 0xffff70f6, 0x00001fe0, 0x0000002f, 0x00000167, 0xffffec26, 0x00001eeb, 0x00000006, 0x000004e5, 0x00006856, 0x00001cc1, 0x00000004, 0x00001c1d, 0x0000e586, 0x00001337, 0x00000006, 0x00003c38, 0x0000d6f2, 0x00000ade, 0x00000008, 0x000063cb, 0x0000b77e, 0x000001c1, 0x00000014, 0x000079ae, 0x0000846b, 0x000000b0, 0x0000006f, 0x00008388, 0x0000492c, 0x0000006f, 0x000000dd, 0x000008cd, 0x00001fdf, 0x0000002e, 0x00000149, 0xffffb4da, 0x000006c2, 0xffffffe3, 0x00000148, 0xffff82e7, 0x000002f6, 0xffffff3f, 0x00000129, 0xffff7bf4, 0x00000126, 0xfffffe16, 0xffffff04, 0xffff8f8f, 0xffffff56, 0xfffffad0, 0xfffffe06, 0xffffad57, 0xfffffbd8, 0xfffff08a, 0xfffffe08, 0xffffd5ea, 0xffffe97b, 0xffffe85d, 0xffffff0a, 0xffffeef5, 0xffffc59d, 0xffffe230, 0xffffff58, 0xfffffaef, 0xffff8f6f, 0xffffe4ef, 0xffffffc2, 0xfffffe20, 0xffff79cf, 0xffffff05, 0xffffff04, 0xfffffe60, 0xffff5501, 0x000006f7, 0xffffffa6, 0xffffffe3, 0xffff744a, 0x000006c3, 0xffffffe4, 0x00000166, 0xffffc8c5, 0x00000648, 0xfffffff3, 0x0000055f, 0x00004440, 0x0000055b, 0xfffffffe, 0x00001dff, 0x0000c0bb, 0x00000360, 0x00000009, 0x000045eb, 0x0000b77e, 0x000001c1, 0x00000014, 0x000079ae, 0x0000a281, 0x0000004f, 0x00000047, 0x0000a18f, 0x00007a9c, 0x00000021, 0x000001ac, 0x0000b698, 0x00004704, 0x00000013, 0x00000318, 0x000041e0, 0x00001eea, 0x00000005, 0x000004c7, 0xffffc663, 0x00000647, 0xfffffff2, 0x00000541, 0xffff72e6, 0x000002ca, 0xffffffb0, 0x00000573, 0xffff4169, 0x00000145, 0xffffff1e, 0xfffffd7e, 0xffff55a0, 0xffffffc0, 0xfffffe01, 0xfffffb89, 0xffff79ef, 0xfffffd37, 0xfffffbf2, 0xfffffa94, 0xffffad57, 0xfffff17c, 0xfffffa67, 0xfffffa9f, 0xffffd858, 0xffffd8b6, 0xfffffa21, 0xfffffbda, 0xfffff0a9, 0xffffad37, 0xfffffc13, 0xfffffd39, 0xfffffc11, 0xffffad37, 0x00000003, 0xfffffba1, 0xfffffda9, 0xffff8ef1, 0x000002fd, 0xfffffe6b, 0xffffff78, 0xffff82d7, 0x000002f7, 0xffffff40, 0x00000147, 0xffffb5c8, 0x000002cb, 0xffffffb1, 0x00000591, 0x00000ab9, 0x00000258, 0xfffffff3, 0x00001eac, 0x000086aa, 0x00000173, 0x00000031, 0x000047f7, 0x0000846b, 0x000000b0, 0x0000006f, 0x00008388, 0x00007a9c, 0x00000021, 0x000001ac, 0x0000b698, 0x000064bd, 0x0000000f, 0x00000a70, 0x0000d667, 0x00003d2e, 0x00000009, 0x0000129b, 0x00006629, 0x00001cc0, 0x00000003, 0x00001bff, 0xffffe9f8, 0x0000055a, 0xfffffffd, 0x00001de1, 0xffff6ec7, 0x00000257, 0xfffffff2, 0x00001e8e, 0xffff1b96, 0x00000148, 0xffffffb8, 0xffffebf3, 0xffff303f, 0x00000039, 0xffffff2e, 0xffffe431, 0xffff5521, 0xffffff02, 0xfffffe41, 0xffffe26f, 0xffff8f11, 0xfffffb9f, 0xfffffd8a, 0xffffe1ad, 0xffffc4c1, 0xffffef52, 0xfffffd0f, 0xffffe97d, 0xffffe87c, 0xffffd5ca, 0xfffffe09, 0xfffff17e, 0xfffffa86, 0xffffd838, 0xffffff05, 0xffffef54, 0xfffffd2e, 0xffffc4a1, 0x00000103, 0xfffffb1f, 0xfffffe28, 0xffffb9f2, 0x00000127, 0xfffffe17, 0xffffff22, 0xffffc15d, 0x00000146, 0xffffff1f, 0xfffffd9c, 0xfffff4c8, 0x00000149, 0xffffffb9, 0xffffec11, 0x00004a33, 0x000000de, 0x0000004b, 0xfffff3d7, 0x0000492c, 0x0000006f, 0x000000dd, 0x000008cd, 0x00004704, 0x00000013, 0x00000318, 0x000041e0, 0x00003d2e, 0x00000009, 0x0000129b, 0x00006629, 0x000027bd, 0x00000007, 0x000026a8, 0x0000fa2e, 0x00001336, 0x00000005, 0x00003c1a, 0x00007c28, 0x0000035f, 0x00000008, 0x000045cd, 0xffffff22, 0x00000172, 0x00000030, 0x000047d9, 0xffff831c, 0x000000dd, 0x0000004a, 0xfffff3b9, 0xffff7116, 0x00000048, 0x0000003b, 0xffffc14b, 0xffff746a, 0xffffffa4, 0xffffffc4, 0xffffb9dd, 0xffff82f7, 0xfffffe69, 0xffffff59, 0xffffb86f, 0xffffba12, 0xfffffb1d, 0xfffffe09, 0xffffc59f, 0xffffe24f, 0xffffeed5, 0xfffffe07, 0xffffd8b8, 0xfffffa40, 0xfffff089, 0xfffffe07, 0xffffd5cc, 0xfffffe28, 0xffffe85c, 0xffffff09, 0xffffeed7, 0xfffffe26, 0xffffe22f, 0xffffff57, 0xfffffad1, 0xfffffe24, 0xffffe4ee, 0xffffffc1, 0xfffffe02, 0xfffffba7, 0xffffecad, 0x0000003a, 0xffffff2f, 0xffffe44f, 0x0000206c, 0x00000049, 0x0000003c, 0xffffc169, 0x00001fdf, 0x0000002e, 0x00000149, 0xffffb4da, 0x00001eea, 0x00000005, 0x000004c7, 0xffffc663, 0x00001cc0, 0x00000003, 0x00001bff, 0xffffe9f8, 0x00001336, 0x00000005, 0x00003c1a, 0x00007c28, 0x00000add, 0x00000007, 0x000063ad, 0x0000fc26, 0x000001c0, 0x00000013, 0x00007990, 0x00007d24, 0x000000af, 0x0000006e, 0x0000836a, 0xffffff22, 0x0000006e, 0x000000dc, 0x000008af, 0xffffec46, 0x0000002d, 0x00000148, 0xffffb4bc, 0xffffc8e5, 0xffffffe2, 0x00000147, 0xffff82c9, 0xffffb5e8, 0xffffff3e, 0x00000128, 0xffff7bd6, 0xffffc17d, 0xfffffe15, 0xffffff03, 0xffff8f71, 0xffffe50e, 0xfffffacf, 0xfffffe05, 0xffffad39, 0xfffffc32, 0xfffffbf1, 0xfffffa93, 0xffffad39, 0x00000022, 0xfffffa66, 0xfffffa9e, 0xffffd83a, 0xffffff24, 0xfffffa20, 0xfffffbd9, 0xfffff08b, 0xfffffe26, 0xfffffc12, 0xfffffd38, 0xfffffbf3, 0xfffffab2, 0xffffff04, 0xffffff03, 0xfffffe42, 0xffffe28d, 0x000006f6, 0xffffffa5, 0xffffffc5, 0xffffb9fb, 0x000006c2, 0xffffffe3, 0x00000148, 0xffff82e7, 0x00000647, 0xfffffff2, 0x00000541, 0xffff72e6, 0x0000055a, 0xfffffffd, 0x00001de1, 0xffff6ec7, 0x0000035f, 0x00000008, 0x000045cd, 0xffffff22, 0x000001c0, 0x00000013, 0x00007990, 0x00007d24, 0x0000004e, 0x00000046, 0x0000a171, 0x0000fc26, 0x00000020, 0x000001ab, 0x0000b67a, 0x00007c28, 0x00000012, 0x00000317, 0x000041c2, 0x00006876, 0x00000004, 0x000004c6, 0xffffc645, 0x00004460, 0xfffffff1, 0x00000540, 0xffff72c8, 0x00000ad9, 0xffffffaf, 0x00000572, 0xffff414b, 0xfffff4e8, 0xffffff1d, 0xfffffd7d, 0xffff5582, 0xffffeccd, 0xfffffe00, 0xfffffb88, 0xffff79d1, 0xffffff24, 0xfffffe40, 0xffffe26e, 0xffff8ef3, 0x0000031c, 0xfffffd89, 0xffffe1ac, 0xffffc4a3, 0x00000122, 0xfffffd0e, 0xffffe97c, 0xffffe85e, 0xffffff28, 0xfffffe08, 0xfffff17d, 0xfffffa68, 0xfffffabd, 0x00000002, 0xfffffba0, 0xfffffd8b, 0xffffe1cb, 0x000002fc, 0xfffffe6a, 0xffffff5a, 0xffffb88d, 0x000002f6, 0xffffff3f, 0x00000129, 0xffff7bf4, 0x000002ca, 0xffffffb0, 0x00000573, 0xffff4169, 0x00000257, 0xfffffff2, 0x00001e8e, 0xffff1b96, 0x00000172, 0x00000030, 0x000047d9, 0xffff831c, 0x000000af, 0x0000006e, 0x0000836a, 0xffffff22, 0x00000020, 0x000001ab, 0x0000b67a, 0x00007c28, 0x0000000e, 0x00000a6f, 0x0000d649, 0x0000fa2e, 0x00000008, 0x0000129a, 0x0000660b, 0x0000e5a6, 0x00000002, 0x00001bfe, 0xffffe9da, 0x0000c0db, 0xfffffffc, 0x00001de0, 0xffff6ea9, 0x000086ca, 0xfffffff1, 0x00001e8d, 0xffff1b78, 0x00004a53, 0xffffffb7, 0xffffebf2, 0xffff3021, 0x0000208c, 0xffffff2d, 0xffffe430, 0xffff5503, 0x00000716, 0xffffffc3, 0xffffb9dc, 0xffff82d9, 0x00000316, 0xffffff58, 0xffffb86e, 0xffffb9f4, 0x00000146, 0xfffffe08, 0xffffc59e, 0xffffe231, 0xffffff76, 0xfffffe06, 0xffffd8b7, 0xfffffa22, 0xfffffbf8, 0xffffff04, 0xffffef53, 0xfffffd10, 0xffffe99b, 0x00000102, 0xfffffb1e, 0xfffffe0a, 0xffffc5bd, 0x00000126, 0xfffffe16, 0xffffff04, 0xffff8f8f, 0x00000145, 0xffffff1e, 0xfffffd7e, 0xffff55a0, 0x00000148, 0xffffffb8, 0xffffebf3, 0xffff303f, 0x000000dd, 0x0000004a, 0xfffff3b9, 0xffff7116, 0x0000006e, 0x000000dc, 0x000008af, 0xffffec46, 0x00000012, 0x00000317, 0x000041c2, 0x00006876, 0x00000008, 0x0000129a, 0x0000660b, 0x0000e5a6, 0x00000006, 0x000026a7, 0x0000fa10, 0x0000d712, 0x00000004, 0x00003c19, 0x00007c0a, 0x0000b79e, 0x00000007, 0x000045cc, 0xffffff04, 0x0000848b, 0x0000002f, 0x000047d8, 0xffff82fe, 0x0000494c, 0x00000049, 0xfffff3b8, 0xffff70f8, 0x00001fff, 0x0000003a, 0xffffc14a, 0xffff744c, 0x000006e2, 0x00000146, 0xffff82c8, 0xffffb5ca, 0x000002ea, 0x00000127, 0xffff7bd5, 0xffffc15f, 0x00000165, 0xffffff02, 0xffff8f70, 0xffffe4f0, 0xffffffe0, 0xfffffe04, 0xffffad38, 0xfffffc14, 0xfffffd57, 0xfffffe06, 0xffffd5cb, 0xfffffe0a, 0xfffff19c, 0xffffff08, 0xffffeed6, 0xfffffe08, 0xffffd8d6, 0xffffff56, 0xfffffad0, 0xfffffe06, 0xffffad57, 0xffffffc0, 0xfffffe01, 0xfffffb89, 0xffff79ef, 0x00000039, 0xffffff2e, 0xffffe431, 0xffff5521, 0x00000048, 0x0000003b, 0xffffc14b, 0xffff746a, 0x0000002d, 0x00000148, 0xffffb4bc, 0xffffc8e5, 0x00000004, 0x000004c6, 0xffffc645, 0x00004460, 0x00000002, 0x00001bfe, 0xffffe9da, 0x0000c0db, 0x00000004, 0x00003c19, 0x00007c0a, 0x0000b79e, 0x00000006, 0x000063ac, 0x0000fc08, 0x0000a2a1, 0x00000012, 0x0000798f, 0x00007d06, 0x00007abc, 0x0000006d, 0x00008369, 0xffffff04, 0x00004724, 0x000000db, 0x000008ae, 0xffffec28, 0x00001f0a, 0x00000147, 0xffffb4bb, 0xffffc8c7, 0x00000667, 0x0000053f, 0xffff72c7, 0x00000abb, 0x00000277, 0x00000571, 0xffff414a, 0xfffff4ca, 0x00000168, 0xfffffd7c, 0xffff5581, 0xffffecaf, 0x00000059, 0xfffffb87, 0xffff79d0, 0xffffff06, 0xffffff22, 0xfffffa92, 0xffffad38, 0x00000004, 0xfffffbbf, 0xfffffa9d, 0xffffd839, 0xffffff06, 0xffffef72, 0xfffffbd8, 0xfffff08a, 0xfffffe08, 0xffffd5ea, 0xfffffd37, 0xfffffbf2, 0xfffffa94, 0xffffad57, 0xffffff02, 0xfffffe41, 0xffffe26f, 0xffff8f11, 0xffffffa4, 0xffffffc4, 0xffffb9dd, 0xffff82f7, 0xffffffe2, 0x00000147, 0xffff82c9, 0xffffb5e8, 0xfffffff1, 0x00000540, 0xffff72c8, 0x00000ad9, 0xfffffffc, 0x00001de0, 0xffff6ea9, 0x000086ca, 0x00000007, 0x000045cc, 0xffffff04, 0x0000848b, 0x00000012, 0x0000798f, 0x00007d06, 0x00007abc, 0x00000045, 0x0000a170, 0x0000fc08, 0x000064dd, 0x000001aa, 0x0000b679, 0x00007c0a, 0x00003d4e, 0x00000316, 0x000041c1, 0x00006858, 0x00001ce0, 0x000004c5, 0xffffc644, 0x00004442, 0x0000057a, 0x00001ddf, 0xffff6ea8, 0x000086ac, 0x00000192, 0x00001e8c, 0xffff1b77, 0x00004a35, 0x000000fd, 0xffffebf1, 0xffff3020, 0x0000206e, 0x00000068, 0xffffe42f, 0xffff5502, 0x000006f8, 0xffffffc4, 0xffffe26d, 0xffff8ef2, 0x000002fe, 0xfffffe89, 0xffffe1ab, 0xffffc4a2, 0x00000104, 0xfffffb3d, 0xffffe97b, 0xffffe85d, 0xffffff0a, 0xffffeef5, 0xfffff17c, 0xfffffa67, 0xfffffa9f, 0xffffd858, 0xfffffb9f, 0xfffffd8a, 0xffffe1ad, 0xffffc4c1, 0xfffffe69, 0xffffff59, 0xffffb86f, 0xffffba12, 0xffffff3e, 0x00000128, 0xffff7bd6, 0xffffc17d, 0xffffffaf, 0x00000572, 0xffff414b, 0xfffff4e8, 0xfffffff1, 0x00001e8d, 0xffff1b78, 0x00004a53, 0x0000002f, 0x000047d8, 0xffff82fe, 0x0000494c, 0x0000006d, 0x00008369, 0xffffff04, 0x00004724, 0x000001aa, 0x0000b679, 0x00007c0a, 0x00003d4e, 0x00000a6e, 0x0000d648, 0x0000fa10, 0x000027dd, 0x00001299, 0x0000660a, 0x0000e588, 0x00001356, 0x00001bfd, 0xffffe9d9, 0x0000c0bd, 0x0000037f, 0x000045cb, 0xffffff03, 0x0000846d, 0x000000cf, 0x000047d7, 0xffff82fd, 0x0000492e, 0x0000008e, 0xfffff3b7, 0xffff70f7, 0x00001fe1, 0x0000004d, 0xffffc149, 0xffff744b, 0x000006c4, 0x00000002, 0xffffb9db, 0xffff82d8, 0x000002f8, 0xffffff5e, 0xffffb86d, 0xffffb9f3, 0x00000128, 0xfffffe35, 0xffffc59d, 0xffffe230, 0xffffff58, 0xfffffaef, 0xffffd8b6, 0xfffffa21, 0xfffffbda, 0xfffff0a9, 0xffffef52, 0xfffffd0f, 0xffffe97d, 0xffffe87c, 0xfffffb1d, 0xfffffe09, 0xffffc59f, 0xffffe24f, 0xfffffe15, 0xffffff03, 0xffff8f71, 0xffffe50e, 0xffffff1d, 0xfffffd7d, 0xffff5582, 0xffffeccd, 0xffffffb7, 0xffffebf2, 0xffff3021, 0x0000208c, 0x00000049, 0xfffff3b8, 0xffff70f8, 0x00001fff, 0x000000db, 0x000008ae, 0xffffec28, 0x00001f0a, 0x00000316, 0x000041c1, 0x00006858, 0x00001ce0, 0x00001299, 0x0000660a, 0x0000e588, 0x00001356, 0x000026a6, 0x0000fa0f, 0x0000d6f4, 0x00000afd, 0x00003c18, 0x00007c09, 0x0000b780, 0x000001e0, 0x0000798e, 0x00007d05, 0x00007a9e, 0x00000040, 0x00008368, 0xffffff03, 0x00004706, 0x00000032, 0x000008ad, 0xffffec27, 0x00001eec, 0x00000024, 0xffffb4ba, 0xffffc8c6, 0x00000649, 0x00000011, 0xffff82c7, 0xffffb5c9, 0x000002cc, 0xffffffcf, 0xffff7bd4, 0xffffc15e, 0x00000147, 0xffffff3d, 0xffff8f6f, 0xffffe4ef, 0xffffffc2, 0xfffffe20, 0xffffad37, 0xfffffc13, 0xfffffd39, 0xfffffc11, 0xffffd5ca, 0xfffffe09, 0xfffff17e, 0xfffffa86, 0xffffeed5, 0xfffffe07, 0xffffd8b8, 0xfffffa40, 0xfffffacf, 0xfffffe05, 0xffffad39, 0xfffffc32, 0xfffffe00, 0xfffffb88, 0xffff79d1, 0xffffff24, 0xffffff2d, 0xffffe430, 0xffff5503, 0x00000716, 0x0000003a, 0xffffc14a, 0xffff744c, 0x000006e2, 0x00000147, 0xffffb4bb, 0xffffc8c7, 0x00000667, 0x000004c5, 0xffffc644, 0x00004442, 0x0000057a, 0x00001bfd, 0xffffe9d9, 0x0000c0bd, 0x0000037f, 0x00003c18, 0x00007c09, 0x0000b780, 0x000001e0, 0x000063ab, 0x0000fc07, 0x0000a283, 0x0000006e, }; const unsigned kExpectedCount_NEON_sdot_4S = 361; #endif // VIXL_SIM_SDOT_4S_TRACE_AARCH64_H_
49.836228
80
0.791924
b2fecf5fb4e7af5d43acd4043c21da474ffbd59c
373
h
C
Source/MiniSolarSystem/Public/RidgidNoiseFilter.h
setg2002/SpaceGame
7e2c78b077e9331aec4310f6cfc9e309c2c6989b
[ "MIT" ]
1
2021-12-29T18:05:35.000Z
2021-12-29T18:05:35.000Z
Source/MiniSolarSystem/Public/RidgidNoiseFilter.h
setg2002/SpaceGame
7e2c78b077e9331aec4310f6cfc9e309c2c6989b
[ "MIT" ]
null
null
null
Source/MiniSolarSystem/Public/RidgidNoiseFilter.h
setg2002/SpaceGame
7e2c78b077e9331aec4310f6cfc9e309c2c6989b
[ "MIT" ]
null
null
null
// Copyright Soren Gilbertson #pragma once #include "CoreMinimal.h" #include "INoiseFilter.h" #include "NoiseSettings.h" /** * */ class MINISOLARSYSTEM_API RidgidNoiseFilter : public INoiseFilter { public: RidgidNoiseFilter(FRidgidNoiseSettings settings); ~RidgidNoiseFilter(); FRidgidNoiseSettings Settings; virtual float Evaluate(FVector point) override; };
16.217391
65
0.774799
19a049a4a1f7b5c7b6229078255dd04950bf904d
2,529
h
C
CnUtils.h
sacnorthern/Arduino-CnUtils
289705abb6b646d047e9a8678eb70c0e9f5d1ffe
[ "CC0-1.0" ]
null
null
null
CnUtils.h
sacnorthern/Arduino-CnUtils
289705abb6b646d047e9a8678eb70c0e9f5d1ffe
[ "CC0-1.0" ]
null
null
null
CnUtils.h
sacnorthern/Arduino-CnUtils
289705abb6b646d047e9a8678eb70c0e9f5d1ffe
[ "CC0-1.0" ]
null
null
null
/*** CrunchyNoodles Utilities and Assorted Sundry Items for Arduino ***/ /*** Brian Witt *** bwitt@value.net *** November 2013 ***/ /*** License: this file in the public domain. ***/ #ifndef _CRUNCHYNOODLES_UTILS_H #define _CRUNCHYNOODLES_UTILS_H #include <Arduino.h> // -------------------------- Magical Definitions -------------------------- /*** Return number of elements in an array. */ #define NELEMENTS(_ary) (sizeof(_ary) / sizeof(_ary[0])) /*** Convert a pointer into an integeral type. */ #define PTR2INT(_p) ( (char *)(_p) - (char *)0 ) // A few boards don't have 'LED_BUILTIN', use Firmata as second-best source. #if defined (__AVR_ATmega32U4__) // 32U4 of Leonardo and BBLeo need assist. #define LED_BUILTIN VERSION_BLINK_PIN #endif /*** A C#-like Key and Value pairing. */ template <class TKey, class TValue> struct KeyValuePair { TKey key; TValue value; }; // -------------------------- Magic C++ Functions -------------------------- /*** * Allow Print-things, e.g. HardwareSerial, to print a prefix string, a number, * and a suffix-string. * * I would love if C++ had extension classes like C#. I looked at IO stream * overloads but could not get it to work. I want to see this: * Serial.print3( "open==", 5, "==close" ); * */ template< typename MiddleType > void print3( Print& p, const char * first, MiddleType val, const char * last ); // --------------------------- Helpers Functions --------------------------- /*** * A small-value version of map() using 'uint8_t' instead of 'long' data types. */ static inline uint8_t map( uint8_t value, uint8_t fromLow, uint8_t fromHigh, uint8_t toLow, uint8_t toHigh ) { return ((uint16_t)value - fromLow) * ((uint16_t)toHigh - toLow) / ((uint16_t)fromHigh - fromLow) + toLow; } //----------------------- // Get the available ram size, i.e. memory not yet claimed by malloc(). // This is measurement of current "top of heap". If there are holes inside // the heap, then more than freeRam() can be allocated. //----------------------- extern size_t freeRam(); extern void printHexWidth( Print &outs, uint16_t hexValue, uint8_t width ); extern void dumpEE( Print &outs, uint16_t eeOffset, uint16_t size ); /*** Read CPU's signature bytes, store to buffer, returns actual stored count as return value */ extern int8_t getCpuSignatureBytes( uint8_t * outs, uint8_t size_outs ); #define VENDOR_ID_ATMEL 0x1114 #define VENDOR_ID_FREESCALE _needs_a_value_ #endif
32.423077
109
0.630684
bf50577f37cf5c279fa879611bfcbe6c21bdbb3f
611
h
C
src/GateNetworks.Application/command.h
jurajtrappl/Gate-networks
84c15684124a99bc16cf8ca20d1d39fc7c31b5b1
[ "MIT" ]
null
null
null
src/GateNetworks.Application/command.h
jurajtrappl/Gate-networks
84c15684124a99bc16cf8ca20d1d39fc7c31b5b1
[ "MIT" ]
null
null
null
src/GateNetworks.Application/command.h
jurajtrappl/Gate-networks
84c15684124a99bc16cf8ca20d1d39fc7c31b5b1
[ "MIT" ]
null
null
null
#pragma once #include "logic/tri_state.h" #include <string> #include <vector> namespace gate_networks::application { /// <summary> /// Wrapper over standard input user entered inputs for the gate network to evaluate for. /// </summary> class Command { public: Command(const std::string& tokens, size_t inputs_count); /// <returns>tri_state representation of command input.</returns> const std::vector<core::logic::Tri_state>& values() const; private: /// <summary> /// Processed tri state representation of command input. /// </summary> std::vector<core::logic::Tri_state> values_; }; }
24.44
90
0.708674
bd04e72c620576a7b0b8b07c2727fa5d748a667f
581
c
C
src/lcd_font.c
rootlocal/stm32-nokia_lcd_5110
6e910f13552c8299b9e0afa523ee036073ac4788
[ "BSD-3-Clause" ]
null
null
null
src/lcd_font.c
rootlocal/stm32-nokia_lcd_5110
6e910f13552c8299b9e0afa523ee036073ac4788
[ "BSD-3-Clause" ]
null
null
null
src/lcd_font.c
rootlocal/stm32-nokia_lcd_5110
6e910f13552c8299b9e0afa523ee036073ac4788
[ "BSD-3-Clause" ]
null
null
null
#include "lcd_font.h" #include "font6x8_bold.h" #include "font_6x8_rus.h" LCD_fonts lcd_font; void LCD_setFONT(LCD_fonts font) { lcd_font = font; } LCD_fonts LCD_getFont(void) { if (lcd_font == 0) { lcd_font = font_6x8_rus; } return lcd_font; } uint8_t LCD_getChar(uint8_t cr, uint8_t line) { uint8_t chars; switch (LCD_getFont()) { case font_6x8_bold: chars = font_6X8_bold[cr][line]; break; case font_6x8_rus: chars = font_6X8_rus[cr][line]; break; } return chars; }
17.088235
47
0.60241
44203984f162f455272905ba5f53fb7fcd3dafc5
2,169
h
C
src/modules/ringtone.h
webosce/audiod-pro
dc4aa3b3cc8aca4338b6c3227f59e161afde7dec
[ "Apache-2.0" ]
null
null
null
src/modules/ringtone.h
webosce/audiod-pro
dc4aa3b3cc8aca4338b6c3227f59e161afde7dec
[ "Apache-2.0" ]
null
null
null
src/modules/ringtone.h
webosce/audiod-pro
dc4aa3b3cc8aca4338b6c3227f59e161afde7dec
[ "Apache-2.0" ]
1
2018-09-29T04:58:10.000Z
2018-09-29T04:58:10.000Z
// Copyright (c) 2012-2018 LG Electronics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #ifndef _RINGTONE_H_ #define _RINGTONE_H_ #include <lunaservice.h> #include "scenario.h" class RingtoneScenarioModule : public ScenarioModule { public: RingtoneScenarioModule(); RingtoneScenarioModule(int default_volume); ~RingtoneScenarioModule() {}; static void RingtoneInterfaceExit(); virtual bool setMuted (bool muted); virtual void onSinkChanged(EVirtualSink sink, EControlEvent event,ESinkType p_eSinkType); virtual void programControlVolume(); virtual void programMuted(); //! eringtones, ealarm, ealerts, enotifications, ecalendar virtual void programRingToneVolumes(bool ramp); //! for private use only. Public because global callbacks need them... :-( void SCOBeepAlarm(int runningCount = 0); //! Returns true if a ringtone or an alarm was muted virtual bool muteIfRinging(); //! Silence ringtone & vibration without muting module void silenceRingtone(); //! Calculate volume adjusted for current situation int getAdjustedRingtoneVolume(bool alertStarting = false) const; // get/set the ringtone with vibration bool getRingtoneVibration(); void setRingtoneVibration(bool enable); bool checkRingtoneVibration(); protected : Volume mRingtoneVolume; bool mRingtoneMuted; bool mSCOBeepAlarmRunning; private: bool mIsRingtoneCombined; }; RingtoneScenarioModule * getRingtoneModule(); void RingtoneCancelVibrate (); #endif // _RINGTONE_H_
28.539474
96
0.722914
9c2971e85c651600c67595a3247600e59403c12f
5,945
c
C
third_party/omr/thread/common/omrthreadnuma.c
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/thread/common/omrthreadnuma.c
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/thread/common/omrthreadnuma.c
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright (c) 1991, 2016 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ * or the Apache License, Version 2.0 which accompanies this distribution and * is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following * Secondary Licenses when the conditions for such availability set * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU * General Public License, version 2 with the GNU Classpath * Exception [1] and GNU General Public License, version 2 with the * OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] http://openjdk.java.net/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception *******************************************************************************/ /** * @file * @ingroup Thread * @brief NUMA support for Thread library. */ #include "omrcfg.h" #include "threaddef.h" /** * Loads the necessary functions for NUMA support from the OS's dynamic library for NUMA. * This will initialize the lib->libNumaHandle and lib->numaAvailable fields if OMR_PORT_NUMA_SUPPORT * is enabled. * * This function must only be called *once*. It is called from omrthread_init(). */ void omrthread_numa_init(omrthread_library_t lib) { } /** * Closes the dynamic library for NUMA. Should only be called from omrthread_shutdown(). */ void omrthread_numa_shutdown(omrthread_library_t lib) { } /** * Sets the NUMA enabled status. * This applies to the entire process. */ void omrthread_numa_set_enabled(BOOLEAN enabled) { } /** * Return the highest NUMA node ID available to the process. * The first node is always identified as 1, as 0 is used to indicate no affinity. * * This function should be called to test the availability of NUMA <em>before</em> * calling any of the other NUMA functions. * * If NUMA is not enabled or supported this will always return 0. * * @return The highest NUMA node ID available to the process. 0 if no affinity, or NUMA not enabled. */ uintptr_t omrthread_numa_get_max_node(void) { /* This is the common function, just return 0 */ return 0; } /** * This performs exactly the same operation as omrthread_numa_set_node_affinity, however it does *not* * lock the thread. This should only be called when a lock on a thread is already obtained. * * @return Returns 0 on success, and -1 if we failed to set the thread's affinity. Note * that this function will return 0 even if NUMA is not available. Use omrthread_numa_get_max_node() * to test for the availability of NUMA. * * @see omrthread_numa_set_node_affinity(omrthread_t thread, const uintptr_t *nodeList, uintptr_t nodeCount, uint32_t flags) */ intptr_t omrthread_numa_set_node_affinity_nolock(omrthread_t thread, const uintptr_t *nodeList, uintptr_t nodeCount, uint32_t flags) { return 0; } /** * Set the affinity for the specified thread so that it runs only (or preferentially) on * processors associated with the specified NUMA nodes contained in the numaNodes array (of nodeCount length). * This may be called before a thread is started or once it is active. * * On Linux, the requested set of CPUs is intersected with the initial CPU affinity of the process. * The J9THREAD_NUMA_OVERRIDE_DEFAULT_AFFINITY flag overrides this behaviour on Linux; * it has no effect on other operating systems. * * Note that in the case that this function is called on a thread that is not yet started, * setting the affinity will be deferred until the thread is started. This function will still * return 0, indicating success, however there is no way to tell if the affinity was successfully * set once the thread is actually started. * * @param[in] thread The thread to be modified. Can be any arbitrary omrthread_t. * @param[in] numaNodes The array of node indexes with which to associate the given thread, where 1 is the first node. * @param[in] nodeCount The number of nodes in the numaNodes array. (0 indicates no affinity) * @param[in] flags control the behavior of the function * * @return 0 on success, -1 on failure. Note that this function will return 0 even if NUMA is not available. * Use omrthread_numa_get_max_node() to test for the availability of NUMA. */ intptr_t omrthread_numa_set_node_affinity(omrthread_t thread, const uintptr_t *numaNodes, uintptr_t nodeCount, uint32_t flags) { /* This is the common function, just return 0 */ return 0; } /** * Determine what the NUMA node affinity is for the specified thread. * * @param[in] thread - the thread to be queried. Can be any arbitrary omrthread_t * @param[out] numaNodes The array of node indexes with which the given thread is associated, where 1 is the first node. * @param[in/out] nodeCount The number of nodes in the numaNodes array, on input, and the number of nodes with which this thread is associated, on output. The minimum of these two values will be the number of entries populated in the numaNodes array (other entries will be untouched). * * @return 0 on success, non-zero if affinity cannot be determined. Note that this function will return 0 even if * NUMA is not available. Use omrthread_numa_get_max_node() to test for the availability of NUMA. */ intptr_t omrthread_numa_get_node_affinity(omrthread_t thread, uintptr_t *numaNodes, uintptr_t *nodeCount) { /* This is the common function, just return 0 */ /* since we know about 0 nodes, don't touch anything in the numaNodes array */ *nodeCount = 0; return 0; } uintptr_t omrthread_numa_get_current_node(){ return 0; }
40.442177
285
0.737931
33ffe3ae658bd4db63c8cd5ee7b61f7e246a58e4
637
h
C
Classes/I7CoreTextViewController.h
jonasschnelli/I7CoreTextExample
37e730740295a4c326daf8beaa7f84c68f871a4b
[ "BSD-4-Clause", "MIT" ]
6
2015-11-05T16:23:56.000Z
2019-02-11T00:49:14.000Z
Classes/I7CoreTextViewController.h
jonasschnelli/I7CoreTextExample
37e730740295a4c326daf8beaa7f84c68f871a4b
[ "BSD-4-Clause", "MIT" ]
null
null
null
Classes/I7CoreTextViewController.h
jonasschnelli/I7CoreTextExample
37e730740295a4c326daf8beaa7f84c68f871a4b
[ "BSD-4-Clause", "MIT" ]
2
2015-11-11T03:09:27.000Z
2021-09-13T09:41:47.000Z
// // I7CoreTextViewController.h // CoreTextExample // // Created by Jonas Schnelli on 19.05.10. // Copyright 2010 include7 AG. All rights reserved. // #import <UIKit/UIKit.h> #import "I7CoreTextView.h" @interface I7CoreTextViewController : UIViewController { I7CoreTextView *coreTextView; UIScrollView *scrollView; UIView *loadingView; } @property (nonatomic, retain) IBOutlet I7CoreTextView *coreTextView; @property (nonatomic, retain) IBOutlet UIScrollView *scrollView; @property (nonatomic, retain) IBOutlet UIView *loadingView; - (IBAction)fontSizeDidChange:(id)sender; - (IBAction)textTypeDidChange:(id)sender; @end
22.75
68
0.767661
41e297cd88125502ccb90dd2136d2b6d12400201
292
c
C
src/graphics.c
ZedZull/goto_engine
c409f2322ee50be8460d602ebb52276432da0879
[ "MIT" ]
1
2016-03-27T03:08:59.000Z
2016-03-27T03:08:59.000Z
src/graphics.c
ZedZull/goto_engine
c409f2322ee50be8460d602ebb52276432da0879
[ "MIT" ]
null
null
null
src/graphics.c
ZedZull/goto_engine
c409f2322ee50be8460d602ebb52276432da0879
[ "MIT" ]
null
null
null
static void graphics_init(int width, int height) { glViewport(0, 0, width, height); glClearColor((100.0f / 255.0f), (149.0f / 255.0f), (237.0f / 255.0f), 1.0f); } static void graphics_begin_frame(void) { glClear(GL_COLOR_BUFFER_BIT); } static void graphics_end_frame(void) { }
22.461538
80
0.684932
cb0ddf69c498c1eb73ee25c7ad3d17c7c49dfbce
1,926
h
C
src/lib/flist.h
tech-niche-biz/bacula-9.4.4
5e74458b612354f6838652dac9ddff94be1bbce6
[ "BSD-2-Clause" ]
null
null
null
src/lib/flist.h
tech-niche-biz/bacula-9.4.4
5e74458b612354f6838652dac9ddff94be1bbce6
[ "BSD-2-Clause" ]
null
null
null
src/lib/flist.h
tech-niche-biz/bacula-9.4.4
5e74458b612354f6838652dac9ddff94be1bbce6
[ "BSD-2-Clause" ]
null
null
null
/* Bacula(R) - The Network Backup Solution Copyright (C) 2000-2017 Kern Sibbald The original author of Bacula is Kern Sibbald, with contributions from many others, a complete list can be found in the file AUTHORS. You may use this file and others of this release according to the license defined in the LICENSE file, which includes the Affero General Public License, v3.0 ("AGPLv3") and some additional permissions and terms pursuant to its AGPLv3 Section 7. This notice must be preserved when any source code is conveyed and/or propagated. Bacula(R) is a registered trademark of Kern Sibbald. */ /* * Kern Sibbald, August 2014. */ /* Second arg of init */ enum { owned_by_flist = true, not_owned_by_flist = false }; /* * Fifo list -- derived from alist */ class flist : public SMARTALLOC { void **items; int num_items; int max_items; int add_item; int get_item; bool own_items; public: flist(int num = 10, bool own=false); ~flist(); void init(int num = 10, bool own=false); bool queue(void *item); void *dequeue(); bool empty() const; bool full() const; int size() const; void destroy(); }; inline bool flist::empty() const { return num_items == 0; } inline bool flist::full() const { return num_items == max_items; } /* * This allows us to do explicit initialization, * allowing us to mix C++ classes inside malloc'ed * C structures. Define before called in constructor. */ inline void flist::init(int num, bool own) { items = NULL; num_items = 0; max_items = num; own_items = own; add_item = 0; get_item = 0; items = (void **)malloc(max_items * sizeof(void *)); } /* Constructor */ inline flist::flist(int num, bool own) { init(num, own); } /* Destructor */ inline flist::~flist() { destroy(); } /* Current size of list */ inline int flist::size() const { return num_items; }
20.0625
73
0.667705
3b120e19325382589b4a14f037017d644297b3ad
2,106
h
C
crypto32/default.h
ab300819/applied-cryptography
3fddc4cda2e1874e978608259034d36c60a4dbba
[ "MIT", "Unlicense" ]
1
2021-04-17T05:01:00.000Z
2021-04-17T05:01:00.000Z
crypto32/default.h
ab300819/applied-cryptography
3fddc4cda2e1874e978608259034d36c60a4dbba
[ "MIT", "Unlicense" ]
null
null
null
crypto32/default.h
ab300819/applied-cryptography
3fddc4cda2e1874e978608259034d36c60a4dbba
[ "MIT", "Unlicense" ]
null
null
null
#ifndef CRYPTOPP_DEFAULT_H #define CRYPTOPP_DEFAULT_H #include "sha.h" #include "hmac.h" #include "des.h" #include "filters.h" NAMESPACE_BEGIN(CryptoPP) typedef DES_EDE2_Encryption Default_ECB_Encryption; typedef DES_EDE2_Decryption Default_ECB_Decryption; typedef SHA DefaultHashModule; typedef HMAC<DefaultHashModule> DefaultMAC; class DefaultEncryptor : public Filter { public: DefaultEncryptor(const char *passphrase, BufferedTransformation *outQueue = NULL); void Detach(BufferedTransformation *newOut = NULL); BufferedTransformation *AttachedTransformation(); void Put(byte inByte); void Put(const byte *inString, unsigned int length); private: member_ptr<Default_ECB_Encryption> m_cipher; }; class DefaultDecryptor : public FilterWithBufferedInput { public: DefaultDecryptor(const char *passphrase, BufferedTransformation *outQueue = NULL); void Detach(BufferedTransformation *newOut = NULL); BufferedTransformation *AttachedTransformation(); // MAC_GOOD and MAC_BAD are not used in this class but are defined for DefaultDecryptorWithMAC enum State {WAITING_FOR_KEYCHECK, KEY_GOOD, KEY_BAD, MAC_GOOD, MAC_BAD}; State CurrentState() const {return m_state;} protected: void FirstPut(const byte *inString); void NextPut(const byte *inString, unsigned int length); void LastPut(const byte *inString, unsigned int length); State m_state; private: void CheckKey(const byte *salt, const byte *keyCheck); SecBlock<char> m_passphrase; member_ptr<Default_ECB_Decryption> m_cipher; }; class DefaultEncryptorWithMAC : public DefaultEncryptor { public: DefaultEncryptorWithMAC(const char *passphrase, BufferedTransformation *outQueue = NULL); void Put(byte inByte); void Put(const byte *inString, unsigned int length); void InputFinished(); private: member_ptr<DefaultMAC> m_mac; }; class DefaultDecryptorWithMAC : public DefaultDecryptor { public: DefaultDecryptorWithMAC(const char *passphrase, BufferedTransformation *outQueue = NULL); void Detach(BufferedTransformation *newOut = NULL); BufferedTransformation *AttachedTransformation(); }; NAMESPACE_END #endif
26
95
0.802944
278be404436abc7ff2feb74e843ed379ef40baa8
325
c
C
chapter_01/1-24.c
ryo-utsunomiya/answers_to_c_programming_language
b5a4ee2e2ef4c8273af3a2276a3a5f7a66012331
[ "MIT" ]
null
null
null
chapter_01/1-24.c
ryo-utsunomiya/answers_to_c_programming_language
b5a4ee2e2ef4c8273af3a2276a3a5f7a66012331
[ "MIT" ]
null
null
null
chapter_01/1-24.c
ryo-utsunomiya/answers_to_c_programming_language
b5a4ee2e2ef4c8273af3a2276a3a5f7a66012331
[ "MIT" ]
null
null
null
/** * Exercise 1-24 * * Write a program to check a C program for rudimentary syntax errors like unbalanced parentheses, brackets and braces. * Don’t forget about quotes, both single and double, escape sequences, and comments. */ #include <stdio.h> int main(void) { printf("Not implemented yet!"); return 0; }
21.666667
119
0.701538
5f73b260593d04097c79a24a1fca3a1fb26b3cca
7,964
c
C
spike/shared/lib/io-flush.c
Changes729/c_cpp_project_template
82857dbc3f45518a0cb02fef40f31ff8bfb7bb4c
[ "RSA-MD" ]
1
2020-01-28T09:02:06.000Z
2020-01-28T09:02:06.000Z
spike/shared/lib/io-flush.c
Changes729/c_cpp_project_template
82857dbc3f45518a0cb02fef40f31ff8bfb7bb4c
[ "RSA-MD" ]
10
2021-04-24T11:54:45.000Z
2021-05-13T02:16:01.000Z
spike/shared/lib/io-flush.c
Changes729/c_cpp_project_template
82857dbc3f45518a0cb02fef40f31ff8bfb7bb4c
[ "RSA-MD" ]
1
2020-01-28T09:02:08.000Z
2020-01-28T09:02:08.000Z
/** See a brief introduction (right-hand button) */ #include "io-flush.h" /* Private include -----------------------------------------------------------*/ #include <assert.h> #include <stdlib.h> #include <sys/epoll.h> #include <sys/poll.h> #include <sys/select.h> #include <unistd.h> #include "glike-list.h" /* Private namespace ---------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ #define POSSESSING__ON(io_list_head) (io_list_head).possessing = true #define POSSESSING_OFF(io_list_head) (io_list_head).possessing = false #define IS_POSSESSING(io_list_head) (io_list_head).possessing == true /* Private typedef -----------------------------------------------------------*/ typedef struct __io_list_head { list_head_t head; size_t count; bool possessing; } io_list_head_t; typedef struct { fd_desc_t pkg; fd_callback_t callback; void* user_data; bool remove; } io_node_t; /* Private template ----------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ static io_list_head_t io_list_head; static int _epoll_fd = -1; /* Private function prototypes -----------------------------------------------*/ static struct timeval _translate_ms(uint32_t ms); static void _io_list_after_loop(); static inline void _io_list_mark_remove(io_node_t*); static inline void _io_list_remove_node(list_t*); /* Private function ----------------------------------------------------------*/ bool io_epoll_fd_init() { assert(_epoll_fd == -1); _epoll_fd = epoll_create1(0); return _epoll_fd != -1; } void io_epoll_fd_deinit() { if(_epoll_fd != -1) close(_epoll_fd); _epoll_fd = -1; } void io_flush_select(uint32_t ms) { struct timeval tv = _translate_ms(ms); fd_set descriptors_read; fd_set descriptors_write; fd_set descriptors_error; int highest_fd = -1; FD_ZERO(&descriptors_read); FD_ZERO(&descriptors_write); FD_ZERO(&descriptors_error); // set fds. io_node_t* node; list_foreach_data(node, &io_list_head.head) { if(node->pkg.flag & IO_NOTICE_READ) { FD_SET(node->pkg.fd, &descriptors_read); } if(node->pkg.flag & IO_NOTICE_WRITE) { FD_SET(node->pkg.fd, &descriptors_write); } if(node->pkg.flag & IO_NOTICE_ERR) { FD_SET(node->pkg.fd, &descriptors_error); } if(node->pkg.fd > highest_fd) { highest_fd = node->pkg.fd; } } // select select(highest_fd + 1, &descriptors_read, &descriptors_write, &descriptors_error, &tv); // map fds. POSSESSING__ON(io_list_head); list_foreach_data(node, &io_list_head.head) { fd_desc_t desc = {node->pkg.fd, 0}; if(node->remove) continue; if(FD_ISSET(node->pkg.fd, &descriptors_read)) desc.flag |= IO_NOTICE_READ; if(FD_ISSET(node->pkg.fd, &descriptors_write)) desc.flag |= IO_NOTICE_WRITE; if(FD_ISSET(node->pkg.fd, &descriptors_error)) desc.flag |= IO_NOTICE_ERR; node->callback(node->user_data, desc); } POSSESSING_OFF(io_list_head); _io_list_after_loop(); } void io_flush_poll(uint32_t ms) { struct pollfd fds[io_list_head.count]; short cond = 0; size_t index = 0; // set fds. io_node_t* node; list_foreach_data(node, &io_list_head.head) { if(node->pkg.flag & IO_NOTICE_READ) cond |= POLLIN; if(node->pkg.flag & IO_NOTICE_WRITE) cond |= POLLOUT; if(node->pkg.flag & IO_NOTICE_ERR) cond |= POLLERR; if(node->pkg.flag & IO_NOTICE_HUP) cond |= POLLHUP; fds[index++] = (struct pollfd){node->pkg.fd, cond, 0}; } poll(fds, index, ms); // map fds. index = 0; POSSESSING__ON(io_list_head); list_foreach_data(node, &io_list_head.head) { short flags = 0; short revents = fds[index++].revents; if(!node->remove && revents != 0) { if(revents & POLLIN) flags |= IO_NOTICE_READ; if(revents & POLLOUT) flags |= IO_NOTICE_WRITE; if(revents & POLLERR) flags |= IO_NOTICE_ERR; if(revents & POLLHUP) flags |= IO_NOTICE_HUP; node->callback(node->user_data, (fd_desc_t){node->pkg.fd, flags}); } } POSSESSING_OFF(io_list_head); _io_list_after_loop(); } void io_flush_epoll(uint32_t ms) { struct epoll_event evs[io_list_head.count]; int nfds = epoll_wait(_epoll_fd, evs, io_list_head.count, ms); POSSESSING__ON(io_list_head); for(size_t i = 0; i < nfds; ++i) { io_node_t* node = evs[i].data.ptr; short flags = 0; uint32_t revents = evs[i].events; if(!node->remove && revents != 0) { if(revents & POLLIN) flags |= IO_NOTICE_READ; if(revents & POLLOUT) flags |= IO_NOTICE_WRITE; if(revents & POLLERR) flags |= IO_NOTICE_ERR; if(revents & POLLHUP) flags |= IO_NOTICE_HUP; node->callback(node->user_data, (fd_desc_t){node->pkg.fd, flags}); } } POSSESSING_OFF(io_list_head); _io_list_after_loop(); } bool io_notice_file(fd_desc_t pkg, fd_callback_t callback, void* user_data) { assert(callback != NULL); io_node_t* node = malloc(sizeof(io_node_t)); node->pkg = pkg; node->callback = callback; node->user_data = user_data; node->remove = false; if(list_add_data_tail(&io_list_head.head, node) != NULL) io_list_head.count++; if(_epoll_fd != -1) { uint32_t cond = 0; if(node->pkg.flag & IO_NOTICE_READ) cond |= POLLIN; if(node->pkg.flag & IO_NOTICE_WRITE) cond |= POLLOUT; if(node->pkg.flag & IO_NOTICE_ERR) cond |= POLLERR; if(node->pkg.flag & IO_NOTICE_HUP) cond |= POLLHUP; struct epoll_event data = {.events = cond, .data = {.ptr = node}}; epoll_ctl(_epoll_fd, EPOLL_CTL_ADD, node->pkg.fd, &data); } } void io_ignore_file(int fd) { io_node_t* node; bool remove = false; list_foreach(list_node, &io_list_head.head) { if(remove) { list_t* node_prev = list_get_prev(&io_list_head.head, list_node); node = node_prev->data; IS_POSSESSING(io_list_head) ? _io_list_mark_remove(node) : _io_list_remove_node(node_prev); } node = list_node->data; remove = (node->pkg.fd == fd); } if(remove) { list_t* node_prev = list_get_last(&io_list_head.head); node = node_prev->data; IS_POSSESSING(io_list_head) ? _io_list_mark_remove(node) : _io_list_remove_node(node_prev); } } bool io_notice_file_update(fd_desc_t pkg) { io_node_t* node; list_foreach_data(node, &io_list_head.head) { if(node->pkg.fd == pkg.fd) { node->pkg.flag = pkg.flag; if(_epoll_fd != -1) { uint32_t cond = 0; if(node->pkg.flag & IO_NOTICE_READ) cond |= POLLIN; if(node->pkg.flag & IO_NOTICE_WRITE) cond |= POLLOUT; if(node->pkg.flag & IO_NOTICE_ERR) cond |= POLLERR; if(node->pkg.flag & IO_NOTICE_HUP) cond |= POLLHUP; struct epoll_event data = {.events = cond, .data = {.ptr = node}}; epoll_ctl(_epoll_fd, EPOLL_CTL_MOD, node->pkg.fd, &data); } break; } } } static void _io_list_after_loop() { io_node_t* node; bool remove = false; list_foreach(list_node, &io_list_head.head) { node = list_node->data; if(remove) { _io_list_remove_node(list_get_prev(&io_list_head.head, list_node)); } remove = node->remove; } if(remove) { _io_list_remove_node(list_get_last(&io_list_head.head)); } } static struct timeval _translate_ms(uint32_t ms) { return (struct timeval){ms / 1000, (ms - ms / 1000) * 1000}; } static inline void _io_list_mark_remove(io_node_t* node) { node->remove = true; } static inline void _io_list_remove_node(list_t* list_node) { if(_epoll_fd != -1) { io_node_t* node = list_node->data; epoll_ctl(_epoll_fd, EPOLL_CTL_DEL, node->pkg.fd, NULL); } free(list_node_remove(list_node)); }
26.814815
80
0.617278
7e9679cd2413fe1a3855d9a038d09602f0592cac
861
h
C
PrivateFrameworks/ContentKit/DCMapsURLGenerator.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
17
2018-11-13T04:02:58.000Z
2022-01-20T09:27:13.000Z
PrivateFrameworks/ContentKit/DCMapsURLGenerator.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
3
2018-04-06T02:02:27.000Z
2018-10-02T01:12:10.000Z
PrivateFrameworks/ContentKit/DCMapsURLGenerator.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
1
2018-09-28T13:54:23.000Z
2018-09-28T13:54:23.000Z
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import <ContentKit/DCURLGenerator.h> @class DCMapsLink, NSMutableDictionary; __attribute__((visibility("hidden"))) @interface DCMapsURLGenerator : DCURLGenerator { NSMutableDictionary *_queryDictionary; DCMapsLink *_mapsLink; } + (id)URLWithMapsLink:(id)arg1; @property(readonly, nonatomic) DCMapsLink *mapsLink; // @synthesize mapsLink=_mapsLink; - (void).cxx_destruct; - (void)setString:(id)arg1 forQueryKey:(id)arg2; - (id)mapType; - (id)directionsMode; - (void)populateQueryDictionary; @property(readonly, nonatomic) NSMutableDictionary *queryDictionary; // @synthesize queryDictionary=_queryDictionary; - (id)URL; - (id)query; - (id)path; - (id)host; - (id)scheme; - (id)initWithMapsLink:(id)arg1; @end
24.6
117
0.731707
7d02db43f2f0f8309b4786ebbc8fcb65a196bc80
9,740
c
C
pkcs11_luna/ext/pk11l.c
larskanis/pkcs11
eeda7cbe721af0c4a0c6535a1fe377884c4d6ef0
[ "MIT" ]
21
2015-04-15T11:56:58.000Z
2022-02-16T19:19:07.000Z
pkcs11_luna/ext/pk11l.c
larskanis/pkcs11
eeda7cbe721af0c4a0c6535a1fe377884c4d6ef0
[ "MIT" ]
7
2015-07-06T19:39:59.000Z
2020-11-06T21:59:07.000Z
pkcs11_luna/ext/pk11l.c
larskanis/pkcs11
eeda7cbe721af0c4a0c6535a1fe377884c4d6ef0
[ "MIT" ]
13
2015-05-12T04:49:35.000Z
2021-12-03T14:51:16.000Z
#include <ruby.h> #include <ruby/thread.h> #include <ruby/encoding.h> #if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) #define _WINDOWS #define OS_WIN32 #define compile_for_windows #else #define OS_LINUX #endif #if defined(compile_for_windows) #include <winbase.h> /* for LoadLibrary() */ #else #include <dlfcn.h> #endif /////////////////////////////////////// static VALUE mPKCS11; static VALUE cPKCS11; static VALUE mLuna; static VALUE eLunaError; static VALUE cLunaCStruct; static VALUE cPkcs11CStruct; static VALUE cCK_C_INITIALIZE_ARGS; static VALUE aCK_C_INITIALIZE_ARGS_members; static VALUE cCK_INFO; static VALUE aCK_INFO_members; static VALUE cCK_TOKEN_INFO; static VALUE aCK_TOKEN_INFO_members; static VALUE cCK_SLOT_INFO; static VALUE aCK_SLOT_INFO_members; static VALUE cCK_MECHANISM_INFO; static VALUE aCK_MECHANISM_INFO_members; static VALUE cCK_SESSION_INFO; static VALUE aCK_SESSION_INFO_members; static VALUE cCK_MECHANISM; static VALUE cCK_ATTRIBUTE; static VALUE vOBJECT_CLASSES; static VALUE vATTRIBUTES; static VALUE vMECHANISMS; static VALUE vRETURN_VALUES; #define MODULE_FOR_STRUCTS mLuna #define MODULE_FOR_CONSTS mLuna #define BASECLASS_FOR_ERRORS eLunaError #define BASECLASS_FOR_STRUCTS cLunaCStruct #define PKCS11_DEFINE_METHOD(name, args) \ rb_define_method(cPKCS11, #name, pkcs11_luna_##name, args); #define GetFunction(obj, name, sval) \ { \ pkcs11_luna_ctx *ctx; \ Data_Get_Struct(obj, pkcs11_luna_ctx, ctx); \ if (!ctx->sfnt_functions) rb_raise(eLunaError, "no function list"); \ sval = (CK_##name)ctx->sfnt_functions->name; \ if (!sval) rb_raise(eLunaError, #name " is not supported."); \ } #define CallFunction(name, func, rv, ...) \ { \ struct tbr_##name##_params params = { \ func, {__VA_ARGS__}, CKR_FUNCTION_FAILED \ }; \ rb_thread_call_without_gvl(tbf_##name, &params, RUBY_UBF_PROCESS, NULL); \ rv = params.retval; \ } #include "cryptoki_v2.h" #include "pk11_struct_macros.h" #include "pk11_const_macros.h" #include "pk11_version.h" #include "pk11l_struct_impl.inc" typedef struct { void *module; CK_FUNCTION_LIST_PTR functions; CK_SFNT_CA_FUNCTION_LIST_PTR sfnt_functions; } pkcs11_luna_ctx; static void pkcs11_luna_raise(VALUE self, CK_RV rv) { rb_funcall(self, rb_intern("vendor_raise_on_return_value"), 1, ULONG2NUM(rv)); rb_raise(eLunaError, "method vendor_raise_on_return_value should never return"); } struct tbr_CA_GetFunctionList_params { CK_CA_GetFunctionList func; struct { CK_SFNT_CA_FUNCTION_LIST_PTR_PTR ppSfntFunctionList; } params; CK_RV retval; }; void * tbf_CA_GetFunctionList( void *data ){ struct tbr_CA_GetFunctionList_params *p = (struct tbr_CA_GetFunctionList_params*)data; p->retval = p->func( p->params.ppSfntFunctionList ); return NULL; } /*struct tbr_CA_SetApplicationID_params { CK_CA_SetApplicationID func; struct { CK_ULONG major; CK_ULONG minor; } params;l CK_RV retval; }; void * tbf_CA_SetApplicationID( void *data ){ struct tbr_CA_SetApplicationID_params *p = (struct tbr_CA_SetApplicationID_params*)data; p->retval = p->func( p->params.major, p->params.minor ); return NULL; } struct tbr_CA_OpenApplicationID_params { CK_CA_OpenApplicationID func; struct { CK_SLOT_ID slot_id; CK_ULONG major; CK_ULONG minor; } params; CK_RV retval; }; void * tbf_CA_OpenApplicationID( void *data ){ struct tbr_CA_OpenApplicationID_params *p = (struct tbr_CA_OpenApplicationID_params*)data; p->retval = p->func( p->params.slot_id, p->params.major, p->params.minor ); return NULL; } struct tbr_CA_CloseApplicationID_params { CK_CA_CloseApplicationID func; struct { CK_SLOT_ID slot_id; CK_ULONG major; CK_ULONG minor; } params; CK_RV retval; }; void * tbf_CA_CloseApplicationID( void *data ){ struct tbr_CA_CloseApplicationID_params *p = (struct tbr_CA_CloseApplicationID_params*)data; p->retval = p->func( p->params.slot_id, p->params.major, p->params.minor); return NULL; } struct tbr_CA_LogExternal_params { CK_CA_LogExternal func; struct { CK_SLOT_ID slot_id; CK_SESSION_HANDLE hSession; CK_CHAR_PTR pString; CK_ULONG ulLen;} params; CK_RV retval; }; void * tbf_CA_LogExternal( void *data ){ struct tbr_CA_LogExternal_params *p = (struct tbr_CA_LogExternal_params*)data; p->retval = p->func( p->params.slot_id, p->params.hSession, p->params.pString, p->params.ulLen); return NULL; }*/ static void pkcs11_luna_ctx_free(pkcs11_luna_ctx *ctx) { free(ctx); } //NOTE: Code commented out as it was decided to only support standard pkcs11 initially.l /*static VALUE pkcs11_luna_CA_SetApplicationID(VALUE self, VALUE major, VALUE minor) { CK_CA_SetApplicationID func; CK_RV rv; GetFunction(self, CA_SetApplicationID, func); CallFunction(CA_SetApplicationID, func, rv, NUM2ULONG(major), NUM2ULONG(minor)); if(rv != CKR_OK) pkcs11_luna_raise(self,rv); return self; } static VALUE pkcs11_luna_CA_OpenApplicationID(VALUE self, VALUE slot_id, VALUE major, VALUE minor) { CK_CA_OpenApplicationID func; CK_RV rv; GetFunction(self, CA_OpenApplicationID, func); CallFunction(CA_OpenApplicationID, func, rv, NUM2ULONG(slot_id), NUM2ULONG(major), NUM2ULONG(minor)); if(rv != CKR_OK) pkcs11_luna_raise(self,rv); return self; } static VALUE pkcs11_luna_CA_CloseApplicationID(VALUE self, VALUE slot_id, VALUE major, VALUE minor) { CK_CA_CloseApplicationID func; CK_RV rv; GetFunction(self, CA_CloseApplicationID, func); CallFunction(CA_CloseApplicationID, func, rv, NUM2ULONG(slot_id), NUM2ULONG(major), NUM2ULONG(minor)); if(rv != CKR_OK) pkcs11_luna_raise(self,rv); return self; }*/ /*static VALUE pkcs11_luna_CA_LogExternal(VALUE self, VALUE slot_id, VALUE session, VALUE message) { CK_CA_LogExternal func; CK_RV rv; GetFunction(self, CA_LogExternal, func); CallFunction(CA_LogExternal, func, rv, NUM2HANDLE(slot_id), NUM2HANDLE(session), (CK_CHAR_PTR)RSTRING_PTR(message), RSTRING_LEN(message)); if(rv != CKR_OK) pkcs11_luna_raise(self,rv); return self; }*/ /* rb_define_method(cPKCS11, "CA_GetFunctionList", pkcs11_CA_GetFunctionList, 0); */ /* * Obtains a pointer to the Cryptoki library's list of function pointers. The pointer * is stored in the {PKCS11::Library} object and used to call any Cryptoki functions. * * @see PKCS11::Library#initialize */ static VALUE pkcs11_luna_CA_GetFunctionList(VALUE self) { pkcs11_luna_ctx *ctx; CK_RV rv; CK_CA_GetFunctionList func; Data_Get_Struct(self, pkcs11_luna_ctx, ctx); #ifdef compile_for_windows func = (CK_CA_GetFunctionList)GetProcAddress(ctx->module, "CA_GetFunctionList"); if(!func){ char error_text[999] = "GetProcAddress() error"; FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_MAX_WIDTH_MASK, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&error_text, sizeof(error_text), NULL); rb_raise(eLunaError, "%s", error_text); } #else func = (CK_CA_GetFunctionList)dlsym(ctx->module, "CA_GetFunctionList"); if(!func) rb_raise(eLunaError, "%sHERE", dlerror()); #endif CallFunction(CA_GetFunctionList, func, rv, &(ctx->sfnt_functions)); if (rv != CKR_OK) pkcs11_luna_raise(self, rv); return self; } static VALUE pkcs11_luna_s_alloc(VALUE self) { VALUE obj; pkcs11_luna_ctx *ctx; obj = Data_Make_Struct(self, pkcs11_luna_ctx, 0, pkcs11_luna_ctx_free, ctx); return obj; } static VALUE pkcs11_luna_initialize(int argc, VALUE *argv, VALUE self) { VALUE path, init_args; rb_scan_args(argc, argv, "02", &path, &init_args); if( !NIL_P(path) ){ rb_funcall(self, rb_intern("load_library"), 1, path); rb_funcall(self, rb_intern("C_GetFunctionList"), 0); rb_funcall(self, rb_intern("CA_GetFunctionList"), 0); rb_funcall2(self, rb_intern("C_Initialize"), 1, &init_args); } return self; } void Init_pkcs11_luna_ext() { VALUE eError; VALUE cLibrary; mPKCS11 = rb_const_get(rb_cObject, rb_intern("PKCS11")); /* Document-module: PKCS11::Luna * * Module to provide functionality for SafeNet's Luna HSMs */ mLuna = rb_define_module_under(mPKCS11, "Luna"); /* Document-class: PKCS11::Luna::Library * * Derived class for Luna Library */ cLibrary = rb_const_get(mPKCS11, rb_intern("Library")); cPKCS11 = rb_define_class_under(mLuna, "Library", cLibrary); rb_define_alloc_func(cPKCS11, pkcs11_luna_s_alloc); rb_define_method(cPKCS11, "initialize", pkcs11_luna_initialize, -1); PKCS11_DEFINE_METHOD(CA_GetFunctionList, 0); //PKCS11_DEFINE_METHOD(CA_LogExternal, 3); //PKCS11_DEFINE_METHOD(CA_SetApplicationID, 2); //PKCS11_DEFINE_METHOD(CA_OpenApplicationID, 3); //PKCS11_DEFINE_METHOD(CA_CloseApplicationID, 3); /* Library version */ rb_define_const( mLuna, "VERSION", rb_str_new2(VERSION) ); eError = rb_const_get(mPKCS11, rb_intern("Error")); /* Document-class: PKCS11::Luna::Error * * Base class for all Luna specific exceptions (CKR_*) */ eLunaError = rb_define_class_under(mLuna, "Error", eError); cPkcs11CStruct = rb_const_get(mPKCS11, rb_intern("CStruct")); \ cLunaCStruct = rb_define_class_under(mLuna, "CStruct", cPkcs11CStruct); #include "pk11l_struct_def.inc" vOBJECT_CLASSES = rb_hash_new(); vATTRIBUTES = rb_hash_new(); vMECHANISMS = rb_hash_new(); vRETURN_VALUES = rb_hash_new(); rb_define_const(mLuna, "OBJECT_CLASSES", vOBJECT_CLASSES); rb_define_const(mLuna, "ATTRIBUTES", vATTRIBUTES); rb_define_const(mLuna, "MECHANISMS", vMECHANISMS); rb_define_const(mLuna, "RETURN_VALUES", vRETURN_VALUES); #include "pk11l_const_def.inc" rb_obj_freeze(vOBJECT_CLASSES); rb_obj_freeze(vATTRIBUTES); rb_obj_freeze(vMECHANISMS); rb_obj_freeze(vRETURN_VALUES); }
28.479532
104
0.750821
a43f8b2ab59a61d257fb611e83507be1b6c6a27b
454
h
C
source/WinSimu/EnmIOStream.h
Borrk/Enzyme-labeled-instrument
a7c8f4459511c774f7e0c4fee1fe05baf1ae2a5f
[ "MIT" ]
null
null
null
source/WinSimu/EnmIOStream.h
Borrk/Enzyme-labeled-instrument
a7c8f4459511c774f7e0c4fee1fe05baf1ae2a5f
[ "MIT" ]
null
null
null
source/WinSimu/EnmIOStream.h
Borrk/Enzyme-labeled-instrument
a7c8f4459511c774f7e0c4fee1fe05baf1ae2a5f
[ "MIT" ]
null
null
null
// EnmIOStream.h: interface for the CEnmIOStream class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_ENMIOSTREAM_H__6F7633C9_63EB_48AD_AE90_016D9E00879C__INCLUDED_) #define AFX_ENMIOSTREAM_H__6F7633C9_63EB_48AD_AE90_016D9E00879C__INCLUDED_ class CEnmIOStream { public: CEnmIOStream(); virtual ~CEnmIOStream(); }; #endif // !defined(AFX_ENMIOSTREAM_H__6F7633C9_63EB_48AD_AE90_016D9E00879C__INCLUDED_)
26.705882
86
0.711454
62b02ff6e06c353436879666c914559bed3a7260
13,954
c
C
lib/commonAPI/rubyvm_stub/ext/platform/wm/dir_stub.c
mensfeld/rhodes
2962610a314ed563a0b7c83fcae6136913a1b033
[ "MIT" ]
173
2015-01-02T11:14:08.000Z
2022-03-05T09:54:54.000Z
lib/commonAPI/rubyvm_stub/ext/platform/wm/dir_stub.c
mensfeld/rhodes
2962610a314ed563a0b7c83fcae6136913a1b033
[ "MIT" ]
263
2015-01-05T04:35:22.000Z
2021-09-07T06:00:02.000Z
lib/commonAPI/rubyvm_stub/ext/platform/wm/dir_stub.c
watusi/rhodes
07161cca58ff6a960bbd1b79b36447b819bfa0eb
[ "MIT" ]
77
2015-01-12T20:57:18.000Z
2022-02-17T15:15:14.000Z
#include <Windows.h> #include <ruby/wince/sys/stat.h> #include <ruby/wince/errno.h> #include <ruby/win32/dir.h> #include <ruby/ruby.h> #include <ruby/encoding.h> #include <ruby/regenc.h> extern int rb_w32_map_errno(unsigned long winerr); extern WCHAR* filecp_to_wstr(const char *str, long *plen); ////////////////////////////////////////////////////////////////////////// // regenc.c const unsigned short OnigEncAsciiCtypeTable[256] = { 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x420c, 0x4209, 0x4208, 0x4208, 0x4208, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4284, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x7ca2, 0x7ca2, 0x7ca2, 0x7ca2, 0x7ca2, 0x7ca2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x51a0, 0x41a0, 0x78e2, 0x78e2, 0x78e2, 0x78e2, 0x78e2, 0x78e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x4008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000 }; ////////////////////////////////////////////////////////////////////////// // defines #define IsWinNT() rb_w32_iswinnt() #define GetBit(bits, i) ((bits)[(i) / CHAR_BIT] & (1 << (i) % CHAR_BIT)) #define SetBit(bits, i) ((bits)[(i) / CHAR_BIT] |= (1 << (i) % CHAR_BIT)) #define BitOfIsDir(n) ((n) * 2) #define BitOfIsRep(n) ((n) * 2 + 1) #define DIRENT_PER_CHAR (CHAR_BIT / 2) #define map_errno(e) rb_w32_map_errno(e) #define rb_isascii(c) ((unsigned long)(c) < 128) #define CTYPE_TO_BIT(ctype) (1<<(ctype)) #define ONIGENC_IS_ASCII_CODE_CTYPE(code,ctype) ((OnigEncAsciiCtypeTable[code] & CTYPE_TO_BIT(ctype)) != 0) #define ONIGENC_CTYPE_ALPHA 1 #define ctype_test(c, ctype) (rb_isascii(c) && ONIGENC_IS_ASCII_CODE_CTYPE((c), ctype)) ////////////////////////////////////////////////////////////////////////// // directory functions int rb_isalpha(int c) { return ctype_test(c, ONIGENC_CTYPE_ALPHA); } #ifdef WIN95 static int win95_stat(const WCHAR *path, struct stati64 *st) { int ret = _wstati64(path, st); if (ret) return ret; if (st->st_mode & S_IFDIR) { return check_valid_dir(path); } return 0; } #else #define win95_stat(path, st) -1 #endif HANDLE open_dir_handle(const WCHAR *filename, WIN32_FIND_DATAW *fd) { HANDLE fh; static const WCHAR wildcard[] = L"\\*"; WCHAR *scanname; WCHAR *p; int len, i; // // Create the search pattern // len = lstrlenW(filename); scanname = ALLOCA_N(WCHAR, len + sizeof(wildcard) / sizeof(WCHAR)); lstrcpyW(scanname, filename); p = CharPrevW(scanname, scanname + len); if (*p == L'/' || *p == L'\\' || *p == L':') lstrcatW(scanname, wildcard + 1); else lstrcatW(scanname, wildcard); for( i = 0; scanname[i]; i++) { if ( scanname[i] == L'/' ) scanname[i] = L'\\'; } // // do the FindFirstFile call // fh = FindFirstFileW(scanname, fd); if (fh == INVALID_HANDLE_VALUE) { DWORD dwErr = GetLastError(); if ( dwErr == 18) fh = 0; else errno = map_errno(GetLastError()); } return fh; } int isUNCRoot(const WCHAR *path) { if (path[0] == L'\\' && path[1] == L'\\') { const WCHAR *p; for (p = path + 2; *p; p++) { if (*p == L'\\') break; } if (p[0] && p[1]) { for (p++; *p; p++) { if (*p == L'\\') break; } if (!p[0] || !p[1] || (p[1] == L'.' && !p[2])) return 1; } } return 0; } unsigned fileattr_to_unixmode(DWORD attr, const WCHAR *path) { unsigned mode = 0; if (attr & FILE_ATTRIBUTE_READONLY) { mode |= S_IREAD; } else { mode |= S_IREAD | S_IWRITE | S_IWUSR; } if (attr & FILE_ATTRIBUTE_DIRECTORY) { mode |= S_IFDIR | S_IEXEC; } else { mode |= S_IFREG; } if (path && (mode & S_IFREG)) { const WCHAR *end = path + lstrlenW(path); while (path < end) { end = CharPrevW(path, end); if (*end == L'.') { if ((_wcsicmp(end, L".bat") == 0) || (_wcsicmp(end, L".cmd") == 0) || (_wcsicmp(end, L".com") == 0) || (_wcsicmp(end, L".exe") == 0)) { mode |= S_IEXEC; } break; } } } mode |= (mode & 0700) >> 3; mode |= (mode & 0700) >> 6; return mode; } int filetime_to_timeval(const FILETIME* ft, struct timeval *tv) { ULARGE_INTEGER tmp; unsigned LONG_LONG lt; tmp.LowPart = ft->dwLowDateTime; tmp.HighPart = ft->dwHighDateTime; lt = tmp.QuadPart; /* lt is now 100-nanosec intervals since 1601/01/01 00:00:00 UTC, convert it into UNIX time (since 1970/01/01 00:00:00 UTC). the first leap second is at 1972/06/30, so we doesn't need to think about it. */ lt /= 10; /* to usec */ lt -= (LONG_LONG)((1970-1601)*365.2425) * 24 * 60 * 60 * 1000 * 1000; tv->tv_sec = (long)(lt / (1000 * 1000)); tv->tv_usec = (long)(lt % (1000 * 1000)); return tv->tv_sec > 0 ? 0 : -1; } time_t filetime_to_unixtime(const FILETIME *ft) { struct timeval tv; if (filetime_to_timeval(ft, &tv) == (time_t)-1) return 0; else return tv.tv_sec; } int check_valid_dir(const WCHAR *path) { WIN32_FIND_DATAW fd = {0}; HANDLE fh = open_dir_handle(path, &fd); if (fh == INVALID_HANDLE_VALUE) return -1; FindClose(fh); return 0; } int winnt_stat(const WCHAR *path, struct stati64 *st) { HANDLE h; WIN32_FIND_DATAW wfd = {0}; memset(st, 0, sizeof(*st)); st->st_nlink = 1; if (wcspbrk(path, L"?*")) { errno = ENOENT; return -1; } h = FindFirstFileW(path, &wfd); if (h != INVALID_HANDLE_VALUE) { FindClose(h); st->st_mode = fileattr_to_unixmode(wfd.dwFileAttributes, path); st->st_atime = filetime_to_unixtime(&wfd.ftLastAccessTime); st->st_mtime = filetime_to_unixtime(&wfd.ftLastWriteTime); st->st_ctime = filetime_to_unixtime(&wfd.ftCreationTime); st->st_size = ((__int64)wfd.nFileSizeHigh << 32) | wfd.nFileSizeLow; } else { // If runtime stat(2) is called for network shares, it fails on WinNT. // Because GetDriveType returns 1 for network shares. (Win98 returns 4) DWORD attr = GetFileAttributesW(path); if (attr == (DWORD)-1L) { errno = map_errno(GetLastError()); return -1; } if (attr & FILE_ATTRIBUTE_DIRECTORY) { if (check_valid_dir(path)) return -1; } st->st_mode = fileattr_to_unixmode(attr, path); } st->st_dev = st->st_rdev = (iswalpha(path[0]) && path[1] == L':') ? towupper(path[0]) - L'A' : _getdrive() - 1; return 0; } int wstati64(const WCHAR *path, struct stati64 *st) { const WCHAR *p; WCHAR *buf1, *s, *end; int len, size; int ret; if (!path || !st) { errno = EFAULT; return -1; } size = lstrlenW(path) + 2; buf1 = ALLOCA_N(WCHAR, size); for (p = path, s = buf1; *p; p++, s++) { if (*p == L'/') *s = L'\\'; else *s = *p; } *s = '\0'; len = s - buf1; if (!len || L'\"' == *(--s)) { errno = ENOENT; return -1; } end = buf1 + len - 1; if (isUNCRoot(buf1)) { if (*end == L'.') *end = L'\0'; else if (*end != L'\\') lstrcatW(buf1, L"\\"); } else if (*end == L'\\' || (buf1 + 1 == end && *end == L':')) lstrcatW(buf1, L"."); ret = IsWinNT() ? winnt_stat(buf1, st) : win95_stat(buf1, st); if (ret == 0) { st->st_mode &= ~(S_IWGRP | S_IWOTH); } return ret; } DIR* opendir_internal(HANDLE fh, WIN32_FIND_DATAW *fd) { DIR *p; long len; long idx; WCHAR *tmpW; char *tmp; if (fh == INVALID_HANDLE_VALUE) { return NULL; } // // Get us a DIR structure // p = calloc(sizeof(DIR), 1); if (p == NULL) return NULL; idx = 0; // // loop finding all the files that match the wildcard // (which should be all of them in this directory!). // the variable idx should point one past the null terminator // of the previous string found. // do { len = lstrlenW(fd->cFileName) + 1; // // bump the string table size by enough for the // new name and it's null terminator // tmpW = realloc(p->start, (idx + len) * sizeof(WCHAR)); if (!tmpW) { error: rb_w32_closedir(p); FindClose(fh); errno = ENOMEM; return NULL; } p->start = tmpW; memcpy(&p->start[idx], fd->cFileName, len * sizeof(WCHAR)); if (p->nfiles % DIRENT_PER_CHAR == 0) { tmp = realloc(p->bits, p->nfiles / DIRENT_PER_CHAR + 1); if (!tmp) goto error; p->bits = tmp; p->bits[p->nfiles / DIRENT_PER_CHAR] = 0; } if (fd->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) SetBit(p->bits, BitOfIsDir(p->nfiles)); if (fd->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) SetBit(p->bits, BitOfIsRep(p->nfiles)); p->nfiles++; idx += len; } while (FindNextFileW(fh, fd)); FindClose(fh); p->size = idx; p->curr = p->start; return p; } DIR* rb_w32_opendir(const char* filename) { struct stati64 sbuf; WIN32_FIND_DATAW fd = {0}; HANDLE fh; WCHAR *wpath; if (!(wpath = filecp_to_wstr(filename, NULL))) return NULL; // // check to see if we've got a directory // if (wstati64(wpath, &sbuf) < 0) { free(wpath); return NULL; } if (!(sbuf.st_mode & S_IFDIR) && (!ISALPHA(filename[0]) || filename[1] != ':' || filename[2] != '\0' || ((1 << ((filename[0] & 0x5f) - 'A')) & GetLogicalDrives()) == 0)) { free(wpath); errno = ENOTDIR; return NULL; } fh = open_dir_handle(wpath, &fd); free(wpath); return opendir_internal(fh, &fd); } void rb_w32_closedir(DIR *dirp) { if (dirp) { if (dirp->dirstr.d_name) free(dirp->dirstr.d_name); if (dirp->start) free(dirp->start); if (dirp->bits) free(dirp->bits); free(dirp); } } void move_to_next_entry(DIR *dirp) { if (dirp->curr) { dirp->loc++; dirp->curr += lstrlenW(dirp->curr) + 1; if (dirp->curr >= (dirp->start + dirp->size)) { dirp->curr = NULL; } } } struct direct* readdir_internal(DIR *dirp, BOOL (*conv)(const WCHAR *, struct direct *, rb_encoding *), rb_encoding *enc) { static int dummy = 0; if (dirp->curr) { // // first set up the structure to return // if (dirp->dirstr.d_name) free(dirp->dirstr.d_name); conv(dirp->curr, &dirp->dirstr, enc); // // Fake inode // dirp->dirstr.d_ino = dummy++; // // Attributes // dirp->dirstr.d_isdir = GetBit(dirp->bits, BitOfIsDir(dirp->loc)); dirp->dirstr.d_isrep = GetBit(dirp->bits, BitOfIsRep(dirp->loc)); // // Now set up for the next call to readdir // move_to_next_entry(dirp); return &(dirp->dirstr); } else return NULL; } char* wstr_to_filecp(const WCHAR *wstr, long *plen) { UINT cp = AreFileApisANSI() ? CP_ACP : CP_OEMCP; char *ptr; int len = WideCharToMultiByte(cp, 0, wstr, -1, NULL, 0, NULL, NULL) - 1; if (!(ptr = malloc(len + 1))) return 0; WideCharToMultiByte(cp, 0, wstr, -1, ptr, len + 1, NULL, NULL); if (plen) *plen = len; return ptr; } BOOL win32_direct_conv(const WCHAR *file, struct direct *entry, rb_encoding *dummy) { if (!(entry->d_name = wstr_to_filecp(file, &entry->d_namlen))) return FALSE; return TRUE; } struct direct* rb_w32_readdir(DIR *dirp) { return readdir_internal(dirp, win32_direct_conv, NULL); }
27.852295
121
0.551455
922e47009bc344172ea6c69c8deab91620478bb0
937
c
C
arch/cortex-m/cpu_cortex-m.c
pellepl/baremetal
e7cb87dd9d4f1c39714b6aee5f217f01dcc2dd0c
[ "MIT" ]
5
2019-11-27T21:34:16.000Z
2021-11-29T13:33:26.000Z
arch/cortex-m/cpu_cortex-m.c
pellepl/baremetal
e7cb87dd9d4f1c39714b6aee5f217f01dcc2dd0c
[ "MIT" ]
null
null
null
arch/cortex-m/cpu_cortex-m.c
pellepl/baremetal
e7cb87dd9d4f1c39714b6aee5f217f01dcc2dd0c
[ "MIT" ]
null
null
null
#include "bmtypes.h" #include _CORTEX_CORE_HEADER #include "cpu.h" __attribute__((weak)) void cpu_init(void) {} __attribute__((weak, noreturn)) void cpu_reset(void) { NVIC_SystemReset(); while(1); } __attribute__((weak)) void cpu_halt(uint32_t milliseconds) { uint32_t ticks_per_ms = cpu_core_clock_freq() / 1000; ticks_per_ms -= 4; // remove 1+3 ticks for loop: subs, bne SysTick->LOAD = ticks_per_ms - 1; SysTick->VAL = 0UL; SysTick->CTRL = (1<<0) | (1<<2); // enable, use core clock while (milliseconds--) { while ((SysTick->CTRL & (1<<16)) == 0); // wait till overflow } SysTick->CTRL = 0; // disable } __attribute__((weak)) void cpu_interrupt_enable(void) { __enable_irq(); } __attribute__((weak)) void cpu_interrupt_disable(void) { __disable_irq(); } __attribute__((weak)) uint32_t cpu_core_clock_freq(void) { SystemCoreClockUpdate(); return SystemCoreClock; }
26.027778
69
0.671291
927337fd064f4f3827f739f9937b6783fe4f7f10
4,073
h
C
sf-ios/SFGeometryCollection.h
bosborn/simple-features-ios
e90f4a17f823f0a17c4d7e08625c79fe3f7785d0
[ "MIT" ]
1
2019-12-03T12:32:14.000Z
2019-12-03T12:32:14.000Z
sf-ios/SFGeometryCollection.h
bosborn/simple-features-ios
e90f4a17f823f0a17c4d7e08625c79fe3f7785d0
[ "MIT" ]
null
null
null
sf-ios/SFGeometryCollection.h
bosborn/simple-features-ios
e90f4a17f823f0a17c4d7e08625c79fe3f7785d0
[ "MIT" ]
3
2020-12-16T21:26:28.000Z
2022-03-11T18:54:47.000Z
// // SFGeometryCollection.h // sf-ios // // Created by Brian Osborn on 6/2/15. // Copyright (c) 2015 NGA. All rights reserved. // #import "SFGeometry.h" @class SFMultiPoint; @class SFMultiLineString; @class SFMultiPolygon; @class SFMultiCurve; @class SFMultiSurface; /** * A collection of zero or more Geometry instances. */ @interface SFGeometryCollection : SFGeometry /** * Array of geometries */ @property (nonatomic, strong) NSMutableArray<SFGeometry *> *geometries; /** * Initialize * * @return new geometry collection */ -(instancetype) init; /** * Initialize * * @param hasZ has z values * @param hasM has m values * * @return new geometry collection */ -(instancetype) initWithHasZ: (BOOL) hasZ andHasM: (BOOL) hasM; /** * Initialize * * @param geometries * list of geometries * * @return new geometry collection */ -(instancetype) initWithGeometries: (NSMutableArray<SFGeometry *> *) geometries; /** * Initialize * * @param geometry * geometry * * @return new geometry collection */ -(instancetype) initWithGeometry: (SFGeometry *) geometry; /** * Initialize * * @param geometryType geometry type * @param hasZ has z values * @param hasM has m values * * @return new geometry collection */ -(instancetype) initWithType: (enum SFGeometryType) geometryType andHasZ: (BOOL) hasZ andHasM: (BOOL) hasM; /** * Add geometry * * @param geometry geometry */ -(void) addGeometry: (SFGeometry *) geometry; /** * Add geometries * * @param geometries * geometries */ -(void) addGeometries: (NSArray<SFGeometry *> *) geometries; /** * Get the number of geometries * * @return geometry count */ -(int) numGeometries; /** * Returns the Nth geometry * * @param n * nth geometry to return * @return geometry */ -(SFGeometry *) geometryAtIndex: (int) n; /** * Get the collection type by evaluating the geometries * * @return collection geometry type, one of: * MULTIPOINT, * MULTILINESTRING, * MULTIPOLYGON, * MULTICURVE, * MULTISURFACE, * GEOMETRYCOLLECTION */ -(enum SFGeometryType) collectionType; /** * Determine if this geometry collection is a MultiPoint instance or * contains only Point geometries * * @return true if a multi point or contains only points */ -(BOOL) isMultiPoint; /** * Get as a MultiPoint, either the current instance or newly created * from the Point geometries * * @return multi point */ -(SFMultiPoint *) asMultiPoint; /** * Determine if this geometry collection is a MultiLineString * instance or contains only LineString geometries * * @return true if a multi line string or contains only line strings */ -(BOOL) isMultiLineString; /** * Get as a MultiLineString, either the current instance or newly * created from the LineString geometries * * @return multi line string */ -(SFMultiLineString *) asMultiLineString; /** * Determine if this geometry collection is a MultiPolygon instance * or contains only Polygon geometries * * @return true if a multi polygon or contains only polygons */ -(BOOL) isMultiPolygon; /** * Get as a MultiPolygon, either the current instance or newly * created from the Polygon geometries * * @return multi polygon */ -(SFMultiPolygon *) asMultiPolygon; /** * Determine if this geometry collection contains only Curve * geometries * * @return true if contains only curves */ -(BOOL) isMultiCurve; /** * Get as a Multi Curve, a Curve typed Geometry Collection * * @return multi curve */ -(SFGeometryCollection *) asMultiCurve; /** * Determine if this geometry collection contains only Surface * geometries * * @return true if contains only surfaces */ -(BOOL) isMultiSurface; /** * Get as a Multi Surface, a Surface typed Geometry Collection * * @return multi surface */ -(SFGeometryCollection *) asMultiSurface; /** * Get as a top level Geometry Collection * * @return geometry collection */ -(SFGeometryCollection *) asGeometryCollection; @end
19.868293
107
0.684017
783c38e382e290effe0d7e46973e8bc296257410
1,419
h
C
PrivateFrameworks/PhotoLibraryPrivate/LiBindPoints.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
17
2018-11-13T04:02:58.000Z
2022-01-20T09:27:13.000Z
PrivateFrameworks/PhotoLibraryPrivate/LiBindPoints.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
3
2018-04-06T02:02:27.000Z
2018-10-02T01:12:10.000Z
PrivateFrameworks/PhotoLibraryPrivate/LiBindPoints.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
1
2018-09-28T13:54:23.000Z
2018-09-28T13:54:23.000Z
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSObject.h" @class NSMutableArray; @interface LiBindPoints : NSObject { unsigned long long _count; unsigned long long _multiBindCount; NSMutableArray *_bindPoints; } + (void)appendQuestionMarkList:(unsigned long long)arg1 toString:(id)arg2; + (id)questionMarkList:(unsigned long long)arg1; + (void)initQuestionMarkCache; + (id)generateQuestionMarkList:(unsigned long long)arg1; + (unsigned long long)countBindPoints:(id)arg1; @property(retain, nonatomic) NSMutableArray *bindPoints; // @synthesize bindPoints=_bindPoints; @property(nonatomic) unsigned long long multiBindCount; // @synthesize multiBindCount=_multiBindCount; @property(nonatomic) unsigned long long count; // @synthesize count=_count; - (void).cxx_destruct; - (id)determineBindPoints:(id)arg1; - (id)multiBindIndexes; - (void)clear; - (void)setPropertyType:(unsigned char)arg1 atIndex:(unsigned long long)arg2; - (unsigned char)propertyTypeAtIndex:(unsigned long long)arg1; - (BOOL)isMultiBindPointAtIndex:(unsigned long long)arg1; - (unsigned long long)numberOfMultiBindPoints; - (unsigned long long)numberOfBindPoints; - (void)addSingleBindPoints:(unsigned long long)arg1; - (void)addMultiBindPoint; - (void)addBindPointWithType:(unsigned char)arg1; - (id)description; - (id)init; @end
33
102
0.763918
a3cff9c0760dfbc018363b1b18607f81545daf85
208
h
C
Pod/Providers/VKontakteWeb/SimpleAuthVKontakteWebProvider.h
mpkupriyanov/SimpleAuth
3a30b547faa64cfe7c6f9f531b33ab38b6854122
[ "MIT" ]
1
2018-10-24T06:19:36.000Z
2018-10-24T06:19:36.000Z
Pod/Providers/VKontakteWeb/SimpleAuthVKontakteWebProvider.h
mpkupriyanov/SimpleAuth
3a30b547faa64cfe7c6f9f531b33ab38b6854122
[ "MIT" ]
null
null
null
Pod/Providers/VKontakteWeb/SimpleAuthVKontakteWebProvider.h
mpkupriyanov/SimpleAuth
3a30b547faa64cfe7c6f9f531b33ab38b6854122
[ "MIT" ]
null
null
null
// // SimpleAuthVKontakteWebProvider.h // SimpleAuth // // Created by Mikhail Kupriyanov on 7/7/15. // #import "SimpleAuthProvider.h" @interface SimpleAuthVKontakteWebProvider : SimpleAuthProvider @end
16
62
0.759615
d8c779980e8b8502bc492af0c4846614cf32d347
367
h
C
Source/Runtime/polos/events/input/key_release.h
PolosGames/Polos
d670eae7a3655f346e899f81a990c0cf338c1538
[ "MIT" ]
6
2022-03-05T20:57:35.000Z
2022-03-10T13:29:08.000Z
Source/Runtime/polos/events/input/key_release.h
PolosGames/Polos
d670eae7a3655f346e899f81a990c0cf338c1538
[ "MIT" ]
null
null
null
Source/Runtime/polos/events/input/key_release.h
PolosGames/Polos
d670eae7a3655f346e899f81a990c0cf338c1538
[ "MIT" ]
1
2022-03-10T12:15:11.000Z
2022-03-10T12:15:11.000Z
#pragma once #ifndef POLOS_EVENTS_INPUT_KEYRELEASE_H #define POLOS_EVENTS_INPUT_KEYRELEASE_H #include "polos/events/event.h" namespace polos { class key_release : public Event<key_release> { public: int32 key; key_release() = default; key_release(int32 key) : key(key) {} }; } #endif /* POLOS_EVENTS_INPUT_KEYRELEASE_H */
17.47619
49
0.689373
1a82833eacd6e389e8fad3d19d3f4d25ede33fd7
398
h
C
MicroShop/MicroShop/ViewControllers/McroShop/Order/SYOrderListViewController.h
ZICUNREN/MicroShopProject
6e5556477a7a857b1c0b7fb3ef67d26baaa7d930
[ "Apache-2.0" ]
null
null
null
MicroShop/MicroShop/ViewControllers/McroShop/Order/SYOrderListViewController.h
ZICUNREN/MicroShopProject
6e5556477a7a857b1c0b7fb3ef67d26baaa7d930
[ "Apache-2.0" ]
null
null
null
MicroShop/MicroShop/ViewControllers/McroShop/Order/SYOrderListViewController.h
ZICUNREN/MicroShopProject
6e5556477a7a857b1c0b7fb3ef67d26baaa7d930
[ "Apache-2.0" ]
null
null
null
// // SYOrderListViewController.h // MicroShop // // Created by siyue on 15/7/15. // Copyright (c) 2015年 App. All rights reserved. // #import "BaseViewController.h" enum { all = 0, waitpay = 1, waitsend = 2, waitcom = 3 }; @interface SYOrderListViewController : BaseViewController @property (assign,nonatomic)BOOL isMySelf; @property (assign,nonatomic)NSInteger type; @end
16.583333
57
0.690955
1514993a7f5b65f841511f03446ef488375ab14f
14,574
c
C
razor.c
abardill/razor
828e9a2d04a0707c5662122bf1b530b08dcacc12
[ "MIT" ]
null
null
null
razor.c
abardill/razor
828e9a2d04a0707c5662122bf1b530b08dcacc12
[ "MIT" ]
null
null
null
razor.c
abardill/razor
828e9a2d04a0707c5662122bf1b530b08dcacc12
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <getopt.h> #include <stdbool.h> #include <zlib.h> #define VERSION 0.1 #define MAX_SEQ_SIZE 32786 #define MAX_HEADER_SIZE 4096 #define MAX_ADAPTERS 64 #define MAX_ADAPTER_LEN 256 #define MIN(a,b) (((a)<(b))?(a):(b)) #define MAX(a,b) (((a)>(b))?(a):(b)) struct Record { char* header; char* sequence; char* comment; char* quality; int len; }; struct TrimArgs { char* adapter; char* adapter_file; int quality_threshold; int min_length; int min_mean_quality; int min_adapter_match; int phred_encoding; bool keep_empty; }; struct Adapters { char* seqs[MAX_ADAPTERS]; int* fail_mtrx[MAX_ADAPTERS]; int lengths[MAX_ADAPTERS]; }; struct StatsReport { unsigned long reads_read; unsigned long reads_quality_filtered; unsigned long reads_adapter_filtered; unsigned long reads_adapter_trimmed; unsigned long reads_quality_trimmed; unsigned long bases_adapter_trimmed; unsigned long bases_quality_trimmed; }; static inline void* zmalloc(size_t size) { void* ptr = malloc(size); if(!ptr && size) { fprintf(stderr, "Could not allocate %zu bytes\n", size); exit(EXIT_FAILURE); } return ptr; } static inline void* zcalloc(size_t nmemb, size_t size) { void* ptr = calloc(nmemb, size); if(!ptr && nmemb && size) { fprintf(stderr, "Could not allocate %zu bytes\n", nmemb * size); exit(EXIT_FAILURE); } return ptr; } int num_places(unsigned long n) { if (n < 10) return 1; return 1 + num_places (n / 10); } void print_stats(struct StatsReport stats, bool trim_adapters, bool trim_quality) { unsigned long max; max = MAX(stats.bases_quality_trimmed, stats.bases_adapter_trimmed); max = MAX(max, stats.reads_read); int max_width = num_places(max); fprintf(stderr, "%*lu reads were read\n", max_width, stats.reads_read); if (trim_adapters){ fprintf(stderr, "%*lu reads underwent adapter trimming\n", max_width, stats.reads_adapter_trimmed); fprintf(stderr, "%*lu of these were filtered\n", max_width, stats.reads_adapter_filtered); fprintf(stderr, "%*lu adapter bases were trimmed\n", max_width, stats.bases_adapter_trimmed); } if (trim_quality) { fprintf(stderr, "%*lu reads underwent quality trimming\n", max_width, stats.reads_quality_trimmed); fprintf(stderr, "%*lu of these were filtered\n", max_width, stats.reads_quality_filtered); fprintf(stderr, "%*lu bases were quality trimmed\n", max_width, stats.bases_quality_trimmed); } } static inline struct Record* init_record() { struct Record* rec = zmalloc(sizeof(struct Record)); rec->header = zmalloc(2 * MAX_HEADER_SIZE + 2 * MAX_SEQ_SIZE); rec->sequence = rec->header + MAX_HEADER_SIZE; rec->comment = rec->sequence + MAX_SEQ_SIZE; rec->quality = rec->comment + MAX_HEADER_SIZE; return rec; } bool quality_trim(int qual, int phred, int min_length, int min_mean_qual, struct Record *rec, struct StatsReport* stats) { int start = 0, end = 0, sum = 0, max = 0, i = 0; int q = qual + phred; while (rec->quality[i] < q && i < rec->len) i++; start = i; while (i < rec->len) { while (rec->quality[i] >= q && i < rec->len) { sum += rec->quality[i++] - q; } if (sum > max) { max = sum; end = i; } while (rec->quality[i] < q && i < rec->len) { sum += rec->quality[i++] - q; } } rec->quality += start; rec->sequence += start; rec->quality[end] = '\0'; rec->sequence[end] = '\0'; int length = end - start; if (rec->len == length) { return true; } else { stats->reads_quality_trimmed++; stats->bases_quality_trimmed += rec->len - length; if ((float)max / (float)length < min_mean_qual || length < min_length) { rec->sequence[0] = '\0'; rec->quality[0] = '\0'; stats->reads_quality_filtered++; return false; } return true; } } bool adapter_trim(int min_length, int num_adapters, struct Adapters* adapters, struct Record* rec, struct StatsReport* stats) { int i, j; for (int k = 0; k < num_adapters; k++) { i = 0, j = 0; while (i < rec->len) { if (rec->sequence[i] == adapters->seqs[k][j]) { if (j == adapters->lengths[k] - 1) { stats->reads_adapter_trimmed++; stats->bases_adapter_trimmed += rec->len - i; rec->len = i - j; if (i - j < min_length) { rec->sequence[0] = '\0'; rec->quality[0] = '\0'; stats->reads_adapter_filtered++; return false; } else { rec->sequence[i - j] = '\0'; rec->quality[i - j] = '\0'; return true; } } else { i++; j++; } } else if (j > 0) { j = adapters->fail_mtrx[k][j - 1]; } else { i++; } } } return true; } void kmp_preprocess(struct Adapters* adapters, int num_adapters) { int i, j; for (int k = 0; k < num_adapters; k++){ i = 1, j = 0; while (i < adapters->lengths[k]){ if (adapters->seqs[k][i] == adapters->seqs[k][j]){ adapters->fail_mtrx[k][i] = j + 1; i++; j++; } else if (j > 0) j = adapters->fail_mtrx[k][j-1]; else { adapters->fail_mtrx[k][i] = 0; i++; } } } } static inline int parse_fasta(gzFile input, int min_match, char* seq) { if (!gzgets(input, seq, MAX_ADAPTER_LEN) || gzeof(input)) return 0; if (seq[0] != '>') { fprintf(stderr, "Expected fasta header starting with '>'; instead got '%c'.\n", seq[0]); exit(EXIT_FAILURE); } int i = 0; gzgets(input, seq, MAX_ADAPTER_LEN); while (seq[i] != '\n'){ switch(seq[i]){ case 'A': case 'C': case 'T': case 'G': case 'U': case 'N': break; default: fprintf(stderr, "Invalid character '%c' detected in adapter file\n" "Valid characters: A,C,G,T,U,N\n", seq[i]); exit(EXIT_FAILURE); } i++; } int length = MIN(i, min_match); seq[length] = '\0'; return length; } int init_adapters(struct Adapters* adapters, char* adapter_file, char* adapter, int min_match) { adapters->seqs[0] = zcalloc(MAX_ADAPTERS * MAX_ADAPTER_LEN, 1); adapters->fail_mtrx[0] = zcalloc(MAX_ADAPTERS * MAX_ADAPTER_LEN, sizeof(int)); int i = 0; if (adapter){ adapter[MIN(min_match, strlen(adapter))] = '\0'; adapters->lengths[i] = strlen(adapter); strcpy(adapters->seqs[i], adapter); i++; } if (adapter_file) { gzFile input = gzopen(adapter_file, "r"); if (!input) { fprintf(stderr, "Error opening '%s': %s\n", adapter_file, strerror(errno)); exit(EXIT_FAILURE); } while (i < MAX_ADAPTERS) { if ((adapters->lengths[i] = parse_fasta(input, min_match, adapters->seqs[i])) <= 0) break; adapters->seqs[i + 1] = adapters->seqs[i] + adapters->lengths[i]; adapters->fail_mtrx[i + 1] = adapters->fail_mtrx[i] + adapters->lengths[i]; i++; } gzclose_r(input); } adapters->seqs[0] = realloc(adapters->seqs[0], i * MAX_ADAPTER_LEN); adapters->fail_mtrx[0] = realloc(adapters->fail_mtrx[0], i * MAX_ADAPTER_LEN); return i; } static inline bool gzgetrec(gzFile input, struct Record* rec) { if (!gzgets(input, rec->header, MAX_HEADER_SIZE)) return 0; gzgets(input, rec->sequence, MAX_SEQ_SIZE); gzgets(input, rec->comment, MAX_HEADER_SIZE); gzgets(input, rec->quality, MAX_SEQ_SIZE); rec->len = strlen(rec->sequence) - 1; if (rec->len != strlen(rec->quality) - 1){ fprintf(stderr, "Error: lengths of sequence and quality strings " "unequal:\n%s%s%s%s\n", rec->header, rec->sequence, rec->comment, rec->quality); exit(EXIT_FAILURE); } if (rec->header[0] != '@'){ fprintf(stderr, "Malformed fastq: header should start with '@', not" "'%c':\n%s\n", rec->header[0], rec->header); exit(EXIT_FAILURE); } if (rec->comment[0] != '+'){ fprintf(stderr, "Malformed fastq: comment should start with '+', not" "'%c':\n%s\n", rec->comment[0], rec->comment); exit(EXIT_FAILURE); } rec->sequence[rec->len] = '\0'; rec->quality[rec->len] = '\0'; return 1; } void process_reads(const char* infile, const char* outfile, bool trim_adapters, bool trim_quality, const struct TrimArgs* trim_args) { gzFile input; if (!strcmp(infile, "-")) input = gzdopen(STDIN_FILENO, "r"); else input = gzopen(infile, "r"); if (!input){ fprintf(stderr, "Error opening '%s': %s\n", infile, strerror(errno)); exit(EXIT_FAILURE); } bool gzip_output = false; void* output; if (!outfile || !strcmp(outfile, "-")) { output = fdopen(STDOUT_FILENO, "w"); } else { char* dot = strrchr(outfile, '.'); if (dot && !strcmp(dot, ".gz")) { output = gzopen(outfile, "w"); gzip_output = true; } else { output = fopen(outfile, "w"); } } if (!output){ fprintf(stderr, "Error opening '%s': %s\n", outfile, strerror(errno)); exit(EXIT_FAILURE); } struct Adapters adapters; int num_adapters = 0; if (trim_adapters){ num_adapters = init_adapters(&adapters, trim_args->adapter_file, trim_args->adapter, trim_args->min_adapter_match); kmp_preprocess(&adapters, num_adapters); } struct Record* rec_ptr = init_record(); struct Record rec; struct StatsReport stats = {0}; bool passed; while (true) { if (gzeof(input)) break; if (!gzgetrec(input, rec_ptr)) break; stats.reads_read++; rec = *rec_ptr; passed = true; if (trim_adapters) passed = adapter_trim(trim_args->min_length, num_adapters, &adapters, &rec, &stats); if (passed && trim_quality) passed = quality_trim(trim_args->quality_threshold, trim_args->phred_encoding, trim_args->min_length, trim_args->min_mean_quality, &rec, &stats); if ( passed || trim_args->keep_empty) { if (gzip_output) { if (!gzprintf(output, "%s%s\n%s%s\n", rec.header, rec.sequence, rec.comment, rec.quality)) { fprintf(stderr, "Error writing to '%s': %s\n", outfile, strerror(errno)); exit(EXIT_FAILURE); } } else { if (!fprintf(output, "%s%s\n%s%s\n", rec.header, rec.sequence, rec.comment, rec.quality)) { fprintf(stderr, "Error writing to '%s': %s\n", outfile, strerror(errno)); exit(EXIT_FAILURE); } } } } print_stats(stats, trim_adapters, trim_quality); gzclose_r(input); if (gzip_output) gzclose_w(output); else fclose(output); // free(rec_ptr->header); // free(rec_ptr); // free(adapters.seqs[0]); // free(adapters.fail_mtrx[0]); } void print_usage() { fprintf(stderr, "Usage: razor [options] [in.fq]\n"); fprintf(stderr, "Options: \n"); fprintf(stderr, " -o, --output=FILE The file to output processed reads to. If unspecified, reads are written to stdout.\n"); fprintf(stderr, " -q, --quality-threshold=INT Trim bases from 5' and 3' ends using the ERNE-FILTER algorithm.\n"); fprintf(stderr, " -l, --min-length=INT After processing, discard sequences below a minimum length [20].\n"); fprintf(stderr, " -m, --min-mean-quality=INT After quality trimming, discard reads below a minimum mean quality.\n"); fprintf(stderr, " -a, --adapter=STR Adapter to be trimmed from the 3' ends of the reads.\n"); fprintf(stderr, " -f, --adapter-file=FILE Fasta file containing adapter sequences.\n"); fprintf(stderr, " -M, --min-adapter-match=INT The minimum number of leading bases a subsequence must share with an adapter\n" " for a match to occur [12].\n"); fprintf(stderr, " -k, --keep-empty Sequences filtered according to the min-length and min-mean-quality options\n" " have their sequence and quality strings truncated to empty and are retained.\n"); fprintf(stderr, " -p, --phred=[33|64] The phred encoding of the quality scores in the input fastq [33].\n"); fprintf(stderr, " --version Display version information and exit.\n"); fprintf(stderr, " --help Display this help text and exit.\n"); } void print_version() { fprintf(stderr, "Razor version %.1f\n", VERSION); } static struct option long_opts[] = { {"output", required_argument, 0, 'o'}, {"quality-threshold", required_argument, 0, 'q'}, {"min-length", required_argument, 0, 'l'}, {"min-mean-quality", required_argument, NULL, 'm'}, {"adapter", required_argument, 0, 'a'}, {"adapter-file", required_argument, 0, 'f'}, {"min-adapter-match", required_argument, 0, 'M'}, {"keep-empty", no_argument, 0, 'k'}, {"phred", required_argument, 0, 'p'}, {"help", no_argument, NULL, 2}, {"version", no_argument, NULL, 3}, {0, 0, 0, 0} }; int main(int argc, char *argv[]) { static char* infile; static char* outfile; static bool trim_adapters = false; static bool trim_quality = false; static struct TrimArgs trim_args = { .quality_threshold = 0, .min_length = 0, .min_mean_quality = 0, .adapter = NULL, .adapter_file = NULL, .min_adapter_match = 0, .keep_empty = false, .phred_encoding = 33, }; static const char* short_opts = "o:q:l:m:a:f:M:p:k"; int c; int index = 0; while((c = getopt_long(argc, argv, short_opts, long_opts, &index)) != -1){ switch(c){ case 'o': outfile = optarg; break; case 'q': trim_args.quality_threshold = atoi(optarg); break; case 'l': trim_args.min_length = atoi(optarg); break; case 'm': trim_args.min_mean_quality = atoi(optarg); break; case 'a': trim_args.adapter = optarg; break; case 'f': trim_args.adapter_file = optarg; break; case 'M': trim_args.min_adapter_match = atoi(optarg); break; case 'k': trim_args.keep_empty = true; break; case 'p': if (atoi(optarg) == 33 || atoi(optarg) == 64){ trim_args.phred_encoding = atoi(optarg); break; } print_usage(); return 1; case 2: print_usage(); return 0; case 3: print_version(); return 0; default: print_usage(); return 1; } } if (argc - optind != 1) { print_usage(); return EXIT_FAILURE; } if (trim_args.adapter || trim_args.adapter_file) { trim_adapters = true; if (!trim_args.min_adapter_match) trim_args.min_adapter_match = 12; } else { if (trim_args.min_adapter_match){ fprintf(stderr, "Error: option --min-adapter-match specified without adapter sequence(s)\n"); return EXIT_FAILURE; } // trim_adapters = false; } if (trim_args.quality_threshold) trim_quality = true; else { if (trim_args.min_mean_quality){ fprintf(stderr, "Error: option --min-mean-quality requires the -q option\n"); return EXIT_FAILURE; } if (!trim_adapters){ fprintf(stderr, "Error: must specify at least one of the following options: -q, -a, -f\n"); return EXIT_FAILURE; } // trim_quality = false; } if (!trim_args.min_length) trim_args.min_length = 20; infile = argv[optind]; process_reads(infile, outfile, trim_adapters, trim_quality, &trim_args); return EXIT_SUCCESS; }
25.479021
127
0.648072
d1c181c0ff92c18ad1f8d0e558afa3e472259426
8,997
h
C
Motif/Core/NSObject+ThemeClassAppliers.h
kunal30xi/Motif
b7a6bb6a20d28d5035e2c83aa2459ab83be14d8a
[ "MIT" ]
984
2015-04-20T23:03:01.000Z
2022-03-02T11:57:10.000Z
Motif/Core/NSObject+ThemeClassAppliers.h
kunal30xi/Motif
b7a6bb6a20d28d5035e2c83aa2459ab83be14d8a
[ "MIT" ]
67
2015-04-07T18:09:26.000Z
2022-01-17T21:50:49.000Z
Motif/Core/NSObject+ThemeClassAppliers.h
kunal30xi/Motif
b7a6bb6a20d28d5035e2c83aa2459ab83be14d8a
[ "MIT" ]
86
2015-04-11T00:00:05.000Z
2021-11-09T03:54:28.000Z
// // NSObject+ThemeAppliers.h // Motif // // Created by Eric Horacek on 12/25/14. // Copyright (c) 2015 Eric Horacek. All rights reserved. // @import Foundation; @class MTFThemeClass; @protocol MTFThemeClassApplicable; NS_ASSUME_NONNULL_BEGIN /** A block that is invoked to apply the property value to an instance of the class that this applier is registered with. @param propertyValue The property value that should be applied to the specified object. @param objectToTheme The object that should have the specified property value applied. */ typedef BOOL (^MTFThemePropertyApplierBlock)(id propertyValue, id objectToTheme, NSError **error); /// A block that is invoked to apply a property value to an instance of the /// class that this applier is registered with. /// /// @param propertyValue The property value that should be applied to the /// specified object, wrapping the desired Objective-C /// value. You should use -[NSValue getValue:] or one of /// the convenience getters, e.g. -[NSValue CGPointValue]. /// /// @param objectToTheme The object that should have the specified property /// value applied. typedef BOOL (^MTFThemePropertyObjCValueApplierBlock)(NSValue *propertyValue, id objectToTheme, NSError **error); /** A block that is invoked to apply the property values to an instance of the class that this applier is registered with. @param valuesForProperties A dictionary of theme class properties keyed by their names, with values of their theme property values. @param objectToTheme The object that should have the specified property values applied. */ typedef BOOL (^MTFThemePropertiesApplierBlock)(NSDictionary<NSString *, id> *valuesForProperties, id objectToTheme, NSError **error); @interface NSObject (ThemeAppliers) /** Registers a block that is invoked to apply a property value to an instance of the receiving class. @param property The name of the theme class property that this applier block is responsible for applying, e.g. "contentInsets". @param applierBlock The block that is invoked when the specified property is applied to an instance of the receiving class. @return An opaque theme class applier. You may discard this reference. */ + (id<MTFThemeClassApplicable>)mtf_registerThemeProperty:(NSString *)property applierBlock:(MTFThemePropertyApplierBlock)applierBlock; /** Registers a block that is invoked to apply a property value to an instance of the receiving class. Before invoking the block, uses the specified class to ensure that the property value is a kind of the correct class. @param property The name of the theme class property that this applier block is responsible for applying, e.g. "contentInsets". @param valueClass The class that the property value is required to be a kind of. @param applierBlock The block that is invoked when the specified property is applied to an instance of the receiving class. @return An opaque theme class applier. You may discard this reference. */ + (id<MTFThemeClassApplicable>)mtf_registerThemeProperty:(NSString *)property requiringValueOfClass:(Class)valueClass applierBlock:(MTFThemePropertyApplierBlock)applierBlock; /// Registers a block that is invoked to apply a property value to an instance /// of the receiving class. /// /// Before invoking the block, uses the specified value transformer to transform /// the property value. /// /// @param property The name of the theme class property that this applier /// block is responsible for applying, e.g. contentInsets. /// /// @param valueObjCType A C string containing the Objective-C type that the /// property value is required to be a kind of. Should be /// invoked with the value of the \@encode directive, e.g. /// `\@encode(CGPoint)`. /// /// @param applierBlock The block that is invoked when the specified property is /// applied to an instance of the receiving class. /// /// @return An opaque theme class applier. You may discard this reference. + (id<MTFThemeClassApplicable>)mtf_registerThemeProperty:(NSString *)property requiringValueOfObjCType:(const char *)valueObjCType applierBlock:(MTFThemePropertyObjCValueApplierBlock)applierBlock; /** Registers a block that is invoked to apply the property values to an instance of the receiving class. The block is only invoked when all of the specified properties are present. @param properties The names of the theme class properties that this applier block is responsible for applying. @param applierBlock The block that is invoked when the specified properties are applied to an instance of the receiving class. @return An opaque theme class applier. You may discard this reference. */ + (id<MTFThemeClassApplicable>)mtf_registerThemeProperties:(NSArray<NSString *> *)properties applierBlock:(MTFThemePropertiesApplierBlock)applierBlock; /** Registers a block that is invoked to apply the property values to an instance of the receiving class. The block is only invoked when all of the specified properties are present. Before invoking the block, uses the specified value transformer to transform the property values, or uses the specified required class to ensure that the property values are a kind of the correct class. @param properties The names of the theme class properties that this applier block is responsible for applying. @param valueTypes The classes or Objective-C types that the applied property values should be type of. Should be in the same order as the properties array, and consist of either Classes or NSString-wrapped Objective-C types, e.g. `NSString.class` or `@(\@encode(UIEdgeInsets))`. @param applierBlock The block that is invoked when the specified properties are applied to an instance of the receiving class. @return An opaque theme class applier. You may discard this reference. */ + (id<MTFThemeClassApplicable>)mtf_registerThemeProperties:(NSArray<NSString *> *)properties requiringValuesOfType:(NSArray *)valueTypes applierBlock:(MTFThemePropertiesApplierBlock)applierBlock; /// Registers a set of keywords that are each mapped to a specific value, such /// that when the specified property is applied with one of the keywords as its /// value, its corresponding value is set with KVC for the specified key path on /// the object that it was applied to. /// /// If the applied property value doesn't match the any of the keywords, the /// applier block returns NO and populates its pass-by-reference error. /// /// Examples /// /// // Applies a textAlignment theme property to UILabels /// [UILabel /// mtf_registerThemeProperty:@"textAlignment" /// forKeyPath:NSStringFromSelector(@selector(textAlignment)) /// withValuesByKeyword:@{ /// @"left": @(NSTextAlignmentLeft), /// @"center": @(NSTextAlignmentCenter), /// @"right": @(NSTextAlignmentRight), /// @"justified": @(NSTextAlignmentJustified), /// @"natural": @(NSTextAlignmentNatural) /// }]; /// /// @param property The name of the theme class property that this applier is /// responsible for applying. /// /// @param keyPath The key path that the values in the valuesByKeyword dictionary /// are set to. /// /// @param valuesByKeyword A dictionary that specifies a mapping from keywords in /// theme class properties to values that are set for the specified key path. /// /// @return An opaque theme class applier. You may discard this reference. + (id<MTFThemeClassApplicable>)mtf_registerThemeProperty:(NSString *)property forKeyPath:(NSString *)keyPath withValuesByKeyword:(NSDictionary<NSString *, id> *)valuesByKeyword; /// Registers the specified theme class applier with the receiving class. /// /// @param applier The applier to register. + (void)mtf_registerThemeClassApplier:(id<MTFThemeClassApplicable>)applier; /// Provides a convenience method for indicating that the application of a theme /// class was unsuccessful by returning NO and populating an error with a /// description of the failure from within an applier block. + (BOOL)mtf_populateApplierError:(NSError **)error withDescription:(NSString *)description; /// Invokes mtf_populateApplierError:withDescription: with the provided /// formatted string. + (BOOL)mtf_populateApplierError:(NSError **)error withDescriptionFormat:(NSString *)descriptionFormat, ... NS_FORMAT_FUNCTION(2,3); @end NS_ASSUME_NONNULL_END
45.670051
196
0.71535
4da0b4aadba6667332a5f85c9ebfc8f2da9c986b
71
h
C
IoTivityServerForRPI3/device/scale3.h
hollobit/CHITOS
17af33fea6fc22d8361d745c215608c12f2c04f3
[ "Apache-2.0" ]
null
null
null
IoTivityServerForRPI3/device/scale3.h
hollobit/CHITOS
17af33fea6fc22d8361d745c215608c12f2c04f3
[ "Apache-2.0" ]
null
null
null
IoTivityServerForRPI3/device/scale3.h
hollobit/CHITOS
17af33fea6fc22d8361d745c215608c12f2c04f3
[ "Apache-2.0" ]
null
null
null
#ifndef SCALE3_H #define SCALE3_H int createScale3Resource (); #endif
11.833333
28
0.788732
a2057f0fa9b92e0e6f3e994e21a3dced6ca7dcc3
291
h
C
repeater.h
Mount256/PVZ_Qt
3d0eece4e86f46faa18a861e979df05550b4a19e
[ "Apache-2.0" ]
1
2020-12-29T07:27:38.000Z
2020-12-29T07:27:38.000Z
repeater.h
Mount256/PVZ_Qt
3d0eece4e86f46faa18a861e979df05550b4a19e
[ "Apache-2.0" ]
null
null
null
repeater.h
Mount256/PVZ_Qt
3d0eece4e86f46faa18a861e979df05550b4a19e
[ "Apache-2.0" ]
2
2020-10-19T07:16:12.000Z
2021-09-28T07:01:22.000Z
#ifndef REPEATER_H #define REPEATER_H #include "plant.h" #include "pea.h" #include "map.h" class Repeater : public Plant { public: Repeater(QPointF point); ~Repeater(); void advance(int phase); private: Pea *pea; int peaCounter, peaCreateTime; }; #endif // REPEATER_H
14.55
34
0.680412
9ece8ba8c68562ba5eecf36103e4fac09385bd12
4,348
h
C
accelerator/proxy_apis.h
yiwei01/tangle-accelerator
a1ff9cf7e3ea75ab39a43a755bd05e256cfa1832
[ "MIT" ]
null
null
null
accelerator/proxy_apis.h
yiwei01/tangle-accelerator
a1ff9cf7e3ea75ab39a43a755bd05e256cfa1832
[ "MIT" ]
null
null
null
accelerator/proxy_apis.h
yiwei01/tangle-accelerator
a1ff9cf7e3ea75ab39a43a755bd05e256cfa1832
[ "MIT" ]
null
null
null
/* * Copyright (C) 2018-2019 BiiLabs Co., Ltd. and Contributors * All Rights Reserved. * This is free software; you can redistribute it and/or modify it under the * terms of the MIT license. A copy of the license can be found in the file * "LICENSE" at the root of this distribution. */ #ifndef ACCELERATOR_PROXY_APIS_H_ #define ACCELERATOR_PROXY_APIS_H_ #include "accelerator/errors.h" #include "cclient/api/core/core_api.h" #include "cclient/request/requests.h" #include "cclient/response/responses.h" #include "utils/logger_helper.h" #ifdef __cplusplus extern "C" { #endif /** * @file proxy_apis.h * @brief Implement Proxy APIs * * tangle-accelerator provides major IRI Proxy APIs wrapper. * The arguments and return strings are all in json format. There can be * different server or protocol integration with these APIs. */ /** * Initialize logger */ void proxy_apis_logger_init(); /** * Release logger * * @return * - zero on success * - EXIT_FAILURE on error */ int proxy_apis_logger_release(); /** * Initialize lock * * @return * - zero on success * - SC_CONF_LOCK_INIT on error */ status_t proxy_apis_lock_init(); /** * Destroy lock * * @return * - zero on success * - SC_CONF_LOCK_DESTROY on error */ status_t proxy_apis_lock_destroy(); /** * @brief Proxy API of checkConsistency * * @param[in] service IRI node end point service * @param[in] obj Transaction hashes to check * @param[out] json_result Result containing transaction objects in json format * * @return * - SC_OK on success * - non-zero on error */ status_t api_check_consistency(const iota_client_service_t* const service, const char* const obj, char** json_result); /** * @brief Return transaction hashes with given information such as bundle hashes, addresses, tags, or approvees. * * Explore transaction hash with given transaction related information. This would * return a list of transaction hashes in json format. * * @param[in] service IRI node end point service * @param[in] obj bundle hashes, addresses, tags, or approvees. * @param[out] json_result Result containing transaction objects in json format * * @return * - SC_OK on success * - non-zero on error */ status_t api_find_transactions(const iota_client_service_t* const service, const char* const obj, char** json_result); /** * @brief Proxy API of getBalances * * @param[in] service IRI node end point service * @param[in] obj Addresses, threshold or tips * @param[out] json_result Result containing transaction objects in json format * * @return * - SC_OK on success * - non-zero on error */ status_t api_get_balances(const iota_client_service_t* const service, const char* const obj, char** json_result); /** * @brief Proxy API of getInclusionStates * * @param[in] service IRI node end point service * @param[in] obj Transactions or tips * @param[out] json_result Result containing transaction objects in json format * * @return * - SC_OK on success * - non-zero on error */ status_t api_get_inclusion_states(const iota_client_service_t* const service, const char* const obj, char** json_result); /** * @brief Proxy API of getNodeInfo * * @param[in] service IRI node end point service * @param[out] json_result Result containing transaction objects in json format * * @return * - SC_OK on success * - non-zero on error */ status_t api_get_node_info(const iota_client_service_t* const service, char** json_result); /** * @brief Proxy API of getTrytes * * @param[in] service IRI node end point service * @param[in] obj Transaction hashes * @param[out] json_result Result containing transaction objects in json format * * @return * - SC_OK on success * - non-zero on error */ status_t api_get_trytes(const iota_client_service_t* const service, const char* const obj, char** json_result); /** * @brief Proxy API of removeNeighbors * * @param[in] service IRI node end point service * @param[in] obj Strings of neighbor URIs to remove * @param[out] json_result Result containing transaction objects in json format * * @return * - SC_OK on success * - non-zero on error */ status_t api_remove_neighbors(const iota_client_service_t* const service, const char* const obj, char** json_result); #ifdef __cplusplus } #endif #endif // ACCELERATOR_PROXY_APIS_H_
26.839506
118
0.728381
9ed932cf33ccf837b4c4a694f2f8be7ca1590831
55,145
c
C
src/session.c
joyent/haproxy-1.4
3b6ebfec1b72148c9628525f6ebe2e6d184960b1
[ "Adobe-Glyph" ]
4
2016-04-07T11:38:53.000Z
2020-01-14T06:29:14.000Z
src/session.c
joyent/haproxy-1.4
3b6ebfec1b72148c9628525f6ebe2e6d184960b1
[ "Adobe-Glyph" ]
null
null
null
src/session.c
joyent/haproxy-1.4
3b6ebfec1b72148c9628525f6ebe2e6d184960b1
[ "Adobe-Glyph" ]
13
2015-04-30T20:58:53.000Z
2021-02-25T14:02:54.000Z
/* * Server management functions. * * Copyright 2000-2008 Willy Tarreau <w@1wt.eu> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * */ #include <stdlib.h> #include <common/config.h> #include <common/debug.h> #include <common/memory.h> #include <types/capture.h> #include <types/global.h> #include <proto/acl.h> #include <proto/backend.h> #include <proto/buffers.h> #include <proto/checks.h> #include <proto/dumpstats.h> #include <proto/hdr_idx.h> #include <proto/log.h> #include <proto/session.h> #include <proto/pattern.h> #include <proto/pipe.h> #include <proto/proto_http.h> #include <proto/proto_tcp.h> #include <proto/proxy.h> #include <proto/queue.h> #include <proto/server.h> #include <proto/stick_table.h> #include <proto/stream_interface.h> #include <proto/stream_sock.h> #include <proto/task.h> struct pool_head *pool2_session; struct list sessions; /* * frees the context associated to a session. It must have been removed first. */ void session_free(struct session *s) { struct http_txn *txn = &s->txn; struct proxy *fe = s->fe; struct bref *bref, *back; int i; if (s->pend_pos) pendconn_free(s->pend_pos); if (s->srv) { /* there may be requests left pending in queue */ if (s->flags & SN_CURR_SESS) { s->flags &= ~SN_CURR_SESS; s->srv->cur_sess--; } if (may_dequeue_tasks(s->srv, s->be)) process_srv_queue(s->srv); } if (unlikely(s->srv_conn)) { /* the session still has a reserved slot on a server, but * it should normally be only the same as the one above, * so this should not happen in fact. */ sess_change_server(s, NULL); } if (s->req->pipe) put_pipe(s->req->pipe); if (s->rep->pipe) put_pipe(s->rep->pipe); pool_free2(pool2_buffer, s->req); pool_free2(pool2_buffer, s->rep); http_end_txn(s); for (i = 0; i < s->store_count; i++) { if (!s->store[i].ts) continue; stksess_free(s->store[i].table, s->store[i].ts); s->store[i].ts = NULL; } if (fe) { pool_free2(fe->hdr_idx_pool, txn->hdr_idx.v); pool_free2(fe->rsp_cap_pool, txn->rsp.cap); pool_free2(fe->req_cap_pool, txn->req.cap); } list_for_each_entry_safe(bref, back, &s->back_refs, users) { /* we have to unlink all watchers. We must not relink them if * this session was the last one in the list. */ LIST_DEL(&bref->users); LIST_INIT(&bref->users); if (s->list.n != &sessions) LIST_ADDQ(&LIST_ELEM(s->list.n, struct session *, list)->back_refs, &bref->users); bref->ref = s->list.n; } LIST_DEL(&s->list); pool_free2(pool2_session, s); /* We may want to free the maximum amount of pools if the proxy is stopping */ if (fe && unlikely(fe->state == PR_STSTOPPED)) { pool_flush2(pool2_buffer); pool_flush2(fe->hdr_idx_pool); pool_flush2(pool2_requri); pool_flush2(pool2_capture); pool_flush2(pool2_session); pool_flush2(fe->req_cap_pool); pool_flush2(fe->rsp_cap_pool); } } /* perform minimal intializations, report 0 in case of error, 1 if OK. */ int init_session() { LIST_INIT(&sessions); pool2_session = create_pool("session", sizeof(struct session), MEM_F_SHARED); return pool2_session != NULL; } void session_process_counters(struct session *s) { unsigned long long bytes; if (s->req) { bytes = s->req->total - s->logs.bytes_in; s->logs.bytes_in = s->req->total; if (bytes) { s->fe->counters.bytes_in += bytes; if (s->be != s->fe) s->be->counters.bytes_in += bytes; if (s->srv) s->srv->counters.bytes_in += bytes; if (s->listener->counters) s->listener->counters->bytes_in += bytes; } } if (s->rep) { bytes = s->rep->total - s->logs.bytes_out; s->logs.bytes_out = s->rep->total; if (bytes) { s->fe->counters.bytes_out += bytes; if (s->be != s->fe) s->be->counters.bytes_out += bytes; if (s->srv) s->srv->counters.bytes_out += bytes; if (s->listener->counters) s->listener->counters->bytes_out += bytes; } } } /* This function is called with (si->state == SI_ST_CON) meaning that a * connection was attempted and that the file descriptor is already allocated. * We must check for establishment, error and abort. Possible output states * are SI_ST_EST (established), SI_ST_CER (error), SI_ST_DIS (abort), and * SI_ST_CON (no change). The function returns 0 if it switches to SI_ST_CER, * otherwise 1. */ int sess_update_st_con_tcp(struct session *s, struct stream_interface *si) { struct buffer *req = si->ob; struct buffer *rep = si->ib; /* If we got an error, or if nothing happened and the connection timed * out, we must give up. The CER state handler will take care of retry * attempts and error reports. */ if (unlikely(si->flags & (SI_FL_EXP|SI_FL_ERR))) { si->exp = TICK_ETERNITY; si->state = SI_ST_CER; si->flags &= ~SI_FL_CAP_SPLICE; fd_delete(si->fd); if (si->err_type) return 0; si->err_loc = s->srv; if (si->flags & SI_FL_ERR) si->err_type = SI_ET_CONN_ERR; else si->err_type = SI_ET_CONN_TO; return 0; } /* OK, maybe we want to abort */ if (!(req->flags & BF_WRITE_PARTIAL) && unlikely((rep->flags & BF_SHUTW) || ((req->flags & BF_SHUTW_NOW) && /* FIXME: this should not prevent a connection from establishing */ (((req->flags & (BF_OUT_EMPTY|BF_WRITE_ACTIVITY)) == BF_OUT_EMPTY) || s->be->options & PR_O_ABRT_CLOSE)))) { /* give up */ si->shutw(si); si->err_type |= SI_ET_CONN_ABRT; si->err_loc = s->srv; si->flags &= ~SI_FL_CAP_SPLICE; if (s->srv_error) s->srv_error(s, si); return 1; } /* we need to wait a bit more if there was no activity either */ if (!(req->flags & BF_WRITE_ACTIVITY)) return 1; /* OK, this means that a connection succeeded. The caller will be * responsible for handling the transition from CON to EST. */ s->logs.t_connect = tv_ms_elapsed(&s->logs.tv_accept, &now); si->exp = TICK_ETERNITY; si->state = SI_ST_EST; si->err_type = SI_ET_NONE; si->err_loc = NULL; return 1; } /* This function is called with (si->state == SI_ST_CER) meaning that a * previous connection attempt has failed and that the file descriptor * has already been released. Possible causes include asynchronous error * notification and time out. Possible output states are SI_ST_CLO when * retries are exhausted, SI_ST_TAR when a delay is wanted before a new * connection attempt, SI_ST_ASS when it's wise to retry on the same server, * and SI_ST_REQ when an immediate redispatch is wanted. The buffers are * marked as in error state. It returns 0. */ int sess_update_st_cer(struct session *s, struct stream_interface *si) { /* we probably have to release last session from the server */ if (s->srv) { health_adjust(s->srv, HANA_STATUS_L4_ERR); if (s->flags & SN_CURR_SESS) { s->flags &= ~SN_CURR_SESS; s->srv->cur_sess--; } } /* ensure that we have enough retries left */ s->conn_retries--; if (s->conn_retries < 0) { if (!si->err_type) { si->err_type = SI_ET_CONN_ERR; si->err_loc = s->srv; } if (s->srv) s->srv->counters.failed_conns++; s->be->counters.failed_conns++; sess_change_server(s, NULL); if (may_dequeue_tasks(s->srv, s->be)) process_srv_queue(s->srv); /* shutw is enough so stop a connecting socket */ si->shutw(si); si->ob->flags |= BF_WRITE_ERROR; si->ib->flags |= BF_READ_ERROR; si->state = SI_ST_CLO; if (s->srv_error) s->srv_error(s, si); return 0; } /* If the "redispatch" option is set on the backend, we are allowed to * retry on another server for the last retry. In order to achieve this, * we must mark the session unassigned, and eventually clear the DIRECT * bit to ignore any persistence cookie. We won't count a retry nor a * redispatch yet, because this will depend on what server is selected. */ if (s->srv && s->conn_retries == 0 && s->be->options & PR_O_REDISP && !(s->flags & SN_FORCE_PRST)) { sess_change_server(s, NULL); if (may_dequeue_tasks(s->srv, s->be)) process_srv_queue(s->srv); s->flags &= ~(SN_DIRECT | SN_ASSIGNED | SN_ADDR_SET); s->prev_srv = s->srv; si->state = SI_ST_REQ; } else { if (s->srv) s->srv->counters.retries++; s->be->counters.retries++; si->state = SI_ST_ASS; } if (si->flags & SI_FL_ERR) { /* The error was an asynchronous connection error, and we will * likely have to retry connecting to the same server, most * likely leading to the same result. To avoid this, we wait * one second before retrying. */ if (!si->err_type) si->err_type = SI_ET_CONN_ERR; si->state = SI_ST_TAR; si->exp = tick_add(now_ms, MS_TO_TICKS(1000)); return 0; } return 0; } /* * This function handles the transition between the SI_ST_CON state and the * SI_ST_EST state. It must only be called after switching from SI_ST_CON to * SI_ST_EST. */ void sess_establish(struct session *s, struct stream_interface *si) { struct buffer *req = si->ob; struct buffer *rep = si->ib; if (s->srv) health_adjust(s->srv, HANA_STATUS_L4_OK); if (s->be->mode == PR_MODE_TCP) { /* let's allow immediate data connection in this case */ /* if the user wants to log as soon as possible, without counting * bytes from the server, then this is the right moment. */ if (s->fe->to_log && !(s->logs.logwait & LW_BYTES)) { s->logs.t_close = s->logs.t_connect; /* to get a valid end date */ s->do_log(s); } } else { s->txn.rsp.msg_state = HTTP_MSG_RPBEFORE; /* reset hdr_idx which was already initialized by the request. * right now, the http parser does it. * hdr_idx_init(&s->txn.hdr_idx); */ } rep->analysers |= s->fe->fe_rsp_ana | s->be->be_rsp_ana; rep->flags |= BF_READ_ATTACHED; /* producer is now attached */ req->wex = TICK_ETERNITY; } /* Update stream interface status for input states SI_ST_ASS, SI_ST_QUE, SI_ST_TAR. * Other input states are simply ignored. * Possible output states are SI_ST_CLO, SI_ST_TAR, SI_ST_ASS, SI_ST_REQ, SI_ST_CON. * Flags must have previously been updated for timeouts and other conditions. */ void sess_update_stream_int(struct session *s, struct stream_interface *si) { DPRINTF(stderr,"[%u] %s: sess=%p rq=%p, rp=%p, exp(r,w)=%u,%u rqf=%08x rpf=%08x rql=%d rpl=%d cs=%d ss=%d\n", now_ms, __FUNCTION__, s, s->req, s->rep, s->req->rex, s->rep->wex, s->req->flags, s->rep->flags, s->req->l, s->rep->l, s->rep->cons->state, s->req->cons->state); if (si->state == SI_ST_ASS) { /* Server assigned to connection request, we have to try to connect now */ int conn_err; conn_err = connect_server(s); if (conn_err == SN_ERR_NONE) { /* state = SI_ST_CON now */ if (s->srv) srv_inc_sess_ctr(s->srv); return; } /* We have received a synchronous error. We might have to * abort, retry immediately or redispatch. */ if (conn_err == SN_ERR_INTERNAL) { if (!si->err_type) { si->err_type = SI_ET_CONN_OTHER; si->err_loc = s->srv; } if (s->srv) srv_inc_sess_ctr(s->srv); if (s->srv) s->srv->counters.failed_conns++; s->be->counters.failed_conns++; /* release other sessions waiting for this server */ sess_change_server(s, NULL); if (may_dequeue_tasks(s->srv, s->be)) process_srv_queue(s->srv); /* Failed and not retryable. */ si->shutr(si); si->shutw(si); si->ob->flags |= BF_WRITE_ERROR; s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now); /* no session was ever accounted for this server */ si->state = SI_ST_CLO; if (s->srv_error) s->srv_error(s, si); return; } /* We are facing a retryable error, but we don't want to run a * turn-around now, as the problem is likely a source port * allocation problem, so we want to retry now. */ si->state = SI_ST_CER; si->flags &= ~SI_FL_ERR; sess_update_st_cer(s, si); /* now si->state is one of SI_ST_CLO, SI_ST_TAR, SI_ST_ASS, SI_ST_REQ */ return; } else if (si->state == SI_ST_QUE) { /* connection request was queued, check for any update */ if (!s->pend_pos) { /* The connection is not in the queue anymore. Either * we have a server connection slot available and we * go directly to the assigned state, or we need to * load-balance first and go to the INI state. */ si->exp = TICK_ETERNITY; if (unlikely(!(s->flags & SN_ASSIGNED))) si->state = SI_ST_REQ; else { s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now); si->state = SI_ST_ASS; } return; } /* Connection request still in queue... */ if (si->flags & SI_FL_EXP) { /* ... and timeout expired */ si->exp = TICK_ETERNITY; s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now); if (s->srv) s->srv->counters.failed_conns++; s->be->counters.failed_conns++; si->shutr(si); si->shutw(si); si->ob->flags |= BF_WRITE_TIMEOUT; if (!si->err_type) si->err_type = SI_ET_QUEUE_TO; si->state = SI_ST_CLO; if (s->srv_error) s->srv_error(s, si); return; } /* Connection remains in queue, check if we have to abort it */ if ((si->ob->flags & (BF_READ_ERROR)) || ((si->ob->flags & BF_SHUTW_NOW) && /* empty and client aborted */ (si->ob->flags & BF_OUT_EMPTY || s->be->options & PR_O_ABRT_CLOSE))) { /* give up */ si->exp = TICK_ETERNITY; s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now); si->shutr(si); si->shutw(si); si->err_type |= SI_ET_QUEUE_ABRT; si->state = SI_ST_CLO; if (s->srv_error) s->srv_error(s, si); return; } /* Nothing changed */ return; } else if (si->state == SI_ST_TAR) { /* Connection request might be aborted */ if ((si->ob->flags & (BF_READ_ERROR)) || ((si->ob->flags & BF_SHUTW_NOW) && /* empty and client aborted */ (si->ob->flags & BF_OUT_EMPTY || s->be->options & PR_O_ABRT_CLOSE))) { /* give up */ si->exp = TICK_ETERNITY; si->shutr(si); si->shutw(si); si->err_type |= SI_ET_CONN_ABRT; si->state = SI_ST_CLO; if (s->srv_error) s->srv_error(s, si); return; } if (!(si->flags & SI_FL_EXP)) return; /* still in turn-around */ si->exp = TICK_ETERNITY; /* we keep trying on the same server as long as the session is * marked "assigned". * FIXME: Should we force a redispatch attempt when the server is down ? */ if (s->flags & SN_ASSIGNED) si->state = SI_ST_ASS; else si->state = SI_ST_REQ; return; } } /* This function initiates a server connection request on a stream interface * already in SI_ST_REQ state. Upon success, the state goes to SI_ST_ASS, * indicating that a server has been assigned. It may also return SI_ST_QUE, * or SI_ST_CLO upon error. */ static void sess_prepare_conn_req(struct session *s, struct stream_interface *si) { DPRINTF(stderr,"[%u] %s: sess=%p rq=%p, rp=%p, exp(r,w)=%u,%u rqf=%08x rpf=%08x rql=%d rpl=%d cs=%d ss=%d\n", now_ms, __FUNCTION__, s, s->req, s->rep, s->req->rex, s->rep->wex, s->req->flags, s->rep->flags, s->req->l, s->rep->l, s->rep->cons->state, s->req->cons->state); if (si->state != SI_ST_REQ) return; /* Try to assign a server */ if (srv_redispatch_connect(s) != 0) { /* We did not get a server. Either we queued the * connection request, or we encountered an error. */ if (si->state == SI_ST_QUE) return; /* we did not get any server, let's check the cause */ si->shutr(si); si->shutw(si); si->ob->flags |= BF_WRITE_ERROR; if (!si->err_type) si->err_type = SI_ET_CONN_OTHER; si->state = SI_ST_CLO; if (s->srv_error) s->srv_error(s, si); return; } /* The server is assigned */ s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now); si->state = SI_ST_ASS; } /* This stream analyser checks the switching rules and changes the backend * if appropriate. The default_backend rule is also considered, then the * target backend's forced persistence rules are also evaluated last if any. * It returns 1 if the processing can continue on next analysers, or zero if it * either needs more data or wants to immediately abort the request. */ int process_switching_rules(struct session *s, struct buffer *req, int an_bit) { struct persist_rule *prst_rule; req->analysers &= ~an_bit; req->analyse_exp = TICK_ETERNITY; DPRINTF(stderr,"[%u] %s: session=%p b=%p, exp(r,w)=%u,%u bf=%08x bl=%d analysers=%02x\n", now_ms, __FUNCTION__, s, req, req->rex, req->wex, req->flags, req->l, req->analysers); /* now check whether we have some switching rules for this request */ if (!(s->flags & SN_BE_ASSIGNED)) { struct switching_rule *rule; list_for_each_entry(rule, &s->fe->switching_rules, list) { int ret; ret = acl_exec_cond(rule->cond, s->fe, s, &s->txn, ACL_DIR_REQ); ret = acl_pass(ret); if (rule->cond->pol == ACL_COND_UNLESS) ret = !ret; if (ret) { if (!session_set_backend(s, rule->be.backend)) goto sw_failed; break; } } /* To ensure correct connection accounting on the backend, we * have to assign one if it was not set (eg: a listen). This * measure also takes care of correctly setting the default * backend if any. */ if (!(s->flags & SN_BE_ASSIGNED)) if (!session_set_backend(s, s->fe->defbe.be ? s->fe->defbe.be : s->be)) goto sw_failed; } /* we don't want to run the HTTP filters again if the backend has not changed */ if (s->fe == s->be) s->req->analysers &= ~AN_REQ_HTTP_PROCESS_BE; /* as soon as we know the backend, we must check if we have a matching forced or ignored * persistence rule, and report that in the session. */ list_for_each_entry(prst_rule, &s->be->persist_rules, list) { int ret = 1; if (prst_rule->cond) { ret = acl_exec_cond(prst_rule->cond, s->be, s, &s->txn, ACL_DIR_REQ); ret = acl_pass(ret); if (prst_rule->cond->pol == ACL_COND_UNLESS) ret = !ret; } if (ret) { /* no rule, or the rule matches */ if (prst_rule->type == PERSIST_TYPE_FORCE) { s->flags |= SN_FORCE_PRST; } else { s->flags |= SN_IGNORE_PRST; } break; } } return 1; sw_failed: /* immediately abort this request in case of allocation failure */ buffer_abort(s->req); buffer_abort(s->rep); if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_RESOURCE; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_R; s->txn.status = 500; s->req->analysers = 0; s->req->analyse_exp = TICK_ETERNITY; return 0; } /* This stream analyser works on a request. It applies all sticking rules on * it then returns 1. The data must already be present in the buffer otherwise * they won't match. It always returns 1. */ int process_sticking_rules(struct session *s, struct buffer *req, int an_bit) { struct proxy *px = s->be; struct sticking_rule *rule; DPRINTF(stderr,"[%u] %s: session=%p b=%p, exp(r,w)=%u,%u bf=%08x bl=%d analysers=%02x\n", now_ms, __FUNCTION__, s, req, req->rex, req->wex, req->flags, req->l, req->analysers); list_for_each_entry(rule, &px->sticking_rules, list) { int ret = 1 ; int i; for (i = 0; i < s->store_count; i++) { if (rule->table.t == s->store[i].table) break; } if (i != s->store_count) continue; if (rule->cond) { ret = acl_exec_cond(rule->cond, px, s, &s->txn, ACL_DIR_REQ); ret = acl_pass(ret); if (rule->cond->pol == ACL_COND_UNLESS) ret = !ret; } if (ret) { struct stktable_key *key; key = pattern_process_key(px, s, &s->txn, PATTERN_FETCH_REQ, rule->expr, rule->table.t->type); if (!key) continue; if (rule->flags & STK_IS_MATCH) { struct stksess *ts; if ((ts = stktable_lookup(rule->table.t, key)) != NULL) { if (!(s->flags & SN_ASSIGNED)) { struct eb32_node *node; /* srv found in table */ node = eb32_lookup(&px->conf.used_server_id, ts->sid); if (node) { struct server *srv; srv = container_of(node, struct server, conf.id); if ((srv->state & SRV_RUNNING) || (px->options & PR_O_PERSIST) || (s->flags & SN_FORCE_PRST)) { s->flags |= SN_DIRECT | SN_ASSIGNED; s->srv = srv; } } } ts->expire = tick_add(now_ms, MS_TO_TICKS(rule->table.t->expire)); } } if (rule->flags & STK_IS_STORE) { if (s->store_count < (sizeof(s->store) / sizeof(s->store[0]))) { struct stksess *ts; ts = stksess_new(rule->table.t, key); if (ts) { s->store[s->store_count].table = rule->table.t; s->store[s->store_count++].ts = ts; } } } } } req->analysers &= ~an_bit; req->analyse_exp = TICK_ETERNITY; return 1; } /* This stream analyser works on a response. It applies all store rules on it * then returns 1. The data must already be present in the buffer otherwise * they won't match. It always returns 1. */ int process_store_rules(struct session *s, struct buffer *rep, int an_bit) { struct proxy *px = s->be; struct sticking_rule *rule; int i; DPRINTF(stderr,"[%u] %s: session=%p b=%p, exp(r,w)=%u,%u bf=%08x bl=%d analysers=%02x\n", now_ms, __FUNCTION__, s, rep, rep->rex, rep->wex, rep->flags, rep->l, rep->analysers); list_for_each_entry(rule, &px->storersp_rules, list) { int ret = 1 ; int storereqidx = -1; for (i = 0; i < s->store_count; i++) { if (rule->table.t == s->store[i].table) { if (!(s->store[i].flags)) storereqidx = i; break; } } if ((i != s->store_count) && (storereqidx == -1)) continue; if (rule->cond) { ret = acl_exec_cond(rule->cond, px, s, &s->txn, ACL_DIR_RTR); ret = acl_pass(ret); if (rule->cond->pol == ACL_COND_UNLESS) ret = !ret; } if (ret) { struct stktable_key *key; key = pattern_process_key(px, s, &s->txn, PATTERN_FETCH_RTR, rule->expr, rule->table.t->type); if (!key) continue; if (storereqidx != -1) { stksess_key(s->store[storereqidx].table, s->store[storereqidx].ts, key); s->store[storereqidx].flags = 1; } else if (s->store_count < (sizeof(s->store) / sizeof(s->store[0]))) { struct stksess *ts; ts = stksess_new(rule->table.t, key); if (ts) { s->store[s->store_count].table = rule->table.t; s->store[s->store_count].flags = 1; s->store[s->store_count++].ts = ts; } } } } /* process store request and store response */ for (i = 0; i < s->store_count; i++) { if (stktable_store(s->store[i].table, s->store[i].ts, s->srv->puid) > 0) stksess_free(s->store[i].table, s->store[i].ts); /* always remove pointer to session to ensure we won't free it again */ s->store[i].ts = NULL; } s->store_count = 0; /* everything is stored */ rep->analysers &= ~an_bit; rep->analyse_exp = TICK_ETERNITY; return 1; } /* This macro is very specific to the function below. See the comments in * process_session() below to understand the logic and the tests. */ #define UPDATE_ANALYSERS(real, list, back, flag) { \ list = (((list) & ~(flag)) | ~(back)) & (real); \ back = real; \ if (!(list)) \ break; \ if (((list) ^ ((list) & ((list) - 1))) < (flag)) \ continue; \ } /* Processes the client, server, request and response jobs of a session task, * then puts it back to the wait queue in a clean state, or cleans up its * resources if it must be deleted. Returns in <next> the date the task wants * to be woken up, or TICK_ETERNITY. In order not to call all functions for * nothing too many times, the request and response buffers flags are monitored * and each function is called only if at least another function has changed at * least one flag it is interested in. */ struct task *process_session(struct task *t) { struct session *s = t->context; unsigned int rqf_last, rpf_last; unsigned int req_ana_back; //DPRINTF(stderr, "%s:%d: cs=%d ss=%d(%d) rqf=0x%08x rpf=0x%08x\n", __FUNCTION__, __LINE__, // s->si[0].state, s->si[1].state, s->si[1].err_type, s->req->flags, s->rep->flags); /* this data may be no longer valid, clear it */ memset(&s->txn.auth, 0, sizeof(s->txn.auth)); /* This flag must explicitly be set every time */ s->req->flags &= ~BF_READ_NOEXP; /* Keep a copy of req/rep flags so that we can detect shutdowns */ rqf_last = s->req->flags; rpf_last = s->rep->flags; /* we don't want the stream interface functions to recursively wake us up */ if (s->req->prod->owner == t) s->req->prod->flags |= SI_FL_DONT_WAKE; if (s->req->cons->owner == t) s->req->cons->flags |= SI_FL_DONT_WAKE; /* 1a: Check for low level timeouts if needed. We just set a flag on * stream interfaces when their timeouts have expired. */ if (unlikely(t->state & TASK_WOKEN_TIMER)) { stream_int_check_timeouts(&s->si[0]); stream_int_check_timeouts(&s->si[1]); /* check buffer timeouts, and close the corresponding stream interfaces * for future reads or writes. Note: this will also concern upper layers * but we do not touch any other flag. We must be careful and correctly * detect state changes when calling them. */ buffer_check_timeouts(s->req); if (unlikely((s->req->flags & (BF_SHUTW|BF_WRITE_TIMEOUT)) == BF_WRITE_TIMEOUT)) { s->req->cons->flags |= SI_FL_NOLINGER; s->req->cons->shutw(s->req->cons); } if (unlikely((s->req->flags & (BF_SHUTR|BF_READ_TIMEOUT)) == BF_READ_TIMEOUT)) s->req->prod->shutr(s->req->prod); buffer_check_timeouts(s->rep); if (unlikely((s->rep->flags & (BF_SHUTW|BF_WRITE_TIMEOUT)) == BF_WRITE_TIMEOUT)) { s->rep->cons->flags |= SI_FL_NOLINGER; s->rep->cons->shutw(s->rep->cons); } if (unlikely((s->rep->flags & (BF_SHUTR|BF_READ_TIMEOUT)) == BF_READ_TIMEOUT)) s->rep->prod->shutr(s->rep->prod); } /* 1b: check for low-level errors reported at the stream interface. * First we check if it's a retryable error (in which case we don't * want to tell the buffer). Otherwise we report the error one level * upper by setting flags into the buffers. Note that the side towards * the client cannot have connect (hence retryable) errors. Also, the * connection setup code must be able to deal with any type of abort. */ if (unlikely(s->si[0].flags & SI_FL_ERR)) { if (s->si[0].state == SI_ST_EST || s->si[0].state == SI_ST_DIS) { s->si[0].shutr(&s->si[0]); s->si[0].shutw(&s->si[0]); stream_int_report_error(&s->si[0]); if (!(s->req->analysers) && !(s->rep->analysers)) { s->be->counters.cli_aborts++; if (s->srv) s->srv->counters.cli_aborts++; if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_CLICL; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_D; } } } if (unlikely(s->si[1].flags & SI_FL_ERR)) { if (s->si[1].state == SI_ST_EST || s->si[1].state == SI_ST_DIS) { s->si[1].shutr(&s->si[1]); s->si[1].shutw(&s->si[1]); stream_int_report_error(&s->si[1]); s->be->counters.failed_resp++; if (s->srv) s->srv->counters.failed_resp++; if (!(s->req->analysers) && !(s->rep->analysers)) { s->be->counters.srv_aborts++; if (s->srv) s->srv->counters.srv_aborts++; if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_SRVCL; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_D; } } /* note: maybe we should process connection errors here ? */ } if (s->si[1].state == SI_ST_CON) { /* we were trying to establish a connection on the server side, * maybe it succeeded, maybe it failed, maybe we timed out, ... */ if (unlikely(!sess_update_st_con_tcp(s, &s->si[1]))) sess_update_st_cer(s, &s->si[1]); else if (s->si[1].state == SI_ST_EST) sess_establish(s, &s->si[1]); /* state is now one of SI_ST_CON (still in progress), SI_ST_EST * (established), SI_ST_DIS (abort), SI_ST_CLO (last error), * SI_ST_ASS/SI_ST_TAR/SI_ST_REQ for retryable errors. */ } resync_stream_interface: /* Check for connection closure */ DPRINTF(stderr, "[%u] %s:%d: task=%p s=%p, sfl=0x%08x, rq=%p, rp=%p, exp(r,w)=%u,%u rqf=%08x rpf=%08x rql=%d rpl=%d cs=%d ss=%d, cet=0x%x set=0x%x retr=%d\n", now_ms, __FUNCTION__, __LINE__, t, s, s->flags, s->req, s->rep, s->req->rex, s->rep->wex, s->req->flags, s->rep->flags, s->req->l, s->rep->l, s->rep->cons->state, s->req->cons->state, s->rep->cons->err_type, s->req->cons->err_type, s->conn_retries); /* nothing special to be done on client side */ if (unlikely(s->req->prod->state == SI_ST_DIS)) s->req->prod->state = SI_ST_CLO; /* When a server-side connection is released, we have to count it and * check for pending connections on this server. */ if (unlikely(s->req->cons->state == SI_ST_DIS)) { s->req->cons->state = SI_ST_CLO; if (s->srv) { if (s->flags & SN_CURR_SESS) { s->flags &= ~SN_CURR_SESS; s->srv->cur_sess--; } sess_change_server(s, NULL); if (may_dequeue_tasks(s->srv, s->be)) process_srv_queue(s->srv); } if (s->req->cons->iohandler == stats_io_handler && s->req->cons->st0 == STAT_CLI_O_SESS && s->data_state == DATA_ST_LIST) { /* This is a fix for a design bug in the stats I/O handler : * "show sess $sess" may corrupt the struct session if not * properly detached. Unfortunately, in 1.4 there is no way * to ensure we always cleanly unregister an I/O handler upon * error. So we're doing the cleanup here if we can detect the * situation. */ if (!LIST_ISEMPTY(&s->data_ctx.sess.bref.users)) { LIST_DEL(&s->data_ctx.sess.bref.users); LIST_INIT(&s->data_ctx.sess.bref.users); } } } /* * Note: of the transient states (REQ, CER, DIS), only REQ may remain * at this point. */ resync_request: /* Analyse request */ if ((s->req->flags & BF_MASK_ANALYSER) || (s->req->flags ^ rqf_last) & BF_MASK_STATIC) { unsigned int flags = s->req->flags; if (s->req->prod->state >= SI_ST_EST) { int max_loops = global.tune.maxpollevents; unsigned int ana_list; unsigned int ana_back; /* it's up to the analysers to stop new connections, * disable reading or closing. Note: if an analyser * disables any of these bits, it is responsible for * enabling them again when it disables itself, so * that other analysers are called in similar conditions. */ buffer_auto_read(s->req); buffer_auto_connect(s->req); buffer_auto_close(s->req); /* We will call all analysers for which a bit is set in * s->req->analysers, following the bit order from LSB * to MSB. The analysers must remove themselves from * the list when not needed. Any analyser may return 0 * to break out of the loop, either because of missing * data to take a decision, or because it decides to * kill the session. We loop at least once through each * analyser, and we may loop again if other analysers * are added in the middle. * * We build a list of analysers to run. We evaluate all * of these analysers in the order of the lower bit to * the higher bit. This ordering is very important. * An analyser will often add/remove other analysers, * including itself. Any changes to itself have no effect * on the loop. If it removes any other analysers, we * want those analysers not to be called anymore during * this loop. If it adds an analyser that is located * after itself, we want it to be scheduled for being * processed during the loop. If it adds an analyser * which is located before it, we want it to switch to * it immediately, even if it has already been called * once but removed since. * * In order to achieve this, we compare the analyser * list after the call with a copy of it before the * call. The work list is fed with analyser bits that * appeared during the call. Then we compare previous * work list with the new one, and check the bits that * appeared. If the lowest of these bits is lower than * the current bit, it means we have enabled a previous * analyser and must immediately loop again. */ ana_list = ana_back = s->req->analysers; while (ana_list && max_loops--) { /* Warning! ensure that analysers are always placed in ascending order! */ if (ana_list & AN_REQ_INSPECT) { if (!tcp_inspect_request(s, s->req, AN_REQ_INSPECT)) break; UPDATE_ANALYSERS(s->req->analysers, ana_list, ana_back, AN_REQ_INSPECT); } if (ana_list & AN_REQ_WAIT_HTTP) { if (!http_wait_for_request(s, s->req, AN_REQ_WAIT_HTTP)) break; UPDATE_ANALYSERS(s->req->analysers, ana_list, ana_back, AN_REQ_WAIT_HTTP); } if (ana_list & AN_REQ_HTTP_PROCESS_FE) { if (!http_process_req_common(s, s->req, AN_REQ_HTTP_PROCESS_FE, s->fe)) break; UPDATE_ANALYSERS(s->req->analysers, ana_list, ana_back, AN_REQ_HTTP_PROCESS_FE); } if (ana_list & AN_REQ_SWITCHING_RULES) { if (!process_switching_rules(s, s->req, AN_REQ_SWITCHING_RULES)) break; UPDATE_ANALYSERS(s->req->analysers, ana_list, ana_back, AN_REQ_SWITCHING_RULES); } if (ana_list & AN_REQ_HTTP_PROCESS_BE) { if (!http_process_req_common(s, s->req, AN_REQ_HTTP_PROCESS_BE, s->be)) break; UPDATE_ANALYSERS(s->req->analysers, ana_list, ana_back, AN_REQ_HTTP_PROCESS_BE); } if (ana_list & AN_REQ_HTTP_TARPIT) { if (!http_process_tarpit(s, s->req, AN_REQ_HTTP_TARPIT)) break; UPDATE_ANALYSERS(s->req->analysers, ana_list, ana_back, AN_REQ_HTTP_TARPIT); } if (ana_list & AN_REQ_HTTP_INNER) { if (!http_process_request(s, s->req, AN_REQ_HTTP_INNER)) break; UPDATE_ANALYSERS(s->req->analysers, ana_list, ana_back, AN_REQ_HTTP_INNER); } if (ana_list & AN_REQ_HTTP_BODY) { if (!http_process_request_body(s, s->req, AN_REQ_HTTP_BODY)) break; UPDATE_ANALYSERS(s->req->analysers, ana_list, ana_back, AN_REQ_HTTP_BODY); } if (ana_list & AN_REQ_PRST_RDP_COOKIE) { if (!tcp_persist_rdp_cookie(s, s->req, AN_REQ_PRST_RDP_COOKIE)) break; UPDATE_ANALYSERS(s->req->analysers, ana_list, ana_back, AN_REQ_PRST_RDP_COOKIE); } if (ana_list & AN_REQ_STICKING_RULES) { if (!process_sticking_rules(s, s->req, AN_REQ_STICKING_RULES)) break; UPDATE_ANALYSERS(s->req->analysers, ana_list, ana_back, AN_REQ_STICKING_RULES); } if (ana_list & AN_REQ_HTTP_XFER_BODY) { if (!http_request_forward_body(s, s->req, AN_REQ_HTTP_XFER_BODY)) break; UPDATE_ANALYSERS(s->req->analysers, ana_list, ana_back, AN_REQ_HTTP_XFER_BODY); } break; } } if ((s->req->flags ^ flags) & BF_MASK_STATIC) { rqf_last = s->req->flags; goto resync_request; } } /* we'll monitor the request analysers while parsing the response, * because some response analysers may indirectly enable new request * analysers (eg: HTTP keep-alive). */ req_ana_back = s->req->analysers; resync_response: /* Analyse response */ if (unlikely(s->rep->flags & BF_HIJACK)) { /* In inject mode, we wake up everytime something has * happened on the write side of the buffer. */ unsigned int flags = s->rep->flags; if ((s->rep->flags & (BF_WRITE_PARTIAL|BF_WRITE_ERROR|BF_SHUTW)) && !(s->rep->flags & BF_FULL)) { s->rep->hijacker(s, s->rep); } if ((s->rep->flags ^ flags) & BF_MASK_STATIC) { rpf_last = s->rep->flags; goto resync_response; } } else if ((s->rep->flags & BF_MASK_ANALYSER) || (s->rep->flags ^ rpf_last) & BF_MASK_STATIC) { unsigned int flags = s->rep->flags; if (s->rep->prod->state >= SI_ST_EST) { int max_loops = global.tune.maxpollevents; unsigned int ana_list; unsigned int ana_back; /* it's up to the analysers to stop disable reading or * closing. Note: if an analyser disables any of these * bits, it is responsible for enabling them again when * it disables itself, so that other analysers are called * in similar conditions. */ buffer_auto_read(s->rep); buffer_auto_close(s->rep); /* We will call all analysers for which a bit is set in * s->rep->analysers, following the bit order from LSB * to MSB. The analysers must remove themselves from * the list when not needed. Any analyser may return 0 * to break out of the loop, either because of missing * data to take a decision, or because it decides to * kill the session. We loop at least once through each * analyser, and we may loop again if other analysers * are added in the middle. */ ana_list = ana_back = s->rep->analysers; while (ana_list && max_loops--) { /* Warning! ensure that analysers are always placed in ascending order! */ if (ana_list & AN_RES_WAIT_HTTP) { if (!http_wait_for_response(s, s->rep, AN_RES_WAIT_HTTP)) break; UPDATE_ANALYSERS(s->rep->analysers, ana_list, ana_back, AN_RES_WAIT_HTTP); } if (ana_list & AN_RES_STORE_RULES) { if (!process_store_rules(s, s->rep, AN_RES_STORE_RULES)) break; UPDATE_ANALYSERS(s->rep->analysers, ana_list, ana_back, AN_RES_STORE_RULES); } if (ana_list & AN_RES_HTTP_PROCESS_BE) { if (!http_process_res_common(s, s->rep, AN_RES_HTTP_PROCESS_BE, s->be)) break; UPDATE_ANALYSERS(s->rep->analysers, ana_list, ana_back, AN_RES_HTTP_PROCESS_BE); } if (ana_list & AN_RES_HTTP_XFER_BODY) { if (!http_response_forward_body(s, s->rep, AN_RES_HTTP_XFER_BODY)) break; UPDATE_ANALYSERS(s->rep->analysers, ana_list, ana_back, AN_RES_HTTP_XFER_BODY); } break; } } if ((s->rep->flags ^ flags) & BF_MASK_STATIC) { rpf_last = s->rep->flags; goto resync_response; } } /* maybe someone has added some request analysers, so we must check and loop */ if (s->req->analysers & ~req_ana_back) goto resync_request; /* FIXME: here we should call protocol handlers which rely on * both buffers. */ /* * Now we propagate unhandled errors to the session. Normally * we're just in a data phase here since it means we have not * seen any analyser who could set an error status. */ if (!(s->flags & SN_ERR_MASK)) { if (s->req->flags & (BF_READ_ERROR|BF_READ_TIMEOUT|BF_WRITE_ERROR|BF_WRITE_TIMEOUT)) { /* Report it if the client got an error or a read timeout expired */ s->req->analysers = 0; if (s->req->flags & BF_READ_ERROR) { s->be->counters.cli_aborts++; if (s->srv) s->srv->counters.cli_aborts++; s->flags |= SN_ERR_CLICL; } else if (s->req->flags & BF_READ_TIMEOUT) { s->be->counters.cli_aborts++; if (s->srv) s->srv->counters.cli_aborts++; s->flags |= SN_ERR_CLITO; } else if (s->req->flags & BF_WRITE_ERROR) { s->be->counters.srv_aborts++; if (s->srv) s->srv->counters.srv_aborts++; s->flags |= SN_ERR_SRVCL; } else { s->be->counters.srv_aborts++; if (s->srv) s->srv->counters.srv_aborts++; s->flags |= SN_ERR_SRVTO; } sess_set_term_flags(s); } else if (s->rep->flags & (BF_READ_ERROR|BF_READ_TIMEOUT|BF_WRITE_ERROR|BF_WRITE_TIMEOUT)) { /* Report it if the server got an error or a read timeout expired */ s->rep->analysers = 0; if (s->rep->flags & BF_READ_ERROR) { s->be->counters.srv_aborts++; if (s->srv) s->srv->counters.srv_aborts++; s->flags |= SN_ERR_SRVCL; } else if (s->rep->flags & BF_READ_TIMEOUT) { s->be->counters.srv_aborts++; if (s->srv) s->srv->counters.srv_aborts++; s->flags |= SN_ERR_SRVTO; } else if (s->rep->flags & BF_WRITE_ERROR) { s->be->counters.cli_aborts++; if (s->srv) s->srv->counters.cli_aborts++; s->flags |= SN_ERR_CLICL; } else { s->be->counters.cli_aborts++; if (s->srv) s->srv->counters.cli_aborts++; s->flags |= SN_ERR_CLITO; } sess_set_term_flags(s); } } /* * Here we take care of forwarding unhandled data. This also includes * connection establishments and shutdown requests. */ /* If noone is interested in analysing data, it's time to forward * everything. We configure the buffer to forward indefinitely. */ if (!s->req->analysers && !(s->req->flags & (BF_HIJACK|BF_SHUTW|BF_SHUTW_NOW)) && (s->req->prod->state >= SI_ST_EST) && (s->req->to_forward != BUF_INFINITE_FORWARD)) { /* This buffer is freewheeling, there's no analyser nor hijacker * attached to it. If any data are left in, we'll permit them to * move. */ buffer_auto_read(s->req); buffer_auto_connect(s->req); buffer_auto_close(s->req); buffer_flush(s->req); /* If the producer is still connected, we'll enable data to flow * from the producer to the consumer (which might possibly not be * connected yet). */ if (!(s->req->flags & (BF_SHUTR|BF_SHUTW|BF_SHUTW_NOW))) buffer_forward(s->req, BUF_INFINITE_FORWARD); } /* check if it is wise to enable kernel splicing to forward request data */ if (!(s->req->flags & (BF_KERN_SPLICING|BF_SHUTR)) && s->req->to_forward && (global.tune.options & GTUNE_USE_SPLICE) && (s->si[0].flags & s->si[1].flags & SI_FL_CAP_SPLICE) && (pipes_used < global.maxpipes) && (((s->fe->options2|s->be->options2) & PR_O2_SPLIC_REQ) || (((s->fe->options2|s->be->options2) & PR_O2_SPLIC_AUT) && (s->req->flags & BF_STREAMER_FAST)))) { s->req->flags |= BF_KERN_SPLICING; } /* reflect what the L7 analysers have seen last */ rqf_last = s->req->flags; /* * Now forward all shutdown requests between both sides of the buffer */ /* first, let's check if the request buffer needs to shutdown(write), which may * happen either because the input is closed or because we want to force a close * once the server has begun to respond. */ if (unlikely((s->req->flags & (BF_SHUTW|BF_SHUTW_NOW|BF_HIJACK|BF_AUTO_CLOSE|BF_SHUTR)) == (BF_AUTO_CLOSE|BF_SHUTR))) buffer_shutw_now(s->req); /* shutdown(write) pending */ if (unlikely((s->req->flags & (BF_SHUTW|BF_SHUTW_NOW|BF_OUT_EMPTY)) == (BF_SHUTW_NOW|BF_OUT_EMPTY))) { if (s->req->flags & BF_READ_ERROR) s->req->cons->flags |= SI_FL_NOLINGER; s->req->cons->shutw(s->req->cons); } /* shutdown(write) done on server side, we must stop the client too */ if (unlikely((s->req->flags & (BF_SHUTW|BF_SHUTR|BF_SHUTR_NOW)) == BF_SHUTW && !s->req->analysers)) buffer_shutr_now(s->req); /* shutdown(read) pending */ if (unlikely((s->req->flags & (BF_SHUTR|BF_SHUTR_NOW)) == BF_SHUTR_NOW)) s->req->prod->shutr(s->req->prod); /* it's possible that an upper layer has requested a connection setup or abort. * There are 2 situations where we decide to establish a new connection : * - there are data scheduled for emission in the buffer * - the BF_AUTO_CONNECT flag is set (active connection) */ if (s->req->cons->state == SI_ST_INI) { if (!(s->req->flags & BF_SHUTW)) { if ((s->req->flags & (BF_AUTO_CONNECT|BF_OUT_EMPTY)) != BF_OUT_EMPTY) { /* If we have a ->connect method, we need to perform a connection request, * otherwise we immediately switch to the connected state. */ if (s->req->cons->connect) s->req->cons->state = SI_ST_REQ; /* new connection requested */ else s->req->cons->state = SI_ST_EST; /* connection established */ } } else { s->req->cons->state = SI_ST_CLO; /* shutw+ini = abort */ buffer_shutw_now(s->req); /* fix buffer flags upon abort */ buffer_shutr_now(s->rep); } } /* we may have a pending connection request, or a connection waiting * for completion. */ if (s->si[1].state >= SI_ST_REQ && s->si[1].state < SI_ST_CON) { do { /* nb: step 1 might switch from QUE to ASS, but we first want * to give a chance to step 2 to perform a redirect if needed. */ if (s->si[1].state != SI_ST_REQ) sess_update_stream_int(s, &s->si[1]); if (s->si[1].state == SI_ST_REQ) sess_prepare_conn_req(s, &s->si[1]); if (s->si[1].state == SI_ST_ASS && s->srv && s->srv->rdr_len && (s->flags & SN_REDIRECTABLE)) perform_http_redirect(s, &s->si[1]); } while (s->si[1].state == SI_ST_ASS); /* Now we can add the server name to a header (if requested) */ /* check for HTTP mode and proxy server_name_hdr_name != NULL */ if ((s->flags & SN_BE_ASSIGNED) && (s->be->mode == PR_MODE_HTTP) && (s->be->server_id_hdr_name != NULL) && (s->srv)) { http_send_name_header(&s->txn, &s->txn.req, s->req, s->be, s->srv->id); } } /* Benchmarks have shown that it's optimal to do a full resync now */ if (s->req->prod->state == SI_ST_DIS || s->req->cons->state == SI_ST_DIS) goto resync_stream_interface; /* otherwise wewant to check if we need to resync the req buffer or not */ if ((s->req->flags ^ rqf_last) & BF_MASK_STATIC) goto resync_request; /* perform output updates to the response buffer */ /* If noone is interested in analysing data, it's time to forward * everything. We configure the buffer to forward indefinitely. */ if (!s->rep->analysers && !(s->rep->flags & (BF_HIJACK|BF_SHUTW|BF_SHUTW_NOW)) && (s->rep->prod->state >= SI_ST_EST) && (s->rep->to_forward != BUF_INFINITE_FORWARD)) { /* This buffer is freewheeling, there's no analyser nor hijacker * attached to it. If any data are left in, we'll permit them to * move. */ buffer_auto_read(s->rep); buffer_auto_close(s->rep); buffer_flush(s->rep); if (!(s->rep->flags & (BF_SHUTR|BF_SHUTW|BF_SHUTW_NOW))) buffer_forward(s->rep, BUF_INFINITE_FORWARD); } /* check if it is wise to enable kernel splicing to forward response data */ if (!(s->rep->flags & (BF_KERN_SPLICING|BF_SHUTR)) && s->rep->to_forward && (global.tune.options & GTUNE_USE_SPLICE) && (s->si[0].flags & s->si[1].flags & SI_FL_CAP_SPLICE) && (pipes_used < global.maxpipes) && (((s->fe->options2|s->be->options2) & PR_O2_SPLIC_RTR) || (((s->fe->options2|s->be->options2) & PR_O2_SPLIC_AUT) && (s->rep->flags & BF_STREAMER_FAST)))) { s->rep->flags |= BF_KERN_SPLICING; } /* reflect what the L7 analysers have seen last */ rpf_last = s->rep->flags; /* * Now forward all shutdown requests between both sides of the buffer */ /* * FIXME: this is probably where we should produce error responses. */ /* first, let's check if the response buffer needs to shutdown(write) */ if (unlikely((s->rep->flags & (BF_SHUTW|BF_SHUTW_NOW|BF_HIJACK|BF_AUTO_CLOSE|BF_SHUTR)) == (BF_AUTO_CLOSE|BF_SHUTR))) buffer_shutw_now(s->rep); /* shutdown(write) pending */ if (unlikely((s->rep->flags & (BF_SHUTW|BF_OUT_EMPTY|BF_SHUTW_NOW)) == (BF_OUT_EMPTY|BF_SHUTW_NOW))) s->rep->cons->shutw(s->rep->cons); /* shutdown(write) done on the client side, we must stop the server too */ if (unlikely((s->rep->flags & (BF_SHUTW|BF_SHUTR|BF_SHUTR_NOW)) == BF_SHUTW) && !s->rep->analysers) buffer_shutr_now(s->rep); /* shutdown(read) pending */ if (unlikely((s->rep->flags & (BF_SHUTR|BF_SHUTR_NOW)) == BF_SHUTR_NOW)) s->rep->prod->shutr(s->rep->prod); if (s->req->prod->state == SI_ST_DIS || s->req->cons->state == SI_ST_DIS) goto resync_stream_interface; if (s->req->flags != rqf_last) goto resync_request; if ((s->rep->flags ^ rpf_last) & BF_MASK_STATIC) goto resync_response; /* we're interested in getting wakeups again */ s->req->prod->flags &= ~SI_FL_DONT_WAKE; s->req->cons->flags &= ~SI_FL_DONT_WAKE; /* This is needed only when debugging is enabled, to indicate * client-side or server-side close. Please note that in the unlikely * event where both sides would close at once, the sequence is reported * on the server side first. */ if (unlikely((global.mode & MODE_DEBUG) && (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) { int len; if (s->si[1].state == SI_ST_CLO && s->si[1].prev_state == SI_ST_EST) { len = sprintf(trash, "%08x:%s.srvcls[%04x:%04x]\n", s->uniq_id, s->be->id, (unsigned short)s->si[0].fd, (unsigned short)s->si[1].fd); if (write(1, trash, len) < 0) /* shut gcc warning */; } if (s->si[0].state == SI_ST_CLO && s->si[0].prev_state == SI_ST_EST) { len = sprintf(trash, "%08x:%s.clicls[%04x:%04x]\n", s->uniq_id, s->be->id, (unsigned short)s->si[0].fd, (unsigned short)s->si[1].fd); if (write(1, trash, len) < 0) /* shut gcc warning */; } } if (likely((s->rep->cons->state != SI_ST_CLO) || (s->req->cons->state > SI_ST_INI && s->req->cons->state < SI_ST_CLO))) { if ((s->fe->options & PR_O_CONTSTATS) && (s->flags & SN_BE_ASSIGNED)) session_process_counters(s); if (s->rep->cons->state == SI_ST_EST && !s->rep->cons->iohandler) s->rep->cons->update(s->rep->cons); if (s->req->cons->state == SI_ST_EST && !s->req->cons->iohandler) s->req->cons->update(s->req->cons); s->req->flags &= ~(BF_READ_NULL|BF_READ_PARTIAL|BF_WRITE_NULL|BF_WRITE_PARTIAL); s->rep->flags &= ~(BF_READ_NULL|BF_READ_PARTIAL|BF_WRITE_NULL|BF_WRITE_PARTIAL); s->si[0].prev_state = s->si[0].state; s->si[1].prev_state = s->si[1].state; s->si[0].flags &= ~(SI_FL_ERR|SI_FL_EXP); s->si[1].flags &= ~(SI_FL_ERR|SI_FL_EXP); /* Trick: if a request is being waiting for the server to respond, * and if we know the server can timeout, we don't want the timeout * to expire on the client side first, but we're still interested * in passing data from the client to the server (eg: POST). Thus, * we can cancel the client's request timeout if the server's * request timeout is set and the server has not yet sent a response. */ if ((s->rep->flags & (BF_AUTO_CLOSE|BF_SHUTR)) == 0 && (tick_isset(s->req->wex) || tick_isset(s->rep->rex))) { s->req->flags |= BF_READ_NOEXP; s->req->rex = TICK_ETERNITY; } /* Call the second stream interface's I/O handler if it's embedded. * Note that this one may wake the task up again. */ if (s->req->cons->iohandler) { s->req->cons->iohandler(s->req->cons); if (task_in_rq(t)) { /* If we woke up, we don't want to requeue the * task to the wait queue, but rather requeue * it into the runqueue ASAP. */ t->expire = TICK_ETERNITY; return t; } } t->expire = tick_first(tick_first(s->req->rex, s->req->wex), tick_first(s->rep->rex, s->rep->wex)); if (s->req->analysers) t->expire = tick_first(t->expire, s->req->analyse_exp); if (s->si[0].exp) t->expire = tick_first(t->expire, s->si[0].exp); if (s->si[1].exp) t->expire = tick_first(t->expire, s->si[1].exp); #ifdef DEBUG_FULL fprintf(stderr, "[%u] queuing with exp=%u req->rex=%u req->wex=%u req->ana_exp=%u" " rep->rex=%u rep->wex=%u, si[0].exp=%u, si[1].exp=%u, cs=%d, ss=%d\n", now_ms, t->expire, s->req->rex, s->req->wex, s->req->analyse_exp, s->rep->rex, s->rep->wex, s->si[0].exp, s->si[1].exp, s->si[0].state, s->si[1].state); #endif #ifdef DEBUG_DEV /* this may only happen when no timeout is set or in case of an FSM bug */ if (!tick_isset(t->expire)) ABORT_NOW(); #endif return t; /* nothing more to do */ } s->fe->feconn--; if (s->flags & SN_BE_ASSIGNED) s->be->beconn--; actconn--; s->listener->nbconn--; if (s->listener->state == LI_FULL && s->listener->nbconn < s->listener->maxconn) { /* we should reactivate the listener */ EV_FD_SET(s->listener->fd, DIR_RD); s->listener->state = LI_READY; } if (unlikely((global.mode & MODE_DEBUG) && (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)))) { int len; len = sprintf(trash, "%08x:%s.closed[%04x:%04x]\n", s->uniq_id, s->be->id, (unsigned short)s->req->prod->fd, (unsigned short)s->req->cons->fd); if (write(1, trash, len) < 0) /* shut gcc warning */; } s->logs.t_close = tv_ms_elapsed(&s->logs.tv_accept, &now); session_process_counters(s); if (s->txn.status) { int n; n = s->txn.status / 100; if (n < 1 || n > 5) n = 0; if (s->fe->mode == PR_MODE_HTTP) s->fe->counters.fe.http.rsp[n]++; if ((s->flags & SN_BE_ASSIGNED) && (s->be->mode == PR_MODE_HTTP)) s->be->counters.be.http.rsp[n]++; } /* let's do a final log if we need it */ if (s->logs.logwait && !(s->flags & SN_MONITOR) && (!(s->fe->options & PR_O_NULLNOLOG) || s->req->total)) { s->do_log(s); } /* the task MUST not be in the run queue anymore */ session_free(s); task_delete(t); task_free(t); return NULL; } /* * This function adjusts sess->srv_conn and maintains the previous and new * server's served session counts. Setting newsrv to NULL is enough to release * current connection slot. This function also notifies any LB algo which might * expect to be informed about any change in the number of active sessions on a * server. */ void sess_change_server(struct session *sess, struct server *newsrv) { if (sess->srv_conn == newsrv) return; if (sess->srv_conn) { sess->srv_conn->served--; if (sess->srv_conn->proxy->lbprm.server_drop_conn) sess->srv_conn->proxy->lbprm.server_drop_conn(sess->srv_conn); sess->srv_conn = NULL; } if (newsrv) { newsrv->served++; if (newsrv->proxy->lbprm.server_take_conn) newsrv->proxy->lbprm.server_take_conn(newsrv); sess->srv_conn = newsrv; } } /* Set correct session termination flags in case no analyser has done it. It * also counts a failed request if the server state has not reached the request * stage. */ void sess_set_term_flags(struct session *s) { if (!(s->flags & SN_FINST_MASK)) { if (s->si[1].state < SI_ST_REQ) { s->fe->counters.failed_req++; if (s->listener->counters) s->listener->counters->failed_req++; s->flags |= SN_FINST_R; } else if (s->si[1].state == SI_ST_QUE) s->flags |= SN_FINST_Q; else if (s->si[1].state < SI_ST_EST) s->flags |= SN_FINST_C; else if (s->si[1].state == SI_ST_EST || s->si[1].prev_state == SI_ST_EST) s->flags |= SN_FINST_D; else s->flags |= SN_FINST_L; } } /* Handle server-side errors for default protocols. It is called whenever a a * connection setup is aborted or a request is aborted in queue. It sets the * session termination flags so that the caller does not have to worry about * them. It's installed as ->srv_error for the server-side stream_interface. */ void default_srv_error(struct session *s, struct stream_interface *si) { int err_type = si->err_type; int err = 0, fin = 0; if (err_type & SI_ET_QUEUE_ABRT) { err = SN_ERR_CLICL; fin = SN_FINST_Q; } else if (err_type & SI_ET_CONN_ABRT) { err = SN_ERR_CLICL; fin = SN_FINST_C; } else if (err_type & SI_ET_QUEUE_TO) { err = SN_ERR_SRVTO; fin = SN_FINST_Q; } else if (err_type & SI_ET_QUEUE_ERR) { err = SN_ERR_SRVCL; fin = SN_FINST_Q; } else if (err_type & SI_ET_CONN_TO) { err = SN_ERR_SRVTO; fin = SN_FINST_C; } else if (err_type & SI_ET_CONN_ERR) { err = SN_ERR_SRVCL; fin = SN_FINST_C; } else /* SI_ET_CONN_OTHER and others */ { err = SN_ERR_INTERNAL; fin = SN_FINST_C; } if (!(s->flags & SN_ERR_MASK)) s->flags |= err; if (!(s->flags & SN_FINST_MASK)) s->flags |= fin; } /* * Local variables: * c-indent-level: 8 * c-basic-offset: 8 * End: */
30.841723
144
0.648672
b101a315c9b7929e2ac90c07b774f6fa6db88c1b
206
h
C
src/graphox/filesystem.h
graphox/graphox
748fd7dd2f3fef4ad5981ea3f9a2081746389a33
[ "Cube", "Zlib" ]
1
2019-10-25T06:00:44.000Z
2019-10-25T06:00:44.000Z
src/graphox/filesystem.h
graphox/graphox
748fd7dd2f3fef4ad5981ea3f9a2081746389a33
[ "Cube", "Zlib" ]
null
null
null
src/graphox/filesystem.h
graphox/graphox
748fd7dd2f3fef4ad5981ea3f9a2081746389a33
[ "Cube", "Zlib" ]
null
null
null
#ifndef GRAPHOX_FILESYSTEM_H #define GRAPHOX_FILESYSTEM_H namespace graphox { namespace filesystem { char *locate(const char *fname); #ifdef OFTL types::String *locate(); #endif } } #endif
11.444444
34
0.713592
fa37c6bbd64281251b58e560df2f7b15cc086593
7,811
c
C
src/cc65/loadexpr.c
sethcoder/cc65
444d2bda1e9eba1f9a9d89c8c9f202072a96434f
[ "Zlib" ]
6
2018-11-28T15:42:20.000Z
2022-01-05T18:59:11.000Z
src/cc65/loadexpr.c
sethcoder/cc65
444d2bda1e9eba1f9a9d89c8c9f202072a96434f
[ "Zlib" ]
1
2018-03-15T21:01:29.000Z
2018-03-15T21:01:29.000Z
src/cc65/loadexpr.c
sethcoder/cc65
444d2bda1e9eba1f9a9d89c8c9f202072a96434f
[ "Zlib" ]
1
2019-09-29T21:09:35.000Z
2019-09-29T21:09:35.000Z
/*****************************************************************************/ /* */ /* loadexpr.c */ /* */ /* Load an expression into the primary register */ /* */ /* */ /* */ /* (C) 2004-2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* cc65 */ #include "codegen.h" #include "error.h" #include "exprdesc.h" #include "global.h" #include "loadexpr.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void LoadConstant (unsigned Flags, ExprDesc* Expr) /* Load the primary register with some constant value. */ { switch (ED_GetLoc (Expr)) { case E_LOC_ABS: /* Number constant */ g_getimmed (Flags | TypeOf (Expr->Type) | CF_CONST, Expr->IVal, 0); break; case E_LOC_GLOBAL: /* Global symbol, load address */ g_getimmed ((Flags | CF_EXTERNAL) & ~CF_CONST, Expr->Name, Expr->IVal); break; case E_LOC_STATIC: case E_LOC_LITERAL: /* Static symbol or literal, load address */ g_getimmed ((Flags | CF_STATIC) & ~CF_CONST, Expr->Name, Expr->IVal); break; case E_LOC_REGISTER: /* Register variable. Taking the address is usually not ** allowed. */ if (IS_Get (&AllowRegVarAddr) == 0) { Error ("Cannot take the address of a register variable"); } g_getimmed ((Flags | CF_REGVAR) & ~CF_CONST, Expr->Name, Expr->IVal); break; case E_LOC_STACK: g_leasp (Expr->IVal); break; default: Internal ("Unknown constant type: %04X", Expr->Flags); } } void LoadExpr (unsigned Flags, struct ExprDesc* Expr) /* Load an expression into the primary register if it is not already there. */ { if (ED_IsLVal (Expr)) { /* Dereferenced lvalue. If this is a bit field its type is unsigned. ** But if the field is completely contained in the lower byte, we will ** throw away the high byte anyway and may therefore load just the ** low byte. */ if (ED_IsBitField (Expr)) { Flags |= (Expr->BitOffs + Expr->BitWidth <= CHAR_BITS)? CF_CHAR : CF_INT; Flags |= CF_UNSIGNED; } else { Flags |= TypeOf (Expr->Type); } if (ED_NeedsTest (Expr)) { Flags |= CF_TEST; } switch (ED_GetLoc (Expr)) { case E_LOC_ABS: /* Absolute: numeric address or const */ g_getstatic (Flags | CF_ABSOLUTE, Expr->IVal, 0); break; case E_LOC_GLOBAL: /* Global variable */ g_getstatic (Flags | CF_EXTERNAL, Expr->Name, Expr->IVal); break; case E_LOC_STATIC: case E_LOC_LITERAL: /* Static variable or literal in the literal pool */ g_getstatic (Flags | CF_STATIC, Expr->Name, Expr->IVal); break; case E_LOC_REGISTER: /* Register variable */ g_getstatic (Flags | CF_REGVAR, Expr->Name, Expr->IVal); break; case E_LOC_STACK: /* Value on the stack */ g_getlocal (Flags, Expr->IVal); break; case E_LOC_PRIMARY: /* The primary register - just test if necessary */ if (Flags & CF_TEST) { g_test (Flags); } break; case E_LOC_EXPR: /* Reference to address in primary with offset in Expr */ g_getind (Flags, Expr->IVal); break; default: Internal ("Invalid location in LoadExpr: 0x%04X", ED_GetLoc (Expr)); } /* Handle bit fields. The actual type may have been casted or ** converted, so be sure to always use unsigned ints for the ** operations. */ if (ED_IsBitField (Expr)) { unsigned F = CF_INT | CF_UNSIGNED | CF_CONST | (Flags & CF_TEST); /* Shift right by the bit offset */ g_asr (F, Expr->BitOffs); /* And by the width if the field doesn't end on an int boundary */ if (Expr->BitOffs + Expr->BitWidth != CHAR_BITS && Expr->BitOffs + Expr->BitWidth != INT_BITS) { g_and (F, (0x0001U << Expr->BitWidth) - 1U); } } /* Expression was tested */ ED_TestDone (Expr); } else { /* An rvalue */ if (ED_IsLocExpr (Expr)) { if (Expr->IVal != 0) { /* We have an expression in the primary plus a constant ** offset. Adjust the value in the primary accordingly. */ Flags |= TypeOf (Expr->Type); g_inc (Flags | CF_CONST, Expr->IVal); } } else { /* Constant of some sort, load it into the primary */ LoadConstant (Flags, Expr); } /* Are we testing this value? */ if (ED_NeedsTest (Expr)) { /* Yes, force a test */ Flags |= TypeOf (Expr->Type); g_test (Flags); ED_TestDone (Expr); } } }
39.055
85
0.425298
fa3b54107ba450e88a1019a2776f936bbafbf542
544
h
C
CustomDS/QueueI.h
dipsonu10/DSALabClass
05c6315da3682339ce7062f0d93fc05618bce22f
[ "MIT" ]
null
null
null
CustomDS/QueueI.h
dipsonu10/DSALabClass
05c6315da3682339ce7062f0d93fc05618bce22f
[ "MIT" ]
4
2021-12-05T10:25:00.000Z
2021-12-13T09:25:02.000Z
CustomDS/QueueI.h
dipsonu10/DSALabClass
05c6315da3682339ce7062f0d93fc05618bce22f
[ "MIT" ]
null
null
null
typedef struct node { int arr[10000]; int front, rear; } Queue; int isEmpty(Queue* top){ return (top->front == -1) ? 1 : 0; } void push(Queue* q, int ele) { if(isEmpty(q)){ (q->front)++; (q->rear)++; } else { (q->rear)++; } q->arr[q->rear] = ele; } void pop(Queue* top){ if(isEmpty(top)){ printf("UnderFlow"); } else if(top->front == top->rear){ top->front = top->rear = -1; } else { (top->front)++; } } int peek(Queue* top){ if(!top){ return -999; } return top->arr[top->front]; }
15.111111
36
0.518382
d268d37725fb9c152d607696de9b0b513c25e61d
4,629
h
C
external_libs/CppUTest/include/CppUTest/TestMemoryAllocator.h
Dasudian/dsd-datahub-sdk-embedded-C
c3e6cdc3db6ef2efdeaab2a32ed78b80f3cbe430
[ "Apache-2.0" ]
5
2019-03-27T17:12:42.000Z
2020-09-25T17:20:36.000Z
external_libs/CppUTest/include/CppUTest/TestMemoryAllocator.h
Dasudian/dsd-datahub-sdk-embedded-C
c3e6cdc3db6ef2efdeaab2a32ed78b80f3cbe430
[ "Apache-2.0" ]
null
null
null
external_libs/CppUTest/include/CppUTest/TestMemoryAllocator.h
Dasudian/dsd-datahub-sdk-embedded-C
c3e6cdc3db6ef2efdeaab2a32ed78b80f3cbe430
[ "Apache-2.0" ]
1
2022-03-24T13:47:17.000Z
2022-03-24T13:47:17.000Z
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * 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 <organization> 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 EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef D_TestMemoryAllocator_h #define D_TestMemoryAllocator_h struct MemoryLeakNode; class TestMemoryAllocator; extern void setCurrentNewAllocator(TestMemoryAllocator* allocator); extern TestMemoryAllocator* getCurrentNewAllocator(); extern void setCurrentNewAllocatorToDefault(); extern TestMemoryAllocator* defaultNewAllocator(); extern void setCurrentNewArrayAllocator(TestMemoryAllocator* allocator); extern TestMemoryAllocator* getCurrentNewArrayAllocator(); extern void setCurrentNewArrayAllocatorToDefault(); extern TestMemoryAllocator* defaultNewArrayAllocator(); extern void setCurrentMallocAllocator(TestMemoryAllocator* allocator); extern TestMemoryAllocator* getCurrentMallocAllocator(); extern void setCurrentMallocAllocatorToDefault(); extern TestMemoryAllocator* defaultMallocAllocator(); class TestMemoryAllocator { public: TestMemoryAllocator(const char* name_str = "generic", const char* alloc_name_str = "alloc", const char* free_name_str = "free"); virtual ~TestMemoryAllocator(); bool hasBeenDestroyed(); virtual char* alloc_memory(size_t size, const char* file, int line); virtual void free_memory(char* memory, const char* file, int line); virtual const char* name() const; virtual const char* alloc_name() const; virtual const char* free_name() const; virtual bool isOfEqualType(TestMemoryAllocator* allocator); virtual char* allocMemoryLeakNode(size_t size); virtual void freeMemoryLeakNode(char* memory); protected: const char* name_; const char* alloc_name_; const char* free_name_; bool hasBeenDestroyed_; }; class CrashOnAllocationAllocator : public TestMemoryAllocator { unsigned allocationToCrashOn_; public: CrashOnAllocationAllocator(); virtual void setNumberToCrashOn(unsigned allocationToCrashOn); virtual char* alloc_memory(size_t size, const char* file, int line) _override; }; class NullUnknownAllocator: public TestMemoryAllocator { public: NullUnknownAllocator(); virtual char* alloc_memory(size_t size, const char* file, int line) _override; virtual void free_memory(char* memory, const char* file, int line) _override; static TestMemoryAllocator* defaultAllocator(); }; class LocationToFailAllocNode; class FailableMemoryAllocator: public TestMemoryAllocator { public: FailableMemoryAllocator(const char* name_str = "failable alloc", const char* alloc_name_str = "alloc", const char* free_name_str = "free"); virtual char* alloc_memory(size_t size, const char* file, int line); virtual char* allocMemoryLeakNode(size_t size); virtual void failAllocNumber(int number); virtual void failNthAllocAt(int allocationNumber, const char* file, int line); virtual void checkAllFailedAllocsWereDone(); virtual void clearFailedAllocs(); protected: LocationToFailAllocNode* head_; int currentAllocNumber_; }; #endif
37.634146
144
0.75351
8285ede37875648c8e749a22854ae576385ef6d9
629
h
C
usr/libexec/gamed/GKMatchmakerBulletin.h
lechium/tvOS124Headers
11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475
[ "MIT" ]
4
2019-08-27T18:03:47.000Z
2021-09-18T06:29:00.000Z
usr/libexec/gamed/GKMatchmakerBulletin.h
lechium/tvOS124Headers
11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475
[ "MIT" ]
null
null
null
usr/libexec/gamed/GKMatchmakerBulletin.h
lechium/tvOS124Headers
11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475
[ "MIT" ]
null
null
null
// // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Jun 10 2020 10:03:13). // // Copyright (C) 1997-2019 Steve Nygard. // #import "GKBulletin.h" @class NSString; @interface GKMatchmakerBulletin : GKBulletin { NSString *_matchID; // 16 = 0x10 } + (void)loadBulletinsForPushNotification:(id)arg1 withHandler:(CDUnknownBlockType)arg2; // IMP=0x00000001000a8abc @property(retain, nonatomic) NSString *matchID; // @synthesize matchID=_matchID; - (void)executeBulletinWithBulletinController:(id)arg1; // IMP=0x00000001000a90fc - (void)dealloc; // IMP=0x00000001000a90a4 @end
27.347826
120
0.745628
82942ad7577a6d601d98c7ee93652f544517f66a
14,906
c
C
plat/marvell/octeontx/otx2/t96/plat_t96_setup.c
Gateworks/atf-newport
67f418ebe7ee6630f77c3ef7a10b7bf6c15c5ce3
[ "BSD-3-Clause" ]
null
null
null
plat/marvell/octeontx/otx2/t96/plat_t96_setup.c
Gateworks/atf-newport
67f418ebe7ee6630f77c3ef7a10b7bf6c15c5ce3
[ "BSD-3-Clause" ]
null
null
null
plat/marvell/octeontx/otx2/t96/plat_t96_setup.c
Gateworks/atf-newport
67f418ebe7ee6630f77c3ef7a10b7bf6c15c5ce3
[ "BSD-3-Clause" ]
1
2021-06-12T11:06:26.000Z
2021-06-12T11:06:26.000Z
/* * Copyright (C) 2016-2018 Marvell International Ltd. * * SPDX-License-Identifier: BSD-3-Clause * https://spdx.org/licenses */ #include <debug.h> #include <platform.h> #include <platform_def.h> #include <platform_setup.h> #include <platform_irqs_def.h> #include <octeontx_common.h> #include <gpio_octeontx.h> #include <octeontx_utils.h> #include <platform_scfg.h> #include <octeontx_plat_configuration.h> #include <plat_otx2_configuration.h> #include <plat_octeontx.h> #include <octeontx_irqs_def.h> #include <plat_scfg.h> #include <qlm.h> static uint64_t msix_addr_save; int plat_octeontx_get_ecams_count(void) { return 1; } int plat_octeontx_get_iobn_count(void) { return 2; } int plat_octeontx_is_lmc_enabled(unsigned lmc) { union cavm_lmcx_dll_ctl2 lmcx_dll_ctl2; if ((plat_get_altpkg() == CN95XXE_PKG) && (lmc == 1)) { return 0; } else if ((plat_get_altpkg() == CN93XX_PKG) && (lmc == 2)) { return 0; } lmcx_dll_ctl2.u = CSR_READ(CAVM_LMCX_DLL_CTL2(lmc)); return (lmcx_dll_ctl2.s.dreset ? 0 : 1); } /******************************************************************************* * Setup secondary CPU JUMP address from RESET ******************************************************************************/ void plat_octeontx_set_secondary_cpu_jump_addr(uint64_t entrypoint_addr) { /* * Assembly for ROM memory: * d508711f ic ialluis * d503201f nop * 58000040 ldr x0, 328 <branch_addr> * d61f0000 br x0 * branch_addr: * Memory is little endain, so 64 bit constants have the first * instruction in the low word */ CSR_WRITE(CAVM_ROM_MEMX(0), 0xd503201fd508711full); CSR_WRITE(CAVM_ROM_MEMX(1), 0xd61f000058000040ull); CSR_WRITE(CAVM_ROM_MEMX(2), entrypoint_addr); } int plat_octeontx_get_mpi_count(void) { return 2; } int plat_octeontx_get_smmu_count(void) { return 1; } int plat_octeontx_get_twsi_count(void) { return 6; } int plat_octeontx_get_cpt_count(void) { return 1; } int plat_octeontx_get_cgx_count(void) { return 3; } int plat_octeontx_get_pem_count(void) { if (plat_get_altpkg() == CN95XXE_PKG) return 1; return 3; } int plat_octeontx_get_gser_count(void) { if (plat_get_altpkg() == CN93XX_PKG) return 6; return 8; } int plat_otx2_get_gserp_count(void) { return 5; } qlm_state_lane_t plat_otx2_get_qlm_state_lane(int qlm, int lane) { qlm_state_lane_t state; state.u = 0; state.s.mode = QLM_MODE_DISABLED; if (qlm >= plat_octeontx_get_gser_count()) return state; if (IS_OCTEONTX_VAR(read_midr(), T96PARTNUM, 3)) { int gserr_qlm; int gserp_count = plat_otx2_get_gserp_count(); if (qlm < gserp_count) return state; gserr_qlm = qlm - gserp_count; state.u = CSR_READ(CAVM_GSERRX_SCRATCHX(gserr_qlm, lane)); } else { state.u = CSR_READ(CAVM_GSERNX_LANEX_SCRATCHX(qlm, lane, 0)); } return state; } int plat_octeontx_get_uaa_count(void) { return 8; } int plat_octeontx_get_rvu_count(void) { return 16; } int plat_octeontx_get_mcc_count(void) { return MAX_MCC; } /* Return number of lanes available for different QLMs. */ int plat_get_max_lane_num(int qlm) { if (IS_OCTEONTX_VAR(read_midr(), T96PARTNUM, 3)) return 4; if ((qlm == 4) || (qlm == 5)) return 2; return 4; } /* Return the CGX<->QLM mapping */ int plat_get_cgx_idx(int qlm) { int idx; switch (qlm) { case 3: case 7: idx = 0; break; case 4: case 5: idx = 1; break; case 6: idx = 2; break; default: idx = -1; break; } return idx; } /* * BDK uses CPC RAM memory as key memory. * This is indicated by storing the ROTPK at TRUST-ROT-ADDR, * which is in range of CPC_RAM_MEMX. * Moreover, ATF needs to have access to SCP-AP Secure0 mailbox. * Map required memory as MT_RW. */ void plat_map_cpc_mem() { cavm_cpc_const_t cpc_const; unsigned long cpc_ram_size, attr; /* Calculate CPC RAM size based on a number of 16KB memory regions */ cpc_const.u = CSR_READ(CAVM_CPC_CONST); cpc_ram_size = cpc_const.s.mem_regions * 0x4000; attr = MT_MEMORY | MT_RW | MT_SECURE; add_map_record(CAVM_CPC_RAM_MEMX(0), cpc_ram_size, attr); /* Map required XCP memory region for doorbell registers */ add_map_record(CAVM_XCP_BAR_E_XCPX_PF_BAR0(CAVM_CPC_XCP_MAP_E_SCP), CAVM_XCP_BAR_E_XCPX_PF_BAR0_SIZE, attr); } void plat_add_mmio() { unsigned long attr; int i, device_type_count; attr = MT_DEVICE | MT_RW | MT_SECURE; add_map_record(CAVM_RST_BAR_E_RST_PF_BAR0_CN9, CAVM_RST_BAR_E_RST_PF_BAR0_CN9_SIZE, attr); add_map_record(CAVM_RST_BAR_E_RST_PF_BAR2, CAVM_RST_BAR_E_RST_PF_BAR2_SIZE, attr); add_map_record(CAVM_RST_BAR_E_RST_PF_BAR4, CAVM_RST_BAR_E_RST_PF_BAR4_SIZE, attr); add_map_record(CAVM_CCS_BAR_E_CCS_PF_BAR0, CAVM_CCS_BAR_E_CCS_PF_BAR0_SIZE, attr); add_map_record(CAVM_MIO_EMM_BAR_E_MIO_EMM_PF_BAR0_CN9, CAVM_MIO_EMM_BAR_E_MIO_EMM_PF_BAR0_CN9_SIZE, attr); add_map_record(CAVM_MIO_EMM_BAR_E_MIO_EMM_PF_BAR4, CAVM_MIO_EMM_BAR_E_MIO_EMM_PF_BAR4_SIZE, attr); add_map_record(CAVM_FUSF_BAR_E_FUSF_PF_BAR0, CAVM_FUSF_BAR_E_FUSF_PF_BAR0_SIZE, attr); device_type_count = plat_octeontx_get_mpi_count(); for (i = 0; i < device_type_count; i++) { add_map_record(CAVM_MPI_BAR_E_MPIX_PF_BAR0(i), CAVM_MPI_BAR_E_MPIX_PF_BAR0_SIZE, attr); add_map_record(CAVM_MPI_BAR_E_MPIX_PF_BAR4(i), CAVM_MPI_BAR_E_MPIX_PF_BAR4_SIZE, attr); } add_map_record(CAVM_GIC_BAR_E_GIC_PF_BAR2, CAVM_GIC_BAR_E_GIC_PF_BAR2_SIZE, attr); add_map_record(GIC_PF_BAR4, GIC_PF_BAR4_SIZE, attr); device_type_count = plat_octeontx_get_smmu_count(); for (i = 0; i < device_type_count; i++) add_map_record(CAVM_SMMU_BAR_E_SMMUX_PF_BAR0_CN8(i), CAVM_SMMU_BAR_E_SMMUX_PF_BAR0_CN8_SIZE, attr); add_map_record(CAVM_GTI_BAR_E_GTI_PF_BAR0_CN9, CAVM_GTI_BAR_E_GTI_PF_BAR0_CN9_SIZE, attr); add_map_record(CAVM_GTI_BAR_E_GTI_PF_BAR4_CN9, CAVM_GTI_BAR_E_GTI_PF_BAR4_CN9_SIZE, attr); for (i = 0; i < MAX_LMC; i++) { add_map_record(CAVM_LMC_BAR_E_LMCX_PF_BAR0(i), CAVM_LMC_BAR_E_LMCX_PF_BAR0_SIZE, attr); add_map_record(CAVM_LMC_BAR_E_LMCX_PF_BAR4(i), CAVM_LMC_BAR_E_LMCX_PF_BAR4_SIZE, attr); } device_type_count = plat_octeontx_get_twsi_count(); for (i = 0; i < device_type_count; i++) { add_map_record(CAVM_MIO_TWS_BAR_E_MIO_TWSX_PF_BAR0_CN9(i), CAVM_MIO_TWS_BAR_E_MIO_TWSX_PF_BAR0_CN9_SIZE, attr); add_map_record(CAVM_MIO_TWS_BAR_E_MIO_TWSX_PF_BAR4(i), CAVM_MIO_TWS_BAR_E_MIO_TWSX_PF_BAR4_SIZE, attr); } device_type_count = plat_octeontx_get_cpt_count(); for (i = 0; i < device_type_count; i++) { add_map_record(CAVM_CPT_BAR_E_CPTX_PF_BAR0(i), CAVM_CPT_BAR_E_CPTX_PF_BAR0_SIZE, attr); add_map_record(CAVM_CPT_BAR_E_CPTX_PF_BAR4(i), CAVM_CPT_BAR_E_CPTX_PF_BAR4_SIZE, attr); add_map_record(CAVM_CPT_BAR_E_CPTX_VFX_BAR0(i, 0), 64*CAVM_CPT_BAR_E_CPTX_VFX_BAR0_SIZE, attr); add_map_record(CAVM_CPT_BAR_E_CPTX_VFX_BAR4(i, 0), 64*CAVM_CPT_BAR_E_CPTX_VFX_BAR4_SIZE, attr); } device_type_count = plat_octeontx_get_cgx_count(); for (i = 0; i < device_type_count; i++) { add_map_record(CAVM_CGX_BAR_E_CGXX_PF_BAR0(i), CAVM_CGX_BAR_E_CGXX_PF_BAR0_SIZE, attr); add_map_record(CAVM_CGX_BAR_E_CGXX_PF_BAR4(i), CAVM_CGX_BAR_E_CGXX_PF_BAR4_SIZE, attr); } device_type_count = plat_octeontx_get_pem_count(); for (i = 0; i < device_type_count; i++) { add_map_record(CAVM_PEM_BAR_E_PEMX_PF_BAR0_CN9(i), CAVM_PEM_BAR_E_PEMX_PF_BAR0_CN9_SIZE, attr); add_map_record(CAVM_PEM_BAR_E_PEMX_PF_BAR4_CN9(i), CAVM_PEM_BAR_E_PEMX_PF_BAR4_CN9_SIZE, attr); } if (IS_OCTEONTX_VAR(read_midr(), T96PARTNUM, 3)) { device_type_count = plat_octeontx_get_cgx_count(); for (i = 0; i < device_type_count; i++) add_map_record(CAVM_GSERR_BAR_E_GSERRX_PF_BAR0(i), CAVM_GSERR_BAR_E_GSERRX_PF_BAR0_SIZE, attr); } else { device_type_count = plat_octeontx_get_gser_count(); for (i = 0; i < device_type_count; i++) add_map_record(CAVM_GSERN_BAR_E_GSERNX_PF_BAR0(i), CAVM_GSERN_BAR_E_GSERNX_PF_BAR0_SIZE, attr); } add_map_record(CAVM_GPIO_BAR_E_GPIO_PF_BAR0_CN9, CAVM_GPIO_BAR_E_GPIO_PF_BAR0_CN9_SIZE, attr); add_map_record(CAVM_GPIO_BAR_E_GPIO_PF_BAR4, CAVM_GPIO_BAR_E_GPIO_PF_BAR4_SIZE, attr); device_type_count = plat_octeontx_get_uaa_count(); for (i = 0; i < device_type_count; i++) { add_map_record(UAAX_PF_BAR0(i), CAVM_UAA_BAR_E_UAAX_PF_BAR0_CN9_SIZE, attr); add_map_record(CAVM_UAA_BAR_E_UAAX_PF_BAR4(i), CAVM_UAA_BAR_E_UAAX_PF_BAR4_SIZE, attr); } device_type_count = plat_octeontx_get_ecams_count(); for (i = 0; i < device_type_count; i++) { add_map_record(CAVM_ECAM_BAR_E_ECAMX_PF_BAR0_CN9(i), CAVM_ECAM_BAR_E_ECAMX_PF_BAR0_CN9_SIZE, attr); add_map_record(ECAM_PF_BAR2(i), CAVM_ECAM_BAR_E_ECAMX_PF_BAR2_CN9_SIZE, attr); } add_map_record(CAVM_ROM_BAR_E_ROM_PF_BAR0, CAVM_ROM_BAR_E_ROM_PF_BAR0_SIZE, attr); device_type_count = plat_octeontx_get_iobn_count(); for (i = 0; i < device_type_count; ++i) { add_map_record(CAVM_IOBN_BAR_E_IOBNX_PF_BAR0_CN9(i), CAVM_IOBN_BAR_E_IOBNX_PF_BAR0_CN9_SIZE , attr); add_map_record(CAVM_IOBN_BAR_E_IOBNX_PF_BAR4(i), CAVM_IOBN_BAR_E_IOBNX_PF_BAR4_SIZE, attr); } add_map_record(CAVM_RVU_BAR_E_RVU_PFX_BAR0(0), CAVM_RVU_BAR_E_RVU_PFX_BAR0_SIZE, attr); device_type_count = plat_octeontx_get_rvu_count(); for (i = 0; i < device_type_count; ++i) add_map_record(CAVM_RVU_BAR_E_RVU_PFX_FUNCX_BAR2(i, 0), CAVM_RVU_BAR_E_RVU_PFX_FUNCX_BAR2_SIZE, attr); /* Add regions for required for RVU init */ add_map_record(CAVM_RVU_BAR_E_RVU_PFX_BAR0(0) + CAVM_RVU_BLOCK_ADDR_E_NIXX(0) * CAVM_RVU_BAR_E_RVU_PFX_BAR0_SIZE, CAVM_RVU_BAR_E_RVU_PFX_BAR0_SIZE, attr); add_map_record(CAVM_RVU_BAR_E_RVU_PFX_BAR0(0) + CAVM_RVU_BLOCK_ADDR_E_NPA * CAVM_RVU_BAR_E_RVU_PFX_BAR0_SIZE, CAVM_RVU_BAR_E_RVU_PFX_BAR0_SIZE, attr); add_map_record(CAVM_RVU_BAR_E_RVU_PFX_BAR0(0) + CAVM_RVU_BLOCK_ADDR_E_SSO * CAVM_RVU_BAR_E_RVU_PFX_BAR0_SIZE, CAVM_RVU_BAR_E_RVU_PFX_BAR0_SIZE, attr); add_map_record(CAVM_RVU_BAR_E_RVU_PFX_BAR0(0) + CAVM_RVU_BLOCK_ADDR_E_SSOW * CAVM_RVU_BAR_E_RVU_PFX_BAR0_SIZE, CAVM_RVU_BAR_E_RVU_PFX_BAR0_SIZE, attr); add_map_record(CAVM_RVU_BAR_E_RVU_PFX_BAR0(0) + CAVM_RVU_BLOCK_ADDR_E_TIM * CAVM_RVU_BAR_E_RVU_PFX_BAR0_SIZE, CAVM_RVU_BAR_E_RVU_PFX_BAR0_SIZE, attr); add_map_record(CAVM_RVU_BAR_E_RVU_PFX_BAR0(0) + CAVM_RVU_BLOCK_ADDR_E_CPTX(0) * CAVM_RVU_BAR_E_RVU_PFX_BAR0_SIZE, CAVM_RVU_BAR_E_RVU_PFX_BAR0_SIZE, attr); add_map_record(CAVM_RVU_BAR_E_RVU_PFX_BAR0(0) + CAVM_RVU_BLOCK_ADDR_E_NDCX(0) * CAVM_RVU_BAR_E_RVU_PFX_BAR0_SIZE, CAVM_RVU_BAR_E_RVU_PFX_BAR0_SIZE, attr); add_map_record(CAVM_RVU_BAR_E_RVU_PFX_BAR0(0) + CAVM_RVU_BLOCK_ADDR_E_NDCX(1) * CAVM_RVU_BAR_E_RVU_PFX_BAR0_SIZE, CAVM_RVU_BAR_E_RVU_PFX_BAR0_SIZE, attr); add_map_record(CAVM_RVU_BAR_E_RVU_PFX_BAR0(0) + CAVM_RVU_BLOCK_ADDR_E_NDCX(2) * CAVM_RVU_BAR_E_RVU_PFX_BAR0_SIZE, CAVM_RVU_BAR_E_RVU_PFX_BAR0_SIZE, attr); add_map_record(CAVM_SMI_BAR_E_SMI_PF_BAR0_CN9, CAVM_SMI_BAR_E_SMI_PF_BAR0_CN9_SIZE, attr); plat_map_cpc_mem(); device_type_count = plat_octeontx_get_mcc_count(); for (i = 0; i < device_type_count; ++i) { add_map_record(CAVM_MCC_BAR_E_MCCX_PF_BAR0(i), CAVM_MCC_BAR_E_MCCX_PF_BAR0_SIZE, attr); add_map_record(CAVM_MCC_BAR_E_MCCX_PF_BAR4(i), CAVM_MCC_BAR_E_MCCX_PF_BAR4_SIZE, attr); } add_map_record(CAVM_MDC_BAR_E_MDC_PF_BAR4, CAVM_MDC_BAR_E_MDC_PF_BAR4_SIZE, attr); /* * Shared memory configuration. * Map additional memory used by RVU/SFP mgmt(shared between AP & MCP). * Do not use add_map_record, it will round size up */ mmap_add_region(RVU_MEM_BASE, RVU_MEM_BASE, RVU_MEM_SIZE, (MT_MEMORY | MT_RW | MT_NS)); mmap_add_region(SFP_SHMEM_BASE, SFP_SHMEM_BASE, SFP_SHMEM_SIZE, (MT_MEMORY | MT_RW | MT_NS)); #ifdef NT_FW_CONFIG mmap_add_region(NT_FW_CONFIG_BASE, NT_FW_CONFIG_BASE, NT_FW_CONFIG_LIMIT, (MT_MEMORY | MT_RW | MT_NS)); #endif } void plat_set_gpio_msix_vectors(int gpio_num, int irq_num, int enable) { uint64_t vector_ptr; int intr_pinx; /* Get the offset of interrupt vector for that GPIO line */ intr_pinx = CAVM_GPIO_INT_VEC_E_INTR_PINX_CN96XX(gpio_num); /* INTR_PINX vector address */ vector_ptr = CAVM_GPIO_BAR_E_GPIO_PF_BAR4 + intr_pinx * 0x10; if (enable) { /* Save vector address so that it can be restored. * The value will be same for set and clear vectors so saving * once will suffice. */ msix_addr_save = octeontx_read64(vector_ptr); /* Enable SECVEC to make the vector secure */ octeontx_write64(vector_ptr, CAVM_GICD_SETSPI_SR | 1); vector_ptr += 0x8; octeontx_write64(vector_ptr, irq_num); /* INTR_PINX_CLEAR vector */ vector_ptr += 0x8; /* Enable SECVEC to make the vector secure */ octeontx_write64(vector_ptr, CAVM_GICD_CLRSPI_SR | 1); vector_ptr += 0x8; octeontx_write64(vector_ptr, irq_num); } else { /* Restore the vector address */ octeontx_write64(vector_ptr, msix_addr_save); /* INTR_PINX_CLEAR vector */ vector_ptr += 0x10; octeontx_write64(vector_ptr, msix_addr_save); } } void plat_gpio_irq_setup(void) { gpio_intercept_interrupts = 1; if (octeontx_register_gpio_handlers() < 0) ERROR("Failed to register GPIO intercept handlers\n"); } /* * This function configures IOBN to grant access for GTI to secure memory */ void plat_gti_access_secure_memory_setup(int do_secure) { /* * dev_idx - Stream's dev number (stream_id<7:0>) * bus_idx - Stream's bus number (stream_id<15:8>). */ uint64_t bus_idx = (CAVM_PCC_DEV_CON_E_GTI_CN9 >> 8) & 0xFF; uint64_t domain_idx = (CAVM_PCC_DEV_CON_E_GTI_CN9 >> 16) & 0xFF; uint64_t dev_idx = (CAVM_PCC_DEV_CON_E_GTI_CN9 >> 3) & 0xFF; cavm_iobnx_domx_busx_streams_t iobn_domx_busx_stream; cavm_iobnx_domx_devx_streams_t iobn_domx_devx_stream; for (int iobn_idx = 0; iobn_idx < plat_octeontx_scfg->iobn_count; iobn_idx++) { iobn_domx_busx_stream.u = CSR_READ( CAVM_IOBNX_DOMX_BUSX_STREAMS(iobn_idx, domain_idx, bus_idx)); if (do_secure) { iobn_domx_busx_stream.s.strm_nsec = 0; iobn_domx_busx_stream.s.phys_nsec = 0; CSR_WRITE(CAVM_IOBNX_DOMX_BUSX_STREAMS( iobn_idx, domain_idx, bus_idx), iobn_domx_busx_stream.u); } iobn_domx_devx_stream.u = CSR_READ( CAVM_IOBNX_DOMX_DEVX_STREAMS(iobn_idx, domain_idx, dev_idx)); if (do_secure) { iobn_domx_devx_stream.s.strm_nsec = 0; iobn_domx_devx_stream.s.phys_nsec = 0; CSR_WRITE(CAVM_IOBNX_DOMX_DEVX_STREAMS( iobn_idx, domain_idx, dev_idx), iobn_domx_devx_stream.u); } } } void plat_gti_irq_setup(int core) { uint64_t vector_ptr; int intr_pinx; /* Get the offset of interrupt vector for this core */ intr_pinx = CAVM_GTI_INT_VEC_E_CORE_WDOGX_INT_CN9(core); /* INTR_PINX vector address */ vector_ptr = CAVM_GTI_BAR_E_GTI_PF_BAR4_CN9 + (intr_pinx << 4); /* Enable SECVEC to make the vector secure */ octeontx_write64(vector_ptr, CAVM_GICD_SETSPI_SR | 1); vector_ptr += 0x8; octeontx_write64(vector_ptr, GTI_CWD_SPI_IRQ(core)); }
30.358452
113
0.765061
301d428aa8fe71304e99fd92f1c701713f781aae
1,270
c
C
contrib/natgrid/Src/natgrid.c
xylar/cdat
8a5080cb18febfde365efc96147e25f51494a2bf
[ "BSD-3-Clause" ]
62
2018-03-30T15:46:56.000Z
2021-12-08T23:30:24.000Z
contrib/natgrid/Src/natgrid.c
xylar/cdat
8a5080cb18febfde365efc96147e25f51494a2bf
[ "BSD-3-Clause" ]
114
2018-03-21T01:12:43.000Z
2021-07-05T12:29:54.000Z
contrib/natgrid/Src/natgrid.c
CDAT/uvcdat
5133560c0c049b5c93ee321ba0af494253b44f91
[ "BSD-3-Clause" ]
14
2018-06-06T02:42:47.000Z
2021-11-26T03:27:00.000Z
/* * This file contains the settings for most of the * global variables by way of including nnmhead.h . */ #include "nnmhead.h" #include "nnghead.h" #include "nntypes.h" #include "nntpvrs.h" #include "nnexver.h" void Terminate() { struct simp *tmp,*tmp0; struct datum *dtmp,*dtmp0; struct neig *ntmp,*ntmp0; struct temp *ttmp,*ttmp0; tmp = rootsimp; while(tmp!=NULL) { tmp0 =tmp->nextsimp; free(tmp); tmp = tmp0; } rootsimp = cursimp = holdsimp = lastsimp = prevsimp = NULL; dtmp = rootdat; while(dtmp!=NULL) { dtmp0 =dtmp->nextdat; free(dtmp); dtmp = dtmp0; } rootdat = curdat = holddat = NULL; ntmp = rootneig; while(ntmp!=NULL) { ntmp0 =ntmp->nextneig; free(ntmp); ntmp = ntmp0; } rootneig = curneig = lastneig = NULL; ttmp = roottemp; while(ttmp!=NULL) { ttmp0 =ttmp->nexttemp; free(ttmp); ttmp = ttmp0; } roottemp = curtemp = lasttemp= prevtemp= NULL; if(points!=NULL) { FreeMatrixd(points); points = NULL; } if(joints!=NULL) { FreeMatrixd(joints); joints = NULL; } if(jndx != NULL) { FreeVecti(jndx); jndx = NULL; } magx = magx_orig; magy = magy_orig; magz = magz_orig; }
19.538462
62
0.586614
305865b98693c15d3bc97539d76fca8f28d41f5f
3,585
c
C
clicks/6dofimu8/example/main.c
dMajoIT/mikrosdk_click_v2
f425fd85054961b4f600d1708cf18ac952a6bdb8
[ "MIT" ]
31
2020-10-02T14:15:14.000Z
2022-03-24T08:33:21.000Z
clicks/6dofimu8/example/main.c
dMajoIT/mikrosdk_click_v2
f425fd85054961b4f600d1708cf18ac952a6bdb8
[ "MIT" ]
4
2020-10-27T14:05:00.000Z
2022-03-10T09:38:57.000Z
clicks/6dofimu8/example/main.c
dMajoIT/mikrosdk_click_v2
f425fd85054961b4f600d1708cf18ac952a6bdb8
[ "MIT" ]
32
2020-11-28T07:56:42.000Z
2022-03-14T19:42:29.000Z
/*! * \file * \brief c6DofImu8 Click example * * # Description * This app gets three-axis gyroscope value, three-axis accelerometer value and temperature. * * The demo application is composed of two sections : * * ## Application Init * Initializes device and performs a device software reset and configuration. * * ## Application Task * Waits until any new data is entered to the data registers and then reads the accelerometer, * gyroscope and temperature data which will be converted and calculated to the properly units each second. * * \author MikroE Team * */ // ------------------------------------------------------------------- INCLUDES #include "board.h" #include "log.h" #include "c6dofimu8.h" // ------------------------------------------------------------------ VARIABLES static c6dofimu8_t c6dofimu8; static log_t logger; // ------------------------------------------------------- ADDITIONAL FUNCTIONS void log_axis ( t_c6dofimu8_axis *log_data ) { log_printf( &logger, "* X-axis : %.3f \r\n", log_data->x ); log_printf( &logger, "* Y-axis : %.3f \r\n", log_data->y ); log_printf( &logger, "* Z-axis : %.3f \r\n", log_data->z ); } // ------------------------------------------------------ APPLICATION FUNCTIONS void application_init ( void ) { log_cfg_t log_cfg; c6dofimu8_cfg_t cfg; /** * Logger initialization. * Default baud rate: 115200 * Default log level: LOG_LEVEL_DEBUG * @note If USB_UART_RX and USB_UART_TX * are defined as HAL_PIN_NC, you will * need to define them manually for log to work. * See @b LOG_MAP_USB_UART macro definition for detailed explanation. */ LOG_MAP_USB_UART( log_cfg ); log_init( &logger, &log_cfg ); log_info( &logger, "---- Application Init ----" ); // Click initialization. c6dofimu8_cfg_setup( &cfg ); C6DOFIMU8_MAP_MIKROBUS( cfg, MIKROBUS_1 ); c6dofimu8_init( &c6dofimu8, &cfg ); Delay_ms( 500 ); c6dofimu8_default_cfg( &c6dofimu8 ); log_printf( &logger, "** 6DOF IMU 8 is initialized **\r\n" ); Delay_ms( 300 ); } void application_task ( void ) { uint8_t data_ready; int8_t temperature; t_c6dofimu8_axis accel_data; t_c6dofimu8_axis gyro_data; data_ready = c6dofimu8_get_drdy_status( &c6dofimu8, C6DOFIMU8_TEMP_DRDY_MASK | C6DOFIMU8_G_DRDY_MASK | C6DOFIMU8_XL_DRDY_MASK ); while ( data_ready == C6DOFIMU8_EVENT_NOT_DETECTED ) { data_ready = c6dofimu8_get_drdy_status( &c6dofimu8, C6DOFIMU8_TEMP_DRDY_MASK | C6DOFIMU8_G_DRDY_MASK | C6DOFIMU8_XL_DRDY_MASK ); } c6dofimu8_get_data( &c6dofimu8, &accel_data, &gyro_data, &temperature ); log_printf( &logger, "** Accelerometer values : \r\n" ); log_axis( &accel_data ); log_printf( &logger, "** Gyroscope values : \r\n" ); log_axis( &gyro_data ); log_printf( &logger, "** Temperature value : %d degC \r\n", ( int16_t )temperature ); log_printf( &logger, "-------------------------------------------------\r\n" ); Delay_ms( 1000 ); } void main ( void ) { application_init( ); for ( ; ; ) { application_task( ); } } // ------------------------------------------------------------------------ END
30.381356
108
0.538075
30764083fb5a0e40ce34bf240c051cf945d863df
604
h
C
CJAnimationKitDemo/Pods/CJBaseUIKit/CJBaseUIKit/UIView/CJDragAction/UIView+CJDragAction.h
dvlproad/CoreAnimation
29bae69429a1e98f76af4b1fc87399dd71aafb8f
[ "MIT" ]
59
2018-08-16T10:09:52.000Z
2022-02-16T05:43:45.000Z
CJAnimationKitDemo/Pods/CJBaseUIKit/CJBaseUIKit/UIView/CJDragAction/UIView+CJDragAction.h
dvlproad/CoreAnimation
29bae69429a1e98f76af4b1fc87399dd71aafb8f
[ "MIT" ]
null
null
null
CJAnimationKitDemo/Pods/CJBaseUIKit/CJBaseUIKit/UIView/CJDragAction/UIView+CJDragAction.h
dvlproad/CoreAnimation
29bae69429a1e98f76af4b1fc87399dd71aafb8f
[ "MIT" ]
15
2018-11-09T01:49:32.000Z
2022-02-14T14:56:12.000Z
// // UIView+CJDragAction.h // CJUIKitDemo // // Created by ciyouzen on 2016/11/05. // Copyright © 2016年 dvlproad. All rights reserved. // #import <UIKit/UIKit.h> /** * 类目说明:通过给View添加UIPanGestureRecognizer手势,使其可以移动到拖动的位置 */ @interface UIView (CJDragAction) @property (nonatomic, assign) BOOL cjDragEnable; /**< 是否允许拖曳(默认YES) */ @property (nonatomic, copy) void(^cjDragBeginBlock)(UIView *view); /**< 开始拖曳的回调 */ @property (nonatomic, copy) void(^cjDragDuringBlock)(UIView *view); /**< 拖曳中的回调 */ @property (nonatomic, copy) void(^cjDragEndBlock)(UIView *view); /**< 结束拖曳的回调 */ @end
26.26087
85
0.68543
3078cee14f9cd8f55cffe36a51091aa218b31b15
15,004
c
C
linux-3.4/drivers/net/wireless/rtl8189_smart/hal/rtl8188e/rtl8188e_dm.c
xregist/v3s-linux-sdk
a2b013e3959662d65650a13fc23ec1cd503865eb
[ "Apache-2.0" ]
null
null
null
linux-3.4/drivers/net/wireless/rtl8189_smart/hal/rtl8188e/rtl8188e_dm.c
xregist/v3s-linux-sdk
a2b013e3959662d65650a13fc23ec1cd503865eb
[ "Apache-2.0" ]
null
null
null
linux-3.4/drivers/net/wireless/rtl8189_smart/hal/rtl8188e/rtl8188e_dm.c
xregist/v3s-linux-sdk
a2b013e3959662d65650a13fc23ec1cd503865eb
[ "Apache-2.0" ]
1
2020-01-31T10:27:07.000Z
2020-01-31T10:27:07.000Z
/****************************************************************************** * * Copyright(c) 2007 - 2011 Realtek Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA * * ******************************************************************************/ //============================================================ // Description: // // This file is for 92CE/92CU dynamic mechanism only // // //============================================================ #define _RTL8188E_DM_C_ //============================================================ // include files //============================================================ #include <drv_types.h> #include <rtl8188e_hal.h> //============================================================ // Global var //============================================================ static VOID dm_CheckProtection( IN PADAPTER Adapter ) { #if 0 PMGNT_INFO pMgntInfo = &(Adapter->MgntInfo); u1Byte CurRate, RateThreshold; if(pMgntInfo->pHTInfo->bCurBW40MHz) RateThreshold = MGN_MCS1; else RateThreshold = MGN_MCS3; if(Adapter->TxStats.CurrentInitTxRate <= RateThreshold) { pMgntInfo->bDmDisableProtect = TRUE; DbgPrint("Forced disable protect: %x\n", Adapter->TxStats.CurrentInitTxRate); } else { pMgntInfo->bDmDisableProtect = FALSE; DbgPrint("Enable protect: %x\n", Adapter->TxStats.CurrentInitTxRate); } #endif } static VOID dm_CheckStatistics( IN PADAPTER Adapter ) { #if 0 if(!Adapter->MgntInfo.bMediaConnect) return; //2008.12.10 tynli Add for getting Current_Tx_Rate_Reg flexibly. rtw_hal_get_hwreg( Adapter, HW_VAR_INIT_TX_RATE, (pu1Byte)(&Adapter->TxStats.CurrentInitTxRate) ); // Calculate current Tx Rate(Successful transmited!!) // Calculate current Rx Rate(Successful received!!) //for tx tx retry count rtw_hal_get_hwreg( Adapter, HW_VAR_RETRY_COUNT, (pu1Byte)(&Adapter->TxStats.NumTxRetryCount) ); #endif } #ifdef CONFIG_SUPPORT_HW_WPS_PBC static void dm_CheckPbcGPIO(_adapter *padapter) { u8 tmp1byte; u8 bPbcPressed = _FALSE; if(!padapter->registrypriv.hw_wps_pbc) return; #ifdef CONFIG_USB_HCI tmp1byte = rtw_read8(padapter, GPIO_IO_SEL); tmp1byte |= (HAL_8188E_HW_GPIO_WPS_BIT); rtw_write8(padapter, GPIO_IO_SEL, tmp1byte); //enable GPIO[2] as output mode tmp1byte &= ~(HAL_8188E_HW_GPIO_WPS_BIT); rtw_write8(padapter, GPIO_IN, tmp1byte); //reset the floating voltage level tmp1byte = rtw_read8(padapter, GPIO_IO_SEL); tmp1byte &= ~(HAL_8188E_HW_GPIO_WPS_BIT); rtw_write8(padapter, GPIO_IO_SEL, tmp1byte); //enable GPIO[2] as input mode tmp1byte =rtw_read8(padapter, GPIO_IN); if (tmp1byte == 0xff) return ; if (tmp1byte&HAL_8188E_HW_GPIO_WPS_BIT) { bPbcPressed = _TRUE; } #else tmp1byte = rtw_read8(padapter, GPIO_IN); //RT_TRACE(COMP_IO, DBG_TRACE, ("dm_CheckPbcGPIO - %x\n", tmp1byte)); if (tmp1byte == 0xff || padapter->init_adpt_in_progress) return ; if((tmp1byte&HAL_8188E_HW_GPIO_WPS_BIT)==0) { bPbcPressed = _TRUE; } #endif if( _TRUE == bPbcPressed) { // Here we only set bPbcPressed to true // After trigger PBC, the variable will be set to false DBG_8192C("CheckPbcGPIO - PBC is pressed\n"); rtw_request_wps_pbc_event(padapter); } } #endif//#ifdef CONFIG_SUPPORT_HW_WPS_PBC #ifdef CONFIG_PCI_HCI // // Description: // Perform interrupt migration dynamically to reduce CPU utilization. // // Assumption: // 1. Do not enable migration under WIFI test. // // Created by Roger, 2010.03.05. // VOID dm_InterruptMigration( IN PADAPTER Adapter ) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); struct mlme_priv *pmlmepriv = &(Adapter->mlmepriv); BOOLEAN bCurrentIntMt, bCurrentACIntDisable; BOOLEAN IntMtToSet = _FALSE; BOOLEAN ACIntToSet = _FALSE; // Retrieve current interrupt migration and Tx four ACs IMR settings first. bCurrentIntMt = pHalData->bInterruptMigration; bCurrentACIntDisable = pHalData->bDisableTxInt; // // <Roger_Notes> Currently we use busy traffic for reference instead of RxIntOK counts to prevent non-linear Rx statistics // when interrupt migration is set before. 2010.03.05. // if(!Adapter->registrypriv.wifi_spec && (check_fwstate(pmlmepriv, _FW_LINKED)== _TRUE) && pmlmepriv->LinkDetectInfo.bHigherBusyTraffic) { IntMtToSet = _TRUE; // To check whether we should disable Tx interrupt or not. if(pmlmepriv->LinkDetectInfo.bHigherBusyRxTraffic ) ACIntToSet = _TRUE; } //Update current settings. if( bCurrentIntMt != IntMtToSet ){ DBG_8192C("%s(): Update interrrupt migration(%d)\n",__FUNCTION__,IntMtToSet); if(IntMtToSet) { // // <Roger_Notes> Set interrrupt migration timer and corresponging Tx/Rx counter. // timer 25ns*0xfa0=100us for 0xf packets. // 2010.03.05. // rtw_write32(Adapter, REG_INT_MIG, 0xff000fa0);// 0x306:Rx, 0x307:Tx pHalData->bInterruptMigration = IntMtToSet; } else { // Reset all interrupt migration settings. rtw_write32(Adapter, REG_INT_MIG, 0); pHalData->bInterruptMigration = IntMtToSet; } } /*if( bCurrentACIntDisable != ACIntToSet ){ DBG_8192C("%s(): Update AC interrrupt(%d)\n",__FUNCTION__,ACIntToSet); if(ACIntToSet) // Disable four ACs interrupts. { // // <Roger_Notes> Disable VO, VI, BE and BK four AC interrupts to gain more efficient CPU utilization. // When extremely highly Rx OK occurs, we will disable Tx interrupts. // 2010.03.05. // UpdateInterruptMask8192CE( Adapter, 0, RT_AC_INT_MASKS ); pHalData->bDisableTxInt = ACIntToSet; } else// Enable four ACs interrupts. { UpdateInterruptMask8192CE( Adapter, RT_AC_INT_MASKS, 0 ); pHalData->bDisableTxInt = ACIntToSet; } }*/ } #endif // // Initialize GPIO setting registers // static void dm_InitGPIOSetting( IN PADAPTER Adapter ) { PHAL_DATA_TYPE pHalData = GET_HAL_DATA(Adapter); u8 tmp1byte; tmp1byte = rtw_read8(Adapter, REG_GPIO_MUXCFG); tmp1byte &= (GPIOSEL_GPIO | ~GPIOSEL_ENBT); #ifdef CONFIG_BT_COEXIST // UMB-B cut bug. We need to support the modification. if (IS_81xxC_VENDOR_UMC_B_CUT(pHalData->VersionID) && pHalData->bt_coexist.BT_Coexist) { tmp1byte |= (BIT5); } #endif rtw_write8(Adapter, REG_GPIO_MUXCFG, tmp1byte); } //============================================================ // functions //============================================================ static void Init_ODM_ComInfo_88E(PADAPTER Adapter) { PHAL_DATA_TYPE pHalData = GET_HAL_DATA(Adapter); struct dm_priv *pdmpriv = &pHalData->dmpriv; PDM_ODM_T pDM_Odm = &(pHalData->odmpriv); u8 cut_ver,fab_ver; Init_ODM_ComInfo(Adapter); ODM_CmnInfoInit(pDM_Odm,ODM_CMNINFO_IC_TYPE,ODM_RTL8188E); fab_ver = ODM_TSMC; cut_ver = ODM_CUT_A; if(IS_VENDOR_8188E_I_CUT_SERIES(Adapter)) cut_ver = ODM_CUT_I; ODM_CmnInfoInit(pDM_Odm,ODM_CMNINFO_FAB_VER,fab_ver); ODM_CmnInfoInit(pDM_Odm,ODM_CMNINFO_CUT_VER,cut_ver); ODM_CmnInfoInit(pDM_Odm, ODM_CMNINFO_RF_ANTENNA_TYPE, pHalData->TRxAntDivType); #ifdef CONFIG_DISABLE_ODM pdmpriv->InitODMFlag = 0; #else pdmpriv->InitODMFlag = ODM_RF_CALIBRATION | ODM_RF_TX_PWR_TRACK //| ; //if(pHalData->AntDivCfg) // pdmpriv->InitODMFlag |= ODM_BB_ANT_DIV; #endif ODM_CmnInfoUpdate(pDM_Odm,ODM_CMNINFO_ABILITY,pdmpriv->InitODMFlag); } static void Update_ODM_ComInfo_88E(PADAPTER Adapter) { PHAL_DATA_TYPE pHalData = GET_HAL_DATA(Adapter); PDM_ODM_T pDM_Odm = &(pHalData->odmpriv); struct dm_priv *pdmpriv = &pHalData->dmpriv; int i; pdmpriv->InitODMFlag = 0 | ODM_BB_DIG | ODM_BB_RA_MASK | ODM_BB_DYNAMIC_TXPWR | ODM_BB_FA_CNT | ODM_BB_RSSI_MONITOR | ODM_BB_CCK_PD | ODM_BB_PWR_SAVE | ODM_BB_CFO_TRACKING | ODM_RF_CALIBRATION | ODM_RF_TX_PWR_TRACK | ODM_BB_NHM_CNT | ODM_BB_PRIMARY_CCA // | ODM_BB_PWR_TRAIN ; if (rtw_odm_adaptivity_needed(Adapter) == _TRUE) pdmpriv->InitODMFlag |= ODM_BB_ADAPTIVITY; if (!Adapter->registrypriv.qos_opt_enable) { pdmpriv->InitODMFlag |= ODM_MAC_EDCA_TURBO; } if(pHalData->AntDivCfg) pdmpriv->InitODMFlag |= ODM_BB_ANT_DIV; #if (MP_DRIVER==1) if (Adapter->registrypriv.mp_mode == 1) { pdmpriv->InitODMFlag = 0 | ODM_RF_CALIBRATION | ODM_RF_TX_PWR_TRACK ; } #endif//(MP_DRIVER==1) #ifdef CONFIG_DISABLE_ODM pdmpriv->InitODMFlag = 0; #endif//CONFIG_DISABLE_ODM ODM_CmnInfoUpdate(pDM_Odm,ODM_CMNINFO_ABILITY,pdmpriv->InitODMFlag); ODM_CmnInfoInit(pDM_Odm, ODM_CMNINFO_RF_ANTENNA_TYPE, pHalData->TRxAntDivType); } void rtl8188e_InitHalDm( IN PADAPTER Adapter ) { PHAL_DATA_TYPE pHalData = GET_HAL_DATA(Adapter); struct dm_priv *pdmpriv = &pHalData->dmpriv; PDM_ODM_T pDM_Odm = &(pHalData->odmpriv); u8 i; #ifdef CONFIG_USB_HCI dm_InitGPIOSetting(Adapter); #endif pdmpriv->DM_Type = DM_Type_ByDriver; pdmpriv->DMFlag = DYNAMIC_FUNC_DISABLE; Update_ODM_ComInfo_88E(Adapter); ODM_DMInit(pDM_Odm); } VOID rtl8188e_HalDmWatchDog( IN PADAPTER Adapter ) { BOOLEAN bFwCurrentInPSMode = _FALSE; BOOLEAN bFwPSAwake = _TRUE; u8 hw_init_completed = _FALSE; PHAL_DATA_TYPE pHalData = GET_HAL_DATA(Adapter); struct dm_priv *pdmpriv = &pHalData->dmpriv; PDM_ODM_T pDM_Odm = &(pHalData->odmpriv); #ifdef CONFIG_CONCURRENT_MODE PADAPTER pbuddy_adapter = Adapter->pbuddy_adapter; #endif //CONFIG_CONCURRENT_MODE _func_enter_; hw_init_completed = Adapter->hw_init_completed; if (hw_init_completed == _FALSE) goto skip_dm; #ifdef CONFIG_LPS bFwCurrentInPSMode = adapter_to_pwrctl(Adapter)->bFwCurrentInPSMode; rtw_hal_get_hwreg(Adapter, HW_VAR_FWLPS_RF_ON, (u8 *)(&bFwPSAwake)); #endif #ifdef CONFIG_P2P_PS // Fw is under p2p powersaving mode, driver should stop dynamic mechanism. // modifed by thomas. 2011.06.11. if(Adapter->wdinfo.p2p_ps_mode) bFwPSAwake = _FALSE; #endif //CONFIG_P2P_PS if( (hw_init_completed == _TRUE) && ((!bFwCurrentInPSMode) && bFwPSAwake)) { // // Calculate Tx/Rx statistics. // dm_CheckStatistics(Adapter); rtw_hal_check_rxfifo_full(Adapter); // // Dynamically switch RTS/CTS protection. // //dm_CheckProtection(Adapter); #ifdef CONFIG_PCI_HCI // 20100630 Joseph: Disable Interrupt Migration mechanism temporarily because it degrades Rx throughput. // Tx Migration settings. //dm_InterruptMigration(Adapter); //if(Adapter->HalFunc.TxCheckStuckHandler(Adapter)) // PlatformScheduleWorkItem(&(GET_HAL_DATA(Adapter)->HalResetWorkItem)); #endif } //ODM if (hw_init_completed == _TRUE) { u8 bLinked=_FALSE; u8 bsta_state=_FALSE; #ifdef CONFIG_DISABLE_ODM pHalData->odmpriv.SupportAbility = 0; #endif if(rtw_linked_check(Adapter)){ bLinked = _TRUE; if (check_fwstate(&Adapter->mlmepriv, WIFI_STATION_STATE)) bsta_state = _TRUE; } #ifdef CONFIG_CONCURRENT_MODE if(pbuddy_adapter && rtw_linked_check(pbuddy_adapter)){ bLinked = _TRUE; if(pbuddy_adapter && check_fwstate(&pbuddy_adapter->mlmepriv, WIFI_STATION_STATE)) bsta_state = _TRUE; } #endif //CONFIG_CONCURRENT_MODE ODM_CmnInfoUpdate(&pHalData->odmpriv ,ODM_CMNINFO_LINK, bLinked); ODM_CmnInfoUpdate(&pHalData->odmpriv ,ODM_CMNINFO_STATION_STATE, bsta_state); ODM_DMWatchdog(&pHalData->odmpriv); } skip_dm: #ifdef CONFIG_SUPPORT_HW_WPS_PBC // Check GPIO to determine current Pbc status. dm_CheckPbcGPIO(Adapter); #endif return; } void rtl8188e_init_dm_priv(IN PADAPTER Adapter) { PHAL_DATA_TYPE pHalData = GET_HAL_DATA(Adapter); struct dm_priv *pdmpriv = &pHalData->dmpriv; PDM_ODM_T podmpriv = &pHalData->odmpriv; _rtw_memset(pdmpriv, 0, sizeof(struct dm_priv)); //_rtw_spinlock_init(&(pHalData->odm_stainfo_lock)); Init_ODM_ComInfo_88E(Adapter); ODM_InitAllTimers(podmpriv ); PHYDM_InitDebugSetting(podmpriv); } void rtl8188e_deinit_dm_priv(IN PADAPTER Adapter) { PHAL_DATA_TYPE pHalData = GET_HAL_DATA(Adapter); struct dm_priv *pdmpriv = &pHalData->dmpriv; PDM_ODM_T podmpriv = &pHalData->odmpriv; //_rtw_spinlock_free(&pHalData->odm_stainfo_lock); ODM_CancelAllTimers(podmpriv); } #ifdef CONFIG_ANTENNA_DIVERSITY // Add new function to reset the state of antenna diversity before link. // // Compare RSSI for deciding antenna void AntDivCompare8188E(PADAPTER Adapter, WLAN_BSSID_EX *dst, WLAN_BSSID_EX *src) { //PADAPTER Adapter = pDM_Odm->Adapter ; HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); if(0 != pHalData->AntDivCfg ) { //DBG_8192C("update_network=> orgRSSI(%d)(%d),newRSSI(%d)(%d)\n",dst->Rssi,query_rx_pwr_percentage(dst->Rssi), // src->Rssi,query_rx_pwr_percentage(src->Rssi)); //select optimum_antenna for before linked =>For antenna diversity if(dst->Rssi >= src->Rssi )//keep org parameter { src->Rssi = dst->Rssi; src->PhyInfo.Optimum_antenna = dst->PhyInfo.Optimum_antenna; } } } // Add new function to reset the state of antenna diversity before link. u8 AntDivBeforeLink8188E(PADAPTER Adapter ) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); PDM_ODM_T pDM_Odm =&pHalData->odmpriv; SWAT_T *pDM_SWAT_Table = &pDM_Odm->DM_SWAT_Table; struct mlme_priv *pmlmepriv = &(Adapter->mlmepriv); // Condition that does not need to use antenna diversity. if(pHalData->AntDivCfg==0) { //DBG_8192C("odm_AntDivBeforeLink8192C(): No AntDiv Mechanism.\n"); return _FALSE; } if(check_fwstate(pmlmepriv, _FW_LINKED) == _TRUE) { return _FALSE; } if(pDM_SWAT_Table->SWAS_NoLink_State == 0){ //switch channel pDM_SWAT_Table->SWAS_NoLink_State = 1; pDM_SWAT_Table->CurAntenna = (pDM_SWAT_Table->CurAntenna==MAIN_ANT)?AUX_ANT:MAIN_ANT; //PHY_SetBBReg(Adapter, rFPGA0_XA_RFInterfaceOE, 0x300, pDM_SWAT_Table->CurAntenna); rtw_antenna_select_cmd(Adapter, pDM_SWAT_Table->CurAntenna, _FALSE); //DBG_8192C("%s change antenna to ANT_( %s ).....\n",__FUNCTION__, (pDM_SWAT_Table->CurAntenna==MAIN_ANT)?"MAIN":"AUX"); return _TRUE; } else { pDM_SWAT_Table->SWAS_NoLink_State = 0; return _FALSE; } } #endif
27.32969
124
0.684951
a9515f207e85a04cd474c507137747c9409300b7
8,261
h
C
src/bthread/execution_queue.h
gtarcoder/brpc
ed01ed4f6c84e95bb0e8564451d40c65bdb432fb
[ "Apache-2.0" ]
5
2017-12-28T02:27:45.000Z
2020-07-18T06:58:39.000Z
src/bthread/execution_queue.h
gtarcoder/brpc
ed01ed4f6c84e95bb0e8564451d40c65bdb432fb
[ "Apache-2.0" ]
1
2019-08-05T13:29:01.000Z
2019-08-05T13:29:01.000Z
src/bthread/execution_queue.h
gxkevin/brpc
a9854d46df6a27d058740bb1dfdc3f3f3d1c9b72
[ "Apache-2.0" ]
11
2017-12-28T03:22:45.000Z
2022-02-09T09:19:48.000Z
// bthread - A M:N threading library to make applications more concurrent. // Copyright (c) 2015 Baidu, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Author: Zhangyi Chen (chenzhangyi01@baidu.com) // Date: 2015/10/23 18:16:16 #ifndef BTHREAD_EXECUTION_QUEUE_H #define BTHREAD_EXECUTION_QUEUE_H #include "bthread/bthread.h" #include "butil/type_traits.h" namespace bthread { // ExecutionQueue is a special wait-free MPSC queue of which the consumer thread // is auto started by the execute operation and auto quits if there are no more // tasks, in another word there isn't a daemon bthread waiting to consume tasks template <typename T> struct ExecutionQueueId; template <typename T> class ExecutionQueue; struct TaskNode; class ExecutionQueueBase; class TaskIteratorBase { DISALLOW_COPY_AND_ASSIGN(TaskIteratorBase); friend class ExecutionQueueBase; public: // Returns true when the ExecutionQueue is stopped and there will never be // more tasks and you can safely release all the related resources ever // after. bool is_queue_stopped() const { return _is_stopped; } operator bool() const; protected: TaskIteratorBase(TaskNode* head, ExecutionQueueBase* queue, bool is_stopped, bool high_priority) : _cur_node(head) , _head(head) , _q(queue) , _is_stopped(is_stopped) , _high_priority(high_priority) , _should_break(false) , _num_iterated(0) { operator++(); } ~TaskIteratorBase(); void operator++(); TaskNode* cur_node() const { return _cur_node; } private: int num_iterated() const { return _num_iterated; } bool should_break_for_high_priority_tasks(); TaskNode* _cur_node; TaskNode* _head; ExecutionQueueBase* _q; bool _is_stopped; bool _high_priority; bool _should_break; int _num_iterated; }; // Iterate over the given tasks // // Examples: // int demo_execute(void* meta, TaskIterator<T>& iter) { // if (iter.is_stopped()) { // // destroy meta and related resources // return 0; // } // for (; iter; ++iter) { // // do_something(*iter) // // or do_something(iter->a_member_of_T) // } // return 0; // } template <typename T> class TaskIterator : public TaskIteratorBase { TaskIterator(); public: typedef T* pointer; typedef T& reference; reference operator*() const; pointer operator->() const { return &(operator*()); } TaskIterator& operator++(); void operator++(int); }; struct TaskHandle { TaskHandle(); TaskNode* node; int64_t version; }; struct TaskOptions { TaskOptions(); TaskOptions(bool high_priority, bool in_place_if_possible); // Executor would execute high-priority tasks in the FIFO order but before // all pending normal-priority tasks. // NOTE: We don't guarantee any kind of real-time as there might be tasks still // in process which are uninterruptible. // // Default: false bool high_priority; // If |in_place_if_possible| is true, execution_queue_execute would call // execute immediately instead of starting a bthread if possible // // Note: Running callbacks in place might cause the dead lock issue, you // should be very careful turning this flag on. // // Default: false bool in_place_if_possible; }; const static TaskOptions TASK_OPTIONS_NORMAL = TaskOptions(false, false); const static TaskOptions TASK_OPTIONS_URGENT = TaskOptions(true, false); const static TaskOptions TASK_OPTIONS_INPLACE = TaskOptions(false, true); class Executor { public: virtual ~Executor() {} // Return 0 on success. virtual int submit(void * (*fn)(void*), void* args) = 0; }; struct ExecutionQueueOptions { ExecutionQueueOptions(); // Attribute of the bthread which execute runs on // default: BTHREAD_ATTR_NORMAL bthread_attr_t bthread_attr; // Executor that tasks run on. bthread will be used when executor = NULL. // Note that TaskOptions.in_place_if_possible = false will not work, if implementation of // Executor is in-place(synchronous). Executor * executor; }; // Start a ExecutionQueue. If |options| is NULL, the queue will be created with // the default options. // Returns 0 on success, errno otherwise // NOTE: type |T| can be non-POD but must be copy-constructible template <typename T> int execution_queue_start( ExecutionQueueId<T>* id, const ExecutionQueueOptions* options, int (*execute)(void* meta, TaskIterator<T>& iter), void* meta); // Stop the ExecutionQueue. // After this function is called: // - All the following calls to execution_queue_execute would fail immediately. // - The executor will call |execute| with TaskIterator::is_queue_stopped() being // true exactly once when all the pending tasks have been executed, and after // this point it's ok to release the resource referenced by |meta|. // Returns 0 on success, errno othrwise template <typename T> int execution_queue_stop(ExecutionQueueId<T> id); // Wait until the the stop task (Iterator::is_queue_stopped() returns true) has // been executed template <typename T> int execution_queue_join(ExecutionQueueId<T> id); // Thread-safe and Wait-free. // Execute a task with defaut TaskOptions (normal task); template <typename T> int execution_queue_execute(ExecutionQueueId<T> id, typename butil::add_const_reference<T>::type task); // Thread-safe and Wait-free. // Execute a task with options. e.g // bthread::execution_queue_execute(queue, task, &bthread::TASK_OPTIONS_URGENT) // If |options| is NULL, we will use default options (normal task) // If |handle| is not NULL, we will assign it with the hanlder of this task. template <typename T> int execution_queue_execute(ExecutionQueueId<T> id, typename butil::add_const_reference<T>::type task, const TaskOptions* options); template <typename T> int execution_queue_execute(ExecutionQueueId<T> id, typename butil::add_const_reference<T>::type task, const TaskOptions* options, TaskHandle* handle); // [Thread safe and ABA free] Cancel the corrosponding task. // Returns: // -1: The task was executed or h is an invalid handle // 0: Success // 1: The task is executing int execution_queue_cancel(const TaskHandle& h); // Thread-safe and Wait-free // Address a reference of ExecutionQueue if |id| references to a valid // ExecutionQueue // // |execution_queue_execute| internally fetches a reference of ExecutionQueue at // the begining and releases it at the end, which makes 2 additional cache // updates. In some critical situation where the overhead of // execution_queue_execute matters, you can avoid this by addressing the // reference at the begining of every producer, and execute tasks execatly // through the reference instead of id. // // Note: It makes |execution_queue_stop| a little complicated in the user level, // as we don't pass the `stop task' to |execute| until no one holds any reference. // If you are not sure about the ownership of the return value (which releasees // the reference of the very ExecutionQueue in the destructor) and don't that // care the overhead of ExecutionQueue, DON'T use this function template <typename T> typename ExecutionQueue<T>::scoped_ptr_t execution_queue_address(ExecutionQueueId<T> id); } // namespace bthread #include "bthread/execution_queue_inl.h" #endif //BTHREAD_EXECUTION_QUEUE_H
35.917391
93
0.6981
a504d1883ddb912ae44fc1cf994f313a5b70e60a
562,516
h
C
Public/Source/GacUI.h
ktty/gac
c80e64eee5cfaf7920fcce1d2c775b3f1ed35d05
[ "MS-PL" ]
null
null
null
Public/Source/GacUI.h
ktty/gac
c80e64eee5cfaf7920fcce1d2c775b3f1ed35d05
[ "MS-PL" ]
1
2019-01-08T03:12:33.000Z
2019-01-08T03:12:33.000Z
Public/Source/GacUI.h
ktty/gac
c80e64eee5cfaf7920fcce1d2c775b3f1ed35d05
[ "MS-PL" ]
null
null
null
/*********************************************************************** THIS FILE IS AUTOMATICALLY GENERATED. DO NOT MODIFY DEVELOPER: 陈梓瀚(vczh) ***********************************************************************/ #include "Vlpp.h" /*********************************************************************** GACVLPPREFERENCES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI Vczh Library++ 3.0 References Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_GACVLPPREFERENCES #define VCZH_PRESENTATION_GACVLPPREFERENCES #endif /*********************************************************************** NATIVEWINDOW\GUITYPES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Common Types Classes: ***********************************************************************/ #ifndef VCZH_PRESENTATION_GUITYPES #define VCZH_PRESENTATION_GUITYPES namespace vl { namespace presentation { /*********************************************************************** Enumerations ***********************************************************************/ enum class Alignment { Left=0, Top=0, Center=1, Right=2, Bottom=2, }; /*********************************************************************** TextPos ***********************************************************************/ struct TextPos { vint row; vint column; TextPos() :row(0) ,column(0) { } TextPos(vint _row, vint _column) :row(_row) ,column(_column) { } vint Compare(const TextPos& value)const { if(row<value.row) return -1; if(row>value.row) return 1; if(column<value.column) return -1; if(column>value.column) return 1; return 0; } bool operator==(const TextPos& value)const {return Compare(value)==0;} bool operator!=(const TextPos& value)const {return Compare(value)!=0;} bool operator<(const TextPos& value)const {return Compare(value)<0;} bool operator<=(const TextPos& value)const {return Compare(value)<=0;} bool operator>(const TextPos& value)const {return Compare(value)>0;} bool operator>=(const TextPos& value)const {return Compare(value)>=0;} }; /*********************************************************************** GridPos ***********************************************************************/ struct GridPos { vint row; vint column; GridPos() :row(0) ,column(0) { } GridPos(vint _row, vint _column) :row(_row) ,column(_column) { } vint Compare(const GridPos& value)const { if(row<value.row) return -1; if(row>value.row) return 1; if(column<value.column) return -1; if(column>value.column) return 1; return 0; } bool operator==(const GridPos& value)const {return Compare(value)==0;} bool operator!=(const GridPos& value)const {return Compare(value)!=0;} bool operator<(const GridPos& value)const {return Compare(value)<0;} bool operator<=(const GridPos& value)const {return Compare(value)<=0;} bool operator>(const GridPos& value)const {return Compare(value)>0;} bool operator>=(const GridPos& value)const {return Compare(value)>=0;} }; /*********************************************************************** Point ***********************************************************************/ struct Point { vint x; vint y; Point() :x(0) ,y(0) { } Point(vint _x, vint _y) :x(_x) ,y(_y) { } bool operator==(Point point)const { return x==point.x && y==point.y; } bool operator!=(Point point)const { return x!=point.x || y!=point.y; } }; /*********************************************************************** Size ***********************************************************************/ struct Size { vint x; vint y; Size() :x(0) ,y(0) { } Size(vint _x, vint _y) :x(_x) ,y(_y) { } bool operator==(Size size)const { return x==size.x && y==size.y; } bool operator!=(Size size)const { return x!=size.x || y!=size.y; } }; /*********************************************************************** Rectangle ***********************************************************************/ struct Rect { vint x1; vint y1; vint x2; vint y2; Rect() :x1(0), y1(0), x2(0), y2(0) { } Rect(vint _x1, vint _y1, vint _x2, vint _y2) :x1(_x1), y1(_y1), x2(_x2), y2(_y2) { } Rect(Point p, Size s) :x1(p.x), y1(p.y), x2(p.x+s.x), y2(p.y+s.y) { } bool operator==(Rect rect)const { return x1==rect.x1 && y1==rect.y1 && x2==rect.x2 && y2==rect.y2; } bool operator!=(Rect rect)const { return x1!=rect.x1 || y1!=rect.y1 || x2!=rect.x2 || y2!=rect.y2; } Point LeftTop()const { return Point(x1, y1); } Point RightBottom()const { return Point(x2, y2); } Size GetSize()const { return Size(x2-x1, y2-y1); } vint Left()const { return x1; } vint Right()const { return x2; } vint Width()const { return x2-x1; } vint Top()const { return y1; } vint Bottom()const { return y2; } vint Height()const { return y2-y1; } void Expand(vint x, vint y) { x1-=x; y1-=y; x2+=x; y2+=y; } void Expand(Size s) { x1-=s.x; y1-=s.y; x2+=s.x; y2+=s.y; } void Move(vint x, vint y) { x1+=x; y1+=y; x2+=x; y2+=y; } void Move(Size s) { x1+=s.x; y1+=s.y; x2+=s.x; y2+=s.y; } bool Contains(Point p) { return x1<=p.x && p.x<x2 && y1<=p.y && p.y<y2; } }; /*********************************************************************** 2D operations ***********************************************************************/ inline Point operator+(Point p, Size s) { return Point(p.x+s.x, p.y+s.y); } inline Point operator+(Size s, Point p) { return Point(p.x+s.x, p.y+s.y); } inline Point operator-(Point p, Size s) { return Point(p.x-s.x, p.y-s.y); } inline Size operator-(Point p1, Point p2) { return Size(p1.x-p2.x, p1.y-p2.y); } inline Size operator+(Size s1, Size s2) { return Size(s1.x+s2.x, s1.y+s2.y); } inline Size operator-(Size s1, Size s2) { return Size(s1.x-s2.x, s1.y-s2.y); } inline Size operator*(Size s, vint i) { return Size(s.x*i, s.y*i); } inline Size operator/(Size s, vint i) { return Size(s.x/i, s.y/i); } inline Point operator+=(Point& s1, Size s2) { s1.x+=s2.x; s1.y+=s2.y; return s1; } inline Point operator-=(Point& s1, Size s2) { s1.x-=s2.x; s1.y-=s2.y; return s1; } inline Size operator+=(Size& s1, Size s2) { s1.x+=s2.x; s1.y+=s2.y; return s1; } inline Size operator-=(Size& s1, Size s2) { s1.x-=s2.x; s1.y-=s2.y; return s1; } /*********************************************************************** Color ***********************************************************************/ struct Color { union { struct { unsigned char r; unsigned char g; unsigned char b; unsigned char a; }; unsigned __int32 value; }; Color() :r(0), g(0), b(0), a(255) { } Color(unsigned char _r, unsigned char _g, unsigned char _b, unsigned char _a=255) :r(_r), g(_g), b(_b), a(_a) { } vint Compare(Color color)const { return value-color.value; } static Color Parse(const WString& value) { const wchar_t* code=L"0123456789ABCDEF"; if((value.Length()==7 || value.Length()==9) && value[0]==L'#') { int index[8]={15, 15, 15, 15, 15, 15, 15, 15}; for(vint i=0;i<value.Length()-1;i++) { index[i]=wcschr(code, value[i+1])-code; if(index[i]<0 || index[i]>15) { return Color(); } } Color c; c.r=(unsigned char)(index[0]*16+index[1]); c.g=(unsigned char)(index[2]*16+index[3]); c.b=(unsigned char)(index[4]*16+index[5]); c.a=(unsigned char)(index[6]*16+index[7]); return c; } return Color(); } WString ToString()const { const wchar_t* code=L"0123456789ABCDEF"; wchar_t result[10]=L"#00000000"; result[1]=code[r/16]; result[2]=code[r%16]; result[3]=code[g/16]; result[4]=code[g%16]; result[5]=code[b/16]; result[6]=code[b%16]; if(a==255) { result[7]=L'\0'; } else { result[7]=code[a/16]; result[8]=code[a%16]; } return result; } bool operator==(Color color)const {return Compare(color)==0;} bool operator!=(Color color)const {return Compare(color)!=0;} bool operator<(Color color)const {return Compare(color)<0;} bool operator<=(Color color)const {return Compare(color)<=0;} bool operator>(Color color)const {return Compare(color)>0;} bool operator>=(Color color)const {return Compare(color)>=0;} }; /*********************************************************************** Margin ***********************************************************************/ struct Margin { vint left; vint top; vint right; vint bottom; Margin() :left(0), top(0), right(0), bottom(0) { } Margin(vint _left, vint _top, vint _right, vint _bottom) :left(_left), top(_top), right(_right), bottom(_bottom) { } bool operator==(Margin margin)const { return left==margin.left && top==margin.top && right==margin.right && bottom==margin.bottom; } bool operator!=(Margin margin)const { return left!=margin.left || top!=margin.top || right!=margin.right || bottom!=margin.bottom; } }; /*********************************************************************** Resources ***********************************************************************/ struct FontProperties { WString fontFamily; vint size; bool bold; bool italic; bool underline; bool strikeline; bool antialias; bool verticalAntialias; FontProperties() :size(0) ,bold(false) ,italic(false) ,underline(false) ,strikeline(false) ,antialias(true) ,verticalAntialias(false) { } vint Compare(const FontProperties& value)const { vint result=0; result=WString::Compare(fontFamily, value.fontFamily); if(result!=0) return result; result=size-value.size; if(result!=0) return result; result=(vint)bold-(vint)value.bold; if(result!=0) return result; result=(vint)italic-(vint)value.italic; if(result!=0) return result; result=(vint)underline-(vint)value.underline; if(result!=0) return result; result=(vint)strikeline-(vint)value.strikeline; if(result!=0) return result; result=(vint)antialias-(vint)value.antialias; if(result!=0) return result; return 0; } bool operator==(const FontProperties& value)const {return Compare(value)==0;} bool operator!=(const FontProperties& value)const {return Compare(value)!=0;} bool operator<(const FontProperties& value)const {return Compare(value)<0;} bool operator<=(const FontProperties& value)const {return Compare(value)<=0;} bool operator>(const FontProperties& value)const {return Compare(value)>0;} bool operator>=(const FontProperties& value)const {return Compare(value)>=0;} }; } } #endif /*********************************************************************** GRAPHICSELEMENT\GUIGRAPHICSELEMENTINTERFACES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Element System and Infrastructure Interfaces Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSELEMENTINTERFACES #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSELEMENTINTERFACES namespace vl { namespace presentation { using namespace reflection; namespace elements { class IGuiGraphicsElement; class IGuiGraphicsElementFactory; class IGuiGraphicsRenderer; class IGuiGraphicsRendererFactory; class IGuiGraphicsRenderTarget; /*********************************************************************** Basic Construction ***********************************************************************/ class IGuiGraphicsElement : public virtual IDescriptable, public Description<IGuiGraphicsElement> { public: virtual IGuiGraphicsElementFactory* GetFactory()=0; virtual IGuiGraphicsRenderer* GetRenderer()=0; }; class IGuiGraphicsElementFactory : public Interface { public: virtual WString GetElementTypeName()=0; virtual IGuiGraphicsElement* Create()=0; }; class IGuiGraphicsRenderer : public Interface { public: virtual IGuiGraphicsRendererFactory* GetFactory()=0; virtual void Initialize(IGuiGraphicsElement* element)=0; virtual void Finalize()=0; virtual void SetRenderTarget(IGuiGraphicsRenderTarget* renderTarget)=0; virtual void Render(Rect bounds)=0; virtual void OnElementStateChanged()=0; virtual Size GetMinSize()=0; }; class IGuiGraphicsRendererFactory : public Interface { public: virtual IGuiGraphicsRenderer* Create()=0; }; class IGuiGraphicsRenderTarget : public Interface { public: virtual void StartRendering()=0; virtual void StopRendering()=0; virtual void PushClipper(Rect clipper)=0; virtual void PopClipper()=0; virtual Rect GetClipper()=0; virtual bool IsClipperCoverWholeTarget()=0; }; } } } #endif /*********************************************************************** GRAPHICSELEMENT\GUIGRAPHICSDOCUMENTINTERFACES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Element System and Infrastructure Interfaces Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSDOCUMENTINTERFACES #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSDOCUMENTINTERFACES namespace vl { namespace presentation { using namespace reflection; namespace elements { /*********************************************************************** Layout Engine ***********************************************************************/ class IGuiGraphicsParagraph; class IGuiGraphicsLayoutProvider; class IGuiGraphicsParagraph : public Interface { public: static const vint NullInteractionId = -1; enum TextStyle { Bold=1, Italic=2, Underline=4, Strikeline=8, }; enum BreakCondition { StickToPreviousRun, StickToNextRun, Alone, }; struct InlineObjectProperties { Size size; vint baseline; BreakCondition breakCondition; InlineObjectProperties() :baseline(-1) { } }; virtual IGuiGraphicsLayoutProvider* GetProvider()=0; virtual IGuiGraphicsRenderTarget* GetRenderTarget()=0; virtual bool GetWrapLine()=0; virtual void SetWrapLine(bool value)=0; virtual vint GetMaxWidth()=0; virtual void SetMaxWidth(vint value)=0; virtual Alignment GetParagraphAlignment()=0; virtual void SetParagraphAlignment(Alignment value)=0; virtual bool SetFont(vint start, vint length, const WString& value)=0; virtual bool SetSize(vint start, vint length, vint value)=0; virtual bool SetStyle(vint start, vint length, TextStyle value)=0; virtual bool SetColor(vint start, vint length, Color value)=0; virtual bool SetInlineObject(vint start, vint length, const InlineObjectProperties& properties, Ptr<IGuiGraphicsElement> value)=0; virtual bool ResetInlineObject(vint start, vint length)=0; virtual bool SetInteractionId(vint start, vint length, vint value=NullInteractionId)=0; virtual bool HitTestPoint(Point point, vint& start, vint& length, vint& interactionId)=0; virtual vint GetHeight()=0; virtual void Render(Rect bounds)=0; }; class IGuiGraphicsLayoutProvider : public Interface { public: virtual Ptr<IGuiGraphicsParagraph> CreateParagraph(const WString& text, IGuiGraphicsRenderTarget* renderTarget)=0; }; } } } #endif /*********************************************************************** NATIVEWINDOW\GUINATIVEWINDOW.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Native Window Interfaces: INativeWindow :窗口适配器 INativeWindowListener :窗口事件监听器 INativeController :全局控制器 INativeControllerListener :全局事件监听器 Renderers: GUI_GRAPHICS_RENDERER_GDI GUI_GRAPHICS_RENDERER_DIRECT2D ***********************************************************************/ #ifndef VCZH_PRESENTATION_GUINATIVEWINDOW #define VCZH_PRESENTATION_GUINATIVEWINDOW namespace vl { namespace presentation { using namespace reflection; class INativeWindow; class INativeWindowListener; class INativeController; class INativeControllerListener; /*********************************************************************** System Object ***********************************************************************/ class INativeScreen : public Interface { public: virtual Rect GetBounds()=0; virtual Rect GetClientBounds()=0; virtual WString GetName()=0; virtual bool IsPrimary()=0; }; class INativeCursor : public virtual IDescriptable, Description<INativeCursor> { public: enum SystemCursorType { SmallWaiting, LargeWaiting, Arrow, Cross, Hand, Help, IBeam, SizeAll, SizeNESW, SizeNS, SizeNWSE, SizeWE, LastSystemCursor=SizeWE, }; static const vint SystemCursorCount=LastSystemCursor+1; public: virtual bool IsSystemCursor()=0; virtual SystemCursorType GetSystemCursorType()=0; }; /*********************************************************************** Image Object ***********************************************************************/ class INativeImageService; class INativeImage; class INativeImageFrame; class INativeImageFrameCache : public Interface { public: virtual void OnAttach(INativeImageFrame* frame)=0; virtual void OnDetach(INativeImageFrame* frame)=0; }; class INativeImageFrame : public virtual IDescriptable, public Description<INativeImageFrame> { public: virtual INativeImage* GetImage()=0; virtual Size GetSize()=0; virtual bool SetCache(void* key, Ptr<INativeImageFrameCache> cache)=0; virtual Ptr<INativeImageFrameCache> GetCache(void* key)=0; virtual Ptr<INativeImageFrameCache> RemoveCache(void* key)=0; }; class INativeImage : public virtual IDescriptable, public Description<INativeImage> { public: enum FormatType { Bmp, Gif, Icon, Jpeg, Png, Tiff, Wmp, Unknown, }; virtual INativeImageService* GetImageService()=0; virtual FormatType GetFormat()=0; virtual vint GetFrameCount()=0; virtual INativeImageFrame* GetFrame(vint index)=0; }; class INativeImageService : public Interface { public: virtual Ptr<INativeImage> CreateImageFromFile(const WString& path)=0; virtual Ptr<INativeImage> CreateImageFromMemory(void* buffer, vint length)=0; virtual Ptr<INativeImage> CreateImageFromStream(stream::IStream& stream)=0; }; /*********************************************************************** Native Window ***********************************************************************/ class INativeWindow : public Interface, public Description<INativeWindow> { public: virtual Rect GetBounds()=0; virtual void SetBounds(const Rect& bounds)=0; virtual Size GetClientSize()=0; virtual void SetClientSize(Size size)=0; virtual Rect GetClientBoundsInScreen()=0; virtual WString GetTitle()=0; virtual void SetTitle(WString title)=0; virtual INativeCursor* GetWindowCursor()=0; virtual void SetWindowCursor(INativeCursor* cursor)=0; virtual Point GetCaretPoint()=0; virtual void SetCaretPoint(Point point)=0; virtual INativeWindow* GetParent()=0; virtual void SetParent(INativeWindow* parent)=0; virtual bool GetAlwaysPassFocusToParent()=0; virtual void SetAlwaysPassFocusToParent(bool value)=0; virtual void EnableCustomFrameMode()=0; virtual void DisableCustomFrameMode()=0; virtual bool IsCustomFrameModeEnabled()=0; enum WindowSizeState { Minimized, Restored, Maximized, }; virtual WindowSizeState GetSizeState()=0; virtual void Show()=0; virtual void ShowDeactivated()=0; virtual void ShowRestored()=0; virtual void ShowMaximized()=0; virtual void ShowMinimized()=0; virtual void Hide()=0; virtual bool IsVisible()=0; virtual void Enable()=0; virtual void Disable()=0; virtual bool IsEnabled()=0; virtual void SetFocus()=0; virtual bool IsFocused()=0; virtual void SetActivate()=0; virtual bool IsActivated()=0; virtual void ShowInTaskBar()=0; virtual void HideInTaskBar()=0; virtual bool IsAppearedInTaskBar()=0; virtual void EnableActivate()=0; virtual void DisableActivate()=0; virtual bool IsEnabledActivate()=0; virtual bool RequireCapture()=0; virtual bool ReleaseCapture()=0; virtual bool IsCapturing()=0; virtual bool GetMaximizedBox()=0; virtual void SetMaximizedBox(bool visible)=0; virtual bool GetMinimizedBox()=0; virtual void SetMinimizedBox(bool visible)=0; virtual bool GetBorder()=0; virtual void SetBorder(bool visible)=0; virtual bool GetSizeBox()=0; virtual void SetSizeBox(bool visible)=0; virtual bool GetIconVisible()=0; virtual void SetIconVisible(bool visible)=0; virtual bool GetTitleBar()=0; virtual void SetTitleBar(bool visible)=0; virtual bool GetTopMost()=0; virtual void SetTopMost(bool topmost)=0; virtual bool InstallListener(INativeWindowListener* listener)=0; virtual bool UninstallListener(INativeWindowListener* listener)=0; virtual void RedrawContent()=0; }; struct NativeWindowMouseInfo { bool ctrl; bool shift; bool left; bool middle; bool right; vint x; vint y; vint wheel; }; struct NativeWindowKeyInfo { vint code; bool ctrl; bool shift; bool alt; bool capslock; }; struct NativeWindowCharInfo { wchar_t code; bool ctrl; bool shift; bool alt; bool capslock; }; class INativeWindowListener : public Interface { public: enum HitTestResult { BorderNoSizing, BorderLeft, BorderRight, BorderTop, BorderBottom, BorderLeftTop, BorderRightTop, BorderLeftBottom, BorderRightBottom, Title, ButtonMinimum, ButtonMaximum, ButtonClose, Client, Icon, NoDecision, }; virtual HitTestResult HitTest(Point location); virtual void Moving(Rect& bounds, bool fixSizeOnly); virtual void Moved(); virtual void Enabled(); virtual void Disabled(); virtual void GotFocus(); virtual void LostFocus(); virtual void Activated(); virtual void Deactivated(); virtual void Opened(); virtual void Closing(bool& cancel); virtual void Closed(); virtual void Paint(); virtual void Destroying(); virtual void Destroyed(); virtual void LeftButtonDown(const NativeWindowMouseInfo& info); virtual void LeftButtonUp(const NativeWindowMouseInfo& info); virtual void LeftButtonDoubleClick(const NativeWindowMouseInfo& info); virtual void RightButtonDown(const NativeWindowMouseInfo& info); virtual void RightButtonUp(const NativeWindowMouseInfo& info); virtual void RightButtonDoubleClick(const NativeWindowMouseInfo& info); virtual void MiddleButtonDown(const NativeWindowMouseInfo& info); virtual void MiddleButtonUp(const NativeWindowMouseInfo& info); virtual void MiddleButtonDoubleClick(const NativeWindowMouseInfo& info); virtual void HorizontalWheel(const NativeWindowMouseInfo& info); virtual void VerticalWheel(const NativeWindowMouseInfo& info); virtual void MouseMoving(const NativeWindowMouseInfo& info); virtual void MouseEntered(); virtual void MouseLeaved(); virtual void KeyDown(const NativeWindowKeyInfo& info); virtual void KeyUp(const NativeWindowKeyInfo& info); virtual void SysKeyDown(const NativeWindowKeyInfo& info); virtual void SysKeyUp(const NativeWindowKeyInfo& info); virtual void Char(const NativeWindowCharInfo& info); }; /*********************************************************************** Native Window Services ***********************************************************************/ class INativeResourceService : public virtual Interface { public: virtual INativeCursor* GetSystemCursor(INativeCursor::SystemCursorType type)=0; virtual INativeCursor* GetDefaultSystemCursor()=0; virtual FontProperties GetDefaultFont()=0; virtual void SetDefaultFont(const FontProperties& value)=0; }; class INativeDelay : public Interface, public Description<INativeDelay> { public: enum ExecuteStatus { Pending, Executing, Executed, Canceled, }; virtual ExecuteStatus GetStatus()=0; virtual bool Delay(vint milliseconds)=0; virtual bool Cancel()=0; }; class INativeAsyncService : public virtual Interface { public: virtual bool IsInMainThread()=0; virtual void InvokeAsync(const Func<void()>& proc)=0; virtual void InvokeInMainThread(const Func<void()>& proc)=0; virtual bool InvokeInMainThreadAndWait(const Func<void()>& proc, vint milliseconds=-1)=0; virtual Ptr<INativeDelay> DelayExecute(const Func<void()>& proc, vint milliseconds)=0; virtual Ptr<INativeDelay> DelayExecuteInMainThread(const Func<void()>& proc, vint milliseconds)=0; }; class INativeClipboardService : public virtual Interface { public: virtual bool ContainsText()=0; virtual WString GetText()=0; virtual bool SetText(const WString& value)=0; }; class INativeScreenService : public virtual Interface { public: virtual vint GetScreenCount()=0; virtual INativeScreen* GetScreen(vint index)=0; virtual INativeScreen* GetScreen(INativeWindow* window)=0; }; class INativeWindowService : public virtual Interface { public: virtual INativeWindow* CreateNativeWindow()=0; virtual void DestroyNativeWindow(INativeWindow* window)=0; virtual INativeWindow* GetMainWindow()=0; virtual INativeWindow* GetWindow(Point location)=0; virtual void Run(INativeWindow* window)=0; }; class INativeInputService : public virtual Interface { public: virtual void StartHookMouse()=0; virtual void StopHookMouse()=0; virtual bool IsHookingMouse()=0; virtual void StartTimer()=0; virtual void StopTimer()=0; virtual bool IsTimerEnabled()=0; virtual bool IsKeyPressing(vint code)=0; virtual bool IsKeyToggled(vint code)=0; virtual WString GetKeyName(vint code)=0; }; class INativeCallbackService : public virtual Interface { public: virtual bool InstallListener(INativeControllerListener* listener)=0; virtual bool UninstallListener(INativeControllerListener* listener)=0; }; class INativeDialogService : public virtual Interface { public: enum MessageBoxButtonsInput { DisplayOK, DisplayOKCancel, DisplayYesNo, DisplayYesNoCancel, DisplayRetryCancel, DisplayAbortRetryIgnore, DisplayCancelTryAgainContinue, }; enum MessageBoxButtonsOutput { SelectOK, SelectCancel, SelectYes, SelectNo, SelectRetry, SelectAbort, SelectIgnore, SelectTryAgain, SelectContinue, }; enum MessageBoxDefaultButton { DefaultFirst, DefaultSecond, DefaultThird, }; enum MessageBoxIcons { IconNone, IconError, IconQuestion, IconWarning, IconInformation, }; enum MessageBoxModalOptions { ModalWindow, ModalTask, ModalSystem, }; virtual MessageBoxButtonsOutput ShowMessageBox(INativeWindow* window, const WString& text, const WString& title=L"", MessageBoxButtonsInput buttons=DisplayOK, MessageBoxDefaultButton defaultButton=DefaultFirst, MessageBoxIcons icon=IconNone, MessageBoxModalOptions modal=ModalWindow)=0; enum ColorDialogCustomColorOptions { CustomColorDisabled, CustomColorEnabled, CustomColorOpened, }; virtual bool ShowColorDialog(INativeWindow* window, Color& selection, bool selected=false, ColorDialogCustomColorOptions customColorOptions=CustomColorEnabled, Color* customColors=0)=0; virtual bool ShowFontDialog(INativeWindow* window, FontProperties& selectionFont, Color& selectionColor, bool selected=false, bool showEffect=true, bool forceFontExist=true)=0; enum FileDialogTypes { FileDialogOpen, FileDialogOpenPreview, FileDialogSave, FileDialogSavePreview, }; enum FileDialogOptions { FileDialogAllowMultipleSelection = 1, FileDialogFileMustExist = 2, FileDialogShowReadOnlyCheckBox = 4, FileDialogDereferenceLinks = 8, FileDialogShowNetworkButton = 16, FileDialogPromptCreateFile = 32, FileDialogPromptOverwriteFile = 64, FileDialogDirectoryMustExist = 128, FileDialogAddToRecent = 256, }; virtual bool ShowFileDialog(INativeWindow* window, collections::List<WString>& selectionFileNames, vint& selectionFilterIndex, FileDialogTypes dialogType, const WString& title, const WString& initialFileName, const WString& initialDirectory, const WString& defaultExtension, const WString& filter, FileDialogOptions options)=0; }; /*********************************************************************** Native Window Controller ***********************************************************************/ class INativeController : public virtual Interface { public: virtual INativeCallbackService* CallbackService()=0; virtual INativeResourceService* ResourceService()=0; virtual INativeAsyncService* AsyncService()=0; virtual INativeClipboardService* ClipboardService()=0; virtual INativeImageService* ImageService()=0; virtual INativeScreenService* ScreenService()=0; virtual INativeWindowService* WindowService()=0; virtual INativeInputService* InputService()=0; virtual INativeDialogService* DialogService()=0; virtual WString GetOSVersion()=0; virtual WString GetExecutablePath()=0; }; class INativeControllerListener : public Interface { public: virtual void LeftButtonDown(Point position); virtual void LeftButtonUp(Point position); virtual void RightButtonDown(Point position); virtual void RightButtonUp(Point position); virtual void MouseMoving(Point position); virtual void GlobalTimer(); virtual void ClipboardUpdated(); virtual void NativeWindowCreated(INativeWindow* window); virtual void NativeWindowDestroying(INativeWindow* window); }; extern INativeController* GetCurrentController(); extern void SetCurrentController(INativeController* controller); } } /*********************************************************************** Native Window Provider ***********************************************************************/ /* * Virtual Keys, Standard Set */ #define VKEY_LBUTTON 0x01 #define VKEY_RBUTTON 0x02 #define VKEY_CANCEL 0x03 #define VKEY_MBUTTON 0x04 /* NOT contiguous with L & RBUTTON */ #define VKEY_XBUTTON1 0x05 /* NOT contiguous with L & RBUTTON */ #define VKEY_XBUTTON2 0x06 /* NOT contiguous with L & RBUTTON */ /* * 0x07 : unassigned */ #define VKEY_BACK 0x08 #define VKEY_TAB 0x09 /* * 0x0A - 0x0B : reserved */ #define VKEY_CLEAR 0x0C #define VKEY_RETURN 0x0D #define VKEY_SHIFT 0x10 #define VKEY_CONTROL 0x11 #define VKEY_MENU 0x12 #define VKEY_PAUSE 0x13 #define VKEY_CAPITAL 0x14 #define VKEY_KANA 0x15 #define VKEY_HANGEUL 0x15 /* old name - should be here for compatibility */ #define VKEY_HANGUL 0x15 #define VKEY_JUNJA 0x17 #define VKEY_FINAL 0x18 #define VKEY_HANJA 0x19 #define VKEY_KANJI 0x19 #define VKEY_ESCAPE 0x1B #define VKEY_CONVERT 0x1C #define VKEY_NONCONVERT 0x1D #define VKEY_ACCEPT 0x1E #define VKEY_MODECHANGE 0x1F #define VKEY_SPACE 0x20 #define VKEY_PRIOR 0x21 #define VKEY_NEXT 0x22 #define VKEY_END 0x23 #define VKEY_HOME 0x24 #define VKEY_LEFT 0x25 #define VKEY_UP 0x26 #define VKEY_RIGHT 0x27 #define VKEY_DOWN 0x28 #define VKEY_SELECT 0x29 #define VKEY_PRINT 0x2A #define VKEY_EXECUTE 0x2B #define VKEY_SNAPSHOT 0x2C #define VKEY_INSERT 0x2D #define VKEY_DELETE 0x2E #define VKEY_HELP 0x2F /* * VKEY_0 - VKEY_9 are the same as ASCII '0' - '9' (0x30 - 0x39) * 0x40 : unassigned * VKEY_A - VKEY_Z are the same as ASCII 'A' - 'Z' (0x41 - 0x5A) */ #define VKEY_LWIN 0x5B #define VKEY_RWIN 0x5C #define VKEY_APPS 0x5D /* * 0x5E : reserved */ #define VKEY_SLEEP 0x5F #define VKEY_NUMPAD0 0x60 #define VKEY_NUMPAD1 0x61 #define VKEY_NUMPAD2 0x62 #define VKEY_NUMPAD3 0x63 #define VKEY_NUMPAD4 0x64 #define VKEY_NUMPAD5 0x65 #define VKEY_NUMPAD6 0x66 #define VKEY_NUMPAD7 0x67 #define VKEY_NUMPAD8 0x68 #define VKEY_NUMPAD9 0x69 #define VKEY_MULTIPLY 0x6A #define VKEY_ADD 0x6B #define VKEY_SEPARATOR 0x6C #define VKEY_SUBTRACT 0x6D #define VKEY_DECIMAL 0x6E #define VKEY_DIVIDE 0x6F #define VKEY_F1 0x70 #define VKEY_F2 0x71 #define VKEY_F3 0x72 #define VKEY_F4 0x73 #define VKEY_F5 0x74 #define VKEY_F6 0x75 #define VKEY_F7 0x76 #define VKEY_F8 0x77 #define VKEY_F9 0x78 #define VKEY_F10 0x79 #define VKEY_F11 0x7A #define VKEY_F12 0x7B #define VKEY_F13 0x7C #define VKEY_F14 0x7D #define VKEY_F15 0x7E #define VKEY_F16 0x7F #define VKEY_F17 0x80 #define VKEY_F18 0x81 #define VKEY_F19 0x82 #define VKEY_F20 0x83 #define VKEY_F21 0x84 #define VKEY_F22 0x85 #define VKEY_F23 0x86 #define VKEY_F24 0x87 /* * 0x88 - 0x8F : unassigned */ #define VKEY_NUMLOCK 0x90 #define VKEY_SCROLL 0x91 /* * NEC PC-9800 kbd definitions */ #define VKEY_OEM_NEC_EQUAL 0x92 // '=' key on numpad /* * Fujitsu/OASYS kbd definitions */ #define VKEY_OEM_FJ_JISHO 0x92 // 'Dictionary' key #define VKEY_OEM_FJ_MASSHOU 0x93 // 'Unregister word' key #define VKEY_OEM_FJ_TOUROKU 0x94 // 'Register word' key #define VKEY_OEM_FJ_LOYA 0x95 // 'Left OYAYUBI' key #define VKEY_OEM_FJ_ROYA 0x96 // 'Right OYAYUBI' key /* * 0x97 - 0x9F : unassigned */ /* * VKEY_L* & VKEY_R* - left and right Alt, Ctrl and Shift virtual keys. * Used only as parameters to GetAsyncKeyState() and GetKeyState(). * No other API or message will distinguish left and right keys in this way. */ #define VKEY_LSHIFT 0xA0 #define VKEY_RSHIFT 0xA1 #define VKEY_LCONTROL 0xA2 #define VKEY_RCONTROL 0xA3 #define VKEY_LMENU 0xA4 #define VKEY_RMENU 0xA5 #define VKEY_BROWSER_BACK 0xA6 #define VKEY_BROWSER_FORWARD 0xA7 #define VKEY_BROWSER_REFRESH 0xA8 #define VKEY_BROWSER_STOP 0xA9 #define VKEY_BROWSER_SEARCH 0xAA #define VKEY_BROWSER_FAVORITES 0xAB #define VKEY_BROWSER_HOME 0xAC #define VKEY_VOLUME_MUTE 0xAD #define VKEY_VOLUME_DOWN 0xAE #define VKEY_VOLUME_UP 0xAF #define VKEY_MEDIA_NEXT_TRACK 0xB0 #define VKEY_MEDIA_PREV_TRACK 0xB1 #define VKEY_MEDIA_STOP 0xB2 #define VKEY_MEDIA_PLAY_PAUSE 0xB3 #define VKEY_LAUNCH_MAIL 0xB4 #define VKEY_LAUNCH_MEDIA_SELECT 0xB5 #define VKEY_LAUNCH_APP1 0xB6 #define VKEY_LAUNCH_APP2 0xB7 /* * 0xB8 - 0xB9 : reserved */ #define VKEY_OEM_1 0xBA // ';:' for US #define VKEY_OEM_PLUS 0xBB // '+' any country #define VKEY_OEM_COMMA 0xBC // ',' any country #define VKEY_OEM_MINUS 0xBD // '-' any country #define VKEY_OEM_PERIOD 0xBE // '.' any country #define VKEY_OEM_2 0xBF // '/?' for US #define VKEY_OEM_3 0xC0 // '`~' for US /* * 0xC1 - 0xD7 : reserved */ /* * 0xD8 - 0xDA : unassigned */ #define VKEY_OEM_4 0xDB // '[{' for US #define VKEY_OEM_5 0xDC // '\|' for US #define VKEY_OEM_6 0xDD // ']}' for US #define VKEY_OEM_7 0xDE // ''"' for US #define VKEY_OEM_8 0xDF /* * 0xE0 : reserved */ /* * Various extended or enhanced keyboards */ #define VKEY_OEM_AX 0xE1 // 'AX' key on Japanese AX kbd #define VKEY_OEM_102 0xE2 // "<>" or "\|" on RT 102-key kbd. #define VKEY_ICO_HELP 0xE3 // Help key on ICO #define VKEY_ICO_00 0xE4 // 00 key on ICO #define VKEY_PROCESSKEY 0xE5 #define VKEY_ICO_CLEAR 0xE6 #define VKEY_PACKET 0xE7 /* * 0xE8 : unassigned */ /* * Nokia/Ericsson definitions */ #define VKEY_OEM_RESET 0xE9 #define VKEY_OEM_JUMP 0xEA #define VKEY_OEM_PA1 0xEB #define VKEY_OEM_PA2 0xEC #define VKEY_OEM_PA3 0xED #define VKEY_OEM_WSCTRL 0xEE #define VKEY_OEM_CUSEL 0xEF #define VKEY_OEM_ATTN 0xF0 #define VKEY_OEM_FINISH 0xF1 #define VKEY_OEM_COPY 0xF2 #define VKEY_OEM_AUTO 0xF3 #define VKEY_OEM_ENLW 0xF4 #define VKEY_OEM_BACKTAB 0xF5 #define VKEY_ATTN 0xF6 #define VKEY_CRSEL 0xF7 #define VKEY_EXSEL 0xF8 #define VKEY_EREOF 0xF9 #define VKEY_PLAY 0xFA #define VKEY_ZOOM 0xFB #define VKEY_NONAME 0xFC #define VKEY_PA1 0xFD #define VKEY_OEM_CLEAR 0xFE #endif /*********************************************************************** GRAPHICSELEMENT\GUIGRAPHICSRESOURCEMANAGER.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Element System and Infrastructure Interfaces Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSRESOURCEMANAGER #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSRESOURCEMANAGER namespace vl { namespace presentation { namespace elements { /*********************************************************************** Resource Manager ***********************************************************************/ class GuiGraphicsResourceManager : public Object { typedef collections::Dictionary<WString, Ptr<IGuiGraphicsElementFactory>> elementFactoryMap; typedef collections::Dictionary<WString, Ptr<IGuiGraphicsRendererFactory>> rendererFactoryMap; protected: elementFactoryMap elementFactories; rendererFactoryMap rendererFactories; public: GuiGraphicsResourceManager(); ~GuiGraphicsResourceManager(); virtual bool RegisterElementFactory(IGuiGraphicsElementFactory* factory); virtual bool RegisterRendererFactory(const WString& elementTypeName, IGuiGraphicsRendererFactory* factory); virtual IGuiGraphicsElementFactory* GetElementFactory(const WString& elementTypeName); virtual IGuiGraphicsRendererFactory* GetRendererFactory(const WString& elementTypeName); virtual IGuiGraphicsRenderTarget* GetRenderTarget(INativeWindow* window)=0; virtual IGuiGraphicsLayoutProvider* GetLayoutProvider()=0; }; extern GuiGraphicsResourceManager* GetGuiGraphicsResourceManager(); extern void SetGuiGraphicsResourceManager(GuiGraphicsResourceManager* resourceManager); extern bool RegisterFactories(IGuiGraphicsElementFactory* elementFactory, IGuiGraphicsRendererFactory* rendererFactory); /*********************************************************************** Helpers ***********************************************************************/ #define DEFINE_GUI_GRAPHICS_ELEMENT(TELEMENT, ELEMENT_TYPE_NAME)\ public:\ class Factory : public Object, public IGuiGraphicsElementFactory\ {\ public:\ WString GetElementTypeName()\ {\ return TELEMENT::GetElementTypeName();\ }\ IGuiGraphicsElement* Create()\ {\ TELEMENT* element=new TELEMENT;\ element->factory=this;\ IGuiGraphicsRendererFactory* rendererFactory=GetGuiGraphicsResourceManager()->GetRendererFactory(GetElementTypeName());\ if(rendererFactory)\ {\ element->renderer=rendererFactory->Create();\ element->renderer->Initialize(element);\ }\ return element;\ }\ };\ protected:\ IGuiGraphicsElementFactory* factory;\ Ptr<IGuiGraphicsRenderer> renderer;\ public:\ static WString GetElementTypeName()\ {\ return ELEMENT_TYPE_NAME;\ }\ static TELEMENT* Create()\ {\ return dynamic_cast<TELEMENT*>(GetGuiGraphicsResourceManager()->GetElementFactory(TELEMENT::GetElementTypeName())->Create());\ }\ IGuiGraphicsElementFactory* GetFactory()override\ {\ return factory;\ }\ IGuiGraphicsRenderer* GetRenderer()override\ {\ return renderer.Obj();\ }\ #define DEFINE_GUI_GRAPHICS_RENDERER(TELEMENT, TRENDERER, TTARGET)\ public:\ class Factory : public Object, public IGuiGraphicsRendererFactory\ {\ public:\ IGuiGraphicsRenderer* Create()\ {\ TRENDERER* renderer=new TRENDERER;\ renderer->factory=this;\ renderer->element=0;\ renderer->renderTarget=0;\ return renderer;\ }\ };\ protected:\ IGuiGraphicsRendererFactory* factory;\ TELEMENT* element;\ TTARGET* renderTarget;\ Size minSize;\ public:\ static void Register()\ {\ RegisterFactories(new TELEMENT::Factory, new TRENDERER::Factory);\ }\ IGuiGraphicsRendererFactory* GetFactory()override\ {\ return factory;\ }\ void Initialize(IGuiGraphicsElement* _element)override\ {\ element=dynamic_cast<TELEMENT*>(_element);\ InitializeInternal();\ }\ void Finalize()override\ {\ FinalizeInternal();\ }\ void SetRenderTarget(IGuiGraphicsRenderTarget* _renderTarget)override\ {\ TTARGET* oldRenderTarget=renderTarget;\ renderTarget=dynamic_cast<TTARGET*>(_renderTarget);\ RenderTargetChangedInternal(oldRenderTarget, renderTarget);\ }\ Size GetMinSize()override\ {\ return minSize;\ }\ #define DEFINE_CACHED_RESOURCE_ALLOCATOR(TKEY, TVALUE)\ public:\ static const vint DeadPackageMax=32;\ struct Package\ {\ TVALUE resource;\ vint counter;\ bool operator==(const Package& package)const{return false;}\ bool operator!=(const Package& package)const{return true;}\ };\ struct DeadPackage\ {\ TKEY key;\ TVALUE value;\ bool operator==(const DeadPackage& package)const{return false;}\ bool operator!=(const DeadPackage& package)const{return true;}\ };\ Dictionary<TKEY, Package> aliveResources;\ List<DeadPackage> deadResources;\ public:\ TVALUE Create(const TKEY& key)\ {\ vint index=aliveResources.Keys().IndexOf(key);\ if(index!=-1)\ {\ Package package=aliveResources.Values().Get(index);\ package.counter++;\ aliveResources.Set(key, package);\ return package.resource;\ }\ TVALUE resource;\ for(vint i=0;i<deadResources.Count();i++)\ {\ if(deadResources[i].key==key)\ {\ DeadPackage deadPackage=deadResources[i];\ deadResources.RemoveAt(i);\ resource=deadPackage.value;\ break;\ }\ }\ if(!resource)\ {\ resource=CreateInternal(key);\ }\ Package package;\ package.resource=resource;\ package.counter=1;\ aliveResources.Add(key, package);\ return package.resource;\ }\ void Destroy(const TKEY& key)\ {\ vint index=aliveResources.Keys().IndexOf(key);\ if(index!=-1)\ {\ Package package=aliveResources.Values().Get(index);\ package.counter--;\ if(package.counter==0)\ {\ aliveResources.Remove(key);\ if(deadResources.Count()==DeadPackageMax)\ {\ deadResources.RemoveAt(DeadPackageMax-1);\ }\ DeadPackage deadPackage;\ deadPackage.key=key;\ deadPackage.value=package.resource;\ deadResources.Insert(0, deadPackage);\ }\ else\ {\ aliveResources.Set(key, package);\ }\ }\ } } } } #endif /*********************************************************************** NATIVEWINDOW\GUIRESOURCE.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Resource Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_GUIRESOURCE #define VCZH_PRESENTATION_GUIRESOURCE namespace vl { namespace presentation { using namespace reflection; class GuiResourceItem; class GuiResourceFolder; class GuiResource; class DocumentTextRun; class DocumentHyperlinkTextRun; class DocumentImageRun; /*********************************************************************** Resource Image ***********************************************************************/ class GuiImageData : public Object, public Description<GuiImageData> { protected: Ptr<INativeImage> image; vint frameIndex; public: GuiImageData(); GuiImageData(Ptr<INativeImage> _image, vint _frameIndex); ~GuiImageData(); Ptr<INativeImage> GetImage(); vint GetFrameIndex(); }; /*********************************************************************** Rich Content Document (model) ***********************************************************************/ class DocumentRun : public Object, public Description<DocumentRun> { public: static const vint NullHyperlinkId = -1; class IVisitor : public Interface { public: virtual void Visit(DocumentTextRun* run)=0; virtual void Visit(DocumentHyperlinkTextRun* run)=0; virtual void Visit(DocumentImageRun* run)=0; }; vint hyperlinkId; DocumentRun():hyperlinkId(NullHyperlinkId){} virtual void Accept(IVisitor* visitor)=0; }; class DocumentTextRun : public DocumentRun, public Description<DocumentTextRun> { public: FontProperties style; Color color; WString text; DocumentTextRun(){} void Accept(IVisitor* visitor)override{visitor->Visit(this);} }; class DocumentHyperlinkTextRun : public DocumentTextRun, public Description<DocumentHyperlinkTextRun> { public: FontProperties normalStyle; Color normalColor; FontProperties activeStyle; Color activeColor; DocumentHyperlinkTextRun(){} void Accept(IVisitor* visitor)override{visitor->Visit(this);} }; class DocumentInlineObjectRun : public DocumentRun, public Description<DocumentInlineObjectRun> { public: Size size; vint baseline; DocumentInlineObjectRun():baseline(-1){} }; class DocumentImageRun : public DocumentInlineObjectRun, public Description<DocumentImageRun> { public: Ptr<INativeImage> image; vint frameIndex; WString source; DocumentImageRun():frameIndex(0){} void Accept(IVisitor* visitor)override{visitor->Visit(this);} }; //-------------------------------------------------------------------------- class DocumentLine : public Object, public Description<DocumentLine> { typedef collections::List<Ptr<DocumentRun>> RunList; public: RunList runs; }; class DocumentParagraph : public Object, public Description<DocumentParagraph> { typedef collections::List<Ptr<DocumentLine>> LineList; public: LineList lines; Alignment alignment; DocumentParagraph():alignment(Alignment::Left){} }; class DocumentResolver : public Object { private: Ptr<DocumentResolver> previousResolver; protected: virtual Ptr<INativeImage> ResolveImageInternal(const WString& protocol, const WString& path)=0; public: DocumentResolver(Ptr<DocumentResolver> _previousResolver); ~DocumentResolver(); Ptr<INativeImage> ResolveImage(const WString& protocol, const WString& path); }; //-------------------------------------------------------------------------- class DocumentStyle : public Object { public: WString parentStyleName; Nullable<WString> face; Nullable<vint> size; Nullable<Color> color; Nullable<bool> bold; Nullable<bool> italic; Nullable<bool> underline; Nullable<bool> strikeline; Nullable<bool> antialias; Nullable<bool> verticalAntialias; }; class DocumentModel : public Object, public Description<DocumentModel> { public: struct HyperlinkInfo { WString reference; vint paragraphIndex; HyperlinkInfo() :paragraphIndex(-1) { } }; private: typedef collections::List<Ptr<DocumentParagraph>> ParagraphList; typedef collections::Dictionary<WString, Ptr<DocumentStyle>> StyleMap; typedef collections::Dictionary<WString, Ptr<parsing::xml::XmlElement>> TemplateMap; typedef collections::Pair<FontProperties, Color> RawStylePair; typedef collections::Dictionary<vint, HyperlinkInfo> HyperlinkMap; public: ParagraphList paragraphs; StyleMap styles; TemplateMap templates; HyperlinkMap hyperlinkInfos; DocumentModel(); RawStylePair GetStyle(const WString& styleName, const RawStylePair& context); vint ActivateHyperlink(vint hyperlinkId, bool active); static Ptr<DocumentModel> LoadFromXml(Ptr<parsing::xml::XmlDocument> xml, Ptr<DocumentResolver> resolver); static Ptr<DocumentModel> LoadFromXml(Ptr<parsing::xml::XmlDocument> xml, const WString& workingDirectory); Ptr<parsing::xml::XmlDocument> SaveToXml(); }; /*********************************************************************** Rich Content Document (resolver) ***********************************************************************/ class DocumentFileProtocolResolver : public DocumentResolver { protected: WString workingDirectory; Ptr<INativeImage> ResolveImageInternal(const WString& protocol, const WString& path)override; public: DocumentFileProtocolResolver(const WString& _workingDirectory, Ptr<DocumentResolver> previousResolver=0); }; class DocumentResProtocolResolver : public DocumentResolver { protected: Ptr<GuiResource> resource; Ptr<INativeImage> ResolveImageInternal(const WString& protocol, const WString& path)override; public: DocumentResProtocolResolver(Ptr<GuiResource> _resource, Ptr<DocumentResolver> previousResolver=0); }; /*********************************************************************** Resource Structure ***********************************************************************/ class GuiResourceNodeBase : public Object { friend class GuiResourceFolder; protected: GuiResourceFolder* parent; WString name; public: GuiResourceNodeBase(); ~GuiResourceNodeBase(); GuiResourceFolder* GetParent(); const WString& GetName(); }; class GuiResourceItem : public GuiResourceNodeBase { friend class GuiResourceFolder; protected: Ptr<Object> content; public: GuiResourceItem(); ~GuiResourceItem(); Ptr<Object> GetContent(); void SetContent(Ptr<Object> value); Ptr<GuiImageData> AsImage(); Ptr<parsing::xml::XmlDocument> AsXml(); Ptr<ObjectBox<WString>> AsString(); Ptr<DocumentModel> AsDocument(); }; class GuiResourceFolder : public GuiResourceNodeBase { protected: typedef collections::Dictionary<WString, Ptr<GuiResourceItem>> ItemMap; typedef collections::Dictionary<WString, Ptr<GuiResourceFolder>> FolderMap; typedef collections::List<Ptr<GuiResourceItem>> ItemList; typedef collections::List<Ptr<GuiResourceFolder>> FolderList; struct DelayLoading { collections::Dictionary<Ptr<GuiResourceItem>, WString> documentModelFolders; }; ItemMap items; FolderMap folders; void LoadResourceFolderXml(DelayLoading& delayLoading, const WString& containingFolder, Ptr<parsing::xml::XmlElement> folderXml, Ptr<parsing::tabling::ParsingTable> xmlParsingTable); public: GuiResourceFolder(); ~GuiResourceFolder(); const ItemList& GetItems(); Ptr<GuiResourceItem> GetItem(const WString& name); bool AddItem(const WString& name, Ptr<GuiResourceItem> item); Ptr<GuiResourceItem> RemoveItem(const WString& name); void ClearItems(); const FolderList& GetFolders(); Ptr<GuiResourceFolder> GetFolder(const WString& name); bool AddFolder(const WString& name, Ptr<GuiResourceFolder> folder); Ptr<GuiResourceFolder> RemoveFolder(const WString& name); void ClearFolders(); Ptr<Object> GetValueByPath(const WString& path); }; /*********************************************************************** Resource Loader ***********************************************************************/ class GuiResource : public GuiResourceFolder, public Description<GuiResource> { public: GuiResource(); ~GuiResource(); static Ptr<GuiResource> LoadFromXml(const WString& filePath); Ptr<DocumentModel> GetDocumentByPath(const WString& path); Ptr<GuiImageData> GetImageByPath(const WString& path); Ptr<parsing::xml::XmlDocument> GetXmlByPath(const WString& path); WString GetStringByPath(const WString& path); }; /*********************************************************************** Resource Loader ***********************************************************************/ extern WString GetFolderPath(const WString& filePath); extern WString GetFileName(const WString& filePath); extern bool LoadTextFile(const WString& filePath, WString& text); extern bool LoadTextFromStream(stream::IStream& stream, WString& text); } } #endif /*********************************************************************** GRAPHICSELEMENT\GUIGRAPHICSELEMENT.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Element System and Infrastructure Interfaces Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSELEMENT #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSELEMENT namespace vl { namespace presentation { namespace elements { /*********************************************************************** Elements ***********************************************************************/ enum class ElementShape { Rectangle, Ellipse, }; class GuiSolidBorderElement : public Object, public IGuiGraphicsElement, public Description<GuiSolidBorderElement> { DEFINE_GUI_GRAPHICS_ELEMENT(GuiSolidBorderElement, L"SolidBorder") protected: Color color; ElementShape shape; GuiSolidBorderElement(); public: ~GuiSolidBorderElement(); Color GetColor(); void SetColor(Color value); ElementShape GetShape(); void SetShape(ElementShape value); }; class GuiRoundBorderElement : public Object, public IGuiGraphicsElement, public Description<GuiRoundBorderElement> { DEFINE_GUI_GRAPHICS_ELEMENT(GuiRoundBorderElement, L"RoundBorder") protected: Color color; vint radius; GuiRoundBorderElement(); public: ~GuiRoundBorderElement(); Color GetColor(); void SetColor(Color value); vint GetRadius(); void SetRadius(vint value); }; class Gui3DBorderElement : public Object, public IGuiGraphicsElement, public Description<Gui3DBorderElement> { DEFINE_GUI_GRAPHICS_ELEMENT(Gui3DBorderElement, L"3DBorder") protected: Color color1; Color color2; Gui3DBorderElement(); public: ~Gui3DBorderElement(); Color GetColor1(); void SetColor1(Color value); Color GetColor2(); void SetColor2(Color value); void SetColors(Color value1, Color value2); }; class Gui3DSplitterElement : public Object, public IGuiGraphicsElement, public Description<Gui3DSplitterElement> { DEFINE_GUI_GRAPHICS_ELEMENT(Gui3DSplitterElement, L"3DSplitter") public: enum Direction { Horizontal, Vertical, }; protected: Color color1; Color color2; Direction direction; Gui3DSplitterElement(); public: ~Gui3DSplitterElement(); Color GetColor1(); void SetColor1(Color value); Color GetColor2(); void SetColor2(Color value); void SetColors(Color value1, Color value2); Direction GetDirection(); void SetDirection(Direction value); }; class GuiSolidBackgroundElement : public Object, public IGuiGraphicsElement, public Description<GuiSolidBackgroundElement> { DEFINE_GUI_GRAPHICS_ELEMENT(GuiSolidBackgroundElement, L"SolidBackground") protected: Color color; ElementShape shape; GuiSolidBackgroundElement(); public: ~GuiSolidBackgroundElement(); Color GetColor(); void SetColor(Color value); ElementShape GetShape(); void SetShape(ElementShape value); }; class GuiGradientBackgroundElement : public Object, public IGuiGraphicsElement, public Description<GuiGradientBackgroundElement> { DEFINE_GUI_GRAPHICS_ELEMENT(GuiGradientBackgroundElement, L"GradientBackground") public: enum Direction { Horizontal, Vertical, Slash, Backslash, }; protected: Color color1, color2; Direction direction; ElementShape shape; GuiGradientBackgroundElement(); public: ~GuiGradientBackgroundElement(); Color GetColor1(); void SetColor1(Color value); Color GetColor2(); void SetColor2(Color value); void SetColors(Color value1, Color value2); Direction GetDirection(); void SetDirection(Direction value); ElementShape GetShape(); void SetShape(ElementShape value); }; class GuiSolidLabelElement : public Object, public IGuiGraphicsElement, public Description<GuiSolidLabelElement> { DEFINE_GUI_GRAPHICS_ELEMENT(GuiSolidLabelElement, L"SolidLabel"); protected: Color color; FontProperties fontProperties; WString text; Alignment hAlignment; Alignment vAlignment; bool wrapLine; bool ellipse; bool multiline; bool wrapLineHeightCalculation; GuiSolidLabelElement(); public: ~GuiSolidLabelElement(); Color GetColor(); void SetColor(Color value); const FontProperties& GetFont(); void SetFont(const FontProperties& value); const WString& GetText(); void SetText(const WString& value); Alignment GetHorizontalAlignment(); Alignment GetVerticalAlignment(); void SetHorizontalAlignment(Alignment value); void SetVerticalAlignment(Alignment value); void SetAlignments(Alignment horizontal, Alignment vertical); bool GetWrapLine(); void SetWrapLine(bool value); bool GetEllipse(); void SetEllipse(bool value); bool GetMultiline(); void SetMultiline(bool value); bool GetWrapLineHeightCalculation(); void SetWrapLineHeightCalculation(bool value); }; class GuiImageFrameElement : public Object, public IGuiGraphicsElement, public Description<GuiImageFrameElement> { DEFINE_GUI_GRAPHICS_ELEMENT(GuiImageFrameElement, L"ImageFrame"); protected: Ptr<INativeImage> image; vint frameIndex; Alignment hAlignment; Alignment vAlignment; bool stretch; bool enabled; GuiImageFrameElement(); public: ~GuiImageFrameElement(); Ptr<INativeImage> GetImage(); vint GetFrameIndex(); void SetImage(Ptr<INativeImage> value); void SetFrameIndex(vint value); void SetImage(Ptr<INativeImage> _image, vint _frameIndex); Alignment GetHorizontalAlignment(); Alignment GetVerticalAlignment(); void SetHorizontalAlignment(Alignment value); void SetVerticalAlignment(Alignment value); void SetAlignments(Alignment horizontal, Alignment vertical); bool GetStretch(); void SetStretch(bool value); bool GetEnabled(); void SetEnabled(bool value); }; class GuiPolygonElement : public Object, public IGuiGraphicsElement, public Description<GuiPolygonElement> { DEFINE_GUI_GRAPHICS_ELEMENT(GuiPolygonElement, L"Polygon"); typedef collections::Array<Point> PointArray; protected: Size size; PointArray points; Color borderColor; Color backgroundColor; GuiPolygonElement(); public: ~GuiPolygonElement(); Size GetSize(); void SetSize(Size value); const Point& GetPoint(vint index); vint GetPointCount(); void SetPoints(const Point* p, vint count); const PointArray& GetPointsArray(); void SetPointsArray(const PointArray& value); Color GetBorderColor(); void SetBorderColor(Color value); Color GetBackgroundColor(); void SetBackgroundColor(Color value); }; } } } #endif /*********************************************************************** GRAPHICSELEMENT\GUIGRAPHICSTEXTELEMENT.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Element System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSTEXTELEMENT #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSTEXTELEMENT namespace vl { namespace presentation { namespace elements { /*********************************************************************** Colorized Plain Text (model) ***********************************************************************/ namespace text { struct CharAtt { unsigned __int32 rightOffset; unsigned __int32 colorIndex; }; struct TextLine { static const vint BlockSize=32; static const vint MaxWidth=0xFFFF; wchar_t* text; CharAtt* att; vint availableOffsetCount; vint bufferLength; vint dataLength; vint lexerFinalState; vint contextFinalState; TextLine(); ~TextLine(); static vint CalculateBufferLength(vint dataLength); bool operator==(const TextLine& value)const{return false;} bool operator!=(const TextLine& value)const{return true;} void Initialize(); void Finalize(); bool IsReady(); bool Modify(vint start, vint count, const wchar_t* input, vint inputCount); TextLine Split(vint index); void AppendAndFinalize(TextLine& line); }; class CharMeasurer : public virtual IDescriptable { protected: IGuiGraphicsRenderTarget* oldRenderTarget; vint rowHeight; vint widths[65536]; virtual vint MeasureWidthInternal(wchar_t character, IGuiGraphicsRenderTarget* renderTarget)=0; virtual vint GetRowHeightInternal(IGuiGraphicsRenderTarget* renderTarget)=0; public: CharMeasurer(vint _rowHeight); ~CharMeasurer(); void SetRenderTarget(IGuiGraphicsRenderTarget* value); vint MeasureWidth(wchar_t character); vint GetRowHeight(); }; class TextLines : public Object, public Description<TextLines> { typedef collections::List<TextLine> TextLineList; protected: TextLineList lines; CharMeasurer* charMeasurer; IGuiGraphicsRenderTarget* renderTarget; vint tabWidth; vint tabSpaceCount; wchar_t passwordChar; public: TextLines(); ~TextLines(); vint GetCount(); TextLine& GetLine(vint row); CharMeasurer* GetCharMeasurer(); void SetCharMeasurer(CharMeasurer* value); IGuiGraphicsRenderTarget* GetRenderTarget(); void SetRenderTarget(IGuiGraphicsRenderTarget* value); WString GetText(TextPos start, TextPos end); WString GetText(); void SetText(const WString& value); bool RemoveLines(vint start, vint count); bool IsAvailable(TextPos pos); TextPos Normalize(TextPos pos); TextPos Modify(TextPos start, TextPos end, const wchar_t** inputs, vint* inputCounts, vint rows); TextPos Modify(TextPos start, TextPos end, const wchar_t* input, vint inputCount); TextPos Modify(TextPos start, TextPos end, const wchar_t* input); TextPos Modify(TextPos start, TextPos end, const WString& input); void Clear(); void ClearMeasurement(); vint GetTabSpaceCount(); void SetTabSpaceCount(vint value); void MeasureRow(vint row); vint GetRowWidth(vint row); vint GetRowHeight(); vint GetMaxWidth(); vint GetMaxHeight(); TextPos GetTextPosFromPoint(Point point); Point GetPointFromTextPos(TextPos pos); Rect GetRectFromTextPos(TextPos pos); wchar_t GetPasswordChar(); void SetPasswordChar(wchar_t value); }; struct ColorItem { Color text; Color background; }; struct ColorEntry { ColorItem normal; ColorItem selectedFocused; ColorItem selectedUnfocused; bool operator==(const ColorEntry& value){return false;} bool operator!=(const ColorEntry& value){return true;} }; } /*********************************************************************** Colorized Plain Text (element) ***********************************************************************/ class GuiColorizedTextElement : public Object, public IGuiGraphicsElement, public Description<GuiColorizedTextElement> { DEFINE_GUI_GRAPHICS_ELEMENT(GuiColorizedTextElement, L"ColorizedText"); typedef collections::Array<text::ColorEntry> ColorArray; public: class ICallback : public virtual IDescriptable, public Description<ICallback> { public: virtual void ColorChanged()=0; virtual void FontChanged()=0; }; protected: ICallback* callback; ColorArray colors; FontProperties font; Point viewPosition; bool isVisuallyEnabled; bool isFocused; TextPos caretBegin; TextPos caretEnd; bool caretVisible; Color caretColor; text::TextLines lines; GuiColorizedTextElement(); public: ~GuiColorizedTextElement(); text::TextLines& GetLines(); ICallback* GetCallback(); void SetCallback(ICallback* value); const ColorArray& GetColors(); void SetColors(const ColorArray& value); const FontProperties& GetFont(); void SetFont(const FontProperties& value); wchar_t GetPasswordChar(); void SetPasswordChar(wchar_t value); Point GetViewPosition(); void SetViewPosition(Point value); bool GetVisuallyEnabled(); void SetVisuallyEnabled(bool value); bool GetFocused(); void SetFocused(bool value); TextPos GetCaretBegin(); void SetCaretBegin(TextPos value); TextPos GetCaretEnd(); void SetCaretEnd(TextPos value); bool GetCaretVisible(); void SetCaretVisible(bool value); Color GetCaretColor(); void SetCaretColor(Color value); }; /*********************************************************************** Rich Content Document (element) ***********************************************************************/ class GuiDocumentElement : public Object, public IGuiGraphicsElement, public Description<GuiColorizedTextElement> { DEFINE_GUI_GRAPHICS_ELEMENT(GuiDocumentElement, L"RichDocument"); public: class GuiDocumentElementRenderer : public Object, public IGuiGraphicsRenderer { DEFINE_GUI_GRAPHICS_RENDERER(GuiDocumentElement, GuiDocumentElementRenderer, IGuiGraphicsRenderTarget) protected: struct ParagraphCache { WString fullText; Ptr<IGuiGraphicsParagraph> graphicsParagraph; }; typedef collections::Array<Ptr<ParagraphCache>> ParagraphCacheArray; protected: vint paragraphDistance; vint lastMaxWidth; vint cachedTotalHeight; IGuiGraphicsLayoutProvider* layoutProvider; ParagraphCacheArray paragraphCaches; collections::Array<vint> paragraphHeights; void InitializeInternal(); void FinalizeInternal(); void RenderTargetChangedInternal(IGuiGraphicsRenderTarget* oldRenderTarget, IGuiGraphicsRenderTarget* newRenderTarget); public: GuiDocumentElementRenderer(); void Render(Rect bounds)override; void OnElementStateChanged()override; void NotifyParagraphUpdated(vint index); vint GetHyperlinkIdFromPoint(Point point); }; protected: Ptr<DocumentModel> document; GuiDocumentElement(); public: ~GuiDocumentElement(); Ptr<DocumentModel> GetDocument(); void SetDocument(Ptr<DocumentModel> value); void NotifyParagraphUpdated(vint index); vint GetHyperlinkIdFromPoint(Point point); void ActivateHyperlink(vint hyperlinkId, bool active); }; } } } #endif /*********************************************************************** GRAPHICSCOMPOSITION\GUIGRAPHICSEVENTRECEIVER.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Event Model Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSEVENTRECEIVER #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSEVENTRECEIVER namespace vl { namespace presentation { namespace controls { namespace tree { class INodeProvider; } } } } namespace vl { namespace presentation { using namespace reflection; namespace compositions { class GuiGraphicsComposition; /*********************************************************************** Event ***********************************************************************/ template<typename T> class GuiGraphicsEvent : public Object, public Description<GuiGraphicsEvent<T>> { public: typedef void(RawFunctionType)(GuiGraphicsComposition*, T&); typedef Func<RawFunctionType> FunctionType; typedef T ArgumentType; class IHandler : public virtual IDescriptable, public Description<IHandler> { public: virtual void Execute(GuiGraphicsComposition* sender, T& argument)=0; }; class FunctionHandler : public Object, public IHandler { protected: FunctionType handler; public: FunctionHandler(const FunctionType& _handler) :handler(_handler) { } void Execute(GuiGraphicsComposition* sender, T& argument)override { handler(sender, argument); } }; protected: struct HandlerNode { Ptr<IHandler> handler; Ptr<HandlerNode> next; }; GuiGraphicsComposition* sender; Ptr<HandlerNode> handlers; public: GuiGraphicsEvent(GuiGraphicsComposition* _sender=0) :sender(_sender) { } ~GuiGraphicsEvent() { } GuiGraphicsComposition* GetAssociatedComposition() { return sender; } void SetAssociatedComposition(GuiGraphicsComposition* _sender) { sender=_sender; } bool Attach(Ptr<IHandler> handler) { Ptr<HandlerNode>* currentHandler=&handlers; while(*currentHandler) { if((*currentHandler)->handler==handler) { return false; } else { currentHandler=&(*currentHandler)->next; } } (*currentHandler)=new HandlerNode; (*currentHandler)->handler=handler; return true; } template<typename TClass, typename TMethod> Ptr<IHandler> AttachMethod(TClass* receiver, TMethod TClass::* method) { Ptr<IHandler> handler=new FunctionHandler(FunctionType(receiver, method)); Attach(handler); return handler; } Ptr<IHandler> AttachFunction(RawFunctionType* function) { Ptr<IHandler> handler=new FunctionHandler(FunctionType(function)); Attach(handler); return handler; } Ptr<IHandler> AttachFunction(const FunctionType& function) { Ptr<IHandler> handler=new FunctionHandler(function); Attach(handler); return handler; } template<typename T> Ptr<IHandler> AttachLambda(const T& lambda) { Ptr<IHandler> handler=new FunctionHandler(FunctionType(lambda)); Attach(handler); return handler; } bool Detach(Ptr<IHandler> handler) { Ptr<HandlerNode>* currentHandler=&handlers; while(*currentHandler) { if((*currentHandler)->handler==handler) { Ptr<HandlerNode> next=(*currentHandler)->next; (*currentHandler)=next; return true; } else { currentHandler=&(*currentHandler)->next; } } return false; } void ExecuteWithNewSender(T& argument, GuiGraphicsComposition* newSender) { Ptr<HandlerNode>* currentHandler=&handlers; while(*currentHandler) { (*currentHandler)->handler->Execute(newSender?newSender:sender, argument); currentHandler=&(*currentHandler)->next; } } void Execute(T& argument) { ExecuteWithNewSender(argument, 0); } }; /*********************************************************************** Predefined Events ***********************************************************************/ struct GuiEventArgs : public Object, public Description<GuiEventArgs> { GuiGraphicsComposition* compositionSource; GuiGraphicsComposition* eventSource; bool handled; GuiEventArgs() :compositionSource(0) ,eventSource(0) ,handled(false) { } GuiEventArgs(GuiGraphicsComposition* composition) :compositionSource(composition) ,eventSource(composition) ,handled(false) { } }; struct GuiRequestEventArgs : public GuiEventArgs, public Description<GuiRequestEventArgs> { bool cancel; GuiRequestEventArgs() :cancel(false) { } GuiRequestEventArgs(GuiGraphicsComposition* composition) :GuiEventArgs(composition) ,cancel(false) { } }; struct GuiKeyEventArgs : public GuiEventArgs, public NativeWindowKeyInfo, public Description<GuiKeyEventArgs> { GuiKeyEventArgs() { } GuiKeyEventArgs(GuiGraphicsComposition* composition) :GuiEventArgs(composition) { } }; struct GuiCharEventArgs : public GuiEventArgs, public NativeWindowCharInfo, public Description<GuiCharEventArgs> { GuiCharEventArgs() { } GuiCharEventArgs(GuiGraphicsComposition* composition) :GuiEventArgs(composition) { } }; struct GuiMouseEventArgs : public GuiEventArgs, public NativeWindowMouseInfo, public Description<GuiMouseEventArgs> { GuiMouseEventArgs() { } GuiMouseEventArgs(GuiGraphicsComposition* composition) :GuiEventArgs(composition) { } }; typedef GuiGraphicsEvent<GuiEventArgs> GuiNotifyEvent; typedef GuiGraphicsEvent<GuiRequestEventArgs> GuiRequestEvent; typedef GuiGraphicsEvent<GuiKeyEventArgs> GuiKeyEvent; typedef GuiGraphicsEvent<GuiCharEventArgs> GuiCharEvent; typedef GuiGraphicsEvent<GuiMouseEventArgs> GuiMouseEvent; /*********************************************************************** Predefined Item Events ***********************************************************************/ struct GuiItemEventArgs : public GuiEventArgs, public Description<GuiItemEventArgs> { vint itemIndex; GuiItemEventArgs() :itemIndex(-1) { } GuiItemEventArgs(GuiGraphicsComposition* composition) :GuiEventArgs(composition) ,itemIndex(-1) { } }; struct GuiItemMouseEventArgs : public GuiMouseEventArgs, public Description<GuiItemMouseEventArgs> { vint itemIndex; GuiItemMouseEventArgs() :itemIndex(-1) { } GuiItemMouseEventArgs(GuiGraphicsComposition* composition) :GuiMouseEventArgs(composition) ,itemIndex(-1) { } }; typedef GuiGraphicsEvent<GuiItemEventArgs> GuiItemNotifyEvent; typedef GuiGraphicsEvent<GuiItemMouseEventArgs> GuiItemMouseEvent; /*********************************************************************** Predefined Node Events ***********************************************************************/ struct GuiNodeEventArgs : public GuiEventArgs, public Description<GuiNodeEventArgs> { controls::tree::INodeProvider* node; GuiNodeEventArgs() :node(0) { } GuiNodeEventArgs(GuiGraphicsComposition* composition) :GuiEventArgs(composition) ,node(0) { } }; struct GuiNodeMouseEventArgs : public GuiMouseEventArgs, public Description<GuiNodeMouseEventArgs> { controls::tree::INodeProvider* node; GuiNodeMouseEventArgs() :node(0) { } GuiNodeMouseEventArgs(GuiGraphicsComposition* composition) :GuiMouseEventArgs(composition) ,node(0) { } }; typedef GuiGraphicsEvent<GuiNodeEventArgs> GuiNodeNotifyEvent; typedef GuiGraphicsEvent<GuiNodeMouseEventArgs> GuiNodeMouseEvent; /*********************************************************************** Event Receiver ***********************************************************************/ class GuiGraphicsEventReceiver : public Object { protected: GuiGraphicsComposition* sender; public: GuiGraphicsEventReceiver(GuiGraphicsComposition* _sender); ~GuiGraphicsEventReceiver(); GuiGraphicsComposition* GetAssociatedComposition(); GuiMouseEvent leftButtonDown; GuiMouseEvent leftButtonUp; GuiMouseEvent leftButtonDoubleClick; GuiMouseEvent middleButtonDown; GuiMouseEvent middleButtonUp; GuiMouseEvent middleButtonDoubleClick; GuiMouseEvent rightButtonDown; GuiMouseEvent rightButtonUp; GuiMouseEvent rightButtonDoubleClick; GuiMouseEvent horizontalWheel; GuiMouseEvent verticalWheel; GuiMouseEvent mouseMove; GuiNotifyEvent mouseEnter; GuiNotifyEvent mouseLeave; GuiKeyEvent previewKey; GuiKeyEvent keyDown; GuiKeyEvent keyUp; GuiKeyEvent systemKeyDown; GuiKeyEvent systemKeyUp; GuiCharEvent previewCharInput; GuiCharEvent charInput; GuiNotifyEvent gotFocus; GuiNotifyEvent lostFocus; GuiNotifyEvent caretNotify; GuiNotifyEvent clipboardNotify; }; } } } #endif /*********************************************************************** GRAPHICSCOMPOSITION\GUIGRAPHICSCOMPOSITIONBASE.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSCOMPOSITIONBASE #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSCOMPOSITIONBASE namespace vl { namespace presentation { namespace controls { class GuiControl; class GuiControlHost; } namespace compositions { class GuiGraphicsHost; /*********************************************************************** Basic Construction ***********************************************************************/ class GuiGraphicsComposition : public Object, public Description<GuiGraphicsComposition> { typedef collections::List<GuiGraphicsComposition*> CompositionList; friend class controls::GuiControl; friend class GuiGraphicsHost; public: enum MinSizeLimitation { NoLimit, LimitToElement, LimitToElementAndChildren, }; protected: CompositionList children; GuiGraphicsComposition* parent; Ptr<elements::IGuiGraphicsElement> ownedElement; bool visible; elements::IGuiGraphicsRenderTarget* renderTarget; MinSizeLimitation minSizeLimitation; Ptr<compositions::GuiGraphicsEventReceiver> eventReceiver; controls::GuiControl* associatedControl; GuiGraphicsHost* associatedHost; INativeCursor* associatedCursor; INativeWindowListener::HitTestResult associatedHitTestResult; Margin margin; Margin internalMargin; Size preferredMinSize; virtual void OnControlParentChanged(controls::GuiControl* control); virtual void OnChildInserted(GuiGraphicsComposition* child); virtual void OnChildRemoved(GuiGraphicsComposition* child); virtual void OnParentChanged(GuiGraphicsComposition* oldParent, GuiGraphicsComposition* newParent); virtual void OnRenderTargetChanged(); virtual void SetAssociatedControl(controls::GuiControl* control); virtual void SetAssociatedHost(GuiGraphicsHost* host); static void SharedPtrDestructorProc(DescriptableObject* obj); public: GuiGraphicsComposition(); ~GuiGraphicsComposition(); GuiGraphicsComposition* GetParent(); const CompositionList& Children(); bool AddChild(GuiGraphicsComposition* child); bool InsertChild(vint index, GuiGraphicsComposition* child); bool RemoveChild(GuiGraphicsComposition* child); bool MoveChild(GuiGraphicsComposition* child, vint newIndex); Ptr<elements::IGuiGraphicsElement> GetOwnedElement(); void SetOwnedElement(Ptr<elements::IGuiGraphicsElement> element); bool GetVisible(); void SetVisible(bool value); MinSizeLimitation GetMinSizeLimitation(); void SetMinSizeLimitation(MinSizeLimitation value); elements::IGuiGraphicsRenderTarget* GetRenderTarget(); void SetRenderTarget(elements::IGuiGraphicsRenderTarget* value); void Render(Size offset); compositions::GuiGraphicsEventReceiver* GetEventReceiver(); bool HasEventReceiver(); GuiGraphicsComposition* FindComposition(Point location); Rect GetGlobalBounds(); controls::GuiControl* GetAssociatedControl(); GuiGraphicsHost* GetAssociatedHost(); INativeCursor* GetAssociatedCursor(); void SetAssociatedCursor(INativeCursor* cursor); INativeWindowListener::HitTestResult GetAssociatedHitTestResult(); void SetAssociatedHitTestResult(INativeWindowListener::HitTestResult value); controls::GuiControl* GetRelatedControl(); GuiGraphicsHost* GetRelatedGraphicsHost(); controls::GuiControlHost* GetRelatedControlHost(); INativeCursor* GetRelatedCursor(); virtual Margin GetMargin(); virtual void SetMargin(Margin value); virtual Margin GetInternalMargin(); virtual void SetInternalMargin(Margin value); virtual Size GetPreferredMinSize(); virtual void SetPreferredMinSize(Size value); virtual Rect GetClientArea(); virtual void ForceCalculateSizeImmediately(); virtual bool IsSizeAffectParent()=0; virtual Size GetMinPreferredClientSize()=0; virtual Rect GetPreferredBounds()=0; virtual Rect GetBounds()=0; }; class GuiGraphicsSite : public GuiGraphicsComposition, public Description<GuiGraphicsSite> { protected: virtual Rect GetBoundsInternal(Rect expectedBounds); public: GuiGraphicsSite(); ~GuiGraphicsSite(); bool IsSizeAffectParent()override; Size GetMinPreferredClientSize()override; Rect GetPreferredBounds()override; }; /*********************************************************************** Helper Functions ***********************************************************************/ extern void SafeDeleteControl(controls::GuiControl* value); extern void SafeDeleteComposition(GuiGraphicsComposition* value); } } } #endif /*********************************************************************** GRAPHICSCOMPOSITION\GUIGRAPHICSBASICCOMPOSITION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSBASICCOMPOSITION #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSBASICCOMPOSITION namespace vl { namespace presentation { namespace compositions { /*********************************************************************** Basic Compositions ***********************************************************************/ class GuiWindowComposition : public GuiGraphicsSite, public Description<GuiWindowComposition> { protected: INativeWindow* attachedWindow; public: GuiWindowComposition(); ~GuiWindowComposition(); INativeWindow* GetAttachedWindow(); void SetAttachedWindow(INativeWindow* window); Rect GetBounds()override; void SetMargin(Margin value)override; }; class GuiBoundsComposition : public GuiGraphicsSite, public Description<GuiBoundsComposition> { protected: Rect compositionBounds; Rect previousBounds; Margin alignmentToParent; public: GuiBoundsComposition(); ~GuiBoundsComposition(); compositions::GuiNotifyEvent BoundsChanged; Rect GetPreferredBounds()override; Rect GetBounds()override; void SetBounds(Rect value); void ClearAlignmentToParent(); Margin GetAlignmentToParent(); void SetAlignmentToParent(Margin value); bool IsAlignedToParent(); }; } } } #endif /*********************************************************************** GRAPHICSCOMPOSITION\GUIGRAPHICSTABLECOMPOSITION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSTABLECOMPOSITION #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSTABLECOMPOSITION namespace vl { namespace presentation { namespace compositions { /*********************************************************************** Table Compositions ***********************************************************************/ class GuiTableComposition; class GuiCellComposition; struct GuiCellOption { enum ComposeType { Absolute, Percentage, MinSize, }; ComposeType composeType; vint absolute; double percentage; GuiCellOption() :composeType(Absolute) ,absolute(20) ,percentage(0) { } bool operator==(const GuiCellOption& value){return false;} bool operator!=(const GuiCellOption& value){return true;} static GuiCellOption AbsoluteOption(vint value) { GuiCellOption option; option.composeType=Absolute; option.absolute=value; return option; } static GuiCellOption PercentageOption(double value) { GuiCellOption option; option.composeType=Percentage; option.percentage=value; return option; } static GuiCellOption MinSizeOption() { GuiCellOption option; option.composeType=MinSize; return option; } }; class GuiTableComposition : public GuiBoundsComposition, public Description<GuiTableComposition> { friend class GuiCellComposition; protected: vint rows; vint columns; vint cellPadding; vint rowExtending; vint columnExtending; collections::Array<GuiCellOption> rowOptions; collections::Array<GuiCellOption> columnOptions; collections::Array<GuiCellComposition*> cellCompositions; collections::Array<Rect> cellBounds; Rect previousBounds; Size previousContentMinSize; Size tableContentMinSize; vint GetSiteIndex(vint _rows, vint _columns, vint _row, vint _column); void SetSitedCell(vint _row, vint _column, GuiCellComposition* cell); void UpdateCellBoundsInternal( collections::Array<vint>& dimSizes, vint& dimSize, vint& dimSizeWithPercentage, collections::Array<GuiCellOption>& dimOptions, vint GuiTableComposition::* dim1, vint GuiTableComposition::* dim2, vint (*getSize)(Size), vint (*getLocation)(GuiCellComposition*), vint (*getSpan)(GuiCellComposition*), vint (*getRow)(vint, vint), vint (*getCol)(vint, vint), vint maxPass ); void UpdateCellBoundsPercentages( collections::Array<vint>& dimSizes, vint dimSize, vint maxDimSize, collections::Array<GuiCellOption>& dimOptions ); vint UpdateCellBoundsOffsets( collections::Array<vint>& offsets, collections::Array<vint>& sizes, vint start, vint max ); void UpdateCellBoundsInternal(); void UpdateTableContentMinSize(); void OnRenderTargetChanged()override; public: GuiTableComposition(); ~GuiTableComposition(); vint GetRows(); vint GetColumns(); bool SetRowsAndColumns(vint _rows, vint _columns); GuiCellComposition* GetSitedCell(vint _row, vint _column); GuiCellOption GetRowOption(vint _row); void SetRowOption(vint _row, GuiCellOption option); GuiCellOption GetColumnOption(vint _column); void SetColumnOption(vint _column, GuiCellOption option); vint GetCellPadding(); void SetCellPadding(vint value); Rect GetCellArea(); void UpdateCellBounds(); void ForceCalculateSizeImmediately()override; Size GetMinPreferredClientSize()override; Rect GetBounds()override; }; class GuiCellComposition : public GuiGraphicsSite, public Description<GuiCellComposition> { friend class GuiTableComposition; protected: vint row; vint rowSpan; vint column; vint columnSpan; GuiTableComposition* tableParent; Size lastPreferredSize; void ClearSitedCells(GuiTableComposition* table); void SetSitedCells(GuiTableComposition* table); void ResetSiteInternal(); bool SetSiteInternal(vint _row, vint _column, vint _rowSpan, vint _columnSpan); void OnParentChanged(GuiGraphicsComposition* oldParent, GuiGraphicsComposition* newParent)override; void OnTableRowsAndColumnsChanged(); public: GuiCellComposition(); ~GuiCellComposition(); GuiTableComposition* GetTableParent(); vint GetRow(); vint GetRowSpan(); vint GetColumn(); vint GetColumnSpan(); bool SetSite(vint _row, vint _column, vint _rowSpan, vint _columnSpan); Rect GetBounds()override; }; } } } #endif /*********************************************************************** GRAPHICSCOMPOSITION\GUIGRAPHICSSTACKCOMPOSITION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSSTACKCOMPOSITION #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSSTACKCOMPOSITION namespace vl { namespace presentation { namespace compositions { /*********************************************************************** Stack Compositions ***********************************************************************/ class GuiStackComposition; class GuiStackItemComposition; class GuiStackComposition : public GuiBoundsComposition, public Description<GuiStackComposition> { friend class GuiStackItemComposition; typedef collections::List<GuiStackItemComposition*> ItemCompositionList; public: enum Direction { Horizontal, Vertical, }; protected: Direction direction; ItemCompositionList stackItems; collections::Array<Rect> stackItemBounds; Size stackItemTotalSize; vint padding; Rect previousBounds; Margin extraMargin; GuiStackItemComposition* ensuringVisibleStackItem; void UpdateStackItemBounds(); void FixStackItemSizes(); void OnBoundsChanged(GuiGraphicsComposition* sender, GuiEventArgs& arguments); void OnChildInserted(GuiGraphicsComposition* child)override; void OnChildRemoved(GuiGraphicsComposition* child)override; public: GuiStackComposition(); ~GuiStackComposition(); const ItemCompositionList& GetStackItems(); bool InsertStackItem(vint index, GuiStackItemComposition* item); Direction GetDirection(); void SetDirection(Direction value); vint GetPadding(); void SetPadding(vint value); Size GetMinPreferredClientSize()override; Rect GetBounds()override; Margin GetExtraMargin(); void SetExtraMargin(Margin value); bool IsStackItemClipped(); bool EnsureVisible(vint index); }; class GuiStackItemComposition : public GuiGraphicsSite, public Description<GuiStackItemComposition> { friend class GuiStackComposition; protected: GuiStackComposition* stackParent; Rect bounds; Margin extraMargin; void OnParentChanged(GuiGraphicsComposition* oldParent, GuiGraphicsComposition* newParent)override; Size GetMinSize(); public: GuiStackItemComposition(); ~GuiStackItemComposition(); bool IsSizeAffectParent()override; Rect GetBounds()override; void SetBounds(Rect value); Margin GetExtraMargin(); void SetExtraMargin(Margin value); }; } } } #endif /*********************************************************************** GRAPHICSCOMPOSITION\GUIGRAPHICSSPECIALIZEDCOMPOSITION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSSPECIALIZEDCOMPOSITION #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSSPECIALIZEDCOMPOSITION namespace vl { namespace presentation { namespace compositions { /*********************************************************************** Specialized Compositions ***********************************************************************/ class GuiSideAlignedComposition : public GuiGraphicsSite, public Description<GuiSideAlignedComposition> { public: enum Direction { Left, Top, Right, Bottom, }; protected: Direction direction; vint maxLength; double maxRatio; public: GuiSideAlignedComposition(); ~GuiSideAlignedComposition(); Direction GetDirection(); void SetDirection(Direction value); vint GetMaxLength(); void SetMaxLength(vint value); double GetMaxRatio(); void SetMaxRatio(double value); bool IsSizeAffectParent()override; Rect GetBounds()override; }; class GuiPartialViewComposition : public GuiGraphicsSite, public Description<GuiPartialViewComposition> { protected: double wRatio; double wPageSize; double hRatio; double hPageSize; public: GuiPartialViewComposition(); ~GuiPartialViewComposition(); double GetWidthRatio(); double GetWidthPageSize(); double GetHeightRatio(); double GetHeightPageSize(); void SetWidthRatio(double value); void SetWidthPageSize(double value); void SetHeightRatio(double value); void SetHeightPageSize(double value); bool IsSizeAffectParent()override; Rect GetBounds()override; }; } } } #endif /*********************************************************************** GRAPHICSCOMPOSITION\GUIGRAPHICSCOMPOSITION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSCOMPOSITION #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSCOMPOSITION namespace vl { namespace presentation { namespace compositions { class GuiSubComponentMeasurer : public Object, public Description<GuiSubComponentMeasurer> { public: class IMeasuringSource : public virtual IDescriptable, public Description<IMeasuringSource> { public: virtual void AttachMeasurer(GuiSubComponentMeasurer* value)=0; virtual void DetachMeasurer(GuiSubComponentMeasurer* value)=0; virtual GuiSubComponentMeasurer* GetAttachedMeasurer()=0; virtual WString GetMeasuringCategory()=0; virtual vint GetSubComponentCount()=0; virtual WString GetSubComponentName(vint index)=0; virtual GuiGraphicsComposition* GetSubComponentComposition(vint index)=0; virtual GuiGraphicsComposition* GetSubComponentComposition(const WString& name)=0; virtual GuiGraphicsComposition* GetMainComposition()=0; virtual void SubComponentPreferredMinSizeUpdated()=0; }; enum Direction { Horizontal, Vertical, }; class MeasuringSource : public Object, public IMeasuringSource, public Description<MeasuringSource> { typedef collections::Dictionary<WString, GuiGraphicsComposition*> SubComponentMap; protected: GuiSubComponentMeasurer* measurer; WString measuringCategory; GuiGraphicsComposition* mainComposition; SubComponentMap subComponents; public: MeasuringSource(const WString& _measuringCategory, GuiGraphicsComposition* _mainComposition); ~MeasuringSource(); bool AddSubComponent(const WString& name, GuiGraphicsComposition* composition); void AttachMeasurer(GuiSubComponentMeasurer* value)override; void DetachMeasurer(GuiSubComponentMeasurer* value)override; GuiSubComponentMeasurer* GetAttachedMeasurer()override; WString GetMeasuringCategory()override; vint GetSubComponentCount()override; WString GetSubComponentName(vint index)override; GuiGraphicsComposition* GetSubComponentComposition(vint index)override; GuiGraphicsComposition* GetSubComponentComposition(const WString& name)override; GuiGraphicsComposition* GetMainComposition()override; void SubComponentPreferredMinSizeUpdated()override; }; protected: typedef collections::List<IMeasuringSource*> MeasuringSourceList; MeasuringSourceList measuringSources; public: GuiSubComponentMeasurer(); ~GuiSubComponentMeasurer(); bool AttachMeasuringSource(IMeasuringSource* value); bool DetachMeasuringSource(IMeasuringSource* value); void MeasureAndUpdate(const WString& measuringCategory, Direction direction); }; } } } #endif /*********************************************************************** GRAPHICSELEMENT\GUIGRAPHICSHOST.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Graphics Composition Host Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSHOST #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSHOST namespace vl { namespace presentation { namespace compositions { /*********************************************************************** Animation ***********************************************************************/ class IGuiGraphicsAnimation : public virtual IDescriptable, public Description<IGuiGraphicsAnimation> { public: virtual vint GetTotalLength()=0; virtual vint GetCurrentPosition()=0; virtual void Play(vint currentPosition, vint totalLength)=0; virtual void Stop()=0; }; class GuiGraphicsAnimationManager : public Object, public Description<GuiGraphicsAnimationManager> { typedef collections::List<Ptr<IGuiGraphicsAnimation>> AnimationList; protected: AnimationList playingAnimations; public: GuiGraphicsAnimationManager(); ~GuiGraphicsAnimationManager(); void AddAnimation(Ptr<IGuiGraphicsAnimation> animation); bool HasAnimation(); void Play(); }; /*********************************************************************** Shortcut Key Manager ***********************************************************************/ class IGuiShortcutKeyManager; class IGuiShortcutKeyItem : public virtual IDescriptable, public Description<IGuiShortcutKeyItem> { public: GuiNotifyEvent Executed; virtual IGuiShortcutKeyManager* GetManager()=0; virtual WString GetName()=0; }; class IGuiShortcutKeyManager : public virtual IDescriptable, public Description<IGuiShortcutKeyManager> { public: virtual vint GetItemCount()=0; virtual IGuiShortcutKeyItem* GetItem(vint index)=0; virtual bool Execute(const NativeWindowKeyInfo& info)=0; }; /*********************************************************************** Host ***********************************************************************/ class GuiGraphicsHost : public Object, private INativeWindowListener, private INativeControllerListener, public Description<GuiGraphicsHost> { typedef collections::List<GuiGraphicsComposition*> CompositionList; public: static const unsigned __int64 CaretInterval=500; protected: INativeWindow* nativeWindow; IGuiShortcutKeyManager* shortcutKeyManager; GuiWindowComposition* windowComposition; GuiGraphicsComposition* focusedComposition; Size previousClientSize; Size minSize; Point caretPoint; unsigned __int64 lastCaretTime; GuiGraphicsAnimationManager animationManager; GuiGraphicsComposition* mouseCaptureComposition; CompositionList mouseEnterCompositions; void DisconnectCompositionInternal(GuiGraphicsComposition* composition); void MouseCapture(const NativeWindowMouseInfo& info); void MouseUncapture(const NativeWindowMouseInfo& info); void OnCharInput(const NativeWindowCharInfo& info, GuiGraphicsComposition* composition, GuiCharEvent GuiGraphicsEventReceiver::* eventReceiverEvent); void OnKeyInput(const NativeWindowKeyInfo& info, GuiGraphicsComposition* composition, GuiKeyEvent GuiGraphicsEventReceiver::* eventReceiverEvent); void RaiseMouseEvent(GuiMouseEventArgs& arguments, GuiGraphicsComposition* composition, GuiMouseEvent GuiGraphicsEventReceiver::* eventReceiverEvent); void OnMouseInput(const NativeWindowMouseInfo& info, GuiMouseEvent GuiGraphicsEventReceiver::* eventReceiverEvent); private: INativeWindowListener::HitTestResult HitTest(Point location)override; void Moving(Rect& bounds, bool fixSizeOnly)override; void Moved()override; void LeftButtonDown(const NativeWindowMouseInfo& info)override; void LeftButtonUp(const NativeWindowMouseInfo& info)override; void LeftButtonDoubleClick(const NativeWindowMouseInfo& info)override; void RightButtonDown(const NativeWindowMouseInfo& info)override; void RightButtonUp(const NativeWindowMouseInfo& info)override; void RightButtonDoubleClick(const NativeWindowMouseInfo& info)override; void MiddleButtonDown(const NativeWindowMouseInfo& info)override; void MiddleButtonUp(const NativeWindowMouseInfo& info)override; void MiddleButtonDoubleClick(const NativeWindowMouseInfo& info)override; void HorizontalWheel(const NativeWindowMouseInfo& info)override; void VerticalWheel(const NativeWindowMouseInfo& info)override; void MouseMoving(const NativeWindowMouseInfo& info)override; void MouseEntered()override; void MouseLeaved()override; void KeyDown(const NativeWindowKeyInfo& info)override; void KeyUp(const NativeWindowKeyInfo& info)override; void SysKeyDown(const NativeWindowKeyInfo& info)override; void SysKeyUp(const NativeWindowKeyInfo& info)override; void Char(const NativeWindowCharInfo& info)override; void GlobalTimer()override; public: GuiGraphicsHost(); ~GuiGraphicsHost(); INativeWindow* GetNativeWindow(); void SetNativeWindow(INativeWindow* _nativeWindow); GuiGraphicsComposition* GetMainComposition(); void Render(); IGuiShortcutKeyManager* GetShortcutKeyManager(); void SetShortcutKeyManager(IGuiShortcutKeyManager* value); bool SetFocus(GuiGraphicsComposition* composition); GuiGraphicsComposition* GetFocusedComposition(); Point GetCaretPoint(); void SetCaretPoint(Point value, GuiGraphicsComposition* referenceComposition=0); GuiGraphicsAnimationManager* GetAnimationManager(); void DisconnectComposition(GuiGraphicsComposition* composition); }; /*********************************************************************** Animation Helpers ***********************************************************************/ class GuiTimeBasedAnimation : public IGuiGraphicsAnimation, public Description<GuiTimeBasedAnimation> { protected: unsigned __int64 startTime; vint length; public: GuiTimeBasedAnimation(vint totalMilliseconds); ~GuiTimeBasedAnimation(); void Restart(vint totalMilliseconds=-1); vint GetTotalLength()override; vint GetCurrentPosition()override; }; /*********************************************************************** Shortcut Key Manager Helpers ***********************************************************************/ class GuiShortcutKeyManager; class GuiShortcutKeyItem : public Object, public IGuiShortcutKeyItem { protected: GuiShortcutKeyManager* shortcutKeyManager; bool ctrl; bool shift; bool alt; vint key; void AttachManager(GuiShortcutKeyManager* manager); void DetachManager(GuiShortcutKeyManager* manager); public: GuiShortcutKeyItem(GuiShortcutKeyManager* _shortcutKeyManager, bool _ctrl, bool _shift, bool _alt, vint _key); ~GuiShortcutKeyItem(); IGuiShortcutKeyManager* GetManager()override; WString GetName()override; bool CanActivate(const NativeWindowKeyInfo& info); bool CanActivate(bool _ctrl, bool _shift, bool _alt, vint _key); }; class GuiShortcutKeyManager : public Object, public IGuiShortcutKeyManager, public Description<GuiShortcutKeyManager> { typedef collections::List<Ptr<GuiShortcutKeyItem>> ShortcutKeyItemList; protected: ShortcutKeyItemList shortcutKeyItems; public: GuiShortcutKeyManager(); ~GuiShortcutKeyManager(); vint GetItemCount()override; IGuiShortcutKeyItem* GetItem(vint index)override; bool Execute(const NativeWindowKeyInfo& info)override; IGuiShortcutKeyItem* CreateShortcut(bool ctrl, bool shift, bool alt, vint key); bool DestroyShortcut(bool ctrl, bool shift, bool alt, vint key); IGuiShortcutKeyItem* TryGetShortcut(bool ctrl, bool shift, bool alt, vint key); }; } } } #endif /*********************************************************************** CONTROLS\GUIBASICCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIBASICCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUIBASICCONTROLS namespace vl { namespace presentation { namespace controls { /*********************************************************************** Basic Construction ***********************************************************************/ class GuiControl : public Object, public Description<GuiControl> { friend class compositions::GuiGraphicsComposition; typedef collections::List<GuiControl*> ControlList; public: class IStyleController : public virtual IDescriptable, public Description<IStyleController> { public: virtual compositions::GuiBoundsComposition* GetBoundsComposition()=0; virtual compositions::GuiGraphicsComposition* GetContainerComposition()=0; virtual void SetFocusableComposition(compositions::GuiGraphicsComposition* value)=0; virtual void SetText(const WString& value)=0; virtual void SetFont(const FontProperties& value)=0; virtual void SetVisuallyEnabled(bool value)=0; }; class EmptyStyleController : public Object, public IStyleController, public Description<EmptyStyleController> { protected: compositions::GuiBoundsComposition* boundsComposition; public: EmptyStyleController(); ~EmptyStyleController(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; }; class IStyleProvider : public virtual IDescriptable, public Description<IStyleProvider> { public: virtual void AssociateStyleController(IStyleController* controller)=0; virtual void SetFocusableComposition(compositions::GuiGraphicsComposition* value)=0; virtual void SetText(const WString& value)=0; virtual void SetFont(const FontProperties& value)=0; virtual void SetVisuallyEnabled(bool value)=0; }; protected: Ptr<IStyleController> styleController; compositions::GuiBoundsComposition* boundsComposition; compositions::GuiGraphicsComposition* focusableComposition; compositions::GuiGraphicsEventReceiver* eventReceiver; bool isEnabled; bool isVisuallyEnabled; bool isVisible; WString text; FontProperties font; GuiControl* parent; ControlList children; Ptr<Object> tag; GuiControl* tooltipControl; vint tooltipWidth; virtual void OnChildInserted(GuiControl* control); virtual void OnChildRemoved(GuiControl* control); virtual void OnParentChanged(GuiControl* oldParent, GuiControl* newParent); virtual void OnParentLineChanged(); virtual void OnRenderTargetChanged(elements::IGuiGraphicsRenderTarget* renderTarget); virtual void OnBeforeReleaseGraphicsHost(); virtual void UpdateVisuallyEnabled(); void SetFocusableComposition(compositions::GuiGraphicsComposition* value); static void SharedPtrDestructorProc(DescriptableObject* obj); public: GuiControl(IStyleController* _styleController); ~GuiControl(); compositions::GuiNotifyEvent VisibleChanged; compositions::GuiNotifyEvent EnabledChanged; compositions::GuiNotifyEvent VisuallyEnabledChanged; compositions::GuiNotifyEvent TextChanged; compositions::GuiNotifyEvent FontChanged; compositions::GuiEventArgs GetNotifyEventArguments(); IStyleController* GetStyleController(); compositions::GuiBoundsComposition* GetBoundsComposition(); compositions::GuiGraphicsComposition* GetContainerComposition(); compositions::GuiGraphicsComposition* GetFocusableComposition(); compositions::GuiGraphicsEventReceiver* GetEventReceiver(); GuiControl* GetParent(); vint GetChildrenCount(); GuiControl* GetChild(vint index); bool AddChild(GuiControl* control); bool HasChild(GuiControl* control); virtual GuiControlHost* GetRelatedControlHost(); virtual bool GetVisuallyEnabled(); virtual bool GetEnabled(); virtual void SetEnabled(bool value); virtual bool GetVisible(); virtual void SetVisible(bool value); virtual const WString& GetText(); virtual void SetText(const WString& value); virtual const FontProperties& GetFont(); virtual void SetFont(const FontProperties& value); virtual void SetFocus(); Ptr<Object> GetTag(); void SetTag(Ptr<Object> value); GuiControl* GetTooltipControl(); GuiControl* SetTooltipControl(GuiControl* value); vint GetTooltipWidth(); void SetTooltipWidth(vint value); bool DisplayTooltip(Point location); void CloseTooltip(); virtual IDescriptable* QueryService(const WString& identifier); template<typename T> T* QueryService() { return dynamic_cast<T*>(QueryService(T::Identifier)); } }; class GuiComponent : public Object, public Description<GuiComponent> { public: GuiComponent(); ~GuiComponent(); }; template<typename T> class GuiObjectComponent : public GuiComponent { public: Ptr<T> object; GuiObjectComponent() { } GuiObjectComponent(Ptr<T> _object) :object(_object) { } }; /*********************************************************************** Label ***********************************************************************/ class GuiLabel : public GuiControl, public Description<GuiLabel> { public: class IStyleController : virtual public GuiControl::IStyleController, public Description<IStyleController> { public: virtual Color GetDefaultTextColor()=0; virtual void SetTextColor(Color value)=0; }; protected: Color textColor; IStyleController* styleController; public: GuiLabel(IStyleController* _styleController); ~GuiLabel(); Color GetTextColor(); void SetTextColor(Color value); }; /*********************************************************************** Buttons ***********************************************************************/ class GuiButton : public GuiControl, public Description<GuiButton> { public: enum ControlState { Normal, Active, Pressed, }; class IStyleController : virtual public GuiControl::IStyleController, public Description<IStyleController> { public: virtual void Transfer(ControlState value)=0; }; protected: IStyleController* styleController; bool clickOnMouseUp; bool mousePressing; bool mouseHoving; ControlState controlState; void OnParentLineChanged()override; void UpdateControlState(); void OnLeftButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnLeftButtonUp(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnMouseEnter(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnMouseLeave(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: GuiButton(IStyleController* _styleController); ~GuiButton(); compositions::GuiNotifyEvent Clicked; bool GetClickOnMouseUp(); void SetClickOnMouseUp(bool value); }; class GuiSelectableButton : public GuiButton, public Description<GuiSelectableButton> { public: class IStyleController : public virtual GuiButton::IStyleController, public Description<IStyleController> { public: virtual void SetSelected(bool value)=0; }; class GroupController : public GuiComponent, public Description<GroupController> { protected: collections::List<GuiSelectableButton*> buttons; public: GroupController(); ~GroupController(); virtual void Attach(GuiSelectableButton* button); virtual void Detach(GuiSelectableButton* button); virtual void OnSelectedChanged(GuiSelectableButton* button)=0; }; class MutexGroupController : public GroupController, public Description<MutexGroupController> { protected: bool suppress; public: MutexGroupController(); ~MutexGroupController(); void OnSelectedChanged(GuiSelectableButton* button)override; }; protected: IStyleController* styleController; GroupController* groupController; bool autoSelection; bool isSelected; void OnClicked(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: GuiSelectableButton(IStyleController* _styleController); ~GuiSelectableButton(); compositions::GuiNotifyEvent GroupControllerChanged; compositions::GuiNotifyEvent AutoSelectionChanged; compositions::GuiNotifyEvent SelectedChanged; virtual GroupController* GetGroupController(); virtual void SetGroupController(GroupController* value); virtual bool GetAutoSelection(); virtual void SetAutoSelection(bool value); virtual bool GetSelected(); virtual void SetSelected(bool value); }; /*********************************************************************** Scrolls ***********************************************************************/ class GuiScroll : public GuiControl, public Description<GuiScroll> { public: class ICommandExecutor : public virtual IDescriptable, public Description<ICommandExecutor> { public: virtual void SmallDecrease()=0; virtual void SmallIncrease()=0; virtual void BigDecrease()=0; virtual void BigIncrease()=0; virtual void SetTotalSize(vint value)=0; virtual void SetPageSize(vint value)=0; virtual void SetPosition(vint value)=0; }; class IStyleController : public virtual GuiControl::IStyleController, public Description<IStyleController> { public: virtual void SetCommandExecutor(ICommandExecutor* value)=0; virtual void SetTotalSize(vint value)=0; virtual void SetPageSize(vint value)=0; virtual void SetPosition(vint value)=0; }; protected: class CommandExecutor : public Object, public ICommandExecutor { protected: GuiScroll* scroll; public: CommandExecutor(GuiScroll* _scroll); ~CommandExecutor(); void SmallDecrease()override; void SmallIncrease()override; void BigDecrease()override; void BigIncrease()override; void SetTotalSize(vint value)override; void SetPageSize(vint value)override; void SetPosition(vint value)override; }; IStyleController* styleController; Ptr<CommandExecutor> commandExecutor; vint totalSize; vint pageSize; vint position; vint smallMove; vint bigMove; public: GuiScroll(IStyleController* _styleController); ~GuiScroll(); compositions::GuiNotifyEvent TotalSizeChanged; compositions::GuiNotifyEvent PageSizeChanged; compositions::GuiNotifyEvent PositionChanged; compositions::GuiNotifyEvent SmallMoveChanged; compositions::GuiNotifyEvent BigMoveChanged; virtual vint GetTotalSize(); virtual void SetTotalSize(vint value); virtual vint GetPageSize(); virtual void SetPageSize(vint value); virtual vint GetPosition(); virtual void SetPosition(vint value); virtual vint GetSmallMove(); virtual void SetSmallMove(vint value); virtual vint GetBigMove(); virtual void SetBigMove(vint value); vint GetMinPosition(); vint GetMaxPosition(); }; namespace list { /*********************************************************************** List interface common implementation ***********************************************************************/ template<typename T, typename K=typename KeyType<T>::Type> class ItemsBase : public Object, public virtual collections::IEnumerable<T> { protected: collections::List<T, K> items; virtual void NotifyUpdateInternal(vint start, vint count, vint newCount) { } virtual bool InsertInternal(vint index, const T& value) { items.Insert(index, value); return true; } virtual bool RemoveAtInternal(vint index, const T& value) { items.RemoveAt(index); return true; } public: ItemsBase() { } ~ItemsBase() { } collections::IEnumerator<T>* CreateEnumerator()const { return items.CreateEnumerator(); } bool NotifyUpdate(vint start, vint count=1) { if(start<0 || start>=items.Count() || count<=0 || start+count>items.Count()) { return false; } else { NotifyUpdateInternal(start, count, count); return true; } } bool Contains(const K& item)const { return items.Contains(item); } vint Count()const { return items.Count(); } vint Count() { return items.Count(); } const T& Get(vint index)const { return items.Get(index); } const T& operator[](vint index)const { return items.Get(index); } vint IndexOf(const K& item)const { return items.IndexOf(item); } vint Add(const T& item) { return Insert(items.Count(), item); } bool Remove(const K& item) { vint index=items.IndexOf(item); if(index==-1) return false; return RemoveAt(index); } bool RemoveAt(vint index) { if(RemoveAtInternal(index, items[index])) { NotifyUpdateInternal(index, 1, 0); return true; } else { return false; } } bool RemoveRange(vint index, vint count) { if(count<=0) return false; if(0<=index && index<items.Count() && index+count<=items.Count()) { while(count-->0) { RemoveAt(index+count); } return true; } else { return false; } } bool Clear() { while(items.Count()>0) { RemoveAt(items.Count()-1); } return true; } vint Insert(vint index, const T& item) { if(InsertInternal(index, item)) { NotifyUpdateInternal(index, 0, 1); return index; } else { return -1; } } bool Set(vint index, const T& item) { if(Insert(index, item)) { return RemoveAt(index+1); } else { return false; } } }; } } } namespace collections { namespace randomaccess_internal { template<typename T> struct RandomAccessable<presentation::controls::list::ItemsBase<T>> { static const bool CanRead = true; static const bool CanResize = false; }; } } } #endif /*********************************************************************** CONTROLS\GUIWINDOWCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIWINDOWCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUIWINDOWCONTROLS namespace vl { namespace presentation { namespace controls { /*********************************************************************** Control Host ***********************************************************************/ class GuiControlHost : public GuiControl, private INativeWindowListener, public Description<GuiControlHost> { protected: compositions::GuiGraphicsHost* host; collections::List<GuiComponent*> components; virtual void OnNativeWindowChanged(); virtual void OnVisualStatusChanged(); private: static const vint TooltipDelayOpenTime=500; static const vint TooltipDelayCloseTime=500; static const vint TooltipDelayLifeTime=5000; Ptr<INativeDelay> tooltipOpenDelay; Ptr<INativeDelay> tooltipCloseDelay; Point tooltipLocation; GuiControl* GetTooltipOwner(Point location); void MoveIntoTooltipControl(GuiControl* tooltipControl, Point location); void MouseMoving(const NativeWindowMouseInfo& info)override; void MouseLeaved()override; void Moved()override; void Enabled()override; void Disabled()override; void GotFocus()override; void LostFocus()override; void Activated()override; void Deactivated()override; void Opened()override; void Closing(bool& cancel)override; void Closed()override; void Destroying()override; public: GuiControlHost(GuiControl::IStyleController* _styleController); ~GuiControlHost(); compositions::GuiNotifyEvent WindowGotFocus; compositions::GuiNotifyEvent WindowLostFocus; compositions::GuiNotifyEvent WindowActivated; compositions::GuiNotifyEvent WindowDeactivated; compositions::GuiNotifyEvent WindowOpened; compositions::GuiRequestEvent WindowClosing; compositions::GuiNotifyEvent WindowClosed; compositions::GuiNotifyEvent WindowDestroying; compositions::GuiGraphicsHost* GetGraphicsHost(); compositions::GuiGraphicsComposition* GetMainComposition(); INativeWindow* GetNativeWindow(); void SetNativeWindow(INativeWindow* window); void ForceCalculateSizeImmediately(); void Render(); bool GetEnabled()override; void SetEnabled(bool value)override; bool GetFocused(); void SetFocused(); bool GetActivated(); void SetActivated(); bool GetShowInTaskBar(); void SetShowInTaskBar(bool value); bool GetEnabledActivate(); void SetEnabledActivate(bool value); bool GetTopMost(); void SetTopMost(bool topmost); bool AddComponent(GuiComponent* component); bool RemoveComponent(GuiComponent* component); bool ContainsComponent(GuiComponent* component); compositions::IGuiShortcutKeyManager* GetShortcutKeyManager(); void SetShortcutKeyManager(compositions::IGuiShortcutKeyManager* value); compositions::GuiGraphicsAnimationManager* GetAnimationManager(); Size GetClientSize(); void SetClientSize(Size value); Rect GetBounds(); void SetBounds(Rect value); GuiControlHost* GetRelatedControlHost()override; const WString& GetText()override; void SetText(const WString& value)override; INativeScreen* GetRelatedScreen(); void Show(); void ShowDeactivated(); void ShowRestored(); void ShowMaximized(); void ShowMinimized(); void Hide(); void Close(); bool GetOpening(); }; /*********************************************************************** Window ***********************************************************************/ class GuiWindow : public GuiControlHost, public Description<GuiWindow> { friend class GuiApplication; public: class IStyleController : virtual public GuiControl::IStyleController, public Description<IStyleController> { public: virtual void AttachWindow(GuiWindow* _window)=0; virtual void InitializeNativeWindowProperties()=0; virtual bool GetMaximizedBox()=0; virtual void SetMaximizedBox(bool visible)=0; virtual bool GetMinimizedBox()=0; virtual void SetMinimizedBox(bool visible)=0; virtual bool GetBorder()=0; virtual void SetBorder(bool visible)=0; virtual bool GetSizeBox()=0; virtual void SetSizeBox(bool visible)=0; virtual bool GetIconVisible()=0; virtual void SetIconVisible(bool visible)=0; virtual bool GetTitleBar()=0; virtual void SetTitleBar(bool visible)=0; }; class DefaultBehaviorStyleController : virtual public IStyleController { protected: GuiWindow* window; public: DefaultBehaviorStyleController(); ~DefaultBehaviorStyleController(); void AttachWindow(GuiWindow* _window)override; void InitializeNativeWindowProperties()override; bool GetMaximizedBox()override; void SetMaximizedBox(bool visible)override; bool GetMinimizedBox()override; void SetMinimizedBox(bool visible)override; bool GetBorder()override; void SetBorder(bool visible)override; bool GetSizeBox()override; void SetSizeBox(bool visible)override; bool GetIconVisible()override; void SetIconVisible(bool visible)override; bool GetTitleBar()override; void SetTitleBar(bool visible)override; }; protected: IStyleController* styleController; void OnNativeWindowChanged()override; void OnVisualStatusChanged()override; virtual void MouseClickedOnOtherWindow(GuiWindow* window); public: GuiWindow(IStyleController* _styleController); ~GuiWindow(); compositions::GuiNotifyEvent ClipboardUpdated; void MoveToScreenCenter(); bool GetMaximizedBox(); void SetMaximizedBox(bool visible); bool GetMinimizedBox(); void SetMinimizedBox(bool visible); bool GetBorder(); void SetBorder(bool visible); bool GetSizeBox(); void SetSizeBox(bool visible); bool GetIconVisible(); void SetIconVisible(bool visible); bool GetTitleBar(); void SetTitleBar(bool visible); }; class GuiPopup : public GuiWindow, public Description<GuiPopup> { protected: void MouseClickedOnOtherWindow(GuiWindow* window)override; void PopupOpened(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void PopupClosed(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: GuiPopup(IStyleController* _styleController); ~GuiPopup(); bool IsClippedByScreen(Point location); void ShowPopup(Point location); void ShowPopup(GuiControl* control, Rect bounds, bool preferredTopBottomSide); void ShowPopup(GuiControl* control, Point location); void ShowPopup(GuiControl* control, bool preferredTopBottomSide); }; class GuiTooltip : public GuiPopup, private INativeControllerListener, public Description<GuiTooltip> { protected: GuiControl* temporaryContentControl; void GlobalTimer()override; void TooltipOpened(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void TooltipClosed(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: GuiTooltip(IStyleController* _styleController); ~GuiTooltip(); vint GetPreferredContentWidth(); void SetPreferredContentWidth(vint value); GuiControl* GetTemporaryContentControl(); void SetTemporaryContentControl(GuiControl* control); }; } } } #endif /*********************************************************************** CONTROLS\GUIAPPLICATION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Application Framework Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIAPPLICATION #define VCZH_PRESENTATION_CONTROLS_GUIAPPLICATION namespace vl { namespace presentation { namespace controls { class GuiApplication : public Object, private INativeControllerListener, public Description<GuiApplication> { friend void GuiApplicationInitialize(); friend class GuiWindow; friend class GuiPopup; friend class Ptr<GuiApplication>; private: void InvokeClipboardNotify(compositions::GuiGraphicsComposition* composition, compositions::GuiEventArgs& arguments); void LeftButtonDown(Point position)override; void LeftButtonUp(Point position)override; void RightButtonDown(Point position)override; void RightButtonUp(Point position)override; void ClipboardUpdated()override; protected: GuiWindow* mainWindow; GuiControl* sharedTooltipOwner; GuiTooltip* sharedTooltipWindow; bool sharedTooltipHovering; bool sharedTooltipClosing; collections::List<GuiWindow*> windows; collections::SortedList<GuiPopup*> openingPopups; GuiApplication(); ~GuiApplication(); void RegisterWindow(GuiWindow* window); void UnregisterWindow(GuiWindow* window); void RegisterPopupOpened(GuiPopup* popup); void RegisterPopupClosed(GuiPopup* popup); void OnMouseDown(Point location); void TooltipMouseEnter(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void TooltipMouseLeave(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: void Run(GuiWindow* _mainWindow); GuiWindow* GetMainWindow(); const collections::List<GuiWindow*>& GetWindows(); GuiWindow* GetWindow(Point location); void ShowTooltip(GuiControl* owner, GuiControl* tooltip, vint preferredContentWidth, Point location); void CloseTooltip(); GuiControl* GetTooltipOwner(); WString GetExecutablePath(); WString GetExecutableFolder(); bool IsInMainThread(); void InvokeAsync(const Func<void()>& proc); void InvokeInMainThread(const Func<void()>& proc); bool InvokeInMainThreadAndWait(const Func<void()>& proc, vint milliseconds=-1); Ptr<INativeDelay> DelayExecute(const Func<void()>& proc, vint milliseconds); Ptr<INativeDelay> DelayExecuteInMainThread(const Func<void()>& proc, vint milliseconds); void RunGuiTask(const Func<void()>& proc); template<typename T> T RunGuiValue(const Func<T()>& proc) { T result; RunGuiTask([&result, &proc]() { result=proc(); }); return result; } template<typename T> void InvokeLambdaInMainThread(const T& proc) { InvokeInMainThread(Func<void()>(proc)); } template<typename T> bool InvokeLambdaInMainThreadAndWait(const T& proc, vint milliseconds=-1) { return InvokeInMainThreadAndWait(Func<void()>(proc), milliseconds); } }; extern GuiApplication* GetApplication(); } } } extern void GuiApplicationMain(); #define GUI_VALUE(x) vl::presentation::controls::GetApplication()->RunGuiValue(LAMBDA([&](){return (x);})) #define GUI_RUN(x) vl::presentation::controls::GetApplication()->RunGuiTask([=](){x}) #endif /*********************************************************************** CONTROLS\GUICONTAINERCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUICONTAINERCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUICONTAINERCONTROLS namespace vl { namespace presentation { namespace controls { /*********************************************************************** Tab Control ***********************************************************************/ class GuiTab; class GuiTabPage : public Object, public Description<GuiTabPage> { friend class GuiTab; friend class Ptr<GuiTabPage>; protected: GuiControl* container; GuiTab* owner; WString text; bool AssociateTab(GuiTab* _owner, GuiControl::IStyleController* _styleController); bool DeassociateTab(GuiTab* _owner); public: GuiTabPage(); ~GuiTabPage(); compositions::GuiNotifyEvent TextChanged; compositions::GuiNotifyEvent PageInstalled; compositions::GuiNotifyEvent PageUninstalled; compositions::GuiNotifyEvent PageContainerReady; GuiControl* GetContainer(); GuiTab* GetOwnerTab(); const WString& GetText(); void SetText(const WString& param); bool GetSelected(); }; class GuiTab : public GuiControl, public Description<GuiTab> { friend class GuiTabPage; public: class ICommandExecutor : public virtual IDescriptable, public Description<ICommandExecutor> { public: virtual void ShowTab(vint index)=0; }; class IStyleController : public virtual GuiControl::IStyleController, public Description<IStyleController> { public: virtual void SetCommandExecutor(ICommandExecutor* value)=0; virtual void InsertTab(vint index)=0; virtual void SetTabText(vint index, const WString& value)=0; virtual void RemoveTab(vint index)=0; virtual void MoveTab(vint oldIndex, vint newIndex)=0; virtual void SetSelectedTab(vint index)=0; virtual GuiControl::IStyleController* CreateTabPageStyleController()=0; }; protected: class CommandExecutor : public Object, public ICommandExecutor { protected: GuiTab* tab; public: CommandExecutor(GuiTab* _tab); ~CommandExecutor(); void ShowTab(vint index)override; }; Ptr<CommandExecutor> commandExecutor; IStyleController* styleController; collections::List<GuiTabPage*> tabPages; GuiTabPage* selectedPage; public: GuiTab(IStyleController* _styleController); ~GuiTab(); compositions::GuiNotifyEvent SelectedPageChanged; GuiTabPage* CreatePage(vint index=-1); bool CreatePage(GuiTabPage* page, vint index=-1); bool RemovePage(GuiTabPage* value); bool MovePage(GuiTabPage* page, vint newIndex); const collections::List<GuiTabPage*>& GetPages(); GuiTabPage* GetSelectedPage(); bool SetSelectedPage(GuiTabPage* value); }; /*********************************************************************** Scroll View ***********************************************************************/ class GuiScrollView : public GuiControl, public Description<GuiScrollView> { public: class IStyleProvider : public virtual GuiControl::IStyleProvider, public Description<IStyleProvider> { public: virtual GuiScroll::IStyleController* CreateHorizontalScrollStyle()=0; virtual GuiScroll::IStyleController* CreateVerticalScrollStyle()=0; virtual vint GetDefaultScrollSize()=0; virtual compositions::GuiGraphicsComposition* InstallBackground(compositions::GuiBoundsComposition* boundsComposition)=0; }; class StyleController : public Object, public GuiControl::IStyleController, public Description<StyleController> { protected: Ptr<IStyleProvider> styleProvider; GuiScrollView* scrollView; GuiScroll* horizontalScroll; GuiScroll* verticalScroll; compositions::GuiBoundsComposition* boundsComposition; compositions::GuiTableComposition* tableComposition; compositions::GuiCellComposition* containerCellComposition; compositions::GuiBoundsComposition* containerComposition; bool horizontalAlwaysVisible; bool verticalAlwaysVisible; void UpdateTable(); public: StyleController(IStyleProvider* _styleProvider); ~StyleController(); void SetScrollView(GuiScrollView* _scrollView); void AdjustView(Size fullSize); IStyleProvider* GetStyleProvider(); GuiScroll* GetHorizontalScroll(); GuiScroll* GetVerticalScroll(); compositions::GuiTableComposition* GetInternalTableComposition(); compositions::GuiBoundsComposition* GetInternalContainerComposition(); bool GetHorizontalAlwaysVisible(); void SetHorizontalAlwaysVisible(bool value); bool GetVerticalAlwaysVisible(); void SetVerticalAlwaysVisible(bool value); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; }; protected: StyleController* styleController; bool supressScrolling; void OnContainerBoundsChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnHorizontalScroll(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnVerticalScroll(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void CallUpdateView(); void Initialize(); virtual Size QueryFullSize()=0; virtual void UpdateView(Rect viewBounds)=0; GuiScrollView(StyleController* _styleController); public: GuiScrollView(IStyleProvider* styleProvider); ~GuiScrollView(); void CalculateView(); Size GetViewSize(); Rect GetViewBounds(); GuiScroll* GetHorizontalScroll(); GuiScroll* GetVerticalScroll(); bool GetHorizontalAlwaysVisible(); void SetHorizontalAlwaysVisible(bool value); bool GetVerticalAlwaysVisible(); void SetVerticalAlwaysVisible(bool value); }; class GuiScrollContainer : public GuiScrollView, public Description<GuiScrollContainer> { public: class StyleController : public GuiScrollView::StyleController, public Description<StyleController> { protected: compositions::GuiBoundsComposition* controlContainerComposition; bool extendToFullWidth; public: StyleController(GuiScrollView::IStyleProvider* styleProvider); ~StyleController(); compositions::GuiGraphicsComposition* GetContainerComposition()override; void MoveContainer(Point leftTop); bool GetExtendToFullWidth(); void SetExtendToFullWidth(bool value); }; protected: StyleController* styleController; void OnControlContainerBoundsChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); Size QueryFullSize()override; void UpdateView(Rect viewBounds)override; public: GuiScrollContainer(GuiScrollContainer::IStyleProvider* styleProvider); ~GuiScrollContainer(); bool GetExtendToFullWidth(); void SetExtendToFullWidth(bool value); }; } } } #endif /*********************************************************************** CONTROLS\LISTCONTROLPACKAGE\GUILISTCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUILISTCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUILISTCONTROLS namespace vl { namespace presentation { namespace controls { /*********************************************************************** List Control ***********************************************************************/ class GuiListControl : public GuiScrollView, public Description<GuiListControl> { public: class IItemProvider; class IItemStyleController; class IItemStyleProvider; //----------------------------------------------------------- // Callback Interfaces //----------------------------------------------------------- class IItemProviderCallback : public virtual IDescriptable, public Description<IItemProviderCallback> { public: virtual void OnAttached(IItemProvider* provider)=0; virtual void OnItemModified(vint start, vint count, vint newCount)=0; }; class IItemArrangerCallback : public virtual IDescriptable, public Description<IItemArrangerCallback> { public: virtual IItemStyleController* RequestItem(vint itemIndex)=0; virtual void ReleaseItem(IItemStyleController* style)=0; virtual void SetViewLocation(Point value)=0; virtual Size GetStylePreferredSize(IItemStyleController* style)=0; virtual void SetStyleAlignmentToParent(IItemStyleController* style, Margin margin)=0; virtual Rect GetStyleBounds(IItemStyleController* style)=0; virtual void SetStyleBounds(IItemStyleController* style, Rect bounds)=0; virtual compositions::GuiGraphicsComposition* GetContainerComposition()=0; virtual void OnTotalSizeChanged()=0; }; //----------------------------------------------------------- // Common Views //----------------------------------------------------------- class IItemPrimaryTextView : public virtual IDescriptable, public Description<IItemPrimaryTextView> { public: static const wchar_t* const Identifier; virtual WString GetPrimaryTextViewText(vint itemIndex)=0; virtual bool ContainsPrimaryText(vint itemIndex)=0; }; //----------------------------------------------------------- // Provider Interfaces //----------------------------------------------------------- enum KeyDirection { Up, Down, Left, Right, Home, End, PageUp, PageDown, PageLeft, PageRight, }; class IItemProvider : public virtual IDescriptable, public Description<IItemProvider> { public: virtual bool AttachCallback(IItemProviderCallback* value)=0; virtual bool DetachCallback(IItemProviderCallback* value)=0; virtual vint Count()=0; virtual IDescriptable* RequestView(const WString& identifier)=0; virtual void ReleaseView(IDescriptable* view)=0; }; class IItemStyleController : public virtual IDescriptable, public Description<IItemStyleController> { public: virtual IItemStyleProvider* GetStyleProvider()=0; virtual vint GetItemStyleId()=0; virtual compositions::GuiBoundsComposition* GetBoundsComposition()=0; virtual bool IsCacheable()=0; virtual bool IsInstalled()=0; virtual void OnInstalled()=0; virtual void OnUninstalled()=0; }; class IItemStyleProvider : public virtual IDescriptable, public Description<IItemStyleProvider> { public: virtual void AttachListControl(GuiListControl* value)=0; virtual void DetachListControl()=0; virtual vint GetItemStyleId(vint itemIndex)=0; virtual IItemStyleController* CreateItemStyle(vint styleId)=0; virtual void DestroyItemStyle(IItemStyleController* style)=0; virtual void Install(IItemStyleController* style, vint itemIndex)=0; }; class IItemArranger : public virtual IItemProviderCallback, public Description<IItemArranger> { public: virtual void AttachListControl(GuiListControl* value)=0; virtual void DetachListControl()=0; virtual IItemArrangerCallback* GetCallback()=0; virtual void SetCallback(IItemArrangerCallback* value)=0; virtual Size GetTotalSize()=0; virtual IItemStyleController* GetVisibleStyle(vint itemIndex)=0; virtual vint GetVisibleIndex(IItemStyleController* style)=0; virtual void OnViewChanged(Rect bounds)=0; virtual vint FindItem(vint itemIndex, KeyDirection key)=0; virtual bool EnsureItemVisible(vint itemIndex)=0; }; class IItemCoordinateTransformer : public virtual IDescriptable, public Description<IItemCoordinateTransformer> { public: virtual Size RealSizeToVirtualSize(Size size)=0; virtual Size VirtualSizeToRealSize(Size size)=0; virtual Point RealPointToVirtualPoint(Size realFullSize, Point point)=0; virtual Point VirtualPointToRealPoint(Size realFullSize, Point point)=0; virtual Rect RealRectToVirtualRect(Size realFullSize, Rect rect)=0; virtual Rect VirtualRectToRealRect(Size realFullSize, Rect rect)=0; virtual Margin RealMarginToVirtualMargin(Margin margin)=0; virtual Margin VirtualMarginToRealMargin(Margin margin)=0; virtual KeyDirection RealKeyDirectionToVirtualKeyDirection(KeyDirection key)=0; }; protected: //----------------------------------------------------------- // ItemCallback //----------------------------------------------------------- class ItemCallback : public IItemProviderCallback, public IItemArrangerCallback { typedef collections::List<IItemStyleController*> StyleList; protected: GuiListControl* listControl; IItemProvider* itemProvider; StyleList cachedStyles; StyleList installedStyles; public: ItemCallback(GuiListControl* _listControl); ~ItemCallback(); void ClearCache(); void OnAttached(IItemProvider* provider)override; void OnItemModified(vint start, vint count, vint newCount)override; IItemStyleController* RequestItem(vint itemIndex)override; void ReleaseItem(IItemStyleController* style)override; void SetViewLocation(Point value)override; Size GetStylePreferredSize(IItemStyleController* style)override; void SetStyleAlignmentToParent(IItemStyleController* style, Margin margin)override; Rect GetStyleBounds(IItemStyleController* style)override; void SetStyleBounds(IItemStyleController* style, Rect bounds)override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void OnTotalSizeChanged()override; }; //----------------------------------------------------------- // State management //----------------------------------------------------------- Ptr<ItemCallback> callback; Ptr<IItemProvider> itemProvider; Ptr<IItemStyleProvider> itemStyleProvider; Ptr<IItemArranger> itemArranger; Ptr<IItemCoordinateTransformer> itemCoordinateTransformer; Size fullSize; virtual void OnItemModified(vint start, vint count, vint newCount); virtual void OnStyleInstalled(vint itemIndex, IItemStyleController* style); virtual void OnStyleUninstalled(IItemStyleController* style); void OnRenderTargetChanged(elements::IGuiGraphicsRenderTarget* renderTarget)override; void OnBeforeReleaseGraphicsHost()override; Size QueryFullSize()override; void UpdateView(Rect viewBounds)override; void OnBoundsMouseButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void SetStyleProviderAndArranger(Ptr<IItemStyleProvider> styleProvider, Ptr<IItemArranger> arranger); //----------------------------------------------------------- // Item event management //----------------------------------------------------------- class VisibleStyleHelper { public: Ptr<compositions::GuiMouseEvent::IHandler> leftButtonDownHandler; Ptr<compositions::GuiMouseEvent::IHandler> leftButtonUpHandler; Ptr<compositions::GuiMouseEvent::IHandler> leftButtonDoubleClickHandler; Ptr<compositions::GuiMouseEvent::IHandler> middleButtonDownHandler; Ptr<compositions::GuiMouseEvent::IHandler> middleButtonUpHandler; Ptr<compositions::GuiMouseEvent::IHandler> middleButtonDoubleClickHandler; Ptr<compositions::GuiMouseEvent::IHandler> rightButtonDownHandler; Ptr<compositions::GuiMouseEvent::IHandler> rightButtonUpHandler; Ptr<compositions::GuiMouseEvent::IHandler> rightButtonDoubleClickHandler; Ptr<compositions::GuiMouseEvent::IHandler> mouseMoveHandler; Ptr<compositions::GuiNotifyEvent::IHandler> mouseEnterHandler; Ptr<compositions::GuiNotifyEvent::IHandler> mouseLeaveHandler; }; friend class collections::ArrayBase<Ptr<VisibleStyleHelper>>; collections::Dictionary<IItemStyleController*, Ptr<VisibleStyleHelper>> visibleStyles; void OnItemMouseEvent(compositions::GuiItemMouseEvent& itemEvent, IItemStyleController* style, compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnItemNotifyEvent(compositions::GuiItemNotifyEvent& itemEvent, IItemStyleController* style, compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void AttachItemEvents(IItemStyleController* style); void DetachItemEvents(IItemStyleController* style); public: GuiListControl(IStyleProvider* _styleProvider, IItemProvider* _itemProvider, bool acceptFocus=false); ~GuiListControl(); compositions::GuiNotifyEvent StyleProviderChanged; compositions::GuiNotifyEvent ArrangerChanged; compositions::GuiNotifyEvent CoordinateTransformerChanged; compositions::GuiItemMouseEvent ItemLeftButtonDown; compositions::GuiItemMouseEvent ItemLeftButtonUp; compositions::GuiItemMouseEvent ItemLeftButtonDoubleClick; compositions::GuiItemMouseEvent ItemMiddleButtonDown; compositions::GuiItemMouseEvent ItemMiddleButtonUp; compositions::GuiItemMouseEvent ItemMiddleButtonDoubleClick; compositions::GuiItemMouseEvent ItemRightButtonDown; compositions::GuiItemMouseEvent ItemRightButtonUp; compositions::GuiItemMouseEvent ItemRightButtonDoubleClick; compositions::GuiItemMouseEvent ItemMouseMove; compositions::GuiItemNotifyEvent ItemMouseEnter; compositions::GuiItemNotifyEvent ItemMouseLeave; virtual IItemProvider* GetItemProvider(); virtual IItemStyleProvider* GetStyleProvider(); virtual Ptr<IItemStyleProvider> SetStyleProvider(Ptr<IItemStyleProvider> value); virtual IItemArranger* GetArranger(); virtual Ptr<IItemArranger> SetArranger(Ptr<IItemArranger> value); virtual IItemCoordinateTransformer* GetCoordinateTransformer(); virtual Ptr<IItemCoordinateTransformer> SetCoordinateTransformer(Ptr<IItemCoordinateTransformer> value); virtual bool EnsureItemVisible(vint itemIndex); }; /*********************************************************************** Selectable List Control ***********************************************************************/ class GuiSelectableListControl : public GuiListControl, public Description<GuiSelectableListControl> { public: class IItemStyleProvider : public virtual GuiListControl::IItemStyleProvider, public Description<IItemStyleProvider> { public: virtual void SetStyleSelected(IItemStyleController* style, bool value)=0; }; protected: Ptr<IItemStyleProvider> selectableStyleProvider; collections::SortedList<vint> selectedItems; bool multiSelect; vint selectedItemIndexStart; vint selectedItemIndexEnd; void OnItemModified(vint start, vint count, vint newCount)override; void OnStyleInstalled(vint itemIndex, IItemStyleController* style)override; void OnStyleUninstalled(IItemStyleController* style)override; virtual void OnItemSelectionChanged(vint itemIndex, bool value); virtual void OnItemSelectionCleared(); void OnItemLeftButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiItemMouseEventArgs& arguments); void OnItemRightButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiItemMouseEventArgs& arguments); void NormalizeSelectedItemIndexStartEnd(); void SetMultipleItemsSelectedSilently(vint start, vint end, bool selected); void OnKeyDown(compositions::GuiGraphicsComposition* sender, compositions::GuiKeyEventArgs& arguments); public: GuiSelectableListControl(IStyleProvider* _styleProvider, IItemProvider* _itemProvider); ~GuiSelectableListControl(); compositions::GuiNotifyEvent SelectionChanged; Ptr<GuiListControl::IItemStyleProvider> SetStyleProvider(Ptr<GuiListControl::IItemStyleProvider> value)override; bool GetMultiSelect(); void SetMultiSelect(bool value); const collections::SortedList<vint>& GetSelectedItems(); bool GetSelected(vint itemIndex); void SetSelected(vint itemIndex, bool value); bool SelectItemsByClick(vint itemIndex, bool ctrl, bool shift, bool leftButton); bool SelectItemsByKey(vint code, bool ctrl, bool shift); void ClearSelection(); }; /*********************************************************************** Predefined ItemCoordinateTransformer ***********************************************************************/ namespace list { class DefaultItemCoordinateTransformer : public Object, virtual public GuiListControl::IItemCoordinateTransformer, public Description<DefaultItemCoordinateTransformer> { public: DefaultItemCoordinateTransformer(); ~DefaultItemCoordinateTransformer(); Size RealSizeToVirtualSize(Size size)override; Size VirtualSizeToRealSize(Size size)override; Point RealPointToVirtualPoint(Size realFullSize, Point point)override; Point VirtualPointToRealPoint(Size realFullSize, Point point)override; Rect RealRectToVirtualRect(Size realFullSize, Rect rect)override; Rect VirtualRectToRealRect(Size realFullSize, Rect rect)override; Margin RealMarginToVirtualMargin(Margin margin)override; Margin VirtualMarginToRealMargin(Margin margin)override; GuiListControl::KeyDirection RealKeyDirectionToVirtualKeyDirection(GuiListControl::KeyDirection key)override; }; class AxisAlignedItemCoordinateTransformer : public Object, virtual public GuiListControl::IItemCoordinateTransformer, public Description<AxisAlignedItemCoordinateTransformer> { public: enum Alignment { LeftDown, RightDown, LeftUp, RightUp, DownLeft, DownRight, UpLeft, UpRight, }; protected: Alignment alignment; public: AxisAlignedItemCoordinateTransformer(Alignment _alignment); ~AxisAlignedItemCoordinateTransformer(); Alignment GetAlignment(); Size RealSizeToVirtualSize(Size size)override; Size VirtualSizeToRealSize(Size size)override; Point RealPointToVirtualPoint(Size realFullSize, Point point)override; Point VirtualPointToRealPoint(Size realFullSize, Point point)override; Rect RealRectToVirtualRect(Size realFullSize, Rect rect)override; Rect VirtualRectToRealRect(Size realFullSize, Rect rect)override; Margin RealMarginToVirtualMargin(Margin margin)override; Margin VirtualMarginToRealMargin(Margin margin)override; GuiListControl::KeyDirection RealKeyDirectionToVirtualKeyDirection(GuiListControl::KeyDirection key)override; }; }; /*********************************************************************** Predefined ItemArranger ***********************************************************************/ namespace list { class RangedItemArrangerBase : public Object, virtual public GuiListControl::IItemArranger, public Description<RangedItemArrangerBase> { typedef collections::List<GuiListControl::IItemStyleController*> StyleList; protected: GuiListControl::IItemArrangerCallback* callback; GuiListControl::IItemProvider* itemProvider; Rect viewBounds; vint startIndex; StyleList visibleStyles; virtual void ClearStyles(); virtual void OnStylesCleared()=0; virtual Size OnCalculateTotalSize()=0; virtual void OnViewChangedInternal(Rect oldBounds, Rect newBounds)=0; public: RangedItemArrangerBase(); ~RangedItemArrangerBase(); void OnAttached(GuiListControl::IItemProvider* provider)override; void OnItemModified(vint start, vint count, vint newCount)override; void AttachListControl(GuiListControl* value)override; void DetachListControl()override; GuiListControl::IItemArrangerCallback* GetCallback()override; void SetCallback(GuiListControl::IItemArrangerCallback* value)override; Size GetTotalSize()override; GuiListControl::IItemStyleController* GetVisibleStyle(vint itemIndex)override; vint GetVisibleIndex(GuiListControl::IItemStyleController* style)override; void OnViewChanged(Rect bounds)override; }; class FixedHeightItemArranger : public RangedItemArrangerBase, public Description<FixedHeightItemArranger> { protected: vint rowHeight; bool suppressOnViewChanged; virtual void RearrangeItemBounds(); virtual vint GetWidth(); virtual vint GetYOffset(); void OnStylesCleared()override; Size OnCalculateTotalSize()override; void OnViewChangedInternal(Rect oldBounds, Rect newBounds)override; public: FixedHeightItemArranger(); ~FixedHeightItemArranger(); vint FindItem(vint itemIndex, GuiListControl::KeyDirection key)override; bool EnsureItemVisible(vint itemIndex)override; }; class FixedSizeMultiColumnItemArranger : public RangedItemArrangerBase, public Description<FixedSizeMultiColumnItemArranger> { protected: Size itemSize; bool suppressOnViewChanged; virtual void RearrangeItemBounds(); void CalculateRange(Size itemSize, Rect bounds, vint count, vint& start, vint& end); void OnStylesCleared()override; Size OnCalculateTotalSize()override; void OnViewChangedInternal(Rect oldBounds, Rect newBounds)override; public: FixedSizeMultiColumnItemArranger(); ~FixedSizeMultiColumnItemArranger(); vint FindItem(vint itemIndex, GuiListControl::KeyDirection key)override; bool EnsureItemVisible(vint itemIndex)override; }; class FixedHeightMultiColumnItemArranger : public RangedItemArrangerBase, public Description<FixedHeightMultiColumnItemArranger> { protected: vint itemHeight; bool suppressOnViewChanged; virtual void RearrangeItemBounds(); void CalculateRange(vint itemHeight, Rect bounds, vint& rows, vint& startColumn); void OnStylesCleared()override; Size OnCalculateTotalSize()override; void OnViewChangedInternal(Rect oldBounds, Rect newBounds)override; public: FixedHeightMultiColumnItemArranger(); ~FixedHeightMultiColumnItemArranger(); vint FindItem(vint itemIndex, GuiListControl::KeyDirection key)override; bool EnsureItemVisible(vint itemIndex)override; }; } /*********************************************************************** Predefined ItemStyleController ***********************************************************************/ namespace list { class ItemStyleControllerBase : public Object, public virtual GuiListControl::IItemStyleController, public Description<ItemStyleControllerBase> { protected: GuiListControl::IItemStyleProvider* provider; vint styleId; compositions::GuiBoundsComposition* boundsComposition; GuiControl* associatedControl; bool isInstalled; void Initialize(compositions::GuiBoundsComposition* _boundsComposition, GuiControl* _associatedControl); void Finalize(); ItemStyleControllerBase(GuiListControl::IItemStyleProvider* _provider, vint _styleId); public: ~ItemStyleControllerBase(); GuiListControl::IItemStyleProvider* GetStyleProvider()override; vint GetItemStyleId()override; compositions::GuiBoundsComposition* GetBoundsComposition()override; bool IsCacheable()override; bool IsInstalled()override; void OnInstalled()override; void OnUninstalled()override; }; } /*********************************************************************** Predefined ItemProvider ***********************************************************************/ namespace list { class ItemProviderBase : public Object, public virtual GuiListControl::IItemProvider, public Description<ItemProviderBase> { protected: collections::List<GuiListControl::IItemProviderCallback*> callbacks; virtual void InvokeOnItemModified(vint start, vint count, vint newCount); public: ItemProviderBase(); ~ItemProviderBase(); bool AttachCallback(GuiListControl::IItemProviderCallback* value); bool DetachCallback(GuiListControl::IItemProviderCallback* value); }; template<typename T> class ListProvider : public ItemProviderBase, public ItemsBase<T> { protected: void NotifyUpdateInternal(vint start, vint count, vint newCount) { InvokeOnItemModified(start, count, newCount); } public: vint Count()override { return items.Count(); } }; } } } } #endif /*********************************************************************** CONTROLS\LISTCONTROLPACKAGE\GUITEXTLISTCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITEXTLISTCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUITEXTLISTCONTROLS namespace vl { namespace presentation { namespace controls { class GuiVirtualTextList; class GuiTextList; namespace list { /*********************************************************************** TextList Style Provider ***********************************************************************/ class TextItemStyleProvider : public Object, public GuiSelectableListControl::IItemStyleProvider, public Description<TextItemStyleProvider> { public: class ITextItemStyleProvider : public virtual IDescriptable, public Description<ITextItemStyleProvider> { public: virtual GuiSelectableButton::IStyleController* CreateBackgroundStyleController()=0; virtual GuiSelectableButton::IStyleController* CreateBulletStyleController()=0; }; class ITextItemView : public virtual GuiListControl::IItemPrimaryTextView, public Description<ITextItemView> { public: static const wchar_t* const Identifier; virtual WString GetText(vint itemIndex)=0; virtual bool GetChecked(vint itemIndex)=0; virtual void SetCheckedSilently(vint itemIndex, bool value)=0; }; class TextItemStyleController : public ItemStyleControllerBase, public Description<TextItemStyleController> { protected: GuiSelectableButton* backgroundButton; GuiSelectableButton* bulletButton; elements::GuiSolidLabelElement* textElement; TextItemStyleProvider* textItemStyleProvider; void OnBulletSelectedChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: TextItemStyleController(TextItemStyleProvider* provider); ~TextItemStyleController(); bool GetSelected(); void SetSelected(bool value); bool GetChecked(); void SetChecked(bool value); const WString& GetText(); void SetText(const WString& value); }; protected: Ptr<ITextItemStyleProvider> textItemStyleProvider; ITextItemView* textItemView; GuiVirtualTextList* listControl; void OnStyleCheckedChanged(TextItemStyleController* style); public: TextItemStyleProvider(ITextItemStyleProvider* _textItemStyleProvider); ~TextItemStyleProvider(); void AttachListControl(GuiListControl* value)override; void DetachListControl()override; vint GetItemStyleId(vint itemIndex)override; GuiListControl::IItemStyleController* CreateItemStyle(vint styleId)override; void DestroyItemStyle(GuiListControl::IItemStyleController* style)override; void Install(GuiListControl::IItemStyleController* style, vint itemIndex)override; void SetStyleSelected(GuiListControl::IItemStyleController* style, bool value)override; }; /*********************************************************************** TextList Data Source ***********************************************************************/ class TextItem : public Object, public Description<TextItem> { friend class TextItemProvider; protected: WString text; bool checked; public: TextItem(); TextItem(const WString& _text, bool _checked=false); ~TextItem(); bool operator==(const TextItem& value)const; bool operator!=(const TextItem& value)const; const WString& GetText(); bool GetChecked(); }; class TextItemProvider : public ListProvider<Ptr<TextItem>>, protected TextItemStyleProvider::ITextItemView, public Description<TextItemProvider> { friend class GuiTextList; protected: GuiTextList* listControl; bool ContainsPrimaryText(vint itemIndex)override; WString GetPrimaryTextViewText(vint itemIndex)override; WString GetText(vint itemIndex)override; bool GetChecked(vint itemIndex)override; void SetCheckedSilently(vint itemIndex, bool value)override; public: TextItemProvider(); ~TextItemProvider(); void SetText(vint itemIndex, const WString& value); void SetChecked(vint itemIndex, bool value); IDescriptable* RequestView(const WString& identifier)override; void ReleaseView(IDescriptable* view)override; }; } /*********************************************************************** TextList Control ***********************************************************************/ class GuiVirtualTextList : public GuiSelectableListControl, public Description<GuiVirtualTextList> { public: GuiVirtualTextList(IStyleProvider* _styleProvider, list::TextItemStyleProvider::ITextItemStyleProvider* _itemStyleProvider, GuiListControl::IItemProvider* _itemProvider); ~GuiVirtualTextList(); compositions::GuiItemNotifyEvent ItemChecked; Ptr<GuiListControl::IItemStyleProvider> SetStyleProvider(Ptr<GuiListControl::IItemStyleProvider> value)override; Ptr<GuiListControl::IItemStyleProvider> ChangeItemStyle(list::TextItemStyleProvider::ITextItemStyleProvider* itemStyleProvider); }; class GuiTextList : public GuiVirtualTextList, public Description<GuiTextList> { protected: list::TextItemProvider* items; public: GuiTextList(IStyleProvider* _styleProvider, list::TextItemStyleProvider::ITextItemStyleProvider* _itemStyleProvider); ~GuiTextList(); list::TextItemProvider& GetItems(); }; } } } #endif /*********************************************************************** CONTROLS\TOOLSTRIPPACKAGE\GUIMENUCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIMENUCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUIMENUCONTROLS namespace vl { namespace presentation { namespace controls { /*********************************************************************** Menu Service ***********************************************************************/ class GuiMenu; class IGuiMenuService : public virtual IDescriptable, public Description<IGuiMenuService> { public: static const wchar_t* const Identifier; enum Direction { Horizontal, Vertical, }; protected: GuiMenu* openingMenu; public: IGuiMenuService(); virtual IGuiMenuService* GetParentMenuService()=0; virtual Direction GetPreferredDirection()=0; virtual bool IsActiveState()=0; virtual bool IsSubMenuActivatedByMouseDown()=0; virtual void MenuItemExecuted(); virtual GuiMenu* GetOpeningMenu(); virtual void MenuOpened(GuiMenu* menu); virtual void MenuClosed(GuiMenu* menu); }; /*********************************************************************** Menu ***********************************************************************/ class GuiMenu : public GuiPopup, private IGuiMenuService, public Description<GuiMenu> { private: IGuiMenuService* parentMenuService; IGuiMenuService* GetParentMenuService()override; Direction GetPreferredDirection()override; bool IsActiveState()override; bool IsSubMenuActivatedByMouseDown()override; void MenuItemExecuted()override; protected: GuiControl* owner; void MouseClickedOnOtherWindow(GuiWindow* window)override; void OnWindowOpened(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnWindowClosed(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: GuiMenu(IStyleController* _styleController, GuiControl* _owner); ~GuiMenu(); void UpdateMenuService(); IDescriptable* QueryService(const WString& identifier)override; }; class GuiMenuBar : public GuiControl, private IGuiMenuService, public Description<GuiMenuBar> { private: IGuiMenuService* GetParentMenuService()override; Direction GetPreferredDirection()override; bool IsActiveState()override; bool IsSubMenuActivatedByMouseDown()override; public: GuiMenuBar(GuiControl::IStyleController* _styleController); ~GuiMenuBar(); IDescriptable* QueryService(const WString& identifier)override; }; /*********************************************************************** MenuButton ***********************************************************************/ class GuiMenuButton : public GuiButton, public Description<GuiMenuButton> { public: static const wchar_t* const MenuItemSubComponentMeasuringCategoryName; class IStyleController : public virtual GuiButton::IStyleController, public Description<IStyleController> { public: virtual GuiMenu::IStyleController* CreateSubMenuStyleController()=0; virtual void SetSubMenuExisting(bool value)=0; virtual void SetSubMenuOpening(bool value)=0; virtual GuiButton* GetSubMenuHost()=0; virtual void SetImage(Ptr<GuiImageData> value)=0; virtual void SetShortcutText(const WString& value)=0; virtual compositions::GuiSubComponentMeasurer::IMeasuringSource* GetMeasuringSource()=0; }; protected: IStyleController* styleController; Ptr<GuiImageData> image; WString shortcutText; GuiMenu* subMenu; bool ownedSubMenu; Size preferredMenuClientSize; IGuiMenuService* ownerMenuService; bool cascadeAction; GuiButton* GetSubMenuHost(); void OpenSubMenuInternal(); void OnParentLineChanged()override; void OnSubMenuWindowOpened(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnSubMenuWindowClosed(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnMouseEnter(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnClicked(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); virtual IGuiMenuService::Direction GetSubMenuDirection(); public: GuiMenuButton(IStyleController* _styleController); ~GuiMenuButton(); compositions::GuiNotifyEvent SubMenuOpeningChanged; compositions::GuiNotifyEvent ImageChanged; compositions::GuiNotifyEvent ShortcutTextChanged; Ptr<GuiImageData> GetImage(); void SetImage(Ptr<GuiImageData> value); const WString& GetShortcutText(); void SetShortcutText(const WString& value); bool IsSubMenuExists(); GuiMenu* GetSubMenu(); void CreateSubMenu(GuiMenu::IStyleController* subMenuStyleController=0); void SetSubMenu(GuiMenu* value, bool owned); void DestroySubMenu(); bool GetOwnedSubMenu(); bool GetSubMenuOpening(); void SetSubMenuOpening(bool value); Size GetPreferredMenuClientSize(); void SetPreferredMenuClientSize(Size value); bool GetCascadeAction(); void SetCascadeAction(bool value); }; } } } #endif /*********************************************************************** CONTROLS\LISTCONTROLPACKAGE\GUILISTVIEWCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUILISTVIEWCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUILISTVIEWCONTROLS namespace vl { namespace presentation { namespace controls { class GuiListViewBase; namespace list { /*********************************************************************** ListView Base ***********************************************************************/ class ListViewItemStyleProviderBase: public Object, public GuiSelectableListControl::IItemStyleProvider, public Description<ListViewItemStyleProviderBase> { public: class ListViewItemStyleController : public ItemStyleControllerBase, public Description<ListViewItemStyleController> { protected: GuiSelectableButton* backgroundButton; ListViewItemStyleProviderBase* listViewItemStyleProvider; public: ListViewItemStyleController(ListViewItemStyleProviderBase* provider); ~ListViewItemStyleController(); bool GetSelected(); void SetSelected(bool value); }; protected: GuiListViewBase* listControl; public: ListViewItemStyleProviderBase(); ~ListViewItemStyleProviderBase(); void AttachListControl(GuiListControl* value)override; void DetachListControl()override; vint GetItemStyleId(vint itemIndex)override; void SetStyleSelected(GuiListControl::IItemStyleController* style, bool value)override; }; } class GuiListViewColumnHeader : public GuiMenuButton, public Description<GuiListViewColumnHeader> { public: enum ColumnSortingState { NotSorted, Ascending, Descending, }; class IStyleController : public virtual GuiMenuButton::IStyleController, public Description<IStyleController> { public: virtual void SetColumnSortingState(ColumnSortingState value)=0; }; protected: IStyleController* styleController; ColumnSortingState columnSortingState; public: GuiListViewColumnHeader(IStyleController* _styleController); ~GuiListViewColumnHeader(); ColumnSortingState GetColumnSortingState(); void SetColumnSortingState(ColumnSortingState value); }; class GuiListViewBase : public GuiSelectableListControl, public Description<GuiListViewBase> { public: class IStyleProvider : public virtual GuiSelectableListControl::IStyleProvider, public Description<IStyleProvider> { public: virtual GuiSelectableButton::IStyleController* CreateItemBackground()=0; virtual GuiListViewColumnHeader::IStyleController* CreateColumnStyle()=0; virtual Color GetPrimaryTextColor()=0; virtual Color GetSecondaryTextColor()=0; virtual Color GetItemSeparatorColor()=0; }; protected: IStyleProvider* styleProvider; public: GuiListViewBase(IStyleProvider* _styleProvider, GuiListControl::IItemProvider* _itemProvider); ~GuiListViewBase(); compositions::GuiItemNotifyEvent ColumnClicked; IStyleProvider* GetListViewStyleProvider(); Ptr<GuiListControl::IItemStyleProvider> SetStyleProvider(Ptr<GuiListControl::IItemStyleProvider> value)override; }; /*********************************************************************** ListView ItemStyleProvider ***********************************************************************/ namespace list { class ListViewItemStyleProvider : public ListViewItemStyleProviderBase, public Description<ListViewItemStyleProvider> { public: class IListViewItemView : public virtual GuiListControl::IItemPrimaryTextView, public Description<IListViewItemView> { public: static const wchar_t* const Identifier; virtual Ptr<GuiImageData> GetSmallImage(vint itemIndex)=0; virtual Ptr<GuiImageData> GetLargeImage(vint itemIndex)=0; virtual WString GetText(vint itemIndex)=0; virtual WString GetSubItem(vint itemIndex, vint index)=0; virtual vint GetDataColumnCount()=0; virtual vint GetDataColumn(vint index)=0; virtual vint GetColumnCount()=0; virtual WString GetColumnText(vint index)=0; }; class IListViewItemContent : public virtual IDescriptable, public Description<IListViewItemContent> { public: virtual compositions::GuiBoundsComposition* GetContentComposition()=0; virtual compositions::GuiBoundsComposition* GetBackgroundDecorator()=0; virtual void Install(GuiListViewBase::IStyleProvider* styleProvider, IListViewItemView* view, vint itemIndex)=0; virtual void Uninstall()=0; }; class IListViewItemContentProvider : public virtual IDescriptable, public Description<IListViewItemContentProvider> { public: virtual GuiListControl::IItemCoordinateTransformer* CreatePreferredCoordinateTransformer()=0; virtual GuiListControl::IItemArranger* CreatePreferredArranger()=0; virtual IListViewItemContent* CreateItemContent(const FontProperties& font)=0; virtual void AttachListControl(GuiListControl* value)=0; virtual void DetachListControl()=0; }; class ListViewContentItemStyleController : public ListViewItemStyleController, public Description<ListViewContentItemStyleController> { protected: ListViewItemStyleProvider* listViewItemStyleProvider; Ptr<IListViewItemContent> content; public: ListViewContentItemStyleController(ListViewItemStyleProvider* provider); ~ListViewContentItemStyleController(); void OnUninstalled()override; IListViewItemContent* GetItemContent(); void Install(IListViewItemView* view, vint itemIndex); }; protected: typedef collections::List<GuiListControl::IItemStyleController*> ItemStyleList; IListViewItemView* listViewItemView; Ptr<IListViewItemContentProvider> listViewItemContentProvider; ItemStyleList itemStyles; public: ListViewItemStyleProvider(Ptr<IListViewItemContentProvider> itemContentProvider); ~ListViewItemStyleProvider(); void AttachListControl(GuiListControl* value)override; void DetachListControl()override; GuiListControl::IItemStyleController* CreateItemStyle(vint styleId)override; void DestroyItemStyle(GuiListControl::IItemStyleController* style)override; void Install(GuiListControl::IItemStyleController* style, vint itemIndex)override; IListViewItemContentProvider* GetItemContentProvider(); const ItemStyleList& GetCreatedItemStyles(); bool IsItemStyleAttachedToListView(GuiListControl::IItemStyleController* itemStyle); IListViewItemContent* GetItemContentFromItemStyleController(GuiListControl::IItemStyleController* itemStyleController); GuiListControl::IItemStyleController* GetItemStyleControllerFromItemContent(IListViewItemContent* itemContent); template<typename T> T* GetItemContent(GuiListControl::IItemStyleController* itemStyleController) { return dynamic_cast<T*>(GetItemContentFromItemStyleController(itemStyleController)); } }; } /*********************************************************************** ListView ItemContentProvider ***********************************************************************/ namespace list { class ListViewBigIconContentProvider : public Object, public virtual ListViewItemStyleProvider::IListViewItemContentProvider, public Description<ListViewBigIconContentProvider> { protected: class ItemContent : public Object, public virtual ListViewItemStyleProvider::IListViewItemContent { protected: compositions::GuiBoundsComposition* contentComposition; elements::GuiImageFrameElement* image; elements::GuiSolidLabelElement* text; public: ItemContent(Size iconSize, const FontProperties& font); ~ItemContent(); compositions::GuiBoundsComposition* GetContentComposition()override; compositions::GuiBoundsComposition* GetBackgroundDecorator()override; void Install(GuiListViewBase::IStyleProvider* styleProvider, ListViewItemStyleProvider::IListViewItemView* view, vint itemIndex)override; void Uninstall()override; }; Size iconSize; public: ListViewBigIconContentProvider(Size _iconSize=Size(32, 32)); ~ListViewBigIconContentProvider(); GuiListControl::IItemCoordinateTransformer* CreatePreferredCoordinateTransformer()override; GuiListControl::IItemArranger* CreatePreferredArranger()override; ListViewItemStyleProvider::IListViewItemContent* CreateItemContent(const FontProperties& font)override; void AttachListControl(GuiListControl* value)override; void DetachListControl()override; }; class ListViewSmallIconContentProvider : public Object, public virtual ListViewItemStyleProvider::IListViewItemContentProvider, public Description<ListViewSmallIconContentProvider> { protected: class ItemContent : public Object, public virtual ListViewItemStyleProvider::IListViewItemContent { protected: compositions::GuiBoundsComposition* contentComposition; elements::GuiImageFrameElement* image; elements::GuiSolidLabelElement* text; public: ItemContent(Size iconSize, const FontProperties& font); ~ItemContent(); compositions::GuiBoundsComposition* GetContentComposition()override; compositions::GuiBoundsComposition* GetBackgroundDecorator()override; void Install(GuiListViewBase::IStyleProvider* styleProvider, ListViewItemStyleProvider::IListViewItemView* view, vint itemIndex)override; void Uninstall()override; }; Size iconSize; public: ListViewSmallIconContentProvider(Size _iconSize=Size(16, 16)); ~ListViewSmallIconContentProvider(); GuiListControl::IItemCoordinateTransformer* CreatePreferredCoordinateTransformer()override; GuiListControl::IItemArranger* CreatePreferredArranger()override; ListViewItemStyleProvider::IListViewItemContent* CreateItemContent(const FontProperties& font)override; void AttachListControl(GuiListControl* value)override; void DetachListControl()override; }; class ListViewListContentProvider : public Object, public virtual ListViewItemStyleProvider::IListViewItemContentProvider, public Description<ListViewListContentProvider> { protected: class ItemContent : public Object, public virtual ListViewItemStyleProvider::IListViewItemContent { protected: compositions::GuiBoundsComposition* contentComposition; elements::GuiImageFrameElement* image; elements::GuiSolidLabelElement* text; public: ItemContent(Size iconSize, const FontProperties& font); ~ItemContent(); compositions::GuiBoundsComposition* GetContentComposition()override; compositions::GuiBoundsComposition* GetBackgroundDecorator()override; void Install(GuiListViewBase::IStyleProvider* styleProvider, ListViewItemStyleProvider::IListViewItemView* view, vint itemIndex)override; void Uninstall()override; }; Size iconSize; public: ListViewListContentProvider(Size _iconSize=Size(16, 16)); ~ListViewListContentProvider(); GuiListControl::IItemCoordinateTransformer* CreatePreferredCoordinateTransformer()override; GuiListControl::IItemArranger* CreatePreferredArranger()override; ListViewItemStyleProvider::IListViewItemContent* CreateItemContent(const FontProperties& font)override; void AttachListControl(GuiListControl* value)override; void DetachListControl()override; }; class ListViewTileContentProvider : public Object, public virtual ListViewItemStyleProvider::IListViewItemContentProvider, public Description<ListViewTileContentProvider> { protected: class ItemContent : public Object, public virtual ListViewItemStyleProvider::IListViewItemContent { typedef collections::Array<elements::GuiSolidLabelElement*> DataTextElementArray; protected: compositions::GuiBoundsComposition* contentComposition; elements::GuiImageFrameElement* image; elements::GuiSolidLabelElement* text; compositions::GuiTableComposition* textTable; DataTextElementArray dataTexts; void RemoveTextElement(vint textRow); elements::GuiSolidLabelElement* CreateTextElement(vint textRow, const FontProperties& font); void ResetTextTable(vint textRows); public: ItemContent(Size iconSize, const FontProperties& font); ~ItemContent(); compositions::GuiBoundsComposition* GetContentComposition()override; compositions::GuiBoundsComposition* GetBackgroundDecorator()override; void Install(GuiListViewBase::IStyleProvider* styleProvider, ListViewItemStyleProvider::IListViewItemView* view, vint itemIndex)override; void Uninstall()override; }; Size iconSize; public: ListViewTileContentProvider(Size _iconSize=Size(32, 32)); ~ListViewTileContentProvider(); GuiListControl::IItemCoordinateTransformer* CreatePreferredCoordinateTransformer()override; GuiListControl::IItemArranger* CreatePreferredArranger()override; ListViewItemStyleProvider::IListViewItemContent* CreateItemContent(const FontProperties& font)override; void AttachListControl(GuiListControl* value)override; void DetachListControl()override; }; class ListViewInformationContentProvider : public Object, public virtual ListViewItemStyleProvider::IListViewItemContentProvider, public Description<ListViewInformationContentProvider> { protected: class ItemContent : public Object, public virtual ListViewItemStyleProvider::IListViewItemContent { typedef collections::Array<elements::GuiSolidLabelElement*> DataTextElementArray; protected: FontProperties baselineFont; compositions::GuiBoundsComposition* contentComposition; elements::GuiImageFrameElement* image; elements::GuiSolidLabelElement* text; compositions::GuiTableComposition* textTable; DataTextElementArray dataTexts; elements::GuiSolidBackgroundElement* bottomLine; compositions::GuiBoundsComposition* bottomLineComposition; public: ItemContent(Size iconSize, const FontProperties& font); ~ItemContent(); compositions::GuiBoundsComposition* GetContentComposition()override; compositions::GuiBoundsComposition* GetBackgroundDecorator()override; void Install(GuiListViewBase::IStyleProvider* styleProvider, ListViewItemStyleProvider::IListViewItemView* view, vint itemIndex)override; void Uninstall()override; }; Size iconSize; public: ListViewInformationContentProvider(Size _iconSize=Size(32, 32)); ~ListViewInformationContentProvider(); GuiListControl::IItemCoordinateTransformer* CreatePreferredCoordinateTransformer()override; GuiListControl::IItemArranger* CreatePreferredArranger()override; ListViewItemStyleProvider::IListViewItemContent* CreateItemContent(const FontProperties& font)override; void AttachListControl(GuiListControl* value)override; void DetachListControl()override; }; /*********************************************************************** ListView ItemContentProvider(Detailed) ***********************************************************************/ class ListViewColumnItemArranger : public FixedHeightItemArranger, public Description<ListViewColumnItemArranger> { typedef collections::List<GuiListViewColumnHeader*> ColumnHeaderButtonList; typedef collections::List<compositions::GuiBoundsComposition*> ColumnHeaderSplitterList; public: static const vint SplitterWidth=8; class IColumnItemViewCallback : public virtual IDescriptable, public Description<IColumnItemViewCallback> { public: virtual void OnColumnChanged()=0; }; class IColumnItemView : public virtual IDescriptable, public Description<IColumnItemView> { public: static const wchar_t* const Identifier; virtual bool AttachCallback(IColumnItemViewCallback* value)=0; virtual bool DetachCallback(IColumnItemViewCallback* value)=0; virtual vint GetColumnCount()=0; virtual WString GetColumnText(vint index)=0; virtual vint GetColumnSize(vint index)=0; virtual void SetColumnSize(vint index, vint value)=0; virtual GuiMenu* GetDropdownPopup(vint index)=0; virtual GuiListViewColumnHeader::ColumnSortingState GetSortingState(vint index)=0; }; protected: class ColumnItemViewCallback : public Object, public virtual IColumnItemViewCallback { protected: ListViewColumnItemArranger* arranger; public: ColumnItemViewCallback(ListViewColumnItemArranger* _arranger); ~ColumnItemViewCallback(); void OnColumnChanged(); }; GuiListViewBase* listView; GuiListViewBase::IStyleProvider* styleProvider; IColumnItemView* columnItemView; Ptr<ColumnItemViewCallback> columnItemViewCallback; compositions::GuiStackComposition* columnHeaders; ColumnHeaderButtonList columnHeaderButtons; ColumnHeaderSplitterList columnHeaderSplitters; bool splitterDragging; vint splitterLatestX; void ColumnClicked(vint index, compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void ColumnBoundsChanged(vint index, compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void ColumnHeaderSplitterLeftButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void ColumnHeaderSplitterLeftButtonUp(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void ColumnHeaderSplitterMouseMove(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void RearrangeItemBounds()override; vint GetWidth()override; vint GetYOffset()override; Size OnCalculateTotalSize()override; void DeleteColumnButtons(); void RebuildColumns(); public: ListViewColumnItemArranger(); ~ListViewColumnItemArranger(); void AttachListControl(GuiListControl* value)override; void DetachListControl()override; }; class ListViewDetailContentProvider : public Object , public virtual ListViewItemStyleProvider::IListViewItemContentProvider , protected virtual ListViewColumnItemArranger::IColumnItemViewCallback , public Description<ListViewDetailContentProvider> { protected: class ItemContent : public Object, public virtual ListViewItemStyleProvider::IListViewItemContent { typedef collections::List<elements::GuiSolidLabelElement*> SubItemList; protected: compositions::GuiBoundsComposition* contentComposition; elements::GuiImageFrameElement* image; elements::GuiSolidLabelElement* text; compositions::GuiTableComposition* textTable; SubItemList subItems; GuiListControl::IItemProvider* itemProvider; ListViewColumnItemArranger::IColumnItemView* columnItemView; public: ItemContent(Size iconSize, const FontProperties& font, GuiListControl::IItemProvider* _itemProvider); ~ItemContent(); compositions::GuiBoundsComposition* GetContentComposition()override; compositions::GuiBoundsComposition* GetBackgroundDecorator()override; void UpdateSubItemSize(); void Install(GuiListViewBase::IStyleProvider* styleProvider, ListViewItemStyleProvider::IListViewItemView* view, vint itemIndex)override; void Uninstall()override; }; Size iconSize; GuiListControl::IItemProvider* itemProvider; ListViewColumnItemArranger::IColumnItemView* columnItemView; ListViewItemStyleProvider* listViewItemStyleProvider; void OnColumnChanged()override; public: ListViewDetailContentProvider(Size _iconSize=Size(16, 16)); ~ListViewDetailContentProvider(); GuiListControl::IItemCoordinateTransformer* CreatePreferredCoordinateTransformer()override; GuiListControl::IItemArranger* CreatePreferredArranger()override; ListViewItemStyleProvider::IListViewItemContent* CreateItemContent(const FontProperties& font)override; void AttachListControl(GuiListControl* value)override; void DetachListControl()override; }; } /*********************************************************************** ListView ***********************************************************************/ namespace list { class ListViewItem : public Object, public Description<ListViewItem> { public: Ptr<GuiImageData> smallImage; Ptr<GuiImageData> largeImage; WString text; collections::List<WString> subItems; Ptr<Object> tag; }; class ListViewColumn : public Object, public Description<ListViewColumn> { public: WString text; vint size; GuiMenu* dropdownPopup; GuiListViewColumnHeader::ColumnSortingState sortingState; ListViewColumn(const WString& _text=L"", vint _size=160); }; class ListViewDataColumns : public ItemsBase<vint> { friend class ListViewItemProvider; protected: ListViewItemProvider* itemProvider; void NotifyUpdateInternal(vint start, vint count, vint newCount)override; public: ListViewDataColumns(); ~ListViewDataColumns(); }; class ListViewColumns : public ItemsBase<Ptr<ListViewColumn>> { friend class ListViewItemProvider; protected: ListViewItemProvider* itemProvider; void NotifyUpdateInternal(vint start, vint count, vint newCount)override; public: ListViewColumns(); ~ListViewColumns(); }; class ListViewItemProvider : public ListProvider<Ptr<ListViewItem>> , protected virtual ListViewItemStyleProvider::IListViewItemView , protected virtual ListViewColumnItemArranger::IColumnItemView , public Description<ListViewItemProvider> { friend class ListViewColumns; friend class ListViewDataColumns; typedef collections::List<ListViewColumnItemArranger::IColumnItemViewCallback*> ColumnItemViewCallbackList; protected: ListViewDataColumns dataColumns; ListViewColumns columns; ColumnItemViewCallbackList columnItemViewCallbacks; bool ContainsPrimaryText(vint itemIndex)override; WString GetPrimaryTextViewText(vint itemIndex)override; Ptr<GuiImageData> GetSmallImage(vint itemIndex)override; Ptr<GuiImageData> GetLargeImage(vint itemIndex)override; WString GetText(vint itemIndex)override; WString GetSubItem(vint itemIndex, vint index)override; vint GetDataColumnCount()override; vint GetDataColumn(vint index)override; bool AttachCallback(ListViewColumnItemArranger::IColumnItemViewCallback* value)override; bool DetachCallback(ListViewColumnItemArranger::IColumnItemViewCallback* value)override; vint GetColumnCount()override; WString GetColumnText(vint index)override; vint GetColumnSize(vint index)override; void SetColumnSize(vint index, vint value)override; GuiMenu* GetDropdownPopup(vint index)override; GuiListViewColumnHeader::ColumnSortingState GetSortingState(vint index)override; public: ListViewItemProvider(); ~ListViewItemProvider(); IDescriptable* RequestView(const WString& identifier)override; void ReleaseView(IDescriptable* view)override; ListViewDataColumns& GetDataColumns(); ListViewColumns& GetColumns(); }; } class GuiVirtualListView : public GuiListViewBase, public Description<GuiVirtualListView> { public: GuiVirtualListView(IStyleProvider* _styleProvider, GuiListControl::IItemProvider* _itemProvider); ~GuiVirtualListView(); virtual bool ChangeItemStyle(Ptr<list::ListViewItemStyleProvider::IListViewItemContentProvider> contentProvider); }; class GuiListView : public GuiVirtualListView, public Description<GuiListView> { protected: list::ListViewItemProvider* items; public: GuiListView(IStyleProvider* _styleProvider); ~GuiListView(); list::ListViewItemProvider& GetItems(); }; } } } #endif /*********************************************************************** CONTROLS\LISTCONTROLPACKAGE\GUITREEVIEWCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITREEVIEWCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUITREEVIEWCONTROLS namespace vl { namespace presentation { namespace controls { /*********************************************************************** GuiVirtualTreeListControl NodeProvider ***********************************************************************/ namespace tree { class INodeProvider; class INodeRootProvider; //----------------------------------------------------------- // Callback Interfaces //----------------------------------------------------------- class INodeProviderCallback : public virtual IDescriptable, public Description<INodeProviderCallback> { public: virtual void OnAttached(INodeRootProvider* provider)=0; virtual void OnBeforeItemModified(INodeProvider* parentNode, vint start, vint count, vint newCount)=0; virtual void OnAfterItemModified(INodeProvider* parentNode, vint start, vint count, vint newCount)=0; virtual void OnItemExpanded(INodeProvider* node)=0; virtual void OnItemCollapsed(INodeProvider* node)=0; }; //----------------------------------------------------------- // Provider Interfaces //----------------------------------------------------------- class INodeProvider : public virtual IDescriptable, public Description<INodeProvider> { public: virtual bool GetExpanding()=0; virtual void SetExpanding(bool value)=0; virtual vint CalculateTotalVisibleNodes()=0; virtual vint GetChildCount()=0; virtual INodeProvider* GetParent()=0; virtual INodeProvider* GetChild(vint index)=0; virtual void Increase()=0; virtual void Release()=0; }; class INodeRootProvider : public virtual IDescriptable, public Description<INodeRootProvider> { public: virtual INodeProvider* GetRootNode()=0; virtual bool CanGetNodeByVisibleIndex()=0; virtual INodeProvider* GetNodeByVisibleIndex(vint index)=0; virtual bool AttachCallback(INodeProviderCallback* value)=0; virtual bool DetachCallback(INodeProviderCallback* value)=0; virtual IDescriptable* RequestView(const WString& identifier)=0; virtual void ReleaseView(IDescriptable* view)=0; }; } namespace tree { //----------------------------------------------------------- // Tree to ListControl (IItemProvider) //----------------------------------------------------------- class INodeItemView : public virtual GuiListControl::IItemPrimaryTextView, public Description<INodeItemView> { public: static const wchar_t* const Identifier; virtual INodeProvider* RequestNode(vint index)=0; virtual void ReleaseNode(INodeProvider* node)=0; virtual vint CalculateNodeVisibilityIndex(INodeProvider* node)=0; }; class INodeItemPrimaryTextView : public virtual IDescriptable, public Description<INodeItemPrimaryTextView> { public: static const wchar_t* const Identifier; virtual WString GetPrimaryTextViewText(INodeProvider* node)=0; }; class NodeItemProvider : public list::ItemProviderBase , protected virtual INodeProviderCallback , protected virtual INodeItemView , public Description<NodeItemProvider> { protected: Ptr<INodeRootProvider> root; INodeItemPrimaryTextView* nodeItemPrimaryTextView; vint offsetBeforeChildModified; INodeProvider* GetNodeByOffset(INodeProvider* provider, vint offset); void OnAttached(INodeRootProvider* provider)override; void OnBeforeItemModified(INodeProvider* parentNode, vint start, vint count, vint newCount)override; void OnAfterItemModified(INodeProvider* parentNode, vint start, vint count, vint newCount)override; void OnItemExpanded(INodeProvider* node)override; void OnItemCollapsed(INodeProvider* node)override; vint CalculateNodeVisibilityIndexInternal(INodeProvider* node); vint CalculateNodeVisibilityIndex(INodeProvider* node)override; bool ContainsPrimaryText(vint itemIndex)override; WString GetPrimaryTextViewText(vint itemIndex)override; INodeProvider* RequestNode(vint index)override; void ReleaseNode(INodeProvider* node)override; public: NodeItemProvider(Ptr<INodeRootProvider> _root); ~NodeItemProvider(); Ptr<INodeRootProvider> GetRoot(); vint Count()override; IDescriptable* RequestView(const WString& identifier)override; void ReleaseView(IDescriptable* view)override; }; //----------------------------------------------------------- // Tree to ListControl (IItemStyleProvider) //----------------------------------------------------------- class INodeItemStyleProvider; class INodeItemStyleController : public virtual GuiListControl::IItemStyleController, public Description<INodeItemStyleController> { public: virtual INodeItemStyleProvider* GetNodeStyleProvider()=0; }; class INodeItemStyleProvider : public virtual IDescriptable, public Description<INodeItemStyleProvider> { public: virtual void BindItemStyleProvider(GuiListControl::IItemStyleProvider* styleProvider)=0; virtual GuiListControl::IItemStyleProvider* GetBindedItemStyleProvider()=0; virtual void AttachListControl(GuiListControl* value)=0; virtual void DetachListControl()=0; virtual vint GetItemStyleId(INodeProvider* node)=0; virtual INodeItemStyleController* CreateItemStyle(vint styleId)=0; virtual void DestroyItemStyle(INodeItemStyleController* style)=0; virtual void Install(INodeItemStyleController* style, INodeProvider* node)=0; virtual void SetStyleSelected(INodeItemStyleController* style, bool value)=0; }; class NodeItemStyleProvider : public Object, public virtual GuiSelectableListControl::IItemStyleProvider, public Description<NodeItemStyleProvider> { protected: Ptr<INodeItemStyleProvider> nodeItemStyleProvider; GuiListControl* listControl; INodeItemView* nodeItemView; public: NodeItemStyleProvider(Ptr<INodeItemStyleProvider> provider); ~NodeItemStyleProvider(); void AttachListControl(GuiListControl* value)override; void DetachListControl()override; vint GetItemStyleId(vint itemIndex)override; GuiListControl::IItemStyleController* CreateItemStyle(vint styleId)override; void DestroyItemStyle(GuiListControl::IItemStyleController* style)override; void Install(GuiListControl::IItemStyleController* style, vint itemIndex)override; void SetStyleSelected(GuiListControl::IItemStyleController* style, bool value)override; }; } /*********************************************************************** GuiVirtualTreeListControl Predefined NodeProvider ***********************************************************************/ namespace tree { class IMemoryNodeData : public virtual IDescriptable, public Description<IMemoryNodeData> { }; class MemoryNodeProvider : public Object , public virtual INodeProvider , public Description<MemoryNodeProvider> { typedef collections::List<Ptr<MemoryNodeProvider>> ChildList; typedef collections::IEnumerator<Ptr<MemoryNodeProvider>> ChildListEnumerator; public: class NodeCollection : public list::ItemsBase<Ptr<MemoryNodeProvider>> { friend class MemoryNodeProvider; protected: MemoryNodeProvider* ownerProvider; void OnBeforeChildModified(vint start, vint count, vint newCount); void OnAfterChildModified(vint start, vint count, vint newCount); bool InsertInternal(vint index, Ptr<MemoryNodeProvider> const& child)override; bool RemoveAtInternal(vint index, Ptr<MemoryNodeProvider> const& child)override; NodeCollection(); public: }; protected: MemoryNodeProvider* parent; bool expanding; vint childCount; vint totalVisibleNodeCount; vint offsetBeforeChildModified; Ptr<IMemoryNodeData> data; NodeCollection children; virtual INodeProviderCallback* GetCallbackProxyInternal(); void OnChildTotalVisibleNodesChanged(vint offset); public: MemoryNodeProvider(); MemoryNodeProvider(const Ptr<IMemoryNodeData>& _data); ~MemoryNodeProvider(); Ptr<IMemoryNodeData> GetData(); void SetData(const Ptr<IMemoryNodeData>& value); void NotifyDataModified(); NodeCollection& Children(); bool GetExpanding()override; void SetExpanding(bool value)override; vint CalculateTotalVisibleNodes()override; vint GetChildCount()override; INodeProvider* GetParent()override; INodeProvider* GetChild(vint index)override; void Increase()override; void Release()override; }; class NodeRootProviderBase : public virtual INodeRootProvider, protected virtual INodeProviderCallback, public Description<NodeRootProviderBase> { collections::List<INodeProviderCallback*> callbacks; protected: void OnAttached(INodeRootProvider* provider)override; void OnBeforeItemModified(INodeProvider* parentNode, vint start, vint count, vint newCount)override; void OnAfterItemModified(INodeProvider* parentNode, vint start, vint count, vint newCount)override; void OnItemExpanded(INodeProvider* node)override; void OnItemCollapsed(INodeProvider* node)override; public: NodeRootProviderBase(); ~NodeRootProviderBase(); bool CanGetNodeByVisibleIndex()override; INodeProvider* GetNodeByVisibleIndex(vint index)override; bool AttachCallback(INodeProviderCallback* value)override; bool DetachCallback(INodeProviderCallback* value)override; IDescriptable* RequestView(const WString& identifier)override; void ReleaseView(IDescriptable* view)override; }; class MemoryNodeRootProvider : public MemoryNodeProvider , public NodeRootProviderBase , public Description<MemoryNodeRootProvider> { protected: INodeProviderCallback* GetCallbackProxyInternal()override; public: MemoryNodeRootProvider(); ~MemoryNodeRootProvider(); INodeProvider* GetRootNode()override; MemoryNodeProvider* GetMemoryNode(INodeProvider* node); }; } /*********************************************************************** GuiVirtualTreeListControl ***********************************************************************/ class GuiVirtualTreeListControl : public GuiSelectableListControl, private virtual tree::INodeProviderCallback, public Description<GuiVirtualTreeListControl> { private: void OnAttached(tree::INodeRootProvider* provider)override; void OnBeforeItemModified(tree::INodeProvider* parentNode, vint start, vint count, vint newCount)override; void OnAfterItemModified(tree::INodeProvider* parentNode, vint start, vint count, vint newCount)override; void OnItemExpanded(tree::INodeProvider* node)override; void OnItemCollapsed(tree::INodeProvider* node)override; protected: tree::NodeItemProvider* nodeItemProvider; tree::INodeItemView* nodeItemView; Ptr<tree::INodeItemStyleProvider> nodeStyleProvider; void OnItemMouseEvent(compositions::GuiNodeMouseEvent& nodeEvent, compositions::GuiGraphicsComposition* sender, compositions::GuiItemMouseEventArgs& arguments); void OnItemNotifyEvent(compositions::GuiNodeNotifyEvent& nodeEvent, compositions::GuiGraphicsComposition* sender, compositions::GuiItemEventArgs& arguments); public: GuiVirtualTreeListControl(IStyleProvider* _styleProvider, Ptr<tree::INodeRootProvider> _nodeRootProvider); ~GuiVirtualTreeListControl(); compositions::GuiNodeMouseEvent NodeLeftButtonDown; compositions::GuiNodeMouseEvent NodeLeftButtonUp; compositions::GuiNodeMouseEvent NodeLeftButtonDoubleClick; compositions::GuiNodeMouseEvent NodeMiddleButtonDown; compositions::GuiNodeMouseEvent NodeMiddleButtonUp; compositions::GuiNodeMouseEvent NodeMiddleButtonDoubleClick; compositions::GuiNodeMouseEvent NodeRightButtonDown; compositions::GuiNodeMouseEvent NodeRightButtonUp; compositions::GuiNodeMouseEvent NodeRightButtonDoubleClick; compositions::GuiNodeMouseEvent NodeMouseMove; compositions::GuiNodeNotifyEvent NodeMouseEnter; compositions::GuiNodeNotifyEvent NodeMouseLeave; compositions::GuiNodeNotifyEvent NodeExpanded; compositions::GuiNodeNotifyEvent NodeCollapsed; tree::INodeItemView* GetNodeItemView(); tree::INodeRootProvider* GetNodeRootProvider(); tree::INodeItemStyleProvider* GetNodeStyleProvider(); Ptr<tree::INodeItemStyleProvider> SetNodeStyleProvider(Ptr<tree::INodeItemStyleProvider> styleProvider); }; /*********************************************************************** TreeView ***********************************************************************/ namespace tree { class ITreeViewItemView : public virtual INodeItemPrimaryTextView, public Description<ITreeViewItemView> { public: static const wchar_t* const Identifier; virtual Ptr<GuiImageData> GetNodeImage(INodeProvider* node)=0; virtual WString GetNodeText(INodeProvider* node)=0; }; class TreeViewItem : public Object, public virtual IMemoryNodeData, public Description<TreeViewItem> { public: Ptr<GuiImageData> image; WString text; Ptr<Object> tag; TreeViewItem(); TreeViewItem(const Ptr<GuiImageData>& _image, const WString& _text); }; class TreeViewItemRootProvider : public MemoryNodeRootProvider , protected virtual ITreeViewItemView , public Description<TreeViewItemRootProvider> { protected: WString GetPrimaryTextViewText(INodeProvider* node)override; Ptr<GuiImageData> GetNodeImage(INodeProvider* node)override; WString GetNodeText(INodeProvider* node)override; public: TreeViewItemRootProvider(); ~TreeViewItemRootProvider(); IDescriptable* RequestView(const WString& identifier)override; void ReleaseView(IDescriptable* view)override; Ptr<TreeViewItem> GetTreeViewData(INodeProvider* node); void SetTreeViewData(INodeProvider* node, Ptr<TreeViewItem> value); void UpdateTreeViewData(INodeProvider* node); }; } class GuiVirtualTreeView : public GuiVirtualTreeListControl, public Description<GuiVirtualTreeView> { public: class IStyleProvider : public virtual GuiVirtualTreeListControl::IStyleProvider, public Description<IStyleProvider> { public: virtual GuiSelectableButton::IStyleController* CreateItemBackground()=0; virtual GuiSelectableButton::IStyleController* CreateItemExpandingDecorator()=0; virtual Color GetTextColor()=0; }; protected: IStyleProvider* styleProvider; public: GuiVirtualTreeView(IStyleProvider* _styleProvider, Ptr<tree::INodeRootProvider> _nodeRootProvider); ~GuiVirtualTreeView(); IStyleProvider* GetTreeViewStyleProvider(); }; class GuiTreeView : public GuiVirtualTreeView, public Description<GuiTreeView> { protected: Ptr<tree::TreeViewItemRootProvider> nodes; public: GuiTreeView(IStyleProvider* _styleProvider); ~GuiTreeView(); Ptr<tree::TreeViewItemRootProvider> Nodes(); }; namespace tree { class TreeViewNodeItemStyleProvider : public Object , public virtual INodeItemStyleProvider , protected virtual INodeProviderCallback , public Description<TreeViewNodeItemStyleProvider> { protected: #pragma warning(push) #pragma warning(disable:4250) class ItemController : public list::ItemStyleControllerBase, public virtual INodeItemStyleController { protected: TreeViewNodeItemStyleProvider* styleProvider; GuiSelectableButton* backgroundButton; GuiSelectableButton* expandingButton; compositions::GuiTableComposition* table; elements::GuiImageFrameElement* image; elements::GuiSolidLabelElement* text; void SwitchNodeExpanding(); void OnBackgroundButtonDoubleClick(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnExpandingButtonDoubleClick(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnExpandingButtonClicked(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: ItemController(TreeViewNodeItemStyleProvider* _styleProvider); INodeItemStyleProvider* GetNodeStyleProvider()override; void Install(INodeProvider* node); bool GetSelected(); void SetSelected(bool value); void UpdateExpandingButton(INodeProvider* associatedNode); }; #pragma warning(pop) GuiVirtualTreeView* treeControl; GuiListControl::IItemStyleProvider* bindedItemStyleProvider; ITreeViewItemView* treeViewItemView; protected: ItemController* GetRelatedController(INodeProvider* node); void UpdateExpandingButton(INodeProvider* node); void OnAttached(INodeRootProvider* provider)override; void OnBeforeItemModified(INodeProvider* parentNode, vint start, vint count, vint newCount)override; void OnAfterItemModified(INodeProvider* parentNode, vint start, vint count, vint newCount)override; void OnItemExpanded(INodeProvider* node)override; void OnItemCollapsed(INodeProvider* node)override; public: TreeViewNodeItemStyleProvider(); ~TreeViewNodeItemStyleProvider(); void BindItemStyleProvider(GuiListControl::IItemStyleProvider* styleProvider)override; GuiListControl::IItemStyleProvider* GetBindedItemStyleProvider()override; void AttachListControl(GuiListControl* value)override; void DetachListControl()override; vint GetItemStyleId(INodeProvider* node)override; INodeItemStyleController* CreateItemStyle(vint styleId)override; void DestroyItemStyle(INodeItemStyleController* style)override; void Install(INodeItemStyleController* style, INodeProvider* node)override; void SetStyleSelected(INodeItemStyleController* style, bool value)override; }; } } } namespace collections { namespace randomaccess_internal { template<> struct RandomAccessable<presentation::controls::tree::MemoryNodeProvider> { static const bool CanRead = true; static const bool CanResize = false; }; } } } #endif /*********************************************************************** CONTROLS\LISTCONTROLPACKAGE\GUICOMBOCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUICOMBOCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUICOMBOCONTROLS namespace vl { namespace presentation { namespace controls { /*********************************************************************** ComboBox Base ***********************************************************************/ class GuiComboBoxBase : public GuiMenuButton, public Description<GuiComboBoxBase> { public: class ICommandExecutor : public virtual IDescriptable, public Description<ICommandExecutor> { public: virtual void SelectItem()=0; }; class IStyleController : public virtual GuiMenuButton::IStyleController, public Description<IStyleController> { public: virtual void SetCommandExecutor(ICommandExecutor* value)=0; virtual void OnItemSelected()=0; }; protected: class CommandExecutor : public Object, public virtual ICommandExecutor { protected: GuiComboBoxBase* combo; public: CommandExecutor(GuiComboBoxBase* _combo); ~CommandExecutor(); void SelectItem()override; }; Ptr<CommandExecutor> commandExecutor; IStyleController* styleController; IGuiMenuService::Direction GetSubMenuDirection()override; virtual void SelectItem(); void OnBoundsChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: GuiComboBoxBase(IStyleController* _styleController); ~GuiComboBoxBase(); compositions::GuiNotifyEvent ItemSelected; }; /*********************************************************************** ComboBox with GuiListControl ***********************************************************************/ class GuiComboBoxListControl : public GuiComboBoxBase, public Description<GuiComboBoxListControl> { protected: GuiSelectableListControl* containedListControl; GuiListControl::IItemPrimaryTextView* primaryTextView; virtual void DisplaySelectedContent(vint itemIndex); void OnListControlSelectionChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: GuiComboBoxListControl(IStyleController* _styleController, GuiSelectableListControl* _containedListControl); ~GuiComboBoxListControl(); compositions::GuiNotifyEvent SelectedIndexChanged; void SetFont(const FontProperties& value)override; GuiSelectableListControl* GetContainedListControl(); vint GetSelectedIndex(); void SetSelectedIndex(vint value); GuiListControl::IItemProvider* GetItemProvider(); }; } } } #endif /*********************************************************************** CONTROLS\GUIDATETIMECONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIDATETIMECONTROLS #define VCZH_PRESENTATION_CONTROLS_GUIDATETIMECONTROLS namespace vl { namespace presentation { namespace controls { /*********************************************************************** DatePicker ***********************************************************************/ class GuiDatePicker : public GuiControl, public Description<GuiDatePicker> { public: class IStyleProvider : public virtual GuiControl::IStyleProvider, public Description<IStyleProvider> { public: virtual GuiSelectableButton::IStyleController* CreateDateButtonStyle()=0; virtual GuiTextList* CreateTextList()=0; virtual GuiComboBoxListControl::IStyleController* CreateComboBoxStyle()=0; virtual Color GetBackgroundColor()=0; virtual Color GetPrimaryTextColor()=0; virtual Color GetSecondaryTextColor()=0; }; class StyleController : public Object, public virtual GuiControl::IStyleController, public Description<StyleController> { protected: static const vint DaysOfWeek=7; static const vint DayRows=6; static const vint DayRowStart=2; static const vint YearFirst=1900; static const vint YearLast=2099; IStyleProvider* styleProvider; GuiDatePicker* datePicker; DateTime currentDate; Locale dateLocale; compositions::GuiTableComposition* boundsComposition; bool preventComboEvent; bool preventButtonEvent; GuiComboBoxListControl* comboYear; GuiTextList* listYears; GuiComboBoxListControl* comboMonth; GuiTextList* listMonths; collections::Array<elements::GuiSolidLabelElement*> labelDaysOfWeek; collections::Array<GuiSelectableButton*> buttonDays; collections::Array<elements::GuiSolidLabelElement*> labelDays; collections::Array<DateTime> dateDays; Ptr<GuiSelectableButton::GroupController> dayMutexController; void SetDay(const DateTime& day, vint& index, bool currentMonth); void DisplayMonth(vint year, vint month); void SelectDay(vint day); void comboYearMonth_SelectedIndexChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void buttonDay_SelectedChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: StyleController(IStyleProvider* _styleProvider); ~StyleController(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; void SetDatePicker(GuiDatePicker* _datePicker); void SetDateLocale(const Locale& _dateLocale); const DateTime& GetDate(); void SetDate(const DateTime& value, bool forceUpdate=false); }; protected: StyleController* styleController; WString dateFormat; Locale dateLocale; void UpdateText(); void NotifyDateChanged(); public: GuiDatePicker(IStyleProvider* _styleProvider); ~GuiDatePicker(); compositions::GuiNotifyEvent DateChanged; compositions::GuiNotifyEvent DateNavigated; compositions::GuiNotifyEvent DateSelected; compositions::GuiNotifyEvent DateFormatChanged; compositions::GuiNotifyEvent DateLocaleChanged; const DateTime& GetDate(); void SetDate(const DateTime& value); const WString& GetDateFormat(); void SetDateFormat(const WString& value); const Locale& GetDateLocale(); void SetDateLocale(const Locale& value); void SetText(const WString& value)override; }; /*********************************************************************** DateComboBox ***********************************************************************/ class GuiDateComboBox : public GuiComboBoxBase, public Description<GuiDateComboBox> { protected: GuiDatePicker* datePicker; DateTime selectedDate; void UpdateText(); void NotifyUpdateSelectedDate(); void OnSubMenuOpeningChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void datePicker_DateLocaleChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void datePicker_DateFormatChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void datePicker_DateSelected(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: GuiDateComboBox(IStyleController* _styleController, GuiDatePicker* _datePicker); ~GuiDateComboBox(); compositions::GuiNotifyEvent SelectedDateChanged; void SetFont(const FontProperties& value)override; const DateTime& GetSelectedDate(); void SetSelectedDate(const DateTime& value); GuiDatePicker* GetDatePicker(); }; } } } #endif /*********************************************************************** CONTROLS\TEXTEDITORPACKAGE\GUITEXTGENERALOPERATIONS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITEXTELEMENTOPERATOR #define VCZH_PRESENTATION_CONTROLS_GUITEXTELEMENTOPERATOR namespace vl { namespace presentation { namespace controls { /*********************************************************************** Common Operations ***********************************************************************/ class ICommonTextEditCallback : public virtual IDescriptable, public Description<ICommonTextEditCallback> { public: struct TextEditPreviewStruct { TextPos originalStart; TextPos originalEnd; WString originalText; WString inputText; vuint editVersion; bool keyInput; TextEditPreviewStruct() :editVersion(0) ,keyInput(false) { } }; struct TextEditNotifyStruct { TextPos originalStart; TextPos originalEnd; WString originalText; TextPos inputStart; TextPos inputEnd; WString inputText; vuint editVersion; bool keyInput; TextEditNotifyStruct() :editVersion(0) ,keyInput(false) { } }; struct TextCaretChangedStruct { TextPos oldBegin; TextPos oldEnd; TextPos newBegin; TextPos newEnd; vuint editVersion; TextCaretChangedStruct() :editVersion(0) { } }; virtual void Attach(elements::GuiColorizedTextElement* element, SpinLock& elementModifyLock, compositions::GuiGraphicsComposition* ownerComposition, vuint editVersion)=0; virtual void Detach()=0; virtual void TextEditPreview(TextEditPreviewStruct& arguments)=0; virtual void TextEditNotify(const TextEditNotifyStruct& arguments)=0; virtual void TextCaretChanged(const TextCaretChangedStruct& arguments)=0; virtual void TextEditFinished(vuint editVersion)=0; }; /*********************************************************************** RepeatingParsingExecutor ***********************************************************************/ struct RepeatingParsingInput { vuint editVersion; WString code; RepeatingParsingInput() :editVersion(0) { } }; struct RepeatingParsingOutput { Ptr<parsing::ParsingTreeObject> node; vuint editVersion; WString code; Ptr<parsing::ParsingScopeSymbol> symbol; Ptr<parsing::ParsingScopeFinder> finder; RepeatingParsingOutput() :editVersion(0) { } }; class RepeatingParsingExecutor; class ILanguageProvider : public IDescriptable, public Description<ILanguageProvider> { public: virtual Ptr<parsing::ParsingScopeSymbol> CreateSymbolFromNode(Ptr<parsing::ParsingTreeObject> obj, RepeatingParsingExecutor* executor, parsing::ParsingScopeFinder* finder)=0; virtual collections::LazyList<Ptr<parsing::ParsingScopeSymbol>> FindReferencedSymbols(parsing::ParsingTreeObject* obj, parsing::ParsingScopeFinder* finder)=0; virtual collections::LazyList<Ptr<parsing::ParsingScopeSymbol>> FindPossibleSymbols(parsing::ParsingTreeObject* obj, const WString& field, parsing::ParsingScopeFinder* finder)=0; }; class RepeatingParsingExecutor : public RepeatingTaskExecutor<RepeatingParsingInput>, public Description<RepeatingParsingExecutor> { public: class ICallback : public virtual Interface { public: virtual void OnParsingFinishedAsync(const RepeatingParsingOutput& output)=0; virtual void RequireAutoSubmitTask(bool enabled)=0; }; class CallbackBase : public virtual ICallback, public virtual ICommonTextEditCallback { private: bool callbackAutoPushing; elements::GuiColorizedTextElement* callbackElement; SpinLock* callbackElementModifyLock; protected: Ptr<RepeatingParsingExecutor> parsingExecutor; public: CallbackBase(Ptr<RepeatingParsingExecutor> _parsingExecutor); ~CallbackBase(); void RequireAutoSubmitTask(bool enabled)override; void Attach(elements::GuiColorizedTextElement* _element, SpinLock& _elementModifyLock, compositions::GuiGraphicsComposition* _ownerComposition, vuint editVersion)override; void Detach()override; void TextEditPreview(TextEditPreviewStruct& arguments)override; void TextEditNotify(const TextEditNotifyStruct& arguments)override; void TextCaretChanged(const TextCaretChangedStruct& arguments)override; void TextEditFinished(vuint editVersion)override; }; struct TokenMetaData { vint tableTokenIndex; vint lexerTokenIndex; vint defaultColorIndex; bool hasContextColor; bool hasAutoComplete; bool isCandidate; WString unescapedRegexText; }; struct FieldMetaData { vint colorIndex; Ptr<collections::List<vint>> semantics; }; private: Ptr<parsing::tabling::ParsingGeneralParser> grammarParser; WString grammarRule; Ptr<ILanguageProvider> languageProvider; collections::List<ICallback*> callbacks; collections::List<ICallback*> activatedCallbacks; ICallback* autoPushingCallback; typedef collections::Pair<WString, WString> FieldDesc; collections::Dictionary<WString, vint> tokenIndexMap; collections::SortedList<WString> semanticIndexMap; collections::Dictionary<vint, TokenMetaData> tokenMetaDatas; collections::Dictionary<FieldDesc, FieldMetaData> fieldMetaDatas; protected: void Execute(const RepeatingParsingInput& input)override; void PrepareMetaData(); virtual void OnContextFinishedAsync(RepeatingParsingOutput& context); public: RepeatingParsingExecutor(Ptr<parsing::tabling::ParsingGeneralParser> _grammarParser, const WString& _grammarRule, Ptr<ILanguageProvider> _languageProvider=0); ~RepeatingParsingExecutor(); Ptr<parsing::tabling::ParsingGeneralParser> GetParser(); bool AttachCallback(ICallback* value); bool DetachCallback(ICallback* value); bool ActivateCallback(ICallback* value); bool DeactivateCallback(ICallback* value); Ptr<ILanguageProvider> GetLanguageProvider(); vint GetTokenIndex(const WString& tokenName); vint GetSemanticId(const WString& name); WString GetSemanticName(vint id); const TokenMetaData& GetTokenMetaData(vint regexTokenIndex); const FieldMetaData& GetFieldMetaData(const WString& type, const WString& field); Ptr<parsing::tabling::ParsingTable::AttributeInfo> GetAttribute(vint index, const WString& name, vint argumentCount); Ptr<parsing::tabling::ParsingTable::AttributeInfo> GetColorAttribute(vint index); Ptr<parsing::tabling::ParsingTable::AttributeInfo> GetContextColorAttribute(vint index); Ptr<parsing::tabling::ParsingTable::AttributeInfo> GetSemanticAttribute(vint index); Ptr<parsing::tabling::ParsingTable::AttributeInfo> GetCandidateAttribute(vint index); Ptr<parsing::tabling::ParsingTable::AttributeInfo> GetAutoCompleteAttribute(vint index); /* @Color(ColorName) field: color of the token field when the token type is marked with @ContextColor token: color of the token @ContextColor() token: the color of the token may be changed if the token field is marked with @Color or @Semantic @Semantic(Type1, Type2, ...) field: After resolved symbols for this field, only types of symbols that specified in the arguments are acceptable. @Candidate() token: when the token can be available after the editing caret, than it will be in the auto complete list. @AutoComplete() token: when the token is editing, an auto complete list will appear if possible */ }; /*********************************************************************** ParsingContext ***********************************************************************/ struct ParsingContext { parsing::ParsingTreeToken* foundToken; parsing::ParsingTreeObject* tokenParent; WString type; WString field; Ptr<collections::List<vint>> acceptableSemanticIds; ParsingContext() :foundToken(0) ,tokenParent(0) { } static bool RetriveContext(ParsingContext& output, parsing::ParsingTreeNode* foundNode, RepeatingParsingExecutor* executor); static bool RetriveContext(ParsingContext& output, parsing::ParsingTextPos pos, parsing::ParsingTreeObject* rootNode, RepeatingParsingExecutor* executor); static bool RetriveContext(ParsingContext& output, parsing::ParsingTextRange range, parsing::ParsingTreeObject* rootNode, RepeatingParsingExecutor* executor); }; } } } #endif /*********************************************************************** CONTROLS\TEXTEDITORPACKAGE\GUITEXTCOLORIZER.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITEXTCOLORIZER #define VCZH_PRESENTATION_CONTROLS_GUITEXTCOLORIZER namespace vl { namespace presentation { namespace controls { /*********************************************************************** GuiTextBoxColorizerBase ***********************************************************************/ class GuiTextBoxColorizerBase : public Object, public virtual ICommonTextEditCallback { public: typedef collections::Array<elements::text::ColorEntry> ColorArray; protected: elements::GuiColorizedTextElement* element; SpinLock* elementModifyLock; volatile vint colorizedLineCount; volatile bool isColorizerRunning; volatile bool isFinalizing; SpinLock colorizerRunningEvent; static void ColorizerThreadProc(void* argument); void StartColorizer(); void StopColorizer(bool forever); void StopColorizerForever(); public: GuiTextBoxColorizerBase(); ~GuiTextBoxColorizerBase(); void Attach(elements::GuiColorizedTextElement* _element, SpinLock& _elementModifyLock, compositions::GuiGraphicsComposition* _ownerComposition, vuint editVersion)override; void Detach()override; void TextEditPreview(TextEditPreviewStruct& arguments)override; void TextEditNotify(const TextEditNotifyStruct& arguments)override; void TextCaretChanged(const TextCaretChangedStruct& arguments)override; void TextEditFinished(vuint editVersion)override; void RestartColorizer(); virtual vint GetLexerStartState()=0; virtual vint GetContextStartState()=0; virtual void ColorizeLineWithCRLF(vint lineIndex, const wchar_t* text, unsigned __int32* colors, vint length, vint& lexerState, vint& contextState)=0; virtual const ColorArray& GetColors()=0; }; /*********************************************************************** GuiTextBoxRegexColorizer ***********************************************************************/ class GuiTextBoxRegexColorizer : public GuiTextBoxColorizerBase { protected: Ptr<regex::RegexLexer> lexer; Ptr<regex::RegexLexerColorizer> colorizer; ColorArray colors; elements::text::ColorEntry defaultColor; collections::List<WString> tokenRegexes; collections::List<elements::text::ColorEntry> tokenColors; collections::List<elements::text::ColorEntry> extraTokenColors; static void ColorizerProc(void* argument, vint start, vint length, vint token); public: GuiTextBoxRegexColorizer(); ~GuiTextBoxRegexColorizer(); elements::text::ColorEntry GetDefaultColor(); collections::List<WString>& GetTokenRegexes(); collections::List<elements::text::ColorEntry>& GetTokenColors(); collections::List<elements::text::ColorEntry>& GetExtraTokenColors(); vint GetExtraTokenIndexStart(); bool SetDefaultColor(elements::text::ColorEntry value); vint AddToken(const WString& regex, elements::text::ColorEntry color); vint AddExtraToken(elements::text::ColorEntry color); void ClearTokens(); void Setup(); virtual void ColorizeTokenContextSensitive(vint lineIndex, const wchar_t* text, vint start, vint length, vint& token, vint& contextState); vint GetLexerStartState()override; vint GetContextStartState()override; void ColorizeLineWithCRLF(vint lineIndex, const wchar_t* text, unsigned __int32* colors, vint length, vint& lexerState, vint& contextState)override; const ColorArray& GetColors()override; }; /*********************************************************************** GuiGrammarColorizer ***********************************************************************/ class GuiGrammarColorizer : public GuiTextBoxRegexColorizer, private RepeatingParsingExecutor::CallbackBase { typedef collections::Pair<WString, WString> FieldDesc; typedef collections::Dictionary<FieldDesc, vint> FieldContextColors; typedef collections::Dictionary<FieldDesc, vint> FieldSemanticColors; typedef elements::text::ColorEntry ColorEntry; public: struct SemanticColorizeContext : ParsingContext { vint semanticId; }; private: collections::Dictionary<WString, ColorEntry> colorSettings; collections::Dictionary<vint, vint> semanticColorMap; SpinLock contextLock; RepeatingParsingOutput context; void OnParsingFinishedAsync(const RepeatingParsingOutput& output)override; protected: virtual void OnContextFinishedAsync(const RepeatingParsingOutput& context); void Attach(elements::GuiColorizedTextElement* _element, SpinLock& _elementModifyLock, compositions::GuiGraphicsComposition* _ownerComposition, vuint editVersion)override; void Detach()override; void TextEditPreview(TextEditPreviewStruct& arguments)override; void TextEditNotify(const TextEditNotifyStruct& arguments)override; void TextCaretChanged(const TextCaretChangedStruct& arguments)override; void TextEditFinished(vuint editVersion)override; virtual void OnSemanticColorize(SemanticColorizeContext& context, const RepeatingParsingOutput& input); void EnsureColorizerFinished(); public: GuiGrammarColorizer(Ptr<RepeatingParsingExecutor> _parsingExecutor); GuiGrammarColorizer(Ptr<parsing::tabling::ParsingGeneralParser> _grammarParser, const WString& _grammarRule); ~GuiGrammarColorizer(); void BeginSetColors(); const collections::SortedList<WString>& GetColorNames(); ColorEntry GetColor(const WString& name); void SetColor(const WString& name, const ColorEntry& entry); void SetColor(const WString& name, const Color& color); void EndSetColors(); void ColorizeTokenContextSensitive(int lineIndex, const wchar_t* text, vint start, vint length, vint& token, int& contextState)override; Ptr<RepeatingParsingExecutor> GetParsingExecutor(); }; } } } #endif /*********************************************************************** CONTROLS\TEXTEDITORPACKAGE\GUITEXTAUTOCOMPLETE.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITEXTAUTOCOMPLETE #define VCZH_PRESENTATION_CONTROLS_GUITEXTAUTOCOMPLETE namespace vl { namespace presentation { namespace controls { /*********************************************************************** GuiTextBoxAutoCompleteBase ***********************************************************************/ class GuiTextBoxAutoCompleteBase : public Object, public virtual ICommonTextEditCallback { protected: elements::GuiColorizedTextElement* element; SpinLock* elementModifyLock; compositions::GuiGraphicsComposition* ownerComposition; GuiPopup* autoCompletePopup; GuiTextList* autoCompleteList; TextPos autoCompleteStartPosition; bool IsPrefix(const WString& prefix, const WString& candidate); public: GuiTextBoxAutoCompleteBase(); ~GuiTextBoxAutoCompleteBase(); void Attach(elements::GuiColorizedTextElement* _element, SpinLock& _elementModifyLock, compositions::GuiGraphicsComposition* _ownerComposition, vuint editVersion)override; void Detach()override; void TextEditPreview(TextEditPreviewStruct& arguments)override; void TextEditNotify(const TextEditNotifyStruct& arguments)override; void TextCaretChanged(const TextCaretChangedStruct& arguments)override; void TextEditFinished(vuint editVersion)override; bool IsListOpening(); void OpenList(TextPos startPosition); void CloseList(); void SetListContent(const collections::SortedList<WString>& items); TextPos GetListStartPosition(); bool SelectPreviousListItem(); bool SelectNextListItem(); bool ApplySelectedListItem(); WString GetSelectedListItem(); void HighlightList(const WString& editingText); }; /*********************************************************************** GuiGrammarAutoComplete ***********************************************************************/ class GuiGrammarAutoComplete : public GuiTextBoxAutoCompleteBase , private RepeatingParsingExecutor::CallbackBase , private RepeatingTaskExecutor<RepeatingParsingOutput> { typedef collections::List<Ptr<parsing::ParsingScopeSymbol>> ParsingScopeSymbolList; public: struct AutoCompleteData : ParsingContext { collections::List<vint> candidates; collections::List<vint> shownCandidates; ParsingScopeSymbolList candidateSymbols; TextPos startPosition; }; struct Context { RepeatingParsingOutput input; WString rule; parsing::ParsingTextRange originalRange; Ptr<parsing::ParsingTreeObject> originalNode; Ptr<parsing::ParsingTreeObject> modifiedNode; WString modifiedCode; vuint modifiedEditVersion; Ptr<AutoCompleteData> autoComplete; Context() :modifiedEditVersion(0) { } }; private: Ptr<parsing::tabling::ParsingGeneralParser> grammarParser; collections::SortedList<WString> leftRecursiveRules; bool editing; SpinLock editTraceLock; collections::List<TextEditNotifyStruct> editTrace; SpinLock contextLock; Context context; void Attach(elements::GuiColorizedTextElement* _element, SpinLock& _elementModifyLock, compositions::GuiGraphicsComposition* _ownerComposition, vuint editVersion)override; void Detach()override; void TextEditPreview(TextEditPreviewStruct& arguments)override; void TextEditNotify(const TextEditNotifyStruct& arguments)override; void TextCaretChanged(const TextCaretChangedStruct& arguments)override; void TextEditFinished(vuint editVersion)override; void OnParsingFinishedAsync(const RepeatingParsingOutput& output)override; void CollectLeftRecursiveRules(); vint UnsafeGetEditTraceIndex(vuint editVersion); TextPos ChooseCorrectTextPos(TextPos pos, const regex::RegexTokens& tokens); void ExecuteRefresh(Context& newContext); bool NormalizeTextPos(Context& newContext, elements::text::TextLines& lines, TextPos& pos); void ExecuteEdit(Context& newContext); void DeleteFutures(collections::List<parsing::tabling::ParsingState::Future*>& futures); regex::RegexToken* TraverseTransitions( parsing::tabling::ParsingState& state, parsing::tabling::ParsingTransitionCollector& transitionCollector, TextPos stopPosition, collections::List<parsing::tabling::ParsingState::Future*>& nonRecoveryFutures, collections::List<parsing::tabling::ParsingState::Future*>& recoveryFutures ); regex::RegexToken* SearchValidInputToken( parsing::tabling::ParsingState& state, parsing::tabling::ParsingTransitionCollector& transitionCollector, TextPos stopPosition, Context& newContext, collections::SortedList<vint>& tableTokenIndices ); TextPos GlobalTextPosToModifiedTextPos(Context& newContext, TextPos pos); TextPos ModifiedTextPosToGlobalTextPos(Context& newContext, TextPos pos); void ExecuteCalculateList(Context& newContext); void Execute(const RepeatingParsingOutput& input)override; void PostList(const Context& newContext, bool byGlobalCorrection); void Initialize(); protected: virtual void OnContextFinishedAsync(Context& context); void EnsureAutoCompleteFinished(); public: GuiGrammarAutoComplete(Ptr<RepeatingParsingExecutor> _parsingExecutor); GuiGrammarAutoComplete(Ptr<parsing::tabling::ParsingGeneralParser> _grammarParser, const WString& _grammarRule); ~GuiGrammarAutoComplete(); Ptr<RepeatingParsingExecutor> GetParsingExecutor(); }; } } } #endif /*********************************************************************** CONTROLS\TEXTEDITORPACKAGE\GUITEXTUNDOREDO.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITEXTUNDOREDO #define VCZH_PRESENTATION_CONTROLS_GUITEXTUNDOREDO namespace vl { namespace presentation { namespace controls { class GuiTextBoxCommonInterface; /*********************************************************************** Undo Redo ***********************************************************************/ class GuiGeneralUndoRedoProcessor : public Object { protected: class IEditStep : public Interface { public: virtual void Undo()=0; virtual void Redo()=0; }; friend class collections::ArrayBase<Ptr<IEditStep>>; protected: collections::List<Ptr<IEditStep>> steps; vint firstFutureStep; vint savedStep; bool performingUndoRedo; void PushStep(Ptr<IEditStep> step); public: GuiGeneralUndoRedoProcessor(); ~GuiGeneralUndoRedoProcessor(); bool CanUndo(); bool CanRedo(); void ClearUndoRedo(); bool GetModified(); void NotifyModificationSaved(); bool Undo(); bool Redo(); }; class GuiTextBoxUndoRedoProcessor : public GuiGeneralUndoRedoProcessor, public ICommonTextEditCallback { protected: class EditStep : public Object, public IEditStep { public: GuiTextBoxUndoRedoProcessor* processor; TextEditNotifyStruct arguments; void Undo(); void Redo(); }; compositions::GuiGraphicsComposition* ownerComposition; public: GuiTextBoxUndoRedoProcessor(); ~GuiTextBoxUndoRedoProcessor(); void Attach(elements::GuiColorizedTextElement* element, SpinLock& elementModifyLock, compositions::GuiGraphicsComposition* _ownerComposition, vuint editVersion)override; void Detach()override; void TextEditPreview(TextEditPreviewStruct& arguments)override; void TextEditNotify(const TextEditNotifyStruct& arguments)override; void TextCaretChanged(const TextCaretChangedStruct& arguments)override; void TextEditFinished(vuint editVersion)override; }; } } } #endif /*********************************************************************** CONTROLS\TEXTEDITORPACKAGE\GUITEXTCOMMONINTERFACE.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITEXTCOMMONINTERFACE #define VCZH_PRESENTATION_CONTROLS_GUITEXTCOMMONINTERFACE namespace vl { namespace presentation { namespace controls { /*********************************************************************** Common Interface ***********************************************************************/ class GuiTextBoxCommonInterface abstract : public Description<GuiTextBoxCommonInterface> { protected: class ICallback : public virtual IDescriptable, public Description<ICallback> { public: virtual TextPos GetLeftWord(TextPos pos)=0; virtual TextPos GetRightWord(TextPos pos)=0; virtual void GetWord(TextPos pos, TextPos& begin, TextPos& end)=0; virtual vint GetPageRows()=0; virtual bool BeforeModify(TextPos start, TextPos end, const WString& originalText, WString& inputText)=0; virtual void AfterModify(TextPos originalStart, TextPos originalEnd, const WString& originalText, TextPos inputStart, TextPos inputEnd, const WString& inputText)=0; virtual void ScrollToView(Point point)=0; virtual vint GetTextMargin()=0; }; class DefaultCallback : public Object, public ICallback, public Description<DefaultCallback> { protected: elements::GuiColorizedTextElement* textElement; compositions::GuiGraphicsComposition* textComposition; bool readonly; public: DefaultCallback(elements::GuiColorizedTextElement* _textElement, compositions::GuiGraphicsComposition* _textComposition); ~DefaultCallback(); TextPos GetLeftWord(TextPos pos)override; TextPos GetRightWord(TextPos pos)override; void GetWord(TextPos pos, TextPos& begin, TextPos& end)override; vint GetPageRows()override; bool BeforeModify(TextPos start, TextPos end, const WString& originalText, WString& inputText)override; }; public: class ShortcutCommand { protected: bool ctrl; bool shift; vint key; Func<void()> action; public: ShortcutCommand(bool _ctrl, bool _shift, vint _key, const Func<void()> _action); ShortcutCommand(bool _ctrl, bool _shift, vint _key, const Func<bool()> _action); ~ShortcutCommand(); bool IsTheRightKey(bool _ctrl, bool _shift, vint _key); void Execute(); }; private: elements::GuiColorizedTextElement* textElement; compositions::GuiGraphicsComposition* textComposition; vuint editVersion; GuiControl* textControl; ICallback* callback; bool dragging; bool readonly; Ptr<GuiTextBoxColorizerBase> colorizer; Ptr<GuiTextBoxAutoCompleteBase> autoComplete; Ptr<GuiTextBoxUndoRedoProcessor> undoRedoProcessor; SpinLock elementModifyLock; collections::List<Ptr<ICommonTextEditCallback>> textEditCallbacks; collections::List<Ptr<ShortcutCommand>> shortcutCommands; bool preventEnterDueToAutoComplete; void UpdateCaretPoint(); void Move(TextPos pos, bool shift); void Modify(TextPos start, TextPos end, const WString& input, bool asKeyInput); bool ProcessKey(vint code, bool shift, bool ctrl); void OnGotFocus(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnLostFocus(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnCaretNotify(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnLeftButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnLeftButtonUp(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnMouseMove(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnKeyDown(compositions::GuiGraphicsComposition* sender, compositions::GuiKeyEventArgs& arguments); void OnCharInput(compositions::GuiGraphicsComposition* sender, compositions::GuiCharEventArgs& arguments); protected: void Install(elements::GuiColorizedTextElement* _textElement, compositions::GuiGraphicsComposition* _textComposition, GuiControl* _textControl); ICallback* GetCallback(); void SetCallback(ICallback* value); bool AttachTextEditCallback(Ptr<ICommonTextEditCallback> value); bool DetachTextEditCallback(Ptr<ICommonTextEditCallback> value); void AddShortcutCommand(Ptr<ShortcutCommand> shortcutCommand); elements::GuiColorizedTextElement* GetTextElement(); void UnsafeSetText(const WString& value); public: GuiTextBoxCommonInterface(); ~GuiTextBoxCommonInterface(); compositions::GuiNotifyEvent SelectionChanged; //================ clipboard operations bool CanCut(); bool CanCopy(); bool CanPaste(); bool Cut(); bool Copy(); bool Paste(); //================ editing control bool GetReadonly(); void SetReadonly(bool value); //================ text operations void SelectAll(); void Select(TextPos begin, TextPos end); WString GetSelectionText(); void SetSelectionText(const WString& value, bool asKeyInput=false); WString GetRowText(vint row); WString GetFragmentText(TextPos start, TextPos end); TextPos GetCaretBegin(); TextPos GetCaretEnd(); TextPos GetCaretSmall(); TextPos GetCaretLarge(); //================ position query vint GetRowWidth(vint row); vint GetRowHeight(); vint GetMaxWidth(); vint GetMaxHeight(); TextPos GetTextPosFromPoint(Point point); Point GetPointFromTextPos(TextPos pos); Rect GetRectFromTextPos(TextPos pos); TextPos GetNearestTextPos(Point point); //================ colorizing Ptr<GuiTextBoxColorizerBase> GetColorizer(); void SetColorizer(Ptr<GuiTextBoxColorizerBase> value); //================ auto complete Ptr<GuiTextBoxAutoCompleteBase> GetAutoComplete(); void SetAutoComplete(Ptr<GuiTextBoxAutoCompleteBase> value); //================ undo redo control vuint GetEditVersion(); bool CanUndo(); bool CanRedo(); void ClearUndoRedo(); bool GetModified(); void NotifyModificationSaved(); bool Undo(); bool Redo(); }; } } } #endif /*********************************************************************** CONTROLS\TEXTEDITORPACKAGE\GUITEXTCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITEXTCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUITEXTCONTROLS namespace vl { namespace presentation { namespace controls { /*********************************************************************** MultilineTextBox ***********************************************************************/ class GuiMultilineTextBox : public GuiScrollView, public GuiTextBoxCommonInterface, public Description<GuiMultilineTextBox> { public: static const vint TextMargin=3; class StyleController : public GuiScrollView::StyleController, public Description<StyleController> { protected: elements::GuiColorizedTextElement* textElement; compositions::GuiBoundsComposition* textComposition; GuiMultilineTextBox* textBox; Ptr<GuiTextBoxCommonInterface::ICallback> defaultCallback; public: StyleController(GuiScrollView::IStyleProvider* styleProvider); ~StyleController(); void Initialize(GuiMultilineTextBox* control); elements::GuiColorizedTextElement* GetTextElement(); compositions::GuiGraphicsComposition* GetTextComposition(); void SetViewPosition(Point value); void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; WString GetText(); void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; }; protected: class TextElementOperatorCallback : public GuiTextBoxCommonInterface::DefaultCallback, public Description<TextElementOperatorCallback> { protected: GuiMultilineTextBox* textControl; StyleController* textController; public: TextElementOperatorCallback(GuiMultilineTextBox* _textControl); void AfterModify(TextPos originalStart, TextPos originalEnd, const WString& originalText, TextPos inputStart, TextPos inputEnd, const WString& inputText)override; void ScrollToView(Point point)override; vint GetTextMargin()override; }; protected: StyleController* styleController; void CalculateViewAndSetScroll(); void OnRenderTargetChanged(elements::IGuiGraphicsRenderTarget* renderTarget)override; Size QueryFullSize()override; void UpdateView(Rect viewBounds)override; void OnBoundsMouseButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); public: GuiMultilineTextBox(GuiMultilineTextBox::IStyleProvider* styleProvider); ~GuiMultilineTextBox(); const WString& GetText()override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; }; /*********************************************************************** SinglelineTextBox ***********************************************************************/ class GuiSinglelineTextBox : public GuiControl, public GuiTextBoxCommonInterface, public Description<GuiSinglelineTextBox> { public: static const vint TextMargin=3; class IStyleProvider : public virtual GuiControl::IStyleProvider, public Description<IStyleProvider> { public: virtual compositions::GuiGraphicsComposition* InstallBackground(compositions::GuiBoundsComposition* background)=0; }; class StyleController : public Object, public GuiControl::IStyleController, public Description<StyleController> { protected: Ptr<IStyleProvider> styleProvider; compositions::GuiBoundsComposition* boundsComposition; compositions::GuiGraphicsComposition* containerComposition; GuiSinglelineTextBox* textBox; elements::GuiColorizedTextElement* textElement; compositions::GuiTableComposition* textCompositionTable; compositions::GuiCellComposition* textComposition; Ptr<GuiTextBoxCommonInterface::ICallback> defaultCallback; public: StyleController(IStyleProvider* _styleProvider); ~StyleController(); void SetTextBox(GuiSinglelineTextBox* control); void RearrangeTextElement(); compositions::GuiBoundsComposition* GetBoundsComposition(); compositions::GuiGraphicsComposition* GetContainerComposition(); void SetFocusableComposition(compositions::GuiGraphicsComposition* value); WString GetText(); void SetText(const WString& value); void SetFont(const FontProperties& value); void SetVisuallyEnabled(bool value); elements::GuiColorizedTextElement* GetTextElement(); compositions::GuiGraphicsComposition* GetTextComposition(); void SetViewPosition(Point value); }; protected: class TextElementOperatorCallback : public GuiTextBoxCommonInterface::DefaultCallback, public Description<TextElementOperatorCallback> { protected: GuiSinglelineTextBox* textControl; StyleController* textController; public: TextElementOperatorCallback(GuiSinglelineTextBox* _textControl); bool BeforeModify(TextPos start, TextPos end, const WString& originalText, WString& inputText)override; void AfterModify(TextPos originalStart, TextPos originalEnd, const WString& originalText, TextPos inputStart, TextPos inputEnd, const WString& inputText)override; void ScrollToView(Point point)override; vint GetTextMargin()override; }; protected: StyleController* styleController; void OnRenderTargetChanged(elements::IGuiGraphicsRenderTarget* renderTarget)override; void OnBoundsMouseButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); public: GuiSinglelineTextBox(GuiSinglelineTextBox::IStyleProvider* styleProvider); ~GuiSinglelineTextBox(); const WString& GetText()override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; wchar_t GetPasswordChar(); void SetPasswordChar(wchar_t value); }; } } } #endif /*********************************************************************** CONTROLS\TEXTEDITORPACKAGE\GUIDOCUMENTVIEWER.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIDOCUMENTVIEWER #define VCZH_PRESENTATION_CONTROLS_GUIDOCUMENTVIEWER namespace vl { namespace presentation { namespace controls { /*********************************************************************** GuiDocumentCommonInterface ***********************************************************************/ class GuiDocumentCommonInterface abstract : public Description<GuiDocumentCommonInterface> { protected: elements::GuiDocumentElement* documentElement; compositions::GuiBoundsComposition* documentComposition; vint activeHyperlinkId; vint draggingHyperlinkId; bool dragging; GuiControl* senderControl; void InstallDocumentViewer(GuiControl* _sender, compositions::GuiGraphicsComposition* _container); void SetActiveHyperlinkId(vint value); void OnMouseMove(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnMouseDown(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnMouseUp(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnMouseLeave(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: GuiDocumentCommonInterface(); ~GuiDocumentCommonInterface(); compositions::GuiNotifyEvent ActiveHyperlinkChanged; compositions::GuiNotifyEvent ActiveHyperlinkExecuted; Ptr<DocumentModel> GetDocument(); void SetDocument(Ptr<DocumentModel> value); void NotifyParagraphUpdated(vint index); vint GetActiveHyperlinkId(); WString GetActiveHyperlinkReference(); }; /*********************************************************************** GuiDocumentViewer ***********************************************************************/ class GuiDocumentViewer : public GuiScrollContainer, public GuiDocumentCommonInterface, public Description<GuiDocumentViewer> { public: GuiDocumentViewer(GuiDocumentViewer::IStyleProvider* styleProvider); ~GuiDocumentViewer(); }; /*********************************************************************** GuiDocumentViewer ***********************************************************************/ class GuiDocumentLabel : public GuiControl, public GuiDocumentCommonInterface, public Description<GuiDocumentLabel> { public: GuiDocumentLabel(GuiDocumentLabel::IStyleController* styleController); ~GuiDocumentLabel(); }; } } } #endif /*********************************************************************** CONTROLS\LISTCONTROLPACKAGE\GUIDATAGRIDINTERFACES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIDATAGRIDINTERFACES #define VCZH_PRESENTATION_CONTROLS_GUIDATAGRIDINTERFACES namespace vl { namespace presentation { namespace controls { namespace list { /*********************************************************************** Datagrid Interfaces ***********************************************************************/ class IDataVisualizerFactory; class IDataVisualizer; class IDataEditorCallback; class IDataEditorFactory; class IDataEditor; class IDataProviderCommandExecutor; class IDataProvider; class IDataVisualizerFactory : public virtual IDescriptable, public Description<IDataVisualizerFactory> { public: virtual Ptr<IDataVisualizer> CreateVisualizer(const FontProperties& font, GuiListViewBase::IStyleProvider* styleProvider)=0; }; class IDataVisualizer : public virtual IDescriptable, public Description<IDataVisualizer> { public: virtual IDataVisualizerFactory* GetFactory()=0; virtual compositions::GuiBoundsComposition* GetBoundsComposition()=0; virtual void BeforeVisualizeCell(IDataProvider* dataProvider, vint row, vint column)=0; virtual IDataVisualizer* GetDecoratedDataVisualizer()=0; virtual void SetSelected(bool value)=0; template<typename T> T* GetVisualizer() { IDataVisualizer* visualizer=this; while(visualizer) { T* result=dynamic_cast<T*>(visualizer); if(result) return result; visualizer=visualizer->GetDecoratedDataVisualizer(); } return 0; }; }; class IDataEditorCallback : public virtual IDescriptable, public Description<IDataEditorCallback> { public: virtual void RequestSaveData()=0; }; class IDataEditorFactory : public virtual IDescriptable, public Description<IDataEditorFactory> { public: virtual Ptr<IDataEditor> CreateEditor(IDataEditorCallback* callback)=0; }; class IDataEditor : public virtual IDescriptable, public Description<IDataEditor> { public: virtual IDataEditorFactory* GetFactory()=0; virtual compositions::GuiBoundsComposition* GetBoundsComposition()=0; virtual void BeforeEditCell(IDataProvider* dataProvider, vint row, vint column)=0; virtual void ReinstallEditor()=0; }; class IDataProviderCommandExecutor : public virtual IDescriptable, public Description<IDataProviderCommandExecutor> { public: virtual void OnDataProviderColumnChanged()=0; virtual void OnDataProviderItemModified(vint start, vint count, vint newCount)=0; }; class IDataProvider : public virtual IDescriptable, public Description<IDataProvider> { public: static const wchar_t* const Identifier; virtual void SetCommandExecutor(IDataProviderCommandExecutor* value)=0; virtual vint GetColumnCount()=0; virtual WString GetColumnText(vint column)=0; virtual vint GetColumnSize(vint column)=0; virtual void SetColumnSize(vint column, vint value)=0; virtual GuiMenu* GetColumnPopup(vint column)=0; virtual bool IsColumnSortable(vint column)=0; virtual void SortByColumn(vint column, bool ascending)=0; virtual vint GetSortedColumn()=0; virtual bool IsSortOrderAscending()=0; virtual vint GetRowCount()=0; virtual Ptr<GuiImageData> GetRowLargeImage(vint row)=0; virtual Ptr<GuiImageData> GetRowSmallImage(vint row)=0; virtual vint GetCellSpan(vint row, vint column)=0; virtual WString GetCellText(vint row, vint column)=0; virtual IDataVisualizerFactory* GetCellDataVisualizerFactory(vint row, vint column)=0; virtual void VisualizeCell(vint row, vint column, IDataVisualizer* dataVisualizer)=0; virtual IDataEditorFactory* GetCellDataEditorFactory(vint row, vint column)=0; virtual void BeforeEditCell(vint row, vint column, IDataEditor* dataEditor)=0; virtual void SaveCellData(vint row, vint column, IDataEditor* dataEditor)=0; }; /*********************************************************************** DataSource Extensions ***********************************************************************/ class IStructuredDataFilterCommandExecutor : public virtual IDescriptable, public Description<IStructuredDataFilterCommandExecutor> { public: virtual void OnFilterChanged()=0; }; class IStructuredDataFilter : public virtual IDescriptable, public Description<IStructuredDataFilter> { public: virtual void SetCommandExecutor(IStructuredDataFilterCommandExecutor* value)=0; virtual bool Filter(vint row)=0; }; class IStructuredDataSorter : public virtual IDescriptable, public Description<IStructuredDataSorter> { public: virtual vint Compare(vint row1, vint row2)=0; }; class IStructuredColumnProvider : public virtual IDescriptable, public Description<IStructuredColumnProvider> { public: virtual WString GetText()=0; virtual vint GetSize()=0; virtual void SetSize(vint value)=0; virtual GuiListViewColumnHeader::ColumnSortingState GetSortingState()=0; virtual void SetSortingState(GuiListViewColumnHeader::ColumnSortingState value)=0; virtual GuiMenu* GetPopup()=0; virtual Ptr<IStructuredDataFilter> GetInherentFilter()=0; virtual Ptr<IStructuredDataSorter> GetInherentSorter()=0; virtual WString GetCellText(vint row)=0; virtual IDataVisualizerFactory* GetCellDataVisualizerFactory(vint row)=0; virtual void VisualizeCell(vint row, IDataVisualizer* dataVisualizer)=0; virtual IDataEditorFactory* GetCellDataEditorFactory(vint row)=0; virtual void BeforeEditCell(vint row, IDataEditor* dataEditor)=0; virtual void SaveCellData(vint row, IDataEditor* dataEditor)=0; }; class IStructuredDataProvider : public virtual IDescriptable, public Description<IStructuredDataProvider> { public: virtual void SetCommandExecutor(IDataProviderCommandExecutor* value)=0; virtual vint GetColumnCount()=0; virtual vint GetRowCount()=0; virtual IStructuredColumnProvider* GetColumn(vint column)=0; virtual Ptr<GuiImageData> GetRowLargeImage(vint row)=0; virtual Ptr<GuiImageData> GetRowSmallImage(vint row)=0; }; } } } } #endif /*********************************************************************** CONTROLS\LISTCONTROLPACKAGE\GUIDATAGRIDSTRUCTURED.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIDATASTRUCTURED #define VCZH_PRESENTATION_CONTROLS_GUIDATASTRUCTURED namespace vl { namespace presentation { namespace controls { namespace list { /*********************************************************************** Filter Extensions ***********************************************************************/ class StructuredDataFilterBase : public Object, public virtual IStructuredDataFilter, public Description<StructuredDataFilterBase> { protected: IStructuredDataFilterCommandExecutor* commandExecutor; void InvokeOnFilterChanged(); public: StructuredDataFilterBase(); void SetCommandExecutor(IStructuredDataFilterCommandExecutor* value)override; }; class StructuredDataMultipleFilter : public StructuredDataFilterBase, public Description<StructuredDataMultipleFilter> { protected: collections::List<Ptr<IStructuredDataFilter>> filters; public: StructuredDataMultipleFilter(); bool AddSubFilter(Ptr<IStructuredDataFilter> value); bool RemoveSubFilter(Ptr<IStructuredDataFilter> value); void SetCommandExecutor(IStructuredDataFilterCommandExecutor* value)override; }; class StructuredDataAndFilter : public StructuredDataMultipleFilter, public Description<StructuredDataAndFilter> { public: StructuredDataAndFilter(); bool Filter(vint row)override; }; class StructuredDataOrFilter : public StructuredDataMultipleFilter, public Description<StructuredDataOrFilter> { public: StructuredDataOrFilter(); bool Filter(vint row)override; }; class StructuredDataNotFilter : public StructuredDataFilterBase, public Description<StructuredDataNotFilter> { protected: Ptr<IStructuredDataFilter> filter; public: StructuredDataNotFilter(); bool SetSubFilter(Ptr<IStructuredDataFilter> value); void SetCommandExecutor(IStructuredDataFilterCommandExecutor* value)override; bool Filter(vint row)override; }; /*********************************************************************** Sorter Extensions ***********************************************************************/ class StructuredDataMultipleSorter : public Object, public virtual IStructuredDataSorter, public Description<StructuredDataMultipleSorter> { protected: Ptr<IStructuredDataSorter> leftSorter; Ptr<IStructuredDataSorter> rightSorter; public: StructuredDataMultipleSorter(); bool SetLeftSorter(Ptr<IStructuredDataSorter> value); bool SetRightSorter(Ptr<IStructuredDataSorter> value); vint Compare(vint row1, vint row2)override; }; class StructuredDataReverseSorter : public Object, public virtual IStructuredDataSorter, public Description<StructuredDataReverseSorter> { protected: Ptr<IStructuredDataSorter> sorter; public: StructuredDataReverseSorter(); bool SetSubSorter(Ptr<IStructuredDataSorter> value); vint Compare(vint row1, vint row2)override; }; /*********************************************************************** Structured DataSource Extensions ***********************************************************************/ class StructuredDataProvider : public Object , public virtual IDataProvider , protected virtual IDataProviderCommandExecutor , protected virtual IStructuredDataFilterCommandExecutor , public Description<StructuredDataProvider> { protected: Ptr<IStructuredDataProvider> structuredDataProvider; IDataProviderCommandExecutor* commandExecutor; Ptr<IStructuredDataFilter> additionalFilter; Ptr<IStructuredDataFilter> currentFilter; Ptr<IStructuredDataSorter> currentSorter; collections::List<vint> reorderedRows; void OnDataProviderColumnChanged()override; void OnDataProviderItemModified(vint start, vint count, vint newCount)override; void OnFilterChanged()override; void RebuildFilter(bool invokeCallback); void ReorderRows(bool invokeCallback); vint TranslateRowNumber(vint row); public: StructuredDataProvider(Ptr<IStructuredDataProvider> provider); ~StructuredDataProvider(); Ptr<IStructuredDataProvider> GetStructuredDataProvider(); Ptr<IStructuredDataFilter> GetAdditionalFilter(); void SetAdditionalFilter(Ptr<IStructuredDataFilter> value); void SetCommandExecutor(IDataProviderCommandExecutor* value)override; vint GetColumnCount()override; WString GetColumnText(vint column)override; vint GetColumnSize(vint column)override; void SetColumnSize(vint column, vint value)override; GuiMenu* GetColumnPopup(vint column)override; bool IsColumnSortable(vint column)override; void SortByColumn(vint column, bool ascending)override; vint GetSortedColumn()override; bool IsSortOrderAscending()override; vint GetRowCount()override; Ptr<GuiImageData> GetRowLargeImage(vint row)override; Ptr<GuiImageData> GetRowSmallImage(vint row)override; vint GetCellSpan(vint row, vint column)override; WString GetCellText(vint row, vint column)override; IDataVisualizerFactory* GetCellDataVisualizerFactory(vint row, vint column)override; void VisualizeCell(vint row, vint column, IDataVisualizer* dataVisualizer)override; IDataEditorFactory* GetCellDataEditorFactory(vint row, vint column)override; void BeforeEditCell(vint row, vint column, IDataEditor* dataEditor)override; void SaveCellData(vint row, vint column, IDataEditor* dataEditor)override; }; class StructuredColummProviderBase : public Object, public virtual IStructuredColumnProvider, public Description<StructuredColummProviderBase> { protected: IDataProviderCommandExecutor* commandExecutor; WString text; vint size; GuiListViewColumnHeader::ColumnSortingState sortingState; GuiMenu* popup; Ptr<IStructuredDataFilter> inherentFilter; Ptr<IStructuredDataSorter> inherentSorter; Ptr<IDataVisualizerFactory> visualizerFactory; Ptr<IDataEditorFactory> editorFactory; public: StructuredColummProviderBase(); ~StructuredColummProviderBase(); void SetCommandExecutor(IDataProviderCommandExecutor* value); StructuredColummProviderBase* SetText(const WString& value); StructuredColummProviderBase* SetPopup(GuiMenu* value); StructuredColummProviderBase* SetInherentFilter(Ptr<IStructuredDataFilter> value); StructuredColummProviderBase* SetInherentSorter(Ptr<IStructuredDataSorter> value); StructuredColummProviderBase* SetVisualizerFactory(Ptr<IDataVisualizerFactory> value); StructuredColummProviderBase* SetEditorFactory(Ptr<IDataEditorFactory> value); WString GetText()override; vint GetSize()override; void SetSize(vint value)override; GuiListViewColumnHeader::ColumnSortingState GetSortingState()override; void SetSortingState(GuiListViewColumnHeader::ColumnSortingState value)override; GuiMenu* GetPopup()override; Ptr<IStructuredDataFilter> GetInherentFilter()override; Ptr<IStructuredDataSorter> GetInherentSorter()override; IDataVisualizerFactory* GetCellDataVisualizerFactory(vint row)override; void VisualizeCell(vint row, IDataVisualizer* dataVisualizer)override; IDataEditorFactory* GetCellDataEditorFactory(vint row)override; void BeforeEditCell(vint row, IDataEditor* dataEditor)override; void SaveCellData(vint row, IDataEditor* dataEditor)override; }; class StructuredDataProviderBase : public Object, public virtual IStructuredDataProvider, public Description<StructuredDataProviderBase> { typedef collections::List<Ptr<StructuredColummProviderBase>> ColumnList; protected: IDataProviderCommandExecutor* commandExecutor; ColumnList columns; bool InsertColumnInternal(vint column, Ptr<StructuredColummProviderBase> value, bool callback); bool AddColumnInternal(Ptr<StructuredColummProviderBase> value, bool callback); bool RemoveColumnInternal(Ptr<StructuredColummProviderBase> value, bool callback); bool ClearColumnsInternal(bool callback); public: StructuredDataProviderBase(); ~StructuredDataProviderBase(); void SetCommandExecutor(IDataProviderCommandExecutor* value)override; vint GetColumnCount()override; IStructuredColumnProvider* GetColumn(vint column)override; Ptr<GuiImageData> GetRowLargeImage(vint row)override; Ptr<GuiImageData> GetRowSmallImage(vint row)override; }; /*********************************************************************** Strong Typed DataSource Extensions ***********************************************************************/ template<typename TRow> class StrongTypedDataProvider; template<typename TRow, typename TColumn> class StrongTypedColumnProviderBase : public StructuredColummProviderBase { public: class FilterBase : public StructuredDataFilterBase { protected: StrongTypedColumnProviderBase<TRow, TColumn>* ownerColumn; StrongTypedDataProvider<TRow>* dataProvider; virtual bool FilterData(const TRow& rowData, const TColumn& cellData)=0; public: FilterBase(StrongTypedColumnProviderBase<TRow, TColumn>* _ownerColumn) :ownerColumn(_ownerColumn) ,dataProvider(_ownerColumn->dataProvider) { } bool Filter(vint row)override { TRow rowData; TColumn cellData; dataProvider->GetRowData(row, rowData); ownerColumn->GetCellData(rowData, cellData); return FilterData(rowData, cellData); } }; class SorterBase : public Object, public virtual IStructuredDataSorter { protected: StrongTypedColumnProviderBase<TRow, TColumn>* ownerColumn; StrongTypedDataProvider<TRow>* dataProvider; virtual vint CompareData(const TRow& rowData1, const TColumn& cellData1, const TRow& rowData2, const TColumn& cellData2)=0; public: SorterBase(StrongTypedColumnProviderBase<TRow, TColumn>* _ownerColumn) :ownerColumn(_ownerColumn) ,dataProvider(_ownerColumn->dataProvider) { } vint Compare(vint row1, vint row2) { TRow rowData1, rowData2; TColumn cellData1, cellData2; dataProvider->GetRowData(row1, rowData1); dataProvider->GetRowData(row2, rowData2); ownerColumn->GetCellData(rowData1, cellData1); ownerColumn->GetCellData(rowData2, cellData2); return CompareData(rowData1, cellData1, rowData2, cellData2); } }; class Sorter : public SorterBase { protected: vint CompareData(const TRow& rowData1, const TColumn& cellData1, const TRow& rowData2, const TColumn& cellData2)override { if(cellData1<cellData2) return -1; if(cellData1>cellData2) return 1; return 0; } public: Sorter(StrongTypedColumnProviderBase<TRow, TColumn>* _ownerColumn) :SorterBase(_ownerColumn) { } }; protected: StrongTypedDataProvider<TRow>* dataProvider; public: StrongTypedColumnProviderBase(StrongTypedDataProvider<TRow>* _dataProvider) :dataProvider(_dataProvider) { } virtual void GetCellData(const TRow& rowData, TColumn& cellData)=0; virtual WString GetCellDataText(const TColumn& cellData)=0; WString GetCellText(vint row)override { TRow rowData; TColumn cellData; dataProvider->GetRowData(row, rowData); GetCellData(rowData, cellData); return GetCellDataText(cellData); } }; template<typename TRow, typename TColumn> class StrongTypedColumnProvider : public StrongTypedColumnProviderBase<TRow, TColumn> { public: StrongTypedColumnProvider(StrongTypedDataProvider<TRow>* _dataProvider) :StrongTypedColumnProviderBase(_dataProvider) { } WString GetCellDataText(const TColumn& cellData)override { return description::BoxValue<TColumn>(cellData).GetText(); } }; template<typename TRow, typename TColumn> class StrongTypedFieldColumnProvider : public StrongTypedColumnProvider<TRow, TColumn> { protected: TColumn TRow::* field; public: StrongTypedFieldColumnProvider(StrongTypedDataProvider<TRow>* _dataProvider, TColumn TRow::* _field) :StrongTypedColumnProvider(_dataProvider) ,field(_field) { } void GetCellData(const TRow& rowData, TColumn& cellData)override { cellData=rowData.*field; } }; template<typename TRow> class StrongTypedDataProvider : public StructuredDataProviderBase { protected: template<typename TColumn> Ptr<StrongTypedColumnProvider<TRow, TColumn>> AddStrongTypedColumn(const WString& text, Ptr<StrongTypedColumnProvider<TRow, TColumn>> column) { column->SetText(text); return AddColumnInternal(column, true)?column:0; } template<typename TColumn> Ptr<StrongTypedColumnProvider<TRow, TColumn>> AddSortableStrongTypedColumn(const WString& text, Ptr<StrongTypedColumnProvider<TRow, TColumn>> column) { if(AddStrongTypedColumn(text, column)) { column->SetInherentSorter(new StrongTypedColumnProvider<TRow, TColumn>::Sorter(column.Obj())); } return column; } template<typename TColumn> Ptr<StrongTypedColumnProvider<TRow, TColumn>> AddFieldColumn(const WString& text, TColumn TRow::* field) { Ptr<StrongTypedFieldColumnProvider<TRow, TColumn>> column=new StrongTypedFieldColumnProvider<TRow, TColumn>(this, field); return AddStrongTypedColumn<TColumn>(text, column); } template<typename TColumn> Ptr<StrongTypedColumnProvider<TRow, TColumn>> AddSortableFieldColumn(const WString& text, TColumn TRow::* field) { Ptr<StrongTypedFieldColumnProvider<TRow, TColumn>> column=new StrongTypedFieldColumnProvider<TRow, TColumn>(this, field); return AddSortableStrongTypedColumn<TColumn>(text, column); } public: StrongTypedDataProvider() { } virtual void GetRowData(vint row, TRow& rowData)=0; }; } } } } #endif /*********************************************************************** CONTROLS\LISTCONTROLPACKAGE\GUIDATAGRIDEXTENSIONS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIDATAEXTENSIONS #define VCZH_PRESENTATION_CONTROLS_GUIDATAEXTENSIONS namespace vl { namespace presentation { namespace controls { namespace list { /*********************************************************************** Extension Bases ***********************************************************************/ class DataVisualizerBase : public Object, public virtual IDataVisualizer { template<typename T> friend class DataVisualizerFactory; template<typename T> friend class DataDecoratableVisualizerFactory; protected: IDataVisualizerFactory* factory; FontProperties font; GuiListViewBase::IStyleProvider* styleProvider; compositions::GuiBoundsComposition* boundsComposition; Ptr<IDataVisualizer> decoratedDataVisualizer; virtual compositions::GuiBoundsComposition* CreateBoundsCompositionInternal(compositions::GuiBoundsComposition* decoratedComposition)=0; public: DataVisualizerBase(Ptr<IDataVisualizer> _decoratedDataVisualizer=0); ~DataVisualizerBase(); IDataVisualizerFactory* GetFactory()override; compositions::GuiBoundsComposition* GetBoundsComposition()override; void BeforeVisualizeCell(IDataProvider* dataProvider, vint row, vint column)override; IDataVisualizer* GetDecoratedDataVisualizer()override; void SetSelected(bool value)override; }; template<typename TVisualizer> class DataVisualizerFactory : public Object, public virtual IDataVisualizerFactory, public Description<DataVisualizerFactory<TVisualizer>> { public: Ptr<IDataVisualizer> CreateVisualizer(const FontProperties& font, GuiListViewBase::IStyleProvider* styleProvider)override { DataVisualizerBase* dataVisualizer=new TVisualizer; dataVisualizer->factory=this; dataVisualizer->font=font; dataVisualizer->styleProvider=styleProvider; return dataVisualizer; } }; template<typename TVisualizer> class DataDecoratableVisualizerFactory : public Object, public virtual IDataVisualizerFactory, public Description<DataDecoratableVisualizerFactory<TVisualizer>> { protected: Ptr<IDataVisualizerFactory> decoratedFactory; public: DataDecoratableVisualizerFactory(Ptr<IDataVisualizerFactory> _decoratedFactory) :decoratedFactory(_decoratedFactory) { } Ptr<IDataVisualizer> CreateVisualizer(const FontProperties& font, GuiListViewBase::IStyleProvider* styleProvider)override { Ptr<IDataVisualizer> decoratedDataVisualizer=decoratedFactory->CreateVisualizer(font, styleProvider); DataVisualizerBase* dataVisualizer=new TVisualizer(decoratedDataVisualizer); dataVisualizer->factory=this; dataVisualizer->font=font; dataVisualizer->styleProvider=styleProvider; return dataVisualizer; } }; class DataEditorBase : public Object, public virtual IDataEditor { template<typename T> friend class DataEditorFactory; protected: IDataEditorFactory* factory; IDataEditorCallback* callback; compositions::GuiBoundsComposition* boundsComposition; virtual compositions::GuiBoundsComposition* CreateBoundsCompositionInternal()=0; public: DataEditorBase(); ~DataEditorBase(); IDataEditorFactory* GetFactory()override; compositions::GuiBoundsComposition* GetBoundsComposition()override; void BeforeEditCell(IDataProvider* dataProvider, vint row, vint column)override; void ReinstallEditor()override; }; template<typename TEditor> class DataEditorFactory : public Object, public virtual IDataEditorFactory, public Description<DataEditorFactory<TEditor>> { public: Ptr<IDataEditor> CreateEditor(IDataEditorCallback* callback)override { DataEditorBase* dataEditor=new TEditor; dataEditor->factory=this; dataEditor->callback=callback; return dataEditor; } }; /*********************************************************************** Visualizer Extensions ***********************************************************************/ class ListViewMainColumnDataVisualizer : public DataVisualizerBase { public: typedef DataVisualizerFactory<ListViewMainColumnDataVisualizer> Factory; protected: elements::GuiImageFrameElement* image; elements::GuiSolidLabelElement* text; compositions::GuiBoundsComposition* CreateBoundsCompositionInternal(compositions::GuiBoundsComposition* decoratedComposition)override; public: ListViewMainColumnDataVisualizer(); void BeforeVisualizeCell(IDataProvider* dataProvider, vint row, vint column)override; elements::GuiSolidLabelElement* GetTextElement(); }; class ListViewSubColumnDataVisualizer : public DataVisualizerBase { public: typedef DataVisualizerFactory<ListViewSubColumnDataVisualizer> Factory; protected: elements::GuiSolidLabelElement* text; compositions::GuiBoundsComposition* CreateBoundsCompositionInternal(compositions::GuiBoundsComposition* decoratedComposition)override; public: ListViewSubColumnDataVisualizer(); void BeforeVisualizeCell(IDataProvider* dataProvider, vint row, vint column)override; elements::GuiSolidLabelElement* GetTextElement(); }; class HyperlinkDataVisualizer : public ListViewSubColumnDataVisualizer { public: typedef DataVisualizerFactory<HyperlinkDataVisualizer> Factory; protected: void label_MouseEnter(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void label_MouseLeave(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); compositions::GuiBoundsComposition* CreateBoundsCompositionInternal(compositions::GuiBoundsComposition* decoratedComposition)override; public: HyperlinkDataVisualizer(); void BeforeVisualizeCell(IDataProvider* dataProvider, vint row, vint column)override; }; class ImageDataVisualizer : public DataVisualizerBase { public: typedef DataVisualizerFactory<ImageDataVisualizer> Factory; protected: elements::GuiImageFrameElement* image; compositions::GuiBoundsComposition* CreateBoundsCompositionInternal(compositions::GuiBoundsComposition* decoratedComposition)override; public: ImageDataVisualizer(); void BeforeVisualizeCell(IDataProvider* dataProvider, vint row, vint column)override; elements::GuiImageFrameElement* GetImageElement(); }; class CellBorderDataVisualizer : public DataVisualizerBase { public: typedef DataDecoratableVisualizerFactory<CellBorderDataVisualizer> Factory; protected: compositions::GuiBoundsComposition* CreateBoundsCompositionInternal(compositions::GuiBoundsComposition* decoratedComposition)override; public: CellBorderDataVisualizer(Ptr<IDataVisualizer> decoratedDataVisualizer); void BeforeVisualizeCell(IDataProvider* dataProvider, vint row, vint column)override; }; class NotifyIconDataVisualizer : public DataVisualizerBase { public: typedef DataDecoratableVisualizerFactory<NotifyIconDataVisualizer> Factory; protected: elements::GuiImageFrameElement* leftImage; elements::GuiImageFrameElement* rightImage; compositions::GuiBoundsComposition* CreateBoundsCompositionInternal(compositions::GuiBoundsComposition* decoratedComposition)override; public: NotifyIconDataVisualizer(Ptr<IDataVisualizer> decoratedDataVisualizer); void BeforeVisualizeCell(IDataProvider* dataProvider, vint row, vint column)override; elements::GuiImageFrameElement* GetLeftImageElement(); elements::GuiImageFrameElement* GetRightImageElement(); }; /*********************************************************************** Editor Extensions ***********************************************************************/ class TextBoxDataEditor : public DataEditorBase { public: typedef DataEditorFactory<TextBoxDataEditor> Factory; protected: GuiSinglelineTextBox* textBox; void OnTextChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); compositions::GuiBoundsComposition* CreateBoundsCompositionInternal()override; public: TextBoxDataEditor(); void BeforeEditCell(IDataProvider* dataProvider, vint row, vint column)override; void ReinstallEditor()override; GuiSinglelineTextBox* GetTextBox(); }; class TextComboBoxDataEditor : public DataEditorBase { public: typedef DataEditorFactory<TextComboBoxDataEditor> Factory; protected: GuiComboBoxListControl* comboBox; GuiTextList* textList; void OnSelectedIndexChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); compositions::GuiBoundsComposition* CreateBoundsCompositionInternal()override; public: TextComboBoxDataEditor(); void BeforeEditCell(IDataProvider* dataProvider, vint row, vint column)override; GuiComboBoxListControl* GetComboBoxControl(); GuiTextList* GetTextListControl(); }; class DateComboBoxDataEditor : public DataEditorBase { public: typedef DataEditorFactory<DateComboBoxDataEditor> Factory; protected: GuiDateComboBox* comboBox; void OnSelectedDateChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); compositions::GuiBoundsComposition* CreateBoundsCompositionInternal()override; public: DateComboBoxDataEditor(); void BeforeEditCell(IDataProvider* dataProvider, vint row, vint column)override; GuiDateComboBox* GetComboBoxControl(); GuiDatePicker* GetDatePickerControl(); }; } } } } #endif /*********************************************************************** CONTROLS\LISTCONTROLPACKAGE\GUIDATAGRIDCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIDATAGRIDCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUIDATAGRIDCONTROLS namespace vl { namespace presentation { namespace controls { class GuiVirtualDataGrid; namespace list { /*********************************************************************** Datagrid ItemProvider ***********************************************************************/ class DataGridItemProvider : public Object , public virtual GuiListControl::IItemProvider , public virtual GuiListControl::IItemPrimaryTextView , public virtual ListViewItemStyleProvider::IListViewItemView , public virtual ListViewColumnItemArranger::IColumnItemView , protected virtual IDataProviderCommandExecutor , public Description<DataGridItemProvider> { protected: IDataProvider* dataProvider; collections::List<GuiListControl::IItemProviderCallback*> itemProviderCallbacks; collections::List<ListViewColumnItemArranger::IColumnItemViewCallback*> columnItemViewCallbacks; void InvokeOnItemModified(vint start, vint count, vint newCount); void InvokeOnColumnChanged(); void OnDataProviderColumnChanged()override; void OnDataProviderItemModified(vint start, vint count, vint newCount)override; public: DataGridItemProvider(IDataProvider* _dataProvider); ~DataGridItemProvider(); IDataProvider* GetDataProvider(); void SortByColumn(vint column, bool ascending=true); // ===================== GuiListControl::IItemProvider ===================== bool AttachCallback(GuiListControl::IItemProviderCallback* value)override; bool DetachCallback(GuiListControl::IItemProviderCallback* value)override; vint Count()override; IDescriptable* RequestView(const WString& identifier)override; void ReleaseView(IDescriptable* view)override; // ===================== GuiListControl::IItemPrimaryTextView ===================== WString GetPrimaryTextViewText(vint itemIndex)override; bool ContainsPrimaryText(vint itemIndex)override; // ===================== list::ListViewItemStyleProvider::IListViewItemView ===================== Ptr<GuiImageData> GetSmallImage(vint itemIndex)override; Ptr<GuiImageData> GetLargeImage(vint itemIndex)override; WString GetText(vint itemIndex)override; WString GetSubItem(vint itemIndex, vint index)override; vint GetDataColumnCount()override; vint GetDataColumn(vint index)override; // ===================== list::ListViewColumnItemArranger::IColumnItemView ===================== bool AttachCallback(ListViewColumnItemArranger::IColumnItemViewCallback* value)override; bool DetachCallback(ListViewColumnItemArranger::IColumnItemViewCallback* value)override; vint GetColumnCount()override; WString GetColumnText(vint index)override; vint GetColumnSize(vint index)override; void SetColumnSize(vint index, vint value)override; GuiMenu* GetDropdownPopup(vint index)override; GuiListViewColumnHeader::ColumnSortingState GetSortingState(vint index)override; }; /*********************************************************************** Datagrid ContentProvider ***********************************************************************/ class DataGridContentProvider : public Object , public virtual ListViewItemStyleProvider::IListViewItemContentProvider , protected virtual ListViewColumnItemArranger::IColumnItemViewCallback , protected virtual GuiListControl::IItemProviderCallback , protected virtual IDataEditorCallback , public Description<ListViewDetailContentProvider> { protected: class ItemContent : public Object, public virtual ListViewItemStyleProvider::IListViewItemContent { protected: compositions::GuiBoundsComposition* contentComposition; compositions::GuiTableComposition* textTable; DataGridContentProvider* contentProvider; FontProperties font; collections::Array<Ptr<IDataVisualizer>> dataVisualizers; IDataEditor* currentEditor; void RemoveCellsAndDataVisualizers(); IDataVisualizerFactory* GetDataVisualizerFactory(vint row, vint column); vint GetCellColumnIndex(compositions::GuiGraphicsComposition* composition); void OnCellButtonUp(compositions::GuiGraphicsComposition* sender, bool openEditor); bool IsInEditor(compositions::GuiMouseEventArgs& arguments); void OnCellButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnCellLeftButtonUp(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnCellRightButtonUp(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); public: ItemContent(DataGridContentProvider* _contentProvider, const FontProperties& _font); ~ItemContent(); compositions::GuiBoundsComposition* GetContentComposition()override; compositions::GuiBoundsComposition* GetBackgroundDecorator()override; void UpdateSubItemSize(); void ForceSetEditor(vint column, IDataEditor* editor); void NotifyCloseEditor(); void NotifySelectCell(vint column); void Install(GuiListViewBase::IStyleProvider* styleProvider, ListViewItemStyleProvider::IListViewItemView* view, vint itemIndex)override; void Uninstall()override; }; GuiVirtualDataGrid* dataGrid; GuiListControl::IItemProvider* itemProvider; list::IDataProvider* dataProvider; ListViewColumnItemArranger::IColumnItemView* columnItemView; ListViewItemStyleProvider* listViewItemStyleProvider; ListViewMainColumnDataVisualizer::Factory mainColumnDataVisualizerFactory; ListViewSubColumnDataVisualizer::Factory subColumnDataVisualizerFactory; GridPos currentCell; Ptr<IDataEditor> currentEditor; bool currentEditorRequestingSaveData; bool currentEditorOpening; void OnColumnChanged()override; void OnAttached(GuiListControl::IItemProvider* provider)override; void OnItemModified(vint start, vint count, vint newCount)override; void NotifyCloseEditor(); void NotifySelectCell(vint row, vint column); void RequestSaveData(); IDataEditor* OpenEditor(vint row, vint column, IDataEditorFactory* editorFactory); void CloseEditor(bool forOpenNewEditor); public: DataGridContentProvider(); ~DataGridContentProvider(); GuiListControl::IItemCoordinateTransformer* CreatePreferredCoordinateTransformer()override; GuiListControl::IItemArranger* CreatePreferredArranger()override; ListViewItemStyleProvider::IListViewItemContent* CreateItemContent(const FontProperties& font)override; void AttachListControl(GuiListControl* value)override; void DetachListControl()override; GridPos GetSelectedCell(); bool SetSelectedCell(const GridPos& value, bool openEditor); }; } /*********************************************************************** Virtual DataGrid Control ***********************************************************************/ class GuiVirtualDataGrid : public GuiVirtualListView, public Description<GuiVirtualDataGrid> { friend class list::DataGridContentProvider; protected: list::DataGridItemProvider* itemProvider; list::DataGridContentProvider* contentProvider; Ptr<list::IDataProvider> dataProvider; Ptr<list::StructuredDataProvider> structuredDataProvider; void OnColumnClicked(compositions::GuiGraphicsComposition* sender, compositions::GuiItemEventArgs& arguments); void Initialize(); void NotifySelectedCellChanged(); public: GuiVirtualDataGrid(IStyleProvider* _styleProvider, list::IDataProvider* _dataProvider); GuiVirtualDataGrid(IStyleProvider* _styleProvider, list::IStructuredDataProvider* _dataProvider); ~GuiVirtualDataGrid(); compositions::GuiNotifyEvent SelectedCellChanged; list::IDataProvider* GetDataProvider(); list::StructuredDataProvider* GetStructuredDataProvider(); GridPos GetSelectedCell(); void SetSelectedCell(const GridPos& value); Ptr<GuiListControl::IItemStyleProvider> SetStyleProvider(Ptr<GuiListControl::IItemStyleProvider> value)override; bool ChangeItemStyle(Ptr<list::ListViewItemStyleProvider::IListViewItemContentProvider> contentProvider)override; }; /*********************************************************************** StringGrid Control ***********************************************************************/ class GuiStringGrid; namespace list { class StringGridProvider; class StringGridItem { public: collections::List<WString> strings; }; class StringGridDataVisualizer : public ListViewSubColumnDataVisualizer { public: typedef DataVisualizerFactory<StringGridDataVisualizer> Factory; public: StringGridDataVisualizer(); void BeforeVisualizeCell(IDataProvider* dataProvider, vint row, vint column)override; void SetSelected(bool value)override; }; class StringGridColumn : public StrongTypedColumnProviderBase<Ptr<StringGridItem>, WString> { protected: StringGridProvider* provider; public: StringGridColumn(StringGridProvider* _provider); ~StringGridColumn(); void GetCellData(const Ptr<StringGridItem>& rowData, WString& cellData)override; void SetCellData(const Ptr<StringGridItem>& rowData, const WString& cellData); WString GetCellDataText(const WString& cellData)override; void BeforeEditCell(vint row, IDataEditor* dataEditor)override; void SaveCellData(vint row, IDataEditor* dataEditor)override; }; class StringGridProvider : private StrongTypedDataProvider<Ptr<StringGridItem>>, public Description<StringGridProvider> { friend class StringGridColumn; friend class GuiStringGrid; protected: bool readonly; collections::List<Ptr<StringGridItem>> items; Ptr<IDataVisualizerFactory> visualizerFactory; Ptr<IDataEditorFactory> editorFactory; void GetRowData(vint row, Ptr<StringGridItem>& rowData)override; bool GetReadonly(); void SetReadonly(bool value); public: StringGridProvider(); ~StringGridProvider(); vint GetRowCount()override; vint GetColumnCount()override; bool InsertRow(vint row); vint AppendRow(); bool MoveRow(vint source, vint target); bool RemoveRow(vint row); bool ClearRows(); WString GetGridString(vint row, vint column); bool SetGridString(vint row, vint column, const WString& value); bool InsertColumn(vint column, const WString& text, vint size=0); vint AppendColumn(const WString& text, vint size=0); bool MoveColumn(vint source, vint target); bool RemoveColumn(vint column); bool ClearColumns(); WString GetColumnText(vint column); bool SetColumnText(vint column, const WString& value); }; } class GuiStringGrid : public GuiVirtualDataGrid, public Description<GuiStringGrid> { protected: list::StringGridProvider* grids; public: GuiStringGrid(IStyleProvider* _styleProvider); ~GuiStringGrid(); list::StringGridProvider& Grids(); bool GetReadonly(); void SetReadonly(bool value); }; } } } #endif /*********************************************************************** CONTROLS\TOOLSTRIPPACKAGE\GUITOOLSTRIPCOMMAND.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITOOLSTRIPCOMMAND #define VCZH_PRESENTATION_CONTROLS_GUITOOLSTRIPCOMMAND namespace vl { namespace presentation { namespace controls { class GuiToolstripCommand : public GuiComponent, public Description<GuiToolstripCommand> { protected: Ptr<GuiImageData> image; WString text; compositions::IGuiShortcutKeyItem* shortcutKeyItem; bool enabled; Ptr<compositions::GuiNotifyEvent::IHandler> shortcutKeyItemExecutedHandler; void OnShortcutKeyItemExecuted(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void InvokeDescriptionChanged(); public: GuiToolstripCommand(); ~GuiToolstripCommand(); compositions::GuiNotifyEvent Executed; compositions::GuiNotifyEvent DescriptionChanged; Ptr<GuiImageData> GetImage(); void SetImage(Ptr<GuiImageData> value); const WString& GetText(); void SetText(const WString& value); compositions::IGuiShortcutKeyItem* GetShortcut(); void SetShortcut(compositions::IGuiShortcutKeyItem* value); bool GetEnabled(); void SetEnabled(bool value); }; } } } #endif /*********************************************************************** CONTROLS\TOOLSTRIPPACKAGE\GUITOOLSTRIPMENU.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITOOLSTRIPMENU #define VCZH_PRESENTATION_CONTROLS_GUITOOLSTRIPMENU namespace vl { namespace presentation { namespace theme { class ITheme; } namespace controls { /*********************************************************************** Toolstrip Item Collection ***********************************************************************/ class GuiToolstripCollection : public list::ItemsBase<GuiControl*> { public: class IContentCallback : public Interface { public: virtual void UpdateLayout()=0; }; protected: IContentCallback* contentCallback; compositions::GuiStackComposition* stackComposition; Ptr<compositions::GuiSubComponentMeasurer> subComponentMeasurer; void InvokeUpdateLayout(); void OnInterestingMenuButtonPropertyChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); bool RemoveAtInternal(vint index, GuiControl* const& control)override; bool InsertInternal(vint index, GuiControl* const& control)override; public: GuiToolstripCollection(IContentCallback* _contentCallback, compositions::GuiStackComposition* _stackComposition, Ptr<compositions::GuiSubComponentMeasurer> _subComponentMeasurer); ~GuiToolstripCollection(); }; /*********************************************************************** Toolstrip Builder Facade ***********************************************************************/ class GuiToolstripButton; class GuiToolstripBuilder : public Object { friend class GuiToolstripMenu; friend class GuiToolstripMenuBar; friend class GuiToolstripToolbar; protected: enum Environment { Menu, MenuBar, Toolbar, }; Environment environment; GuiToolstripCollection* toolstripItems; GuiToolstripBuilder* previousBuilder; theme::ITheme* theme; GuiToolstripButton* lastCreatedButton; GuiToolstripBuilder(Environment _environment, GuiToolstripCollection* _toolstripItems); public: ~GuiToolstripBuilder(); GuiToolstripBuilder* Button(Ptr<GuiImageData> image, const WString& text, GuiToolstripButton** result=0); GuiToolstripBuilder* Button(GuiToolstripCommand* command, GuiToolstripButton** result=0); GuiToolstripBuilder* DropdownButton(Ptr<GuiImageData> image, const WString& text, GuiToolstripButton** result=0); GuiToolstripBuilder* DropdownButton(GuiToolstripCommand* command, GuiToolstripButton** result=0); GuiToolstripBuilder* SplitButton(Ptr<GuiImageData> image, const WString& text, GuiToolstripButton** result=0); GuiToolstripBuilder* SplitButton(GuiToolstripCommand* command, GuiToolstripButton** result=0); GuiToolstripBuilder* Splitter(); GuiToolstripBuilder* Control(GuiControl* control); GuiToolstripBuilder* BeginSubMenu(); GuiToolstripBuilder* EndSubMenu(); }; /*********************************************************************** Toolstrip Container ***********************************************************************/ class GuiToolstripMenu : public GuiMenu, protected GuiToolstripCollection::IContentCallback, Description<GuiToolstripMenu> { protected: compositions::GuiStackComposition* stackComposition; Ptr<GuiToolstripCollection> toolstripItems; Ptr<compositions::GuiSubComponentMeasurer> subComponentMeasurer; Ptr<GuiToolstripBuilder> builder; void UpdateLayout()override; public: GuiToolstripMenu(IStyleController* _styleController, GuiControl* _owner); ~GuiToolstripMenu(); GuiToolstripCollection& GetToolstripItems(); GuiToolstripBuilder* GetBuilder(theme::ITheme* themeObject=0); }; class GuiToolstripMenuBar : public GuiMenuBar, public Description<GuiToolstripMenuBar> { protected: compositions::GuiStackComposition* stackComposition; Ptr<GuiToolstripCollection> toolstripItems; Ptr<GuiToolstripBuilder> builder; public: GuiToolstripMenuBar(IStyleController* _styleController); ~GuiToolstripMenuBar(); GuiToolstripCollection& GetToolstripItems(); GuiToolstripBuilder* GetBuilder(theme::ITheme* themeObject=0); }; class GuiToolstripToolbar : public GuiControl, public Description<GuiToolstripToolbar> { protected: compositions::GuiStackComposition* stackComposition; Ptr<GuiToolstripCollection> toolstripItems; Ptr<GuiToolstripBuilder> builder; public: GuiToolstripToolbar(IStyleController* _styleController); ~GuiToolstripToolbar(); GuiToolstripCollection& GetToolstripItems(); GuiToolstripBuilder* GetBuilder(theme::ITheme* themeObject=0); }; /*********************************************************************** Toolstrip Component ***********************************************************************/ class GuiToolstripButton : public GuiMenuButton, public Description<GuiToolstripButton> { protected: GuiToolstripCommand* command; Ptr<compositions::GuiNotifyEvent::IHandler> descriptionChangedHandler; void UpdateCommandContent(); void OnClicked(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnCommandDescriptionChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: GuiToolstripButton(IStyleController* _styleController); ~GuiToolstripButton(); GuiToolstripCommand* GetCommand(); void SetCommand(GuiToolstripCommand* value); GuiToolstripMenu* GetToolstripSubMenu(); void CreateToolstripSubMenu(GuiToolstripMenu::IStyleController* subMenuStyleController=0); }; } } namespace collections { namespace randomaccess_internal { template<> struct RandomAccessable<presentation::controls::GuiToolstripCollection> { static const bool CanRead = true; static const bool CanResize = false; }; } } } #endif /*********************************************************************** CONTROLS\STYLES\GUITHEMESTYLEFACTORY.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control Styles::Common Style Helpers Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITHEMESTYLEFACTORY #define VCZH_PRESENTATION_CONTROLS_GUITHEMESTYLEFACTORY namespace vl { namespace presentation { namespace theme { class ITheme : public virtual IDescriptable, public Description<ITheme> { public: virtual controls::GuiWindow::IStyleController* CreateWindowStyle()=0; virtual controls::GuiTooltip::IStyleController* CreateTooltipStyle()=0; virtual controls::GuiLabel::IStyleController* CreateLabelStyle()=0; virtual controls::GuiScrollContainer::IStyleProvider* CreateScrollContainerStyle()=0; virtual controls::GuiControl::IStyleController* CreateGroupBoxStyle()=0; virtual controls::GuiTab::IStyleController* CreateTabStyle()=0; virtual controls::GuiComboBoxBase::IStyleController* CreateComboBoxStyle()=0; virtual controls::GuiScrollView::IStyleProvider* CreateMultilineTextBoxStyle()=0; virtual controls::GuiSinglelineTextBox::IStyleProvider* CreateTextBoxStyle()=0; virtual elements::text::ColorEntry GetDefaultTextBoxColorEntry()=0; virtual controls::GuiDocumentViewer::IStyleProvider* CreateDocumentViewerStyle()=0; virtual controls::GuiDocumentLabel::IStyleController* CreateDocumentLabelStyle()=0; virtual controls::GuiListView::IStyleProvider* CreateListViewStyle()=0; virtual controls::GuiTreeView::IStyleProvider* CreateTreeViewStyle()=0; virtual controls::GuiSelectableButton::IStyleController* CreateListItemBackgroundStyle()=0; virtual controls::GuiToolstripMenu::IStyleController* CreateMenuStyle()=0; virtual controls::GuiToolstripMenuBar::IStyleController* CreateMenuBarStyle()=0; virtual controls::GuiControl::IStyleController* CreateMenuSplitterStyle()=0; virtual controls::GuiToolstripButton::IStyleController* CreateMenuBarButtonStyle()=0; virtual controls::GuiToolstripButton::IStyleController* CreateMenuItemButtonStyle()=0; virtual controls::GuiToolstripToolbar::IStyleController* CreateToolbarStyle()=0; virtual controls::GuiToolstripButton::IStyleController* CreateToolbarButtonStyle()=0; virtual controls::GuiToolstripButton::IStyleController* CreateToolbarDropdownButtonStyle()=0; virtual controls::GuiToolstripButton::IStyleController* CreateToolbarSplitButtonStyle()=0; virtual controls::GuiControl::IStyleController* CreateToolbarSplitterStyle()=0; virtual controls::GuiButton::IStyleController* CreateButtonStyle()=0; virtual controls::GuiSelectableButton::IStyleController* CreateCheckBoxStyle()=0; virtual controls::GuiSelectableButton::IStyleController* CreateRadioButtonStyle()=0; virtual controls::GuiDatePicker::IStyleProvider* CreateDatePickerStyle()=0; virtual controls::GuiScroll::IStyleController* CreateHScrollStyle()=0; virtual controls::GuiScroll::IStyleController* CreateVScrollStyle()=0; virtual controls::GuiScroll::IStyleController* CreateHTrackerStyle()=0; virtual controls::GuiScroll::IStyleController* CreateVTrackerStyle()=0; virtual controls::GuiScroll::IStyleController* CreateProgressBarStyle()=0; virtual vint GetScrollDefaultSize()=0; virtual vint GetTrackerDefaultSize()=0; virtual controls::GuiScrollView::IStyleProvider* CreateTextListStyle()=0; virtual controls::list::TextItemStyleProvider::ITextItemStyleProvider* CreateTextListItemStyle()=0; virtual controls::list::TextItemStyleProvider::ITextItemStyleProvider* CreateCheckTextListItemStyle()=0; virtual controls::list::TextItemStyleProvider::ITextItemStyleProvider* CreateRadioTextListItemStyle()=0; }; extern ITheme* GetCurrentTheme(); extern void SetCurrentTheme(ITheme* theam); namespace g { extern controls::GuiWindow* NewWindow(); extern controls::GuiLabel* NewLabel(); extern controls::GuiScrollContainer* NewScrollContainer(); extern controls::GuiControl* NewGroupBox(); extern controls::GuiTab* NewTab(); extern controls::GuiComboBoxListControl* NewComboBox(controls::GuiSelectableListControl* containedListControl); extern controls::GuiMultilineTextBox* NewMultilineTextBox(); extern controls::GuiSinglelineTextBox* NewTextBox(); extern controls::GuiDocumentViewer* NewDocumentViewer(); extern controls::GuiDocumentLabel* NewDocumentLabel(); extern controls::GuiListView* NewListViewBigIcon(); extern controls::GuiListView* NewListViewSmallIcon(); extern controls::GuiListView* NewListViewList(); extern controls::GuiListView* NewListViewDetail(); extern controls::GuiListView* NewListViewTile(); extern controls::GuiListView* NewListViewInformation(); extern controls::GuiTreeView* NewTreeView(); extern controls::GuiStringGrid* NewStringGrid(); extern controls::GuiToolstripMenu* NewMenu(controls::GuiControl* owner); extern controls::GuiToolstripMenuBar* NewMenuBar(); extern controls::GuiControl* NewMenuSplitter(); extern controls::GuiToolstripButton* NewMenuBarButton(); extern controls::GuiToolstripButton* NewMenuItemButton(); extern controls::GuiToolstripToolbar* NewToolbar(); extern controls::GuiToolstripButton* NewToolbarButton(); extern controls::GuiToolstripButton* NewToolbarDropdownButton(); extern controls::GuiToolstripButton* NewToolbarSplitButton(); extern controls::GuiControl* NewToolbarSplitter(); extern controls::GuiButton* NewButton(); extern controls::GuiSelectableButton* NewCheckBox(); extern controls::GuiSelectableButton* NewRadioButton(); extern controls::GuiDatePicker* NewDatePicker(); extern controls::GuiDateComboBox* NewDateComboBox(); extern controls::GuiScroll* NewHScroll(); extern controls::GuiScroll* NewVScroll(); extern controls::GuiScroll* NewHTracker(); extern controls::GuiScroll* NewVTracker(); extern controls::GuiScroll* NewProgressBar(); extern controls::GuiTextList* NewTextList(); extern controls::GuiTextList* NewCheckTextList(); extern controls::GuiTextList* NewRadioTextList(); } } } } #endif /*********************************************************************** CONTROLS\STYLES\GUIWIN7STYLES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control Styles::Windows7 Styles Clases: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIWIN7STYLES #define VCZH_PRESENTATION_CONTROLS_GUIWIN7STYLES namespace vl { namespace presentation { namespace win7 { /*********************************************************************** Theme ***********************************************************************/ class Win7Theme : public Object, public theme::ITheme { public: Win7Theme(); ~Win7Theme(); controls::GuiWindow::IStyleController* CreateWindowStyle()override; controls::GuiTooltip::IStyleController* CreateTooltipStyle()override; controls::GuiLabel::IStyleController* CreateLabelStyle()override; controls::GuiScrollContainer::IStyleProvider* CreateScrollContainerStyle()override; controls::GuiControl::IStyleController* CreateGroupBoxStyle()override; controls::GuiTab::IStyleController* CreateTabStyle()override; controls::GuiComboBoxBase::IStyleController* CreateComboBoxStyle()override; controls::GuiScrollView::IStyleProvider* CreateMultilineTextBoxStyle()override; controls::GuiSinglelineTextBox::IStyleProvider* CreateTextBoxStyle()override; elements::text::ColorEntry GetDefaultTextBoxColorEntry()override; controls::GuiDocumentViewer::IStyleProvider* CreateDocumentViewerStyle()override; controls::GuiDocumentLabel::IStyleController* CreateDocumentLabelStyle()override; controls::GuiListView::IStyleProvider* CreateListViewStyle()override; controls::GuiTreeView::IStyleProvider* CreateTreeViewStyle()override; controls::GuiSelectableButton::IStyleController* CreateListItemBackgroundStyle()override; controls::GuiToolstripMenu::IStyleController* CreateMenuStyle()override; controls::GuiToolstripMenuBar::IStyleController* CreateMenuBarStyle()override; controls::GuiControl::IStyleController* CreateMenuSplitterStyle()override; controls::GuiToolstripButton::IStyleController* CreateMenuBarButtonStyle()override; controls::GuiToolstripButton::IStyleController* CreateMenuItemButtonStyle()override; controls::GuiToolstripToolbar::IStyleController* CreateToolbarStyle()override; controls::GuiToolstripButton::IStyleController* CreateToolbarButtonStyle()override; controls::GuiToolstripButton::IStyleController* CreateToolbarDropdownButtonStyle()override; controls::GuiToolstripButton::IStyleController* CreateToolbarSplitButtonStyle()override; controls::GuiControl::IStyleController* CreateToolbarSplitterStyle()override; controls::GuiButton::IStyleController* CreateButtonStyle()override; controls::GuiSelectableButton::IStyleController* CreateCheckBoxStyle()override; controls::GuiSelectableButton::IStyleController* CreateRadioButtonStyle()override; controls::GuiDatePicker::IStyleProvider* CreateDatePickerStyle()override; controls::GuiScroll::IStyleController* CreateHScrollStyle()override; controls::GuiScroll::IStyleController* CreateVScrollStyle()override; controls::GuiScroll::IStyleController* CreateHTrackerStyle()override; controls::GuiScroll::IStyleController* CreateVTrackerStyle()override; controls::GuiScroll::IStyleController* CreateProgressBarStyle()override; vint GetScrollDefaultSize()override; vint GetTrackerDefaultSize()override; controls::GuiScrollView::IStyleProvider* CreateTextListStyle()override; controls::list::TextItemStyleProvider::ITextItemStyleProvider* CreateTextListItemStyle()override; controls::list::TextItemStyleProvider::ITextItemStyleProvider* CreateCheckTextListItemStyle()override; controls::list::TextItemStyleProvider::ITextItemStyleProvider* CreateRadioTextListItemStyle()override; }; } } } #endif /*********************************************************************** CONTROLS\STYLES\GUIWIN8STYLES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control Styles::Windows8 Styles Clases: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIWIN8STYLES #define VCZH_PRESENTATION_CONTROLS_GUIWIN8STYLES namespace vl { namespace presentation { namespace win8 { /*********************************************************************** Theme ***********************************************************************/ class Win8Theme : public Object, public theme::ITheme { public: Win8Theme(); ~Win8Theme(); controls::GuiWindow::IStyleController* CreateWindowStyle()override; controls::GuiTooltip::IStyleController* CreateTooltipStyle()override; controls::GuiLabel::IStyleController* CreateLabelStyle()override; controls::GuiScrollContainer::IStyleProvider* CreateScrollContainerStyle()override; controls::GuiControl::IStyleController* CreateGroupBoxStyle()override; controls::GuiTab::IStyleController* CreateTabStyle()override; controls::GuiComboBoxBase::IStyleController* CreateComboBoxStyle()override; controls::GuiScrollView::IStyleProvider* CreateMultilineTextBoxStyle()override; controls::GuiSinglelineTextBox::IStyleProvider* CreateTextBoxStyle()override; elements::text::ColorEntry GetDefaultTextBoxColorEntry()override; controls::GuiDocumentViewer::IStyleProvider* CreateDocumentViewerStyle()override; controls::GuiDocumentLabel::IStyleController* CreateDocumentLabelStyle()override; controls::GuiListView::IStyleProvider* CreateListViewStyle()override; controls::GuiTreeView::IStyleProvider* CreateTreeViewStyle()override; controls::GuiSelectableButton::IStyleController* CreateListItemBackgroundStyle()override; controls::GuiToolstripMenu::IStyleController* CreateMenuStyle()override; controls::GuiToolstripMenuBar::IStyleController* CreateMenuBarStyle()override; controls::GuiControl::IStyleController* CreateMenuSplitterStyle()override; controls::GuiToolstripButton::IStyleController* CreateMenuBarButtonStyle()override; controls::GuiToolstripButton::IStyleController* CreateMenuItemButtonStyle()override; controls::GuiToolstripToolbar::IStyleController* CreateToolbarStyle()override; controls::GuiToolstripButton::IStyleController* CreateToolbarButtonStyle()override; controls::GuiToolstripButton::IStyleController* CreateToolbarDropdownButtonStyle()override; controls::GuiToolstripButton::IStyleController* CreateToolbarSplitButtonStyle()override; controls::GuiControl::IStyleController* CreateToolbarSplitterStyle()override; controls::GuiButton::IStyleController* CreateButtonStyle()override; controls::GuiSelectableButton::IStyleController* CreateCheckBoxStyle()override; controls::GuiSelectableButton::IStyleController* CreateRadioButtonStyle()override; controls::GuiDatePicker::IStyleProvider* CreateDatePickerStyle()override; controls::GuiScroll::IStyleController* CreateHScrollStyle()override; controls::GuiScroll::IStyleController* CreateVScrollStyle()override; controls::GuiScroll::IStyleController* CreateHTrackerStyle()override; controls::GuiScroll::IStyleController* CreateVTrackerStyle()override; controls::GuiScroll::IStyleController* CreateProgressBarStyle()override; vint GetScrollDefaultSize()override; vint GetTrackerDefaultSize()override; controls::GuiScrollView::IStyleProvider* CreateTextListStyle()override; controls::list::TextItemStyleProvider::ITextItemStyleProvider* CreateTextListItemStyle()override; controls::list::TextItemStyleProvider::ITextItemStyleProvider* CreateCheckTextListItemStyle()override; controls::list::TextItemStyleProvider::ITextItemStyleProvider* CreateRadioTextListItemStyle()override; }; } } } #endif /*********************************************************************** GACUI.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI Header Files and Common Namespaces Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_GACUI #define VCZH_PRESENTATION_GACUI using namespace vl; using namespace vl::presentation; using namespace vl::presentation::elements; using namespace vl::presentation::compositions; using namespace vl::presentation::controls; using namespace vl::presentation::theme; extern int SetupWindowsGDIRenderer(); extern int SetupWindowsDirect2DRenderer(); #endif /*********************************************************************** REFLECTION\GUIREFLECTIONBASIC.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI Reflection: Basic Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_REFLECTION_GUIREFLECTIONBASIC #define VCZH_PRESENTATION_REFLECTION_GUIREFLECTIONBASIC namespace vl { namespace reflection { namespace description { #ifndef VCZH_DEBUG_NO_REFLECTION /*********************************************************************** Type List ***********************************************************************/ #define GUIREFLECTIONBASIC_TYPELIST(F)\ F(presentation::Color)\ F(presentation::Alignment)\ F(presentation::TextPos)\ F(presentation::GridPos)\ F(presentation::Point)\ F(presentation::Size)\ F(presentation::Rect)\ F(presentation::Margin)\ F(presentation::FontProperties)\ F(presentation::INativeImageFrame)\ F(presentation::INativeImage)\ F(presentation::INativeImage::FormatType)\ F(presentation::INativeCursor)\ F(presentation::INativeCursor::SystemCursorType)\ F(presentation::INativeWindow)\ F(presentation::INativeWindow::WindowSizeState)\ F(presentation::INativeDelay)\ F(presentation::INativeDelay::ExecuteStatus)\ F(presentation::GuiImageData)\ F(presentation::DocumentModel)\ F(presentation::GuiResource)\ F(presentation::elements::IGuiGraphicsElement)\ F(presentation::compositions::GuiGraphicsComposition)\ F(presentation::compositions::GuiGraphicsComposition::MinSizeLimitation)\ F(presentation::INativeWindowListener::HitTestResult)\ F(presentation::compositions::GuiGraphicsSite)\ F(presentation::compositions::GuiWindowComposition)\ F(presentation::compositions::GuiBoundsComposition)\ F(presentation::controls::GuiControl)\ F(presentation::controls::GuiControl::IStyleController)\ F(presentation::controls::GuiControl::IStyleProvider)\ F(presentation::controls::GuiComponent)\ F(presentation::controls::GuiControlHost)\ GUIREFLECTIONBASIC_TYPELIST(DECL_TYPE_INFO) /*********************************************************************** Type Declaration ***********************************************************************/ template<> struct TypedValueSerializerProvider<Color> { static bool Serialize(const Color& input, WString& output); static bool Deserialize(const WString& input, Color& output); }; template<> struct CustomTypeDescriptorSelector<Color> { public: typedef SerializableTypeDescriptor<TypedValueSerializer<Color>> CustomTypeDescriptorImpl; }; /*********************************************************************** Interface Proxy ***********************************************************************/ namespace interface_proxy { class GuiControl_IStyleController : public ValueInterfaceRoot, public virtual GuiControl::IStyleController { public: GuiControl_IStyleController(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static GuiControl::IStyleController* Create(Ptr<IValueInterfaceProxy> _proxy) { return new GuiControl_IStyleController(_proxy); } compositions::GuiBoundsComposition* GetBoundsComposition()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetBoundsComposition); } compositions::GuiGraphicsComposition* GetContainerComposition()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetContainerComposition); } void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override { INVOKE_INTERFACE_PROXY(SetFocusableComposition, value); } void SetText(const WString& value)override { INVOKE_INTERFACE_PROXY(SetText, value); } void SetFont(const FontProperties& value)override { INVOKE_INTERFACE_PROXY(SetFont, value); } void SetVisuallyEnabled(bool value)override { INVOKE_INTERFACE_PROXY(SetVisuallyEnabled, value); } }; class GuiControl_IStyleProvider : public ValueInterfaceRoot, public virtual GuiControl::IStyleProvider { public: GuiControl_IStyleProvider(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static GuiControl::IStyleProvider* Create(Ptr<IValueInterfaceProxy> _proxy) { return new GuiControl_IStyleProvider(_proxy); } void AssociateStyleController(GuiControl::IStyleController* controller)override { INVOKE_INTERFACE_PROXY(AssociateStyleController, controller); } void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override { INVOKE_INTERFACE_PROXY(SetFocusableComposition, value); } void SetText(const WString& value)override { INVOKE_INTERFACE_PROXY(SetText, value); } void SetFont(const FontProperties& value)override { INVOKE_INTERFACE_PROXY(SetFont, value); } void SetVisuallyEnabled(bool value)override { INVOKE_INTERFACE_PROXY(SetVisuallyEnabled, value); } }; } /*********************************************************************** Type Loader ***********************************************************************/ #endif extern bool LoadGuiBasicTypes(); } } } #endif /*********************************************************************** REFLECTION\GUIREFLECTIONELEMENTS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI Reflection: Elements Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_REFLECTION_GUIREFLECTIONELEMENTS #define VCZH_PRESENTATION_REFLECTION_GUIREFLECTIONELEMENTS namespace vl { namespace reflection { namespace description { #ifndef VCZH_DEBUG_NO_REFLECTION /*********************************************************************** Type List ***********************************************************************/ #define GUIREFLECTIONELEMENT_TYPELIST(F)\ F(presentation::elements::ElementShape)\ F(presentation::elements::GuiSolidBorderElement)\ F(presentation::elements::GuiRoundBorderElement)\ F(presentation::elements::Gui3DBorderElement)\ F(presentation::elements::Gui3DSplitterElement)\ F(presentation::elements::Gui3DSplitterElement::Direction)\ F(presentation::elements::GuiSolidBackgroundElement)\ F(presentation::elements::GuiGradientBackgroundElement)\ F(presentation::elements::GuiGradientBackgroundElement::Direction)\ F(presentation::elements::GuiSolidLabelElement)\ F(presentation::elements::GuiImageFrameElement)\ F(presentation::elements::GuiPolygonElement)\ F(presentation::elements::text::TextLines)\ F(presentation::elements::text::ColorItem)\ F(presentation::elements::text::ColorEntry)\ F(presentation::elements::GuiColorizedTextElement)\ F(presentation::elements::GuiDocumentElement)\ GUIREFLECTIONELEMENT_TYPELIST(DECL_TYPE_INFO) /*********************************************************************** Type Loader ***********************************************************************/ #endif extern bool LoadGuiElementTypes(); } } } #endif /*********************************************************************** REFLECTION\GUIREFLECTIONCOMPOSITIONS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI Reflection: Compositions Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_REFLECTION_GUIREFLECTIONCOMPOSITIONS #define VCZH_PRESENTATION_REFLECTION_GUIREFLECTIONCOMPOSITIONS namespace vl { namespace reflection { namespace description { #ifndef VCZH_DEBUG_NO_REFLECTION /*********************************************************************** Type List ***********************************************************************/ #define GUIREFLECTIONCOMPOSITION_TYPELIST(F)\ F(presentation::compositions::GuiStackComposition)\ F(presentation::compositions::GuiStackComposition::Direction)\ F(presentation::compositions::GuiStackItemComposition)\ F(presentation::compositions::GuiCellOption)\ F(presentation::compositions::GuiCellOption::ComposeType)\ F(presentation::compositions::GuiTableComposition)\ F(presentation::compositions::GuiCellComposition)\ F(presentation::compositions::GuiSideAlignedComposition)\ F(presentation::compositions::GuiSideAlignedComposition::Direction)\ F(presentation::compositions::GuiPartialViewComposition)\ F(presentation::compositions::GuiSubComponentMeasurer)\ F(presentation::compositions::GuiSubComponentMeasurer::Direction)\ F(presentation::compositions::GuiSubComponentMeasurer::IMeasuringSource)\ F(presentation::compositions::GuiSubComponentMeasurer::MeasuringSource)\ F(presentation::compositions::IGuiGraphicsAnimation)\ F(presentation::compositions::GuiGraphicsAnimationManager)\ F(presentation::compositions::IGuiShortcutKeyItem)\ F(presentation::compositions::IGuiShortcutKeyManager)\ F(presentation::compositions::GuiShortcutKeyManager)\ GUIREFLECTIONCOMPOSITION_TYPELIST(DECL_TYPE_INFO) /*********************************************************************** Interface Proxy ***********************************************************************/ #pragma warning(push) #pragma warning(disable:4250) namespace interface_proxy { class GuiSubComponentMeasurer_IMeasuringSource : public ValueInterfaceRoot, public virtual GuiSubComponentMeasurer::IMeasuringSource { public: GuiSubComponentMeasurer_IMeasuringSource(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<GuiSubComponentMeasurer::IMeasuringSource> Create(Ptr<IValueInterfaceProxy> proxy) { return new GuiSubComponentMeasurer_IMeasuringSource(proxy); } void AttachMeasurer(GuiSubComponentMeasurer* value)override { INVOKE_INTERFACE_PROXY(AttachMeasurer, value); } void DetachMeasurer(GuiSubComponentMeasurer* value)override { INVOKE_INTERFACE_PROXY(DetachMeasurer, value); } GuiSubComponentMeasurer* GetAttachedMeasurer()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetAttachedMeasurer); } WString GetMeasuringCategory()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetMeasuringCategory); } vint GetSubComponentCount()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetSubComponentCount); } WString GetSubComponentName(vint index)override { return INVOKEGET_INTERFACE_PROXY(GetSubComponentName, index); } GuiGraphicsComposition* GetSubComponentComposition(vint index)override { return INVOKEGET_INTERFACE_PROXY(GetSubComponentComposition, index); } GuiGraphicsComposition* GetSubComponentComposition(const WString& name)override { return INVOKEGET_INTERFACE_PROXY(GetSubComponentComposition, name); } GuiGraphicsComposition* GetMainComposition()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetMainComposition); } void SubComponentPreferredMinSizeUpdated()override { INVOKE_INTERFACE_PROXY_NOPARAM(SubComponentPreferredMinSizeUpdated); } }; class composition_IGuiGraphicsAnimation : public ValueInterfaceRoot, public virtual IGuiGraphicsAnimation { public: composition_IGuiGraphicsAnimation(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<IGuiGraphicsAnimation> Create(Ptr<IValueInterfaceProxy> proxy) { return new composition_IGuiGraphicsAnimation(proxy); } vint GetTotalLength()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetTotalLength); } vint GetCurrentPosition()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetCurrentPosition); } void Play(vint currentPosition, vint totalLength)override { INVOKE_INTERFACE_PROXY(Play, currentPosition, totalLength); } void Stop()override { INVOKE_INTERFACE_PROXY_NOPARAM(Stop); } }; } #pragma warning(pop) /*********************************************************************** Type Loader ***********************************************************************/ #endif extern bool LoadGuiCompositionTypes(); } } } #endif /*********************************************************************** REFLECTION\GUIREFLECTIONCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI Reflection: Basic Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_REFLECTION_GUIREFLECTIONCONTROLS #define VCZH_PRESENTATION_REFLECTION_GUIREFLECTIONCONTROLS namespace vl { namespace reflection { namespace description { #ifndef VCZH_DEBUG_NO_REFLECTION /*********************************************************************** Type List ***********************************************************************/ #define GUIREFLECTIONCONTROLS_TYPELIST(F)\ F(presentation::controls::GuiApplication)\ F(presentation::theme::ITheme)\ F(presentation::controls::GuiLabel)\ F(presentation::controls::GuiLabel::IStyleController)\ F(presentation::controls::GuiButton)\ F(presentation::controls::GuiButton::ControlState)\ F(presentation::controls::GuiButton::IStyleController)\ F(presentation::controls::GuiSelectableButton)\ F(presentation::controls::GuiSelectableButton::IStyleController)\ F(presentation::controls::GuiSelectableButton::GroupController)\ F(presentation::controls::GuiSelectableButton::MutexGroupController)\ F(presentation::controls::GuiScroll)\ F(presentation::controls::GuiScroll::ICommandExecutor)\ F(presentation::controls::GuiScroll::IStyleController)\ F(presentation::controls::GuiTabPage)\ F(presentation::controls::GuiTab)\ F(presentation::controls::GuiTab::ICommandExecutor)\ F(presentation::controls::GuiTab::IStyleController)\ F(presentation::controls::GuiScrollView)\ F(presentation::controls::GuiScrollView::IStyleProvider)\ F(presentation::controls::GuiScrollContainer)\ F(presentation::controls::GuiWindow)\ F(presentation::controls::GuiWindow::IStyleController)\ F(presentation::controls::GuiPopup)\ F(presentation::controls::GuiTooltip)\ F(presentation::controls::GuiListControl)\ F(presentation::controls::GuiListControl::IItemProviderCallback)\ F(presentation::controls::GuiListControl::IItemArrangerCallback)\ F(presentation::controls::GuiListControl::IItemPrimaryTextView)\ F(presentation::controls::GuiListControl::KeyDirection)\ F(presentation::controls::GuiListControl::IItemProvider)\ F(presentation::controls::GuiListControl::IItemStyleController)\ F(presentation::controls::GuiListControl::IItemStyleProvider)\ F(presentation::controls::GuiListControl::IItemArranger)\ F(presentation::controls::GuiListControl::IItemCoordinateTransformer)\ F(presentation::controls::GuiSelectableListControl)\ F(presentation::controls::GuiSelectableListControl::IItemStyleProvider)\ F(presentation::controls::list::DefaultItemCoordinateTransformer)\ F(presentation::controls::list::AxisAlignedItemCoordinateTransformer)\ F(presentation::controls::list::AxisAlignedItemCoordinateTransformer::Alignment)\ F(presentation::controls::list::RangedItemArrangerBase)\ F(presentation::controls::list::FixedHeightItemArranger)\ F(presentation::controls::list::FixedSizeMultiColumnItemArranger)\ F(presentation::controls::list::FixedHeightMultiColumnItemArranger)\ F(presentation::controls::list::ItemStyleControllerBase)\ F(presentation::controls::list::ItemProviderBase)\ F(presentation::controls::list::TextItemStyleProvider)\ F(presentation::controls::list::TextItemStyleProvider::ITextItemStyleProvider)\ F(presentation::controls::list::TextItemStyleProvider::ITextItemView)\ F(presentation::controls::list::TextItemStyleProvider::TextItemStyleController)\ F(presentation::controls::list::TextItem)\ F(presentation::controls::list::TextItemProvider)\ F(presentation::controls::GuiVirtualTextList)\ F(presentation::controls::GuiTextList)\ F(presentation::controls::list::ListViewItemStyleProviderBase)\ F(presentation::controls::list::ListViewItemStyleProviderBase::ListViewItemStyleController)\ F(presentation::controls::GuiListViewColumnHeader)\ F(presentation::controls::GuiListViewColumnHeader::ColumnSortingState)\ F(presentation::controls::GuiListViewColumnHeader::IStyleController)\ F(presentation::controls::GuiListViewBase)\ F(presentation::controls::GuiListViewBase::IStyleProvider)\ F(presentation::controls::list::ListViewItemStyleProvider)\ F(presentation::controls::list::ListViewItemStyleProvider::IListViewItemView)\ F(presentation::controls::list::ListViewItemStyleProvider::IListViewItemContent)\ F(presentation::controls::list::ListViewItemStyleProvider::IListViewItemContentProvider)\ F(presentation::controls::list::ListViewItemStyleProvider::ListViewContentItemStyleController)\ F(presentation::controls::list::ListViewBigIconContentProvider)\ F(presentation::controls::list::ListViewSmallIconContentProvider)\ F(presentation::controls::list::ListViewListContentProvider)\ F(presentation::controls::list::ListViewTileContentProvider)\ F(presentation::controls::list::ListViewInformationContentProvider)\ F(presentation::controls::list::ListViewColumnItemArranger)\ F(presentation::controls::list::ListViewColumnItemArranger::IColumnItemViewCallback)\ F(presentation::controls::list::ListViewColumnItemArranger::IColumnItemView)\ F(presentation::controls::list::ListViewDetailContentProvider)\ F(presentation::controls::list::ListViewItem)\ F(presentation::controls::list::ListViewColumn)\ F(presentation::controls::GuiVirtualListView)\ F(presentation::controls::GuiListView)\ F(presentation::controls::IGuiMenuService)\ F(presentation::controls::IGuiMenuService::Direction)\ F(presentation::controls::GuiMenu)\ F(presentation::controls::GuiMenuBar)\ F(presentation::controls::GuiMenuButton)\ F(presentation::controls::GuiMenuButton::IStyleController)\ F(presentation::controls::tree::INodeProviderCallback)\ F(presentation::controls::tree::INodeProvider)\ F(presentation::controls::tree::INodeRootProvider)\ F(presentation::controls::tree::INodeItemView)\ F(presentation::controls::tree::INodeItemPrimaryTextView)\ F(presentation::controls::tree::NodeItemProvider)\ F(presentation::controls::tree::INodeItemStyleController)\ F(presentation::controls::tree::INodeItemStyleProvider)\ F(presentation::controls::tree::NodeItemStyleProvider)\ F(presentation::controls::tree::IMemoryNodeData)\ F(presentation::controls::tree::MemoryNodeProvider)\ F(presentation::controls::tree::NodeRootProviderBase)\ F(presentation::controls::tree::MemoryNodeRootProvider)\ F(presentation::controls::GuiVirtualTreeListControl)\ F(presentation::controls::tree::ITreeViewItemView)\ F(presentation::controls::tree::TreeViewItem)\ F(presentation::controls::tree::TreeViewItemRootProvider)\ F(presentation::controls::GuiVirtualTreeView)\ F(presentation::controls::GuiVirtualTreeView::IStyleProvider)\ F(presentation::controls::GuiTreeView)\ F(presentation::controls::tree::TreeViewNodeItemStyleProvider)\ F(presentation::controls::GuiComboBoxBase)\ F(presentation::controls::GuiComboBoxBase::ICommandExecutor)\ F(presentation::controls::GuiComboBoxBase::IStyleController)\ F(presentation::controls::GuiComboBoxListControl)\ F(presentation::controls::GuiToolstripCommand)\ F(presentation::controls::GuiToolstripMenu)\ F(presentation::controls::GuiToolstripMenuBar)\ F(presentation::controls::GuiToolstripToolbar)\ F(presentation::controls::GuiToolstripButton)\ F(presentation::controls::GuiDocumentCommonInterface)\ F(presentation::controls::GuiDocumentViewer)\ F(presentation::controls::GuiDocumentLabel)\ F(presentation::controls::GuiTextBoxCommonInterface)\ F(presentation::controls::ILanguageProvider)\ F(presentation::controls::RepeatingParsingExecutor)\ F(presentation::controls::GuiTextBoxColorizerBase)\ F(presentation::controls::GuiTextBoxRegexColorizer)\ F(presentation::controls::GuiGrammarColorizer)\ F(presentation::controls::GuiTextBoxAutoCompleteBase)\ F(presentation::controls::GuiGrammarAutoComplete)\ F(presentation::controls::GuiMultilineTextBox)\ F(presentation::controls::GuiSinglelineTextBox)\ F(presentation::controls::GuiSinglelineTextBox::IStyleProvider)\ F(presentation::controls::list::IDataVisualizerFactory)\ F(presentation::controls::list::IDataVisualizer)\ F(presentation::controls::list::IDataEditorCallback)\ F(presentation::controls::list::IDataEditorFactory)\ F(presentation::controls::list::IDataEditor)\ F(presentation::controls::list::IDataProviderCommandExecutor)\ F(presentation::controls::list::IDataProvider)\ F(presentation::controls::list::IStructuredDataFilterCommandExecutor)\ F(presentation::controls::list::IStructuredDataFilter)\ F(presentation::controls::list::IStructuredDataSorter)\ F(presentation::controls::list::IStructuredColumnProvider)\ F(presentation::controls::list::IStructuredDataProvider)\ F(presentation::controls::list::DataGridContentProvider)\ F(presentation::controls::GuiVirtualDataGrid)\ F(presentation::controls::list::StructuredDataFilterBase)\ F(presentation::controls::list::StructuredDataMultipleFilter)\ F(presentation::controls::list::StructuredDataAndFilter)\ F(presentation::controls::list::StructuredDataOrFilter)\ F(presentation::controls::list::StructuredDataNotFilter)\ F(presentation::controls::list::StructuredDataMultipleSorter)\ F(presentation::controls::list::StructuredDataReverseSorter)\ F(presentation::controls::list::StructuredDataProvider)\ F(presentation::controls::list::ListViewMainColumnDataVisualizer)\ F(presentation::controls::list::ListViewMainColumnDataVisualizer::Factory)\ F(presentation::controls::list::ListViewSubColumnDataVisualizer)\ F(presentation::controls::list::ListViewSubColumnDataVisualizer::Factory)\ F(presentation::controls::list::HyperlinkDataVisualizer)\ F(presentation::controls::list::HyperlinkDataVisualizer::Factory)\ F(presentation::controls::list::ImageDataVisualizer)\ F(presentation::controls::list::ImageDataVisualizer::Factory)\ F(presentation::controls::list::CellBorderDataVisualizer)\ F(presentation::controls::list::CellBorderDataVisualizer::Factory)\ F(presentation::controls::list::NotifyIconDataVisualizer)\ F(presentation::controls::list::NotifyIconDataVisualizer::Factory)\ F(presentation::controls::list::TextBoxDataEditor)\ F(presentation::controls::list::TextBoxDataEditor::Factory)\ F(presentation::controls::list::TextComboBoxDataEditor)\ F(presentation::controls::list::TextComboBoxDataEditor::Factory)\ F(presentation::controls::list::DateComboBoxDataEditor)\ F(presentation::controls::list::DateComboBoxDataEditor::Factory)\ F(presentation::controls::GuiDatePicker)\ F(presentation::controls::GuiDatePicker::IStyleProvider)\ F(presentation::controls::GuiDateComboBox)\ F(presentation::controls::GuiStringGrid)\ F(presentation::controls::list::StringGridProvider)\ GUIREFLECTIONCONTROLS_TYPELIST(DECL_TYPE_INFO) /*********************************************************************** Interface Proxy ***********************************************************************/ #pragma warning(push) #pragma warning(disable:4250) namespace interface_proxy { class GuiLabel_IStyleController : public virtual GuiControl_IStyleController, public virtual GuiLabel::IStyleController { public: GuiLabel_IStyleController(Ptr<IValueInterfaceProxy> _proxy) :GuiControl_IStyleController(_proxy) { } static GuiLabel::IStyleController* Create(Ptr<IValueInterfaceProxy> _proxy) { return new GuiLabel_IStyleController(_proxy); } Color GetDefaultTextColor()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetDefaultTextColor); } void SetTextColor(Color value)override { INVOKE_INTERFACE_PROXY(SetTextColor, value); } }; class GuiButton_IStyleController : public virtual GuiControl_IStyleController, public virtual GuiButton::IStyleController { public: GuiButton_IStyleController(Ptr<IValueInterfaceProxy> _proxy) :GuiControl_IStyleController(_proxy) { } static GuiButton::IStyleController* Create(Ptr<IValueInterfaceProxy> _proxy) { return new GuiButton_IStyleController(_proxy); } void Transfer(GuiButton::ControlState value)override { INVOKE_INTERFACE_PROXY(Transfer, value); } }; class GuiSelectableButton_IStyleController : public virtual GuiButton_IStyleController, public virtual GuiSelectableButton::IStyleController { public: GuiSelectableButton_IStyleController(Ptr<IValueInterfaceProxy> _proxy) :GuiControl_IStyleController(_proxy) ,GuiButton_IStyleController(_proxy) { } static GuiSelectableButton::IStyleController* Create(Ptr<IValueInterfaceProxy> _proxy) { return new GuiSelectableButton_IStyleController(_proxy); } void SetSelected(bool value)override { INVOKE_INTERFACE_PROXY(SetSelected, value); } }; class GuiScroll_IStyleController : public virtual GuiControl_IStyleController, public virtual GuiScroll::IStyleController { public: GuiScroll_IStyleController(Ptr<IValueInterfaceProxy> _proxy) :GuiControl_IStyleController(_proxy) { } static GuiScroll::IStyleController* Create(Ptr<IValueInterfaceProxy> _proxy) { return new GuiScroll_IStyleController(_proxy); } void SetCommandExecutor(GuiScroll::ICommandExecutor* value)override { INVOKE_INTERFACE_PROXY(SetCommandExecutor, value); } void SetTotalSize(vint value)override { INVOKE_INTERFACE_PROXY(SetTotalSize, value); } void SetPageSize(vint value)override { INVOKE_INTERFACE_PROXY(SetPageSize, value); } void SetPosition(vint value)override { INVOKE_INTERFACE_PROXY(SetPosition, value); } }; class GuiTab_IStyleController : public virtual GuiControl_IStyleController, public virtual GuiTab::IStyleController { public: GuiTab_IStyleController(Ptr<IValueInterfaceProxy> _proxy) :GuiControl_IStyleController(_proxy) { } static GuiTab::IStyleController* Create(Ptr<IValueInterfaceProxy> _proxy) { return new GuiTab_IStyleController(_proxy); } void SetCommandExecutor(GuiTab::ICommandExecutor* value)override { INVOKE_INTERFACE_PROXY(SetCommandExecutor, value); } void InsertTab(vint index)override { INVOKE_INTERFACE_PROXY(InsertTab, index); } void SetTabText(vint index, const WString& value)override { INVOKE_INTERFACE_PROXY(SetTabText, index, value); } void RemoveTab(vint index)override { INVOKE_INTERFACE_PROXY(RemoveTab, index); } void MoveTab(vint oldIndex, vint newIndex)override { INVOKE_INTERFACE_PROXY(MoveTab, oldIndex, newIndex); } void SetSelectedTab(vint index)override { INVOKE_INTERFACE_PROXY(SetSelectedTab, index); } GuiControl::IStyleController* CreateTabPageStyleController()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(CreateTabPageStyleController); } }; class GuiScrollView_IStyleProvider : public virtual GuiControl_IStyleProvider, public virtual GuiScrollView::IStyleProvider { public: GuiScrollView_IStyleProvider(Ptr<IValueInterfaceProxy> _proxy) :GuiControl_IStyleProvider(_proxy) { } static GuiScrollView::IStyleProvider* Create(Ptr<IValueInterfaceProxy> _proxy) { return new GuiScrollView_IStyleProvider(_proxy); } GuiScroll::IStyleController* CreateHorizontalScrollStyle()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(CreateHorizontalScrollStyle); } GuiScroll::IStyleController* CreateVerticalScrollStyle()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(CreateVerticalScrollStyle); } vint GetDefaultScrollSize()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetDefaultScrollSize); } compositions::GuiGraphicsComposition* InstallBackground(compositions::GuiBoundsComposition* boundsComposition)override { return INVOKEGET_INTERFACE_PROXY(InstallBackground, boundsComposition); } }; class GuiWindow_IStyleController : public virtual GuiControl_IStyleController, public virtual GuiWindow::IStyleController { public: GuiWindow_IStyleController(Ptr<IValueInterfaceProxy> _proxy) :GuiControl_IStyleController(_proxy) { } static GuiWindow::IStyleController* Create(Ptr<IValueInterfaceProxy> _proxy) { return new GuiWindow_IStyleController(_proxy); } void AttachWindow(GuiWindow* _window)override { INVOKE_INTERFACE_PROXY(ActiveWindow, _window); } void InitializeNativeWindowProperties()override { INVOKE_INTERFACE_PROXY_NOPARAM(InitializeNativeWindowProperties); } bool GetMaximizedBox()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetMaximizedBox); } void SetMaximizedBox(bool visible)override { INVOKE_INTERFACE_PROXY(SetMaximizedBox, visible); } bool GetMinimizedBox()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetMinimizedBox); } void SetMinimizedBox(bool visible)override { INVOKE_INTERFACE_PROXY(SetMinimizedBox, visible); } bool GetBorder()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetBorder); } void SetBorder(bool visible)override { INVOKE_INTERFACE_PROXY(SetBorder, visible); } bool GetSizeBox()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetSizeBox); } void SetSizeBox(bool visible)override { INVOKE_INTERFACE_PROXY(SetSizeBox, visible); } bool GetIconVisible()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetIconVisible); } void SetIconVisible(bool visible)override { INVOKE_INTERFACE_PROXY(SetIconVisible, visible); } bool GetTitleBar()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetTitleBar); } void SetTitleBar(bool visible)override { INVOKE_INTERFACE_PROXY(SetTitleBar, visible); } }; class GuiListControl_IItemProviderCallback : public ValueInterfaceRoot, public virtual GuiListControl::IItemProviderCallback { public: GuiListControl_IItemProviderCallback(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<GuiListControl::IItemProviderCallback> Create(Ptr<IValueInterfaceProxy> proxy) { return new GuiListControl_IItemProviderCallback(proxy); } void OnAttached(GuiListControl::IItemProvider* provider)override { INVOKE_INTERFACE_PROXY(OnAttached, provider); } void OnItemModified(vint start, vint count, vint newCount)override { INVOKE_INTERFACE_PROXY(OnItemModified, start, count, newCount); } }; class GuiListControl_IItemPrimaryTextView : public ValueInterfaceRoot, public virtual GuiListControl::IItemPrimaryTextView { public: GuiListControl_IItemPrimaryTextView(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<GuiListControl::IItemPrimaryTextView> Create(Ptr<IValueInterfaceProxy> proxy) { return new GuiListControl_IItemPrimaryTextView(proxy); } WString GetPrimaryTextViewText(vint itemIndex)override { return INVOKEGET_INTERFACE_PROXY(GetPrimaryTextViewText, itemIndex); } bool ContainsPrimaryText(vint itemIndex)override { return INVOKEGET_INTERFACE_PROXY(ContainsPrimaryText, itemIndex); } }; class GuiListControl_IItemProvider : public ValueInterfaceRoot, public virtual GuiListControl::IItemProvider { public: GuiListControl_IItemProvider(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static GuiListControl::IItemProvider* Create(Ptr<IValueInterfaceProxy> proxy) { return new GuiListControl_IItemProvider(proxy); } bool AttachCallback(GuiListControl::IItemProviderCallback* value)override { return INVOKEGET_INTERFACE_PROXY(AttachCallback, value); } bool DetachCallback(GuiListControl::IItemProviderCallback* value)override { return INVOKEGET_INTERFACE_PROXY(DetachCallback, value); } vint Count()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(Count); } IDescriptable* RequestView(const WString& identifier)override { return INVOKEGET_INTERFACE_PROXY(RequestView, identifier); } void ReleaseView(IDescriptable* view)override { INVOKE_INTERFACE_PROXY(ReleaseView, view); } }; class GuiListControl_IItemStyleController : public ValueInterfaceRoot, public virtual GuiListControl::IItemStyleController { public: GuiListControl_IItemStyleController(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static GuiListControl::IItemStyleController* Create(Ptr<IValueInterfaceProxy> proxy) { return new GuiListControl_IItemStyleController(proxy); } GuiListControl::IItemStyleProvider* GetStyleProvider()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetStyleProvider); } vint GetItemStyleId()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetItemStyleId); } compositions::GuiBoundsComposition* GetBoundsComposition()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetBoundsComposition); } bool IsCacheable()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(IsCacheable); } bool IsInstalled()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(IsInstalled); } void OnInstalled()override { INVOKE_INTERFACE_PROXY_NOPARAM(OnInstalled); } void OnUninstalled()override { INVOKE_INTERFACE_PROXY_NOPARAM(OnUninstalled); } }; class GuiListControl_IItemStyleProvider : public ValueInterfaceRoot, public virtual GuiListControl::IItemStyleProvider { public: GuiListControl_IItemStyleProvider(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<GuiListControl::IItemStyleProvider> Create(Ptr<IValueInterfaceProxy> proxy) { return new GuiListControl_IItemStyleProvider(proxy); } void AttachListControl(GuiListControl* value)override { INVOKE_INTERFACE_PROXY(AttachListControl, value); } void DetachListControl()override { INVOKE_INTERFACE_PROXY_NOPARAM(DetachListControl); } vint GetItemStyleId(vint itemIndex)override { return INVOKEGET_INTERFACE_PROXY(GetItemStyleId, itemIndex); } GuiListControl::IItemStyleController* CreateItemStyle(vint styleId)override { return INVOKEGET_INTERFACE_PROXY(CreateItemStyle, styleId); } void DestroyItemStyle(GuiListControl::IItemStyleController* style)override { INVOKE_INTERFACE_PROXY(DestroyItemStyle, style); } void Install(GuiListControl::IItemStyleController* style, vint itemIndex)override { INVOKE_INTERFACE_PROXY(Install, style, itemIndex); } }; class GuiListControl_IItemArranger : public virtual GuiListControl_IItemProviderCallback, public virtual GuiListControl::IItemArranger { public: GuiListControl_IItemArranger(Ptr<IValueInterfaceProxy> _proxy) :GuiListControl_IItemProviderCallback(_proxy) { } static Ptr<GuiListControl::IItemArranger> Create(Ptr<IValueInterfaceProxy> proxy) { return new GuiListControl_IItemArranger(proxy); } void AttachListControl(GuiListControl* value)override { INVOKE_INTERFACE_PROXY(AttachListControl, value); } void DetachListControl()override { INVOKE_INTERFACE_PROXY(DetachListControl); } GuiListControl::IItemArrangerCallback* GetCallback()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetCallback); } void SetCallback(GuiListControl::IItemArrangerCallback* value)override { INVOKE_INTERFACE_PROXY(SetCallback, value); } Size GetTotalSize()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetTotalSize); } GuiListControl::IItemStyleController* GetVisibleStyle(vint itemIndex)override { return INVOKEGET_INTERFACE_PROXY(GetVisibleStyle, itemIndex); } vint GetVisibleIndex(GuiListControl::IItemStyleController* style)override { return INVOKEGET_INTERFACE_PROXY(GetVisibleIndex, style); } void OnViewChanged(Rect bounds)override { INVOKE_INTERFACE_PROXY(OnViewChanged, bounds); } vint FindItem(vint itemIndex, GuiListControl::KeyDirection key)override { return INVOKEGET_INTERFACE_PROXY(FindItem, itemIndex, key); } bool EnsureItemVisible(vint itemIndex)override { return INVOKEGET_INTERFACE_PROXY(EnsureItemVisible, itemIndex); } }; class GuiListControl_IItemCoordinateTransformer : public ValueInterfaceRoot, public virtual GuiListControl::IItemCoordinateTransformer { public: GuiListControl_IItemCoordinateTransformer(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<GuiListControl::IItemCoordinateTransformer> Create(Ptr<IValueInterfaceProxy> proxy) { return new GuiListControl_IItemCoordinateTransformer(proxy); } Size RealSizeToVirtualSize(Size size)override { return INVOKEGET_INTERFACE_PROXY(RealSizeToVirtualSize, size); } Size VirtualSizeToRealSize(Size size)override { return INVOKEGET_INTERFACE_PROXY(VirtualSizeToRealSize, size); } Point RealPointToVirtualPoint(Size realFullSize, Point point)override { return INVOKEGET_INTERFACE_PROXY(RealPointToVirtualPoint, realFullSize, point); } Point VirtualPointToRealPoint(Size realFullSize, Point point)override { return INVOKEGET_INTERFACE_PROXY(VirtualPointToRealPoint, realFullSize, point); } Rect RealRectToVirtualRect(Size realFullSize, Rect rect)override { return INVOKEGET_INTERFACE_PROXY(RealRectToVirtualRect, realFullSize, rect); } Rect VirtualRectToRealRect(Size realFullSize, Rect rect)override { return INVOKEGET_INTERFACE_PROXY(VirtualRectToRealRect, realFullSize, rect); } Margin RealMarginToVirtualMargin(Margin margin)override { return INVOKEGET_INTERFACE_PROXY(RealMarginToVirtualMargin, margin); } Margin VirtualMarginToRealMargin(Margin margin)override { return INVOKEGET_INTERFACE_PROXY(VirtualMarginToRealMargin, margin); } GuiListControl::KeyDirection RealKeyDirectionToVirtualKeyDirection(GuiListControl::KeyDirection key)override { return INVOKEGET_INTERFACE_PROXY(RealKeyDirectionToVirtualKeyDirection, key); } }; class GuiSelectableListControl_IItemStyleProvider : public virtual GuiListControl_IItemStyleProvider, public virtual GuiSelectableListControl::IItemStyleProvider { public: GuiSelectableListControl_IItemStyleProvider(Ptr<IValueInterfaceProxy> proxy) :GuiListControl_IItemStyleProvider(proxy) { } static Ptr<GuiSelectableListControl::IItemStyleProvider> Create(Ptr<IValueInterfaceProxy> proxy) { return new GuiSelectableListControl_IItemStyleProvider(proxy); } void SetStyleSelected(GuiListControl::IItemStyleController* style, bool value)override { INVOKE_INTERFACE_PROXY(SetStyleSelected, style, value); } }; class TextItemStyleProvider_ITextItemStyleProvider : public ValueInterfaceRoot, public virtual list::TextItemStyleProvider::ITextItemStyleProvider { public: TextItemStyleProvider_ITextItemStyleProvider(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static list::TextItemStyleProvider::ITextItemStyleProvider* Create(Ptr<IValueInterfaceProxy> proxy) { return new TextItemStyleProvider_ITextItemStyleProvider(proxy); } GuiSelectableButton::IStyleController* CreateBackgroundStyleController()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(CreateBackgroundStyleController); } GuiSelectableButton::IStyleController* CreateBulletStyleController()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(CreateBulletStyleController); } }; class TextItemStyleProvider_ITextItemView : public virtual GuiListControl_IItemPrimaryTextView, public virtual list::TextItemStyleProvider::ITextItemView { public: TextItemStyleProvider_ITextItemView(Ptr<IValueInterfaceProxy> _proxy) :GuiListControl_IItemPrimaryTextView(_proxy) { } static Ptr<list::TextItemStyleProvider::ITextItemView> Create(Ptr<IValueInterfaceProxy> proxy) { return new TextItemStyleProvider_ITextItemView(proxy); } WString GetText(vint itemIndex)override { return INVOKEGET_INTERFACE_PROXY(GetText, itemIndex); } bool GetChecked(vint itemIndex)override { return INVOKEGET_INTERFACE_PROXY(GetChecked, itemIndex); } void SetCheckedSilently(vint itemIndex, bool value)override { INVOKE_INTERFACE_PROXY(SetCheckedSilently, itemIndex, value); } }; class GuiListViewBase_IStyleProvider : public virtual GuiScrollView_IStyleProvider, public virtual GuiListViewBase::IStyleProvider { public: GuiListViewBase_IStyleProvider(Ptr<IValueInterfaceProxy> _proxy) :GuiControl_IStyleProvider(_proxy) ,GuiScrollView_IStyleProvider(_proxy) { } static GuiListViewBase::IStyleProvider* Create(Ptr<IValueInterfaceProxy> proxy) { return new GuiListViewBase_IStyleProvider(proxy); } GuiSelectableButton::IStyleController* CreateItemBackground()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(CreateItemBackground); } GuiListViewColumnHeader::IStyleController* CreateColumnStyle()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(CreateColumnStyle); } Color GetPrimaryTextColor()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetPrimaryTextColor); } Color GetSecondaryTextColor()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetSecondaryTextColor); } Color GetItemSeparatorColor()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetItemSeparatorColor); } }; class ListViewItemStyleProvider_IListViewItemView : public virtual GuiListControl_IItemPrimaryTextView, public virtual list::ListViewItemStyleProvider::IListViewItemView { public: ListViewItemStyleProvider_IListViewItemView(Ptr<IValueInterfaceProxy> _proxy) :GuiListControl_IItemPrimaryTextView(_proxy) { } static Ptr<list::ListViewItemStyleProvider::IListViewItemView> Create(Ptr<IValueInterfaceProxy> proxy) { return new ListViewItemStyleProvider_IListViewItemView(proxy); } Ptr<GuiImageData> GetSmallImage(vint itemIndex)override { return INVOKEGET_INTERFACE_PROXY(GetSmallImage, itemIndex); } Ptr<GuiImageData> GetLargeImage(vint itemIndex)override { return INVOKEGET_INTERFACE_PROXY(GetLargeImage, itemIndex); } WString GetText(vint itemIndex)override { return INVOKEGET_INTERFACE_PROXY(GetText, itemIndex); } WString GetSubItem(vint itemIndex, vint index)override { return INVOKEGET_INTERFACE_PROXY(GetSubItem, itemIndex, index); } vint GetDataColumnCount()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetDataColumnCount); } vint GetDataColumn(vint index)override { return INVOKEGET_INTERFACE_PROXY(GetDataColumn, index); } vint GetColumnCount()override { return INVOKEGET_INTERFACE_PROXY(GetColumnCount); } WString GetColumnText(vint index)override { return INVOKEGET_INTERFACE_PROXY(GetColumnText, index); } }; class ListViewItemStyleProvider_IListViewItemContent : public ValueInterfaceRoot, public virtual list::ListViewItemStyleProvider::IListViewItemContent { public: ListViewItemStyleProvider_IListViewItemContent(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static list::ListViewItemStyleProvider::IListViewItemContent* Create(Ptr<IValueInterfaceProxy> proxy) { return new ListViewItemStyleProvider_IListViewItemContent(proxy); } compositions::GuiBoundsComposition* GetContentComposition()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetContentComposition); } compositions::GuiBoundsComposition* GetBackgroundDecorator()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetBackgroundDecorator); } void Install(GuiListViewBase::IStyleProvider* styleProvider, list::ListViewItemStyleProvider::IListViewItemView* view, vint itemIndex)override { INVOKE_INTERFACE_PROXY(Install, styleProvider, view, itemIndex); } void Uninstall()override { INVOKE_INTERFACE_PROXY_NOPARAM(Uninstall); } }; class ListViewItemStyleProvider_IListViewItemContentProvider : public ValueInterfaceRoot, public virtual list::ListViewItemStyleProvider::IListViewItemContentProvider { public: ListViewItemStyleProvider_IListViewItemContentProvider(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<list::ListViewItemStyleProvider::IListViewItemContentProvider> Create(Ptr<IValueInterfaceProxy> proxy) { return new ListViewItemStyleProvider_IListViewItemContentProvider(proxy); } GuiListControl::IItemCoordinateTransformer* CreatePreferredCoordinateTransformer()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(CreatePreferredCoordinateTransformer); } GuiListControl::IItemArranger* CreatePreferredArranger()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(CreatePreferredArranger); } list::ListViewItemStyleProvider::IListViewItemContent* CreateItemContent(const FontProperties& font)override { return INVOKEGET_INTERFACE_PROXY(CreateItemContent, font); } void AttachListControl(GuiListControl* value)override { INVOKE_INTERFACE_PROXY(AttachListControl, value); } void DetachListControl()override { INVOKE_INTERFACE_PROXY_NOPARAM(DetachListControl); } }; class ListViewColumnItemArranger_IColumnItemView : public ValueInterfaceRoot, public virtual list::ListViewColumnItemArranger::IColumnItemView { public: ListViewColumnItemArranger_IColumnItemView(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<list::ListViewColumnItemArranger::IColumnItemView> Create(Ptr<IValueInterfaceProxy> proxy) { return new ListViewColumnItemArranger_IColumnItemView(proxy); } bool AttachCallback(list::ListViewColumnItemArranger::IColumnItemViewCallback* value)override { return INVOKEGET_INTERFACE_PROXY(AttachCallback, value); } bool DetachCallback(list::ListViewColumnItemArranger::IColumnItemViewCallback* value)override { return INVOKEGET_INTERFACE_PROXY(DetachCallback, value); } vint GetColumnCount()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetColumnCount); } WString GetColumnText(vint index)override { return INVOKEGET_INTERFACE_PROXY(GetColumnText, index); } vint GetColumnSize(vint index)override { return INVOKEGET_INTERFACE_PROXY(GetColumnSize, index); } void SetColumnSize(vint index, vint value)override { INVOKE_INTERFACE_PROXY(SetColumnSize, index, value); } GuiMenu* GetDropdownPopup(vint index)override { return INVOKEGET_INTERFACE_PROXY(GetDropdownPopup, index); } GuiListViewColumnHeader::ColumnSortingState GetSortingState(vint index)override { return INVOKEGET_INTERFACE_PROXY(GetSortingState, index); } }; class GuiMenuButton_IStyleController : public virtual GuiButton_IStyleController, public virtual GuiMenuButton::IStyleController { public: GuiMenuButton_IStyleController(Ptr<IValueInterfaceProxy> _proxy) :GuiControl_IStyleController(_proxy) ,GuiButton_IStyleController(_proxy) { } static GuiMenuButton::IStyleController* Create(Ptr<IValueInterfaceProxy> proxy) { return new GuiMenuButton_IStyleController(proxy); } GuiMenu::IStyleController* CreateSubMenuStyleController()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(CreateSubMenuStyleController); } void SetSubMenuExisting(bool value)override { INVOKE_INTERFACE_PROXY(SetSubMenuExisting, value); } void SetSubMenuOpening(bool value)override { INVOKE_INTERFACE_PROXY(SetSubMenuOpening, value); } GuiButton* GetSubMenuHost()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetSubMenuHost); } void SetImage(Ptr<GuiImageData> value)override { INVOKE_INTERFACE_PROXY(SetImage, value); } void SetShortcutText(const WString& value)override { INVOKE_INTERFACE_PROXY(SetShortcutText, value); } compositions::GuiSubComponentMeasurer::IMeasuringSource* GetMeasuringSource()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetMeasuringSource); } }; class GuiListViewColumnHeader_IStyleController : public virtual GuiMenuButton_IStyleController, public virtual GuiListViewColumnHeader::IStyleController { public: GuiListViewColumnHeader_IStyleController(Ptr<IValueInterfaceProxy> _proxy) :GuiControl_IStyleController(_proxy) ,GuiButton_IStyleController(_proxy) ,GuiMenuButton_IStyleController(_proxy) { } static GuiListViewColumnHeader::IStyleController* Create(Ptr<IValueInterfaceProxy> proxy) { return new GuiListViewColumnHeader_IStyleController(proxy); } void SetColumnSortingState(GuiListViewColumnHeader::ColumnSortingState value)override { INVOKE_INTERFACE_PROXY(SetColumnSortingState, value); } }; class tree_INodeProvider : public ValueInterfaceRoot, public virtual tree::INodeProvider { public: tree_INodeProvider(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<tree::INodeProvider> Create(Ptr<IValueInterfaceProxy> proxy) { return new tree_INodeProvider(proxy); } bool GetExpanding()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetExpanding); } void SetExpanding(bool value)override { INVOKE_INTERFACE_PROXY(SetExpanding, value); } vint CalculateTotalVisibleNodes()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(CalculateTotalVisibleNodes); } vint GetChildCount()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetChildCount); } INodeProvider* GetParent()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetParent); } INodeProvider* GetChild(vint index)override { return INVOKEGET_INTERFACE_PROXY(GetChild, index); } void Increase()override { INVOKE_INTERFACE_PROXY_NOPARAM(Increase); } void Release()override { INVOKE_INTERFACE_PROXY_NOPARAM(Release); } }; class tree_INodeRootProvider : public ValueInterfaceRoot, public virtual tree::INodeRootProvider { public: tree_INodeRootProvider(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<tree::INodeRootProvider> Create(Ptr<IValueInterfaceProxy> proxy) { return new tree_INodeRootProvider(proxy); } tree::INodeProvider* GetRootNode()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetRootNode); } bool CanGetNodeByVisibleIndex()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(CanGetNodeByVisibleIndex); } tree::INodeProvider* GetNodeByVisibleIndex(vint index)override { return INVOKEGET_INTERFACE_PROXY(GetNodeByVisibleIndex, index); } bool AttachCallback(tree::INodeProviderCallback* value)override { return INVOKEGET_INTERFACE_PROXY(AttachCallback, value); } bool DetachCallback(tree::INodeProviderCallback* value)override { return INVOKEGET_INTERFACE_PROXY(DetachCallback, value); } IDescriptable* RequestView(const WString& identifier)override { return INVOKEGET_INTERFACE_PROXY(RequestView, identifier); } void ReleaseView(IDescriptable* view)override { INVOKE_INTERFACE_PROXY(ReleaseView, view); } }; class tree_INodeItemView : public virtual GuiListControl_IItemPrimaryTextView, public virtual tree::INodeItemView { public: tree_INodeItemView(Ptr<IValueInterfaceProxy> _proxy) :GuiListControl_IItemPrimaryTextView(_proxy) { } static Ptr<tree::INodeItemView> Create(Ptr<IValueInterfaceProxy> proxy) { return new tree_INodeItemView(proxy); } tree::INodeProvider* RequestNode(vint index)override { return INVOKEGET_INTERFACE_PROXY(RequestNode, index); } void ReleaseNode(tree::INodeProvider* node)override { INVOKE_INTERFACE_PROXY(ReleaseNode, node); } vint CalculateNodeVisibilityIndex(tree::INodeProvider* node)override { return INVOKEGET_INTERFACE_PROXY(CalculateNodeVisibilityIndex, node); } }; class tree_INodeItemPrimaryTextView : public ValueInterfaceRoot, public virtual tree::INodeItemPrimaryTextView { public: tree_INodeItemPrimaryTextView(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<tree::INodeItemPrimaryTextView> Create(Ptr<IValueInterfaceProxy> proxy) { return new tree_INodeItemPrimaryTextView(proxy); } WString GetPrimaryTextViewText(tree::INodeProvider* node)override { return INVOKEGET_INTERFACE_PROXY(GetPrimaryTextViewText, node); } }; class tree_INodeItemStyleController: public virtual GuiListControl_IItemStyleController, public virtual tree::INodeItemStyleController { public: tree_INodeItemStyleController(Ptr<IValueInterfaceProxy> _proxy) :GuiListControl_IItemStyleController(_proxy) { } static tree::INodeItemStyleController* Create(Ptr<IValueInterfaceProxy> proxy) { return new tree_INodeItemStyleController(proxy); } tree::INodeItemStyleProvider* GetNodeStyleProvider()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetNodeStyleProvider); } }; class tree_INodeItemStyleProvider : public ValueInterfaceRoot, public virtual tree::INodeItemStyleProvider { public: tree_INodeItemStyleProvider(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<tree::INodeItemStyleProvider> Create(Ptr<IValueInterfaceProxy> proxy) { return new tree_INodeItemStyleProvider(proxy); } void BindItemStyleProvider(GuiListControl::IItemStyleProvider* styleProvider)override { INVOKE_INTERFACE_PROXY(BindItemStyleProvider, styleProvider); } GuiListControl::IItemStyleProvider* GetBindedItemStyleProvider()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetBindedItemStyleProvider); } void AttachListControl(GuiListControl* value)override { INVOKE_INTERFACE_PROXY(AttachListControl, value); } void DetachListControl()override { INVOKE_INTERFACE_PROXY_NOPARAM(DetachListControl); } vint GetItemStyleId(tree::INodeProvider* node)override { return INVOKEGET_INTERFACE_PROXY(GetItemStyleId, node); } tree::INodeItemStyleController* CreateItemStyle(vint styleId)override { return INVOKEGET_INTERFACE_PROXY(CreateItemStyle, styleId); } void DestroyItemStyle(tree::INodeItemStyleController* style)override { INVOKE_INTERFACE_PROXY(DestroyItemStyle, style); } void Install(tree::INodeItemStyleController* style, tree::INodeProvider* node)override { INVOKE_INTERFACE_PROXY(Install, style, node); } void SetStyleSelected(tree::INodeItemStyleController* style, bool value)override { INVOKE_INTERFACE_PROXY(SetStyleSelected, style, value); } }; class tree_IMemoryNodeData : public ValueInterfaceRoot, public virtual tree::IMemoryNodeData { public: tree_IMemoryNodeData(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<tree::IMemoryNodeData> Create(Ptr<IValueInterfaceProxy> proxy) { return new tree_IMemoryNodeData(proxy); } }; class tree_ITreeViewItemView : public virtual tree_INodeItemPrimaryTextView, public virtual tree::ITreeViewItemView { public: tree_ITreeViewItemView(Ptr<IValueInterfaceProxy> proxy) :tree_INodeItemPrimaryTextView(proxy) { } static Ptr<tree::ITreeViewItemView> Create(Ptr<IValueInterfaceProxy> proxy) { return new tree_ITreeViewItemView(proxy); } Ptr<GuiImageData> GetNodeImage(tree::INodeProvider* node)override { return INVOKEGET_INTERFACE_PROXY(GetNodeImage, node); } WString GetNodeText(tree::INodeProvider* node)override { return INVOKEGET_INTERFACE_PROXY(GetNodeText, node); } }; class GuiVirtualTreeView_IStyleProvider : public virtual GuiScrollView_IStyleProvider, public virtual GuiVirtualTreeView::IStyleProvider { public: GuiVirtualTreeView_IStyleProvider(Ptr<IValueInterfaceProxy> _proxy) :GuiControl_IStyleProvider(_proxy) ,GuiScrollView_IStyleProvider(_proxy) { } static GuiVirtualTreeView::IStyleProvider* Create(Ptr<IValueInterfaceProxy> proxy) { return new GuiVirtualTreeView_IStyleProvider(proxy); } GuiSelectableButton::IStyleController* CreateItemBackground()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(CreateItemBackground); } GuiSelectableButton::IStyleController* CreateItemExpandingDecorator()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(CreateItemExpandingDecorator); } Color GetTextColor()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetTextColor); } }; class GuiComboBoxBase_IStyleController : public virtual GuiMenuButton_IStyleController, public virtual GuiComboBoxBase::IStyleController { public: GuiComboBoxBase_IStyleController(Ptr<IValueInterfaceProxy> _proxy) :GuiControl_IStyleController(_proxy) ,GuiButton_IStyleController(_proxy) ,GuiMenuButton_IStyleController(_proxy) { } static GuiComboBoxBase::IStyleController* Create(Ptr<IValueInterfaceProxy> proxy) { return new GuiComboBoxBase_IStyleController(proxy); } void SetCommandExecutor(GuiComboBoxBase::ICommandExecutor* value)override { INVOKE_INTERFACE_PROXY(SetCommandExecutor, value); } void OnItemSelected()override { INVOKE_INTERFACE_PROXY_NOPARAM(OnItemSelected); } }; class GuiSinglelineTextBox_IStyleProvider : public virtual GuiControl_IStyleProvider, public virtual GuiSinglelineTextBox::IStyleProvider { public: GuiSinglelineTextBox_IStyleProvider(Ptr<IValueInterfaceProxy> _proxy) :GuiControl_IStyleProvider(_proxy) { } static GuiSinglelineTextBox::IStyleProvider* Create(Ptr<IValueInterfaceProxy> proxy) { return new GuiSinglelineTextBox_IStyleProvider(proxy); } compositions::GuiGraphicsComposition* InstallBackground(compositions::GuiBoundsComposition* background)override { return INVOKEGET_INTERFACE_PROXY(InstallBackground, background); } }; class list_IDataVisualizerFactory : public ValueInterfaceRoot, public virtual list::IDataVisualizerFactory { public: list_IDataVisualizerFactory(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<list::IDataVisualizerFactory> Create(Ptr<IValueInterfaceProxy> _proxy) { return new list_IDataVisualizerFactory(_proxy); } Ptr<list::IDataVisualizer> CreateVisualizer(const FontProperties& font, GuiListViewBase::IStyleProvider* styleProvider)override { return INVOKEGET_INTERFACE_PROXY(CreateVisualizer, font, styleProvider); } }; class list_IDataVisualizer : public ValueInterfaceRoot, public virtual list::IDataVisualizer { public: list_IDataVisualizer(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<list::IDataVisualizer> Create(Ptr<IValueInterfaceProxy> _proxy) { return new list_IDataVisualizer(_proxy); } list::IDataVisualizerFactory* GetFactory()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetFactory); } compositions::GuiBoundsComposition* GetBoundsComposition()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetBoundsComposition); } void BeforeVisualizeCell(list::IDataProvider* dataProvider, vint row, vint column)override { INVOKE_INTERFACE_PROXY(dataProvider, row, column); } list::IDataVisualizer* GetDecoratedDataVisualizer()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetDecoratedDataVisualizer); } void SetSelected(bool value)override { INVOKE_INTERFACE_PROXY(SetSelected, value); } }; class list_IDataEditorFactory : public ValueInterfaceRoot, public virtual list::IDataEditorFactory { public: list_IDataEditorFactory(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<list::IDataEditorFactory> Create(Ptr<IValueInterfaceProxy> _proxy) { return new list_IDataEditorFactory(_proxy); } Ptr<list::IDataEditor> CreateEditor(list::IDataEditorCallback* callback) { return INVOKEGET_INTERFACE_PROXY(CreateEditor, callback); } }; class list_IDataEditor : public ValueInterfaceRoot, public virtual list::IDataEditor { public: list_IDataEditor(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<list::IDataEditor> Create(Ptr<IValueInterfaceProxy> _proxy) { return new list_IDataEditor(_proxy); } list::IDataEditorFactory* GetFactory()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetFactory); } compositions::GuiBoundsComposition* GetBoundsComposition()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetBoundsComposition); } void BeforeEditCell(list::IDataProvider* dataProvider, vint row, vint column)override { INVOKE_INTERFACE_PROXY(BeforeEditCell, dataProvider, row, column); } void ReinstallEditor()override { INVOKE_INTERFACE_PROXY_NOPARAM(ReinstallEditor); } }; class list_IDataProvider : public ValueInterfaceRoot, public virtual list::IDataProvider { public: list_IDataProvider(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<list::IDataProvider> Create(Ptr<IValueInterfaceProxy> _proxy) { return new list_IDataProvider(_proxy); } void SetCommandExecutor(list::IDataProviderCommandExecutor* value)override { INVOKE_INTERFACE_PROXY(SetCommandExecutor, value); } vint GetColumnCount()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetColumnCount); } WString GetColumnText(vint column)override { return INVOKEGET_INTERFACE_PROXY(GetColumnText, column); } vint GetColumnSize(vint column)override { return INVOKEGET_INTERFACE_PROXY(GetColumnSize, column); } void SetColumnSize(vint column, vint value)override { INVOKE_INTERFACE_PROXY(SetColumnSize, column, value); } GuiMenu* GetColumnPopup(vint column)override { return INVOKEGET_INTERFACE_PROXY(GetColumnPopup, column); } bool IsColumnSortable(vint column)override { return INVOKEGET_INTERFACE_PROXY(IsColumnSortable, column); } void SortByColumn(vint column, bool ascending)override { INVOKE_INTERFACE_PROXY(SortByColumn, column, ascending); } vint GetSortedColumn()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetSortedColumn); } bool IsSortOrderAscending()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(IsSortOrderAscending); } vint GetRowCount()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetRowCount); } Ptr<GuiImageData> GetRowLargeImage(vint row)override { return INVOKEGET_INTERFACE_PROXY(GetRowLargeImage, row); } Ptr<GuiImageData> GetRowSmallImage(vint row)override { return INVOKEGET_INTERFACE_PROXY(GetRowSmallImage, row); } vint GetCellSpan(vint row, vint column)override { return INVOKEGET_INTERFACE_PROXY(GetCellSpan, row, column); } WString GetCellText(vint row, vint column)override { return INVOKEGET_INTERFACE_PROXY(GetCellText, row, column); } list::IDataVisualizerFactory* GetCellDataVisualizerFactory(vint row, vint column)override { return INVOKEGET_INTERFACE_PROXY(GetCellDataVisualizerFactory, row, column); } void VisualizeCell(vint row, vint column, list::IDataVisualizer* dataVisualizer)override { INVOKE_INTERFACE_PROXY(VisualizeCell, row, column, dataVisualizer); } list::IDataEditorFactory* GetCellDataEditorFactory(vint row, vint column)override { return INVOKEGET_INTERFACE_PROXY(GetCellDataEditorFactory, row, column); } void BeforeEditCell(vint row, vint column, list::IDataEditor* dataEditor)override { INVOKE_INTERFACE_PROXY(BeforeEditCell, row, column, dataEditor); } void SaveCellData(vint row, vint column, list::IDataEditor* dataEditor)override { INVOKE_INTERFACE_PROXY(SaveCellData, row, column, dataEditor); } }; class list_IStructuredDataFilter : public ValueInterfaceRoot, public virtual list::IStructuredDataFilter { public: list_IStructuredDataFilter(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<list::IStructuredDataFilter> Create(Ptr<IValueInterfaceProxy> _proxy) { return new list_IStructuredDataFilter(_proxy); } void SetCommandExecutor(list::IStructuredDataFilterCommandExecutor* value)override { INVOKE_INTERFACE_PROXY(SetCommandExecutor, value); } bool Filter(vint row)override { return INVOKEGET_INTERFACE_PROXY(Filter, row); } }; class list_IStructuredDataSorter : public ValueInterfaceRoot, public virtual list::IStructuredDataSorter { public: list_IStructuredDataSorter(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<list::IStructuredDataSorter> Create(Ptr<IValueInterfaceProxy> _proxy) { return new list_IStructuredDataSorter(_proxy); } vint Compare(vint row1, vint row2)override { return INVOKEGET_INTERFACE_PROXY(Compare, row1, row2); } }; class list_IStructuredColumnProvider : public ValueInterfaceRoot, public virtual list::IStructuredColumnProvider { public: list_IStructuredColumnProvider(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<list::IStructuredColumnProvider> Create(Ptr<IValueInterfaceProxy> _proxy) { return new list_IStructuredColumnProvider(_proxy); } WString GetText()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetText); } vint GetSize()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetSize); } void SetSize(vint value)override { INVOKE_INTERFACE_PROXY(SetSize, value); } GuiListViewColumnHeader::ColumnSortingState GetSortingState()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetSortingState); } void SetSortingState(GuiListViewColumnHeader::ColumnSortingState value)override { INVOKE_INTERFACE_PROXY(SetSortingState, value); } GuiMenu* GetPopup()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetPopup); } Ptr<list::IStructuredDataFilter> GetInherentFilter()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetInherentFilter); } Ptr<list::IStructuredDataSorter> GetInherentSorter()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetInherentSorter); } WString GetCellText(vint row)override { return INVOKEGET_INTERFACE_PROXY(GetCellText, row); } list::IDataVisualizerFactory* GetCellDataVisualizerFactory(vint row)override { return INVOKEGET_INTERFACE_PROXY(GetCellDataVisualizerFactory, row); } void VisualizeCell(vint row, list::IDataVisualizer* dataVisualizer)override { INVOKE_INTERFACE_PROXY(VisualizeCell, row, dataVisualizer); } list::IDataEditorFactory* GetCellDataEditorFactory(vint row)override { return INVOKEGET_INTERFACE_PROXY(GetCellDataEditorFactory, row); } void BeforeEditCell(vint row, list::IDataEditor* dataEditor)override { INVOKE_INTERFACE_PROXY(BeforeEditCell, row, dataEditor); } void SaveCellData(vint row, list::IDataEditor* dataEditor)override { INVOKE_INTERFACE_PROXY(SaveCellData, row, dataEditor); } }; class list_IStructuredDataProvider : public ValueInterfaceRoot, public virtual list::IStructuredDataProvider { public: list_IStructuredDataProvider(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<list::IStructuredDataProvider> Create(Ptr<IValueInterfaceProxy> _proxy) { return new list_IStructuredDataProvider(_proxy); } void SetCommandExecutor(list::IDataProviderCommandExecutor* value) { INVOKE_INTERFACE_PROXY(SetCommandExecutor, value); } vint GetColumnCount() { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetColumnCount); } vint GetRowCount() { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetRowCount); } list::IStructuredColumnProvider* GetColumn(vint column) { return INVOKEGET_INTERFACE_PROXY(GetColumn, column); } Ptr<GuiImageData> GetRowLargeImage(vint row) { return INVOKEGET_INTERFACE_PROXY(GetRowLargeImage, row); } Ptr<GuiImageData> GetRowSmallImage(vint row) { return INVOKEGET_INTERFACE_PROXY(GetRowSmallImage, row); } }; class GuiDatePicker_IStyleProvider : public GuiControl_IStyleProvider, public virtual GuiDatePicker::IStyleProvider { public: GuiDatePicker_IStyleProvider(Ptr<IValueInterfaceProxy> _proxy) :GuiControl_IStyleProvider(_proxy) { } static GuiDatePicker::IStyleProvider* Create(Ptr<IValueInterfaceProxy> _proxy) { return new GuiDatePicker_IStyleProvider(_proxy); } GuiSelectableButton::IStyleController* CreateDateButtonStyle()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(CreateDateButtonStyle); } GuiTextList* CreateTextList()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(CreateTextList); } GuiComboBoxListControl::IStyleController* CreateComboBoxStyle()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(CreateComboBoxStyle); } Color GetBackgroundColor()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetBackgroundColor); } Color GetPrimaryTextColor()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetPrimaryTextColor); } Color GetSecondaryTextColor()override { return INVOKEGET_INTERFACE_PROXY_NOPARAMS(GetSecondaryTextColor); } }; class controls_ILanguageProvider : public ValueInterfaceRoot, public virtual ILanguageProvider { public: controls_ILanguageProvider(Ptr<IValueInterfaceProxy> _proxy) :ValueInterfaceRoot(_proxy) { } static Ptr<ILanguageProvider> Create(Ptr<IValueInterfaceProxy> _proxy) { return new controls_ILanguageProvider(_proxy); } Ptr<parsing::ParsingScopeSymbol> CreateSymbolFromNode(Ptr<parsing::ParsingTreeObject> obj, RepeatingParsingExecutor* executor, parsing::ParsingScopeFinder* finder)override { return INVOKEGET_INTERFACE_PROXY(CreateSymbolFromNode, obj, executor, finder); } collections::LazyList<Ptr<parsing::ParsingScopeSymbol>> FindReferencedSymbols(parsing::ParsingTreeObject* obj, parsing::ParsingScopeFinder* finder)override { return INVOKEGET_INTERFACE_PROXY(FindReferencedSymbols, obj, finder); } collections::LazyList<Ptr<parsing::ParsingScopeSymbol>> FindPossibleSymbols(parsing::ParsingTreeObject* obj, const WString& field, parsing::ParsingScopeFinder* finder)override { return INVOKEGET_INTERFACE_PROXY(FindPossibleSymbols, obj, field, finder); } }; } #pragma warning(pop) /*********************************************************************** Type Loader ***********************************************************************/ #endif extern bool LoadGuiControlsTypes(); } } } #endif /*********************************************************************** REFLECTION\GUIREFLECTIONEVENTS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI Reflection: Events Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_REFLECTION_GUIREFLECTIONEVENTS #define VCZH_PRESENTATION_REFLECTION_GUIREFLECTIONEVENTS namespace vl { namespace reflection { namespace description { #ifndef VCZH_DEBUG_NO_REFLECTION /*********************************************************************** Type List ***********************************************************************/ #define GUIREFLECTIONEVENT_TYPELIST(F)\ F(presentation::compositions::GuiEventArgs)\ F(presentation::compositions::GuiRequestEventArgs)\ F(presentation::compositions::GuiKeyEventArgs)\ F(presentation::compositions::GuiCharEventArgs)\ F(presentation::compositions::GuiMouseEventArgs)\ F(presentation::compositions::GuiItemEventArgs)\ F(presentation::compositions::GuiItemMouseEventArgs)\ F(presentation::compositions::GuiNodeEventArgs)\ F(presentation::compositions::GuiNodeMouseEventArgs)\ GUIREFLECTIONEVENT_TYPELIST(DECL_TYPE_INFO) /*********************************************************************** GuiEventInfoImpl ***********************************************************************/ template<typename T> class GuiEventInfoImpl : public EventInfoImpl { protected: typedef Func<GuiGraphicsEvent<T>*(DescriptableObject*, bool)> EventRetriverFunction; EventRetriverFunction eventRetriver; void AttachInternal(DescriptableObject* thisObject, IEventHandler* eventHandler)override { if(thisObject) { if(EventHandlerImpl* handlerImpl=dynamic_cast<EventHandlerImpl*>(eventHandler)) { GuiGraphicsEvent<T>* eventObject=eventRetriver(thisObject, true); if(eventObject) { Ptr<GuiGraphicsEvent<T>::IHandler> handler=eventObject->AttachLambda( [=](GuiGraphicsComposition* sender, T& arguments) { Value thisObject=BoxValue<GuiGraphicsComposition*>(sender, Description<GuiGraphicsComposition>::GetAssociatedTypeDescriptor()); Value argumentsObject=BoxValue<T*>(&arguments, Description<T>::GetAssociatedTypeDescriptor()); eventHandler->Invoke(thisObject, argumentsObject); }); handlerImpl->SetTag(handler); } } } } void DetachInternal(DescriptableObject* thisObject, IEventHandler* eventHandler)override { if(thisObject) { if(EventHandlerImpl* handlerImpl=dynamic_cast<EventHandlerImpl*>(eventHandler)) { GuiGraphicsEvent<T>* eventObject=eventRetriver(thisObject, false); if(eventObject) { Ptr<GuiGraphicsEvent<T>::IHandler> handler=handlerImpl->GetTag().Cast<GuiGraphicsEvent<T>::IHandler>(); if(handler) { eventObject->Detach(handler); } } } } } void InvokeInternal(DescriptableObject* thisObject, Value& arguments)override { if(thisObject) { GuiGraphicsEvent<T>* eventObject=eventRetriver(thisObject, false); if(eventObject) { T* value=UnboxValue<T*>(arguments, Description<T>::GetAssociatedTypeDescriptor()); eventObject->Execute(*value); } } } Ptr<ITypeInfo> GetHandlerTypeInternal()override { return TypeInfoRetriver<Func<void(GuiGraphicsComposition*, T*)>>::CreateTypeInfo(); } public: GuiEventInfoImpl(ITypeDescriptor* _ownerTypeDescriptor, const WString& _name, const EventRetriverFunction& _eventRetriver) :EventInfoImpl(_ownerTypeDescriptor, _name) ,eventRetriver(_eventRetriver) { } ~GuiEventInfoImpl() { } }; template<typename T> struct GuiEventArgumentTypeRetriver { typedef vint Type; }; template<typename TClass, typename TEvent> struct GuiEventArgumentTypeRetriver<TEvent TClass::*> { typedef typename TEvent::ArgumentType Type; }; /*********************************************************************** Macros ***********************************************************************/ #define CLASS_MEMBER_GUIEVENT(EVENTNAME)\ AddEvent(\ new GuiEventInfoImpl<GuiEventArgumentTypeRetriver<decltype(&ClassType::EVENTNAME)>::Type>(\ this,\ L#EVENTNAME,\ [](DescriptableObject* thisObject, bool addEventHandler){\ return &dynamic_cast<ClassType*>(thisObject)->EVENTNAME;\ }\ )\ );\ #define CLASS_MEMBER_GUIEVENT_COMPOSITION(EVENTNAME)\ AddEvent(\ new GuiEventInfoImpl<GuiEventArgumentTypeRetriver<decltype(&GuiGraphicsEventReceiver::EVENTNAME)>::Type>(\ this,\ L#EVENTNAME,\ [](DescriptableObject* thisObject, bool addEventHandler){\ GuiGraphicsComposition* composition=dynamic_cast<GuiGraphicsComposition*>(thisObject);\ if(!addEventHandler && !composition->HasEventReceiver())\ {\ return (GuiGraphicsEvent<GuiEventArgumentTypeRetriver<decltype(&GuiGraphicsEventReceiver::EVENTNAME)>::Type>*)0;\ }\ return &composition->GetEventReceiver()->EVENTNAME;\ }\ )\ );\ #define CLASS_MEMBER_PROPERTY_GUIEVENT_FAST(PROPERTYNAME)\ CLASS_MEMBER_GUIEVENT(PROPERTYNAME##Changed)\ CLASS_MEMBER_PROPERTY_EVENT_FAST(PROPERTYNAME, PROPERTYNAME##Changed)\ #define CLASS_MEMBER_PROPERTY_GUIEVENT_READONLY_FAST(PROPERTYNAME)\ CLASS_MEMBER_GUIEVENT(PROPERTYNAME##Changed)\ CLASS_MEMBER_PROPERTY_EVENT_READONLY_FAST(PROPERTYNAME, PROPERTYNAME##Changed)\ /*********************************************************************** Type Loader ***********************************************************************/ #endif extern bool LoadGuiEventTypes(); } } } #endif /*********************************************************************** CONTROLS\STYLES\GUICOMMONSTYLES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control Styles::Common Style Helpers Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUICOMMONSTYLES #define VCZH_PRESENTATION_CONTROLS_GUICOMMONSTYLES namespace vl { namespace presentation { namespace common_styles { /*********************************************************************** CommonScrollStyle ***********************************************************************/ class CommonScrollStyle : public Object, public virtual controls::GuiScroll::IStyleController, public Description<CommonScrollStyle> { public: enum Direction { Horizontal, Vertical, }; protected: Direction direction; controls::GuiScroll::ICommandExecutor* commandExecutor; controls::GuiButton* decreaseButton; controls::GuiButton* increaseButton; controls::GuiButton* handleButton; compositions::GuiPartialViewComposition* handleComposition; compositions::GuiBoundsComposition* boundsComposition; compositions::GuiBoundsComposition* containerComposition; vint totalSize; vint pageSize; vint position; Point draggingStartLocation; bool draggingHandle; void UpdateHandle(); void OnDecreaseButtonClicked(compositions::GuiGraphicsComposition* sender,compositions::GuiEventArgs& arguments); void OnIncreaseButtonClicked(compositions::GuiGraphicsComposition* sender,compositions::GuiEventArgs& arguments); void OnHandleMouseDown(compositions::GuiGraphicsComposition* sender,compositions::GuiMouseEventArgs& arguments); void OnHandleMouseMove(compositions::GuiGraphicsComposition* sender,compositions::GuiMouseEventArgs& arguments); void OnHandleMouseUp(compositions::GuiGraphicsComposition* sender,compositions::GuiMouseEventArgs& arguments);; void OnBigMoveMouseDown(compositions::GuiGraphicsComposition* sender,compositions::GuiMouseEventArgs& arguments); virtual controls::GuiButton::IStyleController* CreateDecreaseButtonStyle(Direction direction)=0; virtual controls::GuiButton::IStyleController* CreateIncreaseButtonStyle(Direction direction)=0; virtual controls::GuiButton::IStyleController* CreateHandleButtonStyle(Direction direction)=0; virtual compositions::GuiBoundsComposition* InstallBackground(compositions::GuiBoundsComposition* boundsComposition, Direction direction)=0; void BuildStyle(vint defaultSize, vint arrowSize); public: CommonScrollStyle(Direction _direction); ~CommonScrollStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; void SetCommandExecutor(controls::GuiScroll::ICommandExecutor* value)override; void SetTotalSize(vint value)override; void SetPageSize(vint value)override; void SetPosition(vint value)override; }; /*********************************************************************** CommonTrackStyle ***********************************************************************/ class CommonTrackStyle : public Object, public virtual controls::GuiScroll::IStyleController, public Description<CommonTrackStyle> { public: enum Direction { Horizontal, Vertical, }; protected: Direction direction; controls::GuiScroll::ICommandExecutor* commandExecutor; compositions::GuiBoundsComposition* boundsComposition; controls::GuiButton* handleButton; compositions::GuiTableComposition* handleComposition; vint totalSize; vint pageSize; vint position; Point draggingStartLocation; bool draggingHandle; void UpdateHandle(); void OnHandleMouseDown(compositions::GuiGraphicsComposition* sender,compositions::GuiMouseEventArgs& arguments); void OnHandleMouseMove(compositions::GuiGraphicsComposition* sender,compositions::GuiMouseEventArgs& arguments); void OnHandleMouseUp(compositions::GuiGraphicsComposition* sender,compositions::GuiMouseEventArgs& arguments); virtual controls::GuiButton::IStyleController* CreateHandleButtonStyle(Direction direction)=0; virtual void InstallBackground(compositions::GuiGraphicsComposition* boundsComposition, Direction direction)=0; virtual void InstallTrack(compositions::GuiGraphicsComposition* trackComposition, Direction direction)=0; void BuildStyle(vint trackThickness, vint trackPadding, vint handleLong, vint handleShort); public: CommonTrackStyle(Direction _direction); ~CommonTrackStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; void SetCommandExecutor(controls::GuiScroll::ICommandExecutor* value)override; void SetTotalSize(vint value)override; void SetPageSize(vint value)override; void SetPosition(vint value)override; }; /*********************************************************************** CommonFragmentBuilder ***********************************************************************/ class CommonFragmentBuilder { private: static compositions::GuiBoundsComposition* BuildDockedElementContainer(elements::IGuiGraphicsElement* element); public: static void FillUpArrow(elements::GuiPolygonElement* element); static void FillDownArrow(elements::GuiPolygonElement* element); static void FillLeftArrow(elements::GuiPolygonElement* element); static void FillRightArrow(elements::GuiPolygonElement* element); static elements::GuiPolygonElement* BuildUpArrow(); static elements::GuiPolygonElement* BuildDownArrow(); static elements::GuiPolygonElement* BuildLeftArrow(); static elements::GuiPolygonElement* BuildRightArrow(); static compositions::GuiBoundsComposition* BuildUpArrow(elements::GuiPolygonElement*& elementOut); static compositions::GuiBoundsComposition* BuildDownArrow(elements::GuiPolygonElement*& elementOut); static compositions::GuiBoundsComposition* BuildLeftArrow(elements::GuiPolygonElement*& elementOut); static compositions::GuiBoundsComposition* BuildRightArrow(elements::GuiPolygonElement*& elementOut); }; } /*********************************************************************** Helper Functions ***********************************************************************/ extern unsigned char IntToColor(vint color); extern Color BlendColor(Color c1, Color c2, vint currentPosition, vint totalLength); /*********************************************************************** Animation ***********************************************************************/ #define DEFINE_TRANSFERRING_ANIMATION(TSTATE, TSTYLECONTROLLER)\ class TransferringAnimation : public compositions::GuiTimeBasedAnimation\ {\ protected:\ TSTATE colorBegin;\ TSTATE colorEnd;\ TSTATE colorCurrent;\ TSTYLECONTROLLER* style;\ bool stopped;\ bool disabled;\ bool enableAnimation;\ void PlayInternal(vint currentPosition, vint totalLength);\ public:\ TransferringAnimation(TSTYLECONTROLLER* _style, const TSTATE& begin);\ void Disable();\ void Play(vint currentPosition, vint totalLength)override;\ void Stop()override;\ bool GetEnableAnimation();\ void SetEnableAnimation(bool value);\ void Transfer(const TSTATE& end);\ };\ /*********************************************************************** Animation Implementation ***********************************************************************/ #define DEFAULT_TRANSFERRING_ANIMATION_HOST_GETTER(STYLE) (STYLE->GetBoundsComposition()->GetRelatedGraphicsHost()) #define IMPLEMENT_TRANSFERRING_ANIMATION_BASE(TSTATE, TSTYLECONTROLLER, HOST_GETTER)\ TSTYLECONTROLLER::TransferringAnimation::TransferringAnimation(TSTYLECONTROLLER* _style, const TSTATE& begin)\ :GuiTimeBasedAnimation(0)\ ,colorBegin(begin)\ ,colorEnd(begin)\ ,colorCurrent(begin)\ ,style(_style)\ ,stopped(true)\ ,disabled(false)\ ,enableAnimation(true)\ {\ }\ void TSTYLECONTROLLER::TransferringAnimation::Disable()\ {\ disabled=true;\ }\ void TSTYLECONTROLLER::TransferringAnimation::Play(vint currentPosition, vint totalLength)\ {\ if(!disabled)\ {\ PlayInternal(currentPosition, totalLength);\ }\ }\ void TSTYLECONTROLLER::TransferringAnimation::Stop()\ {\ stopped=true;\ }\ bool TSTYLECONTROLLER::TransferringAnimation::GetEnableAnimation()\ {\ return enableAnimation;\ }\ void TSTYLECONTROLLER::TransferringAnimation::SetEnableAnimation(bool value)\ {\ enableAnimation=value;\ }\ void TSTYLECONTROLLER::TransferringAnimation::Transfer(const TSTATE& end)\ {\ if(colorEnd!=end)\ {\ GuiGraphicsHost* host=HOST_GETTER(style);\ if(enableAnimation && host)\ {\ Restart(120);\ if(stopped)\ {\ colorBegin=colorEnd;\ colorEnd=end;\ host->GetAnimationManager()->AddAnimation(style->transferringAnimation);\ stopped=false;\ }\ else\ {\ colorBegin=colorCurrent;\ colorEnd=end;\ }\ }\ else\ {\ colorBegin=end;\ colorEnd=end;\ colorCurrent=end;\ Play(1, 1);\ }\ }\ }\ void TSTYLECONTROLLER::TransferringAnimation::PlayInternal(vint currentPosition, vint totalLength)\ #define IMPLEMENT_TRANSFERRING_ANIMATION(TSTATE, TSTYLECONTROLLER)\ IMPLEMENT_TRANSFERRING_ANIMATION_BASE(TSTATE, TSTYLECONTROLLER, DEFAULT_TRANSFERRING_ANIMATION_HOST_GETTER) } } #endif /*********************************************************************** CONTROLS\STYLES\WIN7STYLES\GUIWIN7STYLESCOMMON.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control Styles::Windows7 Styles Clases: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_WIN7STYLES_GUIWIN7STYLESCOMMON #define VCZH_PRESENTATION_CONTROLS_WIN7STYLES_GUIWIN7STYLESCOMMON namespace vl { namespace presentation { namespace win7 { /*********************************************************************** Button Configuration ***********************************************************************/ struct Win7ButtonColors { Color borderColor; Color backgroundColor; Color g1; Color g2; Color g3; Color g4; Color textColor; Color bulletLight; Color bulletDark; bool operator==(const Win7ButtonColors& colors) { return borderColor == colors.borderColor && backgroundColor == colors.backgroundColor && g1 == colors.g1 && g2 == colors.g2 && g3 == colors.g3 && g4 == colors.g4 && textColor == colors.textColor && bulletLight == colors.bulletLight && bulletDark == colors.bulletDark; } bool operator!=(const Win7ButtonColors& colors) { return !(*this==colors); } void SetAlphaWithoutText(unsigned char a); static Win7ButtonColors Blend(const Win7ButtonColors& c1, const Win7ButtonColors& c2, vint ratio, vint total); static Win7ButtonColors ButtonNormal(); static Win7ButtonColors ButtonActive(); static Win7ButtonColors ButtonPressed(); static Win7ButtonColors ButtonDisabled(); static Win7ButtonColors ItemNormal(); static Win7ButtonColors ItemActive(); static Win7ButtonColors ItemSelected(); static Win7ButtonColors ItemDisabled(); static Win7ButtonColors CheckedNormal(bool selected); static Win7ButtonColors CheckedActive(bool selected); static Win7ButtonColors CheckedPressed(bool selected); static Win7ButtonColors CheckedDisabled(bool selected); static Win7ButtonColors ToolstripButtonNormal(); static Win7ButtonColors ToolstripButtonActive(); static Win7ButtonColors ToolstripButtonPressed(); static Win7ButtonColors ToolstripButtonDisabled(); static Win7ButtonColors MenuBarButtonNormal(); static Win7ButtonColors MenuBarButtonActive(); static Win7ButtonColors MenuBarButtonPressed(); static Win7ButtonColors MenuBarButtonDisabled(); static Win7ButtonColors MenuItemButtonNormal(); static Win7ButtonColors MenuItemButtonNormalActive(); static Win7ButtonColors MenuItemButtonDisabled(); static Win7ButtonColors MenuItemButtonDisabledActive(); static Win7ButtonColors TabPageHeaderNormal(); static Win7ButtonColors TabPageHeaderActive(); static Win7ButtonColors TabPageHeaderSelected(); }; struct Win7ButtonElements { elements::GuiSolidBorderElement* rectBorderElement; elements::GuiRoundBorderElement* roundBorderElement; elements::GuiSolidBackgroundElement* backgroundElement; elements::GuiGradientBackgroundElement* topGradientElement; elements::GuiGradientBackgroundElement* bottomGradientElement; elements::GuiSolidLabelElement* textElement; compositions::GuiBoundsComposition* textComposition; compositions::GuiBoundsComposition* mainComposition; compositions::GuiBoundsComposition* backgroundComposition; compositions::GuiTableComposition* gradientComposition; static Win7ButtonElements Create(bool verticalGradient, bool roundBorder, Alignment horizontal=Alignment::Center, Alignment vertical=Alignment::Center); void Apply(const Win7ButtonColors& colors); }; struct Win7CheckedButtonElements { elements::GuiSolidBorderElement* borderElement; elements::GuiSolidBackgroundElement* backgroundElement; elements::GuiGradientBackgroundElement* outerGradientElement; elements::GuiGradientBackgroundElement* innerGradientElement; elements::GuiSolidLabelElement* textElement; elements::GuiSolidLabelElement* bulletCheckElement; elements::GuiSolidBackgroundElement* bulletRadioElement; compositions::GuiBoundsComposition* textComposition; compositions::GuiBoundsComposition* mainComposition; static Win7CheckedButtonElements Create(elements::ElementShape shape, bool backgroundVisible); void Apply(const Win7ButtonColors& colors); }; struct Win7MenuItemButtonElements { elements::GuiRoundBorderElement* borderElement; elements::GuiSolidBackgroundElement* backgroundElement; elements::GuiGradientBackgroundElement* gradientElement; elements::Gui3DSplitterElement* splitterElement; compositions::GuiCellComposition* splitterComposition; elements::GuiImageFrameElement* imageElement; elements::GuiSolidLabelElement* textElement; compositions::GuiBoundsComposition* textComposition; elements::GuiSolidLabelElement* shortcutElement; compositions::GuiBoundsComposition* shortcutComposition; elements::GuiPolygonElement* subMenuArrowElement; compositions::GuiGraphicsComposition* subMenuArrowComposition; compositions::GuiBoundsComposition* mainComposition; static Win7MenuItemButtonElements Create(); void Apply(const Win7ButtonColors& colors); void SetActive(bool value); void SetSubMenuExisting(bool value); }; struct Win7TextBoxColors { Color borderColor; Color backgroundColor; bool operator==(const Win7TextBoxColors& colors) { return borderColor == colors.borderColor && backgroundColor == colors.backgroundColor; } bool operator!=(const Win7TextBoxColors& colors) { return !(*this==colors); } static Win7TextBoxColors Blend(const Win7TextBoxColors& c1, const Win7TextBoxColors& c2, vint ratio, vint total); static Win7TextBoxColors Normal(); static Win7TextBoxColors Active(); static Win7TextBoxColors Focused(); static Win7TextBoxColors Disabled(); }; /*********************************************************************** Helper Functions ***********************************************************************/ extern Color Win7GetSystemWindowColor(); extern Color Win7GetSystemTabContentColor(); extern Color Win7GetSystemBorderColor(); extern Color Win7GetSystemBorderSinkColor(); extern Color Win7GetSystemBorderRaiseColor(); extern Color Win7GetSystemTextColor(bool enabled); extern void Win7SetFont(elements::GuiSolidLabelElement* element, compositions::GuiBoundsComposition* composition, const FontProperties& fontProperties); extern void Win7CreateSolidLabelElement(elements::GuiSolidLabelElement*& element, compositions::GuiBoundsComposition*& composition, Alignment horizontal, Alignment vertical); extern elements::text::ColorEntry Win7GetTextBoxTextColor(); } } } #endif /*********************************************************************** CONTROLS\STYLES\WIN7STYLES\GUIWIN7CONTROLSTYLES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control Styles::Windows7 Styles Clases: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_WIN7STYLES_GUIWIN7CONTROLSTYLES #define VCZH_PRESENTATION_CONTROLS_WIN7STYLES_GUIWIN7CONTROLSTYLES namespace vl { namespace presentation { namespace win7 { /*********************************************************************** Container ***********************************************************************/ class Win7EmptyStyle : public Object, public virtual controls::GuiControl::IStyleController, public Description<Win7EmptyStyle> { protected: compositions::GuiBoundsComposition* boundsComposition; public: Win7EmptyStyle(Color color); ~Win7EmptyStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; }; class Win7WindowStyle : public virtual controls::GuiWindow::DefaultBehaviorStyleController, public Description<Win7WindowStyle> { protected: compositions::GuiBoundsComposition* boundsComposition; public: Win7WindowStyle(); ~Win7WindowStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; }; class Win7TooltipStyle : public virtual controls::GuiWindow::DefaultBehaviorStyleController, public Description<Win7TooltipStyle> { protected: compositions::GuiBoundsComposition* boundsComposition; compositions::GuiBoundsComposition* containerComposition; public: Win7TooltipStyle(); ~Win7TooltipStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; }; class Win7LabelStyle : public Object, public virtual controls::GuiLabel::IStyleController, public Description<Win7LabelStyle> { protected: compositions::GuiBoundsComposition* boundsComposition; elements::GuiSolidLabelElement* textElement; public: Win7LabelStyle(); ~Win7LabelStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; Color GetDefaultTextColor()override; void SetTextColor(Color value)override; }; class Win7GroupBoxStyle : public Object, public virtual controls::GuiControl::IStyleController, public Description<Win7GroupBoxStyle> { protected: DEFINE_TRANSFERRING_ANIMATION(Color, Win7GroupBoxStyle) compositions::GuiBoundsComposition* boundsComposition; compositions::GuiBoundsComposition* sinkBorderComposition; compositions::GuiBoundsComposition* raisedBorderComposition; compositions::GuiBoundsComposition* textComposition; compositions::GuiBoundsComposition* textBackgroundComposition; compositions::GuiBoundsComposition* containerComposition; elements::GuiSolidLabelElement* textElement; Ptr<TransferringAnimation> transferringAnimation; void SetMargins(vint fontSize); public: Win7GroupBoxStyle(); ~Win7GroupBoxStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; }; class Win7DatePickerStyle : public Object, public virtual controls::GuiDatePicker::IStyleProvider, public Description<Win7DatePickerStyle> { public: Win7DatePickerStyle(); ~Win7DatePickerStyle(); void AssociateStyleController(controls::GuiControl::IStyleController* controller)override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; controls::GuiSelectableButton::IStyleController* CreateDateButtonStyle()override; controls::GuiTextList* CreateTextList()override; controls::GuiComboBoxListControl::IStyleController* CreateComboBoxStyle()override; Color GetBackgroundColor()override; Color GetPrimaryTextColor()override; Color GetSecondaryTextColor()override; }; } } } #endif /*********************************************************************** CONTROLS\STYLES\WIN7STYLES\GUIWIN7BUTTONSTYLES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control Styles::Windows7 Styles Clases: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_WIN7STYLES_GUIWIN7BUTTONSTYLES #define VCZH_PRESENTATION_CONTROLS_WIN7STYLES_GUIWIN7BUTTONSTYLES namespace vl { namespace presentation { namespace win7 { /*********************************************************************** Button ***********************************************************************/ class Win7ButtonStyleBase : public Object, public virtual controls::GuiSelectableButton::IStyleController, public Description<Win7ButtonStyleBase> { protected: DEFINE_TRANSFERRING_ANIMATION(Win7ButtonColors, Win7ButtonStyleBase) Win7ButtonElements elements; Ptr<TransferringAnimation> transferringAnimation; controls::GuiButton::ControlState controlStyle; bool isVisuallyEnabled; bool isSelected; bool transparentWhenInactive; bool transparentWhenDisabled; virtual void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool selected)=0; virtual void AfterApplyColors(const Win7ButtonColors& colors); public: Win7ButtonStyleBase(bool verticalGradient, bool roundBorder, const Win7ButtonColors& initialColor, Alignment horizontal, Alignment vertical); ~Win7ButtonStyleBase(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; void SetSelected(bool value)override; void Transfer(controls::GuiButton::ControlState value)override; bool GetTransparentWhenInactive(); void SetTransparentWhenInactive(bool value); bool GetTransparentWhenDisabled(); void SetTransparentWhenDisabled(bool value); bool GetAutoSizeForText(); void SetAutoSizeForText(bool value); }; class Win7ButtonStyle : public Win7ButtonStyleBase, public Description<Win7ButtonStyle> { protected: void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool selected)override; public: Win7ButtonStyle(bool verticalGradient=true); ~Win7ButtonStyle(); }; class Win7CheckBoxStyle : public Object, public virtual controls::GuiSelectableButton::IStyleController, public Description<Win7CheckBoxStyle> { public: enum BulletStyle { CheckBox, RadioButton, }; protected: DEFINE_TRANSFERRING_ANIMATION(Win7ButtonColors, Win7CheckBoxStyle) Win7CheckedButtonElements elements; Ptr<TransferringAnimation> transferringAnimation; controls::GuiButton::ControlState controlStyle; bool isVisuallyEnabled; bool isSelected; void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool selected); public: Win7CheckBoxStyle(BulletStyle bulletStyle, bool backgroundVisible=false); ~Win7CheckBoxStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; void SetSelected(bool value)override; void Transfer(controls::GuiButton::ControlState value)override; }; } } } #endif /*********************************************************************** CONTROLS\STYLES\WIN7STYLES\GUIWIN7MENUSTYLES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control Styles::Windows7 Styles Clases: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_WIN7STYLES_GUIWIN7MENUSTYLES #define VCZH_PRESENTATION_CONTROLS_WIN7STYLES_GUIWIN7MENUSTYLES namespace vl { namespace presentation { namespace win7 { /*********************************************************************** Menu Container ***********************************************************************/ class Win7MenuStyle : public Object, public virtual controls::GuiWindow::DefaultBehaviorStyleController, public Description<Win7MenuStyle> { protected: compositions::GuiBoundsComposition* boundsComposition; compositions::GuiBoundsComposition* containerComposition; public: Win7MenuStyle(); ~Win7MenuStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; }; class Win7MenuBarStyle : public Object, public virtual controls::GuiControl::IStyleController, public Description<Win7MenuBarStyle> { protected: compositions::GuiBoundsComposition* boundsComposition; public: Win7MenuBarStyle(); ~Win7MenuBarStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; }; /*********************************************************************** Menu Button ***********************************************************************/ class Win7MenuBarButtonStyle : public Object, public virtual controls::GuiMenuButton::IStyleController, public Description<Win7MenuBarButtonStyle> { protected: Win7ButtonElements elements; controls::GuiButton::ControlState controlStyle; bool isVisuallyEnabled; bool isOpening; void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool opening); public: Win7MenuBarButtonStyle(); ~Win7MenuBarButtonStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; controls::GuiMenu::IStyleController* CreateSubMenuStyleController()override; void SetSubMenuExisting(bool value)override; void SetSubMenuOpening(bool value)override; controls::GuiButton* GetSubMenuHost()override; void SetImage(Ptr<GuiImageData> value)override; void SetShortcutText(const WString& value)override; compositions::GuiSubComponentMeasurer::IMeasuringSource* GetMeasuringSource()override; void Transfer(controls::GuiButton::ControlState value)override; }; class Win7MenuItemButtonStyle : public Object, public virtual controls::GuiMenuButton::IStyleController, public Description<Win7MenuItemButtonStyle> { protected: class MeasuringSource : public compositions::GuiSubComponentMeasurer::MeasuringSource { protected: Win7MenuItemButtonStyle* style; public: MeasuringSource(Win7MenuItemButtonStyle* _style); ~MeasuringSource(); void SubComponentPreferredMinSizeUpdated()override; }; Win7MenuItemButtonElements elements; Ptr<MeasuringSource> measuringSource; controls::GuiButton::ControlState controlStyle; bool isVisuallyEnabled; bool isOpening; void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool opening); public: Win7MenuItemButtonStyle(); ~Win7MenuItemButtonStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; controls::GuiMenu::IStyleController* CreateSubMenuStyleController()override; void SetSubMenuExisting(bool value)override; void SetSubMenuOpening(bool value)override; controls::GuiButton* GetSubMenuHost()override; void SetImage(Ptr<GuiImageData> value)override; void SetShortcutText(const WString& value)override; compositions::GuiSubComponentMeasurer::IMeasuringSource* GetMeasuringSource()override; void Transfer(controls::GuiButton::ControlState value)override; }; class Win7MenuSplitterStyle : public Object, public virtual controls::GuiControl::IStyleController, public Description<Win7MenuSplitterStyle> { protected: compositions::GuiBoundsComposition* boundsComposition; public: Win7MenuSplitterStyle(); ~Win7MenuSplitterStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; }; } } } #endif /*********************************************************************** CONTROLS\STYLES\WIN7STYLES\GUIWIN7TABSTYLES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control Styles::Windows7 Styles Clases: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_WIN7STYLES_GUIWIN7TABSTYLES #define VCZH_PRESENTATION_CONTROLS_WIN7STYLES_GUIWIN7TABSTYLES namespace vl { namespace presentation { namespace win7 { /*********************************************************************** Tab ***********************************************************************/ class Win7TabPageHeaderStyle : public Win7ButtonStyleBase, public Description<Win7TabPageHeaderStyle> { protected: void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool selected)override; public: Win7TabPageHeaderStyle(); ~Win7TabPageHeaderStyle(); void SetFont(const FontProperties& value)override; }; class Win7TabStyle : public Object, public virtual controls::GuiTab::IStyleController, public Description<Win7TabStyle> { protected: compositions::GuiTableComposition* boundsComposition; compositions::GuiBoundsComposition* containerComposition; compositions::GuiStackComposition* tabHeaderComposition; compositions::GuiBoundsComposition* tabContentTopLineComposition; FontProperties headerFont; controls::GuiTab::ICommandExecutor* commandExecutor; Ptr<controls::GuiSelectableButton::MutexGroupController> headerController; collections::List<controls::GuiSelectableButton*> headerButtons; elements::GuiPolygonElement* headerOverflowArrowElement; controls::GuiButton* headerOverflowButton; controls::GuiToolstripMenu* headerOverflowMenu; void OnHeaderButtonClicked(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnTabHeaderBoundsChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnHeaderOverflowButtonClicked(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnHeaderOverflowMenuButtonClicked(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void UpdateHeaderOverflowButtonVisibility(); void UpdateHeaderZOrder(); void UpdateHeaderVisibilityIndex(); void UpdateHeaderLayout(); void Initialize(); protected: virtual controls::GuiSelectableButton::IStyleController* CreateHeaderStyleController(); virtual controls::GuiButton::IStyleController* CreateMenuButtonStyleController(); virtual controls::GuiToolstripMenu::IStyleController* CreateMenuStyleController(); virtual controls::GuiToolstripButton::IStyleController* CreateMenuItemStyleController(); virtual Color GetBorderColor(); virtual Color GetBackgroundColor(); public: Win7TabStyle(bool initialize=true); ~Win7TabStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; void SetCommandExecutor(controls::GuiTab::ICommandExecutor* value)override; void InsertTab(vint index)override; void SetTabText(vint index, const WString& value)override; void RemoveTab(vint index)override; void MoveTab(vint oldIndex, vint newIndex)override; void SetSelectedTab(vint index)override; controls::GuiControl::IStyleController* CreateTabPageStyleController()override; }; } } } #endif /*********************************************************************** CONTROLS\STYLES\WIN7STYLES\GUIWIN7TOOLSTRIPSTYLES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control Styles::Windows7 Styles Clases: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_WIN7STYLES_GUIWIN7TOOLSTRIPSTYLES #define VCZH_PRESENTATION_CONTROLS_WIN7STYLES_GUIWIN7TOOLSTRIPSTYLES namespace vl { namespace presentation { namespace win7 { /*********************************************************************** Toolstrip Button ***********************************************************************/ class Win7ToolstripToolbarStyle : public Win7EmptyStyle, public Description<Win7ToolstripToolbarStyle> { public: Win7ToolstripToolbarStyle(); ~Win7ToolstripToolbarStyle(); }; class Win7ToolstripButtonDropdownStyle : public Object, public virtual controls::GuiButton::IStyleController, public Description<Win7ToolstripButtonDropdownStyle> { protected: compositions::GuiBoundsComposition* boundsComposition; compositions::GuiBoundsComposition* splitterComposition; compositions::GuiBoundsComposition* containerComposition; bool isVisuallyEnabled; controls::GuiButton::ControlState controlState; virtual void TransferInternal(controls::GuiButton::ControlState value, bool enabled); public: Win7ToolstripButtonDropdownStyle(); ~Win7ToolstripButtonDropdownStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; void Transfer(controls::GuiButton::ControlState value)override; }; class Win7ToolstripButtonStyle : public Object, public virtual controls::GuiMenuButton::IStyleController, public Description<Win7ToolstripButtonStyle> { public: enum ButtonStyle { CommandButton, DropdownButton, SplitButton, }; protected: DEFINE_TRANSFERRING_ANIMATION(Win7ButtonColors, Win7ToolstripButtonStyle) Win7ButtonElements elements; Ptr<TransferringAnimation> transferringAnimation; controls::GuiButton::ControlState controlStyle; bool isVisuallyEnabled; bool isOpening; elements::GuiImageFrameElement* imageElement; compositions::GuiBoundsComposition* imageComposition; ButtonStyle buttonStyle; controls::GuiButton* subMenuHost; virtual void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool menuOpening); public: Win7ToolstripButtonStyle(ButtonStyle _buttonStyle); ~Win7ToolstripButtonStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; controls::GuiMenu::IStyleController* CreateSubMenuStyleController()override; void SetSubMenuExisting(bool value)override; void SetSubMenuOpening(bool value)override; controls::GuiButton* GetSubMenuHost()override; void SetImage(Ptr<GuiImageData> value)override; void SetShortcutText(const WString& value)override; compositions::GuiSubComponentMeasurer::IMeasuringSource* GetMeasuringSource()override; void Transfer(controls::GuiButton::ControlState value)override; }; class Win7ToolstripSplitterStyle : public Object, public virtual controls::GuiControl::IStyleController, public Description<Win7ToolstripSplitterStyle> { protected: compositions::GuiBoundsComposition* boundsComposition; public: Win7ToolstripSplitterStyle(); ~Win7ToolstripSplitterStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; }; } } } #endif /*********************************************************************** CONTROLS\STYLES\WIN7STYLES\GUIWIN7SCROLLABLESTYLES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control Styles::Windows7 Styles Clases: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_WIN7STYLES_GUIWIN7SCROLLABLESTYLES #define VCZH_PRESENTATION_CONTROLS_WIN7STYLES_GUIWIN7SCROLLABLESTYLES namespace vl { namespace presentation { namespace win7 { /*********************************************************************** Scroll ***********************************************************************/ class Win7ScrollArrowButtonStyle : public Win7ButtonStyleBase, public Description<Win7ButtonStyle> { protected: elements::GuiPolygonElement* arrowElement; void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool selected)override; void AfterApplyColors(const Win7ButtonColors& colors)override; public: Win7ScrollArrowButtonStyle(common_styles::CommonScrollStyle::Direction direction, bool increaseButton); ~Win7ScrollArrowButtonStyle(); }; class Win7ScrollStyle : public common_styles::CommonScrollStyle, public Description<Win7ScrollStyle> { public: static const vint DefaultSize=18; static const vint ArrowSize=10; protected: controls::GuiButton::IStyleController* CreateDecreaseButtonStyle(Direction direction)override; controls::GuiButton::IStyleController* CreateIncreaseButtonStyle(Direction direction)override; controls::GuiButton::IStyleController* CreateHandleButtonStyle(Direction direction)override; compositions::GuiBoundsComposition* InstallBackground(compositions::GuiBoundsComposition* boundsComposition, Direction direction)override; public: Win7ScrollStyle(Direction _direction); ~Win7ScrollStyle(); }; class Win7TrackStyle : public common_styles::CommonTrackStyle, public Description<Win7TrackStyle> { public: static const vint TrackThickness=4; static const vint TrackPadding=8; static const vint HandleLong=21; static const vint HandleShort=10; protected: controls::GuiButton::IStyleController* CreateHandleButtonStyle(Direction direction)override; void InstallBackground(compositions::GuiGraphicsComposition* boundsComposition, Direction direction)override; void InstallTrack(compositions::GuiGraphicsComposition* trackComposition, Direction direction)override; public: Win7TrackStyle(Direction _direction); ~Win7TrackStyle(); }; class Win7ProgressBarStyle : public Object, public virtual controls::GuiScroll::IStyleController, public Description<Win7ProgressBarStyle> { protected: vint totalSize; vint pageSize; vint position; compositions::GuiBoundsComposition* boundsComposition; compositions::GuiBoundsComposition* containerComposition; compositions::GuiPartialViewComposition* progressComposition; void UpdateProgressBar(); void FillProgressColors(compositions::GuiGraphicsComposition* parent, Color g1, Color g2, Color g3, Color g4, Color g5); public: Win7ProgressBarStyle(); ~Win7ProgressBarStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; void SetCommandExecutor(controls::GuiScroll::ICommandExecutor* value)override; void SetTotalSize(vint value)override; void SetPageSize(vint value)override; void SetPosition(vint value)override; }; /*********************************************************************** ScrollView ***********************************************************************/ class Win7ScrollViewProvider : public Object, public virtual controls::GuiScrollView::IStyleProvider, public Description<Win7ScrollViewProvider> { public: Win7ScrollViewProvider(); ~Win7ScrollViewProvider(); void AssociateStyleController(controls::GuiControl::IStyleController* controller)override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; controls::GuiScroll::IStyleController* CreateHorizontalScrollStyle()override; controls::GuiScroll::IStyleController* CreateVerticalScrollStyle()override; vint GetDefaultScrollSize()override; compositions::GuiGraphicsComposition* InstallBackground(compositions::GuiBoundsComposition* boundsComposition)override; }; /*********************************************************************** TextBox ***********************************************************************/ class Win7TextBoxBackground : public Object, public Description<Win7TextBoxBackground> { protected: DEFINE_TRANSFERRING_ANIMATION(Win7TextBoxColors, Win7TextBoxBackground) elements::GuiRoundBorderElement* borderElement; elements::GuiSolidBackgroundElement* backgroundElement; compositions::GuiGraphicsComposition* focusableComposition; bool isMouseEnter; bool isFocused; bool isVisuallyEnabled; Ptr<TransferringAnimation> transferringAnimation; controls::GuiControl::IStyleController* styleController; elements::GuiColorizedTextElement* textElement; void UpdateStyle(); void Apply(const Win7TextBoxColors& colors); void OnBoundsMouseEnter(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnBoundsMouseLeave(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnBoundsGotFocus(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnBoundsLostFocus(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: Win7TextBoxBackground(); ~Win7TextBoxBackground(); void AssociateStyleController(controls::GuiControl::IStyleController* controller); void SetFocusableComposition(compositions::GuiGraphicsComposition* value); void SetVisuallyEnabled(bool value); compositions::GuiGraphicsComposition* InstallBackground(compositions::GuiBoundsComposition* boundsComposition); void InitializeTextElement(elements::GuiColorizedTextElement* _textElement); }; class Win7MultilineTextBoxProvider : public Win7ScrollViewProvider, public Description<Win7MultilineTextBoxProvider> { protected: Win7TextBoxBackground background; controls::GuiControl::IStyleController* styleController; public: Win7MultilineTextBoxProvider(); ~Win7MultilineTextBoxProvider(); void AssociateStyleController(controls::GuiControl::IStyleController* controller)override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetVisuallyEnabled(bool value)override; compositions::GuiGraphicsComposition* InstallBackground(compositions::GuiBoundsComposition* boundsComposition)override; }; class Win7SinglelineTextBoxProvider : public Object, public virtual controls::GuiSinglelineTextBox::IStyleProvider, public Description<Win7SinglelineTextBoxProvider> { protected: Win7TextBoxBackground background; controls::GuiControl::IStyleController* styleController; public: Win7SinglelineTextBoxProvider(); ~Win7SinglelineTextBoxProvider(); void AssociateStyleController(controls::GuiControl::IStyleController* controller)override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; compositions::GuiGraphicsComposition* InstallBackground(compositions::GuiBoundsComposition* boundsComposition)override; }; } } } #endif /*********************************************************************** CONTROLS\STYLES\WIN7STYLES\GUIWIN7LISTSTYLES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control Styles::Windows7 Styles Clases: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_WIN7STYLES_GUIWIN7LISTSTYLES #define VCZH_PRESENTATION_CONTROLS_WIN7STYLES_GUIWIN7LISTSTYLES namespace vl { namespace presentation { namespace win7 { /*********************************************************************** List Control Buttons ***********************************************************************/ class Win7SelectableItemStyle : public Win7ButtonStyleBase, public Description<Win7SelectableItemStyle> { protected: void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool selected)override; public: Win7SelectableItemStyle(); ~Win7SelectableItemStyle(); }; class Win7ListViewColumnDropDownStyle : public Object, public virtual controls::GuiSelectableButton::IStyleController, public Description<Win7ListViewColumnDropDownStyle> { protected: controls::GuiButton::ControlState controlStyle; bool isVisuallyEnabled; bool isSelected; compositions::GuiBoundsComposition* mainComposition; compositions::GuiBoundsComposition* leftBorderComposition; compositions::GuiBoundsComposition* borderComposition; compositions::GuiBoundsComposition* gradientComposition; compositions::GuiBoundsComposition* arrowComposition; elements::GuiGradientBackgroundElement* leftBorderElement; elements::GuiSolidBorderElement* borderElement; elements::GuiGradientBackgroundElement* gradientElement; elements::GuiPolygonElement* arrowElement; void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool selected); public: Win7ListViewColumnDropDownStyle(); ~Win7ListViewColumnDropDownStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; void SetSelected(bool value)override; void Transfer(controls::GuiButton::ControlState value)override; }; class Win7ListViewColumnHeaderStyle : public Object, public virtual controls::GuiListViewColumnHeader::IStyleController, public Description<Win7ListViewColumnHeaderStyle> { protected: controls::GuiButton::ControlState controlStyle; bool isVisuallyEnabled; bool isSubMenuExisting; bool isSubMenuOpening; compositions::GuiBoundsComposition* mainComposition; compositions::GuiBoundsComposition* rightBorderComposition; compositions::GuiBoundsComposition* borderComposition; compositions::GuiBoundsComposition* gradientComposition; compositions::GuiBoundsComposition* textComposition; compositions::GuiBoundsComposition* arrowComposition; elements::GuiSolidBackgroundElement* backgroundElement; elements::GuiGradientBackgroundElement* rightBorderElement; elements::GuiSolidBorderElement* borderElement; elements::GuiGradientBackgroundElement* gradientElement; elements::GuiSolidLabelElement* textElement; elements::GuiPolygonElement* arrowElement; controls::GuiButton* dropdownButton; void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool subMenuExisting, bool subMenuOpening); public: Win7ListViewColumnHeaderStyle(); ~Win7ListViewColumnHeaderStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; void Transfer(controls::GuiButton::ControlState value)override; controls::GuiMenu::IStyleController* CreateSubMenuStyleController()override; void SetSubMenuExisting(bool value)override; void SetSubMenuOpening(bool value)override; controls::GuiButton* GetSubMenuHost()override; void SetImage(Ptr<GuiImageData> value)override; void SetShortcutText(const WString& value)override; compositions::GuiSubComponentMeasurer::IMeasuringSource* GetMeasuringSource()override; void SetColumnSortingState(controls::GuiListViewColumnHeader::ColumnSortingState value)override; }; class Win7TreeViewExpandingButtonStyle : public Object, public virtual controls::GuiSelectableButton::IStyleController, public Description<Win7TreeViewExpandingButtonStyle> { protected: controls::GuiButton::ControlState controlStyle; bool isVisuallyEnabled; bool isSelected; compositions::GuiBoundsComposition* mainComposition; elements::GuiPolygonElement* polygonElement; void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool selected); public: Win7TreeViewExpandingButtonStyle(); ~Win7TreeViewExpandingButtonStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; void SetSelected(bool value)override; void Transfer(controls::GuiButton::ControlState value)override; }; /*********************************************************************** ComboBox ***********************************************************************/ #pragma warning(push) #pragma warning(disable:4250) class Win7DropDownComboBoxStyle : public Win7ButtonStyle, public virtual controls::GuiComboBoxBase::IStyleController, public Description<Win7DropDownComboBoxStyle> { protected: controls::GuiComboBoxBase::ICommandExecutor* commandExecutor; compositions::GuiTableComposition* table; compositions::GuiCellComposition* textComposition; compositions::GuiCellComposition* dropDownComposition; elements::GuiPolygonElement* dropDownElement; void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool selected)override; void AfterApplyColors(const Win7ButtonColors& colors)override; public: Win7DropDownComboBoxStyle(); ~Win7DropDownComboBoxStyle(); compositions::GuiGraphicsComposition* GetContainerComposition()override; controls::GuiMenu::IStyleController* CreateSubMenuStyleController()override; void SetSubMenuExisting(bool value)override; void SetSubMenuOpening(bool value)override; controls::GuiButton* GetSubMenuHost()override; void SetImage(Ptr<GuiImageData> value)override; void SetShortcutText(const WString& value)override; compositions::GuiSubComponentMeasurer::IMeasuringSource* GetMeasuringSource()override; void SetCommandExecutor(controls::GuiComboBoxBase::ICommandExecutor* value)override; void OnItemSelected()override; }; #pragma warning(pop) /*********************************************************************** List ***********************************************************************/ class Win7TextListProvider : public Object, public virtual controls::list::TextItemStyleProvider::ITextItemStyleProvider, public Description<Win7TextListProvider> { public: Win7TextListProvider(); ~Win7TextListProvider(); controls::GuiSelectableButton::IStyleController* CreateBackgroundStyleController()override; controls::GuiSelectableButton::IStyleController* CreateBulletStyleController()override; }; class Win7CheckTextListProvider : public Win7TextListProvider, public Description<Win7CheckTextListProvider> { public: Win7CheckTextListProvider(); ~Win7CheckTextListProvider(); controls::GuiSelectableButton::IStyleController* CreateBulletStyleController()override; }; class Win7RadioTextListProvider : public Win7TextListProvider, public Description<Win7RadioTextListProvider> { public: Win7RadioTextListProvider(); ~Win7RadioTextListProvider(); controls::GuiSelectableButton::IStyleController* CreateBulletStyleController()override; }; #pragma warning(push) #pragma warning(disable:4250) class Win7ListViewProvider : public Win7MultilineTextBoxProvider, public virtual controls::GuiListView::IStyleProvider, public Description<Win7ListViewProvider> { public: Win7ListViewProvider(); ~Win7ListViewProvider(); controls::GuiSelectableButton::IStyleController* CreateItemBackground()override; controls::GuiListViewColumnHeader::IStyleController* CreateColumnStyle()override; Color GetPrimaryTextColor()override; Color GetSecondaryTextColor()override; Color GetItemSeparatorColor()override; }; class Win7TreeViewProvider : public Win7MultilineTextBoxProvider, public virtual controls::GuiTreeView::IStyleProvider, public Description<Win7TreeViewProvider> { public: Win7TreeViewProvider(); ~Win7TreeViewProvider(); controls::GuiSelectableButton::IStyleController* CreateItemBackground()override; controls::GuiSelectableButton::IStyleController* CreateItemExpandingDecorator()override; Color GetTextColor()override; }; #pragma warning(pop) } } } #endif /*********************************************************************** CONTROLS\STYLES\WIN8STYLES\GUIWIN8STYLESCOMMON.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control Styles::Windows8 Styles Clases: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_WIN8STYLES_GUIWIN8STYLESCOMMON #define VCZH_PRESENTATION_CONTROLS_WIN8STYLES_GUIWIN8STYLESCOMMON namespace vl { namespace presentation { namespace win8 { /*********************************************************************** Button Configuration ***********************************************************************/ struct Win8ButtonColors { Color borderColor; Color g1; Color g2; Color textColor; Color bullet; bool operator==(const Win8ButtonColors& colors) { return borderColor == colors.borderColor && g1 == colors.g1 && g2 == colors.g2 && textColor == colors.textColor && bullet == colors.bullet; } bool operator!=(const Win8ButtonColors& colors) { return !(*this==colors); } void SetAlphaWithoutText(unsigned char a); static Win8ButtonColors Blend(const Win8ButtonColors& c1, const Win8ButtonColors& c2, vint ratio, vint total); static Win8ButtonColors ButtonNormal(); static Win8ButtonColors ButtonActive(); static Win8ButtonColors ButtonPressed(); static Win8ButtonColors ButtonDisabled(); static Win8ButtonColors ItemNormal(); static Win8ButtonColors ItemActive(); static Win8ButtonColors ItemSelected(); static Win8ButtonColors ItemDisabled(); static Win8ButtonColors CheckedNormal(bool selected); static Win8ButtonColors CheckedActive(bool selected); static Win8ButtonColors CheckedPressed(bool selected); static Win8ButtonColors CheckedDisabled(bool selected); static Win8ButtonColors ToolstripButtonNormal(); static Win8ButtonColors ToolstripButtonActive(); static Win8ButtonColors ToolstripButtonPressed(); static Win8ButtonColors ToolstripButtonDisabled(); static Win8ButtonColors ScrollHandleNormal(); static Win8ButtonColors ScrollHandleActive(); static Win8ButtonColors ScrollHandlePressed(); static Win8ButtonColors ScrollHandleDisabled(); static Win8ButtonColors ScrollArrowNormal(); static Win8ButtonColors ScrollArrowActive(); static Win8ButtonColors ScrollArrowPressed(); static Win8ButtonColors ScrollArrowDisabled(); static Win8ButtonColors MenuBarButtonNormal(); static Win8ButtonColors MenuBarButtonActive(); static Win8ButtonColors MenuBarButtonPressed(); static Win8ButtonColors MenuBarButtonDisabled(); static Win8ButtonColors MenuItemButtonNormal(); static Win8ButtonColors MenuItemButtonNormalActive(); static Win8ButtonColors MenuItemButtonDisabled(); static Win8ButtonColors MenuItemButtonDisabledActive(); static Win8ButtonColors TabPageHeaderNormal(); static Win8ButtonColors TabPageHeaderActive(); static Win8ButtonColors TabPageHeaderSelected(); }; struct Win8ButtonElements { elements::GuiSolidBorderElement* rectBorderElement; elements::GuiGradientBackgroundElement* backgroundElement; elements::GuiSolidLabelElement* textElement; compositions::GuiBoundsComposition* textComposition; compositions::GuiBoundsComposition* mainComposition; compositions::GuiBoundsComposition* backgroundComposition; static Win8ButtonElements Create(Alignment horizontal=Alignment::Center, Alignment vertical=Alignment::Center); void Apply(const Win8ButtonColors& colors); }; struct Win8CheckedButtonElements { elements::GuiSolidBorderElement* bulletBorderElement; elements::GuiGradientBackgroundElement* bulletBackgroundElement; elements::GuiSolidLabelElement* bulletCheckElement; elements::GuiSolidBackgroundElement* bulletRadioElement; elements::GuiSolidLabelElement* textElement; compositions::GuiBoundsComposition* textComposition; compositions::GuiBoundsComposition* mainComposition; static Win8CheckedButtonElements Create(elements::ElementShape shape, bool backgroundVisible); void Apply(const Win8ButtonColors& colors); }; struct Win8MenuItemButtonElements { elements::GuiSolidBorderElement* borderElement; elements::GuiGradientBackgroundElement* backgroundElement; elements::GuiSolidBorderElement* splitterElement; compositions::GuiCellComposition* splitterComposition; elements::GuiImageFrameElement* imageElement; elements::GuiSolidLabelElement* textElement; compositions::GuiBoundsComposition* textComposition; elements::GuiSolidLabelElement* shortcutElement; compositions::GuiBoundsComposition* shortcutComposition; elements::GuiPolygonElement* subMenuArrowElement; compositions::GuiGraphicsComposition* subMenuArrowComposition; compositions::GuiBoundsComposition* mainComposition; static Win8MenuItemButtonElements Create(); void Apply(const Win8ButtonColors& colors); void SetActive(bool value); void SetSubMenuExisting(bool value); }; struct Win8TextBoxColors { Color borderColor; Color backgroundColor; bool operator==(const Win8TextBoxColors& colors) { return borderColor == colors.borderColor && backgroundColor == colors.backgroundColor; } bool operator!=(const Win8TextBoxColors& colors) { return !(*this==colors); } static Win8TextBoxColors Blend(const Win8TextBoxColors& c1, const Win8TextBoxColors& c2, vint ratio, vint total); static Win8TextBoxColors Normal(); static Win8TextBoxColors Active(); static Win8TextBoxColors Focused(); static Win8TextBoxColors Disabled(); }; /*********************************************************************** Helper Functions ***********************************************************************/ extern Color Win8GetSystemWindowColor(); extern Color Win8GetSystemTabContentColor(); extern Color Win8GetSystemBorderColor(); extern Color Win8GetSystemTextColor(bool enabled); extern Color Win8GetMenuBorderColor(); extern Color Win8GetMenuSplitterColor(); extern void Win8SetFont(elements::GuiSolidLabelElement* element, compositions::GuiBoundsComposition* composition, const FontProperties& fontProperties); extern void Win8CreateSolidLabelElement(elements::GuiSolidLabelElement*& element, compositions::GuiBoundsComposition*& composition, Alignment horizontal, Alignment vertical); extern elements::text::ColorEntry Win8GetTextBoxTextColor(); } } } #endif /*********************************************************************** CONTROLS\STYLES\WIN8STYLES\GUIWIN8CONTROLSTYLES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control Styles::Windows8 Styles Clases: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_WIN8STYLES_GUIWin8CONTROLSTYLES #define VCZH_PRESENTATION_CONTROLS_WIN8STYLES_GUIWin8CONTROLSTYLES namespace vl { namespace presentation { namespace win8 { /*********************************************************************** Container ***********************************************************************/ class Win8EmptyStyle : public Object, public virtual controls::GuiControl::IStyleController, public Description<Win8EmptyStyle> { protected: compositions::GuiBoundsComposition* boundsComposition; public: Win8EmptyStyle(Color color); ~Win8EmptyStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; }; class Win8WindowStyle : public virtual controls::GuiWindow::DefaultBehaviorStyleController, public Description<Win8WindowStyle> { protected: compositions::GuiBoundsComposition* boundsComposition; public: Win8WindowStyle(); ~Win8WindowStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; }; class Win8TooltipStyle : public virtual controls::GuiWindow::DefaultBehaviorStyleController, public Description<Win8TooltipStyle> { protected: compositions::GuiBoundsComposition* boundsComposition; compositions::GuiBoundsComposition* containerComposition; public: Win8TooltipStyle(); ~Win8TooltipStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; }; class Win8LabelStyle : public Object, public virtual controls::GuiLabel::IStyleController, public Description<Win8LabelStyle> { protected: compositions::GuiBoundsComposition* boundsComposition; elements::GuiSolidLabelElement* textElement; public: Win8LabelStyle(); ~Win8LabelStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; Color GetDefaultTextColor()override; void SetTextColor(Color value)override; }; class Win8GroupBoxStyle : public Object, public virtual controls::GuiControl::IStyleController, public Description<Win8GroupBoxStyle> { protected: DEFINE_TRANSFERRING_ANIMATION(Color, Win8GroupBoxStyle) compositions::GuiBoundsComposition* boundsComposition; compositions::GuiBoundsComposition* borderComposition; compositions::GuiBoundsComposition* textComposition; compositions::GuiBoundsComposition* textBackgroundComposition; compositions::GuiBoundsComposition* containerComposition; elements::GuiSolidLabelElement* textElement; Ptr<TransferringAnimation> transferringAnimation; void SetMargins(vint fontSize); public: Win8GroupBoxStyle(); ~Win8GroupBoxStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; }; class Win8DatePickerStyle : public Object, public virtual controls::GuiDatePicker::IStyleProvider, public Description<Win8DatePickerStyle> { public: Win8DatePickerStyle(); ~Win8DatePickerStyle(); void AssociateStyleController(controls::GuiControl::IStyleController* controller)override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; controls::GuiSelectableButton::IStyleController* CreateDateButtonStyle()override; controls::GuiTextList* CreateTextList()override; controls::GuiComboBoxListControl::IStyleController* CreateComboBoxStyle()override; Color GetBackgroundColor()override; Color GetPrimaryTextColor()override; Color GetSecondaryTextColor()override; }; } } } #endif /*********************************************************************** CONTROLS\STYLES\WIN8STYLES\GUIWIN8BUTTONSTYLES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control Styles::Windows8 Styles Clases: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_WIN7STYLES_GUIWIN8BUTTONSTYLES #define VCZH_PRESENTATION_CONTROLS_WIN7STYLES_GUIWIN8BUTTONSTYLES namespace vl { namespace presentation { namespace win8 { /*********************************************************************** Button ***********************************************************************/ class Win8ButtonStyleBase : public Object, public virtual controls::GuiSelectableButton::IStyleController, public Description<Win8ButtonStyleBase> { protected: DEFINE_TRANSFERRING_ANIMATION(Win8ButtonColors, Win8ButtonStyleBase) Win8ButtonElements elements; Ptr<TransferringAnimation> transferringAnimation; controls::GuiButton::ControlState controlStyle; bool isVisuallyEnabled; bool isSelected; bool transparentWhenInactive; bool transparentWhenDisabled; virtual void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool selected)=0; virtual void AfterApplyColors(const Win8ButtonColors& colors); public: Win8ButtonStyleBase(const Win8ButtonColors& initialColor, Alignment horizontal, Alignment vertical); ~Win8ButtonStyleBase(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; void SetSelected(bool value)override; void Transfer(controls::GuiButton::ControlState value)override; bool GetTransparentWhenInactive(); void SetTransparentWhenInactive(bool value); bool GetTransparentWhenDisabled(); void SetTransparentWhenDisabled(bool value); bool GetAutoSizeForText(); void SetAutoSizeForText(bool value); }; class Win8ButtonStyle : public Win8ButtonStyleBase, public Description<Win8ButtonStyle> { protected: void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool selected)override; public: Win8ButtonStyle(); ~Win8ButtonStyle(); }; class Win8CheckBoxStyle : public Object, public virtual controls::GuiSelectableButton::IStyleController, public Description<Win8CheckBoxStyle> { public: enum BulletStyle { CheckBox, RadioButton, }; protected: DEFINE_TRANSFERRING_ANIMATION(Win8ButtonColors, Win8CheckBoxStyle) Win8CheckedButtonElements elements; Ptr<TransferringAnimation> transferringAnimation; controls::GuiButton::ControlState controlStyle; bool isVisuallyEnabled; bool isSelected; void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool selected); public: Win8CheckBoxStyle(BulletStyle bulletStyle, bool backgroundVisible=false); ~Win8CheckBoxStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; void SetSelected(bool value)override; void Transfer(controls::GuiButton::ControlState value)override; }; } } } #endif /*********************************************************************** CONTROLS\STYLES\WIN8STYLES\GUIWIN8MENUSTYLES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control Styles::Windows8 Styles Clases: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_WIN8STYLES_GUIWIN8MENUSTYLES #define VCZH_PRESENTATION_CONTROLS_WIN8STYLES_GUIWIN8MENUSTYLES namespace vl { namespace presentation { namespace win8 { /*********************************************************************** Menu Container ***********************************************************************/ class Win8MenuStyle : public Object, public virtual controls::GuiWindow::DefaultBehaviorStyleController, public Description<Win8MenuStyle> { protected: compositions::GuiBoundsComposition* boundsComposition; compositions::GuiBoundsComposition* containerComposition; public: Win8MenuStyle(); ~Win8MenuStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; }; class Win8MenuBarStyle : public Object, public virtual controls::GuiControl::IStyleController, public Description<Win8MenuBarStyle> { protected: compositions::GuiBoundsComposition* boundsComposition; compositions::GuiBoundsComposition* containerComposition; public: Win8MenuBarStyle(); ~Win8MenuBarStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; }; /*********************************************************************** Menu Button ***********************************************************************/ class Win8MenuBarButtonStyle : public Object, public virtual controls::GuiMenuButton::IStyleController, public Description<Win8MenuBarButtonStyle> { protected: Win8ButtonElements elements; controls::GuiButton::ControlState controlStyle; bool isVisuallyEnabled; bool isOpening; void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool opening); public: Win8MenuBarButtonStyle(); ~Win8MenuBarButtonStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; controls::GuiMenu::IStyleController* CreateSubMenuStyleController()override; void SetSubMenuExisting(bool value)override; void SetSubMenuOpening(bool value)override; controls::GuiButton* GetSubMenuHost()override; void SetImage(Ptr<GuiImageData> value)override; void SetShortcutText(const WString& value)override; compositions::GuiSubComponentMeasurer::IMeasuringSource* GetMeasuringSource()override; void Transfer(controls::GuiButton::ControlState value)override; }; class Win8MenuItemButtonStyle : public Object, public virtual controls::GuiMenuButton::IStyleController, public Description<Win8MenuItemButtonStyle> { protected: class MeasuringSource : public compositions::GuiSubComponentMeasurer::MeasuringSource { protected: Win8MenuItemButtonStyle* style; public: MeasuringSource(Win8MenuItemButtonStyle* _style); ~MeasuringSource(); void SubComponentPreferredMinSizeUpdated()override; }; Win8MenuItemButtonElements elements; Ptr<MeasuringSource> measuringSource; controls::GuiButton::ControlState controlStyle; bool isVisuallyEnabled; bool isOpening; void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool opening); public: Win8MenuItemButtonStyle(); ~Win8MenuItemButtonStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; controls::GuiMenu::IStyleController* CreateSubMenuStyleController()override; void SetSubMenuExisting(bool value)override; void SetSubMenuOpening(bool value)override; controls::GuiButton* GetSubMenuHost()override; void SetImage(Ptr<GuiImageData> value)override; void SetShortcutText(const WString& value)override; compositions::GuiSubComponentMeasurer::IMeasuringSource* GetMeasuringSource()override; void Transfer(controls::GuiButton::ControlState value)override; }; class Win8MenuSplitterStyle : public Object, public virtual controls::GuiControl::IStyleController, public Description<Win8MenuSplitterStyle> { protected: compositions::GuiBoundsComposition* boundsComposition; public: Win8MenuSplitterStyle(); ~Win8MenuSplitterStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; }; } } } #endif /*********************************************************************** CONTROLS\STYLES\WIN8STYLES\GUIWIN8TABSTYLES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control Styles::Windows8 Styles Clases: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_WIN8STYLES_GUIWIN8TABSTYLES #define VCZH_PRESENTATION_CONTROLS_WIN8STYLES_GUIWIN8TABSTYLES namespace vl { namespace presentation { namespace win8 { /*********************************************************************** Tab ***********************************************************************/ class Win8TabPageHeaderStyle : public Win8ButtonStyleBase, public Description<Win8TabPageHeaderStyle> { protected: void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool selected)override; public: Win8TabPageHeaderStyle(); ~Win8TabPageHeaderStyle(); void SetFont(const FontProperties& value)override; }; class Win8TabStyle : public win7::Win7TabStyle, public Description<Win8TabStyle> { protected: controls::GuiSelectableButton::IStyleController* CreateHeaderStyleController()override; controls::GuiButton::IStyleController* CreateMenuButtonStyleController()override; controls::GuiToolstripMenu::IStyleController* CreateMenuStyleController()override; controls::GuiToolstripButton::IStyleController* CreateMenuItemStyleController()override; Color GetBorderColor()override; Color GetBackgroundColor()override; public: Win8TabStyle(); ~Win8TabStyle(); }; } } } #endif /*********************************************************************** CONTROLS\STYLES\WIN8STYLES\GUIWIN8TOOLSTRIPSTYLES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control Styles::Windows8 Styles Clases: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_WIN8STYLES_GUIWIN8TOOLSTRIPSTYLES #define VCZH_PRESENTATION_CONTROLS_WIN8STYLES_GUIWIN8TOOLSTRIPSTYLES namespace vl { namespace presentation { namespace win8 { /*********************************************************************** Toolstrip Button ***********************************************************************/ class Win8ToolstripToolbarStyle : public Object, public virtual controls::GuiControl::IStyleController, public Description<Win8ToolstripToolbarStyle> { protected: compositions::GuiBoundsComposition* boundsComposition; compositions::GuiBoundsComposition* containerComposition; public: Win8ToolstripToolbarStyle(); ~Win8ToolstripToolbarStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; }; class Win8ToolstripButtonDropdownStyle : public Object, public virtual controls::GuiButton::IStyleController, public Description<Win8ToolstripButtonDropdownStyle> { protected: compositions::GuiBoundsComposition* boundsComposition; compositions::GuiBoundsComposition* splitterComposition; compositions::GuiBoundsComposition* containerComposition; bool isVisuallyEnabled; controls::GuiButton::ControlState controlState; virtual void TransferInternal(controls::GuiButton::ControlState value, bool enabled); public: Win8ToolstripButtonDropdownStyle(); ~Win8ToolstripButtonDropdownStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; void Transfer(controls::GuiButton::ControlState value)override; }; class Win8ToolstripButtonStyle : public Object, public virtual controls::GuiMenuButton::IStyleController, public Description<Win8ToolstripButtonStyle> { public: enum ButtonStyle { CommandButton, DropdownButton, SplitButton, }; protected: DEFINE_TRANSFERRING_ANIMATION(Win8ButtonColors, Win8ToolstripButtonStyle) Win8ButtonElements elements; Ptr<TransferringAnimation> transferringAnimation; controls::GuiButton::ControlState controlStyle; bool isVisuallyEnabled; bool isOpening; elements::GuiImageFrameElement* imageElement; compositions::GuiBoundsComposition* imageComposition; ButtonStyle buttonStyle; controls::GuiButton* subMenuHost; virtual void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool menuOpening); public: Win8ToolstripButtonStyle(ButtonStyle _buttonStyle); ~Win8ToolstripButtonStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; controls::GuiMenu::IStyleController* CreateSubMenuStyleController()override; void SetSubMenuExisting(bool value)override; void SetSubMenuOpening(bool value)override; controls::GuiButton* GetSubMenuHost()override; void SetImage(Ptr<GuiImageData> value)override; void SetShortcutText(const WString& value)override; compositions::GuiSubComponentMeasurer::IMeasuringSource* GetMeasuringSource()override; void Transfer(controls::GuiButton::ControlState value)override; }; class Win8ToolstripSplitterStyle : public Object, public virtual controls::GuiControl::IStyleController, public Description<Win8ToolstripSplitterStyle> { protected: compositions::GuiBoundsComposition* boundsComposition; public: Win8ToolstripSplitterStyle(); ~Win8ToolstripSplitterStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; }; } } } #endif /*********************************************************************** CONTROLS\STYLES\WIN8STYLES\GUIWIN8SCROLLABLESTYLES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control Styles::Windows8 Styles Clases: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_WIN8STYLES_GUIWin8SCROLLABLESTYLES #define VCZH_PRESENTATION_CONTROLS_WIN8STYLES_GUIWin8SCROLLABLESTYLES namespace vl { namespace presentation { namespace win8 { /*********************************************************************** Scroll ***********************************************************************/ class Win8ScrollHandleButtonStyle : public Win8ButtonStyleBase, public Description<Win8ScrollHandleButtonStyle> { protected: void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool selected)override; public: Win8ScrollHandleButtonStyle(); ~Win8ScrollHandleButtonStyle(); }; class Win8ScrollArrowButtonStyle : public Win8ButtonStyleBase, public Description<Win8ScrollArrowButtonStyle> { protected: elements::GuiPolygonElement* arrowElement; void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool selected)override; void AfterApplyColors(const Win8ButtonColors& colors)override; public: Win8ScrollArrowButtonStyle(common_styles::CommonScrollStyle::Direction direction, bool increaseButton); ~Win8ScrollArrowButtonStyle(); }; class Win8ScrollStyle : public common_styles::CommonScrollStyle, public Description<Win8ScrollStyle> { public: static const vint DefaultSize=16; static const vint ArrowSize=8; protected: controls::GuiButton::IStyleController* CreateDecreaseButtonStyle(Direction direction)override; controls::GuiButton::IStyleController* CreateIncreaseButtonStyle(Direction direction)override; controls::GuiButton::IStyleController* CreateHandleButtonStyle(Direction direction)override; compositions::GuiBoundsComposition* InstallBackground(compositions::GuiBoundsComposition* boundsComposition, Direction direction)override; public: Win8ScrollStyle(Direction _direction); ~Win8ScrollStyle(); }; class Win8TrackStyle : public common_styles::CommonTrackStyle, public Description<Win8TrackStyle> { public: static const vint TrackThickness=4; static const vint TrackPadding=6; static const vint HandleLong=16; static const vint HandleShort=10; protected: controls::GuiButton::IStyleController* CreateHandleButtonStyle(Direction direction)override; void InstallBackground(compositions::GuiGraphicsComposition* boundsComposition, Direction direction)override; void InstallTrack(compositions::GuiGraphicsComposition* trackComposition, Direction direction)override; public: Win8TrackStyle(Direction _direction); ~Win8TrackStyle(); }; class Win8ProgressBarStyle : public Object, public virtual controls::GuiScroll::IStyleController, public Description<Win8ProgressBarStyle> { protected: vint totalSize; vint pageSize; vint position; compositions::GuiBoundsComposition* boundsComposition; compositions::GuiBoundsComposition* containerComposition; compositions::GuiPartialViewComposition* progressComposition; void UpdateProgressBar(); public: Win8ProgressBarStyle(); ~Win8ProgressBarStyle(); compositions::GuiBoundsComposition* GetBoundsComposition()override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; void SetCommandExecutor(controls::GuiScroll::ICommandExecutor* value)override; void SetTotalSize(vint value)override; void SetPageSize(vint value)override; void SetPosition(vint value)override; }; /*********************************************************************** ScrollView ***********************************************************************/ class Win8ScrollViewProvider : public Object, public virtual controls::GuiScrollView::IStyleProvider, public Description<Win8ScrollViewProvider> { public: Win8ScrollViewProvider(); ~Win8ScrollViewProvider(); void AssociateStyleController(controls::GuiControl::IStyleController* controller)override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; controls::GuiScroll::IStyleController* CreateHorizontalScrollStyle()override; controls::GuiScroll::IStyleController* CreateVerticalScrollStyle()override; vint GetDefaultScrollSize()override; compositions::GuiGraphicsComposition* InstallBackground(compositions::GuiBoundsComposition* boundsComposition)override; }; /*********************************************************************** TextBox ***********************************************************************/ class Win8TextBoxBackground : public Object, public Description<Win8TextBoxBackground> { protected: DEFINE_TRANSFERRING_ANIMATION(Win8TextBoxColors, Win8TextBoxBackground) elements::GuiSolidBorderElement* borderElement; elements::GuiSolidBackgroundElement* backgroundElement; compositions::GuiGraphicsComposition* focusableComposition; bool isMouseEnter; bool isFocused; bool isVisuallyEnabled; Ptr<TransferringAnimation> transferringAnimation; controls::GuiControl::IStyleController* styleController; elements::GuiColorizedTextElement* textElement; void UpdateStyle(); void Apply(const Win8TextBoxColors& colors); void OnBoundsMouseEnter(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnBoundsMouseLeave(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnBoundsGotFocus(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnBoundsLostFocus(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: Win8TextBoxBackground(); ~Win8TextBoxBackground(); void AssociateStyleController(controls::GuiControl::IStyleController* controller); void SetFocusableComposition(compositions::GuiGraphicsComposition* value); void SetVisuallyEnabled(bool value); compositions::GuiGraphicsComposition* InstallBackground(compositions::GuiBoundsComposition* boundsComposition); void InitializeTextElement(elements::GuiColorizedTextElement* _textElement); }; class Win8MultilineTextBoxProvider : public Win8ScrollViewProvider, public Description<Win8MultilineTextBoxProvider> { protected: Win8TextBoxBackground background; controls::GuiControl::IStyleController* styleController; public: Win8MultilineTextBoxProvider(); ~Win8MultilineTextBoxProvider(); void AssociateStyleController(controls::GuiControl::IStyleController* controller)override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetVisuallyEnabled(bool value)override; compositions::GuiGraphicsComposition* InstallBackground(compositions::GuiBoundsComposition* boundsComposition)override; }; class Win8SinglelineTextBoxProvider : public Object, public virtual controls::GuiSinglelineTextBox::IStyleProvider, public Description<Win8SinglelineTextBoxProvider> { protected: Win8TextBoxBackground background; controls::GuiControl::IStyleController* styleController; public: Win8SinglelineTextBoxProvider(); ~Win8SinglelineTextBoxProvider(); void AssociateStyleController(controls::GuiControl::IStyleController* controller)override; void SetFocusableComposition(compositions::GuiGraphicsComposition* value)override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; void SetVisuallyEnabled(bool value)override; compositions::GuiGraphicsComposition* InstallBackground(compositions::GuiBoundsComposition* boundsComposition)override; }; } } } #endif /*********************************************************************** CONTROLS\STYLES\WIN8STYLES\GUIWIN8LISTSTYLES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: 陈梓瀚(vczh) GacUI::Control Styles::Windows8 Styles Clases: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_WIN8STYLES_GUIWin8LISTSTYLES #define VCZH_PRESENTATION_CONTROLS_WIN8STYLES_GUIWin8LISTSTYLES namespace vl { namespace presentation { namespace win8 { /*********************************************************************** List Control Buttons ***********************************************************************/ class Win8SelectableItemStyle : public Win8ButtonStyleBase, public Description<Win8SelectableItemStyle> { protected: void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool selected)override; public: Win8SelectableItemStyle(); ~Win8SelectableItemStyle(); }; /*********************************************************************** ComboBox ***********************************************************************/ #pragma warning(push) #pragma warning(disable:4250) class Win8DropDownComboBoxStyle : public Win8ButtonStyle, public virtual controls::GuiComboBoxBase::IStyleController, public Description<Win8DropDownComboBoxStyle> { protected: controls::GuiComboBoxBase::ICommandExecutor* commandExecutor; compositions::GuiTableComposition* table; compositions::GuiCellComposition* textComposition; compositions::GuiCellComposition* dropDownComposition; elements::GuiPolygonElement* dropDownElement; void TransferInternal(controls::GuiButton::ControlState value, bool enabled, bool selected)override; void AfterApplyColors(const Win8ButtonColors& colors)override; public: Win8DropDownComboBoxStyle(); ~Win8DropDownComboBoxStyle(); compositions::GuiGraphicsComposition* GetContainerComposition()override; controls::GuiMenu::IStyleController* CreateSubMenuStyleController()override; void SetSubMenuExisting(bool value)override; void SetSubMenuOpening(bool value)override; controls::GuiButton* GetSubMenuHost()override; void SetImage(Ptr<GuiImageData> value)override; void SetShortcutText(const WString& value)override; compositions::GuiSubComponentMeasurer::IMeasuringSource* GetMeasuringSource()override; void SetCommandExecutor(controls::GuiComboBoxBase::ICommandExecutor* value)override; void OnItemSelected()override; }; #pragma warning(pop) /*********************************************************************** List ***********************************************************************/ class Win8TextListProvider : public Object, public virtual controls::list::TextItemStyleProvider::ITextItemStyleProvider, public Description<Win8TextListProvider> { public: Win8TextListProvider(); ~Win8TextListProvider(); controls::GuiSelectableButton::IStyleController* CreateBackgroundStyleController()override; controls::GuiSelectableButton::IStyleController* CreateBulletStyleController()override; }; class Win8CheckTextListProvider : public Win8TextListProvider, public Description<Win8CheckTextListProvider> { public: Win8CheckTextListProvider(); ~Win8CheckTextListProvider(); controls::GuiSelectableButton::IStyleController* CreateBulletStyleController()override; }; class Win8RadioTextListProvider : public Win8TextListProvider, public Description<Win8RadioTextListProvider> { public: Win8RadioTextListProvider(); ~Win8RadioTextListProvider(); controls::GuiSelectableButton::IStyleController* CreateBulletStyleController()override; }; #pragma warning(push) #pragma warning(disable:4250) class Win8ListViewProvider : public Win8MultilineTextBoxProvider, public virtual controls::GuiListView::IStyleProvider, public Description<Win8ListViewProvider> { public: Win8ListViewProvider(); ~Win8ListViewProvider(); controls::GuiSelectableButton::IStyleController* CreateItemBackground()override; controls::GuiListViewColumnHeader::IStyleController* CreateColumnStyle()override; Color GetPrimaryTextColor()override; Color GetSecondaryTextColor()override; Color GetItemSeparatorColor()override; }; class Win8TreeViewProvider : public Win8MultilineTextBoxProvider, public virtual controls::GuiTreeView::IStyleProvider, public Description<Win8TreeViewProvider> { public: Win8TreeViewProvider(); ~Win8TreeViewProvider(); controls::GuiSelectableButton::IStyleController* CreateItemBackground()override; controls::GuiSelectableButton::IStyleController* CreateItemExpandingDecorator()override; Color GetTextColor()override; }; #pragma warning(pop) } } } #endif
36.500941
337
0.63091
2e9eb983f85e37ada828f012a34aad193d7ae40c
2,354
h
C
src/include/gstrace/gstrace_infra.h
opengauss-mirror/openGauss-graph
6beb138fd00abdbfddc999919f90371522118008
[ "MulanPSL-1.0" ]
1
2021-11-05T10:14:39.000Z
2021-11-05T10:14:39.000Z
src/include/gstrace/gstrace_infra.h
opengauss-mirror/openGauss-graph
6beb138fd00abdbfddc999919f90371522118008
[ "MulanPSL-1.0" ]
null
null
null
src/include/gstrace/gstrace_infra.h
opengauss-mirror/openGauss-graph
6beb138fd00abdbfddc999919f90371522118008
[ "MulanPSL-1.0" ]
null
null
null
/* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. * --------------------------------------------------------------------------------------- * * gstrace_infra.h * * * IDENTIFICATION * src/include/gstrace/gstrace_infra.h * * --------------------------------------------------------------------------------------- */ #ifndef TRACE_INFRA_H_ #define TRACE_INFRA_H_ /* use low 16 bits for function name */ #define GS_TRC_COMP_SHIFT 16 #define GS_TRC_FUNC_SHIFT 0 #define GS_TRC_ID_PACK(comp, func) (func | (comp) << GS_TRC_COMP_SHIFT) /* used for gstrace_data() to inform tool how to decode its probe data. */ typedef enum trace_data_fmt { TRC_DATA_FMT_NONE, /* no data in this trace record */ TRC_DATA_FMT_DFLT, /* data is stored with HEX format */ TRC_DATA_FMT_UINT32 /* data is stored as uint32 */ } trace_data_fmt; #ifdef ENABLE_GSTRACE /* Initialize context during startup process. */ extern int gstrace_init(int key); extern void gstrace_destory(int code, uintptr_t arg); /* write one ENTRY trace record */ extern void gstrace_entry(const uint32_t rec_id); /* write one EXIT trace record */ extern void gstrace_exit(const uint32_t rec_id); /* write on DATA trace record. If data_len is greater than 1920, no data is traced. */ extern void gstrace_data( const uint32_t probe, const uint32_t rec_id, const trace_data_fmt fmt_type, const char* pData, size_t data_len); extern int* gstrace_tryblock_entry(int* newTryCounter); extern void gstrace_tryblock_exit(bool inCatch, int* oldTryCounter); #else #define gstrace_init(key) (1) #define gstrace_destory (NULL) #define gstrace_entry(rec_id) #define gstrace_exit(rec_id) #define gstrace_data(probe, rec_id, fmt_type, pData, data_len) #define gstrace_tryblock_entry(curTryCounter) (curTryCounter) #define gstrace_tryblock_exit(inCatch, oldTryCounter) #endif #endif
33.15493
116
0.694562
39e9fcac2204a6057e90aeb5d1e0fdb37460b0b9
3,290
h
C
include/flow/DataSource.h
barczynsky/libflow
ea4d895fb643894028fc848a23cc555d7b40daf6
[ "MIT" ]
1
2020-12-04T02:36:43.000Z
2020-12-04T02:36:43.000Z
include/flow/DataSource.h
barczynsky/libflow
ea4d895fb643894028fc848a23cc555d7b40daf6
[ "MIT" ]
null
null
null
include/flow/DataSource.h
barczynsky/libflow
ea4d895fb643894028fc848a23cc555d7b40daf6
[ "MIT" ]
null
null
null
#pragma once #include <condition_variable> #include <deque> #include <memory> #include <mutex> #include <unordered_set> #include <flow/flow.h> #include <flow/DataBlock.h> namespace flow { template <typename T> class DataSource : public Module { public: typedef DataBlock<T> DataType; typedef std::unique_ptr<DataType> DataPtr; typedef std::shared_ptr<DataType> DataShare; private: bool dry{ false }; size_t value_size{ sizeof(T) }; size_t block_size{ 0 }; size_t block_qty{ 0 }; private: std::mutex vacant_mtx; std::condition_variable vacant_cv; std::deque<DataPtr> vacant_blocks; private: std::mutex active_mtx; std::condition_variable active_cv; std::deque<DataPtr> active_blocks; private: std::mutex shared_mtx; std::condition_variable shared_cv; std::unordered_set<DataType*> shared_blocks; public: DataSource(size_t size = 64*1024, size_t qty = 2): block_size{ size }, block_qty{ qty } { flow::to_kill(this); vacant_blocks.resize(block_qty); for (auto & block : vacant_blocks) { block = std::make_unique<DataType>(block_size); } } DataSource(const DataSource&) = delete; ~DataSource() { this->kill(); std::unique_lock<std::mutex> lck(shared_mtx); shared_cv.wait(lck, [this] { return shared_blocks.empty(); }); } void notify() { vacant_cv.notify_all(); active_cv.notify_all(); } void kill() { dry = true; vacant_cv.notify_all(); active_cv.notify_all(); } public: size_t getBlockSize() { return block_size; } size_t getValueSize() { return value_size; } public: DataShare getVacantBlock() { if (dry) return nullptr; std::unique_lock<std::mutex> lck(vacant_mtx); vacant_cv.wait(lck, [this] { return !vacant_blocks.empty() || dry; }); if (dry) return nullptr; auto data_ptr = vacant_blocks.front().release(); vacant_blocks.pop_front(); DataShare data_share(data_ptr, [this](DataType* ptr) { if (ptr->active()) // diff { std::lock_guard<std::mutex> lck(active_mtx); active_blocks.emplace_back(ptr); active_cv.notify_one(); } else { std::lock_guard<std::mutex> lck(vacant_mtx); vacant_blocks.emplace_back(ptr); vacant_cv.notify_one(); } std::lock_guard<std::mutex> shlck(shared_mtx); shared_blocks.erase(ptr); }); data_ptr->resize(block_size); // diff std::lock_guard<std::mutex> shlck(shared_mtx); shared_blocks.insert(data_ptr); return data_share; } DataShare getActiveBlock() { if (dry) return nullptr; std::unique_lock<std::mutex> lck(active_mtx); active_cv.wait(lck, [this] { return !active_blocks.empty() || dry; }); if (dry) return nullptr; auto data_ptr = active_blocks.front().release(); active_blocks.pop_front(); DataShare data_share(data_ptr, [this](DataType* ptr) { std::lock_guard<std::mutex> lck(vacant_mtx); vacant_blocks.emplace_back(ptr); vacant_cv.notify_one(); ptr->make_vacant(); // diff std::lock_guard<std::mutex> shlck(shared_mtx); shared_blocks.erase(ptr); }); std::lock_guard<std::mutex> shlck(shared_mtx); shared_blocks.insert(data_ptr); return data_share; } }; // class DataSource } // namespace flow
20.434783
55
0.667477
d6bee95ec1de2f6bab580975efe5f7694caf9b7c
330
c
C
old/Lists/Sort_Simple_List2/Type.c
PetropoulakisPanagiotis/algorithms
70ec78e9c4f8164bf29269fe621c1029969fc4f4
[ "MIT" ]
null
null
null
old/Lists/Sort_Simple_List2/Type.c
PetropoulakisPanagiotis/algorithms
70ec78e9c4f8164bf29269fe621c1029969fc4f4
[ "MIT" ]
null
null
null
old/Lists/Sort_Simple_List2/Type.c
PetropoulakisPanagiotis/algorithms
70ec78e9c4f8164bf29269fe621c1029969fc4f4
[ "MIT" ]
null
null
null
#include <stdio.h> #include "Type.h" void Set_Value(TE *EL1, TE EL2){ EL1->x = EL2.x; } void Read_Value(TE *EL){ scanf("%d",&EL->x); } void Write_Value(TE EL){ printf(" %d->",EL.x); } int Equal_Value(TE EL1, TE EL2){ return(EL1.x == EL2.x); } int Min_Value(TE EL1, TE EL2){ return(EL1.x <= EL2.x); }
11.785714
32
0.563636
6c6ebefc6aee67a2d60eeda100204e8e73e18330
5,970
h
C
PrestoData/PrestoData.h
daniel-hall/PrestoData
58ff1aeb78a44326fcb04dfcf14e7697d9aaaa7e
[ "MIT" ]
3
2015-02-14T06:30:40.000Z
2019-04-29T15:51:45.000Z
PrestoData/PrestoData.h
daniel-hall/PrestoData
58ff1aeb78a44326fcb04dfcf14e7697d9aaaa7e
[ "MIT" ]
null
null
null
PrestoData/PrestoData.h
daniel-hall/PrestoData
58ff1aeb78a44326fcb04dfcf14e7697d9aaaa7e
[ "MIT" ]
null
null
null
// // PrestoData.h // // Copyright (c) 2015 Daniel Hall // // 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. #import <Foundation/Foundation.h> #import "NSArray+PrestoData.h" #import "NSMutableDictionary+PrestoData.h" extern NSString *const defaultInnerValueKey; /** A class containing shortcut convenience methods for interacting with PrestoData */ @interface PrestoData : NSObject /**--------------------------------------------------------------------------------------- * @name Modifying JSON Input * --------------------------------------------------------------------------------------- */ /** Returns a PrestoData dictionary or array created by loading a JSON file from the app bundle or document folder, filtering it with an XPath 1.0-style query, setting a new attribute value on all matching descendants, and returning the full modified dictionary or array * * Note: If the attribute already exists, its current value will be replaced by the new value. If the attribute does not yet exist, it will be created with the new value. * * @param filePath An NSString representation of the path to JSON resource that will be loaded from the file system * @param xpathQuery An NSString containing an XPath 1.0-style query to be applied to the JSON, or nil to modify the root object. See documentation here: http://www.w3schools.com/xpath/xpath_syntax.asp * @param value A new NSString or NSNumber value that will be set for the attribute * @param attributeName The name of the attribute to create or modify * @return An NSMutableDictionary or NSArray (depending on what was modeled in the original JSON file) reflecting the changes made to the input JSON */ +(id)objectFromJSON:(NSString *)filePath filteredBy:(NSString *)xpathQuery withNewValue:(id)value forAttribute:(NSString *)attributeName; /** Returns a PrestoData dictionary or array created by loading a JSON file from the app bundle or document folder, filtering it with an XPath 1.0-style query, removing the specified attribute from all matching descendants, and returning the full modified dictionary or array * @param filePath An NSString representation of the path to JSON resource that will be loaded from the file system * @param xpathQuery An NSString containing an XPath 1.0-style query to be applied to the JSON, or nil to modify the root object. See documentation here: http://www.w3schools.com/xpath/xpath_syntax.asp * @param attributeName The name of the attribute to remove * @return An NSMutableDictionary or NSArray (depending on what was modeled in the original JSON file) reflecting the changes made to the input JSON */ +(id)objectFromJSON:(NSString *)filePath filteredBy:(NSString *)xpathQuery removingAttributeNamed:(NSString *)attributeName; /** Returns a PrestoData dictionary or array created by loading a JSON file from the app bundle or document folder, filtering it with an XPath 1.0-style query, adding the specified dictionary element to all matching descendants, and returning the full modified dictionary or array * * Note: If an element already exists with the specified name, the new element and the existing element will be combined into an array of elements * * @param filePath An NSString representation of the path to JSON resource that will be loaded from the file system * @param xpathQuery An NSString containing an XPath 1.0-style query to be applied to the JSON, or nil to modify the root object. See documentation here: http://www.w3schools.com/xpath/xpath_syntax.asp * @param element A PrestoDictionary dictionary that should be added as a child element to the matching descendants * @param elementName The name that the new element will be mapped to * @return An NSMutableDictionary or NSArray (depending on what was modeled in the original JSON file) reflecting the changes made to the input JSON */ +(id)objectFromJSON:(NSString *)filePath filteredBy:(NSString *)xpathQuery withNewElement:(NSMutableDictionary *)element named:(NSString *)elementName; /** Returns a PrestoData dictionary or array created by loading a JSON file from the app bundle or document folder, filtering it with an XPath 1.0-style query, removing any element with the specified name from all matching descendants, and returning the full modified dictionary or array * @param filePath An NSString representation of the path to JSON resource that will be loaded from the file system * @param xpathQuery An NSString containing an XPath 1.0-style query to be applied to the JSON, or nil to modify the root object. See documentation here: http://www.w3schools.com/xpath/xpath_syntax.asp * @param elementName The name of the element to remove from all matching descendants * @return An NSMutableDictionary or NSArray (depending on what was modeled in the original JSON file) reflecting the changes made to the input JSON */ +(id)objectFromJSON:(NSString *)filePath filteredBy:(NSString *)xpathQuery removingElementNamed:(NSString *)elementName; @end
71.071429
287
0.766499
6c9004423a50718235a8a0ccca4d205f0767637e
7,025
h
C
base/core/variables.h
Otacon-404/qo0-base
2de7c14bf1941ad2ad77f30783f9e06fc646a153
[ "MIT" ]
255
2020-05-11T20:43:53.000Z
2022-03-30T20:43:10.000Z
base/core/variables.h
Otacon-404/qo0-base
2de7c14bf1941ad2ad77f30783f9e06fc646a153
[ "MIT" ]
175
2020-05-11T20:29:31.000Z
2022-03-27T12:43:17.000Z
base/core/variables.h
Otacon-404/qo0-base
2de7c14bf1941ad2ad77f30783f9e06fc646a153
[ "MIT" ]
193
2020-05-12T09:52:37.000Z
2022-03-27T23:51:42.000Z
#pragma once // used: define to add values to variables vector #include "config.h" #pragma region variables_array_entries enum EVisualsInfoFlags : int { INFO_FLAG_HELMET = 0, INFO_FLAG_KEVLAR, INFO_FLAG_KIT, INFO_FLAG_ZOOM, INFO_FLAG_MAX }; enum EVisualsRemovals : int { REMOVAL_POSTPROCESSING = 0, REMOVAL_PUNCH, REMOVAL_SMOKE, REMOVAL_SCOPE, REMOVAL_MAX }; #pragma endregion #pragma region variables_combo_entries enum class EAntiAimPitchType : int { NONE = 0, UP, DOWN, ZERO }; enum class EAntiAimYawType : int { NONE = 0, DESYNC }; enum class EVisualsBoxType : int { NONE = 0, FULL, CORNERS }; enum class EVisualsGlowStyle : int { OUTER = 0, COVER, INNER }; enum class EVisualsPlayersChams : int { COVERED = 0, FLAT, WIREFRAME, REFLECTIVE }; enum class EVisualsViewModelChams : int { NO_DRAW = 0, COVERED, FLAT, WIREFRAME, GLOW, SCROLL, CHROME }; #pragma endregion struct Variables_t { #pragma region variables_rage // aimbot C_ADD_VARIABLE(bool, bRage, false); // antiaim C_ADD_VARIABLE(bool, bAntiAim, false); C_ADD_VARIABLE(int, iAntiAimPitch, 0); C_ADD_VARIABLE(int, iAntiAimYaw, 0); C_ADD_VARIABLE(int, iAntiAimDesyncKey, VK_XBUTTON1); #pragma endregion #pragma region variables_legit // aimbot C_ADD_VARIABLE(bool, bLegit, false); // trigger C_ADD_VARIABLE(bool, bTrigger, false); C_ADD_VARIABLE(int, iTriggerKey, 0); C_ADD_VARIABLE(int, iTriggerDelay, 0); C_ADD_VARIABLE(bool, bTriggerAutoWall, false); C_ADD_VARIABLE(int, iTriggerMinimalDamage, 70); C_ADD_VARIABLE(bool, bTriggerHead, true); C_ADD_VARIABLE(bool, bTriggerChest, true); C_ADD_VARIABLE(bool, bTriggerStomach, true); C_ADD_VARIABLE(bool, bTriggerArms, false); C_ADD_VARIABLE(bool, bTriggerLegs, false); #pragma endregion #pragma region variables_visuals C_ADD_VARIABLE(bool, bEsp, false); // main C_ADD_VARIABLE(bool, bEspMain, false); C_ADD_VARIABLE(bool, bEspMainEnemies, false); C_ADD_VARIABLE(bool, bEspMainAllies, false); C_ADD_VARIABLE(bool, bEspMainWeapons, false); C_ADD_VARIABLE(bool, bEspMainGrenades, false); C_ADD_VARIABLE(bool, bEspMainBomb, false); // players C_ADD_VARIABLE(int, iEspMainPlayerBox, static_cast<int>(EVisualsBoxType::FULL)); C_ADD_VARIABLE(Color, colEspMainBoxEnemies, Color(160, 60, 60, 255)); C_ADD_VARIABLE(Color, colEspMainBoxEnemiesWall, Color(200, 185, 110, 255)); C_ADD_VARIABLE(Color, colEspMainBoxAllies, Color(0, 200, 170, 255)); C_ADD_VARIABLE(Color, colEspMainBoxAlliesWall, Color(170, 110, 200, 255)); C_ADD_VARIABLE(bool, bEspMainPlayerFarRadar, false); C_ADD_VARIABLE(bool, bEspMainPlayerInfo, false); /* left */ C_ADD_VARIABLE(bool, bEspMainPlayerHealth, true); C_ADD_VARIABLE(bool, bEspMainPlayerMoney, false); /* top */ C_ADD_VARIABLE(bool, bEspMainPlayerName, true); C_ADD_VARIABLE(bool, bEspMainPlayerFlash, false); /* right */ C_ADD_VARIABLE_VECTOR(bool, INFO_FLAG_MAX, vecEspMainPlayerFlags, true); /* bottom */ C_ADD_VARIABLE(bool, bEspMainPlayerWeapons, true); C_ADD_VARIABLE(bool, bEspMainPlayerAmmo, true); C_ADD_VARIABLE(bool, bEspMainPlayerDistance, false); // weapons C_ADD_VARIABLE(int, iEspMainWeaponBox, static_cast<int>(EVisualsBoxType::NONE)); C_ADD_VARIABLE(Color, colEspMainBoxWeapons, Color(255, 255, 255, 220)); C_ADD_VARIABLE(bool, bEspMainWeaponInfo, false); C_ADD_VARIABLE(bool, bEspMainWeaponIcon, true); C_ADD_VARIABLE(bool, bEspMainWeaponAmmo, true); C_ADD_VARIABLE(bool, bEspMainWeaponDistance, false); // glow C_ADD_VARIABLE(bool, bEspGlow, false); C_ADD_VARIABLE(bool, bEspGlowEnemies, false); C_ADD_VARIABLE(bool, bEspGlowAllies, false); C_ADD_VARIABLE(bool, bEspGlowWeapons, false); C_ADD_VARIABLE(bool, bEspGlowGrenades, false); C_ADD_VARIABLE(bool, bEspGlowBomb, false); C_ADD_VARIABLE(bool, bEspGlowBloom, false); C_ADD_VARIABLE(Color, colEspGlowEnemies, Color(230, 20, 60, 128)); C_ADD_VARIABLE(Color, colEspGlowEnemiesWall, Color(255, 235, 240, 128)); C_ADD_VARIABLE(Color, colEspGlowAllies, Color(85, 140, 255, 128)); C_ADD_VARIABLE(Color, colEspGlowAlliesWall, Color(240, 235, 255, 128)); C_ADD_VARIABLE(Color, colEspGlowWeapons, Color(80, 0, 225, 128)); C_ADD_VARIABLE(Color, colEspGlowGrenades, Color(180, 130, 30, 128)); C_ADD_VARIABLE(Color, colEspGlowBomb, Color(140, 220, 80, 128)); C_ADD_VARIABLE(Color, colEspGlowBombPlanted, Color(200, 210, 80, 128)); // chams C_ADD_VARIABLE(bool, bEspChams, false); C_ADD_VARIABLE(bool, bEspChamsEnemies, false); C_ADD_VARIABLE(bool, bEspChamsAllies, false); C_ADD_VARIABLE(bool, bEspChamsViewModel, false); C_ADD_VARIABLE(bool, bEspChamsXQZ, false); C_ADD_VARIABLE(bool, bEspChamsDisableOcclusion, false); C_ADD_VARIABLE(int, iEspChamsPlayer, static_cast<int>(EVisualsPlayersChams::COVERED)); C_ADD_VARIABLE(int, iEspChamsViewModel, static_cast<int>(EVisualsViewModelChams::WIREFRAME)); C_ADD_VARIABLE(Color, colEspChamsEnemies, Color(180, 65, 65, 255)); C_ADD_VARIABLE(Color, colEspChamsEnemiesWall, Color(180, 180, 40, 255)); C_ADD_VARIABLE(Color, colEspChamsAllies, Color(70, 40, 190, 255)); C_ADD_VARIABLE(Color, colEspChamsAlliesWall, Color(50, 150, 150, 255)); C_ADD_VARIABLE(Color, colEspChamsViewModel, Color(80, 255, 45, 255)); C_ADD_VARIABLE(Color, colEspChamsViewModelAdditional, Color(0, 0, 255, 255)); // world C_ADD_VARIABLE(bool, bWorld, false); C_ADD_VARIABLE(bool, bWorldNightMode, false); C_ADD_VARIABLE(int, iWorldMaxFlash, 100); C_ADD_VARIABLE(int, iWorldThirdPersonKey, 0); C_ADD_VARIABLE(float, flWorldThirdPersonOffset, 150.f); C_ADD_VARIABLE_VECTOR(bool, REMOVAL_MAX, vecWorldRemovals, false); // on-screen C_ADD_VARIABLE(bool, bScreen, false); C_ADD_VARIABLE(float, flScreenCameraFOV, 0.f); C_ADD_VARIABLE(float, flScreenViewModelFOV, 0.f); C_ADD_VARIABLE(bool, bScreenHitMarker, false); C_ADD_VARIABLE(bool, bScreenHitMarkerDamage, false); C_ADD_VARIABLE(bool, bScreenHitMarkerSound, false); C_ADD_VARIABLE(float, flScreenHitMarkerTime, 1.0f); C_ADD_VARIABLE(int, iScreenHitMarkerGap, 5); C_ADD_VARIABLE(int, iScreenHitMarkerLenght, 10); C_ADD_VARIABLE(Color, colScreenHitMarker, Color(255, 255, 255, 255)); C_ADD_VARIABLE(Color, colScreenHitMarkerDamage, Color(200, 55, 20, 255)); #pragma endregion #pragma region variables_misc // movement C_ADD_VARIABLE(bool, bMiscBunnyHop, false); C_ADD_VARIABLE(int, iMiscBunnyHopChance, 100); C_ADD_VARIABLE(bool, bMiscAutoStrafe, false); C_ADD_VARIABLE(bool, bMiscFakeLag, false); C_ADD_VARIABLE(bool, bMiscAutoAccept, false); C_ADD_VARIABLE(bool, bMiscAutoPistol, false); C_ADD_VARIABLE(bool, bMiscNoCrouchCooldown, false); // exploits C_ADD_VARIABLE(bool, bMiscPingSpike, false); C_ADD_VARIABLE(float, flMiscLatencyFactor, 0.4f); C_ADD_VARIABLE(bool, bMiscRevealRanks, false); C_ADD_VARIABLE(bool, bMiscUnlockInventory, false); C_ADD_VARIABLE(bool, bMiscAntiUntrusted, true); #pragma endregion #pragma region variables_menu C_ADD_VARIABLE(int, iMenuKey, VK_HOME); C_ADD_VARIABLE(int, iPanicKey, VK_END); #pragma endregion }; inline Variables_t Vars;
29.766949
94
0.777509
96c1fcaa3a26c4151bd630e27ee0879014391ce2
5,130
h
C
OgreMain/include/Animation/OgreSkeletonAnimManager.h
coolzoom/ogre-next
31ec929356e40becafcdef31686bc90cd6da7530
[ "MIT" ]
1
2021-05-12T18:01:21.000Z
2021-05-12T18:01:21.000Z
OgreMain/include/Animation/OgreSkeletonAnimManager.h
coolzoom/ogre-next
31ec929356e40becafcdef31686bc90cd6da7530
[ "MIT" ]
null
null
null
OgreMain/include/Animation/OgreSkeletonAnimManager.h
coolzoom/ogre-next
31ec929356e40becafcdef31686bc90cd6da7530
[ "MIT" ]
null
null
null
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #ifndef _OgreSkeletonAnimManager_H_ #define _OgreSkeletonAnimManager_H_ #include "OgrePrerequisites.h" #include "OgreIdString.h" #include "Math/Array/OgreBoneMemoryManager.h" #include "ogrestd/list.h" #include "OgreHeaderPrefix.h" namespace Ogre { /** \addtogroup Core * @{ */ /** \addtogroup Animation * @{ */ struct BySkeletonDef { SkeletonDef const *skeletonDef; IdString skeletonDefName; BoneMemoryManager boneMemoryManager; /** MUST be sorted by location in its BoneMemoryManager's slot (in order to update in parallel without causing race conditions) @See threadStarts */ FastArray<SkeletonInstance*> skeletons; /** One per thread (plus one), tells where we should start from in each thread. It's not exactly skeletons.size() / mNumWorkerThreads because we need to account that instances that share the same memory block. */ FastArray<size_t> threadStarts; BySkeletonDef( const SkeletonDef *skeletonDef, size_t threadCount ); void initializeMemoryManager(void); void updateThreadStarts(void); void _updateBoneStartTransforms(void); bool operator == ( IdString name ) const { return skeletonDefName == name; } }; /** This is how the Skeleton system works in 2.0: There is one BoneMemoryManager per skeleton. That means the same BoneMemoryManager manages the allocation of Bone data of all instances based on the same Skeleton definition. In other words, the skeletal animation system has been greatly optimized for the case where there are many instances sharing the same skeleton (regardless of how many animations are in use or if some instances use many more animations at the same time than others). @par At the same time, for multithreading purposes we keep track of all pointers we create and the variable "threadStarts" records where each thread should begin processing. Unlike nodes, we cannot just iterate through empty memory because each skeleton instance is too complex and somewhat heterogeneous. We also have to ensure that (e.g.) if skeletons[0] and skeletons[1] share the same memory block (which is granted by the BoneMemoryManager), they get updated in the same thread. Otherwise race conditions will ensue, due to SIMD branchless selections inside @SkeletonInstance::update. @par Just like other managers (@see mNodeMemoryManager), SceneManager implementations may want to provide more than one SkeletonAnimManager (i.e. one per octant) @remarks The same BoneMemoryManager can't be used for multiple definitions because otherwise many SIMD opportunities are lost due to the heterogeneity of the data (a Skeleton may have 3 bones, 10 animations, another may have 6 bones, 2 animations, etc) unless we wasted a lot of RAM or perform a lot of book-keeping. */ struct _OgreExport SkeletonAnimManager { typedef list<BySkeletonDef>::type BySkeletonDefList; BySkeletonDefList bySkeletonDefs; /// Creates an instance of a skeleton based on the given definition. SkeletonInstance* createSkeletonInstance( const SkeletonDef *skeletonDef, size_t numWorkerThreads ); void destroySkeletonInstance( SkeletonInstance *skeletonInstance ); void removeSkeletonDef( const SkeletonDef *skeletonDef ); }; /** @} */ /** @} */ } #include "OgreHeaderSuffix.h" #endif
41.707317
92
0.681871
29c5094b185ecc43e7aeb106fcbe72d8912c6446
14,722
c
C
nesys-enabler/client.c
Keith-Cancel/Random
6e7a43ffb5fb6cba1e256e80c5458cf111f12e6d
[ "MIT" ]
null
null
null
nesys-enabler/client.c
Keith-Cancel/Random
6e7a43ffb5fb6cba1e256e80c5458cf111f12e6d
[ "MIT" ]
null
null
null
nesys-enabler/client.c
Keith-Cancel/Random
6e7a43ffb5fb6cba1e256e80c5458cf111f12e6d
[ "MIT" ]
null
null
null
#include "client.h" #include "sha256.h" #include <winsock2.h> #include <windows.h> #include <stdio.h> #define HEADER_SZ 6 #define MSG_ID_SUCCESS 0x0000 #define MSG_ID_BAD_DECODE 0x0010 #define MSG_ID_BAD_AUTH 0x0011 #define MSG_ID_PING 0x00ff #define MSG_ID_GET_PROFILE 0x0100 #define MSG_ID_SET_PROFILE 0x0101 #define MSG_ID_GET_CARS 0x0102 #define MSG_ID_NEW_PROFILE 0x0110 #define MSG_ID_PROFILE_EXISTS 0x0111 // 11644473600 / (100 * 10^-9) #define EPOCH_DIFF 116444736000000000ULL struct request_info_s { uint8_t* dat; uint8_t* key; size_t dat_cap; size_t key_len; int64_t last_time; uint32_t ip; uint16_t port; }; // get the unix time stamp in miliseconds static int64_t time_ms() { FILETIME f_time; GetSystemTimeAsFileTime(&f_time); uint64_t time = f_time.dwLowDateTime; time |= ((uint64_t)f_time.dwHighDateTime) << 32; time -= EPOCH_DIFF; time /= 10000; // 10^6 ns in a ms, so 10^6/100 return time; } static int recv_x_bytes(SOCKET s, const uint8_t* data, size_t amt) { size_t offset = 0; while(offset < amt) { int read = recv(s, (char*)(data + offset), amt - offset, 0); if(read == SOCKET_ERROR) { return SOCKET_ERROR; } if(read == 0) { break; } offset += read; } return offset; } static int send_x_bytes(SOCKET s, const uint8_t* data, size_t amt) { size_t offset = 0; while(offset < amt) { int sent = send(s, (char*)(data + offset), amt - offset, 0); if(sent == SOCKET_ERROR) { return SOCKET_ERROR; } offset += sent; } return offset; } static SOCKET socket_create_IPv4_tcp(uint32_t IPv4, uint16_t port) { SOCKET s = socket(AF_INET, SOCK_STREAM, 0); if(s == INVALID_SOCKET) { printf("Failed to create socket!\n"); return INVALID_SOCKET; } DWORD to = 4000; // time out in ms setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (char*)&to, sizeof(DWORD)); setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&to, sizeof(DWORD)); struct sockaddr_in addr = { .sin_addr.s_addr = IPv4, .sin_family = AF_INET, .sin_port = htons(port) }; if(connect(s, (struct sockaddr*)&addr, sizeof(addr)) != 0) { printf("Socket failed to connect!\n"); closesocket(s); return INVALID_SOCKET; } return s; } // Functions for editing message buffer bool request_info_expand_buffer(requestInfo* info, size_t expand_by) { uint8_t* tmp = realloc(info->dat, info->dat_cap + expand_by + 1); if(tmp == NULL) { return false; } info->dat = tmp; info->dat_cap += expand_by; return true; } static bool get_has_hmac(requestInfo* info) { return info->dat[2] & 1; } static bool get_has_timestamp(requestInfo* info) { return info->dat[3] & 1; } static uint16_t get_length(requestInfo* info) { uint16_t len; memcpy(&len, info->dat + 4, 2); len = ntohs(len); return len; } static uint16_t get_msg_id(requestInfo* info) { uint16_t id; memcpy(&id, info->dat, 2); id = ntohs(id); return id; } static int64_t get_time_stamp(requestInfo* info) { if(!get_has_timestamp(info)) { return 0; } size_t pos = HEADER_SZ + get_length(info); if(info->dat_cap < pos + 8) { return 0; } uint64_t time = 0; for(int i = 0; i < 8; i++) { time <<= 8; time |= (info->dat + pos)[i]; } return time; } static size_t get_total_size(requestInfo* info) { size_t len = HEADER_SZ; len += get_length(info); len += get_has_timestamp(info) * 8; len += get_has_hmac(info) * 32; return len; } /* void print_long_hex_str(uint8_t* bytes, size_t len) { for(size_t i = 0; i < len; i++) { if(i > 0 && (i % 4) == 0) { printf(" "); } printf("%x%x", bytes[i] >> 4, bytes[i] & 0xf); } printf("\n"); } */ static bool is_hmac_valid(requestInfo* info) { if(!get_has_hmac(info)) { return false; } size_t msg_len = get_length(info); msg_len += HEADER_SZ; msg_len += get_has_timestamp(info) * 8; if(info->dat_cap < msg_len + 32) { return false; } uint8_t hash[32] = { 0 }; sha256_hmac( info->key, info->key_len, info->dat, msg_len, hash, 32 ); bool valid = true; for(int i = 0; i < 32; i++) { valid &= hash[i] == (info->dat + msg_len)[i]; } return valid; } static void set_has_hmac(requestInfo* info, bool val) { info->dat[2] = val & 1; } static void set_has_timestamp(requestInfo* info, bool val) { info->dat[3] = val & 1; } static void set_length(requestInfo* info, uint16_t len) { uint16_t tmp = htons(len); memcpy(info->dat + 4, &tmp, 2); } static void set_msg_id(requestInfo* info, uint16_t id) { uint16_t tmp = htons(id); memcpy(info->dat, &tmp, 2); } static bool append_body(requestInfo* info, const uint8_t* body, uint16_t len) { size_t length = get_length(info); size_t buf_sz = HEADER_SZ + length + len; if(info->dat_cap < buf_sz) { if(!request_info_expand_buffer(info, buf_sz - info->dat_cap)) { printf("Buffer failed! %d\n", len); return false; } } set_length(info, len + length); memcpy(info->dat + HEADER_SZ + length, body, len); set_has_hmac(info, false); set_has_timestamp(info, false); return true; } static bool set_body(requestInfo* info, const uint8_t* body, uint16_t len) { size_t buf_sz = HEADER_SZ + len; if(info->dat_cap < buf_sz) { if(!request_info_expand_buffer(info, buf_sz - info->dat_cap)) { return false; } } set_length(info, len); memcpy(info->dat + HEADER_SZ, body, len); set_has_hmac(info, false); set_has_timestamp(info, false); return true; } static bool set_time(requestInfo* info, int64_t time) { uint8_t bytes[8] = { 0 }; uint64_t tmp = time; size_t body_len = get_length(info); size_t buf_sz = HEADER_SZ + body_len + 8; if(info->dat_cap < buf_sz) { if(!request_info_expand_buffer(info, buf_sz - info->dat_cap)) { return false; } } for(int i = 0; i < 8; i++) { bytes[7 - i] = tmp & 0xff; tmp >>= 8; } memcpy(info->dat + HEADER_SZ + body_len, bytes, 8); set_has_timestamp(info, true); return true; } static bool set_time_now(requestInfo* info) { return set_time(info, time_ms()); } static bool gen_hmac(requestInfo* info) { size_t msg_len = get_length(info); msg_len += HEADER_SZ; msg_len += get_has_timestamp(info) * 8; size_t buf_sz = msg_len + 32; if(info->dat_cap < buf_sz) { if(!request_info_expand_buffer(info, buf_sz - info->dat_cap)) { return false; } } set_has_hmac(info, true); sha256_hmac( info->key, info->key_len, info->dat, msg_len, info->dat + msg_len, 32 ); return true; } // Process server reponse static requestState get_response(SOCKET s, requestInfo* info, bool need_hmac) { memset(info->dat, 0, info->dat_cap); if(recv_x_bytes(s, info->dat, HEADER_SZ) != HEADER_SZ) { printf("Failed to receive response header: "); if(WSAGetLastError() == WSAETIMEDOUT) { printf("Time out\n"); return TIME_OUT; } printf("Network Failure\n"); return FAILURE; } size_t total_size = get_total_size(info); // Make sure info buffer has enough room for entire message if(info->dat_cap < total_size) { if(!request_info_expand_buffer(info, total_size - info->dat_cap)) { printf("Failed to allocate memory!\n"); return FAILURE; } } total_size -= HEADER_SZ; bool has_time = get_has_timestamp(info); bool has_hmac = get_has_hmac(info); uint16_t msg_id = get_msg_id(info); if(need_hmac && !has_hmac) { return AUTH_FAIL_SERVER; } if(recv_x_bytes(s, info->dat + HEADER_SZ, total_size) != total_size) { printf("Failed to receive response body: "); if(WSAGetLastError() == WSAETIMEDOUT) { printf("Time out\n"); return TIME_OUT; } printf("Network Failure\n"); return FAILURE; } if(has_hmac) { if(!is_hmac_valid(info)) { printf("HMAC or time is not valid!\n"); return AUTH_FAIL_SERVER; } if(!has_time) { printf("HMAC requires time!\n"); } int64_t t = get_time_stamp(info); if(t <= info->last_time) { printf("Time stamp too old! %lld < %lld\n", t, info->last_time); return AUTH_FAIL_SERVER; } info->last_time = t; } switch(msg_id) { case MSG_ID_SUCCESS: return SUCCESS; case MSG_ID_BAD_AUTH: printf("Received an Auth Failed response!\n"); return AUTH_FAIL; default: printf("Unkown message ID: %02x\n", msg_id); return FAILURE; } } static requestState send_reponse(SOCKET s, requestInfo* info) { if(!set_time_now(info) || !gen_hmac(info)) { return FAILURE; } int tot = get_total_size(info); if(send_x_bytes(s, info->dat, tot) != tot) { if(WSAGetLastError() == WSAETIMEDOUT) { return TIME_OUT; } return FAILURE; } return SUCCESS; } requestState ping_server(requestInfo* info, unsigned* ping_time) { requestState ret = SUCCESS; uint64_t time = time_ms(); SOCKET s = socket_create_IPv4_tcp(info->ip, info->port); if(s == INVALID_SOCKET) { if(WSAGetLastError() == WSAETIMEDOUT) { return TIME_OUT; } return FAILURE; } memset(info->dat, 0, info->dat_cap); set_msg_id(info, MSG_ID_PING); ret = send_reponse(s, info); if(ret != SUCCESS) { closesocket(s); return ret; } ret = get_response(s, info, false); if(ret != SUCCESS) { closesocket(s); return ret; } *ping_time = time_ms() - time; closesocket(s); return SUCCESS; } requestState get_new_profile_id(requestInfo* info, uint8_t* id, size_t id_cap) { SOCKET s = socket_create_IPv4_tcp(info->ip, info->port); if(s == INVALID_SOCKET) { if(WSAGetLastError() == WSAETIMEDOUT) { return TIME_OUT; } return FAILURE; } memset(info->dat, 0, info->dat_cap); set_msg_id(info, MSG_ID_NEW_PROFILE); requestState ret = send_reponse(s, info); if(ret != SUCCESS) { closesocket(s); return ret; } ret = get_response(s, info, true); if(ret != SUCCESS) { closesocket(s); return ret; } uint16_t len = get_length(info); len = len > (id_cap - 1) ? id_cap - 1 : len; id[len] = '\0'; memcpy(id, info->dat + HEADER_SZ, len); closesocket(s); return SUCCESS; } requestState get_car_profile(requestInfo* info, const uint8_t* profile_id, const uint8_t* plate_txt, uint8_t* data, size_t data_cap, size_t* written) { memset(info->dat, 0, info->dat_cap); set_msg_id(info, MSG_ID_GET_PROFILE); uint8_t profile_len = strlen((const char*)profile_id); uint8_t plate_len = strlen((const char*)plate_txt); bool appended = true; appended &= append_body(info, &profile_len, 1); appended &= append_body(info, profile_id, profile_len); appended &= append_body(info, &plate_len, 1); appended &= append_body(info, plate_txt, plate_len); if(appended == false) { return FAILURE; } SOCKET s = socket_create_IPv4_tcp(info->ip, info->port); if(s == INVALID_SOCKET) { if(WSAGetLastError() == WSAETIMEDOUT) { return TIME_OUT; } return FAILURE; } requestState ret = send_reponse(s, info); if(ret != SUCCESS) { closesocket(s); return ret; } ret = get_response(s, info, true); if(ret != SUCCESS) { closesocket(s); return ret; } uint16_t length = get_length(info); length = length > data_cap ? data_cap : length; memcpy(data, info->dat + HEADER_SZ, length); *written = length; closesocket(s); return SUCCESS; } requestState save_car_profile(requestInfo* info, const uint8_t* profile_id, const uint8_t* plate_txt, uint8_t* data, size_t data_length) { memset(info->dat, 0, info->dat_cap); set_msg_id(info, MSG_ID_SET_PROFILE); uint8_t profile_len = strlen((const char*)profile_id); uint8_t plate_len = strlen((const char*)plate_txt); bool appended = true; appended &= append_body(info, &profile_len, 1); appended &= append_body(info, profile_id, profile_len); appended &= append_body(info, &plate_len, 1); appended &= append_body(info, plate_txt, plate_len); data_length &= 0xffff; uint16_t data_len = htons(data_length); appended &= append_body(info, (uint8_t*)&data_len, 2); appended &= append_body(info, data, data_length); if(appended == false) { return FAILURE; } SOCKET s = socket_create_IPv4_tcp(info->ip, info->port); if(s == INVALID_SOCKET) { if(WSAGetLastError() == WSAETIMEDOUT) { return TIME_OUT; } return FAILURE; } requestState ret = send_reponse(s, info); if(ret != SUCCESS) { closesocket(s); return ret; } ret = get_response(s, info, true); if(ret != SUCCESS) { closesocket(s); return ret; } closesocket(s); return SUCCESS; } // Buffer creation and size adjust requestInfo* request_info_create(const uint8_t* key, size_t key_len, const uint8_t* IPv4, uint16_t port) { requestInfo* info = malloc(sizeof(requestInfo)); if(info == NULL) { return NULL; } info->dat = malloc(512); if(info->dat == NULL) { free(info); return NULL; } info->key = malloc(key_len); if(info->key == NULL) { free(info->dat); free(info); return NULL; } memset(info->dat, 0, 512); memcpy(info->key, key, key_len); info->dat_cap = 512; info->key_len = key_len; info->port = port; info->ip = inet_addr((char*)IPv4); info->last_time = time_ms() - (20 * 1000); return info; } void request_info_free(requestInfo* info) { free(info->dat); free(info); } bool init_client() { WSADATA wsa; if (WSAStartup(MAKEWORD(2,2),&wsa) != 0) { return false; } return true; } void cleanup_client() { WSACleanup(); }
26.478417
151
0.597949
4b34b0bfe372c6046d4f6efd68568bccadb266f5
20,687
c
C
MultiSource/Benchmarks/MallocBench/perl/regexec.c
gmlueck/llvm-test-suite
7ff842b8fec970561fed78c9347e496538cf74f5
[ "Apache-2.0" ]
70
2019-01-15T03:03:55.000Z
2022-03-28T02:16:13.000Z
MultiSource/Benchmarks/MallocBench/perl/regexec.c
gmlueck/llvm-test-suite
7ff842b8fec970561fed78c9347e496538cf74f5
[ "Apache-2.0" ]
519
2020-09-15T07:40:51.000Z
2022-03-31T20:51:15.000Z
MultiSource/Benchmarks/MallocBench/perl/regexec.c
gmlueck/llvm-test-suite
7ff842b8fec970561fed78c9347e496538cf74f5
[ "Apache-2.0" ]
117
2020-06-24T13:11:04.000Z
2022-03-23T15:44:23.000Z
/* NOTE: this is derived from Henry Spencer's regexp code, and should not * confused with the original package (see point 3 below). Thanks, Henry! */ /* Additional note: this code is very heavily munged from Henry's version * in places. In some spots I've traded clarity for efficiency, so don't * blame Henry for some of the lack of readability. */ /* $RCSfile$$Revision$$Date$ * * $Log$ * Revision 1.1 2004/02/17 22:21:16 criswell * Initial commit of the perl Malloc Benchmark. I've cheated a little by * generating the yacc output files and committing them directly, but it was * easier than disabling the Bison Voodoo that gets executed by default. * * Revision 4.0.1.1 91/04/12 09:07:39 lwall * patch1: regexec only allocated space for 9 subexpresssions * * Revision 4.0 91/03/20 01:39:16 lwall * 4.0 baseline. * */ /* * regcomp and regexec -- regsub and regerror are not used in perl * * Copyright (c) 1986 by University of Toronto. * Written by Henry Spencer. Not derived from licensed software. * * Permission is granted to anyone to use this software for any * purpose on any computer system, and to redistribute it freely, * subject to the following restrictions: * * 1. The author is not responsible for the consequences of use of * this software, no matter how awful, even if they arise * from defects in it. * * 2. The origin of this software must not be misrepresented, either * by explicit claim or by omission. * * 3. Altered versions must be plainly marked as such, and must not * be misrepresented as being the original software. * **** Alterations to Henry's code are... **** **** Copyright (c) 1989, Larry Wall **** **** You may distribute under the terms of the GNU General Public License **** as specified in the README file that comes with the perl 3.0 kit. * * Beware that some of this code is subtly aware of the way operator * precedence is structured in regular expressions. Serious changes in * regular-expression syntax might require a total rethink. */ #include "EXTERN.h" #include "perl.h" #include "regcomp.h" #ifndef STATIC #define STATIC static #endif #ifdef DEBUGGING int regnarrate = 0; #endif #define isALNUM(c) (isascii(c) && (isalpha(c) || isdigit(c) || c == '_')) #define isSPACE(c) (isascii(c) && isspace(c)) #define isDIGIT(c) (isascii(c) && isdigit(c)) #define isUPPER(c) (isascii(c) && isupper(c)) /* * regexec and friends */ /* * Global work variables for regexec(). */ static char *regprecomp; static char *reginput; /* String-input pointer. */ static char regprev; /* char before regbol, \n if none */ static char *regbol; /* Beginning of input, for ^ check. */ static char *regeol; /* End of input, for $ check. */ static char **regstartp; /* Pointer to startp array. */ static char **regendp; /* Ditto for endp. */ static char *reglastparen; /* Similarly for lastparen. */ static char *regtill; static int regmyp_size = 0; static char **regmystartp = Null(char**); static char **regmyendp = Null(char**); /* * Forwards. */ STATIC int regtry(); STATIC int regmatch(); STATIC int regrepeat(); extern int multiline; /* - regexec - match a regexp against a string */ int regexec(prog, stringarg, strend, strbeg, minend, screamer, safebase) register regexp *prog; char *stringarg; register char *strend; /* pointer to null at end of string */ char *strbeg; /* real beginning of string */ int minend; /* end of match must be at least minend after stringarg */ STR *screamer; int safebase; /* no need to remember string in subbase */ { register char *s; register int i; register char *c; register char *string = stringarg; register int tmp; int minlen = 0; /* must match at least this many chars */ int dontbother = 0; /* how many characters not to try at end */ /* Be paranoid... */ if (prog == NULL || string == NULL) { fatal("NULL regexp parameter"); return(0); } if (string == strbeg) /* is ^ valid at stringarg? */ regprev = '\n'; else { regprev = stringarg[-1]; if (!multiline && regprev == '\n') regprev = '\0'; /* force ^ to NOT match */ } regprecomp = prog->precomp; /* Check validity of program. */ if (UCHARAT(prog->program) != MAGIC) { FAIL("corrupted regexp program"); } if (prog->do_folding) { safebase = FALSE; i = strend - string; New(1101,c,i+1,char); (void)bcopy(string, c, i+1); string = c; strend = string + i; for (s = string; s < strend; s++) if (isUPPER(*s)) *s = tolower(*s); } /* If there is a "must appear" string, look for it. */ s = string; if (prog->regmust != Nullstr && (!(prog->reganch & 1) || (multiline && prog->regback >= 0)) ) { if (stringarg == strbeg && screamer) { if (screamfirst[prog->regmust->str_rare] >= 0) s = screaminstr(screamer,prog->regmust); else s = Nullch; } #ifndef lint else s = fbminstr((unsigned char*)s, (unsigned char*)strend, prog->regmust); #endif if (!s) { ++prog->regmust->str_u.str_useful; /* hooray */ goto phooey; /* not present */ } else if (prog->regback >= 0) { s -= prog->regback; if (s < string) s = string; minlen = prog->regback + prog->regmust->str_cur; } else if (--prog->regmust->str_u.str_useful < 0) { /* boo */ str_free(prog->regmust); prog->regmust = Nullstr; /* disable regmust */ s = string; } else { s = string; minlen = prog->regmust->str_cur; } } /* Mark beginning of line for ^ . */ regbol = string; /* Mark end of line for $ (and such) */ regeol = strend; /* see how far we have to get to not match where we matched before */ regtill = string+minend; /* Allocate our backreference arrays */ if ( regmyp_size < prog->nparens + 1 ) { /* Allocate or enlarge the arrays */ regmyp_size = prog->nparens + 1; if ( regmyp_size < 10 ) regmyp_size = 10; /* minimum */ if ( regmystartp ) { /* reallocate larger */ Renew(regmystartp,regmyp_size,char*); Renew(regmyendp, regmyp_size,char*); } else { /* Initial allocation */ New(1102,regmystartp,regmyp_size,char*); New(1102,regmyendp, regmyp_size,char*); } } /* Simplest case: anchored match need be tried only once. */ /* [unless multiline is set] */ if (prog->reganch & 1) { if (regtry(prog, string)) goto got_it; else if (multiline) { if (minlen) dontbother = minlen - 1; strend -= dontbother; /* for multiline we only have to try after newlines */ if (s > string) s--; while (s < strend) { if (*s++ == '\n') { if (s < strend && regtry(prog, s)) goto got_it; } } } goto phooey; } /* Messy cases: unanchored match. */ if (prog->regstart) { if (prog->reganch & 2) { /* we have /x+whatever/ */ /* it must be a one character string */ i = prog->regstart->str_ptr[0]; while (s < strend) { if (*s == i) { if (regtry(prog, s)) goto got_it; s++; while (s < strend && *s == i) s++; } s++; } } else if (prog->regstart->str_pok == 3) { /* We know what string it must start with. */ #ifndef lint while ((s = fbminstr((unsigned char*)s, (unsigned char*)strend, prog->regstart)) != NULL) #else while (s = Nullch) #endif { if (regtry(prog, s)) goto got_it; s++; } } else { c = prog->regstart->str_ptr; while ((s = ninstr(s, strend, c, c + prog->regstart->str_cur )) != NULL) { if (regtry(prog, s)) goto got_it; s++; } } goto phooey; } if (c = prog->regstclass) { int doevery = (prog->reganch & 2) == 0; if (minlen) dontbother = minlen - 1; strend -= dontbother; /* don't bother with what can't match */ tmp = 1; /* We know what class it must start with. */ switch (OP(c)) { case ANYOF: c = OPERAND(c); while (s < strend) { i = UCHARAT(s); if (!(c[i >> 3] & (1 << (i&7)))) { if (tmp && regtry(prog, s)) goto got_it; else tmp = doevery; } else tmp = 1; s++; } break; case BOUND: if (minlen) dontbother++,strend--; if (s != string) { i = s[-1]; tmp = isALNUM(i); } else tmp = isALNUM(regprev); /* assume not alphanumeric */ while (s < strend) { i = *s; if (tmp != isALNUM(i)) { tmp = !tmp; if (regtry(prog, s)) goto got_it; } s++; } if ((minlen || tmp) && regtry(prog,s)) goto got_it; break; case NBOUND: if (minlen) dontbother++,strend--; if (s != string) { i = s[-1]; tmp = isALNUM(i); } else tmp = isALNUM(regprev); /* assume not alphanumeric */ while (s < strend) { i = *s; if (tmp != isALNUM(i)) tmp = !tmp; else if (regtry(prog, s)) goto got_it; s++; } if ((minlen || !tmp) && regtry(prog,s)) goto got_it; break; case ALNUM: while (s < strend) { i = *s; if (isALNUM(i)) { if (tmp && regtry(prog, s)) goto got_it; else tmp = doevery; } else tmp = 1; s++; } break; case NALNUM: while (s < strend) { i = *s; if (!isALNUM(i)) { if (tmp && regtry(prog, s)) goto got_it; else tmp = doevery; } else tmp = 1; s++; } break; case SPACE: while (s < strend) { if (isSPACE(*s)) { if (tmp && regtry(prog, s)) goto got_it; else tmp = doevery; } else tmp = 1; s++; } break; case NSPACE: while (s < strend) { if (!isSPACE(*s)) { if (tmp && regtry(prog, s)) goto got_it; else tmp = doevery; } else tmp = 1; s++; } break; case DIGIT: while (s < strend) { if (isDIGIT(*s)) { if (tmp && regtry(prog, s)) goto got_it; else tmp = doevery; } else tmp = 1; s++; } break; case NDIGIT: while (s < strend) { if (!isDIGIT(*s)) { if (tmp && regtry(prog, s)) goto got_it; else tmp = doevery; } else tmp = 1; s++; } break; } } else { if (minlen) dontbother = minlen - 1; strend -= dontbother; /* We don't know much -- general case. */ do { if (regtry(prog, s)) goto got_it; } while (s++ < strend); } /* Failure. */ goto phooey; got_it: if ((!safebase && (prog->nparens || sawampersand)) || prog->do_folding){ strend += dontbother; /* uncheat */ if (safebase) /* no need for $digit later */ s = strbeg; else if (strbeg != prog->subbase) { i = strend - string + (stringarg - strbeg); s = nsavestr(strbeg,i); /* so $digit will work later */ if (prog->subbase) Safefree(prog->subbase); prog->subbase = s; prog->subend = s+i; } else s = prog->subbase; s += (stringarg - strbeg); for (i = 0; i <= prog->nparens; i++) { if (prog->endp[i]) { prog->startp[i] = s + (prog->startp[i] - string); prog->endp[i] = s + (prog->endp[i] - string); } } if (prog->do_folding) Safefree(string); } return(1); phooey: if (prog->do_folding) Safefree(string); return(0); } /* - regtry - try match at specific point */ static int /* 0 failure, 1 success */ regtry(prog, string) regexp *prog; char *string; { register int i; register char **sp; register char **ep; reginput = string; regstartp = prog->startp; regendp = prog->endp; reglastparen = &prog->lastparen; prog->lastparen = 0; sp = prog->startp; ep = prog->endp; if (prog->nparens) { for (i = prog->nparens; i >= 0; i--) { *sp++ = NULL; *ep++ = NULL; } } if (regmatch(prog->program + 1) && reginput >= regtill) { prog->startp[0] = string; prog->endp[0] = reginput; return(1); } else return(0); } /* - regmatch - main matching routine * * Conceptually the strategy is simple: check to see whether the current * node matches, call self recursively to see whether the rest matches, * and then act accordingly. In practice we make some effort to avoid * recursion, in particular by going through "ordinary" nodes (that don't * need to know whether the rest of the match failed) by a loop instead of * by recursion. */ /* [lwall] I've hoisted the register declarations to the outer block in order to * maybe save a little bit of pushing and popping on the stack. It also takes * advantage of machines that use a register save mask on subroutine entry. */ static int /* 0 failure, 1 success */ regmatch(prog) char *prog; { register char *scan; /* Current node. */ char *next; /* Next node. */ register int nextchar; register int n; /* no or next */ register int ln; /* len or last */ register char *s; /* operand or save */ register char *locinput = reginput; nextchar = *locinput; scan = prog; #ifdef DEBUGGING if (scan != NULL && regnarrate) fprintf(stderr, "%s(\n", regprop(scan)); #endif while (scan != NULL) { #ifdef DEBUGGING if (regnarrate) fprintf(stderr, "%s...\n", regprop(scan)); #endif #ifdef REGALIGN next = scan + NEXT(scan); if (next == scan) next = NULL; #else next = regnext(scan); #endif switch (OP(scan)) { case BOL: if (locinput == regbol ? regprev == '\n' : ((nextchar || locinput < regeol) && locinput[-1] == '\n') ) { /* regtill = regbol; */ break; } return(0); case EOL: if ((nextchar || locinput < regeol) && nextchar != '\n') return(0); if (!multiline && regeol - locinput > 1) return 0; /* regtill = regbol; */ break; case ANY: if ((nextchar == '\0' && locinput >= regeol) || nextchar == '\n') return(0); nextchar = *++locinput; break; case EXACTLY: s = OPERAND(scan); ln = *s++; /* Inline the first character, for speed. */ if (*s != nextchar) return(0); if (regeol - locinput < ln) return 0; if (ln > 1 && bcmp(s, locinput, ln) != 0) return(0); locinput += ln; nextchar = *locinput; break; case ANYOF: s = OPERAND(scan); if (nextchar < 0) nextchar = UCHARAT(locinput); if (s[nextchar >> 3] & (1 << (nextchar&7))) return(0); if (!nextchar && locinput >= regeol) return 0; nextchar = *++locinput; break; case ALNUM: if (!nextchar) return(0); if (!isALNUM(nextchar)) return(0); nextchar = *++locinput; break; case NALNUM: if (!nextchar && locinput >= regeol) return(0); if (isALNUM(nextchar)) return(0); nextchar = *++locinput; break; case NBOUND: case BOUND: if (locinput == regbol) /* was last char in word? */ ln = isALNUM(regprev); else ln = isALNUM(locinput[-1]); n = isALNUM(nextchar); /* is next char in word? */ if ((ln == n) == (OP(scan) == BOUND)) return(0); break; case SPACE: if (!nextchar && locinput >= regeol) return(0); if (!isSPACE(nextchar)) return(0); nextchar = *++locinput; break; case NSPACE: if (!nextchar) return(0); if (isSPACE(nextchar)) return(0); nextchar = *++locinput; break; case DIGIT: if (!isDIGIT(nextchar)) return(0); nextchar = *++locinput; break; case NDIGIT: if (!nextchar && locinput >= regeol) return(0); if (isDIGIT(nextchar)) return(0); nextchar = *++locinput; break; case REF: n = ARG1(scan); /* which paren pair */ s = regmystartp[n]; if (!s) return(0); if (!regmyendp[n]) return(0); if (s == regmyendp[n]) break; /* Inline the first character, for speed. */ if (*s != nextchar) return(0); ln = regmyendp[n] - s; if (locinput + ln > regeol) return 0; if (ln > 1 && bcmp(s, locinput, ln) != 0) return(0); locinput += ln; nextchar = *locinput; break; case NOTHING: break; case BACK: break; case OPEN: n = ARG1(scan); /* which paren pair */ reginput = locinput; regmystartp[n] = locinput; /* for REF */ if (regmatch(next)) { /* * Don't set startp if some later * invocation of the same parentheses * already has. */ if (regstartp[n] == NULL) regstartp[n] = locinput; return(1); } else return(0); /* NOTREACHED */ case CLOSE: { n = ARG1(scan); /* which paren pair */ reginput = locinput; regmyendp[n] = locinput; /* for REF */ if (regmatch(next)) { /* * Don't set endp if some later * invocation of the same parentheses * already has. */ if (regendp[n] == NULL) { regendp[n] = locinput; if (n > *reglastparen) *reglastparen = n; } return(1); } else return(0); } /*NOTREACHED*/ case BRANCH: { if (OP(next) != BRANCH) /* No choice. */ next = NEXTOPER(scan); /* Avoid recursion. */ else { do { reginput = locinput; if (regmatch(NEXTOPER(scan))) return(1); #ifdef REGALIGN if (n = NEXT(scan)) scan += n; else scan = NULL; #else scan = regnext(scan); #endif } while (scan != NULL && OP(scan) == BRANCH); return(0); /* NOTREACHED */ } } break; case CURLY: ln = ARG1(scan); /* min to match */ n = ARG2(scan); /* max to match */ scan = NEXTOPER(scan) + 4; goto repeat; case STAR: ln = 0; n = 0; scan = NEXTOPER(scan); goto repeat; case PLUS: /* * Lookahead to avoid useless match attempts * when we know what character comes next. */ ln = 1; n = 0; scan = NEXTOPER(scan); repeat: if (OP(next) == EXACTLY) nextchar = *(OPERAND(next)+1); else nextchar = -1000; reginput = locinput; n = regrepeat(scan, n); if (!multiline && OP(next) == EOL && ln < n) ln = n; /* why back off? */ while (n >= ln) { /* If it could work, try it. */ if (nextchar == -1000 || *reginput == nextchar) if (regmatch(next)) return(1); /* Couldn't or didn't -- back up. */ n--; reginput = locinput + n; } return(0); case END: reginput = locinput; /* put where regtry can find it */ return(1); /* Success! */ default: printf("%x %d\n",scan,scan[1]); FAIL("regexp memory corruption"); } scan = next; } /* * We get here only if there's trouble -- normally "case END" is * the terminating point. */ FAIL("corrupted regexp pointers"); /*NOTREACHED*/ #ifdef lint return 0; #endif } /* - regrepeat - repeatedly match something simple, report how many */ /* * [This routine now assumes that it will only match on things of length 1. * That was true before, but now we assume scan - reginput is the count, * rather than incrementing count on every character.] */ static int regrepeat(p, max) char *p; int max; { register char *scan; register char *opnd; register int c; register char *loceol = regeol; scan = reginput; if (max && max < loceol - scan) loceol = scan + max; opnd = OPERAND(p); switch (OP(p)) { case ANY: while (scan < loceol && *scan != '\n') scan++; break; case EXACTLY: /* length of string is 1 */ opnd++; while (scan < loceol && *opnd == *scan) scan++; break; case ANYOF: c = UCHARAT(scan); while (scan < loceol && !(opnd[c >> 3] & (1 << (c & 7)))) { scan++; c = UCHARAT(scan); } break; case ALNUM: while (scan < loceol && isALNUM(*scan)) scan++; break; case NALNUM: while (scan < loceol && !isALNUM(*scan)) scan++; break; case SPACE: while (scan < loceol && isSPACE(*scan)) scan++; break; case NSPACE: while (scan < loceol && !isSPACE(*scan)) scan++; break; case DIGIT: while (scan < loceol && isDIGIT(*scan)) scan++; break; case NDIGIT: while (scan < loceol && !isDIGIT(*scan)) scan++; break; default: /* Oh dear. Called inappropriately. */ FAIL("internal regexp foulup"); /* NOTREACHED */ } c = scan - reginput; reginput = scan; return(c); } /* - regnext - dig the "next" pointer out of a node * * [Note, when REGALIGN is defined there are two places in regmatch() * that bypass this code for speed.] */ char * regnext(p) register char *p; { register int offset; if (p == &regdummy) return(NULL); offset = NEXT(p); if (offset == 0) return(NULL); #ifdef REGALIGN return(p+offset); #else if (OP(p) == BACK) return(p-offset); else return(p+offset); #endif }
23.036748
80
0.569295
f4feb33e1cb3e9a1bb41465f3369f0c8f1c64df9
5,136
h
C
components/esp_peripherals/lib/aw2013/aw2013.h
zhangtemplar/esp-adf
dc4f652efe8a3b3638b08a798af6e13763fd95c8
[ "MIT-0" ]
960
2018-04-03T15:13:46.000Z
2022-03-29T02:48:46.000Z
components/esp_peripherals/lib/aw2013/aw2013.h
zhangtemplar/esp-adf
dc4f652efe8a3b3638b08a798af6e13763fd95c8
[ "MIT-0" ]
786
2018-04-08T10:25:08.000Z
2022-03-31T23:20:40.000Z
components/esp_peripherals/lib/aw2013/aw2013.h
zhangtemplar/esp-adf
dc4f652efe8a3b3638b08a798af6e13763fd95c8
[ "MIT-0" ]
512
2018-04-05T18:16:52.000Z
2022-03-31T21:27:53.000Z
/* * ESPRESSIF MIT License * * Copyright (c) 2020 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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. * */ #ifndef _AW2013_H_ #define _AW2013_H_ #include "esp_log.h" #include "esp_err.h" #ifdef __cplusplus extern "C" { #endif #define AW2013_I2C_PORT I2C_NUM_0 #define AW2013_RESET_VALUE 0x55 #define AW2013_REG_RESET 0x00 #define AW2013_REG_GCR 0x01 #define AW2013_REG_LCTR 0x30 #define AW2013_REG_LCFG0 0x31 #define AW2013_REG_LCFG1 0x32 #define AW2013_REG_LCFG2 0x33 #define AW2013_REG_PWM0 0x34 #define AW2013_REG_PWM1 0x35 #define AW2013_REG_PWM2 0x36 #define AW2013_REG_LED0T1T2 0x37 #define AW2013_REG_LED1T1T2 0x3A #define AW2013_REG_LED2T1T2 0x3D #define AW2013_REG_LED0T3T4 0x38 #define AW2013_REG_LED1T3T4 0x3B #define AW2013_REG_LED2T3T4 0x3E #define AW2013_REG_LED0T0CNT 0x39 #define AW2013_REG_LED1T0CNT 0x3C #define AW2013_REG_LED2T0CNT 0x3F typedef enum { AW2013_BRIGHT_0, // Turn off the lights, the electric current is 0mA AW2013_BRIGHT_1, // 5mA AW2013_BRIGHT_2, // 10mA AW2013_BRIGHT_3, // 15mA } aw2013_brightness_t; // Time periods of a auto flash cycle /*-------------------------------------------*\ | __________ | | /| |\ | | / | | \ | | / | | \ | | ________/ | | \__________ | | | | | | | | | | |<--t0->|t1 |<--t2-->|t3 |<--t4-->| | \*-------------------------------------------*/ typedef enum { AW2013_TIME_0, // T0 AW2013_TIME_1, // T1 AW2013_TIME_2, // T2 AW2013_TIME_3, // T3 AW2013_TIME_4 // T4 } aw2013_time_t; typedef enum { // T1-T4 T0 AW2013_TIME_LEVEL_0, // 0.13s (T0 0s) AW2013_TIME_LEVEL_1, // 0.26s (T0 0.13s) AW2013_TIME_LEVEL_2, // 0.52s (T0 0.26s) AW2013_TIME_LEVEL_3, // 1.04s (T0 0.52s) AW2013_TIME_LEVEL_4, // 2.08s (T0 1.04s) AW2013_TIME_LEVEL_5, // 4.16s (T0 2.08s) AW2013_TIME_LEVEL_6, // 8.32s (T0 4.16s) AW2013_TIME_LEVEL_7, // 16.64s (T0 8.32s) AW2013_TIME_LEVEL_8, // (T0 16.64s) } aw2013_time_level_t; /** * @brief Initialize the aw2013 chip * * @return * - ESP_OK Success * - ESP_FAIL error */ esp_err_t aw2013_init(void); /** * @brief Deinitialize the aw2013 chip * * @return * - ESP_OK Success * - ESP_FAIL error */ esp_err_t aw2013_deinit(void); /** * @brief Reset the aw2013 chip * * @return * - ESP_OK Success * - ESP_FAIL error */ esp_err_t aw2013_reset(void); /** * @brief Set rgb value for the aw2013 * * @param value The value to be set * * @return * - ESP_OK Success * - ESP_FAIL error */ esp_err_t aw2013_set_pwm_value(uint32_t value); /** * @brief Set repeat times for auto flash * * @param cnt Number of repetitions * * @return * - ESP_OK Success * - ESP_FAIL error */ esp_err_t aw2013_set_repeat_time(uint8_t cnt); /** * @brief Set the time for each time period for auto flash * * @param time The time period * @param level The time to be set * * @return * - ESP_OK Success * - ESP_FAIL error */ esp_err_t aw2013_set_time(aw2013_time_t time, aw2013_time_level_t level); /** * @brief Set the brightness * * @param bright The brightness to be set * * @return * - ESP_OK Success * - ESP_FAIL error */ esp_err_t aw2013_set_brightness(aw2013_brightness_t bright); /** * @brief Enable the auto flash fuction * * @param en Whether to enable * * @return * - ESP_OK Success * - ESP_FAIL error */ esp_err_t aw2013_enable_auto_flash(bool en); /** * @brief Enable the fade fuction * * @param en Whether to enable * * @return * - ESP_OK Success * - ESP_FAIL error */ esp_err_t aw2013_enable_fade_mode(bool en); #ifdef __cplusplus } #endif #endif
25.68
95
0.63824
63a2c88c3507f767776f2bdbbe08bd506b8c3691
718
c
C
Assignment - 07.c
Wicerradien/C
a0ef1230a916a50918840c88f2eb0d9a8023599c
[ "MIT" ]
null
null
null
Assignment - 07.c
Wicerradien/C
a0ef1230a916a50918840c88f2eb0d9a8023599c
[ "MIT" ]
null
null
null
Assignment - 07.c
Wicerradien/C
a0ef1230a916a50918840c88f2eb0d9a8023599c
[ "MIT" ]
null
null
null
// // main.c // A01 - P07 // // Created by Nafiur Rahman Dhrubo on 4/10/21. // #include <math.h> #include <stdio.h> int main () { double a, b, c, d, R1, R2, RP, IP; printf("Enter a, b, c : "); scanf("%lf %lf %lf", &a, &b, &c); d = b * b - 4 * a * c; if (d > 0) { R1 = (-b + sqrt(d)) / (2 * a); R2 = (-b - sqrt(d)) / (2 * a); printf("Root1 = %lf and Root2 = %lf", R1, R2); } else if (d == 0) { R1 = R2 = -b / (2 * a); printf("Root1 = Root2 = %lf;", R1); } else { RP = -b / (2 * a); IP = sqrt(-d) / (2 * a); printf("Root1 = %lf + %lfi & Root2 = %f - %fi", RP, IP, RP, IP); } return 0; }
17.95
72
0.37883
4989b4fdeb9f78c1a2cd5484a4029d8e1ebe1930
8,567
h
C
fast-monitor/FAST-DLL/framework.h
bobfast/fast
41460b9eba7b160a280fec221d704229d2681f74
[ "MIT" ]
1
2020-10-02T06:55:43.000Z
2020-10-02T06:55:43.000Z
fast-monitor/FAST-DLL/framework.h
bobfast/fast
41460b9eba7b160a280fec221d704229d2681f74
[ "MIT" ]
3
2020-11-16T08:31:04.000Z
2021-09-02T18:51:32.000Z
fast-monitor/FAST-DLL/framework.h
bobfast/fast
41460b9eba7b160a280fec221d704229d2681f74
[ "MIT" ]
null
null
null
#pragma once #include <Windows.h> #include <stdio.h> #include <stdlib.h> #include <locale.h> #include <tchar.h> #include <process.h> #include <psapi.h> #include "dbghelp.h" #pragma comment(lib, "psapi.lib") #pragma comment(lib,"Dbghelp.lib") const int MaxNameLen = 256; #define DLLBASIC_API extern "C" __declspec(dllexport) #define MSG_SIZE 3000 #define NT_SUCCESS(status) (((NTSTATUS)(status)) >= 0) // Enumeration type for NtMapViewOfSection typedef enum class _SECTION_INHERIT { ViewShare = 1, ViewUnmap = 2 } SECTION_INHERIT, * PSECTION_INHERIT; // NtMapViewOfSection Function Pointer Type typedef NTSTATUS(NTAPI* NTMAPVIEWOFSECTION)( HANDLE SectionHandle, HANDLE ProcessHandle, PVOID* BaseAddress, ULONG_PTR ZeroBits, SIZE_T CommitSize, PLARGE_INTEGER SectionOffset, PSIZE_T ViewSize, SECTION_INHERIT InheritDisposition, ULONG AllocationType, ULONG Win32Protect ); // Struct types for NtCreateThreadEx typedef struct _UNICODE_STRING { WORD Length; WORD MaximumLength; WORD* Buffer; } UNICODE_STRING, * PUNICODE_STRING; typedef struct _OBJECT_ATTRIBUTES { ULONG Length; PVOID RootDirectory; PUNICODE_STRING ObjectName; ULONG Attributes; PVOID SecurityDescriptor; PVOID SecurityQualityOfService; } OBJECT_ATTRIBUTES, * POBJECT_ATTRIBUTES; typedef struct _THREAD_INFO { ULONG Flags; ULONG BufferSize; PVOID lpBuffer; ULONG Unknown; } THREAD_INFO, * PTHREAD_INFO; typedef struct _CREATE_THREAD_INFO { ULONG Length; THREAD_INFO Client; THREAD_INFO TEB; } CREATE_THREAD_INFO; // CreateRemoteThread Function Pointer Type typedef HANDLE(WINAPI * CREATEREMOTETHREAD)( HANDLE hProcess, LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId ); // VirtualAllocEx Function Pointer Type typedef LPVOID(WINAPI * VIRTUALALLOCEX)( HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect ); // WriteProcessMemory Function Pointer Type typedef BOOL(WINAPI * WRITEPROCESSMEMORY)( HANDLE hProcess, LPVOID lpBaseAddress, LPCVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesWritten ); // DbgPrint Function Pointer Type typedef NTSTATUS(NTAPI* DBGPRINT)( LPCSTR Format, ... ); // Enumeration & struct types for NtQuerySystemInformation typedef enum _SYSTEM_INFORMATION_CLASS { SystemBasicInformation, SystemProcessorInformation, SystemPerformanceInformation, SystemTimeOfDayInformation, SystemPathInformation, SystemProcessInformation, SystemCallCountInformation, SystemDeviceInformation, SystemProcessorPerformanceInformation, SystemFlagsInformation, SystemCallTimeInformation, SystemModuleInformation, SystemLocksInformation, SystemStackTraceInformation, SystemPagedPoolInformation, SystemNonPagedPoolInformation, SystemHandleInformation, SystemObjectInformation, SystemPageFileInformation, SystemVdmInstemulInformation, SystemVdmBopInformation, SystemFileCacheInformation, SystemPoolTagInformation, SystemInterruptInformation, SystemDpcBehaviorInformation, SystemFullMemoryInformation, SystemLoadGdiDriverInformation, SystemUnloadGdiDriverInformation, SystemTimeAdjustmentInformation, SystemSummaryMemoryInformation, SystemNextEventIdInformation, SystemEventIdsInformation, SystemCrashDumpInformation, SystemExceptionInformation, SystemCrashDumpStateInformation, SystemKernelDebuggerInformation, SystemContextSwitchInformation, SystemRegistryQuotaInformation, SystemExtendServiceTableInformation, SystemPrioritySeperation, SystemPlugPlayBusInformation, SystemDockInformation, _SystemPowerInformation, SystemProcessorSpeedInformation, SystemCurrentTimeZoneInformation, SystemLookasideInformation } SYSTEM_INFORMATION_CLASS, * PSYSTEM_INFORMATION_CLASS; typedef LONG KPRIORITY; typedef LONG KWAIT_REASON; #define STATUS_INFO_LENGTH_MISMATCH (0xC0000004L) typedef struct _VM_COUNTERS { SIZE_T PeakVirtualSize; SIZE_T VirtualSize; ULONG PageFaultCount; // Padding here in 64-bit SIZE_T PeakWorkingSetSize; SIZE_T WorkingSetSize; SIZE_T QuotaPeakPagedPoolUsage; SIZE_T QuotaPagedPoolUsage; SIZE_T QuotaPeakNonPagedPoolUsage; SIZE_T QuotaNonPagedPoolUsage; SIZE_T PagefileUsage; SIZE_T PeakPagefileUsage; } VM_COUNTERS; typedef struct _CLIENT_ID { HANDLE UniqueProcess; HANDLE UniqueThread; } CLIENT_ID, * PCLIENT_ID; typedef struct _SYSTEM_THREAD { LARGE_INTEGER KernelTime; LARGE_INTEGER UserTime; LARGE_INTEGER CreateTime; ULONG WaitTime; PVOID StartAddress; CLIENT_ID ClientId; KPRIORITY Priority; LONG BasePriority; ULONG ContextSwitchCount; ULONG State; KWAIT_REASON WaitReason; } SYSTEM_THREAD, * PSYSTEM_THREAD; typedef struct _SYSTEM_PROCESS_INFORMATION { ULONG NextEntryDelta; ULONG ThreadCount; ULONG Reserved1[6]; LARGE_INTEGER CreateTime; LARGE_INTEGER UserTime; LARGE_INTEGER KernelTime; UNICODE_STRING ProcessName; KPRIORITY BasePriority; ULONG ProcessId; ULONG InheritedFromProcessId; ULONG HandleCount; ULONG Reserved2[2]; VM_COUNTERS VmCounters; IO_COUNTERS IoCounters; SYSTEM_THREAD Threads[1]; } SYSTEM_PROCESS_INFORMATION, * PSYSTEM_PROCESS_INFORMATION; // NtQuerySystemInformation Function Pointer Type typedef NTSTATUS(NTAPI* NTQUERYSYSTEMINFORMATION)( SYSTEM_INFORMATION_CLASS SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength ); void printStack(char buf[]) { BOOL result; char* sp; sp = buf + strnlen_s(buf, MSG_SIZE); HMODULE hModule; HANDLE Process; HANDLE Thread; STACKFRAME64 stack; ULONG frame; DWORD64 displacement; char buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)]; PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)buffer; CONTEXT ctx; char module[MaxNameLen]; RtlCaptureContext(&ctx); memset(&stack, 0, sizeof(STACKFRAME64)); displacement = 0; #if !defined(_M_AMD64) stack.AddrPC.Offset = ctx.Eip; stack.AddrPC.Mode = AddrModeFlat; stack.AddrStack.Offset = ctx.Esp; stack.AddrStack.Mode = AddrModeFlat; stack.AddrFrame.Offset = ctx.Ebp; stack.AddrFrame.Mode = AddrModeFlat; #endif Process = GetCurrentProcess(); Thread = GetCurrentThread(); SymInitialize(Process, NULL, TRUE); //load symbols DWORD offset = 0; for (frame = 0; ; frame++) { //get next call from stack result = StackWalk64 ( #if defined(_M_AMD64) IMAGE_FILE_MACHINE_AMD64 #else IMAGE_FILE_MACHINE_I386 #endif , Process, Thread, &stack, &ctx, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL ); if (!result) break; //get symbol name for address pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO); pSymbol->MaxNameLen = MAX_SYM_NAME; if (!SymFromAddr(Process, (ULONG64)stack.AddrPC.Offset, &displacement, pSymbol)) { sp += sprintf_s(sp, MSG_SIZE - strnlen_s(buf, MSG_SIZE), "%x\n", stack.AddrStack.Offset); continue; } if (frame == 0) { offset = stack.AddrFrame.Offset; continue; } //try to get line hModule = NULL; lstrcpyA(module, ""); GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCTSTR)(stack.AddrPC.Offset), &hModule); //at least print module name if (hModule != NULL) { HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, GetCurrentProcessId()); if (hProc != NULL) { if (GetModuleBaseNameA(hProc, hModule, module, MaxNameLen) != 0) { sp += sprintf_s(sp, MSG_SIZE - strnlen_s(buf, MSG_SIZE), "\n\t %s!%s +0x%x", module, pSymbol->Name, stack.AddrFrame.Offset - offset); CloseHandle(hProc); } } } } sprintf_s(sp, MSG_SIZE - strnlen_s(buf, MSG_SIZE), "*"); SymCleanup(Process); CloseHandle(Thread); CloseHandle(Process); } // RtlCreateUserThread Function Pointer Type typedef NTSTATUS(NTAPI* pfnRtlCreateUserThread)( IN HANDLE ProcessHandle, IN PSECURITY_DESCRIPTOR SecurityDescriptor OPTIONAL, IN BOOLEAN CreateSuspended, IN ULONG StackZeroBits OPTIONAL, IN SIZE_T StackReserve OPTIONAL, IN SIZE_T StackCommit OPTIONAL, IN PTHREAD_START_ROUTINE StartAddress, IN PVOID Parameter OPTIONAL, OUT PHANDLE ThreadHandle OPTIONAL, OUT PCLIENT_ID ClientId OPTIONAL);
25.573134
138
0.755924
e40c0f43777a10af8f5ca238fbf8d7788d8ecb84
1,265
h
C
104UI/include/rig.h
Coderik/104P
37435ff3709fbce9fcc87b59acc46212f484daad
[ "BSD-2-Clause" ]
null
null
null
104UI/include/rig.h
Coderik/104P
37435ff3709fbce9fcc87b59acc46212f484daad
[ "BSD-2-Clause" ]
null
null
null
104UI/include/rig.h
Coderik/104P
37435ff3709fbce9fcc87b59acc46212f484daad
[ "BSD-2-Clause" ]
null
null
null
/** * Copyright (C) 2016, Vadim Fedorov <coderiks@gmail.com> * * This program is free software: you can use, modify and/or * redistribute it under the terms of the simplified BSD * License. You should have received a copy of this license along * this program. If not, see * <http://www.opensource.org/licenses/bsd-license.html>. */ /// Created on: Apr 10, 2013 #ifndef RIG_H_ #define RIG_H_ #include <gdk/gdk.h> #include "i_hull.h" #include "i_rig.h" #include "mouse_event.h" /* * The base class for every specific Rig, which defines interface that the Hull uses * to interact with a Rig. Methods of that interface should be treated like slots. * There ia a default dummy implementation, therefore one can override in derived class * only those methods, which are useful for a specific Rig and just ignore the others. */ class Rig : public IRig { public: virtual ~Rig() {}; /** * NOTE: No requests to the Hull should be done during the initialization. */ virtual void initialize(IHull *hull) = 0; virtual void activate() {}; virtual void deactivate() {}; virtual void sequence_changed() {}; virtual void current_time_changed() {}; virtual void key_pressed(GdkEventKey* event) {}; protected: IHull *_hull; }; #endif /* RIG_H_ */
24.803922
87
0.714625
6fce23209fba6a6cb0017b57b824fbdbdc76375d
3,010
h
C
sample/06.CubeWorld/terrain_item.h
Lauvak/ray
906d3991ddd232a7f78f0e51f29aeead008a139a
[ "BSD-3-Clause" ]
113
2015-06-25T06:24:59.000Z
2021-09-26T02:46:02.000Z
sample/06.CubeWorld/terrain_item.h
Lauvak/ray
906d3991ddd232a7f78f0e51f29aeead008a139a
[ "BSD-3-Clause" ]
2
2015-05-03T07:22:49.000Z
2017-12-11T09:17:20.000Z
sample/06.CubeWorld/terrain_item.h
Lauvak/ray
906d3991ddd232a7f78f0e51f29aeead008a139a
[ "BSD-3-Clause" ]
17
2015-11-10T15:07:15.000Z
2021-01-19T15:28:16.000Z
// +---------------------------------------------------------------------- // | Project : ray. // | All rights reserved. // +---------------------------------------------------------------------- // | Copyright (c) 2013-2015. // +---------------------------------------------------------------------- // | * Redistribution and use of this software 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 ray team, nor the names of its // | contributors may be used to endorse or promote products // | derived from this software without specific prior // | written permission of the ray team. // | // | 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 _H_TERRAIN_ITEM_H_ #define _H_TERRAIN_ITEM_H_ #include "terrain_types.h" class TerrainItem { public: void setInstance(InstanceID id) noexcept; InstanceID getInstance() const noexcept; private: InstanceID _instanceID; }; struct VisiableFaces { InstanceID left; InstanceID right; InstanceID bottom; InstanceID top; InstanceID back; InstanceID front; }; class TerrainObject { public: virtual bool create(TerrainChunk& chunk) noexcept = 0; virtual bool createObject(TerrainChunk& chunk) noexcept = 0; virtual bool setActive(bool active) noexcept = 0; virtual bool update(TerrainChunk& chunk) noexcept = 0; virtual TerrainObjectPtr clone() noexcept = 0; void addItem(TerrainItemPtr item) noexcept; TerrainItems& getItems() noexcept; bool visiable(const TerrainChunk& chunk, const TerrainData& entry, VisiableFaces& faces) noexcept; void makeCube(ray::MeshPropertyPtr data, const VisiableFaces& faces, float x, float y, float z, float n) noexcept; private: TerrainItems items; }; #endif
35
115
0.671761
8d5f353aaaa765406db1e57aad4ee858bddb026f
20,749
h
C
examples/md-flexible/src/parsing/MDFlexConfig.h
neftlon/AutoPas
62866238968a5db9e7bd1f884b7571d5d5ad2370
[ "BSD-2-Clause" ]
null
null
null
examples/md-flexible/src/parsing/MDFlexConfig.h
neftlon/AutoPas
62866238968a5db9e7bd1f884b7571d5d5ad2370
[ "BSD-2-Clause" ]
null
null
null
examples/md-flexible/src/parsing/MDFlexConfig.h
neftlon/AutoPas
62866238968a5db9e7bd1f884b7571d5d5ad2370
[ "BSD-2-Clause" ]
null
null
null
/** * @file MDFlexConfig.h * @author F. Gratl * @date 18.10.2019 */ #pragma once #include <getopt.h> #include <map> #include <set> #include <utility> #include "autopas/options/AcquisitionFunctionOption.h" #include "autopas/options/ContainerOption.h" #include "autopas/options/DataLayoutOption.h" #include "autopas/options/ExtrapolationMethodOption.h" #include "autopas/options/LoadEstimatorOption.h" #include "autopas/options/MPIStrategyOption.h" #include "autopas/options/Newton3Option.h" #include "autopas/options/SelectorStrategyOption.h" #include "autopas/options/TraversalOption.h" #include "autopas/options/TuningStrategyOption.h" #include "autopas/utils/NumberSet.h" #include "src/Objects/CubeClosestPacked.h" #include "src/Objects/CubeGauss.h" #include "src/Objects/CubeGrid.h" #include "src/Objects/CubeUniform.h" #include "src/Objects/Sphere.h" /** * Class containing all necessary parameters for configuring a md-flexible simulation. */ class MDFlexConfig { public: MDFlexConfig() = default; /** * Struct to bundle information for options. * @tparam T Datatype of the option * @tparam getOptChar int for the switch case that is used during cli argument parsing with getOpt. * @note ints should be unique so they can be used for a switch case. * @note getOptChar should never be -1 because getopt uses this value to indicate that there are no more cli arguments * @note use __LINE__ as a cheap generator for unique ints. * @todo c++20: With support for non-type template parameters replace the template getOptChar with the name string * Then the getOptChar can be generated from that (e.g. with a hash) at compile time. Discussed here: * https://github.com/AutoPas/AutoPas/pull/469#discussion_r431270944 */ template <class T, int getOptChar> struct MDFlexOption { /** * Value of this option. */ T value; /** * Indicate whether this option is a flag or takes arguments. */ bool requiresArgument; /** * String representation of the option name. */ std::string name; /** * String describing this option. This is displayed when md-flexible is invoked with --help. */ std::string description; /** * Member to access the template parameter. */ constexpr static int getoptChar{getOptChar}; /** * Constructor * @param value Default value for this option. * @param newName String representation of the option name. * @param requiresArgument Indicate whether this option is a flag or takes arguments. * @param newDescription String describing this option. This is displayed when md-flexible is invoked with --help. */ MDFlexOption(T value, std::string newName, bool requiresArgument, std::string newDescription) : requiresArgument(requiresArgument), name(std::move(newName)), description(std::move(newDescription)), value(std::move(value)) {} /** * Returns a getopt option struct for this object. * @return */ [[nodiscard]] auto toGetoptOption() const { struct option retStruct { name.c_str(), requiresArgument, nullptr, getOptChar }; return retStruct; } }; /** * Convert the content of the config to a string representation. * @return */ [[nodiscard]] std::string to_string() const; /** * Checks parsed Objects and determines the necessary size of the simulation box. */ void calcSimulationBox(); /** * Adds parameters to all relevant particle property attributes and checks if the type already exists. * @param typeId * @param epsilon * @param sigma * @param mass */ void addParticleType(unsigned long typeId, double epsilon, double sigma, double mass); /** * Choice of the functor */ enum class FunctorOption { lj12_6, lj12_6_AVX, lj12_6_Globals }; /** * Choice of the particle generators specified in the command line */ enum class GeneratorOption { grid, uniform, gaussian, sphere, closestPacked }; // All options in the config // Make sure that the description is parsable by `CLIParser::createZSHCompletionFile()`! /** * yamlFilename */ MDFlexOption<std::string, __LINE__> yamlFilename{"", "yaml-filename", true, "Path to a .yaml input file."}; // AutoPas options: /** * containerOptions */ MDFlexOption<std::set<autopas::ContainerOption>, __LINE__> containerOptions{ autopas::ContainerOption::getMostOptions(), "container", true, "List of container options to use. Possible Values: " + autopas::utils::ArrayUtils::to_string(autopas::ContainerOption::getAllOptions(), " ", {"(", ")"})}; /** * dataLayoutOptions */ MDFlexOption<std::set<autopas::DataLayoutOption>, __LINE__> dataLayoutOptions{ autopas::DataLayoutOption::getMostOptions(), "data-layout", true, "List of data layout options to use. Possible Values: " + autopas::utils::ArrayUtils::to_string(autopas::DataLayoutOption::getAllOptions(), " ", {"(", ")"})}; /** * selectorStrategy */ MDFlexOption<autopas::SelectorStrategyOption, __LINE__> selectorStrategy{ autopas::SelectorStrategyOption::fastestAbs, "selector-strategy", true, "Strategy how to reduce the sample measurements to a single value. Possible Values: " + autopas::utils::ArrayUtils::to_string(autopas::SelectorStrategyOption::getAllOptions(), " ", {"(", ")"})}; /** * traversalOptions */ MDFlexOption<std::set<autopas::TraversalOption>, __LINE__> traversalOptions{ autopas::TraversalOption::getMostOptions(), "traversal", true, "List of traversal options to use. Possible Values: " + autopas::utils::ArrayUtils::to_string(autopas::TraversalOption::getAllOptions(), " ", {"(", ")"})}; /** * traversalOptions */ MDFlexOption<std::set<autopas::LoadEstimatorOption>, __LINE__> loadEstimatorOptions{ autopas::LoadEstimatorOption::getMostOptions(), "load-estimator", true, "List of load estimator function choices for traversals that do heuristic load balancing. Possible Values: " + autopas::utils::ArrayUtils::to_string(autopas::LoadEstimatorOption::getAllOptions(), " ", {"(", ")"})}; /** * newton3Options */ MDFlexOption<std::set<autopas::Newton3Option>, __LINE__> newton3Options{ autopas::Newton3Option::getMostOptions(), "newton3", true, "List of newton3 options to use. Possible Values: " + autopas::utils::ArrayUtils::to_string(autopas::Newton3Option::getAllOptions(), " ", {"(", ")"})}; /** * cellSizeFactors */ MDFlexOption<std::shared_ptr<autopas::NumberSet<double>>, __LINE__> cellSizeFactors{ std::make_shared<autopas::NumberSetFinite<double>>(std::set<double>{1.}), "cell-size", true, "Factor for the interaction length to determine the cell size."}; /** * logFileName */ MDFlexOption<std::string, __LINE__> logFileName{"", "log-file", true, "Path to an .out file to store the log output."}; /** * logLevel */ MDFlexOption<autopas::Logger::LogLevel, __LINE__> logLevel{ autopas::Logger::LogLevel::info, "log-level", true, "Log level for AutoPas. Set to debug for tuning information. " "Possible Values: (trace debug info warn error critical off)"}; /** * tuningStrategyOption */ MDFlexOption<autopas::TuningStrategyOption, __LINE__> tuningStrategyOption{ autopas::TuningStrategyOption::fullSearch, "tuning-strategy", true, "Strategy how to reduce the sample measurements to a single value. Possible Values: " + autopas::utils::ArrayUtils::to_string(autopas::TuningStrategyOption::getAllOptions(), " ", {"(", ")"})}; /** * mpiStrategyOption */ MDFlexOption<autopas::MPIStrategyOption, __LINE__> mpiStrategyOption{ autopas::MPIStrategyOption::noMPI, "mpi-strategy", true, "Whether to tune using with MPI or not. Possible Values: " + autopas::utils::ArrayUtils::to_string(autopas::MPIStrategyOption::getAllOptions(), " ", {"(", ")"})}; /** * tuningInterval */ MDFlexOption<unsigned int, __LINE__> tuningInterval{5000, "tuning-interval", true, "Number of iterations between two tuning phases."}; /** * tuningSamples */ MDFlexOption<unsigned int, __LINE__> tuningSamples{3, "tuning-samples", true, "Number of samples to collect per configuration."}; /** * tuningMaxEvidence */ MDFlexOption<unsigned int, __LINE__> tuningMaxEvidence{ 10, "tuning-max-evidence", true, "For Bayesian based tuning strategies: Maximum number of evidences " "tuning strategies that have no finishing indicator take."}; /** * relativeOptimumRange */ MDFlexOption<double, __LINE__> relativeOptimumRange{ 1.2, "relative-optimum-range", true, "For predictive based tuning strategies: Configurations whose predicted performance lies within this range of " "the predicted optimal performance will be tested."}; /** * maxTuningPhasesWithoutTest */ MDFlexOption<unsigned int, __LINE__> maxTuningPhasesWithoutTest{ 5, "max-tuning-phases-without-test", true, "For predictive based tuning strategies: Maximal number of " "tuning phases a configurations can be excluded from testing."}; /** * relativeBlacklistRange */ MDFlexOption<double, __LINE__> relativeBlacklistRange{ 0, "relative-blacklist-range", true, "For predictive based tuning strategies: When the first evidence of a configuration is further away from the " "optimum than this relative range, the configuration is ignored for the rest of the simulation. Set to zero to " "disable blacklisting."}; /** * evidenceFirstPrediction */ MDFlexOption<unsigned int, __LINE__> evidenceFirstPrediction{ 3, "evidence-for-prediction", true, "For predictive based tuning strategies: The number of evidence for a configuration that needs to be gathered " "before the first prediction is made. This number also determines how much evidence is used for the calculation " "of the prediction and for a polynomial extrapolation method, this is also the degree of the polynomial."}; /** * extrapolationMethodOption */ MDFlexOption<autopas::ExtrapolationMethodOption, __LINE__> extrapolationMethodOption{ autopas::ExtrapolationMethodOption::linearRegression, "extrapolation-method", true, "For predictive based tuning strategies: The extrapolation method that calculates the prediction. Possible " "Values: " + autopas::utils::ArrayUtils::to_string(autopas::ExtrapolationMethodOption::getAllOptions(), " ", {"(", ")"})}; /** * vtkFileName */ MDFlexOption<std::string, __LINE__> vtkFileName{"", "vtk-filename", true, "Basename for all VTK output files."}; /** * vtkWriteFrequency */ MDFlexOption<size_t, __LINE__> vtkWriteFrequency{100, "vtk-write-frequency", true, "Number of iterations after which a VTK file is written."}; /** * verletClusterSize */ MDFlexOption<unsigned int, __LINE__> verletClusterSize{4, "verlet-cluster-size", true, "Number of particles in Verlet clusters."}; /** * verletRebuildFrequency */ MDFlexOption<unsigned int, __LINE__> verletRebuildFrequency{ 20, "verlet-rebuild-frequency", true, "Number of iterations after which containers are rebuilt."}; /** * verletSkinRadius */ MDFlexOption<double, __LINE__> verletSkinRadius{.2, "verlet-skin-radius", true, "Skin added to the cutoff to form the interaction length."}; /** * boxMin */ MDFlexOption<std::array<double, 3>, 0> boxMin{ {0, 0, 0}, "box-min", true, "Lower front left corner of the simulation box."}; /** * boxMax */ MDFlexOption<std::array<double, 3>, 0> boxMax{ {1, 1, 1}, "box-max", true, "Upper back right corner of the simulation box."}; /** * acquisitionFunctionOption */ MDFlexOption<autopas::AcquisitionFunctionOption, __LINE__> acquisitionFunctionOption{ autopas::AcquisitionFunctionOption::upperConfidenceBound, "tuning-acquisition-function", true, "For Bayesian based tuning strategies: Function to determine the predicted knowledge gain when testing a given " "configuration. Possible Values: " + autopas::utils::ArrayUtils::to_string(autopas::AcquisitionFunctionOption::getAllOptions(), " ", {"(", ")"})}; // Simulation Options: /** * cutoff */ MDFlexOption<double, __LINE__> cutoff{2., "cutoff", true, "Lennard-Jones force cutoff."}; /** * functorOption */ MDFlexOption<FunctorOption, __LINE__> functorOption{ FunctorOption::lj12_6, "functor", true, "Force functor to use. Possible Values: (lennard-jones lennard-jones-AVX2 lennard-jones-globals)"}; /** * iterations */ MDFlexOption<size_t, __LINE__> iterations{10, "iterations", true, "Number of iterations to simulate."}; /** * tuningPhases */ MDFlexOption<size_t, __LINE__> tuningPhases{ 0, "tuning-phases", true, "Number of tuning phases to simulate. This option overwrites --iterations."}; /** * Periodic boundaries. * This starts with a "not" such that it can be used as a flag with a sane default. */ MDFlexOption<bool, __LINE__> periodic{ true, "periodic-boundaries", true, "(De)Activate periodic boundaries. Possible Values: (true false) Default: true."}; /** * dontMeasureFlops */ MDFlexOption<bool, __LINE__> dontMeasureFlops{true, "no-flops", false, "Set to omit the calculation of flops."}; /** * Omit the creation of a config file at the end of the Simulation. * This starts with a "not" such that it can be used as a flag with a sane default. */ MDFlexOption<bool, __LINE__> dontCreateEndConfig{ true, "no-end-config", false, "Set to omit the creation of a yaml file at the end of a simulation."}; /** * deltaT */ MDFlexOption<double, __LINE__> deltaT{0.001, "deltaT", true, "Length of a timestep. Set to 0 to deactivate time integration."}; /** * epsilonMap */ MDFlexOption<std::map<unsigned long, double>, 0> epsilonMap{ {{0ul, 1.}}, "particle-epsilon", true, "Mapping from particle type to an epsilon value."}; /** * sigmaMap */ MDFlexOption<std::map<unsigned long, double>, 0> sigmaMap{ {{0ul, 1.}}, "particle-sigma", true, "Mapping from particle type to a sigma value."}; /** * massMap */ MDFlexOption<std::map<unsigned long, double>, 0> massMap{ {{0ul, 1.}}, "particle-mass", true, "Mapping from particle type to a mass value."}; // Options for additional Object Generation on command line /** * boxLength */ MDFlexOption<double, __LINE__> boxLength{10, "box-length", true, "Length of the simulation box as a cuboid."}; /** * distributionMean */ MDFlexOption<std::array<double, 3>, __LINE__> distributionMean{ {5., 5., 5.}, "distribution-mean", true, "Mean of the gaussian distribution for random particle initialization."}; /** * distributionStdDev */ MDFlexOption<std::array<double, 3>, __LINE__> distributionStdDev{ {2., 2., 2.}, "distribution-stddeviation", true, "Standard deviation of the gaussian distribution for random particle initialization."}; /** * particlesPerDim */ MDFlexOption<size_t, __LINE__> particlesPerDim{10, "particles-per-dimension", true, "Size of the scenario for the grid generator."}; /** * particlesTotal */ MDFlexOption<size_t, __LINE__> particlesTotal{ 1000, "particles-total", true, "Total number of particles for the random distribution based generators."}; /** * particleSpacing * For a stable grid initialize this as 2^(1/6) sigma */ MDFlexOption<double, __LINE__> particleSpacing{1.1225 * 1, "particle-spacing", true, "Space between two particles for the grid generator."}; /** * generatorOption */ MDFlexOption<GeneratorOption, __LINE__> generatorOption{ GeneratorOption::grid, "particle-generator", true, "Scenario generator. Possible Values: (grid uniform gaussian sphere closestPacking) Default: grid"}; // Object Generation: /** * objectsStr */ static inline const char *objectsStr{"Objects"}; /** * bottomLeftBackCornerStr */ static inline const char *bottomLeftBackCornerStr{"bottomLeftCorner"}; /** * velocityStr */ static inline const char *const velocityStr{"velocity"}; /** * particleTypeStr */ static inline const char *const particleTypeStr{"particle-type"}; /** * particlesPerObjectStr */ static inline const char *const particlesPerObjectStr{"numberOfParticles"}; /** * cubeGridObjectsStr */ static inline const char *const cubeGridObjectsStr{"CubeGrid"}; /** * cubeGridObjects */ std::vector<CubeGrid> cubeGridObjects{}; /** * cubeGaussObjectsStr */ static inline const char *const cubeGaussObjectsStr{"CubeGauss"}; /** * cubeGaussObjects */ std::vector<CubeGauss> cubeGaussObjects{}; /** * cubeUniformObjectsStr */ static inline const char *const cubeUniformObjectsStr{"CubeUniform"}; /** * cubeUniformObjects */ std::vector<CubeUniform> cubeUniformObjects{}; /** * sphereObjectsStr */ static inline const char *const sphereObjectsStr{"Sphere"}; /** * sphereCenterStr */ static inline const char *const sphereCenterStr{"center"}; /** * sphereRadiusStr */ static inline const char *const sphereRadiusStr{"radius"}; /** * sphereObjects */ std::vector<Sphere> sphereObjects{}; /** * cubeClosestPackedObjects */ std::vector<CubeClosestPacked> cubeClosestPackedObjects{}; /** * cubeClosestPackedObjectsStr */ static inline const char *const cubeClosestPackedObjectsStr{"CubeClosestPacked"}; // Thermostat Options /** * useThermostat */ MDFlexOption<bool, __LINE__> useThermostat{ false, "thermostat", true, "(De)Activate the thermostat. Only useful when used to overwrite a yaml file. " "Possible Values: (true false) Default: false"}; /** * initTemperature */ MDFlexOption<double, __LINE__> initTemperature{0., "initialTemperature", true, "Thermostat option. Initial temperature of the system."}; /** * targetTemperature */ MDFlexOption<double, __LINE__> targetTemperature{0., "targetTemperature", true, "Thermostat option. Target temperature of the system."}; /** * deltaTemp */ MDFlexOption<double, __LINE__> deltaTemp{ 0., "deltaTemperature", true, "Thermostat option. Maximal temperature jump the thermostat is allowed to apply."}; /** * thermostatInterval */ MDFlexOption<size_t, __LINE__> thermostatInterval{ 0, "thermostatInterval", true, "Thermostat option. Number of Iterations between two applications of the thermostat."}; /** * addBrownianMotion */ MDFlexOption<bool, __LINE__> addBrownianMotion{ true, "addBrownianMotion", true, "Thermostat option. Whether the particle velocities should be initialized using " "Brownian motion. Possible Values: (true false) Default: true"}; /** * Global external force like e.g. gravity */ MDFlexOption<std::array<double, 3>, __LINE__> globalForce{ {0, 0, 0}, "globalForce", true, "Global force applied on every particle. Useful to model e.g. gravity. Default: {0,0,0}"}; /** * Convenience function testing if the global force contains only 0 entries. * @return false if any entry in globalForce.value is != 0. */ [[nodiscard]] bool globalForceIsZero() const { bool isZero = true; for (auto gf : globalForce.value) { isZero &= gf == 0; } return isZero; } // Checkpoint Options /** * checkpointfile */ MDFlexOption<std::string, __LINE__> checkpointfile{"", "checkpoint", true, "Path to a .vtk File to load as a checkpoint."}; /** * valueOffset used for cli-output alignment */ static constexpr size_t valueOffset{33}; }; /** * Stream insertion operator for MDFlexConfig. * @param os * @param config * @return */ inline std::ostream &operator<<(std::ostream &os, const MDFlexConfig &config) { return os << config.to_string(); }
37.051786
120
0.668321
a5c8139027f4efe1dc568827567804ec69ff272e
634
h
C
bbckit/Foundation/NSTimer/NSTimer+BBCBlock.h
lerosua/bbckit
ac53e60c0a78f8f2b64ec6ab57c792cc132524b4
[ "MIT" ]
1
2018-04-10T09:00:52.000Z
2018-04-10T09:00:52.000Z
bbckit/Foundation/NSTimer/NSTimer+BBCBlock.h
lerosua/bbckit
ac53e60c0a78f8f2b64ec6ab57c792cc132524b4
[ "MIT" ]
null
null
null
bbckit/Foundation/NSTimer/NSTimer+BBCBlock.h
lerosua/bbckit
ac53e60c0a78f8f2b64ec6ab57c792cc132524b4
[ "MIT" ]
1
2018-04-10T09:00:57.000Z
2018-04-10T09:00:57.000Z
// // NSTimer+BBCBlock.h // BBCKit // // Created by lerosua on 16/8/28. // Copyright © 2016年 duowan. All rights reserved. // #import <Foundation/Foundation.h> @interface NSTimer (BBCBlock) /** * NSTimer计划任务,使用Block的方式,block里的self要用weak,解决循环引用问题,并且这个一般在主线程执行,不需要手工加runloop里 * * @param interval 时间间隔 * @param block 要执行的block, 里面引用到的self应该是weak的 * @param repeats 是否重复 * * @return 返回生成的Timer */ + (instancetype) bbc_scheduledTimerWithTimeInterval:(NSTimeInterval)interval block:(void(^)())block repeats:(BOOL)repeats; @end
23.481481
81
0.621451
c4df3c3668b37db4bd3412a3a9b2fa260b27e2d9
14,887
h
C
include/uapi/drm/tegra_drm.h
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
31
2021-04-27T08:50:40.000Z
2022-03-01T02:26:21.000Z
include/uapi/drm/tegra_drm.h
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
13
2021-07-10T04:36:17.000Z
2022-03-03T10:50:05.000Z
include/uapi/drm/tegra_drm.h
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
12
2021-04-06T02:23:10.000Z
2022-02-28T11:43:19.000Z
/* * Copyright (c) 2012-2013, NVIDIA CORPORATION. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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. */ #ifndef _UAPI_TEGRA_DRM_H_ #define _UAPI_TEGRA_DRM_H_ #include "drm.h" #if defined(__cplusplus) extern "C" { #endif #define DRM_TEGRA_GEM_CREATE_TILED (1 << 0) #define DRM_TEGRA_GEM_CREATE_BOTTOM_UP (1 << 1) /** * struct drm_tegra_gem_create - parameters for the GEM object creation IOCTL */ struct drm_tegra_gem_create { /** * @size: * * The size, in bytes, of the buffer object to be created. */ __u64 size; /** * @flags: * * A bitmask of flags that influence the creation of GEM objects: * * DRM_TEGRA_GEM_CREATE_TILED * Use the 16x16 tiling format for this buffer. * * DRM_TEGRA_GEM_CREATE_BOTTOM_UP * The buffer has a bottom-up layout. */ __u32 flags; /** * @handle: * * The handle of the created GEM object. Set by the kernel upon * successful completion of the IOCTL. */ __u32 handle; }; /** * struct drm_tegra_gem_mmap - parameters for the GEM mmap IOCTL */ struct drm_tegra_gem_mmap { /** * @handle: * * Handle of the GEM object to obtain an mmap offset for. */ __u32 handle; /** * @pad: * * Structure padding that may be used in the future. Must be 0. */ __u32 pad; /** * @offset: * * The mmap offset for the given GEM object. Set by the kernel upon * successful completion of the IOCTL. */ __u64 offset; }; /** * struct drm_tegra_syncpt_read - parameters for the read syncpoint IOCTL */ struct drm_tegra_syncpt_read { /** * @id: * * ID of the syncpoint to read the current value from. */ __u32 id; /** * @value: * * The current syncpoint value. Set by the kernel upon successful * completion of the IOCTL. */ __u32 value; }; /** * struct drm_tegra_syncpt_incr - parameters for the increment syncpoint IOCTL */ struct drm_tegra_syncpt_incr { /** * @id: * * ID of the syncpoint to increment. */ __u32 id; /** * @pad: * * Structure padding that may be used in the future. Must be 0. */ __u32 pad; }; /** * struct drm_tegra_syncpt_wait - parameters for the wait syncpoint IOCTL */ struct drm_tegra_syncpt_wait { /** * @id: * * ID of the syncpoint to wait on. */ __u32 id; /** * @thresh: * * Threshold value for which to wait. */ __u32 thresh; /** * @timeout: * * Timeout, in milliseconds, to wait. */ __u32 timeout; /** * @value: * * The new syncpoint value after the wait. Set by the kernel upon * successful completion of the IOCTL. */ __u32 value; }; #define DRM_TEGRA_NO_TIMEOUT (0xffffffff) /** * struct drm_tegra_open_channel - parameters for the open channel IOCTL */ struct drm_tegra_open_channel { /** * @client: * * The client ID for this channel. */ __u32 client; /** * @pad: * * Structure padding that may be used in the future. Must be 0. */ __u32 pad; /** * @context: * * The application context of this channel. Set by the kernel upon * successful completion of the IOCTL. This context needs to be passed * to the DRM_TEGRA_CHANNEL_CLOSE or the DRM_TEGRA_SUBMIT IOCTLs. */ __u64 context; }; /** * struct drm_tegra_close_channel - parameters for the close channel IOCTL */ struct drm_tegra_close_channel { /** * @context: * * The application context of this channel. This is obtained from the * DRM_TEGRA_OPEN_CHANNEL IOCTL. */ __u64 context; }; /** * struct drm_tegra_get_syncpt - parameters for the get syncpoint IOCTL */ struct drm_tegra_get_syncpt { /** * @context: * * The application context identifying the channel for which to obtain * the syncpoint ID. */ __u64 context; /** * @index: * * Index of the client syncpoint for which to obtain the ID. */ __u32 index; /** * @id: * * The ID of the given syncpoint. Set by the kernel upon successful * completion of the IOCTL. */ __u32 id; }; /** * struct drm_tegra_get_syncpt_base - parameters for the get wait base IOCTL */ struct drm_tegra_get_syncpt_base { /** * @context: * * The application context identifying for which channel to obtain the * wait base. */ __u64 context; /** * @syncpt: * * ID of the syncpoint for which to obtain the wait base. */ __u32 syncpt; /** * @id: * * The ID of the wait base corresponding to the client syncpoint. Set * by the kernel upon successful completion of the IOCTL. */ __u32 id; }; /** * struct drm_tegra_syncpt - syncpoint increment operation */ struct drm_tegra_syncpt { /** * @id: * * ID of the syncpoint to operate on. */ __u32 id; /** * @incrs: * * Number of increments to perform for the syncpoint. */ __u32 incrs; }; /** * struct drm_tegra_cmdbuf - structure describing a command buffer */ struct drm_tegra_cmdbuf { /** * @handle: * * Handle to a GEM object containing the command buffer. */ __u32 handle; /** * @offset: * * Offset, in bytes, into the GEM object identified by @handle at * which the command buffer starts. */ __u32 offset; /** * @words: * * Number of 32-bit words in this command buffer. */ __u32 words; /** * @pad: * * Structure padding that may be used in the future. Must be 0. */ __u32 pad; }; /** * struct drm_tegra_reloc - GEM object relocation structure */ struct drm_tegra_reloc { struct { /** * @cmdbuf.handle: * * Handle to the GEM object containing the command buffer for * which to perform this GEM object relocation. */ __u32 handle; /** * @cmdbuf.offset: * * Offset, in bytes, into the command buffer at which to * insert the relocated address. */ __u32 offset; } cmdbuf; struct { /** * @target.handle: * * Handle to the GEM object to be relocated. */ __u32 handle; /** * @target.offset: * * Offset, in bytes, into the target GEM object at which the * relocated data starts. */ __u32 offset; } target; /** * @shift: * * The number of bits by which to shift relocated addresses. */ __u32 shift; /** * @pad: * * Structure padding that may be used in the future. Must be 0. */ __u32 pad; }; /** * struct drm_tegra_waitchk - wait check structure */ struct drm_tegra_waitchk { /** * @handle: * * Handle to the GEM object containing a command stream on which to * perform the wait check. */ __u32 handle; /** * @offset: * * Offset, in bytes, of the location in the command stream to perform * the wait check on. */ __u32 offset; /** * @syncpt: * * ID of the syncpoint to wait check. */ __u32 syncpt; /** * @thresh: * * Threshold value for which to check. */ __u32 thresh; }; /** * struct drm_tegra_submit - job submission structure */ struct drm_tegra_submit { /** * @context: * * The application context identifying the channel to use for the * execution of this job. */ __u64 context; /** * @num_syncpts: * * The number of syncpoints operated on by this job. This defines the * length of the array pointed to by @syncpts. */ __u32 num_syncpts; /** * @num_cmdbufs: * * The number of command buffers to execute as part of this job. This * defines the length of the array pointed to by @cmdbufs. */ __u32 num_cmdbufs; /** * @num_relocs: * * The number of relocations to perform before executing this job. * This defines the length of the array pointed to by @relocs. */ __u32 num_relocs; /** * @num_waitchks: * * The number of wait checks to perform as part of this job. This * defines the length of the array pointed to by @waitchks. */ __u32 num_waitchks; /** * @waitchk_mask: * * Bitmask of valid wait checks. */ __u32 waitchk_mask; /** * @timeout: * * Timeout, in milliseconds, before this job is cancelled. */ __u32 timeout; /** * @syncpts: * * A pointer to an array of &struct drm_tegra_syncpt structures that * specify the syncpoint operations performed as part of this job. * The number of elements in the array must be equal to the value * given by @num_syncpts. */ __u64 syncpts; /** * @cmdbufs: * * A pointer to an array of &struct drm_tegra_cmdbuf structures that * define the command buffers to execute as part of this job. The * number of elements in the array must be equal to the value given * by @num_syncpts. */ __u64 cmdbufs; /** * @relocs: * * A pointer to an array of &struct drm_tegra_reloc structures that * specify the relocations that need to be performed before executing * this job. The number of elements in the array must be equal to the * value given by @num_relocs. */ __u64 relocs; /** * @waitchks: * * A pointer to an array of &struct drm_tegra_waitchk structures that * specify the wait checks to be performed while executing this job. * The number of elements in the array must be equal to the value * given by @num_waitchks. */ __u64 waitchks; /** * @fence: * * The threshold of the syncpoint associated with this job after it * has been completed. Set by the kernel upon successful completion of * the IOCTL. This can be used with the DRM_TEGRA_SYNCPT_WAIT IOCTL to * wait for this job to be finished. */ __u32 fence; /** * @reserved: * * This field is reserved for future use. Must be 0. */ __u32 reserved[5]; }; #define DRM_TEGRA_GEM_TILING_MODE_PITCH 0 #define DRM_TEGRA_GEM_TILING_MODE_TILED 1 #define DRM_TEGRA_GEM_TILING_MODE_BLOCK 2 /** * struct drm_tegra_gem_set_tiling - parameters for the set tiling IOCTL */ struct drm_tegra_gem_set_tiling { /** * @handle: * * Handle to the GEM object for which to set the tiling parameters. */ __u32 handle; /** * @mode: * * The tiling mode to set. Must be one of: * * DRM_TEGRA_GEM_TILING_MODE_PITCH * pitch linear format * * DRM_TEGRA_GEM_TILING_MODE_TILED * 16x16 tiling format * * DRM_TEGRA_GEM_TILING_MODE_BLOCK * 16Bx2 tiling format */ __u32 mode; /** * @value: * * The value to set for the tiling mode parameter. */ __u32 value; /** * @pad: * * Structure padding that may be used in the future. Must be 0. */ __u32 pad; }; /** * struct drm_tegra_gem_get_tiling - parameters for the get tiling IOCTL */ struct drm_tegra_gem_get_tiling { /** * @handle: * * Handle to the GEM object for which to query the tiling parameters. */ __u32 handle; /** * @mode: * * The tiling mode currently associated with the GEM object. Set by * the kernel upon successful completion of the IOCTL. */ __u32 mode; /** * @value: * * The tiling mode parameter currently associated with the GEM object. * Set by the kernel upon successful completion of the IOCTL. */ __u32 value; /** * @pad: * * Structure padding that may be used in the future. Must be 0. */ __u32 pad; }; #define DRM_TEGRA_GEM_BOTTOM_UP (1 << 0) #define DRM_TEGRA_GEM_FLAGS (DRM_TEGRA_GEM_BOTTOM_UP) /** * struct drm_tegra_gem_set_flags - parameters for the set flags IOCTL */ struct drm_tegra_gem_set_flags { /** * @handle: * * Handle to the GEM object for which to set the flags. */ __u32 handle; /** * @flags: * * The flags to set for the GEM object. */ __u32 flags; }; /** * struct drm_tegra_gem_get_flags - parameters for the get flags IOCTL */ struct drm_tegra_gem_get_flags { /** * @handle: * * Handle to the GEM object for which to query the flags. */ __u32 handle; /** * @flags: * * The flags currently associated with the GEM object. Set by the * kernel upon successful completion of the IOCTL. */ __u32 flags; }; #define DRM_TEGRA_GEM_CREATE 0x00 #define DRM_TEGRA_GEM_MMAP 0x01 #define DRM_TEGRA_SYNCPT_READ 0x02 #define DRM_TEGRA_SYNCPT_INCR 0x03 #define DRM_TEGRA_SYNCPT_WAIT 0x04 #define DRM_TEGRA_OPEN_CHANNEL 0x05 #define DRM_TEGRA_CLOSE_CHANNEL 0x06 #define DRM_TEGRA_GET_SYNCPT 0x07 #define DRM_TEGRA_SUBMIT 0x08 #define DRM_TEGRA_GET_SYNCPT_BASE 0x09 #define DRM_TEGRA_GEM_SET_TILING 0x0a #define DRM_TEGRA_GEM_GET_TILING 0x0b #define DRM_TEGRA_GEM_SET_FLAGS 0x0c #define DRM_TEGRA_GEM_GET_FLAGS 0x0d #define DRM_IOCTL_TEGRA_GEM_CREATE DRM_IOWR(DRM_COMMAND_BASE + DRM_TEGRA_GEM_CREATE, struct drm_tegra_gem_create) #define DRM_IOCTL_TEGRA_GEM_MMAP DRM_IOWR(DRM_COMMAND_BASE + DRM_TEGRA_GEM_MMAP, struct drm_tegra_gem_mmap) #define DRM_IOCTL_TEGRA_SYNCPT_READ DRM_IOWR(DRM_COMMAND_BASE + DRM_TEGRA_SYNCPT_READ, struct drm_tegra_syncpt_read) #define DRM_IOCTL_TEGRA_SYNCPT_INCR DRM_IOWR(DRM_COMMAND_BASE + DRM_TEGRA_SYNCPT_INCR, struct drm_tegra_syncpt_incr) #define DRM_IOCTL_TEGRA_SYNCPT_WAIT DRM_IOWR(DRM_COMMAND_BASE + DRM_TEGRA_SYNCPT_WAIT, struct drm_tegra_syncpt_wait) #define DRM_IOCTL_TEGRA_OPEN_CHANNEL DRM_IOWR(DRM_COMMAND_BASE + DRM_TEGRA_OPEN_CHANNEL, struct drm_tegra_open_channel) #define DRM_IOCTL_TEGRA_CLOSE_CHANNEL DRM_IOWR(DRM_COMMAND_BASE + DRM_TEGRA_CLOSE_CHANNEL, struct drm_tegra_close_channel) #define DRM_IOCTL_TEGRA_GET_SYNCPT DRM_IOWR(DRM_COMMAND_BASE + DRM_TEGRA_GET_SYNCPT, struct drm_tegra_get_syncpt) #define DRM_IOCTL_TEGRA_SUBMIT DRM_IOWR(DRM_COMMAND_BASE + DRM_TEGRA_SUBMIT, struct drm_tegra_submit) #define DRM_IOCTL_TEGRA_GET_SYNCPT_BASE DRM_IOWR(DRM_COMMAND_BASE + DRM_TEGRA_GET_SYNCPT_BASE, struct drm_tegra_get_syncpt_base) #define DRM_IOCTL_TEGRA_GEM_SET_TILING DRM_IOWR(DRM_COMMAND_BASE + DRM_TEGRA_GEM_SET_TILING, struct drm_tegra_gem_set_tiling) #define DRM_IOCTL_TEGRA_GEM_GET_TILING DRM_IOWR(DRM_COMMAND_BASE + DRM_TEGRA_GEM_GET_TILING, struct drm_tegra_gem_get_tiling) #define DRM_IOCTL_TEGRA_GEM_SET_FLAGS DRM_IOWR(DRM_COMMAND_BASE + DRM_TEGRA_GEM_SET_FLAGS, struct drm_tegra_gem_set_flags) #define DRM_IOCTL_TEGRA_GEM_GET_FLAGS DRM_IOWR(DRM_COMMAND_BASE + DRM_TEGRA_GEM_GET_FLAGS, struct drm_tegra_gem_get_flags) #if defined(__cplusplus) } #endif #endif
21.828446
128
0.70135
4fd1db25f9ca1b359baf2f1e259dc0567957e9ce
8,963
h
C
libraries/disp/viewers/averageselectionview.h
Andrey1994/mne-cpp
6264b1107b9447b7db64309f73f09e848fd198c4
[ "BSD-3-Clause" ]
2
2021-11-16T19:38:12.000Z
2021-11-18T20:52:08.000Z
libraries/disp/viewers/averageselectionview.h
Andrey1994/mne-cpp
6264b1107b9447b7db64309f73f09e848fd198c4
[ "BSD-3-Clause" ]
null
null
null
libraries/disp/viewers/averageselectionview.h
Andrey1994/mne-cpp
6264b1107b9447b7db64309f73f09e848fd198c4
[ "BSD-3-Clause" ]
1
2021-11-16T19:39:01.000Z
2021-11-16T19:39:01.000Z
//============================================================================================================= /** * @file averageselectionview.h * @author Lorenz Esch <lesch@mgh.harvard.edu> * @version dev * @date July, 2018 * * @section LICENSE * * Copyright (C) 2018, Lorenz Esch. 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 MNE-CPP authors 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. * * * @brief Declaration of the AverageSelectionView Class. * */ #ifndef AVERAGESELECTIONVIEW_H #define AVERAGESELECTIONVIEW_H //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "../disp_global.h" //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QWidget> #include <QMap> //************************************************************************************************************* //============================================================================================================= // Eigen INCLUDES //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // FORWARD DECLARATIONS //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // DEFINE NAMESPACE DISPLIB //============================================================================================================= namespace DISPLIB { //************************************************************************************************************* //============================================================================================================= // DISPLIB FORWARD DECLARATIONS //============================================================================================================= //============================================================================================================= /** * DECLARE CLASS AverageSelectionView * * @brief The AverageSelectionView class provides a view to activate and choose colors for different averages */ class DISPSHARED_EXPORT AverageSelectionView : public QWidget { Q_OBJECT public: typedef QSharedPointer<AverageSelectionView> SPtr; /**< Shared pointer type for AverageSelectionView. */ typedef QSharedPointer<const AverageSelectionView> ConstSPtr; /**< Const shared pointer type for AverageSelectionView. */ //========================================================================================================= /** * Constructs a AverageSelectionView which is a child of parent. * * @param [in] parent parent of widget */ AverageSelectionView(const QString &sSettingsPath="", QWidget *parent = 0, Qt::WindowFlags f = Qt::Widget); //========================================================================================================= /** * Destroys the AverageSelectionView. */ ~AverageSelectionView(); //========================================================================================================= /** * Get the current average colors * * @return Pointer to the current average colors. */ QSharedPointer<QMap<QString, QColor> > getAverageColor() const; //========================================================================================================= /** * Get the current average activations * * @return Pointer to the current average activations. */ QSharedPointer<QMap<QString, bool> > getAverageActivation() const; //========================================================================================================= /** * Set the average colors * * @param [in] qMapAverageColor Pointer to the new average colors */ void setAverageColor(const QSharedPointer<QMap<QString, QColor> > qMapAverageColor); //========================================================================================================= /** * Set the average activations * * @param [in] qMapAverageActivation Pointer to the new average activations */ void setAverageActivation(const QSharedPointer<QMap<QString, bool> > qMapAverageActivation); protected: //========================================================================================================= /** * Saves all important settings of this view via QSettings. * * @param[in] settingsPath the path to store the settings to. */ void saveSettings(const QString& settingsPath); //========================================================================================================= /** * Loads and inits all important settings of this view via QSettings. * * @param[in] settingsPath the path to load the settings from. */ void loadSettings(const QString& settingsPath); //========================================================================================================= /** * Redraw the GUI. */ void redrawGUI(); //========================================================================================================= /** * Call this slot whenever the average selection or color changed. */ void onAverageSelectionColorChanged(); int m_iMaxNumAverages; QSharedPointer<QMap<QString, QColor> > m_qMapAverageColor; /**< Average colors. */ QSharedPointer<QMap<QString, bool> > m_qMapAverageActivation; /**< Average activation status. */ QString m_sSettingsPath; /**< The settings path to store the GUI settings to. */ signals: //========================================================================================================= /** * Emmited when new average color is available * * @param [in] qMapAverageColor the average color map */ void newAverageColorMap(const QSharedPointer<QMap<QString, QColor> > qMapAverageColor); //========================================================================================================= /** * Emmited when new average activation is available * * @param [in] qMapAverageActivation the average activation map */ void newAverageActivationMap(const QSharedPointer<QMap<QString, bool> > qMapAverageActivation); }; } // NAMESPACE #endif // AVERAGESELECTIONVIEW_H
44.371287
135
0.410131
a019edcc59d4e5d86928c6550aeece7fcef26568
3,925
h
C
src/imagine/math/basis.h
ads00/imagine
f8063f636306a18f7c98512548a3c2ef2fd8cc48
[ "MIT" ]
null
null
null
src/imagine/math/basis.h
ads00/imagine
f8063f636306a18f7c98512548a3c2ef2fd8cc48
[ "MIT" ]
null
null
null
src/imagine/math/basis.h
ads00/imagine
f8063f636306a18f7c98512548a3c2ef2fd8cc48
[ "MIT" ]
null
null
null
/* Imagine v0.1 [math] Copyright (c) 2015-present, Hugo (hrkz) Frezat */ #ifndef IG_MATH_BASIS_H #define IG_MATH_BASIS_H #include "imagine/ig.h" #include <cmath> #include <numeric> #include <sstream> namespace ig { // Mathematical constants template <typename Arithmetic> constexpr Arithmetic pi = Arithmetic(3.141592653589793); template <typename Arithmetic> constexpr Arithmetic two_pi = Arithmetic(6.283185307179586); template <typename Arithmetic> constexpr Arithmetic e = Arithmetic(2.718281828459045); template <typename Arithmetic> constexpr Arithmetic sqrt2 = Arithmetic(1.414213562373095); template <typename Arithmetic> constexpr Arithmetic sqrt3 = Arithmetic(1.732050807568877); template <typename Arithmetic> constexpr Arithmetic euler = Arithmetic(0.577215664901532); template <typename Arithmetic> constexpr Arithmetic golden = Arithmetic(1.618033988749894); template <typename Arithmetic> constexpr Arithmetic mertens = Arithmetic(0.261497212847642); template <typename Arithmetic> constexpr Arithmetic bernstein = Arithmetic(0.280169499023869); template <typename Arithmetic> constexpr Arithmetic omega = Arithmetic(0.567143290409783); template <typename Arithmetic> constexpr Arithmetic cahen = Arithmetic(0.643410546288338); template <typename Arithmetic> constexpr Arithmetic laplace = Arithmetic(0.662743419349181); template <typename Arithmetic> constexpr Arithmetic landau = Arithmetic(0.764223653589220); template <typename Arithmetic> constexpr Arithmetic catalan = Arithmetic(0.915965594177219); template <typename Arithmetic> constexpr Arithmetic lengyel = Arithmetic(1.098685805525187); template <typename Arithmetic> constexpr Arithmetic apery = Arithmetic(1.202056903159594); template <typename Arithmetic> constexpr Arithmetic conway = Arithmetic(1.303577269034296); template <typename Arithmetic> constexpr Arithmetic mills = Arithmetic(1.306377883863080); template <typename Arithmetic> constexpr Arithmetic plastic = Arithmetic(1.324717957244746); template <typename Arithmetic> constexpr Arithmetic soldner = Arithmetic(1.451369234883381); template <typename Arithmetic> constexpr Arithmetic backhouse = Arithmetic(1.456074948582689); template <typename Arithmetic> constexpr Arithmetic lieb = Arithmetic(1.539600717839002); template <typename Arithmetic> constexpr Arithmetic niven = Arithmetic(1.705211140105367); template <typename Arithmetic> constexpr Arithmetic parabolic = Arithmetic(2.295587149392638); template <typename Arithmetic> constexpr Arithmetic sierpinski = Arithmetic(2.584981759579253); template <typename Arithmetic> constexpr Arithmetic khinchin = Arithmetic(2.685452001065306); template <typename Arithmetic> constexpr Arithmetic levy = Arithmetic(3.275822918721811); // Physical constants template <typename Arithmetic> constexpr Arithmetic light_speed = Arithmetic(299792458); // speed of light in vaccum in m.s^-1 template <typename Arithmetic> constexpr Arithmetic atomic_mass = Arithmetic(1.660538921e-27); // atomic mass constant in kg template <typename Arithmetic> constexpr Arithmetic gravity = Arithmetic(6.67384e-11); // Newtonian constant of gravitation in m^3.kg^-1.s^-2 template <typename Arithmetic> constexpr Arithmetic planck = Arithmetic(6.62606957e-34); // Planck constant in J.s template <typename Arithmetic> constexpr Arithmetic boltzmann = Arithmetic(1.3806488e-23); // Boltzmann constant in J.K-1 template <typename Arithmetic> constexpr Arithmetic avogadro = Arithmetic(6.02214129e+23); // Avogadro's number in mol-1 template <typename Arithmetic> constexpr auto sign(Arithmetic x) { return (x > 0) - (x < 0); } template <typename Arithmetic> constexpr auto align(Arithmetic x, Arithmetic alignment) { return (x + alignment - 1) &~(alignment - 1); } } // namespace ig #endif // IG_MATH_BASIS_H
61.328125
149
0.781401
ae0f3cd8c4353982a291754f3525b7b75f56a37b
3,721
h
C
cml/include/cml/statistics/char.h
LukasGelbmann/cmathl
30b30377e526718c65b2186b8e3a77ec03db7acb
[ "MIT" ]
34
2018-09-07T12:51:21.000Z
2021-11-26T13:00:54.000Z
cml/include/cml/statistics/char.h
LukasGelbmann/cmathl
30b30377e526718c65b2186b8e3a77ec03db7acb
[ "MIT" ]
6
2018-12-09T02:01:46.000Z
2021-02-24T21:55:30.000Z
cml/include/cml/statistics/char.h
LukasGelbmann/cmathl
30b30377e526718c65b2186b8e3a77ec03db7acb
[ "MIT" ]
5
2018-09-18T08:33:02.000Z
2021-08-23T03:55:09.000Z
#ifndef CML_STATISTICS_H #error "Never use <cml/statistics/char.h> directly; include <cml/statistics.h> instead." #endif #ifndef CML_STATISTICS_CHAR_H #define CML_STATISTICS_CHAR_H #include <stdlib.h> __CML_BEGIN_DECLS double cml_stats_char_mean(const char data[], const size_t stride, const size_t n); double cml_stats_char_variance(const char data[], const size_t stride, const size_t n); double cml_stats_char_sd(const char data[], const size_t stride, const size_t n); double cml_stats_char_variance_with_fixed_mean(const char data[], const size_t stride, const size_t n, const double mean); double cml_stats_char_sd_with_fixed_mean(const char data[], const size_t stride, const size_t n, const double mean); double cml_stats_char_tss(const char data[], const size_t stride, const size_t n); double cml_stats_char_tss_m(const char data[], const size_t stride, const size_t n, const double mean); double cml_stats_char_absdev(const char data[], const size_t stride, const size_t n); double cml_stats_char_skew(const char data[], const size_t stride, const size_t n); double cml_stats_char_kurtosis(const char data[], const size_t stride, const size_t n); double cml_stats_char_lag1_autocorrelation(const char data[], const size_t stride, const size_t n); double cml_stats_char_covariance(const char data1[], const size_t stride1,const char data2[], const size_t stride2, const size_t n); double cml_stats_char_correlation(const char data1[], const size_t stride1,const char data2[], const size_t stride2, const size_t n); double cml_stats_char_spearman(const char data1[], const size_t stride1, const char data2[], const size_t stride2, const size_t n, double work[]); double cml_stats_char_variance_m(const char data[], const size_t stride, const size_t n, const double mean); double cml_stats_char_sd_m(const char data[], const size_t stride, const size_t n, const double mean); double cml_stats_char_absdev_m(const char data[], const size_t stride, const size_t n, const double mean); double cml_stats_char_skew_m_sd(const char data[], const size_t stride, const size_t n, const double mean, const double sd); double cml_stats_char_kurtosis_m_sd(const char data[], const size_t stride, const size_t n, const double mean, const double sd); double cml_stats_char_lag1_autocorrelation_m(const char data[], const size_t stride, const size_t n, const double mean); double cml_stats_char_covariance_m(const char data1[], const size_t stride1,const char data2[], const size_t stride2, const size_t n, const double mean1, const double mean2); double cml_stats_char_pvariance(const char data1[], const size_t stride1, const size_t n1, const char data2[], const size_t stride2, const size_t n2); double cml_stats_char_ttest(const char data1[], const size_t stride1, const size_t n1, const char data2[], const size_t stride2, const size_t n2); char cml_stats_char_max(const char data[], const size_t stride, const size_t n); char cml_stats_char_min(const char data[], const size_t stride, const size_t n); void cml_stats_char_minmax(char * min, char * max, const char data[], const size_t stride, const size_t n); size_t cml_stats_char_max_index(const char data[], const size_t stride, const size_t n); size_t cml_stats_char_min_index(const char data[], const size_t stride, const size_t n); void cml_stats_char_minmax_index(size_t * min_index, size_t * max_index, const char data[], const size_t stride, const size_t n); double cml_stats_char_median_from_sorted_data(const char sorted_data[], const size_t stride, const size_t n); double cml_stats_char_quantile_from_sorted_data(const char sorted_data[], const size_t stride, const size_t n, const double f); __CML_END_DECLS #endif /* CML_STATISTICS_UINT_H */
66.446429
174
0.801666
8f8c66c4498d8573d28f018f47b7b782815270bf
941
h
C
External/libigl-2.1.0/include/igl/directed_edge_parents.h
RokKos/eol-cloth
b9c6f55f25ba17f33532ea5eefa41fedd29c5206
[ "MIT" ]
null
null
null
External/libigl-2.1.0/include/igl/directed_edge_parents.h
RokKos/eol-cloth
b9c6f55f25ba17f33532ea5eefa41fedd29c5206
[ "MIT" ]
null
null
null
External/libigl-2.1.0/include/igl/directed_edge_parents.h
RokKos/eol-cloth
b9c6f55f25ba17f33532ea5eefa41fedd29c5206
[ "MIT" ]
null
null
null
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2014 Alec Jacobson <alecjacobson@gmail.com> // // 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/. #ifndef IGL_DIRECTED_EDGE_PARENTS_H #define IGL_DIRECTED_EDGE_PARENTS_H #include "igl_inline.h" namespace igl { // Recover "parents" (preceding edges) in a tree given just directed edges. // // Inputs: // E #E by 2 list of directed edges // Outputs: // P #E list of parent indices into E (-1) means root // template <typename DerivedE, typename DerivedP> IGL_INLINE void directed_edge_parents( const Eigen::PlainObjectBase<DerivedE> & E, Eigen::PlainObjectBase<DerivedP> & P); } #ifndef IGL_STATIC_LIBRARY # include "directed_edge_parents.cpp" #endif #endif
28.515152
79
0.717322
8f3d6e9cec39edb40f5921c47ebec609c2a17c20
24,823
c
C
gps/gps_qemu.c
aldebaran/device_generic_goldfish
3b04758d1d0e9a525f1d1020d0f18d044edb0a6f
[ "Apache-2.0" ]
null
null
null
gps/gps_qemu.c
aldebaran/device_generic_goldfish
3b04758d1d0e9a525f1d1020d0f18d044edb0a6f
[ "Apache-2.0" ]
null
null
null
gps/gps_qemu.c
aldebaran/device_generic_goldfish
3b04758d1d0e9a525f1d1020d0f18d044edb0a6f
[ "Apache-2.0" ]
1
2019-04-24T04:05:33.000Z
2019-04-24T04:05:33.000Z
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* this implements a GPS hardware library for the Android emulator. * the following code should be built as a shared library that will be * placed into /system/lib/hw/gps.goldfish.so * * it will be loaded by the code in hardware/libhardware/hardware.c * which is itself called from android_location_GpsLocationProvider.cpp */ #include <errno.h> #include <pthread.h> #include <fcntl.h> #include <sys/epoll.h> #include <math.h> #include <time.h> #define LOG_TAG "gps_qemu" #include <cutils/log.h> #include <cutils/sockets.h> #include <hardware/gps.h> #include <hardware/qemud.h> /* the name of the qemud-controlled socket */ #define QEMU_CHANNEL_NAME "gps" #define GPS_DEBUG 0 #if GPS_DEBUG # define D(...) ALOGD(__VA_ARGS__) #else # define D(...) ((void)0) #endif /*****************************************************************/ /*****************************************************************/ /***** *****/ /***** N M E A T O K E N I Z E R *****/ /***** *****/ /*****************************************************************/ /*****************************************************************/ typedef struct { const char* p; const char* end; } Token; #define MAX_NMEA_TOKENS 16 typedef struct { int count; Token tokens[ MAX_NMEA_TOKENS ]; } NmeaTokenizer; static int nmea_tokenizer_init( NmeaTokenizer* t, const char* p, const char* end ) { int count = 0; char* q; // the initial '$' is optional if (p < end && p[0] == '$') p += 1; // remove trailing newline if (end > p && end[-1] == '\n') { end -= 1; if (end > p && end[-1] == '\r') end -= 1; } // get rid of checksum at the end of the sentecne if (end >= p+3 && end[-3] == '*') { end -= 3; } while (p < end) { const char* q = p; q = memchr(p, ',', end-p); if (q == NULL) q = end; if (q > p) { if (count < MAX_NMEA_TOKENS) { t->tokens[count].p = p; t->tokens[count].end = q; count += 1; } } if (q < end) q += 1; p = q; } t->count = count; return count; } static Token nmea_tokenizer_get( NmeaTokenizer* t, int index ) { Token tok; static const char* dummy = ""; if (index < 0 || index >= t->count) { tok.p = tok.end = dummy; } else tok = t->tokens[index]; return tok; } static int str2int( const char* p, const char* end ) { int result = 0; int len = end - p; for ( ; len > 0; len--, p++ ) { int c; if (p >= end) goto Fail; c = *p - '0'; if ((unsigned)c >= 10) goto Fail; result = result*10 + c; } return result; Fail: return -1; } static double str2float( const char* p, const char* end ) { int result = 0; int len = end - p; char temp[16]; if (len >= (int)sizeof(temp)) return 0.; memcpy( temp, p, len ); temp[len] = 0; return strtod( temp, NULL ); } /*****************************************************************/ /*****************************************************************/ /***** *****/ /***** N M E A P A R S E R *****/ /***** *****/ /*****************************************************************/ /*****************************************************************/ #define NMEA_MAX_SIZE 83 typedef struct { int pos; int overflow; int utc_year; int utc_mon; int utc_day; int utc_diff; GpsLocation fix; gps_location_callback callback; char in[ NMEA_MAX_SIZE+1 ]; } NmeaReader; static void nmea_reader_update_utc_diff( NmeaReader* r ) { time_t now = time(NULL); struct tm tm_local; struct tm tm_utc; long time_local, time_utc; gmtime_r( &now, &tm_utc ); localtime_r( &now, &tm_local ); time_local = tm_local.tm_sec + 60*(tm_local.tm_min + 60*(tm_local.tm_hour + 24*(tm_local.tm_yday + 365*tm_local.tm_year))); time_utc = tm_utc.tm_sec + 60*(tm_utc.tm_min + 60*(tm_utc.tm_hour + 24*(tm_utc.tm_yday + 365*tm_utc.tm_year))); r->utc_diff = time_utc - time_local; } static void nmea_reader_init( NmeaReader* r ) { memset( r, 0, sizeof(*r) ); r->pos = 0; r->overflow = 0; r->utc_year = -1; r->utc_mon = -1; r->utc_day = -1; r->callback = NULL; r->fix.size = sizeof(r->fix); nmea_reader_update_utc_diff( r ); } static void nmea_reader_set_callback( NmeaReader* r, gps_location_callback cb ) { r->callback = cb; if (cb != NULL && r->fix.flags != 0) { D("%s: sending latest fix to new callback", __FUNCTION__); r->callback( &r->fix ); r->fix.flags = 0; } } static int nmea_reader_update_time( NmeaReader* r, Token tok ) { int hour, minute; double seconds; struct tm tm; time_t fix_time; if (tok.p + 6 > tok.end) return -1; if (r->utc_year < 0) { // no date yet, get current one time_t now = time(NULL); gmtime_r( &now, &tm ); r->utc_year = tm.tm_year + 1900; r->utc_mon = tm.tm_mon + 1; r->utc_day = tm.tm_mday; } hour = str2int(tok.p, tok.p+2); minute = str2int(tok.p+2, tok.p+4); seconds = str2float(tok.p+4, tok.end); tm.tm_hour = hour; tm.tm_min = minute; tm.tm_sec = (int) seconds; tm.tm_year = r->utc_year - 1900; tm.tm_mon = r->utc_mon - 1; tm.tm_mday = r->utc_day; tm.tm_isdst = -1; fix_time = mktime( &tm ) + r->utc_diff; r->fix.timestamp = (long long)fix_time * 1000; return 0; } static int nmea_reader_update_date( NmeaReader* r, Token date, Token time ) { Token tok = date; int day, mon, year; if (tok.p + 6 != tok.end) { D("date not properly formatted: '%.*s'", tok.end-tok.p, tok.p); return -1; } day = str2int(tok.p, tok.p+2); mon = str2int(tok.p+2, tok.p+4); year = str2int(tok.p+4, tok.p+6) + 2000; if ((day|mon|year) < 0) { D("date not properly formatted: '%.*s'", tok.end-tok.p, tok.p); return -1; } r->utc_year = year; r->utc_mon = mon; r->utc_day = day; return nmea_reader_update_time( r, time ); } static double convert_from_hhmm( Token tok ) { double val = str2float(tok.p, tok.end); int degrees = (int)(floor(val) / 100); double minutes = val - degrees*100.; double dcoord = degrees + minutes / 60.0; return dcoord; } static int nmea_reader_update_latlong( NmeaReader* r, Token latitude, char latitudeHemi, Token longitude, char longitudeHemi ) { double lat, lon; Token tok; tok = latitude; if (tok.p + 6 > tok.end) { D("latitude is too short: '%.*s'", tok.end-tok.p, tok.p); return -1; } lat = convert_from_hhmm(tok); if (latitudeHemi == 'S') lat = -lat; tok = longitude; if (tok.p + 6 > tok.end) { D("longitude is too short: '%.*s'", tok.end-tok.p, tok.p); return -1; } lon = convert_from_hhmm(tok); if (longitudeHemi == 'W') lon = -lon; r->fix.flags |= GPS_LOCATION_HAS_LAT_LONG; r->fix.latitude = lat; r->fix.longitude = lon; return 0; } static int nmea_reader_update_altitude( NmeaReader* r, Token altitude, Token units ) { double alt; Token tok = altitude; if (tok.p >= tok.end) return -1; r->fix.flags |= GPS_LOCATION_HAS_ALTITUDE; r->fix.altitude = str2float(tok.p, tok.end); return 0; } static int nmea_reader_update_bearing( NmeaReader* r, Token bearing ) { double alt; Token tok = bearing; if (tok.p >= tok.end) return -1; r->fix.flags |= GPS_LOCATION_HAS_BEARING; r->fix.bearing = str2float(tok.p, tok.end); return 0; } static int nmea_reader_update_speed( NmeaReader* r, Token speed ) { double alt; Token tok = speed; if (tok.p >= tok.end) return -1; r->fix.flags |= GPS_LOCATION_HAS_SPEED; r->fix.speed = str2float(tok.p, tok.end); return 0; } static int nmea_reader_update_accuracy( NmeaReader* r ) { // Always return 20m accuracy. // Possibly parse it from the NMEA sentence in the future. r->fix.flags |= GPS_LOCATION_HAS_ACCURACY; r->fix.accuracy = 20; return 0; } static void nmea_reader_parse( NmeaReader* r ) { /* we received a complete sentence, now parse it to generate * a new GPS fix... */ NmeaTokenizer tzer[1]; Token tok; D("Received: '%.*s'", r->pos, r->in); if (r->pos < 9) { D("Too short. discarded."); return; } nmea_tokenizer_init(tzer, r->in, r->in + r->pos); #if GPS_DEBUG { int n; D("Found %d tokens", tzer->count); for (n = 0; n < tzer->count; n++) { Token tok = nmea_tokenizer_get(tzer,n); D("%2d: '%.*s'", n, tok.end-tok.p, tok.p); } } #endif tok = nmea_tokenizer_get(tzer, 0); if (tok.p + 5 > tok.end) { D("sentence id '%.*s' too short, ignored.", tok.end-tok.p, tok.p); return; } // ignore first two characters. tok.p += 2; if ( !memcmp(tok.p, "GGA", 3) ) { // GPS fix Token tok_time = nmea_tokenizer_get(tzer,1); Token tok_latitude = nmea_tokenizer_get(tzer,2); Token tok_latitudeHemi = nmea_tokenizer_get(tzer,3); Token tok_longitude = nmea_tokenizer_get(tzer,4); Token tok_longitudeHemi = nmea_tokenizer_get(tzer,5); Token tok_altitude = nmea_tokenizer_get(tzer,9); Token tok_altitudeUnits = nmea_tokenizer_get(tzer,10); nmea_reader_update_time(r, tok_time); nmea_reader_update_latlong(r, tok_latitude, tok_latitudeHemi.p[0], tok_longitude, tok_longitudeHemi.p[0]); nmea_reader_update_altitude(r, tok_altitude, tok_altitudeUnits); } else if ( !memcmp(tok.p, "GSA", 3) ) { // do something ? } else if ( !memcmp(tok.p, "RMC", 3) ) { Token tok_time = nmea_tokenizer_get(tzer,1); Token tok_fixStatus = nmea_tokenizer_get(tzer,2); Token tok_latitude = nmea_tokenizer_get(tzer,3); Token tok_latitudeHemi = nmea_tokenizer_get(tzer,4); Token tok_longitude = nmea_tokenizer_get(tzer,5); Token tok_longitudeHemi = nmea_tokenizer_get(tzer,6); Token tok_speed = nmea_tokenizer_get(tzer,7); Token tok_bearing = nmea_tokenizer_get(tzer,8); Token tok_date = nmea_tokenizer_get(tzer,9); D("in RMC, fixStatus=%c", tok_fixStatus.p[0]); if (tok_fixStatus.p[0] == 'A') { nmea_reader_update_date( r, tok_date, tok_time ); nmea_reader_update_latlong( r, tok_latitude, tok_latitudeHemi.p[0], tok_longitude, tok_longitudeHemi.p[0] ); nmea_reader_update_bearing( r, tok_bearing ); nmea_reader_update_speed ( r, tok_speed ); } } else { tok.p -= 2; D("unknown sentence '%.*s", tok.end-tok.p, tok.p); } // Always update accuracy nmea_reader_update_accuracy( r ); if (r->fix.flags != 0) { #if GPS_DEBUG char temp[256]; char* p = temp; char* end = p + sizeof(temp); struct tm utc; p += snprintf( p, end-p, "sending fix" ); if (r->fix.flags & GPS_LOCATION_HAS_LAT_LONG) { p += snprintf(p, end-p, " lat=%g lon=%g", r->fix.latitude, r->fix.longitude); } if (r->fix.flags & GPS_LOCATION_HAS_ALTITUDE) { p += snprintf(p, end-p, " altitude=%g", r->fix.altitude); } if (r->fix.flags & GPS_LOCATION_HAS_SPEED) { p += snprintf(p, end-p, " speed=%g", r->fix.speed); } if (r->fix.flags & GPS_LOCATION_HAS_BEARING) { p += snprintf(p, end-p, " bearing=%g", r->fix.bearing); } if (r->fix.flags & GPS_LOCATION_HAS_ACCURACY) { p += snprintf(p,end-p, " accuracy=%g", r->fix.accuracy); } gmtime_r( (time_t*) &r->fix.timestamp, &utc ); p += snprintf(p, end-p, " time=%s", asctime( &utc ) ); D(temp); #endif if (r->callback) { r->callback( &r->fix ); r->fix.flags = 0; } else { D("no callback, keeping data until needed !"); } } } static void nmea_reader_addc( NmeaReader* r, int c ) { if (r->overflow) { r->overflow = (c != '\n'); return; } if (r->pos >= (int) sizeof(r->in)-1 ) { r->overflow = 1; r->pos = 0; return; } r->in[r->pos] = (char)c; r->pos += 1; if (c == '\n') { nmea_reader_parse( r ); r->pos = 0; } } /*****************************************************************/ /*****************************************************************/ /***** *****/ /***** C O N N E C T I O N S T A T E *****/ /***** *****/ /*****************************************************************/ /*****************************************************************/ /* commands sent to the gps thread */ enum { CMD_QUIT = 0, CMD_START = 1, CMD_STOP = 2 }; /* this is the state of our connection to the qemu_gpsd daemon */ typedef struct { int init; int fd; GpsCallbacks callbacks; pthread_t thread; int control[2]; } GpsState; static GpsState _gps_state[1]; static void gps_state_done( GpsState* s ) { // tell the thread to quit, and wait for it char cmd = CMD_QUIT; void* dummy; write( s->control[0], &cmd, 1 ); pthread_join(s->thread, &dummy); // close the control socket pair close( s->control[0] ); s->control[0] = -1; close( s->control[1] ); s->control[1] = -1; // close connection to the QEMU GPS daemon close( s->fd ); s->fd = -1; s->init = 0; } static void gps_state_start( GpsState* s ) { char cmd = CMD_START; int ret; do { ret=write( s->control[0], &cmd, 1 ); } while (ret < 0 && errno == EINTR); if (ret != 1) D("%s: could not send CMD_START command: ret=%d: %s", __FUNCTION__, ret, strerror(errno)); } static void gps_state_stop( GpsState* s ) { char cmd = CMD_STOP; int ret; do { ret=write( s->control[0], &cmd, 1 ); } while (ret < 0 && errno == EINTR); if (ret != 1) D("%s: could not send CMD_STOP command: ret=%d: %s", __FUNCTION__, ret, strerror(errno)); } static int epoll_register( int epoll_fd, int fd ) { struct epoll_event ev; int ret, flags; /* important: make the fd non-blocking */ flags = fcntl(fd, F_GETFL); fcntl(fd, F_SETFL, flags | O_NONBLOCK); ev.events = EPOLLIN; ev.data.fd = fd; do { ret = epoll_ctl( epoll_fd, EPOLL_CTL_ADD, fd, &ev ); } while (ret < 0 && errno == EINTR); return ret; } static int epoll_deregister( int epoll_fd, int fd ) { int ret; do { ret = epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd, NULL ); } while (ret < 0 && errno == EINTR); return ret; } /* this is the main thread, it waits for commands from gps_state_start/stop and, * when started, messages from the QEMU GPS daemon. these are simple NMEA sentences * that must be parsed to be converted into GPS fixes sent to the framework */ static void gps_state_thread( void* arg ) { GpsState* state = (GpsState*) arg; NmeaReader reader[1]; int epoll_fd = epoll_create(2); int started = 0; int gps_fd = state->fd; int control_fd = state->control[1]; nmea_reader_init( reader ); // register control file descriptors for polling epoll_register( epoll_fd, control_fd ); epoll_register( epoll_fd, gps_fd ); D("gps thread running"); // now loop for (;;) { struct epoll_event events[2]; int ne, nevents; nevents = epoll_wait( epoll_fd, events, 2, -1 ); if (nevents < 0) { if (errno != EINTR) ALOGE("epoll_wait() unexpected error: %s", strerror(errno)); continue; } D("gps thread received %d events", nevents); for (ne = 0; ne < nevents; ne++) { if ((events[ne].events & (EPOLLERR|EPOLLHUP)) != 0) { ALOGE("EPOLLERR or EPOLLHUP after epoll_wait() !?"); return; } if ((events[ne].events & EPOLLIN) != 0) { int fd = events[ne].data.fd; if (fd == control_fd) { char cmd = 255; int ret; D("gps control fd event"); do { ret = read( fd, &cmd, 1 ); } while (ret < 0 && errno == EINTR); if (cmd == CMD_QUIT) { D("gps thread quitting on demand"); return; } else if (cmd == CMD_START) { if (!started) { D("gps thread starting location_cb=%p", state->callbacks.location_cb); started = 1; nmea_reader_set_callback( reader, state->callbacks.location_cb ); } } else if (cmd == CMD_STOP) { if (started) { D("gps thread stopping"); started = 0; nmea_reader_set_callback( reader, NULL ); } } } else if (fd == gps_fd) { char buff[32]; D("gps fd event"); for (;;) { int nn, ret; ret = read( fd, buff, sizeof(buff) ); if (ret < 0) { if (errno == EINTR) continue; if (errno != EWOULDBLOCK) ALOGE("error while reading from gps daemon socket: %s:", strerror(errno)); break; } D("received %d bytes: %.*s", ret, ret, buff); for (nn = 0; nn < ret; nn++) nmea_reader_addc( reader, buff[nn] ); } D("gps fd event end"); } else { ALOGE("epoll_wait() returned unkown fd %d ?", fd); } } } } } static void gps_state_init( GpsState* state, GpsCallbacks* callbacks ) { state->init = 1; state->control[0] = -1; state->control[1] = -1; state->fd = -1; state->fd = qemud_channel_open(QEMU_CHANNEL_NAME); if (state->fd < 0) { D("no gps emulation detected"); return; } D("gps emulation will read from '%s' qemud channel", QEMU_CHANNEL_NAME ); if ( socketpair( AF_LOCAL, SOCK_STREAM, 0, state->control ) < 0 ) { ALOGE("could not create thread control socket pair: %s", strerror(errno)); goto Fail; } state->thread = callbacks->create_thread_cb( "gps_state_thread", gps_state_thread, state ); if ( !state->thread ) { ALOGE("could not create gps thread: %s", strerror(errno)); goto Fail; } state->callbacks = *callbacks; D("gps state initialized"); return; Fail: gps_state_done( state ); } /*****************************************************************/ /*****************************************************************/ /***** *****/ /***** I N T E R F A C E *****/ /***** *****/ /*****************************************************************/ /*****************************************************************/ static int qemu_gps_init(GpsCallbacks* callbacks) { GpsState* s = _gps_state; if (!s->init) gps_state_init(s, callbacks); if (s->fd < 0) return -1; return 0; } static void qemu_gps_cleanup(void) { GpsState* s = _gps_state; if (s->init) gps_state_done(s); } static int qemu_gps_start() { GpsState* s = _gps_state; if (!s->init) { D("%s: called with uninitialized state !!", __FUNCTION__); return -1; } D("%s: called", __FUNCTION__); gps_state_start(s); return 0; } static int qemu_gps_stop() { GpsState* s = _gps_state; if (!s->init) { D("%s: called with uninitialized state !!", __FUNCTION__); return -1; } D("%s: called", __FUNCTION__); gps_state_stop(s); return 0; } static int qemu_gps_inject_time(GpsUtcTime time, int64_t timeReference, int uncertainty) { return 0; } static int qemu_gps_inject_location(double latitude, double longitude, float accuracy) { return 0; } static void qemu_gps_delete_aiding_data(GpsAidingData flags) { } static int qemu_gps_set_position_mode(GpsPositionMode mode, int fix_frequency) { // FIXME - support fix_frequency return 0; } static const void* qemu_gps_get_extension(const char* name) { // no extensions supported return NULL; } static const GpsInterface qemuGpsInterface = { sizeof(GpsInterface), qemu_gps_init, qemu_gps_start, qemu_gps_stop, qemu_gps_cleanup, qemu_gps_inject_time, qemu_gps_inject_location, qemu_gps_delete_aiding_data, qemu_gps_set_position_mode, qemu_gps_get_extension, }; const GpsInterface* gps__get_gps_interface(struct gps_device_t* dev) { return &qemuGpsInterface; } static int open_gps(const struct hw_module_t* module, char const* name, struct hw_device_t** device) { struct gps_device_t *dev = malloc(sizeof(struct gps_device_t)); memset(dev, 0, sizeof(*dev)); dev->common.tag = HARDWARE_DEVICE_TAG; dev->common.version = 0; dev->common.module = (struct hw_module_t*)module; // dev->common.close = (int (*)(struct hw_device_t*))close_lights; dev->get_gps_interface = gps__get_gps_interface; *device = (struct hw_device_t*)dev; return 0; } static struct hw_module_methods_t gps_module_methods = { .open = open_gps }; struct hw_module_t HAL_MODULE_INFO_SYM = { .tag = HARDWARE_MODULE_TAG, .version_major = 1, .version_minor = 0, .id = GPS_HARDWARE_MODULE_ID, .name = "Goldfish GPS Module", .author = "The Android Open Source Project", .methods = &gps_module_methods, };
25.965481
106
0.493816