max_stars_repo_path
stringlengths
3
199
max_stars_repo_name
stringlengths
6
90
max_stars_count
float64
0
118k
id
stringlengths
3
7
content
stringlengths
14
1,000k
score
float64
0.34
1
label
stringclasses
3 values
main/nokialcd.c
virtualabs/brucon-2019
3
900801
#include "./nokialcd.h" #include "./brucon.h" #include "map.h" #include <freertos/task.h> TickType_t last_click; spi_device_handle_t spi; uint8_t driver; static char x_offset = 0; static char y_offset = 0; static char lastfill = 0; typedef struct { uint8_t cmd; uint8_t data[16]; uint8_t databytes; //No of data in data; bit 7 = delay after set; 0xFF = end of cmds. } lcd_init_cmd_t; uint16_t *frame = NULL;// [ROW_LENGTH*COL_HEIGHT]; uint8_t *framespi = NULL; void do_spi_init(); void switchbacklight(int state){ if(state) last_click=xTaskGetTickCount(); if(esp_reset_reason() == ESP_RST_BROWNOUT){ gpio_set_level(ENSCR_PIN,0); printf("has a brownout, not turning backlight on") ; return; } gpio_set_level(ENSCR_PIN,state); } portMUX_TYPE mmux = portMUX_INITIALIZER_UNLOCKED; portMUX_TYPE * mux = &mmux; void framespi_write9(int offset, uint16_t value) { int index = offset/8; // offset in framespi int shift = offset%8; // bitshift to apply uint8_t mask0 = 0xff<<(8-shift); uint8_t mask1 = 0xff>>(7-shift); framespi[index] = (framespi[index]&mask0)|(value>>1)>>shift; framespi[index+1] = (value&mask1) << (7-shift); } void send_9(uint16_t data){ esp_err_t ret; spi_transaction_t t; uint16_t workaround = SPI_SWAP_DATA_TX(data,9); memset(&t, 0, sizeof(t)); //Zero out the transaction t.length=9; //Command is 9 bits t.tx_buffer=&workaround; //The data is the cmd itself // portENTER_CRITICAL(mux); // __disable_interrupt(); // taskENTER_CRITICAL(); ret= spi_device_transmit(spi, &t);//Transmit! assert(ret==ESP_OK); // portEXIT_CRITICAL(mux); // __enable_interrupt(); // taskEXIT_CRITICAL(); } void lcd_send(char t,uint8_t d) { uint16_t c = ((t<<8) | d); send_9(c); } void lcd_send_framespi(int nbits) { esp_err_t ret; spi_transaction_t t; memset(&t, 0, sizeof(t)); //Zero out the transaction t.length=(nbits/64)*64; //Command is 9 bits t.tx_buffer=framespi; //The data is the cmd itself ret = spi_device_transmit(spi, &t);//Transmit! assert(ret==ESP_OK); } /** * send_frame() * * Sends a 132*132 pixels frame to the screen, the high-speed way. * Takes a framebuffer (132*132 uint16_t values) as 12-bit pixels. * * This function refreshes the whole screen. **/ void send_frame(uint16_t *framebuffer) { int k,i; /* Init column and raw */ lcd_send(LCD_COMMAND,PASETP); lcd_send(LCD_DATA,0); lcd_send(LCD_DATA,131); lcd_send(LCD_COMMAND,CASETP); lcd_send(LCD_DATA,0); lcd_send(LCD_DATA,131); lcd_send(LCD_COMMAND,RAMWRP); /* Send line by line 8 pixels -> 9 bytes*/ memset(framespi, 0x0, 792*sizeof(uint8_t)); i=0; k=0; while (i<ROW_LENGTH*COL_HEIGHT) { framespi_write9(k, ((framebuffer[i]>>4)&0xff) | (LCD_DATA << 8)); k+=9; framespi_write9(k, (framebuffer[i]&0x0F)<<4 | (framebuffer[i+1]>>8) | (LCD_DATA << 8)); k+=9; framespi_write9(k, (framebuffer[i+1]&0xff) | (LCD_DATA << 8)); k+=9; i+=2; if (i%128==0) { lcd_send_framespi(k); k=0; } } } /** * Loads a 132*132 bitmap into the framebuffer, and updates the screen. **/ void lcd_load_bitmap(uint16_t *bitmap) { lcd_bitblt(0,0,132,132,bitmap); } /** * bitblt() * * Bitblt a region into our framebuffer. * This routine DOES NOT refresh screen ! * **/ void lcd_bitblt(int x, int y, int width, int height, uint16_t *region) { int w,z; for (w=0;w<height;w++) for (z=0;z<width;z++) frame[(y+w)*ROW_LENGTH + (132 - x+z)] = region[w*ROW_LENGTH + z]; } /** * region_fill() * * Fill a region with the given color. * **/ void lcd_region_fill(int x, int y, int width, int height, uint16_t color) { int w,z; for (w=0;w<height;w++) for (z=0;z<width;z++) frame[(y+w)*ROW_LENGTH + (132 - x+z)] = color; } void lcd_cmd(uint8_t cmd) { uint16_t c = (0x000 | cmd); send_9(c); } void lcd_data(uint8_t data) { uint16_t c = (0x100 | data); send_9(c); } void lcd_spi_pre_transfer_callback(spi_transaction_t *t) { gpio_set_level(LCD_CS, 0); } void lcd_spi_post_transfer_callback(spi_transaction_t *t) { gpio_set_level(LCD_CS, 1); } void init_lcd(int type) { esp_err_t ret; gpio_config_t io_conf; /* Allocate framebuffer */ frame = (uint16_t*) malloc(ROW_LENGTH*COL_HEIGHT*sizeof(uint16_t)); /* Allocate frame SPI transactions buffer. */ framespi = (uint8_t*) heap_caps_malloc(792*sizeof(uint8_t), MALLOC_CAP_DMA); vPortCPUInitializeMutex(mux); driver = type; io_conf.intr_type = GPIO_PIN_INTR_DISABLE; io_conf.mode = GPIO_MODE_OUTPUT; io_conf.pin_bit_mask = (1ULL<<LCD_SCK) | (1ULL<<LCD_DIO) | (1ULL<<LCD_RST) | (1ULL<<LCD_CS)| (1ULL<<TRIGLA); io_conf.pull_down_en = 0; io_conf.pull_up_en = 0; gpio_config(&io_conf); TRIG; LCD_SCK_L; LCD_DIO_L; dl_us(10); LCD_CS_H; dl_us(10); LCD_RST_L; dl_us(200); LCD_SCK_H; LCD_DIO_H; LCD_RST_H; spi_bus_config_t buscfg={ .mosi_io_num=LCD_DIO, .sclk_io_num=LCD_SCK, .quadwp_io_num=-1, .quadhd_io_num=-1 }; spi_device_interface_config_t devcfg={ .clock_speed_hz=30000000, //Clock out at 1 MHz .mode=3, //SPI mode 3 .queue_size=50, //We want to be able to queue 7 transactions at a time .pre_cb=NULL, .cs_ena_pretrans = 0, .cs_ena_posttrans = 0, .spics_io_num=LCD_CS, //CS pin /* .pre_cb=lcd_spi_pre_transfer_callback, //Specify pre-transfer callback to handle D/C line .post_cb=lcd_spi_post_transfer_callback //Specify pre-transfer callback to handle D/C line*/ }; gpio_config_t io_conf2={ .intr_type = GPIO_PIN_INTR_DISABLE, .mode = GPIO_MODE_OUTPUT, .pin_bit_mask = (1ULL<<LCD_SCK) | (1ULL<<LCD_DIO) | (1ULL<<LCD_RST) | (1ULL<<LCD_CS)| (1ULL<<TRIGLA), .pull_down_en = 0, .pull_up_en = 0 }; gpio_config(&io_conf2); driver = type; ret=spi_bus_initialize(HSPI_HOST, &buscfg, 1); assert(ret==ESP_OK); //Attach the LCD to the SPI bus ret=spi_bus_add_device(HSPI_HOST, &devcfg, &spi); assert(ret==ESP_OK); do_spi_init(); io_conf.intr_type = GPIO_PIN_INTR_DISABLE; io_conf.mode = GPIO_MODE_OUTPUT; io_conf.pin_bit_mask = (1ULL<<ENSCR_PIN); io_conf.pull_down_en = 0; io_conf.pull_up_en = 0; gpio_config(&io_conf); io_conf.intr_type = GPIO_PIN_INTR_DISABLE; io_conf.mode = GPIO_MODE_OUTPUT; io_conf.pin_bit_mask = 0; io_conf.pull_down_en = 0; io_conf.pull_up_en = 0; gpio_config(&io_conf); } void do_spi_init() { TRIG; LCD_CS_H; dl_us(10); LCD_RST_L; dl_us(200); LCD_RST_H; lcd_send(LCD_COMMAND,SLEEPOUT); // Sleep Out (0x11) lcd_send(LCD_COMMAND,BSTRON); // Booster voltage on (0x03) lcd_send(LCD_COMMAND,DISPON); // Display on (0x29) // lcd_send(LCD_COMMAND,INVON); // Inversion on (0x20) // 12-bit color pixel format: lcd_send(LCD_COMMAND,PCOLMOD); // Color interface format (0x3A) lcd_send(LCD_DATA,0x03); // 0b011 is 12-bit/pixel mode lcd_send(LCD_COMMAND,MADCTL); // Memory Access Control(PHILLIPS) lcd_send(LCD_DATA,0x00); lcd_send(LCD_COMMAND,SETCON); // Set Contrast(PHILLIPS) lcd_send(LCD_DATA,0x3f); lcd_send(LCD_COMMAND,NOPP); // nop(PHILLIPS) } void fillframe12B(uint16_t color_12b) { uint32_t i =0; while(i<(ROW_LENGTH*COL_HEIGHT)) frame[i++]=color_12b; } int lcd_commit(void) { if (frame != NULL) { send_frame(frame); return 1; } else return 0; } void go_framep(uint16_t *p) { lcd_send(LCD_COMMAND,PASETP); lcd_send(LCD_DATA,0); lcd_send(LCD_DATA,131); lcd_send(LCD_COMMAND,CASETP); lcd_send(LCD_DATA,0); lcd_send(LCD_DATA,131); lcd_send(LCD_COMMAND,RAMWRP); for(unsigned int i=0; i < (ROW_LENGTH*COL_HEIGHT); i+=2) { lcd_send(LCD_DATA,( (*(p+i)) >>4)&0xFF); lcd_send(LCD_DATA,( ((*(p+i)) &0x0F)<<4)|( (*(p+i+1))>>8)); lcd_send(LCD_DATA,( (*(p+i+1)) &0xFF)); } x_offset = 0; y_offset = 0; } void lcd_clearB12(int color){ lastfill=color; lcd_send(LCD_COMMAND,PASETP); lcd_send(LCD_DATA,0); lcd_send(LCD_DATA,131); lcd_send(LCD_COMMAND,CASETP); lcd_send(LCD_DATA,0); lcd_send(LCD_DATA,131); lcd_send(LCD_COMMAND,RAMWRP); }; void lcd_contrast(char setting){ setting &= 0x7F; // msb is not used, mask it out lcd_send(LCD_COMMAND,SETCON); // contrast command (PHILLIPS) lcd_send(LCD_DATA,setting); // volume (contrast) setting - course adjustment, -- original was 24 }; void lcd_setChar(char c, int x, int y, int fColor, int bColor, char transp) { y = (COL_HEIGHT - 1) - y; // make display "right" side up x = (ROW_LENGTH - 2) - x; int i,j; unsigned int nCols; unsigned int nRows; unsigned int nBytes; unsigned char PixelRow; unsigned char Mask; unsigned int Word0; unsigned int Word1; const unsigned char *pFont; const unsigned char *pChar; // get pointer to the beginning of the selected font table pFont = (const unsigned char *)FONT8x16; // get the nColumns, nRows and nBytes nCols = *(pFont); nRows = *(pFont + 1); nBytes = *(pFont + 2); // get pointer to the last byte of the desired character pChar = pFont + (nBytes * (c - 0x1F)) + nBytes - 1; if (driver) // if it's an epson { // Row address set (command 0x2B) lcd_send(LCD_COMMAND,PASET); lcd_send(LCD_DATA,x); lcd_send(LCD_DATA,x + nRows - 1); // Column address set (command 0x2A) lcd_send(LCD_COMMAND,CASET); lcd_send(LCD_DATA,y); lcd_send(LCD_DATA,y + nCols - 1); // WRITE MEMORY lcd_send(LCD_COMMAND,RAMWR); // loop on each row, working backwards from the bottom to the top for (i = nRows - 1; i >= 0; i--) { // copy pixel row from font table and then decrement row PixelRow = *(pChar++); // loop on each pixel in the row (left to right) // Note: we do two pixels each loop Mask = 0x80; for (j = 0; j < nCols; j += 2) { // if pixel bit set, use foreground color; else use the background color // now get the pixel color for two successive pixels if ((PixelRow & Mask) == 0) Word0 = frame[i*ROW_LENGTH+j]; else Word0 = fColor; Mask = Mask >> 1; if ((PixelRow & Mask) == 0) Word1 = bColor; else Word1 = fColor; Mask = Mask >> 1; // use this information to output three data bytes lcd_send(LCD_DATA,(Word0 >> 4) & 0xFF); lcd_send(LCD_DATA,((Word0 & 0xF) << 4) | ((Word1 >> 8) & 0xF)); lcd_send(LCD_DATA,Word1 & 0xFF); } } } else { // fColor = swapColors(fColor); // bColor = swapColors(bColor); // Row address set (command 0x2B) lcd_send(LCD_COMMAND,PASETP); lcd_send(LCD_DATA,x); lcd_send(LCD_DATA,x + nRows - 1); // Column address set (command 0x2A) lcd_send(LCD_COMMAND,CASETP); lcd_send(LCD_DATA,y); lcd_send(LCD_DATA,y + nCols - 1); // WRITE MEMORY lcd_send(LCD_COMMAND,RAMWRP); // loop on each row, working backwards from the bottom to the top pChar+=nBytes-1; // stick pChar at the end of the row - gonna reverse print on phillips for (i = nRows - 1; i >= 0; i--) { // copy pixel row from font table and then decrement row PixelRow = *(pChar--); // loop on each pixel in the row (left to right) // Note: we do two pixels each loop Mask = 0x01; // <- opposite of epson for (j = 0; j < nCols; j += 2) { // if pixel bit set, use foreground color; else use the background color // now get the pixel color for two successive pixels if ((PixelRow & Mask) == 0) Word0 = bColor;//frame[i*ROW_LENGTH+j]; else Word0 = fColor; Mask = Mask << 1; // <- opposite of epson if ((PixelRow & Mask) == 0) Word1 = bColor;//frame[i*ROW_LENGTH+j]; else Word1 = fColor; Mask = Mask << 1; // <- opposite of epson // use this information to output three data bytes lcd_send(LCD_DATA,(Word0 >> 4) & 0xFF); lcd_send(LCD_DATA,((Word0 & 0xF) << 4) | ((Word1 >> 8) & 0xF)); lcd_send(LCD_DATA,Word1 & 0xFF); } } } } void lcd_setStr(char *pString, int x, int y, int fColor, int bColor, char uselastfill, char newline) { x = x + 12; y = y + 7; int originalY = y; // loop until null-terminator is seen while (*pString != 0x00) { // draw the character lcd_setChar(*pString++, x, y, fColor, bColor,uselastfill); // advance the y position y = y + 8; // bail out if y exceeds 131 if ((y > 131) ) { if(newline){ x = x + 16; y = originalY; } else { break; } } if (x > 131) break; } } void lcd_pixel(int color, unsigned char x, unsigned char y) { y = (COL_HEIGHT - 1) - y; x = (ROW_LENGTH - 1) - x; frame[y*ROW_LENGTH + x] = color; } void lcd_line(int x0, int y0, int x1, int y1, int color) { int dy = y1 - y0; // Difference between y0 and y1 int dx = x1 - x0; // Difference between x0 and x1 int stepx, stepy; if (dy < 0) { dy = -dy; stepy = -1; } else stepy = 1; if (dx < 0) { dx = -dx; stepx = -1; } else stepx = 1; dy <<= 1; // dy is now 2*dy dx <<= 1; // dx is now 2*dx lcd_pixel(color, x0, y0); if (dx > dy) { int fraction = dy - (dx >> 1); while (x0 != x1) { if (fraction >= 0) { y0 += stepy; fraction -= dx; } x0 += stepx; fraction += dy; lcd_pixel(color, x0, y0); } } else { int fraction = dx - (dy >> 1); while (y0 != y1) { if (fraction >= 0) { x0 += stepx; fraction -= dy; } y0 += stepy; fraction += dx; lcd_pixel(color, x0, y0); } } }
0.984375
high
lib/air/test/unit_test/collection/mock_output_observer.h
YongJin-Cho/poseidonos
3
901313
<reponame>YongJin-Cho/poseidonos #include "src/output/Out.cpp" #include "src/output/OutputManager.cpp" #include "src/output/OutputObserver.cpp" #include "src/output/OutputObserver.h" class MockOutputObserver : public output::Observer { public: //MockOutputObserver() {} virtual ~MockOutputObserver() { } virtual void Update(uint32_t type1, uint32_t type2, uint32_t value1, uint32_t value2, int pid, int cmd_type, int cmd_order) { return; } virtual void Handle() { return; } private: };
0.574219
high
BusinessWeekly/Class/Recommend/Views/Date2TableViewCell.h
binghuizi/syBusiness
0
901825
<reponame>binghuizi/syBusiness // // Date2TableViewCell.h // BusinessWeekly // // Created by scjy on 16/2/4. // Copyright © 2016年 scjy. All rights reserved. // #import <UIKit/UIKit.h> #import "RecommModel.h" @interface Date2TableViewCell : UITableViewCell @property (weak, nonatomic) IBOutlet UIImageView *headImageView; @property (weak, nonatomic) IBOutlet UILabel *titleLabel; @property (weak, nonatomic) IBOutlet UILabel *descLabel; @property(nonatomic,strong) RecommModel *recomModel; @end
0.671875
medium
ios/Pods/Headers/Public/YBUtils/NSDictionary+Yibin.h
panyibin/walletTest3
0
902337
<gh_stars>0 // // NSDictionary+Yibin.h // Pods-YBUtils_Example // // Created by PanYibin on 2018/3/11. // #import <Foundation/Foundation.h> @interface NSDictionary (Yibin) - (BOOL)getBoolForKey:(NSString*)key; - (NSInteger)getIntegerForKey:(NSString*)key; - (float)getFloatForKey:(NSString*)key; - (NSString*)getStringForKey:(NSString*)key; - (NSArray*)getArrayForKey:(NSString*)key; - (NSDictionary*)getDictionaryForKey:(NSString*)key; @end
0.859375
high
features/frameworks/TARGET_PSA/val.h
pattyolanterns/mbed-os
5
902849
/** @file * Copyright (c) 2018-2019, Arm Limited or its affiliates. All rights reserved. * SPDX-License-Identifier : Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ #ifndef _VAL_COMMON_H_ #define _VAL_COMMON_H_ #include "pal_common.h" #ifndef VAL_NSPE_BUILD #define STATIC_DECLARE static #else #define STATIC_DECLARE #endif #ifndef __WEAK #define __WEAK __attribute__((weak)) #endif #ifndef __UNUSED #define __UNUSED __attribute__((unused)) #endif #ifndef TRUE #define TRUE 0 #endif #ifndef FALSE #define FALSE 1 #endif #ifndef INT_MAX #define INT_MAX 0xFFFFFFFF #endif #define _CONCAT(A,B) A##B #define CONCAT(A,B) _CONCAT(A,B) /* test status defines */ #define TEST_START 0x01 #define TEST_END 0x02 #define TEST_PASS 0x04 #define TEST_FAIL 0x08 #define TEST_SKIP 0x10 #define TEST_PENDING 0x20 #define TEST_NUM_BIT 32 #define TEST_STATE_BIT 8 #define TEST_STATUS_BIT 0 #define TEST_NUM_MASK 0xFFFFFFFF #define TEST_STATE_MASK 0xFF #define TEST_STATUS_MASK 0xFF #define RESULT_START(status) (((TEST_START) << TEST_STATE_BIT) | ((status) << TEST_STATUS_BIT)) #define RESULT_END(status) (((TEST_END) << TEST_STATE_BIT) | ((status) << TEST_STATUS_BIT)) #define RESULT_PASS(status) (((TEST_PASS) << TEST_STATE_BIT) | ((status) << TEST_STATUS_BIT)) #define RESULT_FAIL(status) (((TEST_FAIL) << TEST_STATE_BIT) | ((status) << TEST_STATUS_BIT)) #define RESULT_SKIP(status) (((TEST_SKIP) << TEST_STATE_BIT) | ((status) << TEST_STATUS_BIT)) #define RESULT_PENDING(status) (((TEST_PENDING) << TEST_STATE_BIT) | ((status) << TEST_STATUS_BIT)) #define IS_TEST_FAIL(status) (((status >> TEST_STATE_BIT) & TEST_STATE_MASK) == TEST_FAIL) #define IS_TEST_PASS(status) (((status >> TEST_STATE_BIT) & TEST_STATE_MASK) == TEST_PASS) #define IS_TEST_SKIP(status) (((status >> TEST_STATE_BIT) & TEST_STATE_MASK) == TEST_SKIP) #define IS_TEST_PENDING(status) (((status >> TEST_STATE_BIT) & TEST_STATE_MASK) == TEST_PENDING) #define IS_TEST_START(status) (((status >> TEST_STATE_BIT) & TEST_STATE_MASK) == TEST_START) #define IS_TEST_END(status) (((status >> TEST_STATE_BIT) & TEST_STATE_MASK) == TEST_END) #define VAL_ERROR(status) ((status & TEST_STATUS_MASK) ? 1 : 0) /* Test Defines */ #define TEST_PUBLISH(test_id, entry) #define VAL_MAX_TEST_PER_COMP 200 #define VAL_FF_BASE 0 #define VAL_CRYPTO_BASE 1 #define VAL_PROTECTED_STORAGE_BASE 2 #define VAL_INTERNAL_TRUSTED_STORAGE_BASE 3 #define VAL_INITIAL_ATTESTATION_BASE 4 #define VAL_GET_COMP_NUM(test_id) \ ((test_id - (test_id % VAL_MAX_TEST_PER_COMP)) / VAL_MAX_TEST_PER_COMP) #define VAL_GET_TEST_NUM(test_id) (test_id % VAL_MAX_TEST_PER_COMP) #define VAL_CREATE_TEST_ID(comp,num) ((comp*VAL_MAX_TEST_PER_COMP) + num) #define TEST_FIELD(num1,num2) (num2 << 8 | num1) #define GET_TEST_ISOLATION_LEVEL(num) (num & 0x3) #define GET_WD_TIMOUT_TYPE(num) ((num >> 8) & 0x7) #define TEST_CHECKPOINT_NUM(n) n #define TEST(n) n #define BLOCK(n) n #define BLOCK_NUM_POS 8 #define ACTION_POS 16 #define GET_TEST_NUM(n) (0xff & n) #define GET_BLOCK_NUM(n) ((n >> BLOCK_NUM_POS) & 0xff) #define GET_ACTION_NUM(n) ((n >> ACTION_POS) & 0xff) #define TEST_EXECUTE_FUNC 1 #define TEST_RETURN_RESULT 2 #define INVALID_HANDLE 0x1234DEAD #define VAL_NVMEM_BLOCK_SIZE 4 #define VAL_NVMEM_OFFSET(nvmem_idx) (nvmem_idx * VAL_NVMEM_BLOCK_SIZE) #define UART_INIT_SIGN 0xff #define UART_PRINT_SIGN 0xfe #define TEST_PANIC() \ do { \ } while(1) #define TEST_ASSERT_EQUAL(arg1, arg2, checkpoint) \ do { \ if ((arg1) != arg2) \ { \ val->print(PRINT_ERROR, "\tFailed at Checkpoint: %d\n", checkpoint); \ val->print(PRINT_ERROR, "\tActual: %d\n", arg1); \ val->print(PRINT_ERROR, "\tExpected: %d\n", arg2); \ return 1; \ } \ } while (0) #define TEST_ASSERT_DUAL(arg1, status1, status2, checkpoint) \ do { \ if ((arg1) != status1 && (arg1) != status2) \ { \ val->print(PRINT_ERROR, "\tFailed at Checkpoint: %d\n", checkpoint); \ val->print(PRINT_ERROR, "\tActual: %d\n", arg1); \ val->print(PRINT_ERROR, "\tExpected: %d", status1); \ val->print(PRINT_ERROR, "or %d\n", status2); \ return 1; \ } \ } while (0) #define TEST_ASSERT_NOT_EQUAL(arg1, arg2, checkpoint) \ do { \ if ((arg1) == arg2) \ { \ val->print(PRINT_ERROR, "\tFailed at Checkpoint: %d\n", checkpoint); \ val->print(PRINT_ERROR, "\tValue: %d\n", arg1); \ return 1; \ } \ } while (0) #define TEST_ASSERT_MEMCMP(buf1, buf2, size, checkpoint) \ do { \ if (memcmp(buf1, buf2, size)) \ { \ val->print(PRINT_ERROR, "\tFailed at Checkpoint: %d : ", checkpoint); \ val->print(PRINT_ERROR, "Unequal data in compared buffers\n", 0); \ return 1; \ } \ } while (0) /* enums */ typedef enum { CALLER_NONSECURE = 0x0, CALLER_SECURE = 0x1, } caller_security_t; typedef enum { TEST_ISOLATION_L1 = 0x1, TEST_ISOLATION_L2 = 0x2, TEST_ISOLATION_L3 = 0x3, } test_isolation_level_t; typedef enum { BOOT_UNKNOWN = 0x1, BOOT_NOT_EXPECTED = 0x2, BOOT_EXPECTED_NS = 0x3, BOOT_EXPECTED_S = 0x4, BOOT_EXPECTED_BUT_FAILED = 0x5, BOOT_EXPECTED_CRYPTO = 0x6, } boot_state_t; typedef enum { NV_BOOT = 0x0, NV_TEST_ID_PREVIOUS = 0x1, NV_TEST_ID_CURRENT = 0x2, NV_TEST_CNT = 0x3, } nvmem_index_t; /* enums to report test sub-state */ typedef enum { VAL_STATUS_SUCCESS = 0x0, VAL_STATUS_INVALID = 0x10, VAL_STATUS_ERROR = 0x11, VAL_STATUS_NOT_FOUND = 0x12, VAL_STATUS_LOAD_ERROR = 0x13, VAL_STATUS_INSUFFICIENT_SIZE = 0x14, VAL_STATUS_CONNECTION_FAILED = 0x15, VAL_STATUS_CALL_FAILED = 0x16, VAL_STATUS_READ_FAILED = 0x17, VAL_STATUS_WRITE_FAILED = 0x18, VAL_STATUS_ISOLATION_LEVEL_NOT_SUPP = 0x19, VAL_STATUS_INIT_FAILED = 0x1A, VAL_STATUS_SPM_FAILED = 0x1B, VAL_STATUS_SPM_UNEXPECTED_BEH = 0x1C, VAL_STATUS_FRAMEWORK_VERSION_FAILED = 0x1D, VAL_STATUS_VERSION_API_FAILED = 0x1E, VAL_STATUS_INVALID_HANDLE = 0x1F, VAL_STATUS_INVALID_MSG_TYPE = 0x20, VAL_STATUS_WRONG_IDENTITY = 0x21, VAL_STATUS_MSG_INSIZE_FAILED = 0x22, VAL_STATUS_MSG_OUTSIZE_FAILED = 0x23, VAL_STATUS_SKIP_FAILED = 0x24, VAL_STATUS_CRYPTO_FAILURE = 0x25, VAL_STATUS_INVALID_SIZE = 0x26, VAL_STATUS_DATA_MISMATCH = 0x27, VAL_STATUS_BOOT_EXPECTED_BUT_FAILED = 0x28, VAL_STATUS_INIT_ALREADY_DONE = 0x29, VAL_STATUS_HEAP_NOT_AVAILABLE = 0x2A, VAL_STATUS_UNSUPPORTED = 0x2B, VAL_STATUS_ERROR_MAX = INT_MAX, } val_status_t; /* verbosity enums */ typedef enum { PRINT_INFO = 1, PRINT_DEBUG = 2, PRINT_TEST = 3, PRINT_WARN = 4, PRINT_ERROR = 5, PRINT_ALWAYS = 9 } print_verbosity_t; /* Interrupt test function id enums */ typedef enum { TEST_PSA_EOI_WITH_NON_INTR_SIGNAL = 1, TEST_PSA_EOI_WITH_MULTIPLE_SIGNALS = 2, TEST_PSA_EOI_WITH_UNASSERTED_SIGNAL = 3, TEST_INTR_SERVICE = 4, } test_intr_fn_id_t; /* typedef's */ typedef struct { boot_state_t state; } boot_t; typedef struct { uint32_t pass_cnt:8; uint32_t skip_cnt:8; uint32_t fail_cnt:8; uint32_t sim_error_cnt:8; } test_count_t; typedef struct { uint16_t test_num; uint8_t block_num; } test_info_t; /* struture to capture test state */ typedef struct { uint16_t reserved; uint8_t state; uint8_t status; } test_status_buffer_t; typedef int32_t (*client_test_t)(caller_security_t caller); typedef int32_t (*server_test_t)(void); #endif /* VAL_COMMON_H */
0.996094
high
platform/vendor_bsp/nationz/Nationstech.N32G45x_Library.0.4.0/n32g45x_std_periph_driver/inc/n32g45x_usart.h
rceet/TencentOS-tiny
4
903361
<gh_stars>1-10 /***************************************************************************** * Copyright (c) 2019, Nations Technologies Inc. * * All rights reserved. * **************************************************************************** * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the disclaimer below. * * Nations' name may not be used to endorse or promote products derived from * this software without specific prior written permission. * * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY NATIONS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * DISCLAIMED. IN NO EVENT SHALL NATIONS 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. * ****************************************************************************/ /** * @file n32g45x_usart.h * @author Nations Solution Team * @version v1.0.0 * * @copyright Copyright (c) 2019, Nations Technologies Inc. All rights reserved. */ #ifndef __N32G45X_USART_H__ #define __N32G45X_USART_H__ #ifdef __cplusplus extern "C" { #endif #include "n32g45x.h" /** @addtogroup N32G45X_StdPeriph_Driver * @{ */ /** @addtogroup USART * @{ */ /** @addtogroup USART_Exported_Types * @{ */ /** * @brief USART Init Structure definition */ typedef struct { uint32_t BaudRate; /*!< This member configures the USART communication baud rate. The baud rate is computed using the following formula: - IntegerDivider = ((PCLKx) / (16 * (USART_InitStruct->BaudRate))) - FractionalDivider = ((IntegerDivider - ((u32) IntegerDivider)) * 16) + 0.5 */ uint16_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. This parameter can be a value of @ref USART_Word_Length */ uint16_t StopBits; /*!< Specifies the number of stop bits transmitted. This parameter can be a value of @ref USART_Stop_Bits */ uint16_t Parity; /*!< Specifies the parity mode. This parameter can be a value of @ref Parity @note When parity is enabled, the computed parity is inserted at the MSB position of the transmitted data (9th bit when the word length is set to 9 data bits; 8th bit when the word length is set to 8 data bits). */ uint16_t Mode; /*!< Specifies wether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref Mode */ uint16_t HardwareFlowControl; /*!< Specifies wether the hardware flow control mode is enabled or disabled. This parameter can be a value of @ref USART_Hardware_Flow_Control */ } USART_InitType; /** * @brief USART Clock Init Structure definition */ typedef struct { uint16_t Clock; /*!< Specifies whether the USART clock is enabled or disabled. This parameter can be a value of @ref Clock */ uint16_t Polarity; /*!< Specifies the steady state value of the serial clock. This parameter can be a value of @ref USART_Clock_Polarity */ uint16_t Phase; /*!< Specifies the clock transition on which the bit capture is made. This parameter can be a value of @ref USART_Clock_Phase */ uint16_t LastBit; /*!< Specifies whether the clock pulse corresponding to the last transmitted data bit (MSB) has to be output on the SCLK pin in synchronous mode. This parameter can be a value of @ref USART_Last_Bit */ } USART_ClockInitType; /** * @} */ /** @addtogroup USART_Exported_Constants * @{ */ #define IS_USART_ALL_PERIPH(PERIPH) \ (((PERIPH) == USART1) || ((PERIPH) == USART2) || ((PERIPH) == USART3) || ((PERIPH) == UART4) \ || ((PERIPH) == UART5) || ((PERIPH) == UART6) || ((PERIPH) == UART7)) #define IS_USART_123_PERIPH(PERIPH) (((PERIPH) == USART1) || ((PERIPH) == USART2) || ((PERIPH) == USART3)) #define IS_USART_1234_PERIPH(PERIPH) \ (((PERIPH) == USART1) || ((PERIPH) == USART2) || ((PERIPH) == USART3) || ((PERIPH) == UART4)) /** @addtogroup USART_Word_Length * @{ */ #define USART_WL_8B ((uint16_t)0x0000) #define USART_WL_9B ((uint16_t)0x1000) #define IS_USART_WORD_LENGTH(LENGTH) (((LENGTH) == USART_WL_8B) || ((LENGTH) == USART_WL_9B)) /** * @} */ /** @addtogroup USART_Stop_Bits * @{ */ #define USART_STPB_1 ((uint16_t)0x0000) #define USART_STPB_0_5 ((uint16_t)0x1000) #define USART_STPB_2 ((uint16_t)0x2000) #define USART_STPB_1_5 ((uint16_t)0x3000) #define IS_USART_STOPBITS(STOPBITS) \ (((STOPBITS) == USART_STPB_1) || ((STOPBITS) == USART_STPB_0_5) || ((STOPBITS) == USART_STPB_2) \ || ((STOPBITS) == USART_STPB_1_5)) /** * @} */ /** @addtogroup Parity * @{ */ #define USART_PE_NO ((uint16_t)0x0000) #define USART_PE_EVEN ((uint16_t)0x0400) #define USART_PE_ODD ((uint16_t)0x0600) #define IS_USART_PARITY(PARITY) (((PARITY) == USART_PE_NO) || ((PARITY) == USART_PE_EVEN) || ((PARITY) == USART_PE_ODD)) /** * @} */ /** @addtogroup Mode * @{ */ #define USART_MODE_RX ((uint16_t)0x0004) #define USART_MODE_TX ((uint16_t)0x0008) #define IS_USART_MODE(MODE) ((((MODE) & (uint16_t)0xFFF3) == 0x00) && ((MODE) != (uint16_t)0x00)) /** * @} */ /** @addtogroup USART_Hardware_Flow_Control * @{ */ #define USART_HFCTRL_NONE ((uint16_t)0x0000) #define USART_HFCTRL_RTS ((uint16_t)0x0100) #define USART_HFCTRL_CTS ((uint16_t)0x0200) #define USART_HFCTRL_RTS_CTS ((uint16_t)0x0300) #define IS_USART_HARDWARE_FLOW_CONTROL(CONTROL) \ (((CONTROL) == USART_HFCTRL_NONE) || ((CONTROL) == USART_HFCTRL_RTS) || ((CONTROL) == USART_HFCTRL_CTS) \ || ((CONTROL) == USART_HFCTRL_RTS_CTS)) /** * @} */ /** @addtogroup Clock * @{ */ #define USART_CLK_DISABLE ((uint16_t)0x0000) #define USART_CLK_ENABLE ((uint16_t)0x0800) #define IS_USART_CLOCK(CLOCK) (((CLOCK) == USART_CLK_DISABLE) || ((CLOCK) == USART_CLK_ENABLE)) /** * @} */ /** @addtogroup USART_Clock_Polarity * @{ */ #define USART_CLKPOL_LOW ((uint16_t)0x0000) #define USART_CLKPOL_HIGH ((uint16_t)0x0400) #define IS_USART_CPOL(CPOL) (((CPOL) == USART_CLKPOL_LOW) || ((CPOL) == USART_CLKPOL_HIGH)) /** * @} */ /** @addtogroup USART_Clock_Phase * @{ */ #define USART_CLKPHA_1EDGE ((uint16_t)0x0000) #define USART_CLKPHA_2EDGE ((uint16_t)0x0200) #define IS_USART_CPHA(CPHA) (((CPHA) == USART_CLKPHA_1EDGE) || ((CPHA) == USART_CLKPHA_2EDGE)) /** * @} */ /** @addtogroup USART_Last_Bit * @{ */ #define USART_CLKLB_DISABLE ((uint16_t)0x0000) #define USART_CLKLB_ENABLE ((uint16_t)0x0100) #define IS_USART_LASTBIT(LASTBIT) (((LASTBIT) == USART_CLKLB_DISABLE) || ((LASTBIT) == USART_CLKLB_ENABLE)) /** * @} */ /** @addtogroup USART_Interrupt_definition * @{ */ #define USART_INT_PEF ((uint16_t)0x0028) #define USART_INT_TXDE ((uint16_t)0x0727) #define USART_INT_TXC ((uint16_t)0x0626) #define USART_INT_RXDNE ((uint16_t)0x0525) #define USART_INT_IDLEF ((uint16_t)0x0424) #define USART_INT_LINBD ((uint16_t)0x0846) #define USART_INT_CTSF ((uint16_t)0x096A) #define USART_INT_ERRF ((uint16_t)0x0060) #define USART_INT_OREF ((uint16_t)0x0360) #define USART_INT_NEF ((uint16_t)0x0260) #define USART_INT_FEF ((uint16_t)0x0160) #define IS_USART_CFG_INT(IT) \ (((IT) == USART_INT_PEF) || ((IT) == USART_INT_TXDE) || ((IT) == USART_INT_TXC) || ((IT) == USART_INT_RXDNE) \ || ((IT) == USART_INT_IDLEF) || ((IT) == USART_INT_LINBD) || ((IT) == USART_INT_CTSF) \ || ((IT) == USART_INT_ERRF)) #define IS_USART_GET_INT(IT) \ (((IT) == USART_INT_PEF) || ((IT) == USART_INT_TXDE) || ((IT) == USART_INT_TXC) || ((IT) == USART_INT_RXDNE) \ || ((IT) == USART_INT_IDLEF) || ((IT) == USART_INT_LINBD) || ((IT) == USART_INT_CTSF) || ((IT) == USART_INT_OREF) \ || ((IT) == USART_INT_NEF) || ((IT) == USART_INT_FEF)) #define IS_USART_CLR_INT(IT) \ (((IT) == USART_INT_TXC) || ((IT) == USART_INT_RXDNE) || ((IT) == USART_INT_LINBD) || ((IT) == USART_INT_CTSF)) /** * @} */ /** @addtogroup USART_DMA_Requests * @{ */ #define USART_DMAREQ_TX ((uint16_t)0x0080) #define USART_DMAREQ_RX ((uint16_t)0x0040) #define IS_USART_DMAREQ(DMAREQ) ((((DMAREQ) & (uint16_t)0xFF3F) == 0x00) && ((DMAREQ) != (uint16_t)0x00)) /** * @} */ /** @addtogroup USART_WakeUp_methods * @{ */ #define USART_WUM_IDLELINE ((uint16_t)0x0000) #define USART_WUM_ADDRMASK ((uint16_t)0x0800) #define IS_USART_WAKEUP(WAKEUP) (((WAKEUP) == USART_WUM_IDLELINE) || ((WAKEUP) == USART_WUM_ADDRMASK)) /** * @} */ /** @addtogroup USART_LIN_Break_Detection_Length * @{ */ #define USART_LINBDL_10B ((uint16_t)0x0000) #define USART_LINBDL_11B ((uint16_t)0x0020) #define IS_USART_LIN_BREAK_DETECT_LENGTH(LENGTH) (((LENGTH) == USART_LINBDL_10B) || ((LENGTH) == USART_LINBDL_11B)) /** * @} */ /** @addtogroup USART_IrDA_Low_Power * @{ */ #define USART_IRDAMODE_LOWPPWER ((uint16_t)0x0004) #define USART_IRDAMODE_NORMAL ((uint16_t)0x0000) #define IS_USART_IRDA_MODE(MODE) (((MODE) == USART_IRDAMODE_LOWPPWER) || ((MODE) == USART_IRDAMODE_NORMAL)) /** * @} */ /** @addtogroup USART_Flags * @{ */ #define USART_FLAG_CTSF ((uint16_t)0x0200) #define USART_FLAG_LINBD ((uint16_t)0x0100) #define USART_FLAG_TXDE ((uint16_t)0x0080) #define USART_FLAG_TXC ((uint16_t)0x0040) #define USART_FLAG_RXDNE ((uint16_t)0x0020) #define USART_FLAG_IDLEF ((uint16_t)0x0010) #define USART_FLAG_OREF ((uint16_t)0x0008) #define USART_FLAG_NEF ((uint16_t)0x0004) #define USART_FLAG_FEF ((uint16_t)0x0002) #define USART_FLAG_PEF ((uint16_t)0x0001) #define IS_USART_FLAG(FLAG) \ (((FLAG) == USART_FLAG_PEF) || ((FLAG) == USART_FLAG_TXDE) || ((FLAG) == USART_FLAG_TXC) \ || ((FLAG) == USART_FLAG_RXDNE) || ((FLAG) == USART_FLAG_IDLEF) || ((FLAG) == USART_FLAG_LINBD) \ || ((FLAG) == USART_FLAG_CTSF) || ((FLAG) == USART_FLAG_OREF) || ((FLAG) == USART_FLAG_NEF) \ || ((FLAG) == USART_FLAG_FEF)) #define IS_USART_CLEAR_FLAG(FLAG) ((((FLAG) & (uint16_t)0xFC9F) == 0x00) && ((FLAG) != (uint16_t)0x00)) #define IS_USART_PERIPH_FLAG(PERIPH, USART_FLAG) \ ((((*(uint32_t*)&(PERIPH)) != UART4_BASE) && ((*(uint32_t*)&(PERIPH)) != UART5_BASE)) \ || ((USART_FLAG) != USART_FLAG_CTSF)) #define IS_USART_BAUDRATE(BAUDRATE) (((BAUDRATE) > 0) && ((BAUDRATE) < 0x0044AA21)) #define IS_USART_ADDRESS(ADDRESS) ((ADDRESS) <= 0xF) #define IS_USART_DATA(DATA) ((DATA) <= 0x1FF) /** * @} */ /** * @} */ /** @addtogroup USART_Exported_Macros * @{ */ /** * @} */ /** @addtogroup USART_Exported_Functions * @{ */ void USART_DeInit(USART_Module* USARTx); void USART_Init(USART_Module* USARTx, USART_InitType* USART_InitStruct); void USART_StructInit(USART_InitType* USART_InitStruct); void USART_ClockInit(USART_Module* USARTx, USART_ClockInitType* USART_ClockInitStruct); void USART_ClockStructInit(USART_ClockInitType* USART_ClockInitStruct); void USART_Enable(USART_Module* USARTx, FunctionalState Cmd); void USART_ConfigInt(USART_Module* USARTx, uint16_t USART_INT, FunctionalState Cmd); void USART_EnableDMA(USART_Module* USARTx, uint16_t USART_DMAReq, FunctionalState Cmd); void USART_SetAddr(USART_Module* USARTx, uint8_t USART_Addr); void USART_ConfigWakeUpMode(USART_Module* USARTx, uint16_t USART_WakeUpMode); void USART_EnableRcvWakeUp(USART_Module* USARTx, FunctionalState Cmd); void USART_ConfigLINBreakDetectLength(USART_Module* USARTx, uint16_t USART_LINBreakDetectLength); void USART_EnableLIN(USART_Module* USARTx, FunctionalState Cmd); void USART_SendData(USART_Module* USARTx, uint16_t Data); uint16_t USART_ReceiveData(USART_Module* USARTx); void USART_SendBreak(USART_Module* USARTx); void USART_SetGuardTime(USART_Module* USARTx, uint8_t USART_GuardTime); void USART_SetPrescaler(USART_Module* USARTx, uint8_t USART_Prescaler); void USART_EnableSmartCard(USART_Module* USARTx, FunctionalState Cmd); void USART_SetSmartCardNACK(USART_Module* USARTx, FunctionalState Cmd); void USART_EnableHalfDuplex(USART_Module* USARTx, FunctionalState Cmd); void USART_ConfigOverSampling8(USART_Module* USARTx, FunctionalState Cmd); void USART_ConfigOneBitMethod(USART_Module* USARTx, FunctionalState Cmd); void USART_ConfigIrDAMode(USART_Module* USARTx, uint16_t USART_IrDAMode); void USART_EnableIrDA(USART_Module* USARTx, FunctionalState Cmd); FlagStatus USART_GetFlagStatus(USART_Module* USARTx, uint16_t USART_FLAG); void USART_ClrFlag(USART_Module* USARTx, uint16_t USART_FLAG); INTStatus USART_GetIntStatus(USART_Module* USARTx, uint16_t USART_INT); void USART_ClrIntPendingBit(USART_Module* USARTx, uint16_t USART_INT); #ifdef __cplusplus } #endif #endif /* __N32G45X_USART_H__ */ /** * @} */ /** * @} */ /** * @} */
0.996094
high
src/init.h
tradecraftio/tradecraft
10
903873
// Copyright (c) 2009-2010 <NAME> // Copyright (c) 2009-2018 The Bitcoin Core developers // Copyright (c) 2011-2021 The Freicoin Developers // // This program is free software: you can redistribute it and/or modify it under // the terms of version 3 of the GNU Affero General Public License as published // by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more // details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #ifndef FREICOIN_INIT_H #define FREICOIN_INIT_H #include <memory> #include <string> #include <util/system.h> namespace interfaces { class Chain; class ChainClient; } // namespace interfaces //! Pointers to interfaces used during init and destroyed on shutdown. struct InitInterfaces { std::unique_ptr<interfaces::Chain> chain; std::vector<std::unique_ptr<interfaces::ChainClient>> chain_clients; }; namespace boost { class thread_group; } // namespace boost /** Interrupt threads */ void Interrupt(); void Shutdown(InitInterfaces& interfaces); //!Initialize the logging infrastructure void InitLogging(); //!Parameter interaction: change current parameters depending on various rules void InitParameterInteraction(); /** Initialize freicoin: Basic context setup. * @note This can be done before daemonization. Do not call Shutdown() if this function fails. * @pre Parameters should be parsed and config file should be read. */ bool AppInitBasicSetup(); /** * Initialization: parameter interaction. * @note This can be done before daemonization. Do not call Shutdown() if this function fails. * @pre Parameters should be parsed and config file should be read, AppInitBasicSetup should have been called. */ bool AppInitParameterInteraction(); /** * Initialization sanity checks: ecc init, sanity checks, dir lock. * @note This can be done before daemonization. Do not call Shutdown() if this function fails. * @pre Parameters should be parsed and config file should be read, AppInitParameterInteraction should have been called. */ bool AppInitSanityChecks(); /** * Lock freicoin data directory. * @note This should only be done after daemonization. Do not call Shutdown() if this function fails. * @pre Parameters should be parsed and config file should be read, AppInitSanityChecks should have been called. */ bool AppInitLockDataDirectory(); /** * Freicoin main initialization. * @note This should only be done after daemonization. Call Shutdown() if this function fails. * @pre Parameters should be parsed and config file should be read, AppInitLockDataDirectory should have been called. */ bool AppInitMain(InitInterfaces& interfaces); /** * Setup the arguments for gArgs */ void SetupServerArgs(); /** Returns licensing information (for -version) */ std::string LicenseInfo(); #endif // FREICOIN_INIT_H
0.996094
high
src/getput.c
skawamoto0/FFFTP-Classic
0
904385
<reponame>skawamoto0/FFFTP-Classic<filename>src/getput.c /*============================================================================= * * ダウンロード/アップロード * =============================================================================== / Copyright (C) 1997-2007 Sota. All rights reserved. / / Redistribution and use in source and binary forms, with or without / modification, are permitted provided that the following conditions / are met: / / 1. Redistributions of source code must retain the above copyright / notice, this list of conditions and the following disclaimer. / 2. Redistributions in binary form must reproduce the above copyright / notice, this list of conditions and the following disclaimer in the / documentation and/or other materials provided with the distribution. / / THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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. /============================================================================*/ /* このソースは一部、WS_FTP Version 93.12.05 のソースを参考にしました。 */ /* スレッドの作成/終了に関して、樋口殿作成のパッチを組み込みました。 */ /* 一部、高速化のためのコード追加 by H.Shirouzu at 2002/10/02 */ #define STRICT #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <mbstring.h> #include <time.h> // ゾーンID設定追加 #undef _WIN32_IE #define _WIN32_IE _WIN32_IE_IE60SP2 // IPv6対応 //#include <winsock.h> #include <winsock2.h> #include <windowsx.h> #include <commctrl.h> #include <process.h> #include "common.h" #include "resource.h" #define SET_BUFFER_SIZE /* Add by H.Shirouzu at 2002/10/02 */ #undef BUFSIZE #define BUFSIZE (32 * 1024) #define SOCKBUF_SIZE (256 * 1024) /* End */ #ifdef DISABLE_TRANSFER_NETWORK_BUFFERS #undef BUFSIZE #define BUFSIZE (64 * 1024) // RWIN値以下で充分な大きさが望ましいと思われる。 #undef SET_BUFFER_SIZE #endif #define TIMER_DISPLAY 1 /* 表示更新用タイマのID */ #define DISPLAY_TIMING 500 /* 表示更新時間 0.5秒 */ #define ERR_MSG_LEN 1024 /* 削除確認ダイアログの情報 */ typedef struct { int Cur; TRANSPACKET *Pkt; } MIRRORDELETEINFO; /*===== プロトタイプ =====*/ static void DispTransPacket(TRANSPACKET *Pkt); static void EraseTransFileList(void); static ULONG WINAPI TransferThread(void *Dummy); static int MakeNonFullPath(TRANSPACKET *Pkt, char *CurDir, char *Tmp); // ミラーリング設定追加 static int SetDownloadedFileTime(TRANSPACKET *Pkt); static int DownloadNonPassive(TRANSPACKET *Pkt, int *CancelCheckWork); static int DownloadPassive(TRANSPACKET *Pkt, int *CancelCheckWork); static int DownloadFile(TRANSPACKET *Pkt, SOCKET dSkt, int CreateMode, int *CancelCheckWork); static void DispDownloadFinishMsg(TRANSPACKET *Pkt, int iRetCode); // 再転送対応 //static int DispUpDownErrDialog(int ResID, HWND hWnd, char *Fname); static int DispUpDownErrDialog(int ResID, HWND hWnd, TRANSPACKET *Pkt); // 64ビット対応 //static BOOL CALLBACK UpDownErrorDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); static INT_PTR CALLBACK UpDownErrorDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); static int SetDownloadResume(TRANSPACKET *Pkt, int ProcMode, LONGLONG Size, int *Mode, int *CancelCheckWork); // 64ビット対応 //static BOOL CALLBACK NoResumeWndProc(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam); static INT_PTR CALLBACK NoResumeWndProc(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam); static int DoUpload(SOCKET cSkt, TRANSPACKET *Pkt); static int UploadNonPassive(TRANSPACKET *Pkt); static int UploadPassive(TRANSPACKET *Pkt); static int UploadFile(TRANSPACKET *Pkt, SOCKET dSkt); // 同時接続対応 //static int TermCodeConvAndSend(TERMCODECONVINFO *tInfo, SOCKET Skt, char *Data, int Size, int Ascii); static int TermCodeConvAndSend(TERMCODECONVINFO *tInfo, SOCKET Skt, char *Data, int Size, int Ascii, int *CancelCheckWork); static void DispUploadFinishMsg(TRANSPACKET *Pkt, int iRetCode); static int SetUploadResume(TRANSPACKET *Pkt, int ProcMode, LONGLONG Size, int *Mode); static LRESULT CALLBACK TransDlgProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam); static void DispTransferStatus(HWND hWnd, int End, TRANSPACKET *Pkt); static void DispTransFileInfo(TRANSPACKET *Pkt, char *Title, int SkipButton, int Info); // IPv6対応 //static int GetAdrsAndPort(char *Str, char *Adrs, int *Port, int Max); static int GetAdrsAndPort(SOCKET Skt, char *Str, char *Adrs, int *Port, int Max); static int GetAdrsAndPortIPv4(SOCKET Skt, char *Str, char *Adrs, int *Port, int Max); static int GetAdrsAndPortIPv6(SOCKET Skt, char *Str, char *Adrs, int *Port, int Max); static int IsSpecialDevice(char *Fname); static int MirrorDelNotify(int Cur, int Notify, TRANSPACKET *Pkt); // 64ビット対応 //static BOOL CALLBACK MirrorDeleteDialogCallBack(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam); static INT_PTR CALLBACK MirrorDeleteDialogCallBack(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam); static void SetErrorMsg(char *fmt, ...); // 同時接続対応 static char* GetErrMsg(); /*===== ローカルなワーク =====*/ // 同時接続対応 //static HANDLE hTransferThread; static HANDLE hTransferThread[MAX_DATA_CONNECTION]; static int fTransferThreadExit = FALSE; static HANDLE hRunMutex; /* 転送スレッド実行ミューテックス */ static HANDLE hListAccMutex; /* 転送ファイルアクセス用ミューテックス */ static int TransFiles = 0; /* 転送待ちファイル数 */ static TRANSPACKET *TransPacketBase = NULL; /* 転送ファイルリスト */ // 同時接続対応 static TRANSPACKET *NextTransPacketBase = NULL; // 同時接続対応 //static int Canceled; /* 中止フラグ YES/NO */ static int Canceled[MAX_DATA_CONNECTION]; /* 中止フラグ YES/NO */ static int ClearAll; /* 全て中止フラグ YES/NO */ static int ForceAbort; /* 転送中止フラグ */ /* このフラグはスレッドを終了させるときに使う */ // 同時接続対応 //static LONGLONG AllTransSizeNow; /* 今回の転送で転送したサイズ */ //static time_t TimeStart; /* 転送開始時間 */ static LONGLONG AllTransSizeNow[MAX_DATA_CONNECTION]; /* 今回の転送で転送したサイズ */ static time_t TimeStart[MAX_DATA_CONNECTION]; /* 転送開始時間 */ static int KeepDlg = NO; /* 転送中ダイアログを消さないかどうか (YES/NO) */ static int MoveToForeground = NO; /* ウインドウを前面に移動するかどうか (YES/NO) */ // 同時接続対応 //static char CurDir[FMAX_PATH+1] = { "" }; static char CurDir[MAX_DATA_CONNECTION][FMAX_PATH+1]; // 同時接続対応 //static char ErrMsg[ERR_MSG_LEN+7]; static char ErrMsg[MAX_DATA_CONNECTION+1][ERR_MSG_LEN+7]; static DWORD ErrMsgThreadId[MAX_DATA_CONNECTION+1]; static HANDLE hErrMsgMutex; // 同時接続対応 static int WaitForMainThread = NO; // 再転送対応 static int TransferErrorMode = EXIST_OVW; static int TransferErrorNotify = NO; // タスクバー進捗表示 static LONGLONG TransferSizeLeft = 0; static LONGLONG TransferSizeTotal = 0; static int TransferErrorDisplay = 0; // ゾーンID設定追加 IZoneIdentifier* pZoneIdentifier; IPersistFile* pPersistFile; /*===== 外部参照 =====*/ /* 設定値 */ extern int SaveTimeStamp; extern int RmEOF; // extern int TimeOut; extern int FwallType; extern int MirUpDelNotify; extern int MirDownDelNotify; extern int FolderAttr; extern int FolderAttrNum; // 同時接続対応 extern int SendQuit; // 自動切断対策 extern time_t LastDataConnectionTime; // ゾーンID設定追加 extern int MarkAsInternet; /*----- ファイル転送スレッドを起動する ---------------------------------------- * * Parameter * なし * * Return Value * なし *----------------------------------------------------------------------------*/ int MakeTransferThread(void) { DWORD dwID; int i; hListAccMutex = CreateMutex( NULL, FALSE, NULL ); hRunMutex = CreateMutex( NULL, TRUE, NULL ); // 同時接続対応 hErrMsgMutex = CreateMutex( NULL, FALSE, NULL ); ClearAll = NO; ForceAbort = NO; fTransferThreadExit = FALSE; // 同時接続対応 // hTransferThread = (HANDLE)_beginthreadex(NULL, 0, TransferThread, 0, 0, &dwID); // if (hTransferThread == NULL) // return(FFFTP_FAIL); /* XXX */ for(i = 0; i < MAX_DATA_CONNECTION; i++) { hTransferThread[i] = (HANDLE)_beginthreadex(NULL, 0, TransferThread, (void*)i, 0, &dwID); if(hTransferThread[i] == NULL) return FFFTP_FAIL; } return(FFFTP_SUCCESS); } /*----- ファイル転送スレッドを終了する ---------------------------------------- * * Parameter * なし * * Return Value * なし *----------------------------------------------------------------------------*/ void CloseTransferThread(void) { int i; // 同時接続対応 // Canceled = YES; for(i = 0; i < MAX_DATA_CONNECTION; i++) Canceled[i] = YES; ClearAll = YES; // 同時接続対応 // ForceAbort = YES; fTransferThreadExit = TRUE; // 同時接続対応 // while(WaitForSingleObject(hTransferThread, 10) == WAIT_TIMEOUT) // { // BackgrndMessageProc(); // Canceled = YES; // } // CloseHandle(hTransferThread); for(i = 0; i < MAX_DATA_CONNECTION; i++) { while(WaitForSingleObject(hTransferThread[i], 10) == WAIT_TIMEOUT) { BackgrndMessageProc(); Canceled[i] = YES; } CloseHandle(hTransferThread[i]); } ReleaseMutex( hRunMutex ); CloseHandle( hListAccMutex ); CloseHandle( hRunMutex ); // 同時接続対応 CloseHandle( hErrMsgMutex ); return; } // 同時接続対応 void AbortAllTransfer() { int i; while(TransPacketBase != NULL) { for(i = 0; i < MAX_DATA_CONNECTION; i++) Canceled[i] = YES; ClearAll = YES; if(BackgrndMessageProc() == YES) break; Sleep(10); } ClearAll = NO; } /*----- 転送するファイル情報をリストに追加する -------------------------------- * * Parameter * TRANSPACKET *Pkt : 転送ファイル情報 * TRANSPACKET **Base : リストの先頭 * * Return Value * int ステータス * FFFTP_SUCCESS/FFFTP_FAIL *----------------------------------------------------------------------------*/ int AddTmpTransFileList(TRANSPACKET *Pkt, TRANSPACKET **Base) { TRANSPACKET *Pos; TRANSPACKET *Prev; int Sts; Sts = FFFTP_FAIL; if((Pos = malloc(sizeof(TRANSPACKET))) != NULL) { memcpy(Pos, Pkt, sizeof(TRANSPACKET)); Pos->Next = NULL; if(*Base == NULL) *Base = Pos; else { Prev = *Base; while(Prev->Next != NULL) Prev = Prev->Next; Prev->Next = Pos; } Sts = FFFTP_SUCCESS; } return(Sts); } /*----- 転送するファイル情報リストをクリアする -------------------------------- * * Parameter * TRANSPACKET **Base : リストの先頭 * * Return Value * なし *----------------------------------------------------------------------------*/ void EraseTmpTransFileList(TRANSPACKET **Base) { TRANSPACKET *Pos; TRANSPACKET *Next; Pos = *Base; while(Pos != NULL) { Next = Pos->Next; free(Pos); Pos = Next; } *Base = NULL; return; } /*----- 転送するファイル情報リストから1つの情報を取り除く -------------------- * * Parameter * TRANSPACKET *Pkt : 転送ファイル情報 * TRANSPACKET **Base : リストの先頭 * * Return Value * int ステータス * FFFTP_SUCCESS/FFFTP_FAIL *----------------------------------------------------------------------------*/ int RemoveTmpTransFileListItem(TRANSPACKET **Base, int Num) { TRANSPACKET *Pos; TRANSPACKET *Prev; int Sts; Sts = FFFTP_FAIL; Pos = *Base; if(Num == 0) { *Base = Pos->Next; free(Pos); Sts = FFFTP_SUCCESS; } else { while(Pos != NULL) { Prev = Pos; Pos = Pos->Next; if(--Num == 0) { Prev->Next = Pos->Next; free(Pos); Sts = FFFTP_SUCCESS; break; } } } return(Sts); } /*----- 転送するファイル情報を転送ファイルリストに登録する -------------------- * * Parameter * TRANSPACKET *Pkt : 転送ファイル情報 * * Return Value * なし *----------------------------------------------------------------------------*/ void AddTransFileList(TRANSPACKET *Pkt) { // 同時接続対応 TRANSPACKET *Pos; DispTransPacket(Pkt); // 同時接続対応 // WaitForSingleObject(hListAccMutex, INFINITE); while(WaitForSingleObject(hListAccMutex, 0) == WAIT_TIMEOUT) { WaitForMainThread = YES; BackgrndMessageProc(); Sleep(1); } // 同時接続対応 Pos = TransPacketBase; if(Pos != NULL) { while(Pos->Next != NULL) Pos = Pos->Next; } if(AddTmpTransFileList(Pkt, &TransPacketBase) == FFFTP_SUCCESS) { if((strncmp(Pkt->Cmd, "RETR", 4) == 0) || (strncmp(Pkt->Cmd, "STOR", 4) == 0)) { TransFiles++; // タスクバー進捗表示 TransferSizeLeft += Pkt->Size; TransferSizeTotal += Pkt->Size; PostMessage(GetMainHwnd(), WM_CHANGE_COND, 0, 0); } } // 同時接続対応 if(NextTransPacketBase == NULL) { if(Pos) NextTransPacketBase = Pos->Next; else NextTransPacketBase = TransPacketBase; } ReleaseMutex(hListAccMutex); // 同時接続対応 WaitForMainThread = NO; return; } // バグ対策 void AddNullTransFileList() { TRANSPACKET Pkt; memset(&Pkt, 0, sizeof(TRANSPACKET)); strcpy(Pkt.Cmd, "NULL"); AddTransFileList(&Pkt); } /*----- 転送ファイル情報を転送ファイルリストに追加する ------------------------ * * Parameter * TRANSPACKET *Pkt : 転送ファイル情報 * TRANSPACKET **Base : リストの先頭 * * Return Value * なし * * Note * Pkt自体をリストに連結する *----------------------------------------------------------------------------*/ void AppendTransFileList(TRANSPACKET *Pkt) { TRANSPACKET *Pos; // 同時接続対応 // WaitForSingleObject(hListAccMutex, INFINITE); while(WaitForSingleObject(hListAccMutex, 0) == WAIT_TIMEOUT) { WaitForMainThread = YES; BackgrndMessageProc(); Sleep(1); } if(TransPacketBase == NULL) TransPacketBase = Pkt; else { Pos = TransPacketBase; while(Pos->Next != NULL) Pos = Pos->Next; Pos->Next = Pkt; } // 同時接続対応 if(NextTransPacketBase == NULL) NextTransPacketBase = Pkt; while(Pkt != NULL) { DispTransPacket(Pkt); if((strncmp(Pkt->Cmd, "RETR", 4) == 0) || (strncmp(Pkt->Cmd, "STOR", 4) == 0)) { TransFiles++; // タスクバー進捗表示 TransferSizeLeft += Pkt->Size; TransferSizeTotal += Pkt->Size; PostMessage(GetMainHwnd(), WM_CHANGE_COND, 0, 0); } Pkt = Pkt->Next; } ReleaseMutex(hListAccMutex); // 同時接続対応 WaitForMainThread = NO; return; } /*----- 転送ファイル情報を表示する -------------------------------------------- * * Parameter * TRANSPACKET *Pkt : 転送ファイル情報 * * Return Value * なし *----------------------------------------------------------------------------*/ static void DispTransPacket(TRANSPACKET *Pkt) { if((strncmp(Pkt->Cmd, "RETR", 4) == 0) || (strncmp(Pkt->Cmd, "STOR", 4) == 0)) DoPrintf("TransList Cmd=%s : %s : %s", Pkt->Cmd, Pkt->RemoteFile, Pkt->LocalFile); else if(strncmp(Pkt->Cmd, "R-", 2) == 0) DoPrintf("TransList Cmd=%s : %s", Pkt->Cmd, Pkt->RemoteFile); else if(strncmp(Pkt->Cmd, "L-", 2) == 0) DoPrintf("TransList Cmd=%s : %s", Pkt->Cmd, Pkt->LocalFile); else if(strncmp(Pkt->Cmd, "MKD", 3) == 0) { if(strlen(Pkt->LocalFile) > 0) DoPrintf("TransList Cmd=%s : %s", Pkt->Cmd, Pkt->LocalFile); else DoPrintf("TransList Cmd=%s : %s", Pkt->Cmd, Pkt->RemoteFile); } else DoPrintf("TransList Cmd=%s", Pkt->Cmd); return; } /*----- 転送ファイルリストをクリアする ---------------------------------------- * * Parameter * なし * * Return Value * なし *----------------------------------------------------------------------------*/ static void EraseTransFileList(void) { TRANSPACKET *New; TRANSPACKET *Next; TRANSPACKET *NotDel; // TRANSPACKET Pkt; NotDel = NULL; // 同時接続対応 // WaitForSingleObject(hListAccMutex, INFINITE); while(WaitForSingleObject(hListAccMutex, 0) == WAIT_TIMEOUT) { WaitForMainThread = YES; BackgrndMessageProc(); Sleep(1); } New = TransPacketBase; while(New != NULL) { /* 最後の"BACKCUR"は必要なので消さない */ if(strcmp(New->Cmd, "BACKCUR") == 0) { if(NotDel != NULL) // 同時接続対応 // free(NotDel); strcpy(NotDel->Cmd, ""); NotDel = New; New = New->Next; // 同時接続対応 // NotDel->Next = NULL; } else { Next = New->Next; // 同時接続対応 // free(New); strcpy(New->Cmd, ""); New = Next; } } TransPacketBase = NotDel; // 同時接続対応 NextTransPacketBase = NotDel; TransFiles = 0; // タスクバー進捗表示 TransferSizeLeft = 0; TransferSizeTotal = 0; PostMessage(GetMainHwnd(), WM_CHANGE_COND, 0, 0); ReleaseMutex(hListAccMutex); // 同時接続対応 WaitForMainThread = NO; // 同時接続対応 // strcpy(Pkt.Cmd, "GOQUIT"); // AddTransFileList(&Pkt); return; } /*----- 転送中ダイアログを消さないようにするかどうかを設定 -------------------- * * Parameter * int Sw : 転送中ダイアログを消さないかどうか (YES/NO) * * Return Value * なし *----------------------------------------------------------------------------*/ void KeepTransferDialog(int Sw) { KeepDlg = Sw; return; } /*----- 現在転送中かどうかを返す ---------------------------------------------- * * Parameter * なし * * Return Value * int ステータス (YES/NO=転送中ではない) *----------------------------------------------------------------------------*/ int AskTransferNow(void) { return(TransPacketBase != NULL ? YES : NO); } /*----- 転送するファイルの数を返す -------------------------------------------- * * Parameter * なし * * Return Value * int 転送するファイルの数 *----------------------------------------------------------------------------*/ int AskTransferFileNum(void) { return(TransFiles); } /*----- 転送中ウインドウを前面に出す ------------------------------------------ * * Parameter * なし * * Return Value * なし *----------------------------------------------------------------------------*/ void GoForwardTransWindow(void) { MoveToForeground = YES; return; } /*----- 転送ソケットのカレントディレクトリ情報を初期化 ------------------------ * * Parameter * なし * * Return Value * なし *----------------------------------------------------------------------------*/ void InitTransCurDir(void) { // 同時接続対応 // strcpy(CurDir, ""); int i; for(i = 0; i < MAX_DATA_CONNECTION; i++) strcpy(CurDir[i], ""); return; } /*----- ファイル転送スレッドのメインループ ------------------------------------ * * Parameter * void *Dummy : 使わない * * Return Value * なし *----------------------------------------------------------------------------*/ static ULONG WINAPI TransferThread(void *Dummy) { TRANSPACKET *Pos; HWND hWndTrans; char Tmp[FMAX_PATH+1]; int CwdSts; int GoExit; // int Down; // int Up; static int Down; static int Up; int DelNotify; int ThreadCount; SOCKET TrnSkt; RECT WndRect; int i; DWORD LastUsed; int LastError; int Sts; hWndTrans = NULL; Down = NO; Up = NO; GoExit = NO; DelNotify = NO; // 同時接続対応 // ソケットは各転送スレッドが管理 ThreadCount = (int)Dummy; TrnSkt = INVALID_SOCKET; LastError = NO; SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); while((TransPacketBase != NULL) || (WaitForSingleObject(hRunMutex, 200) == WAIT_TIMEOUT)) { if(fTransferThreadExit == TRUE) break; if(WaitForMainThread == YES) { BackgrndMessageProc(); Sleep(100); continue; } // WaitForSingleObject(hListAccMutex, INFINITE); while(WaitForSingleObject(hListAccMutex, 0) == WAIT_TIMEOUT) { BackgrndMessageProc(); Sleep(1); } // memset(ErrMsg, NUL, ERR_MSG_LEN+7); memset(GetErrMsg(), NUL, ERR_MSG_LEN+7); // Canceled = NO; Canceled[ThreadCount] = NO; while(TransPacketBase != NULL && strcmp(TransPacketBase->Cmd, "") == 0) { Pos = TransPacketBase; TransPacketBase = TransPacketBase->Next; free(Pos); if(TransPacketBase == NULL) GoExit = YES; } if(AskReuseCmdSkt() == YES && ThreadCount == 0) { TrnSkt = AskTrnCtrlSkt(); // セッションあたりの転送量制限対策 if(TrnSkt != INVALID_SOCKET && AskErrorReconnect() == YES && LastError == YES) { ReleaseMutex(hListAccMutex); PostMessage(GetMainHwnd(), WM_RECONNECTSOCKET, 0, 0); Sleep(100); TrnSkt = INVALID_SOCKET; // WaitForSingleObject(hListAccMutex, INFINITE); while(WaitForSingleObject(hListAccMutex, 0) == WAIT_TIMEOUT) { BackgrndMessageProc(); Sleep(1); } } } else { // セッションあたりの転送量制限対策 if(TrnSkt != INVALID_SOCKET && AskErrorReconnect() == YES && LastError == YES) { ReleaseMutex(hListAccMutex); DoQUIT(TrnSkt, &Canceled[ThreadCount]); DoClose(TrnSkt); TrnSkt = INVALID_SOCKET; // WaitForSingleObject(hListAccMutex, INFINITE); while(WaitForSingleObject(hListAccMutex, 0) == WAIT_TIMEOUT) { BackgrndMessageProc(); Sleep(1); } } if(TransPacketBase && AskConnecting() == YES && ThreadCount < AskMaxThreadCount()) { ReleaseMutex(hListAccMutex); if(TrnSkt == INVALID_SOCKET) ReConnectTrnSkt(&TrnSkt, &Canceled[ThreadCount]); else CheckClosedAndReconnectTrnSkt(&TrnSkt, &Canceled[ThreadCount]); // 同時ログイン数制限対策 if(TrnSkt == INVALID_SOCKET) { // 同時ログイン数制限に引っかかった可能性あり // 負荷を下げるために約10秒間待機 i = 1000; while(i > 0) { BackgrndMessageProc(); Sleep(10); i--; } } LastUsed = timeGetTime(); // WaitForSingleObject(hListAccMutex, INFINITE); while(WaitForSingleObject(hListAccMutex, 0) == WAIT_TIMEOUT) { BackgrndMessageProc(); Sleep(1); } } else { if(TrnSkt != INVALID_SOCKET) { // 同時ログイン数制限対策 // 60秒間使用されなければログアウト if(timeGetTime() - LastUsed > 60000 || AskConnecting() == NO || ThreadCount >= AskMaxThreadCount()) { ReleaseMutex(hListAccMutex); DoQUIT(TrnSkt, &Canceled[ThreadCount]); DoClose(TrnSkt); TrnSkt = INVALID_SOCKET; // WaitForSingleObject(hListAccMutex, INFINITE); while(WaitForSingleObject(hListAccMutex, 0) == WAIT_TIMEOUT) { BackgrndMessageProc(); Sleep(1); } } } } } LastError = NO; // if(TransPacketBase != NULL) if(TrnSkt != INVALID_SOCKET && NextTransPacketBase != NULL) { Pos = NextTransPacketBase; NextTransPacketBase = NextTransPacketBase->Next; // ディレクトリ操作は非同期で行わない // ReleaseMutex(hListAccMutex); if(hWndTrans == NULL) { // if((strncmp(TransPacketBase->Cmd, "RETR", 4) == 0) || // (strncmp(TransPacketBase->Cmd, "STOR", 4) == 0) || // (strncmp(TransPacketBase->Cmd, "MKD", 3) == 0) || // (strncmp(TransPacketBase->Cmd, "L-", 2) == 0) || // (strncmp(TransPacketBase->Cmd, "R-", 2) == 0)) if((strncmp(Pos->Cmd, "RETR", 4) == 0) || (strncmp(Pos->Cmd, "STOR", 4) == 0) || (strncmp(Pos->Cmd, "MKD", 3) == 0) || (strncmp(Pos->Cmd, "L-", 2) == 0) || (strncmp(Pos->Cmd, "R-", 2) == 0)) { hWndTrans = CreateDialog(GetFtpInst(), MAKEINTRESOURCE(transfer_dlg), HWND_DESKTOP, (DLGPROC)TransDlgProc); if(MoveToForeground == YES) SetForegroundWindow(hWndTrans); ShowWindow(hWndTrans, SW_SHOWNOACTIVATE); GetWindowRect(hWndTrans, &WndRect); SetWindowPos(hWndTrans, NULL, WndRect.left, WndRect.top + (WndRect.bottom - WndRect.top) * ThreadCount - (WndRect.bottom - WndRect.top) * (AskMaxThreadCount() - 1) / 2, 0, 0, SWP_NOSIZE | SWP_NOZORDER); } } // TransPacketBase->hWndTrans = hWndTrans; Pos->hWndTrans = hWndTrans; Pos->ctrl_skt = TrnSkt; Pos->Abort = ABORT_NONE; Pos->ThreadCount = ThreadCount; if(hWndTrans != NULL) { if(MoveToForeground == YES) { SetForegroundWindow(hWndTrans); MoveToForeground = NO; } } if(hWndTrans != NULL) // SendMessage(hWndTrans, WM_SET_PACKET, 0, (LPARAM)TransPacketBase); SendMessage(hWndTrans, WM_SET_PACKET, 0, (LPARAM)Pos); // 中断後に受信バッファに応答が残っていると次のコマンドの応答が正しく処理できない RemoveReceivedData(TrnSkt); /* ダウンロード */ // if(strncmp(TransPacketBase->Cmd, "RETR", 4) == 0) if(strncmp(Pos->Cmd, "RETR", 4) == 0) { // 一部TYPE、STOR(RETR)、PORT(PASV)を並列に処理できないホストがあるため // ReleaseMutex(hListAccMutex); /* 不正なパスを検出 */ // if(CheckPathViolation(TransPacketBase) == NO) if(CheckPathViolation(Pos) == NO) { /* フルパスを使わないための処理 */ // if(MakeNonFullPath(TransPacketBase, CurDir, Tmp) == FFFTP_SUCCESS) if(MakeNonFullPath(Pos, CurDir[Pos->ThreadCount], Tmp) == FFFTP_SUCCESS) { // if(strncmp(TransPacketBase->Cmd, "RETR-S", 6) == 0) if(strncmp(Pos->Cmd, "RETR-S", 6) == 0) { /* サイズと日付を取得 */ // DoSIZE(TransPacketBase->RemoteFile, &TransPacketBase->Size); // DoMDTM(TransPacketBase->RemoteFile, &TransPacketBase->Time); // strcpy(TransPacketBase->Cmd, "RETR "); DoSIZE(TrnSkt, Pos->RemoteFile, &Pos->Size, &Canceled[Pos->ThreadCount]); DoMDTM(TrnSkt, Pos->RemoteFile, &Pos->Time, &Canceled[Pos->ThreadCount]); strcpy(Pos->Cmd, "RETR "); } Down = YES; // if(DoDownload(AskTrnCtrlSkt(), TransPacketBase, NO) == 429) // { // if(ReConnectTrnSkt() == FFFTP_SUCCESS) // DoDownload(AskTrnCtrlSkt(), TransPacketBase, NO, &Canceled); // ミラーリング設定追加 if(Pos->NoTransfer == NO) { Sts = DoDownload(TrnSkt, Pos, NO, &Canceled[Pos->ThreadCount]) / 100; if(Sts != FTP_COMPLETE) LastError = YES; // ゾーンID設定追加 if(MarkAsInternet == YES && IsZoneIDLoaded() == YES) MarkFileAsDownloadedFromInternet(Pos->LocalFile); } // ミラーリング設定追加 if((SaveTimeStamp == YES) && ((Pos->Time.dwLowDateTime != 0) || (Pos->Time.dwHighDateTime != 0))) { SetDownloadedFileTime(Pos); } } } // 一部TYPE、STOR(RETR)、PORT(PASV)を並列に処理できないホストがあるため ReleaseMutex(hListAccMutex); } /* アップロード */ // else if(strncmp(TransPacketBase->Cmd, "STOR", 4) == 0) else if(strncmp(Pos->Cmd, "STOR", 4) == 0) { // 一部TYPE、STOR(RETR)、PORT(PASV)を並列に処理できないホストがあるため // ReleaseMutex(hListAccMutex); /* フルパスを使わないための処理 */ // if(MakeNonFullPath(TransPacketBase, CurDir, Tmp) == FFFTP_SUCCESS) if(MakeNonFullPath(Pos, CurDir[Pos->ThreadCount], Tmp) == FFFTP_SUCCESS) { Up = YES; // if(DoUpload(AskTrnCtrlSkt(), TransPacketBase) == 429) // { // if(ReConnectTrnSkt() == FFFTP_SUCCESS) // DoUpload(AskTrnCtrlSkt(), TransPacketBase); // ミラーリング設定追加 if(Pos->NoTransfer == NO) { Sts = DoUpload(TrnSkt, Pos) / 100; if(Sts != FTP_COMPLETE) LastError = YES; } // ホスト側の日時設定 /* ファイルのタイムスタンプを合わせる */ if((SaveTimeStamp == YES) && ((Pos->Time.dwLowDateTime != 0) || (Pos->Time.dwHighDateTime != 0))) { DoMFMT(TrnSkt, Pos->RemoteFile, &Pos->Time, &Canceled[Pos->ThreadCount]); } } // 一部TYPE、STOR(RETR)、PORT(PASV)を並列に処理できないホストがあるため ReleaseMutex(hListAccMutex); } /* フォルダ作成(ローカルまたはホスト) */ // else if(strncmp(TransPacketBase->Cmd, "MKD", 3) == 0) else if(strncmp(Pos->Cmd, "MKD", 3) == 0) { // DispTransFileInfo(TransPacketBase, MSGJPN078, FALSE, YES); DispTransFileInfo(Pos, MSGJPN078, FALSE, YES); // if(strlen(TransPacketBase->RemoteFile) > 0) if(strlen(Pos->RemoteFile) > 0) { /* フルパスを使わないための処理 */ CwdSts = FTP_COMPLETE; // strcpy(Tmp, TransPacketBase->RemoteFile); strcpy(Tmp, Pos->RemoteFile); // if(ProcForNonFullpath(Tmp, CurDir, hWndTrans, 1) == FFFTP_FAIL) if(ProcForNonFullpath(TrnSkt, Tmp, CurDir[Pos->ThreadCount], hWndTrans, &Canceled[Pos->ThreadCount]) == FFFTP_FAIL) { ClearAll = YES; CwdSts = FTP_ERROR; } if(CwdSts == FTP_COMPLETE) { Up = YES; // CommandProcTrn(NULL, "MKD %s", Tmp); CommandProcTrn(TrnSkt, NULL, &Canceled[Pos->ThreadCount], "MKD %s", Tmp); /* すでにフォルダがある場合もあるので、 */ /* ここではエラーチェックはしない */ if(FolderAttr) // CommandProcTrn(NULL, "%s %03d %s", AskHostChmodCmd(), FolderAttrNum, Tmp); CommandProcTrn(TrnSkt, NULL, &Canceled[Pos->ThreadCount], "%s %03d %s", AskHostChmodCmd(), FolderAttrNum, Tmp); } } // else if(strlen(TransPacketBase->LocalFile) > 0) else if(strlen(Pos->LocalFile) > 0) { Down = YES; // DoLocalMKD(TransPacketBase->LocalFile); DoLocalMKD(Pos->LocalFile); } ReleaseMutex(hListAccMutex); } /* ディレクトリ作成(常にホスト側) */ // else if(strncmp(TransPacketBase->Cmd, "R-MKD", 5) == 0) else if(strncmp(Pos->Cmd, "R-MKD", 5) == 0) { // DispTransFileInfo(TransPacketBase, MSGJPN079, FALSE, YES); DispTransFileInfo(Pos, MSGJPN079, FALSE, YES); /* フルパスを使わないための処理 */ // if(MakeNonFullPath(TransPacketBase, CurDir, Tmp) == FFFTP_SUCCESS) if(MakeNonFullPath(Pos, CurDir[Pos->ThreadCount], Tmp) == FFFTP_SUCCESS) { Up = YES; // CommandProcTrn(NULL, "%s%s", TransPacketBase->Cmd+2, TransPacketBase->RemoteFile); CommandProcTrn(TrnSkt, NULL, &Canceled[Pos->ThreadCount], "%s%s", Pos->Cmd+2, Pos->RemoteFile); if(FolderAttr) // CommandProcTrn(NULL, "%s %03d %s", AskHostChmodCmd(), FolderAttrNum, TransPacketBase->RemoteFile); CommandProcTrn(TrnSkt, NULL, &Canceled[Pos->ThreadCount], "%s %03d %s", AskHostChmodCmd(), FolderAttrNum, Pos->RemoteFile); } ReleaseMutex(hListAccMutex); } /* ディレクトリ削除(常にホスト側) */ // else if(strncmp(TransPacketBase->Cmd, "R-RMD", 5) == 0) else if(strncmp(Pos->Cmd, "R-RMD", 5) == 0) { // DispTransFileInfo(TransPacketBase, MSGJPN080, FALSE, YES); DispTransFileInfo(Pos, MSGJPN080, FALSE, YES); // DelNotify = MirrorDelNotify(WIN_REMOTE, DelNotify, TransPacketBase); DelNotify = MirrorDelNotify(WIN_REMOTE, DelNotify, Pos); if((DelNotify == YES) || (DelNotify == YES_ALL)) { /* フルパスを使わないための処理 */ // if(MakeNonFullPath(TransPacketBase, CurDir, Tmp) == FFFTP_SUCCESS) if(MakeNonFullPath(Pos, CurDir[Pos->ThreadCount], Tmp) == FFFTP_SUCCESS) { Up = YES; // CommandProcTrn(NULL, "%s%s", TransPacketBase->Cmd+2, TransPacketBase->RemoteFile); CommandProcTrn(TrnSkt, NULL, &Canceled[Pos->ThreadCount], "%s%s", Pos->Cmd+2, Pos->RemoteFile); } } ReleaseMutex(hListAccMutex); } /* ファイル削除(常にホスト側) */ // else if(strncmp(TransPacketBase->Cmd, "R-DELE", 6) == 0) else if(strncmp(Pos->Cmd, "R-DELE", 6) == 0) { // DispTransFileInfo(TransPacketBase, MSGJPN081, FALSE, YES); DispTransFileInfo(Pos, MSGJPN081, FALSE, YES); // DelNotify = MirrorDelNotify(WIN_REMOTE, DelNotify, TransPacketBase); DelNotify = MirrorDelNotify(WIN_REMOTE, DelNotify, Pos); if((DelNotify == YES) || (DelNotify == YES_ALL)) { /* フルパスを使わないための処理 */ // if(MakeNonFullPath(TransPacketBase, CurDir, Tmp) == FFFTP_SUCCESS) if(MakeNonFullPath(Pos, CurDir[Pos->ThreadCount], Tmp) == FFFTP_SUCCESS) { Up = YES; // CommandProcTrn(NULL, "%s%s", TransPacketBase->Cmd+2, TransPacketBase->RemoteFile); CommandProcTrn(TrnSkt, NULL, &Canceled[Pos->ThreadCount], "%s%s", Pos->Cmd+2, Pos->RemoteFile); } } ReleaseMutex(hListAccMutex); } /* ディレクトリ作成(常にローカル側) */ // else if(strncmp(TransPacketBase->Cmd, "L-MKD", 5) == 0) else if(strncmp(Pos->Cmd, "L-MKD", 5) == 0) { // DispTransFileInfo(TransPacketBase, MSGJPN082, FALSE, YES); DispTransFileInfo(Pos, MSGJPN082, FALSE, YES); Down = YES; // DoLocalMKD(TransPacketBase->LocalFile); DoLocalMKD(Pos->LocalFile); ReleaseMutex(hListAccMutex); } /* ディレクトリ削除(常にローカル側) */ // else if(strncmp(TransPacketBase->Cmd, "L-RMD", 5) == 0) else if(strncmp(Pos->Cmd, "L-RMD", 5) == 0) { // DispTransFileInfo(TransPacketBase, MSGJPN083, FALSE, YES); DispTransFileInfo(Pos, MSGJPN083, FALSE, YES); // DelNotify = MirrorDelNotify(WIN_LOCAL, DelNotify, TransPacketBase); DelNotify = MirrorDelNotify(WIN_LOCAL, DelNotify, Pos); if((DelNotify == YES) || (DelNotify == YES_ALL)) { Down = YES; // DoLocalRMD(TransPacketBase->LocalFile); DoLocalRMD(Pos->LocalFile); } ReleaseMutex(hListAccMutex); } /* ファイル削除(常にローカル側) */ // else if(strncmp(TransPacketBase->Cmd, "L-DELE", 6) == 0) else if(strncmp(Pos->Cmd, "L-DELE", 6) == 0) { // DispTransFileInfo(TransPacketBase, MSGJPN084, FALSE, YES); DispTransFileInfo(Pos, MSGJPN084, FALSE, YES); // DelNotify = MirrorDelNotify(WIN_LOCAL, DelNotify, TransPacketBase); DelNotify = MirrorDelNotify(WIN_LOCAL, DelNotify, Pos); if((DelNotify == YES) || (DelNotify == YES_ALL)) { Down = YES; // DoLocalDELE(TransPacketBase->LocalFile); DoLocalDELE(Pos->LocalFile); } ReleaseMutex(hListAccMutex); } /* カレントディレクトリを設定 */ // else if(strcmp(TransPacketBase->Cmd, "SETCUR") == 0) else if(strcmp(Pos->Cmd, "SETCUR") == 0) { // if(AskShareProh() == YES) if(AskReuseCmdSkt() == NO || AskShareProh() == YES) { // if(strcmp(CurDir, TransPacketBase->RemoteFile) != 0) if(strcmp(CurDir[Pos->ThreadCount], Pos->RemoteFile) != 0) { // if(CommandProcTrn(NULL, "CWD %s", TransPacketBase->RemoteFile)/100 != FTP_COMPLETE) if(CommandProcTrn(TrnSkt, NULL, &Canceled[Pos->ThreadCount], "CWD %s", Pos->RemoteFile)/100 != FTP_COMPLETE) { DispCWDerror(hWndTrans); ClearAll = YES; } } } // strcpy(CurDir, TransPacketBase->RemoteFile); strcpy(CurDir[Pos->ThreadCount], Pos->RemoteFile); ReleaseMutex(hListAccMutex); } /* カレントディレクトリを戻す */ // else if(strcmp(TransPacketBase->Cmd, "BACKCUR") == 0) else if(strcmp(Pos->Cmd, "BACKCUR") == 0) { // if(AskShareProh() == NO) if(AskReuseCmdSkt() == YES && AskShareProh() == NO) { // if(strcmp(CurDir, TransPacketBase->RemoteFile) != 0) // CommandProcTrn(NULL, "CWD %s", TransPacketBase->RemoteFile); // strcpy(CurDir, TransPacketBase->RemoteFile); if(strcmp(CurDir[Pos->ThreadCount], Pos->RemoteFile) != 0) CommandProcTrn(TrnSkt, NULL, &Canceled[Pos->ThreadCount], "CWD %s", Pos->RemoteFile); strcpy(CurDir[Pos->ThreadCount], Pos->RemoteFile); } ReleaseMutex(hListAccMutex); } /* 自動終了のための通知 */ // else if(strcmp(TransPacketBase->Cmd, "GOQUIT") == 0) // else if(strcmp(Pos->Cmd, "GOQUIT") == 0) // { // ReleaseMutex(hListAccMutex); // GoExit = YES; // } // バグ対策 else if(strcmp(Pos->Cmd, "NULL") == 0) { Sleep(0); Sleep(100); ReleaseMutex(hListAccMutex); } else ReleaseMutex(hListAccMutex); /*===== 1つの処理終わり =====*/ if(ForceAbort == NO) { // WaitForSingleObject(hListAccMutex, INFINITE); while(WaitForSingleObject(hListAccMutex, 0) == WAIT_TIMEOUT) { BackgrndMessageProc(); Sleep(1); } if(ClearAll == YES) // EraseTransFileList(); { for(i = 0; i < MAX_DATA_CONNECTION; i++) Canceled[i] = YES; if(Pos != NULL) strcpy(Pos->Cmd, ""); Pos = NULL; EraseTransFileList(); GoExit = YES; } else { // if((strncmp(TransPacketBase->Cmd, "RETR", 4) == 0) || // (strncmp(TransPacketBase->Cmd, "STOR", 4) == 0)) if((strncmp(Pos->Cmd, "RETR", 4) == 0) || (strncmp(Pos->Cmd, "STOR", 4) == 0) || (strncmp(Pos->Cmd, "STOU", 4) == 0)) { // TransFiles--; if(TransFiles > 0) TransFiles--; // タスクバー進捗表示 if(TransferSizeLeft > 0) TransferSizeLeft -= Pos->Size; if(TransferSizeLeft < 0) TransferSizeLeft = 0; if(TransFiles == 0) TransferSizeTotal = 0; PostMessage(GetMainHwnd(), WM_CHANGE_COND, 0, 0); } // Pos = TransPacketBase; // TransPacketBase = TransPacketBase->Next; // free(Pos); } // ClearAll = NO; ReleaseMutex(hListAccMutex); if(BackgrndMessageProc() == YES) { WaitForSingleObject(hListAccMutex, INFINITE); EraseTransFileList(); ReleaseMutex(hListAccMutex); } } if(hWndTrans != NULL) SendMessage(hWndTrans, WM_SET_PACKET, 0, 0); if(Pos != NULL) strcpy(Pos->Cmd, ""); LastUsed = timeGetTime(); } // else else if(TransPacketBase == NULL) { ClearAll = NO; DelNotify = NO; if(GoExit == YES) { SoundPlay(SND_TRANS); if(AskAutoExit() == NO) { if(Down == YES) PostMessage(GetMainHwnd(), WM_REFRESH_LOCAL_FLG, 0, 0); if(Up == YES) PostMessage(GetMainHwnd(), WM_REFRESH_REMOTE_FLG, 0, 0); } Down = NO; Up = NO; PostMessage(GetMainHwnd(), WM_COMMAND, MAKEWPARAM(MENU_AUTO_EXIT, 0), 0); GoExit = NO; } ReleaseMutex(hListAccMutex); if(KeepDlg == NO) { if(hWndTrans != NULL) { DestroyWindow(hWndTrans); hWndTrans = NULL; // if(GoExit == YES) // { // SoundPlay(SND_TRANS); // // if(AskAutoExit() == NO) // { // if(Down == YES) // PostMessage(GetMainHwnd(), WM_REFRESH_LOCAL_FLG, 0, 0); // if(Up == YES) // PostMessage(GetMainHwnd(), WM_REFRESH_REMOTE_FLG, 0, 0); // } // Down = NO; // Up = NO; // } } } BackgrndMessageProc(); // Sleep(1); Sleep(100); // 再転送対応 TransferErrorMode = AskTransferErrorMode(); TransferErrorNotify = AskTransferErrorNotify(); } else { ReleaseMutex(hListAccMutex); if(hWndTrans != NULL) { DestroyWindow(hWndTrans); hWndTrans = NULL; } BackgrndMessageProc(); if(ThreadCount < AskMaxThreadCount()) Sleep(1); else Sleep(100); } } if(AskReuseCmdSkt() == NO || ThreadCount > 0) { if(TrnSkt != INVALID_SOCKET) { SendData(TrnSkt, "QUIT\r\n", 6, 0, &Canceled[ThreadCount]); DoClose(TrnSkt); } } return 0; } /*----- フルパスを使わないファイルアクセスの準備 ------------------------------ * * Parameter * TRANSPACKET *Pkt : 転送パケット * char *Cur : カレントディレクトリ * char *Tmp : 作業用エリア * * Return Value * int ステータス(FFFTP_SUCCESS/FFFTP_FAIL) * * Note * フルパスを使わない時は、 * このモジュール内で CWD を行ない、 * Pkt->RemoteFile にファイル名のみ残す。(パス名は消す) *----------------------------------------------------------------------------*/ // 同時接続対応 static int MakeNonFullPath(TRANSPACKET *Pkt, char *Cur, char *Tmp) { int Sts; // Sts = ProcForNonFullpath(Pkt->RemoteFile, Cur, Pkt->hWndTrans, 1); Sts = ProcForNonFullpath(Pkt->ctrl_skt, Pkt->RemoteFile, Cur, Pkt->hWndTrans, &Canceled[Pkt->ThreadCount]); if(Sts == FFFTP_FAIL) ClearAll = YES; return(Sts); } // ミラーリング設定追加 static int SetDownloadedFileTime(TRANSPACKET *Pkt) { int Sts; HANDLE hFile; Sts = FFFTP_FAIL; if((hFile = CreateFile(Pkt->LocalFile, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) != INVALID_HANDLE_VALUE) { if(SetFileTime(hFile, &Pkt->Time, &Pkt->Time, &Pkt->Time)) Sts = FFFTP_SUCCESS; CloseHandle(hFile); } return Sts; } /*----- ダウンロードを行なう -------------------------------------------------- * * Parameter * SOCKET cSkt : コントロールソケット * TRANSPACKET *Pkt : 転送ファイル情報 * int DirList : ディレクトリリストのダウンロード(YES/NO) * * Return Value * int 応答コード * * Note * このモジュールは、ファイル一覧の取得などを行なう際にメインのスレッド * からも呼ばれる。メインのスレッドから呼ばれる時は Pkt->hWndTrans == NULL。 *----------------------------------------------------------------------------*/ int DoDownload(SOCKET cSkt, TRANSPACKET *Pkt, int DirList, int *CancelCheckWork) { int iRetCode; char Reply[ERR_MSG_LEN+7]; Pkt->ctrl_skt = cSkt; if(IsSpecialDevice(GetFileName(Pkt->LocalFile)) == YES) { iRetCode = 500; SetTaskMsg(MSGJPN085, GetFileName(Pkt->LocalFile)); // エラーによってはダイアログが表示されない場合があるバグ対策 // DispDownloadFinishMsg(Pkt, iRetCode); } else if(Pkt->Mode != EXIST_IGNORE) { if(Pkt->Type == TYPE_I) Pkt->KanjiCode = KANJI_NOCNV; iRetCode = command(Pkt->ctrl_skt, Reply, CancelCheckWork, "TYPE %c", Pkt->Type); if(iRetCode/100 < FTP_RETRY) { if(Pkt->hWndTrans != NULL) { // 同時接続対応 // AllTransSizeNow = 0; AllTransSizeNow[Pkt->ThreadCount] = 0; if(DirList == NO) DispTransFileInfo(Pkt, MSGJPN086, TRUE, YES); else DispTransFileInfo(Pkt, MSGJPN087, FALSE, NO); } if(BackgrndMessageProc() == NO) { if(AskPasvMode() != YES) iRetCode = DownloadNonPassive(Pkt, CancelCheckWork); else iRetCode = DownloadPassive(Pkt, CancelCheckWork); } else iRetCode = 500; } else SetErrorMsg(Reply); // エラーによってはダイアログが表示されない場合があるバグ対策 DispDownloadFinishMsg(Pkt, iRetCode); } else { DispTransFileInfo(Pkt, MSGJPN088, TRUE, YES); SetTaskMsg(MSGJPN089, Pkt->RemoteFile); iRetCode = 200; } return(iRetCode); } /*----- 通常モードでファイルをダウンロード ------------------------------------ * * Parameter * TRANSPACKET *Pkt : 転送ファイル情報 * * Return Value * int 応答コード *----------------------------------------------------------------------------*/ static int DownloadNonPassive(TRANSPACKET *Pkt, int *CancelCheckWork) { int iRetCode; int iLength; SOCKET data_socket = INVALID_SOCKET; // data channel socket SOCKET listen_socket = INVALID_SOCKET; // data listen socket // 念のため // char Buf[1024]; char Buf[FMAX_PATH+1024]; int CreateMode; // IPv6対応 // struct sockaddr_in saSockAddr1; struct sockaddr_in saSockAddrIPv4; struct sockaddr_in6 saSockAddrIPv6; // UPnP対応 int Port; char Reply[ERR_MSG_LEN+7]; if((listen_socket = GetFTPListenSocket(Pkt->ctrl_skt, CancelCheckWork)) != INVALID_SOCKET) { if(SetDownloadResume(Pkt, Pkt->Mode, Pkt->ExistSize, &CreateMode, CancelCheckWork) == YES) { sprintf(Buf, "%s%s", Pkt->Cmd, Pkt->RemoteFile); iRetCode = command(Pkt->ctrl_skt, Reply, CancelCheckWork, "%s", Buf); if(iRetCode/100 == FTP_PRELIM) { // 同時接続対応 // if(SocksGet2ndBindReply(listen_socket, &data_socket) == FFFTP_FAIL) if(SocksGet2ndBindReply(listen_socket, &data_socket, CancelCheckWork) == FFFTP_FAIL) { // IPv6対応 // iLength = sizeof(saSockAddr1); // data_socket = do_accept(listen_socket, (struct sockaddr *)&saSockAddr1, (int *)&iLength); switch(AskCurNetType()) { case NTYPE_IPV4: iLength=sizeof(saSockAddrIPv4); data_socket = do_accept(listen_socket,(struct sockaddr *)&saSockAddrIPv4, (int *)&iLength); break; case NTYPE_IPV6: iLength=sizeof(saSockAddrIPv6); data_socket = do_accept(listen_socket,(struct sockaddr *)&saSockAddrIPv6, (int *)&iLength); break; } if(shutdown(listen_socket, 1) != 0) ReportWSError("shutdown listen", WSAGetLastError()); // UPnP対応 if(IsUPnPLoaded() == YES) { if(GetAsyncTableDataMapPort(listen_socket, &Port) == YES) RemovePortMapping(Port); } listen_socket = DoClose(listen_socket); if(data_socket == INVALID_SOCKET) { SetErrorMsg(MSGJPN280); ReportWSError("accept", WSAGetLastError()); iRetCode = 500; } else // IPv6対応 // DoPrintf("Skt=%u : accept from %s port %u", data_socket, inet_ntoa(saSockAddr1.sin_addr), ntohs(saSockAddr1.sin_port)); { switch(AskCurNetType()) { case NTYPE_IPV4: DoPrintf("Skt=%u : accept from %s port %u", data_socket, inet_ntoa(saSockAddrIPv4.sin_addr), ntohs(saSockAddrIPv4.sin_port)); break; case NTYPE_IPV6: DoPrintf("Skt=%u : accept from %s port %u", data_socket, inet6_ntoa(saSockAddrIPv6.sin6_addr), ntohs(saSockAddrIPv6.sin6_port)); break; } } } if(data_socket != INVALID_SOCKET) { // 一部TYPE、STOR(RETR)、PORT(PASV)を並列に処理できないホストがあるため ReleaseMutex(hListAccMutex); // FTPS対応 // iRetCode = DownloadFile(Pkt, data_socket, CreateMode, CancelCheckWork); if(IsSSLAttached(Pkt->ctrl_skt)) { if(AttachSSL(data_socket, Pkt->ctrl_skt, CancelCheckWork, FALSE, NULL)) iRetCode = DownloadFile(Pkt, data_socket, CreateMode, CancelCheckWork); else iRetCode = 500; } else iRetCode = DownloadFile(Pkt, data_socket, CreateMode, CancelCheckWork); // data_socket = DoClose(data_socket); } } else { SetErrorMsg(Reply); SetTaskMsg(MSGJPN090); // UPnP対応 if(IsUPnPLoaded() == YES) { if(GetAsyncTableDataMapPort(listen_socket, &Port) == YES) RemovePortMapping(Port); } listen_socket = DoClose(listen_socket); iRetCode = 500; } } else // バグ修正 // iRetCode = 500; { // UPnP対応 if(IsUPnPLoaded() == YES) { if(GetAsyncTableDataMapPort(listen_socket, &Port) == YES) RemovePortMapping(Port); } listen_socket = DoClose(listen_socket); iRetCode = 500; } } else { iRetCode = 500; SetErrorMsg(MSGJPN279); } // エラーによってはダイアログが表示されない場合があるバグ対策 // DispDownloadFinishMsg(Pkt, iRetCode); return(iRetCode); } /*----- Passiveモードでファイルをダウンロード --------------------------------- * * Parameter * TRANSPACKET *Pkt : 転送ファイル情報 * * Return Value * int 応答コード *----------------------------------------------------------------------------*/ static int DownloadPassive(TRANSPACKET *Pkt, int *CancelCheckWork) { int iRetCode; SOCKET data_socket = INVALID_SOCKET; // data channel socket // 念のため // char Buf[1024]; char Buf[FMAX_PATH+1024]; int CreateMode; // IPv6対応 // char Adrs[20]; char Adrs[40]; int Port; int Flg; char Reply[ERR_MSG_LEN+7]; // IPv6対応 // iRetCode = command(Pkt->ctrl_skt, Buf, CancelCheckWork, "PASV"); switch(AskCurNetType()) { case NTYPE_IPV4: iRetCode = command(Pkt->ctrl_skt, Buf, CancelCheckWork, "PASV"); break; case NTYPE_IPV6: iRetCode = command(Pkt->ctrl_skt, Buf, CancelCheckWork, "EPSV"); break; } if(iRetCode/100 == FTP_COMPLETE) { // IPv6対応 // if(GetAdrsAndPort(Buf, Adrs, &Port, 19) == FFFTP_SUCCESS) if(GetAdrsAndPort(Pkt->ctrl_skt, Buf, Adrs, &Port, 39) == FFFTP_SUCCESS) { if((data_socket = connectsock(Adrs, Port, MSGJPN091, CancelCheckWork)) != INVALID_SOCKET) { // 変数が未初期化のバグ修正 Flg = 1; if(setsockopt(data_socket, IPPROTO_TCP, TCP_NODELAY, (LPSTR)&Flg, sizeof(Flg)) == SOCKET_ERROR) ReportWSError("setsockopt", WSAGetLastError()); if(SetDownloadResume(Pkt, Pkt->Mode, Pkt->ExistSize, &CreateMode, CancelCheckWork) == YES) { sprintf(Buf, "%s%s", Pkt->Cmd, Pkt->RemoteFile); iRetCode = command(Pkt->ctrl_skt, Reply, CancelCheckWork, "%s", Buf); if(iRetCode/100 == FTP_PRELIM) { // 一部TYPE、STOR(RETR)、PORT(PASV)を並列に処理できないホストがあるため ReleaseMutex(hListAccMutex); // FTPS対応 // iRetCode = DownloadFile(Pkt, data_socket, CreateMode, CancelCheckWork); if(IsSSLAttached(Pkt->ctrl_skt)) { if(AttachSSL(data_socket, Pkt->ctrl_skt, CancelCheckWork, FALSE, NULL)) iRetCode = DownloadFile(Pkt, data_socket, CreateMode, CancelCheckWork); else iRetCode = 500; } else iRetCode = DownloadFile(Pkt, data_socket, CreateMode, CancelCheckWork); // data_socket = DoClose(data_socket); } else { SetErrorMsg(Reply); SetTaskMsg(MSGJPN092); data_socket = DoClose(data_socket); iRetCode = 500; } } else iRetCode = 500; } else iRetCode = 500; } else { SetErrorMsg(MSGJPN093); SetTaskMsg(MSGJPN093); iRetCode = 500; } } else SetErrorMsg(Buf); // エラーによってはダイアログが表示されない場合があるバグ対策 // DispDownloadFinishMsg(Pkt, iRetCode); return(iRetCode); } /*----- ダウンロードの実行 ---------------------------------------------------- * * Parameter * TRANSPACKET *Pkt : 転送ファイル情報 * SOCKET dSkt : データソケット * int CreateMode : ファイル作成モード (CREATE_ALWAYS/OPEN_ALWAYS) * * Return Value * int 応答コード * * Note * 転送の経過表示は * ダイアログを出す(Pkt->hWndTrans!=NULL)場合、インターバルタイマで経過を表示する * ダイアログを出さない場合、このルーチンからDispDownloadSize()を呼ぶ *----------------------------------------------------------------------------*/ static int DownloadFile(TRANSPACKET *Pkt, SOCKET dSkt, int CreateMode, int *CancelCheckWork) { int iNumBytes; char Buf[BUFSIZE]; char Buf2[BUFSIZE+3]; HANDLE iFileHandle; SECURITY_ATTRIBUTES Sec; DWORD Writed; CODECONVINFO cInfo; int Continue; // fd_set ReadFds; // struct timeval Tout; // struct timeval *ToutPtr; int iRetCode; int TimeOutErr; char TmpBuf[ONELINE_BUF_SIZE]; DWORD dwFileAttributes; #ifdef SET_BUFFER_SIZE /* Add by H.Shirouzu at 2002/10/02 */ int buf_size = SOCKBUF_SIZE; for ( ; buf_size > 0; buf_size /= 2) if (setsockopt(dSkt, SOL_SOCKET, SO_RCVBUF, (char *)&buf_size, sizeof(buf_size)) == 0) break; /* End */ #endif // 念のため受信バッファを無効にする #ifdef DISABLE_TRANSFER_NETWORK_BUFFERS int buf_size = 0; setsockopt(dSkt, SOL_SOCKET, SO_RCVBUF, (char *)&buf_size, sizeof(buf_size)); #endif Pkt->Abort = ABORT_NONE; Sec.nLength = sizeof(SECURITY_ATTRIBUTES); Sec.lpSecurityDescriptor = NULL; Sec.bInheritHandle = FALSE; dwFileAttributes = GetFileAttributes(Pkt->LocalFile); if (dwFileAttributes != INVALID_FILE_ATTRIBUTES && (dwFileAttributes & FILE_ATTRIBUTE_READONLY)) { // 読み取り専用 if (MessageBox(GetMainHwnd(), MSGJPN296, MSGJPN086, MB_YESNO) == IDYES) { // 属性を解除 SetFileAttributes(Pkt->LocalFile, dwFileAttributes ^ FILE_ATTRIBUTE_READONLY); } } if((iFileHandle = CreateFile(Pkt->LocalFile, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, &Sec, CreateMode, FILE_ATTRIBUTE_NORMAL, NULL)) != INVALID_HANDLE_VALUE) { // UTF-8対応 char Buf3[(BUFSIZE + 3) * 4]; CODECONVINFO cInfo2; int ProcessedBOM = NO; // 4GB超対応(kaokunさん提供) DWORD High = 0; if(CreateMode == OPEN_ALWAYS) // 4GB超対応(kaokunさん提供) // SetFilePointer(iFileHandle, 0, 0, FILE_END); SetFilePointer(iFileHandle, 0, &High, FILE_END); if(Pkt->hWndTrans != NULL) { // 同時接続対応 // TimeStart = time(NULL); TimeStart[Pkt->ThreadCount] = time(NULL); SetTimer(Pkt->hWndTrans, TIMER_DISPLAY, DISPLAY_TIMING, NULL); } InitCodeConvInfo(&cInfo); cInfo.KanaCnv = Pkt->KanaCnv; InitCodeConvInfo(&cInfo2); cInfo2.KanaCnv = Pkt->KanaCnv; /*===== ファイルを受信するループ =====*/ while((Pkt->Abort == ABORT_NONE) && (ForceAbort == NO)) { // FD_ZERO(&ReadFds); // FD_SET(dSkt, &ReadFds); // ToutPtr = NULL; // if(TimeOut != 0) // { // Tout.tv_sec = TimeOut; // Tout.tv_usec = 0; // ToutPtr = &Tout; // } // iNumBytes = select(0, &ReadFds, NULL, NULL, ToutPtr); // if(iNumBytes == SOCKET_ERROR) // { // ReportWSError("select", WSAGetLastError()); // if(Pkt->Abort == ABORT_NONE) // Pkt->Abort = ABORT_ERROR; // break; // } // else if(iNumBytes == 0) // { // SetErrorMsg(MSGJPN094); // SetTaskMsg(MSGJPN094); // Pkt->Abort = ABORT_ERROR; // break; // } if((iNumBytes = do_recv(dSkt, Buf, BUFSIZE, 0, &TimeOutErr, CancelCheckWork)) <= 0) { if(TimeOutErr == YES) { SetErrorMsg(MSGJPN094); SetTaskMsg(MSGJPN094); if(Pkt->hWndTrans != NULL) ClearAll = YES; if(Pkt->Abort == ABORT_NONE) Pkt->Abort = ABORT_ERROR; } else if(iNumBytes == SOCKET_ERROR) { if(Pkt->Abort == ABORT_NONE) Pkt->Abort = ABORT_ERROR; } break; } /* 漢字コード変換 */ if(Pkt->KanjiCode != KANJI_NOCNV) { cInfo.Str = Buf; cInfo.StrLen = iNumBytes; cInfo.Buf = Buf2; cInfo.BufSize = BUFSIZE+3; do { // ここで全てUTF-8へ変換する // TODO: SJIS以外も直接UTF-8へ変換 // if(Pkt->KanjiCode == KANJI_JIS) // Continue = ConvJIStoSJIS(&cInfo); // else // Continue = ConvEUCtoSJIS(&cInfo); switch(Pkt->KanjiCode) { case KANJI_SJIS: switch(Pkt->KanjiCodeDesired) { case KANJI_SJIS: // memcpy(Buf3, cInfo.Str, cInfo.StrLen); // cInfo2.OutLen = cInfo.StrLen; // Continue = NO; // カナ変換のため Continue = ConvSJIStoJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvJIStoSJIS(&cInfo2); break; case KANJI_JIS: Continue = ConvSJIStoJIS(&cInfo); memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_EUC: Continue = ConvSJIStoEUC(&cInfo); memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_UTF8N: Continue = ConvSJIStoUTF8N(&cInfo); memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_UTF8BOM: if(ProcessedBOM == NO) { memcpy(Buf3, "\xEF\xBB\xBF", 3); cInfo2.OutLen = 3; Continue = YES; ProcessedBOM = YES; break; } Continue = ConvSJIStoUTF8N(&cInfo); memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; } break; case KANJI_JIS: switch(Pkt->KanjiCodeDesired) { case KANJI_SJIS: Continue = ConvJIStoSJIS(&cInfo); memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_JIS: // memcpy(Buf3, cInfo.Str, cInfo.StrLen); // cInfo2.OutLen = cInfo.StrLen; // Continue = NO; // カナ変換のため Continue = ConvJIStoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoJIS(&cInfo2); break; case KANJI_EUC: Continue = ConvJIStoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoEUC(&cInfo2); break; case KANJI_UTF8N: Continue = ConvJIStoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoUTF8N(&cInfo2); break; case KANJI_UTF8BOM: if(ProcessedBOM == NO) { memcpy(Buf3, "\xEF\xBB\xBF", 3); cInfo2.OutLen = 3; Continue = YES; ProcessedBOM = YES; break; } Continue = ConvJIStoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoUTF8N(&cInfo2); break; } break; case KANJI_EUC: switch(Pkt->KanjiCodeDesired) { case KANJI_SJIS: Continue = ConvEUCtoSJIS(&cInfo); memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_JIS: Continue = ConvEUCtoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoJIS(&cInfo2); break; case KANJI_EUC: // memcpy(Buf3, cInfo.Str, cInfo.StrLen); // cInfo2.OutLen = cInfo.StrLen; // Continue = NO; // カナ変換のため Continue = ConvEUCtoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoEUC(&cInfo2); break; case KANJI_UTF8N: Continue = ConvEUCtoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoUTF8N(&cInfo2); break; case KANJI_UTF8BOM: if(ProcessedBOM == NO) { memcpy(Buf3, "\xEF\xBB\xBF", 3); cInfo2.OutLen = 3; Continue = YES; ProcessedBOM = YES; break; } Continue = ConvEUCtoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoUTF8N(&cInfo2); break; } break; case KANJI_UTF8N: switch(Pkt->KanjiCodeDesired) { case KANJI_SJIS: Continue = ConvUTF8NtoSJIS(&cInfo); memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_JIS: Continue = ConvUTF8NtoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoJIS(&cInfo2); break; case KANJI_EUC: Continue = ConvUTF8NtoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoEUC(&cInfo2); break; case KANJI_UTF8N: memcpy(Buf3, cInfo.Str, cInfo.StrLen); cInfo2.OutLen = cInfo.StrLen; Continue = NO; break; case KANJI_UTF8BOM: if(ProcessedBOM == NO) { memcpy(Buf3, "\xEF\xBB\xBF", 3); cInfo2.OutLen = 3; Continue = YES; ProcessedBOM = YES; break; } memcpy(Buf3, cInfo.Str, cInfo.StrLen); cInfo2.OutLen = cInfo.StrLen; Continue = NO; break; } break; case KANJI_UTF8BOM: if(ProcessedBOM == NO) { if(memcmp(Buf, "\xEF\xBB\xBF", 3) == 0) { cInfo.Str += 3; cInfo.StrLen -= 3; } cInfo2.OutLen = 0; switch(Pkt->KanjiCodeDesired) { case KANJI_UTF8BOM: memcpy(Buf3, "\xEF\xBB\xBF", 3); cInfo2.OutLen = 3; break; } Continue = YES; ProcessedBOM = YES; break; } switch(Pkt->KanjiCodeDesired) { case KANJI_SJIS: Continue = ConvUTF8NtoSJIS(&cInfo); memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_JIS: Continue = ConvUTF8NtoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoJIS(&cInfo2); break; case KANJI_EUC: Continue = ConvUTF8NtoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoEUC(&cInfo2); break; case KANJI_UTF8N: memcpy(Buf3, cInfo.Str, cInfo.StrLen); cInfo2.OutLen = cInfo.StrLen; Continue = NO; break; case KANJI_UTF8BOM: memcpy(Buf3, cInfo.Str, cInfo.StrLen); cInfo2.OutLen = cInfo.StrLen; Continue = NO; break; } break; } // if(WriteFile(iFileHandle, Buf2, cInfo.OutLen, &Writed, NULL) == FALSE) if(WriteFile(iFileHandle, Buf3, cInfo2.OutLen, &Writed, NULL) == FALSE) Pkt->Abort = ABORT_DISKFULL; } while((Continue == YES) && (Pkt->Abort == ABORT_NONE)); } else { if(WriteFile(iFileHandle, Buf, iNumBytes, &Writed, NULL) == FALSE) Pkt->Abort = ABORT_DISKFULL; } Pkt->ExistSize += iNumBytes; if(Pkt->hWndTrans != NULL) // 同時接続対応 // AllTransSizeNow += iNumBytes; AllTransSizeNow[Pkt->ThreadCount] += iNumBytes; else { /* 転送ダイアログを出さない時の経過表示 */ DispDownloadSize(Pkt->ExistSize); } if(BackgrndMessageProc() == YES) ForceAbort = YES; } /* 書き残したデータを書き込む */ if(Pkt->KanjiCode != KANJI_NOCNV) { cInfo.Buf = Buf2; cInfo.BufSize = BUFSIZE+3; FlushRestData(&cInfo); switch(Pkt->KanjiCode) { case KANJI_SJIS: switch(Pkt->KanjiCodeDesired) { case KANJI_SJIS: // カナ変換のため cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvJIStoSJIS(&cInfo2); break; case KANJI_JIS: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_EUC: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_UTF8N: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_UTF8BOM: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; } break; case KANJI_JIS: switch(Pkt->KanjiCodeDesired) { case KANJI_SJIS: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_JIS: // カナ変換のため cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoJIS(&cInfo2); break; case KANJI_EUC: cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoEUC(&cInfo2); break; case KANJI_UTF8N: cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoUTF8N(&cInfo2); break; case KANJI_UTF8BOM: cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoUTF8N(&cInfo2); break; } break; case KANJI_EUC: switch(Pkt->KanjiCodeDesired) { case KANJI_SJIS: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_JIS: cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoJIS(&cInfo2); break; case KANJI_EUC: // カナ変換のため cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoEUC(&cInfo2); break; case KANJI_UTF8N: cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoUTF8N(&cInfo2); break; case KANJI_UTF8BOM: cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoUTF8N(&cInfo2); break; } break; case KANJI_UTF8N: switch(Pkt->KanjiCodeDesired) { case KANJI_SJIS: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_JIS: cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoJIS(&cInfo2); break; case KANJI_EUC: cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoEUC(&cInfo2); break; case KANJI_UTF8N: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_UTF8BOM: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; } break; case KANJI_UTF8BOM: switch(Pkt->KanjiCodeDesired) { case KANJI_SJIS: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_JIS: cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoJIS(&cInfo2); break; case KANJI_EUC: cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoEUC(&cInfo2); break; case KANJI_UTF8N: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_UTF8BOM: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; } break; } // if(WriteFile(iFileHandle, Buf2, cInfo.OutLen, &Writed, NULL) == FALSE) if(WriteFile(iFileHandle, Buf3, cInfo2.OutLen, &Writed, NULL) == FALSE) Pkt->Abort = ABORT_DISKFULL; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; FlushRestData(&cInfo2); if(WriteFile(iFileHandle, Buf3, cInfo2.OutLen, &Writed, NULL) == FALSE) Pkt->Abort = ABORT_DISKFULL; } /* グラフ表示を更新 */ if(Pkt->hWndTrans != NULL) { KillTimer(Pkt->hWndTrans, TIMER_DISPLAY); DispTransferStatus(Pkt->hWndTrans, YES, Pkt); // 同時接続対応 // TimeStart = time(NULL) - TimeStart + 1; TimeStart[Pkt->ThreadCount] = time(NULL) - TimeStart[Pkt->ThreadCount] + 1; } else { /* 転送ダイアログを出さない時の経過表示を消す */ DispDownloadSize(-1); } /* ファイルのタイムスタンプを合わせる */ // ミラーリング設定追加 // if((SaveTimeStamp == YES) && // ((Pkt->Time.dwLowDateTime != 0) || (Pkt->Time.dwHighDateTime != 0))) // { // SetFileTime(iFileHandle, &Pkt->Time, &Pkt->Time, &Pkt->Time); // } CloseHandle(iFileHandle); if(iNumBytes == SOCKET_ERROR) ReportWSError("recv",WSAGetLastError()); } else { SetErrorMsg(MSGJPN095, Pkt->LocalFile); SetTaskMsg(MSGJPN095, Pkt->LocalFile); Pkt->Abort = ABORT_ERROR; } if(shutdown(dSkt, 1) != 0) ReportWSError("shutdown", WSAGetLastError()); // 自動切断対策 LastDataConnectionTime = time(NULL); DoClose(dSkt); if(ForceAbort == NO) { /* Abortをホストに伝える */ if(Pkt->Abort != ABORT_NONE && iFileHandle != INVALID_HANDLE_VALUE) { SendData(Pkt->ctrl_skt, "\xFF\xF4\xFF", 3, MSG_OOB, CancelCheckWork); /* MSG_OOBに注意 */ SendData(Pkt->ctrl_skt, "\xF2", 1, 0, CancelCheckWork); command(Pkt->ctrl_skt, NULL, CancelCheckWork, "ABOR"); } } iRetCode = ReadReplyMessage(Pkt->ctrl_skt, Buf, 1024, CancelCheckWork, TmpBuf); //#pragma aaa //DoPrintf("##DOWN REPLY : %s", Buf); if(Pkt->Abort == ABORT_DISKFULL) { SetErrorMsg(MSGJPN096); SetTaskMsg(MSGJPN096); } // バグ修正 // if(iRetCode >= FTP_RETRY) if((iRetCode/100) >= FTP_RETRY) SetErrorMsg(Buf); if(Pkt->Abort != ABORT_NONE) iRetCode = 500; return(iRetCode); } /*----- ダウンロード終了/中止時のメッセージを表示 ---------------------------- * * Parameter * TRANSPACKET *Pkt : 転送ファイル情報 * int iRetCode : 応答コード * * Return Value * なし *----------------------------------------------------------------------------*/ static void DispDownloadFinishMsg(TRANSPACKET *Pkt, int iRetCode) { char Fname[FMAX_PATH+1]; // 同時接続対応 ReleaseMutex(hListAccMutex); if(ForceAbort == NO) { if((iRetCode/100) >= FTP_CONTINUE) { strcpy(Fname, Pkt->RemoteFile); #if defined(HAVE_OPENVMS) /* OpenVMSの場合、空ディレクトリへ移動すると550 File not foundになって * エラーダイアログやエラーメッセージが出るので何もしない */ if (AskHostType() == HTYPE_VMS) return; #endif #if defined(HAVE_TANDEM) /* HP Nonstop Server の場合、ファイルのない subvol へ移動すると550 File not found * になるが問題ないのでエラーダイアログやエラーメッセージを出さないため */ if (AskHostType() == HTYPE_TANDEM) return; #endif // MLSD対応 // if((strncmp(Pkt->Cmd, "NLST", 4) == 0) || (strncmp(Pkt->Cmd, "LIST", 4) == 0)) if((strncmp(Pkt->Cmd, "NLST", 4) == 0) || (strncmp(Pkt->Cmd, "LIST", 4) == 0) || (strncmp(Pkt->Cmd, "MLSD", 4) == 0)) { SetTaskMsg(MSGJPN097); strcpy(Fname, MSGJPN098); } // 同時接続対応 // else if((Pkt->hWndTrans != NULL) && (TimeStart != 0)) // SetTaskMsg(MSGJPN099, TimeStart, Pkt->ExistSize/TimeStart); else if((Pkt->hWndTrans != NULL) && (TimeStart[Pkt->ThreadCount] != 0)) SetTaskMsg(MSGJPN099, TimeStart[Pkt->ThreadCount], Pkt->ExistSize/TimeStart[Pkt->ThreadCount]); else SetTaskMsg(MSGJPN100); if(Pkt->Abort != ABORT_USER) { // 全て中止を選択後にダイアログが表示されるバグ対策 // if(DispUpDownErrDialog(downerr_dlg, Pkt->hWndTrans, Fname) == NO) // 再転送対応 // if(Canceled[Pkt->ThreadCount] == NO && ClearAll == NO && DispUpDownErrDialog(downerr_dlg, Pkt->hWndTrans, Fname) == NO) // ClearAll = YES; if(Canceled[Pkt->ThreadCount] == NO && ClearAll == NO) { if(strncmp(Pkt->Cmd, "RETR", 4) == 0 || strncmp(Pkt->Cmd, "STOR", 4) == 0) { // タスクバー進捗表示 TransferErrorDisplay++; if(TransferErrorNotify == YES && DispUpDownErrDialog(downerr_dlg, Pkt->hWndTrans, Pkt) == NO) ClearAll = YES; else { Pkt->Mode = TransferErrorMode; AddTransFileList(Pkt); } // タスクバー進捗表示 TransferErrorDisplay--; } } } } else { // MLSD対応 // if((strncmp(Pkt->Cmd, "NLST", 4) == 0) || (strncmp(Pkt->Cmd, "LIST", 4) == 0)) if((strncmp(Pkt->Cmd, "NLST", 4) == 0) || (strncmp(Pkt->Cmd, "LIST", 4) == 0) || (strncmp(Pkt->Cmd, "MLSD", 4) == 0)) SetTaskMsg(MSGJPN101, Pkt->ExistSize); // 同時接続対応 // else if((Pkt->hWndTrans != NULL) && (TimeStart != 0)) // SetTaskMsg(MSGJPN102, TimeStart, Pkt->ExistSize/TimeStart); else if((Pkt->hWndTrans != NULL) && (TimeStart[Pkt->ThreadCount] != 0)) // "0 B/S"と表示されるバグを修正 // 原因は%dにあたる部分に64ビット値が渡されているため // SetTaskMsg(MSGJPN102, TimeStart[Pkt->ThreadCount], Pkt->ExistSize/TimeStart[Pkt->ThreadCount]); SetTaskMsg(MSGJPN102, (LONG)TimeStart[Pkt->ThreadCount], (LONG)(Pkt->ExistSize/TimeStart[Pkt->ThreadCount])); else SetTaskMsg(MSGJPN103, Pkt->ExistSize); } } return; } /*----- ダウンロード/アップロードエラーのダイアログを表示 -------------------- * * Parameter * int RedID : ダイアログボックスのリソースID * HWND hWnd : 書き込み中ダイアログのウインドウ * char *Fname : ファイル名 * * Return Value * int ステータス (YES=中止/NO=全て中止) *----------------------------------------------------------------------------*/ // 再転送対応 //static int DispUpDownErrDialog(int ResID, HWND hWnd, char *Fname) static int DispUpDownErrDialog(int ResID, HWND hWnd, TRANSPACKET *Pkt) { if(hWnd == NULL) hWnd = GetMainHwnd(); SoundPlay(SND_ERROR); // 再転送対応 // return(DialogBoxParam(GetFtpInst(), MAKEINTRESOURCE(ResID), hWnd, UpDownErrorDialogProc, (LPARAM)Fname)); return(DialogBoxParam(GetFtpInst(), MAKEINTRESOURCE(ResID), hWnd, UpDownErrorDialogProc, (LPARAM)Pkt)); } /*----- ダウンロードエラー/アップロードエラーダイアログのコールバック -------- * * Parameter * HWND hDlg : ウインドウハンドル * UINT message : メッセージ番号 * WPARAM wParam : メッセージの WPARAM 引数 * LPARAM lParam : メッセージの LPARAM 引数 * * Return Value * BOOL TRUE/FALSE *----------------------------------------------------------------------------*/ // 64ビット対応 //static BOOL CALLBACK UpDownErrorDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) static INT_PTR CALLBACK UpDownErrorDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { static TRANSPACKET *Pkt; static const RADIOBUTTON DownExistButton[] = { { DOWN_EXIST_OVW, EXIST_OVW }, { DOWN_EXIST_RESUME, EXIST_RESUME }, { DOWN_EXIST_IGNORE, EXIST_IGNORE } }; #define DOWNEXISTBUTTONS (sizeof(DownExistButton)/sizeof(RADIOBUTTON)) switch (message) { case WM_INITDIALOG : Pkt = (TRANSPACKET *)lParam; // SendDlgItemMessage(hDlg, UPDOWN_ERR_FNAME, WM_SETTEXT, 0, (LPARAM)lParam); SendDlgItemMessage(hDlg, UPDOWN_ERR_FNAME, WM_SETTEXT, 0, (LPARAM)Pkt->RemoteFile); // 同時接続対応 // SendDlgItemMessage(hDlg, UPDOWN_ERR_MSG, WM_SETTEXT, 0, (LPARAM)ErrMsg); SendDlgItemMessage(hDlg, UPDOWN_ERR_MSG, WM_SETTEXT, 0, (LPARAM)GetErrMsg()); if((Pkt->Type == TYPE_A) || (Pkt->ExistSize <= 0)) EnableWindow(GetDlgItem(hDlg, DOWN_EXIST_RESUME), FALSE); SetRadioButtonByValue(hDlg, TransferErrorMode, DownExistButton, DOWNEXISTBUTTONS); return(TRUE); case WM_COMMAND : switch(GET_WM_COMMAND_ID(wParam, lParam)) { case IDOK_ALL : TransferErrorNotify = NO; /* ここに break はない */ case IDOK : TransferErrorMode = AskRadioButtonValue(hDlg, DownExistButton, DOWNEXISTBUTTONS); EndDialog(hDlg, YES); break; case IDCANCEL : EndDialog(hDlg, NO); break; case IDHELP : // hHelpWin = HtmlHelp(NULL, AskHelpFilePath(), HH_HELP_CONTEXT, IDH_HELP_TOPIC_0000009); break; } return(TRUE); } return(FALSE); } /*----- ダウンロードのリジュームの準備を行う ---------------------------------- * * Parameter * TRANSPACKET *Pkt : 転送ファイル情報 * iont ProcMode : 処理モード(EXIST_xxx) * LONGLONG Size : ロード済みのファイルのサイズ * int *Mode : ファイル作成モード (CREATE_xxxx) * * Return Value * int 転送を行うかどうか(YES/NO=このファイルを中止/NO_ALL=全て中止) * * Note * Pkt->ExistSizeのセットを行なう *----------------------------------------------------------------------------*/ static int SetDownloadResume(TRANSPACKET *Pkt, int ProcMode, LONGLONG Size, int *Mode, int *CancelCheckWork) { int iRetCode; int Com; char Reply[ERR_MSG_LEN+7]; char Tmp[40]; Com = YES; Pkt->ExistSize = 0; *Mode = CREATE_ALWAYS; if(ProcMode == EXIST_RESUME) { iRetCode = command(Pkt->ctrl_skt, Reply, CancelCheckWork, "REST %s", MakeNumString(Size, Tmp, FALSE)); if(iRetCode/100 < FTP_RETRY) { /* リジューム */ if(Pkt->hWndTrans != NULL) Pkt->ExistSize = Size; *Mode = OPEN_ALWAYS; } else { Com = DialogBox(GetFtpInst(), MAKEINTRESOURCE(noresume_dlg), Pkt->hWndTrans, NoResumeWndProc); if(Com != YES) { if(Com == NO_ALL) /* 全て中止 */ ClearAll = YES; Pkt->Abort = ABORT_USER; } } } return(Com); } /*----- resumeエラーダイアログのコールバック ---------------------------------- * * Parameter * HWND hDlg : ウインドウハンドル * UINT message : メッセージ番号 * WPARAM wParam : メッセージの WPARAM 引数 * LPARAM lParam : メッセージの LPARAM 引数 * * Return Value * BOOL TRUE/FALSE *----------------------------------------------------------------------------*/ // 64ビット対応 //static BOOL CALLBACK NoResumeWndProc(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam) static INT_PTR CALLBACK NoResumeWndProc(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam) { switch (iMessage) { case WM_INITDIALOG : return(TRUE); case WM_COMMAND : switch(GET_WM_COMMAND_ID(wParam, lParam)) { case IDOK : EndDialog(hDlg, YES); break; case IDCANCEL : EndDialog(hDlg, NO); break; case RESUME_CANCEL_ALL : EndDialog(hDlg, NO_ALL); break; } return(TRUE); } return(FALSE); } /*----- アップロードを行なう -------------------------------------------------- * * Parameter * SOCKET cSkt : コントロールソケット * TRANSPACKET *Pkt : 転送ファイル情報 * * Return Value * int 応答コード *----------------------------------------------------------------------------*/ static int DoUpload(SOCKET cSkt, TRANSPACKET *Pkt) { int iRetCode; char Reply[ERR_MSG_LEN+7]; Pkt->ctrl_skt = cSkt; if(Pkt->Mode != EXIST_IGNORE) { if(CheckFileReadable(Pkt->LocalFile) == FFFTP_SUCCESS) { if(Pkt->Type == TYPE_I) Pkt->KanjiCode = KANJI_NOCNV; // 同時接続対応 // iRetCode = command(Pkt->ctrl_skt, Reply, &Canceled, "TYPE %c", Pkt->Type); iRetCode = command(Pkt->ctrl_skt, Reply, &Canceled[Pkt->ThreadCount], "TYPE %c", Pkt->Type); if(iRetCode/100 < FTP_RETRY) { if(Pkt->Mode == EXIST_UNIQUE) strcpy(Pkt->Cmd, "STOU "); if(Pkt->hWndTrans != NULL) DispTransFileInfo(Pkt, MSGJPN104, TRUE, YES); if(BackgrndMessageProc() == NO) { if(AskPasvMode() != YES) iRetCode = UploadNonPassive(Pkt); else iRetCode = UploadPassive(Pkt); } else iRetCode = 500; } else SetErrorMsg(Reply); /* 属性変更 */ if((Pkt->Attr != -1) && ((iRetCode/100) == FTP_COMPLETE)) // 同時接続対応 // command(Pkt->ctrl_skt, Reply, &Canceled, "%s %03X %s", AskHostChmodCmd(), Pkt->Attr, Pkt->RemoteFile); command(Pkt->ctrl_skt, Reply, &Canceled[Pkt->ThreadCount], "%s %03X %s", AskHostChmodCmd(), Pkt->Attr, Pkt->RemoteFile); } else { SetErrorMsg(MSGJPN105, Pkt->LocalFile); SetTaskMsg(MSGJPN105, Pkt->LocalFile); iRetCode = 500; Pkt->Abort = ABORT_ERROR; // エラーによってはダイアログが表示されない場合があるバグ対策 // DispUploadFinishMsg(Pkt, iRetCode); } // エラーによってはダイアログが表示されない場合があるバグ対策 DispUploadFinishMsg(Pkt, iRetCode); } else { DispTransFileInfo(Pkt, MSGJPN106, TRUE, YES); SetTaskMsg(MSGJPN107, Pkt->LocalFile); iRetCode = 200; } return(iRetCode); } /*----- 通常モードでファイルをアップロード ------------------------------------ * * Parameter * TRANSPACKET *Pkt : 転送ファイル情報 * * Return Value * int 応答コード *----------------------------------------------------------------------------*/ static int UploadNonPassive(TRANSPACKET *Pkt) { int iRetCode; int iLength; SOCKET data_socket = INVALID_SOCKET; // data channel socket SOCKET listen_socket = INVALID_SOCKET; // data listen socket // 念のため // char Buf[1024]; char Buf[FMAX_PATH+1024]; // IPv6対応 // struct sockaddr_in saSockAddr1; struct sockaddr_in saSockAddrIPv4; struct sockaddr_in6 saSockAddrIPv6; // UPnP対応 int Port; int Resume; char Reply[ERR_MSG_LEN+7]; // 同時接続対応 // if((listen_socket = GetFTPListenSocket(Pkt->ctrl_skt, &Canceled)) != INVALID_SOCKET) if((listen_socket = GetFTPListenSocket(Pkt->ctrl_skt, &Canceled[Pkt->ThreadCount])) != INVALID_SOCKET) { SetUploadResume(Pkt, Pkt->Mode, Pkt->ExistSize, &Resume); if(Resume == NO) #if defined(HAVE_TANDEM) if(AskHostType() == HTYPE_TANDEM && AskOSS() == NO && Pkt->Type != TYPE_A) { if( Pkt->PriExt == DEF_PRIEXT && Pkt->SecExt == DEF_SECEXT && Pkt->MaxExt == DEF_MAXEXT) { // EXTENTがデフォルトのときはコードのみ sprintf(Buf, "%s%s,%d", Pkt->Cmd, Pkt->RemoteFile, Pkt->FileCode); } else { sprintf(Buf, "%s%s,%d,%d,%d,%d", Pkt->Cmd, Pkt->RemoteFile, Pkt->FileCode, Pkt->PriExt, Pkt->SecExt, Pkt->MaxExt); } } else #endif sprintf(Buf, "%s%s", Pkt->Cmd, Pkt->RemoteFile); else sprintf(Buf, "%s%s", "APPE ", Pkt->RemoteFile); // 同時接続対応 // iRetCode = command(Pkt->ctrl_skt, Reply, &Canceled, "%s", Buf); iRetCode = command(Pkt->ctrl_skt, Reply, &Canceled[Pkt->ThreadCount], "%s", Buf); if((iRetCode/100) == FTP_PRELIM) { // STOUの応答を処理 // 応答の形式に規格が無くファイル名を取得できないため属性変更を無効化 if(Pkt->Mode == EXIST_UNIQUE) Pkt->Attr = -1; // 同時接続対応 // if(SocksGet2ndBindReply(listen_socket, &data_socket) == FFFTP_FAIL) if(SocksGet2ndBindReply(listen_socket, &data_socket, &Canceled[Pkt->ThreadCount]) == FFFTP_FAIL) { // IPv6対応 // iLength=sizeof(saSockAddr1); // data_socket = do_accept(listen_socket,(struct sockaddr *)&saSockAddr1, (int *)&iLength); switch(AskCurNetType()) { case NTYPE_IPV4: iLength=sizeof(saSockAddrIPv4); data_socket = do_accept(listen_socket,(struct sockaddr *)&saSockAddrIPv4, (int *)&iLength); break; case NTYPE_IPV6: iLength=sizeof(saSockAddrIPv6); data_socket = do_accept(listen_socket,(struct sockaddr *)&saSockAddrIPv6, (int *)&iLength); break; } if(shutdown(listen_socket, 1) != 0) ReportWSError("shutdown listen", WSAGetLastError()); // UPnP対応 if(IsUPnPLoaded() == YES) { if(GetAsyncTableDataMapPort(listen_socket, &Port) == YES) RemovePortMapping(Port); } listen_socket = DoClose(listen_socket); if(data_socket == INVALID_SOCKET) { SetErrorMsg(MSGJPN280); ReportWSError("accept", WSAGetLastError()); iRetCode = 500; } else // IPv6対応 // DoPrintf("Skt=%u : accept from %s port %u", data_socket, inet_ntoa(saSockAddr1.sin_addr), ntohs(saSockAddr1.sin_port)); { switch(AskCurNetType()) { case NTYPE_IPV4: DoPrintf("Skt=%u : accept from %s port %u", data_socket, inet_ntoa(saSockAddrIPv4.sin_addr), ntohs(saSockAddrIPv4.sin_port)); break; case NTYPE_IPV6: DoPrintf("Skt=%u : accept from %s port %u", data_socket, inet6_ntoa(saSockAddrIPv6.sin6_addr), ntohs(saSockAddrIPv6.sin6_port)); break; } } } if(data_socket != INVALID_SOCKET) { // 一部TYPE、STOR(RETR)、PORT(PASV)を並列に処理できないホストがあるため ReleaseMutex(hListAccMutex); // FTPS対応 // iRetCode = UploadFile(Pkt, data_socket); if(IsSSLAttached(Pkt->ctrl_skt)) { if(AttachSSL(data_socket, Pkt->ctrl_skt, &Canceled[Pkt->ThreadCount], FALSE, NULL)) iRetCode = UploadFile(Pkt, data_socket); else iRetCode = 500; } else iRetCode = UploadFile(Pkt, data_socket); data_socket = DoClose(data_socket); } } else { SetErrorMsg(Reply); SetTaskMsg(MSGJPN108); // UPnP対応 if(IsUPnPLoaded() == YES) { if(GetAsyncTableDataMapPort(listen_socket, &Port) == YES) RemovePortMapping(Port); } listen_socket = DoClose(listen_socket); iRetCode = 500; } } else { SetErrorMsg(MSGJPN279); iRetCode = 500; } // エラーによってはダイアログが表示されない場合があるバグ対策 // DispUploadFinishMsg(Pkt, iRetCode); return(iRetCode); } /*----- Passiveモードでファイルをアップロード --------------------------------- * * Parameter * TRANSPACKET *Pkt : 転送ファイル情報 * * Return Value * int 応答コード *----------------------------------------------------------------------------*/ static int UploadPassive(TRANSPACKET *Pkt) { int iRetCode; SOCKET data_socket = INVALID_SOCKET; // data channel socket // 念のため // char Buf[1024]; char Buf[FMAX_PATH+1024]; // IPv6対応 // char Adrs[20]; char Adrs[40]; int Port; int Flg; int Resume; char Reply[ERR_MSG_LEN+7]; // 同時接続対応 // iRetCode = command(Pkt->ctrl_skt, Buf, &Canceled, "PASV"); // IPv6対応 // iRetCode = command(Pkt->ctrl_skt, Buf, &Canceled[Pkt->ThreadCount], "PASV"); switch(AskCurNetType()) { case NTYPE_IPV4: iRetCode = command(Pkt->ctrl_skt, Buf, &Canceled[Pkt->ThreadCount], "PASV"); break; case NTYPE_IPV6: iRetCode = command(Pkt->ctrl_skt, Buf, &Canceled[Pkt->ThreadCount], "EPSV"); break; } if(iRetCode/100 == FTP_COMPLETE) { // IPv6対応 // if(GetAdrsAndPort(Buf, Adrs, &Port, 19) == FFFTP_SUCCESS) if(GetAdrsAndPort(Pkt->ctrl_skt, Buf, Adrs, &Port, 39) == FFFTP_SUCCESS) { // 同時接続対応 // if((data_socket = connectsock(Adrs, Port, MSGJPN109, &Canceled)) != INVALID_SOCKET) if((data_socket = connectsock(Adrs, Port, MSGJPN109, &Canceled[Pkt->ThreadCount])) != INVALID_SOCKET) { // 変数が未初期化のバグ修正 Flg = 1; if(setsockopt(data_socket, IPPROTO_TCP, TCP_NODELAY, (LPSTR)&Flg, sizeof(Flg)) == SOCKET_ERROR) ReportWSError("setsockopt", WSAGetLastError()); SetUploadResume(Pkt, Pkt->Mode, Pkt->ExistSize, &Resume); if(Resume == NO) #if defined(HAVE_TANDEM) if(AskHostType() == HTYPE_TANDEM && AskOSS() == NO && Pkt->Type != TYPE_A) { if( Pkt->PriExt == DEF_PRIEXT && Pkt->SecExt == DEF_SECEXT && Pkt->MaxExt == DEF_MAXEXT) { // EXTENTがデフォルトのときはコードのみ sprintf(Buf, "%s%s,%d", Pkt->Cmd, Pkt->RemoteFile, Pkt->FileCode); } else { sprintf(Buf, "%s%s,%d,%d,%d,%d", Pkt->Cmd, Pkt->RemoteFile, Pkt->FileCode, Pkt->PriExt, Pkt->SecExt, Pkt->MaxExt); } } else #endif sprintf(Buf, "%s%s", Pkt->Cmd, Pkt->RemoteFile); else sprintf(Buf, "%s%s", "APPE ", Pkt->RemoteFile); // 同時接続対応 // iRetCode = command(Pkt->ctrl_skt, Reply, &Canceled, "%s", Buf); iRetCode = command(Pkt->ctrl_skt, Reply, &Canceled[Pkt->ThreadCount], "%s", Buf); if(iRetCode/100 == FTP_PRELIM) { // STOUの応答を処理 // 応答の形式に規格が無くファイル名を取得できないため属性変更を無効化 if(Pkt->Mode == EXIST_UNIQUE) Pkt->Attr = -1; // 一部TYPE、STOR(RETR)、PORT(PASV)を並列に処理できないホストがあるため ReleaseMutex(hListAccMutex); // FTPS対応 // iRetCode = UploadFile(Pkt, data_socket); if(IsSSLAttached(Pkt->ctrl_skt)) { if(AttachSSL(data_socket, Pkt->ctrl_skt, &Canceled[Pkt->ThreadCount], FALSE, NULL)) iRetCode = UploadFile(Pkt, data_socket); else iRetCode = 500; } else iRetCode = UploadFile(Pkt, data_socket); data_socket = DoClose(data_socket); } else { SetErrorMsg(Reply); SetTaskMsg(MSGJPN110); data_socket = DoClose(data_socket); iRetCode = 500; } } else { SetErrorMsg(MSGJPN281); iRetCode = 500; } } else { SetErrorMsg(Buf); SetTaskMsg(MSGJPN111); iRetCode = 500; } } else SetErrorMsg(Buf); // エラーによってはダイアログが表示されない場合があるバグ対策 // DispUploadFinishMsg(Pkt, iRetCode); return(iRetCode); } /*----- アップロードの実行 ---------------------------------------------------- * * Parameter * TRANSPACKET *Pkt : 転送ファイル情報 * SOCKET dSkt : データソケット * * Return Value * int 応答コード * * Note * 転送の経過表示は、インターバルタイマで経過を表示する * 転送ダイアログを出さないでアップロードすることはない *----------------------------------------------------------------------------*/ static int UploadFile(TRANSPACKET *Pkt, SOCKET dSkt) { DWORD iNumBytes; HANDLE iFileHandle; SECURITY_ATTRIBUTES Sec; char Buf[BUFSIZE]; char Buf2[BUFSIZE+3]; CODECONVINFO cInfo; TERMCODECONVINFO tInfo; int Continue; char *EofPos; int iRetCode; #if 0 int TimeOutErr; #endif char TmpBuf[ONELINE_BUF_SIZE]; DWORD Low; DWORD High; #ifdef SET_BUFFER_SIZE /* Add by H.Shirouzu at 2002/10/02 */ int buf_size = SOCKBUF_SIZE; for ( ; buf_size > 0; buf_size /= 2) if (setsockopt(dSkt, SOL_SOCKET, SO_SNDBUF, (char *)&buf_size, sizeof(buf_size)) == 0) break; /* End */ #endif // 念のため送信バッファを無効にする #ifdef DISABLE_TRANSFER_NETWORK_BUFFERS int buf_size = 0; setsockopt(dSkt, SOL_SOCKET, SO_SNDBUF, (char *)&buf_size, sizeof(buf_size)); #endif Pkt->Abort = ABORT_NONE; Sec.nLength = sizeof(SECURITY_ATTRIBUTES); Sec.lpSecurityDescriptor = NULL; Sec.bInheritHandle = FALSE; if((iFileHandle = CreateFile(Pkt->LocalFile, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, &Sec, OPEN_EXISTING, 0, NULL)) != INVALID_HANDLE_VALUE) { // UTF-8対応 char Buf3[(BUFSIZE + 3) * 4]; CODECONVINFO cInfo2; int ProcessedBOM = NO; if(Pkt->hWndTrans != NULL) { Low = GetFileSize(iFileHandle, &High); Pkt->Size = MakeLongLong(High, Low); High = (DWORD)HIGH32(Pkt->ExistSize); Low = (DWORD)LOW32(Pkt->ExistSize); SetFilePointer(iFileHandle, Low, &High, FILE_BEGIN); // 同時接続対応 // AllTransSizeNow = 0; // TimeStart = time(NULL); AllTransSizeNow[Pkt->ThreadCount] = 0; TimeStart[Pkt->ThreadCount] = time(NULL); SetTimer(Pkt->hWndTrans, TIMER_DISPLAY, DISPLAY_TIMING, NULL); } InitCodeConvInfo(&cInfo); cInfo.KanaCnv = Pkt->KanaCnv; InitTermCodeConvInfo(&tInfo); InitCodeConvInfo(&cInfo2); cInfo2.KanaCnv = Pkt->KanaCnv; /*===== ファイルを送信するループ =====*/ while((Pkt->Abort == ABORT_NONE) && (ForceAbort == NO) && (ReadFile(iFileHandle, Buf, BUFSIZE, &iNumBytes, NULL) == TRUE)) { if(iNumBytes == 0) break; /* EOF除去 */ EofPos = NULL; if((RmEOF == YES) && (Pkt->Type == TYPE_A)) { if((EofPos = memchr(Buf, 0x1A, iNumBytes)) != NULL) iNumBytes = EofPos - Buf; } /* 漢字コード変換 */ if(Pkt->KanjiCode != KANJI_NOCNV) { cInfo.Str = Buf; cInfo.StrLen = iNumBytes; cInfo.Buf = Buf2; cInfo.BufSize = BUFSIZE+3; do { // ここで全てUTF-8へ変換する // TODO: SJIS以外も直接UTF-8へ変換 // if(Pkt->KanjiCode == KANJI_JIS) // Continue = ConvSJIStoJIS(&cInfo); // else // Continue = ConvSJIStoEUC(&cInfo); switch(Pkt->KanjiCodeDesired) { case KANJI_SJIS: switch(Pkt->KanjiCode) { case KANJI_SJIS: // memcpy(Buf3, cInfo.Str, cInfo.StrLen); // cInfo2.OutLen = cInfo.StrLen; // Continue = NO; // カナ変換のため Continue = ConvSJIStoJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvJIStoSJIS(&cInfo2); break; case KANJI_JIS: Continue = ConvSJIStoJIS(&cInfo); memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_EUC: Continue = ConvSJIStoEUC(&cInfo); memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_UTF8N: Continue = ConvSJIStoUTF8N(&cInfo); memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_UTF8BOM: if(ProcessedBOM == NO) { memcpy(Buf3, "\xEF\xBB\xBF", 3); cInfo2.OutLen = 3; Continue = YES; ProcessedBOM = YES; break; } Continue = ConvSJIStoUTF8N(&cInfo); memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; } break; case KANJI_JIS: switch(Pkt->KanjiCode) { case KANJI_SJIS: Continue = ConvJIStoSJIS(&cInfo); memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_JIS: // memcpy(Buf3, cInfo.Str, cInfo.StrLen); // cInfo2.OutLen = cInfo.StrLen; // Continue = NO; // カナ変換のため Continue = ConvJIStoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoJIS(&cInfo2); break; case KANJI_EUC: Continue = ConvJIStoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoEUC(&cInfo2); break; case KANJI_UTF8N: Continue = ConvJIStoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoUTF8N(&cInfo2); break; case KANJI_UTF8BOM: if(ProcessedBOM == NO) { memcpy(Buf3, "\xEF\xBB\xBF", 3); cInfo2.OutLen = 3; Continue = YES; ProcessedBOM = YES; break; } Continue = ConvJIStoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoUTF8N(&cInfo2); break; } break; case KANJI_EUC: switch(Pkt->KanjiCode) { case KANJI_SJIS: Continue = ConvEUCtoSJIS(&cInfo); memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_JIS: Continue = ConvEUCtoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoJIS(&cInfo2); break; case KANJI_EUC: // memcpy(Buf3, cInfo.Str, cInfo.StrLen); // cInfo2.OutLen = cInfo.StrLen; // Continue = NO; // カナ変換のため Continue = ConvEUCtoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoEUC(&cInfo2); break; case KANJI_UTF8N: Continue = ConvEUCtoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoUTF8N(&cInfo2); break; case KANJI_UTF8BOM: if(ProcessedBOM == NO) { memcpy(Buf3, "\xEF\xBB\xBF", 3); cInfo2.OutLen = 3; Continue = YES; ProcessedBOM = YES; break; } Continue = ConvEUCtoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoUTF8N(&cInfo2); break; } break; case KANJI_UTF8N: switch(Pkt->KanjiCode) { case KANJI_SJIS: Continue = ConvUTF8NtoSJIS(&cInfo); memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_JIS: Continue = ConvUTF8NtoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoJIS(&cInfo2); break; case KANJI_EUC: Continue = ConvUTF8NtoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoEUC(&cInfo2); break; case KANJI_UTF8N: memcpy(Buf3, cInfo.Str, cInfo.StrLen); cInfo2.OutLen = cInfo.StrLen; Continue = NO; break; case KANJI_UTF8BOM: if(ProcessedBOM == NO) { memcpy(Buf3, "\xEF\xBB\xBF", 3); cInfo2.OutLen = 3; Continue = YES; ProcessedBOM = YES; break; } memcpy(Buf3, cInfo.Str, cInfo.StrLen); cInfo2.OutLen = cInfo.StrLen; Continue = NO; break; } break; case KANJI_UTF8BOM: if(ProcessedBOM == NO) { if(memcmp(Buf, "\xEF\xBB\xBF", 3) == 0) { cInfo.Str += 3; cInfo.StrLen -= 3; } cInfo2.OutLen = 0; switch(Pkt->KanjiCode) { case KANJI_UTF8BOM: memcpy(Buf3, "\xEF\xBB\xBF", 3); cInfo2.OutLen = 3; break; } Continue = YES; ProcessedBOM = YES; break; } switch(Pkt->KanjiCode) { case KANJI_SJIS: Continue = ConvUTF8NtoSJIS(&cInfo); memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_JIS: Continue = ConvUTF8NtoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoJIS(&cInfo2); break; case KANJI_EUC: Continue = ConvUTF8NtoSJIS(&cInfo); cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoEUC(&cInfo2); break; case KANJI_UTF8N: memcpy(Buf3, cInfo.Str, cInfo.StrLen); cInfo2.OutLen = cInfo.StrLen; Continue = NO; break; case KANJI_UTF8BOM: memcpy(Buf3, cInfo.Str, cInfo.StrLen); cInfo2.OutLen = cInfo.StrLen; Continue = NO; break; } break; } // if(TermCodeConvAndSend(&tInfo, dSkt, Buf2, cInfo.OutLen, Pkt->Type) == FFFTP_FAIL) if(TermCodeConvAndSend(&tInfo, dSkt, Buf3, cInfo2.OutLen, Pkt->Type, &Canceled[Pkt->ThreadCount]) == FFFTP_FAIL) { Pkt->Abort = ABORT_ERROR; break; } } while(Continue == YES); } else { // 同時接続対応 // if(TermCodeConvAndSend(&tInfo, dSkt, Buf, iNumBytes, Pkt->Type) == FFFTP_FAIL) if(TermCodeConvAndSend(&tInfo, dSkt, Buf, iNumBytes, Pkt->Type, &Canceled[Pkt->ThreadCount]) == FFFTP_FAIL) Pkt->Abort = ABORT_ERROR; } Pkt->ExistSize += iNumBytes; if(Pkt->hWndTrans != NULL) // 同時接続対応 // AllTransSizeNow += iNumBytes; AllTransSizeNow[Pkt->ThreadCount] += iNumBytes; if(BackgrndMessageProc() == YES) ForceAbort = YES; if(EofPos != NULL) break; } if((ForceAbort == NO) && (Pkt->Abort == ABORT_NONE)) { /* 送り残したデータを送信 */ if(Pkt->KanjiCode != KANJI_NOCNV) { cInfo.Buf = Buf2; cInfo.BufSize = BUFSIZE+3; FlushRestData(&cInfo); switch(Pkt->KanjiCodeDesired) { case KANJI_SJIS: switch(Pkt->KanjiCode) { case KANJI_SJIS: // カナ変換のため cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvJIStoSJIS(&cInfo2); break; case KANJI_JIS: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_EUC: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_UTF8N: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_UTF8BOM: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; } break; case KANJI_JIS: switch(Pkt->KanjiCode) { case KANJI_SJIS: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_JIS: // カナ変換のため cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoJIS(&cInfo2); break; case KANJI_EUC: cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoEUC(&cInfo2); break; case KANJI_UTF8N: cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoUTF8N(&cInfo2); break; case KANJI_UTF8BOM: cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoUTF8N(&cInfo2); break; } break; case KANJI_EUC: switch(Pkt->KanjiCode) { case KANJI_SJIS: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_JIS: cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoJIS(&cInfo2); break; case KANJI_EUC: // カナ変換のため cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoEUC(&cInfo2); break; case KANJI_UTF8N: cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoUTF8N(&cInfo2); break; case KANJI_UTF8BOM: cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoUTF8N(&cInfo2); break; } break; case KANJI_UTF8N: switch(Pkt->KanjiCode) { case KANJI_SJIS: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_JIS: cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoJIS(&cInfo2); break; case KANJI_EUC: cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoEUC(&cInfo2); break; case KANJI_UTF8N: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_UTF8BOM: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; } break; case KANJI_UTF8BOM: switch(Pkt->KanjiCode) { case KANJI_SJIS: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_JIS: cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoJIS(&cInfo2); break; case KANJI_EUC: cInfo2.Str = cInfo.Buf; cInfo2.StrLen = cInfo.OutLen; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; ConvSJIStoEUC(&cInfo2); break; case KANJI_UTF8N: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; case KANJI_UTF8BOM: memcpy(Buf3, cInfo.Buf, cInfo.OutLen); cInfo2.OutLen = cInfo.OutLen; break; } break; } // if(TermCodeConvAndSend(&tInfo, dSkt, Buf2, cInfo.OutLen, Pkt->Type) == FFFTP_FAIL) if(TermCodeConvAndSend(&tInfo, dSkt, Buf3, cInfo2.OutLen, Pkt->Type, &Canceled[Pkt->ThreadCount]) == FFFTP_FAIL) Pkt->Abort = ABORT_ERROR; cInfo2.Buf = Buf3; cInfo2.BufSize = (BUFSIZE + 3) * 4; FlushRestData(&cInfo2); if(TermCodeConvAndSend(&tInfo, dSkt, Buf3, cInfo2.OutLen, Pkt->Type, &Canceled[Pkt->ThreadCount]) == FFFTP_FAIL) Pkt->Abort = ABORT_ERROR; } tInfo.Buf = Buf2; tInfo.BufSize = BUFSIZE+3; FlushRestTermCodeConvData(&tInfo); // 同時接続対応 // if(SendData(dSkt, Buf2, tInfo.OutLen, 0, &Canceled) == FFFTP_FAIL) if(SendData(dSkt, Buf2, tInfo.OutLen, 0, &Canceled[Pkt->ThreadCount]) == FFFTP_FAIL) Pkt->Abort = ABORT_ERROR; } /* グラフ表示を更新 */ if(Pkt->hWndTrans != NULL) { KillTimer(Pkt->hWndTrans, TIMER_DISPLAY); DispTransferStatus(Pkt->hWndTrans, YES, Pkt); // 同時接続対応 // TimeStart = time(NULL) - TimeStart + 1; TimeStart[Pkt->ThreadCount] = time(NULL) - TimeStart[Pkt->ThreadCount] + 1; } CloseHandle(iFileHandle); } else { SetErrorMsg(MSGJPN112, Pkt->LocalFile); SetTaskMsg(MSGJPN112, Pkt->LocalFile); Pkt->Abort = ABORT_ERROR; } // 自動切断対策 LastDataConnectionTime = time(NULL); if(shutdown(dSkt, 1) != 0) ReportWSError("shutdown", WSAGetLastError()); #if 0 /* clean up */ while(do_recv(dSkt, Buf, BUFSIZE, 0, &TimeOutErr, &Canceled) > 0) ; #endif // 同時接続対応 // iRetCode = ReadReplyMessage(Pkt->ctrl_skt, Buf, 1024, &Canceled, TmpBuf); iRetCode = ReadReplyMessage(Pkt->ctrl_skt, Buf, 1024, &Canceled[Pkt->ThreadCount], TmpBuf); //#pragma aaa //DoPrintf("##UP REPLY : %s", Buf); // バグ修正 // if(iRetCode >= FTP_RETRY) if((iRetCode/100) >= FTP_RETRY) SetErrorMsg(Buf); if(Pkt->Abort != ABORT_NONE) iRetCode = 500; return(iRetCode); } /*----- バッファの内容を改行コード変換して送信 -------------------------------- * * Parameter * TERMCODECONVINFO *tInfo : 改行コード変換パケット * SOCKET Skt : ソケット * char *Data : データ * int Size : データのサイズ * int Ascii : モード  (TYPE_xx) * * Return Value * int 応答コード *----------------------------------------------------------------------------*/ // 同時接続対応 //static int TermCodeConvAndSend(TERMCODECONVINFO *tInfo, SOCKET Skt, char *Data, int Size, int Ascii) static int TermCodeConvAndSend(TERMCODECONVINFO *tInfo, SOCKET Skt, char *Data, int Size, int Ascii, int *CancelCheckWork) { char Buf3[BUFSIZE*2]; int Continue; int Ret; Ret = FFFTP_SUCCESS; // CR-LF以外の改行コードを変換しないモードはここへ追加 if(Ascii == TYPE_A) { tInfo->Str = Data; tInfo->StrLen = Size; tInfo->Buf = Buf3; tInfo->BufSize = BUFSIZE*2; do { Continue = ConvTermCodeToCRLF(tInfo); // 同時接続対応 // if((Ret = SendData(Skt, Buf3, tInfo->OutLen, 0, &Canceled)) == FFFTP_FAIL) if((Ret = SendData(Skt, Buf3, tInfo->OutLen, 0, CancelCheckWork)) == FFFTP_FAIL) break; } while(Continue == YES); } else // 同時接続対応 // Ret = SendData(Skt, Data, Size, 0, &Canceled); Ret = SendData(Skt, Data, Size, 0, CancelCheckWork); return(Ret); } /*----- アップロード終了/中止時のメッセージを表示 ---------------------------- * * Parameter * TRANSPACKET *Pkt : 転送ファイル情報 * int iRetCode : 応答コード * * Return Value * なし *----------------------------------------------------------------------------*/ static void DispUploadFinishMsg(TRANSPACKET *Pkt, int iRetCode) { // 同時接続対応 ReleaseMutex(hListAccMutex); if(ForceAbort == NO) { if((iRetCode/100) >= FTP_CONTINUE) { // 同時接続対応 // if((Pkt->hWndTrans != NULL) && (TimeStart != 0)) // SetTaskMsg(MSGJPN113, TimeStart, Pkt->ExistSize/TimeStart); if((Pkt->hWndTrans != NULL) && (TimeStart[Pkt->ThreadCount] != 0)) SetTaskMsg(MSGJPN113, TimeStart[Pkt->ThreadCount], Pkt->ExistSize/TimeStart[Pkt->ThreadCount]); else SetTaskMsg(MSGJPN114); if(Pkt->Abort != ABORT_USER) { // 全て中止を選択後にダイアログが表示されるバグ対策 // if(DispUpDownErrDialog(uperr_dlg, Pkt->hWndTrans, Pkt->LocalFile) == NO) // 再転送対応 // if(Canceled[Pkt->ThreadCount] == NO && ClearAll == NO && DispUpDownErrDialog(uperr_dlg, Pkt->hWndTrans, Pkt->LocalFile) == NO) // ClearAll = YES; if(Canceled[Pkt->ThreadCount] == NO && ClearAll == NO) { if(strncmp(Pkt->Cmd, "RETR", 4) == 0 || strncmp(Pkt->Cmd, "STOR", 4) == 0) { // タスクバー進捗表示 TransferErrorDisplay++; if(TransferErrorNotify == YES && DispUpDownErrDialog(uperr_dlg, Pkt->hWndTrans, Pkt) == NO) ClearAll = YES; else { Pkt->Mode = TransferErrorMode; AddTransFileList(Pkt); } // タスクバー進捗表示 TransferErrorDisplay--; } } } } else { // 同時接続対応 // if((Pkt->hWndTrans != NULL) && (TimeStart != 0)) // SetTaskMsg(MSGJPN115, TimeStart, Pkt->ExistSize/TimeStart); if((Pkt->hWndTrans != NULL) && (TimeStart[Pkt->ThreadCount] != 0)) // "0 B/S"と表示されるバグを修正 // 原因は%dにあたる部分に64ビット値が渡されているため // SetTaskMsg(MSGJPN115, TimeStart[Pkt->ThreadCount], Pkt->ExistSize/TimeStart[Pkt->ThreadCount]); SetTaskMsg(MSGJPN115, (LONG)TimeStart[Pkt->ThreadCount], (LONG)(Pkt->ExistSize/TimeStart[Pkt->ThreadCount])); else SetTaskMsg(MSGJPN116); } } return; } /*----- アップロードのリジュームの準備を行う ---------------------------------- * * Parameter * TRANSPACKET *Pkt : 転送ファイル情報 * iont ProcMode : 処理モード(EXIST_xxx) * LONGLONG Size : ホストにあるファイルのサイズ * int *Mode : リジュームを行うかどうか (YES/NO) * * Return Value * int ステータス = YES * * Note * Pkt->ExistSizeのセットを行なう *----------------------------------------------------------------------------*/ static int SetUploadResume(TRANSPACKET *Pkt, int ProcMode, LONGLONG Size, int *Mode) { Pkt->ExistSize = 0; *Mode = NO; if(ProcMode == EXIST_RESUME) { if(Pkt->hWndTrans != NULL) { Pkt->ExistSize = Size; *Mode = YES; } } return(YES); } /*----- 転送中ダイアログボックスのコールバック -------------------------------- * * Parameter * HWND hDlg : ウインドウハンドル * UINT message : メッセージ番号 * WPARAM wParam : メッセージの WPARAM 引数 * LPARAM lParam : メッセージの LPARAM 引数 * * Return Value * BOOL TRUE/FALSE *----------------------------------------------------------------------------*/ static LRESULT CALLBACK TransDlgProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam) { RECT RectDlg; RECT RectPar; HMENU hMenu; // 同時接続対応 // static TRANSPACKET *Pkt; TRANSPACKET *Pkt; int i; switch(Msg) { case WM_INITDIALOG : GetWindowRect(hDlg, &RectDlg); RectDlg.right -= RectDlg.left; RectDlg.bottom -= RectDlg.top; GetWindowRect(GetMainHwnd(), &RectPar); MoveWindow(hDlg, ((RectPar.right + RectPar.left) / 2) - (RectDlg.right / 2), ((RectPar.bottom + RectPar.top) / 2) - (RectDlg.bottom / 2), RectDlg.right, RectDlg.bottom, FALSE); hMenu = GetSystemMenu(hDlg, FALSE); EnableMenuItem(hMenu, SC_CLOSE, MF_GRAYED); break; case WM_COMMAND : switch(LOWORD(wParam)) { case TRANS_STOP_NEXT : ClearAll = YES; break; case TRANS_STOP_ALL : ClearAll = YES; for(i = 0; i < MAX_DATA_CONNECTION; i++) Canceled[i] = YES; /* ここに break はない */ case IDCANCEL : // 64ビット対応 // if(!(Pkt = (TRANSPACKET*)GetWindowLong(hDlg, GWL_USERDATA))) if(!(Pkt = (TRANSPACKET*)GetWindowLongPtr(hDlg, GWLP_USERDATA))) break; Pkt->Abort = ABORT_USER; // Canceled = YES; Canceled[Pkt->ThreadCount] = YES; break; } break; case WM_TIMER : if(wParam == TIMER_DISPLAY) { if(MoveToForeground == YES) SetForegroundWindow(hDlg); MoveToForeground = NO; KillTimer(hDlg, TIMER_DISPLAY); // 64ビット対応 // if(!(Pkt = (TRANSPACKET*)GetWindowLong(hDlg, GWL_USERDATA))) if(!(Pkt = (TRANSPACKET*)GetWindowLongPtr(hDlg, GWLP_USERDATA))) break; DispTransferStatus(hDlg, NO, Pkt); SetTimer(hDlg, TIMER_DISPLAY, DISPLAY_TIMING, NULL); } break; case WM_SET_PACKET : // Pkt = (TRANSPACKET *)lParam; // 64ビット対応 // SetWindowLong(hDlg, GWL_USERDATA, (LONG)lParam); SetWindowLongPtr(hDlg, GWLP_USERDATA, (LONG_PTR)lParam); break; } return(FALSE); } /*----- 転送ステータスを表示 -------------------------------------------------- * * Parameter * HWND hWnd : ウインドウハンドル * int End : 転送が完了したかどうか (YES/NO) * * Return Value * なし *----------------------------------------------------------------------------*/ static void DispTransferStatus(HWND hWnd, int End, TRANSPACKET *Pkt) { time_t TotalLap; int Per; LONGLONG Bps; LONGLONG Transed; char Num1[40]; char Num2[40]; char Tmp[80]; char Str[80]; char *Pos; if(hWnd != NULL) { SendMessage(hWnd, WM_GETTEXT, 79, (LPARAM)Str); if((Pos = strchr(Str, ')')) != NULL) Pos ++; else Pos = Str; sprintf(Tmp, "(%d)%s", AskTransferFileNum(), Pos); SendMessage(hWnd, WM_SETTEXT, 0, (LPARAM)Tmp); if(Pkt->Abort == ABORT_NONE) { if(End == NO) { // 同時接続対応 // TotalLap = time(NULL) - TimeStart + 1; TotalLap = time(NULL) - TimeStart[Pkt->ThreadCount] + 1; Bps = 0; if(TotalLap != 0) // 同時接続対応 // Bps = AllTransSizeNow / TotalLap; Bps = AllTransSizeNow[Pkt->ThreadCount] / TotalLap; Transed = Pkt->Size - Pkt->ExistSize; if(Pkt->Size <= 0) sprintf(Tmp, "%d ", Pkt->ExistSize); else if(Pkt->Size < 1024) sprintf(Tmp, "%s / %s ", MakeNumString(Pkt->ExistSize, Num1, TRUE), MakeNumString(Pkt->Size, Num2, TRUE)); else sprintf(Tmp, "%sk / %sk ", MakeNumString(Pkt->ExistSize/1024, Num1, TRUE), MakeNumString(Pkt->Size/1024, Num2, TRUE)); strcpy(Str, Tmp); if(Bps == 0) sprintf(Tmp, "( 0 B/S )"); else if(Bps < 1000) sprintf(Tmp, "( %s B/S )", MakeNumString(Bps, Num1, TRUE)); else sprintf(Tmp, "( %s.%02d KB/S )", MakeNumString(Bps/1000, Num1, TRUE), (int)((Bps%1000)/10)); strcat(Str, Tmp); if((Bps > 0) && (Pkt->Size > 0) && (Transed >= 0)) { sprintf(Tmp, " %d:%02d", (int)((Transed/Bps)/60), (int)((Transed/Bps)%60)); strcat(Str, Tmp); } else strcat(Str, " ??:??"); } else strcpy(Str, MSGJPN117); } else strcpy(Str, MSGJPN118); SendDlgItemMessage(hWnd, TRANS_STATUS, WM_SETTEXT, 0, (LPARAM)Str); if(Pkt->Size <= 0) Per = 0; else if(Pkt->Size < 1024*1024) Per = (int)(Pkt->ExistSize * 100 / Pkt->Size); else Per = (int)((Pkt->ExistSize/1024) * 100 / (Pkt->Size/1024)); SendDlgItemMessage(hWnd, TRANS_TIME_BAR, PBM_SETPOS, Per, 0); } return; } /*----- 転送するファイルの情報を表示 ------------------------------------------ * * Parameter * TRANSPACKET *Pkt : 転送ファイル情報 * char *Title : ウインドウのタイトル * int SkipButton : 「このファイルを中止」ボタンの有無 (TRUE/FALSE) * int Info : ファイル情報を表示するかどうか (YES/NO) * * Return Value * なし *----------------------------------------------------------------------------*/ static void DispTransFileInfo(TRANSPACKET *Pkt, char *Title, int SkipButton, int Info) { char Tmp[40]; if(Pkt->hWndTrans != NULL) { EnableWindow(GetDlgItem(Pkt->hWndTrans, IDCANCEL), SkipButton); sprintf(Tmp, "(%d)%s", AskTransferFileNum(), Title); SendMessage(Pkt->hWndTrans, WM_SETTEXT, 0, (LPARAM)Tmp); SendDlgItemMessage(Pkt->hWndTrans, TRANS_STATUS, WM_SETTEXT, 0, (LPARAM)""); SendDlgItemMessage(Pkt->hWndTrans, TRANS_TIME_BAR, PBM_SETRANGE, 0, MAKELPARAM(0, 100)); SendDlgItemMessage(Pkt->hWndTrans, TRANS_TIME_BAR, PBM_SETSTEP, 1, 0); SendDlgItemMessage(Pkt->hWndTrans, TRANS_TIME_BAR, PBM_SETPOS, 0, 0); if(Info == YES) { DispStaticText(GetDlgItem(Pkt->hWndTrans, TRANS_REMOTE), Pkt->RemoteFile); DispStaticText(GetDlgItem(Pkt->hWndTrans, TRANS_LOCAL), Pkt->LocalFile); if(Pkt->Type == TYPE_I) SendDlgItemMessage(Pkt->hWndTrans, TRANS_MODE, WM_SETTEXT, 0, (LPARAM)MSGJPN119); else if(Pkt->Type == TYPE_A) SendDlgItemMessage(Pkt->hWndTrans, TRANS_MODE, WM_SETTEXT, 0, (LPARAM)MSGJPN120); // UTF-8対応 if(Pkt->KanjiCode == KANJI_NOCNV) SendDlgItemMessage(Pkt->hWndTrans, TRANS_KANJI, WM_SETTEXT, 0, (LPARAM)MSGJPN121); else if(Pkt->KanjiCode == KANJI_SJIS) SendDlgItemMessage(Pkt->hWndTrans, TRANS_KANJI, WM_SETTEXT, 0, (LPARAM)MSGJPN305); else if(Pkt->KanjiCode == KANJI_JIS) SendDlgItemMessage(Pkt->hWndTrans, TRANS_KANJI, WM_SETTEXT, 0, (LPARAM)MSGJPN122); else if(Pkt->KanjiCode == KANJI_EUC) SendDlgItemMessage(Pkt->hWndTrans, TRANS_KANJI, WM_SETTEXT, 0, (LPARAM)MSGJPN123); else if(Pkt->KanjiCode == KANJI_UTF8N) SendDlgItemMessage(Pkt->hWndTrans, TRANS_KANJI, WM_SETTEXT, 0, (LPARAM)MSGJPN306); else if(Pkt->KanjiCode == KANJI_UTF8BOM) SendDlgItemMessage(Pkt->hWndTrans, TRANS_KANJI, WM_SETTEXT, 0, (LPARAM)MSGJPN329); } else { SendDlgItemMessage(Pkt->hWndTrans, TRANS_REMOTE, WM_SETTEXT, 0, (LPARAM)""); SendDlgItemMessage(Pkt->hWndTrans, TRANS_LOCAL, WM_SETTEXT, 0, (LPARAM)""); SendDlgItemMessage(Pkt->hWndTrans, TRANS_MODE, WM_SETTEXT, 0, (LPARAM)""); SendDlgItemMessage(Pkt->hWndTrans, TRANS_KANJI, WM_SETTEXT, 0, (LPARAM)""); } } return; } /*----- PASVコマンドの戻り値からアドレスとポート番号を抽出 -------------------- * * Parameter * char *Str : PASVコマンドのリプライ * char *Adrs : アドレスのコピー先 ("www.xxx.yyy.zzz") * int *Port : ポート番号をセットするワーク * int Max : アドレス文字列の最大長 * * Return Value * int ステータス * FFFTP_SUCCESS/FFFTP_FAIL *----------------------------------------------------------------------------*/ static int GetAdrsAndPort(SOCKET Skt, char *Str, char *Adrs, int *Port, int Max) { int Result; Result = FFFTP_FAIL; switch(AskCurNetType()) { case NTYPE_IPV4: Result = GetAdrsAndPortIPv4(Skt, Str, Adrs, Port, Max); break; case NTYPE_IPV6: Result = GetAdrsAndPortIPv6(Skt, Str, Adrs, Port, Max); break; } return Result; } // IPv6対応 //static int GetAdrsAndPort(char *Str, char *Adrs, int *Port, int Max) static int GetAdrsAndPortIPv4(SOCKET Skt, char *Str, char *Adrs, int *Port, int Max) { char *Pos; char *Btm; // コンマではなくドットを返すホストがあるため char *OldBtm; int Sts; // ホスト側の設定ミス対策 struct sockaddr_in SockAddr; Sts = FFFTP_FAIL; Pos = strchr(Str, '('); if(Pos != NULL) { Pos++; Btm = strchr(Pos, ','); // コンマではなくドットを返すホストがあるため if(Btm == NULL) Btm = strchr(Pos, '.'); if(Btm != NULL) { Btm++; // コンマではなくドットを返すホストがあるため // Btm = strchr(Btm, ','); OldBtm = Btm; Btm = strchr(OldBtm, ','); if(Btm == NULL) Btm = strchr(OldBtm, '.'); if(Btm != NULL) { Btm++; // コンマではなくドットを返すホストがあるため // Btm = strchr(Btm, ','); OldBtm = Btm; Btm = strchr(OldBtm, ','); if(Btm == NULL) Btm = strchr(OldBtm, '.'); if(Btm != NULL) { Btm++; // コンマではなくドットを返すホストがあるため // Btm = strchr(Btm, ','); OldBtm = Btm; Btm = strchr(OldBtm, ','); if(Btm == NULL) Btm = strchr(OldBtm, '.'); if(Btm != NULL) { if((Btm - Pos) <= Max) { // ホスト側の設定ミス対策 // strncpy(Adrs, Pos, Btm - Pos); // *(Adrs + (Btm - Pos)) = NUL; // ReplaceAll(Adrs, ',', '.'); if(AskNoPasvAdrs() == NO) { strncpy(Adrs, Pos, Btm - Pos); *(Adrs + (Btm - Pos)) = NUL; ReplaceAll(Adrs, ',', '.'); } else { if(GetAsyncTableDataIPv4(Skt, &SockAddr, NULL) == YES) AddressToStringIPv4(Adrs, &SockAddr.sin_addr); } Pos = Btm + 1; Btm = strchr(Pos, ','); // コンマではなくドットを返すホストがあるため if(Btm == NULL) Btm = strchr(Pos, '.'); if(Btm != NULL) { Btm++; *Port = (atoi(Pos) * 0x100) + atoi(Btm); Sts = FFFTP_SUCCESS; } } } } } } } return(Sts); } // IPv6対応 static int GetAdrsAndPortIPv6(SOCKET Skt, char *Str, char *Adrs, int *Port, int Max) { char *Pos; char *Btm; int Sts; // int i; struct sockaddr_in6 SockAddr; Sts = FFFTP_FAIL; Btm = strchr(Str, '('); if(Btm != NULL) { Btm++; Btm = strchr(Btm, '|'); if(Btm != NULL) { Pos = Btm + 1; Btm = strchr(Pos, '|'); if(Btm != NULL) { Pos = Btm + 1; Btm = strchr(Pos, '|'); if(Btm != NULL) { if((Btm - Pos) <= Max) { // ホスト側の設定ミス対策 if(AskNoPasvAdrs() == NO && (Btm - Pos) > 0) { strncpy(Adrs, Pos, Btm - Pos); *(Adrs + (Btm - Pos)) = NUL; } else { // i = sizeof(SockAddr); // if(getpeername(Skt, (struct sockaddr*)&SockAddr, &i) != SOCKET_ERROR) if(GetAsyncTableDataIPv6(Skt, &SockAddr, NULL) == YES) AddressToStringIPv6(Adrs, &SockAddr.sin6_addr); } Pos = Btm + 1; Btm = strchr(Pos, '|'); if(Btm != NULL) { Btm++; *Port = atoi(Pos); Btm = strchr(Btm, ')'); if(Btm != NULL) Sts = FFFTP_SUCCESS; } } } } } } return(Sts); } /*----- Windowsのスペシャルデバイスかどうかを返す ----------------------------- * * Parameter * char *Fname : ファイル名 * * Return Value * int ステータス (YES/NO) *----------------------------------------------------------------------------*/ static int IsSpecialDevice(char *Fname) { int Sts; Sts = NO; // 比較が不完全なバグ修正 // if((_stricmp(Fname, "CON") == 0) || // (_stricmp(Fname, "PRN") == 0) || // (_stricmp(Fname, "AUX") == 0) || // (_strnicmp(Fname, "CON.", 4) == 0) || // (_strnicmp(Fname, "PRN.", 4) == 0) || // (_strnicmp(Fname, "AUX.", 4) == 0)) // { // Sts = YES; // } if(_strnicmp(Fname, "AUX", 3) == 0|| _strnicmp(Fname, "CON", 3) == 0 || _strnicmp(Fname, "NUL", 3) == 0 || _strnicmp(Fname, "PRN", 3) == 0) { if(*(Fname + 3) == '\0' || *(Fname + 3) == '.') Sts = YES; } else if(_strnicmp(Fname, "COM", 3) == 0 || _strnicmp(Fname, "LPT", 3) == 0) { if(isdigit(*(Fname + 3)) != 0) { if(*(Fname + 4) == '\0' || *(Fname + 4) == '.') Sts = YES; } } return(Sts); } /*----- ミラーリングでのファイル削除確認 -------------------------------------- * * Parameter * int Cur * int Notify * TRANSPACKET *Pkt * * Return Value * BOOL TRUE/FALSE *----------------------------------------------------------------------------*/ static int MirrorDelNotify(int Cur, int Notify, TRANSPACKET *Pkt) { MIRRORDELETEINFO DelInfo; HWND hWnd; if(((Cur == WIN_LOCAL) && (MirDownDelNotify == NO)) || ((Cur == WIN_REMOTE) && (MirUpDelNotify == NO))) { Notify = YES_ALL; } if(Notify != YES_ALL) { DelInfo.Cur = Cur; DelInfo.Pkt = Pkt; hWnd = Pkt->hWndTrans; if(hWnd == NULL) hWnd = GetMainHwnd(); Notify = DialogBoxParam(GetFtpInst(), MAKEINTRESOURCE(delete_dlg), hWnd, MirrorDeleteDialogCallBack, (LPARAM)&DelInfo); } return(Notify); } /*----- ミラーリングでのファイル削除ダイアログのコールバック ------------------ * * Parameter * HWND hDlg : ウインドウハンドル * UINT message : メッセージ番号 * WPARAM wParam : メッセージの WPARAM 引数 * LPARAM lParam : メッセージの LPARAM 引数 * * Return Value * BOOL TRUE/FALSE *----------------------------------------------------------------------------*/ // 64ビット対応 //static BOOL CALLBACK MirrorDeleteDialogCallBack(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam) static INT_PTR CALLBACK MirrorDeleteDialogCallBack(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam) { static MIRRORDELETEINFO *DelInfo; switch (iMessage) { case WM_INITDIALOG : DelInfo = (MIRRORDELETEINFO *)lParam; if(DelInfo->Cur == WIN_LOCAL) { SendMessage(hDlg, WM_SETTEXT, 0, (LPARAM)MSGJPN124); SendDlgItemMessage(hDlg, DELETE_TEXT, WM_SETTEXT, 0, (LPARAM)DelInfo->Pkt->LocalFile); } else { SendMessage(hDlg, WM_SETTEXT, 0, (LPARAM)MSGJPN125); SendDlgItemMessage(hDlg, DELETE_TEXT, WM_SETTEXT, 0, (LPARAM)DelInfo->Pkt->RemoteFile); } return(TRUE); case WM_COMMAND : switch(GET_WM_COMMAND_ID(wParam, lParam)) { case IDOK : EndDialog(hDlg, YES); break; case DELETE_NO : EndDialog(hDlg, NO); break; case DELETE_ALL : EndDialog(hDlg, YES_ALL); break; case IDCANCEL : ClearAll = YES; EndDialog(hDlg, NO_ALL); break; } return(TRUE); } return(FALSE); } static void SetErrorMsg(char *fmt, ...) { va_list Args; // 同時接続対応 // if(strlen(ErrMsg) == 0) if(strlen(GetErrMsg()) == 0) { va_start(Args, fmt); // 同時接続対応 // wvsprintf(ErrMsg, fmt, Args); wvsprintf(GetErrMsg(), fmt, Args); va_end(Args); } return; } /*----- ダウンロード時の不正なパスをチェック ---------------------------------- * * Parameter * TRANSPACKET *packet : ダウンロード情報 * * Return Value * int YES=不正なパス/NO=問題ないパス *----------------------------------------------------------------------------*/ int CheckPathViolation(TRANSPACKET *packet) { int result = NO; char *msg; if((strncmp(packet->RemoteFile, "..\\", 3) == 0) || (strncmp(packet->RemoteFile, "../", 3) == 0) || (strstr(packet->RemoteFile, "\\..\\") != NULL) || (strstr(packet->RemoteFile, "/../") != NULL)) { msg = malloc(strlen(MSGJPN297) + strlen(packet->RemoteFile) + 1); if(msg) { sprintf(msg, MSGJPN297, packet->RemoteFile); MessageBox(GetMainHwnd(), msg, MSGJPN086, MB_OK); free(msg); } result = YES; } return(result); } // 同時接続対応 static char* GetErrMsg() { char* r; DWORD ThreadId; int i; r = NULL; WaitForSingleObject(hErrMsgMutex, INFINITE); ThreadId = GetCurrentThreadId(); i = 0; while(i < MAX_DATA_CONNECTION + 1) { if(ErrMsgThreadId[i] == ThreadId) { r = ErrMsg[i]; break; } i++; } if(!r) { i = 0; while(i < MAX_DATA_CONNECTION + 1) { if(ErrMsgThreadId[i] == 0) { ErrMsgThreadId[i] = ThreadId; r = ErrMsg[i]; break; } i++; } } ReleaseMutex(hErrMsgMutex); return r; } // タスクバー進捗表示 LONGLONG AskTransferSizeLeft(void) { return(TransferSizeLeft); } LONGLONG AskTransferSizeTotal(void) { return(TransferSizeTotal); } int AskTransferErrorDisplay(void) { return(TransferErrorDisplay); } // ゾーンID設定追加 int LoadZoneID() { int Sts; Sts = FFFTP_FAIL; if(IsMainThread()) { if(CoCreateInstance(&CLSID_PersistentZoneIdentifier, NULL, CLSCTX_ALL, &IID_IZoneIdentifier, (void**)&pZoneIdentifier) == S_OK) { if(pZoneIdentifier->lpVtbl->SetId(pZoneIdentifier, URLZONE_INTERNET) == S_OK) { if(pZoneIdentifier->lpVtbl->QueryInterface(pZoneIdentifier, &IID_IPersistFile, (void**)&pPersistFile) == S_OK) Sts = FFFTP_SUCCESS; } } } return Sts; } void FreeZoneID() { if(IsMainThread()) { if(pPersistFile != NULL) pPersistFile->lpVtbl->Release(pPersistFile); pPersistFile = NULL; if(pZoneIdentifier != NULL) pZoneIdentifier->lpVtbl->Release(pZoneIdentifier); pZoneIdentifier = NULL; } } int IsZoneIDLoaded() { int Sts; Sts = NO; if(pZoneIdentifier != NULL && pPersistFile != NULL) Sts = YES; return Sts; } int MarkFileAsDownloadedFromInternet(char* Fname) { int Sts; WCHAR Tmp1[FMAX_PATH+1]; BSTR Tmp2; MARKFILEASDOWNLOADEDFROMINTERNETDATA Data; Sts = FFFTP_FAIL; if(IsMainThread()) { MtoW(Tmp1, FMAX_PATH, Fname, -1); if((Tmp2 = SysAllocString(Tmp1)) != NULL) { if(pPersistFile->lpVtbl->Save(pPersistFile, Tmp2, FALSE) == S_OK) Sts = FFFTP_SUCCESS; SysFreeString(Tmp2); } } else { if(Data.h = CreateEvent(NULL, TRUE, FALSE, NULL)) { Data.Fname = Fname; if(PostMessage(GetMainHwnd(), WM_MARKFILEASDOWNLOADEDFROMINTERNET, 0, (LPARAM)&Data)) { if(WaitForSingleObject(Data.h, INFINITE) == WAIT_OBJECT_0) Sts = Data.r; } CloseHandle(Data.h); } } return Sts; }
0.984375
high
thirdparty/ULib/include/ulib/timer.h
liftchampion/nativejson-benchmark
0
904897
<reponame>liftchampion/nativejson-benchmark // ============================================================================ // // = LIBRARY // ULib - c++ library // // = FILENAME // timer.h // // = AUTHOR // <NAME> // // ============================================================================ #ifndef ULIB_TIMER_H #define ULIB_TIMER_H #include <ulib/event/event_time.h> #include <ulib/utility/interrupt.h> class UNotifier; class UServer_Base; // UNotifier use this class to notify a timeout from select() class U_EXPORT UTimer { public: // Check for memory error U_MEMORY_TEST // Allocator e Deallocator U_MEMORY_ALLOCATOR U_MEMORY_DEALLOCATOR enum Type { SYNC, ASYNC, NOSIGNAL }; UTimer() { U_TRACE_REGISTER_OBJECT(0, UTimer, "", 0) next = 0; alarm = 0; } ~UTimer() { U_TRACE_UNREGISTER_OBJECT(0, UTimer) } // SERVICES static bool empty() { U_TRACE_NO_PARAM(0, "UTimer::empty()") if (first == 0) U_RETURN(true); U_RETURN(false); } static bool isAlarm() { U_TRACE_NO_PARAM(0, "UTimer::isAlarm()") if (UInterrupt::timerval.it_value.tv_sec != 0 || UInterrupt::timerval.it_value.tv_usec != 0) { U_RETURN(true); } U_RETURN(false); } static void clear(); // cancel all timers and free storage, usually in preparation for exitting static void init(Type mode); // initialize the timer package static void insert(UEventTime* palarm); // set up a timer, either periodic or one-shot // deschedule a timer. Note that non-periodic timers are automatically descheduled when they run, so you don't have to call this on them static void erase(UTimer* item) { U_TRACE(0, "UTimer::erase(%p)", item) U_INTERNAL_ASSERT_POINTER(first) if (mode != NOSIGNAL) delete item; else { // put it on the free list item->next = pool; pool = item; } } static void erase(UEventTime* palarm); // run the list of timers. Your main program needs to call this every so often, or as indicated by getTimeout() static void run(); static void setTimer(); static UEventTime* getTimeout() // returns a timeout indicating how long until the next timer triggers { U_TRACE_NO_PARAM(0, "UTimer::getTimeout()") if ( first && (run(), first)) { UEventTime* a = first->alarm; U_ASSERT(a->checkTolerance()) U_RETURN_POINTER(a, UEventTime); } U_RETURN_POINTER(0, UEventTime); } static bool isHandler(UEventTime* palarm) { U_TRACE(0, "UTimer::isHandler(%p)", palarm) for (UTimer* item = first; item; item = item->next) { if (item->alarm == palarm) { U_INTERNAL_DUMP("item = %p", item) U_RETURN(true); } } U_RETURN(false); } // manage signal static RETSIGTYPE handlerAlarm(int signo) { U_TRACE(0, "[SIGALRM] UTimer::handlerAlarm(%d)", signo) setTimer(); } // STREAM #ifdef U_STDCPP_ENABLE friend U_EXPORT ostream& operator<<(ostream& os, const UTimer& t); // DEBUG # ifdef DEBUG static void printInfo(ostream& os); void outputEntry(ostream& os) const U_NO_EXPORT; const char* dump(bool reset) const; # endif #endif protected: UTimer* next; UEventTime* alarm; static int mode; static UTimer* pool; // free list static UTimer* first; // active list static void callHandlerTimeout(); static void updateTimeToExpire(UEventTime* ptime); #ifdef DEBUG static bool invariant(); #endif private: void insertEntry() U_NO_EXPORT; bool operator< (const UTimer& t) const { return (*alarm < *t.alarm); } bool operator> (const UTimer& t) const { return t.operator<(*this); } bool operator<=(const UTimer& t) const { return !t.operator<(*this); } bool operator>=(const UTimer& t) const { return ! operator<(t); } bool operator==(const UTimer& t) const { return (*alarm == *t.alarm); } bool operator!=(const UTimer& t) const { return ! operator==(t); } U_DISALLOW_COPY_AND_ASSIGN(UTimer) friend class UNotifier; friend class UServer_Base; }; #endif
0.996094
high
core/include/mmcore/ResourceTestModule.h
azuki-monster/megamol
49
905409
<reponame>azuki-monster/megamol<filename>core/include/mmcore/ResourceTestModule.h #pragma once #include "mmcore/Module.h" #include "CUDA_Context.h" namespace megamol::core { class ResourceTestModule : public Module { public: std::vector<std::string> requested_lifetime_resources() override { auto req = Module::requested_lifetime_resources(); req.push_back(frontend_resources::CUDA_Context_Req_Name); return req; } static const char* ClassName(void) { return "ResourceTestModule"; } static const char* Description(void) { return "Showcase for frontend resource handling"; } static bool IsAvailable(void) { return true; } ResourceTestModule(); virtual ~ResourceTestModule(); protected: bool create() override; void release() override; private: }; } // namespace megamol::core
0.953125
high
v0100/cgmips.c
PartyPlanner64/SmallerC
0
905921
<reponame>PartyPlanner64/SmallerC /* Copyright (c) 2012-2015, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE 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. */ /*****************************************************************************/ /* */ /* Smaller C */ /* */ /* A simple and small single-pass C compiler */ /* */ /* MIPS code generator */ /* */ /*****************************************************************************/ // Works around bugs in RetroBSD's as instruction reordering // *PP64 insert NOPs #define REORDER_WORKAROUND // *PP64 use SLL and SRL #define DONT_USE_SEH // *PP64 less noisy #define NO_ANNOTATIONS // *PP64 All addu and subu that were acting on immediates changed to addiu STATIC void GenInit(void) { // initialization of target-specific code generator SizeOfWord = 4; OutputFormat = FormatSegmented; // *PP64 no indent CodeHeaderFooter[0] = ".text"; DataHeaderFooter[0] = ".data"; RoDataHeaderFooter[0] = ".rdata"; BssHeaderFooter[0] = ".bss"; // CodeHeaderFooter[0] = "\t; text"; // DataHeaderFooter[0] = "\t; data"; // RoDataHeaderFooter[0] = "\t; rdata"; // BssHeaderFooter[0] = "\t; bss"; UseLeadingUnderscores = 0; #ifdef REORDER_WORKAROUND // *PP64 this directive is not understood FileHeader = ""; //"\t.set\tnoreorder"; #else FileHeader = "\t.set\treorder"; #endif } STATIC int GenInitParams(int argc, char** argv, int* idx) { (void)argc; // initialization of target-specific code generator with parameters if (!strcmp(argv[*idx], "-v")) { // RetroBSD's cc may supply this parameter. Just need to consume it. return 1; } return 0; } STATIC void GenInitFinalize(void) { // finalization of initialization of target-specific code generator } STATIC void GenStartCommentLine(void) { printf2(" ; "); // *PP64 use semi-colon } STATIC void GenWordAlignment(int bss) { (void)bss; printf2("\t.align 4\n"); // *PP64 align 4 is safer than 2 } STATIC void GenLabel(char* Label, int Static) { { if (!Static && GenExterns) printf2("\t.globl\t%s\n", Label); printf2("%s:\n", Label); } } STATIC void GenPrintLabel(char* Label) { { // *PP64 use Lcmpbranch* for labels instead of $L* if (isdigit(*Label)) printf2("Lcmpbranch%s", Label); else printf2("%s", Label); } } STATIC void GenNumLabel(int Label) { printf2("Lcmpbranch%d:\n", Label); } STATIC void GenPrintNumLabel(int label) { printf2("Lcmpbranch%d", label); } STATIC void GenZeroData(unsigned Size, int bss) { (void)bss; // *PP64 use .fill instead of .space printf2("\t.fill\t%u\n", truncUint(Size)); // or ".fill size" } STATIC void GenIntData(int Size, int Val) { Val = truncInt(Val); if (Size == 1) printf2("\t.byte\t%d\n", Val); else if (Size == 2) printf2("\t.halfword\t%d\n", Val); // *PP64 use .halfword instead of .half else if (Size == 4) printf2("\t.word\t%d\n", Val); } STATIC void GenStartAsciiString(void) { printf2("\t.ascii\t"); } STATIC void GenAddrData(int Size, char* Label, int ofs) { ofs = truncInt(ofs); if (Size == 1) printf2("\t.byte\t"); else if (Size == 2) printf2("\t.halfword\t"); // *PP64 use .halfword instead of .half else if (Size == 4) printf2("\t.word\t"); GenPrintLabel(Label); if (ofs) printf2(" %+d", ofs); puts2(""); } STATIC int GenFxnSizeNeeded(void) { return 0; } STATIC void GenRecordFxnSize(char* startLabelName, int endLabelNo) { (void)startLabelName; (void)endLabelNo; } #define MipsInstrNop 0x00 #define MipsInstrMov 0x01 #define MipsInstrMfLo 0x02 #define MipsInstrMfHi 0x03 #define MipsInstrLA 0x06 #define MipsInstrLI 0x07 //#define MipsInstrLUI #define MipsInstrLB 0x08 #define MipsInstrLBU 0x09 #define MipsInstrLH 0x0A #define MipsInstrLHU 0x0B #define MipsInstrLW 0x0C #define MipsInstrSB 0x0D #define MipsInstrSH 0x0E #define MipsInstrSW 0x0F #define MipsInstrAddU 0x10 #define MipsInstrSubU 0x11 #define MipsInstrAnd 0x12 #define MipsInstrOr 0x13 #define MipsInstrXor 0x14 #define MipsInstrNor 0x15 #define MipsInstrSLL 0x16 #define MipsInstrSRL 0x17 #define MipsInstrSRA 0x18 #define MipsInstrMul 0x19 #define MipsInstrDiv 0x1A #define MipsInstrDivU 0x1B #define MipsInstrSLT 0x1C #define MipsInstrSLTU 0x1D #define MipsInstrJ 0x1E #define MipsInstrJAL 0x1F #define MipsInstrBEQ 0x20 #define MipsInstrBNE 0x21 #define MipsInstrBLTZ 0x22 #define MipsInstrBGEZ 0x23 #define MipsInstrBLEZ 0x24 #define MipsInstrBGTZ 0x25 #define MipsInstrSeb 0x26 #define MipsInstrSeh 0x27 // *PP64 added: #define MipsInstrAddiu 0x28 #define MipsInstrAndi 0x29 #define MipsInstrXori 0x2A #define MipsInstrOri 0x2B #define MipsInstrJR 0x2C #define MipsInstrSLLV 0x2E #define MipsInstrSRLV 0x2F #define MipsInstrSRAV 0x30 #define MipsInstrSLTI 0x9D #define MipsInstrSLTIU 0x9E STATIC void GenPrintInstr(int instr, int val) { char* p = ""; (void)val; switch (instr) { case MipsInstrNop : p = "nop"; break; case MipsInstrMov : p = "move"; break; case MipsInstrMfLo : p = "mflo"; break; case MipsInstrMfHi : p = "mfhi"; break; case MipsInstrLA : p = "li"; break; // *PP64 use li case MipsInstrLI : p = "li"; break; // case MipsInstrLUI : p = "lui"; break; case MipsInstrLB : p = "lb"; break; case MipsInstrLBU : p = "lbu"; break; case MipsInstrLH : p = "lh"; break; case MipsInstrLHU : p = "lhu"; break; case MipsInstrLW : p = "lw"; break; case MipsInstrSB : p = "sb"; break; case MipsInstrSH : p = "sh"; break; case MipsInstrSW : p = "sw"; break; case MipsInstrAddU : p = "addu"; break; case MipsInstrSubU : p = "subu"; break; case MipsInstrAnd : p = "and"; break; case MipsInstrOr : p = "or"; break; case MipsInstrXor : p = "xor"; break; case MipsInstrNor : p = "nor"; break; case MipsInstrSLL : p = "sll"; break; case MipsInstrSRL : p = "srl"; break; case MipsInstrSRA : p = "sra"; break; case MipsInstrMul : p = "mult"; break; // *PP64 was "mul" case MipsInstrDiv : p = "div"; break; case MipsInstrDivU : p = "divu"; break; case MipsInstrSLT : p = "slt"; break; case MipsInstrSLTU : p = "sltu"; break; case MipsInstrJ : p = "j"; break; case MipsInstrJAL : p = "jal"; break; case MipsInstrBEQ : p = "beq"; break; case MipsInstrBNE : p = "bne"; break; case MipsInstrBLTZ : p = "bltz"; break; case MipsInstrBGEZ : p = "bgez"; break; case MipsInstrBLEZ : p = "blez"; break; case MipsInstrBGTZ : p = "bgtz"; break; case MipsInstrSeb : p = "seb"; break; case MipsInstrSeh : p = "seh"; break; case MipsInstrAddiu: p = "addiu"; break; case MipsInstrAndi : p = "andi"; break; case MipsInstrXori : p = "xori"; break; case MipsInstrOri : p = "ori"; break; case MipsInstrJR : p = "jr"; break; case MipsInstrSLLV : p = "sllv"; break; case MipsInstrSRLV : p = "srlv"; break; case MipsInstrSRAV : p = "srav"; break; case MipsInstrSLTI : p = "slti"; break; case MipsInstrSLTIU: p = "sltiu"; break; } printf2("\t%s\t", p); } #define MipsOpRegZero 0x00 #define MipsOpRegAt 0x01 #define MipsOpRegV0 0x02 #define MipsOpRegV1 0x03 #define MipsOpRegA0 0x04 #define MipsOpRegA1 0x05 #define MipsOpRegA2 0x06 #define MipsOpRegA3 0x07 #define MipsOpRegT0 0x08 #define MipsOpRegT1 0x09 #define MipsOpRegT2 0x0A #define MipsOpRegT3 0x0B #define MipsOpRegT4 0x0C #define MipsOpRegT5 0x0D #define MipsOpRegT6 0x0E #define MipsOpRegT7 0x0F #define MipsOpRegS0 0x10 #define MipsOpRegS1 0x11 #define MipsOpRegS2 0x12 #define MipsOpRegS3 0x13 #define MipsOpRegS4 0x14 #define MipsOpRegS5 0x15 #define MipsOpRegS6 0x16 #define MipsOpRegS7 0x17 #define MipsOpRegT8 0x18 #define MipsOpRegT9 0x19 #define MipsOpRegSp 0x1D #define MipsOpRegFp 0x1E #define MipsOpRegRa 0x1F #define MipsOpIndRegZero 0x20 #define MipsOpIndRegAt 0x21 #define MipsOpIndRegV0 0x22 #define MipsOpIndRegV1 0x23 #define MipsOpIndRegA0 0x24 #define MipsOpIndRegA1 0x25 #define MipsOpIndRegA2 0x26 #define MipsOpIndRegA3 0x27 #define MipsOpIndRegT0 0x28 #define MipsOpIndRegT1 0x29 #define MipsOpIndRegSp 0x3D #define MipsOpIndRegFp 0x3E #define MipsOpIndRegRa 0x3F #define MipsOpConst 0x80 #define MipsOpLabel 0x81 #define MipsOpNumLabel 0x82 #define MipsOpLabelLo 0x83 #define MipsOpIndLocal MipsOpIndRegFp #define MAX_TEMP_REGS 8 // this many temp registers used beginning with T0 to hold subexpression results #define TEMP_REG_A MipsOpRegT8 // two temporary registers used for momentary operations, similarly to the AT register #define TEMP_REG_B MipsOpRegT9 // *PP64 added for stack alignment // Assumes v is at least divisible by 4. STATIC int EnsureDivisibleBy8(int v) { if ((v % 8) != 0) { if (v < 0) { v -= 4; } else { v += 4; } } return v; } #ifdef REORDER_WORKAROUND STATIC void GenNop(void) { puts2("\tnop"); } #endif STATIC void GenPrintOperand(int op, int val) { if (op >= MipsOpRegZero && op <= MipsOpRegRa) { printf2("$%d", op); } else if (op >= MipsOpIndRegZero && op <= MipsOpIndRegRa) { printf2("%d($%d)", truncInt(val), op - MipsOpIndRegZero); } else { switch (op) { case MipsOpConst: printf2("%d", truncInt(val)); break; case MipsOpLabelLo: // *PP64 plain lo() instead of %%lo() //printf2("%%lo("); printf2("lo("); GenPrintLabel(IdentTable + val); printf2(")($1)"); break; case MipsOpLabel: GenPrintLabel(IdentTable + val); break; case MipsOpNumLabel: GenPrintNumLabel(val); break; default: //error("WTF!\n"); errorInternal(100); break; } } } STATIC void GenPrintOperandSeparator(void) { printf2(", "); } STATIC void GenPrintNewLine(void) { puts2(""); } STATIC void GenPrintInstr1Operand(int instr, int instrval, int operand, int operandval) { GenPrintInstr(instr, instrval); GenPrintOperand(operand, operandval); GenPrintNewLine(); #ifdef REORDER_WORKAROUND if (instr == MipsInstrJ || instr == MipsInstrJR || instr == MipsInstrJAL) GenNop(); #endif } STATIC void GenPrintInstr2Operands(int instr, int instrval, int operand1, int operand1val, int operand2, int operand2val) { if (operand2 == MipsOpConst && operand2val == 0 && (instr == MipsInstrAddU || instr == MipsInstrSubU || instr == MipsInstrAddiu)) return; GenPrintInstr(instr, instrval); GenPrintOperand(operand1, operand1val); GenPrintOperandSeparator(); GenPrintOperand(operand2, operand2val); GenPrintNewLine(); #ifdef REORDER_WORKAROUND if (instr == MipsInstrBLTZ || instr == MipsInstrBGEZ || instr == MipsInstrBGTZ || instr == MipsInstrBLEZ) GenNop(); #endif } STATIC void GenPrintInstr3Operands(int instr, int instrval, int operand1, int operand1val, int operand2, int operand2val, int operand3, int operand3val) { if (operand3 == MipsOpConst && operand3val == 0 && (instr == MipsInstrAddU || instr == MipsInstrSubU || instr == MipsInstrAddiu) && operand1 == operand2) return; GenPrintInstr(instr, instrval); GenPrintOperand(operand1, operand1val); GenPrintOperandSeparator(); GenPrintOperand(operand2, operand2val); GenPrintOperandSeparator(); GenPrintOperand(operand3, operand3val); GenPrintNewLine(); #ifdef REORDER_WORKAROUND if (instr == MipsInstrBEQ || instr == MipsInstrBNE) GenNop(); #endif } STATIC void GenExtendRegIfNeeded(int reg, int opSz) { if (opSz == -1) { #ifdef DONT_USE_SEH GenPrintInstr3Operands(MipsInstrSLL, 0, reg, 0, reg, 0, MipsOpConst, 24); GenPrintInstr3Operands(MipsInstrSRA, 0, reg, 0, reg, 0, MipsOpConst, 24); #else GenPrintInstr2Operands(MipsInstrSeb, 0, reg, 0, reg, 0); #endif } else if (opSz == 1) { GenPrintInstr3Operands(MipsInstrAndi, 0, reg, 0, reg, 0, MipsOpConst, 0xFF); } else if (opSz == -2) { #ifdef DONT_USE_SEH GenPrintInstr3Operands(MipsInstrSLL, 0, reg, 0, reg, 0, MipsOpConst, 16); GenPrintInstr3Operands(MipsInstrSRA, 0, reg, 0, reg, 0, MipsOpConst, 16); #else GenPrintInstr2Operands(MipsInstrSeh, 0, reg, 0, reg, 0); #endif } else if (opSz == 2) { GenPrintInstr3Operands(MipsInstrAndi, 0, reg, 0, reg, 0, MipsOpConst, 0xFFFF); } } STATIC void GenJumpUncond(int label) { GenPrintInstr1Operand(MipsInstrJ, 0, MipsOpNumLabel, label); } extern int GenWreg; // GenWreg is defined below STATIC void GenJumpIfEqual(int val, int label) { GenPrintInstr2Operands(MipsInstrLI, 0, TEMP_REG_B, 0, MipsOpConst, val); GenPrintInstr3Operands(MipsInstrBEQ, 0, GenWreg, 0, TEMP_REG_B, 0, MipsOpNumLabel, label); } STATIC void GenJumpIfZero(int label) { #ifndef NO_ANNOTATIONS printf2(" # JumpIfZero\n"); #endif GenPrintInstr3Operands(MipsInstrBEQ, 0, GenWreg, 0, MipsOpRegZero, 0, MipsOpNumLabel, label); } STATIC void GenJumpIfNotZero(int label) { #ifndef NO_ANNOTATIONS printf2(" # JumpIfNotZero\n"); #endif GenPrintInstr3Operands(MipsInstrBNE, 0, GenWreg, 0, MipsOpRegZero, 0, MipsOpNumLabel, label); } fpos_t GenPrologPos; int GenLeaf; STATIC void GenWriteFrameSize(void) { unsigned size = 8/*RA + FP*/ - CurFxnMinLocalOfs; unsigned safesize = EnsureDivisibleBy8(size); unsigned fpadj = (size != safesize) ? size - 4 : size - 8; printf2("\taddiu\t$29, $29, -%-10u\n", safesize); // 10 chars are enough for 32-bit unsigned ints printf2("\tsw\t$30, %10u($29)\n", fpadj); printf2("\taddiu\t$30, $29, %-10u\n", fpadj); printf2("\t%csw\t$31, 4($30)\n", GenLeaf ? ';' : ' '); // *PP64 use ; for comments } STATIC void GenUpdateFrameSize(void) { fpos_t pos; fgetpos(OutFile, &pos); fsetpos(OutFile, &GenPrologPos); GenWriteFrameSize(); fsetpos(OutFile, &pos); } STATIC void GenFxnProlog(void) { if (CurFxnParamCntMin && CurFxnParamCntMax) { int i, cnt = CurFxnParamCntMax; if (cnt > 4) cnt = 4; // TBD!!! for structure passing use the cumulative parameter size // instead of the number of parameters. Currently this bug is masked // by the subroutine that pushes structures on the stack (it copies // all words except the first to the stack). But passing structures // in registers from assembly code won't always work. for (i = 0; i < cnt; i++) GenPrintInstr2Operands(MipsInstrSW, 0, MipsOpRegA0 + i, 0, MipsOpIndRegSp, 4 * i); } GenLeaf = 1; // will be reset to 0 if a call is generated fgetpos(OutFile, &GenPrologPos); GenWriteFrameSize(); } STATIC void GenGrowStack(int size) { if (!size) return; GenPrintInstr3Operands(MipsInstrAddiu, 0, MipsOpRegSp, 0, MipsOpRegSp, 0, MipsOpConst, -size); } STATIC void GenFxnEpilog(void) { GenUpdateFrameSize(); if (!GenLeaf) GenPrintInstr2Operands(MipsInstrLW, 0, MipsOpRegRa, 0, MipsOpIndRegFp, 4); GenPrintInstr2Operands(MipsInstrLW, 0, MipsOpRegFp, 0, MipsOpIndRegFp, 0); GenPrintInstr3Operands(MipsInstrAddiu, 0, MipsOpRegSp, 0, MipsOpRegSp, 0, MipsOpConst, EnsureDivisibleBy8(8/*RA + FP*/ - CurFxnMinLocalOfs)); GenPrintInstr1Operand(MipsInstrJR, 0, MipsOpRegRa, 0); } STATIC int GenMaxLocalsSize(void) { return 0x7FFFFFFF; } STATIC int GenGetBinaryOperatorInstr(int tok) { switch (tok) { case tokPostAdd: case tokAssignAdd: case '+': return MipsInstrAddU; case tokPostSub: case tokAssignSub: case '-': return MipsInstrSubU; case '&': case tokAssignAnd: return MipsInstrAnd; case '^': case tokAssignXor: return MipsInstrXor; case '|': case tokAssignOr: return MipsInstrOr; case '<': case '>': case tokLEQ: case tokGEQ: case tokEQ: case tokNEQ: case tokULess: case tokUGreater: case tokULEQ: case tokUGEQ: return MipsInstrNop; case '*': case tokAssignMul: return MipsInstrMul; case '/': case '%': case tokAssignDiv: case tokAssignMod: return MipsInstrDiv; case tokUDiv: case tokUMod: case tokAssignUDiv: case tokAssignUMod: return MipsInstrDivU; case tokLShift: case tokAssignLSh: return MipsInstrSLLV; case tokRShift: case tokAssignRSh: return MipsInstrSRAV; case tokURShift: case tokAssignURSh: return MipsInstrSRLV; default: //error("Error: Invalid operator\n"); errorInternal(101); return 0; } } // *PP64 added STATIC int GenImmediateVersionOfInstr(int instr) { switch (instr) { case MipsInstrAddU: return MipsInstrAddiu; case MipsInstrAnd: return MipsInstrAndi; case MipsInstrXor: return MipsInstrXori; case MipsInstrOr: return MipsInstrOri; case MipsInstrSLLV: return MipsInstrSLL; case MipsInstrSRAV: return MipsInstrSRA; case MipsInstrSRLV: return MipsInstrSRL; default: return instr; } } STATIC void GenPreIdentAccess(int label) { // *PP64 hi instead of %%hi // printf2("\t.set\tnoat\n\tlui\t$1, %%hi("); printf2("\tlui\t$1, hi("); GenPrintLabel(IdentTable + label); puts2(")"); } STATIC void GenPostIdentAccess(void) { // *PP64 no //puts2("\t.set\tat"); } STATIC void GenReadIdent(int regDst, int opSz, int label) { int instr = MipsInstrLW; GenPreIdentAccess(label); if (opSz == -1) { instr = MipsInstrLB; } else if (opSz == 1) { instr = MipsInstrLBU; } else if (opSz == -2) { instr = MipsInstrLH; } else if (opSz == 2) { instr = MipsInstrLHU; } GenPrintInstr2Operands(instr, 0, regDst, 0, MipsOpLabelLo, label); GenPostIdentAccess(); } STATIC void GenReadLocal(int regDst, int opSz, int ofs) { int instr = MipsInstrLW; if (opSz == -1) { instr = MipsInstrLB; } else if (opSz == 1) { instr = MipsInstrLBU; } else if (opSz == -2) { instr = MipsInstrLH; } else if (opSz == 2) { instr = MipsInstrLHU; } GenPrintInstr2Operands(instr, 0, regDst, 0, MipsOpIndRegFp, ofs); } STATIC void GenReadIndirect(int regDst, int regSrc, int opSz) { int instr = MipsInstrLW; if (opSz == -1) { instr = MipsInstrLB; } else if (opSz == 1) { instr = MipsInstrLBU; } else if (opSz == -2) { instr = MipsInstrLH; } else if (opSz == 2) { instr = MipsInstrLHU; } GenPrintInstr2Operands(instr, 0, regDst, 0, regSrc + MipsOpIndRegZero, 0); } STATIC void GenWriteIdent(int regSrc, int opSz, int label) { int instr = MipsInstrSW; GenPreIdentAccess(label); if (opSz == -1 || opSz == 1) { instr = MipsInstrSB; } else if (opSz == -2 || opSz == 2) { instr = MipsInstrSH; } GenPrintInstr2Operands(instr, 0, regSrc, 0, MipsOpLabelLo, label); GenPostIdentAccess(); } STATIC void GenWriteLocal(int regSrc, int opSz, int ofs) { int instr = MipsInstrSW; if (opSz == -1 || opSz == 1) { instr = MipsInstrSB; } else if (opSz == -2 || opSz == 2) { instr = MipsInstrSH; } GenPrintInstr2Operands(instr, 0, regSrc, 0, MipsOpIndRegFp, ofs); } STATIC void GenWriteIndirect(int regDst, int regSrc, int opSz) { int instr = MipsInstrSW; if (opSz == -1 || opSz == 1) { instr = MipsInstrSB; } else if (opSz == -2 || opSz == 2) { instr = MipsInstrSH; } GenPrintInstr2Operands(instr, 0, regSrc, 0, regDst + MipsOpIndRegZero, 0); } STATIC void GenIncDecIdent(int regDst, int opSz, int label, int tok) { int val = 1; if (tok != tokInc) { val = -1; } GenReadIdent(regDst, opSz, label); GenPrintInstr3Operands(MipsInstrAddiu, 0, regDst, 0, regDst, 0, MipsOpConst, val); GenWriteIdent(regDst, opSz, label); GenExtendRegIfNeeded(regDst, opSz); } STATIC void GenIncDecLocal(int regDst, int opSz, int ofs, int tok) { int val = 1; if (tok != tokInc) { val = -1; } GenReadLocal(regDst, opSz, ofs); GenPrintInstr3Operands(MipsInstrAddiu, 0, regDst, 0, regDst, 0, MipsOpConst, val); GenWriteLocal(regDst, opSz, ofs); GenExtendRegIfNeeded(regDst, opSz); } STATIC void GenIncDecIndirect(int regDst, int regSrc, int opSz, int tok) { int val = 1; if (tok != tokInc) { val = -1; } GenReadIndirect(regDst, regSrc, opSz); GenPrintInstr3Operands(MipsInstrAddiu, 0, regDst, 0, regDst, 0, MipsOpConst, val); GenWriteIndirect(regSrc, regDst, opSz); GenExtendRegIfNeeded(regDst, opSz); } STATIC void GenPostIncDecIdent(int regDst, int opSz, int label, int tok) { int val = 1; if (tok != tokPostInc) val = -1; GenReadIdent(regDst, opSz, label); GenPrintInstr3Operands(MipsInstrAddiu, 0, regDst, 0, regDst, 0, MipsOpConst, val); GenWriteIdent(regDst, opSz, label); GenPrintInstr3Operands(MipsInstrAddiu, 0, regDst, 0, regDst, 0, MipsOpConst, -val); GenExtendRegIfNeeded(regDst, opSz); } STATIC void GenPostIncDecLocal(int regDst, int opSz, int ofs, int tok) { int val = 1; if (tok != tokPostInc) val = -1; GenReadLocal(regDst, opSz, ofs); GenPrintInstr3Operands(MipsInstrAddiu, 0, regDst, 0, regDst, 0, MipsOpConst, val); GenWriteLocal(regDst, opSz, ofs); GenPrintInstr3Operands(MipsInstrAddiu, 0, regDst, 0, regDst, 0, MipsOpConst, -val); GenExtendRegIfNeeded(regDst, opSz); } STATIC void GenPostIncDecIndirect(int regDst, int regSrc, int opSz, int tok) { int val = 1; if (tok != tokPostInc) val = -1; GenReadIndirect(regDst, regSrc, opSz); GenPrintInstr3Operands(MipsInstrAddiu, 0, regDst, 0, regDst, 0, MipsOpConst, val); GenWriteIndirect(regSrc, regDst, opSz); GenPrintInstr3Operands(MipsInstrAddiu, 0, regDst, 0, regDst, 0, MipsOpConst, -val); GenExtendRegIfNeeded(regDst, opSz); } int CanUseTempRegs; int TempsUsed; int GenWreg = MipsOpRegV0; // current working register (V0 or Tn or An) int GenLreg, GenRreg; // left operand register and right operand register after GenPopReg() /* General idea behind GenWreg, GenLreg, GenRreg: - In expressions w/o function calls: Subexpressions are evaluated in V0, T0, T1, ..., T<MAX_TEMP_REGS-1>. If those registers aren't enough, the stack is used additionally. The expression result ends up in V0, which is handy for returning from functions. In the process, GenWreg is the current working register and is one of: V0, T0, T1, ... . All unary operators are evaluated in the current working register. GenPushReg() and GenPopReg() advance GenWreg as needed when handling binary operators. GenPopReg() sets GenWreg, GenLreg and GenRreg. GenLreg and GenRreg are the registers where the left and right operands of a binary operator are. When the exression runs out of the temporary registers, the stack is used. While it is being used, GenWreg remains equal to the last temporary register, and GenPopReg() sets GenLreg = TEMP_REG_A. Hence, after GenPopReg() the operands of the binary operator are always in registers and can be directly manipulated with. Following GenPopReg(), binary operator evaluation must take the left and right operands from GenLreg and GenRreg and write the evaluated result into GenWreg. Care must be taken as GenWreg will be the same as either GenLreg (when the popped operand comes from T0-T<MAX_TEMP_REGS-1>) or GenRreg (when the popped operand comes from the stack in TEMP_REG_A). - In expressions with function calls: GenWreg is always V0 in subexpressions that aren't function parameters. These subexpressions get automatically pushed onto the stack as necessary. GenWreg is always V0 in expressions, where return values from function calls are used as parameters into other called functions. IOW, this is the case when the function call depth is greater than 1. Subexpressions in such expressions get automatically pushed onto the stack as necessary. GenWreg is A0-A3 in subexpressions that are function parameters when the function call depth is 1. Basically, while a function parameter is evaluated, it's evaluated in the register from where the called function will take it. This avoids some of unnecessary register copies and stack manipulations in the most simple and very common cases of function calls. */ STATIC void GenWregInc(int inc) { if (inc > 0) { // Advance the current working register to the next available temporary register if (GenWreg == MipsOpRegV0) GenWreg = MipsOpRegT0; else GenWreg++; } else { // Return to the previous current working register if (GenWreg == MipsOpRegT0) GenWreg = MipsOpRegV0; else GenWreg--; } } STATIC void GenPushReg(void) { if (CanUseTempRegs && TempsUsed < MAX_TEMP_REGS) { GenWregInc(1); TempsUsed++; return; } GenPrintInstr3Operands(MipsInstrAddiu, 0, MipsOpRegSp, 0, MipsOpRegSp, 0, MipsOpConst, -4); GenPrintInstr2Operands(MipsInstrSW, 0, GenWreg, 0, MipsOpIndRegSp, 0); TempsUsed++; } STATIC void GenPopReg(void) { TempsUsed--; if (CanUseTempRegs && TempsUsed < MAX_TEMP_REGS) { GenRreg = GenWreg; GenWregInc(-1); GenLreg = GenWreg; return; } GenPrintInstr2Operands(MipsInstrLW, 0, TEMP_REG_A, 0, MipsOpIndRegSp, 0); GenPrintInstr3Operands(MipsInstrAddiu, 0, MipsOpRegSp, 0, MipsOpRegSp, 0, MipsOpConst, 4); GenLreg = TEMP_REG_A; GenRreg = GenWreg; } #define tokRevIdent 0x100 #define tokRevLocalOfs 0x101 #define tokAssign0 0x102 #define tokNum0 0x103 STATIC void GenPrep(int* idx) { int tok; int oldIdxRight, oldIdxLeft, t0, t1; if (*idx < 0) //error("GenFuse(): idx < 0\n"); errorInternal(100); tok = stack[*idx][0]; oldIdxRight = --*idx; switch (tok) { case tokUDiv: case tokUMod: case tokAssignUDiv: case tokAssignUMod: if (stack[oldIdxRight][0] == tokNumInt || stack[oldIdxRight][0] == tokNumUint) { // Change unsigned division to right shift and unsigned modulo to bitwise and unsigned m = truncUint(stack[oldIdxRight][1]); if (m && !(m & (m - 1))) { if (tok == tokUMod || tok == tokAssignUMod) { stack[oldIdxRight][1] = (int)(m - 1); tok = (tok == tokUMod) ? '&' : tokAssignAnd; } else { t1 = 0; while (m >>= 1) t1++; stack[oldIdxRight][1] = t1; tok = (tok == tokUDiv) ? tokURShift : tokAssignURSh; } stack[oldIdxRight + 1][0] = tok; } } } switch (tok) { case tokNumUint: stack[oldIdxRight + 1][0] = tokNumInt; // reduce the number of cases since tokNumInt and tokNumUint are handled the same way // fallthrough case tokNumInt: case tokNum0: case tokIdent: case tokLocalOfs: break; case tokPostAdd: case tokPostSub: case '-': case '/': case '%': case tokUDiv: case tokUMod: case tokLShift: case tokRShift: case tokURShift: case tokLogAnd: case tokLogOr: case tokComma: GenPrep(idx); // fallthrough case tokShortCirc: case tokGoto: case tokUnaryStar: case tokInc: case tokDec: case tokPostInc: case tokPostDec: case '~': case tokUnaryPlus: case tokUnaryMinus: case tok_Bool: case tokVoid: case tokUChar: case tokSChar: case tokShort: case tokUShort: GenPrep(idx); break; case '=': if (oldIdxRight + 1 == sp - 1 && (stack[oldIdxRight][0] == tokNumInt || stack[oldIdxRight][0] == tokNumUint) && truncUint(stack[oldIdxRight][1]) == 0) { // Special case for assigning 0 while throwing away the expression result value // TBD??? , stack[oldIdxRight][0] = tokNum0; // this zero constant will not be loaded into a register stack[oldIdxRight + 1][0] = tokAssign0; // change '=' to tokAssign0 } // fallthrough case tokAssignAdd: case tokAssignSub: case tokAssignMul: case tokAssignDiv: case tokAssignUDiv: case tokAssignMod: case tokAssignUMod: case tokAssignLSh: case tokAssignRSh: case tokAssignURSh: case tokAssignAnd: case tokAssignXor: case tokAssignOr: GenPrep(idx); oldIdxLeft = *idx; GenPrep(idx); // If the left operand is an identifier (with static or auto storage), swap it with the right operand // and mark it specially, so it can be used directly if ((t0 = stack[oldIdxLeft][0]) == tokIdent || t0 == tokLocalOfs) { t1 = stack[oldIdxLeft][1]; memmove(stack[oldIdxLeft], stack[oldIdxLeft + 1], (oldIdxRight - oldIdxLeft) * sizeof(stack[0])); stack[oldIdxRight][0] = (t0 == tokIdent) ? tokRevIdent : tokRevLocalOfs; stack[oldIdxRight][1] = t1; } break; case '+': case '*': case '&': case '^': case '|': case tokEQ: case tokNEQ: case '<': case '>': case tokLEQ: case tokGEQ: case tokULess: case tokUGreater: case tokULEQ: case tokUGEQ: GenPrep(idx); oldIdxLeft = *idx; GenPrep(idx); // If the right operand isn't a constant, but the left operand is, swap the operands // so the constant can become an immediate right operand in the instruction t1 = stack[oldIdxRight][0]; t0 = stack[oldIdxLeft][0]; if (t1 != tokNumInt && t0 == tokNumInt) { int xor; t1 = stack[oldIdxLeft][1]; memmove(stack[oldIdxLeft], stack[oldIdxLeft + 1], (oldIdxRight - oldIdxLeft) * sizeof(stack[0])); stack[oldIdxRight][0] = t0; stack[oldIdxRight][1] = t1; switch (tok) { case '<': case '>': xor = '<' ^ '>'; break; case tokLEQ: case tokGEQ: xor = tokLEQ ^ tokGEQ; break; case tokULess: case tokUGreater: xor = tokULess ^ tokUGreater; break; case tokULEQ: case tokUGEQ: xor = tokULEQ ^ tokUGEQ; break; default: xor = 0; break; } tok ^= xor; } // Handle a few special cases and transform the instruction if (stack[oldIdxRight][0] == tokNumInt) { unsigned m = truncUint(stack[oldIdxRight][1]); switch (tok) { case '*': // Change multiplication to left shift, this helps indexing arrays of ints/pointers/etc if (m && !(m & (m - 1))) { t1 = 0; while (m >>= 1) t1++; stack[oldIdxRight][1] = t1; tok = tokLShift; } break; case tokLEQ: // left <= const will later change to left < const+1, but const+1 must be <=0x7FFFFFFF if (m == 0x7FFFFFFF) { // left <= 0x7FFFFFFF is always true, change to the equivalent left >= 0u stack[oldIdxRight][1] = 0; tok = tokUGEQ; } break; case tokULEQ: // left <= const will later change to left < const+1, but const+1 must be <=0xFFFFFFFFu if (m == 0xFFFFFFFF) { // left <= 0xFFFFFFFFu is always true, change to the equivalent left >= 0u stack[oldIdxRight][1] = 0; tok = tokUGEQ; } break; case '>': // left > const will later change to !(left < const+1), but const+1 must be <=0x7FFFFFFF if (m == 0x7FFFFFFF) { // left > 0x7FFFFFFF is always false, change to the equivalent left & 0 stack[oldIdxRight][1] = 0; tok = '&'; } break; case tokUGreater: // left > const will later change to !(left < const+1), but const+1 must be <=0xFFFFFFFFu if (m == 0xFFFFFFFF) { // left > 0xFFFFFFFFu is always false, change to the equivalent left & 0 stack[oldIdxRight][1] = 0; tok = '&'; } break; } } stack[oldIdxRight + 1][0] = tok; break; case ')': while (stack[*idx][0] != '(') { GenPrep(idx); if (stack[*idx][0] == ',') --*idx; } --*idx; break; default: //error("GenPrep: unexpected token %s\n", GetTokenName(tok)); errorInternal(101); } } /* ; l <[u] 0 // slt[u] w, w, 0 "k" l <[u] const // slt[u] w, w, const "m" l <[u] r // slt[u] w, l, r "i" * if (l < 0) // bgez w, Lskip "f" if (l <[u] const) // slt[u] w, w, const; beq w, $0, Lskip "mc" if (l <[u] r) // slt[u] w, l, r; beq w, $0, Lskip "ic" ; l <=[u] 0 // slt[u] w, w, 1 "l" l <=[u] const // slt[u] w, w, const + 1 "n" l <=[u] r // slt[u] w, r, l; xor w, w, 1 "js" * if (l <= 0) // bgtz w, Lskip "g" if (l <=[u] const) // slt[u] w, w, const + 1; beq w, $0, Lskip "nc" if (l <=[u] r) // slt[u] w, r, l; bne w, $0, Lskip "jd" l >[u] 0 // slt[u] w, $0, w "o" l >[u] const // slt[u] w, w, const + 1; xor w, w, 1 "ns" l >[u] r // slt[u] w, r, l "j" * if (l > 0) // blez w, Lskip "h" **if (l >u 0) // beq w, $0, Lskip if (l >[u] const) // slt[u] w, w, const + 1; bne w, $0, Lskip "nd" if (l >[u] r) // slt[u] w, r, l; beq w, $0, Lskip "jc" ; l >=[u] 0 // slt[u] w, w, 0; xor w, w, 1 "ks" l >=[u] const // slt[u] w, w, const; xor w, w, 1 "ms" l >=[u] r // slt[u] w, l, r; xor w, w, 1 "is" * if (l >= 0) // bltz w, Lskip "e" if (l >=[u] const) // slt[u] w, w, const; bne w, $0, Lskip "md" if (l >=[u] r) // slt[u] w, l, r; bne w, $0, Lskip "id" l == 0 // sltu w, w, 1 "q" l == const // xor w, w, const; sltu w, w, 1 "tq" l == r // xor w, l, r; sltu w, w, 1 "rq" if (l == 0) // bne w, $0, Lskip "d" if (l == const) // xor w, w, const; bne w, $0, Lskip "td" if (l == r) // bne l, r, Lskip "b" l != 0 // sltu w, $0, w "p" l != const // xor w, w, const; sltu w, $0, w "tp" l != r // xor w, l, r; sltu w, $0, w "rp" if (l != 0) // beq w, $0, Lskip "c" if (l != const) // xor w, w, const; beq w, $0, Lskip "tc" if (l != r) // beq l, r, Lskip "a" */ char CmpBlocks[6/*op*/][2/*condbranch*/][3/*constness*/][2] = { { { "k", "m", "i" }, { "f", "mc", "ic" } }, { { "l", "n", "js" }, { "g", "nc", "jd" } }, { { "o", "ns", "j" }, { "h", "nd", "jc" } }, { { "ks", "ms", "is" }, { "e", "md", "id" } }, { { "q", "tq", "rq" }, { "d", "td", "b" } }, { { "p", "tp", "rp" }, { "c", "tc", "a" } } }; STATIC void GenCmp(int* idx, int op) { // constness: 0 = zero const, 1 = non-zero const, 2 = non-const int constness = (stack[*idx - 1][0] == tokNumInt) ? (stack[*idx - 1][1] != 0) : 2; int constval = (constness == 1) ? truncInt(stack[*idx - 1][1]) : 0; // condbranch: 0 = no conditional branch, 1 = branch if true, 2 = branch if false int condbranch = (*idx + 1 < sp) ? (stack[*idx + 1][0] == tokIf) + (stack[*idx + 1][0] == tokIfNot) * 2 : 0; int unsign = op >> 4; int slt = unsign ? MipsInstrSLTU : MipsInstrSLT; int slti = unsign ? MipsInstrSLTIU : MipsInstrSLTI; int label = condbranch ? stack[*idx + 1][1] : 0; char* p; int i; op &= 0xF; if (constness == 2) GenPopReg(); // bltz, blez, bgez, bgtz are for signed comparison with 0 only, // so for conditional branches on <0u, <=0u, >0u, >=0u use the general method instead if (condbranch && op < 4 && constness == 0 && unsign) { // Except, >0u is more optimal as !=0 if (op == 2) op = 5; else constness = 1; } p = CmpBlocks[op][condbranch != 0][constness]; for (i = 0; i < 2; i++) { switch (p[i]) { case 'a': condbranch ^= 3; // fallthrough case 'b': GenPrintInstr3Operands((condbranch == 1) ? MipsInstrBEQ : MipsInstrBNE, 0, GenLreg, 0, GenRreg, 0, MipsOpNumLabel, label); break; case 'c': condbranch ^= 3; // fallthrough case 'd': GenPrintInstr3Operands((condbranch == 1) ? MipsInstrBEQ : MipsInstrBNE, 0, GenWreg, 0, MipsOpRegZero, 0, MipsOpNumLabel, label); break; case 'e': condbranch ^= 3; // fallthrough case 'f': GenPrintInstr2Operands((condbranch == 1) ? MipsInstrBLTZ : MipsInstrBGEZ, 0, GenWreg, 0, MipsOpNumLabel, label); break; case 'g': condbranch ^= 3; // fallthrough case 'h': GenPrintInstr2Operands((condbranch == 1) ? MipsInstrBGTZ : MipsInstrBLEZ, 0, GenWreg, 0, MipsOpNumLabel, label); break; case 'i': GenPrintInstr3Operands(slt, 0, GenWreg, 0, GenLreg, 0, GenRreg, 0); break; case 'j': GenPrintInstr3Operands(slt, 0, GenWreg, 0, GenRreg, 0, GenLreg, 0); break; case 'k': GenPrintInstr3Operands(slt, 0, GenWreg, 0, GenWreg, 0, MipsOpRegZero, 0); break; case 'l': GenPrintInstr3Operands(slti, 0, GenWreg, 0, GenWreg, 0, MipsOpConst, 1); break; case 'n': constval++; // fallthrough case 'm': GenPrintInstr2Operands(MipsInstrLI, 0, MipsOpRegAt, 0, MipsOpConst, constval); GenPrintInstr3Operands(slt, 0, GenWreg, 0, GenWreg, 0, MipsOpRegAt, 0); break; case 'o': GenPrintInstr3Operands(slt, 0, GenWreg, 0, MipsOpRegZero, 0, GenWreg, 0); break; case 'p': GenPrintInstr3Operands(MipsInstrSLTU, 0, GenWreg, 0, MipsOpRegZero, 0, GenWreg, 0); break; case 'q': GenPrintInstr3Operands(MipsInstrSLTIU, 0, GenWreg, 0, GenWreg, 0, MipsOpConst, 1); break; case 'r': GenPrintInstr3Operands(MipsInstrXor, 0, GenWreg, 0, GenLreg, 0, GenRreg, 0); break; case 's': GenPrintInstr3Operands(MipsInstrXori, 0, GenWreg, 0, GenWreg, 0, MipsOpConst, 1); break; case 't': GenPrintInstr2Operands(MipsInstrLI, 0, MipsOpRegAt, 0, MipsOpConst, constval); GenPrintInstr3Operands(MipsInstrXor, 0, GenWreg, 0, GenWreg, 0, MipsOpRegAt, 0); break; } } *idx += condbranch != 0; } STATIC int GenIsCmp(int t) { return t == '<' || t == '>' || t == tokGEQ || t == tokLEQ || t == tokULess || t == tokUGreater || t == tokUGEQ || t == tokULEQ || t == tokEQ || t == tokNEQ; } // Improved register/stack-based code generator // DONE: test 32-bit code generation STATIC void GenExpr0(void) { int i; int gotUnary = 0; int maxCallDepth = 0; int callDepth = 0; int paramOfs = 0; int t = sp - 1; if (stack[t][0] == tokIf || stack[t][0] == tokIfNot || stack[t][0] == tokReturn) t--; GenPrep(&t); for (i = 0; i < sp; i++) if (stack[i][0] == '(') { if (++callDepth > maxCallDepth) maxCallDepth = callDepth; } else if (stack[i][0] == ')') { callDepth--; } CanUseTempRegs = maxCallDepth == 0; TempsUsed = 0; if (GenWreg != MipsOpRegV0) errorInternal(102); for (i = 0; i < sp; i++) { int tok = stack[i][0]; int v = stack[i][1]; #ifndef NO_ANNOTATIONS switch (tok) { case tokNumInt: printf2(" # %d\n", truncInt(v)); break; //case tokNumUint: printf2(" # %uu\n", truncUint(v)); break; case tokIdent: case tokRevIdent: printf2(" # %s\n", IdentTable + v); break; case tokLocalOfs: case tokRevLocalOfs: printf2(" # local ofs\n"); break; case ')': printf2(" # ) fxn call\n"); break; case tokUnaryStar: printf2(" # * (read dereference)\n"); break; case '=': printf2(" # = (write dereference)\n"); break; case tokShortCirc: printf2(" # short-circuit "); break; case tokGoto: printf2(" # sh-circ-goto "); break; case tokLogAnd: printf2(" # short-circuit && target\n"); break; case tokLogOr: printf2(" # short-circuit || target\n"); break; case tokIf: case tokIfNot: case tokReturn: break; case tokNum0: printf2(" # 0\n"); break; case tokAssign0: printf2(" # =\n"); break; default: printf2(" # %s\n", GetTokenName(tok)); break; } #endif switch (tok) { case tokNumInt: if (!(i + 1 < sp && ((t = stack[i + 1][0]) == '+' || t == '-' || t == '&' || t == '^' || t == '|' || t == tokLShift || t == tokRShift || t == tokURShift || GenIsCmp(t)))) { if (gotUnary) GenPushReg(); GenPrintInstr2Operands(MipsInstrLI, 0, GenWreg, 0, MipsOpConst, v); } gotUnary = 1; break; case tokIdent: if (gotUnary) GenPushReg(); if (!(i + 1 < sp && ((t = stack[i + 1][0]) == ')' || t == tokUnaryStar || t == tokInc || t == tokDec || t == tokPostInc || t == tokPostDec))) { GenPrintInstr2Operands(MipsInstrLA, 0, GenWreg, 0, MipsOpLabel, v); } gotUnary = 1; break; case tokLocalOfs: if (gotUnary) GenPushReg(); if (!(i + 1 < sp && ((t = stack[i + 1][0]) == tokUnaryStar || t == tokInc || t == tokDec || t == tokPostInc || t == tokPostDec))) { GenPrintInstr3Operands(MipsInstrAddiu, 0, GenWreg, 0, MipsOpRegFp, 0, MipsOpConst, v); } gotUnary = 1; break; case '(': if (gotUnary) GenPushReg(); gotUnary = 0; if (maxCallDepth != 1 && v < 16) GenGrowStack(16 - v); // *PP64 do we need EnsureDivisibleBy8 here? Not sure paramOfs = v - 4; if (maxCallDepth == 1) { if (v > 16) { // *PP64 ensure stack divisible by 8 (before we load all the stack args!) // Are there an odd number of args beyond A3? int paramsWillMisalign = (paramOfs % 8) == 0; if (paramsWillMisalign == 1) { GenGrowStack(4); GenStartCommentLine(); printf2("params misalign fix. TempsUsed: %d\n", TempsUsed); } } int stackIsMisaligned = TempsUsed % 2 != 0; if (stackIsMisaligned == 1) { GenGrowStack(4); GenStartCommentLine(); printf2("stack misalign fix. TempsUsed: %d\n", TempsUsed); } } if (maxCallDepth == 1 && paramOfs >= 0 && paramOfs <= 12) { // Work directly in A0-A3 instead of working in V0 and avoid copying V0 to A0-A3 GenWreg = MipsOpRegA0 + paramOfs / 4; } break; case ',': if (maxCallDepth == 1) { if (paramOfs == 16) { // Got the last on-stack parameter, the rest will go in A0-A3 GenPushReg(); gotUnary = 0; GenWreg = MipsOpRegA3; } if (paramOfs >= 0 && paramOfs <= 12) { // Advance to the next An reg or revert to V0 if (paramOfs) GenWreg--; else GenWreg = MipsOpRegV0; gotUnary = 0; } paramOfs -= 4; } break; case ')': GenLeaf = 0; if (maxCallDepth != 1) { if (v >= 4) GenPrintInstr2Operands(MipsInstrLW, 0, MipsOpRegA0, 0, MipsOpIndRegSp, 0); if (v >= 8) GenPrintInstr2Operands(MipsInstrLW, 0, MipsOpRegA1, 0, MipsOpIndRegSp, 4); if (v >= 12) GenPrintInstr2Operands(MipsInstrLW, 0, MipsOpRegA2, 0, MipsOpIndRegSp, 8); if (v >= 16) GenPrintInstr2Operands(MipsInstrLW, 0, MipsOpRegA3, 0, MipsOpIndRegSp, 12); } else { GenGrowStack(16); } if (v < 16) // *PP64 moved this up for check below v = 16; if (stack[i - 1][0] == tokIdent) { GenPrintInstr1Operand(MipsInstrJAL, 0, MipsOpLabel, stack[i - 1][1]); } else { GenPrintInstr1Operand(MipsInstrJAL, 0, GenWreg, 0); } // *PP64 ensure stack divisible by 8 if (maxCallDepth == 1) { if (EnsureDivisibleBy8(v) != v) { GenStartCommentLine(); printf2("params misalign fix undo. TempsUsed: %d\n", TempsUsed); } int stackAdjust = -EnsureDivisibleBy8(v); if (TempsUsed > 0) { // At this point, TempsUsed includes temps for A4+ args, which are irrelevant. int relevantTemps = (v > 16) ? (TempsUsed - ((v / 4) - 4)) : TempsUsed; if (relevantTemps > 0) { int stackIsMisaligned = relevantTemps % 2 != 0; if (stackIsMisaligned == 1) { GenStartCommentLine(); printf2("stack misalign fix undo. TempsUsed: %d\n", TempsUsed); stackAdjust -= 4; } } } GenGrowStack(stackAdjust); } else { GenGrowStack(-v); } break; case tokUnaryStar: if (stack[i - 1][0] == tokIdent) GenReadIdent(GenWreg, v, stack[i - 1][1]); else if (stack[i - 1][0] == tokLocalOfs) GenReadLocal(GenWreg, v, stack[i - 1][1]); else GenReadIndirect(GenWreg, GenWreg, v); break; case tokUnaryPlus: break; case '~': GenPrintInstr3Operands(MipsInstrNor, 0, GenWreg, 0, GenWreg, 0, GenWreg, 0); break; case tokUnaryMinus: GenPrintInstr3Operands(MipsInstrSubU, 0, GenWreg, 0, MipsOpRegZero, 0, GenWreg, 0); break; case '+': case '-': case '&': case '^': case '|': if (stack[i - 1][0] == tokNumInt) { int theconst = stack[i - 1][1]; int instr = GenGetBinaryOperatorInstr(tok); GenPrintInstr2Operands(MipsInstrLI, 0, MipsOpRegAt, 0, MipsOpConst, theconst); GenPrintInstr3Operands(instr, 0, GenWreg, 0, GenWreg, 0, MipsOpRegAt, 0); } else { int instr = GenGetBinaryOperatorInstr(tok); GenPopReg(); GenPrintInstr3Operands(instr, 0, GenWreg, 0, GenLreg, 0, GenRreg, 0); } break; // *PP64 break out more cases case tokLShift: case tokRShift: case tokURShift: if (stack[i - 1][0] == tokNumInt) { int theconst = stack[i - 1][1]; int instr = GenGetBinaryOperatorInstr(tok); instr = GenImmediateVersionOfInstr(instr); GenPrintInstr3Operands(instr, 0, GenWreg, 0, GenWreg, 0, MipsOpConst, theconst); } else { int instr = GenGetBinaryOperatorInstr(tok); GenPopReg(); GenPrintInstr3Operands(instr, 0, GenWreg, 0, GenLreg, 0, GenRreg, 0); } break; // *PP64 added case to reduce to 2 regs + mflo case '*': { int instr = GenGetBinaryOperatorInstr(tok); GenPopReg(); GenPrintInstr2Operands(instr, 0, GenLreg, 0, GenRreg, 0); GenPrintInstr1Operand(MipsInstrMfLo, 0, GenWreg, 0); } break; case '/': case tokUDiv: case '%': case tokUMod: { GenPopReg(); // *PP64 no, div does not have 3 regs... if (tok == '/' || tok == '%') GenPrintInstr2Operands(MipsInstrDiv, 0, GenLreg, 0, GenRreg, 0); else GenPrintInstr2Operands(MipsInstrDivU, 0, GenLreg, 0, GenRreg, 0); if (tok == '%' || tok == tokUMod) GenPrintInstr1Operand(MipsInstrMfHi, 0, GenWreg, 0); else GenPrintInstr1Operand(MipsInstrMfLo, 0, GenWreg, 0); } break; case tokInc: case tokDec: if (stack[i - 1][0] == tokIdent) { GenIncDecIdent(GenWreg, v, stack[i - 1][1], tok); } else if (stack[i - 1][0] == tokLocalOfs) { GenIncDecLocal(GenWreg, v, stack[i - 1][1], tok); } else { GenPrintInstr2Operands(MipsInstrMov, 0, TEMP_REG_A, 0, GenWreg, 0); GenIncDecIndirect(GenWreg, TEMP_REG_A, v, tok); } break; case tokPostInc: case tokPostDec: if (stack[i - 1][0] == tokIdent) { GenPostIncDecIdent(GenWreg, v, stack[i - 1][1], tok); } else if (stack[i - 1][0] == tokLocalOfs) { GenPostIncDecLocal(GenWreg, v, stack[i - 1][1], tok); } else { GenPrintInstr2Operands(MipsInstrMov, 0, TEMP_REG_A, 0, GenWreg, 0); GenPostIncDecIndirect(GenWreg, TEMP_REG_A, v, tok); } break; case tokPostAdd: case tokPostSub: { int instr = GenGetBinaryOperatorInstr(tok); GenPopReg(); if (GenWreg == GenLreg) { GenPrintInstr2Operands(MipsInstrMov, 0, TEMP_REG_B, 0, GenLreg, 0); GenReadIndirect(GenWreg, TEMP_REG_B, v); GenPrintInstr3Operands(instr, 0, TEMP_REG_A, 0, GenWreg, 0, GenRreg, 0); GenWriteIndirect(TEMP_REG_B, TEMP_REG_A, v); } else { // GenWreg == GenRreg here GenPrintInstr2Operands(MipsInstrMov, 0, TEMP_REG_B, 0, GenRreg, 0); GenReadIndirect(GenWreg, GenLreg, v); GenPrintInstr3Operands(instr, 0, TEMP_REG_B, 0, GenWreg, 0, TEMP_REG_B, 0); GenWriteIndirect(GenLreg, TEMP_REG_B, v); } } break; case tokAssignAdd: case tokAssignSub: case tokAssignAnd: case tokAssignXor: case tokAssignOr: case tokAssignLSh: case tokAssignRSh: case tokAssignURSh: if (stack[i - 1][0] == tokRevLocalOfs || stack[i - 1][0] == tokRevIdent) { int instr = GenGetBinaryOperatorInstr(tok); if (stack[i - 1][0] == tokRevLocalOfs) GenReadLocal(TEMP_REG_B, v, stack[i - 1][1]); else GenReadIdent(TEMP_REG_B, v, stack[i - 1][1]); GenPrintInstr3Operands(instr, 0, GenWreg, 0, TEMP_REG_B, 0, GenWreg, 0); if (stack[i - 1][0] == tokRevLocalOfs) GenWriteLocal(GenWreg, v, stack[i - 1][1]); else GenWriteIdent(GenWreg, v, stack[i - 1][1]); } else { int instr = GenGetBinaryOperatorInstr(tok); int lsaved, rsaved; GenPopReg(); if (GenWreg == GenLreg) { GenPrintInstr2Operands(MipsInstrMov, 0, TEMP_REG_B, 0, GenLreg, 0); lsaved = TEMP_REG_B; rsaved = GenRreg; } else { // GenWreg == GenRreg here GenPrintInstr2Operands(MipsInstrMov, 0, TEMP_REG_B, 0, GenRreg, 0); rsaved = TEMP_REG_B; lsaved = GenLreg; } GenReadIndirect(GenWreg, GenLreg, v); // destroys either GenLreg or GenRreg because GenWreg coincides with one of them GenPrintInstr3Operands(instr, 0, GenWreg, 0, GenWreg, 0, rsaved, 0); GenWriteIndirect(lsaved, GenWreg, v); } GenExtendRegIfNeeded(GenWreg, v); break; // *PP64 split this out and fix the 3 regs issue. case tokAssignMul: if (stack[i - 1][0] == tokRevLocalOfs || stack[i - 1][0] == tokRevIdent) { int instr = GenGetBinaryOperatorInstr(tok); if (stack[i - 1][0] == tokRevLocalOfs) GenReadLocal(TEMP_REG_B, v, stack[i - 1][1]); else GenReadIdent(TEMP_REG_B, v, stack[i - 1][1]); GenPrintInstr2Operands(instr, 0, TEMP_REG_B, 0, GenWreg, 0); GenPrintInstr1Operand(MipsInstrMfLo, 0, GenWreg, 0); if (stack[i - 1][0] == tokRevLocalOfs) GenWriteLocal(GenWreg, v, stack[i - 1][1]); else GenWriteIdent(GenWreg, v, stack[i - 1][1]); } else { int instr = GenGetBinaryOperatorInstr(tok); int lsaved, rsaved; GenPopReg(); if (GenWreg == GenLreg) { GenPrintInstr2Operands(MipsInstrMov, 0, TEMP_REG_B, 0, GenLreg, 0); lsaved = TEMP_REG_B; rsaved = GenRreg; } else { // GenWreg == GenRreg here GenPrintInstr2Operands(MipsInstrMov, 0, TEMP_REG_B, 0, GenRreg, 0); rsaved = TEMP_REG_B; lsaved = GenLreg; } GenReadIndirect(GenWreg, GenLreg, v); // destroys either GenLreg or GenRreg because GenWreg coincides with one of them GenPrintInstr2Operands(instr, 0, GenWreg, 0, rsaved, 0); GenPrintInstr1Operand(MipsInstrMfLo, 0, GenWreg, 0); GenWriteIndirect(lsaved, GenWreg, v); } GenExtendRegIfNeeded(GenWreg, v); break; case tokAssignDiv: case tokAssignUDiv: case tokAssignMod: case tokAssignUMod: if (stack[i - 1][0] == tokRevLocalOfs || stack[i - 1][0] == tokRevIdent) { if (stack[i - 1][0] == tokRevLocalOfs) GenReadLocal(TEMP_REG_B, v, stack[i - 1][1]); else GenReadIdent(TEMP_REG_B, v, stack[i - 1][1]); // *PP64 div does not have 3 regs if (tok == tokAssignDiv || tok == tokAssignMod) GenPrintInstr2Operands(MipsInstrDiv, 0, TEMP_REG_B, 0, GenWreg, 0); else GenPrintInstr2Operands(MipsInstrDivU, 0, TEMP_REG_B, 0, GenWreg, 0); if (tok == tokAssignMod || tok == tokAssignUMod) GenPrintInstr1Operand(MipsInstrMfHi, 0, GenWreg, 0); else GenPrintInstr1Operand(MipsInstrMfLo, 0, GenWreg, 0); if (stack[i - 1][0] == tokRevLocalOfs) GenWriteLocal(GenWreg, v, stack[i - 1][1]); else GenWriteIdent(GenWreg, v, stack[i - 1][1]); } else { int lsaved, rsaved; GenPopReg(); if (GenWreg == GenLreg) { GenPrintInstr2Operands(MipsInstrMov, 0, TEMP_REG_B, 0, GenLreg, 0); lsaved = TEMP_REG_B; rsaved = GenRreg; } else { // GenWreg == GenRreg here GenPrintInstr2Operands(MipsInstrMov, 0, TEMP_REG_B, 0, GenRreg, 0); rsaved = TEMP_REG_B; lsaved = GenLreg; } GenReadIndirect(GenWreg, GenLreg, v); // destroys either GenLreg or GenRreg because GenWreg coincides with one of them // *PP64 div has 2 regs if (tok == tokAssignDiv || tok == tokAssignMod) GenPrintInstr2Operands(MipsInstrDiv, 0, GenWreg, 0, rsaved, 0); else GenPrintInstr2Operands(MipsInstrDivU, 0, GenWreg, 0, rsaved, 0); if (tok == tokAssignMod || tok == tokAssignUMod) GenPrintInstr1Operand(MipsInstrMfHi, 0, GenWreg, 0); else GenPrintInstr1Operand(MipsInstrMfLo, 0, GenWreg, 0); GenWriteIndirect(lsaved, GenWreg, v); } GenExtendRegIfNeeded(GenWreg, v); break; case '=': if (stack[i - 1][0] == tokRevLocalOfs) { GenWriteLocal(GenWreg, v, stack[i - 1][1]); } else if (stack[i - 1][0] == tokRevIdent) { GenWriteIdent(GenWreg, v, stack[i - 1][1]); } else { GenPopReg(); GenWriteIndirect(GenLreg, GenRreg, v); if (GenWreg != GenRreg) GenPrintInstr2Operands(MipsInstrMov, 0, GenWreg, 0, GenRreg, 0); } GenExtendRegIfNeeded(GenWreg, v); break; case tokAssign0: // assignment of 0, while throwing away the expression result value if (stack[i - 1][0] == tokRevLocalOfs) { GenWriteLocal(MipsOpRegZero, v, stack[i - 1][1]); } else if (stack[i - 1][0] == tokRevIdent) { GenWriteIdent(MipsOpRegZero, v, stack[i - 1][1]); } else { GenWriteIndirect(GenWreg, MipsOpRegZero, v); } break; case '<': GenCmp(&i, 0x00); break; case tokLEQ: GenCmp(&i, 0x01); break; case '>': GenCmp(&i, 0x02); break; case tokGEQ: GenCmp(&i, 0x03); break; case tokULess: GenCmp(&i, 0x10); break; case tokULEQ: GenCmp(&i, 0x11); break; case tokUGreater: GenCmp(&i, 0x12); break; case tokUGEQ: GenCmp(&i, 0x13); break; case tokEQ: GenCmp(&i, 0x04); break; case tokNEQ: GenCmp(&i, 0x05); break; case tok_Bool: GenPrintInstr3Operands(MipsInstrSLTU, 0, GenWreg, 0, MipsOpRegZero, 0, GenWreg, 0); break; case tokSChar: #ifdef DONT_USE_SEH GenPrintInstr3Operands(MipsInstrSLL, 0, GenWreg, 0, GenWreg, 0, MipsOpConst, 24); GenPrintInstr3Operands(MipsInstrSRA, 0, GenWreg, 0, GenWreg, 0, MipsOpConst, 24); #else GenPrintInstr2Operands(MipsInstrSeb, 0, GenWreg, 0, GenWreg, 0); #endif break; case tokUChar: GenPrintInstr3Operands(MipsInstrAndi, 0, GenWreg, 0, GenWreg, 0, MipsOpConst, 0xFF); break; case tokShort: #ifdef DONT_USE_SEH GenPrintInstr3Operands(MipsInstrSLL, 0, GenWreg, 0, GenWreg, 0, MipsOpConst, 16); GenPrintInstr3Operands(MipsInstrSRA, 0, GenWreg, 0, GenWreg, 0, MipsOpConst, 16); #else GenPrintInstr2Operands(MipsInstrSeh, 0, GenWreg, 0, GenWreg, 0); #endif break; case tokUShort: GenPrintInstr3Operands(MipsInstrAndi, 0, GenWreg, 0, GenWreg, 0, MipsOpConst, 0xFFFF); break; case tokShortCirc: #ifndef NO_ANNOTATIONS if (v >= 0) printf2("&&\n"); else printf2("||\n"); #endif if (v >= 0) GenJumpIfZero(v); // && else GenJumpIfNotZero(-v); // || gotUnary = 0; break; case tokGoto: #ifndef NO_ANNOTATIONS printf2("goto\n"); #endif GenJumpUncond(v); gotUnary = 0; break; case tokLogAnd: case tokLogOr: GenNumLabel(v); break; case tokVoid: gotUnary = 0; break; case tokRevIdent: case tokRevLocalOfs: case tokComma: case tokReturn: case tokNum0: break; case tokIf: GenJumpIfNotZero(stack[i][1]); break; case tokIfNot: GenJumpIfZero(stack[i][1]); break; default: //error("Error: Internal Error: GenExpr0(): unexpected token %s\n", GetTokenName(tok)); errorInternal(103); break; } } if (GenWreg != MipsOpRegV0) errorInternal(104); } STATIC void GenDumpChar(int ch) { if (ch < 0) { if (TokenStringLen) printf2("\"\n"); return; } if (TokenStringLen == 0) { GenStartAsciiString(); printf2("\""); } if (ch >= 0x20 && ch <= 0x7E) { if (ch == '"' || ch == '\\') printf2("\\"); printf2("%c", ch); } else { printf2("\\%03o", ch); } } STATIC void GenExpr(void) { GenExpr0(); } STATIC void GenFin(void) { if (StructCpyLabel) { int lbl = LabelCnt++; puts2(CodeHeaderFooter[0]); GenNumLabel(StructCpyLabel); puts2("\tmove\t$2, $6\n" "\tmove\t$3, $6"); GenNumLabel(lbl); puts2("\tlbu\t$6, 0($5)\n" "\taddiu\t$5, $5, 1\n" "\taddiu\t$4, $4, -1\n" "\tsb\t$6, 0($3)\n" "\taddiu\t$3, $3, 1"); printf2("\tbne\t$4, $0, "); GenPrintNumLabel(lbl); puts2(""); #ifdef REORDER_WORKAROUND GenNop(); #endif puts2("\tjr\t$31"); #ifdef REORDER_WORKAROUND GenNop(); #endif puts2(CodeHeaderFooter[1]); } #ifndef NO_STRUCT_BY_VAL if (StructPushLabel) { int lbl = LabelCnt++; puts2(CodeHeaderFooter[0]); GenNumLabel(StructPushLabel); puts2("\tmove\t$6, $5\n" "\taddiu\t$6, $6, 3\n" "\tli\t$3, -4\n" "\tand\t$6, $6, $3\n" "\tsubu\t$29, $29, $6\n" "\taddiu\t$3, $29, 16\n" "\tmove\t$2, $3"); GenNumLabel(lbl); puts2("\tlbu\t$6, 0($4)\n" "\taddiu\t$4, $4, 1\n" "\taddiu\t$5, $5, -1\n" "\tsb\t$6, 0($3)\n" "\taddiu\t$3, $3, 1"); printf2("\tbne\t$5, $0, "); GenPrintNumLabel(lbl); puts2(""); #ifdef REORDER_WORKAROUND GenNop(); #endif puts2("\tlw\t$2, 0($2)\n" "\taddiu\t$29, $29, 4\n" "\tjr\t$31"); #ifdef REORDER_WORKAROUND GenNop(); #endif puts2(CodeHeaderFooter[1]); } #endif }
0.992188
high
pw_transfer/public/pw_transfer/internal/server_context.h
bouffalolab/pigweed
1
906433
// Copyright 2022 The Pigweed Authors // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. #pragma once #include "pw_assert/assert.h" #include "pw_containers/intrusive_list.h" #include "pw_result/result.h" #include "pw_rpc/raw/server_reader_writer.h" #include "pw_transfer/handler.h" #include "pw_transfer/internal/context.h" namespace pw::transfer::internal { // Transfer context for use within the transfer service (server-side). Stores a // pointer to a transfer handler when active to stream the transfer data. class ServerContext final : public Context { public: constexpr ServerContext() : handler_(nullptr) {} // Sets the handler. The handler isn't set by Context::Initialize() since // ClientContexts don't track it. void set_handler(Handler& handler) { handler_ = &handler; } private: // Ends the transfer with the given status, calling the handler's Finalize // method. No chunks are sent. // // Returns DATA_LOSS if the finalize call fails. // // Precondition: Transfer context is active. Status FinalCleanup(Status status) override; Handler* handler_; }; } // namespace pw::transfer::internal
0.996094
high
include/cnl/_impl/num_traits/set_tag.h
decaf-emu/cnl
0
906945
// Copyright <NAME> 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file ../LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #if !defined(CNL_IMPL_NUM_TRAITS_SET_TAG_H) #define CNL_IMPL_NUM_TRAITS_SET_TAG_H #include "tag.h" /// compositional numeric library namespace cnl { /// \brief meta-function object that transforms a component from one Tag type to another /// /// \tparam T component to transform /// \tparam OutRep new behavior type being wrapped by the resultant type /// /// \sa to_rep, from_rep, set_rep, tag template<typename T, tag OutTag, class Enable = void> struct set_tag; namespace _impl { template<typename T, tag OutTag> using set_tag_t = typename set_tag<T, OutTag>::type; } } #endif // CNL_IMPL_NUM_TRAITS_SET_TAG_H
0.992188
high
include/toolkit/core/RefCounted.h
nneesshh/mytoolkit
0
907457
<filename>include/toolkit/core/RefCounted.h #ifndef __CORE_REF_COUNTED_H__ #define __CORE_REF_COUNTED_H__ #include "../platform/types.h" #include <atomic> #ifdef _MSC_VER #pragma warning(disable : 4786) #endif #ifndef __cplusplus #error RefCounted requires C++ #endif class IRefCounted { protected: /** * Protected so users of refcounted classes don't use std::auto_ptr * or the delete operator. * * Interfaces that derive from RefCounted should define an inline, * empty, protected destructor as well. */ virtual ~IRefCounted() { } public: /** * Add a reference to the internal reference count. */ MYDLL_METHOD(void) ref() = 0; /** * Remove a reference from the internal reference count. When this * reaches 0, the object is destroyed. */ MYDLL_METHOD(void) unref() = 0; /** * Return reference count. */ MYDLL_METHOD(int) refcount() const = 0; }; /** * A basic implementation of the RefCounted interface. Derive * your implementations from RefImplementation<YourInterface>. */ template<class Interface> class RefImplementation : public Interface { protected: RefImplementation() { _ref_count = 0; } /** * So the implementation can put its destruction logic in the destructor, * as natural C++ code does. */ virtual ~RefImplementation() { } public: void MYAPI_CALL ref() { ++_ref_count; } void MYAPI_CALL unref() { if (--_ref_count == 0) { delete this; } } int MYAPI_CALL refcount() const { return _ref_count; } private: std::atomic_int _ref_count; }; /* auto ptr for IRefCounted */ template<typename T> class RefPtr { public: RefPtr(T* rsh = nullptr) { _ptr = nullptr; *this = rsh; } RefPtr(const RefPtr<T>& rsh) { _ptr = nullptr; *this = rsh; } virtual ~RefPtr() { if (_ptr) { _ptr->unref(); _ptr = 0; } } RefPtr<T>& operator=(T* rsh) { if (rsh != _ptr) { if (_ptr) { _ptr->unref(); } _ptr = rsh; if (_ptr) { _ptr->ref(); } } return *this; } RefPtr<T>& operator=(const RefPtr<T>& rsh) { *this = rsh._ptr; return *this; } T* operator->() const { return _ptr; } T& operator*() const { return *_ptr; } operator bool() const { return (_ptr != 0); } T* get() const { return _ptr; } private: T* _ptr; }; template<typename T, typename U> bool operator==(const RefPtr<T>& a, const RefPtr<U>& b) { return (a.get() == b.get()); } template<typename T> bool operator==(const RefPtr<T>& a, const T* b) { return (a.get() == b); } template<typename T> bool operator==(const T* a, const RefPtr<T>& b) { return (a == b.get()); } template<typename T, typename U> bool operator!=(const RefPtr<T>& a, const RefPtr<U>& b) { return (a.get() != b.get()); } template<typename T> bool operator!=(const RefPtr<T>& a, const T* b) { return (a.get() != b); } template<typename T> bool operator!=(const T* a, const RefPtr<T>& b) { return (a != b.get()); } #endif
0.996094
high
Descending Europa/Temp/StagingArea/Data/il2cppOutput/AssemblyU2DCSharpU2Dfirstpass_U3CPrivateImplementa3053238933.h
screwylightbulb/europa
0
907969
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_Object4170816371.h" #include "AssemblyU2DCSharpU2Dfirstpass_U3CPrivateImplementa1676615736.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <PrivateImplementationDetails> struct U3CPrivateImplementationDetailsU3E_t3053238938 : public Il2CppObject { public: public: }; struct U3CPrivateImplementationDetailsU3E_t3053238938_StaticFields { public: // <PrivateImplementationDetails>/$ArrayType$124 <PrivateImplementationDetails>::$$field-0 U24ArrayTypeU24124_t1676615737 ___U24U24fieldU2D0_0; public: inline static int32_t get_offset_of_U24U24fieldU2D0_0() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3053238938_StaticFields, ___U24U24fieldU2D0_0)); } inline U24ArrayTypeU24124_t1676615737 get_U24U24fieldU2D0_0() const { return ___U24U24fieldU2D0_0; } inline U24ArrayTypeU24124_t1676615737 * get_address_of_U24U24fieldU2D0_0() { return &___U24U24fieldU2D0_0; } inline void set_U24U24fieldU2D0_0(U24ArrayTypeU24124_t1676615737 value) { ___U24U24fieldU2D0_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
0.976563
high
Desktop/CCore/inc/video/DragWindow.h
SergeyStrukov/CCore-2-xx
0
908481
<reponame>SergeyStrukov/CCore-2-xx /* DragWindow.h */ //---------------------------------------------------------------------------------------- // // Project: CCore 2.00 // // Tag: Desktop // // License: Boost Software License - Version 1.0 - August 17th, 2003 // // see http://www.boost.org/LICENSE_1_0.txt or the local copy // // Copyright (c) 2016 <NAME>. All rights reserved. // //---------------------------------------------------------------------------------------- #ifndef CCore_inc_video_DragWindow_h #define CCore_inc_video_DragWindow_h #include <CCore/inc/video/ClientWindow.h> #include <CCore/inc/video/Font.h> #include <CCore/inc/video/FrameGuards.h> #include <CCore/inc/video/RefVal.h> #include <CCore/inc/String.h> #include <CCore/inc/DeferCall.h> #include <CCore/inc/Signal.h> namespace CCore { namespace Video { /* consts */ enum DragType { DragType_None = 0, DragType_Top, DragType_TopLeft, DragType_Left, DragType_BottomLeft, DragType_Bottom, DragType_BottomRight, DragType_Right, DragType_TopRight, DragType_Bar, DragType_Alert, DragType_Min, DragType_Max, DragType_Close }; enum AlertType { AlertType_No = 0, AlertType_Closed, AlertType_Opened }; /* DragPane() */ void DragPane(Pane &place,Point delta,DragType drag_type); /* classes */ class DragShape; template <class Shape> class DragWindowOf; /* class DragShape */ class DragShape { public: struct Config { RefVal<MCoord> width = Fraction(6,2) ; RefVal<Coord> frame_dxy = 12 ; RefVal<Coord> title_dy = 32 ; RefVal<Coord> btn_dx = 26 ; RefVal<Coord> btn_dy = 24 ; RefVal<VColor> top = Gray ; RefVal<VColor> bottom = Snow ; RefVal<VColor> frame = Snow ; RefVal<VColor> drag = Silver ; RefVal<VColor> dragHilight = Green ; RefVal<VColor> dragActive = Red ; RefVal<VColor> active = RoyalBlue ; RefVal<VColor> inactive = Silver ; RefVal<VColor> title = Black ; RefVal<VColor> btnFace = SteelBlue ; RefVal<VColor> btnFaceHilight = Green ; RefVal<VColor> btnPict = White ; RefVal<VColor> btnPictClose = Red ; RefVal<VColor> btnPictAlert = Red ; RefVal<VColor> btnPictNoAlert = Gray ; RefVal<VColor> btnPictCloseAlert = Orange ; RefVal<VColor> shade_color = Violet ; RefVal<Clr> shade_alpha = 64 ; RefVal<Font> title_font; RefVal<unsigned> blink_time = 3*25 ; RefVal<unsigned> blink_period = 3 ; RefVal<DefString> fatal_error = "Fatal error"_def ; Config() {} }; const Config &cfg; private: Point size; Pane dragTopLeft; Pane dragLeft; Pane dragBottomLeft; Pane dragBottom; Pane dragBottomRight; Pane dragRight; Pane dragTopRight; Pane dragBar; Pane titleBar; Pane btnAlert; Pane btnMin; Pane btnMax; Pane btnClose; Pane client; private: class DrawArt; VColor dragColor(DragType zone) const; void draw_Frame(DrawArt &art) const; void draw_TopLeft(DrawArt &art) const; void draw_Left(DrawArt &art) const; void draw_BottomLeft(DrawArt &art) const; void draw_Bottom(DrawArt &art) const; void draw_BottomRight(DrawArt &art) const; void draw_Right(DrawArt &art) const; void draw_TopRight(DrawArt &art) const; void draw_Bar(DrawArt &art) const; void draw_Alert(DrawArt &art) const; void draw_Min(DrawArt &art) const; void draw_Max(DrawArt &art) const; void draw_Close(DrawArt &art) const; public: // state bool has_focus = false ; bool max_button = true ; bool is_main = true ; DragType drag_type = DragType_None ; DragType hilight = DragType_None ; DragType btn_type = DragType_None ; AlertType alert_type = AlertType_No ; bool alert_blink = false ; String title; // methods explicit DragShape(const Config &cfg_) : cfg(cfg_) {} Point getDeltaSize() const; Coord getMinDx(StrLen title) const; Pane getClient() const { return client; } void reset(const String &title,bool is_main,bool max_button); void layout(Point size); void draw(const DrawBuf &buf) const; void draw(const DrawBuf &buf,DragType drag_type) const; Pane getPane(DragType drag_type) const; DragType dragTest(Point point) const; }; /* class DragWindowOf<Shape> */ template <class Shape> class DragWindowOf : public FrameWindow , public SubWindowHost { public: using ShapeType = Shape ; using ConfigType = typename Shape::Config ; private: Shape shape; ClientWindow *client = 0 ; ClientWindow *alert_client = 0 ; Point size; Point drag_from; bool client_enter = false ; bool client_capture = false ; bool delay_draw = false ; bool enable_react = true ; unsigned tick_count = 0 ; private: void guardClient() { if( !client ) GuardNoClient(); } void guardDead() { if( isAlive() ) GuardNotDead(); } void reset() { size=Null; client_enter=false; client_capture=false; delay_draw=false; enable_react=true; tick_count=0; } void replace(Pane place,Point delta,DragType drag_type) { DragPane(place,delta,drag_type); Point new_size(place.dx,place.dy); if( new_size>Null && new_size<=host->getMaxSize() ) { Pane screen=Pane(Null,desktop->getScreenSize()); if( +Inf(place,screen) ) { if( !shape.max_button ) { shape.max_button=true; redrawFrame(DragType_Max); } host->move(place); host->invalidate(1); } } } void replace(Point delta,DragType drag_type) { Pane place=host->getPlace(); replace(place,delta,drag_type); } void startDrag(Point point,DragType drag_type) { shape.drag_type=drag_type; if( !client_capture ) host->captureMouse(); Pane place=host->getPlace(); drag_from=point+place.getBase(); redrawAll(); } void dragTo(Point point) { Pane place=host->getPlace(); Point delta=Diff(drag_from,point+place.getBase()); replace(place,delta,shape.drag_type); } void endDrag() { shape.drag_type=DragType_None; redrawAll(); } void endDrag(Point point) { dragTo(point); shape.drag_type=DragType_None; if( !client_capture ) host->releaseMouse(); redrawAll(); } void btnDown(DragType drag_type) { shape.btn_type=drag_type; redrawFrame(drag_type); } void btnUp(Point point) { auto type=Replace(shape.btn_type,DragType_None); redrawFrame(type); if( shape.dragTest(point)==type ) { switch( type ) { case DragType_Alert : switchClients(); break; case DragType_Min : minimize(); break; case DragType_Max : maximize(); break; case DragType_Close : destroy(); break; } } } void moveBtn(Point point) { if( shape.dragTest(point)!=shape.btn_type ) endBtn(); } void endBtn() { redrawFrame(Replace(shape.btn_type,DragType_None)); } void hilightFrame(Point point) { auto drag_type=shape.dragTest(point); if( drag_type==DragType_Bar ) drag_type=DragType_None; if( drag_type!=shape.hilight ) { auto type=Replace(shape.hilight,drag_type); redrawFrame(type); redrawFrame(drag_type); } } void endHilightFrame() { if( shape.hilight ) { redrawFrame(Replace(shape.hilight,DragType_None)); } } bool forwardKey(VKey vkey,KeyMod kmod,unsigned repeat=1) { if( kmod&KeyMod_Alt ) { switch( vkey ) { case VKey_Left : replace(Point(-(Coord)repeat,0),(kmod&KeyMod_Shift)?DragType_Right:DragType_Bar); return true; case VKey_Right : replace(Point((Coord)repeat,0),(kmod&KeyMod_Shift)?DragType_Right:DragType_Bar); return true; case VKey_Up : replace(Point(0,-(Coord)repeat),(kmod&KeyMod_Shift)?DragType_Bottom:DragType_Bar); return true; case VKey_Down : replace(Point(0,(Coord)repeat),(kmod&KeyMod_Shift)?DragType_Bottom:DragType_Bar); return true; case VKey_F2 : minimize(); return true; case VKey_F3 : maximize(); return true; case VKey_F4 : destroy(); return true; case VKey_F12 : switchClients(); return true; default: return false; } } else { return false; } } bool forwardKeyUp(VKey vkey,KeyMod kmod,unsigned =1) { if( kmod&KeyMod_Alt ) { switch( vkey ) { case VKey_Left : case VKey_Right : case VKey_Up : case VKey_Down : case VKey_F2 : case VKey_F3 : case VKey_F4 : case VKey_F12 : return true; default: return false; } } else { return false; } } ClientWindow & getClient() { if( alert_client && shape.alert_type==AlertType_Opened ) return *alert_client; guardClient(); return *client; } SubWindow & getClientSub() { return getClient().getSubWindow(); } void shade(FrameBuf<DesktopColor> &buf) { if( !enable_react ) buf.erase(+shape.cfg.shade_color,+shape.cfg.shade_alpha); } template <class Func> void redraw(Func func) { if( host->isDead() ) return; if( host->getToken() ) { delay_draw=true; return; } FrameBuf<DesktopColor> buf(host->getDrawPlane()); if( size<=buf.getSize() ) { func(buf); } else { buf.erase(Black); host->invalidate(1); } } void redrawFrame() { redraw( [this] (FrameBuf<DesktopColor> &buf) { try { shape.draw(buf); } catch(CatchType) {} shade(buf); host->invalidate(1); } ); } void redrawFrame(DragType drag_type) { Pane pane=shape.getPane(drag_type); if( !pane ) return; redraw( [this,drag_type,pane] (FrameBuf<DesktopColor> &buf) { try { shape.draw(buf,drag_type); } catch(CatchType) {} shade(buf); host->invalidate(pane,1); } ); } void pushAlertBlink() { if( !tick_count ) { tick_count=+shape.cfg.blink_time; defer_tick.start(); } else { tick_count=+shape.cfg.blink_time; } } void tick() { if( tick_count ) { if( !(tick_count%+shape.cfg.blink_period) ) { shape.alert_blink=!shape.alert_blink; redrawFrame(DragType_Alert); } tick_count--; } else { defer_tick.stop(); shape.alert_blink=false; redrawFrame(DragType_Alert); } } void switchClients() { if( shape.alert_type && alert_client ) { getClientSub().close(); shape.alert_type=(shape.alert_type==AlertType_Closed)?AlertType_Opened:AlertType_Closed; getClientSub().open(); redrawAll(); } } public: DragWindowOf(Desktop *desktop,const ConfigType &cfg) : FrameWindow(desktop), shape(cfg), input(this), connector_updateConfig(this,&DragWindowOf<Shape>::updateConfig), connector_alert(this,&DragWindowOf<Shape>::alert) { defer_tick=input.create(&DragWindowOf<Shape>::tick); } DragWindowOf(Desktop *desktop,const ConfigType &cfg,Signal<> &update) : DragWindowOf(desktop,cfg) { connector_updateConfig.connect(update); } virtual ~DragWindowOf() { } // methods Point getDeltaSize() const { return shape.getDeltaSize(); } Point getMinSize(StrLen title,Point size) const { size+=shape.getDeltaSize(); return Point(Max(size.x,shape.getMinDx(title)),size.y); } void bindUpdate(Signal<> &update) { connector_updateConfig.disconnect(); connector_updateConfig.connect(update); } void bindClient(ClientWindow &client_) { guardDead(); client=&client_; } void bindAlertClient(ClientWindow &alert_client_) { guardDead(); alert_client=&alert_client_; } void createMain(CmdDisplay cmd_display,Point max_size,const String &title) { guardClient(); shape.reset(title,true, cmd_display!=CmdDisplay_Maximized ); host->createMain(max_size); host->setTitle(Range(title)); host->display(cmd_display); } void createMain(CmdDisplay cmd_display,Pane pane,Point max_size,const String &title) { guardClient(); shape.reset(title,true, cmd_display!=CmdDisplay_Maximized ); host->createMain(pane,max_size); host->setTitle(Range(title)); host->display(cmd_display); } void create(Pane pane,Point max_size,const String &title) { guardClient(); shape.reset(title,false,true); host->create(pane,max_size); host->show(); } void create(FrameWindow *parent,Pane pane,Point max_size,const String &title) { guardClient(); shape.reset(title,false,true); host->create(parent->getHost(),pane,max_size); host->show(); } void destroy() { if( client && client->askDestroy() ) { host->destroy(); destroyed.assert(); } } void minimize() { if( shape.is_main ) host->display(CmdDisplay_Minimized); } void maximize() { if( shape.max_button ) { shape.max_button=false; redrawFrame(DragType_Max); host->display(CmdDisplay_Maximized); } else { shape.max_button=true; redrawFrame(DragType_Max); host->display(CmdDisplay_Restore); } } void redrawAll(bool do_layout=false) { if( do_layout ) { shape.layout(size); if( client ) client->getSubWindow().setPlace(shape.getClient()); if( alert_client ) alert_client->getSubWindow().setPlace(shape.getClient()); } redraw( [this] (FrameBuf<DesktopColor> &buf) { try { shape.draw(buf); } catch(CatchType) {} getClientSub().forward_draw(buf,shape.drag_type); shade(buf); host->invalidate(1); } ); } void redrawClient() { redraw( [this] (FrameBuf<DesktopColor> &buf) { getClientSub().forward_draw(buf,shape.drag_type); shade(buf); host->invalidate(shape.getClient(),1); } ); } void redrawClient(Pane pane) { redraw( [this,pane] (FrameBuf<DesktopColor> &buf) { getClientSub().forward_draw(buf,pane,shape.drag_type); shade(buf); host->invalidate(pane,1); } ); } unsigned getToken() { return host->getToken(); } void setTitle(const String &title) { shape.title=title; host->setTitle(Range(title)); redrawFrame(); } void connectAlert(Signal<> &signal) { connector_alert.connect(signal); } // SubWindowHost virtual FrameWindow * getFrame() { return this; } virtual Point getScreenOrigin() { Pane pane=host->getPlace(); return pane.getBase(); } virtual void redraw(Pane pane) { input.redrawClient(pane); } virtual void setFocus(SubWindow *) { if( shape.has_focus ) { getClientSub().gainFocus(); } } virtual void captureMouse(SubWindow *) { if( !client_capture ) { client_capture=true; if( !shape.drag_type ) host->captureMouse(); } } virtual void releaseMouse(SubWindow *) { if( client_capture ) { client_capture=false; if( !shape.drag_type ) host->releaseMouse(); } } // base virtual void alive() { reset(); host->trackMouseHover(); host->trackMouseLeave(); if( client ) client->alive(); if( alert_client ) alert_client->alive(); getClientSub().open(); } virtual void dead() { getClientSub().close(); if( client ) client->dead(); if( alert_client ) alert_client->dead(); } virtual void askClose() { destroy(); } virtual void setSize(Point size_,bool buf_dirty) { if( size!=size_ || buf_dirty ) { size=size_; redrawAll(true); } } virtual void paintDone(unsigned) { if( delay_draw ) { delay_draw=false; redrawAll(); } } // keyboard virtual void gainFocus() { shape.has_focus=true; redrawFrame(); getClientSub().gainFocus(); } virtual void looseFocus() { shape.has_focus=false; redrawFrame(); getClientSub().looseFocus(); } // mouse virtual void looseCapture() { if( shape.drag_type ) endDrag(); if( client_capture ) { client_capture=false; getClientSub().looseCapture(); } } virtual void setMouseShape(Point point,KeyMod kmod) { switch( shape.dragTest(point) ) { case DragType_Top : host->setMouseShape(Mouse_SizeUpDown); break; case DragType_TopLeft : host->setMouseShape(Mouse_SizeUpLeft); break; case DragType_Left : host->setMouseShape(Mouse_SizeLeftRight); break; case DragType_BottomLeft : host->setMouseShape(Mouse_SizeUpRight); break; case DragType_Bottom : host->setMouseShape(Mouse_SizeUpDown); break; case DragType_BottomRight : host->setMouseShape(Mouse_SizeUpLeft); break; case DragType_Right : host->setMouseShape(Mouse_SizeLeftRight); break; case DragType_TopRight : host->setMouseShape(Mouse_SizeUpRight); break; case DragType_Alert : case DragType_Min : case DragType_Max : host->setMouseShape(Mouse_Hand); break; case DragType_Close : host->setMouseShape(Mouse_Stop); break; case DragType_Bar : host->setMouseShape(Mouse_SizeAll); break; default: host->setMouseShape(getClientSub().forward_getMouseShape(point,kmod)); } } // user input virtual void disableReact() { enable_react=false; redrawAll(); } virtual void enableReact() { enable_react=true; redrawAll(); } virtual void react(UserAction action) { if( enable_react ) action.dispatch(*this); } void react_other(UserAction action) { if( action.fromKeyboard() ) { getClientSub().react(action); } else { if( shape.drag_type || shape.btn_type ) return; Point point=action.getPoint(); if( client_capture || shape.getClient().contains(point) ) { getClientSub().forward_react(action); } } } void react_Key(VKey vkey,KeyMod kmod) { if( !forwardKey(vkey,kmod) ) getClientSub().put_Key(vkey,kmod); } void react_Key(VKey vkey,KeyMod kmod,unsigned repeat) { if( !forwardKey(vkey,kmod,repeat) ) getClientSub().put_Key(vkey,kmod,repeat); } void react_KeyUp(VKey vkey,KeyMod kmod) { if( !forwardKeyUp(vkey,kmod) ) getClientSub().put_KeyUp(vkey,kmod); } void react_KeyUp(VKey vkey,KeyMod kmod,unsigned repeat) { if( !forwardKeyUp(vkey,kmod,repeat) ) getClientSub().put_KeyUp(vkey,kmod,repeat); } void react_LeftClick(Point point,MouseKey mkey) { switch( auto drag_type=shape.dragTest(point) ) { case DragType_None : { if( client_capture || shape.getClient().contains(point) ) { getClientSub().forward().put_LeftClick(point,mkey); } } break; case DragType_Alert : case DragType_Min : case DragType_Max : case DragType_Close : { if( !shape.drag_type && !shape.btn_type ) btnDown(drag_type); } break; default: { if( !shape.drag_type && !shape.btn_type ) startDrag(point,drag_type); } } } void react_LeftUp(Point point,MouseKey mkey) { if( shape.drag_type ) { endDrag(point); } else if( shape.btn_type ) { btnUp(point); } else if( client_capture || shape.getClient().contains(point) ) { getClientSub().forward().put_LeftUp(point,mkey); } hilightFrame(point); } void react_Move(Point point,MouseKey mkey) { if( shape.drag_type ) { if( mkey&MouseKey_Left ) dragTo(point); else endDrag(point); } else if( shape.btn_type ) { if( mkey&MouseKey_Left ) moveBtn(point); else endBtn(); } else { hilightFrame(point); if( shape.getClient().contains(point) ) { client_enter=true; getClientSub().forward().put_Move(point,mkey); } else { if( client_capture ) getClientSub().forward().put_Move(point,mkey); if( client_enter ) { client_enter=false; getClientSub().put_Leave(); } } } } void react_Leave() { if( shape.btn_type ) { endBtn(); } else if( !shape.drag_type ) { endHilightFrame(); } if( client_enter ) { client_enter=false; getClientSub().put_Leave(); } } // signals Signal<> destroyed; // DeferInput class Input : DeferInput<DragWindowOf<Shape> > { friend class DragWindowOf<Shape>; explicit Input(DragWindowOf<Shape> *window) : DeferInput<DragWindowOf<Shape> >(window) {} ~Input() {} using DeferInput<DragWindowOf<Shape> >::try_post; public: void redrawAll(bool do_layout=false) { try_post(&DragWindowOf<Shape>::redrawAll,do_layout); } void redrawClient() { try_post(&DragWindowOf<Shape>::redrawClient); } void redrawClient(Pane pane) { try_post(&DragWindowOf<Shape>::redrawClient,pane); } }; Input input; private: DeferTick defer_tick; void updateConfig() { input.redrawAll(true); } void alert() { switch( shape.alert_type ) { case AlertType_No : { shape.alert_type=AlertType_Closed; redrawFrame(DragType_Alert); pushAlertBlink(); } break; case AlertType_Closed : { pushAlertBlink(); } break; case AlertType_Opened : { redrawClient(); } break; } } SignalConnector<DragWindowOf<Shape> > connector_updateConfig; SignalConnector<DragWindowOf<Shape> > connector_alert; }; /* type DragWindow */ using DragWindow = DragWindowOf<DragShape> ; } // namespace Video } // namespace CCore #endif
0.996094
high
testfiles/sv-comp-2019/16.shadowing.c
moves-rwth/nitwit-validator
4
908993
extern void __VERIFIER_error() ; extern int __VERIFIER_nondet_int(); extern unsigned int __VERIFIER_nondet_uint(); extern unsigned short __VERIFIER_nondet_ushort(); extern short __VERIFIER_nondet_short(); extern long __VERIFIER_nondet_long(); extern unsigned long __VERIFIER_nondet_ulong(); extern char __VERIFIER_nondet_char(); extern unsigned char __VERIFIER_nondet_uchar(); extern double __VERIFIER_nondet_double(); extern double __VERIFIER_nondet_float(); int main() { int i = 7; double d = 2.1; float f = __VERIFIER_nondet_float(); { int i = 1; i = 230920; float f = d * i; } if (f == 27.0 && i == 7) __VERIFIER_error(); return 0; }
0.53125
high
rapidjson/rapidjson.h
jesrui/hn2sqlite
1
909505
<gh_stars>1-10 #ifndef RAPIDJSON_RAPIDJSON_H_ #define RAPIDJSON_RAPIDJSON_H_ // Copyright (c) 2011 <NAME> (<EMAIL>) // Version 0.1 #include <cstdlib> // malloc(), realloc(), free() #include <cstring> // memcpy() /////////////////////////////////////////////////////////////////////////////// // RAPIDJSON_NO_INT64DEFINE // Here defines int64_t and uint64_t types in global namespace. // If user have their own definition, can define RAPIDJSON_NO_INT64DEFINE to disable this. #ifndef RAPIDJSON_NO_INT64DEFINE #ifdef _MSC_VER typedef __int64 int64_t; typedef unsigned __int64 uint64_t; #define RAPIDJSON_FORCEINLINE __forceinline #else #include <inttypes.h> #define RAPIDJSON_FORCEINLINE #endif #endif // RAPIDJSON_NO_INT64TYPEDEF /////////////////////////////////////////////////////////////////////////////// // RAPIDJSON_ENDIAN #define RAPIDJSON_LITTLEENDIAN 0 //!< Little endian machine #define RAPIDJSON_BIGENDIAN 1 //!< Big endian machine //! Endianness of the machine. /*! GCC provided macro for detecting endianness of the target machine. But other compilers may not have this. User can define RAPIDJSON_ENDIAN to either RAPIDJSON_LITTLEENDIAN or RAPIDJSON_BIGENDIAN. */ #ifndef RAPIDJSON_ENDIAN #ifdef __BYTE_ORDER__ #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ #define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN #else #define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN #endif // __BYTE_ORDER__ #else #define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN // Assumes little endian otherwise. #endif #endif // RAPIDJSON_ENDIAN /////////////////////////////////////////////////////////////////////////////// // RAPIDJSON_ALIGNSIZE //! Data alignment of the machine. /*! Some machine requires strict data alignment. Currently the default uses 4 bytes alignment. User can customize this. */ #ifndef RAPIDJSON_ALIGN #define RAPIDJSON_ALIGN(x) ((x + 3) & ~3) #endif /////////////////////////////////////////////////////////////////////////////// // RAPIDJSON_SSE2/RAPIDJSON_SSE42/RAPIDJSON_SIMD // Enable SSE2 optimization. //#define RAPIDJSON_SSE2 // Enable SSE4.2 optimization. //#define RAPIDJSON_SSE42 #if defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42) #define RAPIDJSON_SIMD #endif /////////////////////////////////////////////////////////////////////////////// // RAPIDJSON_NO_SIZETYPEDEFINE #ifndef RAPIDJSON_NO_SIZETYPEDEFINE namespace rapidjson { //! Use 32-bit array/string indices even for 64-bit platform, instead of using size_t. /*! User may override the SizeType by defining RAPIDJSON_NO_SIZETYPEDEFINE. */ typedef unsigned SizeType; } // namespace rapidjson #endif /////////////////////////////////////////////////////////////////////////////// // RAPIDJSON_ASSERT //! Assertion. /*! By default, rapidjson uses C assert() for assertion. User can override it by defining RAPIDJSON_ASSERT(x) macro. */ #ifndef RAPIDJSON_ASSERT #include <cassert> #define RAPIDJSON_ASSERT(x) assert(x) #endif // RAPIDJSON_ASSERT /////////////////////////////////////////////////////////////////////////////// // RAPIDJSON_STATIC_ASSERT // Adopt from boost #ifndef RAPIDJSON_STATIC_ASSERT namespace rapidjson { template <bool x> struct STATIC_ASSERTION_FAILURE; template <> struct STATIC_ASSERTION_FAILURE<true> { enum { value = 1 }; }; template<int x> struct StaticAssertTest {}; } // namespace rapidjson #define RAPIDJSON_JOIN(X, Y) RAPIDJSON_DO_JOIN(X, Y) #define RAPIDJSON_DO_JOIN(X, Y) RAPIDJSON_DO_JOIN2(X, Y) #define RAPIDJSON_DO_JOIN2(X, Y) X##Y #define RAPIDJSON_STATIC_ASSERT(x) typedef ::rapidjson::StaticAssertTest<\ sizeof(::rapidjson::STATIC_ASSERTION_FAILURE<bool(x) >)>\ RAPIDJSON_JOIN(StaticAssertTypedef, __LINE__) #endif /////////////////////////////////////////////////////////////////////////////// // Helpers #define RAPIDJSON_MULTILINEMACRO_BEGIN do { #define RAPIDJSON_MULTILINEMACRO_END \ } while((void)0, 0) /////////////////////////////////////////////////////////////////////////////// // Allocators and Encodings #include "allocators.h" #include "encodings.h" namespace rapidjson { /////////////////////////////////////////////////////////////////////////////// // Stream /*! \class rapidjson::Stream \brief Concept for reading and writing characters. For read-only stream, no need to implement PutBegin(), Put(), Flush() and PutEnd(). For write-only stream, only need to implement Put() and Flush(). \code concept Stream { typename Ch; //!< Character type of the stream. //! Read the current character from stream without moving the read cursor. Ch Peek() const; //! Read the current character from stream and moving the read cursor to next character. Ch Take(); //! Get the current read cursor. //! \return Number of characters read from start. size_t Tell(); //! Begin writing operation at the current read pointer. //! \return The begin writer pointer. Ch* PutBegin(); //! Write a character. void Put(Ch c); //! Flush the buffer. void Flush(); //! End the writing operation. //! \param begin The begin write pointer returned by PutBegin(). //! \return Number of characters written. size_t PutEnd(Ch* begin); } \endcode */ //! Put N copies of a character to a stream. template<typename Stream, typename Ch> inline void PutN(Stream& stream, Ch c, size_t n) { for (size_t i = 0; i < n; i++) stream.Put(c); } /////////////////////////////////////////////////////////////////////////////// // StringStream //! Read-only string stream. /*! \implements Stream */ template <typename Encoding> struct GenericStringStream { typedef typename Encoding::Ch Ch; GenericStringStream(const Ch *src) : src_(src), head_(src) {} Ch Peek() const { return *src_; } Ch Take() { return *src_++; } size_t Tell() const { return src_ - head_; } Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } void Put(Ch) { RAPIDJSON_ASSERT(false); } void Flush() { RAPIDJSON_ASSERT(false); } size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } const Ch* src_; //!< Current read position. const Ch* head_; //!< Original head of the string. }; typedef GenericStringStream<UTF8<> > StringStream; /////////////////////////////////////////////////////////////////////////////// // InsituStringStream //! A read-write string stream. /*! This string stream is particularly designed for in-situ parsing. \implements Stream */ template <typename Encoding> struct GenericInsituStringStream { typedef typename Encoding::Ch Ch; GenericInsituStringStream(Ch *src) : src_(src), dst_(0), head_(src) {} // Read Ch Peek() { return *src_; } Ch Take() { return *src_++; } size_t Tell() { return src_ - head_; } // Write Ch* PutBegin() { return dst_ = src_; } void Put(Ch c) { RAPIDJSON_ASSERT(dst_ != 0); *dst_++ = c; } void Flush() {} size_t PutEnd(Ch* begin) { return dst_ - begin; } Ch* src_; Ch* dst_; Ch* head_; }; typedef GenericInsituStringStream<UTF8<> > InsituStringStream; /////////////////////////////////////////////////////////////////////////////// // Type //! Type of JSON value enum Type { kNullType = 0, //!< null kFalseType = 1, //!< false kTrueType = 2, //!< true kObjectType = 3, //!< object kArrayType = 4, //!< array kStringType = 5, //!< string kNumberType = 6 //!< number }; } // namespace rapidjson #endif // RAPIDJSON_RAPIDJSON_H_
0.996094
high
linux-4.14.90-dev/linux-4.14.90/drivers/clk/mxs/clk-ssp.c
bingchunjin/1806_SDK
55
910017
<filename>linux-4.14.90-dev/linux-4.14.90/drivers/clk/mxs/clk-ssp.c /* * Copyright 2012 DENX Software Engineering, GmbH * * Pulled from code: * Portions copyright (C) 2003 <NAME>, PXA MMCI Driver * Portions copyright (C) 2004-2005 <NAME>, W83L51xD SD/MMC driver * * Copyright 2008 Embedded Alley Solutions, Inc. * Copyright 2009-2011 Freescale Semiconductor, Inc. * * The code contained herein is licensed under the GNU General Public * License. You may obtain a copy of the GNU General Public License * Version 2 or later at the following locations: * * http://www.opensource.org/licenses/gpl-license.html * http://www.gnu.org/copyleft/gpl.html */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/clk.h> #include <linux/module.h> #include <linux/device.h> #include <linux/io.h> #include <linux/spi/mxs-spi.h> void mxs_ssp_set_clk_rate(struct mxs_ssp *ssp, unsigned int rate) { unsigned int ssp_clk, ssp_sck; u32 clock_divide, clock_rate; u32 val; ssp_clk = clk_get_rate(ssp->clk); for (clock_divide = 2; clock_divide <= 254; clock_divide += 2) { clock_rate = DIV_ROUND_UP(ssp_clk, rate * clock_divide); clock_rate = (clock_rate > 0) ? clock_rate - 1 : 0; if (clock_rate <= 255) break; } if (clock_divide > 254) { dev_err(ssp->dev, "%s: cannot set clock to %d\n", __func__, rate); return; } ssp_sck = ssp_clk / clock_divide / (1 + clock_rate); val = readl(ssp->base + HW_SSP_TIMING(ssp)); val &= ~(BM_SSP_TIMING_CLOCK_DIVIDE | BM_SSP_TIMING_CLOCK_RATE); val |= BF_SSP(clock_divide, TIMING_CLOCK_DIVIDE); val |= BF_SSP(clock_rate, TIMING_CLOCK_RATE); writel(val, ssp->base + HW_SSP_TIMING(ssp)); ssp->clk_rate = ssp_sck; dev_dbg(ssp->dev, "%s: clock_divide %d, clock_rate %d, ssp_clk %d, rate_actual %d, rate_requested %d\n", __func__, clock_divide, clock_rate, ssp_clk, ssp_sck, rate); } EXPORT_SYMBOL_GPL(mxs_ssp_set_clk_rate);
0.972656
high
src/propagators/UnfoundedBasedCheck.h
bernardocuteri/wasp
19
910529
<reponame>bernardocuteri/wasp<filename>src/propagators/UnfoundedBasedCheck.h /* * * Copyright 2013 <NAME>, <NAME>, and <NAME>. * * 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 WASP_UNFOUNDEDBASEDCHECK_H #define WASP_UNFOUNDEDBASEDCHECK_H #include <vector> #include "../util/WaspAssert.h" #include "../stl/Vector.h" #include "HCComponent.h" #include "../Literal.h" #include "../Solver.h" using namespace std; class Clause; class Learning; class Rule; class UnfoundedBasedCheck : public HCComponent { public: UnfoundedBasedCheck( vector< GUSData* >& gusData_, Solver& s, unsigned numberOfInputAtoms ); inline ~UnfoundedBasedCheck(){} virtual bool onLiteralFalse( Literal literal ); void processRule( Rule* rule ); void processComponentBeforeStarting(); private: inline void addHCVariableProtected( Var v ); vector< Var > hcVariablesNotTrueAtLevelZero; vector< Var > externalVars; unsigned int varsAtLevelZero; unsigned int numberOfAttachedVars; inline UnfoundedBasedCheck( const UnfoundedBasedCheck& orig ); void addClausesForHCAtoms(); inline void attachVar( Var v ){ numberOfAttachedVars++; attachLiterals( Literal( v, POSITIVE ) ); } void initDataStructures(); void checkModel( vector< Literal >& assumptions ); void testModel(); void computeAssumptions( vector< Literal >& assumptions ); void iterationInternalLiterals( vector< Literal >& assumptions ); void iterationExternalLiterals( vector< Literal >& assumptions ); inline bool addLiteralInClause( Literal lit, Clause* clause ); inline void addExternalVariable( Var v ); #ifdef TRACE_ON template< class T > void printVector( const vector< T >& v, const string& description ) { trace_tag( cerr, modelchecker, 2 ); cerr << description << ": "; if( !v.empty() ) { cerr << v[ 0 ]; for( unsigned int i = 1; i < v.size(); i++ ) cerr << ", " << v[ i ]; } else cerr << "empty"; cerr << endl; } void printVector( const Vector< Literal >& v, const string& description ) { trace_tag( cerr, modelchecker, 2 ); cerr << description << ": "; if( !v.empty() ) { cerr << v[ 0 ]; for( unsigned int i = 1; i < v.size(); i++ ) cerr << ", " << v[ i ]; } else cerr << "empty"; cerr << endl; } void printVector( const Vector< Var >& v, const string& description ) { trace_tag( cerr, modelchecker, 2 ); cerr << description << ": "; if( !v.empty() ) { cerr << Literal( v[ 0 ] ); for( unsigned int i = 1; i < v.size(); i++ ) cerr << ", " << Literal( v[ i ] ); } else cerr << "empty"; cerr << endl; } #endif }; void UnfoundedBasedCheck::addHCVariableProtected( Var v ) { attachVar( v ); solver.setComponent( v, NULL ); solver.setHCComponent( v, this ); checker.addVariable(); getGUSData( v ).unfoundedVarForHCC = checker.numberOfVariables(); checker.addVariable(); getGUSData( v ).headVarForHCC = checker.numberOfVariables(); trace_msg( modelchecker, 1, "Adding variable: " << Literal( v, POSITIVE ) << " with id: " << v << " - u" << Literal( v, POSITIVE ) << " with id: " << getGUSData( v ).unfoundedVarForHCC << " - h" << Literal( v, POSITIVE ) << " with id: " << getGUSData( v ).headVarForHCC ); // #ifdef TRACE_ON // VariableNames::setName( getGUSData( v ).unfoundedVarForHCC, "u" + VariableNames::getName( v ) ); // VariableNames::setName( getGUSData( v ).headVarForHCC, "h" + VariableNames::getName( v ) ); // #endif } bool UnfoundedBasedCheck::addLiteralInClause( Literal lit, Clause* clause ) { bool retVal = checker.isTrue( lit ) ? false : true; if( !checker.isUndefined( lit ) ) clause->addLiteral( lit ); return retVal; } void UnfoundedBasedCheck::addExternalVariable( Var v ) { //TODO: FIX ME with a smarter strategy! if( find( externalVars.begin(), externalVars.end(), v ) != externalVars.end() ) return; externalVars.push_back( v ); attachVar( v ); } #endif
0.992188
high
Source/ToonTanks/Components/HealthComponent.h
DavidConsidine/ToonTanks
0
911041
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/ActorComponent.h" #include "HealthComponent.generated.h" class ATankGameModeBase; UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class TOONTANKS_API UHealthComponent : public UActorComponent { GENERATED_BODY() public: // Sets default values for this component's properties UHealthComponent(); protected: // Called when the game starts virtual void BeginPlay() override; UFUNCTION() void TakeDamage(AActor* DamagedActor, float Damage, const class UDamageType* DamageType, class AController* InstigatedBy, AActor* DamageActor); private: UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Health", meta = (AllowPrivateAccess = "true")) float DefaultHealth = 100.0f; float Health = 0.0f; AActor* Owner; ATankGameModeBase* GameModeRef; };
0.5
medium
solution/problem007.c
jo0t4/project-euler
0
911553
/* * By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. * What is the 10 001st prime number? */ #include <stdio.h> #include <stdlib.h> int main() { int number, primeNumber, counter = 0; for(primeNumber = 5; ; primeNumber += 2) { here: for(number = 3; number < primeNumber; number += 2) { if(primeNumber % number == 0) { primeNumber += 2; goto here; } else if (number == primeNumber - 2) { counter += 1; if(counter == 9999) { printf("Answer: %d\n", primeNumber); goto end; } } } } end: return 0; }
0.652344
high
Graphics/Scene/IluminationItem.h
vagnerlands/GameEngine
1
912065
#ifndef _ILight_H_ #define _ILight_H_ #include "CommonTypes.h" #include "IvVector3.h" using namespace Types; namespace Graphics { enum ELightType { LightType_Omni = 0, LightType_Directional, LightType_Total }; // Everything that can be rendered shall be a "IDrawable" class IluminationItem { public: IluminationItem(const std::string id, IvVector3& location, ELightType type); // virtual destructor virtual ~IluminationItem() { } // for comparison virtual bool operator==(const IluminationItem& other) { return other.m_id == m_id; } // for comparison virtual bool operator==(const std::string& otherid) { return otherid == m_id; } virtual void SetLocation(const IvVector3& location); virtual void SetDirection(ELightType type); void IncreaseAttenuation(float increaseValue); void SetLightColor(const IvVector3& lightColor); virtual const IvVector3& GetLocation() const; virtual ELightType GetDirection() const; Float GetLightAttenuation() const; const IvVector3& GetLightColor() const; protected: IvVector3 m_location; ELightType m_type; std::string m_id; float m_lightAttenuation; IvVector3 m_lightColor; private: // copy operations IluminationItem(const IluminationItem& other) = delete; IluminationItem& operator=(const IluminationItem& other) = delete; }; inline const IvVector3& IluminationItem::GetLocation() const { return m_location; } inline ELightType IluminationItem::GetDirection() const { return m_type; } inline Float IluminationItem::GetLightAttenuation() const { return m_lightAttenuation; } inline const IvVector3& IluminationItem::GetLightColor() const { return m_lightColor; } inline void IluminationItem::IncreaseAttenuation(float increaseValue) { m_lightAttenuation += increaseValue; if (m_lightAttenuation < 0.f) { m_lightAttenuation = 0.f; } printf("[ DEBUG ] Light Attenuation value %.8f\n", m_lightAttenuation); } inline void IluminationItem::SetLightColor(const IvVector3& lightColor) { m_lightColor = lightColor; } } #endif // _ILight_H_
0.992188
high
src/main/include/commands/PAT/CmdTurnWoFCW.h
FRC-7464-ORION/FRC-7464-ORION--PublicRobotCode
2
912577
/** =========================================================================== * @file CmdTurnWoFCW.h * @brief This file declares the CmdTurnWoFCW class. * * The CmdTurnWoFCW class is used to allow the robot to turn the Wheel of * Fortune (WoF) clockwise (CW). * * COPYRIGHT NOTICES: * * Some portions: * * Copyright (c) 2017-2019 FIRST. All Rights Reserved. * Open Source Software - may be modified and shared by FRC teams. The code * must be accompanied by the FIRST BSD license file in the root directory of * the project. * * Some portions: * * Copyright (c) 2020 FRC Team #7464 - ORION. All Rights Reserved. * Open Source Software - may be modified and shared by FRC teams. The code * must be accompanied by the FRC Team #7464 - ORION BSD license file in * the root directory of the project. * ============================================================================= */ // INCLUDE GUARD - see https://en.wikipedia.org/wiki/Include_guard // If we have not already defined CMDTURNWOFCW_H... #ifndef CMDTURNWOFCW_H // Define CMDTURNWOFCW_H #define CMDTURNWOFCW_H /*************************** Local Header Files *******************************/ // Include the robot constants header file #include "RobotConstants.h" // Include the header file for the PAT Turner subsystem, which this is a // command for #include "subsystems/SubSysPATTurner.h" /************************** Library Header Files ******************************/ // Include the header file for the NEW(2020) Command base class #include <frc2/command/CommandBase.h> // Include the header file for the NEW(2020) Command helper class #include <frc2/command/CommandHelper.h> // For the joystick #include <frc/Joystick.h> /** **************************************************************************** * @class CmdTurnWoFCW * @brief This is a class that defines a command used in allowing the robot * to turn the Wheel of Fortune (WoF) clockwise (CW). * @author FRC Team #7464 - ORION ******************************************************************************/ class CmdTurnWoFCW : public frc2::CommandHelper<frc2::CommandBase, CmdTurnWoFCW> { public: /********************** PUBLIC MEMBER FUNCTIONS ***************************/ /** * The CmdTurnWoFCW class constructor. * * @param subsystem The subsystem used by this command * @param joystick The joystick used by this command */ explicit CmdTurnWoFCW(SubSysPATTurner* subsystem, frc::Joystick* joystick); /** The CmdTurnWoFCW class destructor. */ ~CmdTurnWoFCW(); /** * The initialize method is called the first time this Command is run after * being started. */ void Initialize() override; /** * The execute method is called repeatedly until this Command either * finishes or is canceled. */ void Execute() override; /** * Returns whether this command is finished. * If it is, then the command will be removed and End() will be called. * * It may be useful for a team to reference the IsTimedOut() method for * time-sensitive commands. * * Returning false will result in the command never ending automatically. * It may still be cancelled manually or interrupted by another command. * * Returning true will result in the command executing once and finishing * immediately. We recommend using InstantCommand for this. * * @return True = Command finished, False = Command not finished */ bool IsFinished() override; /** * Called when either the command finishes normally, or when it is * interrupted/canceled. * * This is where you may want to wrap up loose ends, like shutting off * a motor that was being used in the command. * * @param interrupted false = not interrupted, true = interrupted */ void End(bool interrupted) override; private: /********************* PRIVATE MEMBER FUNCTIONS ***************************/ /********************* PRIVATE MEMBER VARIABLES ***************************/ /** A pointer to a PAT Turner subsystem */ SubSysPATTurner* m_subSysPATTurner; /** A pointer to the joystick used to turn WoF CW */ frc::Joystick* m_joystick; }; // end class CmdTurnWoFCW #endif // #ifndef CMDTURNWOFCW_H
0.996094
high
java/cpp/adapters/ConfigReader.h
ekra-ltd/opendnp3
108
913089
<gh_stars>100-1000 /* * Copyright 2013-2020 Automatak, LLC * * Licensed to Green Energy Corp (www.greenenergycorp.com) and Automatak * LLC (www.automatak.com) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. Green Energy Corp and Automatak LLC license * this file to you under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may obtain * a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef OPENDNP3_CONFIG_READER_H #define OPENDNP3_CONFIG_READER_H #include <opendnp3/master/MasterStackConfig.h> #include <opendnp3/outstation/OutstationStackConfig.h> #include <jni.h> #include <string> #include "../jni/JNIWrappers.h" class ConfigReader { public: static opendnp3::MasterStackConfig Convert(JNIEnv* env, jni::JMasterStackConfig jcfg); static opendnp3::OutstationStackConfig Convert(JNIEnv* env, jni::JOutstationStackConfig jcfg); private: static opendnp3::LinkConfig Convert(JNIEnv* env, jni::JLinkLayerConfig jlinkcfg); static opendnp3::MasterParams Convert(JNIEnv* apEnv, jni::JMasterConfig jcfg); static opendnp3::ClassField Convert(JNIEnv* env, jni::JClassField jclassmask); static opendnp3::StaticTypeBitField Convert(JNIEnv* env, jni::JStaticTypeBitField jbitfield); static opendnp3::EventBufferConfig Convert(JNIEnv* env, jni::JEventBufferConfig jeventconfig); static opendnp3::OutstationParams Convert(JNIEnv* env, jni::JOutstationConfig jconfig); static opendnp3::DatabaseConfig Convert(JNIEnv* env, jni::JDatabaseConfig jdb); static opendnp3::TimeDuration Convert(JNIEnv* env, jni::JDuration jduration); static opendnp3::NumRetries Convert(JNIEnv* env, jni::JNumRetries jnumretries); static opendnp3::BinaryConfig Convert(JNIEnv* env, jni::JBinaryConfig jconfig); static opendnp3::DoubleBitBinaryConfig Convert(JNIEnv* env, jni::JDoubleBinaryConfig jconfig); static opendnp3::AnalogConfig Convert(JNIEnv* env, jni::JAnalogConfig jconfig); static opendnp3::CounterConfig Convert(JNIEnv* env, jni::JCounterConfig jconfig); static opendnp3::FrozenCounterConfig Convert(JNIEnv* env, jni::JFrozenCounterConfig jconfig); static opendnp3::BOStatusConfig Convert(JNIEnv* env, jni::JBinaryOutputStatusConfig jconfig); static opendnp3::AOStatusConfig Convert(JNIEnv* env, jni::JAnalogOutputStatusConfig jconfig); }; #endif
0.992188
high
src/LMS7002M_filter_cal.c
LUMERIIX/LMS7002M-driver
31
913601
/// /// \file LMS7002M_filter_cal.c /// /// Common filter calibration functions for the LMS7002M C driver. /// /// \copyright /// Copyright (c) 2016-2016 Fairwaves, Inc. /// Copyright (c) 2016-2016 Rice University /// SPDX-License-Identifier: Apache-2.0 /// http://www.apache.org/licenses/LICENSE-2.0 /// #include "LMS7002M_impl.h" #include "LMS7002M_filter_cal.h" #include <LMS7002M/LMS7002M_time.h> static long long cal_rssi_sleep_ticks(void) { return (LMS7_time_tps())/1000; //1 ms -> ticks } uint16_t cal_read_rssi(LMS7002M_t *self, const LMS7002M_chan_t channel) { LMS7_sleep_for(cal_rssi_sleep_ticks()); return LMS7002M_rxtsp_read_rssi(self, channel); } void set_addrs_to_default(LMS7002M_t *self, const LMS7002M_chan_t channel, const int start_addr, const int stop_addr) { LMS7002M_set_mac_ch(self, channel); for (int addr = start_addr; addr <= stop_addr; addr++) { int value = LMS7002M_regs_default(addr); if (value == -1) continue; //not in map LMS7002M_regs_set(LMS7002M_regs(self), addr, value); LMS7002M_regs_spi_write(self, addr); } } int cal_gain_selection(LMS7002M_t *self, const LMS7002M_chan_t channel) { while (true) { const int rssi_value_50k = cal_read_rssi(self, channel); if (rssi_value_50k < 0x8400) break; LMS7002M_regs(self)->reg_0x0108_cg_iamp_tbb++; if (LMS7002M_regs(self)->reg_0x0108_cg_iamp_tbb > 63) { if (LMS7002M_regs(self)->reg_0x0119_g_pga_rbb > 31) break; LMS7002M_regs(self)->reg_0x0108_cg_iamp_tbb = 1; LMS7002M_regs(self)->reg_0x0119_g_pga_rbb += 6; } LMS7002M_regs_spi_write(self, 0x0108); LMS7002M_regs_spi_write(self, 0x0119); } return cal_read_rssi(self, channel); } int cal_setup_cgen(LMS7002M_t *self, const double bw) { double cgen_freq = bw*20; if (cgen_freq < 60e6) cgen_freq = 60e6; if (cgen_freq > 640e6) cgen_freq = 640e6; while ((int)(cgen_freq/1e6) == (int)(bw/16e6)) cgen_freq -= 10e6; return LMS7002M_set_data_clock(self, self->cgen_fref, cgen_freq, NULL); }
0.984375
high
general/pcidrv/kmdf/HW/precomp.h
ixjf/Windows-driver-samples
3,084
914113
// // precomp.h for pcidrv driver // #define WIN9X_COMPAT_SPINLOCK #include <ntddk.h> #include <wdf.h> typedef unsigned int UINT; typedef unsigned int *PUINT; #include <initguid.h> // required for GUID definitions #include <wdmguid.h> // required for WMILIB_CONTEXT #include <wmistr.h> #include <wmilib.h> #include <ntintsafe.h> // // Disable warnings that prevent our driver from compiling with /W4 MSC_WARNING_LEVEL // // Disable warning C4214: nonstandard extension used : bit field types other than int // Disable warning C4201: nonstandard extension used : nameless struct/union // Disable warning C4115: named type definition in parentheses // #pragma warning(disable:4214) #pragma warning(disable:4201) #pragma warning(disable:4115) #include "ntddndis.h" // for OIDs #pragma warning(default:4214) #pragma warning(default:4201) #pragma warning(default:4115) #include "nuiouser.h" // for ioctls recevied from ndisedge #include "public.h" #include "e100_equ.h" #include "e100_557.h" #include "trace.h" #include "nic_def.h" #include "pcidrv.h" #include "macros.h"
0.808594
high
G39_Lab2 - Stacks, Subroutines, and C/address_map_arm.h
ismailfaruk/ECSE324--Computer-Organization
3
914625
<filename>G39_Lab2 - Stacks, Subroutines, and C/address_map_arm.h /* This files provides address values that exist in the system */ #define BOARD "DE1-SoC" /* Memory */ #define DDR_BASE 0x00000000 #define DDR_END 0x3FFFFFFF #define A9_ONCHIP_BASE 0xFFFF0000 #define A9_ONCHIP_END 0xFFFFFFFF #define SDRAM_BASE 0xC0000000 #define SDRAM_END 0xC3FFFFFF #define FPGA_ONCHIP_BASE 0xC8000000 #define FPGA_ONCHIP_END 0xC803FFFF #define FPGA_CHAR_BASE 0xC9000000 #define FPGA_CHAR_END 0xC9001FFF /* Cyclone V FPGA devices */ #define LEDR_BASE 0xFF200000 #define HEX3_HEX0_BASE 0xFF200020 #define HEX5_HEX4_BASE 0xFF200030 #define SW_BASE 0xFF200040 #define KEY_BASE 0xFF200050 #define JP1_BASE 0xFF200060 #define JP2_BASE 0xFF200070 #define PS2_BASE 0xFF200100 #define PS2_DUAL_BASE 0xFF200108 #define JTAG_UART_BASE 0xFF201000 #define JTAG_UART_2_BASE 0xFF201008 #define IrDA_BASE 0xFF201020 #define TIMER_BASE 0xFF202000 #define TIMER_2_BASE 0xFF202020 #define AV_CONFIG_BASE 0xFF203000 #define PIXEL_BUF_CTRL_BASE 0xFF203020 #define CHAR_BUF_CTRL_BASE 0xFF203030 #define AUDIO_BASE 0xFF203040 #define VIDEO_IN_BASE 0xFF203060 #define ADC_BASE 0xFF204000 /* Cyclone V HPS devices */ #define HPS_GPIO1_BASE 0xFF709000 #define I2C0_BASE 0xFFC04000 #define I2C1_BASE 0xFFC05000 #define I2C2_BASE 0xFFC06000 #define I2C3_BASE 0xFFC07000 #define HPS_TIMER0_BASE 0xFFC08000 #define HPS_TIMER1_BASE 0xFFC09000 #define HPS_TIMER2_BASE 0xFFD00000 #define HPS_TIMER3_BASE 0xFFD01000 #define FPGA_BRIDGE 0xFFD0501C /* ARM A9 MPCORE devices */ #define PERIPH_BASE 0xFFFEC000 // base address of peripheral devices #define MPCORE_PRIV_TIMER 0xFFFEC600 // PERIPH_BASE + 0x0600 /* Interrupt controller (GIC) CPU interface(s) */ #define MPCORE_GIC_CPUIF 0xFFFEC100 // PERIPH_BASE + 0x100 #define ICCICR 0x00 // offset to CPU interface control reg #define ICCPMR 0x04 // offset to interrupt priority mask reg #define ICCIAR 0x0C // offset to interrupt acknowledge reg #define ICCEOIR 0x10 // offset to end of interrupt reg /* Interrupt controller (GIC) distributor interface(s) */ #define MPCORE_GIC_DIST 0xFFFED000 // PERIPH_BASE + 0x1000 #define ICDDCR 0x00 // offset to distributor control reg #define ICDISER 0x100 // offset to interrupt set-enable regs #define ICDICER 0x180 // offset to interrupt clear-enable regs #define ICDIPTR 0x800 // offset to interrupt processor targets regs #define ICDICFR 0xC00 // offset to interrupt configuration regs
0.988281
high
aoj/Volume00/0052/solve.c
tobyapi/online-judge-solutions
0
915137
<reponame>tobyapi/online-judge-solutions<gh_stars>0 #include<stdio.h> int main(void){ int n,ans; while(ans=0,scanf("%d",&n),n){ while(n/=5)ans+=n; printf("%d\n",ans); } return 0; }
0.6875
low
scip/src/scip/set.h
avrech/scipoptsuite-6.0.2-avrech
0
915649
<filename>scip/src/scip/set.h /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* SCIP --- Solving Constraint Integer Programs */ /* */ /* Copyright (C) 2002-2019 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* SCIP is distributed under the terms of the ZIB Academic License. */ /* */ /* You should have received a copy of the ZIB Academic License */ /* along with SCIP; see the file COPYING. If not visit scip.zib.de. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /**@file set.h * @ingroup INTERNALAPI * @brief internal methods for global SCIP settings * @author <NAME> * @author <NAME> */ /*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/ #ifndef __SCIP_SET_H__ #define __SCIP_SET_H__ #include "scip/def.h" #include "blockmemshell/memory.h" #include "scip/type_bandit.h" #include "scip/type_set.h" #include "scip/type_stat.h" #include "scip/type_clock.h" #include "scip/type_paramset.h" #include "scip/type_event.h" #include "scip/type_scip.h" #include "scip/type_branch.h" #include "scip/type_conflict.h" #include "scip/type_cons.h" #include "scip/type_disp.h" #include "scip/type_heur.h" #include "scip/type_compr.h" #include "scip/type_nodesel.h" #include "scip/type_presol.h" #include "scip/type_pricer.h" #include "scip/type_reader.h" #include "scip/type_relax.h" #include "scip/type_sepa.h" #include "scip/type_table.h" #include "scip/type_prop.h" #include "scip/type_benders.h" #include "scip/struct_set.h" #ifdef NDEBUG #include "scip/pub_misc.h" #endif #ifdef __cplusplus extern "C" { #endif /** copies plugins from sourcescip to targetscip; in case that a constraint handler which does not need constraints * cannot be copied, valid will return FALSE. All plugins can declare that, if their copy process failed, the * copied SCIP instance might not represent the same problem semantics as the original. * Note that in this case dual reductions might be invalid. */ SCIP_RETCODE SCIPsetCopyPlugins( SCIP_SET* sourceset, /**< source SCIP_SET data structure */ SCIP_SET* targetset, /**< target SCIP_SET data structure */ SCIP_Bool copyreaders, /**< should the file readers be copied */ SCIP_Bool copypricers, /**< should the variable pricers be copied */ SCIP_Bool copyconshdlrs, /**< should the constraint handlers be copied */ SCIP_Bool copyconflicthdlrs, /**< should the conflict handlers be copied */ SCIP_Bool copypresolvers, /**< should the presolvers be copied */ SCIP_Bool copyrelaxators, /**< should the relaxators be copied */ SCIP_Bool copyseparators, /**< should the separators be copied */ SCIP_Bool copypropagators, /**< should the propagators be copied */ SCIP_Bool copyheuristics, /**< should the heuristics be copied */ SCIP_Bool copyeventhdlrs, /**< should the event handlers be copied */ SCIP_Bool copynodeselectors, /**< should the node selectors be copied */ SCIP_Bool copybranchrules, /**< should the branchrules be copied */ SCIP_Bool copydisplays, /**< should the display columns be copied */ SCIP_Bool copydialogs, /**< should the dialogs be copied */ SCIP_Bool copytables, /**< should the statistics tables be copied */ SCIP_Bool copynlpis, /**< should the NLP interfaces be copied */ SCIP_Bool* allvalid /**< pointer to store whether all plugins were validly copied */ ); /** copies parameters from sourcescip to targetscip */ SCIP_RETCODE SCIPsetCopyParams( SCIP_SET* sourceset, /**< source SCIP_SET data structure */ SCIP_SET* targetset, /**< target SCIP_SET data structure */ SCIP_MESSAGEHDLR* messagehdlr /**< message handler of target SCIP */ ); /** creates global SCIP settings */ SCIP_RETCODE SCIPsetCreate( SCIP_SET** set, /**< pointer to SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ BMS_BLKMEM* blkmem, /**< block memory */ SCIP* scip /**< SCIP data structure */ ); /** frees global SCIP settings */ SCIP_RETCODE SCIPsetFree( SCIP_SET** set, /**< pointer to SCIP settings */ BMS_BLKMEM* blkmem /**< block memory */ ); /** returns current stage of SCIP */ SCIP_STAGE SCIPsetGetStage( SCIP_SET* set /**< pointer to SCIP settings */ ); /** creates a SCIP_Bool parameter, sets it to its default value, and adds it to the parameter set */ SCIP_RETCODE SCIPsetAddBoolParam( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ BMS_BLKMEM* blkmem, /**< block memory */ const char* name, /**< name of the parameter */ const char* desc, /**< description of the parameter */ SCIP_Bool* valueptr, /**< pointer to store the current parameter value, or NULL */ SCIP_Bool isadvanced, /**< is this parameter an advanced parameter? */ SCIP_Bool defaultvalue, /**< default value of the parameter */ SCIP_DECL_PARAMCHGD ((*paramchgd)), /**< change information method of parameter */ SCIP_PARAMDATA* paramdata /**< locally defined parameter specific data */ ); /** creates a int parameter, sets it to its default value, and adds it to the parameter set */ SCIP_RETCODE SCIPsetAddIntParam( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ BMS_BLKMEM* blkmem, /**< block memory */ const char* name, /**< name of the parameter */ const char* desc, /**< description of the parameter */ int* valueptr, /**< pointer to store the current parameter value, or NULL */ SCIP_Bool isadvanced, /**< is this parameter an advanced parameter? */ int defaultvalue, /**< default value of the parameter */ int minvalue, /**< minimum value for parameter */ int maxvalue, /**< maximum value for parameter */ SCIP_DECL_PARAMCHGD ((*paramchgd)), /**< change information method of parameter */ SCIP_PARAMDATA* paramdata /**< locally defined parameter specific data */ ); /** creates a SCIP_Longint parameter, sets it to its default value, and adds it to the parameter set */ SCIP_RETCODE SCIPsetAddLongintParam( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ BMS_BLKMEM* blkmem, /**< block memory */ const char* name, /**< name of the parameter */ const char* desc, /**< description of the parameter */ SCIP_Longint* valueptr, /**< pointer to store the current parameter value, or NULL */ SCIP_Bool isadvanced, /**< is this parameter an advanced parameter? */ SCIP_Longint defaultvalue, /**< default value of the parameter */ SCIP_Longint minvalue, /**< minimum value for parameter */ SCIP_Longint maxvalue, /**< maximum value for parameter */ SCIP_DECL_PARAMCHGD ((*paramchgd)), /**< change information method of parameter */ SCIP_PARAMDATA* paramdata /**< locally defined parameter specific data */ ); /** creates a SCIP_Real parameter, sets it to its default value, and adds it to the parameter set */ SCIP_RETCODE SCIPsetAddRealParam( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ BMS_BLKMEM* blkmem, /**< block memory */ const char* name, /**< name of the parameter */ const char* desc, /**< description of the parameter */ SCIP_Real* valueptr, /**< pointer to store the current parameter value, or NULL */ SCIP_Bool isadvanced, /**< is this parameter an advanced parameter? */ SCIP_Real defaultvalue, /**< default value of the parameter */ SCIP_Real minvalue, /**< minimum value for parameter */ SCIP_Real maxvalue, /**< maximum value for parameter */ SCIP_DECL_PARAMCHGD ((*paramchgd)), /**< change information method of parameter */ SCIP_PARAMDATA* paramdata /**< locally defined parameter specific data */ ); /** creates a char parameter, sets it to its default value, and adds it to the parameter set */ SCIP_RETCODE SCIPsetAddCharParam( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ BMS_BLKMEM* blkmem, /**< block memory */ const char* name, /**< name of the parameter */ const char* desc, /**< description of the parameter */ char* valueptr, /**< pointer to store the current parameter value, or NULL */ SCIP_Bool isadvanced, /**< is this parameter an advanced parameter? */ char defaultvalue, /**< default value of the parameter */ const char* allowedvalues, /**< array with possible parameter values, or NULL if not restricted */ SCIP_DECL_PARAMCHGD ((*paramchgd)), /**< change information method of parameter */ SCIP_PARAMDATA* paramdata /**< locally defined parameter specific data */ ); /** creates a string parameter, sets it to its default value, and adds it to the parameter set */ SCIP_RETCODE SCIPsetAddStringParam( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ BMS_BLKMEM* blkmem, /**< block memory */ const char* name, /**< name of the parameter */ const char* desc, /**< description of the parameter */ char** valueptr, /**< pointer to store the current parameter value, or NULL */ SCIP_Bool isadvanced, /**< is this parameter an advanced parameter? */ const char* defaultvalue, /**< default value of the parameter */ SCIP_DECL_PARAMCHGD ((*paramchgd)), /**< change information method of parameter */ SCIP_PARAMDATA* paramdata /**< locally defined parameter specific data */ ); /** gets the fixing status value of an existing parameter */ SCIP_Bool SCIPsetIsParamFixed( SCIP_SET* set, /**< global SCIP settings */ const char* name /**< name of the parameter */ ); /** returns the pointer to the SCIP parameter with the given name */ SCIP_PARAM* SCIPsetGetParam( SCIP_SET* set, /**< global SCIP settings */ const char* name /**< name of the parameter */ ); /** gets the value of an existing SCIP_Bool parameter */ SCIP_RETCODE SCIPsetGetBoolParam( SCIP_SET* set, /**< global SCIP settings */ const char* name, /**< name of the parameter */ SCIP_Bool* value /**< pointer to store the parameter */ ); /** gets the value of an existing Int parameter */ SCIP_RETCODE SCIPsetGetIntParam( SCIP_SET* set, /**< global SCIP settings */ const char* name, /**< name of the parameter */ int* value /**< pointer to store the parameter */ ); /** gets the value of an existing SCIP_Longint parameter */ SCIP_RETCODE SCIPsetGetLongintParam( SCIP_SET* set, /**< global SCIP settings */ const char* name, /**< name of the parameter */ SCIP_Longint* value /**< pointer to store the parameter */ ); /** gets the value of an existing SCIP_Real parameter */ SCIP_RETCODE SCIPsetGetRealParam( SCIP_SET* set, /**< global SCIP settings */ const char* name, /**< name of the parameter */ SCIP_Real* value /**< pointer to store the parameter */ ); /** gets the value of an existing Char parameter */ SCIP_RETCODE SCIPsetGetCharParam( SCIP_SET* set, /**< global SCIP settings */ const char* name, /**< name of the parameter */ char* value /**< pointer to store the parameter */ ); /** gets the value of an existing String parameter */ SCIP_RETCODE SCIPsetGetStringParam( SCIP_SET* set, /**< global SCIP settings */ const char* name, /**< name of the parameter */ char** value /**< pointer to store the parameter */ ); /** changes the fixing status of an existing parameter */ SCIP_RETCODE SCIPsetChgParamFixed( SCIP_SET* set, /**< global SCIP settings */ const char* name, /**< name of the parameter */ SCIP_Bool fixed /**< new fixing status of the parameter */ ); /** changes the value of an existing parameter */ SCIP_RETCODE SCIPsetSetParam( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ const char* name, /**< name of the parameter */ void* value /**< new value of the parameter */ ); /** changes the value of an existing SCIP_Bool parameter */ SCIP_RETCODE SCIPsetChgBoolParam( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ SCIP_PARAM* param, /**< parameter */ SCIP_Bool value /**< new value of the parameter */ ); /** changes the value of an existing SCIP_Bool parameter */ SCIP_RETCODE SCIPsetSetBoolParam( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ const char* name, /**< name of the parameter */ SCIP_Bool value /**< new value of the parameter */ ); /** changes the default value of an existing SCIP_Bool parameter */ SCIP_RETCODE SCIPsetSetDefaultBoolParam( SCIP_SET* set, /**< global SCIP settings */ const char* name, /**< name of the parameter */ SCIP_Bool defaultvalue /**< new default value of the parameter */ ); /** changes the value of an existing Int parameter */ SCIP_RETCODE SCIPsetChgIntParam( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ SCIP_PARAM* param, /**< parameter */ int value /**< new value of the parameter */ ); /** changes the value of an existing Int parameter */ SCIP_RETCODE SCIPsetSetIntParam( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ const char* name, /**< name of the parameter */ int value /**< new value of the parameter */ ); /** changes the default value of an existing Int parameter */ SCIP_RETCODE SCIPsetSetDefaultIntParam( SCIP_SET* set, /**< global SCIP settings */ const char* name, /**< name of the parameter */ int defaultvalue /**< new default value of the parameter */ ); /** changes the value of an existing SCIP_Longint parameter */ SCIP_RETCODE SCIPsetChgLongintParam( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ SCIP_PARAM* param, /**< parameter */ SCIP_Longint value /**< new value of the parameter */ ); /** changes the value of an existing SCIP_Longint parameter */ SCIP_RETCODE SCIPsetSetLongintParam( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ const char* name, /**< name of the parameter */ SCIP_Longint value /**< new value of the parameter */ ); /** changes the value of an existing SCIP_Real parameter */ SCIP_RETCODE SCIPsetChgRealParam( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ SCIP_PARAM* param, /**< parameter */ SCIP_Real value /**< new value of the parameter */ ); /** changes the value of an existing SCIP_Real parameter */ SCIP_RETCODE SCIPsetSetRealParam( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ const char* name, /**< name of the parameter */ SCIP_Real value /**< new value of the parameter */ ); /** changes the value of an existing Char parameter */ SCIP_RETCODE SCIPsetChgCharParam( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ SCIP_PARAM* param, /**< parameter */ char value /**< new value of the parameter */ ); /** changes the value of an existing Char parameter */ SCIP_RETCODE SCIPsetSetCharParam( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ const char* name, /**< name of the parameter */ char value /**< new value of the parameter */ ); /** changes the value of an existing String parameter */ SCIP_RETCODE SCIPsetChgStringParam( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ SCIP_PARAM* param, /**< parameter */ const char* value /**< new value of the parameter */ ); /** changes the value of an existing String parameter */ SCIP_RETCODE SCIPsetSetStringParam( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ const char* name, /**< name of the parameter */ const char* value /**< new value of the parameter */ ); /** reads parameters from a file */ SCIP_RETCODE SCIPsetReadParams( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ const char* filename /**< file name */ ); /** writes all parameters in the parameter set to a file */ SCIP_RETCODE SCIPsetWriteParams( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ const char* filename, /**< file name, or NULL for stdout */ SCIP_Bool comments, /**< should parameter descriptions be written as comments? */ SCIP_Bool onlychanged /**< should only the parameters been written, that are changed from default? */ ); /** resets a single parameters to its default value */ SCIP_RETCODE SCIPsetResetParam( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ const char* name /**< name of the parameter */ ); /** resets all parameters to their default values */ SCIP_RETCODE SCIPsetResetParams( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr /**< message handler */ ); /** sets parameters to * * - \ref SCIP_PARAMEMPHASIS_DEFAULT to use default values (see also SCIPsetResetParams()) * - \ref SCIP_PARAMEMPHASIS_COUNTER to get feasible and "fast" counting process * - \ref SCIP_PARAMEMPHASIS_CPSOLVER to get CP like search (e.g. no LP relaxation) * - \ref SCIP_PARAMEMPHASIS_EASYCIP to solve easy problems fast * - \ref SCIP_PARAMEMPHASIS_FEASIBILITY to detect feasibility fast * - \ref SCIP_PARAMEMPHASIS_HARDLP to be capable to handle hard LPs * - \ref SCIP_PARAMEMPHASIS_OPTIMALITY to prove optimality fast * - \ref SCIP_PARAMEMPHASIS_PHASEFEAS to find feasible solutions during a 3 phase solution process * - \ref SCIP_PARAMEMPHASIS_PHASEIMPROVE to find improved solutions during a 3 phase solution process * - \ref SCIP_PARAMEMPHASIS_PHASEPROOF to proof optimality during a 3 phase solution process */ SCIP_RETCODE SCIPsetSetEmphasis( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ SCIP_PARAMEMPHASIS paramemphasis, /**< parameter settings */ SCIP_Bool quiet /**< should the parameter be set quiet (no output) */ ); /** set parameters for reoptimization */ SCIP_RETCODE SCIPsetSetReoptimizationParams( SCIP_SET* set, /**< SCIP data structure */ SCIP_MESSAGEHDLR* messagehdlr /**< message handler */ ); /** enable or disable all plugin timers depending on the value of the flag \p enabled */ void SCIPsetEnableOrDisablePluginClocks( SCIP_SET* set, /**< SCIP settings */ SCIP_Bool enabled /**< should plugin clocks be enabled? */ ); /** sets parameters to deactivate separators and heuristics that use auxiliary SCIP instances; should be called for * auxiliary SCIP instances to avoid recursion */ SCIP_RETCODE SCIPsetSetSubscipsOff( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ SCIP_Bool quiet /**< should the parameter be set quiet (no output) */ ); /** sets heuristic parameters values to * - SCIP_PARAMSETTING_DEFAULT which are the default values of all heuristic parameters * - SCIP_PARAMSETTING_FAST such that the time spend for heuristic is decreased * - SCIP_PARAMSETTING_AGGRESSIVE such that the heuristic are called more aggregative * - SCIP_PARAMSETTING_OFF which turn off all heuristics */ SCIP_RETCODE SCIPsetSetHeuristics( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ SCIP_PARAMSETTING paramsetting, /**< parameter settings */ SCIP_Bool quiet /**< should the parameter be set quiet (no output) */ ); /** sets presolving parameters to * - SCIP_PARAMSETTING_DEFAULT which are the default values of all presolving parameters * - SCIP_PARAMSETTING_FAST such that the time spend for presolving is decreased * - SCIP_PARAMSETTING_AGGRESSIVE such that the presolving is more aggregative * - SCIP_PARAMSETTING_OFF which turn off all presolving */ SCIP_RETCODE SCIPsetSetPresolving( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ SCIP_PARAMSETTING paramsetting, /**< parameter settings */ SCIP_Bool quiet /**< should the parameter be set quiet (no output) */ ); /** sets separating parameters to * - SCIP_PARAMSETTING_DEFAULT which are the default values of all separating parameters * - SCIP_PARAMSETTING_FAST such that the time spend for separating is decreased * - SCIP_PARAMSETTING_AGGRESSIVE such that the separating is done more aggregative * - SCIP_PARAMSETTING_OFF which turn off all separating */ SCIP_RETCODE SCIPsetSetSeparating( SCIP_SET* set, /**< global SCIP settings */ SCIP_MESSAGEHDLR* messagehdlr, /**< message handler */ SCIP_PARAMSETTING paramsetting, /**< parameter settings */ SCIP_Bool quiet /**< should the parameter be set quiet (no output) */ ); /** returns the array of all available SCIP parameters */ SCIP_PARAM** SCIPsetGetParams( SCIP_SET* set /**< global SCIP settings */ ); /** returns the total number of all available SCIP parameters */ int SCIPsetGetNParams( SCIP_SET* set /**< global SCIP settings */ ); /** inserts file reader in file reader list */ SCIP_RETCODE SCIPsetIncludeReader( SCIP_SET* set, /**< global SCIP settings */ SCIP_READER* reader /**< file reader */ ); /** returns the file reader of the given name, or NULL if not existing */ SCIP_READER* SCIPsetFindReader( SCIP_SET* set, /**< global SCIP settings */ const char* name /**< name of file reader */ ); /** inserts variable pricer in variable pricer list */ SCIP_RETCODE SCIPsetIncludePricer( SCIP_SET* set, /**< global SCIP settings */ SCIP_PRICER* pricer /**< variable pricer */ ); /** returns the variable pricer of the given name, or NULL if not existing */ SCIP_PRICER* SCIPsetFindPricer( SCIP_SET* set, /**< global SCIP settings */ const char* name /**< name of variable pricer */ ); /** sorts pricers by priorities */ void SCIPsetSortPricers( SCIP_SET* set /**< global SCIP settings */ ); /** sorts pricers by name */ void SCIPsetSortPricersName( SCIP_SET* set /**< global SCIP settings */ ); /** inserts Benders' decomposition into the Benders' decomposition list */ SCIP_RETCODE SCIPsetIncludeBenders( SCIP_SET* set, /**< global SCIP settings */ SCIP_BENDERS* benders /**< Benders' decomposition */ ); /** returns the Benders' decomposition of the given name, or NULL if not existing */ SCIP_BENDERS* SCIPsetFindBenders( SCIP_SET* set, /**< global SCIP settings */ const char* name /**< name of Benders' decomposition */ ); /** sorts Benders' decomposition by priorities */ void SCIPsetSortBenders( SCIP_SET* set /**< global SCIP settings */ ); /** sorts Benders' decomposition by name */ void SCIPsetSortBendersName( SCIP_SET* set /**< global SCIP settings */ ); /** inserts constraint handler in constraint handler list */ SCIP_RETCODE SCIPsetIncludeConshdlr( SCIP_SET* set, /**< global SCIP settings */ SCIP_CONSHDLR* conshdlr /**< constraint handler */ ); /** reinserts a constraint handler with modified sepa priority into the sepa priority sorted array */ void SCIPsetReinsertConshdlrSepaPrio( SCIP_SET* set, /**< global SCIP settings */ SCIP_CONSHDLR* conshdlr, /**< constraint handler to be reinserted */ int oldpriority /**< the old separation priority of constraint handler */ ); /** returns the constraint handler of the given name, or NULL if not existing */ SCIP_CONSHDLR* SCIPsetFindConshdlr( SCIP_SET* set, /**< global SCIP settings */ const char* name /**< name of constraint handler */ ); /** inserts conflict handler in conflict handler list */ SCIP_RETCODE SCIPsetIncludeConflicthdlr( SCIP_SET* set, /**< global SCIP settings */ SCIP_CONFLICTHDLR* conflicthdlr /**< conflict handler */ ); /** returns the conflict handler of the given name, or NULL if not existing */ SCIP_CONFLICTHDLR* SCIPsetFindConflicthdlr( SCIP_SET* set, /**< global SCIP settings */ const char* name /**< name of conflict handler */ ); /** sorts conflict handlers by priorities */ void SCIPsetSortConflicthdlrs( SCIP_SET* set /**< global SCIP settings */ ); /** sorts conflict handlers by name */ void SCIPsetSortConflicthdlrsName( SCIP_SET* set /**< global SCIP settings */ ); /** inserts presolver in presolver list */ SCIP_RETCODE SCIPsetIncludePresol( SCIP_SET* set, /**< global SCIP settings */ SCIP_PRESOL* presol /**< presolver */ ); /** returns the presolver of the given name, or NULL if not existing */ SCIP_PRESOL* SCIPsetFindPresol( SCIP_SET* set, /**< global SCIP settings */ const char* name /**< name of presolver */ ); /** sorts presolvers by priorities */ void SCIPsetSortPresols( SCIP_SET* set /**< global SCIP settings */ ); /** sorts presolvers by name */ void SCIPsetSortPresolsName( SCIP_SET* set /**< global SCIP settings */ ); /** inserts relaxator in relaxator list */ SCIP_RETCODE SCIPsetIncludeRelax( SCIP_SET* set, /**< global SCIP settings */ SCIP_RELAX* relax /**< relaxator */ ); /** returns the relaxator of the given name, or NULL if not existing */ SCIP_RELAX* SCIPsetFindRelax( SCIP_SET* set, /**< global SCIP settings */ const char* name /**< name of relaxator */ ); /** sorts relaxators by priorities */ void SCIPsetSortRelaxs( SCIP_SET* set /**< global SCIP settings */ ); /** sorts relaxators by name */ void SCIPsetSortRelaxsName( SCIP_SET* set /**< global SCIP settings */ ); /** inserts separator in separator list */ SCIP_RETCODE SCIPsetIncludeSepa( SCIP_SET* set, /**< global SCIP settings */ SCIP_SEPA* sepa /**< separator */ ); /** returns the separator of the given name, or NULL if not existing */ SCIP_SEPA* SCIPsetFindSepa( SCIP_SET* set, /**< global SCIP settings */ const char* name /**< name of separator */ ); /** sorts separators by priorities */ void SCIPsetSortSepas( SCIP_SET* set /**< global SCIP settings */ ); /** sorts separators by name */ void SCIPsetSortSepasName( SCIP_SET* set /**< global SCIP settings */ ); /** inserts propagator in propagator list */ SCIP_RETCODE SCIPsetIncludeProp( SCIP_SET* set, /**< global SCIP settings */ SCIP_PROP* prop /**< propagator */ ); /** returns the propagator of the given name, or NULL if not existing */ SCIP_PROP* SCIPsetFindProp( SCIP_SET* set, /**< global SCIP settings */ const char* name /**< name of propagator */ ); /** sorts propagators by priorities */ void SCIPsetSortProps( SCIP_SET* set /**< global SCIP settings */ ); /** sorts propagators by priorities for presolving */ void SCIPsetSortPropsPresol( SCIP_SET* set /**< global SCIP settings */ ); /** sorts propagators w.r.t. names */ void SCIPsetSortPropsName( SCIP_SET* set /**< global SCIP settings */ ); /** inserts concurrent solver type into the concurrent solver type list */ SCIP_RETCODE SCIPsetIncludeConcsolverType( SCIP_SET* set, /**< global SCIP settings */ SCIP_CONCSOLVERTYPE* concsolvertype /**< concurrent solver type */ ); /** returns the concurrent solver type with the given name, or NULL if not existing */ SCIP_CONCSOLVERTYPE* SCIPsetFindConcsolverType( SCIP_SET* set, /**< global SCIP settings */ const char* name /**< name of concurrent solver type */ ); /** inserts concurrent solver into the concurrent solver list */ SCIP_RETCODE SCIPsetIncludeConcsolver( SCIP_SET* set, /**< global SCIP settings */ SCIP_CONCSOLVER* concsolver /**< concurrent solver */ ); /** frees all concurrent solvers in the concurrent solver list */ SCIP_RETCODE SCIPsetFreeConcsolvers( SCIP_SET* set /**< global SCIP settings */ ); /** inserts primal heuristic in primal heuristic list */ SCIP_RETCODE SCIPsetIncludeHeur( SCIP_SET* set, /**< global SCIP settings */ SCIP_HEUR* heur /**< primal heuristic */ ); /** returns the primal heuristic of the given name, or NULL if not existing */ SCIP_HEUR* SCIPsetFindHeur( SCIP_SET* set, /**< global SCIP settings */ const char* name /**< name of primal heuristic */ ); /** sorts heuristics by priorities */ void SCIPsetSortHeurs( SCIP_SET* set /**< global SCIP settings */ ); /** sorts heuristics by name */ void SCIPsetSortHeursName( SCIP_SET* set /**< global SCIP settings */ ); /** inserts tree compression in tree compression list */ SCIP_RETCODE SCIPsetIncludeCompr( SCIP_SET* set, /**< global SCIP settings */ SCIP_COMPR* compr /**< tree compression */ ); /** returns the tree compression of the given name, or NULL if not existing */ SCIP_COMPR* SCIPsetFindCompr( SCIP_SET* set, /**< global SCIP settings */ const char* name /**< name of tree compression */ ); /** sorts compressions by priorities */ void SCIPsetSortComprs( SCIP_SET* set /**< global SCIP settings */ ); /** sorts heuristics by names */ void SCIPsetSortComprsName( SCIP_SET* set /**< global SCIP settings */ ); /** inserts event handler in event handler list */ SCIP_RETCODE SCIPsetIncludeEventhdlr( SCIP_SET* set, /**< global SCIP settings */ SCIP_EVENTHDLR* eventhdlr /**< event handler */ ); /** returns the event handler of the given name, or NULL if not existing */ SCIP_EVENTHDLR* SCIPsetFindEventhdlr( SCIP_SET* set, /**< global SCIP settings */ const char* name /**< name of event handler */ ); /** inserts node selector in node selector list */ SCIP_RETCODE SCIPsetIncludeNodesel( SCIP_SET* set, /**< global SCIP settings */ SCIP_NODESEL* nodesel /**< node selector */ ); /** returns the node selector of the given name, or NULL if not existing */ SCIP_NODESEL* SCIPsetFindNodesel( SCIP_SET* set, /**< global SCIP settings */ const char* name /**< name of event handler */ ); /** returns node selector with highest priority in the current mode */ SCIP_NODESEL* SCIPsetGetNodesel( SCIP_SET* set, /**< global SCIP settings */ SCIP_STAT* stat /**< dynamic problem statistics */ ); /** inserts branching rule in branching rule list */ SCIP_RETCODE SCIPsetIncludeBranchrule( SCIP_SET* set, /**< global SCIP settings */ SCIP_BRANCHRULE* branchrule /**< branching rule */ ); /** returns the branching rule of the given name, or NULL if not existing */ SCIP_BRANCHRULE* SCIPsetFindBranchrule( SCIP_SET* set, /**< global SCIP settings */ const char* name /**< name of event handler */ ); /** sorts branching rules by priorities */ void SCIPsetSortBranchrules( SCIP_SET* set /**< global SCIP settings */ ); /** sorts branching rules by name */ void SCIPsetSortBranchrulesName( SCIP_SET* set /**< global SCIP settings */ ); /** inserts display column in display column list */ SCIP_RETCODE SCIPsetIncludeDisp( SCIP_SET* set, /**< global SCIP settings */ SCIP_DISP* disp /**< display column */ ); /** returns the display column of the given name, or NULL if not existing */ SCIP_DISP* SCIPsetFindDisp( SCIP_SET* set, /**< global SCIP settings */ const char* name /**< name of display */ ); /** inserts statistics table in statistics table list */ SCIP_RETCODE SCIPsetIncludeTable( SCIP_SET* set, /**< global SCIP settings */ SCIP_TABLE* table /**< statistics table */ ); /** returns the statistics table of the given name, or NULL if not existing */ SCIP_TABLE* SCIPsetFindTable( SCIP_SET* set, /**< global SCIP settings */ const char* name /**< name of statistics table */ ); /** inserts dialog in dialog list */ SCIP_RETCODE SCIPsetIncludeDialog( SCIP_SET* set, /**< global SCIP settings */ SCIP_DIALOG* dialog /**< dialog */ ); /** returns if the dialog already exists */ SCIP_Bool SCIPsetExistsDialog( SCIP_SET* set, /**< global SCIP settings */ SCIP_DIALOG* dialog /**< dialog */ ); /** inserts NLPI in NLPI list */ SCIP_RETCODE SCIPsetIncludeNlpi( SCIP_SET* set, /**< global SCIP settings */ SCIP_NLPI* nlpi /**< NLPI */ ); /** returns the NLPI of the given name, or NULL if not existing */ SCIP_NLPI* SCIPsetFindNlpi( SCIP_SET* set, /**< global SCIP settings */ const char* name /**< name of NLPI */ ); /** sorts NLPIs by priorities */ void SCIPsetSortNlpis( SCIP_SET* set /**< global SCIP settings */ ); /** set priority of an NLPI */ void SCIPsetSetPriorityNlpi( SCIP_SET* set, /**< global SCIP settings */ SCIP_NLPI* nlpi, /**< NLPI */ int priority /**< new priority of NLPI */ ); /** inserts information about an external code in external codes list */ SCIP_RETCODE SCIPsetIncludeExternalCode( SCIP_SET* set, /**< global SCIP settings */ const char* name, /**< name of external code */ const char* description /**< description of external code, can be NULL */ ); /** inserts bandit virtual function table into set */ SCIP_RETCODE SCIPsetIncludeBanditvtable( SCIP_SET* set, /**< global SCIP settings */ SCIP_BANDITVTABLE* banditvtable /**< bandit algorithm virtual function table */ ); /** returns the bandit virtual function table of the given name, or NULL if not existing */ SCIP_BANDITVTABLE* SCIPsetFindBanditvtable( SCIP_SET* set, /**< global SCIP settings */ const char* name /**< name of bandit algorithm virtual function table */ ); /** calls init methods of all plugins */ SCIP_RETCODE SCIPsetInitPlugins( SCIP_SET* set, /**< global SCIP settings */ BMS_BLKMEM* blkmem, /**< block memory */ SCIP_STAT* stat /**< dynamic problem statistics */ ); /** calls exit methods of all plugins */ SCIP_RETCODE SCIPsetExitPlugins( SCIP_SET* set, /**< global SCIP settings */ BMS_BLKMEM* blkmem, /**< block memory */ SCIP_STAT* stat /**< dynamic problem statistics */ ); /** calls initpre methods of all plugins */ SCIP_RETCODE SCIPsetInitprePlugins( SCIP_SET* set, /**< global SCIP settings */ BMS_BLKMEM* blkmem, /**< block memory */ SCIP_STAT* stat /**< dynamic problem statistics */ ); /** calls exitpre methods of all plugins */ SCIP_RETCODE SCIPsetExitprePlugins( SCIP_SET* set, /**< global SCIP settings */ BMS_BLKMEM* blkmem, /**< block memory */ SCIP_STAT* stat /**< dynamic problem statistics */ ); /** calls initsol methods of all plugins */ SCIP_RETCODE SCIPsetInitsolPlugins( SCIP_SET* set, /**< global SCIP settings */ BMS_BLKMEM* blkmem, /**< block memory */ SCIP_STAT* stat /**< dynamic problem statistics */ ); /** calls exitsol methods of all plugins */ SCIP_RETCODE SCIPsetExitsolPlugins( SCIP_SET* set, /**< global SCIP settings */ BMS_BLKMEM* blkmem, /**< block memory */ SCIP_STAT* stat, /**< dynamic problem statistics */ SCIP_Bool restart /**< was this exit solve call triggered by a restart? */ ); /** calculate memory size for dynamically allocated arrays */ int SCIPsetCalcMemGrowSize( SCIP_SET* set, /**< global SCIP settings */ int num /**< minimum number of entries to store */ ); /** calculate memory size for tree array */ int SCIPsetCalcTreeGrowSize( SCIP_SET* set, /**< global SCIP settings */ int num /**< minimum number of entries to store */ ); /** calculate memory size for path array */ int SCIPsetCalcPathGrowSize( SCIP_SET* set, /**< global SCIP settings */ int num /**< minimum number of entries to store */ ); /** sets verbosity level for message output */ SCIP_RETCODE SCIPsetSetVerbLevel( SCIP_SET* set, /**< global SCIP settings */ SCIP_VERBLEVEL verblevel /**< verbosity level for message output */ ); /** sets feasibility tolerance */ SCIP_RETCODE SCIPsetSetFeastol( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real feastol /**< new feasibility tolerance */ ); /** sets primal feasibility tolerance of LP solver */ SCIP_RETCODE SCIPsetSetLpfeastol( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real lpfeastol, /**< new primal feasibility tolerance of LP solver */ SCIP_Bool printnewvalue /**< should "numerics/lpfeastol = ..." be printed? */ ); /** sets feasibility tolerance for reduced costs in LP solution */ SCIP_RETCODE SCIPsetSetDualfeastol( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real dualfeastol /**< new reduced costs feasibility tolerance */ ); /** sets LP convergence tolerance used in barrier algorithm */ SCIP_RETCODE SCIPsetSetBarrierconvtol( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real barrierconvtol /**< new convergence tolerance used in barrier algorithm */ ); /** sets primal feasibility tolerance for relaxations (relaxfeastol) * * @note Set to SCIP_INVALID to apply relaxation-specific feasibility tolerance only. * * @return Previous value of relaxfeastol. */ SCIP_Real SCIPsetSetRelaxfeastol( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real relaxfeastol /**< new primal feasibility tolerance for relaxations, or SCIP_INVALID */ ); /** marks that some limit parameter was changed */ void SCIPsetSetLimitChanged( SCIP_SET* set /**< global SCIP settings */ ); /** returns the maximal number of variables priced into the LP per round */ int SCIPsetGetPriceMaxvars( SCIP_SET* set, /**< global SCIP settings */ SCIP_Bool root /**< are we at the root node? */ ); /** returns the maximal number of cuts separated per round */ int SCIPsetGetSepaMaxcuts( SCIP_SET* set, /**< global SCIP settings */ SCIP_Bool root /**< are we at the root node? */ ); /** returns user defined objective value (in original space) for reference purposes */ SCIP_Real SCIPsetGetReferencevalue( SCIP_SET* set /**< global SCIP settings */ ); /** returns debug solution data */ SCIP_DEBUGSOLDATA* SCIPsetGetDebugSolData( SCIP_SET* set /**< global SCIP settings */ ); /** Checks, if an iteratively updated value is reliable or should be recomputed from scratch. * This is useful, if the value, e.g., the activity of a linear constraint or the pseudo objective value, gets a high * absolute value during the optimization process which is later reduced significantly. In this case, the last digits * were cancelled out when increasing the value and are random after decreasing it. * We dot not consider the cancellations which can occur during increasing the absolute value because they just cannot * be expressed using fixed precision floating point arithmetic, anymore. * The idea to get more reliable values is to always store the last reliable value, where increasing the absolute of * the value is viewed as preserving reliability. Then, after each update, the new absolute value can be compared * against the last reliable one with this method, checking whether it was decreased by a factor of at least * "lp/recompfac" and should be recomputed. */ SCIP_Bool SCIPsetIsUpdateUnreliable( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real newvalue, /**< new value after update */ SCIP_Real oldvalue /**< old value, i.e., last reliable value */ ); /** modifies an initial seed value with the global shift of random seeds */ unsigned int SCIPsetInitializeRandomSeed( SCIP_SET* set, /**< global SCIP settings */ unsigned int initialseedvalue /**< initial seed value to be modified */ ); /** returns value treated as infinity */ SCIP_Real SCIPsetInfinity( SCIP_SET* set /**< global SCIP settings */ ); /** returns the minimum value that is regarded as huge and should be handled separately (e.g., in activity * computation) */ SCIP_Real SCIPsetGetHugeValue( SCIP_SET* set /**< global SCIP settings */ ); /** returns value treated as zero */ SCIP_Real SCIPsetEpsilon( SCIP_SET* set /**< global SCIP settings */ ); /** returns value treated as zero for sums of floating point values */ SCIP_Real SCIPsetSumepsilon( SCIP_SET* set /**< global SCIP settings */ ); /** returns feasibility tolerance for constraints */ SCIP_Real SCIPsetFeastol( SCIP_SET* set /**< global SCIP settings */ ); /** returns primal feasibility tolerance of LP solver given as minimum of lpfeastol option and relaxfeastol */ SCIP_Real SCIPsetLpfeastol( SCIP_SET* set /**< global SCIP settings */ ); /** returns feasibility tolerance for reduced costs */ SCIP_Real SCIPsetDualfeastol( SCIP_SET* set /**< global SCIP settings */ ); /** returns convergence tolerance used in barrier algorithm */ SCIP_Real SCIPsetBarrierconvtol( SCIP_SET* set /**< global SCIP settings */ ); /** returns minimal variable distance value to use for pseudo cost updates */ SCIP_Real SCIPsetPseudocosteps( SCIP_SET* set /**< global SCIP settings */ ); /** returns minimal minimal objective distance value to use for pseudo cost updates */ SCIP_Real SCIPsetPseudocostdelta( SCIP_SET* set /**< global SCIP settings */ ); /** return the delta to use for computing the cutoff bound for integral objectives */ SCIP_Real SCIPsetCutoffbounddelta( SCIP_SET* set /**< global SCIP settings */ ); /** return the primal feasibility tolerance for relaxations */ SCIP_Real SCIPsetRelaxfeastol( SCIP_SET* set /**< global SCIP settings */ ); /** returns minimal decrease factor that causes the recomputation of a value * (e.g., pseudo objective) instead of an update */ SCIP_Real SCIPsetRecompfac( SCIP_SET* set /**< global SCIP settings */ ); /** checks, if values are in range of epsilon */ SCIP_Bool SCIPsetIsEQ( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if val1 is (more than epsilon) lower than val2 */ SCIP_Bool SCIPsetIsLT( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if val1 is not (more than epsilon) greater than val2 */ SCIP_Bool SCIPsetIsLE( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if val1 is (more than epsilon) greater than val2 */ SCIP_Bool SCIPsetIsGT( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if val1 is not (more than epsilon) lower than val2 */ SCIP_Bool SCIPsetIsGE( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if value is (positive) infinite */ SCIP_Bool SCIPsetIsInfinity( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against infinity */ ); /** checks, if value is huge and should be handled separately (e.g., in activity computation) */ SCIP_Bool SCIPsetIsHugeValue( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be checked whether it is huge */ ); /** checks, if value is in range epsilon of 0.0 */ SCIP_Bool SCIPsetIsZero( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** checks, if value is greater than epsilon */ SCIP_Bool SCIPsetIsPositive( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** checks, if value is lower than -epsilon */ SCIP_Bool SCIPsetIsNegative( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** checks, if value is integral within epsilon */ SCIP_Bool SCIPsetIsIntegral( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** checks whether the product val * scalar is integral in epsilon scaled by scalar */ SCIP_Bool SCIPsetIsScalingIntegral( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val, /**< unscaled value to check for scaled integrality */ SCIP_Real scalar /**< value to scale val with for checking for integrality */ ); /** checks, if given fractional part is smaller than epsilon */ SCIP_Bool SCIPsetIsFracIntegral( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** rounds value + feasibility tolerance down to the next integer in epsilon tolerance */ SCIP_Real SCIPsetFloor( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** rounds value - feasibility tolerance up to the next integer in epsilon tolerance */ SCIP_Real SCIPsetCeil( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** rounds value to the nearest integer in epsilon tolerance */ SCIP_Real SCIPsetRound( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** returns fractional part of value, i.e. x - floor(x) in epsilon tolerance */ SCIP_Real SCIPsetFrac( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to return fractional part for */ ); /** checks, if values are in range of sumepsilon */ SCIP_Bool SCIPsetIsSumEQ( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if val1 is (more than sumepsilon) lower than val2 */ SCIP_Bool SCIPsetIsSumLT( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if val1 is not (more than sumepsilon) greater than val2 */ SCIP_Bool SCIPsetIsSumLE( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if val1 is (more than sumepsilon) greater than val2 */ SCIP_Bool SCIPsetIsSumGT( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if val1 is not (more than sumepsilon) lower than val2 */ SCIP_Bool SCIPsetIsSumGE( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if value is in range sumepsilon of 0.0 */ SCIP_Bool SCIPsetIsSumZero( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** checks, if value is greater than sumepsilon */ SCIP_Bool SCIPsetIsSumPositive( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** checks, if value is lower than -sumepsilon */ SCIP_Bool SCIPsetIsSumNegative( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** rounds value + sumepsilon tolerance down to the next integer */ SCIP_Real SCIPsetSumFloor( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to process */ ); /** rounds value - sumepsilon tolerance up to the next integer */ SCIP_Real SCIPsetSumCeil( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to process */ ); /** rounds value to the nearest integer in sumepsilon tolerance */ SCIP_Real SCIPsetSumRound( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to process */ ); /** returns fractional part of value, i.e. x - floor(x) in sumepsilon tolerance */ SCIP_Real SCIPsetSumFrac( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to process */ ); /** checks, if relative difference of values is in range of feastol */ SCIP_Bool SCIPsetIsFeasEQ( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if relative difference of val1 and val2 is lower than feastol */ SCIP_Bool SCIPsetIsFeasLT( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if relative difference of val1 and val2 is not greater than feastol */ SCIP_Bool SCIPsetIsFeasLE( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if relative difference of val1 and val2 is greater than feastol */ SCIP_Bool SCIPsetIsFeasGT( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if relative difference of val1 and val2 is not lower than -feastol */ SCIP_Bool SCIPsetIsFeasGE( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if value is in range feasibility tolerance of 0.0 */ SCIP_Bool SCIPsetIsFeasZero( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** checks, if value is greater than feasibility tolerance */ SCIP_Bool SCIPsetIsFeasPositive( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** checks, if value is lower than -feasibility tolerance */ SCIP_Bool SCIPsetIsFeasNegative( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** checks, if value is integral within the feasibility bounds */ SCIP_Bool SCIPsetIsFeasIntegral( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** checks, if given fractional part is smaller than feastol */ SCIP_Bool SCIPsetIsFeasFracIntegral( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** rounds value + feasibility tolerance down to the next integer */ SCIP_Real SCIPsetFeasFloor( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** rounds value - feasibility tolerance up to the next integer */ SCIP_Real SCIPsetFeasCeil( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** rounds value to the nearest integer in feasibility tolerance */ SCIP_Real SCIPsetFeasRound( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** returns fractional part of value, i.e. x - floor(x) in feasibility tolerance */ SCIP_Real SCIPsetFeasFrac( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to return fractional part for */ ); /** checks, if relative difference of values is in range of dual feasibility tolerance */ SCIP_Bool SCIPsetIsDualfeasEQ( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if relative difference of val1 and val2 is lower than dual feasibility tolerance */ SCIP_Bool SCIPsetIsDualfeasLT( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if relative difference of val1 and val2 is not greater than dual feasibility tolerance */ SCIP_Bool SCIPsetIsDualfeasLE( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if relative difference of val1 and val2 is greater than dual feasibility tolerance */ SCIP_Bool SCIPsetIsDualfeasGT( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if relative difference of val1 and val2 is not lower than -dual feasibility tolerance */ SCIP_Bool SCIPsetIsDualfeasGE( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if value is in range dual feasibility tolerance of 0.0 */ SCIP_Bool SCIPsetIsDualfeasZero( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** checks, if value is greater than dual feasibility tolerance */ SCIP_Bool SCIPsetIsDualfeasPositive( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** checks, if value is lower than -dual feasibility tolerance */ SCIP_Bool SCIPsetIsDualfeasNegative( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** checks, if value is integral within the dual feasibility bounds */ SCIP_Bool SCIPsetIsDualfeasIntegral( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** checks, if given fractional part is smaller than dual feasibility tolerance */ SCIP_Bool SCIPsetIsDualfeasFracIntegral( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** rounds value + dual feasibility tolerance down to the next integer */ SCIP_Real SCIPsetDualfeasFloor( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** rounds value - dual feasibility tolerance up to the next integer */ SCIP_Real SCIPsetDualfeasCeil( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** rounds value to the nearest integer in dual feasibility tolerance */ SCIP_Real SCIPsetDualfeasRound( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to be compared against zero */ ); /** returns fractional part of value, i.e. x - floor(x) in dual feasibility tolerance */ SCIP_Real SCIPsetDualfeasFrac( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val /**< value to return fractional part for */ ); /** checks, if the given new lower bound is at least min(oldub - oldlb, |oldlb|) times the bound * strengthening epsilon better than the old one or the change in the lower bound would fix the * sign of the variable */ SCIP_Bool SCIPsetIsLbBetter( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real newlb, /**< new lower bound */ SCIP_Real oldlb, /**< old lower bound */ SCIP_Real oldub /**< old upper bound */ ); /** checks, if the given new upper bound is at least min(oldub - oldlb, |oldub|) times the bound * strengthening epsilon better than the old one or the change in the upper bound would fix the * sign of the variable */ SCIP_Bool SCIPsetIsUbBetter( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real newub, /**< new upper bound */ SCIP_Real oldlb, /**< old lower bound */ SCIP_Real oldub /**< old upper bound */ ); /** checks, if the given cut's efficacy is larger than the minimal cut efficacy */ SCIP_Bool SCIPsetIsEfficacious( SCIP_SET* set, /**< global SCIP settings */ SCIP_Bool root, /**< should the root's minimal cut efficacy be used? */ SCIP_Real efficacy /**< efficacy of the cut */ ); /** checks, if relative difference of values is in range of epsilon */ SCIP_Bool SCIPsetIsRelEQ( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if relative difference of val1 and val2 is lower than epsilon */ SCIP_Bool SCIPsetIsRelLT( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if relative difference of val1 and val2 is not greater than epsilon */ SCIP_Bool SCIPsetIsRelLE( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if relative difference of val1 and val2 is greater than epsilon */ SCIP_Bool SCIPsetIsRelGT( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if relative difference of val1 and val2 is not lower than -epsilon */ SCIP_Bool SCIPsetIsRelGE( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if relative difference of values is in range of sumepsilon */ SCIP_Bool SCIPsetIsSumRelEQ( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if relative difference of val1 and val2 is lower than sumepsilon */ SCIP_Bool SCIPsetIsSumRelLT( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if relative difference of val1 and val2 is not greater than sumepsilon */ SCIP_Bool SCIPsetIsSumRelLE( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if relative difference of val1 and val2 is greater than sumepsilon */ SCIP_Bool SCIPsetIsSumRelGT( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); /** checks, if relative difference of val1 and val2 is not lower than -sumepsilon */ SCIP_Bool SCIPsetIsSumRelGE( SCIP_SET* set, /**< global SCIP settings */ SCIP_Real val1, /**< first value to be compared */ SCIP_Real val2 /**< second value to be compared */ ); #ifdef NDEBUG /* In optimized mode, the function calls are overwritten by defines to reduce the number of function calls and * speed up the algorithms. */ #define SCIPsetInfinity(set) ( (set)->num_infinity ) #define SCIPsetGetHugeValue(set) ( (set)->num_hugeval ) #define SCIPsetEpsilon(set) ( (set)->num_epsilon ) #define SCIPsetSumepsilon(set) ( (set)->num_sumepsilon ) #define SCIPsetFeastol(set) ( (set)->num_feastol ) #define SCIPsetLpfeastol(set) ( (set)->num_relaxfeastol == SCIP_INVALID ? (set)->num_lpfeastol : MIN((set)->num_lpfeastol, (set)->num_relaxfeastol) ) #define SCIPsetDualfeastol(set) ( (set)->num_dualfeastol ) #define SCIPsetBarrierconvtol(set) ( (set)->num_barrierconvtol ) #define SCIPsetPseudocosteps(set) ( (set)->num_pseudocosteps ) #define SCIPsetPseudocostdelta(set) ( (set)->num_pseudocostdelta ) #define SCIPsetRelaxfeastol(set) ( (set)->num_relaxfeastol ) #define SCIPsetCutoffbounddelta(set) ( MIN(100.0 * SCIPsetFeastol(set), 0.0001) ) #define SCIPsetRecompfac(set) ( (set)->num_recompfac ) #define SCIPsetIsEQ(set, val1, val2) ( EPSEQ(val1, val2, (set)->num_epsilon) ) #define SCIPsetIsLT(set, val1, val2) ( EPSLT(val1, val2, (set)->num_epsilon) ) #define SCIPsetIsLE(set, val1, val2) ( EPSLE(val1, val2, (set)->num_epsilon) ) #define SCIPsetIsGT(set, val1, val2) ( EPSGT(val1, val2, (set)->num_epsilon) ) #define SCIPsetIsGE(set, val1, val2) ( EPSGE(val1, val2, (set)->num_epsilon) ) #define SCIPsetIsInfinity(set, val) ( (val) >= (set)->num_infinity ) #define SCIPsetIsHugeValue(set, val) ( (val) >= (set)->num_hugeval ) #define SCIPsetIsZero(set, val) ( EPSZ(val, (set)->num_epsilon) ) #define SCIPsetIsPositive(set, val) ( EPSP(val, (set)->num_epsilon) ) #define SCIPsetIsNegative(set, val) ( EPSN(val, (set)->num_epsilon) ) #define SCIPsetIsIntegral(set, val) ( EPSISINT(val, (set)->num_epsilon) ) #define SCIPsetIsScalingIntegral(set, val, scalar) \ ( EPSISINT((scalar)*(val), MAX(REALABS(scalar), 1.0)*(set)->num_epsilon) ) #define SCIPsetIsFracIntegral(set, val) ( !EPSP(val, (set)->num_epsilon) ) #define SCIPsetFloor(set, val) ( EPSFLOOR(val, (set)->num_epsilon) ) #define SCIPsetCeil(set, val) ( EPSCEIL(val, (set)->num_epsilon) ) #define SCIPsetRound(set, val) ( EPSROUND(val, (set)->num_epsilon) ) #define SCIPsetFrac(set, val) ( EPSFRAC(val, (set)->num_epsilon) ) #define SCIPsetIsSumEQ(set, val1, val2) ( EPSEQ(val1, val2, (set)->num_sumepsilon) ) #define SCIPsetIsSumLT(set, val1, val2) ( EPSLT(val1, val2, (set)->num_sumepsilon) ) #define SCIPsetIsSumLE(set, val1, val2) ( EPSLE(val1, val2, (set)->num_sumepsilon) ) #define SCIPsetIsSumGT(set, val1, val2) ( EPSGT(val1, val2, (set)->num_sumepsilon) ) #define SCIPsetIsSumGE(set, val1, val2) ( EPSGE(val1, val2, (set)->num_sumepsilon) ) #define SCIPsetIsSumZero(set, val) ( EPSZ(val, (set)->num_sumepsilon) ) #define SCIPsetIsSumPositive(set, val) ( EPSP(val, (set)->num_sumepsilon) ) #define SCIPsetIsSumNegative(set, val) ( EPSN(val, (set)->num_sumepsilon) ) #define SCIPsetSumFloor(set, val) ( EPSFLOOR(val, (set)->num_sumepsilon) ) #define SCIPsetSumCeil(set, val) ( EPSCEIL(val, (set)->num_sumepsilon) ) #define SCIPsetSumRound(set, val) ( EPSROUND(val, (set)->num_sumepsilon) ) #define SCIPsetSumFrac(set, val) ( EPSFRAC(val, (set)->num_sumepsilon) ) #define SCIPsetIsFeasEQ(set, val1, val2) ( EPSZ(SCIPrelDiff(val1, val2), (set)->num_feastol) ) #define SCIPsetIsFeasLT(set, val1, val2) ( EPSN(SCIPrelDiff(val1, val2), (set)->num_feastol) ) #define SCIPsetIsFeasLE(set, val1, val2) ( !EPSP(SCIPrelDiff(val1, val2), (set)->num_feastol) ) #define SCIPsetIsFeasGT(set, val1, val2) ( EPSP(SCIPrelDiff(val1, val2), (set)->num_feastol) ) #define SCIPsetIsFeasGE(set, val1, val2) ( !EPSN(SCIPrelDiff(val1, val2), (set)->num_feastol) ) #define SCIPsetIsFeasZero(set, val) ( EPSZ(val, (set)->num_feastol) ) #define SCIPsetIsFeasPositive(set, val) ( EPSP(val, (set)->num_feastol) ) #define SCIPsetIsFeasNegative(set, val) ( EPSN(val, (set)->num_feastol) ) #define SCIPsetIsFeasIntegral(set, val) ( EPSISINT(val, (set)->num_feastol) ) #define SCIPsetIsFeasFracIntegral(set, val) ( !EPSP(val, (set)->num_feastol) ) #define SCIPsetFeasFloor(set, val) ( EPSFLOOR(val, (set)->num_feastol) ) #define SCIPsetFeasCeil(set, val) ( EPSCEIL(val, (set)->num_feastol) ) #define SCIPsetFeasRound(set, val) ( EPSROUND(val, (set)->num_feastol) ) #define SCIPsetFeasFrac(set, val) ( EPSFRAC(val, (set)->num_feastol) ) #define SCIPsetIsDualfeasEQ(set, val1, val2) ( EPSZ(SCIPrelDiff(val1, val2), (set)->num_dualfeastol) ) #define SCIPsetIsDualfeasLT(set, val1, val2) ( EPSN(SCIPrelDiff(val1, val2), (set)->num_dualfeastol) ) #define SCIPsetIsDualfeasLE(set, val1, val2) ( !EPSP(SCIPrelDiff(val1, val2), (set)->num_dualfeastol) ) #define SCIPsetIsDualfeasGT(set, val1, val2) ( EPSP(SCIPrelDiff(val1, val2), (set)->num_dualfeastol) ) #define SCIPsetIsDualfeasGE(set, val1, val2) ( !EPSN(SCIPrelDiff(val1, val2), (set)->num_dualfeastol) ) #define SCIPsetIsDualfeasZero(set, val) ( EPSZ(val, (set)->num_dualfeastol) ) #define SCIPsetIsDualfeasPositive(set, val) ( EPSP(val, (set)->num_dualfeastol) ) #define SCIPsetIsDualfeasNegative(set, val) ( EPSN(val, (set)->num_dualfeastol) ) #define SCIPsetIsDualfeasIntegral(set, val) ( EPSISINT(val, (set)->num_dualfeastol) ) #define SCIPsetIsDualfeasFracIntegral(set, val) ( !EPSP(val, (set)->num_dualfeastol) ) #define SCIPsetDualfeasFloor(set, val) ( EPSFLOOR(val, (set)->num_dualfeastol) ) #define SCIPsetDualfeasCeil(set, val) ( EPSCEIL(val, (set)->num_dualfeastol) ) #define SCIPsetDualfeasRound(set, val) ( EPSROUND(val, (set)->num_dualfeastol) ) #define SCIPsetDualfeasFrac(set, val) ( EPSFRAC(val, (set)->num_dualfeastol) ) #define SCIPsetIsLbBetter(set, newlb, oldlb, oldub) ( ((oldlb) < 0.0 && (newlb) >= 0.0) || EPSGT(newlb, oldlb, \ set->num_boundstreps * MAX(MIN((oldub) - (oldlb), REALABS(oldlb)), 1e-3)) ) #define SCIPsetIsUbBetter(set, newub, oldlb, oldub) ( ((oldub) > 0.0 && (newub) <= 0.0) || EPSLT(newub, oldub, \ set->num_boundstreps * MAX(MIN((oldub) - (oldlb), REALABS(oldub)), 1e-3)) ) #define SCIPsetIsEfficacious(set, root, efficacy) \ ( root ? EPSP(efficacy, (set)->sepa_minefficacyroot) : EPSP(efficacy, (set)->sepa_minefficacy) ) #define SCIPsetIsRelEQ(set, val1, val2) ( EPSZ(SCIPrelDiff(val1, val2), (set)->num_epsilon) ) #define SCIPsetIsRelLT(set, val1, val2) ( EPSN(SCIPrelDiff(val1, val2), (set)->num_epsilon) ) #define SCIPsetIsRelLE(set, val1, val2) ( !EPSP(SCIPrelDiff(val1, val2), (set)->num_epsilon) ) #define SCIPsetIsRelGT(set, val1, val2) ( EPSP(SCIPrelDiff(val1, val2), (set)->num_epsilon) ) #define SCIPsetIsRelGE(set, val1, val2) ( !EPSN(SCIPrelDiff(val1, val2), (set)->num_epsilon) ) #define SCIPsetIsSumRelEQ(set, val1, val2) ( EPSZ(SCIPrelDiff(val1, val2), (set)->num_sumepsilon) ) #define SCIPsetIsSumRelLT(set, val1, val2) ( EPSN(SCIPrelDiff(val1, val2), (set)->num_sumepsilon) ) #define SCIPsetIsSumRelLE(set, val1, val2) ( !EPSP(SCIPrelDiff(val1, val2), (set)->num_sumepsilon) ) #define SCIPsetIsSumRelGT(set, val1, val2) ( EPSP(SCIPrelDiff(val1, val2), (set)->num_sumepsilon) ) #define SCIPsetIsSumRelGE(set, val1, val2) ( !EPSN(SCIPrelDiff(val1, val2), (set)->num_sumepsilon) ) #define SCIPsetIsUpdateUnreliable(set, newvalue, oldvalue) \ ( (ABS(oldvalue) / MAX(ABS(newvalue), set->num_epsilon)) >= set->num_recompfac ) #define SCIPsetInitializeRandomSeed(set, val) ( (val + (set)->random_randomseedshift) ) #endif #define SCIPsetAllocBuffer(set,ptr) ( (BMSallocBufferMemory((set)->buffer, (ptr)) == NULL) ? SCIP_NOMEMORY : SCIP_OKAY ) #define SCIPsetAllocBufferSize(set,ptr,size) ( (BMSallocBufferMemorySize((set)->buffer, (ptr), (size)) == NULL) ? SCIP_NOMEMORY : SCIP_OKAY ) #define SCIPsetAllocBufferArray(set,ptr,num) ( (BMSallocBufferMemoryArray((set)->buffer, (ptr), (num)) == NULL) ? SCIP_NOMEMORY : SCIP_OKAY ) #define SCIPsetDuplicateBufferSize(set,ptr,source,size) ( (BMSduplicateBufferMemory((set)->buffer, (ptr), (source), (size)) == NULL) ? SCIP_NOMEMORY : SCIP_OKAY ) #define SCIPsetDuplicateBufferArray(set,ptr,source,num) ( (BMSduplicateBufferMemoryArray((set)->buffer, (ptr), (source), (num)) == NULL) ? SCIP_NOMEMORY : SCIP_OKAY ) #define SCIPsetReallocBufferSize(set,ptr,size) ( (BMSreallocBufferMemorySize((set)->buffer, (ptr), (size)) == NULL) ? SCIP_NOMEMORY : SCIP_OKAY ) #define SCIPsetReallocBufferArray(set,ptr,num) ( (BMSreallocBufferMemoryArray((set)->buffer, (ptr), (num)) == NULL) ? SCIP_NOMEMORY : SCIP_OKAY ) #define SCIPsetFreeBuffer(set,ptr) BMSfreeBufferMemory((set)->buffer, (ptr)) #define SCIPsetFreeBufferSize(set,ptr) BMSfreeBufferMemorySize((set)->buffer, (ptr)) #define SCIPsetFreeBufferArray(set,ptr) BMSfreeBufferMemoryArray((set)->buffer, (ptr)) #define SCIPsetAllocCleanBuffer(set,ptr) ( (BMSallocBufferMemory((set)->cleanbuffer, (ptr)) == NULL) ? SCIP_NOMEMORY : SCIP_OKAY ) #define SCIPsetAllocCleanBufferSize(set,ptr,size) ( (BMSallocBufferMemorySize((set)->cleanbuffer, (ptr), (size)) == NULL) ? SCIP_NOMEMORY : SCIP_OKAY ) #define SCIPsetAllocCleanBufferArray(set,ptr,num) ( (BMSallocBufferMemoryArray((set)->cleanbuffer, (ptr), (num)) == NULL) ? SCIP_NOMEMORY : SCIP_OKAY ) #define SCIPsetFreeCleanBuffer(set,ptr) BMSfreeBufferMemory((set)->cleanbuffer, (ptr)) #define SCIPsetFreeCleanBufferSize(set,ptr) BMSfreeBufferMemorySize((set)->cleanbuffer, (ptr)) #define SCIPsetFreeCleanBufferArray(set,ptr) BMSfreeBufferMemoryArray((set)->cleanbuffer, (ptr)) /* if we have a C99 compiler */ #ifdef SCIP_HAVE_VARIADIC_MACROS /** prints a debugging message if SCIP_DEBUG flag is set */ #ifdef SCIP_DEBUG #define SCIPsetDebugMsg(set, ...) SCIPsetPrintDebugMessage(set, __FILE__, __LINE__, __VA_ARGS__) #define SCIPsetDebugMsgPrint(set, ...) SCIPsetDebugMessagePrint(set, __VA_ARGS__) #else #define SCIPsetDebugMsg(set, ...) while ( FALSE ) SCIPsetPrintDebugMessage(set, __FILE__, __LINE__, __VA_ARGS__) #define SCIPsetDebugMsgPrint(set, ...) while ( FALSE ) SCIPsetDebugMessagePrint(set, __VA_ARGS__) #endif #else /* if we do not have a C99 compiler, use a workaround that prints a message, but not the file and linenumber */ /** prints a debugging message if SCIP_DEBUG flag is set */ #ifdef SCIP_DEBUG #define SCIPsetDebugMsg printf("debug: "), SCIPsetDebugMessagePrint #define SCIPsetDebugMsgPrint printf("debug: "), SCIPsetDebugMessagePrint #else #define SCIPsetDebugMsg while ( FALSE ) SCIPsetDebugMsgPrint #define SCIPsetDebugMsgPrint while ( FALSE ) SCIPsetDebugMessagePrint #endif #endif /** prints a debug message */ SCIP_EXPORT void SCIPsetPrintDebugMessage( SCIP_SET* set, /**< global SCIP settings */ const char* sourcefile, /**< name of the source file that called the function */ int sourceline, /**< line in the source file where the function was called */ const char* formatstr, /**< format string like in printf() function */ ... /**< format arguments line in printf() function */ ); /** prints a debug message without precode */ SCIP_EXPORT void SCIPsetDebugMessagePrint( SCIP_SET* set, /**< global SCIP settings */ const char* formatstr, /**< format string like in printf() function */ ... /**< format arguments line in printf() function */ ); #ifdef __cplusplus } #endif #endif
0.996094
high
src/symbol.c
kingletbv/carburetta
6
916161
/* Copyright 2020-2021 Kinglet B.V. * * 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 STDLIB_H_INCLUDED #define STDLIB_H_INCLUDED #include <stdlib.h> #endif #ifndef STDINT_H_INCLUDED #define STDINT_H_INCLUDED #include <stdint.h> #endif #ifndef STRING_H_INCLUDED #define STRING_H_INCLUDED #include <string.h> #endif #ifndef XLTS_H_INCLUDED #define XLTS_H_INCLUDED #include "xlts.h" #endif #ifndef ASSERT_H_INCLUDED #define ASSERT_H_INCLUDED #include <assert.h> #endif #ifndef SYMBOL_H_INCLUDED #define SYMBOL_H_INCLUDED #include "symbol.h" #endif void symbol_table_init(struct symbol_table *st) { memset(st->hash_table_, 0, sizeof(st->hash_table_)); st->non_terminals_ = NULL; st->terminals_ = NULL; } void symbol_table_cleanup(struct symbol_table *st) { struct symbol *sym, *next; sym = st->non_terminals_; if (sym) { next = sym->next_; /* next == head of list */ do { sym = next; next = sym->next_; symbol_cleanup(sym); free(sym); } while (sym != st->non_terminals_); /* while not last */ st->non_terminals_ = NULL; } sym = st->terminals_; if (sym) { next = sym->next_; do { sym = next; next = sym->next_; symbol_cleanup(sym); free(sym); } while (sym != st->terminals_); st->terminals_ = NULL; } } void symbol_init(struct symbol *sym) { sym->st_ = SYM_UNDEFINED; xlts_init(&sym->def_); sym->ordinal_ = 0; sym->next_ = NULL; sym->hash_chain_ = NULL; snippet_init(&sym->type_snippet_); sym->assigned_type_ = NULL; } void symbol_cleanup(struct symbol *sym) { snippet_cleanup(&sym->type_snippet_); xlts_cleanup(&sym->def_); } /* Follows same logic as in mode.c */ static uint8_t sym_standardize_char(uint8_t c) { if (c == '-') c = '_'; if ((c >= 'a') && (c <= 'z')) c = c + 'A' - 'a'; return c; } static int sym_hash(const char *id) { uint64_t hash_value = 0; while (*id) { uint8_t c = sym_standardize_char(*(uint8_t *)id); /* Dashes convert to underscores, letters are all upper-cased, to ensure the symbols are unique *after* hashing */ hash_value = (hash_value << 7) | (hash_value >> ((-7) & 63)); hash_value += c; id++; } return (int)(hash_value % SYMBOL_TABLE_SIZE); } static int sym_cmp(const char *left, const char *right) { while (*left && *right) { uint8_t left_value = sym_standardize_char((uint8_t)*left); uint8_t right_value = sym_standardize_char((uint8_t)*right); if (left_value < right_value) return -1; if (left_value > right_value) return 1; left++; right++; } if (*left) { return 1; } if (*right) { return -1; } return 0; } struct symbol *symbol_find_or_add(struct symbol_table *st, sym_type_t symtype, struct xlts *id, int *is_new) { int idx = sym_hash(id->translated_); struct symbol *sym, *last; sym = last = st->hash_table_[idx]; if (sym) { do { sym = sym->hash_chain_; if (!sym_cmp(sym->def_.translated_, id->translated_)) { *is_new = 0; return sym; } } while (sym != last); } sym = (struct symbol *)malloc(sizeof(struct symbol)); if (!sym) { return NULL; } symbol_init(sym); sym->st_ = symtype; sym->hash_chain_ = last ? last->hash_chain_ : sym; if (last) { last->hash_chain_ = sym; } st->hash_table_[idx] = sym; sym->ordinal_ = 0; xlts_append(&sym->def_, id); if (symtype == SYM_NONTERMINAL) { if (st->non_terminals_) { sym->next_ = st->non_terminals_->next_; st->non_terminals_->next_ = sym; } else { sym->next_ = sym; } st->non_terminals_ = sym; } else /* symtype == SYM_TERMINAL */ { assert(symtype == SYM_TERMINAL); if (st->terminals_) { sym->next_ = st->terminals_->next_; st->terminals_->next_ = sym; } else { sym->next_ = sym; } st->terminals_ = sym; } *is_new = 1; return sym; } struct symbol *symbol_find(struct symbol_table *st, const char *id) { int idx = sym_hash(id); struct symbol *sym, *last; sym = last = st->hash_table_[idx]; if (sym) { do { sym = sym->hash_chain_; if (!sym_cmp(sym->def_.translated_, id)) { return sym; } } while (sym != last); } return NULL; /* not found */ } struct symbol *symbol_find_by_ordinal(struct symbol_table *st, int n) { struct symbol *sym; sym = st->terminals_; if (sym) { do { if (sym->ordinal_ == n) return sym; sym = sym->next_; } while (sym != st->terminals_); } sym = st->non_terminals_; if (sym) { do { if (sym->ordinal_ == n) return sym; sym = sym->next_; } while (sym != st->non_terminals_); } return NULL; }
1
high
mex/include/wildmagic-5.7/include/Wm5BSplineReduction.h
sangyoonHan/extern
0
916673
// Geometric Tools, LLC // Copyright (c) 1998-2011 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 5.0.1 (2010/10/01) #ifndef WM5BSPLINEREDUCTION_H #define WM5BSPLINEREDUCTION_H #include "Wm5MathematicsLIB.h" #include "Wm5Vector2.h" #include "Wm5Vector3.h" namespace Wm5 { template <typename Real, typename TVector> class WM5_MATHEMATICS_ITEM BSplineReduction { public: // The input quantity numCtrlPoints must be 2 or larger. The caller is // responsible for deleting the input array ctrlPoints and the output array // akCtrlOut. The degree degree of the input curve must satisfy the // condition 1 <= degree <= numCtrlPoints-1. The degree of the output // curve is the same as that of the input curve. The value fraction // must be in [0,1]. If the fraction is 1, the output curve is identical // to the input curve. If the fraction is too small to produce a valid // number of control points, the output control quantity is chosen to be // outNumCtrlPoints = degree+1. BSplineReduction (int numCtrlPoints, const TVector* ctrlPoints, int degree, Real fraction, int& outNumCtrlPoints, TVector*& outCtrlPoints); ~BSplineReduction (); private: Real MinSupport (int basis, int i) const; Real MaxSupport (int basis, int i) const; Real F (int basis, int i, int j, Real t); static Real Integrand (Real t, void* data); int mDegree; int mQuantity[2]; int mNumKnots[2]; // N+D+2 Real* mKnot[2]; // For the integration-based least-squares fitting. int mBasis[2], mIndex[2]; }; typedef BSplineReduction<float,Vector2f> BSplineReduction2f; typedef BSplineReduction<double,Vector2d> BSplineReduction2d; typedef BSplineReduction<float,Vector3f> BSplineReduction3f; typedef BSplineReduction<double,Vector3d> BSplineReduction3d; } #endif
0.992188
high
AVN/AVNNewsItemDetailViewController.h
martentamerius/avn-ios
0
917185
// // AVNNewsItemDetailViewController.h // AVN // // Created by <NAME> on 21-05-14. // Copyright (c) 2014 AVN. All rights reserved. // #import <UIKit/UIKit.h> #import "AVNNewsItem.h" @interface AVNNewsItemDetailViewController : UIViewController @property (strong, nonatomic) AVNNewsItem *selectedNewsItem; @end
0.625
medium
magicavoxel_vox/src/cpp_stl_98/magicavoxel_vox.h
kaitai-io/formats-kaitai-io.github.io
4
917697
<reponame>kaitai-io/formats-kaitai-io.github.io #ifndef MAGICAVOXEL_VOX_H_ #define MAGICAVOXEL_VOX_H_ // This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild #include "kaitai/kaitaistruct.h" #include <stdint.h> #include <vector> #if KAITAI_STRUCT_VERSION < 9000L #error "Incompatible Kaitai Struct C++/STL API: version 0.9 or later is required" #endif /** * \sa https://ephtracy.github.io/ MagicaVoxel Homepage * \sa https://github.com/ephtracy/voxel-model/blob/master/MagicaVoxel-file-format-vox.txt Format Description */ class magicavoxel_vox_t : public kaitai::kstruct { public: class chunk_t; class size_t; class rgba_t; class pack_t; class matt_t; class xyzi_t; class color_t; class voxel_t; enum chunk_type_t { CHUNK_TYPE_MAIN = 1296124238, CHUNK_TYPE_MATT = 1296127060, CHUNK_TYPE_PACK = 1346454347, CHUNK_TYPE_RGBA = 1380401729, CHUNK_TYPE_SIZE = 1397316165, CHUNK_TYPE_XYZI = 1482250825 }; enum material_type_t { MATERIAL_TYPE_DIFFUSE = 0, MATERIAL_TYPE_METAL = 1, MATERIAL_TYPE_GLASS = 2, MATERIAL_TYPE_EMISSIVE = 3 }; enum property_bits_type_t { PROPERTY_BITS_TYPE_PLASTIC = 1, PROPERTY_BITS_TYPE_ROUGHNESS = 2, PROPERTY_BITS_TYPE_SPECULAR = 4, PROPERTY_BITS_TYPE_IOR = 8, PROPERTY_BITS_TYPE_ATTENUATION = 16, PROPERTY_BITS_TYPE_POWER = 32, PROPERTY_BITS_TYPE_GLOW = 64, PROPERTY_BITS_TYPE_IS_TOTAL_POWER = 128 }; magicavoxel_vox_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent = 0, magicavoxel_vox_t* p__root = 0); private: void _read(); void _clean_up(); public: ~magicavoxel_vox_t(); class chunk_t : public kaitai::kstruct { public: chunk_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent = 0, magicavoxel_vox_t* p__root = 0); private: void _read(); void _clean_up(); public: ~chunk_t(); private: chunk_type_t m_chunk_id; uint32_t m_num_bytes_of_chunk_content; uint32_t m_num_bytes_of_children_chunks; kaitai::kstruct* m_chunk_content; bool n_chunk_content; public: bool _is_null_chunk_content() { chunk_content(); return n_chunk_content; }; private: std::vector<chunk_t*>* m_children_chunks; bool n_children_chunks; public: bool _is_null_children_chunks() { children_chunks(); return n_children_chunks; }; private: magicavoxel_vox_t* m__root; kaitai::kstruct* m__parent; std::string m__raw_chunk_content; bool n__raw_chunk_content; public: bool _is_null__raw_chunk_content() { _raw_chunk_content(); return n__raw_chunk_content; }; private: kaitai::kstream* m__io__raw_chunk_content; public: chunk_type_t chunk_id() const { return m_chunk_id; } uint32_t num_bytes_of_chunk_content() const { return m_num_bytes_of_chunk_content; } uint32_t num_bytes_of_children_chunks() const { return m_num_bytes_of_children_chunks; } kaitai::kstruct* chunk_content() const { return m_chunk_content; } std::vector<chunk_t*>* children_chunks() const { return m_children_chunks; } magicavoxel_vox_t* _root() const { return m__root; } kaitai::kstruct* _parent() const { return m__parent; } std::string _raw_chunk_content() const { return m__raw_chunk_content; } kaitai::kstream* _io__raw_chunk_content() const { return m__io__raw_chunk_content; } }; class size_t : public kaitai::kstruct { public: size_t(kaitai::kstream* p__io, magicavoxel_vox_t::chunk_t* p__parent = 0, magicavoxel_vox_t* p__root = 0); private: void _read(); void _clean_up(); public: ~size_t(); private: uint32_t m_size_x; uint32_t m_size_y; uint32_t m_size_z; magicavoxel_vox_t* m__root; magicavoxel_vox_t::chunk_t* m__parent; public: uint32_t size_x() const { return m_size_x; } uint32_t size_y() const { return m_size_y; } uint32_t size_z() const { return m_size_z; } magicavoxel_vox_t* _root() const { return m__root; } magicavoxel_vox_t::chunk_t* _parent() const { return m__parent; } }; class rgba_t : public kaitai::kstruct { public: rgba_t(kaitai::kstream* p__io, magicavoxel_vox_t::chunk_t* p__parent = 0, magicavoxel_vox_t* p__root = 0); private: void _read(); void _clean_up(); public: ~rgba_t(); private: std::vector<color_t*>* m_colors; magicavoxel_vox_t* m__root; magicavoxel_vox_t::chunk_t* m__parent; public: std::vector<color_t*>* colors() const { return m_colors; } magicavoxel_vox_t* _root() const { return m__root; } magicavoxel_vox_t::chunk_t* _parent() const { return m__parent; } }; class pack_t : public kaitai::kstruct { public: pack_t(kaitai::kstream* p__io, magicavoxel_vox_t::chunk_t* p__parent = 0, magicavoxel_vox_t* p__root = 0); private: void _read(); void _clean_up(); public: ~pack_t(); private: uint32_t m_num_models; magicavoxel_vox_t* m__root; magicavoxel_vox_t::chunk_t* m__parent; public: uint32_t num_models() const { return m_num_models; } magicavoxel_vox_t* _root() const { return m__root; } magicavoxel_vox_t::chunk_t* _parent() const { return m__parent; } }; class matt_t : public kaitai::kstruct { public: matt_t(kaitai::kstream* p__io, magicavoxel_vox_t::chunk_t* p__parent = 0, magicavoxel_vox_t* p__root = 0); private: void _read(); void _clean_up(); public: ~matt_t(); private: bool f_has_is_total_power; bool m_has_is_total_power; public: bool has_is_total_power(); private: bool f_has_plastic; bool m_has_plastic; public: bool has_plastic(); private: bool f_has_attenuation; bool m_has_attenuation; public: bool has_attenuation(); private: bool f_has_power; bool m_has_power; public: bool has_power(); private: bool f_has_roughness; bool m_has_roughness; public: bool has_roughness(); private: bool f_has_specular; bool m_has_specular; public: bool has_specular(); private: bool f_has_ior; bool m_has_ior; public: bool has_ior(); private: bool f_has_glow; bool m_has_glow; public: bool has_glow(); private: uint32_t m_id; material_type_t m_material_type; float m_material_weight; uint32_t m_property_bits; float m_plastic; bool n_plastic; public: bool _is_null_plastic() { plastic(); return n_plastic; }; private: float m_roughness; bool n_roughness; public: bool _is_null_roughness() { roughness(); return n_roughness; }; private: float m_specular; bool n_specular; public: bool _is_null_specular() { specular(); return n_specular; }; private: float m_ior; bool n_ior; public: bool _is_null_ior() { ior(); return n_ior; }; private: float m_attenuation; bool n_attenuation; public: bool _is_null_attenuation() { attenuation(); return n_attenuation; }; private: float m_power; bool n_power; public: bool _is_null_power() { power(); return n_power; }; private: float m_glow; bool n_glow; public: bool _is_null_glow() { glow(); return n_glow; }; private: float m_is_total_power; bool n_is_total_power; public: bool _is_null_is_total_power() { is_total_power(); return n_is_total_power; }; private: magicavoxel_vox_t* m__root; magicavoxel_vox_t::chunk_t* m__parent; public: uint32_t id() const { return m_id; } material_type_t material_type() const { return m_material_type; } float material_weight() const { return m_material_weight; } uint32_t property_bits() const { return m_property_bits; } float plastic() const { return m_plastic; } float roughness() const { return m_roughness; } float specular() const { return m_specular; } float ior() const { return m_ior; } float attenuation() const { return m_attenuation; } float power() const { return m_power; } float glow() const { return m_glow; } float is_total_power() const { return m_is_total_power; } magicavoxel_vox_t* _root() const { return m__root; } magicavoxel_vox_t::chunk_t* _parent() const { return m__parent; } }; class xyzi_t : public kaitai::kstruct { public: xyzi_t(kaitai::kstream* p__io, magicavoxel_vox_t::chunk_t* p__parent = 0, magicavoxel_vox_t* p__root = 0); private: void _read(); void _clean_up(); public: ~xyzi_t(); private: uint32_t m_num_voxels; std::vector<voxel_t*>* m_voxels; magicavoxel_vox_t* m__root; magicavoxel_vox_t::chunk_t* m__parent; public: uint32_t num_voxels() const { return m_num_voxels; } std::vector<voxel_t*>* voxels() const { return m_voxels; } magicavoxel_vox_t* _root() const { return m__root; } magicavoxel_vox_t::chunk_t* _parent() const { return m__parent; } }; class color_t : public kaitai::kstruct { public: color_t(kaitai::kstream* p__io, magicavoxel_vox_t::rgba_t* p__parent = 0, magicavoxel_vox_t* p__root = 0); private: void _read(); void _clean_up(); public: ~color_t(); private: uint8_t m_r; uint8_t m_g; uint8_t m_b; uint8_t m_a; magicavoxel_vox_t* m__root; magicavoxel_vox_t::rgba_t* m__parent; public: uint8_t r() const { return m_r; } uint8_t g() const { return m_g; } uint8_t b() const { return m_b; } uint8_t a() const { return m_a; } magicavoxel_vox_t* _root() const { return m__root; } magicavoxel_vox_t::rgba_t* _parent() const { return m__parent; } }; class voxel_t : public kaitai::kstruct { public: voxel_t(kaitai::kstream* p__io, magicavoxel_vox_t::xyzi_t* p__parent = 0, magicavoxel_vox_t* p__root = 0); private: void _read(); void _clean_up(); public: ~voxel_t(); private: uint8_t m_x; uint8_t m_y; uint8_t m_z; uint8_t m_color_index; magicavoxel_vox_t* m__root; magicavoxel_vox_t::xyzi_t* m__parent; public: uint8_t x() const { return m_x; } uint8_t y() const { return m_y; } uint8_t z() const { return m_z; } uint8_t color_index() const { return m_color_index; } magicavoxel_vox_t* _root() const { return m__root; } magicavoxel_vox_t::xyzi_t* _parent() const { return m__parent; } }; private: std::string m_magic; uint32_t m_version; chunk_t* m_main; magicavoxel_vox_t* m__root; kaitai::kstruct* m__parent; public: std::string magic() const { return m_magic; } /** * 150 expected */ uint32_t version() const { return m_version; } chunk_t* main() const { return m_main; } magicavoxel_vox_t* _root() const { return m__root; } kaitai::kstruct* _parent() const { return m__parent; } }; #endif // MAGICAVOXEL_VOX_H_
0.992188
high
code/SetVector.h
abidanBrito/set-class
0
918209
/* ------------------------------------------------------------------------ AUTHOR: <NAME> FILE: SetVector.h DATE: 20/01/2020 STATE: DONE FUNCTIONALITY: Set class definition (vector implementation). ------------------------------------------------------------------------ NOTICE: Copyright (c) 2020 <NAME>. ------------------------------------------------------------------------ */ // TODO(abi): Add extra functionalities, such as intersection, difference, // symmetric difference, etc. #ifndef SETVECTOR_H #define SETVECTOR_H #include <optional> // Required for std::optional and std::nullopt. #include <vector> // Required for std::vector. // --------------------------------------------------- // Set class definition. // --------------------------------------------------- class Set { private: std::vector<double> elements; // MEMBER FUNCTIONS - DECLARATIONS private: std::optional <unsigned int> at(double); // Returns index of a given element. public: unsigned int size() const; // Returns size of the set. void add(double element); // Adds a given element. void remove(double element); // Deletes a given element. void empty(); // Empties the set. bool within(double element) const; // Checks for a given element. bool isSubset(Set const & referenceSet) const; // Checks for a subset. bool isProperSubset(Set const & referenceSet) const; // Checks for a proper subset. Set join(Set const & anotherSet) const; // Concatenates two sets. Set complement(Set const & universalSet) const; // Complement, given a universal set. std::optional <double> meanValue() const; // Returns the average. void print() const; // Prints the set. void sort(); // Sorts using bubbleSort algorithm. }; #endif
0.996094
high
Pods/Target Support Files/Pods-CarDash/Pods-CarDash-umbrella.h
alexandreblin/ios-car-dashboard
43
918721
#import <UIKit/UIKit.h> FOUNDATION_EXPORT double Pods_CarDashVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_CarDashVersionString[];
0.894531
low
CopperEngine/src/Copper/Core/Application.h
vanCopper/CopperEngine
0
919233
<reponame>vanCopper/CopperEngine #pragma once #include "Core.h" #include "Window.h" #include "Copper/Events/Event.h" #include "Copper/Events/ApplicationEvent.h" #include "Copper/Core/LayerStack.h" namespace CopperEngine { class COPPER_API Application { public: Application(); virtual ~Application(); void Run(); void OnEvent(Event& event); void PushLayer(Layer* layer); void PushOverlay(Layer* layer); Window& GetWindow() { return *m_Window; } static Application& Get() { return *s_Instance; } private: std::unique_ptr<Window> m_Window; LayerStack m_LayerStack; bool m_Running = true; bool OnWindowClose(WindowCloseEvent& event); private: static Application* s_Instance; }; //To be defined in CLINET. Application* CreateApplication(); }
0.984375
high
UnrealEngine-4.11.2-release/Engine/Source/Editor/HierarchicalLODOutliner/Private/HLODOutlinerDragDrop.h
armroyce/Unreal
1
919745
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #pragma once #include "HierarchicalLODOutlinerPrivatePCH.h" #include "ActorDragDropGraphEdOp.h" class ALODActor; namespace HLODOutliner { struct ITreeItem; typedef TSharedPtr<ITreeItem> FTreeItemPtr; /** Consilidated drag/drop information parsed for the HLOD outliner */ struct FDragDropPayload { /** Default constructor, resulting in unset contents */ FDragDropPayload(); /** Populate this payload from an array of tree items */ template<typename TItem> FDragDropPayload(const TArray<TItem>& InDraggedItems) { for (const auto& Item : InDraggedItems) { Item->PopulateDragDropPayload(*this); } } /** Optional array of dragged LOD actors */ TOptional<TArray<TWeakObjectPtr<AActor>>> LODActors; /** OPtional array of dragged static mesh actors */ TOptional<TArray<TWeakObjectPtr<AActor>>> StaticMeshActors; /** Flag whether or not this is a drop coming from the SceneOutliner or within the HLOD Outliner */ bool bSceneOutliner; /** World instance that is being used for the HLOD Outliner */ UWorld* OutlinerWorld; /** * Parse a drag operation into our list of actors and folders * @return true if the operation is viable for the HLOD outliner to process, false otherwise */ bool ParseDrag(const FDragDropOperation& Operation); }; /** Construct a new Drag and drop operation for a scene outliner */ TSharedPtr<FDragDropOperation> CreateDragDropOperation(const TArray<FTreeItemPtr>& InTreeItems); /** A drag/drop operation that was started from the scene outliner */ struct FHLODOutlinerDragDropOp : public FDragDropOperation { enum ToolTipTextType { ToolTip_Compatible, ToolTip_Incompatible, ToolTip_MultipleSelection_Compatible, ToolTip_MultipleSelection_Incompatible, ToolTip_CompatibleMoveToCluster, ToolTip_MultipleSelection_CompatibleMoveToCluster, ToolTip_CompatibleAddToCluster, ToolTip_MultipleSelection_CompatibleAddToCluster, ToolTip_CompatibleMergeCluster, ToolTip_MultipleSelection_CompatibleMergeClusters, ToolTip_CompatibleChildCluster, ToolTip_MultipleSelection_CompatibleChildClusters, ToolTip_CompatibleNewCluster, ToolTip_MultipleSelection_CompatibleNewCluster }; DRAG_DROP_OPERATOR_TYPE(FHLODOutlinerDragDropOp, FDragDropOperation); FHLODOutlinerDragDropOp(const FDragDropPayload& DraggedObjects); using FDragDropOperation::Construct; /** Actor drag operation */ TSharedPtr<FActorDragDropOp> StaticMeshActorOp; TSharedPtr<FActorDragDropOp> LODActorOp; void ResetTooltip() { OverrideText = FText(); OverrideIcon = nullptr; } void SetTooltip(FText InOverrideText, const FSlateBrush* InOverrideIcon) { OverrideText = InOverrideText; OverrideIcon = InOverrideIcon; } virtual TSharedPtr<SWidget> GetDefaultDecorator() const override; private: EVisibility GetOverrideVisibility() const; EVisibility GetDefaultVisibility() const; FText OverrideText; FText GetOverrideText() const { return OverrideText; } const FSlateBrush* OverrideIcon; const FSlateBrush* GetOverrideIcon() const { return OverrideIcon; } }; /** Struct used for validation of a drag/drop operation in the scene outliner */ struct FDragValidationInfo { /** The tooltip type to display on the operation */ FHLODOutlinerDragDropOp::ToolTipTextType TooltipType; /** The tooltip text to display on the operation */ FText ValidationText; /** Construct this validation information out of a tooltip type and some text */ FDragValidationInfo(const FHLODOutlinerDragDropOp::ToolTipTextType InTooltipType, const FText InValidationText) : TooltipType(InTooltipType) , ValidationText(InValidationText) {} /** Return a generic invalid result */ static FDragValidationInfo Invalid() { return FDragValidationInfo(FHLODOutlinerDragDropOp::ToolTip_Incompatible, FText()); } /** @return true if this operation is valid, false otherwise */ bool IsValid() const { switch (TooltipType) { case FHLODOutlinerDragDropOp::ToolTip_Compatible: case FHLODOutlinerDragDropOp::ToolTip_MultipleSelection_Compatible: case FHLODOutlinerDragDropOp::ToolTip_CompatibleMoveToCluster: case FHLODOutlinerDragDropOp::ToolTip_MultipleSelection_CompatibleMoveToCluster: case FHLODOutlinerDragDropOp::ToolTip_CompatibleAddToCluster: case FHLODOutlinerDragDropOp::ToolTip_MultipleSelection_CompatibleAddToCluster: case FHLODOutlinerDragDropOp::ToolTip_CompatibleMergeCluster: case FHLODOutlinerDragDropOp::ToolTip_MultipleSelection_CompatibleMergeClusters: case FHLODOutlinerDragDropOp::ToolTip_CompatibleChildCluster: case FHLODOutlinerDragDropOp::ToolTip_MultipleSelection_CompatibleChildClusters: case FHLODOutlinerDragDropOp::ToolTip_CompatibleNewCluster: case FHLODOutlinerDragDropOp::ToolTip_MultipleSelection_CompatibleNewCluster: return true; default: return false; } } }; };
0.996094
high
System/Library/PrivateFrameworks/RemoteManagement.framework/RMAskForTimeInterface.h
lechium/iPhoneOS_12.1.1_Headers
12
920257
/* * This header is generated by classdump-dyld 1.0 * on Saturday, June 1, 2019 at 6:52:57 PM Mountain Standard Time * Operating System: Version 12.1.1 (Build 16C5050a) * Image Source: /System/Library/PrivateFrameworks/RemoteManagement.framework/RemoteManagement * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ @protocol RMAskForTimeInterface <NSObject> @required -(void)sendAskForTimeRequest:(id)arg1 completionHandler:(/*^block*/id)arg2; -(void)approveExceptionForRequest:(id)arg1 completionHandler:(/*^block*/id)arg2; -(void)fetchLastResponseForRequestedResourceIdentifier:(id)arg1 usageType:(long long)arg2 withCompletionHandler:(/*^block*/id)arg3; -(void)handleAnswer:(long long)arg1 requestIdentifier:(id)arg2 timeApproved:(id)arg3 completionHandler:(/*^block*/id)arg4; @end
0.644531
high
llvm-gcc-4.2-2.9/gcc/testsuite/gcc.dg/ucnid-1.c
vidkidz/crossbridge
1
920769
<reponame>vidkidz/crossbridge /* { dg-do run } */ /* { dg-options "-std=c99 -fextended-identifiers" } */ void abort (void); int main (void) { int \u00C0 = 1; int \u00C1 = 2; int \U000000C2 = 3; int wh\u00ff = 4; int a\u00c4b\u0441\U000003b4e = 5; if (\u00C0 != 1) abort (); if (\u00c1 != 2) abort (); if (\u00C2 != 3) abort (); if (wh\u00ff != 4) abort (); if (a\u00c4b\u0441\U000003b4e != 5) abort (); return 0; }
0.730469
high
src/forms/SystemLog.h
SSBMTonberry/loggery
0
921281
<gh_stars>0 // // Created by robin on 30.08.18. // #ifndef LOGGERY_SYSTEMLOG_H #define LOGGERY_SYSTEMLOG_H #include <string> #include <chrono> #include "fmt/format.h" #include "fmt/time.h" #include "../classes/Color.hpp" #include "../gui/Text.h" #include "../gui/Textbox.h" namespace ly { class SystemLog { public: static SystemLog *get() { static SystemLog log; return &log; } bool process(); void add(const std::string &text, const ImVec4 &color = {255, 255, 255, 255}); void addSuccess(const std::string &text, bool useTimestamp = true); void addInfo(const std::string &text, bool useTimestamp = true); void addWarning(const std::string &text, bool useTimestamp = true); void addError(const std::string &text, bool useTimestamp = true); void clear(); const std::string ID = "System log###666"; const ImVec4 SuccessColor {(float)0/255, (float)182/255, (float)0/255, (float)255/255}; const ImVec4 InfoColor{(float)146/255, (float)182/255, (float)255/255, (float)255/255}; const ImVec4 WarningColor {(float)255/255, (float)219/255, (float)0/255, (float)255/255}; const ImVec4 ErrorColor {(float)240/255, (float)0/255, (float)0/255, (float)255/255}; protected: std::string getTimestamp(bool includeDate = false); std::vector<ly::Text> getFilteredTexts(const std::string_view &filter); //std::string m_id; ImVec2 m_sizeOnFirstUse; bool m_isVisible = true; Textbox m_filter = {"filter"}; std::vector<ly::Text> m_filteredTexts; std::vector<ly::Text> m_texts; private: explicit SystemLog(const ImVec2 &sizeOnFirstUse = {640, 480}); }; } #endif //LOGGERY_SYSTEMLOG_H
0.984375
high
tests/com.oracle.truffle.llvm.tests.interop/interop/interop060.c
pointhi/sulong
1
921793
<filename>tests/com.oracle.truffle.llvm.tests.interop/interop/interop060.c<gh_stars>1-10 #include <polyglot.h> typedef void *VALUE; struct Foreign { VALUE a; VALUE b; }; int main() { struct Foreign *foreign = polyglot_import("foreign"); if ((int) foreign->a != 0) { return 100 + (int) foreign->a; } if ((int) foreign->b != 1) { return 200 + (int) foreign->b; } foreign->a = 101; foreign->b = 102; return 0; }
0.671875
high
MPU9250.h
gr82morozr/MPU9250
0
922305
/****************************************************************************** MPU9250.h - MPU-9250 Digital Motion Processor Arduino Library - This is wrapper package of SparkFun_MPU9250_Arduino_Library - Modified for ESP32 (tested on ) ******************************************************************************/ #ifndef _GT_MPU9250_H_ #define _GT_MPU9250_H_ #include <Arduino.h> #include <Wire.h> #include <MPU9250_RegisterMap.h> #include <MPU9250_Common.h> // Include the Invensense MPU9250 driver and DMP keys: extern "C" { #include "util/inv_mpu.h" #include "util/inv_mpu_dmp_motion_driver.h" #include "util/inv_mpu.h" } class MPU9250 { public: int ax, ay, az; // raw data read from register int gx, gy, gz; // raw data read from register int mx, my, mz; // raw data read from register long qw, qx, qy, qz; long temperature; unsigned long time; float pitch, roll, yaw; float heading; float aX, aY, aZ; // real data calculated with scale factor from raw data float gX, gY, gZ; // real data calculated with scale factor from raw data float mX, mY, mZ; // real data calculated with scale factor from raw data float aX_offset, aY_offset, aZ_offset ; // accelerometer offset values float gX_offset, gY_offset, gZ_offset ; // gyroscope offset values float mX_offset, mY_offset, mZ_offset ; // magnetometer offset values MPU9250(); // begin(void) -- Verifies communication with the MPU-9250 and the AK8963, // and initializes them to the default state: // All sensors enabled // Gyro FSR: +/- 2000 dps // Accel FSR: +/- 2g // LPF: 42 Hz // FIFO: 50 Hz, disabled // Output: INT_SUCCESS (0) on success, otherwise error int_return_t begin(int sda_pin, int scl_pin); int_return_t begin(); // with default sda=21,scl=22 pin of ESP32 // set_sensors(unsigned char) -- Turn on or off MPU-9250 sensors. Any of the // following defines can be combined: INV_XYZ_GYRO, INV_XYZ_ACCEL, // INV_XYZ_COMPASS, INV_X_GYRO, INV_Y_GYRO, or INV_Z_GYRO // Input: Combination of enabled sensors. // Unless specified a sensor will be disabled. // Output: INT_SUCCESS (0) on success, otherwise error int_return_t set_sensors(unsigned char sensors); // set_gyro_scale(unsigned short) -- Sets the full-scale range of the gyroscope // Input: Gyro DPS - 250, 500, 1000, or 2000 // Output: INT_SUCCESS (0) on success, otherwise error int_return_t set_gyro_scale(unsigned short fsr); // get_gyro_scale -- Returns the current gyroscope FSR // Output: Current Gyro DPS - 250, 500, 1000, or 2000 unsigned short get_gyro_scale(void); // get_gyro_sensitivity -- Returns current gyroscope sensitivity. The FSR divided by // the resolution of the sensor (signed 16-bit). // Output: Currently set gyroscope sensitivity (e.g. 131, 65.5, 32.8, 16.4) float get_gyro_sensitivity(void); // set_accel_scale(unsigned short) -- Sets the FSR of the accelerometer // // Input: Accel g range - 2, 4, 8, or 16 // Output: INT_SUCCESS (0) on success, otherwise error int_return_t set_accel_scale(unsigned char fsr); // get_accel_scale -- Returns the current accelerometer FSR // Output: Current Accel g - 2, 4, 8, or 16 unsigned char get_accel_scale(void); // get_accel_sensitivity -- Returns current accelerometer sensitivity. The FSR // divided by the resolution of the sensor (signed 16-bit). // Output: Currently set accel sensitivity (e.g. 16384, 8192, 4096, 2048) unsigned short get_accel_sensitivity(void); // get_mag_scale -- Returns the current magnetometer FSR // Output: Current mag uT range - +/-1450 uT unsigned short get_mag_scale(void); // get_mag_sensitivity -- Returns current magnetometer sensitivity. The FSR // divided by the resolution of the sensor (signed 16-bit). // Output: Currently set mag sensitivity (e.g. 0.15) float get_mag_sensitivity(void); // setLPF -- Sets the digital low-pass filter of the accel and gyro. // Can be any of the following: 188, 98, 42, 20, 10, 5 (value in Hz) // Input: 188, 98, 42, 20, 10, or 5 (defaults to 5 if incorrectly set) // Output: INT_SUCCESS (0) on success, otherwise error int_return_t setLPF(unsigned short lpf); // getLPF -- Returns the set value of the LPF. // Output: 5, 10, 20, 42, 98, or 188 if set. 0 if the LPF is disabled. unsigned short getLPF(void); // set_sample_rate -- Set the gyroscope and accelerometer sample rate to a // value between 4Hz and 1000Hz (1kHz). // The library will make an attempt to get as close as possible to the // requested sample rate. // Input: Value between 4 and 1000, indicating the desired sample rate // Output: INT_SUCCESS (0) on success, otherwise error int_return_t set_sample_rate(unsigned short rate); // get_sample_rate -- Get the currently set sample rate. // May differ slightly from what was set in set_sample_rate. // Output: set sample rate of the accel/gyro. A value between 4-1000. unsigned short get_sample_rate(void); // set_mag_sample_rate -- Set the magnetometer sample rate to a value // between 1Hz and 100 Hz. // The library will make an attempt to get as close as possible to the // requested sample rate. // Input: Value between 1 and 100, indicating the desired sample rate // Output: INT_SUCCESS (0) on success, otherwise error int_return_t set_mag_sample_rate(unsigned short rate); // get_mag_sample_rate -- Get the currently set magnetometer sample rate. // May differ slightly from what was set in set_mag_sample_rate. // // Output: set sample rate of the magnetometer. A value between 1-100 unsigned short get_mag_sample_rate(void); // is_data_ready -- checks to see if new accel/gyro data is available. // (New magnetometer data cannot be checked, as the library runs that sensor // in single-conversion mode.) // Output: true if new accel/gyro data is available bool is_data_ready(); // update -- Reads latest data from the MPU-9250's data registers. // Sensors to be updated can be set using the [sensors] parameter. // [sensors] can be any combination of UPDATE_ACCEL, UPDATE_GYRO, // UPDATE_COMPASS, and UPDATE_TEMP. // Output: INT_SUCCESS (0) on success, otherwise error // Note: after a successful update the public sensor variables // (e.g. ax, ay, az, gx, gy, gz) will be updated with new data int_return_t update(unsigned char sensors = UPDATE_ACCEL | UPDATE_GYRO | UPDATE_COMPASS); // update_accel, update_gyro, update_mag, and update_temp are // called by the update() public method. They read from their respective // sensor and update the class variable (e.g. ax, ay, az) // Output: INT_SUCCESS (0) on success, otherwise error int_return_t update_accel(void); int_return_t update_gyro(void); int_return_t update_mag(void); int_return_t update_temp(void); // config_fifo(unsigned char) -- Initialize the FIFO, set it to read from // a select set of sensors. // Any of the following defines can be combined for the [sensors] parameter: // INV_XYZ_GYRO, INV_XYZ_ACCEL, INV_X_GYRO, INV_Y_GYRO, or INV_Z_GYRO // Input: Combination of sensors to be read into FIFO // Output: INT_SUCCESS (0) on success, otherwise error int_return_t config_fifo(unsigned char sensors); // get_fifo_config -- Returns the sensors configured to be read into the FIFO // Output: combination of INV_XYZ_GYRO, INV_XYZ_ACCEL, INV_Y_GYRO, // INV_X_GYRO, or INV_Z_GYRO unsigned char get_fifo_config(void); // get_fifo_available -- Returns the number of bytes currently filled in the FIFO // Outputs: Number of bytes filled in the FIFO (up to 512) unsigned short get_fifo_available(void); // update_fifo -- Reads from the top of the FIFO, and stores the new data // in ax, ay, az, gx, gy, or gz (depending on how the FIFO is configured). // Output: INT_SUCCESS (0) on success, otherwise error int_return_t update_fifo(void); // reset_fifo -- Resets the FIFO's read/write pointers // Output: INT_SUCCESS (0) on success, otherwise error int_return_t reset_fifo(void); // enable_interrupt -- Configure the MPU-9250's interrupt output to indicate // when new data is ready. // Input: 0 to disable, >=1 to enable // Output: INT_SUCCESS (0) on success, otherwise error int_return_t enable_interrupt(unsigned char enable = 1); // set_interrupt_level -- Configure the MPU-9250's interrupt to be either active- // high or active-low. // Input: 0 for active-high, 1 for active-low // Output: INT_SUCCESS (0) on success, otherwise error int_return_t set_interrupt_level(unsigned char active_low); // set_int_latched -- Configure the MPU-9250's interrupt to latch or operate // as a 50us pulse. // Input: 0 for // Output: INT_SUCCESS (0) on success, otherwise error int_return_t set_int_latched(unsigned char enable); // get_int_status -- Reads the MPU-9250's INT_STATUS register, which can // indicate what (if anything) caused an interrupt (e.g. FIFO overflow or // or data read). // Output: contents of the INT_STATUS register short get_int_status(void); // begin_dmp -- Initialize the DMP, enable one or more features, and set the FIFO's sample rate // features can be any one of // DMP_FEATURE_TAP -- Tap detection // DMP_FEATURE_ANDROID_ORIENT -- Orientation (portrait/landscape) detection // DMP_FEATURE_LP_QUAT -- Accelerometer, low-power quaternion calculation // DMP_FEATURE_PEDOMETER -- Pedometer (always enabled) // DMP_FEATURE_6X_LP_QUAT -- 6-axis (accel/gyro) quaternion calculation // DMP_FEATURE_GYRO_CAL -- Gyroscope calibration (0's out after 8 seconds of no motion) // DMP_FEATURE_SEND_RAW_ACCEL -- Send raw accelerometer values to FIFO // DMP_FEATURE_SEND_RAW_GYRO -- Send raw gyroscope values to FIFO // DMP_FEATURE_SEND_CAL_GYRO -- Send calibrated gyroscop values to FIFO // fifoRate can be anywhere between 4 and 200Hz. // Input: OR'd list of features and requested FIFO sampling rate // Output: INT_SUCCESS (0) on success, otherwise error int_return_t begin_dmp(unsigned short features = 0, unsigned short fifoRate = MAX_DMP_SAMPLE_RATE); // get_dmp_fifo_rate -- Returns the sample rate of the FIFO // Output: Set sample rate, in Hz, of the FIFO unsigned short get_dmp_fifo_rate(void); // set_dmp_fifo_rate -- Sets the rate of the FIFO. // Input: Requested sample rate in Hz (range: 4-200) // Output: INT_SUCCESS (0) on success, otherwise error int_return_t set_dmp_fifo_rate(unsigned short rate); // update_dmp_fifo -- Reads from the top of the FIFO and fills accelerometer, gyroscope, // quaternion, and time public variables (depending on how the DMP is configured). // Should be called whenever an MPU interrupt is detected // Once read sucess, ax, ay, az // Output: INT_SUCCESS (0) on success, otherwise error // int_return_t update_dmp_fifo(void); // enable_dmp_features -- Enable one, or multiple DMP features. // Input: An OR'd list of features (see begin_dmp) // Output: INT_SUCCESS (0) on success, otherwise error int_return_t enable_dmp_features(unsigned short mask); // get_dmp_features -- Returns the OR'd list of enabled DMP features // // Output: OR'd list of DMP feature's (see begin_dmp for list) unsigned short get_dmp_features(void); // set_dmp_tap -- Enable tap detection and configure threshold, tap time, and minimum tap count. // Inputs: x/y/zThresh - accelerometer threshold on each axis. Range: 0 to 1600. 0 disables tap // detection on that axis. Units are mg/ms. // taps - minimum number of taps to create a tap event (Range: 1-4) // tapTime - Minimum number of milliseconds between separate taps // tapMulti - Maximum number of milliseconds combined taps // Output: INT_SUCCESS (0) on success, otherwise error int_return_t set_dmp_tap(unsigned short xThresh = 250, unsigned short yThresh = 250, unsigned short zThresh = 250, unsigned char taps = 1, unsigned short tapTime = 100, unsigned short tapMulti = 500); // is_dmp_tap_available -- Returns true if a new tap is available // Output: True if new tap data is available. Cleared on get_dmp_tap_dir or get_dmp_tap_count. bool is_dmp_tap_available(void); // get_dmp_tap_dir -- Returns the tap direction. // Output: One of the following: TAP_X_UP, TAP_X_DOWN, TAP_Y_UP, TAP_Y_DOWN, TAP_Z_UP, // or TAP_Z_DOWN unsigned char get_dmp_tap_dir(void); // get_dmp_tap_count -- Returns the number of taps in the sensed direction // Output: Value between 1-8 indicating successive number of taps sensed. unsigned char get_dmp_tap_count(void); // set_dmp_orientation -- Set orientation matrix, used for orientation sensing. // Use default_orientation matrix as an example input. // Input: Gyro and accel orientation in body frame (9-byte array) // Output: INT_SUCCESS (0) on success, otherwise error int_return_t set_dmp_orientation(const signed char * orientationMatrix = default_orientation); // get_dmp_orientation -- Get the orientation, if any. // Output: If an orientation is detected, // one of ORIENT_LANDSCAPE // ORIENT_PORTRAIT, // ORIENT_REVERSE_LANDSCAPE // ORIENT_REVERSE_PORTRAIT unsigned char get_dmp_orientation(void); // enable_dmp_3quat -- Enable 3-axis quaternion calculation // Output: INT_SUCCESS (0) on success, otherwise error int_return_t enable_dmp_3quat(void); // enable_dmp_6quat -- Enable 6-axis quaternion calculation // Output: INT_SUCCESS (0) on success, otherwise error int_return_t enable_dmp_6quat(void); // get_dmp_pedometer_steps -- Get number of steps in pedometer register // Output: Number of steps sensed unsigned long get_dmp_pedometer_steps(void); // set_dmp_pedometer_steps -- Set number of steps to a value // Input: Desired number of steps to begin incrementing from // Output: INT_SUCCESS (0) on success, otherwise error int_return_t set_dmp_pedometer_steps(unsigned long steps); // get_dmp_pedometer_time -- Get number of milliseconds ellapsed over stepping // Output: Number of milliseconds where steps were detected unsigned long get_dmp_pedometer_time(void); // set_dmp_pedometer_time -- Set number time to begin incrementing step time counter from // Input: Desired number of milliseconds // Output: INT_SUCCESS (0) on success, otherwise error int_return_t set_dmp_pedometer_time(unsigned long time); // set_dmp_int_mode -- // Output: INT_SUCCESS (0) on success, otherwise error int_return_t set_dmp_int_mode(unsigned char mode); // set_gyro_bias -- // Output: INT_SUCCESS (0) on success, otherwise error int_return_t set_gyro_bias(long * bias); // set_accel_bias -- // Output: INT_SUCCESS (0) on success, otherwise error int_return_t set_accel_bias(long * bias); // lowPowerAccel -- // Output: INT_SUCCESS (0) on success, otherwise error // Accelerometer Low-Power Mode. Rate options: // 1.25 (1), 2.5 (2), 5, 10, 20, 40, // 80, 160, 320, or 640 Hz // Disables compass and gyro int_return_t lowPowerAccel(unsigned short rate); // calc_accel -- Convert 16-bit signed acceleration value to g's float calc_accel(int axis); // calc_gyro -- Convert 16-bit signed gyroscope value to degree's per second float calc_gyro(int axis); // calc_mag -- Convert 16-bit signed magnetometer value to microtesla (uT) float calc_mag(int axis); // calc_quat -- Convert Q30-format quaternion to a vector between +/- 1 float calc_quat(long axis); // calc_euler_angles -- Compute euler angles based on most recently read qw, qx, qy, and qz // Input: boolean indicating whether angle results are presented in degrees or radians // Output: class variables roll, pitch, and yaw will be updated on exit. void calc_euler_angles(bool degrees = true); // calc_mag_heading -- Compute heading based on most recently read mx, my, and mz values // Output: class variable heading will be updated on exit float calc_mag_heading(void); // run_self_test -- Run gyro and accel self-test. // Output: Returns bit mask, 1 indicates success. A 0x7 is success on all sensors. // Bit pos 0: gyro // Bit pos 1: accel // Bit pos 2: mag int run_self_test(unsigned char debug = 0); // calibration of the sensors int_return_t cal_sensors(); int_return_t cal_mag(); private: unsigned short _accel_sensitivity; float _gyro_sensitivity, _mag_sensitivity; // Convert a QN-format number to a float float qn_fmt_2_float(long number, unsigned char q); unsigned short orientation_row_2_scale(const signed char *row); // load_dmp_image -- Loads the DMP with 3062-byte image memory. Must be called to begin DMP. // This function is called by the begin_dmp function. // Output: INT_SUCCESS (0) on success, otherwise error int_return_t load_dmp_image(void); }; #endif // _GT_MPU9250_H_
0.996094
high
CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/java/awt/CheckboxMenuItem.h
chewaiwai/huaweicloud-sdk-c-obs
22
922817
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*- #ifndef __java_awt_CheckboxMenuItem__ #define __java_awt_CheckboxMenuItem__ #pragma interface #include <java/awt/MenuItem.h> #include <gcj/array.h> extern "Java" { namespace java { namespace awt { class AWTEvent; class CheckboxMenuItem; namespace event { class ItemEvent; class ItemListener; } } } namespace javax { namespace accessibility { class AccessibleContext; } } } class java::awt::CheckboxMenuItem : public ::java::awt::MenuItem { public: CheckboxMenuItem(); CheckboxMenuItem(::java::lang::String *); CheckboxMenuItem(::java::lang::String *, jboolean); virtual jboolean getState(); virtual void setState(jboolean); virtual JArray< ::java::lang::Object * > * getSelectedObjects(); virtual void addNotify(); virtual void addItemListener(::java::awt::event::ItemListener *); virtual void removeItemListener(::java::awt::event::ItemListener *); public: // actually protected virtual void processEvent(::java::awt::AWTEvent *); virtual void processItemEvent(::java::awt::event::ItemEvent *); public: // actually package-private virtual void dispatchEventImpl(::java::awt::AWTEvent *); public: virtual ::java::lang::String * paramString(); virtual JArray< ::java::util::EventListener * > * getListeners(::java::lang::Class *); virtual JArray< ::java::awt::event::ItemListener * > * getItemListeners(); virtual ::javax::accessibility::AccessibleContext * getAccessibleContext(); public: // actually package-private virtual ::java::lang::String * generateName(); private: static jlong getUniqueLong(); static jlong next_chkmenuitem_number; static const jlong serialVersionUID = 6190621106981774043LL; jboolean __attribute__((aligned(__alignof__( ::java::awt::MenuItem)))) state; ::java::awt::event::ItemListener * item_listeners; public: static ::java::lang::Class class$; }; #endif // __java_awt_CheckboxMenuItem__
0.984375
high
Assignment 11/Member.h
tomy0000000/YZU-Computer-Programming-II
1
923329
// // Member.h // Hw 11 // Object Oriented Vieshow Cinemas Taipei QSquare system // // Created by <NAME> on 2018/6/3. // Copyright © 2018年 <NAME>. All rights reserved. // #ifndef Member_h #define Member_h #include <string> using std::string; class Member { public: Member(string theEmail = "", string thePassword = "", string theIdNumber = "", string theName = "", string thePhone = ""); string getEmail(); string getPassword(); string getIdNumber(); string getName(); string getPhone(); void setEmail(string theEmail); void setPassword(string thePassword); void setIdNumber(string theIdNumber); void setName(string theName); void setPhone(string thePhone); // Display details of the member void display(); private: char email[40]; char password[24]; char idNumber[12]; char name[12]; char phone[12]; }; #endif
0.964844
high
cli_notify.c
perj/movactl
1
923841
<reponame>perj/movactl<filename>cli_notify.c<gh_stars>1-10 /* * Copyright (c) 2008, 2011 <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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. */ #include <stdio.h> #include <stdlib.h> #include <err.h> #include <string.h> #include <sys/queue.h> #include <sys/uio.h> #include <unistd.h> #include <event.h> #include <syslog.h> #include "cli.h" #include "base64.h" #include "complete.h" typedef void (*notify_cb_t)(int fd, const char *name, const char *code, const char *arg, size_t len); struct notify_data { TAILQ_ENTRY(notify_data) link; const char *name; const char *code; notify_cb_t cb; int once; }; TAILQ_HEAD(, notify_data) notifies = TAILQ_HEAD_INITIALIZER(notifies); static void start_notify(int fd, const char *name, const char *code, notify_cb_t cb, int once) { struct notify_data *data = malloc(sizeof (*data)); struct iovec vecs[3]; if (!data) err(1, "malloc"); data->name = name; data->code = code; data->cb = cb; data->once = once; TAILQ_INSERT_TAIL(&notifies, data, link); vecs[0].iov_base = (void*)"STRT"; vecs[0].iov_len = 4; vecs[1].iov_base = (void*)code; vecs[1].iov_len = 4; vecs[2].iov_base = (void*)"\n"; vecs[2].iov_len = 1; if (writev(fd, vecs, 3) == -1) err(1, "writev"); } static void stop_notify(int fd, struct notify_data *data) { struct notify_data *d; TAILQ_REMOVE(&notifies, data, link); TAILQ_FOREACH(d, &notifies, link) { if (strcmp(d->code, data->code) == 0) break; } if (!d) { struct iovec vecs[3]; vecs[0].iov_base = (void*)"STOP"; vecs[0].iov_len = 4; vecs[1].iov_base = (void*)data->code; vecs[1].iov_len = 4; vecs[2].iov_base = (void*)"\n"; vecs[2].iov_len = 1; if (writev(fd, vecs, 3) == -1) err(1, "writev"); } free(data); } #define ESTART(type) \ void notify_ ## type ## _cb (int fd, const char *n, const char *code, const char *val, size_t len) { \ if (len != 4) \ return; \ \ int v = debase64_int24(val); \ switch (v) { #define EV(type, name, val) \ case val: \ printf("%s " #name "\n", n); \ fflush(stdout); \ break; #define EEND(type) \ default: \ printf("%s unknown:0x%x\n", n, v); \ fflush(stdout); \ } \ } #include "status_enums.h" #undef ESTART #undef EV #undef EEND void notify_int_cb (int fd, const char *n, const char *code, const char *val, size_t len) { if (len != 4) return; printf ("%s %d\n", n, debase64_int24(val)); fflush(stdout); } void notify_string_cb (int fd, const char *n, const char *code, const char *val, size_t len) { printf ("%s %.*s\n", n, (int)len, val); fflush(stdout); } struct notify_code { const char *name; const char *code; notify_cb_t cb; } notify_codes[] = { #define NOTIFY(name, code, type) { #name, code, notify_ ## type ## _cb }, #define STATUS(name, code, type) { #name, code, notify_ ## type ## _cb }, #include "all_notify.h" #undef NOTIFY #undef STATUS { NULL } }; static int filter_notifies (int fd, struct complete_candidate **cands) { struct complete_candidate *cand, **pcand; struct evbuffer *buf = evbuffer_new(); char *line; evbuffer_add(buf, "QSTS", 4); for (cand = *cands ; cand ; cand = cand->next) evbuffer_add(buf, ((struct notify_code*)cand->aux)->code, 4); //syslog(LOG_DEBUG, "QSTS fd: %d query: %.*s", fd, (int)EVBUFFER_LENGTH(buf), EVBUFFER_DATA(buf)); evbuffer_add(buf, "\n", 1); write (fd, EVBUFFER_DATA(buf), EVBUFFER_LENGTH(buf)); evbuffer_drain(buf, EVBUFFER_LENGTH(buf)); while (!(line = evbuffer_readline(buf))) evbuffer_read(buf, fd, 1024); if (strncmp(line, "EDIS", 4) == 0) return 1; if (strncmp(line, "QSTS", 4) != 0) errx(1, "Unexpected reply, not QSTS: %s", line); line += 4; /* Reply should be in same order as query. */ pcand = cands; while ((cand = *pcand)) { if (strncmp(((struct notify_code*)cand->aux)->code, line, 4) == 0) { pcand = &cand->next; line += 4; } else { *pcand = cand->next; free(cand); } } return 0; } int cli_notify (int fd, int argc, char *argv[], int once) { int num = 0; struct evbuffer *data; struct complete_candidate *candidates = NULL, *cand; struct notify_code *nc; int argi = 0; do { candidates = NULL; for (nc = notify_codes ; nc->name ; nc++) { cand = malloc (sizeof (*cand)); if (!cand) err (1, "malloc"); cand->name = nc->name; cand->name_off = 0; cand->next = candidates; cand->aux = nc; candidates = cand; } //syslog(LOG_DEBUG, "complete at %d '%s'", argi, argv[argi]); argi += complete(&candidates, argc - argi, (const char**)argv + argi, (void(*)(struct complete_candidate*))free); //syslog(LOG_DEBUG, "after complete at %d '%s'", argi, argv[argi]); if (candidates) { if (filter_notifies(fd, &candidates)) errx(1, "server disabled"); } if (!candidates) errx (1, "No matching notification"); if (candidates->next) { fprintf (stderr, "Multiple matches:\n"); for (cand = candidates; cand; cand = cand->next) { fprintf (stderr, "%s\n", cand->name); } return 1; } nc = candidates->aux; start_notify(fd, nc->name, nc->code, nc->cb, once); num++; free(candidates); } while (argi < argc); data = evbuffer_new(); while (!TAILQ_EMPTY(&notifies)) { int res = evbuffer_read(data, fd, 1024); char *line; if (res < 0) err (1, "evbuffer_read"); if (res == 0) errx (1, "EOF"); while ((line = evbuffer_readline(data))) { int len = strlen(line); if (len >= 8 && strncmp(line, "STAT", 4) == 0) { const char *l = line + 4; const char *v = line + 8; struct notify_data *d; TAILQ_FOREACH(d, &notifies, link) { if (strncmp(l, d->code, 4) == 0) { d->cb(fd, d->name, d->code, v, len - 8); if (d->once) { stop_notify(fd, d); break; /* XXX multiple with same code? */ } } } } } } return 0; }
0.996094
high
src/gui/gnuplot.h
Abhisheknishant/Flint
9
924353
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */ #ifndef FLINT_GUI_GNUPLOT_H_ #define FLINT_GUI_GNUPLOT_H_ #include <iostream> #include <map> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-qual" #include <wx/wx.h> #pragma GCC diagnostic pop namespace flint { namespace gui { struct LineGraphOption { std::map<unsigned int, wxString> input_files; unsigned int num_variables; unsigned int skip; int x; std::map<unsigned int, wxString> y1; std::map<unsigned int, wxString> y2; bool legend; bool log_x; bool log_y1; bool log_y2; }; struct DpsGraphOption { wxString dps_path; unsigned int num_variables; unsigned int skip; std::map<unsigned int, unsigned int> m; }; bool PlotLineGraph(const LineGraphOption &option, const DpsGraphOption *dgo, std::ostream &os); } } #endif
0.675781
high
notify_test2.c
jrepp/craftsman_console
0
924865
<filename>notify_test2.c #include <stdio.h> #include "notify.h" void change_event(int idx, const struct inotify_event *ev) { printf("\nchange_event %d %d %s\n", idx, ev->mask, ev->name); if (ev->mask & IN_OPEN) printf("IN_OPEN: "); if (ev->mask & IN_DELETE_SELF) printf("IN_DELETE_SELF: "); if (ev->mask & IN_DELETE) printf("IN_DELETE: "); if (ev->mask & IN_CLOSE_NOWRITE) printf("IN_CLOSE_NOWRITE: "); if (ev->mask & IN_CLOSE_WRITE) printf("IN_CLOSE_WRITE: "); if (ev->mask & IN_IGNORED) printf("IN_IGNORED: "); } int main(int argc, char **argv) { if (argc <= 1) { puts("Usage: a.out <watchlist>\n"); return 1; } notify_init(IN_CLOSE_WRITE, argc - 1, argv + 1); printf("%d\n", notify_last_error()); while (true) { if (!notify_poll(change_event)) printf("lastError %d\n", notify_last_error()); } notify_shutdown(); return 0; }
0.761719
high
gl_server/servergles.c
challenzhou/gl-streaming
1
925377
<reponame>challenzhou/gl-streaming // This file declare OpenGL ES methods on server side #include "glserver.h" void glse_glBindBuffer() { GLSE_SET_COMMAND_PTR(c, glBindBuffer); glBindBuffer(c->target, c->buffer); } void glse_glBindTexture() { GLSE_SET_COMMAND_PTR(c, glBindTexture); glBindTexture(c->target, c->texture); } void glse_glBlendEquationSeparate() { GLSE_SET_COMMAND_PTR(c, glBlendEquationSeparate); glBlendEquationSeparate(c->modeRGB, c->modeAlpha); } void glse_glBlendFuncSeparate() { GLSE_SET_COMMAND_PTR(c, glBlendFuncSeparate); glBlendFuncSeparate(c->srcRGB, c->dstRGB, c->srcAlpha, c->dstAlpha); } void glse_glBufferData() { GLSE_SET_COMMAND_PTR(c,glBufferData ); glBufferData(c->target, c->size, glsec_global.tmp_buf.buf, c->usage); } void glse_glBufferSubData() { GLSE_SET_COMMAND_PTR(c, glBufferSubData); glBufferSubData(c->target, c->offset, c->size, glsec_global.tmp_buf.buf); } void glse_glClear() { GLSE_SET_COMMAND_PTR(c, glClear); glClear(c->mask); } void glse_glClearColor() { GLSE_SET_COMMAND_PTR(c, glClearColor); glClearColor(c->red, c->green, c->blue, c->alpha); } void glse_glColorMask() { GLSE_SET_COMMAND_PTR(c, glColorMask); glColorMask(c->red, c->green, c->blue, c->alpha); } void glse_glDeleteBuffers() { GLSE_SET_COMMAND_PTR(c, glDeleteBuffers); glDeleteBuffers (c->n, (GLuint *)glsec_global.tmp_buf.buf); } void glse_glDepthFunc() { GLSE_SET_COMMAND_PTR(c, glDepthFunc); glDepthFunc(c->func); } void glse_glDrawArrays() { GLSE_SET_COMMAND_PTR(c, glDrawArrays); glDrawArrays(c->mode, c->first, c->count); } void glse_glEnable() { GLSE_SET_COMMAND_PTR(c, glEnable); glEnable(c->cap); } void glse_glGenBuffers() { GLSE_SET_COMMAND_PTR(c, glGenBuffers); glGenBuffers(c->n, (GLuint*)glsec_global.tmp_buf.buf); uint32_t size = c->n * sizeof(uint32_t); glse_cmd_send_data(0, size, (char *)glsec_global.tmp_buf.buf); } void glse_glGenTextures() { GLSE_SET_COMMAND_PTR(c, glGenTextures); glGenTextures(c->n, (GLuint*)glsec_global.tmp_buf.buf); uint32_t size = c->n * sizeof(uint32_t); glse_cmd_send_data(0, size, (char *)glsec_global.tmp_buf.buf); } void glse_glGetActiveUniform() { GLSE_SET_COMMAND_PTR(c, glGetActiveUniform); gls_ret_glGetActiveUniform_t *ret = (gls_ret_glGetActiveUniform_t *)glsec_global.tmp_buf.buf; char* name; glGetActiveUniform (c->program, c->index, c->bufsize, &ret->length, &ret->size, &ret->type, name); ret->cmd = GLSC_glGetActiveUniform; ret->name[GLS_STRING_SIZE_PLUS - 1] = '\0'; strncpy(ret->name, name, ret->length); glse_cmd_send_data(0, sizeof(gls_ret_glGetActiveUniform_t), (char *)glsec_global.tmp_buf.buf); } void glse_glGetAttribLocation() { GLSE_SET_COMMAND_PTR(c, glGetAttribLocation); int index = glGetAttribLocation (c->program, c->name); gls_ret_glGetAttribLocation_t *ret = (gls_ret_glGetAttribLocation_t *)glsec_global.tmp_buf.buf; ret->cmd = GLSC_glGetAttribLocation; ret->index = index; glse_cmd_send_data(0, sizeof(gls_ret_glGetAttribLocation_t), (char *)glsec_global.tmp_buf.buf); } void glse_glGetError() { GLuint error = glGetError(); // Should check gl error inside glGetError() ??? gls_ret_glGetError_t *ret = (gls_ret_glGetError_t *)glsec_global.tmp_buf.buf; ret->cmd = GLSC_glGetError; ret->error = error; glse_cmd_send_data(0, sizeof(gls_ret_glGetError_t), (char *)glsec_global.tmp_buf.buf); } void glse_glGetFloatv() { GLSE_SET_COMMAND_PTR(c, glGetFloatv); gls_ret_glGetFloatv_t *ret = (gls_ret_glGetFloatv_t *)glsec_global.tmp_buf.buf; glGetFloatv(c->name, &ret->params); ret->cmd = GLSC_glGetFloatv; glse_cmd_send_data(0,sizeof(gls_ret_glGetFloatv_t),(char *)glsec_global.tmp_buf.buf); } void glse_glGetIntegerv() { GLSE_SET_COMMAND_PTR(c, glGetIntegerv); gls_ret_glGetIntegerv_t *ret = (gls_ret_glGetIntegerv_t *)glsec_global.tmp_buf.buf; glGetIntegerv(c->name, &ret->params); ret->cmd = GLSC_glGetIntegerv; glse_cmd_send_data(0,sizeof(gls_ret_glGetIntegerv_t),(char *)glsec_global.tmp_buf.buf); } void glse_glGetProgramInfoLog() { GLSE_SET_COMMAND_PTR(c, glGetProgramInfoLog); gls_ret_glGetProgramInfoLog_t *ret = (gls_ret_glGetProgramInfoLog_t *)glsec_global.tmp_buf.buf; uint32_t maxsize = GLSE_TMP_BUFFER_SIZE - (uint32_t)((char*)ret->infolog - (char*)ret) - 256; if (c->bufsize > maxsize) { c->bufsize = maxsize; } glGetProgramInfoLog(c->program, c->bufsize, (GLsizei*)&ret->length, (GLchar*)ret->infolog); ret->cmd = GLSC_glGetProgramInfoLog; uint32_t size = (uint32_t)((char*)ret->infolog - (char*)ret) + ret->length + 1; glse_cmd_send_data(0, size, (char *)glsec_global.tmp_buf.buf); } void glse_glGetProgramiv() { GLSE_SET_COMMAND_PTR(c, glGetProgramiv); gls_ret_glGetProgramiv_t *ret = (gls_ret_glGetProgramiv_t *)glsec_global.tmp_buf.buf; glGetProgramiv(c->program, c->pname, &ret->params); // LOGD("GLGetProgramiv from %p return %i", c->pname, ret->params); ret->cmd = GLSC_glGetProgramiv; glse_cmd_send_data(0,sizeof(gls_ret_glGetProgramiv_t),(char *)glsec_global.tmp_buf.buf); } void glse_glGetShaderiv() { GLSE_SET_COMMAND_PTR(c, glGetShaderiv); gls_ret_glGetShaderiv_t *ret = (gls_ret_glGetShaderiv_t *)glsec_global.tmp_buf.buf; glGetShaderiv(c->shader, c->pname, &ret->params); ret->cmd = GLSC_glGetShaderiv; glse_cmd_send_data(0,sizeof(gls_ret_glGetShaderiv_t),(char *)glsec_global.tmp_buf.buf); } void glse_glGetString() { GLSE_SET_COMMAND_PTR(c, glGetString); gls_ret_glGetString_t *ret = (gls_ret_glGetString_t *)glsec_global.tmp_buf.buf; const char *params = glGetString(c->name); ret->cmd = GLSC_glGetString; // LOGD("Client asking for %i, return %s", c->name, params); ret->params[GLS_STRING_SIZE_PLUS - 1] = '\0'; strncpy(ret->params, params, GLS_STRING_SIZE); glse_cmd_send_data(0,sizeof(gls_ret_glGetString_t),(char *)glsec_global.tmp_buf.buf); } void glse_glGetUniformLocation() { GLSE_SET_COMMAND_PTR(c, glGetUniformLocation); int location = glGetUniformLocation (c->program, (const GLchar*)c->name); gls_ret_glGetUniformLocation_t *ret = (gls_ret_glGetUniformLocation_t *)glsec_global.tmp_buf.buf; ret->cmd = GLSC_glGetUniformLocation; ret->location = (int32_t)location; glse_cmd_send_data(0, sizeof(gls_ret_glGetUniformLocation_t), (char *)glsec_global.tmp_buf.buf); } void glse_glEnableVertexAttribArray() { GLSE_SET_COMMAND_PTR(c,glEnableVertexAttribArray ); glEnableVertexAttribArray(c->index); } void glse_glVertexAttribPointer() { GLSE_SET_COMMAND_PTR(c, glVertexAttribPointer); glVertexAttribPointer(c->indx, c->size, c->type, c->normalized, c->stride, (const GLvoid*)c->ptr); } void glse_glBindFramebuffer() { GLSE_SET_COMMAND_PTR(c, glBindFramebuffer); glBindFramebuffer(c->target, c->framebuffer); } void glse_glViewport() { GLSE_SET_COMMAND_PTR(c, glViewport); glViewport(c->x, c->y, c->width, c->height); } void glse_glUseProgram() { GLSE_SET_COMMAND_PTR(c, glUseProgram); glUseProgram(c->program); } void glse_glCreateShader() { GLSE_SET_COMMAND_PTR(c, glCreateShader); uint32_t obj = glCreateShader(c->type); gls_ret_glCreateShader_t *ret = (gls_ret_glCreateShader_t *)glsec_global.tmp_buf.buf; ret->cmd = GLSC_glCreateShader; ret->obj = obj; glse_cmd_send_data(0, sizeof(gls_ret_glCreateShader_t), (char *)glsec_global.tmp_buf.buf); } void glse_glShaderSource() { GLSE_SET_COMMAND_PTR(c, glShaderSource); gls_data_glShaderSource_t *dat = (gls_data_glShaderSource_t *)glsec_global.tmp_buf.buf; unsigned int i; for (i = 0; i < c->count; i++) { dat->string[i] = (uint32_t)(dat->data + dat->string[i]); } glShaderSource(c->shader, c->count, (const GLchar**)dat->string, dat->length); // Debug: print shader to log /* LOGD("\n ----- BEGIN SHADER CONTENT -----"); size_t size_all = (size_t)(dat->data - (char *)dat); uint32_t stroffset = 0; // unsigned int i; for (i = 0; i < c->count; i++) { char *strptr = (char *)dat->string[i]; size_t strsize; if (dat->length == NULL) { strsize = 0; } else { strsize = dat->length[i]; } if (strsize == 0) { strsize = strnlen(strptr, 0xA00000); } if (strsize > 0x100000) { return; } size_all += strsize + 1; if (size_all > GLS_TMP_BUFFER_SIZE) { return; } stroffset = stroffset + strsize + 1; LOGD("gls debug: shader length = %i", strsize); LOGD("%s", strptr); } LOGD(" ----- ENDED SHADER CONTENT -----\n"); */ } void glse_glCompileShader() { GLSE_SET_COMMAND_PTR(c, glCompileShader); glCompileShader(c->shader); } void glse_glCreateProgram() { GLuint program = glCreateProgram(); gls_ret_glCreateProgram_t *ret = (gls_ret_glCreateProgram_t *)glsec_global.tmp_buf.buf; ret->cmd = GLSC_glCreateProgram; ret->program = program; glse_cmd_send_data(0, sizeof(gls_ret_glCreateProgram_t), (char *)glsec_global.tmp_buf.buf); } void glse_glAttachShader() { GLSE_SET_COMMAND_PTR(c, glAttachShader); glAttachShader(c->program, c->shader); } void glse_glLinkProgram() { GLSE_SET_COMMAND_PTR(c, glLinkProgram); glLinkProgram(c->program); } void glse_glDeleteProgram() { GLSE_SET_COMMAND_PTR(c, glDeleteProgram); glDeleteProgram(c->program); } void glse_glDeleteShader() { GLSE_SET_COMMAND_PTR(c, glDeleteShader); glDeleteShader(c->shader); } void glse_glUniform1f() { GLSE_SET_COMMAND_PTR(c, glUniform1f); glUniform1f(c->location, c->x); } void glse_glDisableVertexAttribArray() { GLSE_SET_COMMAND_PTR(c, glDisableVertexAttribArray); glDisableVertexAttribArray(c->index); } void glse_glDisable() { GLSE_SET_COMMAND_PTR(c, glDisable); glDisable(c->cap); } void glse_glDrawElements() { GLSE_SET_COMMAND_PTR(c, glDrawElements); glDrawElements (c->mode, c->count, c->type, (const GLvoid*)c->indices); } void glse_glGetShaderInfoLog() { GLSE_SET_COMMAND_PTR(c, glGetShaderInfoLog); gls_ret_glGetShaderInfoLog_t *ret = (gls_ret_glGetShaderInfoLog_t *)glsec_global.tmp_buf.buf; uint32_t maxsize = GLSE_TMP_BUFFER_SIZE - (uint32_t)((char*)ret->infolog - (char*)ret) - 256; if (c->bufsize > maxsize) { c->bufsize = maxsize; } glGetShaderInfoLog(c->shader, c->bufsize, (GLsizei*)&ret->length, (GLchar*)ret->infolog); ret->cmd = GLSC_glGetShaderInfoLog; uint32_t size = (uint32_t)((char*)ret->infolog - (char*)ret) + ret->length + 1; glse_cmd_send_data(0, size, (char *)glsec_global.tmp_buf.buf); } void glse_glBindAttribLocation() { GLSE_SET_COMMAND_PTR(c, glBindAttribLocation); glBindAttribLocation (c->program, c->index, c->name); } void glse_glUniform4fv() { GLSE_SET_COMMAND_PTR(c, glUniform4fv); glUniform4fv (c->location, c->count, (const GLfloat *)c->v); } void glse_glUniformMatrix4fv() { GLSE_SET_COMMAND_PTR(c, glUniformMatrix4fv); glUniformMatrix4fv(c->location, c->count, c->transpose, (const GLfloat *)c->value); } void glse_glFinish() { GLSE_SET_COMMAND_PTR(c, glFinish); glFinish(); gls_command_t *ret = (gls_command_t *)glsec_global.tmp_buf.buf; ret->cmd = c->cmd; size_t size = sizeof(gls_command_t); glse_cmd_send_data(0, size, glsec_global.tmp_buf.buf); } void glse_glFlush() { glFlush(); } void glse_glTexParameteri() { GLSE_SET_COMMAND_PTR(c, glTexParameteri); glTexParameteri (c->target, c->pname, c->param); } void glse_glTexImage2D() { GLSE_SET_COMMAND_PTR(c, glTexImage2D); glTexImage2D(c->target, c->level, c->internalformat, c->width, c->height, c->border, c->format, c->type, c->pixels); } // Based from glTexImage2D void glse_glTexSubImage2D() { GLSE_SET_COMMAND_PTR(c, glTexSubImage2D); glTexSubImage2D(c->target, c->level, c->xoffset, c->yoffset, c->width, c->height, c->format, c->type, c->pixels); } void glse_glDeleteTextures() { GLSE_SET_COMMAND_PTR(c, glDeleteTextures); glDeleteTextures(c->n, c->textures); } void glse_glPixelStorei() { GLSE_SET_COMMAND_PTR(c, glPixelStorei); glPixelStorei(c->pname, c->param); } void glse_glActiveTexture() { GLSE_SET_COMMAND_PTR(c, glActiveTexture); glActiveTexture(c->texture); } void glse_glBlendFunc() { GLSE_SET_COMMAND_PTR(c, glBlendFunc); glBlendFunc(c->sfactor, c->dfactor); } void glse_glCullFace() { GLSE_SET_COMMAND_PTR(c, glCullFace); glActiveTexture(c->mode); } void glse_glDepthMask() { GLSE_SET_COMMAND_PTR(c, glDepthMask); glDepthMask(c->flag); } void glse_glDepthRangef() { GLSE_SET_COMMAND_PTR(c, glDepthRangef); glDepthRangef(c->zNear, c->zFar); } void glse_glStencilFunc() { GLSE_SET_COMMAND_PTR(c, glStencilFunc); glStencilFunc(c->func, c->r, c->m); } void glse_glStencilOp() { GLSE_SET_COMMAND_PTR(c, glStencilOp); glStencilOp(c->fail, c->zfail, c->zpass); } void glse_glPolygonOffset() { GLSE_SET_COMMAND_PTR(c, glPolygonOffset); glPolygonOffset(c->factor, c->units); } void glse_glStencilMask() { GLSE_SET_COMMAND_PTR(c, glStencilMask); glStencilMask(c->mask); } void glse_glLineWidth() { GLSE_SET_COMMAND_PTR(c, glLineWidth); glLineWidth(c->width); } void glse_glHint() { GLSE_SET_COMMAND_PTR(c, glHint); glHint(c->target, c->mode); } void glse_glClearDepthf() { GLSE_SET_COMMAND_PTR(c, glClearDepthf); glClearDepthf(c->depth); } void glse_glReadPixels() { GLSE_SET_COMMAND_PTR(c, glReadPixels); gls_ret_glReadPixels_t *ret = (gls_ret_glReadPixels_t *)glsec_global.tmp_buf.buf; glReadPixels(c->x, c->y, c->width, c->height, c->format, c->type, &ret->pixels); ret->cmd = glReadPixels; glse_cmd_send_data(0, sizeof(gls_ret_glReadPixels_t), (char *)glsec_global.tmp_buf.buf); // gls_cmd_send_data(0, (uint32_t) (c->width * c->height) /* correct??? */ , (void *)ret->pixels); } /* void glse_() { GLSE_SET_COMMAND_PTR(c, ); } gls_ret__t *ret = (gls_ret__t *)glsec_global.tmp_buf.buf; ret->cmd = GLSC_; ret-> = ; glse_cmd_send_data(0, sizeof(gls_ret__t), (char *)glsec_global.tmp_buf.buf); */ int gles_flushCommand(gls_command_t *c) { // LOGD("Flushing command %i\n", c->cmd); switch (c->cmd) { case GLSC_glAttachShader: glse_glAttachShader(); pop_batch_command(sizeof(gls_glAttachShader_t)); break; case GLSC_glActiveTexture: glse_glActiveTexture(); pop_batch_command(sizeof(gls_glActiveTexture_t)); break; case GLSC_glBindBuffer: glse_glBindBuffer(); pop_batch_command(sizeof(gls_glBindBuffer_t)); break; case GLSC_glBindTexture: glse_glBindTexture(); pop_batch_command(sizeof(gls_glBindTexture_t)); break; case GLSC_glBindAttribLocation: glse_glBindAttribLocation(); pop_batch_command(sizeof(gls_glBindAttribLocation_t)); break; case GLSC_glBindFramebuffer: glse_glBindFramebuffer(); pop_batch_command(sizeof(gls_glBindFramebuffer_t)); break; case GLSC_glBlendFuncSeparate: glse_glBlendFuncSeparate(); pop_batch_command(sizeof(gls_glBlendFuncSeparate_t)); break; case GLSC_glBlendEquationSeparate: glse_glBlendEquationSeparate(); pop_batch_command(sizeof(gls_glBlendEquationSeparate_t)); break; case GLSC_glClear: glse_glClear(); pop_batch_command(sizeof(gls_glClear_t)); break; case GLSC_glClearColor: glse_glClearColor(); pop_batch_command(sizeof(gls_glClearColor_t)); break; case GLSC_glColorMask: glse_glColorMask(); pop_batch_command(sizeof(gls_glColorMask_t)); break; case GLSC_glCompileShader: glse_glCompileShader(); pop_batch_command(sizeof(gls_glCompileShader_t)); break; case GLSC_glDeleteProgram: glse_glDeleteProgram(); pop_batch_command(sizeof(gls_glDeleteProgram_t)); break; case GLSC_glDeleteShader: glse_glDeleteShader(); pop_batch_command(sizeof(gls_glDeleteShader_t)); break; case GLSC_glDeleteTextures: glse_glDeleteTextures(); pop_batch_command(((gls_glDeleteTextures_t *)c)->cmd_size); break; case GLSC_glDepthFunc: glse_glDepthFunc(); pop_batch_command(sizeof(gls_glDepthFunc_t)); break; case GLSC_glDisable: glse_glDisable(); pop_batch_command(sizeof(gls_glDisable_t)); break; case GLSC_glDisableVertexAttribArray: glse_glDisableVertexAttribArray(); pop_batch_command(sizeof(gls_glDisableVertexAttribArray_t)); break; case GLSC_glDrawArrays: glse_glDrawArrays(); pop_batch_command(sizeof(gls_glDrawArrays_t)); break; case GLSC_glDrawElements: glse_glDrawElements(); pop_batch_command(sizeof(gls_glDrawElements_t)); break; case GLSC_glEnable: glse_glEnable(); pop_batch_command(sizeof(gls_glEnable_t)); break; case GLSC_glEnableVertexAttribArray: glse_glEnableVertexAttribArray(); pop_batch_command(sizeof(gls_glEnableVertexAttribArray_t)); break; case GLSC_glFlush: glse_glFlush(); pop_batch_command(sizeof(gls_command_t)); break; case GLSC_glLinkProgram: glse_glLinkProgram(); pop_batch_command(sizeof(gls_glLinkProgram_t)); break; case GLSC_glPixelStorei: glse_glPixelStorei(); pop_batch_command(sizeof(gls_glPixelStorei_t)); break; case GLSC_glTexImage2D: glse_glTexImage2D(); pop_batch_command(((gls_glTexImage2D_t *)c)->cmd_size); break; case GLSC_glTexParameteri: glse_glTexParameteri(); pop_batch_command(sizeof(gls_glTexParameteri_t)); break; case GLSC_glUniform1f: glse_glUniform1f(); pop_batch_command(sizeof(gls_glUniform1f_t)); break; case GLSC_glUniform4fv: glse_glUniform4fv(); pop_batch_command(((gls_glUniform4fv_t *)c)->cmd_size); break; case GLSC_glUniformMatrix4fv: glse_glUniformMatrix4fv(); pop_batch_command(((gls_glUniformMatrix4fv_t *)c)->cmd_size); break; case GLSC_glUseProgram: glse_glUseProgram(); pop_batch_command(sizeof(gls_glUseProgram_t)); break; case GLSC_glVertexAttribPointer: glse_glVertexAttribPointer(); pop_batch_command(sizeof(gls_glVertexAttribPointer_t)); break; case GLSC_glViewport: glse_glViewport(); pop_batch_command(sizeof(gls_glViewport_t)); break; case GLSC_glBlendFunc: glse_glBlendFunc(); pop_batch_command(sizeof(gls_glBlendFunc_t)); break; case GLSC_glClearDepthf: glse_glClearDepthf(); pop_batch_command(sizeof(gls_glClearDepthf_t)); break; case GLSC_glCullFace: glse_glCullFace(); pop_batch_command(sizeof(gls_glCullFace_t)); break; case GLSC_glDepthMask: glse_glDepthMask(); pop_batch_command(sizeof(gls_glDepthMask_t)); break; case GLSC_glDepthRangef: glse_glDepthRangef(); pop_batch_command(sizeof(gls_glDepthRangef_t)); break; case GLSC_glHint: glse_glHint(); pop_batch_command(sizeof(gls_glHint_t)); break; case GLSC_glLineWidth: glse_glLineWidth(); pop_batch_command(sizeof(gls_glLineWidth_t)); break; case GLSC_glPolygonOffset: glse_glPolygonOffset(); pop_batch_command(sizeof(gls_glPolygonOffset_t)); break; case GLSC_glStencilFunc: glse_glStencilFunc(); pop_batch_command(sizeof(gls_glStencilFunc_t)); break; case GLSC_glStencilMask: glse_glStencilMask(); pop_batch_command(sizeof(gls_glStencilMask_t)); break; case GLSC_glStencilOp: glse_glStencilOp(); pop_batch_command(sizeof(gls_glStencilOp_t)); break; case GLSC_glTexSubImage2D: glse_glTexSubImage2D(); pop_batch_command(((gls_glTexSubImage2D_t *)c)->cmd_size); break; /* case GLSC_glXXX: glse_glXXX(); pop_batch_command(sizeof(gls_glXXX_t)); break; */ default: return FALSE; } check_gl_err(c->cmd); return TRUE; } int gles_executeCommand(gls_command_t *c) { // LOGD("Executing command %i\n", c->cmd); switch (c->cmd) { case GLSC_glBufferData: glse_glBufferData(); break; case GLSC_glBufferSubData: glse_glBufferSubData(); break; case GLSC_glCreateProgram: glse_glCreateProgram(); break; case GLSC_glCreateShader: glse_glCreateShader(); break; case GLSC_glDeleteBuffers: glse_glDeleteBuffers(); break; case GLSC_glFinish: glse_glFinish(); break; case GLSC_glGenBuffers: glse_glGenBuffers(); break; case GLSC_glGenTextures: glse_glGenTextures(); break; case GLSC_glGetActiveUniform: glse_glGetActiveUniform(); break; case GLSC_glGetAttribLocation: glse_glGetAttribLocation(); break; case GLSC_glGetError: glse_glGetError(); break; case GLSC_glGetFloatv: glse_glGetFloatv(); break; case GLSC_glGetIntegerv: glse_glGetIntegerv(); break; case GLSC_glGetProgramInfoLog: glse_glGetProgramInfoLog(); break; case GLSC_glGetProgramiv: glse_glGetProgramiv(); break; case GLSC_glGetShaderInfoLog: glse_glGetShaderInfoLog(); break; case GLSC_glGetShaderiv: glse_glGetShaderiv(); break; case GLSC_glGetString: glse_glGetString(); break; case GLSC_glGetUniformLocation: glse_glGetUniformLocation(); break; case GLSC_glReadPixels: glse_glReadPixels(); break; case GLSC_glShaderSource: glse_glShaderSource(); break; default: return FALSE; } check_gl_err(c->cmd); return TRUE; }
0.992188
high
src/robot_sim/include/robot_sim/joint_state_publisher.h
zuurw/Robotics-ColumbiaX-Project3
7
925889
#pragma once #include <boost/shared_ptr.hpp> #include <vector> #include <ros/ros.h> #include "robot_sim/robot.h" namespace robot_sim { class JointStatePublisher { public: JointStatePublisher(boost::shared_ptr<Robot> robot) : root_nh_(""), robot_(robot) {} bool init(double rate); private: ros::NodeHandle root_nh_; boost::shared_ptr<Robot> robot_; ros::Publisher state_publisher_; ros::Timer state_timer_; void callback(const ros::TimerEvent&); }; } //namespace robot_sim
0.832031
high
SG-Engine/src/SGEngine/Events/ApplicationEvents.h
Ahmed-YehiaGPEL/SG-Engine
0
926401
#pragma once #include "Event.h" namespace SGEngine { class SGE_API WindowResizeEvent : public Event { public: WindowResizeEvent(const int width, const int height) : mWidth(width) , mHeight(height) { } EVENT_CLASS_TYPE(WindowResize); EVENT_CLASS_CATEGORY(EventCategory::EventCategoryApplication); int GetWidth() const { return mWidth; } int GetHeight() const { return mHeight; } std::string ToString() const override { std::stringstream ss; ss << "Window Resized: " << mWidth << "," << mHeight; return ss.str(); } private: int mWidth, mHeight; }; class SGE_API WindowCloseEvent : public Event { public: EVENT_CLASS_TYPE(WindowClose); EVENT_CLASS_CATEGORY(EventCategory::EventCategoryApplication); }; class SGE_API WindowFocusEvent : public Event { public: EVENT_CLASS_TYPE(WindowFocus); EVENT_CLASS_CATEGORY(EventCategory::EventCategoryApplication); }; class SGE_API WindowLostFocus : public Event { public: EVENT_CLASS_TYPE(WindowLostFocus); EVENT_CLASS_CATEGORY(EventCategory::EventCategoryApplication); }; class SGE_API WindowMoved : public Event { public: EVENT_CLASS_TYPE(WindowMoved); EVENT_CLASS_CATEGORY(EventCategory::EventCategoryApplication); }; class SGE_API AppUpdateEvent : public Event { public: EVENT_CLASS_TYPE(AppUpdate); EVENT_CLASS_CATEGORY(EventCategory::EventCategoryApplication); }; class SGE_API AppTickEvent : public Event { public: AppTickEvent(const float deltaTime) :mDeltaTime(deltaTime) { } EVENT_CLASS_TYPE(WindowFocus); EVENT_CLASS_CATEGORY(EventCategory::EventCategoryApplication); float GetDeltaTime() const { return mDeltaTime; } private: float mDeltaTime; }; class SGE_API AppRenderEvent : public Event { EVENT_CLASS_TYPE(AppRender) EVENT_CLASS_CATEGORY(EventCategory::EventCategoryApplication) }; }
0.996094
high
include/lib/a4988.h
daHaimi/rabamOS
0
926913
#ifndef RABAMOS_A4988_H #define RABAMOS_A4988_H #define MS_DIV_1 1 #define MS_DIV_2 2 #define MS_DIV_4 4 #define MS_DIV_8 8 #define MS_DIV_16 16 #define DIR_FORWARD 0 #define DIR_BACKWARD 1 typedef struct { uint16_t steps_round; uint16_t delay; uint8_t microstepping; } motor_config_t; typedef struct { uint8_t dir: 1; uint8_t sleep: 1; } pin_status_t; typedef struct { uint8_t microstepping; uint8_t pin_step; uint8_t pin_dir; uint8_t pin_sleep; pin_status_t * pin_status; motor_config_t * config; } motor_t; motor_t * init_motor(uint8_t pin_step, uint8_t pin_dir, uint8_t pin_sleep, uint16_t resolution); void motor_step(motor_t *motor); void motor_pause(motor_t *motor); void motor_unpause(motor_t *motor); void motor_set_dir(motor_t *motor, uint8_t dir); void motor_switch_dir(motor_t *motor); void motor_turn_steps(motor_t *motor, uint64_t steps); void motor_turn_steps_in_usec(motor_t *motor, uint64_t steps, uint32_t usec); #endif
0.988281
high
include/FPL/ParserBase.h
cschladetsch/FPL
0
927425
<reponame>cschladetsch/FPL<filename>include/FPL/ParserBase.h #pragma once #include <FPL/Process.h>
0.871094
low
FlixApp/views/movieCell.h
nihaljemal/FlixApp
0
927937
// // movieCell.h // FlixApp // // Created by <NAME> on 6/28/18. // Copyright © 2018 Facebook. All rights reserved. // #import <UIKit/UIKit.h> @interface movieCell : UITableViewCell @property (weak, nonatomic) IBOutlet UILabel *titleLabel; @property (weak, nonatomic) IBOutlet UILabel *SynopsisLabel; @property (weak, nonatomic) IBOutlet UIImageView *posterLabel; @end
0.753906
medium
test/JPEG/static-ext_lib/src/decoding_tree.h
TAFFO-org/TAFFO
3
928449
#pragma once #include <numeric> #include <vector> typedef enum { kLeft, kRight } Direction; template <typename T> class DecodingTree { public: explicit DecodingTree(const std::vector<T>& codes, const std::vector<size_t>& counts) : tree_(1, Node()) , position_(0) { if (std::accumulate(counts.begin(), counts.end(), 0) != codes.size()) { throw std::runtime_error("DecodingTree: inconsistent number of codes."); } int levelInTree = 0; int level = 0; int position = 0; size_t cumCounts = 0; for (size_t i = 0; i < codes.size(); ++i) { while (cumCounts == i) { cumCounts += counts[level]; ++level; } const T& code = codes[i]; while (levelInTree < level) { Node& node = tree_[position]; int newPosition = tree_.size(); if (node.left == Node::UNDEFINED) { node.left = newPosition; } else if (node.right == Node::UNDEFINED) { node.right = newPosition; } else { position = node.parent; --levelInTree; if (levelInTree < 0) { throw std::runtime_error("DecodingTree: incorrect tree definition."); } continue; } Node newNode; newNode.parent = position; tree_.push_back(newNode); position = newPosition; ++levelInTree; } Node& node = tree_[position]; node.value = code; node.isLeaf = true; position = node.parent; --levelInTree; } } bool step(Direction dir) { if (dir == kLeft) { position_ = tree_[position_].left; } else { position_ = tree_[position_].right; } if (position_ >= tree_.size()) { throw std::runtime_error("DecodingTree: traversed out of bounds."); } return tree_[position_].isLeaf; } const T& getValue() const { const Node& node = tree_.at(position_); if (!node.isLeaf) { throw std::runtime_error("DecodingTree: taking value of a non-leaf node."); } return node.value; } void reset() { position_ = 0; } private: struct Node { static const int UNDEFINED = -1; Node() : left(UNDEFINED), right(UNDEFINED), isLeaf(false) {} int left; int right; int parent; bool isLeaf; T value; }; std::vector<Node> tree_; int position_; };
0.996094
high
2021-S1/W4/list1.c
BoomlabsInc/BCSF
2
928961
#include <stdio.h> #include <stdlib.h> typedef struct nodo { int Valor; struct nodo* siguiente; } nodo; int main() { nodo* lista = NULL; // Crear una lista vacía. nodo* n = malloc(sizeof(nodo)); if(n == NULL) { printf("Error de memoria.\n"); return 1; } // Tenemos nuevo nodo! :D // (*n).Valor = 2; // (*n).siguiente = NULL; n -> Valor = 2; n -> siguiente = NULL; lista = n; // Agregando n como primer elemento de la lista n = malloc(sizeof(nodo)); if(n == NULL) { printf("Error de memoria.\n"); return 1; } n -> Valor = 4; n -> siguiente = NULL; // Recorrer toda la lista de nodos nodo* tmp = lista; while(tmp->siguiente != NULL) { tmp = tmp -> siguiente; } // Cuando lleguemos acá, tmp va a estar apuntando al último nodo de la lista. tmp -> siguiente = n; // haciendo de n el último nodo // Agregar un nodo al inicio de la colección. n = malloc(sizeof(nodo)); if(n == NULL) { printf("Error de memoria.\n"); return 1; } n -> Valor = 1; n -> siguiente = NULL; n -> siguiente = lista; lista = n; // agregando un elemento al principio. // Imprimir la colección tmp = lista; while(tmp -> siguiente != NULL) { printf("%i -> ", tmp -> Valor); tmp = tmp-> siguiente; } printf("%i \n", tmp -> Valor); }
0.953125
high
tools/widl/typelib.c
roytam1/wine-win31look
1
929473
/* * IDL Compiler * * Copyright 2004 <NAME> * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <assert.h> #include <ctype.h> #include <signal.h> #include "widl.h" #include "utils.h" #include "parser.h" #include "header.h" #include "typelib.h" int in_typelib = 0; static FILE* typelib; /* Copied from wtypes.h. Not included directly because that would create a * circular dependency (after all, wtypes.h is generated by widl...) */ enum VARENUM { VT_EMPTY = 0, VT_NULL = 1, VT_I2 = 2, VT_I4 = 3, VT_R4 = 4, VT_R8 = 5, VT_CY = 6, VT_DATE = 7, VT_BSTR = 8, VT_DISPATCH = 9, VT_ERROR = 10, VT_BOOL = 11, VT_VARIANT = 12, VT_UNKNOWN = 13, VT_DECIMAL = 14, VT_I1 = 16, VT_UI1 = 17, VT_UI2 = 18, VT_UI4 = 19, VT_I8 = 20, VT_UI8 = 21, VT_INT = 22, VT_UINT = 23, VT_VOID = 24, VT_HRESULT = 25, VT_PTR = 26, VT_SAFEARRAY = 27, VT_CARRAY = 28, VT_USERDEFINED = 29, VT_LPSTR = 30, VT_LPWSTR = 31, VT_RECORD = 36, VT_FILETIME = 64, VT_BLOB = 65, VT_STREAM = 66, VT_STORAGE = 67, VT_STREAMED_OBJECT = 68, VT_STORED_OBJECT = 69, VT_BLOB_OBJECT = 70, VT_CF = 71, VT_CLSID = 72, VT_BSTR_BLOB = 0xfff, VT_VECTOR = 0x1000, VT_ARRAY = 0x2000, VT_BYREF = 0x4000, VT_RESERVED = 0x8000, VT_ILLEGAL = 0xffff, VT_ILLEGALMASKED = 0xfff, VT_TYPEMASK = 0xfff }; /* List of oleauto types that should be recognized by name. * (most of) these seem to be intrinsic types in mktyplib. */ static struct oatype { const char *kw; unsigned short vt; } oatypes[] = { {"BSTR", VT_BSTR}, {"CURRENCY", VT_CY}, {"DATE", VT_DATE}, {"DECIMAL", VT_DECIMAL}, {"HRESULT", VT_HRESULT}, {"LPSTR", VT_LPSTR}, {"LPWSTR", VT_LPWSTR}, {"SCODE", VT_ERROR}, {"VARIANT", VT_VARIANT} }; #define NTYPES (sizeof(oatypes)/sizeof(oatypes[0])) #define KWP(p) ((struct oatype *)(p)) static int kw_cmp_func(const void *s1, const void *s2) { return strcmp(KWP(s1)->kw, KWP(s2)->kw); } static unsigned short builtin_vt(const char *kw) { struct oatype key, *kwp; key.kw = kw; #ifdef KW_BSEARCH kwp = bsearch(&key, oatypes, NTYPES, sizeof(oatypes[0]), kw_cmp_func); #else { int i; for (kwp=NULL, i=0; i < NTYPES; i++) if (!kw_cmp_func(&key, &oatypes[i])) { kwp = &oatypes[i]; break; } } #endif if (kwp) { return kwp->vt; } return 0; } static int match(const char*n, const char*m) { if (!n) return 0; return !strcmp(n, m); } unsigned short get_type_vt(type_t *t) { unsigned short vt; if (t->name) { vt = builtin_vt(t->name); if (vt) return vt; } switch (t->type) { case RPC_FC_BYTE: case RPC_FC_USMALL: return VT_UI1; case RPC_FC_CHAR: case RPC_FC_SMALL: return VT_I1; case RPC_FC_WCHAR: return VT_I2; /* mktyplib seems to parse wchar_t as short */ case RPC_FC_SHORT: return VT_I2; case RPC_FC_USHORT: return VT_UI2; case RPC_FC_LONG: if (t->ref && match(t->ref->name, "int")) return VT_INT; return VT_I4; case RPC_FC_ULONG: if (t->ref && match(t->ref->name, "int")) return VT_UINT; return VT_UI4; case RPC_FC_HYPER: if (t->sign < 0) return VT_UI8; if (t->ref && match(t->ref->name, "MIDL_uhyper")) return VT_UI8; return VT_I8; case RPC_FC_FLOAT: return VT_R4; case RPC_FC_DOUBLE: return VT_R8; case RPC_FC_RP: case RPC_FC_UP: case RPC_FC_OP: case RPC_FC_FP: /* it's a pointer... */ if (t->ref && t->ref->type == RPC_FC_IP) { /* it's to an interface, which one? */ if (match(t->ref->name, "IDispatch")) return VT_DISPATCH; if (match(t->ref->name, "IUnknown")) return VT_UNKNOWN; } /* FIXME: should we recurse and add a VT_BYREF? */ /* Or just return VT_PTR? */ error("get_type_vt: unknown-deref-type: %d\n", t->ref->type); break; default: error("get_type_vt: unknown-type: %d\n", t->type); } return 0; } unsigned short get_var_vt(var_t *v) { unsigned short vt; if (v->tname) { vt = builtin_vt(v->tname); if (vt) return vt; } return get_type_vt(v->type); } void start_typelib(char *name, attr_t *attrs) { in_typelib++; if (!do_everything && !typelib_only) return; typelib = fopen(typelib_name, "wb"); } void end_typelib(void) { if (typelib) fclose(typelib); in_typelib--; } void add_interface(type_t *iface) { if (!typelib) return; /* FIXME: add interface and dependent types to typelib */ printf("add interface: %s\n", iface->name); } void add_coclass(class_t *cls) { ifref_t *lcur = cls->ifaces; ifref_t *cur; if (lcur) { while (NEXT_LINK(lcur)) lcur = NEXT_LINK(lcur); } if (!typelib) return; /* install interfaces the coclass depends on */ cur = lcur; while (cur) { add_interface(cur->iface); cur = PREV_LINK(cur); } /* FIXME: add coclass to typelib */ printf("add coclass: %s\n", cls->name); } void add_module(type_t *module) { if (!typelib) return; /* FIXME: add module to typelib */ printf("add module: %s\n", module->name); }
0.996094
high
2021.11.29-Lesson-10/Project2/myLib.h
021213/programming-c-rus-2021-2022
0
929985
<filename>2021.11.29-Lesson-10/Project2/myLib.h #pragma once int g(int); int f(int);
0.914063
low
AtlasBase/Clint/misc/ARCHDEF/IBMz19664/lapack/gcc/atlas_ctGetNB_geqrf.h
kevleyski/math-atlas
135
930497
#ifndef ATL_ctGetNB_geqrf /* * NB selection for GEQRF: Side='RIGHT', Uplo='UPPER' * M : 25,240,480,1040,1280,1520,2080 * N : 25,240,480,1040,1280,1520,2080 * NB : 4,40,20,24,80,80,80 */ #define ATL_ctGetNB_geqrf(n_, nb_) \ { \ if ((n_) < 132) (nb_) = 4; \ else if ((n_) < 360) (nb_) = 40; \ else if ((n_) < 760) (nb_) = 20; \ else if ((n_) < 1160) (nb_) = 24; \ else (nb_) = 80; \ } #endif /* end ifndef ATL_ctGetNB_geqrf */
0.664063
high
mtk/mmsdk_feature/mmsdk/feature/mmsdk/EffectHalBase.h
mhdzumair/android_device_e4
9
931009
<gh_stars>1-10 /* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein is * confidential and proprietary to MediaTek Inc. and/or its licensors. Without * the prior written permission of MediaTek inc. and/or its licensors, any * reproduction, modification, use or disclosure of MediaTek Software, and * information contained herein, in whole or in part, shall be strictly * prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER * ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR * NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK * SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE * RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE * MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE * CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek * Software") have been modified by MediaTek Inc. All revisions are subject to * any receiver's applicable license agreements with MediaTek Inc. */ #ifndef _MTK_PLATFORM_HARDWARE_INCLUDE_MTKCAM_EFFECT_HAL_BASE_H_ #define _MTK_PLATFORM_HARDWARE_INCLUDE_MTKCAM_EFFECT_HAL_BASE_H_ #include <mmsdk/IEffectHal.h> #include <utils/Vector.h> #include <utils/RefBase.h> /****************************************************************************** * ******************************************************************************/ namespace android { //class Vector; //class sp; class IGraphicBufferProducer; }; namespace NSCam { //class EffectHalBase : public IEffectHal /** * @brief EffectHalBase implement the IEffectHal inteface and declare pure virtual functions let feature owner implemenetation. * */ class EffectHalBase : public IEffectHal { public: EffectHalBase(); virtual ~EffectHalBase(); public: // may change state /** * @brief Change state to STATE_INIT and call initImpl() that overriding by derived class. * @details - This function couldn’t be overridden anymore. - This function should be called on STATE_UNINIT. - This function may change status to STATE_INIT. */ virtual android::status_t init() final; /** * @brief Change state to STATE_UNINIT and call uninitImpl() that overriding by derived class. * @details - This function couldn’t be overridden anymore. - This function should be called on STATE_INIT. - This function may change status to STATE_UNINIT. */ virtual android::status_t uninit() final; /** * @brief This function will check all capture parameters are setting done via allParameterConfigured() and change statue to STATE_CONFIGURED. * @details - This function couldn’t be overridden anymore. - This function should be called on STATE_INIT. - This function may change status to STATE_CONFIGURED. */ virtual android::status_t configure() final; /** * @brief Release resource and change status to STATE_INIT. * @details - This function couldn’t be overridden anymore. - This function should be called on STATE_CONFIGURED. - This function may change status to STATE_INIT. */ virtual android::status_t unconfigure() final; /** * @brief Start this session. Change state to STATE_RUNNING and call startImpl() that overriding by derived class. * @details - This function couldn’t be overridden anymore. - This function should be called on STATE_CONFIGURED. - This function may change status to STATE_RUNNING. */ virtual uint64_t start() final; /** * @brief Abort this session. This function will change state to STATE_CONFIGURED and call abortImpl() that overriding by derived class. * @details - This function couldn’t be overridden anymore. - This function should be called on STATE_RUNNING. - This function may change status to STATE_CONFIGURED. */ virtual android::status_t abort(EffectParameter const *parameter=NULL) final; public: // would not change state virtual android::status_t getNameVersion(EffectHalVersion &nameVersion) const final; virtual android::status_t setEffectListener(const android::wp<IEffectListener>&) final; virtual android::status_t setParameter(android::String8 &key, android::String8 &object) final; virtual android::status_t setParameters(const android::sp<EffectParameter> parameter) final; virtual android::status_t getCaptureRequirement(EffectParameter *inputParam, Vector<EffectCaptureRequirement> &requirements) const final; //non-blocking virtual android::status_t prepare() final; virtual android::status_t release() final; //non-blocking virtual android::status_t updateEffectRequest(const android::sp<EffectRequest> request) final; public: //debug public: //autotest private: android::wp<IEffectListener> mpListener; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- private: enum State {STATE_UNINIT = 0x01 , STATE_INIT = 0x02 , STATE_CONFIGURED = 0x04 , STATE_RUNNING = 0x08 }; State mState; bool mPrepared; uint64_t mUid; //android::Vector<android::sp<android::IGraphicBufferProducer> > mOutputSurfaces; protected: //call those in sub-class android::status_t prepareDone(const EffectResult& result, android::status_t state); // android::status_t addInputFrameDone(EffectResult result, const android::sp<EffectParameter> parameter, android::status_t state); //TTT3 // android::status_t addOutputFrameDone(EffectResult result, const android::sp<EffectParameter> parameter, android::status_t state); //TTT3 // android::status_t startDone(const EffectResult& result, const EffectParameter& parameter, android::status_t state); protected: //should be implement in sub-class virtual bool allParameterConfigured() = 0; virtual android::status_t initImpl() = 0; virtual android::status_t uninitImpl() = 0; //non-blocking virtual android::status_t prepareImpl() = 0; virtual android::status_t releaseImpl() = 0; virtual android::status_t getNameVersionImpl(EffectHalVersion &nameVersion) const = 0; virtual android::status_t getCaptureRequirementImpl(EffectParameter *inputParam, Vector<EffectCaptureRequirement> &requirements) const = 0; virtual android::status_t setParameterImpl(android::String8 &key, android::String8 &object) = 0; virtual android::status_t setParametersImpl(android::sp<EffectParameter> parameter) = 0; virtual android::status_t startImpl(uint64_t *uid=NULL) = 0; virtual android::status_t abortImpl(EffectResult &result, EffectParameter const *parameter=NULL) = 0; //non-blocking virtual android::status_t updateEffectRequestImpl(const android::sp<EffectRequest> request) = 0; }; } //namespace NSCam { #endif //_MTK_PLATFORM_HARDWARE_INCLUDE_MTKCAM_EFFECT_HAL_BASE_H_
0.996094
high
src/mirheo/core/marching_cubes.h
noabauma/Mirheo
22
931521
<filename>src/mirheo/core/marching_cubes.h // Copyright 2020 ETH Zurich. All Rights Reserved. #pragma once #include "domain.h" #include <functional> #include <vector> namespace mirheo { namespace marching_cubes { /// Represents a surface implicitly with a scalar field /// The zero level set represents the surface using ImplicitSurfaceFunction = std::function< real(real3) >; /// simple tructure that represents a triangle in 3D struct Triangle { real3 a; ///< vertex 0 real3 b; ///< vertex 1 real3 c; ///< vertex 2 }; /** \brief Create an explicit surface (triangles) from implicit surface (scalar field) using marching cubes \param [in] domain Domain information \param [in] resolution the number of grid points in each direction \param [in] surface The scalar field that represents implicitly the surface (0 levelset) \param [out] triangles The explicit surface representation */ void computeTriangles(DomainInfo domain, real3 resolution, const ImplicitSurfaceFunction& surface, std::vector<Triangle>& triangles); } // namespace marching_cubes } // namespace mirheo
0.996094
high
System/Library/PrivateFrameworks/NeutrinoCore.framework/NUVideoPlaybackFrameJob.h
zhangkn/iOS14Header
1
7065257
<reponame>zhangkn/iOS14Header /* * This header is generated by classdump-dyld 1.0 * on Sunday, September 27, 2020 at 11:45:08 AM Mountain Standard Time * Operating System: Version 14.0 (Build 18A373) * Image Source: /System/Library/PrivateFrameworks/NeutrinoCore.framework/NeutrinoCore * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <NeutrinoCore/NURenderJob.h> @interface NUVideoPlaybackFrameJob : NURenderJob -(id)initWithRequest:(id)arg1 ; -(id)result; -(BOOL)render:(out id*)arg1 ; -(id)renderer:(out id*)arg1 ; -(BOOL)wantsCompleteStage; -(BOOL)wantsPrepareNodeCached; -(BOOL)wantsRenderNodeCached; -(id)scalePolicy; -(id)newRenderPipelineStateForEvaluationMode:(long long)arg1 ; -(BOOL)wantsOutputVideoFrame; -(id)initWithVideoFrameRequest:(id)arg1 ; -(id)frameRequest; @end
0.605469
high
opencl/test/unit_test/os_interface/linux/device_command_stream_fixture_prelim.h
mattcarter2017/compute-runtime
0
7065769
<gh_stars>0 /* * Copyright (C) 2022 Intel Corporation * * SPDX-License-Identifier: MIT * */ #pragma once #include "shared/test/common/os_interface/linux/device_command_stream_fixture.h" #include "opencl/test/unit_test/os_interface/linux/device_command_stream_fixture_context.h" class DrmMockCustomPrelim : public DrmMockCustom { public: using Drm::cacheInfo; using Drm::ioctlHelper; using Drm::memoryInfo; DrmMockCustomPrelim(RootDeviceEnvironment &rootDeviceEnvironment) : DrmMockCustom(rootDeviceEnvironment) { setupIoctlHelper(IGFX_UNKNOWN); } void getPrelimVersion(std::string &prelimVersion) override { prelimVersion = "2.0"; } int ioctlExtra(unsigned long request, void *arg) override { return context.ioctlExtra(request, arg); } void execBufferExtensions(void *arg) override { return context.execBufferExtensions(arg); } DrmMockCustomPrelimContext context{}; };
0.988281
high
LittleBearDllNew/function/ShellCommand.h
satadriver/LittleBear
0
7066281
<reponame>satadriver/LittleBear #pragma once #ifndef RUN_CMD_H_H_H #define RUN_CMD_H_H_H DWORD __stdcall RunShellCmd(char *cmd); #endif
0.933594
low
fw/include/readline.h
emeb/OrangeCrab-Litex-ADC
2
7066793
#ifndef __READLINE_H__ #define __READLINE_H__ #include <stdlib.h> #include <stdio.h> #define CMD_LINE_BUFFER_SIZE 64 #define PROMPT "\e[92;1mlitex\e[0m> " #define ESC 27 struct esc_cmds { const char *seq; char val; }; #define CTL_CH(c) ((c) - 'a' + 1) /* Misc. non-Ascii keys */ #define KEY_UP CTL_CH('p') /* cursor key Up */ #define KEY_DOWN CTL_CH('n') /* cursor key Down */ #define KEY_RIGHT CTL_CH('f') /* Cursor Key Right */ #define KEY_LEFT CTL_CH('b') /* cursor key Left */ #define KEY_HOME CTL_CH('a') /* Cursor Key Home */ #define KEY_ERASE_TO_EOL CTL_CH('k') #define KEY_REFRESH_TO_EOL CTL_CH('e') #define KEY_ERASE_LINE CTL_CH('x') #define KEY_INSERT CTL_CH('o') #define KEY_CLEAR_SCREEN CTL_CH('l') #define KEY_DEL7 127 #define KEY_END 133 /* Cursor Key End */ #define KEY_PAGEUP 135 /* Cursor Key Page Up */ #define KEY_PAGEDOWN 136 /* Cursor Key Page Down */ #define KEY_DEL 137 /* Cursor Key Del */ #define MAX_CMDBUF_SIZE 256 #define CTL_BACKSPACE ('\b') #define DEL 255 #define DEL7 127 #define CREAD_HIST_CHAR ('!') #define HIST_MAX 10 #define putnstr(str,n) do { \ printf ("%.*s", n, str); \ } while (0) #define getcmd_putch(ch) putchar(ch) #define getcmd_cbeep() getcmd_putch('\a') #define ANSI_CLEAR_SCREEN "\e[2J\e[;H" #define BEGINNING_OF_LINE() { \ while (num) { \ getcmd_putch(CTL_BACKSPACE); \ num--; \ } \ } #define ERASE_TO_EOL() { \ if (num < eol_num) { \ int t; \ for (t = num; t < eol_num; t++) \ getcmd_putch(' '); \ while (t-- > num) \ getcmd_putch(CTL_BACKSPACE); \ eol_num = num; \ } \ } #define REFRESH_TO_EOL() { \ if (num < eol_num) { \ wlen = eol_num - num; \ putnstr(buf + num, (int)wlen); \ num = eol_num; \ } \ } int readline(char *buf, int len); void hist_init(void); #endif /* READLINE_H_ */
0.972656
high
Projects/RainDrops/RainDrops/RainDrops/PlayerFactory.h
kaushal135/NetworkingAstroids
0
7067305
#pragma once #include "Component.h" class PlayerFactory : public Component { DECLARE_DYNAMIC_DERIVED_CLASS(PlayerFactory, Component) enum NetworkPackets { SPAWN }; public: void initialize() override; virtual void update(float deltaTime); virtual void load(XMLElement* element); void spawnPlayer(RakNet::BitStream& bitStream); private: int numCurrentPlayer = 0; bool isSpawned[2] = { false, false }; STRCODE playerPrefabID[2]; STRCODE playerPool[2] = {0,0}; };
0.820313
high
src/r_exasol/connection/connection_establisher.h
exasol/r-exasol
12
7067817
<filename>src/r_exasol/connection/connection_establisher.h<gh_stars>10-100 #ifndef R_EXASOL_CONNECTION_ESTABLISHER_H #define R_EXASOL_CONNECTION_ESTABLISHER_H #include <string> #include <r_exasol/connection/connection_info.h> namespace exa { class ConnectionEstablisher { public: virtual ~ConnectionEstablisher() = default; virtual ConnectionInfo connect(const char *host, uint16_t port) = 0; }; } #endif //R_EXASOL_CONNECTION_ESTABLISHER_H
0.949219
high
Conditions/ConditionLE.h
yehonatansofri/SonySim
0
7068329
/** * class for less then or equal condition. * * @author Jhonny * @date 12.23.19 */ #ifndef CONDITIONLE_H #define CONDITIONLE_H #include "Condition.h" class ConditionLE : public Condition { public: int isTrue() override; ConditionLE(string left, string right) : Condition(left, right) {} ~ConditionLE() = default; }; #endif //CONDITIONLE_H
0.925781
high
2017/8/NSTimerFireDate/NSTimerFireDate/DetailViewController.h
chunxigege/learnDemo
0
7068841
<gh_stars>0 // // DetailViewController.h // NSTimerFireDate // // Created by chunxi on 2017/8/15. // Copyright © 2017年 chunxi. All rights reserved. // #import <UIKit/UIKit.h> @interface DetailViewController : UIViewController @end
0.417969
low
Lista_3Vetores/exercicio_vetores_15.c
nem080/Linguagem-C
2
7069353
<filename>Lista_3Vetores/exercicio_vetores_15.c /*exerxixio_15_vetores*/ #include <stdio.h> #include <stdlib.h> int vt[20]; int vt2[20]; int a, i, n = 0, rep = 0; int main() { printf("\n\tInsira uma contidade de vinte numeros\n\n"); for (i = 0; i < 20; i++) { printf("\t Digite o %d valor: ", i+1); scanf("%d", &vt[i]); if (i == 0) { vt2[n] = vt[i]; n++; } else { rep = 0; for (a = 0; a < n; a++) { if(vt[i] == vt2[a]) { rep++; } } if (rep < 1) { vt2[n] = vt[i]; n++; } } } for( i = 0; i < rep; i++) { for( a = 0; a < n; a++ ) { if( vt[i] == vt2[a] ) break; } if( a == n ) { vt2[n] = vt[i]; n++; } } printf("\n Vetor sem repetição: "); for (i = 0; i < n; i++) printf("%d ", vt2[i]); return 0; }
0.609375
high
sdk-6.5.20/src/sal/appl/pci_common.c
copslock/broadcom_cpri
0
7069865
<reponame>copslock/broadcom_cpri /* * * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. * * SAL PCI abstraction common to all platforms * See also: unix/pci.c */ #if !defined(BCM_ICS) && !defined(__KERNEL__) && !defined(GHS) #include <sal/types.h> #include <sal/appl/io.h> #include <sal/appl/pci.h> #ifndef PCI_MAX_BUS # ifdef PLISIM # define PCI_MAX_BUS 1 # else # define PCI_MAX_BUS 4 # endif #endif #ifndef PCI_MAX_DEV #define PCI_MAX_DEV 32 #endif #if defined(OVERRIDE_PCI_MAX_DEV) #undef PCI_MAX_DEV #define PCI_MAX_DEV OVERRIDE_PCI_MAX_DEV #endif #if defined(OVERRIDE_PCI_MAX_BUS) #undef PCI_MAX_BUS #define PCI_MAX_BUS OVERRIDE_PCI_MAX_BUS #endif #if defined(OVERRIDE_PCI_BUS_NO_START) #define PCI_BUS_NO_START OVERRIDE_PCI_BUS_NO_START #else #define PCI_BUS_NO_START 0 #endif /* * For historical reasons the PCI probe function skips device 12 * by default to prevent a system hang on certain platforms. * Override this value with zero to probe all PCI devices. */ #if defined(OVERRIDE_PCI_SKIP_DEV_MASK) #define PCI_SKIP_DEV_MASK OVERRIDE_PCI_SKIP_DEV_MASK #else #define PCI_SKIP_DEV_MASK (1L << 12) #endif /* * pci_device_iter * * Scans all PCI busses and slots. * Calls a user-supplied routine once per PCI device found. * Passes the device location (dev) and device IDs to the routine. * Continues as long as the user routine returns 0. * Otherwise, stops and returns the value from the user routine. */ int pci_device_iter(int (*rtn)(pci_dev_t *dev, uint16 pciVenID, uint16 pciDevID, uint8 pciRevID)) { uint32 venID, devID, revID; int rv = 0; pci_dev_t dev; sal_memset(&dev, 0, sizeof(pci_dev_t)); for (dev.busNo = PCI_BUS_NO_START; dev.busNo < PCI_MAX_BUS && rv == 0; dev.busNo++) { for (dev.devNo = 0; dev.devNo < PCI_MAX_DEV && rv == 0; dev.devNo++) { if ((1L << dev.devNo) & PCI_SKIP_DEV_MASK) { continue; } venID = pci_config_getw(&dev, PCI_CONF_VENDOR_ID) & 0xffff; if (venID == 0xffff) { continue; } devID = pci_config_getw(&dev, PCI_CONF_VENDOR_ID) >> 16; revID = pci_config_getw(&dev, PCI_CONF_REVISION_ID) & 0xff; rv = (*rtn)(&dev, venID, devID, revID); } } return rv; } /* * Scan function 0 of all busses and devices, printing a line for each * device found. */ void pci_print_all(void) { int dev_count = PCI_MAX_DEV; int bus_count = PCI_MAX_BUS; pci_dev_t dev; /* coverity[stack_use_callee_max : FALSE] */ sal_memset(&dev, 0, sizeof(pci_dev_t)); sal_printf("Scanning function 0 of PCI busses 0-%d, devices 0-%d\n", bus_count - 1, dev_count - 1); sal_printf("bus dev fn venID devID class rev MBAR0 MBAR1 MBAR2 MBAR3 MBAR4 MBAR5 IPIN ILINE\n"); for (dev.busNo = PCI_BUS_NO_START; dev.busNo < bus_count; dev.busNo++) for (dev.devNo = 0; dev.devNo < dev_count; dev.devNo++) { uint32 vendorID, deviceID, class, revID; uint32 MBAR0, MBAR1, MBAR2, MBAR3, MBAR4, MBAR5, ipin, iline; vendorID = (pci_config_getw(&dev, PCI_CONF_VENDOR_ID) & 0x0000ffff); if (vendorID == 0xffff) continue; #define CONFIG(offset) pci_config_getw(&dev, (offset)) deviceID = (CONFIG(PCI_CONF_VENDOR_ID) & 0xffff0000) >> 16; class = (CONFIG(PCI_CONF_REVISION_ID) & 0xffffff00) >> 8; revID = (CONFIG(PCI_CONF_REVISION_ID) & 0x000000ff) >> 0; MBAR0 = (CONFIG(PCI_CONF_BAR0) & 0xffffffff) >> 0; MBAR1 = (CONFIG(PCI_CONF_BAR1) & 0xffffffff) >> 0; MBAR2 = (CONFIG(PCI_CONF_BAR2) & 0xffffffff) >> 0; MBAR3 = (CONFIG(PCI_CONF_BAR3) & 0xffffffff) >> 0; MBAR4 = (CONFIG(PCI_CONF_BAR4) & 0xffffffff) >> 0; MBAR5 = (CONFIG(PCI_CONF_BAR5) & 0xffffffff) >> 0; iline = (CONFIG(PCI_CONF_INTERRUPT_LINE) & 0x000000ff) >> 0; ipin = (CONFIG(PCI_CONF_INTERRUPT_LINE) & 0x0000ff00) >> 8; #undef CONFIG sal_printf("%02x %02x %02x %04x %04x " "%06x %02x %08x %08x %08x %08x %08x %08x %02x %02x\n", dev.busNo, dev.devNo, dev.funcNo, vendorID, deviceID, class, revID, MBAR0, MBAR1, MBAR2, MBAR3, MBAR4, MBAR5, ipin, iline); } } void pci_print_config(pci_dev_t *dev) { uint32 data; data = pci_config_getw(dev, PCI_CONF_VENDOR_ID); sal_printf("%04x: %08x DeviceID=%04x VendorID=%04x\n", PCI_CONF_VENDOR_ID, data, (data & 0xffff0000) >> 16, (data & 0x0000ffff) >> 0); data = pci_config_getw(dev, PCI_CONF_COMMAND); sal_printf("%04x: %08x Status=%04x Command=%04x\n", PCI_CONF_COMMAND, data, (data & 0xffff0000) >> 16, (data & 0x0000ffff) >> 0); data = pci_config_getw(dev, PCI_CONF_REVISION_ID); sal_printf("%04x: %08x ClassCode=%06x RevisionID=%02x\n", PCI_CONF_REVISION_ID, data, (data & 0xffffff00) >> 8, (data & 0x000000ff) >> 0); data = pci_config_getw(dev, PCI_CONF_CACHE_LINE_SIZE); sal_printf("%04x: %08x BIST=%02x HeaderType=%02x " "LatencyTimer=%02x CacheLineSize=%02x\n", PCI_CONF_CACHE_LINE_SIZE, data, (data & 0xff000000) >> 24, (data & 0x00ff0000) >> 16, (data & 0x0000ff00) >> 8, (data & 0x000000ff) >> 0); data = pci_config_getw(dev, PCI_CONF_BAR0); sal_printf("%04x: %08x BaseAddress0=%08x\n", PCI_CONF_BAR0, data, data); data = pci_config_getw(dev, PCI_CONF_BAR1); sal_printf("%04x: %08x BaseAddress1=%08x\n", PCI_CONF_BAR1, data, data); data = pci_config_getw(dev, PCI_CONF_BAR2); sal_printf("%04x: %08x BaseAddress2=%08x\n", PCI_CONF_BAR2, data, data); data = pci_config_getw(dev, PCI_CONF_BAR3); sal_printf("%04x: %08x BaseAddress3=%08x\n", PCI_CONF_BAR3, data, data); data = pci_config_getw(dev, PCI_CONF_BAR4); sal_printf("%04x: %08x BaseAddress4=%08x\n", PCI_CONF_BAR4, data, data); data = pci_config_getw(dev, PCI_CONF_BAR5); sal_printf("%04x: %08x BaseAddress5=%08x\n", PCI_CONF_BAR5, data, data); data = pci_config_getw(dev, PCI_CONF_CB_CIS_PTR); sal_printf("%04x: %08x CardbusCISPointer=%08x\n", PCI_CONF_CB_CIS_PTR, data, data); data = pci_config_getw(dev, PCI_CONF_SUBSYS_VENDOR_ID); sal_printf("%04x: %08x SubsystemID=%02x SubsystemVendorID=%02x\n", PCI_CONF_SUBSYS_VENDOR_ID, data, (data & 0xffff0000) >> 16, (data & 0x0000ffff) >> 0); data = pci_config_getw(dev, PCI_CONF_EXP_ROM); sal_printf("%04x: %08x ExpansionROMBaseAddress=%08x\n", PCI_CONF_EXP_ROM, data, data); data = pci_config_getw(dev, 0x34); sal_printf("%04x: %08x Reserved=%06x CapabilitiesPointer=%02x\n", 0x34, data, (data & 0xffffff00) >> 8, (data & 0x000000ff) >> 0); data = pci_config_getw(dev, 0x38); sal_printf("%04x: %08x Reserved=%08x\n", 0x38, data, data); data = pci_config_getw(dev, PCI_CONF_INTERRUPT_LINE); sal_printf("%04x: %08x Max_Lat=%02x Min_Gnt=%02x " "InterruptLine=%02x InterruptPin=%02x\n", PCI_CONF_INTERRUPT_LINE, data, (data & 0xff000000) >> 24, (data & 0x00ff0000) >> 16, (data & 0x0000ff00) >> 8, (data & 0x000000ff) >> 0); data = pci_config_getw(dev, 0x40); sal_printf("%04x: %08x Reserved=%02x " "RetryTimeoutValue=%02x TRDYTimeoutValue=%02x\n", 0x40, data, (data & 0xffff0000) >> 16, (data & 0x0000ff00) >> 8, (data & 0x000000ff) >> 0); } #else typedef int _sal_appl_pci_common_not_empty; /* Make ISO compilers happy. */ #endif /* !BCM_ICS && !LINUX && !GHS */
0.996094
high
ArtikCloud/Model/ACCertificateFields.h
artikcloud/artikcloud-objc
2
7070377
<filename>ArtikCloud/Model/ACCertificateFields.h #import <Foundation/Foundation.h> #import "ACObject.h" /** * ARTIK Cloud API * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: 2.0.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ #import "ACValidityPeriod.h" @protocol ACCertificateFields @end @interface ACCertificateFields : ACObject /* version [optional] */ @property(nonatomic) NSNumber* version; /* serialNumber [optional] */ @property(nonatomic) NSString* serialNumber; /* signatureAlgorithm [optional] */ @property(nonatomic) NSString* signatureAlgorithm; /* subject [optional] */ @property(nonatomic) NSString* subject; /* issuer [optional] */ @property(nonatomic) NSString* issuer; @property(nonatomic) ACValidityPeriod* validity; @end
0.855469
high
OSGViewWrap/OSGEarthView.h
dgk0218/My3DFactoryPublic
2
7070889
pragma once #include <windows.h> #include <osgViewer/Viewer> #include <osgViewer/ViewerEventHandlers> #include <osgViewer/api/win32/GraphicsWindowWin32> #include <osgGA/TrackballManipulator> #include <osgGA/KeySwitchMatrixManipulator> #include <osgDB/DatabasePager> #include <osgDB/Registry> #include <osgDB/ReadFile> #include <osgUtil/Optimizer> #include <string> #include <osgGA/StateSetManipulator> #include <osgEarth/EarthManipulator> #include <osgEarth/Map> #include <osgEarth/MapNode> //#include <osgEarthDrivers/tms/TMSOptions> //#include <osgEarthDrivers/model_feature_geom/FeatureGeomModelOptions> //#include <osgEarthDrivers/feature_ogr/OGRFeatureOptions> #include <osgEarthDrivers/cache_filesystem/FileSystemCache> #include <osgEarth/EarthManipulator> #include <osgEarth/GeodeticGraticule> #include <osgEarth/LatLongFormatter> #include <osgEarth/Controls> #include <osgEarth/MouseCoordsTool> #include <osgEarth/AutoClipPlaneHandler> #include <osg/PositionAttitudeTransform> #include <osg/Group> #include <osg/Node> #include <osgDB/ReadFile> #include <osgEarth/ImageLayer> #include <osgEarth/Notify> #include <osgEarth/EarthManipulator> #include <osgEarth/ExampleResources> #include <osgEarth/MapNode> //#include <osgEarth/ThreadingUtils> #include <osgEarth/Metrics> using namespace osgEarth::Util; class OSGWrapper { public: OSGWrapper(HWND hWnd); ~OSGWrapper(); void InitOSG(std::string filename); void InitManipulators(void); void InitSceneGraph(void); void InitCameraConfig(void); void PreFrameUpdate(void); void PostFrameUpdate(void); void Done(bool value) { mDone = value; } bool Done(void) { return mDone; } osg::ref_ptr<osgViewer::Viewer> getViewer() { return viewer; } osg::ref_ptr<EarthManipulator> getEm() { return manip; } osg::ref_ptr<osg::Group> getRoot() { return mRoot; } osg::ref_ptr<osgEarth::Map> getMap() { return mMap; } osg::ref_ptr<osgEarth::MapNode> getMapNode() { return mMapNode; } private: bool mDone; std::string m_ModelName; HWND m_hWnd; osg::ref_ptr<osgViewer::Viewer> viewer; osg::ref_ptr<osg::Group> mRoot; osg::ref_ptr<osg::Node> mModel; osg::ref_ptr<osgEarth::Map> mMap; osg::ref_ptr<osgEarth::MapNode> mMapNode; osg::ref_ptr < EarthManipulator> manip; }; class CRenderingThread : public OpenThreads::Thread { public: CRenderingThread(OSGWrapper* ptr); CRenderingThread(OSGWrapper* ptr, bool is3dThread); virtual ~CRenderingThread(); void Done(bool); bool isEnd(); void setOsgRuningFlag(bool); bool getOsgRuningState(); virtual void run(); protected: OSGWrapper* _ptr; bool _done; bool _is3Dthread; bool _osgRuningFlag; bool _osgRuningState; };
0.984375
high
usr/libexec/nsurlsessiond/PDURLSessionProxyInvalidateSession.h
lechium/tvOS135Headers
2
7071401
<gh_stars>1-10 // // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Jun 10 2020 10:03:13). // // Copyright (C) 1997-2019 <NAME>. // #import <ProtocolBuffer/PBCodable.h> #import "NSCopying-Protocol.h" @class PDURLSessionProxySessionMessage; @interface PDURLSessionProxyInvalidateSession : PBCodable <NSCopying> { PDURLSessionProxySessionMessage *_session; // 8 = 0x8 _Bool _shouldCancel; // 16 = 0x10 struct { unsigned int shouldCancel:1; } _has; // 20 = 0x14 } - (void).cxx_destruct; // IMP=0x0000000100038ee0 @property(nonatomic) _Bool shouldCancel; // @synthesize shouldCancel=_shouldCancel; @property(retain, nonatomic) PDURLSessionProxySessionMessage *session; // @synthesize session=_session; - (void)mergeFrom:(id)arg1; // IMP=0x0000000100038e1c - (unsigned long long)hash; // IMP=0x0000000100038db4 - (_Bool)isEqual:(id)arg1; // IMP=0x0000000100038cd0 - (id)copyWithZone:(struct _NSZone *)arg1; // IMP=0x0000000100038c28 - (void)copyTo:(id)arg1; // IMP=0x0000000100038bb0 - (void)writeTo:(id)arg1; // IMP=0x0000000100038b40 - (_Bool)readFrom:(id)arg1; // IMP=0x0000000100038894 - (id)dictionaryRepresentation; // IMP=0x00000001000387a4 - (id)description; // IMP=0x00000001000386f0 @property(nonatomic) _Bool hasShouldCancel; @property(readonly, nonatomic) _Bool hasSession; @end
0.84375
high
rtdb/rtmalloc/tlsf-arch_dep.h
mischumok/kogmo-rtdb
1
7071913
<gh_stars>1-10 /* * Two Levels Segregate Fit memory allocator (TLSF) * Version 2.2.0 * * Written by <NAME> <<EMAIL>> * * Thanks to <NAME> for his suggestions and reviews * * Copyright (C) 2006, 2005, 2004 * * This code is released using a dual license strategy: GPL/LGPL * You can choose the licence that better fits your requirements. * * Released under the terms of the GNU General Public License Version 2.0 * Released under the terms of the GNU Lesser General Public License Version 2.1 * */ #ifndef _ARCH_DEP_H_ #define _ARCH_DEP_H_ #ifdef _IA32_ static inline int _ffs(int x) { int r; __asm__("bsfl %1,%0\n\t" "jnz 1f\n\t" "movl $-1,%0\n" "1:" : "=r" (r) : "g" (x)); return r; } static inline int _fls(int x) { int r; __asm__("bsrl %1,%0\n\t" "jnz 1f\n\t" "movl $-1,%0\n" "1:" : "=r" (r) : "g" (x)); return r; } #else static inline int _ffs (int x) { int r = 0; if (!x) return -1; if (!(x & 0xffff)) { x >>= 16; r += 16; } if (!(x & 0xff)) { x >>= 8; r += 8; } if (!(x & 0xf)) { x >>= 4; r += 4; } if (!(x & 0x3)) { x >>= 2; r += 2; } if (!(x & 0x1)) { x >>= 1; r += 1; } return r; } static inline int _fls (int x) { int r = 31; if (!x) return -1; if (!(x & 0xffff0000)) { x <<= 16; r -= 16; } if (!(x & 0xff000000)) { x <<= 8; r -= 8; } if (!(x & 0xf0000000)) { x <<= 4; r -= 4; } if (!(x & 0xc0000000)) { x <<= 2; r -= 2; } if (!(x & 0x80000000)) { x <<= 1; r -= 1; } return r; } #endif #endif /* !_ARCH_DEP_H_ */
0.972656
high
Frameworks/MapKit.framework/MKMapItemMetadataDealRequest.h
shaojiankui/iOS10-Runtime-Headers
36
7072425
/* Generated by RuntimeBrowser Image: /System/Library/Frameworks/MapKit.framework/MapKit */ @interface MKMapItemMetadataDealRequest : MKMapItemMetadataRequest { id /* block */ _dealHandler; } @property (nonatomic, copy) id /* block */ dealHandler; + (id)requestWithMapItem:(id)arg1; - (void).cxx_destruct; - (id /* block */)dealHandler; - (void)handleData:(id)arg1; - (void)handleError:(id)arg1; - (void)setDealHandler:(id /* block */)arg1; - (id)url; - (id)urlRequest; @end
0.574219
medium
interfaces/dia/plug-ins/dxf/dxf-import.c
krattai/monoflow
1
7072937
/* -*- Mode: C; c-basic-offset: 4 -*- */ /* Dia -- an diagram creation/manipulation program * Copyright (C) 1998 <NAME> * * dxf-import.c: dxf import filter for dia * Copyright (C) 2000 <NAME> * Copyright (C) 2002 <NAME> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <glib.h> #include <glib/gstdio.h> #include "intl.h" #include "message.h" #include "geometry.h" #include "diarenderer.h" #include "filter.h" #include "object.h" #include "properties.h" #include "propinternals.h" #include "autocad_pal.h" #include "group.h" #include "create.h" #include "attributes.h" static real coord_scale = 1.0, measure_scale = 1.0; static real text_scale = 1.0; #define WIDTH_SCALE (coord_scale * measure_scale) #define DEFAULT_LINE_WIDTH 0.001 Point extent_min, extent_max; Point limit_min, limit_max; /* maximum line length */ #define DXF_LINE_LENGTH 256 typedef struct _DxfLayerData { char layerName[256]; int acad_colour; } DxfLayerData; typedef struct _DxfData { int code; char codeline[DXF_LINE_LENGTH]; char value[DXF_LINE_LENGTH]; } DxfData; gboolean import_dxf(const gchar *filename, DiagramData *dia, void* user_data); gboolean read_dxf_codes(FILE *filedxf, DxfData *data); DiaObject *read_entity_line_dxf(FILE *filedxf, DxfData *data, DiagramData *dia); DiaObject *read_entity_circle_dxf(FILE *filedxf, DxfData *data, DiagramData *dia); DiaObject *read_entity_ellipse_dxf(FILE *filedxf, DxfData *data, DiagramData *dia); DiaObject *read_entity_arc_dxf(FILE *filedxf, DxfData *data, DiagramData *dia); DiaObject *read_entity_solid_dxf(FILE *filedxf, DxfData *data, DiagramData *dia); DiaObject *read_entity_polyline_dxf(FILE *filedxf, DxfData *data, DiagramData *dia); DiaObject *read_entity_text_dxf(FILE *filedxf, DxfData *data, DiagramData *dia); void read_entity_measurement_dxf(FILE *filedxf, DxfData *data, DiagramData *dia); void read_entity_scale_dxf(FILE *filedxf, DxfData *data, DiagramData *dia); void read_entity_textsize_dxf(FILE *filedxf, DxfData *data, DiagramData *dia); void read_entity_mesurement_dxf(FILE *filedxf, DxfData *data, DiagramData *dia); void read_table_layer_dxf(FILE *filedxf, DxfData *data, DiagramData *dia); void read_section_header_dxf(FILE *filedxf, DxfData *data, DiagramData *dia); void read_section_classes_dxf(FILE *filedxf, DxfData *data, DiagramData *dia); void read_section_tables_dxf(FILE *filedxf, DxfData *data, DiagramData *dia); void read_section_entities_dxf(FILE *filedxf, DxfData *data, DiagramData *dia); void read_section_blocks_dxf(FILE *filedxf, DxfData *data, DiagramData *dia); Layer *layer_find_by_name(char *layername, DiagramData *dia); LineStyle get_dia_linestyle_dxf(char *dxflinestyle); /* returns the layer with the given name */ /* TODO: merge this with other layer code? */ Layer * layer_find_by_name(char *layername, DiagramData *dia) { Layer *matching_layer, *layer; guint i; matching_layer = NULL; for (i=0; i<dia->layers->len; i++) { layer = (Layer *)g_ptr_array_index(dia->layers, i); if(strcmp(layer->name, layername) == 0) { matching_layer = layer; break; } } if( matching_layer == NULL ) { matching_layer = new_layer(g_strdup( layername ), dia); data_add_layer(dia, matching_layer); } return matching_layer; } /* returns the matching dia linestyle for a given dxf linestyle */ /* if no matching style is found, LINESTYLE solid is returned as a default */ LineStyle get_dia_linestyle_dxf(char *dxflinestyle) { if (strcmp(dxflinestyle, "DASHED") == 0) return LINESTYLE_DASHED; if (strcmp(dxflinestyle, "DASHDOT") == 0) return LINESTYLE_DASH_DOT; if (strcmp(dxflinestyle, "DOT") == 0) return LINESTYLE_DOTTED; if (strcmp(dxflinestyle, "DIVIDE") == 0) return LINESTYLE_DASH_DOT_DOT; return LINESTYLE_SOLID; } static PropDescription dxf_prop_descs[] = { { "start_point", PROP_TYPE_POINT }, { "end_point", PROP_TYPE_POINT }, { "line_colour", PROP_TYPE_COLOUR }, { PROP_STDNAME_LINE_WIDTH, PROP_STDTYPE_LINE_WIDTH }, { "line_style", PROP_TYPE_LINESTYLE}, PROP_DESC_END}; /* reads a line entity from the dxf file and creates a line object in dia*/ DiaObject * read_entity_line_dxf(FILE *filedxf, DxfData *data, DiagramData *dia) { /* line data */ Point start, end; DiaObjectType *otype = object_get_type("Standard - Line"); Handle *h1, *h2; DiaObject *line_obj; Color line_colour = { 0.0, 0.0, 0.0 }; RGB_t color; GPtrArray *props; PointProperty *ptprop; LinestyleProperty *lsprop; ColorProperty *cprop; RealProperty *rprop; real line_width = DEFAULT_LINE_WIDTH; LineStyle style = LINESTYLE_SOLID; Layer *layer = dia->active_layer; end.x=0; end.y=0; do { if(read_dxf_codes(filedxf, data) == FALSE){ return( NULL ); } switch(data->code){ case 6: style = get_dia_linestyle_dxf(data->value); break; case 8: layer = layer_find_by_name(data->value, dia); break; case 10: start.x = g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; break; case 11: end.x = g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; break; case 20: start.y = (-1)*g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; break; case 21: end.y = (-1)*g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; break; case 39: line_width = g_ascii_strtod(data->value, NULL) * WIDTH_SCALE; /*printf( "line width %f\n", line_width ); */ break; case 62 : color = pal_get_rgb (atoi(data->value)); line_colour.red = color.r / 255.0; line_colour.green = color.g / 255.0; line_colour.blue = color.b / 255.0; break; } } while(data->code != 0); line_obj = otype->ops->create(&start, otype->default_user_data, &h1, &h2); props = prop_list_from_descs(dxf_prop_descs,pdtpp_true); g_assert(props->len == 5); ptprop = g_ptr_array_index(props,0); ptprop->point_data = start; ptprop = g_ptr_array_index(props,1); ptprop->point_data = end; cprop = g_ptr_array_index(props,2); cprop->color_data = line_colour; rprop = g_ptr_array_index(props,3); rprop->real_data = line_width; lsprop = g_ptr_array_index(props,4); lsprop->style = style; lsprop->dash = 1.0; line_obj->ops->set_props(line_obj, props); prop_list_free(props); if (layer) layer_add_object(layer, line_obj); else return line_obj; /* don't add it it twice */ return NULL; } static PropDescription dxf_solid_prop_descs[] = { { "line_colour", PROP_TYPE_COLOUR }, { PROP_STDNAME_LINE_WIDTH, PROP_STDTYPE_LINE_WIDTH }, { "line_style", PROP_TYPE_LINESTYLE }, { "fill_colour", PROP_TYPE_COLOUR }, { "show_background", PROP_TYPE_BOOL }, PROP_DESC_END}; /* reads a solid entity from the dxf file and creates a polygon object in dia*/ DiaObject * read_entity_solid_dxf(FILE *filedxf, DxfData *data, DiagramData *dia) { /* polygon data */ Point p[4]; DiaObjectType *otype = object_get_type("Standard - Polygon"); Handle *h1, *h2; DiaObject *polygon_obj; MultipointCreateData *pcd; Color fill_colour = { 0.5, 0.5, 0.5 }; GPtrArray *props; LinestyleProperty *lsprop; ColorProperty *cprop, *fprop; RealProperty *rprop; BoolProperty *bprop; real line_width = 0.001; LineStyle style = LINESTYLE_SOLID; Layer *layer = dia->active_layer; RGB_t color; /* printf( "Solid " ); */ do { if(read_dxf_codes(filedxf, data) == FALSE){ return( NULL ); } switch(data->code){ case 6: style = get_dia_linestyle_dxf(data->value); break; case 8: layer = layer_find_by_name(data->value, dia); /*printf( "layer: %s ", data->value );*/ break; case 10: p[0].x = g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; /*printf( "P0.x: %f ", p[0].x );*/ break; case 11: p[1].x = g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; /*printf( "P1.x: %f ", p[1].x );*/ break; case 12: p[2].x = g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; /*printf( "P2.x: %f ", p[2].x );*/ break; case 13: p[3].x = g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; /*printf( "P3.x: %f ", p[3].x );*/ break; case 20: p[0].y = (-1)*g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; /*printf( "P0.y: %f ", p[0].y );*/ break; case 21: p[1].y = (-1)*g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; /*printf( "P1.y: %f ", p[1].y );*/ break; case 22: p[2].y = (-1)*g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; /*printf( "P2.y: %f ", p[2].y );*/ break; case 23: p[3].y = (-1)*g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; /*printf( "P3.y: %f\n", p[3].y );*/ break; case 39: line_width = g_ascii_strtod(data->value, NULL) * WIDTH_SCALE; /*printf( "width %f\n", line_width );*/ break; case 62: color = pal_get_rgb (atoi(data->value)); fill_colour.red = color.r / 255.0; fill_colour.green = color.g / 255.0; fill_colour.blue = color.b / 255.0; break; } } while(data->code != 0); pcd = g_new( MultipointCreateData, 1); if( p[2].x != p[3].x || p[2].y != p[3].y ) pcd->num_points = 4; else pcd->num_points = 3; pcd->points = g_new( Point, pcd->num_points ); memcpy( pcd->points, p, sizeof( Point ) * pcd->num_points ); polygon_obj = otype->ops->create( NULL, pcd, &h1, &h2 ); props = prop_list_from_descs( dxf_solid_prop_descs, pdtpp_true ); g_assert(props->len == 5); cprop = g_ptr_array_index( props,0 ); cprop->color_data = fill_colour; rprop = g_ptr_array_index( props,1 ); rprop->real_data = line_width; lsprop = g_ptr_array_index( props,2 ); lsprop->style = style; lsprop->dash = 1.0; fprop = g_ptr_array_index( props, 3 ); fprop->color_data = fill_colour; bprop = g_ptr_array_index( props, 4 ); bprop->bool_data = TRUE; polygon_obj->ops->set_props( polygon_obj, props ); prop_list_free(props); if (layer) layer_add_object( layer, polygon_obj ); else return polygon_obj; return NULL; } static PropDescription dxf_polyline_prop_descs[] = { { "line_colour", PROP_TYPE_COLOUR }, { PROP_STDNAME_LINE_WIDTH, PROP_STDTYPE_LINE_WIDTH }, { "line_style", PROP_TYPE_LINESTYLE }, PROP_DESC_END}; static int is_equal( double a, double b ) { double epsilon = 0.00001; if( a == b ) return( 1 ); if(( a + epsilon ) > b && ( a - epsilon ) < b ) return( 1 ); return( 0 ); } /* reads a polyline entity from the dxf file and creates a polyline object in dia*/ DiaObject * read_entity_polyline_dxf(FILE *filedxf, DxfData *data, DiagramData *dia) { int i; /* polygon data */ Point *p = NULL, start, end, center; DiaObjectType *otype = object_get_type("Standard - PolyLine"); Handle *h1, *h2; DiaObject *polyline_obj; MultipointCreateData *pcd; Color line_colour = { 0.0, 0.0, 0.0 }; GPtrArray *props; LinestyleProperty *lsprop; ColorProperty *cprop; RealProperty *rprop; real line_width = DEFAULT_LINE_WIDTH; real radius, start_angle = 0; LineStyle style = LINESTYLE_SOLID; Layer *layer = dia->active_layer; RGB_t color; unsigned char closed = 0; int points = 0; real bulge = 0.0; int bulge_end = -1; gboolean bulge_x_avail = FALSE, bulge_y_avail = FALSE; do { if(read_dxf_codes(filedxf, data) == FALSE){ return( NULL ); } switch(data->code){ case 0: if( !strcmp( data->value, "VERTEX" )) { points++; p = g_realloc( p, sizeof( Point ) * points ); /*printf( "Vertex %d\n", points );*/ } break; case 6: style = get_dia_linestyle_dxf(data->value); break; case 8: layer = layer_find_by_name(data->value, dia); /*printf( "layer: %s ", data->value );*/ break; case 10: if( points != 0 ) { p[points-1].x = g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; /*printf( "P[%d].x: %f ", points-1, p[points-1].x );*/ bulge_x_avail = (bulge_end == points); } break; case 20: if( points != 0 ) { p[points-1].y = (-1)*g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; /*printf( "P[%d].y: %f\n", points-1, p[points-1].y );*/ bulge_y_avail = (bulge_end == points); } break; case 39: line_width = g_ascii_strtod(data->value, NULL) * WIDTH_SCALE; /*printf( "width %f\n", line_width );*/ break; case 40: /* default starting width */ case 41: /* default ending width */ line_width = g_ascii_strtod(data->value, NULL) * WIDTH_SCALE; break; case 42: bulge = g_ascii_strtod(data->value, NULL); /* The bulge is meant to be _between_ two VERTEX, here: p[points-1] and p[points,] * but we have not yet read the end point; so just remember the point to 'bulge to' */ bulge_end = points+1; bulge_x_avail = bulge_y_avail = FALSE; break; case 62: color = pal_get_rgb (atoi(data->value)); line_colour.red = color.r / 255.0; line_colour.green = color.g / 255.0; line_colour.blue = color.b / 255.0; break; case 70: closed = 1 & atoi( data->value ); /*printf( "closed %d %s", closed, data->value );*/ break; } if (points == bulge_end && bulge_x_avail && bulge_y_avail) { /* turn the last segment into a bulge */ p = g_realloc( p, sizeof( Point ) * ( points + 10 )); if (points < 2) continue; start = p[points-2]; end = p[points-1]; radius = sqrt( pow( end.x - start.x, 2 ) + pow( end.y - start.y, 2 ))/2; center.x = start.x + ( end.x - start.x )/2; center.y = start.y + ( end.y - start.y )/2; if( is_equal( start.x, end.x )) { if( is_equal( start.y, end.y )) { continue; /* better than complaining? */ g_warning("Bad vertex bulge"); } else if( start.y > center.y ) { /*start_angle = 90.0;*/ start_angle = M_PI/2; } else { /*start_angle = 270.0;*/ start_angle = M_PI * 1.5; } } else if( is_equal( start.y, end.y )) { if( is_equal( start.x, end.x )) { continue; g_warning("Bad vertex bulge"); } else if( start.x > center.x ) { start_angle = 0.0; } else { start_angle = M_PI; } } else { start_angle = atan( center.y - start.y /center.x - start.x ); } /*printf( "start x %f end x %f center x %f\n", start.x, end.x, center.x ); printf( "start y %f end y %f center y %f\n", start.y, end.y, center.y ); printf( "bulge %s %f startx_angle %f\n", data->value, radius, start_angle );*/ for( i=(points-1); i<(points+9); i++ ) { p[i].x = center.x + cos( start_angle ) * radius; p[i].y = center.y + sin( start_angle ) * radius; start_angle += (-M_PI/10.0 * bulge); /*printf( "i %d x %f y %f\n", i, p[i].x, p[i].y );*/ } points += 10; p[points-1] = end; } } while( strcmp( data->value, "SEQEND" )); if( points == 0 ) { printf( "No vertexes defined\n" ); return( NULL ); } pcd = g_new( MultipointCreateData, 1); if( closed ) { otype = object_get_type("Standard - Polygon"); } pcd->num_points = points; pcd->points = g_new( Point, pcd->num_points ); memcpy( pcd->points, p, sizeof( Point ) * pcd->num_points ); g_free( p ); polyline_obj = otype->ops->create( NULL, pcd, &h1, &h2 ); props = prop_list_from_descs( dxf_polyline_prop_descs, pdtpp_true ); g_assert( props->len == 3 ); cprop = g_ptr_array_index( props,0 ); cprop->color_data = line_colour; rprop = g_ptr_array_index( props,1 ); rprop->real_data = line_width; lsprop = g_ptr_array_index( props,2 ); lsprop->style = style; lsprop->dash = 1.0; polyline_obj->ops->set_props( polyline_obj, props ); prop_list_free(props); if (layer) layer_add_object( layer, polyline_obj ); else return polyline_obj; return NULL; /* don't add it twice */ } static PropDescription dxf_ellipse_prop_descs[] = { { "elem_corner", PROP_TYPE_POINT }, { "elem_width", PROP_TYPE_REAL }, { "elem_height", PROP_TYPE_REAL }, { "line_colour", PROP_TYPE_COLOUR }, { PROP_STDNAME_LINE_WIDTH, PROP_STDTYPE_LINE_WIDTH }, { "show_background", PROP_TYPE_BOOL}, PROP_DESC_END}; /* reads a circle entity from the dxf file and creates a circle object in dia*/ DiaObject *read_entity_circle_dxf(FILE *filedxf, DxfData *data, DiagramData *dia) { /* circle data */ Point center; real radius = 1.0; DiaObjectType *otype = object_get_type("Standard - Ellipse"); Handle *h1, *h2; DiaObject *ellipse_obj; Color line_colour = { 0.0, 0.0, 0.0 }; PointProperty *ptprop; RealProperty *rprop; BoolProperty *bprop; ColorProperty *cprop; GPtrArray *props; real line_width = DEFAULT_LINE_WIDTH; Layer *layer = dia->active_layer; do { if(read_dxf_codes(filedxf, data) == FALSE){ return( NULL ); } switch(data->code){ case 8: layer = layer_find_by_name(data->value, dia); break; case 10: center.x = g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; break; case 20: center.y = (-1)*g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; break; case 39: line_width = g_ascii_strtod(data->value, NULL) * WIDTH_SCALE; break; case 40: radius = g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; break; } } while(data->code != 0); center.x -= radius; center.y -= radius; ellipse_obj = otype->ops->create(&center, otype->default_user_data, &h1, &h2); props = prop_list_from_descs(dxf_ellipse_prop_descs,pdtpp_true); g_assert(props->len == 6); ptprop = g_ptr_array_index(props,0); ptprop->point_data = center; rprop = g_ptr_array_index(props,1); rprop->real_data = radius * 2.0; rprop = g_ptr_array_index(props,2); rprop->real_data = radius * 2.0; cprop = g_ptr_array_index(props,3); cprop->color_data = line_colour; rprop = g_ptr_array_index(props,4); rprop->real_data = line_width; bprop = g_ptr_array_index(props,5); bprop->bool_data = FALSE; ellipse_obj->ops->set_props(ellipse_obj, props); prop_list_free(props); if (layer) layer_add_object(layer, ellipse_obj); else return ellipse_obj; return NULL; /* don't add it twice */ } static PropDescription dxf_arc_prop_descs[] = { { "start_point", PROP_TYPE_POINT }, { "end_point", PROP_TYPE_POINT }, { "curve_distance", PROP_TYPE_REAL }, { "line_colour", PROP_TYPE_COLOUR }, { PROP_STDNAME_LINE_WIDTH, PROP_STDTYPE_LINE_WIDTH }, PROP_DESC_END}; /* reads a circle entity from the dxf file and creates a circle object in dia*/ DiaObject *read_entity_arc_dxf(FILE *filedxf, DxfData *data, DiagramData *dia) { /* arc data */ Point start,center,end; real radius = 1.0, start_angle = 0.0, end_angle=360.0; real curve_distance; DiaObjectType *otype = object_get_type("Standard - Arc"); Handle *h1, *h2; DiaObject *arc_obj; Color line_colour = { 0.0, 0.0, 0.0 }; ColorProperty *cprop; PointProperty *ptprop; RealProperty *rprop; GPtrArray *props; real line_width = DEFAULT_LINE_WIDTH; Layer *layer = dia->active_layer; do { if(read_dxf_codes(filedxf, data) == FALSE){ return( NULL ); } switch(data->code){ case 8: layer = layer_find_by_name(data->value, dia); break; case 10: center.x = g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; break; case 20: center.y = (-1)*g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; break; case 39: line_width = g_ascii_strtod(data->value, NULL) * WIDTH_SCALE; break; case 40: radius = g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; break; case 50: start_angle = g_ascii_strtod(data->value, NULL)*M_PI/180.0; break; case 51: end_angle = g_ascii_strtod(data->value, NULL)*M_PI/180.0; break; } } while(data->code != 0); /* printf("c.x=%f c.y=%f s",center.x,center.y); */ start.x = center.x + cos(start_angle) * radius; start.y = center.y - sin(start_angle) * radius; end.x = center.x + cos(end_angle) * radius; end.y = center.y - sin(end_angle) * radius; /*printf("s.x=%f s.y=%f e.x=%f e.y=%f\n",start.x,start.y,end.x,end.y);*/ if (end_angle < start_angle) end_angle += 2.0*M_PI; curve_distance = radius * (1 - cos ((end_angle - start_angle)/2)); /*printf("start_angle: %f end_angle: %f radius:%f curve_distance:%f\n", start_angle,end_angle,radius,curve_distance);*/ arc_obj = otype->ops->create(&center, otype->default_user_data, &h1, &h2); props = prop_list_from_descs(dxf_arc_prop_descs,pdtpp_true); g_assert(props->len == 5); ptprop = g_ptr_array_index(props,0); ptprop->point_data = start; ptprop = g_ptr_array_index(props,1); ptprop->point_data = end; rprop = g_ptr_array_index(props,2); rprop->real_data = curve_distance; cprop = g_ptr_array_index(props,3); cprop->color_data = line_colour; rprop = g_ptr_array_index(props,4); rprop->real_data = line_width; arc_obj->ops->set_props(arc_obj, props); prop_list_free(props); if (layer) layer_add_object(layer, arc_obj); else return arc_obj ; return NULL; /* don't add it twice */ } /* reads an ellipse entity from the dxf file and creates an ellipse object in dia*/ DiaObject * read_entity_ellipse_dxf(FILE *filedxf, DxfData *data, DiagramData *dia) { /* ellipse data */ Point center; real width = 1.0; real ratio_width_height = 1.0; DiaObjectType *otype = object_get_type("Standard - Ellipse"); Handle *h1, *h2; DiaObject *ellipse_obj; Color line_colour = { 0.0, 0.0, 0.0 }; PointProperty *ptprop; RealProperty *rprop; BoolProperty *bprop; ColorProperty *cprop; GPtrArray *props; real line_width = DEFAULT_LINE_WIDTH; Layer *layer = dia->active_layer; do { if(read_dxf_codes(filedxf, data) == FALSE){ return( NULL ); } switch(data->code){ case 8: layer = layer_find_by_name(data->value, dia); break; case 10: center.x = g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; break; case 11: ratio_width_height = g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; break; case 20: center.y = (-1)*g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; break; case 39: line_width = g_ascii_strtod(data->value, NULL) * WIDTH_SCALE; break; case 40: width = g_ascii_strtod(data->value, NULL) * WIDTH_SCALE; /* XXX what scale */ break; } } while(data->code != 0); center.x -= width; center.y -= (width*ratio_width_height); ellipse_obj = otype->ops->create(&center, otype->default_user_data, &h1, &h2); props = prop_list_from_descs(dxf_ellipse_prop_descs,pdtpp_true); g_assert(props->len == 6); ptprop = g_ptr_array_index(props,0); ptprop->point_data = center; rprop = g_ptr_array_index(props,1); rprop->real_data = width; rprop = g_ptr_array_index(props,2); rprop->real_data = width * ratio_width_height; cprop = g_ptr_array_index(props,3); cprop->color_data = line_colour; rprop = g_ptr_array_index(props,4); rprop->real_data = line_width; bprop = g_ptr_array_index(props,5); bprop->bool_data = FALSE; ellipse_obj->ops->set_props(ellipse_obj, props); prop_list_free(props); if (layer) layer_add_object(layer, ellipse_obj); else return ellipse_obj; return NULL; /* don't add it twice */ } static PropDescription dxf_text_prop_descs[] = { { "text", PROP_TYPE_TEXT }, PROP_DESC_END}; DiaObject * read_entity_text_dxf(FILE *filedxf, DxfData *data, DiagramData *dia) { RGB_t color; /* text data */ Point location; real height = text_scale * coord_scale * measure_scale; real y_offset = 0; Alignment textalignment = ALIGN_LEFT; char *textvalue = NULL, *textp; DiaObjectType *otype = object_get_type("Standard - Text"); Handle *h1, *h2; DiaObject *text_obj; Color text_colour = { 0.0, 0.0, 0.0 }; TextProperty *tprop; GPtrArray *props; Layer *layer = dia->active_layer; do { if (read_dxf_codes(filedxf, data) == FALSE) { return( NULL ); } switch (data->code) { case 1: textvalue = g_strdup(data->value); textp = textvalue; /* FIXME - poor tab to space converter */ do { if( textp[0] == '^' && textp[1] == 'I' ) { textp[0] = ' '; textp[1] = ' '; textp++; } } while( *(++textp) != '\0' ); /*printf( "Found text: %s\n", textvalue );*/ break; case 8: layer = layer_find_by_name(data->value, dia); break; case 10: location.x = g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; /*printf( "Found text location x: %f\n", location.x );*/ break; case 11: location.x = g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; /*printf( "Found text location x: %f\n", location.x );*/ break; case 20: location.y = (-1)*g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; /*printf( "Found text location y: %f\n", location.y );*/ break; case 21: location.y = (-1)*g_ascii_strtod(data->value, NULL) * coord_scale * measure_scale; /*location.y = (-1)*g_ascii_strtod(data->value, NULL) / text_scale;*/ /*printf( "Found text location y: %f\n", location.y );*/ break; case 40: height = g_ascii_strtod(data->value, NULL) * text_scale * coord_scale * measure_scale; /*printf( "text height %f\n", height );*/ break; case 62: color = pal_get_rgb (atoi(data->value)); text_colour.red = color.r / 255.0; text_colour.green = color.g / 255.0; text_colour.blue = color.b / 255.0; break; case 72: switch(atoi(data->value)) { case 0: textalignment = ALIGN_LEFT; break; case 1: textalignment = ALIGN_CENTER; break; case 2: textalignment = ALIGN_RIGHT; break; case 3: /* FIXME - it's not clear what these are */ break; case 4: /* FIXME - it's not clear what these are */ break; case 5: /* FIXME - it's not clear what these are */ break; } break; case 73: switch(atoi(data->value)) { case 0: case 1: /* FIXME - not really the same vertical alignment */ /* 0 = baseline */ /* 1 = bottom */ y_offset = 0; break; case 2: /* 2 = middle */ y_offset = 0.5; break; case 3: /* 3 = top */ y_offset = 1; break; } break; } } while(data->code != 0); location.y += y_offset * height; text_obj = otype->ops->create(&location, otype->default_user_data, &h1, &h2); props = prop_list_from_descs(dxf_text_prop_descs,pdtpp_true); g_assert(props->len == 1); tprop = g_ptr_array_index(props,0); g_free(tprop->text_data); tprop->text_data = textvalue; tprop->attr.alignment = textalignment; tprop->attr.position.x = location.x; tprop->attr.position.y = location.y; attributes_get_default_font(&tprop->attr.font, &tprop->attr.height); tprop->attr.color = text_colour; tprop->attr.height = height; text_obj->ops->set_props(text_obj, props); prop_list_free(props); if (layer) layer_add_object(layer, text_obj); else return text_obj; return NULL; /* don't add it twice */ } /* reads the layer table from the dxf file and creates the layers */ void read_table_layer_dxf(FILE *filedxf, DxfData *data, DiagramData *dia) { do { if(read_dxf_codes(filedxf, data) == FALSE){ return; } else { if(data->code == 2){ layer_find_by_name( data->value, dia ); } } } while ((data->code != 0) || (strcmp(data->value, "ENDTAB") != 0)); } /* reads a scale entity from the dxf file */ void read_entity_scale_dxf(FILE *filedxf, DxfData *data, DiagramData *dia) { if(read_dxf_codes(filedxf, data) == FALSE) return; switch(data->code) { case 40: coord_scale = g_ascii_strtod(data->value, NULL); g_message("Scale: %f", coord_scale ); break; default: break; } } /* reads a scale entity from the dxf file */ void read_entity_measurement_dxf(FILE *filedxf, DxfData *data, DiagramData *dia) { if(read_dxf_codes(filedxf, data) == FALSE) return; switch(data->code) { case 70: /* value 0 = English, 1 = Metric */ if( atoi( data->value ) == 0 ) measure_scale = 2.54; else measure_scale = 1.0; /*printf( "Measure Scale: %f\n", measure_scale );*/ break; default: break; } } /* reads a textsize entity from the dxf file */ void read_entity_textsize_dxf(FILE *filedxf, DxfData *data, DiagramData *dia) { if(read_dxf_codes(filedxf, data) == FALSE) return; switch(data->code) { case 40: text_scale = g_ascii_strtod(data->value, NULL); /*printf( "Text Size: %f\n", text_scale );*/ break; default: break; } } /* reads the headers section of the dxf file */ void read_section_header_dxf(FILE *filedxf, DxfData *data, DiagramData *dia) { if(read_dxf_codes(filedxf, data) == FALSE){ return; } do { if((data->code == 9) && (strcmp(data->value, "$DIMSCALE") == 0)) { read_entity_scale_dxf(filedxf, data, dia); } else if((data->code == 9) && (strcmp(data->value, "$TEXTSIZE") == 0)) { read_entity_textsize_dxf(filedxf, data, dia); } else if((data->code == 9) && (strcmp(data->value, "$MEASUREMENT") == 0)) { read_entity_measurement_dxf(filedxf, data, dia); } else { if(read_dxf_codes(filedxf, data) == FALSE){ return; } } } while ((data->code != 0) || (strcmp(data->value, "ENDSEC") != 0)); } /* reads the classes section of the dxf file */ void read_section_classes_dxf(FILE *filedxf, DxfData *data, DiagramData *dia) { if(read_dxf_codes(filedxf, data) == FALSE){ return; } do { if((data->code == 9) && (strcmp(data->value, "$LTSCALE") == 0)) { read_entity_scale_dxf(filedxf, data, dia); } else if((data->code == 9) && (strcmp(data->value, "$TEXTSIZE") == 0)) { read_entity_textsize_dxf(filedxf, data, dia); } else { if(read_dxf_codes(filedxf, data) == FALSE){ return; } } } while ((data->code != 0) || (strcmp(data->value, "ENDSEC") != 0)); } /* reads the tables section of the dxf file */ void read_section_tables_dxf(FILE *filedxf, DxfData *data, DiagramData *dia) { if(read_dxf_codes(filedxf, data) == FALSE){ return; } do { if((data->code == 0) && (strcmp(data->value, "LAYER") == 0)) { read_table_layer_dxf(filedxf, data, dia); } else { if(read_dxf_codes(filedxf, data) == FALSE){ return; } } } while ((data->code != 0) || (strcmp(data->value, "ENDSEC") != 0)); } /* reads the entities section of the dxf file */ void read_section_entities_dxf(FILE *filedxf, DxfData *data, DiagramData *dia) { if (read_dxf_codes(filedxf, data) == FALSE){ return; } do { if((data->code == 0) && (strcmp(data->value, "LINE") == 0)) { read_entity_line_dxf(filedxf, data, dia); } else if((data->code == 0) && (strcmp(data->value, "VERTEX") == 0)) { read_entity_line_dxf(filedxf, data, dia); } else if((data->code == 0) && (strcmp(data->value, "SOLID") == 0)) { read_entity_solid_dxf(filedxf, data, dia); } else if((data->code == 0) && (strcmp(data->value, "POLYLINE") == 0)) { read_entity_polyline_dxf(filedxf, data, dia); } else if((data->code == 0) && (strcmp(data->value, "CIRCLE") == 0)) { read_entity_circle_dxf(filedxf, data, dia); } else if((data->code == 0) && (strcmp(data->value, "ELLIPSE") == 0)) { read_entity_ellipse_dxf(filedxf, data, dia); } else if((data->code == 0) && (strcmp(data->value, "TEXT") == 0)) { read_entity_text_dxf(filedxf, data, dia); } else if((data->code == 0) && (strcmp(data->value, "ARC") == 0)) { read_entity_arc_dxf(filedxf,data,dia); } else { if(read_dxf_codes(filedxf, data) == FALSE) { return; } } } while((data->code != 0) || (strcmp(data->value, "ENDSEC") != 0)); } /* reads the blocks section of the dxf file */ void read_section_blocks_dxf(FILE *filedxf, DxfData *data, DiagramData *dia) { int group_items = 0, group = 0; GList *group_list = NULL; DiaObject *obj = NULL; Layer *group_layer = NULL; if (read_dxf_codes(filedxf, data) == FALSE){ return; } do { if((data->code == 0) && (strcmp(data->value, "LINE") == 0)) { obj = read_entity_line_dxf(filedxf, data, dia); } else if((data->code == 0) && (strcmp(data->value, "SOLID") == 0)) { obj = read_entity_solid_dxf(filedxf, data, dia); } else if((data->code == 0) && (strcmp(data->value, "VERTEX") == 0)) { read_entity_line_dxf(filedxf, data, dia); } else if((data->code == 0) && (strcmp(data->value, "POLYLINE") == 0)) { obj = read_entity_polyline_dxf(filedxf, data, dia); } else if((data->code == 0) && (strcmp(data->value, "CIRCLE") == 0)) { obj = read_entity_circle_dxf(filedxf, data, dia); } else if((data->code == 0) && (strcmp(data->value, "ELLIPSE") == 0)) { obj = read_entity_ellipse_dxf(filedxf, data, dia); } else if((data->code == 0) && (strcmp(data->value, "TEXT") == 0)) { obj = read_entity_text_dxf(filedxf, data, dia); } else if((data->code == 0) && (strcmp(data->value, "ARC") == 0)) { obj = read_entity_arc_dxf(filedxf,data,dia); } else if((data->code == 0) && (strcmp(data->value, "BLOCK") == 0)) { /* printf("Begin group\n" ); */ group = TRUE; group_items = 0; group_list = NULL; group_layer = NULL; do { if(read_dxf_codes(filedxf, data) == FALSE) return; if(data->code == 8) { group_layer = layer_find_by_name( data->value, dia ); data_set_active_layer (dia, group_layer); } } while(data->code != 0); } else if((data->code == 0) && (strcmp(data->value, "ENDBLK") == 0)) { /* printf( "End group %d\n", group_items ); */ if( group && group_items > 0 && group_list != NULL ) { obj = group_create( group_list ); if( NULL == group_layer ) layer_add_object( dia->active_layer, obj ); else layer_add_object( group_layer, obj ); } group = FALSE; group_items = 0; group_list = NULL; obj = NULL; if(read_dxf_codes(filedxf, data) == FALSE) return; } else { if(read_dxf_codes(filedxf, data) == FALSE) { return; } } if( group && obj != NULL ) { group_items++; group_list = g_list_prepend( group_list, obj ); obj = NULL; } } while((data->code != 0) || (strcmp(data->value, "ENDSEC") != 0)); } /* imports the given dxf-file, returns TRUE if successful */ gboolean import_dxf(const gchar *filename, DiagramData *dia, void* user_data) { FILE *filedxf; DxfData *data; filedxf = g_fopen(filename,"r"); if(filedxf == NULL){ message_error(_("Couldn't open: '%s' for reading.\n"), dia_message_filename(filename)); return FALSE; } data = g_new(DxfData, 1); do { if(read_dxf_codes(filedxf, data) == FALSE) { g_free(data); message_error(_("read_dxf_codes failed on '%s'\n"), dia_message_filename(filename) ); return FALSE; } else { if (0 == data->code && strstr(data->codeline, "AutoCAD Binary DXF")) { g_free(data); message_error(_("Binary DXF from '%s' not supported\n"), dia_message_filename(filename) ); return FALSE; } if (0 == data->code) { if(strcmp(data->value, "SECTION") == 0) { /* don't think we need to do anything */ } else if(strcmp(data->value, "ENDSEC") == 0) { /* don't think we need to do anything */ } else if(strcmp(data->value, "EOF") == 0) { /* handled below */ } else { g_print ("DXF 0:%s not handled\n", data->value); } } else if(data->code == 2) { if(strcmp(data->value, "ENTITIES") == 0) { /*printf( "reading section entities\n" );*/ read_section_entities_dxf(filedxf, data, dia); } else if(strcmp(data->value, "BLOCKS") == 0) { /*printf( "reading section BLOCKS\n" );*/ read_section_blocks_dxf(filedxf, data, dia); } else if(strcmp(data->value, "CLASSES") == 0) { /*printf( "reading section CLASSES\n" );*/ read_section_classes_dxf(filedxf, data, dia); } else if(strcmp(data->value, "HEADER") == 0) { /*printf( "reading section HEADER\n" );*/ read_section_header_dxf(filedxf, data, dia); } else if(strcmp(data->value, "TABLES") == 0) { /*printf( "reading section tables\n" );*/ read_section_tables_dxf(filedxf, data, dia); } else if(strcmp(data->value, "OBJECTS") == 0) { /*printf( "reading section objects\n" );*/ read_section_entities_dxf(filedxf, data, dia); } } else g_warning("Unknown dxf code %d", data->code); } }while((data->code != 0) || (strcmp(data->value, "EOF") != 0)); g_free(data); return TRUE; } /* reads a code/value pair from the DXF file */ gboolean read_dxf_codes(FILE *filedxf, DxfData *data){ int i; char *c; if(fgets(data->codeline, DXF_LINE_LENGTH, filedxf) == NULL){ return FALSE; } data->code = atoi(data->codeline); if(fgets(data->value, DXF_LINE_LENGTH, filedxf) == NULL){ return FALSE; } c=data->value; for(i=0; i < DXF_LINE_LENGTH; i++){ if((c[i] == '\n')||(c[i] == '\r')){ c[i] = 0; break; } } return TRUE; } /* interface from filter.h */ static const gchar *extensions[] = {"dxf", NULL }; DiaImportFilter dxf_import_filter = { N_("Drawing Interchange File"), extensions, import_dxf };
0.996094
high
ext/phalcon/db/adapter/pdo/sqlite.zep.h
stokes-php/phalcon
1
7073449
<gh_stars>1-10 extern zend_class_entry *phalcon_db_adapter_pdo_sqlite_ce; ZEPHIR_INIT_CLASS(Phalcon_Db_Adapter_Pdo_Sqlite); PHP_METHOD(Phalcon_Db_Adapter_Pdo_Sqlite, connect); PHP_METHOD(Phalcon_Db_Adapter_Pdo_Sqlite, describeColumns); PHP_METHOD(Phalcon_Db_Adapter_Pdo_Sqlite, describeIndexes); PHP_METHOD(Phalcon_Db_Adapter_Pdo_Sqlite, describeReferences); PHP_METHOD(Phalcon_Db_Adapter_Pdo_Sqlite, useExplicitIdValue); PHP_METHOD(Phalcon_Db_Adapter_Pdo_Sqlite, getDefaultValue); ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_adapter_pdo_sqlite_connect, 0, 0, 0) ZEND_ARG_ARRAY_INFO(0, descriptor, 1) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_adapter_pdo_sqlite_describecolumns, 0, 0, 1) ZEND_ARG_INFO(0, table) ZEND_ARG_INFO(0, schema) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_adapter_pdo_sqlite_describeindexes, 0, 0, 1) ZEND_ARG_INFO(0, table) ZEND_ARG_INFO(0, schema) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_adapter_pdo_sqlite_describereferences, 0, 0, 1) ZEND_ARG_INFO(0, table) ZEND_ARG_INFO(0, schema) ZEND_END_ARG_INFO() ZEPHIR_INIT_FUNCS(phalcon_db_adapter_pdo_sqlite_method_entry) { PHP_ME(Phalcon_Db_Adapter_Pdo_Sqlite, connect, arginfo_phalcon_db_adapter_pdo_sqlite_connect, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo_Sqlite, describeColumns, arginfo_phalcon_db_adapter_pdo_sqlite_describecolumns, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo_Sqlite, describeIndexes, arginfo_phalcon_db_adapter_pdo_sqlite_describeindexes, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo_Sqlite, describeReferences, arginfo_phalcon_db_adapter_pdo_sqlite_describereferences, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo_Sqlite, useExplicitIdValue, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo_Sqlite, getDefaultValue, NULL, ZEND_ACC_PUBLIC) PHP_FE_END };
0.800781
high
ios/chrome/browser/ui/overlays/infobar_modal/infobar_modal_overlay_coordinator+modal_configuration.h
sarang-apps/darshan_browser
575
7073961
<reponame>sarang-apps/darshan_browser // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_CHROME_BROWSER_UI_OVERLAYS_INFOBAR_MODAL_INFOBAR_MODAL_OVERLAY_COORDINATOR_MODAL_CONFIGURATION_H_ #define IOS_CHROME_BROWSER_UI_OVERLAYS_INFOBAR_MODAL_INFOBAR_MODAL_OVERLAY_COORDINATOR_MODAL_CONFIGURATION_H_ #import <UIKit/UIKit.h> #import "ios/chrome/browser/ui/overlays/infobar_modal/infobar_modal_overlay_coordinator.h" @class InfobarModalOverlayMediator; // Category implemented by InfobarModalOverlayCoordinator subclasses to // configure the view to display for infobar modals. @interface InfobarModalOverlayCoordinator (ModalConfiguration) // The mediator used to configure the modal view controller. Created in // |-configureModal|. @property(nonatomic, readonly) InfobarModalOverlayMediator* modalMediator; // The view controller to display for the infobar modal. Created in // |-configureModal|. This view controller is not the view controller returned // by the InfobarModalOverlayCoordinator.viewController property, but is added // as a child view controller to the top-level infobar modal container view. @property(nonatomic, readonly) UIViewController* modalViewController; // Creates a modal view controller and configures it with a new mediator. // Resets |modalViewController| and |modalMediator| to the new instances. - (void)configureModal; // Resets |modalMediator| and |modalViewController|. - (void)resetModal; @end #endif // IOS_CHROME_BROWSER_UI_OVERLAYS_INFOBAR_MODAL_INFOBAR_MODAL_OVERLAY_COORDINATOR_MODAL_CONFIGURATION_H_
0.953125
high
InterfaCSS/InterfaCSS.h
MyFiziqApp/InterfaCSS
84
7074473
<filename>InterfaCSS/InterfaCSS.h // // InterfaCSS.h // Part of InterfaCSS - http://www.github.com/tolo/InterfaCSS // // Copyright (c) <NAME>, Leafnode AB. // License: MIT (http://www.github.com/tolo/InterfaCSS/LICENSE) // #import <UIKit/UIKit.h> #import <Foundation/Foundation.h> #define ISS_EQUAL_FLT(x, y) (fabs((x) - (y)) < FLT_EPSILON) #ifndef ISS_UIKIT_SDK_VERSION #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #define ISS_UIKIT_SDK_VERSION __IPHONE_OS_VERSION_MIN_REQUIRED #elif defined(__TV_OS_VERSION_MIN_REQUIRED) #define ISS_UIKIT_SDK_VERSION __TV_OS_VERSION_MIN_REQUIRED #else #define ISS_UIKIT_SDK_VERSION 80000 #endif #endif @protocol ISSStyleSheetParser; @class ISSViewPrototype; @class ISSPropertyRegistry; #pragma mark - Common block type definitions typedef NSArray* _Nonnull (^ISSWillApplyStylingNotificationBlock)(NSArray* _Nonnull propertyDeclarations); typedef void (^ISSDidApplyStylingNotificationBlock)(NSArray* _Nonnull propertyDeclarations); #pragma mark - Common notification definitions extern NSString* _Nonnull const ISSWillRefreshStyleSheetsNotification; extern NSString* _Nonnull const ISSDidRefreshStyleSheetNotification; #import "ISSPropertyDefinition.h" #import "ISSStyleSheet.h" #import "ISSViewBuilder.h" #import "UIView+InterfaCSS.h" #import "UITableView+InterfaCSS.h" #import "NSObject+ISSLogSupport.h" NS_ASSUME_NONNULL_BEGIN /** * The heart, core and essence of InterfaCSS. Handles loading of stylesheets and keeps track of all style information. */ @interface InterfaCSS : NSObject #pragma mark - Static methods /** * Gets the shared InterfaCSS instance. */ + (InterfaCSS*) interfaCSS __deprecated_msg("use `[InterfaCSS sharedInstance]`"); /** * Gets the shared InterfaCSS instance. */ + (InterfaCSS*) sharedInstance; /** * Clears and resets all loaded stylesheets, registered style class names and caches. */ + (void) clearResetAndUnload; #pragma mark - Behavioural properties /** * Setting this flag to `YES` prevents "overwriting" of font and text color in attributed text of labels (and buttons) when styles are applied. * Default value is `NO` */ @property (nonatomic) BOOL preventOverwriteOfAttributedTextAttributes; /** * If this flag is set to `YES`, any type selector that don't match a valid UIKit type will instead be used as a style class selector. Default is `NO`. */ @property (nonatomic) BOOL useLenientSelectorParsing; /** * The interval at which refreshable stylesheets are refreshed. Default is 5 seconds. If value is set to <= 0, automatic refresh is disabled. Note: this is only use for stylesheets loaded from a remote URL. */ @property (nonatomic) NSTimeInterval stylesheetAutoRefreshInterval; /** * Flag indicating if refreshable stylesheets always should be processed after "normal" stylesheets, and thereby always being able to override those. Default is `YES`. */ @property (nonatomic) NSTimeInterval processRefreshableStylesheetsLast; /** * Flag indicating if unknown type selectors should automatically be registered as canonical type classes (i.e. valid type selector classes) when encountered * in a stylesheet. As an alternative to this, consider using `[ISSPropertyRegistry registerCanonicalTypeClass:]` * * Default value of this property is `YES`. * * @see [ISSPropertyRegistry registerCanonicalTypeClass:] */ @property (nonatomic) BOOL allowAutomaticRegistrationOfCustomTypeSelectorClasses; /** * Enables or disables the use of selector specificity (see http://www.w3.org/TR/css3-selectors/#specificity ) when calculating the effective styles (and order) for an element. Default value of this property is `NO`. */ @property (nonatomic) BOOL useSelectorSpecificity; /** * Enables or disables manual styling. If this property is set to `YES`, no calls to `applyStyling` etc will be scheduled automatically by InterfaCSS. Default value of this property is `NO`. */ @property (nonatomic) BOOL useManualStyling; #pragma mark - Properties /** * The property registry keeps track on all properties that can be set through stylesheets. */ @property (nonatomic, readonly, strong) ISSPropertyRegistry* propertyRegistry; /** * All currently active stylesheets (`ISSStyleSheet`). */ @property (nonatomic, readonly, strong) NSMutableArray* styleSheets; /** * The current stylesheet parser. */ @property (nonatomic, strong) id<ISSStyleSheetParser> parser; #pragma mark - Styling /** * Clears all cached information, including cached style data, related to the specified UI element, but does not initiate re-styling. */ - (void) clearCachedStylesForUIElement:(id)uiElement; /** * Clears all cached information, including cached style data, for the specified element and (optionally) its subviews, but does not initiate re-styling. */ - (void) clearCachedStylesForUIElement:(id)uiElement includeSubViews:(BOOL)includeSubViews; /** * Clears all cached information, including cached style data, if needed, for the specified element and (optionally) its subviews, but does not initiate re-styling. */ - (void) clearCachedStylesIfNeededForUIElement:(id)uiElement includeSubViews:(BOOL)includeSubViews; /** * Schedules styling of the specified UI object. */ - (void) scheduleApplyStyling:(id)uiElement animated:(BOOL)animated; /** * Schedules styling of the specified UI object, but only if it hasn't already been scheduled for an ancestor element. */ - (void) scheduleApplyStylingIfNeeded:(id)uiElement animated:(BOOL)animated force:(BOOL)force; /** * Schedules styling of the specified UI object. */ - (void) scheduleApplyStyling:(id)uiElement animated:(BOOL)animated force:(BOOL)force; /** * Cancel previously scheduled styling of the specified UI object. */ - (void) cancelScheduledApplyStyling:(id)uiElement; /** * Applies styling of the specified UI object and also all its children. */ - (void) applyStyling:(id)uiElement; /** * Applies styling of the specified UI object and optionally also all its children. */ - (void) applyStyling:(id)uiElement includeSubViews:(BOOL)includeSubViews; /** * Applies styling of the specified UI object and optionally also all its children. */ - (void) applyStyling:(id)uiElement includeSubViews:(BOOL)includeSubViews force:(BOOL)force; /** * Applies styling of the specified UI object, and also all its children, in an animation block. */ - (void) applyStylingWithAnimation:(id)uiElement; /** * Applies styling of the specified UI object, and optionally also all its children, in an animation block. */ - (void) applyStylingWithAnimation:(id)uiElement includeSubViews:(BOOL)includeSubViews; /** * Applies styling of the specified UI object, and optionally also all its children, in an animation block. */ - (void) applyStylingWithAnimation:(id)uiElement includeSubViews:(BOOL)includeSubViews force:(BOOL)force; /** * Applies styling of the specified UI object and also all its children, but only if styling has already been scheduled (i.e. one of the scheduleApplyStyling methods has been * called - this is for instance done automatically whenever new style classes are added etc), and only if a parent element hasn't scheduled styling, in which case styling will * be applied to this element shortly anyway. */ - (void) applyStylingIfScheduled:(id)uiElement; #pragma mark - Style classes /** * Gets the current style classes for the specified UI element. */ - (NSSet*) styleClassesForUIElement:(id)uiElement; /** * Checks if the specified class is set on the specified UI element. */ - (BOOL) uiElement:(id)uiElement hasStyleClass:(NSString*)styleClass; /** * Sets the style classes for the specified UI element, replacing any previous style classes. */ - (void) setStyleClasses:(NSSet*)styleClasses forUIElement:(id)uiElement; /** * Adds a style class to the specified UI element. */ - (void) addStyleClass:(NSString*)styleClass forUIElement:(id)uiElement; /** * Removes a style class from the specified UI element. */ - (void) removeStyleClass:(NSString*)styleClass forUIElement:(id)uiElement; #pragma mark - Element id /** * Sets the unique element identifier to be associated with the specified element. * * Note: Setting an element id also affects how style information is cached for the specified element, and its decendants. More precicely, when using an element id, * styling identities (effectively the cache key for the styling information) can be calculated more effectively, since the element id can be used as starting point * for the view hierarchy "path" that styling identities consist of. This also means that it's imporant to keep element ids unique. */ - (void) setElementId:(nullable NSString*)elementId forUIElement:(id)uiElement; /** * Gets the unique element identifier associated with the specified element. */ - (nullable NSString*) elementIdForUIElement:(id)uiElement; #pragma mark - Additional styling control /** * Sets a callback block for getting notified when styles will be applied to the specified UI element. Makes it possible to prevent some properties from being applied, by returning a different * list of properties than the list passed as a parameter to the block. */ - (void) setWillApplyStylingBlock:(nullable ISSWillApplyStylingNotificationBlock)willApplyStylingBlock forUIElement:(id)uiElement; /** Gets the current callback block for getting notified when styles will be applied to the specified UI element.*/ - (nullable ISSWillApplyStylingNotificationBlock) willApplyStylingBlockForUIElement:(id)uiElement; /** * Sets a callback block for getting notified when styles have been applied to the specified UI element. Makes it possible to for instance adjust property values or update dependent properties. */ - (void) setDidApplyStylingBlock:(nullable ISSDidApplyStylingNotificationBlock)didApplyStylingBlock forUIElement:(id)uiElement; /** Gets the current callback block for getting notified when styles have been applied to the specified UI element.*/ - (nullable ISSDidApplyStylingNotificationBlock) didApplyStylingBlockForUIElement:(id)uiElement; /** * Sets a custom styling identity that overrides the default mechanism for assigning styling identities to elements (which essentially involves building a full view * hierarchy "path" of an element, such as "UIWindow UIView UIView[class]"). The styling identity is effectively the cache key for the styling information * associated with a UI element, and setting this to a custom value makes it possible to (further) increase performance by sharing cached styles with * UI elements located in different places in the view hierarchy for instance. Examples of places where setting this property can be useful is for instance * the root view of a view controller, a custom UI component or other views that can be styles regardless of the ancestor view hierarchy. * * NOTE: When using a custom styling identity for a view, avoid using style declarations that depends on the view hierarchy above that view (i.e. use of chained * or nested selectors that ). */ - (void) setCustomStylingIdentity:(nullable NSString*)customStylingIdentity forUIElement:(id)uiElement; /** Gets the custom styling identity. */ - (nullable NSString*) customStylingIdentityForUIElement:(id)uiElement; /** * Disables or re-enables styling of the specified UI element. If `enabled` is set to `NO`, InterfaCSS will stop applying styling information to the element and it's children, * but any styles that have already been applied will remain. This method can for instance be useful for setting initial styles for a view via InterfaCSS, * and then take control of the styling manually, without the risk of InterfaCSS overwriting any modified properties. */ - (void) setStylingEnabled:(BOOL)enabled forUIElement:(id)uiElement; /** Returns `YES` if styling is enabled for the specified UI element. */ - (BOOL) isStylingEnabledForUIElement:(id)uiElement; /** Returns `YES` if styling has been successfully applied to the specified UI element. */ - (BOOL) isStylingAppliedForUIElement:(id)uiElement; /** * Disables or re-enables styling of a specific property in the specified UI element. If `enabled` is set to `NO`, InterfaCSS will stop applying styling information to the * property, but any value that has already been applied will remain. This method can for instance be useful for setting initial styles for a view via InterfaCSS, * and then take control of the styling manually, without the risk of InterfaCSS overwriting property values. */ - (void) setStylingEnabled:(BOOL)enabled forProperty:(NSString*)propertyName inUIElement:(id)uiElement; /** Returns `YES` if styling is enabled for a specific property in the specified UI element. */ - (BOOL) isStylingEnabledForProperty:(NSString*)propertyName inUIElement:(id)uiElement; /** Finds a sub view with the specified element identifier. */ - (nullable id) subviewWithElementId:(NSString*)elementId inView:(id)view; /** Finds a super view with the specified element identifier. */ - (nullable id) superviewWithElementId:(NSString*)elementId inView:(id)view; - (void) autoPopulatePropertiesInViewHierarchyFromView:(UIView*)view inOwner:(id)owner; #pragma mark - Stylesheets /** * Loads a stylesheet from the main bundle. */ - (nullable ISSStyleSheet*) loadStyleSheetFromMainBundleFile:(NSString*)styleSheetFileName; - (nullable ISSStyleSheet*) loadStyleSheetFromMainBundleFile:(NSString*)styleSheetFileName withScope:(nullable ISSStyleSheetScope*)scope; /** * Loads a stylesheet from an absolute file path. */ - (nullable ISSStyleSheet*) loadStyleSheetFromFile:(NSString*)styleSheetFilePath; - (nullable ISSStyleSheet*) loadStyleSheetFromFile:(NSString*)styleSheetFilePath withScope:(nullable ISSStyleSheetScope*)scope; /** * Loads an auto-refreshable stylesheet from a URL (both file and http URLs are supported). * Note: Refreshable stylesheets are only intended for use during development, and not in production. */ - (nullable ISSStyleSheet*) loadRefreshableStyleSheetFromURL:(NSURL*)styleSheetFileURL; - (nullable ISSStyleSheet*) loadRefreshableStyleSheetFromURL:(NSURL*)styleSheetFileURL withScope:(nullable ISSStyleSheetScope*)scope; /** * Loads an auto-refreshable stylesheet from a local file path, and starts monitoring the file for changes. * Note: Refreshable stylesheets are only intended for use during development, and not in production. */ - (nullable ISSStyleSheet*) loadRefreshableStyleSheetFromLocalFile:(NSString*)styleSheetFilePath; - (nullable ISSStyleSheet*) loadRefreshableStyleSheetFromLocalFile:(NSString*)styleSheetFilePath withScope:(nullable ISSStyleSheetScope*)scope; /** Reloads all (remote) refreshable stylesheets. If force is `YES`, stylesheets will be reloaded even if they haven't been modified. */ - (void) reloadRefreshableStyleSheets:(BOOL)force; /** Reloads a refreshable stylesheet. If force is `YES`, the stylesheet will be reloaded even if is hasn't been modified. */ - (void) reloadRefreshableStyleSheet:(ISSStyleSheet*)styleSheet force:(BOOL)force; /** * Unloads the specified styleSheet. * @param styleSheet the stylesheet to unload. * @param refreshStyling YES if styling on all tracked views should be reset and reapplied as a result of this call, otherwise NO. */ - (void) unloadStyleSheet:(ISSStyleSheet*)styleSheet refreshStyling:(BOOL)refreshStyling; /** * Unloads all loaded stylesheets, effectively resetting the styling of all views. * @param refreshStyling YES if styling on all tracked views should be reset and reapplied as a result of this call, otherwise NO. */ - (void) unloadAllStyleSheets:(BOOL)refreshStyling; /** * Clears all cached style information and re-applies styles for all views. */ - (void) refreshStyling; /** * Clears all cached style information, but does not initiate re-styling. */ - (void) clearAllCachedStyles; #pragma mark - Prototypes /** * Registers a prototype defined in a view definition file. */ - (void) registerPrototype:(ISSViewPrototype*)prototype; /** * Registers a prototype defined in a view definition file. */ - (void) registerPrototype:(ISSViewPrototype*)prototype inElement:(id)registeredInElement; /** * Creates a view from a prototype defined in a view definition file. */ - (nullable UIView*) viewFromPrototypeWithName:(NSString*)prototypeName; /** * Creates a view from a prototype defined in a view definition file. */ - (nullable UIView*) viewFromPrototypeWithName:(NSString*)prototypeName prototypeParent:(nullable id)prototypeParent; /** * Creates a view from a prototype defined in a view definition file. */ - (nullable UIView*) viewFromPrototypeWithName:(NSString*)prototypeName registeredInElement:(nullable id)registeredInElement prototypeParent:(nullable id)prototypeParent; #pragma mark - Variable access /** * Returns the raw value of the stylesheet variable with the specified name. */ - (nullable NSString*) valueOfStyleSheetVariableWithName:(NSString*)variableName; /** * Returns the value of the stylesheet variable with the specified name, transformed to the specified type. */ - (nullable id) transformedValueOfStyleSheetVariableWithName:(NSString*)variableName asPropertyType:(ISSPropertyType)propertyType; /** * Returns the value of the stylesheet variable with the specified name, transformed using the specified property definition. */ - (nullable id) transformedValueOfStyleSheetVariableWithName:(NSString*)variableName forPropertyDefinition:(ISSPropertyDefinition*)propertyDefinition; /** * Sets the raw value of the stylesheet variable with the specified name. */ - (void) setValue:(nullable NSString*)value forStyleSheetVariableWithName:(NSString*)variableName; #pragma mark - Debugging support /** * Logs the active style declarations for the specified UI element. */ - (void) logMatchingStyleDeclarationsForUIElement:(id)uiElement; @end NS_ASSUME_NONNULL_END
0.996094
high
Graphics-Engine/Graphics-Engine/src/Entity.h
Hernibyte/TSDV_Graphics-Engine-2D
0
7074985
<reponame>Hernibyte/TSDV_Graphics-Engine-2D<gh_stars>0 #ifndef ENTITY_H #define ENTITY_H #include "Renderer.h" class Entity { public: Transform transform; Entity(Renderer& renderer) { render = &renderer; transform = Transform(); } protected: Renderer* render; }; #endif // !ENTITY_H
0.960938
high
locomotion_framework/controllers/hierarchical_control/include/mwoibn/hierarchical_control/actions/secondary.h
ADVRHumanoids/DrivingFramework
1
7075497
<gh_stars>1-10 #ifndef __MWOIBN_HIERARCHICAL_CONTROL_ACTIONS_SECONDARY_H #define __MWOIBN_HIERARCHICAL_CONTROL_ACTIONS_SECONDARY_H #include "mwoibn/hierarchical_control/tasks/controller_task.h" #include "mwoibn/hierarchical_control/actions/task.h" #include "mwoibn/hierarchical_control/maps/task_map.h" #include "mwoibn/hierarchical_control/actions/primary.h" namespace mwoibn { namespace hierarchical_control { namespace actions { class Secondary : public Task { public: Secondary(actions::Task& action, memory::Manager& memory, maps::TaskMap& map) : Task(memory), _action(&action), _map(map){ } Secondary(memory::Manager& memory, maps::TaskMap& map) : Task(memory), _map(map){ } const Secondary& operator=(const Secondary& secondary){ return secondary; } virtual ~Secondary(){ } virtual void assign(actions::Task& action){ _action = &action; _next = &action; } virtual void release(){ _next = _action; _map.swap(_action->baseAction().getTask(), *_action); // should this be a swap or operator _memory.release(*this); } virtual actions::Primary& baseAction() { return _action->baseAction(); } virtual void run(){ } virtual actions::Task& action(){ return *_action; } virtual actions::Task& next() { _action = &(_action->next()); if(_next != this) release(); return *_next; } protected: // Secondary(){ // } actions::Task* _action; //actions::Task* _next; maps::TaskMap& _map; }; } } // namespace package } // namespace library #endif
0.984375
high
regression/cbmc/01_cbmc_Malloc11/main.c
shmarovfedor/esbmc
143
7076009
int main() { int *p; p=malloc(100*sizeof(int)); // buffer overflow p[100]=1; }
0.953125
low
chrome/browser/ui/ash/holding_space/holding_space_downloads_delegate.h
Ron423c/chromium
575
7076521
<reponame>Ron423c/chromium<filename>chrome/browser/ui/ash/holding_space/holding_space_downloads_delegate.h // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_ASH_HOLDING_SPACE_HOLDING_SPACE_DOWNLOADS_DELEGATE_H_ #define CHROME_BROWSER_UI_ASH_HOLDING_SPACE_HOLDING_SPACE_DOWNLOADS_DELEGATE_H_ #include <memory> #include "base/callback.h" #include "base/scoped_observer.h" #include "chrome/browser/ui/ash/holding_space/holding_space_keyed_service_delegate.h" #include "components/download/public/common/download_item.h" #include "content/public/browser/download_manager.h" namespace base { class FilePath; } // namespace base namespace ash { // A delegate of `HoldingSpaceKeyedService` tasked with monitoring the status of // of downloads and notifying a callback on download completion. class HoldingSpaceDownloadsDelegate : public HoldingSpaceKeyedServiceDelegate, public content::DownloadManager::Observer, public download::DownloadItem::Observer { public: // Callback to be invoked when a download is completed. Note that this // callback will only be invoked after holding space persistence is restored. using ItemDownloadedCallback = base::RepeatingCallback<void(const base::FilePath&)>; HoldingSpaceDownloadsDelegate( Profile* profile, HoldingSpaceModel* model, ItemDownloadedCallback item_downloaded_callback); HoldingSpaceDownloadsDelegate(const HoldingSpaceDownloadsDelegate&) = delete; HoldingSpaceDownloadsDelegate& operator=( const HoldingSpaceDownloadsDelegate&) = delete; ~HoldingSpaceDownloadsDelegate() override; // Sets the `content::DownloadManager` to be used for testing. // NOTE: This method must be called prior to delegate initialization. static void SetDownloadManagerForTesting( content::DownloadManager* download_manager); private: // HoldingSpaceKeyedServiceDelegate: void Init() override; void OnPersistenceRestored() override; // content::DownloadManager::Observer: void OnManagerInitialized() override; void ManagerGoingDown(content::DownloadManager* manager) override; void OnDownloadCreated(content::DownloadManager* manager, download::DownloadItem* item) override; // download::DownloadItem::Observer: void OnDownloadUpdated(download::DownloadItem* item) override; // Invoked when the specified `file_path` has completed downloading. void OnDownloadCompleted(const base::FilePath& file_path); // Removes all observers. void RemoveObservers(); // Callback to invoke when a download is completed. ItemDownloadedCallback item_downloaded_callback_; ScopedObserver<content::DownloadManager, content::DownloadManager::Observer> download_manager_observer_{this}; ScopedObserver<download::DownloadItem, download::DownloadItem::Observer> download_item_observer_{this}; base::WeakPtrFactory<HoldingSpaceDownloadsDelegate> weak_factory_{this}; }; } // namespace ash #endif // CHROME_BROWSER_UI_ASH_HOLDING_SPACE_HOLDING_SPACE_DOWNLOADS_DELEGATE_H_
0.992188
high
src/pubkey.h
bitcoinpostquantum/bitcoinpq
1
7077033
// Copyright (c) 2009-2010 <NAME> // Copyright (c) 2009-2017 The Bitcoin Core developers // Copyright (c) 2017 The Zcash developers // Copyright (c) 2018 The Bitcoin Post-Quantum developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_PUBKEY_H #define BITCOIN_PUBKEY_H #include <hash.h> #include <serialize.h> #include <uint256.h> #include <streams.h> #include "crypt_xmss.h" #include <script/standard.h> #include <stdexcept> #include <vector> #include <cstdint> const unsigned int BIP32_EXTKEY_SIZE = 74; /** A reference to a CKey: the Hash160 of its serialized public key: * KeyID = RIPEMD160(SHA256(pubkey)) */ class CKeyID : public uint160 { public: CKeyID() : uint160() {} explicit CKeyID(const uint160& in) : uint160(in) {} }; typedef uint256 ChainCode; using CKeyType = bpqcrypto::KeyType; extern std::string KeyTypeToString(CKeyType keytype); /** An encapsulated public key. */ class CPubKey { public: /** * secp256k1: */ static const unsigned int ECDSA_PUBLIC_KEY_SIZE = 65; static const unsigned int ECDSA_COMPRESSED_PUBLIC_KEY_SIZE = 33; static const unsigned int ECDSA_SIGNATURE_SIZE = 72; static const unsigned int ECDSA_COMPACT_SIGNATURE_SIZE = 65; /** * see www.keylength.com * script supports up to 75 for single byte push */ static_assert( ECDSA_PUBLIC_KEY_SIZE >= ECDSA_COMPRESSED_PUBLIC_KEY_SIZE, "COMPRESSED_PUBLIC_KEY_SIZE is larger than PUBLIC_KEY_SIZE"); /** * xmss */ // public key length including prefix static const unsigned int XMSS_256_PUBLIC_KEY_SIZE = 69; static const unsigned int XMSS_512_PUBLIC_KEY_SIZE = 133; // prefix for XMSS public key // values 16+ reserved for XMSS public keys versions static const uint8_t HDR_XMSS_V1 = 16; private: /** * Just store the serialized data. * Its length can very cheaply be computed from the first byte. */ std::vector<uint8_t> vch; //uint8_t vch[80]; //! Compute the length of a pubkey with a given first byte. unsigned int static GetLen1(unsigned char chHeader) { if (chHeader == 2 || chHeader == 3) return ECDSA_COMPRESSED_PUBLIC_KEY_SIZE; if (chHeader == 4 || chHeader == 6 || chHeader == 7) return ECDSA_PUBLIC_KEY_SIZE; if (chHeader == HDR_XMSS_V1) return XMSS_256_PUBLIC_KEY_SIZE; return 0; } //! Set this key data to be invalid void Invalidate() { vch.clear(); //vch.resize(1); //vch[0] = 0xFF; } public: //! Construct an invalid public key. CPubKey() { //vch.resize(80); Invalidate(); } //! Initialize a public key void Set(uint8_t const * data, size_t size); template <typename T> void Set(const T pbegin, const T pend) { int len = pend - pbegin; Set((uint8_t const*)&pbegin[0], len); } void Set(std::vector<uint8_t> const & raw_key) { Set(raw_key.data(), raw_key.size()); } //! Construct a public key using begin/end iterators to byte data. template <typename T> CPubKey(const T pbegin, const T pend) { Set(pbegin, pend); } explicit CPubKey(std::vector<uint8_t> const & raw_key) { Set(raw_key); } CPubKey(uint8_t const * pbegin, uint8_t const * pend) { Set(pbegin, pend); } CKeyType GetKeyType() const; //! Simple read-only vector-like interface to the pubkey data. unsigned int size() const { return vch.size(); } //GetLen(vch[0]); } const unsigned char* begin() const { return vch.data(); } const unsigned char* end() const { return vch.data() + size(); } const unsigned char& operator[](unsigned int pos) const { return vch[pos]; } std::vector<uint8_t> const & raw_pubkey() const { return vch; } //! Comparator implementation. friend bool operator==(const CPubKey& a, const CPubKey& b) { //return a.vch[0] == b.vch[0] && // memcmp(a.vch, b.vch, a.size()) == 0; return a.vch == b.vch; } friend bool operator!=(const CPubKey& a, const CPubKey& b) { return !(a == b); } friend bool operator<(const CPubKey& a, const CPubKey& b) { //return a.vch[0] < b.vch[0] || // (a.vch[0] == b.vch[0] && memcmp(a.vch, b.vch, a.size()) < 0); return a.vch < b.vch; } //! Implement serialization, as if this was a byte vector. template <typename Stream> void Serialize(Stream& s) const { unsigned int len = size(); ::WriteCompactSize(s, len); s.write((char const*)begin(), len); } template <typename Stream> void Unserialize(Stream& s) { unsigned int len = ::ReadCompactSize(s); vch.resize(len); s.read((char*)vch.data(), len); } //! Get the KeyID of this public key (hash of its serialization) CKeyID GetID() const { return CKeyID(Hash160(vch.data(), vch.data() + size())); } //! Get the 256-bit hash of this public key. //! SHA256(SHA256(pubkey)) uint256 GetHash() const { return Hash(vch.data(), vch.data() + size()); } /* * Check syntactic correctness. * * Note that this is consensus critical as CheckSig() calls it! */ bool IsValid() const { return size() > 0; } //! fully validate whether this is a valid public key (more expensive than IsValid()) bool IsFullyValid() const; //! Check whether this is a compressed public key. bool IsCompressed() const { //return size() > 0 && (vch[0] == 2 || vch[0] == 3); return size() == ECDSA_COMPRESSED_PUBLIC_KEY_SIZE; } bool IsXMSS() const { return vch.size() > 0 && vch[0] == HDR_XMSS_V1; } size_t GetMaxUseCount() const; /** * Verify a DER signature (~72 bytes). * If this public key is not fully valid, the return value will be false. */ bool Verify(const uint8_t * msg, size_t msg_size, std::vector<unsigned char> const & vchSig) const; template <typename T> bool Verify(T const & msg, std::vector<unsigned char> const & vchSig) const { auto && beg = msg.begin(); auto && end = msg.end(); size_t len = end - beg; return len > 0 && Verify((uint8_t const *)&beg[0], len, vchSig); } bool VerifyHash(const uint256& hash, const std::vector<unsigned char>& vchSig) const; //! Recover a public key from a compact signature. bool RecoverCompact(std::string const & msg, const std::vector<unsigned char>& vchSig); bool RecoverCompact(const uint256& hash, const std::vector<unsigned char>& vchSig); //! Turn this public key into an uncompressed public key. bool Decompress(); //! Derive BIP32 child pubkey. bool Derive(CPubKey& pubkeyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const; }; struct CExtPubKey { unsigned char nDepth; unsigned char vchFingerprint[4]; unsigned int nChild; ChainCode chaincode; CPubKey pubkey; friend bool operator==(const CExtPubKey &a, const CExtPubKey &b) { return a.nDepth == b.nDepth && memcmp(&a.vchFingerprint[0], &b.vchFingerprint[0], sizeof(vchFingerprint)) == 0 && a.nChild == b.nChild && a.chaincode == b.chaincode && a.pubkey == b.pubkey; } void Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const; void Decode(const unsigned char code[BIP32_EXTKEY_SIZE]); bool Derive(CExtPubKey& out, unsigned int nChild) const; void Serialize(CSizeComputer& s) const { // Optimized implementation for ::GetSerializeSize that avoids copying. s.seek(BIP32_EXTKEY_SIZE + 1); // add one byte for the size (compact int) } template <typename Stream> void Serialize(Stream& s) const { if ( pubkey.IsXMSS() ) { // TODO: encode unsigned int len = pubkey.size(); ::WriteCompactSize(s, len); s.write((const char *)&pubkey.begin()[0], len); } else { unsigned int len = BIP32_EXTKEY_SIZE; ::WriteCompactSize(s, len); unsigned char code[BIP32_EXTKEY_SIZE]; Encode(code); s.write((const char *)&code[0], len); } } template <typename Stream> void Unserialize(Stream& s) { unsigned int len = ::ReadCompactSize(s); if ( len != BIP32_EXTKEY_SIZE ) { std::vector<uint8_t> code(len); s.read((char *)code.data(), len); // TODO: decode pubkey.Set(code.begin(), code.end()); } else { unsigned char code[BIP32_EXTKEY_SIZE]; if (len != BIP32_EXTKEY_SIZE) throw std::runtime_error("Invalid extended key size\n"); s.read((char *)&code[0], len); Decode(code); } } }; inline bool is_key_segwit_useable(CPubKey const & pubkey ) { return pubkey.IsXMSS() || pubkey.IsCompressed(); } #endif // BITCOIN_PUBKEY_H
1
high
submodules/MtProtoKit/MTProtoKit/MTInternalMessageParser.h
miladajilian/MimMessenger
6
7077545
#import <Foundation/Foundation.h> @interface MTInternalMessageParser : NSObject + (id)parseMessage:(NSData *)data; + (id)unwrapMessage:(NSData *)data; @end
0.921875
high
Extras/files/2/array_pass.c
nikhilnayak98/CSE3041
1
7078057
<reponame>nikhilnayak98/CSE3041<filename>Extras/files/2/array_pass.c #include <stdio.h> #include <stdlib.h> //int SumOfElements(int A[]) int SumOfElements(int A[]) { int size=sizeof(A)/sizeof(A[0]); printf("size of A in SOE:=%d and size of A[0] in SOE:=%d\n", sizeof(A), sizeof(A[0])); int i, sum=0; for(i=0; i<size; i++) sum+=A[i]; return sum; } int main() { int A[]= {1, 2, 3, 4, 5}; int size=sizeof(A)/sizeof(A[0]); printf("size of A in main:=%d and size of A[0] in main:=%d\n", sizeof(A), sizeof(A[0])); int total =SumOfElements(A); //int total =SumOfElements(A); printf("Sum of lelements = %d \n", total); }
0.542969
high
shotgun/lib/sendsite.h
chad/rubinius
3
7078569
#ifndef RBX_SENDSITE_H #define RBX_SENDSITE_H typedef struct send_site _send_site; typedef void (*send_site_lookup)(struct message *msg); /* Send sites is the core of method dispatch caching used by Rubinius. It is half C, half Ruby implementation. It is created for every message send site (or, for those coming from Java world, method call site) to store information about receiver and method responding to message sent. This information later help use cached compiled method if the method receiver handles message with has already been executed at this send site. Selector is an object that represents a message (method name) and collection of references to every send site that uses the same message. Selectors are not used in method dispatch process though: they provide a reverse lookup of send sites for given method name. You can pass -ps and -pss flags to Rubinius on launch and summary of most frequently encountered selectors and send sites will be printed on exit (so they stand for "print selectors" and "print send sites"). Note that it summarizes most often send messages (method names), not actual methods executed, because many methods may have the same name in different classes or modules. Note that OBJECT fields must be located at the start of the SendSite. == References Send sites are also known as call sites in a variery of literature and on Wikipedia: http://tinyurl.com/22jpuy <NAME> wrote a great post on send sites in Rubinius: http://tinyurl.com/34c6e8 == Structure fields name : the name of the message (i.e. method) this send site sends (calls) sender : reference to the CompiledMethod in which the SendSite is located selector : a reference to the Selector instance corresponding to the message name data1 : class of the receiver data2 : The CompiledMethod corresponding to this message on the receiver class, as encountered on the last dispatch. When a message is dispatched, this is the target object that needs to be located; it contains the bytecode for the method on the receiver. data3 : the module data4 : the primitive index if the SendSite resolves to a primitive method hits : counter of successfull caches of the receiver method misses : counter of unsuccessful caches, respectively lookup : pointer to function that performs actual method lookup c_data : for an FFI send site, holds the address of the FFI stub function to call. for a primitive send site, holds the address of the primitive function to call. */ struct send_site { OBJECT name; OBJECT sender; OBJECT selector; OBJECT data1; OBJECT data2; OBJECT data3; int data4; int hits, misses; send_site_lookup lookup; void *c_data; }; #define SENDSITE(obj) ((struct send_site*)BYTES_OF(obj)) #define SEND_SITE_OBJECT_FIELDS 6 void send_site_init(STATE); OBJECT send_site_create(STATE, OBJECT name); void send_site_set_sender(STATE, OBJECT self, OBJECT cm); #endif
0.996094
high
Doge/src/Doge/Renderer/Context.h
batuhanbozyel/RendererFramework
2
7079081
#pragma once #include <GLFW/glfw3.h> namespace Doge { class Window; class Context { public: Context(GLFWwindow* window); ~Context(); static void GLFWInit(); static void GLFWTerminate(); static void MakeCurrent(GLFWwindow* window); protected: void PollEvents(); void SwapBuffers(); inline GLFWwindow* SetWindow(GLFWwindow* window) { m_Window = window; } inline GLFWwindow* GetNativeWindow() const { return m_Window; } private: GLFWwindow* m_Window; static bool s_Initialized; friend Window; }; }
0.941406
high
VITimelineViewDemo/AppDelegate.h
VideoFlint/VITimelineView
50
7079593
<reponame>VideoFlint/VITimelineView // // AppDelegate.h // VITimelineViewDemo // // Created by Vito on 2018/11/15. // Copyright © 2018 vito. All rights reserved. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
0.558594
high
API/PacketTypeData.h
shadowIdeas/shadowAPI3
8
7080105
#pragma once #include "PacketTypeIdentifier.h" struct PacketTypeData { PacketTypeIdentifier identifier; UINT size; std::vector<BYTE> data; };
0.988281
high
firmware/xmc4500_relax_kit/smart_logger/deffs.h
hmz06967/smart_logger
1
7080617
/** * @file deffs.h * * @date 28.2.19 * @author <NAME> * @brief definitions and variables file for the application. */ #ifndef DEFFS_H_ #define DEFFS_H_ // definitions #define LED1 P1_1 ///< LED1 on XMC4500 relax kit connected to the Port 1.1. #define LED2 P1_0 ///< LED2 on XMC4500 relax kit connected to the Port 1.0. #define BUTTON1 P1_14 ///< Button 1 on XMC4500 relax kit connected to the Port 1.14. #define BUTTON2 P1_15 ///< Button 2 on XMC4500 relax kit connected to the Port 1.15. #define SAMPLING_PERIOD 1 #define CELL_VOLTAGES_SAMPLING_PERIOD 10 #define CAN_TIMEOUT 5 #define CELL_VOLTAGES_FLOW_COUNT 8 #define CELL_VOLTAGES_DATA_FLOW_COUNT 4 #define CELL_COUNTS 93 #define SET_TIME_MENU_ITEMS_COUNT 8 ///< Timer set menu items count uint8_t dataUpdated = 0; uint8_t cellVoltagesUpdated=0; unsigned long int sampleCounter=0; void UpdateLCD(void); FATFS FatFs; ///< FatFs work area needed for each volume. FIL Fil; ///< File object needed for each open file. XMC_RTC_TIME_t current_time; XMC_RTC_TIME_t set_time; uint8_t setTimeOnProcces=0; ///< Process indicator variable for the time set state machine. uint8_t setTimeMenu = 0; ///< Menu variable for time set uint8_t button2Pressed=0; enum timeSetStates { SET_TIME_IDLE = 0, ///< Idle state. SET_TIME_INIT, ///< Init state. YEAR, ///< Year set state. MONTH, ///< Month set state. DAY, ///< Day set state. HOUR, ///< Hour set state. MINUTE, ///< Minute set state. SET_OK ///< Time set ok state }; //uint8_t timeSetState= SET_TIME_IDLE; ///< State holder variable for the time set state machine. enum enumStates{ IDLE=0, ///< Idle state. GET_VELOCITY, ///< Get Smart velocity value. GET_BATT_AMP, ///< Get battery current. GET_BATT_VOLTAGE, ///< Get battery main voltage. GET_MODULE_TEMPS, ///< Get battery module temperatures. GET_CELL_VOLTAGES ///< Get battery cell voltages. }; uint8_t state = IDLE; ///< State holder variable for the main state machine. enum enumBattVoltStates{ BATT_VOLT_IDLE = 0, ///< Batt voltage idle state. BATT_VOLT_REQ_RESPONSE, ///< Batt voltage request response state. BATT_VOLT_FLOW_RESPONSE ///< Batt voltage flow control response state. }; uint8_t stateBattVolt = BATT_VOLT_IDLE; ///< State holder variable for battery voltage state machine. enum enumModuleTempsStates{ MODULE_TEMPS_IDLE = 0, ///< Module temperatures idle state. MODULE_TEMPS_REQ_RESPONSE, ///< Module temperatures request response state. MODULE_TEMPS_FLOW_RESPONSE ///< Module temperatures flow control response state. }; uint8_t stateModuleTemps = MODULE_TEMPS_IDLE; ///< State holder variable for module temperatures state machine. enum enumCellVoltagesStates{ CELL_VOLTAGES_IDLE = 0, ///< Cell voltages idle state. CELL_VOLTAGES_REQ_RESPONSE, ///< Cell voltages request response state. CELL_VOLTAGES_FLOW_CONTROL, ///< Cell voltages flow control response state. CELL_VOLTAGES_LAST_FLOW_PACKAGE ///< Cell voltages last flow package state }; uint8_t stateCellVoltages = CELL_VOLTAGES_IDLE; ///< State holder variable for module temperatures state machine. uint8_t cellVoltagesFlowCounter = 0; uint8_t onProcess = 0; ///< Process indicator variable for the main state machine. uint8_t samplingTimer=0; uint8_t canTimeoutTimerEnable=0; uint8_t canTimeoutCounter=0; /// Flow control package. uint8_t flowControl[8] = {0x30, 0x08, 0x14, 0xff, 0xff, 0xff, 0xff, 0xff}; /// Battery amp request package. uint8_t reqBattAmp[8] = {0x03, 0x22, 0x02, 0x03, 0xff, 0xff, 0xff, 0xff}; /// Battery voltage request package. uint8_t reqBattVolt[8] = {0x03, 0x22, 0x02, 0x04, 0xff, 0xff, 0xff, 0xff}; /// Module temperatures request package. uint8_t reqModuleTemps[8] = {0x03, 0x22, 0x02, 0x02, 0xff, 0xff, 0xff, 0xff}; /// Battery cell voltages request package. uint8_t reqCellVoltages[8] = {0x03, 0x22, 0x02, 0x08, 0xff, 0xff, 0xff, 0xff}; typedef struct { uint16_t velocitiy; float battAmp; float battVolt; float battPower; float battEnergy; float bms; uint8_t tempRawBytes[18]; float temps[9]; union { uint8_t cellVotlagesBytes[CELL_VOLTAGES_DATA_FLOW_COUNT*56+4]; ///< Byte array for cell voltages to read easily from can frames. uint16_t cellVoltages[CELL_VOLTAGES_DATA_FLOW_COUNT*28+2]; ///< Word array for cell voltages to represent in milliVolts. }; } smartData_t; smartData_t smartdata; #endif /* DEFFS_H_ */
0.984375
high
3RVX/MeterWnd/Meters/VerticalTile.h
grtamm/3RVX
320
7081129
// Copyright (c) 2015, <NAME>. // Distributed under the BSD 2-Clause License (see LICENSE.txt for details) #pragma once #include "HorizontalTile.h" class VerticalTile : public HorizontalTile { public: VerticalTile(std::wstring bitmapName, int x, int y, int units) : HorizontalTile(bitmapName, x, y, units) { } virtual void Draw(Gdiplus::Bitmap *buffer, Gdiplus::Graphics *graphics); };
0.953125
high
src/ib/ptl_hdr.h
tkordenbrock/portals4
20
7081641
<gh_stars>10-100 /** * @file ptl_hdr.h * * @brief This file contains the interface for message headers. */ #ifndef PTL_HDR_H #define PTL_HDR_H /* * PTL_XPORT_HDR * mainly carries information needed to route * packet to remote site and validate it * packed some unrelated info into the first word */ #define PTL_HDR_VER_1 (1) /* note: please keep all init->target before all tgt->init */ enum hdr_op { /* from init to target */ OP_PUT = 1, OP_GET, OP_ATOMIC, OP_FETCH, OP_SWAP, /* must be last of requests */ /* Either way. */ OP_RDMA_DISC, /* from target to init. Do not change the order. */ OP_REPLY, OP_ACK, OP_CT_ACK, OP_OC_ACK, OP_NO_ACK, /* when remote ME has ACK_DISABLE */ OP_LAST, }; enum hdr_fmt { PKT_FMT_REQ, PKT_FMT_REPLY, PKT_FMT_ACK, PKT_FMT_LAST, }; /** * @brief Common header for portals request/response messages. */ struct hdr_common { unsigned int version:4; unsigned int operation:4; unsigned int ni_fail:4; /* response only */ unsigned int data_in:1; unsigned int data_out:1; unsigned int matching_list:2; /* response only */ unsigned int operand:1; unsigned int pad:6; unsigned int physical:1; /* PPE */ unsigned int ni_type:4; /* request only */ unsigned int pkt_fmt:4; /* request only */ __le32 handle; union { __le32 src_nid; __le32 src_rank; }; __le32 src_pid; #if IS_PPE /* This information is always needed by the PPE to find the * destination NI. */ __le32 hash; union { __le32 dst_nid; __le32 dst_rank; }; __le32 dst_pid; #endif }; /** * @brief Header for Portals request messages. * * Due to headers being reused to send a reply/ack, hdr_common must * be first, followed by hdr_region. */ typedef struct req_hdr { struct hdr_common h1; unsigned int ack_req:4; unsigned int atom_type:4; unsigned int atom_op:5; unsigned int reserved_19:19; __le64 rlength; __le64 roffset; __le64 match_bits; __le64 hdr_data; __le32 pt_index; __le32 uid; #if WITH_TRANSPORT_UDP unsigned int udp_is_large:1; unsigned int fragment_seq:8; #endif } req_hdr_t; /* Header for an ack or a reply. */ typedef struct ack_hdr { struct hdr_common h1; __le64 mlength; __le64 moffset; } ack_hdr_t; #endif /* PTL_HDR_H */
0.996094
high
include/ekutil/span.h
eliaskosunen/ekutil
0
7082153
<filename>include/ekutil/span.h // Copyright 2018-2019 <NAME> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // This file is a part of ekutil: // https://github.com/eliaskosunen/ekutil #ifndef EKUTIL_SPAN_H #define EKUTIL_SPAN_H #include "compat.h" #include <iterator> #include <type_traits> namespace ekutil { /** * A view over a contiguous range. * Stripped-down version of `std::span`. */ template <typename T> class span { public: using element_type = T; using value_type = typename std::remove_cv<T>::type; using index_type = std::ptrdiff_t; using difference_type = std::ptrdiff_t; using pointer = T*; using const_pointer = T*; using reference = T&; using iterator = pointer; using const_iterator = const_pointer; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; EKUTIL_CONSTEXPR span() noexcept = default; EKUTIL_CONSTEXPR span(pointer ptr, index_type count) noexcept : m_ptr(ptr), m_size(count) { } EKUTIL_CONSTEXPR span(pointer first, pointer last) noexcept : span(first, last - first) { } EKUTIL_CONSTEXPR iterator begin() const noexcept { return m_ptr; } EKUTIL_CONSTEXPR iterator end() const noexcept { return m_ptr + m_size; } EKUTIL_CONSTEXPR reverse_iterator rbegin() const noexcept { return reverse_iterator{end()}; } EKUTIL_CONSTEXPR reverse_iterator rend() const noexcept { return reverse_iterator{begin()}; } EKUTIL_CONSTEXPR const_iterator cbegin() const noexcept { return m_ptr; } EKUTIL_CONSTEXPR const_iterator cend() const noexcept { return m_ptr + m_size; } EKUTIL_CONSTEXPR const_reverse_iterator crbegin() const noexcept { return reverse_iterator{cend()}; } EKUTIL_CONSTEXPR const_reverse_iterator crend() const noexcept { return reverse_iterator{cbegin()}; } EKUTIL_CONSTEXPR14 reference operator[](index_type i) const noexcept { return *(m_ptr + i); } EKUTIL_CONSTEXPR pointer data() const noexcept { return m_ptr; } EKUTIL_CONSTEXPR index_type size() const noexcept { return m_size; } EKUTIL_CONSTEXPR14 span<T> subspan(index_type off) const { return span<T>(data() + off, size() - off); } EKUTIL_CONSTEXPR14 span<T> subspan(index_type off, difference_type count) const { return span<T>(data() + off, count); } private: pointer m_ptr{nullptr}; index_type m_size{0}; }; template <typename T> EKUTIL_CONSTEXPR span<T> make_span(T* ptr, std::ptrdiff_t count) noexcept { return span<T>(ptr, count); } template <typename T> EKUTIL_CONSTEXPR span<T> make_span(T* first, T* last) noexcept { return span<T>(first, last); } template <typename T> EKUTIL_CONSTEXPR span<typename T::value_type> make_span( T& container) noexcept { return span<typename T::value_type>( std::addressof(*std::begin(container)), std::addressof(*(std::end(container) - 1)) + 1); } } // namespace ekutil #endif // EKUTIL_SPAN_H
0.996094
high
cpp/binary_search_tree.h
runningforlife/CodingExamples
0
7082665
<reponame>runningforlife/CodingExamples #ifndef _BINARY_SEARCH_TREE_H #define _BINARY_SEARCH_TREE_Hi struct TreeNode { int key; struct TreeNode *left; struct TreeNode *right; TreeNode() { this->key = -1; this->left = nullptr; this->right = nullptr; } TreeNode(int key) { this->key = key; this->left = nullptr; this->right = nullptr; } }; class BinaryTree { public: BinaryTree() { root = nullptr; } void insert(int key); struct TreeNode *find(int key); struct TreeNode *deleteNode(int key); void dumpTree(); private: struct TreeNode *root; void insertRecursive(int key, struct TreeNode *&node); struct TreeNode *findNode(int key, struct TreeNode *node); void visitTree(struct TreeNode *node, int* count); }; #endif
0.988281
high
JWBasicFoundation/Classes/JWBasicFoundation.h
liujunwei2018/JWBasicFoundation
0
7083177
<reponame>liujunwei2018/JWBasicFoundation<filename>JWBasicFoundation/Classes/JWBasicFoundation.h<gh_stars>0 // // JWBasicFoundation.h // JWBasicFoundation // // Created by 刘君威 on 2020/2/4. // Copyright © 2020 liujunwei. All rights reserved. // #ifndef JWBasicFoundation_h #define JWBasicFoundation_h #import "NSArray+Blank.h" #import "NSArray+JW.h" #import "NSMutableArray+JW.h" #import "NSData+JW.h" #import "NSDate+JW.h" #import "NSDateFormatter+JW.h" #import "NSDictionary+JW.h" #import "NSMutableDictionary+JW.h" #import "NSNotificationCenter+JW.h" #import "NSString+JW.h" #import "JWWeakTimer.h" #endif /* JWBasicFoundation_h */
0.945313
high
Config.h
1-gcc/Loup
0
7083689
// Config.h // (C) Copyright 2017 by <NAME> see License.txt for details // #pragma once #include <set> #include <string> class Config { public: class Options { public: char * pathConfigFile; Options(); }; class PortInfo { public: unsigned short port; PortInfo * nextPort; PortInfo() { port = 0; nextPort = NULL; } PortInfo(unsigned short port) { this->port = port; nextPort = NULL; } }; static const int UNLIMITED = 0; size_t countProcesses; size_t maxConnectionsPerProcess; size_t countPorts; size_t sleepTime; int timeout; char * logFile; char * connectTo; char * connectPort; std::set<std::string> traceFlags; PortInfo * ports; Options options; bool storeWrite; bool storeRead; Config(); bool load(); protected: bool parseLine(const char* buffer, size_t bufsize, size_t line); void addPort(unsigned short port); };
0.898438
high
tests/check_pcrio.c
sandsmark/pcrio
0
7084201
<reponame>sandsmark/pcrio #include <check.h> #include <string.h> #include <stdlib.h> #include <memory.h> #include "../pcrio.h" #define LANG_EN 1033 #define L_AOE "lang/aoe/language.dll" #define L_AOK "lang/aok/language.dll" // TODO get_stringL test errors struct pcr_file * test_read_file(const char *filename, pcr_error_code *err) { struct pcr_file *pcr_file = NULL; pcr_file = pcr_read_file(filename, err); fail_unless (PCR_SUCCESS(*err), "failed to read %s", filename); return pcr_file; } void test_check_string(struct pcr_file *pf, uint32_t id, int32_t lang, const char *str) { char *buff = NULL; int buff_size; buff_size = pcr_get_strlenL(pf, id, lang) + 1; buff = (char *)malloc(sizeof(char) * buff_size); fail_unless(buff != NULL, "alloc failed"); pcr_get_stringL(pf, id, lang, buff, buff_size); fail_if(pcr_get_stringL(pf, id, lang, buff, buff_size) != 0, NULL); fail_unless(strcmp(buff, str) == 0, "Read string: \"%s\" differs from: \"%s\".", buff, str); free(buff); } void test_read_only(const char *filename) { pcr_error_code err = PCR_ERROR_NONE; pcr_free(test_read_file(filename, &err)); } START_TEST (test_pcrio_read) { test_read_only(L_AOE); test_read_only(L_AOK); test_read_only("lang/aok/language_x1.dll"); test_read_only("lang/aok/language_x1_p1.dll"); test_read_only("lang/sw/language.dll"); test_read_only("lang/sw/language_x1.dll"); } END_TEST START_TEST (test_pcrio_rw) { pcr_error_code err = PCR_ERROR_NONE; struct pcr_file *pf = NULL; pf = test_read_file("lang/other/section_null.dll", &err); pcr_write_file("out.dll", pf, &err); fail_unless(err == PCR_ERROR_NONE, NULL); pcr_free(pf); } END_TEST START_TEST (test_pcrio_pcr_get_string) { pcr_error_code err = PCR_ERROR_NONE; struct pcr_file *pf = NULL; pf = test_read_file(L_AOK, &err); // random read test fail_unless(pcr_get_strlenL(pf, 4488, pcr_get_default_language(pf)->id) == 14, NULL); fail_unless(pcr_get_strlen(pf, 4488) == 14, NULL); const struct pcr_language *lang = pcr_get_default_language(pf); char *buff = (char *)malloc(sizeof(char) * 20); fail_unless(buff != NULL, "alloc failed"); fail_unless(pcr_get_stringL(pf, 4488, lang->id, buff, 20) == 0, NULL); fail_unless(strcmp(buff, "Takeda Shingen") == 0, NULL); buff[3] = '\0'; buff[4] = '\0'; fail_unless(pcr_get_stringL(pf, 4488, lang->id, buff, 4) == 0, NULL); fail_unless(strcmp(buff, "Take") == 0, NULL); fail_unless(pcr_get_stringL(pf, 4488, 1234, buff, 15) == 0, NULL); fail_unless(strlen(buff) == 0, NULL); int i; for (i=0; i<15; i++) fail_if(buff[i] != '\0', NULL); free(buff); pcr_free(pf); } END_TEST START_TEST (test_pcrio_rw_strings) { pcr_error_code err = PCR_ERROR_NONE; struct pcr_file *pf = NULL; pf = test_read_file(L_AOE, &err); struct pcr_language lang = *pcr_get_default_language(pf); pcr_set_stringC(pf, 9999, lang, "test"); pcr_write_file("out.dll", pf, &err); fail_unless(PCR_SUCCESS(err), NULL); pcr_free(pf); pf = test_read_file("out.dll", &err); test_check_string(pf, 101, LANG_EN, "1"); test_check_string(pf, 54518, LANG_EN, "Click to order units to repair a building or boat."); test_check_string(pf, 9999, LANG_EN, "test"); const struct language_info_array *ci_arr = pcr_get_language_info(pf); fail_unless(ci_arr->count == 1, NULL); fail_unless(ci_arr->array[0].lang.id == LANG_EN, NULL); } END_TEST START_TEST (test_pcrio_aok_stress) { pcr_error_code err = PCR_ERROR_NONE; struct pcr_file *pf = NULL; pf = test_read_file(L_AOK, &err); uint32_t index = 64000; struct pcr_language lang = *pcr_get_default_language(pf); for (; index < 70000; index++) pcr_set_stringC(pf, index, lang, "testtesttest"); pcr_write_file("out_big_aok.dll", pf, &err); pcr_free(pf); pf = test_read_file("out_big_aok.dll", &err); for (index = 64000; index < 70000; index++) test_check_string(pf, index, LANG_EN, "testtesttest"); for (index = 64000; index < 70000; index++) pcr_set_stringC(pf, index, lang, ""); pcr_write_file("not_so_big_aok.dll", pf, &err); fail_unless(PCR_SUCCESS(err), NULL); pcr_free(pf); } END_TEST START_TEST (test_pcrio_get_codepage) { pcr_error_code err = PCR_ERROR_NONE; struct pcr_file *pf = NULL; pf = test_read_file(L_AOK, &err); fail_unless(pcr_get_codepage(pf, 4488) == 0, NULL); fail_unless(pcr_get_codepageL(pf, 4488, LANG_EN) == 0, NULL); fail_unless(pcr_get_codepage(pf, 1010) == 0, NULL); // no string, but lang dir fail_unless(pcr_get_codepage(pf, 70000) == 0, NULL); // no string, no lang fail_unless(pcr_get_codepageL(pf, 70000, 1234) == (unsigned)PCR_RET_ERR_LANG_NOT_SET, NULL); pcr_free(pf); } END_TEST Suite * pcrio_suite (void) { Suite *s = suite_create ("pcrio"); TCase *tc_core = tcase_create("Core"); tcase_add_test(tc_core, test_pcrio_read); tcase_add_test(tc_core, test_pcrio_rw); tcase_add_test(tc_core, test_pcrio_rw_strings); tcase_add_test(tc_core, test_pcrio_aok_stress); tcase_add_test(tc_core, test_pcrio_pcr_get_string); tcase_add_test(tc_core, test_pcrio_get_codepage); suite_add_tcase(s, tc_core); return s; } int main(void) { int number_failed; Suite *s = pcrio_suite(); SRunner *sr = srunner_create(s); srunner_run_all(sr, CK_NORMAL); number_failed = srunner_ntests_failed(sr); srunner_free(sr); return (number_failed == 0) ? 0 : -1; }
0.996094
high
SWIG_CGAL/Kernel/Direction_3.h
chrisidefix/cgal-bindings
33
7084713
<reponame>chrisidefix/cgal-bindings // ------------------------------------------------------------------------------ // Copyright (c) 2011 GeometryFactory (FRANCE) // Distributed under the Boost Software License, Version 1.0. (See accompany- // ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // ------------------------------------------------------------------------------ #ifndef SWIG_CGAL_KERNEL_DIRECTION_3_H #define SWIG_CGAL_KERNEL_DIRECTION_3_H #include <SWIG_CGAL/Kernel/Direction_3_decl.h> #include <SWIG_CGAL/Kernel/Direction_3_impl.h> #endif //SWIG_CGAL_KERNEL_DIRECTION_3_H
0.800781
high