hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
260
max_issues_repo_name
stringlengths
5
109
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
260
max_forks_repo_name
stringlengths
5
109
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
3493799933d619fe01d91cc5a5d067bdb965fda1
939
h
C
src/wstring.h
8bitslime/Winter
2a2ae7ef57313d4611432e4e58285ba098ccb223
[ "MIT" ]
2
2019-02-24T09:00:24.000Z
2020-12-24T23:27:01.000Z
src/wstring.h
8bitslime/Winter
2a2ae7ef57313d4611432e4e58285ba098ccb223
[ "MIT" ]
null
null
null
src/wstring.h
8bitslime/Winter
2a2ae7ef57313d4611432e4e58285ba098ccb223
[ "MIT" ]
null
null
null
#ifndef WSTRING_H #define WSTRING_H //TODO unicode #include "wtype.h" #include "object.h" typedef struct wstring_t { REFCOUNT; hash_t hash; size_t length; size_t capacity; char *data; } wstring_t; //Creates an automatic string with a literal value (no allocations) #define AUTO_STRING(str) (wstring_t){REF_PERSISTENT, 0, (sizeof(str)/sizeof(*str)), 0, str} wstring_t *_winter_stringAlloc(winterState_t *state, size_t size); wstring_t *_winter_stringCreateSize(winterState_t *state, const char *string, size_t size); wstring_t *_winter_stringCreate(winterState_t *state, const char *string); void _winter_stringFree(winterState_t *state, wstring_t *string); hash_t _winter_stringHash(wstring_t *string); bool_t _winter_stringCompare(wstring_t *a, wstring_t *b); wstring_t *_winter_stringDup(winterState_t *state, const wstring_t *string); wstring_t *_winter_stringCat(winterState_t *state, wstring_t *a, wstring_t *b); #endif
29.34375
91
0.787007
[ "object" ]
349bcb31d65fb3106dd863adfaea5dc5df8636e6
2,111
h
C
3rd_party_programs/exonerate-2.2.0/src/model/coding2coding.h
b-brankovics/grabb
4ea7081305489b59b5fe94ce9f93f358851931ca
[ "MIT" ]
12
2015-10-29T15:55:02.000Z
2021-09-10T05:17:16.000Z
3rd_party_programs/exonerate-2.2.0/src/model/coding2coding.h
b-brankovics/grabb
4ea7081305489b59b5fe94ce9f93f358851931ca
[ "MIT" ]
3
2017-01-13T12:03:29.000Z
2018-10-05T15:02:45.000Z
3rd_party_programs/exonerate-2.2.0/src/model/coding2coding.h
b-brankovics/grabb
4ea7081305489b59b5fe94ce9f93f358851931ca
[ "MIT" ]
7
2017-02-17T21:11:10.000Z
2021-04-08T21:06:56.000Z
/****************************************************************\ * * * Coding DNA comparison model * * * * Guy St.C. Slater.. mailto:guy@ebi.ac.uk * * Copyright (C) 2000-2008. All Rights Reserved. * * * * This source code is distributed under the terms of the * * GNU General Public License, version 3. See the file COPYING * * or http://www.gnu.org/licenses/gpl.txt for details * * * * If you use this code, please keep this notice intact. * * * \****************************************************************/ #ifndef INCLUDED_CODING2CODING_H #define INCLUDED_CODING2CODING_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #include "c4.h" #include "sequence.h" #include "affine.h" typedef struct { Affine_Data ad; /* inherit */ } Coding2Coding_Data; /**/ #define Coding2Coding_Data_get_submat(c2dd) \ Affine_Data_get_protein_submat(&((c2dd)->ad)) #define Coding2Coding_Data_get_translate(c2dd) \ Affine_Data_get_translate(&((c2dd)->ad)) #define Coding2Coding_Data_get_Frameshift_Data(c2dd) \ Affine_Data_get_Frameshift_Data(&((c2dd)->ad)) #define Coding2Coding_Data_get_Intron_Data(c2dd) \ Affine_Data_get_Intron_Data(&((c2dd)->ad)) void Coding2Coding_Data_init(Coding2Coding_Data *c2cd, Sequence *query, Sequence *target); Coding2Coding_Data *Coding2Coding_Data_create(Sequence *query, Sequence *target); void Coding2Coding_Data_clear(Coding2Coding_Data *c2cd); void Coding2Coding_Data_destroy(Coding2Coding_Data *c2cd); /**/ C4_Model *Coding2Coding_create(void); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* INCLUDED_CODING2CODING_H */
35.779661
66
0.522027
[ "model" ]
349f0b8fcb50185c4c7e8bc7243fd088faab6bd9
913
h
C
Clerk/UI/Alerts/AlertsListDataModel.h
sergeylenkov/Clerk
b220864e89559207c5eeea113668891236fcbfb9
[ "MIT" ]
14
2016-11-01T15:48:02.000Z
2020-07-15T13:00:27.000Z
Clerk/UI/Alerts/AlertsListDataModel.h
sergeylenkov/Clerk
b220864e89559207c5eeea113668891236fcbfb9
[ "MIT" ]
29
2017-11-16T04:15:33.000Z
2021-12-22T07:15:42.000Z
Clerk/UI/Alerts/AlertsListDataModel.h
sergeylenkov/Clerk
b220864e89559207c5eeea113668891236fcbfb9
[ "MIT" ]
2
2018-08-15T15:25:11.000Z
2019-01-28T12:49:50.000Z
#pragma once #include <wx/dataview.h> #include "../../Utils/Utils.h" #include "../../Data/ViewModels/AlertViewModel.h" using namespace Clerk::Data; using namespace Clerk::Utils; class AlertsListDataModel : public wxDataViewListStore { public: enum class Columns { Name, Type, Period, Condition, Amount, Last }; AlertsListDataModel(); ~AlertsListDataModel(); void SetItems(std::vector<std::shared_ptr<AlertViewModel>> alerts); virtual unsigned int GetColumnCount() const; virtual wxString GetColumnType(unsigned int column) const; virtual void GetValueByRow(wxVariant &variant, unsigned int row, unsigned int column) const; virtual bool GetAttrByRow(unsigned int row, unsigned int column, wxDataViewItemAttr &attr) const; virtual bool SetValueByRow(const wxVariant &variant, unsigned int row, unsigned int column); private: std::vector<std::shared_ptr<AlertViewModel>> _alerts; };
24.026316
98
0.761227
[ "vector" ]
34a4ac270e60cba637b3ff2b46341cc24a99ccac
23,224
c
C
viewkel/band_graphs.c
richardjgowers/yaehmop
d8c7e437b949af4868f7d79c68faf77433081549
[ "BSD-2-Clause" ]
17
2016-08-07T05:17:19.000Z
2022-01-19T16:57:28.000Z
viewkel/band_graphs.c
richardjgowers/yaehmop
d8c7e437b949af4868f7d79c68faf77433081549
[ "BSD-2-Clause" ]
26
2016-07-28T18:59:31.000Z
2021-02-22T13:03:01.000Z
viewkel/band_graphs.c
richardjgowers/yaehmop
d8c7e437b949af4868f7d79c68faf77433081549
[ "BSD-2-Clause" ]
12
2016-07-28T18:57:32.000Z
2022-01-19T17:07:25.000Z
/******************************************************* Copyright (C) 1995 Greg Landrum All rights reserved This file is part of yaehmop. 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ********************************************************************/ /******** this has got the stuff for dealing with band graphs.... Created by greg Landrum June 1994 *********/ /*** Recent Edit History: 03.05.98 gL: bounding boxes adjusted. 14.06.98 gL: added support for reading out Fermi levels (if there) added some EOF checking in read_band_data 26.09.98 gL: various modifications to remove warning when compiled with -Wall under gcc (yeah yeah... it's anal). Hopefully this will fix a nasty crashing bug though. 18.10.98 gL: support for fatbands added. draw_band_graph still needs to be modified a little bit to be able to deal with multiple fatbands plots in one file. Uh, not that there is currently any software which generates such a data file... there will be though, yes there will... you'll see. ***/ #include "viewkel.h" /**************************************************************************** * * Procedure preprocess_band_graph_data * * Arguments: band_graph: a pointer to band_graph_type * * Returns: none * * Action: This does any preprocessing which is needed on the band graph data. * ****************************************************************************/ void preprocess_band_graph_data( band_graph_type *band_graph ) { float xscale,yscale; float oldmax_x,oldmin_x; int i,j,k; #ifdef SUPPORT_FATBANDS int fatband_offset; #endif /* save the x axis maxima and minima */ oldmax_x = band_graph->the_data->max_x; oldmin_x = band_graph->the_data->min_x; /* find the tic mark spacing */ find_tic_sep(band_graph->the_data); band_graph->the_data->max_x = oldmax_x; band_graph->the_data->min_x = oldmin_x; /* scale all the points to fit in a DEF_GRAPH_X x DEF_GRAPH_Y box */ xscale = DEF_GRAPH_X/(band_graph->the_data->max_x - band_graph->the_data->min_x); yscale = DEF_GRAPH_Y/(band_graph->the_data->max_y - band_graph->the_data->min_y); #ifdef SUPPORT_FATBANDS fatband_offset = band_graph->the_data->num_p*band_graph->the_data->num_curves; #endif for( i=0; i<band_graph->the_data->num_p; i++ ){ for(j=0;j<band_graph->the_data->num_curves;j++){ band_graph->the_data->data[i*band_graph->the_data->num_curves+j].x = band_graph->the_data->raw_data[i*band_graph->the_data->num_curves+j].x*xscale; if( band_graph->the_data->raw_data[i*band_graph->the_data->num_curves+j].y > band_graph->the_data->max_y ){ band_graph->the_data->data[i*band_graph->the_data->num_curves+j].y = band_graph->the_data->max_y * yscale; #ifdef SUPPORT_FATBANDS for(k=1;k<=band_graph->num_fatbands;k++){ band_graph->the_data->data[k*fatband_offset + i*band_graph->the_data->num_curves+j].y = 0; } #endif } else if( band_graph->the_data->raw_data[i*band_graph->the_data->num_curves+j].y < band_graph->the_data->min_y ){ band_graph->the_data->data[i*band_graph->the_data->num_curves+j].y = band_graph->the_data->min_y * yscale; #ifdef SUPPORT_FATBANDS for(k=1;k<=band_graph->num_fatbands;k++){ band_graph->the_data->data[k*fatband_offset + i*band_graph->the_data->num_curves+j].y = 0; } #endif } else{ band_graph->the_data->data[i*band_graph->the_data->num_curves+j].y = band_graph->the_data->raw_data[i*band_graph->the_data->num_curves+j].y * yscale; #ifdef SUPPORT_FATBANDS for(k=1;k<=band_graph->num_fatbands;k++){ band_graph->the_data->data[k*fatband_offset + i*band_graph->the_data->num_curves+j].y = band_graph->the_data->raw_data[k*fatband_offset + i*band_graph->the_data->num_curves+j].y*yscale; } #endif } } } /* change the x tic marks */ band_graph->the_data->tic_sep_x = band_graph->points_per_line; band_graph->the_data->num_tics_x = band_graph->num_special_points; /* adjust the tic mark spacing to fit the new scaling */ band_graph->the_data->tic_sep_x *= xscale; band_graph->the_data->tic_sep_y *= yscale; band_graph->the_data->tic_start_x *= xscale; band_graph->the_data->tic_start_y *= yscale; } /**************************************************************************** * * Procedure read_band_data * * Arguments: infile: pointer to FILE * band_graph: pointer to band_graph_type * * Returns: none * * Action: Reads in all the data needed to construct a band structure * graph from 'infile and stores it in the proper format in 'band_graph * ****************************************************************************/ void read_band_data(FILE *infile,band_graph_type *band_graph) { graph_type *the_data; char instring[MAX_STR_LEN],foostring[MAX_STR_LEN]; int eof_hit; int i,j,k; int points_per_line,num_special_points,num_orbs; int tot_num_points; float max_x,max_y,min_x,min_y; #ifdef SUPPORT_FATBANDS int num_fatbands=0; int points_required; #endif /* read out the number of special points */ skipcomments(infile,instring); if( instring[0] == '#' || instring[1] == '#'){ #ifdef SUPPORT_FATBANDS upcase(instring); if( strstr(instring,"FATBANDS") ){ sscanf(instring,"%s %d",foostring,&num_fatbands); band_graph->num_fatbands = num_fatbands; } #endif skipcomments(infile,instring); } sscanf(instring,"%d",&num_special_points); band_graph->num_special_points = num_special_points; /* read out the number of k-points per symmetry line */ skipcomments(infile,instring); sscanf(instring,"%d",&points_per_line); band_graph->points_per_line = points_per_line; /* read out the number of orbitals */ skipcomments(infile,instring); sscanf(instring,"%d",&num_orbs); /* get all the memory that we need */ band_graph->special_points = (special_point_type *)D_CALLOC(num_special_points, sizeof(special_point_type)); if( !band_graph->special_points ) fatal("Can't get memory for special_points."); band_graph->the_data = (graph_type *)D_CALLOC(1,sizeof(graph_type)); if( !band_graph->the_data )fatal("Can't get memory for the_data."); the_data = band_graph->the_data; tot_num_points = the_data->num_p = (num_special_points-1)*points_per_line + 1; the_data->num_curves = num_orbs; #ifdef SUPPORT_FATBANDS points_required = the_data->num_curves*the_data->num_p + num_fatbands*the_data->num_curves*the_data->num_p; the_data->raw_data = (point_type2D *)D_CALLOC(points_required,sizeof(point_type2D)); #else the_data->raw_data = (point_type2D *)D_CALLOC(the_data->num_curves*the_data->num_p, sizeof(point_type2D)); #endif if(!the_data->raw_data)fatal("Can't allocate the_data->raw_data"); the_data->curves_to_display = (char *)D_CALLOC(1,sizeof(char)); if( !the_data->curves_to_display )fatal("Can't get space for curves_to_display."); the_data->curves_to_display[0] = 1; the_data->styles = (char *)D_CALLOC(1,sizeof(char)); if( !the_data->styles )fatal("Can't get space for styles."); the_data->styles[0] = 0; /* now read out the special point information */ for(i=0;i<num_special_points;i++){ skipcomments(infile,instring); sscanf(instring,"%s %lf %lf %lf",band_graph->special_points[i].name, &band_graph->special_points[i].loc.x,&band_graph->special_points[i].loc.y, &band_graph->special_points[i].loc.z); } /* now read out the actual information */ for(i=0;i<tot_num_points;i++){ for(j=0;j<num_orbs;j++){ the_data->raw_data[i*num_orbs+j].x = i; eof_hit = skipcomments(infile,instring); if( eof_hit < 0 ){ fprintf(stderr,"EOF hit whilst reading band file\n"); fprintf(stderr,"We had read %d points of %d,\n", i,tot_num_points); fprintf(stderr,"\tand died on orbital %d of %d\n", j,num_orbs); error("Early EOF"); the_data->num_curves = 0; return; } #ifdef SUPPORT_FATBANDS sscanf((const char *)strtok(instring," "),"%lf",&the_data->raw_data[i*num_orbs+j].y); for(k=1;k<=num_fatbands;k++){ sscanf((const char *)strtok(0," "),"%lf", &the_data->raw_data[k*num_orbs*tot_num_points + i*num_orbs+j].y); } #else sscanf(instring,"%lf",&the_data->raw_data[i*num_orbs+j].y); #endif } } /* check if there's a Fermi Energy present */ while(eof_hit >= 0 && !strstr(instring,"FERMI_ENERGY")){ eof_hit = skipcomments(infile,instring); upcase(instring); } if (!eof_hit){ sscanf(instring,"%s %lf",foostring,&band_graph->Fermi_E); band_graph->show_fermi = 1; } #ifdef SUPPORT_FATBANDS points_required = the_data->num_curves*the_data->num_p + num_fatbands*the_data->num_curves*the_data->num_p; the_data->data = (point_type2D *)D_CALLOC((unsigned)points_required,sizeof(point_type2D)); #else the_data->data = (point_type2D *)D_CALLOC((unsigned)tot_num_points*num_orbs, sizeof(point_type2D)); #endif if( !the_data->data ) fatal("Can't get space for graph data."); /* find the minimum and maximum values (to use in scaling) */ min_y = min_x = 1e10; max_y = max_x = -1e10; for( i=0; i<tot_num_points; i++ ){ if(the_data->raw_data[i*num_orbs].x > max_x) max_x = the_data->raw_data[i*num_orbs].x; if(the_data->raw_data[i*num_orbs].x < min_x) min_x = the_data->raw_data[i*num_orbs].x; for(j=0;j<num_orbs;j++){ if(the_data->raw_data[i*num_orbs+j].y > max_y) max_y = the_data->raw_data[i*num_orbs+j].y; if(the_data->raw_data[i*num_orbs+j].y < min_y) min_y = the_data->raw_data[i*num_orbs+j].y; } } the_data->max_x = max_x; the_data->max_y = max_y; the_data->min_x = min_x; the_data->min_y = min_y; } /**************************************************************************** * * Procedure new_band_graph * * Arguments: filename: pointer to char * * Returns: none * * Action: does everything to get space for and read in a new band_graph * ****************************************************************************/ void new_band_graph(char *filename) { char failed = 0; char file_name[80]; char *theinline; FILE *infile; graph_type *the_graph; /* set up a new object to hold the thing */ makenewobject(); whichobj = head->obj; /* now build the band_graph primitive */ whichobj->prim = (prim_type *)D_CALLOC(1,sizeof(prim_type)); if( !whichobj->prim )fatal("Can't get space for prop_graph primitive."); whichobj->prim->which = BAND_GRAPH; whichobj->prim->band_graph = (band_graph_type *)D_CALLOC(1,sizeof(band_graph_type)); if( !whichobj->prim->band_graph ) fatal("Can't get space for band_graph."); #ifndef USING_THE_MAC if( !filename ){ display("Look in the xterm..."); #ifndef USE_READLINE printf("Enter the file name containing the band structure data: "); scanf("%s",file_name); #else theinline= readline("Enter the file name containing the band structure data: "); add_history(theinline); if( theinline ){ sscanf(theinline,"%s",file_name); free(theinline); } else { error("Bad file name"); file_name[0] = 0; } #endif } else{ strcpy(file_name,filename); } /* open the file */ infile = fopen(file_name,"r"); if(!infile){ printf("Problems opening file: %s\n",file_name); display("oooooops!"); failed = 1; } #else if(!filename){ infile = choose_mac_file(file_name,MAC_FOPEN_OPEN_CD); } else{ strcpy(file_name,filename); infile = fopen(file_name,"r"); } if( !infile ){ printf("Problems opening file: %s\n",file_name); display("oooooops!"); failed = 1; } #endif /* get the initial data */ if( !failed ){ strcpy(whichobj->prim->band_graph->filename,file_name); read_band_data(infile,whichobj->prim->band_graph); preprocess_band_graph_data(whichobj->prim->band_graph); } /* check to see if any curves were actually read in.... */ if(!whichobj->prim->band_graph->the_data->num_curves || failed){ /* no... free the memory that we asked for */ D_FREE(whichobj->prim->band_graph->the_data); D_FREE(whichobj->prim->band_graph); D_FREE(whichobj->prim); D_FREE(whichobj); whichobj=0; head->obj=0; head = head->next; return; } else{ whichobj->scale.x=whichobj->scale.y=whichobj->scale.z=2.0*GRAPHICS_SCALE; whichobj->cent.x=-180;whichobj->cent.y=180; whichobj->cent.z=0*GRAPHICS_SCALE; whichobj->trans.x=0;whichobj->trans.y=0; whichobj->trans.z=0; /* now fill in the legends... */ the_graph = whichobj->prim->band_graph->the_data; strcpy(the_graph->ylegend,"Energy (eV)"); the_graph->do_x_tics = 1; the_graph->do_y_tics = 1; #ifdef SUPPORT_FATBANDS if( whichobj->prim->band_graph->num_fatbands ){ whichobj->prim->band_graph->fatband_scale = 1.0; whichobj->prim->band_graph->fatband_fill = FATBANDS_LINE; whichobj->prim->band_graph->fatbands_on = 1; } #endif build_band_button_window(&button_wins,whichobj->prim->band_graph); whichobj->prim->but_win = button_wins; } } /**************************************************************************** * * Procedure draw_band_graph * * Arguments: prim: pointer to primitive_type * obj: pointer to object_type * * Returns: none * * Action: Draws in a band structure graph. * This takes care of the user specified scaling and translating. * ****************************************************************************/ void draw_band_graph(prim_type *prim,object_type *obj) { static XPoint *points=0; static point_type2D *fpoints=0; static int num_points=0; int i,j; graph_type *the_graph; band_graph_type *band_graph; point_type2D origin,dim; char numstring[20]; float xloc,yloc; float scaled_fermi; float xscale,yscale; float inv_xscale,inv_yscale; int max_str_len; float xref,yref; float yval; #ifdef SUPPORT_FATBANDS int tot_num_p; float fat_width1,fat_width2; point_type2D fb_p1,fb_p2; #endif the_graph = prim->band_graph->the_data; band_graph = prim->band_graph; /* check to see if we need to re-determine the location of tic marks */ if( the_graph->old_max_x != the_graph->max_x || the_graph->old_max_y != the_graph->max_y || the_graph->old_min_x != the_graph->min_x || the_graph->old_min_y != the_graph->min_y ){ preprocess_band_graph_data(band_graph); the_graph->old_max_x = the_graph->max_x; the_graph->old_max_y = the_graph->max_y; the_graph->old_min_x = the_graph->min_x; the_graph->old_min_y = the_graph->min_y; } /* check to see if we need memory for the Xpoints */ if( !points || num_points < the_graph->num_p ){ if( points ) free(points); num_points = the_graph->num_p; points = (XPoint *)calloc(num_points,sizeof(XPoint)); if( !points ) fatal("Can't allocate memory for point storage in draw_graph."); if( fpoints ) free(fpoints); fpoints = (point_type2D *)calloc(num_points,sizeof(point_type2D)); if( !fpoints ) fatal("Can't allocate memory for fpoint storage in draw_graph."); } /* inverse scaling terms */ inv_xscale = (the_graph->max_x - the_graph->min_x) / DEF_GRAPH_X; inv_yscale = (the_graph->max_y - the_graph->min_y) / DEF_GRAPH_Y; xscale = 1/inv_xscale; yscale = 1/inv_yscale; /* determine the location of the origin on screen */ origin.x = obj->cent.x + obj->trans.x + g_xmax / 2; origin.y = obj->cent.y - obj->trans.y + g_ymax / 2; dim.x = DEF_GRAPH_X * obj->scale.x; dim.y = DEF_GRAPH_Y * obj->scale.y; /* draw in a box surrounding the plot */ g_change_linestyle(0); g_rectangle(origin.x,origin.y,dim.x,dim.y); /* find the point in data space which will appear at the origin */ xref = the_graph->min_x*DEF_GRAPH_X/(the_graph->max_x-the_graph->min_x); yref = the_graph->min_y*DEF_GRAPH_Y/(the_graph->max_y-the_graph->min_y); /* determine the bounding box for this object */ localmin.x = obj->bmin.x = origin.x; localmin.y = obj->bmin.y = origin.y - dim.y; localmax.x = obj->bmax.x = origin.x + dim.x; localmax.y = obj->bmax.y = origin.y; /****** Instead of tic marks on the X axis, put in vertical lines delineating the symmetry lines ******/ if(the_graph->do_x_tics){ for(i=0;i<the_graph->num_tics_x;i++){ xloc = origin.x + obj->scale.x * i * the_graph->tic_sep_x, g_line(xloc,origin.y+obj->scale.y*TIC_DIM,xloc,origin.y-dim.y); /***** do the label *****/ strcpy(numstring,band_graph->special_points[i].name); yloc = origin.y+obj->scale.y*TIC_DIM; g_center_text(xloc,yloc,numstring); } } /* Y tics */ if( the_graph->do_y_tics ){ max_str_len = 0; for(i=0;i<(int)rint(the_graph->num_tics_y);i++){ yloc = origin.y + obj->scale.y * (yref - the_graph->tic_start_y - i * the_graph->tic_sep_y); g_line(origin.x-obj->scale.x*TIC_DIM,yloc,origin.x,yloc); yval = (the_graph->tic_start_y + i*the_graph->tic_sep_y)*inv_yscale; if( fabs(yval) < 1e-12 ) yval = 0.0; sprintf(numstring,"%lg",yval); xloc = origin.x-obj->scale.x*TIC_DIM-3; g_right_text(xloc,yloc,numstring); } obj->bmin.x -= obj->scale.x*TIC_DIM; } /* put in legends if they are needed */ if( the_graph->xlegend[0] != 0 && the_graph->do_x_tics ){ xloc = origin.x + dim.x/2; yloc = origin.y+obj->scale.y*TIC_DIM*(1.1); g_xlegend(xloc,yloc,the_graph->xlegend); obj->bmax.y += 2.1*PS_options.fontsize; } if( the_graph->ylegend[0] != 0 && the_graph->do_y_tics ){ yloc = origin.y - dim.y/2; xloc = origin.x-obj->scale.x*TIC_DIM*5.0; g_ylegend(xloc,yloc,the_graph->ylegend); obj->bmin.x -= 3.0*PS_options.fontsize; } /* Now do the title */ if( the_graph->title[0] != 0 && the_graph->do_title){ xloc = origin.x + dim.x/2; yloc = origin.y - dim.y; g_title(xloc,yloc,the_graph->title); } /****** put in the fermi level if the user asked for it ******/ if( prim->band_graph->show_fermi ){ if( prim->band_graph->Fermi_E > the_graph->min_y && prim->band_graph->Fermi_E < the_graph->max_y ){ scaled_fermi = prim->band_graph->Fermi_E * yscale; yloc = origin.y + (yref - scaled_fermi)*obj->scale.y; xloc = origin.x; /* use a dashed line */ g_change_linestyle(1); /* draw a line */ g_line(xloc,yloc,xloc+dim.x,yloc); /* set the line style back to the default */ g_change_linestyle(0); } } /* now do the plot itself */ if( the_graph->curves_to_display[0] ){ #ifdef SUPPORT_FATBANDS tot_num_p = the_graph->num_curves*the_graph->num_p; #endif for(i=0;i<the_graph->num_curves;i++){ g_change_linestyle(the_graph->styles[0]); #ifdef SUPPORT_FATBANDS if( prim->band_graph->num_fatbands && prim->band_graph->fatbands_on ){ g_change_linewidth(0.5); for(j=0;j<the_graph->num_p-1;j++){ fat_width1 = the_graph->data[tot_num_p + j*the_graph->num_curves + i].y; fat_width2 = the_graph->data[tot_num_p + (j+1)*the_graph->num_curves + i].y; fat_width1 *= prim->band_graph->fatband_scale/2.0; fat_width2 *= prim->band_graph->fatband_scale/2.0; fb_p1.x = the_graph->data[j*the_graph->num_curves + i].x - xref; fb_p1.y = yref - the_graph->data[j*the_graph->num_curves + i].y; fb_p2.x = the_graph->data[(j+1)*the_graph->num_curves + i].x - xref; fb_p2.y = yref - the_graph->data[(j+1)*the_graph->num_curves + i].y; points[0].x = (int)(origin.x + fb_p1.x*obj->scale.x); points[0].y = (int)(origin.y + (fb_p1.y+fat_width1)*obj->scale.y); points[1].x = (int)(origin.x + fb_p1.x*obj->scale.x); points[1].y = (int)(origin.y + (fb_p1.y - fat_width1)*obj->scale.y); points[2].x = (int)(origin.x + fb_p2.x*obj->scale.x); points[2].y = (int)(origin.y + (fb_p2.y - fat_width2)*obj->scale.y); points[3].x = (int)(origin.x + fb_p2.x*obj->scale.x); points[3].y = (int)(origin.y + (fb_p2.y + fat_width2)*obj->scale.y); points[4].x = points[0].x; points[4].y = points[0].y; switch(prim->band_graph->fatband_fill){ case FATBANDS_SHADE: g_change_color(2); g_filled_polygon(points,4); break; case FATBANDS_LINE: g_change_color(0); g_open_polygon(points,4); break; } } g_change_linewidth(1.0); } g_change_color(0); for(j=0;j<the_graph->num_p;j++){ points[j].x = fpoints[j].x = origin.x + (the_graph->data[j*the_graph->num_curves + i].x - xref)*obj->scale.x; points[j].y = fpoints[j].y = origin.y + (yref - the_graph->data[j*the_graph->num_curves + i].y)*obj->scale.y; } g_lines(points,fpoints,the_graph->num_p,0); g_change_linewidth(1.0); #else for(j=0;j<the_graph->num_p;j++){ points[j].x = fpoints[j].x = origin.x + (the_graph->data[j*the_graph->num_curves + i].x - xref)*obj->scale.x; points[j].y = fpoints[j].y = origin.y + (yref - the_graph->data[j*the_graph->num_curves + i].y)*obj->scale.y; } g_lines(points,fpoints,the_graph->num_p,0); #endif /* set the line style back to the default value */ g_change_linestyle(0); } } }
33.319943
93
0.632148
[ "object" ]
34b60fa8055f1023dabb98e08963d25a401fbebe
9,971
h
C
0.29.0/gnustep-gui-0.29.0/Headers/AppKit/NSOutlineView.h
mlcldh/GNUstepGUI
4f807d6750d7a7a5c3b67c6fe4d742eb2f69c100
[ "MIT" ]
1
2022-01-11T02:45:11.000Z
2022-01-11T02:45:11.000Z
0.29.0/gnustep-gui-0.29.0/Headers/AppKit/NSOutlineView.h
mlcldh/GNUstepGUI
4f807d6750d7a7a5c3b67c6fe4d742eb2f69c100
[ "MIT" ]
null
null
null
0.29.0/gnustep-gui-0.29.0/Headers/AppKit/NSOutlineView.h
mlcldh/GNUstepGUI
4f807d6750d7a7a5c3b67c6fe4d742eb2f69c100
[ "MIT" ]
1
2022-03-20T01:16:47.000Z
2022-03-20T01:16:47.000Z
/* NSOutlineView.h The outline class. Copyright (C) 2001 Free Software Foundation, Inc. Author: Gregory John Casamento <greg_casamento@yahoo.com> Date: October 2001 This file is part of the GNUstep GUI Library. 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 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; see the file COPYING.LIB. If not, see <http://www.gnu.org/licenses/> or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef _GNUstep_H_NSOutlineView #define _GNUstep_H_NSOutlineView #import <GNUstepBase/GSVersionMacros.h> #import <AppKit/NSTableView.h> @class NSMapTable; @class NSMutableArray; @class NSString; @class NSURL; @interface NSOutlineView : NSTableView { NSMapTable *_itemDict; NSMutableArray *_items; NSMutableArray *_expandedItems; NSMutableArray *_selectedItems; /* No longer in use */ NSMapTable *_levelOfItems; BOOL _autoResizesOutlineColumn; BOOL _indentationMarkerFollowsCell; BOOL _autosaveExpandedItems; CGFloat _indentationPerLevel; NSTableColumn *_outlineTableColumn; } // Instance methods - (BOOL) autoResizesOutlineColumn; - (BOOL) autosaveExpandedItems; - (void) collapseItem: (id)item; - (void) collapseItem: (id)item collapseChildren: (BOOL)collapseChildren; - (void) expandItem: (id)item; - (void) expandItem: (id)item expandChildren: (BOOL)expandChildren; #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) - (NSRect) frameOfOutlineCellAtRow: (NSInteger)row; #endif - (BOOL) indentationMarkerFollowsCell; - (CGFloat) indentationPerLevel; - (BOOL) isExpandable: (id)item; - (BOOL) isItemExpanded: (id)item; - (id) itemAtRow: (NSInteger)row; - (NSInteger) levelForItem: (id)item; - (NSInteger) levelForRow: (NSInteger)row; - (NSTableColumn *) outlineTableColumn; #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) - (id) parentForItem: (id)item; #endif - (void) reloadItem: (id)item; - (void) reloadItem: (id)item reloadChildren: (BOOL)reloadChildren; - (NSInteger) rowForItem: (id)item; - (void) setAutoresizesOutlineColumn: (BOOL)resize; - (void) setAutosaveExpandedItems: (BOOL)flag; - (void) setDropItem: (id)item dropChildIndex: (NSInteger)childIndex; - (void) setIndentationMarkerFollowsCell: (BOOL)followsCell; - (void) setIndentationPerLevel: (CGFloat)newIndentLevel; - (void) setOutlineTableColumn: (NSTableColumn *)outlineTableColumn; - (BOOL) shouldCollapseAutoExpandedItemsForDeposited: (BOOL)deposited; @end /* interface of NSOutlineView */ /** * protocol NSOutlineViewDataSource */ @protocol NSOutlineViewDataSource /** * Called to perform drop operation and returns YES if successful, * and NO otherwise. */ - (BOOL) outlineView: (NSOutlineView *)outlineView acceptDrop: (id <NSDraggingInfo>)info item: (id)item childIndex: (NSInteger)index; /** * Implementation of this method is required. Returns the child at * the specified index for the given item. */ - (id) outlineView: (NSOutlineView *)outlineView child: (NSInteger)index ofItem: (id)item; /** * This is a required method. Returns whether or not the outline view * item specified is expandable or not. */ - (BOOL) outlineView: (NSOutlineView *)outlineView isItemExpandable: (id)item; /** * Returns the item for the given persistent object. */ - (id) outlineView: (NSOutlineView *)outlineView itemForPersistentObject: (id)object; /* * This is a required method. Returns the number of children of * the given item. */ - (NSInteger) outlineView: (NSOutlineView *)outlineView numberOfChildrenOfItem: (id)item; /** * This is a required method. Returns the object corresponding to the * item representing it in the outline view. */ - (id) outlineView: (NSOutlineView *)outlineView objectValueForTableColumn: (NSTableColumn *)tableColumn byItem: (id)item; /** * Returns the persistent object for the item specified. */ - (id) outlineView: (NSOutlineView *)outlineView persistentObjectForItem: (id)item; /** * Sets the object value of the given item in the given table column * to the object provided. */ - (void) outlineView: (NSOutlineView *)outlineView setObjectValue: (id)object forTableColumn: (NSTableColumn *)tableColumn byItem: (id)item; /** * Used by the Drag and Drop system. Returns the drag operation which should * be used when -outlineView:acceptDrop:item:childIndex: is called. */ - (NSDragOperation) outlineView: (NSOutlineView*)outlineView validateDrop: (id <NSDraggingInfo>)info proposedItem: (id)item proposedChildIndex: (NSInteger)index; /** * Causes the outline view to write the specified items to the pastboard. */ - (BOOL) outlineView: (NSOutlineView *)outlineView writeItems: (NSArray*)items toPasteboard: (NSPasteboard*)pboard; #if OS_API_VERSION(MAC_OS_X_VERSION_10_3, GS_API_LATEST) - (void) outlineView: (NSOutlineView *)outlineView sortDescriptorsDidChange: (NSArray *)oldSortDescriptors; #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_4, GS_API_LATEST) - (NSArray *) outlineView: (NSOutlineView *)outlineView namesOfPromisedFilesDroppedAtDestination: (NSURL *)dropDestination forDraggedItems: (NSArray *)items; #endif @end /* * Constants */ enum { NSOutlineViewDropOnItemIndex = -1 }; /* * Notifications */ APPKIT_EXPORT NSString *NSOutlineViewColumnDidMoveNotification; APPKIT_EXPORT NSString *NSOutlineViewColumnDidResizeNotification; APPKIT_EXPORT NSString *NSOutlineViewSelectionDidChangeNotification; APPKIT_EXPORT NSString *NSOutlineViewSelectionIsChangingNotification; APPKIT_EXPORT NSString *NSOutlineViewItemDidExpandNotification; APPKIT_EXPORT NSString *NSOutlineViewItemDidCollapseNotification; APPKIT_EXPORT NSString *NSOutlineViewItemWillExpandNotification; APPKIT_EXPORT NSString *NSOutlineViewItemWillCollapseNotification; /* * Methods Implemented by the Delegate */ @protocol NSOutlineViewDelegate // notification methods /** * Called after the column has moved. */ - (void) outlineViewColumnDidMove: (NSNotification *)aNotification; /** * Called after the view column is resized. */ - (void) outlineViewColumnDidResize: (NSNotification *)aNotification; /** * Called after the item has collapsed. */ - (void) outlineViewItemDidCollapse: (NSNotification *)aNotification; /** * Called after the item has expanded */ - (void) outlineViewItemDidExpand: (NSNotification *)aNotification; /** * Called before the item has collapsed. */ - (void) outlineViewItemWillCollapse: (NSNotification *)aNotification; /** * Called before the item is expanded. */ - (void) outlineViewItemWillExpand: (NSNotification *)aNotification; /** * Called when the selection has changed. */ - (void) outlineViewSelectionDidChange: (NSNotification *)aNotification; /** * Called when the selection is about to change. */ - (void) outlineViewSelectionIsChanging: (NSNotification *)aNotification; // delegate methods /** * Returns whether or not the specified item should be allowed to collapse. */ - (BOOL) outlineView: (NSOutlineView *)outlineView shouldCollapseItem: (id)item; /** * Returns whether or not the given table column should be allowed to be edited. */ - (BOOL) outlineView: (NSOutlineView *)outlineView shouldEditTableColumn: (NSTableColumn *)tableColumn item: (id)item; /** * Returns whether or not the specified item should be expanded. */ - (BOOL) outlineView: (NSOutlineView *)outlineView shouldExpandItem: (id)item; /** * Returns YES or NO depending on if the given item is selectable. If YES, the item is selected, * otherwise the outline view will reject the selection. */ - (BOOL) outlineView: (NSOutlineView *)outlineView shouldSelectItem: (id)item; /** * Returns YES or NO depending on if the given table column is selectable according * to the delegate. If NO is returned the outline view will not allow the selection, if YES * it will allow the selection. */ - (BOOL) outlineView: (NSOutlineView *)outlineView shouldSelectTableColumn: (NSTableColumn *)tableColumn; /** * Called when the given cell is about to be displayed. This method is * useful for making last second modifications to what will be shown. */ - (void) outlineView: (NSOutlineView *)outlineView willDisplayCell: (id)cell forTableColumn: (NSTableColumn *)tableColumn item: (id)item; #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) - (NSCell *) outlineView: (NSOutlineView *)outlineView dataCellForTableColumn: (NSTableColumn *)aTableColumn item: (id)item; #endif /** * Called when the given cell in the outline column is about to be displayed. This method is * useful for making last second modifications to what will be shown. */ - (void) outlineView: (NSOutlineView *)outlineView willDisplayOutlineCell: (id)cell forTableColumn: (NSTableColumn *)tableColumn item: (id)item; /** * Called before the selection is modified. This method should return YES if * the selection is allowed and NO, if not. */ - (BOOL) selectionShouldChangeInOutlineView: (NSOutlineView *)outlineView; #if OS_API_VERSION(MAC_OS_X_VERSION_10_3, GS_API_LATEST) - (void) outlineView: (NSOutlineView *)outlineView didClickTableColumn: (NSTableColumn *)aTableColumn; #endif @end #endif /* _GNUstep_H_NSOutlineView */
33.016556
97
0.743255
[ "object" ]
34bf78ebc6a4074c2d34990755b922133dc26b86
3,139
h
C
include/level/lvl_sparkAni.h
DerekSlagle/spiderSolitaire
aa6075a4eca0be14dcb3dd2a807c8c5b29806afb
[ "MIT" ]
null
null
null
include/level/lvl_sparkAni.h
DerekSlagle/spiderSolitaire
aa6075a4eca0be14dcb3dd2a807c8c5b29806afb
[ "MIT" ]
null
null
null
include/level/lvl_sparkAni.h
DerekSlagle/spiderSolitaire
aa6075a4eca0be14dcb3dd2a807c8c5b29806afb
[ "MIT" ]
null
null
null
#ifndef LVL_SPARKANI_H_INCLUDED #define LVL_SPARKANI_H_INCLUDED #include "Level.h" #include "../spark.h" #include "../button_types/buttStrip.h" #include "../controls/sparkEmitterControl.h" #include "../controls/forceControl.h" #include "../controls/printerControl.h" #include "../graphFuncs.h" class lvl_sparkAni : public Level { public: std::vector<sparkAni*> pSpkAniVec; std::vector<sf::Vertex> vtxVec;// test sparkAni::copyToCurve spriteSheet dotSS; sf::Image BkgdImg; sf::Texture BkgdTxt; sf::Sprite BkgdSpr; sparkPrinter spkPrnt; emitter spkEmitter; sf::CircleShape emitMark; sparkEmitterControl emitControl; std::vector<spark> sparkVec; std::vector<spark>::iterator sparkIt; spark* getNextSpark(); void updateSparks( std::vector<spark>& spkVec, bool& anyLive, float dt ); bool anyLive_emit = false; // bool anyLive_print = false; // obstacles std::vector<sf::CircleShape> circleVec; std::vector<sf::Vertex> lineVec; bool LoadBarriers(); float cr = 0.8f;// coeff rest // graphFuncs controls for them graphFuncs gfPoly, gfSine; float Amp_s, wvLen_s; polyNomial poly1; float angFreq_p = 0.01f; graphFuncs gfHyper;// hyperbola float hypA = 1.0f, hypB = 1.0f;// y*y = hypB*x*x + hypA bool topBranch = true; graphFuncs gfFlower; int numPetals = 3; float R_Flwr = 100.0f, Rin_Flwr = 100.0f;//, angFreq_Flwr = 0.0f; graphFuncs gfEllip, gfEllip2; float elip_a = 1.0f, elip_b = 1.0f;// no explicit time variation dydt = 0 float elip_a2 = 1.0f, elip_b2 = 1.0f; float Amp_e2 = 0.0f, angFreq_e2 = 0.0f, pulseTime_e2 = 0.0f;// modulates as Amp_e2*cosf(angFreq_e2*t) graphFuncs gfPolygon; polygonReg pgReg; polygonIrreg pgIrreg; graphFuncs gfPolyIR; // float angFreq_pgn; std::vector<graphFuncs*> pGfVec;// so can process all above in loops sf::Vertex Nline[2];// view normal to gf curve when key N is held bool seeLine = false; // controls for them buttonList hitList;// list std::vector<controlSurface> CsurfVec; std::vector<multiSelector> MsVec; std::vector<buttonValOnHit> VohVec; std::vector<slideBar> SbVec; buttonRect showAxesButt;// toggle drawing of coordinate axis // emit from graphFuncs gfEmitter gfEmit; buttonRect gfEmitButt; buttonValOnHit hitOfstStrip;// vary the offset from curve when hit // vary mass buttStrip massBS; // forces forceControl theFC; printerControl thePrinter; // special functions // buttonRect LoadSparksNowButt; buttonRect fireWorkButt; // firework fireWork fw1, fw2, fw3; sf::Vector2f fwPos1, fwPos2, fwPos3; sf::Vector2f fireOfst; // functions lvl_sparkAni():Level() { std::cout << "Hello from lvl_sparkAni ctor\n"; } virtual bool init(); virtual bool handleEvent( sf::Event& rEvent ); virtual void update( float dt ); virtual void draw( sf::RenderTarget& RT ) const; void dragSparkAnis(); void cleanup(); virtual ~lvl_sparkAni() { cleanup(); } }; #endif // LVL_SPARKANI_H_INCLUDED
27.778761
105
0.677604
[ "vector" ]
34bf7949db336c34a16e256d2b89dd0bbd699392
2,620
h
C
src/devices/machine/ram.h
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/devices/machine/ram.h
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/devices/machine/ram.h
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Nathan Woods, Dirk Best /************************************************************************* RAM device Provides a configurable amount of RAM to drivers **************************************************************************/ #ifndef MAME_MACHINE_RAM_H #define MAME_MACHINE_RAM_H #pragma once #include <memory> #include <utility> #include <vector> /*************************************************************************** CONSTANTS ***************************************************************************/ #define RAM_TAG "ram" /*************************************************************************** TYPE DEFINITIONS ***************************************************************************/ class ram_device : public device_t { public: using extra_option = std::pair<std::string, u32>; using extra_option_vector = std::vector<extra_option>; // construction/destruction ram_device(machine_config const &mconfig, char const *tag, device_t *owner, u32 clock = 0); // accessors u32 size() const { return m_size; } u32 mask() const { return m_size - 1; } u8 *pointer() { return &m_pointer[0]; } char const *default_size_string() const { return m_default_size; }; u32 default_size() const; extra_option_vector const &extra_options() const; // read/write u8 read(offs_t offset) { return m_pointer[offset % m_size]; } void write(offs_t offset, u8 data) { m_pointer[offset % m_size] = data; } // inline configuration helpers ram_device &set_default_size(char const *default_size) { m_default_size = default_size; return *this; } ram_device &set_extra_options(char const *extra_options) { m_extra_options_string = extra_options && extra_options[0] ? extra_options : nullptr; m_extra_options.clear(); return *this; } ram_device &set_default_value(u8 default_value) { m_default_value = default_value; return *this; } protected: virtual void device_start() override; virtual void device_validity_check(validity_checker &valid) const override; private: bool is_valid_size(u32 size) const; // device state u32 m_size; std::unique_ptr<u8 []> m_pointer; // device config char const * m_default_size; u8 m_default_value; mutable extra_option_vector m_extra_options; char const * m_extra_options_string; }; // device type definition DECLARE_DEVICE_TYPE(RAM, ram_device) // device iterator typedef device_type_enumerator<ram_device> ram_device_enumerator; #endif // MAME_MACHINE_RAM_H
29.438202
104
0.591221
[ "vector" ]
34c0b7ff7971905a2952e0b1b62ec24d8b0a371b
596
h
C
Sources/Backend/Operations/UpdatesSearchOperation.h
slavikus/Icy
68bbc38c90c02cb5410bc00bc36e2be26f610190
[ "MIT" ]
8
2016-06-23T14:57:38.000Z
2021-09-21T17:26:57.000Z
Sources/Backend/Operations/UpdatesSearchOperation.h
iMokhles/Icy
a06b21a13d35949d9b32a178e941cde586aa40c2
[ "MIT" ]
null
null
null
Sources/Backend/Operations/UpdatesSearchOperation.h
iMokhles/Icy
a06b21a13d35949d9b32a178e941cde586aa40c2
[ "MIT" ]
7
2016-06-23T03:36:51.000Z
2021-12-04T09:21:02.000Z
// // UpdatesSearchOperation.h // Icy // // Created by Slava Karpenko on 3/23/09. // Copyright 2009 Ripdev. All rights reserved. // #import <Foundation/Foundation.h> // Notification name being posted on the main thread... [notification object] will contain the updates array #define kIcyUpdatedPackagesUpdatedNotification @"com.ripdev.icy.updated-updated" @class Database; @interface UpdatesSearchOperation : NSOperation { Database* mDB; } - (void)_checkUpdate:(NSDictionary*)pack withArray:(NSMutableArray*)updatedPackages; - (NSDictionary*)_findPackage:(NSString*)packageID; @end
24.833333
108
0.761745
[ "object" ]
34cb31a4aa50bf1e9acb455c626f4fc9fa9c35ce
17,733
h
C
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/common/matrix.h
txlos/wpf
4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1
[ "MIT" ]
5,937
2018-12-04T16:32:50.000Z
2022-03-31T09:48:37.000Z
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/common/matrix.h
txlos/wpf
4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1
[ "MIT" ]
4,151
2018-12-04T16:38:19.000Z
2022-03-31T18:41:14.000Z
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/common/matrix.h
txlos/wpf
4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1
[ "MIT" ]
1,084
2018-12-04T16:24:21.000Z
2022-03-30T13:52:03.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //+----------------------------------------------------------------------- // // // Description: // Definition of the matrix transform class used by the MIL. // This class derives from CBaseMatrix which derives from D3DMATRIX, and // adds no additional data to the memory footprint. This is done to // maximize interchangeability between matrix classes and minimize // overhead. // //------------------------------------------------------------------------ #pragma once MtExtern(CMatrix); //+---------------------------------------------------------------------------- // // Class: // CMatrix<InCoordSpace, OutCoordSpace> // // Synopsis: // Extends CBaseMatrix class with coordinate space type safety and // coordinate space transform related operations. // //----------------------------------------------------------------------------- template <typename InCoordSpace, typename OutCoordSpace> class CMatrix : public CBaseMatrix { // No extra data members, including vtables, should ever be added to CMatrix void _CAssertSize_() { C_ASSERT(sizeof(CMatrix) == sizeof(CBaseMatrix)); } public: DECLARE_METERHEAP_ALLOC(ProcessHeap, Mt(CMatrix)); // CMILMatrix constructors that expose CBaseMatrix constructors CMatrix(bool fInitialize) : CBaseMatrix(fInitialize) {} CMatrix(__in_ecount(1) MilMatrix3x2D const *pMatrix) : CBaseMatrix(pMatrix) {} CMatrix(__in_ecount(16) const float * pf) : CBaseMatrix(pf) {} CMatrix(__in_ecount(1) const CMatrix& m) : CBaseMatrix(m) { } CMatrix(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33) : CBaseMatrix( m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { } template<typename... Args> inline CMatrix(Args&&...args) : CBaseMatrix(std::forward<Args>(args)...) { // empty } //+------------------------------------------------------------------------ // // Member: // refIdentity / pIdentity // // Synopsis: // Convenience methods to get a space specific identity matrix to // transform from one space to another // // Notes: // Use should be limited as usage normally indicates preprocessing of // coordinate space and treating the results as it they were not // preprocessed and only transforming them later by this identity // transform. // //------------------------------------------------------------------------- static __returnro CMatrix const &refIdentity() { return ReinterpretBase(IdentityMatrix); } static __returnro CMatrix const *pIdentity() { return ReinterpretBase(&IdentityMatrix); } //+------------------------------------------------------------------------ // // Member: // InferAffineMatrix // // Synopsis: // Set transform value to the transform needed to convert from InSpace // rectangle to OutSpace parallelogram. OutSpace parallelogram is // specified either and 3 points or a rectangle. // //------------------------------------------------------------------------- void InferAffineMatrix( __in_ecount(1) const CRectF<InCoordSpace> &rcInSpace, __in_ecount(3) const MilPoint2F *rgptOutSpace ) { CBaseMatrix::InferAffineMatrix(rcInSpace, rgptOutSpace); } void InferAffineMatrix( __in_ecount(1) const CRectF<InCoordSpace> &rcInSpace, __in_ecount(1) const CRectF<OutCoordSpace> &rcOutSpace ) { CBaseMatrix::InferAffineMatrix(rcInSpace, rcOutSpace); } //+------------------------------------------------------------------------ // // Member: // Transform2DBounds* // // Synopsis: // Convert a bounding rectangle from one coordinate space to another // always expanding bounds to ensure any point within InSpace bounds // transformed to Out space will fall within output OutSpace bounds. // // Transform2DBounds is common implementation and does not check for // NaN results. It produces NaN results somewhat erratically. See // CBaseMatrix::Transform2DBounds implementation notes. // // Transform2DBoundsConservative watches for NaN results and produces // infinite bounds. See CBaseMatrix::Transform2DBoundsConservative // implementation notes. // // Transform2DBoundsNullSafe checks for a NULL matrix (this) and // simply copies result assuming NULL implies identity transform. // //------------------------------------------------------------------------- void Transform2DBounds( __in_ecount(1) const CRectF<InCoordSpace> &rcInSpace, __out_ecount(1) CRectF<OutCoordSpace> &rcOutSpace ) const { CBaseMatrix::Transform2DBounds(rcInSpace, rcOutSpace); } void Transform2DBoundsConservative( __in_ecount(1) const CRectF<InCoordSpace> &rcInSpace, __out_ecount(1) CRectF<OutCoordSpace> &rcOutSpace ) const { CBaseMatrix::Transform2DBoundsConservative(rcInSpace, rcOutSpace); } static void Transform2DBoundsNullSafe( __in_ecount_opt(1) const CMatrix *matrix, __in_ecount(1) const CRectF<InCoordSpace> &rcInSpace, __out_ecount(1) CRectF<OutCoordSpace> &rcOutSpace ) { CBaseMatrix::Transform2DBoundsNullSafe(matrix, rcInSpace, rcOutSpace); } void Transform2DBoundsNullSafe( __in_ecount(1) const CRectF<InCoordSpace> &rcInSpace, __out_ecount(1) CRectF<OutCoordSpace> &rcOutSpace ) const { CBaseMatrix::Transform2DBoundsNullSafe(this, rcInSpace, rcOutSpace); } //+------------------------------------------------------------------------ // // Member: // SetToMultiplyResult // // Synopsis: // Set transform value to the multiplied result of m1 and m2. // //------------------------------------------------------------------------- template <typename CommonCoordSpace> VOID SetToMultiplyResult( __in_ecount(1) const CMatrix<InCoordSpace,CommonCoordSpace> &m1, __in_ecount(1) const CMatrix<CommonCoordSpace,OutCoordSpace> &m2 ) { CBaseMatrix::SetToMultiplyResult(m1, m2); } //+------------------------------------------------------------------------ // // Member: // Invert // // Synopsis: // Set transform value to the inversion of "in". // //------------------------------------------------------------------------- BOOL Invert( __in_ecount(1) const CMatrix<OutCoordSpace,InCoordSpace> &in ) { return CBaseMatrix::Invert(in); } //+------------------------------------------------------------------------ // // Member: // ComputePrefilteringDimensions // // Synopsis: // Given a realization of a certain size, estimate an intermediate // size to which the realization could be prefiltered to provide high // quality sampling with a 2x2 linear reconstruction filter. // //------------------------------------------------------------------------- VOID ComputePrefilteringDimensions( __range(>=, 1) UINT uRealizationWidth, __range(>=, 1) UINT uRealizationHeight, REAL rShrinkFactorThreshold, __deref_out_range(>=, 1) UINT &uDesiredWidth, __deref_out_range(>=, 1) UINT &uDesiredHeight ) const { { C_ASSERT(InCoordSpace::Id == CoordinateSpaceId::RealizationSampling); } { C_ASSERT( (OutCoordSpace::Id == CoordinateSpaceId::Device) || (OutCoordSpace::Id == CoordinateSpaceId::IdealSampling)); } CBaseMatrix::ComputePrefilteringDimensions( uRealizationWidth, uRealizationHeight, rShrinkFactorThreshold, uDesiredWidth, uDesiredHeight ); } //+------------------------------------------------------------------------ // // Member: // AdjustForPrefiltering // // Synopsis: // Given a realization of a certain size, estimate an intermediate // size to which the realization could be prefiltered to provide high // quality sampling with a 2x2 linear reconstruction filter. // // Then remove the corresponding scale factor from this transform if and only if: // (*puDesiredWidth != uBitmapWidth) || (*puDesiredHeight != uBitmapHeight) // //------------------------------------------------------------------------- VOID AdjustForPrefiltering( __range(>=, 1) UINT uRealizationWidth, __range(>=, 1) UINT uRealizationHeight, REAL rShrinkFactorThreshold, __deref_out_range(>=, 1) UINT *puDesiredWidth, __deref_out_range(>=, 1) UINT *puDesiredHeight ) { { C_ASSERT(InCoordSpace::Id == CoordinateSpaceId::RealizationSampling); } { C_ASSERT( (OutCoordSpace::Id == CoordinateSpaceId::Device) || (OutCoordSpace::Id == CoordinateSpaceId::IdealSampling)); } CBaseMatrix::AdjustForPrefiltering( uRealizationWidth, uRealizationHeight, rShrinkFactorThreshold, puDesiredWidth, puDesiredHeight); } //========================================================================= // Casting Helper Routines // //+------------------------------------------------------------------------ // // Member: // ReinterpretAsVariantOut // // Synopsis: // Reinterpret this transform as having Variant Out coordinate space. // Use should be limited. // //------------------------------------------------------------------------- __ecount(1) CMatrix<InCoordSpace,CoordinateSpace::Variant> const &ReinterpretAsVariantOut( ) const { C_ASSERT(OutCoordSpace::Id != CoordinateSpaceId::Invalid); C_ASSERT(sizeof(*this) == sizeof(CMatrix<InCoordSpace,CoordinateSpace::Variant>)); return reinterpret_cast<CMatrix<InCoordSpace,CoordinateSpace::Variant> const &>(*this); } //+------------------------------------------------------------------------ // // Member: // ReinterpretBase // // Synopsis: // Casting helpers to reinterpret base type as space specific type, // which is safe because all data members should be the same // // Notes: // These members should not be used to reinterpret one coordinate // space transform to another. See Reinterpret*Space1*As*Space2* // methods below for such reinterpretation needs. // //------------------------------------------------------------------------- static __returnro CMatrix const &ReinterpretBase( __in_ecount(1) CBaseMatrix const &m ) { return static_cast<CMatrix const &>(m); } static __returnro CMatrix const *ReinterpretBase( __in_ecount(1) CBaseMatrix const *pm ) { return static_cast<CMatrix const *>(pm); } static __ecount(1) CMatrix *ReinterpretBaseForModification( __in_ecount(1) CBaseMatrix *pm ) { return static_cast<CMatrix *>(pm); } }; // Explicit instantiation of at least one type to trigger compile errors early typedef CMatrix<CoordinateSpace::TextureSampling, CoordinateSpace::IdealSampling> CMatrixTextureSamplingToIdealSampling; //+---------------------------------------------------------------------------- // // Function: // Reinterpret*Space1*As*Space2* // // Synopsis: // Helper methods to reinterpret one coordinate space as another // coordinate space. Use of helpers are preferred over direct // reinterpret_cast, becacuse reinterpret_cast is dangerous and at least // here sizes can be asserted. // //----------------------------------------------------------------------------- //+---------------------------------------------------------------------------- // // Function: // ReinterpretLocalRenderingAsBaseSampling // // Synopsis: // Helper method to reinterpret LocalRendering coordinate space as // BaseSampling coordinate space. This is a common operation for 2D // rendering primitives. // //----------------------------------------------------------------------------- MIL_FORCEINLINE __returnro const CMatrix<CoordinateSpace::BaseSampling,CoordinateSpace::Device> & ReinterpretLocalRenderingAsBaseSampling( __in_ecount(1) const CMatrix<CoordinateSpace::LocalRendering,CoordinateSpace::Device> &m ) { C_ASSERT(sizeof(m) == sizeof( CMatrix<CoordinateSpace::BaseSampling,CoordinateSpace::Device> )); return reinterpret_cast<const CMatrix<CoordinateSpace::BaseSampling,CoordinateSpace::Device> &>(m); } //+---------------------------------------------------------------------------- // // Function: // ReinterpretIdealSamplingAsDevice // // Synopsis: // Helper method to reinterpret IdealSampling coordinate space as Device // coordinate space. IdealSampling is the coordinate space used when // Device space is desired, but only an approximation can be made. This // happens when rendering primitive does not provide a direct mapping from // source to target, i.e. mesh primitives. At some point we don't care to // carry the differentiation any further and use this method to // reinterpret IdealSampling as Device. // //----------------------------------------------------------------------------- MIL_FORCEINLINE __returnro const CMatrix<CoordinateSpace::BaseSampling,CoordinateSpace::Device> & ReinterpretIdealSamplingAsDevice( __in_ecount(1) const CMatrix<CoordinateSpace::BaseSampling,CoordinateSpace::IdealSampling> &m ) { C_ASSERT(sizeof(m) == sizeof( CMatrix<CoordinateSpace::BaseSampling,CoordinateSpace::Device> )); return reinterpret_cast<const CMatrix<CoordinateSpace::BaseSampling,CoordinateSpace::Device> &>(m); } //+---------------------------------------------------------------------------- // // Function: // ReinterpretLocalRenderingAsRealizationSampling // // Synopsis: // Helper method to reinterpret LocalRendering coordinate space as // RealizationSampling coordinate space. Quite similar to reinterpreting // LocalRendering as BaseSampling, but for case of DrawBitmap when source // based coordinates are used. // //----------------------------------------------------------------------------- MIL_FORCEINLINE __returnro const CMatrix<CoordinateSpace::RealizationSampling,CoordinateSpace::Device> & ReinterpretLocalRenderingAsRealizationSampling( __in_ecount(1) const CMatrix<CoordinateSpace::LocalRendering,CoordinateSpace::Device> &m ) { C_ASSERT(sizeof(m) == sizeof( CMatrix<CoordinateSpace::RealizationSampling,CoordinateSpace::Device> )); return reinterpret_cast<const CMatrix<CoordinateSpace::RealizationSampling,CoordinateSpace::Device> &>(m); } //+---------------------------------------------------------------------------- // // Function: // ReinterpretPageInPixelsAsLocalRendering // // Synopsis: // Helper method to reinterpret PageInPixels coordinate space as // LocalRendering coordinate space. Useful when LocalRendering (Shape) // has been flattened to PageInPixels and LocalToPageInPixel transform is // then set to Identity, but source (brush) transform must respect the // true LocalRenderingToPageInPixels transform. // //----------------------------------------------------------------------------- MIL_FORCEINLINE __returnro const CMatrix<CoordinateSpace::BaseSampling,CoordinateSpace::LocalRendering> & ReinterpretPageInPixelsAsLocalRendering( __in_ecount(1) const CMatrix<CoordinateSpace::BaseSampling,CoordinateSpace::PageInPixels> &m ) { C_ASSERT(sizeof(m) == sizeof( CMatrix<CoordinateSpace::BaseSampling,CoordinateSpace::LocalRendering> )); return reinterpret_cast<const CMatrix<CoordinateSpace::BaseSampling,CoordinateSpace::LocalRendering> &>(m); } //+---------------------------------------------------------------------------- // // Function: // ReinterpretLocalRenderingAsMILMatrix // // Synopsis: // Helper method to reinterpret PageInPixels coordinate space as // LocalRendering coordinate space. Useful when LocalRendering (Shape) // has been flattened to PageInPixels and LocalToPageInPixel transform is // then set to Identity, but source (brush) transform must respect the // true LocalRenderingToPageInPixels transform. See // CDrawingContext::DrawVisualTree. // //----------------------------------------------------------------------------- MIL_FORCEINLINE __returnro const CMILMatrix * ReinterpretLocalRenderingAsMILMatrix( __in_ecount(1) const CMatrix<CoordinateSpace::LocalRendering,CoordinateSpace::PageInPixels> *m ) { C_ASSERT(sizeof(*m) == sizeof( CMILMatrix )); return reinterpret_cast<const CMILMatrix *>(m); }
36.487654
120
0.567811
[ "mesh", "shape", "transform" ]
34e441bfd83c35c1f8f9dd078d4c6f69db6e8294
771
h
C
flower_equals_win/logic/Grid.h
Garoli/flower-equals-win-game
c6965b9dfa38de124e3e8991a0d92509a54365df
[ "Unlicense", "MIT" ]
null
null
null
flower_equals_win/logic/Grid.h
Garoli/flower-equals-win-game
c6965b9dfa38de124e3e8991a0d92509a54365df
[ "Unlicense", "MIT" ]
null
null
null
flower_equals_win/logic/Grid.h
Garoli/flower-equals-win-game
c6965b9dfa38de124e3e8991a0d92509a54365df
[ "Unlicense", "MIT" ]
null
null
null
#ifndef GRID_H #define GRID_H #include <string> #include <vector> #include "Cell.h" #include "Direction.h" class Grid { public: explicit Grid(const std::string &); void display() const; Cell * getCell(int, int) const; bool isCoordinateValid(int, int) const; std::vector<Cell *> getNeighbors(Cell *) const; static void moveTo(Cell *, Cell *); void move(Cell *, Direction); void moveBee(Direction); bool canMove(Cell *, Direction) const; void removeAllWall(); Cell * getCell(Container *); Cell *** getDatas() const; int getColumnSize() const; int getRowSize() const; bool canPushBlock(int, int, Direction) const; bool isOver(Direction) const; private: int columnSize; int rowSize; Cell *** datas; Cell * beeCell; }; #endif // GRID_H
24.09375
49
0.690013
[ "vector" ]
34e4eaad5e17ed16ee1daaa67b47146e04cb9a41
3,996
h
C
include/photesthesis/util.h
graydon/photesthesis
7d33b421a08e09455a6d4eed6ddb879d94f15b2e
[ "Apache-2.0" ]
11
2021-02-13T09:06:13.000Z
2021-04-15T17:30:57.000Z
include/photesthesis/util.h
graydon/photesthesis
7d33b421a08e09455a6d4eed6ddb879d94f15b2e
[ "Apache-2.0" ]
12
2021-02-22T22:40:35.000Z
2021-06-01T22:41:03.000Z
include/photesthesis/util.h
graydon/photesthesis
7d33b421a08e09455a6d4eed6ddb879d94f15b2e
[ "Apache-2.0" ]
1
2021-02-18T16:04:05.000Z
2021-02-18T16:04:05.000Z
#pragma once // Copyright 2021 Stellar Development Foundation and contributors. Licensed // under the Apache License, Version 2.0. See the COPYING file at the root // of this distribution or at http://www.apache.org/licenses/LICENSE-2.0 #include <map> #include <photesthesis/3rdparty/xxhash64.h> #include <photesthesis/symbol.h> #include <photesthesis/value.h> #include <random> #include <sstream> #include <stdexcept> #include <vector> namespace photesthesis { inline void addStringToHash(XXHash64& h, std::string const& s) { h.add(s.c_str(), s.size()); } inline void addValueToHash(XXHash64& h, Value v) { std::ostringstream oss; oss << v; addStringToHash(h, oss.str()); } inline void addSymbolToHash(XXHash64& h, Symbol s) { addStringToHash(h, s.getString()); } inline void addKeyValueToHash(XXHash64& h, Symbol k, Value v) { addSymbolToHash(h, k); addStringToHash(h, "="); addValueToHash(h, v); } inline Symbol headSymbol(Value v) { Symbol sym(""); Value rest; if (v.match(sym, rest)) { return sym; } throw std::runtime_error("expected head symbol in list"); } inline Symbol headSymbol(std::shared_ptr<const PairValue> pv) { Symbol sym(""); Value rest; if (pv->match(sym, rest)) { return sym; } throw std::runtime_error("expected head symbol in list"); } template <typename T> T const& pickUniform(std::default_random_engine& gen, std::vector<T> const& elts) { if (elts.empty()) { throw std::runtime_error("pick_uniform on empty vector"); } std::uniform_int_distribution<size_t> dist(0, elts.size() - 1); return elts.at(dist(gen)); } template <typename K, typename V> std::pair<const K, V> const& pickUniform(std::default_random_engine& gen, std::map<K, V> const& elts) { if (elts.empty()) { throw std::runtime_error("pick_uniform on empty map"); } std::uniform_int_distribution<size_t> dist(0, elts.size() - 1); auto i = elts.cbegin(); std::advance(i, dist(gen)); return *i; } template <typename T> void expectVal(std::istream& is, T const& expected, T const& got) { if (expected != got) { throw std::runtime_error( std::string("input failure at offset ") + std::to_string(is.tellg()) + std::string(": expected '") + std::to_string(expected) + std::string("' but got '") + std::to_string(got) + std::string("'")); } } inline void expectStr(std::istream& is, std::string const& expected, std::string const& got) { if (expected != got) { throw std::runtime_error( std::string("input failure at offset ") + std::to_string(is.tellg()) + std::string(": expected '") + expected + std::string("' but got '") + got + std::string("'")); } } inline void expectNonemptyStr(std::istream& is, std::string const& s) { if (s.empty()) { throw std::runtime_error( std::string("input read unexpected empty string at offset ") + std::to_string(is.tellg())); } } inline void scanWhitespace(std::istream& is) { while (is.good() && std::isspace(is.peek())) { char c; is.get(c); } } template <typename K, typename V> bool vecMapHas(std::vector<std::pair<K, V>> const& map, K const& k) { for (auto const& pair : map) { if (pair.first == k) { return true; } } return false; } template <typename K, typename V> V const& vecMapGet(std::vector<std::pair<K, V>> const& map, K const& k) { for (auto const& pair : map) { if (pair.first == k) { return pair.second; } } throw std::runtime_error(std::string("unknown param: ") + k.getString()); } template <typename K, typename V> void vecMapAdd(std::vector<std::pair<K, V>>& map, K const& k, V const& v) { assert(!vecMapHas(map, k)); map.emplace_back(k, v); } } // namespace photesthesis
22.2
80
0.612613
[ "vector" ]
42be79ddbda4dc91b543536666755052bb39d7b0
4,316
h
C
derecho/subgroup_info.h
scottslewis/derecho-unified
cc2e23547b09386d18cb01de9221035e5fa70006
[ "BSD-3-Clause" ]
null
null
null
derecho/subgroup_info.h
scottslewis/derecho-unified
cc2e23547b09386d18cb01de9221035e5fa70006
[ "BSD-3-Clause" ]
null
null
null
derecho/subgroup_info.h
scottslewis/derecho-unified
cc2e23547b09386d18cb01de9221035e5fa70006
[ "BSD-3-Clause" ]
1
2018-10-26T09:02:47.000Z
2018-10-26T09:02:47.000Z
/** * @file subgroup_info.h * * @date Feb 17, 2017 */ #pragma once #include <cstdint> #include <functional> #include <list> #include <map> #include <memory> #include <typeindex> #include <vector> #include "derecho_exception.h" namespace derecho { class View; class SubView; /** * An exception that indicates that a subgroup membership function was unable * to finish executing because its enclosing Group was not in a valid state. * Usually this means that the Group did not have enough members to completely * provision the subgroup, or specific nodes that the subgroup needed were not * available. */ class subgroup_provisioning_exception : public derecho_exception { public: subgroup_provisioning_exception(const std::string& message = "") : derecho_exception(message) {} }; /** The type to use in the SubgroupInfo maps for a subgroup * that doesn't implement a Replicated Object */ struct RawObject {}; /** * The data structure used to store a subgroups-and-shards layout for a single * subgroup type (i.e. Replicated Object type). The outer vector represents * subgroups of the same type, and the inner vector represents shards of each * subgroup, so the vectors map subgroup index -> shard index -> sub-view of * that shard. */ using subgroup_shard_layout_t = std::vector<std::vector<SubView>>; /** The type of a lambda function that generates subgroup and shard views * for a specific subgroup type. This is a function that takes the current View * as input and outputs a vector-of-vectors representing subgroups and shards. */ using shard_view_generator_t = std::function<subgroup_shard_layout_t(const View&, int&, bool)>; /** * Container for whatever information is needed to describe a Group's subgroups * and shards. */ struct SubgroupInfo { /** * A map of functions that generate SubViews for each subgroup and shard * of a given type, indexed by the type of Replicated Object whose subgroups * they describe. */ const std::map<std::type_index, shard_view_generator_t> subgroup_membership_functions; /** * This list should contain the same Replicated Object types as the keys of * subgroup_membership_functions, listed in the order those membership * functions should be executed. This can be used to specify dependencies between * membership functions: if one membership function depends on knowing the * result of another membership function, they can be ordered so the * dependent function runs second. */ const std::list<std::type_index> membership_function_order; SubgroupInfo(std::map<std::type_index, shard_view_generator_t> subgroup_membership_functions, std::list<std::type_index> membership_function_order) : subgroup_membership_functions(subgroup_membership_functions), membership_function_order(membership_function_order) { } SubgroupInfo(std::map<std::type_index, shard_view_generator_t> subgroup_membership_functions) : subgroup_membership_functions(subgroup_membership_functions), membership_function_order([subgroup_membership_functions]() { std::list<std::type_index> membership_function_order; // if no ordering is given, choose the ordering as given by the keys of the subgroup_membership functions map for(const auto& p : subgroup_membership_functions) { membership_function_order.push_back(p.first); } return membership_function_order; }()) { } }; /** * Constructs a std::list of the keys in a std::map, in the same order as they * appear in the std::map. This is a general-purpose function that could have * many uses, but it's included here because it is helpful in constructing * membership_function_order when there are no dependencies between functions * (thus, they should just run in the order of their appearance in the map). * @param map A std::map * @return A std::list containing a copy of each key in the map, in the same order */ template <typename K, typename V> std::list<K> keys_as_list(const std::map<K, V>& map) { std::list<K> keys; for(const auto& pair : map) { keys.emplace_back(pair.first); } return keys; } }
38.882883
127
0.718258
[ "object", "vector" ]
42c2db7f9db3206e50e42c225297774970650481
19,813
h
C
platform/micrium_os/fs/source/shared/crc/edc_crc.h
lmnotran/gecko_sdk
2e82050dc8823c9fe0e8908c1b2666fb83056230
[ "Zlib" ]
82
2016-06-29T17:24:43.000Z
2021-04-16T06:49:17.000Z
platform/micrium_os/fs/source/shared/crc/edc_crc.h
GoldSora/sdk_support
5f92c311a302e2ba06040ec37f8ac4eba91b3d5d
[ "Zlib" ]
7
2020-08-25T02:41:16.000Z
2022-03-21T19:55:46.000Z
platform/micrium_os/fs/source/shared/crc/edc_crc.h
GoldSora/sdk_support
5f92c311a302e2ba06040ec37f8ac4eba91b3d5d
[ "Zlib" ]
56
2016-08-02T10:50:50.000Z
2021-07-19T08:57:34.000Z
/***************************************************************************//** * @file * @brief File System - Cyclic Redundancy Check (Crc) Calculation ******************************************************************************* * # License * <b>Copyright 2018 Silicon Laboratories Inc. www.silabs.com</b> ******************************************************************************* * * The licensor of this software is Silicon Laboratories Inc. Your use of this * software is governed by the terms of Silicon Labs Master Software License * Agreement (MSLA) available at * www.silabs.com/about-us/legal/master-software-license-agreement. * The software is governed by the sections of the MSLA applicable to Micrium * Software. * ******************************************************************************/ /******************************************************************************************************** ******************************************************************************************************** * MODULE ******************************************************************************************************** *******************************************************************************************************/ #ifndef EDC_CRC_H_ #define EDC_CRC_H_ /******************************************************************************************************** ******************************************************************************************************** * INCLUDE FILES ******************************************************************************************************** *******************************************************************************************************/ #include <cpu/include/cpu.h> #include <common/include/rtos_path.h> #include <fs_storage_cfg.h> /******************************************************************************************************** ******************************************************************************************************** * DEFINES ******************************************************************************************************** *******************************************************************************************************/ #define FS_STORAGE_CFG_CRC16_1021_EN DEF_ENABLED #define FS_STORAGE_CFG_CRC16_8005_EN DEF_DISABLED #define FS_STORAGE_CFG_CRC16_8048_EN DEF_DISABLED #define FS_STORAGE_CFG_CRC32_EN DEF_DISABLED #define FS_STORAGE_CFG_CRC16_1021_REF_EN DEF_DISABLED #define FS_STORAGE_CFG_CRC16_8005_REF_EN DEF_DISABLED #define FS_STORAGE_CFG_CRC16_8048_REF_EN DEF_DISABLED #define FS_STORAGE_CFG_CRC32_REF_EN DEF_DISABLED /******************************************************************************************************** ******************************************************************************************************** * DATA TYPES ******************************************************************************************************** *******************************************************************************************************/ typedef struct crc_model_16 { CPU_INT16U Poly; CPU_INT16U InitVal; CPU_BOOLEAN Reflect; CPU_INT16U XorOut; const CPU_INT16U *TblPtr; } CRC_MODEL_16; typedef struct crc_model_32 { CPU_INT32U Poly; CPU_INT32U InitVal; CPU_BOOLEAN Reflect; CPU_INT32U XorOut; const CPU_INT32U *TblPtr; } CRC_MODEL_32; typedef struct crc_calc_16 { CRC_MODEL_16 Model; CPU_INT16U CRC_Curr; } CRC_CALC_16; typedef struct crc_calc_32 { CRC_MODEL_32 Model; CPU_INT32U CRC_Curr; } CRC_CALC_32; /******************************************************************************************************** * GLOBAL VARIABLES * * Note(s) : (1) Constant tables for several common CRCs are supplied. Unfortunately, there often exists * no definitive specification of these CRCs or such specification is difficult to obtain. * Consequently, the most convenient method for determining the necessary CRC is accomplished * by comparing CRCs from real tests with CRCs from example tests. CRC outputs for the input * ASCII string "123456789" are given in this table : * * ------------------------------------------------------------------ * | POLY | REFLECT? | INIT VAL | COMP. OUT? | CRC | * -------------+------------+------------+------------+------------- * | 0x1021 | NO | 0x0000 | NO | 0x31C3 | * | 0x1021 | NO | 0x0000 | YES | 0xCE3C | * | 0x1021 | NO | 0x1D0F | NO | 0xE5CC | * | 0x1021 | NO | 0xFFFF | NO | 0x29B1 | * | 0x1021 | NO | 0xFFFF | YES | 0xD64E | * -------------+------------+------------+------------+------------- * | 0x1021 | YES | 0x0000 | NO | 0x2189 | * | 0x1021 | YES | 0x0000 | YES | 0xDE76 | * | 0x1021 | YES | 0xFFFF | NO | 0x6F91 | * | 0x1021 | YES | 0xFFFF | YES | 0x906E | * -------------+------------+------------+------------+------------- * | 0x8005 | NO | 0x0000 | NO | 0xFEE8 | * | 0x8005 | NO | 0x0000 | YES | 0x0117 | * | 0x8005 | NO | 0xFFFF | NO | 0xAEE7 | * | 0x8005 | NO | 0xFFFF | YES | 0x5118 | * -------------+------------+------------+------------+------------- * | 0x8005 | YES | 0x0000 | NO | 0xBB3D | * | 0x8005 | YES | 0x0000 | YES | 0x44C2 | * | 0x8005 | YES | 0xFFFF | NO | 0x4B37 | * | 0x8005 | YES | 0xFFFF | YES | 0xB4C8 | * -------------+------------+------------+------------+------------- * | 0x8048 | NO | 0x0000 | NO | 0x80A0 | * | 0x8048 | NO | 0x0000 | YES | 0x7F5F | * | 0x8048 | NO | 0xFFFF | NO | 0xE8E0 | * | 0x8048 | NO | 0xFFFF | YES | 0x171F | * -------------+------------+------------+------------+------------- * | 0x8048 | YES | 0x0000 | NO | 0x1506 | * | 0x8048 | YES | 0x0000 | YES | 0xEAF9 | * | 0x8048 | YES | 0xFFFF | NO | 0x1710 | * | 0x8048 | YES | 0xFFFF | YES | 0xE8EF | * -------------+------------+------------+------------+------------- * | 0x04C11DB7 | NO | 0x00000000 | NO | 0x89A1897F | * | 0x04C11DB7 | NO | 0x00000000 | YES | 0x765E7680 | * | 0x04C11DB7 | NO | 0xFFFFFFFF | NO | 0x0376E6E7 | * | 0x04C11DB7 | NO | 0xFFFFFFFF | YES | 0xFC891918 | * -------------+------------+------------+------------+------------- * | 0x04C11DB7 | YES | 0x00000000 | NO | 0x2DFD2D88 | * | 0x04C11DB7 | YES | 0x00000000 | YES | 0xD202D277 | * | 0x04C11DB7 | YES | 0xFFFFFFFF | NO | 0x340BC6D9 | * | 0x04C11DB7 | YES | 0xFFFFFFFF | YES | 0xCBF43926 | * -------------+------------+------------+------------+------------- * * (a) The column 'COMP. OUT?' (short for 'COMPLEMENT OUTPUT?') indicates whether the output * XOR value would be either 0xFFFF (for a CRC16) or 0xFFFFFFFF (for a CRC32). * * (1) If YES, this means that the CRC model struct ('CRC_MODEL_16' or 'CRC_MODEL_32') * should have a 'XorOut' member equal to 0xFFFF or 0xFFFFFFFF, respectively. * * (2) If NO, this means that the CRC model struct ('CRC_MODEL_16' or 'CRC_MODEL_32') * should have a 'XorOut' member equal to 0x0000 or 0x00000000, respectively. * * (b) The column 'REFLECT?' indicates that BOTH the input data & final output value * would be reflected. * * (1) If YES, this means that the CRC model struct ('CRC_MODEL_16' or 'CRC_MODEL_32') * should have a 'Reflect' member equal to DEF_YES. * * (2) If NO, this means that the CRC model struct ('CRC_MODEL_16' or 'CRC_MODEL_32') * should have a 'Reflect' member equal to DEF_NO. * * (2) The constant tables depend ONLY on the polynomial & whether the data is reflected. * The additional model parameters, such as the initial value & the XOR for the output, * do not matter. Consequently, the provided tables may be used with user-defined models * that differ only in initial value &/or XOR for the output with the models provided * here. *******************************************************************************************************/ #if (FS_STORAGE_CFG_CRC16_1021_EN == DEF_ENABLED) extern const CPU_INT16U CRC_TblCRC16_1021[256]; extern const CRC_MODEL_16 CRC_ModelCRC16_1021; #endif #if (FS_STORAGE_CFG_CRC16_1021_REF_EN == DEF_ENABLED) extern const CPU_INT16U CRC_TblCRC16_1021_ref[256]; extern const CRC_MODEL_16 CRC_ModelCRC16_1021_ref; #endif #if (FS_STORAGE_CFG_CRC16_8005_EN == DEF_ENABLED) extern const CPU_INT16U CRC_TblCRC16_8005[256]; extern const CRC_MODEL_16 CRC_ModelCRC16_8005; #endif #if (FS_STORAGE_CFG_CRC16_8005_REF_EN == DEF_ENABLED) extern const CPU_INT16U CRC_TblCRC16_8005_ref[256]; extern const CRC_MODEL_16 CRC_ModelCRC16_8005_ref; #endif #if (FS_STORAGE_CFG_CRC16_8048_EN == DEF_ENABLED) extern const CPU_INT16U CRC_TblCRC16_8048[256]; extern const CRC_MODEL_16 CRC_ModelCRC16_8048; #endif #if (FS_STORAGE_CFG_CRC16_8048_REF_EN == DEF_ENABLED) extern const CPU_INT16U CRC_TblCRC16_8048_ref[256]; extern const CRC_MODEL_16 CRC_ModelCRC16_8048_ref; #endif #if (FS_STORAGE_CFG_CRC32_EN == DEF_ENABLED) extern const CPU_INT32U CRC_TblCRC32[256]; extern const CRC_MODEL_32 CRC_ModelCRC32; #endif #if (FS_STORAGE_CFG_CRC32_REF_EN == DEF_ENABLED) extern const CPU_INT32U CRC_TblCRC32_ref[256]; extern const CRC_MODEL_32 CRC_ModelCRC32_ref; #endif /******************************************************************************************************** ******************************************************************************************************** * FUNCTION PROTOTYPES ******************************************************************************************************** *******************************************************************************************************/ // ------------- 16-BIT CRC ON DATA STREAM ------------ void CRC_Open_16Bit(CRC_MODEL_16 *p_model, CRC_CALC_16 *p_calc, RTOS_ERR *p_err); void CRC_WrBlock_16Bit(CRC_CALC_16 *p_calc, void *p_data, CPU_SIZE_T size); void CRC_WrOctet_16Bit(CRC_CALC_16 *p_calc, CPU_INT08U octet); CPU_INT16U CRC_Close_16Bit(CRC_CALC_16 *p_calc); // ------------- 32-BIT CRC ON DATA STREAM ------------ void CRC_Open_32Bit(CRC_MODEL_32 *p_model, CRC_CALC_32 *p_calc, RTOS_ERR *p_err); void CRC_WrBlock_32Bit(CRC_CALC_32 *p_calc, void *p_data, CPU_SIZE_T size); void CRC_WrOctet_32Bit(CRC_CALC_32 *p_calc, CPU_INT08U octet); CPU_INT32U CRC_Close_32Bit(CRC_CALC_32 *p_calc); // --------------------- Reflection ------------------- CPU_INT08U CRC_Reflect_08Bit(CPU_INT08U datum); CPU_INT16U CRC_Reflect_16Bit(CPU_INT16U datum); CPU_INT32U CRC_Reflect_32Bit(CPU_INT32U datum); // -------------- CALCULATION ON DATA SET ------------- CPU_INT16U CRC_ChkSumCalc_16Bit(CRC_MODEL_16 *p_model, void *p_data, CPU_SIZE_T size); CPU_INT32U CRC_ChkSumCalc_32Bit(CRC_MODEL_32 *p_model, void *p_data, CPU_SIZE_T size); /******************************************************************************************************** * FUNCTION PROTOTYPES * defined in edc_crc_a.asm *******************************************************************************************************/ #if (FS_CORE_CFG_OPTIMIZE_ASM_EN == DEF_ENABLED) CPU_INT16U CRC_ChkSumCalcTbl_16Bit(CPU_INT16U init_val, const CPU_INT16U *p_tbl, CPU_INT08U *p_data, CPU_SIZE_T size); CPU_INT16U CRC_ChkSumCalcTbl_16Bit_ref(CPU_INT16U init_val, const CPU_INT16U *p_tbl, CPU_INT08U *p_data, CPU_SIZE_T size); CPU_INT32U CRC_ChkSumCalcTbl_32Bit(CPU_INT32U init_val, const CPU_INT32U *p_tbl, CPU_INT08U *p_data, CPU_SIZE_T size); CPU_INT32U CRC_ChkSumCalcTbl_32Bit_ref(CPU_INT32U init_val, const CPU_INT32U *p_tbl, CPU_INT08U *p_data, CPU_SIZE_T size); #endif /******************************************************************************************************** ******************************************************************************************************** * CONFIGURATION ERRORS ******************************************************************************************************** *******************************************************************************************************/ #ifndef FS_STORAGE_CFG_CRC_OPTIMIZE_ASM_EN #error "FS_STORAGE_CFG_CRC_OPTIMIZE_ASM_EN not #define'd in 'fs_storage_cfg.h'. MUST be DEF_ENABLED or DEF_DISABLED." #elif ((FS_STORAGE_CFG_CRC_OPTIMIZE_ASM_EN != DEF_ENABLED) \ && (FS_STORAGE_CFG_CRC_OPTIMIZE_ASM_EN != DEF_DISABLED)) #error "FS_STORAGE_CFG_CRC_OPTIMIZE_ASM_EN illegally #define'd in 'fs_storage_cfg.h'. MUST be DEF_ENABLED or DEF_DISABLED." #endif #ifndef FS_STORAGE_CFG_CRC16_1021_EN #error "FS_STORAGE_CFG_CRC16_1021_EN not #define'd in 'edc_crc.h'. MUST be DEF_ENABLED or DEF_DISABLED." #elif ((FS_STORAGE_CFG_CRC16_1021_EN != DEF_ENABLED) \ && (FS_STORAGE_CFG_CRC16_1021_EN != DEF_DISABLED)) #error "FS_STORAGE_CFG_CRC16_1021_EN illegally #define'd in 'edc_crc.h'. MUST be DEF_ENABLED or DEF_DISABLED." #endif #ifndef FS_STORAGE_CFG_CRC16_1021_REF_EN #error "FS_STORAGE_CFG_CRC16_1021_REF_EN not #define'd in 'edc_crc.h'. MUST be DEF_ENABLED or DEF_DISABLED." #elif ((FS_STORAGE_CFG_CRC16_1021_REF_EN != DEF_ENABLED) \ && (FS_STORAGE_CFG_CRC16_1021_REF_EN != DEF_DISABLED)) #error "FS_STORAGE_CFG_CRC16_1021_REF_EN illegally #define'd in 'edc_crc.h'. MUST be DEF_ENABLED or DEF_DISABLED." #endif #ifndef FS_STORAGE_CFG_CRC16_8005_EN #error "FS_STORAGE_CFG_CRC16_8005_EN not #define'd in 'edc_crc.h'. MUST be DEF_ENABLED or DEF_DISABLED." #elif ((FS_STORAGE_CFG_CRC16_8005_EN != DEF_ENABLED) \ && (FS_STORAGE_CFG_CRC16_8005_EN != DEF_DISABLED)) #error "FS_STORAGE_CFG_CRC16_8005_EN illegally #define'd in 'edc_crc.h'. MUST be DEF_ENABLED or DEF_DISABLED." #endif #ifndef FS_STORAGE_CFG_CRC16_8005_REF_EN #error "FS_STORAGE_CFG_CRC16_8005_REF_EN not #define'd in 'edc_crc.h'. MUST be DEF_ENABLED or DEF_DISABLED." #elif ((FS_STORAGE_CFG_CRC16_8005_REF_EN != DEF_ENABLED) \ && (FS_STORAGE_CFG_CRC16_8005_REF_EN != DEF_DISABLED)) #error "FS_STORAGE_CFG_CRC16_8005_REF_EN illegally #define'd in 'edc_crc.h'. MUST be DEF_ENABLED or DEF_DISABLED." #endif #ifndef FS_STORAGE_CFG_CRC16_8048_EN #error "FS_STORAGE_CFG_CRC16_8048_EN not #define'd in 'edc_crc.h'. MUST be DEF_ENABLED or DEF_DISABLED." #elif ((FS_STORAGE_CFG_CRC16_8048_EN != DEF_ENABLED) \ && (FS_STORAGE_CFG_CRC16_8048_EN != DEF_DISABLED)) #error "FS_STORAGE_CFG_CRC16_8048_EN illegally #define'd in 'edc_crc.h'. MUST be DEF_ENABLED or DEF_DISABLED." #endif #ifndef FS_STORAGE_CFG_CRC16_8048_REF_EN #error "FS_STORAGE_CFG_CRC16_8048_REF_EN not #define'd in 'edc_crc.h'. MUST be DEF_ENABLED or DEF_DISABLED." #elif ((FS_STORAGE_CFG_CRC16_8048_REF_EN != DEF_ENABLED) \ && (FS_STORAGE_CFG_CRC16_8048_REF_EN != DEF_DISABLED)) #error "FS_STORAGE_CFG_CRC16_8048_REF_EN illegally #define'd in 'edc_crc.h'. MUST be DEF_ENABLED or DEF_DISABLED." #endif #ifndef FS_STORAGE_CFG_CRC32_EN #error "FS_STORAGE_CFG_CRC32_EN not #define'd in 'edc_crc.h'. MUST be DEF_ENABLED or DEF_DISABLED." #elif ((FS_STORAGE_CFG_CRC32_EN != DEF_ENABLED) \ && (FS_STORAGE_CFG_CRC32_EN != DEF_DISABLED)) #error "FS_STORAGE_CFG_CRC32_EN illegally #define'd in 'edc_crc.h'. MUST be DEF_ENABLED or DEF_DISABLED." #endif #ifndef FS_STORAGE_CFG_CRC32_REF_EN #error "FS_STORAGE_CFG_CRC32_REF_EN not #define'd in 'edc_crc.h'. MUST be DEF_ENABLED or DEF_DISABLED." #elif ((FS_STORAGE_CFG_CRC32_REF_EN != DEF_ENABLED) \ && (FS_STORAGE_CFG_CRC32_REF_EN != DEF_DISABLED)) #error "FS_STORAGE_CFG_CRC32_REF_EN illegally #define'd in 'edc_crc.h'. MUST be DEF_ENABLED or DEF_DISABLED." #endif /******************************************************************************************************** ******************************************************************************************************** * MODULE END ******************************************************************************************************** *******************************************************************************************************/ #endif
54.581267
124
0.432191
[ "model" ]
42cf7e94dfb20c006faa9fd72be6e3c8b5fb4c66
8,547
h
C
ThirdParty/Havok/include/Physics2012/Collide/Shape/Convex/ConvexVertices/hkpConvexVerticesShape.h
wobbier/source3-engine
f59df759ee197aef5191cf13768c303c6ed17bf5
[ "MIT" ]
11
2016-08-02T03:40:36.000Z
2022-03-15T13:41:29.000Z
ThirdParty/Havok/include/Physics2012/Collide/Shape/Convex/ConvexVertices/hkpConvexVerticesShape.h
wobbier/source3-engine
f59df759ee197aef5191cf13768c303c6ed17bf5
[ "MIT" ]
null
null
null
ThirdParty/Havok/include/Physics2012/Collide/Shape/Convex/ConvexVertices/hkpConvexVerticesShape.h
wobbier/source3-engine
f59df759ee197aef5191cf13768c303c6ed17bf5
[ "MIT" ]
8
2017-03-17T05:59:25.000Z
2021-02-27T08:51:46.000Z
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2014 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HKP_CONVEX_VERTICES_SHAPE_H #define HKP_CONVEX_VERTICES_SHAPE_H #include <Common/Base/Math/Vector/hkFourTransposedPoints.h> #include <Common/Base/Types/Geometry/Aabb/hkAabbUtil.h> #include <Physics2012/Collide/Shape/Convex/hkpConvexShape.h> extern const class hkClass hkpConvexVerticesShapeFourVectorsClass; extern const hkClass hkpConvexVerticesShapeClass; struct hkStridedVertices; class hkpConvexVerticesConnectivity; /// A convex geometric shape, specified by a set of vertices in the shape's local space. /// An optional set of corresponding planes may be provided - if present, they will improve /// ray cast performance. Optional connectivity information may also be provided - this is /// required for certain algorithms, but not for most use cases. class hkpConvexVerticesShape : public hkpConvexShape { //+version(6) public: HK_DECLARE_CLASS_ALLOCATOR( HK_MEMORY_CLASS_SHAPE ); HK_DECLARE_REFLECTION(); HK_DECLARE_GET_SIZE_FOR_SPU( hkpConvexVerticesShape ); HKCD_DECLARE_SHAPE_TYPE( hkcdShapeType::CONVEX_VERTICES ); public: /// Build configuration. /// Warning: m_useOptimizedShrinking is not always robust and is disable by default. struct BuildConfig { BuildConfig(); hkBool m_createConnectivity; ///< Create connectivity (default: false). hkBool m_shrinkByConvexRadius; ///< Shrink vertices by convex radius (default: true), so that raycast and physics collisions are consistent. hkBool m_useOptimizedShrinking; ///< Optimized shrinking such as the number of vertices after shrinking is less or equal to the unshrunk shape vertices count. hkReal m_convexRadius; ///< Convex radius (default: hkConvexShapeDefaultRadius). int m_maxVertices; ///< Maximum vertices, used for simplification (default: 0, no simplification). hkReal m_maxRelativeShrink; ///< Maximum relative shrink factor (default: 0.05) (relative to the AABB of the object). hkReal m_maxShrinkingVerticesDisplacement; ///< Maximum vertices displacement due to shrinking (default: 0.07). hkReal m_maxCosAngleForBevelPlanes; ///< If the cos angle (== dot product) of two neighboring face normals is smaller than this, a bevel plane is inserted to optimize raycast behavior (default -0.1f) }; public: /// Create a shape from the given vertices, automatically setting planes equations and connectivity. /// Also shrink the shape vertices so that collision detection and ray cast results are consistent. /// Notes: This is the recommended way to create a convex vertices shape. hkpConvexVerticesShape( const hkStridedVertices& vertices, const BuildConfig& config=BuildConfig() ); /// Create a shape from the given vertices and matching plane equations. /// These are plane equations of the convex hull and can be generated /// using the hkGeometryUtility::createConvexGeometry method. /// This constructor makes an internal copy of the vertices. /// You should take care of not passing in unnecessary vertices, e.g., inner vertices or /// duplicated vertices. hkGeometryUtility::createConvexGeometry will also give /// you back a clean list of vertices to use. hkpConvexVerticesShape( const hkStridedVertices& vertsIn, const hkArray<hkVector4>& planeEquations, hkReal radius = hkConvexShapeDefaultRadius ); /// Create a shape from precomputed data. /// Note: numVertices is the actual number of vertices, not the number of hkFourTransposedPoints structures. hkpConvexVerticesShape( hkFourTransposedPoints* rotatedVertices, int numVertices, hkVector4* planes, int numPlanes, const hkAabb& aabb, hkReal radius = hkConvexShapeDefaultRadius ); /// Create an empty shape. hkpConvexVerticesShape( hkReal radius = hkConvexShapeDefaultRadius ); /// Serialization constructor. hkpConvexVerticesShape( hkFinishLoadedObjectFlag flag ); /// Destructor ~hkpConvexVerticesShape(); /// Allocates a new convex vertices shape at the given memory location static HK_FORCE_INLINE hkpConvexVerticesShape* HK_CALL createInPlace( hkUint8*& memPtr, hkReal convexRadius ); public: /// The original vertices passed during construction are stored in a packed form within the shape. /// This retrieves the original vertices into the provided array. void getOriginalVertices( hkArray<hkVector4>& vertices ) const; /// Returns the plane equations, if any const hkArray<hkVector4>& getPlaneEquations() const; /// Overwrite plane equations void setPlaneEquations( const hkArray<hkVector4>& planes ); /// Overwrite only the convex radius without caring about plane equations or shape shrinking. void setRadiusUnchecked( hkReal radius ) { m_radius = radius; } // Utility function to convert this shape to a new space void transformVerticesAndPlaneEquations( const hkTransform& t ); // Utility function to overwrite the vertices void copyVertexData( const hkReal* vertexIn, int byteStriding, int numVertices ); // // Connectivity // // Get the connectivity. This is optional for this shape. Returns HK_NULL if connectivity is not present. HK_FORCE_INLINE const hkpConvexVerticesConnectivity* getConnectivity() const { return m_connectivity; } // Set the connectivity. Setting to HK_NULL will remove connectivity information. // The connectivity information is a 'cache' of information - so can be used to modify a const shape void setConnectivity( const hkpConvexVerticesConnectivity* connect, bool sort=true ); // hkpConvexShape interface implementation void getFirstVertex(hkVector4& v) const; protected: void sortPlanes(void); public: // // hkpShapeBase interface implementation // virtual void getSupportingVertex( hkVector4Parameter direction, hkcdVertex& supportingVertexOut ) const; // Note: You must be able to supply one valid vertex corresponding to ID 0. // This is a requirement because getFirstVertex() is not supported on SPU. virtual void convertVertexIdsToVertices( const hkpVertexId* ids, int numIds, hkcdVertex* verticesOut ) const; virtual void getCentre( hkVector4& centreOut ) const; virtual HK_FORCE_INLINE int getNumCollisionSpheres() const; virtual const hkSphere* getCollisionSpheres( hkSphere* sphereBuffer ) const; virtual void getAabb( const hkTransform& localToWorld, hkReal tolerance, hkAabb& out ) const; virtual hkBool castRay( const hkpShapeRayCastInput& input, hkpShapeRayCastOutput& results ) const; public: // Cached AABB hkVector4 m_aabbHalfExtents; hkVector4 m_aabbCenter; /// The vertices, packed in a transposed format hkArray<hkFourTransposedPoints> m_rotatedVertices; //+overridetype(hkArray<hkMatrix3>) hkInt32 m_numVertices; // Internal flag indicating whether the vertices reside in SPU memory. // This should be true only if constructed on-the-fly by some container shapes. hkBool m_useSpuBuffer; //+default(0) +nosave /// Optional plane equations, for faster ray cast queries. mutable hkArray<hkVector4> m_planeEquations; /// Optional (reference counted) vertex connectivity information for this shape. /// Set to HK_NULL if connectivity information is not present. mutable const hkpConvexVerticesConnectivity* m_connectivity; }; #include <Physics2012/Collide/Shape/Convex/ConvexVertices/hkpConvexVerticesShape.inl> #endif // HKP_CONVEX_VERTICES_SHAPE_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20140907) * * Confidential Information of Havok. (C) Copyright 1999-2014 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
44.284974
251
0.769861
[ "geometry", "object", "shape", "vector" ]
42e62a43f8ff0a37fac3a55a0307510dfcd0b95a
3,611
h
C
XMLBindings/APLXML_Base.h
rajive/dnp3
f5d8dbcec2085eaeb980e66d07df19b7bb9c20aa
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
XMLBindings/APLXML_Base.h
rajive/dnp3
f5d8dbcec2085eaeb980e66d07df19b7bb9c20aa
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
XMLBindings/APLXML_Base.h
rajive/dnp3
f5d8dbcec2085eaeb980e66d07df19b7bb9c20aa
[ "ECL-2.0", "Apache-2.0" ]
2
2019-03-31T15:27:05.000Z
2019-09-17T16:12:53.000Z
/* ****************************** GENERATED CONTENT DO NOT ALTER! ********************************* */ #ifndef _APLXML_BASE_H_ #define _APLXML_BASE_H_ #include <APLXML/tinybinding.h> using namespace std; namespace APLXML_Base { enum BaudRateEnum { BAUDRATE_1200, BAUDRATE_1800, BAUDRATE_2400, BAUDRATE_4800, BAUDRATE_9600, BAUDRATE_19200, BAUDRATE_38400, BAUDRATE_57600, BAUDRATE_115200, BAUDRATE_230400, }; BaudRateEnum FromString_BaudRateEnum(TiXmlNode* apParent, const char* aValue); string ToString_BaudRateEnum(BaudRateEnum aValue); enum DBitsEnum { DATABITS_7, DATABITS_8, }; DBitsEnum FromString_DBitsEnum(TiXmlNode* apParent, const char* aValue); string ToString_DBitsEnum(DBitsEnum aValue); enum FlowControlEnum { FLOW_NONE, FLOW_HARDWARE, FLOW_XONXOFF, }; FlowControlEnum FromString_FlowControlEnum(TiXmlNode* apParent, const char* aValue); string ToString_FlowControlEnum(FlowControlEnum aValue); enum LogLevelEnum { LOG_DEBUG, LOG_COMM, LOG_INTERPRET, LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_EVENT, }; LogLevelEnum FromString_LogLevelEnum(TiXmlNode* apParent, const char* aValue); string ToString_LogLevelEnum(LogLevelEnum aValue); enum ParityEnum { PARITY_NONE, PARITY_EVEN, PARITY_ODD, }; ParityEnum FromString_ParityEnum(TiXmlNode* apParent, const char* aValue); string ToString_ParityEnum(ParityEnum aValue); class PhysicalLayerDescriptor_t : public IXMLDataBound { public: void toXml(TiXmlNode* pParent, bool aCreateNode, bool aIgnoreValid); void fromXml(TiXmlNode* pNode); string Name; int OpenRetryMS; }; enum StopBitsEnum { STOPBITS_0, STOPBITS_1, STOPBITS_2, }; StopBitsEnum FromString_StopBitsEnum(TiXmlNode* apParent, const char* aValue); string ToString_StopBitsEnum(StopBitsEnum aValue); class TCPClient_t : public APLXML_Base::PhysicalLayerDescriptor_t{ public: void toXml(TiXmlNode* pParent, bool aCreateNode, bool aIgnoreValid); void fromXml(TiXmlNode* pNode); string Address; int Port; }; class TCPServer_t : public APLXML_Base::PhysicalLayerDescriptor_t{ public: void toXml(TiXmlNode* pParent, bool aCreateNode, bool aIgnoreValid); void fromXml(TiXmlNode* pNode); string Endpoint; int Port; }; class Log_t : public IXMLDataBound { public: void toXml(TiXmlNode* pParent, bool aCreateNode, bool aIgnoreValid); void fromXml(TiXmlNode* pNode); LogLevelEnum Filter; }; class Serial_t : public APLXML_Base::PhysicalLayerDescriptor_t{ public: void toXml(TiXmlNode* pParent, bool aCreateNode, bool aIgnoreValid); void fromXml(TiXmlNode* pNode); string Device; BaudRateEnum BaudRate; ParityEnum Parity; DBitsEnum DBits; StopBitsEnum StopBits; FlowControlEnum FlowControl; }; #ifdef SWIG } %template(Serial_c) std::vector<APLXML_Base::Serial_t*>; namespace APLXML_Base{ #endif #ifdef SWIG } %template(TCPClient_c) std::vector<APLXML_Base::TCPClient_t*>; namespace APLXML_Base{ #endif #ifdef SWIG } %template(TCPServer_c) std::vector<APLXML_Base::TCPServer_t*>; namespace APLXML_Base{ #endif class PhysicalLayerList_t : public IXMLDataBound { public: void toXml(TiXmlNode* pParent, bool aCreateNode, bool aIgnoreValid); void fromXml(TiXmlNode* pNode); PhysicalLayerList_t(); #ifdef SWIG %immutable TCPServerVector; #endif private: collectedType < TCPServer_t > TCPServer; public: vector < TCPServer_t* >& TCPServerVector; #ifdef SWIG %immutable TCPClientVector; #endif private: collectedType < TCPClient_t > TCPClient; public: vector < TCPClient_t* >& TCPClientVector; #ifdef SWIG %immutable SerialVector; #endif private: collectedType < Serial_t > Serial; public: vector < Serial_t* >& SerialVector; }; } #endif
24.732877
85
0.779839
[ "vector" ]
42e7f0260afe72b337f1d5b07415a6da8c2182c3
2,618
h
C
Dashboard/inc/renderer.h
Pippo98/telemetry
e78abc82c94d840a94422b3177aff02f10aa1352
[ "MIT" ]
null
null
null
Dashboard/inc/renderer.h
Pippo98/telemetry
e78abc82c94d840a94422b3177aff02f10aa1352
[ "MIT" ]
6
2021-05-12T10:48:08.000Z
2021-05-13T11:44:32.000Z
Dashboard/inc/renderer.h
Pippo98/telemetry
e78abc82c94d840a94422b3177aff02f10aa1352
[ "MIT" ]
1
2021-08-24T13:57:28.000Z
2021-08-24T13:57:28.000Z
#pragma once #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string> #include <iostream> #include <chrono> #include <unordered_map> #include <opencv2/dnn/dnn.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/videoio.hpp> #include "devices.pb.h" #include <google/protobuf/message.h> #include <google/protobuf/text_format.h> #include <google/protobuf/util/json_util.h> #include <mutex> #include <atomic> #include <thread> #include <condition_variable> using namespace std; using namespace cv; using namespace std::chrono; using namespace google::protobuf; using namespace google::protobuf::util; struct Box { int x; int y; int w; int h; }; struct Sate_t { double timestamp; string value; }; class Data{}; class Page; class ChimeraData : public Data { public: ChimeraData(devices::Chimera* chim): data(chim){}; void SetData(devices::Chimera* chim) { data = chim; }; // void PushData(devices::Chimera* chim); devices::Chimera* data = nullptr; // unordered_map<string, unordered_map<string, vector<double>>> sensor_values; // unordered_map<string, vector<Sate_t>> state_values; private: // int max_count = 1000; }; class Renderer { public: Renderer(int w, int h); void SetBackground(int R, int G, int B); void SetFrameRate(int); void Kill(); void WaitForFinish(); void Pause(); void Start(); void ToggleStartStop(); void SetOnKeyPress(void (*func)(char& )) { on_key_press = func; }; /** * Adds a page to vector of pages that can be rendered * @param *page pointer to page * @param idx index in wich the page is added -1 pushes at last position */ void AddPage(Page* page, int idx=-1); /** * Removes a page from vector of pages that can be rendered * @param *page pointer to page (it does not delete the whole pointer) */ void RemovePage(Page* page); /** * Removes a page t given index -1 means last position */ void RemovePage(int idx=-1); /** * Returns page at index * @param idx index of page to be returned if -1 returns current */ Page* GetPage(int idx=-1); void MoveLeft(); void MoveRight(); /** * Renders page at index * @param idx if -1 renders last page */ void MoveToIndex(int idx=-1); private: void Render(); void DrawFooter(Mat*); Page* current_page = nullptr; vector<Page *> pages; int page_idx; int W, H; thread* render_thread = nullptr; Mat background; Mat render_image; float frame_rate; atomic<int> pause; atomic<bool> kill; void (*on_key_press)(char&) = nullptr; };
18.7
80
0.682582
[ "render", "vector" ]
42f271d4b51dbaf84011dfe7a2b1c1f4a3832a7f
139,778
c
C
Esm/ib/src/smi/sm/sm_topology.c
dsilakov/opa-fm
72d7942fd7f33c1b67d8cd981efe1bd8733ef54a
[ "Intel" ]
null
null
null
Esm/ib/src/smi/sm/sm_topology.c
dsilakov/opa-fm
72d7942fd7f33c1b67d8cd981efe1bd8733ef54a
[ "Intel" ]
2
2021-04-13T12:59:17.000Z
2021-12-10T19:14:13.000Z
Esm/ib/src/smi/sm/sm_topology.c
dsilakov/opa-fm
72d7942fd7f33c1b67d8cd981efe1bd8733ef54a
[ "Intel" ]
5
2021-02-24T23:01:54.000Z
2022-03-30T18:54:05.000Z
/* BEGIN_ICS_COPYRIGHT7 **************************************** Copyright (c) 2015-2020, Intel Corporation Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** END_ICS_COPYRIGHT7 ****************************************/ /* [ICS VERSION STRING: unknown] */ //===========================================================================// // // FILE NAME // sm_topology.c // // DESCRIPTION // This thread will do the bulk of the work. It discovers the // the topology, initializes the FIs and switches, and then // tells the state machine to transition to another state. // //===========================================================================// #include "os_g.h" #include "ib_types.h" #include "ib_macros.h" #include "ib_mad.h" #include "ib_sa.h" #include "ib_status.h" #include "cs_g.h" #include "cs_csm_log.h" #include "sm_counters.h" #include "sm_l.h" #include "sa_l.h" #include "cs_queue.h" #include "cs_bitset.h" #include "sm_dbsync.h" #include "stl_cca.h" #include "ispinlock.h" #include "topology.h" #include "sm_parallelsweep.h" #include "sm_discovery.h" #include "sm_activate.h" #include "sm_pkeys.h" #include "sm_switch_info.h" #include "sm_qos.h" #include "sm_update_fields.h" #include "sm_lid_assignment.h" #include "sm_cable_info.h" #include "sm_congestion.h" #include "sm_ar.h" #include <stl_helper.h> #if defined(__VXWORKS__) #include "bspcommon/h/usrBootManager.h" #endif extern uint8_t smTerminateAfter; extern char* smDumpCounters; extern boolean lid_space_exhausted; extern SmMaiHandle_t * fd_sminfo; extern char* printLoopPaths(int, int); extern char * snprintfcat(char * buf, int * len, const char * format, ...); #ifdef IB_STACK_OPENIB #include "mal_g.h" #endif int isSweeping = 0; int activateInProgress = 0; int forceRebalanceNextSweep = 0; int oldSmActiveCount = 0; // variables used to synchronize sweeps on traps uint32_t smFabricDiscoveryNeeded=0; uint64_t lastTimeDiscoveryRequested=0; void dump_cost_array(uint16_t *); void showSmParms(void); Status_t sweep_initialize(SweepContext_t *); Status_t sweep_transition(SweepContext_t *); Status_t sweep_resolve(SweepContext_t *); Status_t sweep_assignments_looptest(SweepContext_t *); Status_t sweep_assignments_setup_switches(SweepContext_t *); Status_t sweep_assignments_lids(SweepContext_t *); Status_t sweep_adaptiverouting(SweepContext_t *); Status_t sweep_cableinfo(SweepContext_t *); Status_t sweep_post_activate(SweepContext_t *); Status_t sweep_multicast(SweepContext_t *); Status_t sweep_cache_build(SweepContext_t *); Status_t sweep_loopTest(SweepContext_t *); Status_t topology_changes(Topology_t *old_topo, Topology_t *new_topo); Status_t topology_TrapUp(STL_NOTICE * noticep, Topology_t *, Topology_t *, Node_t *, Port_t *); Status_t topology_TrapDown(STL_NOTICE * noticep, Topology_t *, Topology_t *, Node_t *, Port_t *); Status_t topology_TrapCostMatrixChange(STL_NOTICE *noticep); Status_t topology_free_topology(Topology_t * topop, boolean need_old_topo_lock, boolean freeRoutingMod); Status_t topology_copy(void); void topology_clearNew(void); Status_t topology_cache_copy(void); Status_t topology_congestion(void); Status_t copy_congestion_control_data(void); Status_t topology_assignments_delayedpkeys(void); Status_t topology_reregisters(void); Status_t topology_db(void); Status_t topology_fe(void); Status_t topology_dump(void); Status_t topology_setup_routing_cost_matrix(void); Status_t topology_sm_port_init_failure(void); Status_t topology_setup_switches_LR_DR(void); Status_t topology_update_cableinfo(void); typedef Status_t (*TFunc_t)(SweepContext_t *sweep_context); typedef struct { char * name; TFunc_t func; } TFuncEntry_t; #define MAKE_TFUNC(name) { #name, name } #define END_TFUNC() { "(null)", NULL } TFuncEntry_t sweep_functions[] = { MAKE_TFUNC(sweep_initialize), // Initialize data structures, local SM port. MAKE_TFUNC(sweep_discovery), // Initial exploration of the fabric MAKE_TFUNC(sweep_transition), // Determine if this SM should be MASTER or STANDBY. MAKE_TFUNC(sweep_userexit), // NOOP! MAKE_TFUNC(sweep_resolve), // Resolve LID assignments. MAKE_TFUNC(sweep_get_pkey), MAKE_TFUNC(sweep_assignments_looptest), MAKE_TFUNC(sweep_assignments_switchinfo), MAKE_TFUNC(sweep_assignments_setup_switches), MAKE_TFUNC(sweep_assignments_lids), MAKE_TFUNC(sweep_assignments_update_fields), MAKE_TFUNC(sweep_assignments_vlarb), MAKE_TFUNC(sweep_assignments_buffer_control), MAKE_TFUNC(sweep_adaptiverouting), // Transmit PGTs and PGFTs to switches. MAKE_TFUNC(sweep_arm), // Bring all links to armed. MAKE_TFUNC(sweep_activate), // Bring all links to active. MAKE_TFUNC(sweep_cableinfo), // Fetch cableinfo. MAKE_TFUNC(sweep_post_activate), // Misc post-activation non-packet logic. MAKE_TFUNC(sm_dbsync_upsmlist), // Update our list of SMs in the fabric MAKE_TFUNC(sweep_multicast), // Build MFTs MAKE_TFUNC(sweep_cache_build), // Builds caches that are used by the SA. MAKE_TFUNC(sweep_loopTest), // Embedded only. Injects packets into fabric. END_TFUNC() }; static const char *sweep_reasons[] = { [SM_SWEEP_REASON_INIT] = "Initial sweep.", [SM_SWEEP_REASON_SCHEDULED] = "Scheduled sweep interval", [SM_SWEEP_REASON_RECONFIG] = "FM reconfigured.", [SM_SWEEP_REASON_MCMEMBER] = "Multicast group Membership change.", [SM_SWEEP_REASON_ACTIVATE_FAIL] = "Failed to activate port(s) in the fabric.", [SM_SWEEP_REASON_ROUTING_FAIL] = "Error while programming routing forwarding table(s) in fabric.", [SM_SWEEP_REASON_MC_ROUTING_FAIL] = "Error while programming multicast table(s) in fabric.", [SM_SWEEP_REASON_UNEXPECTED_BOUNCE] = "Port(s) in fabric bounced unexpectedly during bringup.", [SM_SWEEP_REASON_LOCAL_PORT_FAIL] = "Our SM's port wasn't ready, or went down unexpectedly.", [SM_SWEEP_REASON_STATE_TRANSITION] = "Our SM state transitioned to DISCOVERY or MASTER.", [SM_SWEEP_REASON_SECONDARY_TROUBLE] = "Abnormal behavior from a secondary SM observed.", [SM_SWEEP_REASON_MASTER_TROUBLE] = "Abnormal behavior from the MASTER SM observed.", [SM_SWEEP_REASON_UPDATED_STANDBY] = "Status changed for a STANDBY SM in fabric.", [SM_SWEEP_REASON_HANDOFF] = "Preparation for handoff to another SM.", [SM_SWEEP_REASON_UNEXPECTED_SM] = "Found a SM we haven't seen before.", [SM_SWEEP_REASON_FORCED] = "SM sweep forced by user.", [SM_SWEEP_REASON_INTERVAL_CHANGE] = "SM sweep interval changed by user.", [SM_SWEEP_REASON_FAILED_SWEEP] = "Problems during previous sweep, retrying.", [SM_SWEEP_REASON_TRAP_EVENT] = "Trap event occurred that requires re-sweep.", [SM_SWEEP_REASON_UNQUARANTINE] = "Last sweep succeeded with quarantined devices: clearing short-term quarantine and retrying.", [SM_SWEEP_REASON_UNDETERMINED] = "No reason was specified (WARNING: abnormal!)." }; SweepReason_t sm_resweep_reason = SM_SWEEP_REASON_INIT; uint64_t topology_wakeup_time; int topo_retry_backoff = 0; /*Default behavior - no retry back off*/ uint32_t topo_retry_backoff_interval = 0; static SmCsmMsgType_t nodeAppearanceSeverity = CSM_SEV_NOTICE; static int sweepNodeChangeMsgCount = 0; static int sweepNodeAppearanceInfoMsgCount = 0; static int sweepNodeDisappearanceInfoMsgCount = 0; Topology_t old_topology; Topology_t sm_newTopology; Topology_t *sm_topop = &sm_newTopology; Popo_t sm_popo; FabricData_t preDefTopology; bitset_t old_switchesInUse; bitset_t new_switchesInUse; bitset_t new_endnodesInUse; int topo_errors=0; /* number of errors during fabric init */ int topo_abandon_count=0; /* number of consecutive times we abandoned sweep */ int topology_once = -1; int topology_changed = 0; int topology_switch_port_changes = 0; /* there are switches with switch port change flag set*/ int topology_cost_path_changes = 0; int topology_changed_count = 0; uint32_t topology_passcount = 0ull; int routing_recalculated = 0; sm_dispatch_t sm_asyncDispatch; uint32_t topology_port_bounce_log_num = 0; // Number of times we have logged a port bounce this sweep static int topology_resweep = 0; // request to resweep immediately static ATOMIC_UINT topology_triggered; // true when a sweep has been triggered // unconditionally send MFTs regardless of previous sweep state static int topology_forceMfts = 0; int topology_main_exit = 0; static int sm_port_retry_count=0; /*keep track of sm port initialization retries*/ static int cca_discovery_count = 0; extern Sema_t topology_sema; #ifdef __VXWORKS__ #include "bspcommon/h/sysPrintf.h" void topology_uninitialize(void); #else #define sysPrintf printf #define SYS_PINFO #endif // external functions extern int saSubscriberSize(void); extern int saServiceRecordSize(void); extern int saMcGroupSize(void); extern int saMcMemberSize(void); extern int saMaxResponseSize(void); extern int saNodeRecordSize(void); extern Status_t sm_sa_forward_trap(STL_NOTICE * noticep); extern char* printSwitchLft(int nodeIdx, int useNew, int haveLock, int buffer); extern Status_t sm_cong_config_copy(void); VirtualFabrics_t *previousVfPtr; extern VirtualFabrics_t *updatedVirtualFabrics; #ifndef __VXWORKS__ extern uint32_t xml_trace; int sm_peer_quarantined = 0; #endif void reset_port_retry_count(void) { sm_port_retry_count = 0; } int topology_resweep_requested(void) { return topology_resweep; } int topology_main_exited(void) { return topology_main_exit; } int topology_sweep_triggered(void) { return AtomicRead(&topology_triggered); } static const char* GetStr_SpeedActive(STL_PORT_INFO *portInfo, char *buf, size_t len) { return (StlLinkSpeedToText(portInfo->LinkSpeed.Active, buf, len)); } static const char* GetStr_SpeedSupport(STL_PORT_INFO *portInfo, char *buf, size_t len) { return (StlLinkSpeedToText(portInfo->LinkSpeed.Supported, buf, len)); } /* * clean up the SA tables when we transition to Standby state */ static void clearSaTables(SweepContext_t *sweep_context) { /* * clear everything if transitioning from master to standby or less */ if (sm_prevState == SM_STATE_MASTER) { IB_LOG_INFO0("Clearing lidmap, services, subscriptions, SA context, groups and SM list"); /* clear the lidmap and reset sm_lid */ if (vs_wrlock(&old_topology_lock) == VSTATUS_OK) { sm_lidmap_reset(); (void)vs_rwunlock(&old_topology_lock); } // Reset the lid assignment hints sm_lmc_e0_freeLid_hint = 1 << sm_config.lmc_e0; sm_lmc_freeLid_hint = 1 << sm_config.lmc; sm_lmc_0_freeLid_hint = 1; sm_lid = sm_config.lid; /* clear subscriptions, sa context, broadcast groups, sm table, and service records here */ (void) sa_SubscriberClear(); (void) sa_cntxt_clear(); (void) sa_ServiceRecClear(); (void) sm_dbsync_upsmlist(sweep_context); /* clean out all sm records except for ours */ if (sm_state > SM_STATE_NOTACTIVE) (void)clearBroadcastGroups(TRUE); } else { IB_LOG_INFO0("Clearing lidmap and the Sm list"); /* clear the lidmap and reset sm_lid */ if (vs_wrlock(&old_topology_lock) == VSTATUS_OK) { sm_lidmap_reset(); (void)vs_rwunlock(&old_topology_lock); } // Reset the lid assignment hints sm_lmc_e0_freeLid_hint = 1 << sm_config.lmc_e0; sm_lmc_freeLid_hint = 1 << sm_config.lmc; sm_lmc_0_freeLid_hint = 1; /* clear just the SM table otherwise */ (void) sm_dbsync_upsmlist(sweep_context); /* clean out all sm records except for ours */ } } //---------------------------------------------------------------------------- /** @param compare @c a and @c b */ boolean sm_eq_XmitQ(const struct XmitQ_s * a, const struct XmitQ_s * b, uint8 actVls) { uint8 i; for (i = 0; i < MAX(actVls, 16); ++i) { if (actVls < 16 && i == actVls) i = 15; // Skip to VL15 if (a[i].VLStallCount != b[i].VLStallCount) return 0; if (a[i].HOQLife != b[i].HOQLife) return 0; } return 1; } //---------------------------------------------------------------------------- int sm_evalPreemptLargePkt(int cfgLarge, Node_t * nodep) { // Algorithm is (x + 1) * INC int x = cfgLarge / SM_PREEMPT_LARGE_PACKET_INC - 1; // Value must fit in 4 bit field x &= 0xf; return x; } //---------------------------------------------------------------------------- int sm_evalPreemptSmallPkt(int cfgSmall, Node_t * nodep) { // Algorithm is (x + 1) * INC int x = cfgSmall / SM_PREEMPT_SMALL_PACKET_INC - 1; // Value must fit in 8 bit field x &= 0xff; return x; } //---------------------------------------------------------------------------- int sm_evalPreemptLimit(int cfgLimit, Node_t * nodep) { // Algorithm is x * INC. Zero means zero, 255 means infinite int x = cfgLimit / SM_PREEMPT_LIMIT_INC; // Value must fit in 8 bit field x &= 0xff; return x; } //---------------------------------------------------------------------------- // to be called from within a sweep. requests another sweep be performed // after this one, but allows the current sweep to succeed void sm_request_resweep(int forceLfts, int forceMfts, SweepReason_t reason) { uint64_t now, next; if (! topology_resweep || (forceMfts && ! topology_forceMfts) || (forceLfts && ! forceRebalanceNextSweep) ){ IB_LOG_INFINI_INFO_FMT(__func__, "SM Resweep (with%s %s, with%s MFT) scheduled.", (forceLfts||forceRebalanceNextSweep)?"":"out", sm_fwd_table_type_str(sm_topop), (forceMfts||topology_forceMfts)?"":"out"); } if (forceLfts) forceRebalanceNextSweep = 1; if (forceMfts) topology_forceMfts = 1; topology_resweep = 1; setResweepReason(reason); // if we're already queued up for the next sweep, this will wake us. // if we're already in a sweep, this will get overwritten to the correct // value because of hte topology_resweep flag (we may end up with one // more sweep than expected) (void)vs_time_get(&now); next = now + VTIMER_1S * 5; if (next < topology_wakeup_time) topology_wakeup_time = next; } void sm_trigger_sweep(SweepReason_t reason) { setResweepReason(reason); AtomicWrite(&topology_triggered, 1); (void)vs_time_get(&topology_sema_setTime); (void)cs_vsema(&topology_sema); // Since a sweep is triggered, clear the smFabricDiscoveryNeeded indicator smFabricDiscoveryNeeded = 0; // Since a sweep is triggered, clear the lastTimeDiscoveryRequested indicator lastTimeDiscoveryRequested = 0; } /* * interval is the smallest interval in seconds with which retries will start * interval_max_limit is the upper limit for the retry interval in seconds * interval_reset = 1 means after upper limit of intervals is hit, retries will again * start with topo_retry_interval * interval_reset = 0 means after upper limit of intervals is hit, retries will continue * to use a retry interval of topo_retry_interval_max_limit * retry_count is the number of retries attempted till now */ static void topo_enable_retry_backoff(uint32_t interval, uint32_t interval_max_limit, int interval_reset, int retry_count) { /* Use an incremental backoff of multiples of topo_retry_interval with an upper bound of * topo_retry_interval_limit. */ topo_retry_backoff_interval = interval * retry_count; if (topo_retry_backoff_interval > interval_max_limit) { if (interval_reset) { /* Reset interval to start again with topo_retry_interval */ topo_retry_backoff_interval = topo_retry_backoff_interval % interval_max_limit; if (topo_retry_backoff_interval == 0) topo_retry_backoff_interval = interval_max_limit; } else { /* Continue to use topo_retry_interval_max_limit as the retry interval */ topo_retry_backoff_interval = interval_max_limit; } } topo_retry_backoff = 1; } SweepContext_t sm_sweep_context = {0}; ParallelSweepContext_t *sm_psc_g = NULL; void topology_main(uint32_t argc, uint8_t ** argv) { int i; int topologSemCount=0; uint64_t now, temp64; Status_t status = VSTATUS_OK; int newTopologyValid = 1; int sweepStartPacketCount=0; int oldSmCount = 0, newSmActiveCount = 0, oldSwitchCount = 0, oldHfiCount = 0, oldEndPortCount = 0, oldTotalPorts = 0; #ifdef __VXWORKS__ uint8_t shutdown=0; #endif IB_ENTER(__func__, 0, 0, 0, 0); topology_main_exit = 0; AtomicWrite(&topology_triggered, 0); cca_discovery_count = 0; // // Get my thread name. // (void)vs_thread_name(&sm_threads[SM_THREAD_TOPOLOGY].name); // // Init data structures for tracking entities removed from fabric. // sm_removedEntities_init(); if (!bitset_init(&sm_pool, &new_switchesInUse, SM_NODE_NUM) || !bitset_init(&sm_pool, &old_switchesInUse, SM_NODE_NUM) || !bitset_init(&sm_pool, &new_endnodesInUse, SM_NODE_NUM)) { return; } // // Initialize persistent topology // sm_popo_init(&sm_popo); // // Initialize our counters // sm_init_counters(); // // wait for topology_rcv thread // while ((status = cs_psema(&topology_rcv_sema)) != VSTATUS_OK) { IB_LOG_ERRORRC("timeout returned while waiting for topology_rcv_sema rc:", status); } // // Wait for the async thread to kick us off. After it does, we run through // the topology setup code. We then get the timer to determine when to do // this again. // /* * move SM to discovery state now */ (void)sm_transition(SM_STATE_DISCOVERING); // Initialize the thread pool for parallel sweep. sm_psc_g = psc_init(); if (!sm_psc_g) { IB_FATAL_ERROR_NODUMP("Unable to allocate threads for sweep."); return; } while (1) { if(topology_main_exit == 1){ #ifdef __VXWORKS__ ESM_LOG_ESMINFO("Topology Task exiting OK.", 0); #endif break; } nodeAppearanceSeverity = CSM_SEV_NOTICE; sweepNodeChangeMsgCount = 0; sweepNodeAppearanceInfoMsgCount = 0; sweepNodeDisappearanceInfoMsgCount = 0; oldSmCount = sm_dbsync_getSmCount(); if (sm_config.config_consistency_check_level != CHECK_ACTION_CCC_LEVEL) oldSmActiveCount = oldSmCount; newTopologyValid = 1; topology_changed = 0; topology_switch_port_changes = 0; topology_cost_path_changes = 0; routing_recalculated = 0; status = VSTATUS_OK; topologSemCount = -1; topology_resweep = 0; while (status == VSTATUS_OK && topologSemCount != 0) { if ((status = cs_psema(&topology_sema)) != VSTATUS_OK) { IB_FATAL_ERROR_NODUMP("TT: aborting - failed to take topology_sema"); } else { if ((status = cs_sema_getcount(&topology_sema, &topologSemCount)) != VSTATUS_OK) { IB_FATAL_ERROR_NODUMP("TT: aborting - failed to get topology_sema count"); } } AtomicWrite(&topology_triggered, 0); } if(topology_main_exit == 1){ #ifdef __VXWORKS__ ESM_LOG_ESMINFO("Topology Task exiting OK.", 0); #endif break; } (void)vs_time_get(&topology_sema_runTime); sweepStartPacketCount = sm_smInfo.ActCount; if (sm_debug != 0) { (void)printf("."); (void)fflush(stdout); } topo_retry_backoff = 0; #ifndef __VXWORKS__ // sm_peer_quarantined implies sm_state == SM_STATE_NOTACTIVE if (sm_peer_quarantined && sm_state == SM_STATE_NOTACTIVE) { STL_PORT_INFO portInfo; uint8_t path[64]; memset((void*)path, 0, 64); SmpAddr_t addr = SMP_ADDR_CREATE_DR(path); status = SM_Get_PortInfo(fd_sminfo, 1<<24, &addr, &portInfo); if (status != VSTATUS_OK) { IB_LOG_ERROR_FMT(__func__, "Failed to get local port info; cannot transition back to DISCOVERING"); } else if (sm_peer_quarantined && !portInfo.PortStates.s.IsSMConfigurationStarted && portInfo.PortStates.s.PortState > IB_PORT_DOWN) { sm_peer_quarantined = 0; sm_transition(SM_STATE_DISCOVERING); } } #endif if ((sm_state == SM_STATE_DISCOVERING) || (sm_state == SM_STATE_MASTER)) { if (!sweepsPaused) { char tempStr[256]; int prev_topo_errors = topo_errors; int prev_topo_abandon_count = topo_abandon_count; snprintf(tempStr, 256, "TT: DISCOVERY CYCLE START - REASON: %s\n", sweep_reasons[sm_resweep_reason]); #if !defined(__VXWORKS__) IB_LOG_INFINI_INFO0(tempStr); #else if (smDebugPerf) { IB_LOG_INFINI_INFO0(tempStr); } #endif sm_resweep_reason = SM_SWEEP_REASON_UNDETERMINED; isSweeping = 1; (void)vs_lock(&new_topology_lock); for (i = 0; sweep_functions[i].func != NULL; i++) { uint64_t tstart; vs_time_get(&tstart); uint32_t pstart = AtomicRead(&smCounters[smCounterSmPacketTransmits].sinceLastSweep); uint32_t rstart = AtomicRead(&smCounters[smCounterPacketRetransmits].sinceLastSweep); sm_sweep_context.psc = sm_psc_g; // explicitly initializing psc for each sweep func status = (sweep_functions[i]).func(&sm_sweep_context); uint64_t tend; vs_time_get(&tend); uint32_t pend = AtomicRead(&smCounters[smCounterSmPacketTransmits].sinceLastSweep); uint32_t rend = AtomicRead(&smCounters[smCounterPacketRetransmits].sinceLastSweep); if (smDebugPerf) { IB_LOG_INFINI_INFO_FMT(__func__, "TT: FUNC: %s: elapsed=%"PRIu64" packets=%u retries=%u status=%u", sweep_functions[i].name, tend - tstart, pend - pstart, rend - rstart, status); } // if the local port was marked down mid-sweep, we're not // going to make progress. reset the short-term quarantine // and force the status to UNRECOVERABLE if (sm_topop->node_head) { Port_t * sm_portp = sm_get_port(sm_topop->node_head, sm_config.port); if (sm_portp && sm_portp->state == IB_PORT_DOWN) { sm_popo_clear_short_quarantine(&sm_popo); status = VSTATUS_UNRECOVERABLE; } } if (status != VSTATUS_OK) { // UNRECOVERABLE errors indicate sweep-local unrecoverable problems. // future sweeps may succeed, but don't attempt progress on abandonment if (status != VSTATUS_UNRECOVERABLE && status != VSTATUS_NOT_MASTER) { // catch-all for any error condition that did not adjust the global topology // error counter or topology abandonment counter. // if the timeout limit is exceeded, don't cause a brute-force sweep, // but allow one to progress if it's already triggered. // // lid space exhaustion should also avoid brute force sweeps in // favor of abandoning (at normal sweep intervals) until the // problem is corrected // if (!lid_space_exhausted && status != VSTATUS_TIMEOUT_LIMIT) { if (topo_errors == prev_topo_errors) topo_errors++; if (topo_abandon_count == prev_topo_abandon_count) topo_abandon_count++; } if (topo_errors > sm_config.topo_errors_threshold && topo_abandon_count > sm_config.topo_abandon_threshold) { // abandonment threshold exceeded, so ignore error conditions and // continue the sweep of the entire fabric continue; } } // If the sweep is unrecoverable, stop being master if (status == VSTATUS_UNRECOVERABLE) { (void)sm_transition(SM_STATE_DISCOVERING); } /* * PR# 101511 * new topology is most likely incomplete. This can be caused when a * switch, discovered by sweep_discovery, is removed from fabric before * topology_assigments is called. The window of opportunity for hitting * this grows with the size of the fabric. */ newTopologyValid = 0; // new topology is not reliable, re-sweep if (status != VSTATUS_NOT_MASTER) { if (!lid_space_exhausted) IB_LOG_WARNRC("TT: too many errors during sweep, will re-sweep in a few seconds rc:", status); else IB_LOG_WARNRC("TT: LID space exhausted, rc:", status); } break; } if(topology_main_exit == 1){ #ifdef __VXWORKS__ ESM_LOG_ESMINFO("Topology Task exiting OK.", 0); #endif newTopologyValid = 0; break; } } /* clear topology error counters and sweep abandonment counters */ if (topo_abandon_count > sm_config.topo_abandon_threshold || topo_errors == 0) topo_abandon_count = 0; topo_errors = 0; /* bump dispatcher passcount to ensure inflight requests handled appropriately */ sm_dispatch_bump_passcount(&sm_asyncDispatch); /* copy new topology view to old only if complete */ if (newTopologyValid) { oldSwitchCount = old_topology.num_sws; oldHfiCount = (old_topology.num_nodes - old_topology.num_sws); oldEndPortCount = old_topology.num_endports; oldTotalPorts = old_topology.num_ports; sm_compactSwitchSpace(&sm_newTopology, &new_switchesInUse); sm_clearSwitchPortChange(&sm_newTopology); (void)topology_copy(); if (previousVfPtr) { //release old vfs_ptr releaseVirtualFabricsConfig(previousVfPtr); updatedVirtualFabrics = NULL; previousVfPtr = NULL; } // IB_LOG_INFINI_INFO("SM Pool Size= ", vs_pool_size(&sm_pool)); /* Track how many times we do full discovery */ ++topology_passcount; activateInProgress = 0; isSweeping = 0; lid_space_exhausted = FALSE; (void)topology_dump(); /* Send Delayed Pkey Writes now that Topo is in SA */ (void)topology_assignments_delayedpkeys(); /* Send Client Rereg to ports */ (void)topology_reregisters(); } else { /* release allocated storage in bad new topology */ if(!topology_main_exit) { topology_clearNew(); } if (sm_state == SM_STATE_STANDBY || sm_state == SM_STATE_NOTACTIVE) { /* we are no longer the master sm, clear passcount and SA tables */ topology_passcount = 0; clearSaTables(&sm_sweep_context); /* should also clear old_topo on transition away from master */ topology_free_topology(&old_topology, TRUE, FALSE); } } (void)vs_unlock(&new_topology_lock); /* print DG and VF memberships per node */ printDgVfMemberships(); } //skip sweep if sweepsPaused else { newTopologyValid = 0; } if (sm_debug) sm_popo_report(&sm_popo); (void)vs_time_get(&now); if (newTopologyValid) { int newSmCount = sm_dbsync_getSmCount(); int swDelta = ((int)sm_topop->num_sws - oldSwitchCount); int hcaDelta = (((int)sm_topop->num_nodes - (int)sm_topop->num_sws) - oldHfiCount); int epDelta = ((int)sm_topop->num_endports - oldEndPortCount); int tpDelta = ((int)sm_topop->num_ports - oldTotalPorts); int smDelta = (newSmCount - oldSmCount); int haveDelta = (swDelta | hcaDelta | epDelta | tpDelta | smDelta); temp64 = now - topology_sema_runTime; #ifdef __VXWORKS__ if (haveDelta || smDebugPerf || ((sm_config.timer/1000000) >= 300) || ((temp64/1000000) > 60)) { #endif IB_LOG_INFINI_INFO_FMT(__func__, "DISCOVERY CYCLE END. %d SWs, %d HFIs, %d end ports, %d total ports, %d SM(s), %d packets, %d retries, %d.%.3d sec sweep", sm_topop->num_sws, (sm_topop->num_nodes-sm_topop->num_sws), sm_topop->num_endports, sm_topop->num_ports, newSmCount, ((unsigned int)sm_smInfo.ActCount - sweepStartPacketCount), (int)AtomicRead(&smCounters[smCounterPacketRetransmits].sinceLastSweep), (unsigned int)(temp64/1000000), (unsigned int)((temp64 - temp64/1000000*1000000))/1000); #if !defined(__VXWORKS__) if (sm_config.sm_debug_perf) { char buf[128]; FILE *f = fopen("/proc/self/statm", "r"); if (f && fgets(buf,sizeof(buf),f)) { IB_LOG_INFINI_INFO_FMT(__func__, "MEMORY CONSUMPTION: %s",buf); } if (f) fclose(f); } #endif #ifdef __VXWORKS__ if (!shutdown && sm_topop->num_nodes >= MAX_SUBNET_SIZE) { shutdown=1; IB_LOG_ERROR_FMT(__func__, "TT: aborting - fabric size exceeds the %d maximum nodes supported by the ESM", MAX_SUBNET_SIZE); smCsmLogMessage(CSM_SEV_NOTICE, CSM_COND_SM_SHUTDOWN, getMyCsmNodeId(), NULL, "Terminating SM after %d sweeps.", topology_passcount); sm_control_shutdown(NULL); exit(0); } } #endif SET_PEAK_COUNTER(smMaxSweepTime, (uint32)(temp64/1000)); #ifndef __VXWORKS__ if (smDumpCounters) { char *buff = sm_print_counters_to_buf(); FILE *f = fopen(smDumpCounters,"a"); if (f && buff) fputs(buff, f); if (f) fclose(f); if (buff) vs_pool_free(&sm_pool, (void*)buff); } #endif if (smTerminateAfter && topology_passcount >= smTerminateAfter) { smCsmLogMessage(CSM_SEV_NOTICE, CSM_COND_SM_SHUTDOWN, getMyCsmNodeId(), NULL, "Terminating SM after %d sweeps.", topology_passcount); IB_FATAL_ERROR_NODUMP("Terminating SM."); } else if ( (topology_passcount > 1) && ( haveDelta )) { if (sweepNodeAppearanceInfoMsgCount != 0) { smCsmLogMessage(CSM_SEV_NOTICE, CSM_COND_APPEARANCE, getMyCsmNodeId(), NULL, "An additional %d nodes appeared in the fabric and were logged " "as INFO messages", sweepNodeAppearanceInfoMsgCount); } if (sweepNodeDisappearanceInfoMsgCount != 0) { smCsmLogMessage(CSM_SEV_NOTICE, CSM_COND_DISAPPEARANCE, getMyCsmNodeId(), NULL, "An additional %d nodes disappeared from the fabric and were logged " "as INFO messages", sweepNodeDisappearanceInfoMsgCount); } smCsmLogMessage(CSM_SEV_NOTICE, CSM_COND_FABRIC_SUMMARY, getMyCsmNodeId(), NULL, "Change Summary: %d SWs %s, %d HFIs %s, %d end ports %s, " "%d total ports %s, %d SMs %s", abs(swDelta), swDelta >= 0 ? "appeared" : "disappeared", abs(hcaDelta), hcaDelta >= 0 ? "appeared" : "disappeared", abs(epDelta), epDelta >= 0 ? "appeared" : "disappeared", abs(tpDelta), tpDelta >= 0 ? "appeared" : "disappeared", abs(smDelta), smDelta >= 0 ? "appeared" : "disappeared"); } if (haveDelta) smCsmLogMessage(CSM_SEV_INFO, CSM_COND_FABRIC_SUMMARY, getMyCsmNodeId(), NULL, "%d SWs, %d HFIs, %d end ports, %d total ports, %d SM(s)", sm_topop->num_sws, (sm_topop->num_nodes-sm_topop->num_sws), sm_topop->num_endports, sm_topop->num_ports, newSmCount); if (sm_config.config_consistency_check_level == CHECK_ACTION_CCC_LEVEL) newSmActiveCount = sm_dbsync_getActiveSmCount(); else newSmActiveCount = newSmCount; if ((oldSmActiveCount > 1) && (newSmActiveCount == 1)) smCsmLogMessage(CSM_SEV_WARNING, CSM_COND_REDUNDANCY_LOST, getMyCsmNodeId(), NULL, "Only one SM remains in fabric"); else if ((topology_passcount == 1) && (newSmActiveCount == 1)) IB_LOG_INFINI_INFO_FMT(__func__, "SM redundancy not available"); else if ((oldSmActiveCount == 1) && (newSmActiveCount > 1)) smCsmLogMessage(CSM_SEV_NOTICE, CSM_COND_REDUNDANCY_RESTORED, getMyCsmNodeId(), NULL, "%d SM's now online in fabric", newSmActiveCount); if (sm_config.config_consistency_check_level == CHECK_ACTION_CCC_LEVEL) oldSmActiveCount = newSmActiveCount; // if we've found more HFI's than we're configured for, issue a warning if (sm_topop->num_endports > sm_config.subnet_size) { IB_LOG_WARN_FMT(__func__, "the number of HFI EndPorts %d on the fabric exceeds the configured subnet size %d", sm_topop->num_endports, sm_config.subnet_size); } #if 0 if (smDebugPerf || saDebugPerf) sm_print_counters_to_stream(stdout); #endif sm_process_sweep_counters(); /* if topology change allow a rediscovery of CCA */ if (haveDelta) cca_discovery_count = 0; if (sm_popo_clear_short_quarantine(&sm_popo)) sm_request_resweep(0, 0, SM_SWEEP_REASON_UNQUARANTINE); } else if (!sweepsPaused){ IB_LOG_INFINI_INFO_FMT(__func__, "DISCOVERY CYCLE FAIL. %d SWs, %d HFIs, %d end ports, %d total ports, %d packets, %d retries", sm_topop->num_sws, (sm_topop->num_nodes-sm_topop->num_sws), sm_topop->num_endports, sm_topop->num_ports, ((unsigned int)sm_smInfo.ActCount - sweepStartPacketCount), (int)AtomicRead(&smCounters[smCounterPacketRetransmits].sinceLastSweep)); } } else { /* clear the SA tables if necessary */ clearSaTables(&sm_sweep_context); topology_passcount=0; /* should also clear old_topo on transition away from master */ topology_free_topology(&old_topology, TRUE, FALSE); } (void)vs_time_get(&now); if (newTopologyValid && !topology_resweep) { forceRebalanceNextSweep = 0; if (sm_config.timer != 0) { topology_wakeup_time = now + sm_config.timer; } else { topology_wakeup_time = 0; } } else { if (lid_space_exhausted){ if (sm_config.timer != 0){ topology_wakeup_time = now + sm_config.timer; } else topology_wakeup_time = 0; } else { const uint32_t factor = topo_retry_backoff ? topo_retry_backoff_interval : 5; topology_wakeup_time = now + VTIMER_1S * factor; // re-sweep after delay. } setResweepReason(SM_SWEEP_REASON_FAILED_SWEEP); } if (newTopologyValid) { // configure congestion control outside of the sweep // this will abort if another sweep is triggered (void)topology_congestion(); } sm_popo_end_sweep(&sm_popo); } // End of while(1) if (sm_psc_g) { psc_cleanup(sm_psc_g); } /* clear the isSM bit from our port */ sm_clearIsSM(); #ifdef __VXWORKS__ // We need to clean the globals here. topology_uninitialize(); #endif cs_vsema(&topo_terminated_sema); IB_EXIT(__func__, VSTATUS_OK); //IB_LOG_INFINI_INFO0("topology_main thread: Exiting OK"); return; } #ifdef __VXWORKS__ void topology_uninitialize(void) { topology_wakeup_time = 0; bitset_free(&old_switchesInUse); bitset_free(&new_switchesInUse); bitset_free(&new_endnodesInUse); (void)vs_lock(&new_topology_lock); topology_free_topology(&old_topology, TRUE, TRUE); (void)vs_unlock(&new_topology_lock); memset(&old_topology, 0, sizeof(old_topology)); memset(&sm_newTopology, 0, sizeof(sm_newTopology)); sm_topop = &sm_newTopology; topology_once = -1; topology_changed = 0; topology_switch_port_changes = 0; topology_cost_path_changes = 0; topology_passcount = 0ull; sm_dispatch_destroy(&sm_asyncDispatch); sm_removedEntities_destroy(); sm_popo_destroy(&sm_popo); } #endif static int verify_admin_membership(Port_t *portp) { int vfi, dg; VF_t *vfp = NULL; int okay = 0; (void)vs_rdlock(&old_topology_lock); if (old_topology.vfs_ptr) { // Find the Admin VF. for (vfi=0; vfi < old_topology.vfs_ptr->number_of_vfs_all; vfi++) { if (old_topology.vfs_ptr->v_fabric_all[vfi].standby) continue; // Multiple VFs can have the Admin PKey, but only one can have the SA application if (old_topology.vfs_ptr->v_fabric_all[vfi].apps.select_sa) { vfp = &old_topology.vfs_ptr->v_fabric_all[vfi]; break; } } if (vfp == NULL) { (void)vs_rwunlock(&old_topology_lock); IB_LOG_ERROR_FMT(__func__,"Could not identify the Admin VF."); goto done; } IB_LOG_INFO_FMT(__func__,"\"%s\" is the admin VF.", vfp->name); for (dg=0; dg < vfp->number_of_full_members; dg++) { int dgIdx = vfp->full_member[dg].dg_index; if (dgIdx != -1) { if(isDgMember(dgIdx,portp->portData)) { okay=1; break; } } } // If security is off, then all members are full members if (!okay && !vfp->security) for (dg=0; dg < vfp->number_of_limited_members; dg++) { int dgIdx = vfp->limited_member[dg].dg_index; if (dgIdx != -1) { if(isDgMember(dgIdx,portp->portData)) { okay=1; break; } } } if (!okay) { IB_LOG_ERROR_FMT(__func__, "SM's port is not a full member of the \"%s\" VF.", vfp->name); } else { IB_LOG_INFO_FMT(__func__, "SM's port is a full member of the \"%s\" fabric via the" "\"%s\" group.", vfp->name, vfp->full_member[dg].member); } } else { IB_LOG_ERROR_FMT(__func__,"Unable to validate SM's membership in Admin VF."); } done: (void)vs_rwunlock(&old_topology_lock); return okay; } static Status_t _query_local_port(uint8_t * lastMsg, STL_NODE_INFO * nodeInfo, STL_PORT_INFO * portInfo) { Status_t status; uint8_t path[64] = { 0 }; SmpAddr_t addr = SMP_ADDR_CREATE_DR(path); // get PortInfo record of the local port status = SM_Get_PortInfo(fd_topology, (1<<24) | STL_SM_CONF_START_ATTR_MOD, &addr, portInfo); if (status != VSTATUS_OK) { IB_WARN_NOREPEAT(*lastMsg, 1, "can't get PortInfo, sleeping rc: %u", status); return status; } if (portInfo->PortStates.s.PortState < IB_PORT_INIT) { // Wait until the port is at least in INIT because the LNI process // may change the local pkey table and other port information. IB_WARN_NOREPEAT(*lastMsg, 2, "Waiting for port (portnum=%d) to reach state INIT (portstate=%s)...", sm_config.port, IbPortStateToText(portInfo->PortStates.s.PortState)); return VSTATUS_UNRECOVERABLE; } // Get NodeInfo record of the local port status = SM_Get_NodeInfo(fd_topology, 0, &addr, nodeInfo); if (status != VSTATUS_OK) { IB_WARN_NOREPEAT(*lastMsg, 3, "can't get NodeInfo, sleeping rc: %u", status); return status; } // Verify that the port has MgmtAllowed authority. if (nodeInfo->NodeType == NI_TYPE_SWITCH) { // get SwitchInfo record of the local switch STL_SWITCH_INFO switchInfo; status = SM_Get_SwitchInfo(fd_topology, 0, &addr, &switchInfo); if (status != VSTATUS_OK) { IB_WARN_NOREPEAT(*lastMsg, 4, "can't get local SwitchInfo, sleeping rc: %u", status); return status; } if (!switchInfo.u2.s.EnhancedPort0) { IB_WARN_NOREPEAT(*lastMsg, 5, "MgmtAllowed not enabled for the local Embedded SM, sleeping rc: %u", status); return VSTATUS_MISMATCH; } } else if (nodeInfo->NodeType == NI_TYPE_CA) { if (portInfo->PortNeighborMode.NeighborNodeType == STL_NEIGH_NODE_TYPE_HFI) { // Back to back configuration. sm_hfi_direct_connect = TRUE; IB_LOG_INFO_FMT(__func__, "Host SM's port is connected to an hfi port."); } else if (portInfo->PortNeighborMode.NeighborNodeType == STL_NEIGH_NODE_TYPE_SW) { // Normal fabric configuration. sm_hfi_direct_connect = FALSE; if (!portInfo->PortNeighborMode.MgmtAllowed) { IB_WARN_NOREPEAT(*lastMsg, 6, "Host SM's port is connected to a switch port but MgmtAllowed is not set. sleeping"); return VSTATUS_UNRECOVERABLE; } else { IB_LOG_INFO_FMT(__func__, "Host SM's port is connected to a switch port."); } } else { IB_ERROR_NOREPEAT(*lastMsg, 7, "SM's port is connected to an unknown type of node (NeighborNodeType = %d)", portInfo->PortNeighborMode.NeighborNodeType); return VSTATUS_UNRECOVERABLE; } } else { IB_WARN_NOREPEAT(*lastMsg, 8, "SM is running on an unknown node type. sleeping rc: %u", status); return VSTATUS_MISMATCH; } return status; } Status_t sweep_initialize(SweepContext_t *sweep_context) { uint8_t path[64] = { 0 }; // Used by the IB_*_NOREPEAT macros. Declared static in case the function // gets called multiple times in a single sweep. static uint8_t lastMsg = 0; #if defined(CAL_IBACCESS) uint32_t mask; #endif Status_t status; STL_PORT_INFO portInfo; STL_NODE_INFO nodeInfo; Port_t *portp; Node_t *nodep; SmpAddr_t addr; IB_ENTER(__func__, 0, 0, 0, 0); // // Loop until we've successfully talked to the local port. In general, if // we fail to get a MAD, or if a status check fails, wait a few seconds // and re-start the loop. // while (TRUE) { // Stop if we've been externally terminated. if(topology_main_exit) { #ifdef __VXWORKS__ ESM_LOG_ESMINFO("Topology Task exiting OK.", 0); #endif return VSTATUS_UNRECOVERABLE; } // if cumulative timeout is reached while we're in this loop for // whatever reason, queries will always fail and we'll livelock. reset // cumulative timeout to avoid this. this also acts as the first reset // of the sweep, clearing any cumulative timeout incurred between // sweeps sm_popo_reset_errors(&sm_popo); status = _query_local_port(&lastMsg, &nodeInfo, &portInfo); if (status == VSTATUS_OK) break; // Local Port Failures, should stop being master if (status == VSTATUS_UNRECOVERABLE) { (void)sm_transition(SM_STATE_DISCOVERING); } vs_thread_sleep(5 * VTIMER_1S); } // // Clear and initialize the new topology structure. // Note that our caller must hold the new topology lock. // (void)memset((void *)&sm_newTopology, 0, sizeof(Topology_t)); // // Update the new topology's virtual fabrics ptr and save off the old ptr // to be deleted later // if (updatedVirtualFabrics) { sm_newTopology.vfs_ptr = updatedVirtualFabrics; previousVfPtr = old_topology.vfs_ptr; } else { sm_newTopology.vfs_ptr = old_topology.vfs_ptr; } sm_newTopology.maxMcastMtu = STL_MTU_MAX; sm_newTopology.maxMcastRate = IB_STATIC_RATE_MAX; bitset_clear_all(&new_switchesInUse); bitset_clear_all(&new_endnodesInUse); // Initialize the quick maps that store the sorted GUID lists status = vs_pool_alloc(&sm_pool, sizeof(cl_qmap_t), (void *)&sm_newTopology.nodeIdMap); if (status != VSTATUS_OK) IB_FATAL_ERROR_NODUMP("Failed to allocate node ID map"); status = vs_pool_alloc(&sm_pool, sizeof(cl_qmap_t), (void *)&sm_newTopology.nodeMap); if (status != VSTATUS_OK) IB_FATAL_ERROR_NODUMP("Failed to allocate node map"); status = vs_pool_alloc(&sm_pool, sizeof(cl_qmap_t), (void *)&sm_newTopology.portMap); if (status != VSTATUS_OK) IB_FATAL_ERROR_NODUMP("Failed to allocate port map"); status = vs_pool_alloc(&sm_pool, sizeof(cl_qmap_t), (void *)&sm_newTopology.quarantinedNodeMap); if (status != VSTATUS_OK) IB_FATAL_ERROR_NODUMP("Failed to allocate quarantined node map"); status = vs_pool_alloc(&sm_pool, sizeof(cl_qmap_t), (void *)&sm_newTopology.switchLids); if (status != VSTATUS_OK) IB_FATAL_ERROR_NODUMP("Failed to allocate switch lid map"); cl_qmap_init(sm_newTopology.nodeIdMap, NULL); cl_qmap_init(sm_newTopology.nodeMap, NULL); cl_qmap_init(sm_newTopology.portMap, NULL); cl_qmap_init(sm_newTopology.quarantinedNodeMap, NULL); cl_qmap_init(sm_newTopology.switchLids, NULL); sm_newTopology.nodeArray = NULL; memset(&sm_newTopology.preDefLogCounts, 0, sizeof(PreDefTopoLogCounts)); status = vs_wrlock(&old_topology_lock); if (status != VSTATUS_OK) IB_FATAL_ERROR_NODUMP("Failed to acquire old topology lock"); if (sm_topop->routingModule == NULL && old_topology.routingModule != NULL) { if ((status = vs_pool_alloc(&sm_pool, sizeof(RoutingModule_t), (void *)&sm_topop->routingModule)) != VSTATUS_OK) { goto unlock_bail; } memset(sm_topop->routingModule, 0, sizeof(RoutingModule_t)); if (old_topology.routingModule->copy) { status = old_topology.routingModule->copy(sm_topop->routingModule, old_topology.routingModule); if (status != VSTATUS_OK) { goto unlock_bail; } } else { memcpy(sm_topop->routingModule, old_topology.routingModule, sizeof(RoutingModule_t)); } } unlock_bail: vs_rwunlock(&old_topology_lock); if (status != VSTATUS_OK) IB_FATAL_ERROR_NODUMP("Failed to release old topology lock"); if (sm_state == SM_STATE_DISCOVERING) { // Local port connection to neighbor switch (root switch) disrupted for some reason. // LFTs might be incomplete (especially if the root switch is an unmanaged switch that was rebooted), // so indicate that a fabric change has been detected to ensure update of LFTs. topology_changed = 1; } status = sm_setup_local_node(sm_topop, &preDefTopology); if (status != VSTATUS_OK) { IB_ERROR_NOREPEAT(lastMsg,15, "Can't set up my local node, sleeping rc: %u", status); return VSTATUS_UNRECOVERABLE; } nodep = sm_topop->node_head; if (!nodep) { IB_ERROR_NOREPEAT(lastMsg,16,"Local node has not been initialized, sleeping rc: %u", status); return VSTATUS_UNRECOVERABLE; } if (!sm_valid_port((portp = sm_get_port(nodep,sm_config.port)))) { IB_ERROR_NOREPEAT(lastMsg,17,"Failed to get a valid SM port, sleeping"); return VSTATUS_UNRECOVERABLE; } // // Validate our Admin VF membership. We could not do this until after // sm_setup_node() had been run on our local node. // if (!verify_admin_membership(portp)) { IB_ERROR_NOREPEAT(lastMsg,18,"SM port is not a full member of the admin VF, " "sleeping rc: %u", VSTATUS_BAD); vs_thread_sleep(5 * VTIMER_1S); return VSTATUS_UNRECOVERABLE; } // // Always set the pkey here. In the B2B case it isn't set in LNI, // in the switch case, the pkey is set in LNI but might have been // cleared by another SM after LNI but before we started. // status = sm_set_local_port_pkey(&nodeInfo); if (status != VSTATUS_OK) { IB_ERROR_NOREPEAT(lastMsg,19, "can't set PKey table, sleeping rc: %u", status); return VSTATUS_UNRECOVERABLE; } // // Verify we can talk to our neighbor. // Note that there's no equivalent check for the ESM because switch port 0 // doesn't have a neighbor. // if (nodeInfo.NodeType == NI_TYPE_CA) { STL_NODE_INFO neighborNodeInfo; // Build a 1 hop DR path. path[0]++; path[path[0]] = sm_config.port; // Verify we can talk to our neighbor. SMP_ADDR_SET_DR(&addr, path); status = SM_Get_NodeInfo(fd_topology, 0, &addr, &neighborNodeInfo); if (status != VSTATUS_OK) { IB_ERROR_NOREPEAT(lastMsg,20, "Can't get neighbor NodeInfo, sleeping rc: %u", status); return VSTATUS_UNRECOVERABLE; } } // Announce that we are an SM. Note that this is safe to do on each sweep. #if defined(IB_STACK_OPENIB) status = ib_enable_is_sm(); if (status != VSTATUS_OK) { IB_ERROR_NOREPEAT(lastMsg,21, "Can't set isSM, sleeping rc: %u", status); return VSTATUS_UNRECOVERABLE; } #elif defined(CAL_IBACCESS) mask = portInfo.CapabilityMask.AsReg32 | PI_CM_IS_SM; status = sm_set_CapabilityMask(fd_topology, sm_config.port, mask); if (status != VSTATUS_OK) { IB_ERROR_NOREPEAT(lastMsg,21, "can't set isSM, sleeping rc: %u", status); return VSTATUS_UNRECOVERABLE; } #endif // Rather than get the port info again, just to get the updated capmask, // let's just set the bit in the capmask we've already got: portp->portData->capmask |= PI_CM_IS_SM; portp->portData->portInfo.CapabilityMask.AsReg32 |= PI_CM_IS_SM; topology_wakeup_time = 0ull; // We've completed successfully, clear the IB_*_ONCE tracking. lastMsg = 0; IB_EXIT(__func__, VSTATUS_OK); return(VSTATUS_OK); } /* * Determine wheter we should be the MAster of the fabric using * the info collected during the discovery phase. */ Status_t sweep_transition(SweepContext_t *sweep_context) { Status_t status; uint8_t doHandover=0, suspendDiscovery=0; uint8_t willHandover=0; STL_SM_INFO smInfoCopy; SmRecp smrecp; CS_HashTableItr_t itr; SmRecp topSm=NULL; IB_ENTER(__func__, 0, 0, 0, 0); /* * Find highest priority SM in list with the proper SMKey other than us * We are the first entry in the list */ if (cs_hashtable_count(smRecords.smMap) > 1) { sm_saw_another_sm = TRUE; cs_hashtable_iterator(smRecords.smMap, &itr); do { smrecp = cs_hashtable_iterator_value(&itr); /* skip ourselves, inactive SM's, and SM's without the proper SMKey */ if (smrecp->portguid == sm_smInfo.PortGUID || /* this is our entry */ smrecp->smInfoRec.SMInfo.u.s.SMStateCurrent == SM_STATE_NOTACTIVE || smrecp->smInfoRec.SMInfo.SM_Key != sm_smInfo.SM_Key) { continue; } else if (topSm) { if (topSm->smInfoRec.SMInfo.u.s.Priority > smrecp->smInfoRec.SMInfo.u.s.Priority) { /* topSm is still the one */ } else if (topSm->smInfoRec.SMInfo.u.s.Priority < smrecp->smInfoRec.SMInfo.u.s.Priority) { topSm = smrecp; } else if (topSm->smInfoRec.SMInfo.PortGUID > smrecp->smInfoRec.SMInfo.PortGUID) { topSm = smrecp; } } else { topSm = smrecp; } } while (cs_hashtable_iterator_advance(&itr)); } if (!topSm) { /* we are it; become or stay master */ if (sm_state != SM_STATE_MASTER) (void)sm_transition(SM_STATE_MASTER); // no other SM and we're master... re-elevate our priority sm_elevatePriority(); return(VSTATUS_OK); } /* * Determine who should be MASTER based on the rules outlined in Infiniband * Architecture Release 1.2 Volume 1 - General Specification, section 14.4.1 */ switch (sm_smInfo.u.s.SMStateCurrent) { case SM_STATE_DISCOVERING: switch (topSm->smInfoRec.SMInfo.u.s.SMStateCurrent) { case SM_STATE_MASTER: /* make the transition to STANDBY now, remote will decide if we should takeover */ IB_LOG_INFO_FMT(__func__, "%s STANDBY, found MASTER SM %s : "FMT_U64, (sm_smInfo.u.s.SMStateCurrent==SM_STATE_DISCOVERING) ? "Becoming" : "Remaining in", topSm->nodeDescString, topSm->smInfoRec.SMInfo.PortGUID); (void)memcpy((void *)sm_topop->sm_path, (void *)topSm->path, 64); (void)sm_transition(SM_STATE_STANDBY); break; case SM_STATE_STANDBY: case SM_STATE_DISCOVERING: /* determine who should become master based on priority/Guid rules */ if (sm_smInfo.u.s.Priority > topSm->smInfoRec.SMInfo.u.s.Priority || (sm_smInfo.u.s.Priority == topSm->smInfoRec.SMInfo.u.s.Priority && sm_smInfo.PortGUID < topSm->smInfoRec.SMInfo.PortGUID)) { /* make the transition to MASTER now */ IB_LOG_INFO_FMT(__func__, FMT_U64" becoming MASTER over remote SM %s : "FMT_U64, sm_smInfo.PortGUID, topSm->nodeDescString, topSm->smInfoRec.SMInfo.PortGUID); (void)sm_transition(SM_STATE_MASTER); } else { /* make the transition to STANDBY now */ IB_LOG_INFO_FMT(__func__, FMT_U64" becoming STANDBY, remote %s : "FMT_U64" will be MASTER", sm_smInfo.PortGUID, topSm->nodeDescString, topSm->smInfoRec.SMInfo.PortGUID); (void)memcpy((void *)sm_topop->sm_path, (void *)topSm->path, 64); (void)sm_transition(SM_STATE_STANDBY); } break; default: IB_LOG_INFINI_INFO_FMT(__func__, "Remote SM %s : "FMT_U64" is not Active", topSm->nodeDescString, topSm->smInfoRec.SMInfo.PortGUID); break; // do nothing for Not Active state } /* end switch on your_state */ break; case SM_STATE_MASTER: switch (topSm->smInfoRec.SMInfo.u.s.SMStateCurrent) { case SM_STATE_MASTER: case SM_STATE_STANDBY: /* determine who should be master based on priority/Guid rules */ if (sm_smInfo.u.s.Priority < topSm->smInfoRec.SMInfo.u.s.Priority || (sm_smInfo.u.s.Priority == topSm->smInfoRec.SMInfo.u.s.Priority && sm_smInfo.PortGUID > topSm->smInfoRec.SMInfo.PortGUID)) { willHandover = 1; // will eventually handover once dbsync done /* handover to any master SM and to stanby SMs that support synchronization if they're in synchronized state */ char *reason; if (sm_dbsync_isUpToDate(topSm->smInfoRec.SMInfo.PortGUID, &reason)) { doHandover = 1; } else { IB_LOG_INFINI_INFO_FMT(__func__, "Delaying handover to remote standby SM %s : "FMT_U64": %s", topSm->nodeDescString, topSm->smInfoRec.SMInfo.PortGUID,reason); } } else if (topSm->smInfoRec.SMInfo.u.s.SMStateCurrent == SM_STATE_MASTER) { /* * Remote, if Master, is expected to relinquish his part of subnet by sending us a HANDOVER */ IB_LOG_WARN_FMT(__func__, "Suspending Discovery - expecting handover from Master SM %s : "FMT_U64, topSm->nodeDescString, topSm->smInfoRec.SMInfo.PortGUID); /* suspend discovery until remote hands over */ suspendDiscovery = 1; } break; case SM_STATE_DISCOVERING: if (sm_smInfo.u.s.Priority < topSm->smInfoRec.SMInfo.u.s.Priority || (sm_smInfo.u.s.Priority == topSm->smInfoRec.SMInfo.u.s.Priority && sm_smInfo.PortGUID > topSm->smInfoRec.SMInfo.PortGUID)) { willHandover = 1; // will eventually handover once discovers IB_LOG_INFINI_INFO_FMT(__func__, "Remote SM %s : "FMT_U64" is still DISCOVERING, will catch next sweep", topSm->nodeDescString, topSm->smInfoRec.SMInfo.PortGUID); } break; default: IB_LOG_INFINI_INFO_FMT(__func__, "Remote SM %s : "FMT_U64" is not Active", topSm->nodeDescString, topSm->smInfoRec.SMInfo.PortGUID); break; // do nothing for Not Active state } /* end switch on your_state */ break; case SM_STATE_STANDBY: IB_LOG_WARN_FMT(__func__, "The SM on this node["FMT_U64"] is in STANDBY and should just be polling the master", sm_smInfo.PortGUID); break; default: IB_LOG_INFINI_INFO_FMT(__func__, "The SM on this node["FMT_U64"] is not Active", sm_smInfo.PortGUID); break; /* should not be here if we're not active */ } /* end switch on my_state */ /* * If we are relinquishing MASTERness of the subnet to the other guy, * we must send him a HANDOVER request. */ if (doHandover) { sm_smInfo.ActCount++; smInfoCopy = sm_smInfo; SmpAddr_t addr = SMP_ADDR_CREATE_DR(topSm->path); status = SM_Set_SMInfo(fd_topology, SM_AMOD_HANDOVER, &addr, &smInfoCopy, sm_config.mkey); if (status != VSTATUS_OK) { IB_LOG_ERROR_FMT(__func__, "could not perform HANDOVER to remote SM %s : "FMT_U64, topSm->nodeDescString, topSm->smInfoRec.SMInfo.PortGUID); } else { IB_LOG_INFINI_INFO_FMT(__func__, "sent HANDOVER to remote SM %s : "FMT_U64, topSm->nodeDescString, topSm->smInfoRec.SMInfo.PortGUID); /* set path to new master now but don't change state till ACK received in async */ (void)memcpy((void *)sm_topop->sm_path, (void *)topSm->path, 64); } /* suspend discovery when handing over */ suspendDiscovery = 1; /* set handover flag to indicate async thread (sm_fsm.c) that we have processed the handover. * do this even in case of failing to successfully send the handover, otherwise async thread * will not trigger a sweep for handover */ (void)vs_lock(&handover_sent_lock); handover_sent = 1; (void)vs_unlock(&handover_sent_lock); } else if (sm_state == SM_STATE_MASTER && ! willHandover) { // we don't plan to handover and we're master... re-elevate our priority sm_elevatePriority(); } /* * stop discovery if not master or dual master * In dual master case, we will suspend discovery actions * until remote hands over control of it's portion of subnet */ if (sm_state != SM_STATE_MASTER || suspendDiscovery) status = VSTATUS_NOT_MASTER; else { status = VSTATUS_OK; } IB_EXIT(__func__, status); return(status); } /* sweep_transition */ Status_t sweep_resolve(SweepContext_t *sweep_context) { int max_lid; int delta; Node_t *nodep; Port_t *portp; IB_ENTER(__func__, 0, 0, 0, 0); // // Setup the basic LID information for the topology. // if (!sm_valid_port((portp = sm_get_port(sm_topop->node_head,sm_config.port)))) { IB_LOG_ERROR0("failed to get SM port"); IB_EXIT(__func__, VSTATUS_BAD); return(VSTATUS_BAD); } // It is probably unnecessay to update or assign the SM port's LID here // as if LID updating/assignment failed in sweep_discovery(), execution // wouldn't get here. But should not cause any harm to do it again here int newLidCount; if (sm_update_or_assign_lid(portp, 1, &newLidCount, NULL) != VSTATUS_OK) return VSTATUS_BAD; topology_changed |= !!(newLidCount); // // This routine tries to reconcile the old view of the fabric (pointed // to by 'old_topology') with the new view of the fabric (pointed to // by 'sm_newTopology'). We try to keep everything the same between // the 2 view in order to not disturb things that are already in place. // // // If we aren't the master SM, then we go no further. // if (sm_state != SM_STATE_MASTER) { IB_EXIT(__func__, VSTATUS_NOT_MASTER); return(VSTATUS_NOT_MASTER); } Status_t s = sm_lidmap_update_missing(); if (s != VSTATUS_OK) return s; // // For every link that is up and doesn't have a LID assigned, we need to // give it a range of LIDs. // for_all_nodes(&sm_newTopology, nodep) { for_all_end_ports(nodep, portp) { if (!sm_valid_port(portp) || portp->state <= IB_PORT_DOWN) { continue; } int newLidCount; Node_t *neighbor = sm_find_node(&sm_newTopology, portp->nodeno); if ( (s = sm_update_or_assign_lid(portp, 1, &newLidCount, neighbor)) != VSTATUS_OK) { sm_mark_link_down(&sm_newTopology, portp); if(lid_space_exhausted) return s; } if (newLidCount) { sm_mark_new_endnode(nodep); topology_changed = 1; } } } // // Find the maximum LID assigned for using in the LFT later. // sm_newTopology.maxLid = 0; for_all_nodes(&sm_newTopology, nodep) { for_all_end_ports(nodep, portp) { if (!sm_valid_port(portp) || portp->state <= IB_PORT_DOWN) { continue; } if ((portp->portData->lid <= STL_GET_UNICAST_LID_MAX()) && (portp->portData->lid != RESERVED_LID) && (portp->portData->lid != STL_LID_PERMISSIVE)) { delta = 1 << portp->portData->lmc; max_lid = portp->portData->lid + delta - 1; if (max_lid > sm_newTopology.maxLid) { sm_newTopology.maxLid = max_lid; } if (nodep->nodeInfo.NodeType == NI_TYPE_SWITCH){ //insert into switch list if (cl_qmap_insert(sm_newTopology.switchLids, (uint64_t)portp->portData->lid, &nodep->switchLidMapObj.item) != &nodep->switchLidMapObj.item) { IB_LOG_WARN_FMT(__func__, "Error adding switch LID 0x%x to tree. Already in tree!", portp->portData->lid); } else { cl_qmap_set_obj(&nodep->switchLidMapObj, nodep); } } } } } if (smDebugPerf) IB_LOG_INFINI_INFO_FMT(__func__, "max lid 0x%08x", sm_newTopology.maxLid); IB_EXIT(__func__, VSTATUS_OK); return(VSTATUS_OK); } Status_t topology_sm_port_init_failure() { Status_t status=VSTATUS_UNRECOVERABLE; topo_errors = 1; topo_abandon_count++; /* PR 111089 - For HSM Enable retry backoff trying in multiples of 5s * with an upper limit of 15s. */ sm_port_retry_count++; topo_enable_retry_backoff(5, 15, 0, sm_port_retry_count); IB_LOG_ERROR_FMT(__func__, "Unable to initialize the local port, please check the state of the SM device"); return(status); } /* Initialize port 0 of switches and setup LFTs using mixed LR-DR SMPs*/ Status_t topology_setup_switches_LR_DR() { SwitchList_t root_switch; Status_t status; Port_t *portp; int rebalance = forceRebalanceNextSweep; int routing_needed = 1; int route_root_switch = 0; status = topology_setup_routing_cost_matrix(); if (status == VSTATUS_KNOWN) { routing_needed = 0; /* Known topology i.e no changes in topology, old lft data was copied. No new LFT programing required */ } else if (status != VSTATUS_OK) { IB_LOG_INFINI_INFO_FMT(__func__, "Routing calculations failed"); return status; } else { if (sm_config.force_rebalance) rebalance = 1; routing_needed = 1; } if (rebalance) routing_needed = 1; /* First initialize and assign LID to the SM port so that SM can send/recv LR SMPs*/ portp = sm_get_port(sm_topop->node_head, sm_config.port); if (!sm_valid_port(portp)) { IB_LOG_WARN_FMT(__func__, "Failed to get SM's port "FMT_U64, sm_topop->node_head->nodeInfo.NodeGUID); return VSTATUS_BAD; } /* sm_initialize_port_LR_DR called with NULL psc and NULL fd for now. Once switch programming is performed in parallel, the NULL will be replaced */ /* with the psc specific mai->fd. */ status = sm_initialize_port_LR_DR(NULL, NULL, sm_topop, sm_topop->node_head, portp); if (status != VSTATUS_OK) { /* we are unable to initialize the local port */ return topology_sm_port_init_failure(); } else { sm_port_retry_count = 0; } /* Check if we have any switches at all - HSM back to back with another host */ if (sm_topop->num_sws == 0) return VSTATUS_OK; if (sm_topop->routingModule->funcs.init_switch_routing) { status = sm_topop->routingModule->funcs.init_switch_routing(sm_topop, &routing_needed, &rebalance); if (status != VSTATUS_OK) { IB_LOG_ERROR_FMT(__func__, "Switch forwarding table initialization failed. status : %d", status); return status; } } /* First program the root switch*/ /* RMW - TBD - this will write entry switch LRDR even in case of loss/gain of remote ISL */ if (!bitset_test(&old_switchesInUse, sm_topop->switch_head->swIdx) || routing_needed) route_root_switch = 1; else route_root_switch = 0; /* initialize port 0 of root switch and program minimal LFT if routing is required*/ if ((status = sm_initialize_switch_LR_DR(sm_topop, sm_topop->switch_head, 0, 0, route_root_switch)) != VSTATUS_OK) { IB_LOG_INFINI_INFO_FMT(__func__, "Basic routing programming failed for root switch "FMT_U64" status %d", sm_topop->switch_head->nodeInfo.NodeGUID, status); if (sm_topop->deltaLidBlocks_init) { bitset_free(&sm_topop->deltaLidBlocks); sm_topop->deltaLidBlocks_init=0; } return status; } if (route_root_switch) { Port_t *neighbor_portp = sm_find_port(sm_topop, portp->nodeno, portp->portno); /* Program full LFT*/ root_switch.switchp = sm_topop->switch_head; root_switch.next = NULL; SmpAddr_t addr = SMP_ADDR_CREATE_DR(PathToPort(sm_topop->switch_head, neighbor_portp)); // sm_initialize_port called with NULL psc and NULL fd for now. Once switch programming is performed in parallel, the NULL will be replaced // with the psc specific mai->fd. if ((neighbor_portp == NULL) || (status = sm_initialize_port(NULL, NULL, sm_topop, sm_topop->switch_head, neighbor_portp, &addr) != VSTATUS_OK)) { IB_LOG_INFINI_INFO_FMT(__func__, "Neighbor port programming of root switch "FMT_U64" failed with status %d", sm_topop->switch_head->nodeInfo.NodeGUID, status); if (sm_topop->deltaLidBlocks_init) { bitset_free(&sm_topop->deltaLidBlocks); sm_topop->deltaLidBlocks_init=0; } return status; } // PR-119954 reported a memory leak in the case when sm_calculate_lft() is called to allocate a new lft for the new // root node structure and this lft is replaced by another lft in sm_routing_route_old_switch_LR() without // freeing the lft allocated in sm_calculate_lft(). This function was updated so that // route_root_switch is ORed with rebalance in the call to sm_routing_route_switch_LR(). // This prevents sm_routing_route_old_switch_LR() from being called in the above scenario. This fixes the memory leak. if ((status = sm_routing_route_switch_LR(sm_topop, &root_switch, route_root_switch || rebalance)) != VSTATUS_OK) { IB_LOG_INFINI_INFO_FMT(__func__, "Full LFT programming failed for root switch "FMT_U64" status %d", sm_topop->switch_head->nodeInfo.NodeGUID, status); if (sm_topop->deltaLidBlocks_init) { bitset_free(&sm_topop->deltaLidBlocks); sm_topop->deltaLidBlocks_init=0; } return status; } } sm_topop->switch_head->initDone = 1; status = sm_topop->routingModule->funcs.setup_switches_lrdr(sm_topop, rebalance, routing_needed); if (sm_topop->deltaLidBlocks_init) { bitset_free(&sm_topop->deltaLidBlocks); sm_topop->deltaLidBlocks_init=0; } return status; } Status_t sweep_assignments_looptest(SweepContext_t *sweep_context) { Status_t status; if (sm_state != SM_STATE_MASTER) return VSTATUS_NOT_MASTER; if ((status = loopTest_userexit_findPaths(sm_topop)) != VSTATUS_OK) { IB_LOG_ERROR_FMT(__func__, "loopTest can't generate lids"); } else if (loopPathLidEnd != 0) { sm_topop->maxLid = loopPathLidEnd; } return VSTATUS_OK; } Status_t sweep_assignments_setup_switches(SweepContext_t *sweep_context) { Status_t status; Node_t *nodep; Node_t *oldnodep; if (sm_state != SM_STATE_MASTER) return VSTATUS_NOT_MASTER; if (topology_passcount) { /* MWHEINZ: FIXME - investigate why we do this here and not in the topology copy routines. */ /* If we found switches that do not support mixed LR DR SMPs in the last sweep, * copy that information to the new topology so that we do not waste time retrying * sending mixed LR DR SMPs to such switches and directly send only pure DR SMPs. */ for_all_switch_nodes(&old_topology, oldnodep) { if (oldnodep->noLRDRSupport) { /* Find the node in the new topology*/ nodep = sm_find_guid(sm_topop, oldnodep->nodeInfo.NodeGUID); if (nodep) nodep->noLRDRSupport = 1; } } } /* Setup the switches using mixed LR-DR SMPs*/ if ((status = topology_setup_switches_LR_DR()) != VSTATUS_OK) { IB_LOG_INFINI_INFO_FMT(__func__, "Setting up switches with mixed LR-DR SMPs failed"); return status; } return VSTATUS_OK; } Status_t sweep_assignments_lids(SweepContext_t *sweep_context) { Status_t status; if (sm_state != SM_STATE_MASTER) return VSTATUS_NOT_MASTER; if((status = parallel_endnode_lid_assignments(sweep_context)) != VSTATUS_OK) { return status; } return VSTATUS_OK; } Status_t topology_setup_routing_cost_matrix(void) { Status_t status = VSTATUS_OK; uint64_t sTime, eTime; int newSwitchesInFabric=0; int rebalance=0; IB_ENTER(__func__, 0, 0, 0, 0); /* If we aren't the master SM, then we go no further.*/ if (sm_state != SM_STATE_MASTER) { IB_EXIT(__func__, VSTATUS_NOT_MASTER); return VSTATUS_NOT_MASTER; } if (smDebugPerf) { vs_time_get(&sTime); IB_LOG_INFINI_INFO("START topology_setup_routing_cost_matrix for nodes=", sm_topop->num_nodes); IB_LOG_INFINI_INFO("topology_changed=", topology_changed); bitset_info_log(&old_switchesInUse, "old_switchesInUse"); bitset_info_log(&new_switchesInUse, "new_switchesInUse"); if (new_endnodesInUse.nset_m) { bitset_info_log(&new_endnodesInUse, "new_endnodesInUse"); } } newSwitchesInFabric = !bitset_equal(&old_switchesInUse, &new_switchesInUse); /* recalculate the path and cost arrays only if topology has changed or first time through */ if ( topology_changed || topology_passcount == 0 || newSwitchesInFabric || old_topology.num_sws != sm_newTopology.num_sws) { rebalance = 1; if (smDebugPerf) IB_LOG_INFINI_INFO0("Calculating topology paths"); status = sm_topop->routingModule->funcs.allocate_cost_matrix(sm_topop); if (status != VSTATUS_OK) { IB_LOG_ERRORRC("failed to allocate cost data; rc:", status); IB_EXIT(__func__, status); return status; } if (smDebugPerf) { vs_time_get(&eTime); IB_LOG_INFINI_INFO("END topology_setup_routing_cost_matrix/setup init path array;" " elapsed time(usecs)=", (int)(eTime-sTime)); vs_time_get(&sTime); } sm_topop->routingModule->funcs.initialize_cost_matrix(sm_topop); if (smDebugPerf) { vs_time_get(&eTime); IB_LOG_INFINI_INFO("END topology_setup_routing_cost_matrix/setup initial cost/path arrays;" " elapsed time(usecs)=", (int)(eTime-sTime)); vs_time_get(&sTime); } sm_topop->routingModule->funcs.calculate_cost_matrix(sm_topop, sm_topop->max_sws, sm_topop->cost, sm_topop->path); if (smDebugPerf) { vs_time_get(&eTime); IB_LOG_INFINI_INFO("END topology_setup_routing_cost_matrix/calculation of cost and path arrays;" " elapsed time(usec)=", (int)(eTime-sTime)); } status = sm_topop->routingModule->funcs.post_process_routing(sm_topop, &old_topology, &rebalance); if (status != VSTATUS_OK) { IB_LOG_ERRORRC("Failed to process 'post-routing' routing hook; rc:", status); return status; } } else if (old_topology.num_sws) { rebalance = forceRebalanceNextSweep || (sm_config.force_rebalance && (new_endnodesInUse.nset_m || old_topology.num_endports != sm_newTopology.num_endports)); /* no topology change, just copy over the old data */ status = sm_routing_copy_cost_matrix(&old_topology, sm_topop); if (status != VSTATUS_OK) { IB_LOG_ERRORRC("failed to copy cost data; rc:", status); IB_EXIT(__func__, status); return status; } status = sm_topop->routingModule->funcs.post_process_routing_copy(&old_topology, sm_topop, &rebalance); if (status != VSTATUS_OK) { IB_LOG_ERRORRC("Failed to process 'post-routing (copy)' routing hook; rc:", status); return status; } if (!rebalance) { status = sm_topop->routingModule->funcs.copy_routing(&old_topology, sm_topop); if (status != VSTATUS_OK) { IB_LOG_ERRORRC("failed to copy LFTs; rc:", status); IB_EXIT(__func__, status); return status; } if (smDebugPerf) { vs_time_get(&eTime); IB_LOG_INFINI_INFO("END topology_setup_routing_cost_matrix/copy over cost, path" ", and lft arrays; elapsed time(usec)=", (int)(eTime-sTime)); } } } else { // this is the odd case where HFM is the only thing in fabric // (it has it's port down) sm_topop->bytesCost = 0; sm_topop->bytesPath = 0; sm_topop->cost = NULL; sm_topop->path = NULL; if (!sm_newTopology.num_ports) { IB_LOG_WARN0("Host SM's port is down, re-starting sweep"); sm_request_resweep(0, 0, SM_SWEEP_REASON_LOCAL_PORT_FAIL); return(VSTATUS_NOT_MASTER); } else { IB_LOG_INFINI_INFO0("Host SM's port is connected to another HFI port"); } } if ((status == VSTATUS_OK) && !rebalance) status = VSTATUS_KNOWN; IB_EXIT(__func__, status); return status; } Status_t sweep_adaptiverouting(SweepContext_t *sweep_context) { Status_t status = VSTATUS_OK; IB_ENTER(__func__, 0, 0, 0, 0); // // If we aren't the master SM, then we go no further. // if (sm_state != SM_STATE_MASTER) { IB_EXIT(__func__, VSTATUS_NOT_MASTER); return VSTATUS_NOT_MASTER; } if (sm_adaptiveRouting.enable) { if ((status = parallel_ar(sm_psc_g)) != VSTATUS_OK) { return status; } } IB_EXIT(__func__, VSTATUS_OK); return(VSTATUS_OK); } Status_t sweep_cableinfo(SweepContext_t *sweep_context) { Status_t status = VSTATUS_OK; // If we aren't the master SM, then we go no further. if (sm_state != SM_STATE_MASTER) return VSTATUS_NOT_MASTER; if (sm_config.cableInfoPolicy > CIP_NONE) { if ((status == parallel_cable_info(sweep_context)) != VSTATUS_OK) { return status; } } return VSTATUS_OK; } Status_t sweep_post_activate(SweepContext_t *sweep_context) { Port_t* portp; // If we aren't the master SM, then we go no further. if (sm_state != SM_STATE_MASTER) return VSTATUS_NOT_MASTER; if (topology_passcount) { sm_cong_config_copy(); } //Make sure LinkInitReason is set correctly for all quarantined nodes //that we are not activating QuarantinedNode_t *qnodep; int linkInitReason=0; for_all_quarantined_nodes(sm_topop, qnodep) { if (qnodep->quarantineReasons & ( STL_QUARANTINE_REASON_SMALL_MTU_SIZE | STL_QUARANTINE_REASON_VL_COUNT | STL_QUARANTINE_REASON_BAD_PACKET_FORMATS | STL_QUARANTINE_REASON_MAXLID)) { linkInitReason = STL_LINKINIT_INSUFIC_CAPABILITY; } else linkInitReason = STL_LINKINIT_QUARANTINED; for_all_ports(qnodep->quarantinedNode, portp) { if(!sm_valid_port(portp)) { if(portp && sm_dynamic_port_alloc()) { if ((portp->portData = sm_alloc_port(NULL, qnodep->quarantinedNode, portp->index)) == NULL) { IB_LOG_ERROR_FMT(__func__, "cannot create port %d for quarantined node %s", portp->index, sm_nodeDescString(qnodep->quarantinedNode)); continue; } } else if (!portp) continue; } sm_set_linkinit_reason(qnodep->quarantinedNode, portp, linkInitReason); sm_enable_port_led(fd_topology, qnodep->quarantinedNode, portp, TRUE); } //set linkInit reason for connected authentic port if(sm_valid_port(qnodep->authenticNodePort)) { sm_set_linkinit_reason(qnodep->authenticNode, qnodep->authenticNodePort, linkInitReason); sm_enable_port_led(fd_topology, qnodep->authenticNode, qnodep->authenticNodePort, TRUE); } } // Print out a pre-defined topology verification summary message (if feature is enabled) if(sm_config.preDefTopo.enabled) { char buf[255]; snprintf(buf, sizeof(buf), "SM: Pre-Defined Topology: Warning Counts: NodeDesc: %d, NodeGUID: %d, PortGUID: %d, Undefined Link: %d", sm_topop->preDefLogCounts.nodeDescWarn, sm_topop->preDefLogCounts.nodeGuidWarn, sm_topop->preDefLogCounts.portGuidWarn, sm_topop->preDefLogCounts.undefinedLinkWarn); vs_log_output_message(buf, FALSE); snprintf(buf, sizeof(buf), "SM: Pre-Defined Topology: Quarantine Counts: NodeDesc: %d, NodeGUID: %d, PortGUID: %d, Undefined Link: %d", sm_topop->preDefLogCounts.nodeDescQuarantined, sm_topop->preDefLogCounts.nodeGuidQuarantined, sm_topop->preDefLogCounts.portGuidQuarantined, sm_topop->preDefLogCounts.undefinedLinkQuarantined); vs_log_output_message(buf, FALSE); } return VSTATUS_OK; } Status_t sweep_multicast(SweepContext_t *sweep_context) { Status_t status=VSTATUS_OK; boolean smSendOutMFTs = 0; IB_ENTER(__func__, 0, 0, 0, 0); /* * If we aren't the master SM, then we go no further. */ if (sm_state != SM_STATE_MASTER) { IB_EXIT(__func__, VSTATUS_NOT_MASTER); return VSTATUS_NOT_MASTER; } sm_topop->routingModule->funcs.build_spanning_trees(); /* * Setup the MFTs of the switches. */ // Nota Bene: This function does an atomic compare and store operation. // IFF sm_McGroups_Need_Prog is 1, set it to zero and return true. if (AtomicCompareStore(&sm_McGroups_Need_Prog, 1, 0)) { smSendOutMFTs = 1; } if (new_endnodesInUse.nset_m || topology_changed || topology_switch_port_changes || (topology_passcount == 0) || (sm_newTopology.maxMcastRate < old_topology.maxMcastRate) || (sm_newTopology.maxMcastMtu < old_topology.maxMcastMtu)) { smSendOutMFTs = 1; } if (smSendOutMFTs) { status = sm_calculate_mfts(); } else { /* just copy over the switch mfts to new topology */ status = sm_multicast_switch_mft_copy(); } //TODO: McPrejoin - make sure this logic is correct after the rebase... if (smSendOutMFTs || topology_forceMfts || topology_changed || topology_passcount <= 1) { int force = topology_forceMfts; topology_forceMfts = 0; if (topology_passcount > 1) { if (vs_rdlock(&old_topology_lock) != VSTATUS_OK) { IB_LOG_ERROR_FMT(__func__, "Unable to get the old topology" " lock. Programming MFT without the old topology data."); status = sm_set_all_mft(force, &sm_newTopology, NULL); } else { status = sm_set_all_mft(force, &sm_newTopology, &old_topology); vs_rwunlock(&old_topology_lock); } } else { status = sm_set_all_mft(force, &sm_newTopology, NULL); } if (status != VSTATUS_OK) { if (status != VSTATUS_NOT_MASTER) { /* reprogram the switches */ sm_request_resweep(0, 1, SM_SWEEP_REASON_MC_ROUTING_FAIL); } } } IB_EXIT(__func__, status); return(status); } static void _format_link_down_reason(Popo_t *popop, Port_t *portp, Port_t *linked_portp, char *buf, size_t bufsize) { STL_LINKDOWN_REASON ldr = {{0}}; STL_LINKDOWN_REASON linked_ldr = {{0}}; uint64_t thisSweep = sm_popo_get_sweep_start(popop); boolean useLDR = sm_popo_find_lastest_ldr(popop, portp, &ldr) && ldr.Timestamp == thisSweep; boolean useLinkedLDR = sm_popo_find_lastest_ldr(popop, linked_portp, &linked_ldr) && linked_ldr.Timestamp == thisSweep; if (useLDR) { if (ldr.LinkDownReason != 0) { snprintf(buf, bufsize, "LinkDownReason: %s [%u] ", StlLinkDownReasonToText(ldr.LinkDownReason), ldr.LinkDownReason); } else if (ldr.NeighborLinkDownReason != 0) { snprintf(buf, bufsize, "NeighborLinkDownReason: %s [%u] ", StlLinkDownReasonToText(ldr.NeighborLinkDownReason), ldr.NeighborLinkDownReason); } } if (useLinkedLDR) { int cnt = strlen(buf); if (linked_ldr.NeighborLinkDownReason != 0 && linked_ldr.NeighborLinkDownReason != ldr.LinkDownReason && linked_ldr.NeighborLinkDownReason != STL_LINKDOWN_REASON_NEIGHBOR_UNKNOWN) { snprintf(buf+cnt, bufsize-cnt, "LINKED:NeighborLinkDownReason: %s [%u]", StlLinkDownReasonToText(linked_ldr.NeighborLinkDownReason), linked_ldr.NeighborLinkDownReason); } else if (linked_ldr.LinkDownReason != 0 && linked_ldr.LinkDownReason != ldr.NeighborLinkDownReason && linked_ldr.LinkDownReason != STL_LINKDOWN_REASON_NEIGHBOR_UNKNOWN) { snprintf(buf+cnt, bufsize-cnt, "LINKED:LinkDownReason: %s [%u]", StlLinkDownReasonToText(linked_ldr.LinkDownReason), linked_ldr.LinkDownReason); } } } void topology_log_isl_change(Topology_t *old_topo, Node_t *nodep, Port_t *portp, SmCsmMsgCondition_t condition, char *detail) { Port_t *linkedToPortp = NULL; SmCsmNodeId_t csmNode, csmConnectedNode; char ldr_buf[120] = {0}; if (portp->portData->pLid == 0xC000) { smCsmFormatNodeId(&csmNode, (uint8_t *)sm_nodeDescString(nodep), portp->index, nodep->nodeInfo.NodeGUID); if ( (linkedToPortp = sm_find_port(old_topo, portp->nodeno, portp->portno)) != NULL && sm_valid_port(linkedToPortp)) { smCsmFormatNodeId(&csmConnectedNode, (uint8_t *)sm_nodeDescString(linkedToPortp->portData->nodePtr), linkedToPortp->index, (linkedToPortp->portData->nodePtr)->nodeInfo.NodeGUID); _format_link_down_reason(&sm_popo, portp, linkedToPortp, ldr_buf, sizeof(ldr_buf)); smCsmLogMessage(CSM_SEV_NOTICE, condition, &csmNode, &csmConnectedNode, "%s %s", detail, ldr_buf); } else { _format_link_down_reason(&sm_popo, portp, NULL, ldr_buf, sizeof(ldr_buf)); smCsmLogMessage(CSM_SEV_NOTICE, condition, &csmNode, NULL, "%s %s", detail, ldr_buf); } } else { if ( (linkedToPortp = sm_find_port(old_topo, portp->nodeno, portp->portno)) != NULL && sm_valid_port(linkedToPortp)) { linkedToPortp->portData->pLid = 0xC000; } } } // // Find what changed between the two fabrics // Send GID In/out service traps // Status_t topology_changes(Topology_t *old_topo, Topology_t *new_topo) { Status_t status = VSTATUS_OK; Port_t *portp = NULL; Port_t *oldPortp = NULL; Node_t *oldNodep = NULL; Port_t *newPortp = NULL; Node_t *newNodep = NULL; STL_NOTICE notice; #ifdef __VXWORKS__ uint8_t *oldChanges = old_topo->pad; uint8_t *newChanges = new_topo->pad; #else uint8_t *oldChanges = NULL; uint8_t *newChanges = NULL; #endif /* __VXWORKS__ */ const char detailAppearance[] = "inter-switch link appeared"; const char detailDisappearance[] = "inter-switch link disappeared"; IB_ENTER(__func__, 0, 0, 0, 0); memset(&notice, 0, sizeof(notice)); notice.Attributes.Generic.u.s.IsGeneric = 1; notice.Attributes.Generic.u.s.Type = NOTICE_TYPE_INFO; notice.Attributes.Generic.u.s.ProducerType = NOTICE_PRODUCERTYPE_CLASSMANAGER; notice.IssuerLID = sm_lid; notice.Stats.s.Toggle = 0; notice.Stats.s.Count = 0; if (!sm_valid_port((portp = sm_get_port(new_topo->node_head,sm_config.port)))) { IB_LOG_ERROR0("failed to get SM port"); IB_EXIT(__func__, VSTATUS_BAD); return(VSTATUS_BAD); } memcpy(notice.IssuerGID.Raw, portp->portData->gid, sizeof(notice.IssuerGID.Raw)); /* * Go through each old node and for each old node look for it in the new topology * If you get a match see if states changed */ #ifdef __VXWORKS__ memset(oldChanges, 0, old_topo->num_nodes * sizeof(uint8_t)); memset(newChanges, 0, new_topo->num_nodes * sizeof(uint8_t)); #else if (old_topo->num_nodes > 0) { status = vs_pool_alloc(&sm_pool, old_topo->num_nodes * sizeof(uint8_t), (void*)&oldChanges); if(status != VSTATUS_OK) { IB_LOG_ERRORRC("failed to allocate memory rc:", status); return status; } memset(oldChanges, 0, old_topo->num_nodes * sizeof(uint8_t)); } if (new_topo->num_nodes > 0) { status = vs_pool_alloc(&sm_pool, new_topo->num_nodes * sizeof(uint8_t), (void*)&newChanges); if(status != VSTATUS_OK) { IB_LOG_ERRORRC("failed to allocate memory rc:", status); (void)vs_pool_free(&sm_pool, oldChanges); return status; } memset(newChanges, 0, new_topo->num_nodes * sizeof(uint8_t)); } #endif /*__VXWORKS__*/ for_all_nodes(old_topo, oldNodep) { if ((newNodep = sm_find_guid(new_topo, oldNodep->nodeInfo.NodeGUID)) != NULL) { if(oldChanges != NULL) oldChanges[oldNodep->index] = 1; if(newChanges != NULL) newChanges[newNodep->index] = 1; for_all_end_ports2Nodes(oldNodep, oldPortp, newNodep, newPortp) { if (oldPortp->state <= IB_PORT_INIT) { if (sm_valid_port(newPortp) && newPortp->state >= IB_PORT_ARMED) { /* New GID added, add to list of things to trap on */ status = topology_TrapUp(&notice, new_topo, old_topo, newNodep, newPortp); } } else if (newPortp->state <= IB_PORT_INIT) { /* Old GID lost, add to list of things to trap on */ if (sm_valid_port(oldPortp)) { status = topology_TrapDown(&notice, old_topo, new_topo, oldNodep, oldPortp); } } } /* Only if we aren't an HFI */ if (oldNodep->nodeInfo.NodeType != NI_TYPE_CA) { /* Cycle through old port list, reporting downed ports in the new topo. * We do this with some serious magic here. First, we detect ports on the * 'oldNode' that are in the old topology and *not* the new topology. If we * detect one of them, we follow the link in the old topology and set the pLid * field of the neighboring node to 0xC000 (an invalid lid) to flag that we * should report the link. * * When we encounter a port with the pLid set to 0xC000, we know that we should * report the downed link. This ensures: * - That we only report the link once * - That both nodes that share the link are in both the new & old topology * * TODO: * * The use of the pLid field for this function is valid b/c it is currently unused * *and* we blow away the old topo right after this function gets called. A cleaner * way of doing this may be to used the unused 'flags' variable in the PortData_t * structure. This cleanup should be deferred until we revamp the PortData_t struct * to consume less memory. */ for_all_ports(oldNodep, oldPortp) { newPortp = sm_get_port(newNodep, oldPortp->index); if (sm_valid_port(oldPortp) && sm_valid_port(newPortp)) { // typically depending on frequency the port might be either intermittenly unstable or flapping if ((oldPortp->state > IB_PORT_INIT) && (newPortp->state <= IB_PORT_INIT)) { (void)topology_log_isl_change(old_topo, oldNodep, oldPortp, CSM_COND_DISAPPEARANCE, (char *)detailDisappearance); } else if ((newPortp->state > IB_PORT_INIT) && (oldPortp->state <= IB_PORT_INIT)) { (void)topology_log_isl_change(new_topo, newNodep, newPortp, CSM_COND_APPEARANCE, (char *)detailAppearance); } } else { // typically the port has either been DISABLED or ENABLED if (sm_valid_port(oldPortp) && (oldPortp->state > IB_PORT_INIT)) { (void)topology_log_isl_change(old_topo, oldNodep, oldPortp, CSM_COND_DISAPPEARANCE, (char *)detailDisappearance); } else if (sm_valid_port(newPortp) && (newPortp->state > IB_PORT_INIT)) { (void)topology_log_isl_change(new_topo, newNodep, newPortp, CSM_COND_APPEARANCE, (char *)detailAppearance); } } } } } if (oldChanges != NULL && !oldChanges[oldNodep->index]) { /* Never found old node, add all of its armed or active ports to GID Lost list */ for_all_end_ports(oldNodep, oldPortp) { if (sm_valid_port(oldPortp) && oldPortp->state >= IB_PORT_ARMED) { /* port lost send trap */ status = topology_TrapDown(&notice, old_topo, new_topo, oldNodep, oldPortp); } } oldChanges[oldNodep->index] = 1; } } /* end for_all_nodes(&old_topology, oldNodep) */ /* * Go through all the new topology nodes looking for nodes * that were not found in the previous run * don't bother if first time through */ if (old_topo->num_nodes > 0) { for_all_nodes(new_topo, newNodep) { if (newChanges != NULL && !newChanges[newNodep->index]) { /* This is a new node, need to send trap for all ports up */ for_all_end_ports(newNodep, newPortp) { if (sm_valid_port(newPortp) && newPortp->state >= IB_PORT_ARMED) { /* New GID added, add to list of things to trap on */ status = topology_TrapUp(&notice, new_topo, old_topo, newNodep, newPortp); } } } } /* end for_all_nodes(new_topo, newNodep) */ } /* Generate Trap if Cost Matrix has Changed */ if (topology_cost_path_changes && routing_recalculated) { status = topology_TrapCostMatrixChange(&notice); } #ifndef __VXWORKS__ (void)vs_pool_free(&sm_pool, oldChanges); (void)vs_pool_free(&sm_pool, newChanges); #endif /* __VXWORKS__ */ IB_EXIT(__func__, status); return status; } // // Given two topologies, and a node that is present only in tp_present, figure out the port on // the node that connected the node to the tp_missing topology. We do this by cycling through // the nodes connected to the node in question, looking for the first one that still exists // in both topologies. // Status_t sm_find_missing_linked_ports(Topology_t * tp_present, Topology_t * tp_missing, Node_t * node, Port_t ** _nodePortp, Port_t ** _neighborPortp) { Status_t status = VSTATUS_NOT_FOUND; Port_t * portp = NULL, * neighborPortp = NULL; // Set to NULL *_nodePortp = *_neighborPortp = NULL; for_all_physical_ports(node, portp) { if (sm_valid_port(portp) && portp->state >= IB_PORT_ARMED) { neighborPortp = sm_find_port(sm_topop, portp->nodeno, portp->portno); // If neighbor exists in both topologies, we have a winner! if ( sm_valid_port(neighborPortp) && sm_find_port(sm_topop, portp->nodeno, portp->portno) != NULL) { *_nodePortp = portp; *_neighborPortp = neighborPortp; status = VSTATUS_OK; break; } } } return status; } Status_t topology_TrapUp(STL_NOTICE * noticep, Topology_t * tp_present, Topology_t * tp_missing, Node_t * node, Port_t * port) { STL_NOTICE * trap64 = (STL_NOTICE *)noticep; STL_TRAP_GID * trap64DataDetails = (STL_TRAP_GID *)noticep->Data; Status_t status; SmCsmNodeId_t nodeId, linkedId, * linkedIdPtr = NULL; Port_t * p1p, * p2p, * linkedToPortp = NULL; char ldr_buf[120] = {0}; IB_ENTER(__func__, 0, 0, 0, 0); memcpy(trap64DataDetails->Gid.Raw, port->portData->gid, sizeof(trap64DataDetails->Gid.Raw)); trap64->Attributes.Generic.TrapNumber = MAD_SMT_PORT_UP; /* queue up trap forwarding request to sm_async */ if ((status = sm_sa_forward_trap(noticep)) != VSTATUS_OK){ IB_LOG_ERRORRC("unable to queue trap to sm_async rc:", status); } /* mark topology as changed */ topology_changed = 1; /* no message on first sweep */ if (topology_passcount) { if ( (sm_config.node_appearance_msg_thresh != 0) && (++sweepNodeChangeMsgCount > sm_config.node_appearance_msg_thresh)) { nodeAppearanceSeverity = CSM_SEV_INFO; ++sweepNodeAppearanceInfoMsgCount; } if (node->nodeInfo.NodeType == NI_TYPE_SWITCH) { if (sm_find_missing_linked_ports(tp_present, tp_missing, node, &p1p, &p2p) == VSTATUS_OK) { port = p1p; linkedToPortp = p2p; } else if (sm_find_missing_linked_ports(tp_present, tp_present, node, &p1p, &p2p) == VSTATUS_OK) { linkedToPortp = p2p; } } else if ( (linkedToPortp = sm_find_port(tp_present, port->nodeno, port->portno)) != NULL && !sm_valid_port(linkedToPortp)) { linkedToPortp = NULL; } if (linkedToPortp != NULL) { smCsmFormatNodeId(&linkedId, (uint8_t *)sm_nodeDescString(linkedToPortp->portData->nodePtr), linkedToPortp->index, linkedToPortp->portData->nodePtr->nodeInfo.NodeGUID); linkedIdPtr = &linkedId; } if (node->nodeInfo.NodeType == NI_TYPE_SWITCH) { _format_link_down_reason(&sm_popo, port, linkedToPortp, ldr_buf, sizeof(ldr_buf)); smCsmFormatNodeId(&nodeId, (uint8_t *)sm_nodeDescString(node), port->index, node->nodeInfo.NodeGUID); smCsmLogMessage(nodeAppearanceSeverity, CSM_COND_APPEARANCE, &nodeId, linkedIdPtr, "NodeType: switch %s", ldr_buf); } else { _format_link_down_reason(&sm_popo, port, linkedToPortp, ldr_buf, sizeof(ldr_buf)); smCsmFormatNodeId(&nodeId, (uint8_t *)sm_nodeDescString(node), port->index, port->portData->guid); smCsmLogMessage(nodeAppearanceSeverity, CSM_COND_APPEARANCE, &nodeId, linkedIdPtr, "NodeType: hfi %s", ldr_buf); } } IB_EXIT(__func__, VSTATUS_OK); return(VSTATUS_OK); } Status_t topology_TrapDown(STL_NOTICE * noticep, Topology_t * tp_present, Topology_t * tp_missing, Node_t * node, Port_t * port) { McGroup_t * mcGroup; McGroup_t * prevMcGroup; McMember_t * mcMember; Guid_t mcastGid[2], portguid; SubscriberKeyp subsKeyp; STL_INFORM_INFO_RECORD *iRecordp = NULL; STL_NOTICE * trap67 = (STL_NOTICE *)noticep; STL_NOTICE * trap65 = (STL_NOTICE *)noticep; STL_TRAP_GID * trapDataDetails = (STL_TRAP_GID *)noticep->Data; Status_t status; int32_t moreEntries=1; CS_HashTableItr_t itr; uint32_t groupChanges=0; SmCsmNodeId_t nodeId, linkedId, * linkedIdPtr = NULL; Port_t * extPortp, * p1p, * p2p, * linkedToPortp = NULL; char ldr_buf[120] = {0}; IB_ENTER(__func__, 0, 0, 0, 0); /* mark topology as changed */ topology_changed = 1; if ( (sm_config.node_appearance_msg_thresh != 0) && (++sweepNodeChangeMsgCount > sm_config.node_appearance_msg_thresh)) { nodeAppearanceSeverity = CSM_SEV_INFO; ++sweepNodeDisappearanceInfoMsgCount; } /* find linked-to port */ extPortp = linkedToPortp = NULL; if (node->nodeInfo.NodeType == NI_TYPE_SWITCH) { if (sm_find_missing_linked_ports(tp_present, tp_missing, node, &p1p, &p2p) == VSTATUS_OK) { extPortp = p1p; linkedToPortp = p2p; } else if (sm_find_missing_linked_ports(tp_present, tp_present, node, &p1p, &p2p) == VSTATUS_OK) { linkedToPortp = p2p; } } else if ( (linkedToPortp = sm_find_port(tp_present, port->nodeno, port->portno)) != NULL && !sm_valid_port(linkedToPortp)) { linkedToPortp = NULL; } if (linkedToPortp != NULL) { smCsmFormatNodeId(&linkedId, (uint8_t *)sm_nodeDescString(linkedToPortp->portData->nodePtr), linkedToPortp->index, linkedToPortp->portData->nodePtr->nodeInfo.NodeGUID); linkedIdPtr = &linkedId; } if (node->nodeInfo.NodeType == NI_TYPE_SWITCH) { _format_link_down_reason(&sm_popo, extPortp ? extPortp : port, linkedToPortp, ldr_buf, sizeof(ldr_buf)); smCsmFormatNodeId(&nodeId, (uint8_t *)sm_nodeDescString(node), extPortp ? extPortp->index : port->index, node->nodeInfo.NodeGUID); smCsmLogMessage(nodeAppearanceSeverity, CSM_COND_DISAPPEARANCE, &nodeId, linkedIdPtr, "NodeType: switch %s", ldr_buf); } else { _format_link_down_reason(&sm_popo, port, linkedToPortp, ldr_buf, sizeof(ldr_buf)); smCsmFormatNodeId(&nodeId, (uint8_t *)sm_nodeDescString(node), port->index, port->portData->guid); smCsmLogMessage(nodeAppearanceSeverity, CSM_COND_DISAPPEARANCE, &nodeId, linkedIdPtr, "NodeType: hfi %s", ldr_buf); } // if applicable, clean it out of the list of disabled ports (void)sm_removedEntities_clearNode(node); /* remove down node from subscriber list if neccessary */ memcpy(trapDataDetails->Gid.Raw, port->portData->gid, sizeof(trapDataDetails->Gid.Raw)); trap65->Attributes.Generic.TrapNumber = MAD_SMT_PORT_DOWN; (void)vs_lock(&saSubscribers.subsLock); if (cs_hashtable_count(saSubscribers.subsMap) > 0) { cs_hashtable_iterator(saSubscribers.subsMap, &itr); do { subsKeyp = cs_hashtable_iterator_key(&itr); iRecordp = cs_hashtable_iterator_value(&itr); if (iRecordp->RID.SubscriberLID==port->portData->lid) { /* sync the delete with standby SMs */ (void)sm_dbsync_syncInform(DBSYNC_TYPE_DELETE, subsKeyp, iRecordp); /* remove the entry from hashtable and free the value - key is freed by remove func */ moreEntries = cs_hashtable_iterator_remove(&itr); free(iRecordp); } else { /* advance the iterator */ moreEntries = cs_hashtable_iterator_advance(&itr); } } while (moreEntries); } (void)vs_unlock(&saSubscribers.subsLock); /* If this node was providing any services, remove the service records */ if (vs_lock(&saServiceRecords.serviceRecLock) == VSTATUS_OK) { OpaServiceRecord_t * pOsr = NULL; if (cs_hashtable_count(saServiceRecords.serviceRecMap) > 0) { cs_hashtable_iterator(saServiceRecords.serviceRecMap, &itr); do { pOsr = cs_hashtable_iterator_value(&itr); if (memcmp(&pOsr->serviceRecord.RID.ServiceGID, port->portData->gid, sizeof(IB_GID)) == 0) { IB_LOG_INFO_FMT(__func__, "Deleting service for GID " FMT_GID " that " "went out of service", STLGIDPRINTARGS2(port->portData->gid)); moreEntries = cs_hashtable_iterator_remove(&itr); /* sync the service record deletion to standby SMs if necessary */ (void)sm_dbsync_syncService(DBSYNC_TYPE_DELETE, pOsr); /* remove the entry from hashtable and free the value - key is freed by remove func */ free(pOsr); } else { moreEntries = cs_hashtable_iterator_advance(&itr); } } while (moreEntries); } vs_unlock(&saServiceRecords.serviceRecLock); } /* queue up port down trap forwarding request to sm_async */ if ((status = sm_sa_forward_trap(noticep)) != VSTATUS_OK){ IB_LOG_ERRORRC("unable to queue trap to sm_async rc:", status); } /* Remove this node from any multicast groups it was in */ /* This may actually cause a group to go away and itself generate a trap */ /* If a group has to be deleted we will use trap 67, setup the number here */ trap67->Attributes.Generic.TrapNumber = MAD_SMT_MCAST_GRP_DELETED; prevMcGroup = NULL; (void)vs_lock(&sm_McGroups_lock); mcGroup = sm_McGroups; while (mcGroup) { /* Walk through all groups and ... */ IB_GID gid; memcpy(gid.Raw, port->portData->gid, sizeof(IB_GID)); BSWAP_IB_GID(&gid); mcMember = sm_find_multicast_member(mcGroup, gid); /* ...look for this gid as a member */ if (!mcMember) { /* Didn't find it in this group, try the next one */ prevMcGroup = mcGroup; mcGroup = mcGroup->next; continue; } /* indicate group table changed */ groupChanges = 1; mcastGid[0] = mcGroup->mGid.AsReg64s.H; mcastGid[1] = mcGroup->mGid.AsReg64s.L; /* save the portguid before deleting the member */ portguid = mcMember->portGuid; /* Found it, now we must remove it */ if (!(mcMember->state & MCMEMBER_STATE_FULL_MEMBER)) { IB_LOG_INFO_FMT(__func__, "Non full mcMember "FMT_U64" of multicast group " "GID "FMT_GID" is no longer in fabric", portguid, mcastGid[0], mcastGid[1]); } else { mcGroup->members_full--; IB_LOG_INFO_FMT(__func__, "Full mcMember "FMT_U64" of multicast group " "GID "FMT_GID" is no longer in fabric", portguid, mcastGid[0], mcastGid[1]); } McMember_Delete(mcGroup, mcMember); if (mcGroup->members_full == 0) { IB_LOG_INFINI_INFO_FMT(__func__, "Last full member of multicast group " "GID "FMT_GID" is no longer in fabric, deleting all members", mcastGid[0], mcastGid[1]); while (mcGroup->mcMembers) { /* MUST copy head pointer into temp * Passing mcGroup->members directly to the delete macro will corrupt the list */ mcMember = mcGroup->mcMembers; IB_LOG_INFO_FMT(__func__, "Deleting non full mcMember "FMT_U64, mcMember->portGuid); McMember_Delete(mcGroup, mcMember); } } else { IB_LOG_INFO_FMT(__func__, "Full member "FMT_U64" of multicast group " "GID "FMT_GID" is no longer in fabric", portguid, mcastGid[0], mcastGid[1]); } if (mcGroup->mcMembers == NULL) { /* Group is empty, delete it */ memcpy(trapDataDetails->Gid.Raw, mcGroup->mGid.Raw, sizeof(trapDataDetails->Gid.Raw)); if (mcGroup == sm_McGroups) { McGroup_Delete(mcGroup); mcGroup = sm_McGroups; } else { McGroup_Delete(mcGroup); mcGroup = prevMcGroup->next; } status = sm_sa_forward_trap(noticep); if (status != VSTATUS_OK) { IB_LOG_ERRORRC("failed to queue up trap 67 (multicast group delete) to sm_async rc:", status); } } else { prevMcGroup = mcGroup; mcGroup = mcGroup->next; } } // end for_all_multicast_groups (void)vs_unlock(&sm_McGroups_lock); /* ask for a full sync of group table if there were changes */ if (groupChanges) { /* sync the group change with standby SMs */ (void)sm_dbsync_syncGroup(DBSYNC_TYPE_FULL, NULL); } IB_EXIT(__func__, VSTATUS_OK); return(VSTATUS_OK); } Status_t topology_TrapCostMatrixChange(STL_NOTICE *noticep) { Status_t status = VSTATUS_OK; STL_NOTICE * trap2049 = (STL_NOTICE *)noticep; trap2049->Attributes.Generic.TrapNumber = STL_TRAP_COST_MATRIX_CHANGE; /* queue up trap forwarding request to sm_async */ if ((status = sm_sa_forward_trap(noticep)) != VSTATUS_OK){ IB_LOG_ERRORRC("unable to queue trap to sm_async rc:", status); } IB_EXIT(__func__, status); return status; } Status_t topology_copy(void) { Node_t *nodep, *oldnodep; Port_t *portp, *oldportp; int delta, nextLid, lid, i; int copyMcDosThreshold; int copyNodeDescs; uint64_t sTime, eTime; IB_ENTER(__func__, 0, 0, 0, 0); if (smDebugPerf) { vs_time_get(&sTime); IB_LOG_INFINI_INFO0("START"); } /* * Save the old topology and copy the new topology to it. The new * topology can't be bad since only this thread writes it. */ (void)vs_wrlock(&old_topology_lock); // Copy bitset from new to old if a reconfig happened if (updatedVirtualFabrics) { VirtualFabrics_t *oldVF = old_topology.vfs_ptr; McGroup_t *mcgp, *tmpgrp; McMember_t *mcmbp; int vf; (void)vs_lock(&sm_McGroups_lock); for (vf=0; vf < oldVF->number_of_vfs_all; vf++) { // VF transitions from active to standby if (oldVF->v_fabric_all[vf].reconf_idx.new_index == (uint32_t)(-1)) { IB_LOG_INFINI_INFO_FMT(__func__, "VF %s change from ACT to STB or REMOVED", oldVF->v_fabric_all[vf].name ); mcgp = sm_McGroups; while(mcgp) { if (bitset_test(&mcgp->vfMembers, vf)) { //find members in VF for_all_multicast_members(mcgp, mcmbp) { uint64_t mcMemberGuid = mcmbp->record.RID.PortGID.Type.Global.InterfaceID; Port_t *portp; if (mcMemberGuid != 0) { if ((portp = sm_find_port_guid(&old_topology, mcmbp->portGuid)) != NULL) { if (bitset_test(&portp->portData->vfMember,vf)) { IB_LOG_INFINI_INFO_FMT_VF(oldVF->v_fabric_all[vf].name, __func__, "port_guid "FMT_U64" moved to STB\n", mcmbp->portGuid); //mark node that is not a member if (portp->portData->portInfo.PortStates.s.PortState == IB_PORT_ACTIVE) { // Indicate that reregistration is pending; will persist across // sweeps until it succeeds or is no longer required (e.g. state change) portp->poportp->registration.reregisterPending = 1; } //bitset_clear(&portp->portData->vfMember,vf); } } } } //reset bit for that VF bitset_clear(&mcgp->vfMembers, vf); } // if there is no other VF matching, check it has no members and then delete it if (bitset_nset(&mcgp->vfMembers) == 0 && bitset_nset(&mcgp->new_vfMembers) == 0) { while (mcgp->mcMembers) { // MUST copy head pointer into temp // Passing mcGroup->members directly to the delete macro will corrupt the list mcmbp = mcgp->mcMembers; McMember_Delete(mcgp, mcmbp); } if (mcgp->mcMembers == NULL) { // Group is empty, delete it IB_LOG_INFINI_INFO_FMT_VF(oldVF->v_fabric_all[vf].name, __func__, "Group is empty, deleting MGID: "FMT_GID, mcgp->mGid.Type.Global.SubnetPrefix, mcgp->mGid.Type.Global.InterfaceID); tmpgrp = mcgp->next; McGroup_Delete(mcgp); mcgp = tmpgrp; } } else { mcgp = mcgp->next; } } // End of while mcgp } // End of if Vf Removed } // End of for all old VFs for_all_multicast_groups(mcgp) { bitset_copy(&mcgp->vfMembers, &mcgp->new_vfMembers); } (void)vs_unlock(&sm_McGroups_lock); } (void)vs_lock(&saCache.lock); copyNodeDescs = (old_topology.lastNDTrapTime > sm_newTopology.sweepStartTime); /* Generate Traps for topology changes */ topology_changes(&old_topology, &sm_newTopology); bitset_copy(&old_switchesInUse, &new_switchesInUse); bitset_clear_all(&new_switchesInUse); bitset_clear_all(&new_endnodesInUse); /* clear out and rebuild the old topology node pointers in lidmap */ for (i = 0; i <= STL_GET_UNICAST_LID_MAX(); i++) { lidmap[i].oldNodep = NULL; } /* point node entry pointer in lidmap table to newer old_topology */ for_all_nodes(&sm_newTopology, nodep) { oldnodep = NULL; copyMcDosThreshold = FALSE; if (nodep->oldExists) { oldnodep = nodep->old; } if (sm_mcDosThreshold && nodep->nodeInfo.NodeType == NI_TYPE_CA) { copyMcDosThreshold = TRUE; } if (copyNodeDescs && oldnodep) { nodep->nodeDescChgTrap = oldnodep->nodeDescChgTrap; } for_all_end_ports(nodep, portp) { if (!sm_valid_port(portp) || portp->state <= IB_PORT_DOWN) { continue; } else { delta = 1 << portp->portData->lmc; nextLid = portp->portData->lid + delta; for (lid = portp->portData->lid; lid < nextLid; ++lid) { lidmap[lid].oldNodep = lidmap[lid].newNodep; /* point to new topology now */ lidmap[lid].newNodep = NULL; lidmap[lid].newPortp = NULL; } if (oldnodep) { oldportp = sm_get_port(oldnodep, portp->index); if (sm_valid_port(oldportp)) { /* copy over SA threshold counters from old topology */ if (copyMcDosThreshold) { portp->portData->mcDeleteStartTime = oldportp->portData->mcDeleteStartTime; portp->portData->mcDeleteCount = oldportp->portData->mcDeleteCount; } } } } } } /* free Old topology */ topology_free_topology(&old_topology, FALSE, TRUE); /* Copy New Topology to old_topology */ (void)memcpy((void *)&old_topology, (void *)&sm_newTopology, sizeof(Topology_t)); /* clear out all new topology node pointers in lidmap */ for (i = 0; i <= STL_GET_UNICAST_LID_MAX(); i++) { lidmap[i].newNodep = NULL; lidmap[i].newPortp = NULL; } /* make the cached SA records active */ (void)topology_cache_copy(); (void)vs_unlock(&saCache.lock); // TBD - can we trust topology_changed? MFT programming doesn't // doesn't seem to get set on HFI going down nor up if (topology_changed) { ++topology_changed_count; if (smDebugPerf) { IB_LOG_INFINI_INFO("topology_changed:", topology_changed_count); } } (void)vs_rwunlock(&old_topology_lock); #ifndef __VXWORKS__ /* Not needed for ESM as we can call printLoopPaths on command line whenever required*/ /* print loop paths, uses old topology. So old topology has to be valid for printLoopPaths to work. For this to work for the first sweep too, we need to do this after new topology is copied to old topology */ if (esmLoopTestOn && smDebugPerf) { printLoopPaths(-1, /* do not buffer */ 0); } #endif if (smDebugPerf) { vs_time_get(&eTime); IB_LOG_INFINI_INFO("END; elapsed time(usecs)=", (int)(eTime - sTime)); } IB_EXIT(__func__, 0); return (VSTATUS_OK); } Status_t topology_free_topology(Topology_t * topop, boolean need_old_topo_lock, boolean freeRoutingMod) { LoopPath_t *loopPath; QuarantinedNode_t *qnodep; Node_t *nodep; if (!need_old_topo_lock || (need_old_topo_lock && vs_wrlock(&old_topology_lock) == VSTATUS_OK)) { /* * old_topology_lock is used here because any CableInfo in * sm_newTopology after a failed sweep came from old_topology, * however, we should only consider the ports in sm_newTopology * since these are the ones we're sure have had their * cableInfo copied. */ Port_t *portp; for_all_nodes(topop, nodep) { for_all_ports(nodep, portp) { if (!sm_valid_port(portp) || !portp->portData->cableInfo) continue; sm_CableInfo_free(portp->portData->cableInfo); portp->portData->cableInfo = NULL; } } if (need_old_topo_lock) vs_rwunlock(&old_topology_lock); } if(topop->nodeIdMap){ cl_qmap_remove_all(topop->nodeIdMap); (void)vs_pool_free(&sm_pool, (void *)topop->nodeIdMap); topop->nodeIdMap = NULL; } if(topop->nodeMap){ cl_qmap_remove_all(topop->nodeMap); (void)vs_pool_free(&sm_pool, (void *)topop->nodeMap); topop->nodeMap = NULL; } if(topop->portMap){ cl_qmap_remove_all(topop->portMap); (void)vs_pool_free(&sm_pool, (void *)topop->portMap); topop->portMap = NULL; } if(topop->nodeArray != NULL) { (void)vs_pool_free(&sm_pool, (void *)topop->nodeArray); topop->nodeArray = NULL; } if(topop->quarantinedNodeMap){ cl_qmap_remove_all(topop->quarantinedNodeMap); (void)vs_pool_free(&sm_pool, (void *)topop->quarantinedNodeMap); topop->quarantinedNodeMap = NULL; } if(topop->switchLids){ cl_qmap_remove_all(topop->switchLids); (void)vs_pool_free(&sm_pool, (void *)topop->switchLids); topop->switchLids = NULL; } while ((qnodep = topop->quarantined_node_head) != NULL) { topop->quarantined_node_head = qnodep->next; Node_Quarantined_Delete(topop, qnodep); topop->num_quarantined_nodes--; } DEBUG_ASSERT(topop->num_quarantined_nodes == 0); topop->num_quarantined_nodes = 0; while ((nodep = topop->node_head) != NULL) { topop->node_head = nodep->next; topop->num_nodes--; if (nodep->nodeInfo.NodeType == NI_TYPE_CA) { topop->num_ports--; topop->num_endports--; } else { Port_t *portp = NULL; for_all_ports(nodep, portp) { if (sm_valid_port(portp)) { topop->num_ports--; } } topop->num_sws--; } Node_Delete(topop, nodep); } DEBUG_ASSERT(topop->num_nodes == 0); topop->num_nodes = 0; DEBUG_ASSERT(topop->num_sws == 0); topop->num_sws = 0; DEBUG_ASSERT(topop->num_ports == 0); topop->num_ports = 0; DEBUG_ASSERT(topop->num_endports == 0); topop->num_endports = 0; topop->max_sws = 0; if (topop->cost != NULL) { (void)vs_pool_free(&sm_pool, (void *)topop->cost); topop->cost = NULL; } if (topop->path != NULL) { (void)vs_pool_free(&sm_pool, (void *)topop->path); topop->path = NULL; } if (freeRoutingMod && topop->routingModule) sm_routing_freeModule(&topop->routingModule); // release memory allocated for loop paths topop->numLoopPaths = 0; while ((loopPath = topop->loopPaths) != NULL) { topop->loopPaths = loopPath->next; (void)vs_pool_free(&sm_pool, (void *)loopPath); } return VSTATUS_OK; } /* * Clear an unreliable new topology view. This can be caused when * a discovered switch is removed before topology_assigments is called. * The window of opportunity for hitting this grows with the size of the * fabric. */ void topology_clearNew(void) { Node_t *nodep; Port_t *portp; int lid, nextLid, delta, i; IB_ENTER(__func__, 0, 0, 0, 0); // // Clear the bad new topology. // Lock is already held by topology_main which calls us // /* * clear node entry pointer to new topology and reset lid topology pass count to * previous good topology_count. Just in case it was modified during invalid sweep. */ /* clear out new topology node pointers in lid map */ if (lidmap) for (i=0; i<= STL_GET_UNICAST_LID_MAX(); i++) { lidmap[i].newNodep = NULL; lidmap[i].newPortp = NULL; } if (lidmap) for_all_nodes(&old_topology, nodep) { for_all_end_ports(nodep, portp) { // .pass will have only been updated if the LID was // checked and determined valid during the sweep. if (sm_valid_port(portp) && portp->portData->lid > 0 && portp->portData->lid <= STL_GET_UNICAST_LID_MAX() && lidmap[portp->portData->lid].pass >= (topology_passcount + 1)) { delta = 1 << portp->portData->lmc; nextLid = portp->portData->lid + delta; for (lid = portp->portData->lid; lid < nextLid; ++lid) lidmap[lid].pass = topology_passcount; } } } topology_free_topology(&sm_newTopology, TRUE, TRUE); IB_EXIT(__func__, 0); return; } // This is called from under the sm_newTopology lock and only modifies the // "build" cache, which is the cached data for the new topology. // Status_t sweep_cache_build(SweepContext_t *sweep_context) { Status_t rc; int i; SACacheEntry_t *cache; IB_ENTER(__func__, 0, 0, 0, 0); // allocate/build new cache structures for (i = 0; i < SA_NUM_CACHES; i++) { rc = vs_pool_alloc(&sm_pool, sizeof(SACacheEntry_t), (void*)&cache); if (rc != VSTATUS_OK) { IB_LOG_WARNRC("failed to allocate memory for SA cache structure rc:", rc); saCache.build[i] = NULL; } else { memset(cache, 0, sizeof(SACacheEntry_t)); rc = saCacheBuildFunctions[i](cache, &sm_newTopology); if (rc != VSTATUS_OK) { IB_LOG_WARN_FMT(__func__, "failed to build cache at index %d, rc: %u", i, rc); (void)vs_pool_free(&sm_pool, cache); saCache.build[i] = NULL; } else { saCache.build[i] = cache; } } } rc = VSTATUS_OK; IB_EXIT(__func__, rc); return rc; } // This is called from under the old_topology lock and copies the built cache // data into "current". // Status_t topology_cache_copy(void) { Status_t rc; int i, count; IB_ENTER(__func__, 0, 0, 0, 0); // save existing caches on the previous list if they're in use. // otherwise, free them. move caches for new topology into "current" for (i = 0, count = 0; i < SA_NUM_CACHES; i++) { if (saCache.current[i] != NULL) { if (saCache.current[i]->valid) { if (saCache.current[i]->refCount) { saCache.current[i]->next = saCache.previous; saCache.previous = saCache.current[i]; count++; } else { if (saCache.current[i]->data) (void)vs_pool_free(&sm_pool, saCache.current[i]->data); (void)vs_pool_free(&sm_pool, saCache.current[i]); } } else { (void)vs_pool_free(&sm_pool, saCache.current[i]); } } saCache.current[i] = saCache.build[i]; saCache.build[i] = NULL; } IB_LOG_INFO("in-use elements moved into SA cache history:", count); rc = VSTATUS_OK; IB_EXIT(__func__, rc); return rc; } Status_t copy_congestion_control_data(void) { Node_t *nodep; IB_ENTER(__func__, 0, 0, 0, 0); for_all_nodes(sm_topop, nodep) { Status_t status; if (AtomicRead(&topology_triggered)) { IB_LOG_INFINI_INFO0("New sweep request, delaying Congestion Configuration until after next sweep"); status = VSTATUS_OK; break; } if (nodep->nodeInfo.NodeType == STL_NODE_SW) status = stl_sm_cca_copy_sw_data(nodep); else status = stl_sm_cca_copy_hfi_data(nodep); if (status != VSTATUS_OK) IB_LOG_INFO_FMT(__func__, "Failed to copy CCA data for NodeGuid "FMT_U64" [%s]; rc: %d", nodep->nodeInfo.NodeGUID, sm_nodeDescString(nodep), status); } IB_EXIT(__func__, VSTATUS_OK); return VSTATUS_OK; } Status_t topology_congestion(void) { uint64_t sTime, eTime; Status_t status = VSTATUS_OK; IB_ENTER(__func__, 0, 0, 0, 0); if (smDebugPerf) { vs_time_get(&sTime); IB_LOG_INFINI_INFO0("START"); } if ((status = parallel_congestion(sm_psc_g)) != VSTATUS_OK) { return status; } if (smDebugPerf) { vs_time_get(&eTime); IB_LOG_INFINI_INFO("END, elapsed time (usec) - ", (int)(eTime-sTime)); } IB_EXIT(__func__, VSTATUS_OK); return VSTATUS_OK; } Status_t topology_assignments_delayedpkeys(void) { Status_t status; uint64_t sTime, eTime; if (smDebugPerf) { vs_time_get(&sTime); IB_LOG_INFINI_INFO0("START SET Delayed Pkey Writes"); } status = sm_set_delayed_pkeys(); if (smDebugPerf) { vs_time_get(&eTime); IB_LOG_INFINI_INFO("END SET Delayed Pkey Writes, elapsed time(usecs)=", (int)(eTime - sTime)); } return status; } Status_t topology_reregisters(void) { Status_t status; uint64_t sTime, eTime; if (smDebugPerf) { vs_time_get(&sTime); IB_LOG_INFINI_INFO0("START SET Client Reregister"); } status = sm_set_all_reregisters(); if (smDebugPerf) { vs_time_get(&eTime); IB_LOG_INFINI_INFO("END SET Client Reregister, elapsed time(usecs)=", (int)(eTime - sTime)); } return status; } static int s_esmLoopTestOption; static int s_esmLoopTestOptionSet; int esmLoopTestOptionSet(int val) { s_esmLoopTestOption = val; s_esmLoopTestOptionSet = TRUE; return 0; } int esmLoopTestOptionGet(void) { #if defined(__VXWORKS__) if (!s_esmLoopTestOptionSet) { s_esmLoopTestOption = bmGetValueAsInt("esmLoopTestOption", 0xb5); s_esmLoopTestOptionSet = TRUE; if (s_esmLoopTestOption == 0) { sysPrintf("Using historical loop test pattern\n"); } else sysPrintf("Using loop test pattern=0x%02x\n", s_esmLoopTestOption & 0xff); } #endif return s_esmLoopTestOption; } /* put the lop test message on the wire */ Status_t sendLoopMsg(int lid) { int option = esmLoopTestOptionGet(); Mai_t out_mad; Status_t status=VSTATUS_OK; uint64_t tid; mai_alloc_tid(fd_loopTest->fdMai, MAD_CV_SUBN_ADM, &tid); // send a mad packet out to the lid //IB_LOG_INFINI_INFOX("sending loop test packet out to LID ", lid); Mai_Init(&out_mad); AddrInfo_Init(&out_mad, sm_lid, lid, 0, getDefaultPKey(), MAI_GSI_QP, MAI_GSI_QP, GSI_WELLKNOWN_QKEY); LRMad_Init(&out_mad, MAD_CV_SUBN_ADM, MAD_CM_SEND, (tid), 0x777, 0x0, sm_config.mkey); if (option) { LRSmp_t *lrp = (LRSmp_t *)&out_mad.data; (void)memset((void *)lrp, (option & 0xff), sizeof(*lrp)); } else { char pktData[] = "LOOP TEST DATA PACKET....."; LRData_Init(&out_mad, pktData, sizeof(pktData)); } INCREMENT_COUNTER(smCounterSmPacketTransmits); status = mai_send(fd_loopTest->fdMai, &out_mad); if (status != VSTATUS_OK) { IB_LOG_ERRORRC("can't send loop mad rc:", status); } return(status); } // loop test packet inject Status_t sweep_loopTest (SweepContext_t *sweep_context) { int i,j; LoopPath_t *loopPath; IB_ENTER(__func__, 0, 0, 0, 0); if (!esmLoopTestOn) return VSTATUS_OK; if (smDebugPerf) { IB_LOG_INFINI_INFO_FMT(__func__, "FastMode=%d, FastMode MinISLRedundancy=%d, InjectEachSweep=%d, TotalPktsInjected since start=%d", esmLoopTestFast, esmLoopTestMinISLRedundancy, esmLoopTestInjectEachSweep, esmLoopTestTotalPktsInjected); } if (!esmLoopTestForceInject && !esmLoopTestInjectEachSweep && esmLoopTestTotalPktsInjected > 0) return VSTATUS_OK; // // Send loop messages. // for (j=1; j<=esmLoopTestNumPkts; j++) { if (esmLoopTestInjectNode >= 0) { // a specific switch is desired for (loopPath=sm_topop->loopPaths; loopPath != NULL; loopPath = loopPath->next) { for (i=1; i<=loopPath->nodeIdx[0]; i++) { if (esmLoopTestInjectNode == loopPath->nodeIdx[i]) { sendLoopMsg(loopPath->lid); break; } } } } else { // do all switches loops for (i=loopPathLidEnd; i>=loopPathLidStart; i--) { // send a mad packet out to the lid sendLoopMsg(i); } } } printf("sweep_loopTest: DONE\n"); if (loopPathLidEnd >= loopPathLidStart) { esmLoopTestTotalPktsInjected += esmLoopTestNumPkts; IB_LOG_INFINI_INFO_FMT(__func__, "Injected %d packets. Total packets injected since start of loop test = %d", esmLoopTestNumPkts, esmLoopTestTotalPktsInjected); } if (esmLoopTestForceInject) esmLoopTestForceInject = 0; IB_LOG_INFINI_INFO0("END sweep_loopTest"); return(VSTATUS_OK); } /* * Dump topology to console */ static char* dump_topology(char* buf, int buffer) { int i; Node_t *nodep; Port_t *portp; int len = 500; if (buffer && buf == NULL) { if (vs_pool_alloc(&sm_pool, len, (void*)&buf) != VSTATUS_OK) { IB_FATAL_ERROR_NODUMP("dump_topology: CAN'T ALLOCATE SPACE."); return NULL; } buf[0] = '\0'; } /* Dump each node and active port */ if (sm_state == SM_STATE_MASTER) { for_all_nodes(&old_topology, nodep) { char buf1[32], buf2[32], buf3[32], buf4[32]; buf = snprintfcat(buf, &len, "-----------------------------------------------------------------------------------------\n"); buf = snprintfcat(buf, &len, "%s\n", sm_nodeDescString(nodep)); buf = snprintfcat(buf, &len, "-----------------------------------------------------------------------------------------\n"); buf = snprintfcat(buf, &len, "Node[%3d] => "FMT_U64" (%x) ports=%d, path=", (int)nodep->index, nodep->nodeInfo.NodeGUID, nodep->nodeInfo.NodeType, (int)nodep->nodeInfo.NumPorts); for (i = 1; i <= (int)nodep->path[0]; i++) { buf = snprintfcat(buf, &len, "%2d ", nodep->path[i]); } buf = snprintfcat(buf, &len, "\n"); buf = snprintfcat(buf, &len, " Port ---- GUID ---- (S) LID LMC _VL_ __MTU__ __WIDTH__ _____SPEED_______ CAP_MASK N# P#\n"); for_all_ports(nodep, portp) { if (!sm_valid_port(portp) || portp->state <= IB_PORT_DOWN) { continue; } if (nodep->nodeInfo.NodeType == NI_TYPE_SWITCH && portp->index > 0) { buf = snprintfcat(buf, &len, "%12d "FMT_U64" %d %2d/%2d %3s/%3s %6s/%3s %11s %3s %08x %4d %2d ", portp->index, portp->portData->guid, (int)portp->state, portp->portData->vl0,portp->portData->vl1, IbMTUToText(portp->portData->mtuSupported), IbMTUToText(portp->portData->maxVlMtu), StlLinkWidthToText(portp->portData->portInfo.LinkWidth.Supported, buf1, sizeof(buf1)), StlLinkWidthToText(portp->portData->portInfo.LinkWidth.Active, buf2, sizeof(buf2)), GetStr_SpeedSupport(&portp->portData->portInfo, buf3, sizeof(buf3)), GetStr_SpeedActive(&portp->portData->portInfo, buf4, sizeof(buf4)), (int)portp->portData->capmask, (int)portp->nodeno, (int)portp->portno); } else { buf = snprintfcat(buf, &len, "%12d "FMT_U64" %d %08x %04x %2d/%2d %3s/%3s %6s/%3s %11s %3s %08x %4d %2d ", portp->index, portp->portData->guid, (int)portp->state, (int)portp->portData->lid, portp->portData->lmc, portp->portData->vl0, portp->portData->vl1, IbMTUToText(portp->portData->mtuSupported), IbMTUToText(portp->portData->maxVlMtu), StlLinkWidthToText(portp->portData->portInfo.LinkWidth.Supported, buf1, sizeof(buf1)), StlLinkWidthToText(portp->portData->portInfo.LinkWidth.Active, buf2, sizeof(buf2)), GetStr_SpeedSupport(&portp->portData->portInfo, buf3, sizeof(buf3)), GetStr_SpeedActive(&portp->portData->portInfo, buf4, sizeof(buf4)), (int)portp->portData->capmask, (int)portp->nodeno, (int)portp->portno); } if (portp->path[0] != 0xff) { for (i = 1; i <= (int)portp->path[0]; i++) { buf = snprintfcat(buf, &len, "%2d ", portp->path[i]); } } buf = snprintfcat(buf, &len, "\n"); } buf = snprintfcat(buf, &len, "\n"); } buf = snprintfcat(buf, &len, "==================================================================================\n"); } /* if state is Master */ return buf; } Status_t topology_dump(void) { //int i; //Node_t *nodep; //Port_t *portp; IB_ENTER(__func__, 0, 0, 0, 0); // // If we are NOT debugging, then return. // if (sm_debug == 0) { IB_EXIT(__func__, VSTATUS_OK); return(VSTATUS_OK); } // // Only display if there are changes. // if ((topology_changed == 0) || (topology_once < 0)) { IB_EXIT(__func__, VSTATUS_OK); return(VSTATUS_OK); } topology_once++; /* Dump the SM state, pass count, MAD count, priority, and MKey */ printf("\nsm_state = %s count = %d LMC = %d, Topology Pass count = %d, Priority = %d, Mkey = "FMT_U64"\n\n", sm_getStateText(sm_state), (int)sm_smInfo.ActCount, (int)sm_config.lmc, (int)topology_passcount, sm_smInfo.u.s.Priority, sm_config.mkey); if (sm_state == SM_STATE_MASTER) { dump_topology(NULL, /* do not buffer */ 0); dump_cost_array((uint16_t *)sm_newTopology.cost); (void)fflush(stdout); showSmParms(); (void)fflush(stdout); printSwitchLft(-1, 1, 1, /* do not buffer */ 0); /* Print all lfts from new topo and we already have the lock */ (void)fflush(stdout); } IB_EXIT(__func__, VSTATUS_OK); return(VSTATUS_OK); } char* sm_topology_dump(int buffer) { char * buf = NULL; int len = 500; IB_ENTER(__func__, 0, 0, 0, 0); if (buffer) { if (vs_pool_alloc(&sm_pool, len, (void*)&buf) != VSTATUS_OK) { IB_FATAL_ERROR_NODUMP("sm_topology_dump: CAN'T ALLOCATE SPACE."); return NULL; } buf[0] = '\0'; } if (topology_passcount < 1) { if (sm_state == 0xffffffff) { buf = snprintfcat(buf, &len, "Fabric Manager is not running at this time!\n"); } else { buf = snprintfcat(buf, &len, "\nSM is currently in the %s state, count = %d, Priority = %d, Mkey = "FMT_U64"\n\n", sm_getStateText(sm_state), (int)sm_smInfo.ActCount, sm_smInfo.u.s.Priority, sm_config.mkey); } return buf; } (void)vs_rdlock(&old_topology_lock); // // Dump the SM state and MAD count. // snprintfcat(buf, &len, "\nsm_state = %s count = %d LMC = %d, Topology Pass count = %d, Priority = %d, Mkey = "FMT_U64"\n\n", sm_getStateText(sm_state), (int)sm_smInfo.ActCount, (int)sm_config.lmc, (int)topology_passcount, sm_smInfo.u.s.Priority, sm_config.mkey); // // Dump each node and active port. // if (sm_state == SM_STATE_MASTER) { buf = dump_topology(buf, buffer); } /* if state is Master */ (void)vs_rwunlock(&old_topology_lock); IB_EXIT(__func__, VSTATUS_OK); return buf; } void dump_cost_array(uint16_t *cost) { int ij; int i, j; int num_nodes = sm_topop->max_sws; IB_ENTER(__func__, 0, 0, 0, 0); if (cost) { printf("\nCOST:\n"); printf(" i j"); for (j = 0; j < num_nodes; j++) { printf("%6d", j); } printf("\n"); for (i = 0; i < sm_topop->num_nodes; i++) { printf("%6d ", i); for (j = 0; j < sm_topop->num_nodes; j++) { ij = Index(i, j); printf("%6d", (int)cost[ij]); } printf("\n"); } } else { printf("\nCOST MATRIX IS NULL.\n"); } printf("\n************************************************\n\n"); IB_EXIT(__func__, VSTATUS_OK); return; } void showSmParms() { if (sm_state > SM_STATE_NOTACTIVE) { printf("SM priority is set to %d\n", (int)sm_config.priority); printf("SM elevated priority is set to %d\n", (int)sm_config.elevated_priority); printf("SM LMC is set to %d\n", (int)sm_config.lmc); printf("SM E0 LMC is set to %d\n", (int)sm_config.lmc_e0); printf("SM sweep rate is set to %d\n", (int)sm_getSweepRate()); printf("SM max attempts on receive set to %d \n", (int)sm_config.max_retries); printf("SM max receive wait interval set to %d millisecs\n", (int)sm_config.rcv_wait_msec); printf("switchLifetime set to %d \n", (int)sm_config.switch_lifetime_n2); printf("HoqLife set to %d \n", (int)sm_config.hoqlife_n2); printf("VL Stall set to %d \n", (int)sm_config.vlstall); printf("packetLifetime constant is set to %d \n", (int)sm_config.sa_packet_lifetime_n2); if (sa_dynamicPlt[0] == 1) { printf("Dynamic PLT ON using values: 1 hop=%d, 2 hops=%d, 3 hops=%d, 4 hops=%d, 5 hops=%d, 6 hops=%d, 7 hops=%d, 8+hops=%d \n", sa_dynamicPlt[1], sa_dynamicPlt[2], sa_dynamicPlt[3], sa_dynamicPlt[4], sa_dynamicPlt[5], sa_dynamicPlt[6], sa_dynamicPlt[7], sa_dynamicPlt[9]); } else { printf("Dynamic PLT is OFF, using constant value of %d \n", (int)sm_config.sa_packet_lifetime_n2); } printf("SM DBSync interval set to %d \n", (int)sm_config.db_sync_interval); printf("SM topology errors threshold set to %d, max retry to %d\n", (int)sm_config.topo_errors_threshold, (int)sm_config.topo_abandon_threshold); } else { printf("SM is not active on this node!\n"); } } void setRcvRetries(uint8_t retryCount) { if (retryCount > 0 && retryCount <= 10) { sm_config.max_retries = retryCount; printf("SM max attempts on receive set to %d\n", (int)sm_config.max_retries); } else { printf("SM max attempts on receive should be 1-10; Current value is %d\n", (int)sm_config.max_retries); } } void setRcvWait(uint32_t rcvwait) { if (rcvwait >= 32 && rcvwait <= 10000) { sm_config.rcv_wait_msec = rcvwait; printf("SM receive wait interval set to %d millisecs\n", (int)sm_config.rcv_wait_msec); } else { printf("SM receive wait interval should be between 32 msecs and 10000 msecs; Current value is %d millisecs\n", (int)sm_config.rcv_wait_msec); } } void setSwitchLifetime(uint8_t sl) { if (sl <= SM_MAX_SWITCH_LIFETIME) { sm_config.switch_lifetime_n2 = sl; sysPrintf(SYS_PINFO"switchLifetime set to %d; force an SM sweep to make changes go into effect \n", (int)sm_config.switch_lifetime_n2); } else { printf("switchLifetime should be %d-%d; current value is %d \n", SM_MIN_SWITCH_LIFETIME, SM_MAX_SWITCH_LIFETIME, (int)sm_config.switch_lifetime_n2); } } void setHoqLife(uint8_t hoq) { if (hoq <= SM_MAX_HOQ_LIFE) { sm_config.hoqlife_n2 = hoq; sysPrintf(SYS_PINFO"HoqLife set to %d; force an SM sweep to make changes go into effect \n", (int)sm_config.hoqlife_n2); } else { printf("HoqLife should be (%d-%d); current value is %d \n", SM_MIN_HOQ_LIFE, SM_MAX_HOQ_LIFE, (int)sm_config.hoqlife_n2); } } void setVlStall(uint8_t stall) { if (stall >= SM_MIN_VL_STALL && stall <= SM_MAX_VL_STALL) { sm_config.vlstall = stall; sysPrintf(SYS_PINFO"VL Stall set to %d; force an SM sweep to make changes go into effect \n", (int)sm_config.vlstall); } else { printf("VL Stall should be %d-%d; current value is %d \n", SM_MIN_VL_STALL, SM_MAX_VL_STALL, (int)sm_config.vlstall); } } void topology_main_kill(void){ topology_main_exit = 1; // XXX get this through sweep context struct? may be psc_<> api functions should not be exposed sweep context struct? psc_stop(sm_psc_g); } // TBD - this code is a duplicate VxWorks specific copy of code in other HSM // tools such as test/smi/sm/smpoolsize.c char* printTopology(int buffer) { return sm_topology_dump(buffer); } #ifdef __VXWORKS__ int printMasterLMC() { sysPrintf("The master LMC is %d\n", (int)sm_config.lmc); return (int)sm_config.lmc; } int printSMLid() { sysPrintf("The SM LID is 0x%.4X\n", (int)sm_lid); return (int)sm_lid; } int printMasterSMLid() { STL_PORT_INFO portInfo; uint8_t path[64]; Status_t status; (void)memset((void *)path, 0, 64); SmpAddr_t addr = SMP_ADDR_CREATE_DR(path); if ((status = SM_Get_PortInfo(fd_sminfo, 1<<24, &addr, &portInfo)) != VSTATUS_OK) { sysPrintf("Unable to obtain Master SM LID - status=%d\n", (int)status); } else { sysPrintf("The Master SM LID is 0x%.4X\n", portInfo.MasterSMLID); } return (int)portInfo.MasterSMLID; } void dumpLidMap() { int i; int lastSet = 1; Port_t *portp=NULL; if (topology_passcount >= 1) { sysPrintf("----------------------------------------------------------------------------------\n"); sysPrintf("SM is currently in the %s state, with Topology Pass count = %d\n", sm_getStateText(sm_state), (int)topology_passcount); sysPrintf("----------------------------------------------------------------------------------\n"); (void)vs_rdlock(&old_topology_lock); for (i = 1; i <= STL_GET_UNICAST_LID_MAX(); ++i) { if (lidmap[i].guid == 0) { if (lastSet || i == STL_GET_UNICAST_LID_MAX()) { sysPrintf("Lid 0x%.8x: guid = 0x%.8x%.8x, pass = %u\n", i, (unsigned int)(lidmap[i].guid >> 32),(unsigned int)(lidmap[i].guid & 0xffffffffULL), (unsigned int)lidmap[i].pass); lastSet = 0; } } else { if ((topology_passcount-lidmap[i].pass == 0) && (portp = sm_find_port_guid(&old_topology, lidmap[i].guid)) != NULL) { sysPrintf("Lid 0x%.8x: guid = 0x%.8x%.8x, pass = %u, %s\n", i, (unsigned int)(lidmap[i].guid >> 32),(unsigned int)(lidmap[i].guid & 0xffffffffULL), (unsigned int)lidmap[i].pass, sm_nodeDescString((Node_t *)(portp->portData->nodePtr))); } else { sysPrintf("Lid 0x%.8x: guid = 0x%.8x%.8x, pass = %u\n", i, (unsigned int)(lidmap[i].guid >> 32),(unsigned int)(lidmap[i].guid & 0xffffffffULL), (unsigned int)lidmap[i].pass); } lastSet = 1; } } (void)vs_rwunlock(&old_topology_lock); } else { if (sm_state == 0xffffffff) { sysPrintf("\nSM is not running at this time!\n\n"); } else { sysPrintf("\nSM is currently in the %s state, count = %d\n\n", sm_getStateText(sm_state), (int)sm_smInfo.ActCount); } } } int printMaxLid() { if (topology_passcount >= 1) { sysPrintf("The maximum LID is 0x%.4X\n", (int)old_topology.maxLid); } else { if (sm_state == 0xffffffff) { sysPrintf("\nSM is not running at this time!\n\n"); } else { sysPrintf("\nSM is currently in the %s state, count = %d\n\n", sm_getStateText(sm_state), (int)sm_smInfo.ActCount); } } return old_topology.maxLid; } int smCASize(void) { size_t size = sizeof(Node_t) + (3 * sizeof(Port_t)) + sizeof(PortData_t); sysPrintf("The size of one FI in the topology is %d bytes\n", size); return size; } int smSwitchSize(int numSwitches, int numPorts, int numActivePorts, int numSwitches2, int numFIs, int lmc, int mlidTableCap) { size_t size; int sizelft; //@todo: probably not the right size since we round-up now instead of doing '+ 64' for LFT allocations sizelft = (numSwitches + numSwitches2 + numFIs) * (1 << lmc) + 64; //sysPrintf("The size of a Switch LFT table is %d bytes\n", sizelft); size = sizeof(Node_t); size += ((numPorts + 1) * (sizeof(Port_t))) + ((numActivePorts+1) * sizeof(PortData_t)); //size += ((numPorts2 + 1) * (sizeof(Port_t))) + ((numActivePorts2+1) * sizeof(PortData_t)) size += 16 + sizelft + sizeof(uint16_t * ) * mlidTableCap + sizeof(uint16_t) * mlidTableCap * 16; sysPrintf("The average size of one Switch in the topology is %d bytes\n", size); return size; } int smPortSize(void) { size_t size = sizeof(Port_t) + sizeof(PortData_t); sysPrintf("The size of one port in the topology is %d bytes\n", size); return size; } int smLidmapSize(void) { size_t size = sizeof(LidMap_t) * (STL_GET_UNICAST_LID_MAX() + 1); sysPrintf("The size LidMap in the topology is %d bytes\n", size); return size; } void smFabricSizeUsage(void) { fprintf(stderr, "smFabricSize #FIs #SwType1 #PortsSwType1 #SwType2 #PortsSwType2 #ActivePortsSwType2 -l lmc\n"); fprintf(stderr, " must enter #FIs, #SwType1, and #PortsSwType1 at minimum\n"); fprintf(stderr, " all other entries default to zero if not entered\n"); return; } uint64_t smFabricSize(int numFIs, int numSwitches, int numSwitchPorts, int numSwitches2, int numSwitchPorts2, int numSwitchActivePorts2, int nsp2, int lmc) { size_t numTopologies = 2; size_t numMcGroups = 4; size_t numCaSubscriptions = 4; size_t numManagers = 4; // PM, BM, FE, PSM size_t numSmSubs = 7; // PM, BM, FE all do GID IN/OUT, FE does PortState size_t numStandbys = 2; size_t numHostServices = 2; if (!numFIs || !numSwitches || !numSwitchPorts) { smFabricSizeUsage(); return 0; } // probably not the right size since we do 'ROUNDUP' instead of '+ 64'; also should change to size_t to guard against overflow int sizelft = (numSwitches + numSwitches2 + numFIs) * (1 << lmc) + 64; sysPrintf("The size of a Switch LFT table is %d bytes\n", sizelft); uint64_t caSize = smCASize() * numTopologies; uint64_t switchSize = smSwitchSize(numSwitches, numSwitchPorts, numSwitchPorts, numSwitches2, numFIs, lmc, DEFAULT_SW_MLID_TABLE_CAP) * numTopologies; uint64_t switchSize2 = smSwitchSize(numSwitches2, numSwitchPorts2, numSwitchActivePorts2, numSwitches, numFIs, lmc, DEFAULT_SW_MLID_TABLE_CAP) * numTopologies; uint64_t subscriberSize = saSubscriberSize(); uint64_t serviceRecordSize = saServiceRecordSize(); uint64_t groupSize = saMcGroupSize(); uint64_t memberSize = saMcMemberSize(); uint64_t pathArraySize = sizeof(uint16_t) * numTopologies; uint64_t costArraySize = sizeof(uint16_t) * numTopologies; uint64_t maxResponseSize = saMaxResponseSize(); uint64_t nodeRecordSize = saNodeRecordSize(); uint64_t lidMapSize = smLidmapSize(); uint64_t smSize = numSmSubs * subscriberSize + numManagers * serviceRecordSize; uint64_t standbySize = smSize * numStandbys; uint64_t size = 0; caSize += numHostServices * serviceRecordSize + numCaSubscriptions * subscriberSize + numMcGroups * memberSize; caSize *= numFIs; switchSize *= numSwitches; switchSize2 *= numSwitches2; /* now for total switch size */ switchSize += switchSize2; groupSize *= numMcGroups; costArraySize *= (numSwitches+numSwitches2) * (numSwitches+numSwitches2); pathArraySize *= (numSwitches+numSwitches2) * (numSwitches+numSwitches2); /* lets assume max 4 sweeps worth of SA noderecord caching */ nodeRecordSize *= (numFIs+numSwitches+numSwitches2) * 4; size = caSize + switchSize + smSize + standbySize + groupSize + costArraySize + pathArraySize + maxResponseSize + nodeRecordSize + lidMapSize; // add in 10% fudge factor size += size/10; sysPrintf("The total for FIs in the fabric is %"CS64"d bytes\n", caSize); sysPrintf("The total for switches in the fabric is %"CS64"d bytes\n", switchSize); sysPrintf("The total for the master SM is %"CS64"d bytes\n", smSize); sysPrintf("The total for %d standby SMs is %"CS64"d bytes\n", numStandbys, standbySize); sysPrintf("The total for %d multicast groups is %"CS64"d bytes\n", numMcGroups, groupSize); sysPrintf("The total for the cost array is %"CS64"d bytes\n", costArraySize); sysPrintf("The total for the path array is %"CS64"d bytes\n", pathArraySize); sysPrintf("The total for the LidMap is %"CS64"d bytes\n", lidMapSize); sysPrintf("The total for SA max response is %"CS64"d bytes\n", maxResponseSize); sysPrintf("The total for sending all node records to 1/4 the nodes at once is %"CS64"d bytes\n", nodeRecordSize); sysPrintf("The topology size of a fabric with %d FIs and %d %d port switches and %d %d port (%d active) switches is %"CS64"d bytes\n", numFIs, numSwitches, numSwitchPorts, numSwitches2, numSwitchPorts2, numSwitchActivePorts2, size); return size; } #endif void printDgVfMemberships(void) { #if 0 (void)vs_rdlock(&old_topology_lock); VirtualFabrics_t *VirtualFabrics = old_topology.vfs_ptr; //Print DG and VF memberships for every port on all nodes int idx; int dgIdx; int numPorts; Node_t *nodep; Port_t* portPtr; DGConfig_t*dgp; IB_LOG_INFINI_INFO_FMT(__func__, "Device Group Info:"); for (dgIdx=0; dgIdx<dg_config.number_of_dgs; ++dgIdx) { dgp = dg_config.dg[dgIdx]; if (dgp->name != NULL) IB_LOG_INFINI_INFO_FMT(__func__, " DG: %s Idx: %d", dgp->name, dgIdx); } //Print all defined VFs int vfIdx = 0; int vf; if (VirtualFabrics) { VF_t* vfp; IB_LOG_INFINI_INFO_FMT(__func__, "Number of Active VFs: %d", VirtualFabrics->number_of_vfs_all); for (vf=0; vf < VirtualFabrics->number_of_vfs_all; vf++) { vfp = &VirtualFabrics->v_fabrics_all[vf]; if (VirtualFabrics->v_fabric_all[vf].standby) continue; IB_LOG_INFINI_INFO_FMT(__func__, " VF: %s Idx: %d", vfp->name, vfp->index); } } char dbgBuf[500]; int len = 500; for (idx = 0, nodep = sm_topop->node_head; nodep != NULL; ++idx, nodep = nodep->next) { numPorts = nodep->nodeInfo.NumPorts; int numDgMemberships = 0; int numVfMemberships = 0; for_all_ports(nodep,portPtr) { if (!sm_valid_port(portPtr) || portPtr->state <= IB_PORT_DOWN) continue; else { snprintf(dbgBuf, len, "%s:%d DG: ", nodep->nodeDesc.NodeString, portPtr->index); //loop and print all dg indexes for this port numDgMemberships = 0; for (dgIdx=0; (dgIdx = bitset_find_next_one(&portPtr->portData->dgMember, dgIdx)) != -1; dgIdx++) { if (numDgMemberships) { snprintfcat(dbgBuf, &len, ", %d", dgIdx); } else { snprintfcat(dbgBuf, &len, "%d", dgIdx); } numDgMemberships++; } snprintfcat(dbgBuf, &len, " VF: "); numVfMemberships = 0; for (vfIdx=0; (vfIdx = bitset_find_next_one(&portPtr->portData->vfMember, vfIdx)) != -1; vfIdx++) { if (numVfMemberships) { snprintfcat(dbgBuf, &len, ", %d", vfIdx); } else { snprintfcat(dbgBuf, &len, "%d", vfIdx); } numVfMemberships++; } if ((numDgMemberships == 0) && (numVfMemberships == 0) ) snprintfcat(dbgBuf, &len, " -- No DG or VF Memberships"); IB_LOG_INFINI_INFO_FMT(__func__, "%s", dbgBuf); } } } (void)vs_rwunlock(&old_topology_lock); #endif }
34.667163
194
0.683727
[ "3d" ]
6e0506dd0e55d93642497ee3c127afbd06ee9c59
26,634
h
C
WRK-V1.2/csharp/inc/predeftype.h
intj-t/openvmsft
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
[ "Intel" ]
null
null
null
WRK-V1.2/csharp/inc/predeftype.h
intj-t/openvmsft
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
[ "Intel" ]
null
null
null
WRK-V1.2/csharp/inc/predeftype.h
intj-t/openvmsft
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
[ "Intel" ]
null
null
null
// ==++== // // // Copyright (c) 2006 Microsoft Corporation. All rights reserved. // // The use and distribution terms for this software are contained in the file // named license.txt, which can be found in the root of this distribution. // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // You must not remove this notice, or any other, from this software. // // // ==--== // =========================================================================== // File: predeftyp.h // // Contains a list of the various predefined types. // =========================================================================== #if !defined(PREDEFTYPEDEF) #error Must define PREDEFTYPEDEF macro before including predeftyp.h #endif // The "required" column is very important. It means that the compiler requires that type to // be present in any compilation. It should only be set for types we know will be on any // platform. If not set, then the compiler may only require the type for certain constructs. // id full type name required simple numer AggKind fund type elementtype, nice name, zero, quasi simple numer, attribute arg size serialization type, predef attribute, arity, in mscorlib) PREDEFTYPEDEF(PT_BYTE, "System.Byte", 1, 1, 1, Struct, FT_U1, ELEMENT_TYPE_U1, L"byte", 0, 0, 1, SERIALIZATION_TYPE_U1, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_SHORT, "System.Int16", 1, 1, 1, Struct, FT_I2, ELEMENT_TYPE_I2, L"short", 0, 0, 2, SERIALIZATION_TYPE_I2, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_INT, "System.Int32", 1, 1, 1, Struct, FT_I4, ELEMENT_TYPE_I4, L"int", 0, 0, 4, SERIALIZATION_TYPE_I4, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_LONG, "System.Int64", 1, 1, 1, Struct, FT_I8, ELEMENT_TYPE_I8, L"long", &longZero, 0, 8, SERIALIZATION_TYPE_I8, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_FLOAT, "System.Single", 1, 1, 1, Struct, FT_R4, ELEMENT_TYPE_R4, L"float", &doubleZero, 0, 4, SERIALIZATION_TYPE_R4, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_DOUBLE, "System.Double", 1, 1, 1, Struct, FT_R8, ELEMENT_TYPE_R8, L"double", &doubleZero, 0, 8, SERIALIZATION_TYPE_R8, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_DECIMAL,"System.Decimal", 0, 1, 1, Struct, FT_STRUCT, ELEMENT_TYPE_END, L"decimal", &decimalZero, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_CHAR, "System.Char", 1, 1, 0, Struct, FT_U2, ELEMENT_TYPE_CHAR, L"char", 0, 0, 2, SERIALIZATION_TYPE_CHAR, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_BOOL, "System.Boolean", 1, 1, 0, Struct, FT_I1, ELEMENT_TYPE_BOOLEAN, L"bool", 0, 0, 1, SERIALIZATION_TYPE_BOOLEAN, PA_COUNT, 0, 1) // "simple" types are certain types that the compiler knows about for conversion and operator purposes.ses. // Keep these first so that we can build conversion tables on their ordinals... Don't change the orderder // of the simple types because it will mess up conversion tables. // The following Quasi-Simple types are considered simple, except they are non-CLS compliant PREDEFTYPEDEF(PT_SBYTE, "System.SByte", 1, 1, 1, Struct, FT_I1, ELEMENT_TYPE_I1, L"sbyte", 0, 1, 1, SERIALIZATION_TYPE_I1, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_USHORT, "System.UInt16", 1, 1, 1, Struct, FT_U2, ELEMENT_TYPE_U2, L"ushort", 0, 1, 2, SERIALIZATION_TYPE_U2, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_UINT, "System.UInt32", 1, 1, 1, Struct, FT_U4, ELEMENT_TYPE_U4, L"uint", 0, 1, 4, SERIALIZATION_TYPE_U4, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_ULONG, "System.UInt64", 1, 1, 1, Struct, FT_U8, ELEMENT_TYPE_U8, L"ulong", &longZero, 1, 8, SERIALIZATION_TYPE_U8, PA_COUNT, 0, 1) // The special "pointer-sized int" types. Note that this are not considered numeric types from the compiler's point of view -- // they are special only in that they have special signature encodings. // id full type name required simple numer AggKind fund type elementtype, nice name, zero, quasi simple numer, attribute arg size serialization type, predef attribute, arity, in mscorlib) PREDEFTYPEDEF(PT_INTPTR, "System.IntPtr", 1, 0, 0, Struct, FT_STRUCT,ELEMENT_TYPE_I, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_UINTPTR, "System.UIntPtr", 1, 0, 0, Struct, FT_STRUCT,ELEMENT_TYPE_U, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) // id full type name required simple numer AggKind fund type elementtype, nice name, zero, quasi simple numer, attribute arg size serialization type, predef attribute, arity, in mscorlib) PREDEFTYPEDEF(PT_OBJECT, "System.Object", 1, 0, 0, Class, FT_REF, ELEMENT_TYPE_OBJECT, L"object", 0, 0, -1, SERIALIZATION_TYPE_TAGGED_OBJECT, PA_COUNT, 0, 1) // THE ORDER ABOVE HERE IS IMPORTANT!!! It is used in tables in both fncbind and ilgen PREDEFTYPEDEF(PT_STRING, "System.String", 1, 0, 0, Class, FT_REF, ELEMENT_TYPE_STRING, L"string", 0, 0, -1, SERIALIZATION_TYPE_STRING, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_DELEGATE,"System.Delegate", 1, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_MULTIDEL,"System.MulticastDelegate", 1, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_ARRAY, "System.Array", 1, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_EXCEPTION,"System.Exception", 1, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_TYPE, "System.Type", 1, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, -1, SERIALIZATION_TYPE_TYPE, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_CRITICAL,"System.Threading.Monitor", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_VALUE, "System.ValueType", 1, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_ENUM, "System.Enum", 1, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) // predefined attribute types PREDEFTYPEDEF(PT_SECURITYATTRIBUTE, "System.Security.Permissions.CodeAccessSecurityAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_SECURITYPERMATTRIBUTE, "System.Security.Permissions.SecurityPermissionAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_UNVERIFCODEATTRIBUTE, "System.Security.UnverifiableCodeAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_DEBUGGABLEATTRIBUTE, "System.Diagnostics.DebuggableAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_DEBUGGABLE, 0, 1) PREDEFTYPEDEF(PT_MARSHALBYREF, "System.MarshalByRefObject", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_CONTEXTBOUND, "System.ContextBoundObject", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_IN, "System.Runtime.InteropServices.InAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_IN, 0, 1) PREDEFTYPEDEF(PT_OUT, "System.Runtime.InteropServices.OutAttribute", 1, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_OUT, 0, 1) PREDEFTYPEDEF(PT_ATTRIBUTE, "System.Attribute", 1, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_ATTRIBUTEUSAGE, "System.AttributeUsageAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_ATTRIBUTEUSAGE, 0, 1) PREDEFTYPEDEF(PT_ATTRIBUTETARGETS, "System.AttributeTargets", 0, 0, 0, Enum, FT_STRUCT, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_OBSOLETE, "System.ObsoleteAttribute",0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_OBSOLETE, 0, 1) PREDEFTYPEDEF(PT_CONDITIONAL, "System.Diagnostics.ConditionalAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_CONDITIONAL, 0, 1) PREDEFTYPEDEF(PT_CLSCOMPLIANT, "System.CLSCompliantAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_CLSCOMPLIANT, 0, 1) PREDEFTYPEDEF(PT_GUID, "System.Runtime.InteropServices.GuidAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_GUID, 0, 1) PREDEFTYPEDEF(PT_DEFAULTMEMBER, "System.Reflection.DefaultMemberAttribute", 1, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_DEFAULTMEMBER, 0, 1) PREDEFTYPEDEF(PT_PARAMS, "System.ParamArrayAttribute",1, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_PARAMARRAY, 0, 1) PREDEFTYPEDEF(PT_COMIMPORT, "System.Runtime.InteropServices.ComImportAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COMIMPORT, 0, 1) PREDEFTYPEDEF(PT_FIELDOFFSET, "System.Runtime.InteropServices.FieldOffsetAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_STRUCTOFFSET, 0, 1) PREDEFTYPEDEF(PT_STRUCTLAYOUT, "System.Runtime.InteropServices.StructLayoutAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_STRUCTLAYOUT, 0, 1) PREDEFTYPEDEF(PT_LAYOUTKIND, "System.Runtime.InteropServices.LayoutKind", 0, 0, 0, Enum, FT_STRUCT, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_MARSHALAS, "System.Runtime.InteropServices.MarshalAsAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_DLLIMPORT, "System.Runtime.InteropServices.DllImportAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_DLLIMPORT, 0, 1) PREDEFTYPEDEF(PT_INDEXERNAME, "System.Runtime.CompilerServices.IndexerNameAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_NAME, 0, 1) PREDEFTYPEDEF(PT_DECIMALCONSTANT, "System.Runtime.CompilerServices.DecimalConstantAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_REQUIRED, "System.Runtime.CompilerServices.RequiredAttributeAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_REQUIRED, 0, 1) PREDEFTYPEDEF(PT_DEFAULTVALUE, "System.Runtime.InteropServices.DefaultParameterValueAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_DEFAULTVALUE, 0, 0) PREDEFTYPEDEF(PT_UNMANAGEDFUNCTIONPOINTER, "System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_UNMANAGEDFUNCTIONPOINTER, 0, 0) // predefined types for the BCL PREDEFTYPEDEF(PT_REFANY, "System.TypedReference", 0, 0, 0, Struct, FT_STRUCT,ELEMENT_TYPE_TYPEDBYREF, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_ARGITERATOR, "System.ArgIterator", 0, 0, 0, Struct, FT_STRUCT,ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_TYPEHANDLE, "System.RuntimeTypeHandle", 1, 0, 0, Struct, FT_STRUCT,ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_FIELDHANDLE, "System.RuntimeFieldHandle", 1, 0, 0, Struct, FT_STRUCT,ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_METHODHANDLE, "System.RuntimeMethodHandle", 0, 0, 0, Struct, FT_STRUCT,ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_ARGUMENTHANDLE, "System.RuntimeArgumentHandle", 0, 0, 0, Struct, FT_STRUCT,ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_HASHTABLE, "System.Collections.Hashtable", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_G_DICTIONARY, "System.Collections.Generic.Dictionary", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 2, 1) PREDEFTYPEDEF(PT_IASYNCRESULT, "System.IAsyncResult", 0, 0, 0, Interface,FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_ASYNCCBDEL, "System.AsyncCallback", 0, 0, 0, Delegate, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_SECURITYACTION,"System.Security.Permissions.SecurityAction", 0, 0, 0, Enum, FT_I4, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_IDISPOSABLE, "System.IDisposable", 1, 0, 0, Interface,FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_IENUMERABLE, "System.Collections.IEnumerable", 1, 0, 0, Interface,FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_IENUMERATOR, "System.Collections.IEnumerator", 1, 0, 0, Interface,FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_SYSTEMVOID, "System.Void", 1, 0, 0, Struct, FT_STRUCT, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_RUNTIMEHELPERS, "System.Runtime.CompilerServices.RuntimeHelpers", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) // signature MODIFIER for marking volatile fields PREDEFTYPEDEF(PT_VOLATILEMOD, "System.Runtime.CompilerServices.IsVolatile", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) // Sets the CoClass for a COM interface wrapper PREDEFTYPEDEF(PT_COCLASS, "System.Runtime.InteropServices.CoClassAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COCLASS, 0, 1) // For instantiating a type variable. PREDEFTYPEDEF(PT_ACTIVATOR, "System.Activator", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) // Generic variants of enumerator interfaces PREDEFTYPEDEF(PT_G_IENUMERABLE, "System.Collections.Generic.IEnumerable", 0, 0, 0, Interface,FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 1, 1) PREDEFTYPEDEF(PT_G_IENUMERATOR, "System.Collections.Generic.IEnumerator", 0, 0, 0, Interface,FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 1, 1) // Nullable<T> PREDEFTYPEDEF(PT_G_OPTIONAL, "System.Nullable", 0, 0, 0, Struct, FT_STRUCT, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 1, 1) // Marks a fixed buffer field PREDEFTYPEDEF(PT_FIXEDBUFFER, "System.Runtime.CompilerServices.FixedBufferAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_FIXED, 0, 1) // Sets the module-level default character set marshalling PREDEFTYPEDEF(PT_DEFAULTCHARSET, "System.Runtime.InteropServices.DefaultCharSetAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_DEFAULTCHARSET, 0, 1) // Used to disable string interning PREDEFTYPEDEF(PT_COMPILATIONRELAXATIONS, "System.Runtime.CompilerServices.CompilationRelaxationsAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COMPILATIONRELAXATIONS, 0, 1) // Used to enable wrapped exceptions PREDEFTYPEDEF(PT_RUNTIMECOMPATIBILITY, "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_RUNTIMECOMPATIBILITY, 0, 1) // Used for friend assmeblies PREDEFTYPEDEF(PT_FRIENDASSEMBLY, "System.Runtime.CompilerServices.InternalsVisibleToAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_FRIENDASSEMBLY, 0, 1) // Used to hide compiler-generated code from the debugger PREDEFTYPEDEF(PT_DEBUGGERHIDDEN, "System.Diagnostics.DebuggerHiddenAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) // Used for type forwarders PREDEFTYPEDEF(PT_TYPEFORWARDER, "System.Runtime.CompilerServices.TypeForwardedToAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_TYPEFORWARDER, 0, 1) // Used to warn on usage of this instead of command-line options PREDEFTYPEDEF(PT_KEYFILE, "System.Reflection.AssemblyKeyFileAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_KEYFILE, 0, 1) PREDEFTYPEDEF(PT_KEYNAME, "System.Reflection.AssemblyKeyNameAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_KEYNAME, 0, 1) PREDEFTYPEDEF(PT_DELAYSIGN, "System.Reflection.AssemblyDelaySignAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_DELAYSIGN, 0, 1) PREDEFTYPEDEF(PT_NOTSUPPORTEDEXCEPTION, "System.NotSupportedException", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_INTERLOCKED, "System.Threading.Interlocked", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_COMPILERGENERATED, "System.Runtime.CompilerServices.CompilerGeneratedAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_UNSAFEVALUETYPE, "System.Runtime.CompilerServices.UnsafeValueTypeAttribute", 0, 0, 0, Class, FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 0, 1) PREDEFTYPEDEF(PT_G_ICOLLECTION, "System.Collections.Generic.ICollection", 0, 0, 0, Interface,FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 1, 1) PREDEFTYPEDEF(PT_G_ILIST, "System.Collections.Generic.IList", 0, 0, 0, Interface,FT_REF, ELEMENT_TYPE_END, NULL, 0, 0, 0, 0, PA_COUNT, 1, 1) // Auto undef the macro. #undef PREDEFTYPEDEF
115.8
232
0.458887
[ "object" ]
6e067a80f473f7ad25012a570427944c2f854743
3,424
c
C
ijkplayer-armv7a/src/main/jni/ijkmedia/ijksdl/android/jjk/c/java/util/ArrayList.c
BigHeartC/IPTV_plus
3f1223a93bdd19c5ae6a3f37aca7acb59f569bcd
[ "Apache-2.0" ]
47
2015-12-22T12:52:36.000Z
2022-02-23T12:55:29.000Z
ijkplayer-x86/src/main/jni/ijkmedia/ijksdl/android/jjk/c/java/util/ArrayList.c
Mendim/IPTV_plus
3f1223a93bdd19c5ae6a3f37aca7acb59f569bcd
[ "Apache-2.0" ]
2
2016-03-23T06:46:23.000Z
2017-05-12T08:04:17.000Z
ijkplayer-x86/src/main/jni/ijkmedia/ijksdl/android/jjk/c/java/util/ArrayList.c
Mendim/IPTV_plus
3f1223a93bdd19c5ae6a3f37aca7acb59f569bcd
[ "Apache-2.0" ]
39
2015-12-22T16:26:57.000Z
2021-07-16T09:57:59.000Z
/* * copyright (c) 2015 Zhang Rui <bbcallen@gmail.com> * * This file is part of ijkPlayer. * * ijkPlayer 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. * * ijkPlayer 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 ijkPlayer; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "ArrayList.h" typedef struct JJKC_ArrayList { jclass id; jmethodID constructor_ArrayList; jmethodID method_add; } JJKC_ArrayList; static JJKC_ArrayList class_JJKC_ArrayList; jobject JJKC_ArrayList__ArrayList(JNIEnv *env) { return (*env)->NewObject(env, class_JJKC_ArrayList.id, class_JJKC_ArrayList.constructor_ArrayList); } jobject JJKC_ArrayList__ArrayList__catchAll(JNIEnv *env) { jobject ret_object = JJKC_ArrayList__ArrayList(env); if (JJK_ExceptionCheck__catchAll(env) || !ret_object) { return NULL; } return ret_object; } jobject JJKC_ArrayList__ArrayList__asGlobalRef__catchAll(JNIEnv *env) { jobject ret_object = NULL; jobject local_object = JJKC_ArrayList__ArrayList__catchAll(env); if (JJK_ExceptionCheck__catchAll(env) || !local_object) { ret_object = NULL; goto fail; } ret_object = JJK_NewGlobalRef__catchAll(env, local_object); if (!ret_object) { ret_object = NULL; goto fail; } fail: JJK_DeleteLocalRef__p(env, &local_object); return ret_object; } jboolean JJKC_ArrayList__add(JNIEnv *env, jobject thiz, jobject object) { return (*env)->CallBooleanMethod(env, thiz, class_JJKC_ArrayList.method_add, object); } jboolean JJKC_ArrayList__add__catchAll(JNIEnv *env, jobject thiz, jobject object) { jboolean ret_value = JJKC_ArrayList__add(env, thiz, object); if (JJK_ExceptionCheck__catchAll(env)) { return false; } return ret_value; } int JJK_loadClass__JJKC_ArrayList(JNIEnv *env) { int ret = -1; const char *JJK_UNUSED(name) = NULL; const char *JJK_UNUSED(sign) = NULL; jclass JJK_UNUSED(class_id) = NULL; int JJK_UNUSED(api_level) = 0; sign = "java/util/ArrayList"; class_JJKC_ArrayList.id = JJK_FindClass__asGlobalRef__catchAll(env, sign); if (class_JJKC_ArrayList.id == NULL) goto fail; class_id = class_JJKC_ArrayList.id; name = "<init>"; sign = "()V"; class_JJKC_ArrayList.constructor_ArrayList = JJK_GetMethodID__catchAll(env, class_id, name, sign); if (class_JJKC_ArrayList.constructor_ArrayList == NULL) goto fail; class_id = class_JJKC_ArrayList.id; name = "add"; sign = "(Ljava/lang/Object;)Z"; class_JJKC_ArrayList.method_add = JJK_GetMethodID__catchAll(env, class_id, name, sign); if (class_JJKC_ArrayList.method_add == NULL) goto fail; ALOGD("JJKLoader: OK: '%s' loaded\n", "java.util.ArrayList"); ret = 0; fail: return ret; }
30.300885
103
0.704439
[ "object" ]
6e0b80135ae5c6cd1be69d4301c7b8bd590007ff
108,013
c
C
aset_CCcc/src/SET_symbol.c
kit-transue/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
2
2015-11-24T03:31:12.000Z
2015-11-24T16:01:57.000Z
aset_CCcc/src/SET_symbol.c
radtek/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
null
null
null
aset_CCcc/src/SET_symbol.c
radtek/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
1
2019-05-19T02:26:08.000Z
2019-05-19T02:26:08.000Z
/************************************************************************* * Copyright (c) 2015, Synopsys, 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: * * * * 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 * * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *************************************************************************/ #include "basic_hdrs.h" #include "fe_common.h" #include "SET_symbol.h" #include "SET_names.h" #include "SET_symid.h" #include "SET_il.h" #include "SET_additions.h" #include "SET_complaints.h" #include "SET_ast.h" #include "SET_process_entry.h" #include "SET_scope.h" #include "symbol_tbl.h" #include "cmd_line.h" #include "il_to_str.h" /* The following variables are used for metering memory usage by the * functions in this file. */ static size_t sym_summary_meter; /* The following function adds a function name (given its routine_ptr) * to the string. */ void add_fcn_name_to_string(a_routine_ptr routine_ptr, string_buffer_ref bp) { a_type_ptr routine_type = skip_typerefs(routine_ptr->type); an_il_to_str_output_control_block_ptr ocb = ocb_of_string_buf(bp); form_name(&routine_ptr->source_corresp, iek_routine, ocb); if (routine_ptr->is_template_function) { form_template_args(routine_ptr->template_arg_list, ocb); } if (routine_type->variant.routine.extra_info && il_header.source_language == sl_Cplusplus && routine_ptr->source_corresp.name_linkage != nlk_external) { a_boolean saved_flag = ocb->suppress_all_typedefs; ocb->suppress_all_typedefs = TRUE; form_function_declarator(routine_type, ocb); ocb->suppress_all_typedefs = saved_flag; } } /* @@@ */ typedef struct a_retry *a_retry_ptr; typedef struct a_retry { char *entry_ptr; an_il_entry_kind entry_kind; a_retry_ptr next; } a_retry; a_retry_ptr retry_list = NULL; a_retry_ptr retry_list_last = NULL; /* Add entry to the retry list, for processing at end if not otherwise done. */ static void process_symbol_of_entry_if_needed(char *entry_ptr, an_il_entry_kind entry_kind) { if (!generate_multiple_IF_files && !il_entry_prefix_of(entry_ptr).SET_SYM_written) { a_retry_ptr retry = (a_retry_ptr)malloc(sizeof(a_retry)); retry->entry_ptr = entry_ptr; retry->entry_kind = entry_kind; retry->next = NULL; if (retry_list_last != NULL) { retry_list_last->next = retry; } else { retry_list = retry; } retry_list_last = retry; } } static void process_symbol_of_entry(char *entry_ptr, an_il_entry_kind entry_kind); /* Process entries on the retry list, for those which don't have SYMs written. */ void retry_process_symbol() { a_retry_ptr retry = retry_list; for (; retry != NULL; retry = retry->next) { if (!il_entry_prefix_of(retry->entry_ptr).SET_SYM_written) { process_symbol_of_entry(retry->entry_ptr, retry->entry_kind); } } } /* * -------------------- FORMATTING UTILITIES -------------------- * * functions: insert_sym_prefix decorate_name_and_finish * string_constant_to_string constant_to_string * format_rel write_rel add_access_spec write_context_rel * format_atr write_atr add_attrib expr_node_name * * These functions provide consistency of output and conciseness of * processing code when writing the various kinds of lines in the main * section of the IF file. In addition, the ...constant... functions * are used in creating AST operands. expr_node_name is used in * creating both preprocessor and parser AST nodes. */ /* The following function inserts the standard SYM prefix into the output * string in preparation for the insertion of the name (which must be * done on a per-kind basis). Note that the use of the macro * SET_symid_of has the side effect of assigning next_symid to the * entry and incrementing next_symid, if the entry does not already * have a symid. */ void insert_sym_prefix(const char* sym_kind, void* entry_ptr, an_il_entry_kind entry_kind, a_boolean compiler_generated, a_boolean from_template, string_buffer_ref output_buffer) { unsigned long id = SET_symid_of(entry_ptr, entry_kind); add_3_chars_to_string("SYM", output_buffer); add_symid_to_string(id, output_buffer); fulfill_SYM(entry_ptr); add_to_string(sym_kind, output_buffer); if (from_template) { add_to_string_with_len("_tmpl", 5, output_buffer); } if (compiler_generated) { add_to_string_with_len(" :cg", 4, output_buffer); } add_2_chars_to_string(" \"", output_buffer); /* mark the output buffer bit as set */ if (generate_multiple_IF_files) { set_outbuf_bit_of_clique(entry_ptr, output_buffer); } } /* The following function decorates the names of entities local to a * function with the function name and block number, if any; global * entities are left unchanged. It then adds the closing quote. */ void decorate_name_and_finish(const void* entry_ptr, an_il_entry_kind entry_kind, a_boolean add_block_qual, a_boolean add_closing_quote, string_buffer_ref bp) { if (fcn_name) { add_3_chars_to_string(" @ ", bp); add_to_string(fcn_name, bp); if (add_block_qual) { int *bstp = block_stack_top(); if (bstp != NULL) { add_num_to_string(*bstp, " {", "}", bp); } } } if (add_closing_quote) { add_1_char_to_string('\"', bp); } } /* The following function is parallel to decorate_name_and_finish, * for use when the block tracking is not valid. It works fine except * for nameless entities (including 'this'). */ static void finish_plain_name(const void* entry_ptr, an_il_entry_kind entry_kind, a_boolean add_block_qual, a_boolean add_closing_quote, string_buffer_ptr bp) { a_scope_ptr scp = scope_of_entry(entry_ptr, entry_kind); a_scope_ptr fscp = scp; while (fscp != NULL && ( fscp->kind == sck_func_prototype || fscp->kind == sck_block || fscp->kind == sck_condition)) { fscp = fscp->parent; } if (fscp != NULL && fscp->kind == sck_function) { add_3_chars_to_string(" @ ", bp); add_fcn_name_to_string(fscp->variant.routine.ptr, bp); if (add_block_qual) { if (scp->kind == sck_block || scp->kind == sck_condition) { int id = scp->if_id; if (id < 0) { complain(error_csev, "Can't put id of block into name."); } else { add_num_to_string(id, " {", "}", bp); } } } } else if (scp != NULL && scp->kind == sck_block) { complain(error_csev, "Can't form name for block."); } if (add_closing_quote) { add_1_char_to_string('\"', bp); } } /* Track which buffers have the SYM line for ellipsis. */ static unsigned char *ellipsis_outbuf_bit_arr = NULL; void write_ellipsis_symbol(unsigned long id, string_buffer_ptr output_buffer) { if (output_buffer != NULL && (!generate_multiple_IF_files || !is_output_buffer_bit_set(&ellipsis_outbuf_bit_arr, output_buffer))) { add_3_chars_to_string("SYM", output_buffer); add_symid_to_string(id, output_buffer); add_to_string("type \"...\"", output_buffer); terminate_string(output_buffer); write_atr(id, "ellipsis", output_buffer); /* mark the output buffer bit as set */ if (generate_multiple_IF_files) { set_output_buffer_bit(&ellipsis_outbuf_bit_arr, output_buffer); } } } void write_symbol_for_fcn_id(string_buffer_ptr bp) { if (generate_multiple_IF_files && curr_fcn) { write_symbol_for_il_node(curr_fcn, iek_routine, bp); } } void write_sym_line_for_source_file(a_source_file_ptr source, string_buffer_ptr output_buffer) { if (generate_multiple_IF_files && output_buffer != NULL && !is_output_buffer_bit_set(&source->SET_outbuf_bit_arr, output_buffer)) { if (!source->is_interesting || (get_buffer_of_source_file(source) != output_buffer)) { /* assign symid here */ if (!source->symid) { source->symid = next_symid++; } add_3_chars_to_string("SYM", output_buffer); add_symid_to_string(source->symid, output_buffer); add_to_string_with_len("file ", 5, output_buffer); add_quoted_str_to_string(absolute_path_of(source->full_name), TRUE /*add quotes*/, output_buffer); terminate_string(output_buffer); set_output_buffer_bit(&source->SET_outbuf_bit_arr, output_buffer); } } } void write_define_relation(a_seq_number seq, unsigned long symid, string_buffer_ptr output_buffer) { if (output_buffer != NULL) { a_line_number line_number; a_boolean at_end_of_source; unsigned long nesting_depth; a_source_file_ptr sfp = source_file_for_seq(seq, &line_number, &at_end_of_source, TRUE); if (sfp) { write_sym_line_for_source_file(sfp, output_buffer); write_rel(sfp->symid, "define", symid, output_buffer); } } } void write_type_rel_for_void_ptr(void* ilp, an_il_entry_kind il_kind, string_buffer_ptr output_buffer) { a_type_ptr type_ptr = (a_type_ptr)ilp; if (type_ptr->kind == tk_pointer && output_buffer != NULL) { a_type_ptr base_type = (a_type_ptr)type_ptr->variant.pointer.type; if (base_type->kind == tk_void) { format_rel(SET_symid_of(base_type, iek_type), "type", il_entry_prefix_of(type_ptr).SET_symid, output_buffer); add_to_string("pointer", output_buffer); terminate_string(output_buffer); } } } /* The following function adds a printable representation of a string * constant to the specified string_buffer. The spelling of the * constant is simply enclosed in quotes and embedded quotes are only * singly-escaped, that is, the three-character string a"b will be * represented as "\"a\"b\"", not as "\"a\\\"b\"". */ #define TRUNCATED_MSG "...<truncated>" #define MAX_STR_LEN_IN_IF (10000 - sizeof(TRUNCATED_MSG)) static void string_constant_to_string(a_constant_ptr constant_ptr, string_buffer_ref bp) { int i; a_targ_size_t len = constant_ptr->variant.string.length; char* str = constant_ptr->variant.string.value; a_boolean truncated; if (len > MAX_STR_LEN_IN_IF) { len = MAX_STR_LEN_IN_IF; truncated = TRUE; } else truncated = FALSE; if (is_wide_string_constant(constant_ptr)) { unsigned long wc; add_3_chars_to_string("L\\\"", bp); for (i = 0; i < len; i += targ_sizeof_wchar_t) { wc = extract_wide_char_from_string(str + i); /* Suppress the last character if NUL */ if (i != (len - targ_sizeof_wchar_t) || wc != '\0') { form_wide_char(wc, ocb_of_string_buf(bp)); } } } else { add_2_chars_to_string("\\\"", bp); for (i = 0; i < len; i++) { if (i != (len - 1) || str[i] != '\0') { form_char(str[i], ocb_of_string_buf(bp)); } } } if (truncated) { add_to_string(TRUNCATED_MSG, bp); } add_2_chars_to_string("\\\"", bp); } /* The following function adds a printable representation of a constant * to the specified string_buffer. * * This function uses the trial buffer. */ void constant_to_string(a_constant_ptr constant_ptr, string_buffer_ref bp) { if (constant_ptr->kind == ck_aggregate) { add_to_string("{...}", bp); } else if (constant_ptr->kind == ck_string) { string_constant_to_string(constant_ptr, bp); } else if (constant_ptr->kind == ck_address && constant_ptr->variant.address.kind == abk_constant && constant_ptr->variant.address.variant.constant->kind == ck_string) { string_constant_to_string(constant_ptr-> variant.address.variant.constant, bp); } else if (constant_ptr->type && is_character_type(constant_ptr->type)) { a_boolean ofl; add_1_char_to_string('\'', bp); form_char((char) value_of_integer_constant(constant_ptr, &ofl), ocb_of_string_buf(bp)); add_1_char_to_string('\'', bp); } else if (bp == &trial_buf) { complain(error_csev, "Can't convert constant in trial_buf."); } else { /* Suppress enumerator name in output (so that, e.g., * "enum { a = 5 }; a;" will show up as "5" and not "a" * in the AST, per Pero's spec). Cases where the enum * name is desired, as in the SYM line, are handled * by calling form_name directly instead of this fcn. */ an_il_to_str_output_control_block *trial_ocb = ocb_of_string_buf(&trial_buf); a_boolean saved_flag = trial_ocb->suppress_enum_name; trial_ocb->suppress_enum_name = TRUE; form_constant(constant_ptr, /*need_parens=*/FALSE, trial_ocb); trial_ocb->suppress_enum_name = saved_flag; add_quoted_str_to_string(terminate_string(&trial_buf), /*add_quotes=*/FALSE, bp); } } /* The following function creates an unterminated REL line (not * including any attributes on that line) in the output string_buffer. */ void format_rel(unsigned long first_symid, const char* rel_name, unsigned long second_symid, string_buffer_ref output_buffer) { add_3_chars_to_string("REL", output_buffer); add_symid_to_string(first_symid, output_buffer); add_1_char_to_string('\"', output_buffer); add_to_string(rel_name, output_buffer); add_1_char_to_string('\"', output_buffer); add_symid_to_string(second_symid, output_buffer); } /* The following function formats and terminates a REL line (without * attributes) in the output string_buffer. */ void write_rel(unsigned long first_symid, const char* rel_name, unsigned long second_symid, string_buffer_ptr output_buffer) { if (output_buffer != NULL) { format_rel(first_symid, rel_name, second_symid, output_buffer); terminate_string(output_buffer); } } /* The following function formats and terminates a REL line for the * "specialize" relation, including full, partial, and explicit * attributes. */ void write_specialize_rel(unsigned long inst_symid, unsigned long template_symid, const char* full_or_part, a_boolean is_explicit, string_buffer_ptr output_buffer) { if (output_buffer != NULL) { format_rel(inst_symid, "specialize", template_symid, output_buffer); if (full_or_part) { add_to_string(full_or_part, output_buffer); if (is_explicit) { add_to_string(",explicit", output_buffer); } } else if (is_explicit) { add_to_string("explicit", output_buffer); } terminate_string(output_buffer); } } /* The following function adds an access qualifier to the current * string being constructed in the output string_buffer. */ static void add_access_spec(int access_spec, string_buffer_ref output_buffer) { if (access_spec == as_public) { add_to_string("public", output_buffer); } else if (access_spec == as_protected) { add_to_string("protected", output_buffer); } else if (access_spec == as_private) { add_to_string("private", output_buffer); } else complain_int(error_csev, "Unexpected access $1", access_spec); } /* The following function formats and terminates a "context" REL line * in the output string_buffer, including the access specifier. */ void write_context_rel(unsigned long class_symid, unsigned long member_symid, int access, string_buffer_ptr output_buffer) { if (output_buffer != NULL) { format_rel(class_symid, "context", member_symid, output_buffer); add_access_spec(access, output_buffer); terminate_string(output_buffer); } } /* The following function formats an ATR line for the specified * symbol and attribute. */ static void format_atr(unsigned long symid, const char* attrib, string_buffer_ptr output_buffer) { if (output_buffer != NULL) { add_3_chars_to_string("ATR", output_buffer); add_symid_to_string(symid, output_buffer); add_to_string(attrib, output_buffer); } } /* The following function writes an ATR line to the IF file. */ void write_atr(unsigned long symid, const char* attrib, string_buffer_ptr output_buffer) { if (output_buffer != NULL) { format_atr(symid, attrib, output_buffer); terminate_string(output_buffer); } } #if 0 static a_type_ptr parent_class_of_entry(char *entry_ptr, an_il_entry_kind entry_kind) { switch(entry_kind) { case iek_constant: return ((a_constant_ptr)entry_ptr)->source_corresp.parent.class_type; case } #endif static void write_specialize_rel_for_templ_inst(a_symbol_ptr inst_sym, unsigned long inst_symid, string_buffer_ptr output_buffer) { if (output_buffer != NULL) { a_type_ptr inst_class = inst_sym->parent.class_type; a_symbol_ptr inst_class_sym = inst_class ? (a_symbol_ptr) inst_class->source_corresp.assoc_info : NULL; a_symbol_ptr tmpl_class = inst_class_sym ? inst_class_sym->variant.class_struct_union.extra_info-> class_template : NULL; a_symbol_ptr sym; for (sym = inst_sym->header->inactive_symbols; sym; sym = sym->next) { if (sym != inst_sym && sym->is_class_member) { a_type_ptr sym_tmpl_class = sym->parent.class_type; if (sym_tmpl_class && !is_auto_gen_class(sym_tmpl_class) && sym_tmpl_class->source_corresp.assoc_info && ((a_symbol_ptr) sym_tmpl_class->source_corresp.assoc_info)-> variant.class_struct_union.extra_info->class_template == tmpl_class && sym->kind == inst_sym->kind) { unsigned long tmpl_member_symid; if (sym->kind == sk_type) { tmpl_member_symid = SET_symid_and_write_sym(sym->variant.type.ptr, iek_type, output_buffer); } else if (sym->kind == sk_enum_tag) { tmpl_member_symid = SET_symid_and_write_sym(sym->variant.enumeration.type, iek_type, output_buffer); } else if (sym->kind == sk_constant) { tmpl_member_symid = SET_symid_and_write_sym(sym->variant.constant, iek_constant, output_buffer); } else if (sym->kind == sk_field) { tmpl_member_symid = SET_symid_and_write_sym(sym->variant.field.ptr, iek_field, output_buffer); } else if (sym->kind == sk_projection) { tmpl_member_symid = 0; } else { complain_int(error_csev, "Unexpected template member kind $1", sym->kind); tmpl_member_symid = 0; } if (tmpl_member_symid) { write_specialize_rel(inst_symid, tmpl_member_symid, NULL, FALSE, output_buffer); } } } } } } /* The following function is called to add an attribute to the specified * string_buffer. The atr_added parameter is used to keep track of * whether a comma is needed before adding the string. */ static void add_attrib(const char* attrib, a_boolean* atr_added, string_buffer_ref bp) { if (*atr_added) { add_2_chars_to_string(", ", bp); } add_to_string(attrib, bp); *atr_added = TRUE; } static a_boolean is_anonymous(a_tagged_pointer ent) { an_il_entry_kind kind = (an_il_entry_kind)ent.kind; a_source_correspondence_ptr scp = source_corresp_of_entry(ent.ptr, (an_il_entry_kind)ent.kind); return scp != NULL && unmangled_name_of(scp) == NULL; } /* The following function writes a string to the output_buf of the * form "<unnamed # var_name>" for a nameless type that is used in * the type of "var_name" (the first variable or field in the * declarator list of the declaration in which the nameless type * is contained). Note that this differs from the treatment of * typedefs for nameless types, where the name is the first that * is a synonym of the type; here it is the first, regardless of * whether type modifiers are part of the declarator. */ void form_unnamed(a_type_ptr tp, an_il_to_str_output_control_block_ptr ocb) { a_source_sequence_entry_ptr seq; (*ocb->output_str)("<unnamed"); for (seq = tp->source_corresp.source_sequence_entry; seq; seq = seq->next) { if (seq->entity.kind == iek_src_seq_end_of_construct) { a_src_seq_end_of_construct_ptr eoc = (a_src_seq_end_of_construct_ptr) seq->entity.ptr; if (eoc->entity.ptr == (char*) tp) { break; } } } if (seq && !seq->next) { a_source_sequence_entry_ptr parent_seq; for (parent_seq = orphaned_list_parent_seq_list; parent_seq; parent_seq = parent_seq->next) { if (parent_seq->entity.kind == iek_src_seq_sublist) { a_src_seq_sublist_ptr sublist = (a_src_seq_sublist_ptr) parent_seq->entity.ptr; a_source_sequence_entry_ptr subseq; for (subseq = sublist->source_sequence_list; subseq; subseq = subseq->next) { if (subseq->entity.kind == iek_type && subseq->entity.ptr == (char*) tp) { seq = parent_seq; break; } } if (seq == parent_seq) { break; } } } } if (seq && seq->next && !tp->autonomous_primary_tag_decl) { /* make seq point to entry for first declarator after type */ a_source_sequence_entry_ptr seqn = seq->next; if (seqn->entity.kind == iek_variable) { a_variable_ptr vp = (a_variable_ptr) seqn->entity.ptr; (*ocb->output_str)(" # "); form_name(&vp->source_corresp, iek_variable, ocb); /*TBD: decorate_name_and_finish(...) */ } else if (seqn->entity.kind == iek_field) { a_field_ptr fp = (a_field_ptr) seqn->entity.ptr; (*ocb->output_str)(" # "); form_name(&fp->source_corresp, iek_field, ocb); /*TBD: decorate_name_and_finish(...) */ } } else { int index, count; a_tagged_pointer ent; ent.kind = iek_type; ent.ptr = (char *)tp; if (find_child_index(/* seq->entity */ ent, is_anonymous, &index, &count) && count > 1) { char buffer[50]; (*ocb->output_str)(" # "); sprintf(buffer, "%d", index + 1); ocb->output_str(buffer); } } (*ocb->output_str)(">"); } /* The following function will write a SYM line for a given il entry * pointer to the given output file/buffer if it has not already been * written to it. Associated relations and attributes are also written * unless they are to be handled in the tree walk. */ void write_symbol_for_il_node(void *ilp, an_il_entry_kind il_kind, string_buffer_ptr output_buffer) { an_il_entry_prefix_ptr ep = &il_entry_prefix_of(ilp); /* skip writing SYM line if il node already has an "error_symid" assigned to it */ if (ep->SET_symid == error_symid) { return; } if (output_buffer != NULL && !is_output_buffer_bit_set(&ep->SET_outbuf_bit_arr, output_buffer)) { string_buffer_ptr def_buffer = get_buffer_from_il_node(ilp); write_referenced_symbol_info(ilp, il_kind, output_buffer, (def_buffer == output_buffer)); /* set output buffer bit */ set_outbuf_bit_of_clique(ilp, output_buffer); /* write "pointer" REL line between "void" and "void*" */ if (il_kind == iek_type) { write_type_rel_for_void_ptr(ilp, il_kind, output_buffer); } } } /* The following function is called for data members, nested * non-class types (typedefs and enums), and enumerators of template * classes (prototype instantiations, actually) to add the * "specialize" RELs with the corresponding members of instances * of the parent template class. */ void write_tmpl_mbr_specialize_rels(a_symbol_ptr mbr, unsigned long mbr_symid, string_buffer_ptr output_buffer) { a_type_ptr proto_class = mbr->parent.class_type; a_symbol_ptr proto_class_sym = proto_class ? (a_symbol_ptr) proto_class->source_corresp.assoc_info : NULL; a_symbol_ptr tmpl_class = proto_class_sym ? proto_class_sym->variant.class_struct_union.extra_info-> class_template : NULL; a_symbol_ptr sym; for (sym = mbr->header->inactive_symbols; sym; sym = sym->next) { if (sym != mbr && sym->is_class_member) { a_type_ptr inst_class = sym->parent.class_type; if (inst_class && inst_class->variant.class_struct_union.is_template_class && !inst_class->variant.class_struct_union.is_specialized && inst_class->source_corresp.assoc_info && ((a_symbol_ptr) inst_class->source_corresp.assoc_info)-> variant.class_struct_union.extra_info->class_template == tmpl_class && sym->kind == mbr->kind) { /* This class is an instance of the template parent of * mbr_sym; find the symid of the instance member and * write the "specialize" REL. */ unsigned long inst_symid; if (sym->kind == sk_type) { inst_symid = SET_symid_and_write_sym(sym->variant.type.ptr, iek_type, output_buffer); process_symbol_of_entry_if_needed((char*)sym->variant.type.ptr, iek_type); } else if (sym->kind == sk_enum_tag) { inst_symid = SET_symid_and_write_sym(sym->variant.enumeration.type, iek_type, output_buffer); } else if (sym->kind == sk_constant) { inst_symid = SET_symid_and_write_sym(sym->variant.constant, iek_constant, output_buffer); } else if (sym->kind == sk_field) { inst_symid = SET_symid_and_write_sym(sym->variant.field.ptr, iek_field, output_buffer); } else if (sym->kind == sk_projection) { inst_symid = 0; } else { complain_int(error_csev, "Unexpected template member kind $1", sym->kind); inst_symid = 0; } if (inst_symid) { write_specialize_rel(inst_symid, mbr_symid, /*full_or_part=*/NULL, /*explicit=*/FALSE, get_buffer_from_il_node(inst_class)); } } } } } /* -------------------- FILE SCREENING -------------------- * * structs: sym_summary_info * * variables: SET_file_is_interesting sym_summary_info_block * next_free_sym_summary_info * * functions: SET_is_file_interesting add_summary_info * write_summary_sym_info * * macros: interesting_node SYM_SUMMARY_INFO_BLOK_COUNT * * Files are categorized as either "interesting" or "uninteresting," * depending on whether information from that file is desired in the IF. * Each time input is switched from one file to another (for each * #include and end-of-file), the global flag SET_file_is_interesting * is set accordingly. This flag is copied into each IL node that is * created as il_entry_prefix::full_SET_dump. The value of this flag * is returned by the macro interesting_node. * * Nodes that are not intresting are processed separately from interesting * nodes: instead of immediately causing output to the IF file, the * function add_summary_info is called to capture the basic information * about the node (since IL nodes are not self-defining) in a * sym_summary_info object, which is then attached to the node via the * SET_info field of the node's an_il_entry_prefix. If a reference to * the node is later encountered from an interesting node and the node * has no symid, write_summary_sym_info is called (from assign_symid as * a side_effect of the SET_symid_of macro) to add a SYM line to the IF * using the stored info. * * The decision as to whether a file is interesting or not is made by * the function SET_is_file_interesting. */ /* The following structure is used to provide sufficient information * (the spelling of the kind and name of the entity) to allow a SYM * line to be printed for references to entities from "uninteresting" * files. Such entities are handled specially by process_entry, * filling in a pointer to this structure in the SET_info of the * entity in place of the pointer to ast_node_info that is placed * there for "interesting" entities. */ typedef struct sym_summary_info { const char* kind; const char* name; } sym_summary_info; typedef sym_summary_info* sym_summary_info_ptr; /* The usual block allocation scheme: */ static sym_summary_info_ptr sym_summary_info_block; static size_t next_free_sym_summary_info; #define SYM_SUMMARY_INFO_BLOCK_COUNT 2000 /* The following function creates a new sym_summary_info object, * initializes it with the specified strings, and inserts it as * the SET_info of the specified IL node. */ void add_summary_info(void* ilp, const char* kind, const char* name) { sym_summary_info_ptr sip; if (!sym_summary_info_block || next_free_sym_summary_info >= SYM_SUMMARY_INFO_BLOCK_COUNT) { sym_summary_info_block = (sym_summary_info_ptr) malloc(SYM_SUMMARY_INFO_BLOCK_COUNT * sizeof(sym_summary_info)); sym_summary_meter += SYM_SUMMARY_INFO_BLOCK_COUNT * sizeof(sym_summary_info); next_free_sym_summary_info = 0; } sip = sym_summary_info_block + next_free_sym_summary_info++; sip->kind = kind; sip->name = name; il_entry_prefix_of(ilp).SET_info = sip; } void write_summary_sym_info(void *ilp, an_il_entry_kind il_kind, string_buffer_ptr output_buffer) { if (output_buffer != NULL) { an_il_entry_prefix_ptr ep = &il_entry_prefix_of(ilp); sym_summary_info_ptr sip = (sym_summary_info_ptr) ep->SET_info; add_3_chars_to_string("SYM", output_buffer); add_symid_to_string(ep->SET_symid, output_buffer); add_to_string(sip->kind, output_buffer); add_2_chars_to_string(" \"", output_buffer); add_to_string(sip->name, output_buffer); add_1_char_to_string('\"', output_buffer); terminate_string(output_buffer); } fulfill_SYM(ilp); /* write "pointer" REL line between "void" and "void*" */ if (il_kind == iek_type) { write_type_rel_for_void_ptr(ilp, il_kind, output_buffer); } } /* The following function takes the symbol pointer of a template function * or static data member and returns its qualified name and the symid of * its parent class. The qualified name is created in the trial_buf. */ static const char* template_qual_name_and_parent_symid(a_symbol_ptr sym, a_tagged_pointer* parent_tag) { if (sym->is_class_member && sym->parent.class_type) { a_type_ptr parent_class = sym->parent.class_type; a_boolean is_member_of_real_instance = FALSE; if (parent_class->variant.class_struct_union.is_template_class && !parent_class->variant.class_struct_union.is_specialized) { a_symbol_ptr parent_sym = (a_symbol_ptr) parent_class->source_corresp.assoc_info; a_class_symbol_supplement_ptr parent_info = (parent_sym) ? parent_sym->variant.class_struct_union.extra_info : NULL; a_template_symbol_supplement_ptr parent_template_info = (parent_info) ? parent_info->template_info : NULL; if (!parent_template_info) { /* We only set the parent symid here for members of real * instances, not prototype instances, because the "context" * REL will be output by create_ast_for_template_member * for members of prototype instances; setting the * parent symid here would cause a duplicate. */ SET_symid_of(parent_class, iek_type); parent_tag->ptr = (char *)parent_class; parent_tag->kind = iek_type; is_member_of_real_instance = TRUE; } } else { SET_symid_of(parent_class, iek_type); parent_tag->ptr = (char *)parent_class; parent_tag->kind = iek_type; } if (sym->kind != sk_class_template || is_member_of_real_instance) { form_name(&parent_class->source_corresp, iek_type, ocb_of_string_buf(&trial_buf)); add_2_chars_to_string("::", &trial_buf); } } else if (sym->parent.namespace_ptr) { SET_symid_of(sym->parent.namespace_ptr, iek_namespace); parent_tag->ptr = (char *)sym->parent.namespace_ptr; parent_tag->kind = iek_namespace; if (sym->kind != sk_class_template) { form_name(&sym->parent.namespace_ptr->source_corresp, iek_namespace, ocb_of_string_buf(&trial_buf)); add_2_chars_to_string("::", &trial_buf); } } if (sym->kind == sk_class_template) { a_template_symbol_supplement_ptr tmpl_supp = sym->variant.template_info; a_symbol_ptr proto_sym = tmpl_supp ? tmpl_supp->variant.class_template.prototype_instantiation : NULL; a_type_ptr proto_class = (proto_sym && (proto_sym->kind == sk_class_or_struct_tag || proto_sym->kind == sk_union_tag)) ? proto_sym->variant.class_struct_union.type : NULL; if (proto_class) { form_name(&proto_class->source_corresp, iek_type, ocb_of_string_buf(&trial_buf)); } else if (sym->variant.template_info->prototype_template) { /* This is a member template of a real instance, so there is * no prototype for this one. What we have to do is find the * prototype for the member of the prototype instance and * get its unqualified name (the qualification was added * above under control of the is_member_of_real_instance * flag). */ tmpl_supp = sym->variant.template_info->prototype_template-> variant.template_info; proto_sym = tmpl_supp ? tmpl_supp->variant.class_template.prototype_instantiation : NULL; proto_class = (proto_sym && (proto_sym->kind == sk_class_or_struct_tag || proto_sym->kind == sk_union_tag)) ? proto_sym->variant.class_struct_union.type : NULL; if (proto_class) { form_unqualified_name(&proto_class->source_corresp, iek_type, ocb_of_string_buf(&trial_buf)); } else add_to_string(sym->header->identifier, &trial_buf); } else add_to_string(sym->header->identifier, &trial_buf); } else { add_to_string(sym->header->identifier, &trial_buf); if (sym->kind == sk_routine || sym->kind == sk_member_function) { an_il_to_str_output_control_block* ocb = ocb_of_string_buf(&trial_buf); a_boolean saved_flag = ocb->suppress_all_typedefs; ocb->suppress_all_typedefs = TRUE; form_function_declarator(skip_typerefs(sym->variant.routine. ptr->type), ocb); ocb->suppress_all_typedefs = saved_flag; } else if (sym->kind == sk_function_template) { a_template_param_ptr tpl_parm; an_il_to_str_output_control_block* ocb; a_boolean saved_flag; add_1_char_to_string('<', &trial_buf); if (sym->variant.template_info != NULL && sym->variant.template_info->cache.decl_info != NULL) { for (tpl_parm = sym->variant.template_info->cache.decl_info-> parameters; tpl_parm; tpl_parm = tpl_parm->next) { add_to_string(tpl_parm->param_symbol->header->identifier, &trial_buf); if (tpl_parm->next) { add_2_chars_to_string(", ", &trial_buf); } } } add_1_char_to_string('>', &trial_buf); ocb = ocb_of_string_buf(&trial_buf); saved_flag = ocb->suppress_all_typedefs; ocb->suppress_all_typedefs = TRUE; form_function_declarator(skip_typerefs(sym->variant.template_info-> variant.function.routine-> type), ocb); ocb->suppress_all_typedefs = saved_flag; } } return terminate_string(&trial_buf); } /* The following function writes SYM line for a given il entry in the given * output buffer. It also writes REL and ATR lines if sym_line_only is not * true. Most of the stuff here is grabbed from the process_entry function. * This function is used to write information of a symbol that is referenced * in this file(represented by output_buffer), regardless of whether it is * defined in this file. Thus, unlike process_entry, this function will not * write SMT lines or AST. */ static void write_symbol(char *entry_ptr, an_il_entry_kind entry_kind, string_buffer_ptr output_buffer, a_boolean sym_line_only, a_boolean in_il_walk, a_boolean write_noninvertible_relations) { a_boolean for_entry = FALSE; /* The following variable is set TRUE to indicate that AST should be * created for class members of templates, even though they appear * to be members of template instances (in this case, the prototype * instantiation). */ a_boolean prototype_instance_member = entry_is_prototype_instance_member(entry_ptr, entry_kind); void (*finish_name)(const void *, an_il_entry_kind entry_kind, a_boolean, a_boolean, string_buffer_ptr) = in_il_walk ? decorate_name_and_finish : finish_plain_name; a_boolean write_parent_relations = generate_multiple_IF_files; a_boolean write_child_relations = !generate_multiple_IF_files; a_boolean mark_definitions = in_il_walk; if (write_noninvertible_relations && sym_line_only) { complain(error_csev, "Writing only SYM line."); } if (in_il_walk && !write_noninvertible_relations) { complain(error_csev, "IL walk is not writing all relations."); } if (output_buffer == NULL) { return; } switch (entry_kind) { case iek_none: { } break; case iek_source_file: { } break; case iek_constant: { a_constant_ptr constant_ptr = (a_constant_ptr) entry_ptr; a_boolean is_case_label = (constant_ptr->source_corresp.decl_pos_info && constant_ptr->source_corresp.decl_pos_info-> specifiers_range.start.seq); a_type_ptr parent = (constant_ptr->source_corresp.is_class_member) ? constant_ptr->source_corresp.parent.class_type : NULL; a_boolean is_template_member = in_template_function || (parent && parent->variant.class_struct_union.is_template_class && !parent->variant.class_struct_union.is_specialized && !prototype_instance_member); unsigned long constant_symid; if ( in_il_walk && ( ( constant_ptr->const_expr && ( !is_case_label || constant_ptr->const_expr->kind == enk_constant) && !constant_ptr->source_corresp.name) || constant_ptr->kind == ck_dynamic_init || (GNU_compatible_AST && constant_ptr->kind == ck_aggregate) || (constant_ptr->from_asm && !emit_asm_strings))) { break; } if (constant_ptr->kind == ck_string || (constant_ptr->kind == ck_address && constant_ptr->variant.address.kind == abk_constant && constant_ptr->variant.address.variant.constant-> kind == ck_string)) { insert_sym_prefix("string", constant_ptr, iek_constant, FALSE, FALSE, output_buffer); } else if (constant_ptr->kind == ck_integer && constant_ptr->source_corresp.name) { insert_sym_prefix("evalue", constant_ptr, iek_constant, FALSE, prototype_instance_member, output_buffer); } else insert_sym_prefix("constant", constant_ptr, iek_constant, FALSE, prototype_instance_member, output_buffer); if (constant_ptr->source_corresp.name) { form_name(&constant_ptr->source_corresp, iek_constant, ocb_of_string_buf(output_buffer)); finish_name(constant_ptr, iek_constant, /*add_block_qual=*/TRUE, /*add_closing_quote=*/TRUE, output_buffer); } else { constant_to_string(constant_ptr, output_buffer); add_1_char_to_string('\"', output_buffer); } if (mark_definitions && constant_ptr->source_corresp.name && !is_template_member) { add_sym_def_pos_to_string(&constant_ptr->source_corresp.decl_position, output_buffer); } terminate_string(output_buffer); if (!sym_line_only || is_auto_gen_member(&constant_ptr->source_corresp)) { constant_symid = SET_symid_of(constant_ptr, iek_constant); if (constant_ptr->type) { write_rel( SET_symid_and_write_sym(constant_ptr->type, iek_type, output_buffer), "type", constant_symid, output_buffer); } if (!in_il_walk) { /* write "define" relation for enum value reference */ if (constant_ptr->kind == ck_integer && constant_ptr->source_corresp.name && !is_template_member) { write_define_relation(constant_ptr->source_corresp.decl_position.seq, constant_symid, output_buffer); } } if (write_parent_relations) { /* write "context" REL between constant and its parent class/struct/union or namespace */ if (constant_ptr->source_corresp.is_class_member) { a_type_ptr parent = constant_ptr->source_corresp.parent.class_type; write_context_rel(SET_symid_and_write_sym(parent, iek_type, output_buffer), constant_symid, constant_ptr->source_corresp.access, output_buffer); } else { a_namespace_ptr namespace_ptr = constant_ptr->source_corresp.parent.namespace_ptr; if (namespace_ptr) { write_rel(SET_symid_and_write_sym(namespace_ptr, iek_namespace, output_buffer), "context", constant_symid, output_buffer); } } } } } break; case iek_param_type: { if (!in_il_walk) { a_param_type_ptr param_ptr = (a_param_type_ptr) entry_ptr; unsigned long param_symid; insert_sym_prefix("variable", param_ptr, iek_param_type, /*compiler_generated=*/FALSE, prototype_instance_member, output_buffer); if (param_ptr->name) { add_to_string(param_ptr->name, output_buffer); } else add_to_string("<unnamed>", output_buffer); add_to_string_with_len(" @ \"", 4, output_buffer); terminate_string(output_buffer); param_symid = SET_symid_of(param_ptr, iek_param_type); write_rel(SET_symid_and_write_sym(param_ptr->type, iek_type, output_buffer), "type", param_symid, output_buffer); write_atr(param_symid, "auto", output_buffer); } } break; case iek_routine_type_supplement: { } break; case iek_based_type_list_member: { } break; case iek_type: { a_type_ptr type_ptr = (a_type_ptr) entry_ptr; a_boolean is_typedef = FALSE; a_boolean is_class_struct_union = (type_ptr->kind == tk_class || type_ptr->kind == tk_struct || type_ptr->kind == tk_union); a_boolean is_auto_gen_type = ((is_class_struct_union && is_auto_gen_class(type_ptr)) || (is_auto_gen_member(&type_ptr->source_corresp))); /* During il_walk do not write SYM, REL, etc for tk_routine types * (but do the AST) in "multiple_iffs" mode. The SYM, REL, etc will * be written if the type gets referenced. */ if (generate_multiple_IF_files && in_il_walk && type_ptr->kind == tk_routine) { break; } if (!in_il_walk && is_class_struct_union) { /* from "type" il node try to find its corresponding "template" il node */ a_source_correspondence *scp = source_corresp_for_il_entry(entry_ptr, iek_type); a_symbol_ptr entry_sym = (scp) ? (a_symbol_ptr)scp->assoc_info : NULL; a_type_ptr classp = (entry_sym) ? entry_sym->variant.class_struct_union.type : NULL; a_class_symbol_supplement_ptr cssp = (entry_sym) ? entry_sym->variant.class_struct_union.extra_info : NULL; a_template_symbol_supplement_ptr tssp = cssp ? cssp->template_info : NULL; a_template_ptr tpl = tssp ? tssp->il_template_entry : NULL; #if DEBUG if (type_ptr != classp) { worry("Symbol type differs from source sequence type."); } #endif if (classp && tpl) { SET_symid_and_write_sym(tpl, iek_template, output_buffer); break; } } if (in_il_walk && is_class_struct_union && type_ptr->variant.class_struct_union.is_nonreal_class && type_ptr->variant.class_struct_union.is_prototype_instantiation) { /* This is a prototype instantiation, which should not * be handled here but processed by the code in the * iek_template case. */ } else if (!in_il_walk && is_builtin_typedef(type_ptr)) { /* SYM line is emitted for the "bool" type, not the typedef. */ SET_symid_and_write_sym(bool_type(), iek_type, output_buffer); break; } else { if (type_ptr->kind == tk_integer && type_ptr->variant.integer.enum_type) { insert_sym_prefix("enum", type_ptr, iek_type, FALSE, prototype_instance_member, output_buffer); } else if (type_is_class(type_ptr)) { if (type_ptr->kind == tk_class) { insert_sym_prefix("class", type_ptr, iek_type, FALSE, prototype_instance_member, output_buffer); } else if (type_ptr->kind == tk_struct) { insert_sym_prefix("struct", type_ptr, iek_type, FALSE, prototype_instance_member, output_buffer); } else { insert_sym_prefix("union", type_ptr, iek_type, FALSE, prototype_instance_member, output_buffer); } } else if (type_ptr->kind == tk_typeref && type_ptr->source_corresp.name) { insert_sym_prefix("typedef", type_ptr, iek_type, FALSE, prototype_instance_member, output_buffer); is_typedef = TRUE; } else insert_sym_prefix("type", type_ptr, iek_type, FALSE, FALSE, output_buffer); if (is_typedef) { form_name(&type_ptr->source_corresp, iek_type, ocb_of_string_buf(output_buffer)); } else form_type(type_ptr, ocb_of_string_buf(output_buffer)); if (type_ptr->source_corresp.is_local_to_function) { finish_name(type_ptr, iek_type, /*add_block_qual=*/TRUE, /*add_closing_quote=*/TRUE, output_buffer); } else add_1_char_to_string('\"', output_buffer); if (!((type_ptr->kind == tk_class || type_ptr->kind == tk_struct || type_ptr->kind == tk_union) && (type_ptr->size == 0 || is_auto_gen_class(type_ptr))) && !in_template_function && mark_definitions) { /* Do not add position (indicating that the type is defined) if * it's a class/struct/union that's incomplete or the result of * automatic instantiation, or if the type (of any kind) is * defined inside a template function. */ add_sym_def_pos_to_string(&type_ptr->source_corresp.decl_position, output_buffer); } terminate_string(output_buffer); } if (!sym_line_only || (type_ptr->kind == tk_typeref && !type_ptr->source_corresp.name) || type_ptr->kind == tk_pointer || is_auto_gen_type || type_ptr->kind == tk_routine) { unsigned long type_symid = SET_symid_and_write_sym(type_ptr, iek_type, output_buffer); if (type_ptr->kind == tk_integer && type_ptr->variant.integer.enum_type) { a_constant_ptr enumerator = type_ptr->variant.integer.enum_info.constant_list; if (!type_ptr->source_corresp.name) { write_atr(type_symid, "nameless", output_buffer); } if (!in_il_walk) { /* write "define" relation for enum reference */ if (!in_template_function) { write_define_relation(type_ptr->source_corresp.decl_position.seq, type_symid, output_buffer); } } if (write_parent_relations && is_auto_gen_type && type_ptr->source_corresp.assoc_info) { a_symbol_ptr enum_sym = (a_symbol_ptr)type_ptr->source_corresp.assoc_info; if (enum_sym) { write_specialize_rel_for_templ_inst(enum_sym, type_symid, output_buffer); } } if (write_noninvertible_relations) { while(enumerator) { write_rel(type_symid, "enumerate", SET_symid_and_write_sym(enumerator, iek_constant, output_buffer), output_buffer); enumerator = enumerator->next; } } } else if (type_ptr->kind == tk_routine) { a_routine_type_supplement_ptr extra_info = type_ptr->variant.routine.extra_info; a_param_type_ptr param_type; int argno = 1; if (extra_info->routine_name_linkage == nlk_external && il_header.source_language == sl_Cplusplus) { write_atr(type_symid, "linkage(c)", output_buffer); } format_rel(SET_symid_and_write_sym(type_ptr->variant.routine.return_type, iek_type, output_buffer), "type", type_symid, output_buffer); add_to_string("return", output_buffer); terminate_string(output_buffer); for (param_type = extra_info->param_type_list; param_type; param_type = param_type->next) { format_rel(SET_symid_and_write_sym(param_type->type, iek_type, output_buffer), "type", type_symid, output_buffer); add_num_to_string(argno++, "argument(", ")", output_buffer); terminate_string(output_buffer); if (in_il_walk && !extra_info->assoc_routine && param_type->decl_pos_info) { /* param is not part of a definition; must do * entire SYM, type REL, auto ATR now. */ unsigned long parm_symid = SET_symid_of(param_type, iek_param_type); insert_sym_prefix("variable", param_type, iek_param_type, /*compiler_generated=*/FALSE, prototype_instance_member, output_buffer); if (param_type->name) { add_to_string(param_type->name, output_buffer); } else add_to_string("<unnamed>", output_buffer); add_to_string_with_len(" @ \"", 4, output_buffer); terminate_string(output_buffer); write_rel(SET_symid_and_write_sym(param_type->type, iek_type, output_buffer), "type", parm_symid, output_buffer); write_atr(parm_symid, "auto", output_buffer); } } if (extra_info->has_ellipsis) { format_rel(symid_of_ellipsis(output_buffer), "type", type_symid, output_buffer); add_num_to_string(argno++, "argument(", ")", output_buffer); terminate_string(output_buffer); } } else if (type_ptr->kind == tk_array) { format_rel(SET_symid_and_write_sym(type_ptr->variant.array.element_type, iek_type, output_buffer), "type", type_symid, output_buffer); add_to_string("array", output_buffer); if (!type_ptr->variant.array.is_variable_size_array) { add_num_to_string(type_ptr->variant.array.variant.number_of_elements, "(", ")", output_buffer); } terminate_string(output_buffer); } else if (type_ptr->kind == tk_class || type_ptr->kind == tk_struct || type_ptr->kind == tk_union) { a_field_ptr field; a_class_type_supplement_ptr extra_info = type_ptr->variant.class_struct_union.extra_info; a_scope_ptr class_scope = (extra_info) ? extra_info->assoc_scope : NULL; if (type_symid == 0) { complain(error_csev, "type_symid was not set."); } if (!type_ptr->source_corresp.name) { write_atr(type_symid, "nameless", output_buffer); } if (extra_info) { a_base_class_ptr base; for (base = extra_info->base_classes; base; base = base->next) { if (base->direct) { format_rel(type_symid, "subclass", SET_symid_and_write_sym(base->type, iek_type, output_buffer), output_buffer); if (base->is_virtual) { add_to_string("virtual", output_buffer); } else add_access_spec(base->derivation->access, output_buffer); terminate_string(output_buffer); } } if (type_ptr->variant.class_struct_union.is_template_class) { a_template_arg_ptr tp_arg; for (tp_arg = extra_info->template_arg_list; tp_arg; tp_arg = tp_arg->next) { if (tp_arg->kind == (a_templ_arg_kind)tak_type) { format_rel(SET_symid_and_write_sym(tp_arg->variant.type, iek_type, output_buffer), "argument", type_symid, output_buffer); add_to_string("template", output_buffer); terminate_string(output_buffer); if (tp_arg->variant.type->kind == tk_pointer) process_symbol_of_entry_if_needed ( (char*)tp_arg->variant.type, iek_type); } else if (tp_arg->kind == (a_templ_arg_kind)tak_template ) { format_rel(SET_symid_and_write_sym(tp_arg->variant.templ.ptr, iek_template, output_buffer), "argument", type_symid, output_buffer); add_to_string("template", output_buffer); terminate_string(output_buffer); } else if (!tp_arg->is_array_bound_of_unknown_type) { if (tp_arg->variant.constant->kind == ck_address) { /* This is a pointer non-type argument; make * the relation with the entity pointed to by * the address constant ("variable" will give * the right address, even if it's not a * variable), not the constant itself. */ format_rel(SET_symid_and_write_sym(tp_arg->variant.constant->variant.address.variant.variable, iek_variable, output_buffer), "argument", type_symid, output_buffer); } else { process_symbol_of_entry_if_needed((char*) tp_arg->variant.constant, iek_constant); format_rel(SET_symid_and_write_sym(tp_arg->variant.constant, iek_constant, output_buffer), "argument", type_symid, output_buffer); } add_to_string("template", output_buffer); terminate_string(output_buffer); } } } /* write "specialize" REL between instantiation and prototype template */ if (write_parent_relations && !type_ptr->variant.class_struct_union.is_prototype_instantiation && extra_info->assoc_template) { write_specialize_rel(type_symid, SET_symid_and_write_sym(extra_info->assoc_template, iek_template, output_buffer), "full", type_ptr->variant.class_struct_union.is_specialized, output_buffer); } /* For an instantiated class write symbol info for all the instantiated types(like enum, typedefs) defined within the template class.*/ if (is_auto_gen_type && class_scope) { a_type_ptr type; for (type = class_scope->types; type; type = type->next) { SET_symid_and_write_sym(type, iek_type, output_buffer); } } } if (write_child_relations) { for (field = type_ptr->variant.class_struct_union.field_list; field; field = field->next) { write_context_rel(type_symid, SET_symid_and_write_sym(field, iek_field, output_buffer), field->source_corresp.access, output_buffer); } } if (write_child_relations && class_scope) { a_constant_ptr constant; a_type_ptr type; a_variable_ptr variable; a_routine_ptr routine; for (routine = class_scope->routines; routine; routine = routine->next) { a_routine_type_supplement_ptr extra_info = skip_typerefs(routine->type)-> variant.routine.extra_info; write_context_rel(type_symid, SET_symid_and_write_sym(routine, iek_routine, output_buffer), routine->source_corresp.access, output_buffer); if (!extra_info->this_class) { write_atr(SET_symid_and_write_sym(routine, iek_routine, output_buffer), "static", output_buffer); } } for (variable = class_scope->variables; variable; variable = variable->next) { write_context_rel(type_symid, SET_symid_and_write_sym(variable, iek_variable, output_buffer), variable->source_corresp.access, output_buffer); write_atr(SET_symid_and_write_sym(variable, iek_variable, output_buffer), "static", output_buffer); } for (type = class_scope->types; type; type = type->next) { write_context_rel(type_symid, SET_symid_and_write_sym(type, iek_type, output_buffer), type->source_corresp.access, output_buffer); } for (constant = class_scope->constants; constant; constant = constant->next) { write_context_rel(type_symid, SET_symid_and_write_sym(constant, iek_constant, output_buffer), constant->source_corresp.access, output_buffer); } } if (write_noninvertible_relations && class_scope) { a_using_decl_ptr using_decl; for (using_decl = class_scope->using_decls; using_decl; using_decl = using_decl->next) { format_rel(type_symid, "context", SET_symid_and_write_sym(using_decl->entity.ptr, using_decl->entity.kind, output_buffer), output_buffer); add_access_spec(using_decl->access, output_buffer); add_to_string(", using", output_buffer); terminate_string(output_buffer); } } if (write_noninvertible_relations && extra_info && type_symid != 0) { a_routine_list_entry_ptr friend_fcn; a_class_list_entry_ptr friend_class; for (friend_fcn = extra_info->friend_routines; friend_fcn; friend_fcn = friend_fcn->next) { write_rel(SET_symid_and_write_sym(friend_fcn->routine, iek_routine, output_buffer), "friend", type_symid, output_buffer); } for (friend_class = extra_info->friend_classes; friend_class; friend_class = friend_class->next) { write_rel(SET_symid_and_write_sym(friend_class->class_type, iek_type, output_buffer), "friend", type_symid, output_buffer); } } } else if (type_ptr->kind == tk_typeref) { unsigned int type_quals = type_ptr->variant.typeref.qualifiers; unsigned int base_quals; a_boolean atr_added = FALSE; a_type_ptr typeref_ptr = type_ptr->variant.typeref.type; write_define_relation(type_ptr->source_corresp.decl_position.seq, type_symid, output_buffer); format_rel(SET_symid_and_write_sym(typeref_ptr, iek_type, output_buffer), "type", type_symid, output_buffer); if (type_ptr->variant.typeref.type->kind == tk_typeref) { base_quals = type_ptr->variant.typeref.type-> variant.typeref.qualifiers; } else base_quals = 0; if ((base_quals & TQ_CONST) ^ (type_quals & TQ_CONST)) { add_attrib("const", &atr_added, output_buffer); } if ((base_quals & TQ_VOLATILE) ^ (type_quals & TQ_VOLATILE)) { add_attrib("volatile", &atr_added, output_buffer); } if ((base_quals & TQ_RESTRICT) ^ (type_quals & TQ_RESTRICT)) { add_attrib("restrict", &atr_added, output_buffer); } #ifdef MICROSOFT_EXTENSIONS_ALLOWED if ((base_quals & TQ_UNALIGNED) ^ (type_quals & TQ_UNALIGNED)) { add_attrib("unaligned", &atr_added, output_buffer); } if ((base_quals & TQ_NEAR) ^ (type_quals & TQ_NEAR)) { add_attrib("near", &atr_added, output_buffer); } if ((base_quals & TQ_FAR) ^ (type_quals & TQ_FAR)) { add_attrib("far", &atr_added, output_buffer); } #endif /* MICROSOFT_EXTENSIONS_ALLOWED */ terminate_string(output_buffer); /* Write "specialize" relations between instantiated "typedef" and prototype template "typedef". */ if (write_parent_relations && is_auto_gen_type && type_ptr->source_corresp.assoc_info) { a_symbol_ptr typedef_sym = (a_symbol_ptr)type_ptr->source_corresp.assoc_info; if (typedef_sym) { write_specialize_rel_for_templ_inst(typedef_sym, type_symid, output_buffer); } } } else if (type_ptr->kind == tk_pointer) { format_rel(SET_symid_and_write_sym(type_ptr->variant.pointer.type, iek_type, output_buffer), "type", type_symid, output_buffer); if (type_ptr->variant.pointer.is_reference) { add_to_string("reference", output_buffer); } else add_to_string("pointer", output_buffer); terminate_string(output_buffer); } else if (type_ptr->kind == tk_ptr_to_member) { unsigned long class_symid = SET_symid_and_write_sym(type_ptr->variant.ptr_to_member.class_of_which_a_member, iek_type, output_buffer); process_symbol_of_entry_if_needed( (char*)type_ptr->variant.ptr_to_member.class_of_which_a_member, iek_type); format_rel(SET_symid_and_write_sym(type_ptr->variant.ptr_to_member.type, iek_type, output_buffer), "type", type_symid, output_buffer); add_to_string("pointer(", output_buffer); add_symid_to_string(class_symid, output_buffer); add_1_char_to_string(')', output_buffer); terminate_string(output_buffer); } if (write_parent_relations) { /* write "context" REL between type and its parent class/struct/union or namespace */ if (type_ptr->source_corresp.is_class_member) { a_type_ptr parent = type_ptr->source_corresp.parent.class_type; write_context_rel(SET_symid_and_write_sym(parent, iek_type, output_buffer), type_symid, type_ptr->source_corresp.access, output_buffer); } else { a_namespace_ptr namespace_ptr = type_ptr->source_corresp.parent.namespace_ptr; if (namespace_ptr) { write_rel(SET_symid_and_write_sym(namespace_ptr, iek_namespace, output_buffer), "context", type_symid, output_buffer); } } } } /* !sym_line_only */ } /* case iek_type */ break; case iek_variable: { a_variable_ptr variable_ptr = (a_variable_ptr) entry_ptr; a_boolean atr_required = FALSE; a_boolean has_default_expr = param_var_has_default(variable_ptr); a_boolean is_template_instance = variable_ptr->is_template_static_data_member && !variable_ptr->is_specialized; a_boolean is_auto_gen_var = is_auto_gen_member(&variable_ptr->source_corresp); a_template_ptr templ_ptr = variable_has_tpl_entry(variable_ptr); if (!in_il_walk && templ_ptr) { SET_symid_and_write_sym(templ_ptr, iek_template, output_buffer); break; } insert_sym_prefix("variable", variable_ptr, iek_variable, FALSE, prototype_instance_member, output_buffer); if (variable_ptr->is_this_parameter) { add_to_string("this", output_buffer); } else { form_name(&variable_ptr->source_corresp, iek_variable, ocb_of_string_buf(output_buffer)); } finish_name(variable_ptr, iek_variable, /*add_block_qual=*/TRUE, /*add_closing_quote=*/TRUE, output_buffer); if (mark_definitions && variable_ptr->storage_class != sc_extern && !is_template_instance && !in_template_function && !(common_tentative_defs && il_header.source_language == sl_C && variable_ptr->storage_class == sc_unspecified && variable_ptr->init_kind == initk_none)) { add_sym_def_pos_to_string(&variable_ptr->source_corresp.decl_position, output_buffer); } terminate_string(output_buffer); if (!sym_line_only || is_auto_gen_var) { unsigned long variable_symid = SET_symid_of(variable_ptr, iek_variable); write_rel(SET_symid_and_write_sym(variable_ptr->type, iek_type, output_buffer), "type", variable_symid, output_buffer); add_3_chars_to_string("ATR", &trial_buf); add_symid_to_string(variable_symid, &trial_buf); switch(variable_ptr->storage_class) { case sc_static: add_attrib("static", &atr_required, &trial_buf); break; case sc_auto: add_attrib("auto", &atr_required, &trial_buf); break; case sc_register: add_attrib("register", &atr_required, &trial_buf); break; default: /* presumably "extern", the default */ break; } if (variable_ptr->source_corresp.name_linkage == nlk_external && il_header.source_language == sl_Cplusplus) { add_attrib("linkage(c)", &atr_required, &trial_buf); } if (atr_required) { add_to_string(terminate_string(&trial_buf), output_buffer); terminate_string(output_buffer); } else terminate_string(&trial_buf); /* forget it */ if (!in_il_walk) { /* write "define" relation for variable reference */ if (!variable_ptr->source_corresp.is_class_member && variable_ptr->storage_class != sc_extern && !is_template_instance && !in_template_function && !(common_tentative_defs && il_header.source_language == sl_C && variable_ptr->storage_class == sc_unspecified && variable_ptr->init_kind == initk_none)) { write_define_relation(variable_ptr->source_corresp.decl_position.seq, variable_symid, output_buffer); } } if (write_parent_relations) { /* write "context" REL between variable and its parent class/struct/union or namespace */ if (variable_ptr->source_corresp.is_class_member) { a_type_ptr parent = variable_ptr->source_corresp.parent.class_type; write_context_rel(SET_symid_and_write_sym(parent, iek_type, output_buffer), variable_symid, variable_ptr->source_corresp.access, output_buffer); /* Also write "static" attribute for static data member. */ write_atr(variable_symid, "static", output_buffer); } else { a_namespace_ptr namespace_ptr = variable_ptr->source_corresp.parent.namespace_ptr; if (namespace_ptr) { write_rel(SET_symid_and_write_sym(namespace_ptr, iek_namespace, output_buffer), "context", variable_symid, output_buffer); } } /* write "specialize" REL between instantiation and prototype template */ if (is_auto_gen_var && variable_ptr->assoc_template) { write_specialize_rel(variable_symid, SET_symid_and_write_sym(variable_ptr->assoc_template, iek_template, output_buffer), NULL, variable_ptr->is_specialized, output_buffer); } } } } break; #ifdef CIL case iek_field: { a_field_ptr field_ptr = (a_field_ptr) entry_ptr; a_type_ptr parent = field_ptr->source_corresp.parent.class_type; a_boolean is_template_member = in_template_function || (parent->variant.class_struct_union.is_template_class && !parent->variant.class_struct_union.is_specialized && !prototype_instance_member); a_boolean is_auto_gen_field = (parent && is_auto_gen_class(parent)); insert_sym_prefix("field", field_ptr, iek_field, FALSE, prototype_instance_member, output_buffer); form_name(&field_ptr->source_corresp, iek_field, ocb_of_string_buf(output_buffer)); add_1_char_to_string('\"', output_buffer); if (mark_definitions && !is_template_member) { add_sym_def_pos_to_string(&field_ptr->source_corresp.decl_position, output_buffer); } terminate_string(output_buffer); if (!sym_line_only || is_auto_gen_field) { unsigned long field_symid = SET_symid_of(field_ptr, iek_field); write_rel(SET_symid_and_write_sym(field_ptr->type, iek_type, output_buffer), "type", field_symid, output_buffer); if (field_ptr->is_mutable) { write_atr(field_symid, "mutable", output_buffer); } if (write_parent_relations) { /* write "context" REL between field and its parent class/struct/union or namespace */ if (field_ptr->source_corresp.is_class_member) { write_context_rel(SET_symid_and_write_sym(parent, iek_type, output_buffer), field_symid, field_ptr->source_corresp.access, output_buffer); } else { a_namespace_ptr namespace_ptr = field_ptr->source_corresp.parent.namespace_ptr; if (namespace_ptr) { write_rel(SET_symid_and_write_sym(namespace_ptr, iek_namespace, output_buffer), "context", field_symid, output_buffer); } } /* write "specialize" REL between instantiation and prototype template */ if (is_auto_gen_field) { a_symbol_ptr field_sym = (a_symbol_ptr)field_ptr->source_corresp.assoc_info; write_specialize_rel_for_templ_inst(field_sym, field_symid, output_buffer); } } } } break; case iek_exception_specification: { } break; case iek_exception_specification_type: { } break; #endif /* ifdef CIL */ case iek_routine: { a_routine_ptr routine_ptr = (a_routine_ptr) entry_ptr; a_type_ptr routine_type = routine_ptr->type; a_boolean atr_required = FALSE; a_boolean is_prototype_instance_fcn = routine_ptr->is_template_function && !routine_ptr->is_specialized && routine_ptr->is_prototype_instantiation; a_boolean template_mbr = routine_ptr->source_corresp.is_class_member && routine_ptr->source_corresp.parent.class_type != NULL && routine_ptr->source_corresp.parent.class_type->variant.class_struct_union.is_template_class; a_boolean mere_template = template_mbr && routine_ptr->source_corresp.source_sequence_entry == NULL; unsigned long return_symid; a_boolean is_auto_gen_rout = is_auto_gen_routine(routine_ptr); a_template_ptr templ_ptr = has_tpl_entry(routine_ptr); if (!in_il_walk && templ_ptr) { SET_symid_and_write_sym(templ_ptr, iek_template, output_buffer); break; } if (in_il_walk && is_prototype_instance_fcn && routine_ptr->assoc_template != NULL) { /* instance of a function template or a member function template, so it * has its own template IL entry: Avoid processing its SYM line twice. */ } #if 0 Haven''t gotten this criterion correct. For now, duplicate SYM lines may occur. else if (prototype_instance_member && template_mbr && routine_ptr->source_corresp.parent.class_type->variant.class_struct_union.extra_info != NULL && routine_ptr->source_corresp.parent.class_type->variant.class_struct_union.extra_info->assoc_template != NULL) { /* instance of a function template or a member function template, so it * has its own template IL entry: Avoid processing its SYM line twice. */ a_template_ptr assoc_template = routine_ptr->assoc_template; } #endif else { insert_sym_prefix("function", routine_ptr, iek_routine, routine_ptr->compiler_generated, prototype_instance_member || is_prototype_instance_fcn, output_buffer); add_fcn_name_to_string(routine_ptr, output_buffer); add_to_string("\"", output_buffer); if (mark_definitions && routine_ptr->assoc_scope != NULL_region_number && !is_auto_gen_rout && !routine_ptr->compiler_generated) { a_scope_ptr scope_ptr = il_header.region_scope_entry[routine_ptr->assoc_scope]; if (scope_ptr) { a_statement_ptr assoc_block = scope_ptr->assoc_block; if (assoc_block) { add_sym_def_pos_to_string(&routine_ptr->source_corresp.decl_position, output_buffer); } } } terminate_string(output_buffer); } if (!sym_line_only || is_auto_gen_rout) { unsigned long routine_symid = SET_symid_and_write_sym(routine_ptr, iek_routine, output_buffer); a_routine_type_supplement_ptr extra_info = (routine_type->kind == tk_routine) ? routine_type->variant.routine.extra_info : NULL; return_symid = SET_symid_and_write_sym(routine_type->variant.routine.return_type, iek_type, output_buffer); write_rel(SET_symid_and_write_sym(routine_type, iek_type, output_buffer), "type", routine_symid, output_buffer); format_rel(return_symid, "type", routine_symid, output_buffer); add_to_string("return", output_buffer); terminate_string(output_buffer); add_3_chars_to_string("ATR", &trial_buf); add_symid_to_string(routine_symid, &trial_buf); process_symbol_of_entry_if_needed((char *)routine_type, iek_type); switch(routine_ptr->special_kind) { case sfk_constructor: add_attrib("constructor", &atr_required, &trial_buf); if (routine_ptr->is_explicit_constructor) { add_attrib("explicit", &atr_required, &trial_buf); } break; case sfk_destructor: add_attrib("destructor", &atr_required, &trial_buf); break; case sfk_conversion: case sfk_operator: add_attrib("operator", &atr_required, &trial_buf); break; default: /* add nothing */ break; } if (routine_ptr->storage_class == sc_static && !(extra_info && extra_info->this_class)) { add_attrib("static", &atr_required, &trial_buf); } else if (routine_ptr->is_virtual) { add_attrib("virtual", &atr_required, &trial_buf); if (routine_ptr->pure_virtual) { add_attrib("pure", &atr_required, &trial_buf); } } if (routine_ptr->is_inline) { add_attrib("inline", &atr_required, &trial_buf); } if (routine_ptr->source_corresp.name_linkage == nlk_external && il_header.source_language == sl_Cplusplus) { add_attrib("linkage(c)", &atr_required, &trial_buf); } if (il_header.source_language != sl_Cplusplus || routine_ptr->source_corresp.name_linkage == nlk_external) { an_il_to_str_output_control_block* ocb = ocb_of_string_buf(&trial_buf); a_boolean saved_flag = ocb->suppress_all_typedefs; ocb->suppress_all_typedefs = TRUE; add_attrib("c_proto(\"", &atr_required, &trial_buf); form_function_declarator(skip_typerefs(routine_type), ocb); add_2_chars_to_string("\")", &trial_buf); ocb->suppress_all_typedefs = saved_flag; } if (atr_required) { add_to_string(terminate_string(&trial_buf), output_buffer); terminate_string(output_buffer); } else terminate_string(&trial_buf); /* forget it */ if (routine_ptr->is_template_function) { a_template_arg_ptr tp_arg; for (tp_arg = routine_ptr->template_arg_list; tp_arg; tp_arg = tp_arg->next) { if (tp_arg->kind == (a_templ_arg_kind)tak_type) { format_rel(SET_symid_and_write_sym(tp_arg->variant.type, iek_type, output_buffer), "argument", routine_symid, output_buffer); add_to_string("template", output_buffer); terminate_string(output_buffer); } else if (tp_arg->kind == (a_templ_arg_kind)tak_template) { format_rel(SET_symid_and_write_sym(tp_arg->variant.templ.ptr, iek_template, output_buffer), "argument", routine_symid, output_buffer); add_to_string("template", output_buffer); terminate_string(output_buffer); } else if (!tp_arg->is_array_bound_of_unknown_type) { if (tp_arg->variant.constant->kind == ck_address) { /* Make relation with entity pointed to by the * address constant, not the constant itself. */ format_rel(SET_symid_and_write_sym(tp_arg->variant.constant->variant.address.variant.variable, iek_variable, output_buffer), "argument", routine_symid, output_buffer); } else { /* The constant may have been bypassed during the normal * tree walk; ensure at least a SYM line here. */ process_symbol_of_entry_if_needed((char*) tp_arg->variant.constant, iek_constant); format_rel(SET_symid_and_write_sym(tp_arg->variant.constant, iek_constant, output_buffer), "argument", routine_symid, output_buffer); } add_to_string("template", output_buffer); terminate_string(output_buffer); } } } if (write_noninvertible_relations && extra_info && extra_info->exception_specification) { an_exception_specification_type_ptr throw_spec; for (throw_spec = extra_info->exception_specification-> exception_specification_type_list; throw_spec; throw_spec = throw_spec->next) { if (!throw_spec->redundant) { format_rel(routine_symid, "throw", SET_symid_and_write_sym(throw_spec->type, iek_type, output_buffer), output_buffer); add_to_string("declared", output_buffer); terminate_string(output_buffer); } } } if (!in_il_walk) { /* write "define" relation for non member function reference */ if (!routine_ptr->source_corresp.is_class_member && routine_ptr->assoc_scope != NULL_region_number && !is_auto_gen_rout && !routine_ptr->compiler_generated) { a_scope_ptr scope_ptr = il_header.region_scope_entry[routine_ptr->assoc_scope]; a_statement_ptr assoc_block = (scope_ptr) ? scope_ptr->assoc_block : NULL; if (assoc_block) { write_define_relation(routine_ptr->source_corresp.decl_position.seq, routine_symid, output_buffer); } } } if (write_parent_relations) { /* write "context" REL between routine and its parent class/struct/union or namespace */ if (routine_ptr->source_corresp.is_class_member) { a_type_ptr parent = routine_ptr->source_corresp.parent.class_type; write_context_rel(SET_symid_and_write_sym(parent, iek_type, output_buffer), routine_symid, routine_ptr->source_corresp.access, output_buffer); /* Also write "static" attribute for static member routine. */ if (extra_info && !extra_info->this_class) { write_atr(routine_symid, "static", output_buffer); } } else { a_namespace_ptr namespace_ptr = routine_ptr->source_corresp.parent.namespace_ptr; if (namespace_ptr) { write_rel(SET_symid_and_write_sym(namespace_ptr, iek_namespace, output_buffer), "context", routine_symid, output_buffer); } } /* write "specialize" REL between instantiation and prototype template */ if (!routine_ptr->is_prototype_instantiation && routine_ptr->assoc_template) { write_specialize_rel(routine_symid, SET_symid_and_write_sym(routine_ptr->assoc_template, iek_template, output_buffer), NULL, routine_ptr->is_specialized, output_buffer); } } } } break; case iek_label: { a_label_ptr label_ptr = (a_label_ptr) entry_ptr; if (label_ptr->source_corresp.name) { insert_sym_prefix("label", label_ptr, iek_label, FALSE, FALSE, output_buffer); form_name(&label_ptr->source_corresp, iek_label, ocb_of_string_buf(output_buffer)); finish_name(label_ptr, iek_label, /*add_block_qual=*/FALSE, /*add_closing_quote=*/TRUE, output_buffer); if (mark_definitions && !in_template_function) { add_sym_def_pos_and_len_to_string(&label_ptr->source_corresp.decl_position, output_buffer); } terminate_string(output_buffer); } } break; case iek_expr_node: { if (in_il_walk) { an_expr_node_ptr expr = (an_expr_node_ptr) entry_ptr; a_boolean symid_slot_taken = FALSE; a_boolean compiler_generated = FALSE; a_boolean use_only_range_start_and_len = FALSE; switch(expr->kind) { case enk_new_delete: { a_new_delete_supplement_ptr new_del = (a_new_delete_supplement_ptr) expr->variant.new_delete; if (new_del->routine) { if (fcn_id && !(generate_multiple_IF_files && is_auto_gen_routine(curr_fcn))) { write_symbol_for_fcn_id(output_buffer); write_rel(fcn_id, "call", SET_symid_and_write_sym(new_del->routine, iek_routine, output_buffer), output_buffer); } } } break; case enk_routine_address: if (!expr->variant.routine.ptr) { /* NULL pointer to function: we have to manufacture a SYM. */ insert_sym_prefix("constant", expr, iek_expr_node, FALSE, FALSE, output_buffer); add_to_string("0\"", output_buffer); terminate_string(output_buffer); write_rel(SET_symid_and_write_sym(expr->type, iek_type, output_buffer), "type", SET_symid_of(expr, iek_expr_node), output_buffer); } break; case enk_operation: if (expr->kind == enk_operation && expr->variant.operation.kind == eok_call) { an_expr_node_ptr callee = expr->variant.operation.operands; if (fcn_id && callee->kind == enk_routine_address && !(generate_multiple_IF_files && is_auto_gen_routine(curr_fcn))) { write_symbol_for_fcn_id(output_buffer); write_rel(fcn_id, "call", SET_symid_and_write_sym(callee->variant.routine.ptr, iek_routine, output_buffer), output_buffer); } } break; default: break; } } } break; #ifdef CIL case iek_for_loop: { } break; case iek_switch_clause: { } break; case iek_handler: { if (in_il_walk) { a_handler_ptr handler = (a_handler_ptr) entry_ptr; write_symbol_for_fcn_id(output_buffer); if (handler->parameter) { write_rel(fcn_id, "catch", SET_symid_and_write_sym(handler->parameter->type, iek_type, output_buffer), output_buffer); } else write_rel(fcn_id, "catch", symid_of_ellipsis(output_buffer), output_buffer); } } break; case iek_try_supplement: { } break; #if MICROSOFT_EXTENSIONS_ALLOWED case iek_microsoft_try_supplement: { } break; #endif /* MICROSOFT_EXTENSIONS_ALLOWED */ #endif /* ifdef CIL */ case iek_block: { } break; case iek_statement: { } break; case iek_object_lifetime: { } break; case iek_scope: { if (in_il_walk) { a_scope_ptr ptr = (a_scope_ptr) entry_ptr; if (ptr->kind == sck_function) { a_routine_ptr routine_ptr = ptr->variant.routine.ptr; if (routine_ptr && ast_info_of(routine_ptr)) { a_variable_ptr parm; unsigned int argno = 1; if (generate_multiple_IF_files) { string_buffer_ptr alt_output_buffer = get_buffer_from_il_node(routine_ptr); if (alt_output_buffer != NULL && output_buffer != alt_output_buffer) { output_buffer = alt_output_buffer; } } write_symbol_for_fcn_id(output_buffer); for (parm = ptr->variant.routine.parameters; parm; parm = parm->next) { format_rel(SET_symid_and_write_sym(parm, iek_variable, output_buffer), "argument", fcn_id, output_buffer); add_num_to_string(argno++, "order(", ")", output_buffer); terminate_string(output_buffer); } } } } } break; case iek_id_name: { } break; case iek_string_text: { } break; case iek_other_text: { } break; #ifdef FIL case iek_internal_complex_value: { } break; case iek_bound_info_entry: { } break; case iek_do_loop: { } break; case iek_label_list_entry: { } break; case iek_io_specifier: { } break; case iek_io_list_item: { } break; case iek_namelist_group_member: { } break; case iek_namelist_group: { } break; case iek_input_output_description: { } break; case iek_entry_param: { } break; case iek_entry_description: { } break; #endif /* ifdef FIL */ #ifdef CIL case iek_namespace: { a_namespace_ptr namespace_ptr = (a_namespace_ptr) entry_ptr; insert_sym_prefix("namespace", namespace_ptr, iek_namespace, FALSE, FALSE, output_buffer); form_name(&namespace_ptr->source_corresp, iek_namespace, ocb_of_string_buf(output_buffer)); add_1_char_to_string('\"', output_buffer); terminate_string(output_buffer); if (!sym_line_only) { unsigned long namespace_symid = SET_symid_of(namespace_ptr, iek_namespace); if (namespace_ptr->is_namespace_alias) { write_rel(namespace_symid, "alias", SET_symid_and_write_sym(namespace_ptr->variant.assoc_namespace, iek_namespace, output_buffer), output_buffer); } else { a_scope_ptr scope = namespace_ptr->variant.assoc_scope; if (write_child_relations && scope) { a_constant_ptr constant; a_type_ptr type; a_variable_ptr variable; a_routine_ptr routine; a_namespace_ptr nested_namespace; a_using_decl_ptr using_decl; string_buffer_ptr bp = output_buffer; for (constant = scope->constants; constant; constant = constant->next) { write_rel(SET_symid_and_write_sym(namespace_ptr, iek_namespace, bp), "context", SET_symid_and_write_sym(constant, iek_constant, bp), bp); } for (type = scope->types; type; type = type->next) { write_rel(SET_symid_and_write_sym(namespace_ptr, iek_namespace, bp), "context", SET_symid_and_write_sym(type, iek_type, bp), bp); } for (variable = scope->variables; variable; variable = variable->next) { write_rel(SET_symid_and_write_sym(namespace_ptr, iek_namespace, bp), "context", SET_symid_and_write_sym(variable, iek_variable, bp), bp); } for (routine = scope->routines; routine; routine = routine->next) { write_rel(SET_symid_and_write_sym(namespace_ptr, iek_namespace, bp), "context", SET_symid_and_write_sym(routine, iek_routine, bp), bp); } for (nested_namespace = scope->namespaces; nested_namespace; nested_namespace = nested_namespace->next) { write_rel(SET_symid_and_write_sym(namespace_ptr, iek_namespace, bp), "context", SET_symid_and_write_sym(nested_namespace, iek_namespace, bp), bp); } } if (write_noninvertible_relations && scope) { a_using_decl_ptr using_decl; string_buffer_ptr bp = output_buffer; for (using_decl = scope->using_decls; using_decl; using_decl = using_decl->next) { if (generate_multiple_IF_files) { bp = get_buffer_from_il_node(using_decl); } if (bp) { format_rel(SET_symid_and_write_sym(namespace_ptr, iek_namespace, bp), "context", SET_symid_and_write_sym(using_decl->entity.ptr, using_decl->entity.kind, bp), bp); add_to_string("using", bp); terminate_string(bp); } } } if (write_parent_relations && !namespace_ptr->source_corresp.is_class_member) { a_namespace_ptr parent_namespace = namespace_ptr->source_corresp.parent.namespace_ptr; /* write "context" REL between namespace and its parent namespace */ if (parent_namespace) { write_rel(SET_symid_and_write_sym(parent_namespace, iek_namespace, output_buffer), "context", namespace_symid, output_buffer); } } } } } break; case iek_using_decl: { } break; case iek_dynamic_init: { if (in_il_walk) { a_dynamic_init_ptr init = (a_dynamic_init_ptr) entry_ptr; if (!init->variable && init->kind != dik_none && init->destructor && init->lifetime && !init->is_constructor_init) { insert_sym_prefix("variable", init, iek_dynamic_init, /*compiler_generated=*/TRUE, /*from_template=*/FALSE, output_buffer); add_to_string("<unnamed>", output_buffer); finish_name(init, iek_dynamic_init, /*add_block_qual=*/TRUE, /*add_closing_quote=*/TRUE, output_buffer); terminate_string(output_buffer); if (fcn_name) { write_atr(SET_symid_of(init, iek_dynamic_init), "auto", output_buffer); } } if (init->kind == dik_constructor) { if (fcn_id && !(generate_multiple_IF_files && is_auto_gen_routine(curr_fcn))) { write_symbol_for_fcn_id(output_buffer); write_rel(fcn_id, "call", SET_symid_and_write_sym(init->variant.constructor.ptr, iek_routine, output_buffer), output_buffer); } } if (fcn_id && init->destructor) { a_boolean is_base_dtor = FALSE; if (init->is_constructor_init && curr_fcn && curr_fcn->special_kind == sfk_constructor) { a_type_ptr derived_class = curr_fcn->source_corresp.parent.class_type; a_type_ptr base_class = init->destructor->source_corresp.parent.class_type; if (derived_class && base_class && find_direct_base_class_of(derived_class, base_class)) { is_base_dtor = TRUE; } } if (!is_base_dtor && !(generate_multiple_IF_files && is_auto_gen_routine(curr_fcn))) { /* We suppress calls to base class destructors because * the reference to the base class destructor from the * derived class constructor, with a virtual destructor, * makes the "where used" query useless: if you have * D1 and D2 both derived from B, you get the ridiculous * result that D1's destructor is called from D2's * constructor! */ write_symbol_for_fcn_id(output_buffer); write_rel(fcn_id, "call", SET_symid_and_write_sym(init->destructor, iek_routine, output_buffer), output_buffer); } } } } break; case iek_local_static_variable_init: { } break; case iek_vla_dimension: { } break; case iek_overriding_virtual_function: { } break; case iek_derivation_step: { } break; case iek_base_class_derivation: { } break; case iek_base_class: { } break; case iek_class_list_entry: { } break; case iek_routine_list_entry: { } break; case iek_class_type_supplement: { } break; case iek_template_param_type_supplement: { } break; case iek_constructor_init: { } break; case iek_asm_entry: { } break; case iek_template_arg: { } break; case iek_new_delete_supplement: { } break; case iek_throw_supplement: { if (in_il_walk) { a_throw_supplement_ptr throw = (a_throw_supplement_ptr) entry_ptr; write_symbol_for_fcn_id(output_buffer); format_rel(fcn_id, "throw", SET_symid_and_write_sym(throw->type, iek_type, output_buffer), output_buffer); add_to_string("actual", output_buffer); terminate_string(output_buffer); } } break; case iek_condition_supplement: { } break; #if !ABI_CHANGES_FOR_RTTI case iek_accessible_base_class: { } break; #endif /* !ABI_CHANGES_FOR_RTTI */ #if DO_IL_LOWERING && !DO_FULL_PORTABLE_EH_LOWERING case iek_eh_prologue_supplement: { } break; #endif /* DO_IL_LOWERING && !DO_FULL_PORTABLE_EH_LOWERING */ #endif /* ifdef CIL */ #if GENERATE_SOURCE_SEQUENCE_LISTS case iek_source_sequence_entry: { } break; case iek_src_seq_secondary_decl: { } break; case iek_src_seq_end_of_construct: { } break; case iek_src_seq_sublist: { } break; #if COMMENTS_IN_SOURCE_SEQUENCE_LISTS case iek_comment: { } break; #endif /* COMMENTS_IN_SOURCE_SEQUENCE_LISTS */ case iek_instantiation_directive: { } break; #endif /* GENERATE_SOURCE_SEQUENCE_LISTS */ #if SCOPE_ORPHANED_LIST_PROCESSING_NEEDED case iek_scope_orphaned_list_header: { if (in_il_walk) { orphaned_list_parent_seq_list = NULL; } } break; #endif /* SCOPE_ORPHANED_LIST_PROCESSING_NEEDED */ #if RECORD_HIDDEN_NAMES_IN_IL case iek_hidden_name: { } break; #endif /* RECORD_HIDDEN_NAMES_IN_IL */ case iek_pragma: { } break; case iek_template: { a_template_ptr template = (a_template_ptr) entry_ptr; a_symbol_ptr sym = (a_symbol_ptr) template-> source_corresp.assoc_info; a_template_symbol_supplement_ptr template_info; a_tagged_pointer parent_tag = {0, NULL}; unsigned long parent_symid = 0; a_type_kind kw_kind = tk_class; a_boolean is_auto_gen = is_auto_gen_member(&template->source_corresp); a_boolean defined_externally = FALSE; a_boolean is_canonical = (template == template->canonical_template); a_template_ptr definition_template = template->canonical_template != NULL ? template->canonical_template->definition_template : NULL; a_boolean is_definition = (definition_template == template); a_type_ptr parent = NULL; switch (template->kind) { case templk_class: case templk_member_class: if (template->prototype_instantiation.type != NULL) { a_type_ptr inst_type = template->prototype_instantiation.type; if (inst_type != NULL) { parent = inst_type->source_corresp.parent.class_type; } } break; case templk_function: case templk_member_function: if (template->prototype_instantiation.routine != NULL) { a_routine_ptr inst_rout = template->prototype_instantiation.routine; if (inst_rout) { parent = inst_rout->source_corresp.parent.class_type; } } break; case templk_static_data_member: if (template->prototype_instantiation.variable != NULL) { a_variable_ptr inst_var = template->prototype_instantiation.variable; if (inst_var) { parent = inst_var->source_corresp.parent.class_type; } } break; default: break; } if (is_auto_gen || is_specialized(template)) { /* Can't identify this template with the canonical declaration. */ } else { a_template_ptr external_tmpl = NULL; switch (template->kind) { case templk_function: case templk_member_function: if (template->prototype_instantiation.routine != NULL) { external_tmpl = has_tpl_entry(template->prototype_instantiation.routine); } break; case templk_static_data_member: if (template->prototype_instantiation.variable != NULL) { external_tmpl = variable_has_tpl_entry(template->prototype_instantiation.variable); } break; default: break; } defined_externally = (external_tmpl != NULL && external_tmpl->canonical_template != template->canonical_template); } if (is_definition && sym == NULL) { sym = (a_symbol_ptr)template->canonical_template ->source_corresp.assoc_info; } if (sym == NULL) { /* * The parser did not consider this template as 'interesting', * probably because it is a forward declaration for an already * declared template. Previously to EDG 2.43, it used to * report it anyway, but now this causes a crash, since sym * is used further down in this code without checking its * value. This means that we can safely 'break' in this case, * since sym was probably never NULL before (otherwise, of * course, we would've had a crash) */ if (is_definition) { worry("Expected symbol for template definition."); } if (definition_template == NULL && is_canonical) { worry("Expected symbol for canonical template declaration."); } if (!in_il_walk) { /* Complain because this check wasn't here before the modularization, and it could cause a change in results. */ complain(error_csev, "Expected symbol for template."); } break; } if (in_il_walk && ast_info_of(template)) { /* Must be a member template, already processed */ break; } if (template->kind == templk_class || template->kind == templk_member_class) { if (template->kind == templk_class) { template_info = sym ? sym->variant.template_info : NULL; if (template_info) { kw_kind = template_info->variant.class_template.type_kind; } } else kw_kind = sym->variant.class_struct_union.type->kind; } /* During il_walk output the SYM line & relations * if this is the definition or the canonical declaration. */ if ((definition_template != NULL ? is_definition : (is_canonical && !defined_externally)) || is_auto_gen || is_specialized(template) || !in_il_walk) { if (template->kind == templk_class || template->kind == templk_member_class) { if (kw_kind == tk_struct) { insert_sym_prefix("struct", template, iek_template, FALSE, TRUE, output_buffer); } else if (kw_kind == tk_union) { insert_sym_prefix("union", template, iek_template, FALSE, TRUE, output_buffer); } else insert_sym_prefix("class", template, iek_template, FALSE, TRUE, output_buffer); } else if (template->kind == templk_function || template->kind == templk_member_function) { insert_sym_prefix("function", template, iek_template, FALSE, TRUE, output_buffer); } else if (template->kind == templk_static_data_member) { insert_sym_prefix("variable", template, iek_template, FALSE, TRUE, output_buffer); } else { /* This might occur after a source error. */ insert_sym_prefix("template", template, iek_template, FALSE, FALSE, output_buffer); } add_to_string(template_qual_name_and_parent_symid(sym, &parent_tag), output_buffer); add_1_char_to_string('\"', output_buffer); if (mark_definitions && (is_definition || template->kind == templk_static_data_member)) { /* We won't see a static data member template unless we * see the definition; the declaration inside the class * won't create a template node. Otherwise, we check * for the definition range to see if the template was * defined and we should issue a position. */ add_sym_def_pos_to_string(&template->source_corresp.decl_position, output_buffer); } terminate_string(output_buffer); if (!sym_line_only || is_auto_gen_member(&template->source_corresp)) { unsigned long template_symid = SET_symid_of(template, iek_template); write_atr(template_symid, "template", output_buffer); if (parent_tag.ptr) { parent_symid = SET_symid_and_write_sym((void*)parent_tag.ptr, parent_tag.kind, output_buffer); } if (parent_symid) { write_context_rel(parent_symid, template_symid, template->source_corresp.access, output_buffer); } if (write_parent_relations) { if (parent) { write_context_rel(SET_symid_and_write_sym(parent, iek_type, output_buffer), template_symid, template->source_corresp.access, output_buffer); } /* write "static" attribute */ if (template->kind == templk_member_function) { a_routine_ptr inst_rout = template->prototype_instantiation.routine; if (inst_rout && inst_rout->source_corresp.is_class_member) { a_type_ptr inst_rout_type = inst_rout->type; a_routine_type_supplement_ptr extra_info = (inst_rout_type->kind == tk_routine) ? inst_rout_type->variant.routine.extra_info : NULL; if (extra_info && !extra_info->this_class) { write_atr(template_symid, "static", output_buffer); } } } else if (template->kind == templk_static_data_member) { write_atr(template_symid, "static", output_buffer); } } if (write_parent_relations && (template->kind == templk_class || template->kind == templk_member_class)) { /* Write "specialize" relation with "partial" attribute between * a partially specialized template and the primary template. */ a_symbol_ptr primary_template_sym; a_template_ptr primary_template; a_template_symbol_supplement_ptr primary_supp; a_symbol_ptr psym; if (template->kind == templk_class) { template_info = sym->variant.template_info; } else { template_info = sym->variant.class_struct_union.extra_info ->template_info; } if (template_info && sym->kind == sk_class_template) { /* For a partial specialization, primary_template_sym points * back to the primary template of which this is a partial * specialization. */ primary_template_sym = template_info->variant.class_template.primary_template_sym; if (primary_template_sym && primary_template_sym->kind == sk_class_template) { primary_supp = primary_template_sym->variant.template_info; primary_template = primary_supp->il_template_entry; /* Goes through all the partial specializations of the * primary template until one of them matches with the * current template. */ psym = primary_supp ? primary_supp->variant.class_template.partial_specializations : NULL; for (; psym; psym = psym->next) { a_template_ptr specialization = psym->variant.template_info->il_template_entry; if (specialization == template) { /* The current template is a partial specialization, write a "partial", "specialize" relation. */ write_specialize_rel(template_symid, SET_symid_and_write_sym(primary_template, iek_template, output_buffer), /*full_or_part=*/"partial", /*explicit=*/TRUE, output_buffer); break; } } } } } if (write_child_relations && sym) { if (template->kind == templk_class || template->kind == templk_member_class) { if (template->kind == templk_class) { template_info = sym->variant.template_info; } else { template_info = sym->variant.class_struct_union.extra_info ->template_info; } sym = template_info ? template_info->variant.class_template.instantiations : NULL; for (; sym; sym = next_instance_sym(sym)) { a_type_ptr type = sym->variant.class_struct_union.type; if (type) { write_specialize_rel(SET_symid_and_write_sym(type, iek_type, output_buffer), template_symid, /*full_or_part=*/"full", /*explicit=*/type->variant. class_struct_union.is_specialized, output_buffer); process_symbol_of_entry_if_needed((char *)type, iek_type); } } sym = template_info ? template_info->variant.class_template.partial_specializations : NULL; for (; sym; sym = sym->next) { a_template_ptr specialization = sym->variant.template_info->il_template_entry; if (specialization) { write_specialize_rel(SET_symid_and_write_sym(specialization, iek_template, output_buffer), template_symid, /*full_or_part=*/"partial", /*explicit=*/TRUE, output_buffer); } } } else if (template->kind == templk_function || template->kind == templk_member_function) { a_template_instance_ptr inst; if (template->kind == templk_function) { template_info = sym->variant.template_info; } else if (sym->variant.routine.instance_ptr != NULL) { template_info = sym->variant.routine.instance_ptr->template_info; } for (inst = template_info ? template_info->variant.function.instantiations : NULL; inst; inst = inst->next) { if (inst->instance_sym != inst->template_sym) { /* this is a "real" instance, not a member of * a prototype instantiation. */ a_routine_ptr fcn = inst->instance_sym-> variant.routine.ptr; write_specialize_rel(SET_symid_and_write_sym(fcn, iek_routine, output_buffer), template_symid, /*full_or_part=*/NULL, /*explicit=*/fcn->is_specialized, output_buffer); } } } else if (template->kind == templk_static_data_member) { a_template_instance_ptr inst; inst = sym->variant.static_data_member.instance_ptr; if (inst && inst->template_info) { a_template_instance_ptr definition; for (definition = inst->template_info->variant. static_data_member.definitions; definition; definition = definition->next) { if (definition->instance_sym) { a_variable_ptr var = definition->instance_sym-> variant.static_data_member.variable; if (var) { write_specialize_rel(SET_symid_and_write_sym(var, iek_variable, output_buffer), template_symid, /*full_or_part=*/NULL, /*explicit=*/var->is_specialized, output_buffer); } } } } } } } } /* end of handling SYM line etc. for defn or canonical decl */ else { /* Not the primary occurrence of this template; don't generate SYM. * e.g. for a member template of a class template, it recurs as * a member of the prototype instantation, t165.C. */ if (!in_il_walk) { worry("Before modularization, would have written symbol info."); } } } break; #if RECORD_MACROS_IN_IL case iek_macro: break; #endif /* RECORD_MACROS_IN_IL */ #if ONE_INSTANTIATION_PER_OBJECT case iek_per_instantiation_needed_flags_entry: break; #endif /* ONE_INSTANTIATION_PER_OBJECT */ #if EXTRA_SOURCE_POSITIONS_IN_IL case iek_decl_position_supplement: break; #endif /* EXTRA_SOURCE_POSITIONS_IN_IL */ #if PROTOTYPE_INSTANTIATIONS_IN_IL case iek_template_decl: break; case iek_template_parameter: break; #endif /* PROTOTYPE_INSTANTIATIONS_IN_IL */ /* XXX: these enumerations need to be examined */ #if RECORD_FORM_OF_NAME_REFERENCE case iek_name_reference: case iek_name_qualifier: #endif /* RECORD_FORM_OF_NAME_REFERENCE */ #if MICROSOFT_EXTENSIONS_ALLOWED case iek_ms_attribute: case iek_ms_attribute_arg: #endif /* MICROSOFT_EXTENSIONS_ALLOWED */ case iek_seq_number_lookup_entry: #if MACRO_INVOCATION_TREE_IN_IL case iek_macro_invocation_record_block: #endif /* MACRO_INVOCATION_TREE_IN_IL */ #if GENERATE_MICROSOFT_IF_EXISTS_ENTRIES case iek_ms_if_exists: #endif /* GENERATE_MICROSOFT_IF_EXISTS_ENTRIES */ case iek_local_expr_node_ref: #if EXPR_RANGE_MODIFIERS_IN_IL case iek_expr_range_modifier: #endif /* EXPR_RANGE_MODIFIERS_IN_IL */ #if GENERATE_SOURCE_SEQUENCE_LISTS case iek_static_assertion: #endif /* GENERATE_SOURCE_SEQUENCE_LISTS */ break; /* /XXX: pending enumerations */ default: complain_int(error_csev, "Unsupported entry kind $1", entry_kind); break; } /* switch */ } /* write_symbol */ void write_referenced_symbol_info(char *entry_ptr, an_il_entry_kind entry_kind, string_buffer_ptr output_buffer, a_boolean sym_line_only) { befriend_clique(entry_ptr, entry_kind); write_symbol(entry_ptr, entry_kind, output_buffer, sym_line_only, FALSE, FALSE); } void write_symbol_of_entry(char *entry_ptr, an_il_entry_kind entry_kind, a_boolean in_il_walk, a_boolean write_noninvertible_relations) { string_buffer_ptr output_buffer = get_buffer_from_il_node(entry_ptr); write_symbol(entry_ptr, entry_kind, output_buffer, FALSE, in_il_walk, write_noninvertible_relations); } static void process_symbol_of_entry(char *entry_ptr, an_il_entry_kind entry_kind) { if (!skip_entry(entry_ptr, entry_kind)) { write_symbol_of_entry(entry_ptr, entry_kind, FALSE, TRUE); } } /* process_symbol_of_entry */ /* The following function is called in response to the command line * option --SET_memory_metering; it shows the memory usage of all the * data structures managed in this file. */ void dump_symbol_memory_meters() { fprintf(stderr, "sym_summary_meter =\t\t%10lu\n", (unsigned long)sym_summary_meter); }
35.321452
132
0.678483
[ "object" ]
6e0e7654a2bebb00fdebead4fb0281ae8f2e665b
1,015
h
C
src/SuperimposeMesh/include/SuperimposeMesh/Model.h
xEnVrE/superimpose-mesh-lib
da269af9baf9a583e4a0cf9cea3288b7e8d037b3
[ "BSD-3-Clause" ]
14
2017-04-12T09:03:40.000Z
2022-03-09T16:22:49.000Z
src/SuperimposeMesh/include/SuperimposeMesh/Model.h
Pandinosaurus/superimpose-mesh-lib
da269af9baf9a583e4a0cf9cea3288b7e8d037b3
[ "BSD-3-Clause" ]
23
2018-05-05T17:52:12.000Z
2021-02-17T13:23:27.000Z
src/SuperimposeMesh/include/SuperimposeMesh/Model.h
Pandinosaurus/superimpose-mesh-lib
da269af9baf9a583e4a0cf9cea3288b7e8d037b3
[ "BSD-3-Clause" ]
7
2017-05-19T07:26:23.000Z
2020-11-07T00:14:53.000Z
/* * Copyright (C) 2016-2019 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * BSD 3-Clause license. See the accompanying LICENSE file for details. */ #ifndef MODEL_H #define MODEL_H #include <SuperimposeMesh/Shader.h> #include <SuperimposeMesh/Mesh.h> #include <vector> #include <string> #include <assimp/scene.h> #include <GL/glew.h> class Model { public: Model(const GLchar* path); void Draw(Shader shader); bool has_texture(); protected: void loadModel(std::string path); void processNode(aiNode* node, const aiScene* scene); Mesh processMesh(aiMesh* mesh, const aiScene* scene); GLint TextureFromFile(const char* path, std::string directory); std::vector<Mesh::Texture> loadMaterialTextures(aiMaterial* mat, aiTextureType type, std::string typeName); private: std::vector<Mesh> meshes_; std::string directory_; std::vector<Mesh::Texture> textures_loaded_; }; #endif /* MODEL_H */
19.901961
111
0.714286
[ "mesh", "vector", "model" ]
6e19a0e07e5508aa766d2b26ae6c4bf2d73e40c4
3,549
h
C
Battleships/Source/Core/Entity/Actor/FActor.h
RodrigoHolztrattner/Battleships
cf3e9c8a4a40f52aee41a7b9baaac5a406365a06
[ "MIT" ]
null
null
null
Battleships/Source/Core/Entity/Actor/FActor.h
RodrigoHolztrattner/Battleships
cf3e9c8a4a40f52aee41a7b9baaac5a406365a06
[ "MIT" ]
null
null
null
Battleships/Source/Core/Entity/Actor/FActor.h
RodrigoHolztrattner/Battleships
cf3e9c8a4a40f52aee41a7b9baaac5a406365a06
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Filename: FActor.h //////////////////////////////////////////////////////////////////////////////// #ifndef _FActor_H_ #define _FActor_H_ ///////////// // LINKING // ///////////// ////////////// // INCLUDES // ////////////// #include "..\..\Containers\Array\TArray.h" #include "..\..\Support\Math\WMath.h" #include "..\IEntity.h" #include "FObject.h" // Declare we know IRenderable class IRenderable; class FShaderBase; ///////////// // DEFINES // ///////////// /* => Actor (props/doodads and unit will extend this class) - Placeable in world (3D) - Have an array of renderables - Can have more actors linked - Can have IA or movements - Can block path - Extend entity */ //////////////////////////////////////////////////////////////////////////////// // Class name: FActor //////////////////////////////////////////////////////////////////////////////// class FActor : public FObject, public IEntity { private: public: /////////////////////////////////// // CREATION / DESTRUCTION / BASE // /////////////////////////////////// // Create a instance of this object and return a ptr to it template <typename ActorClass> static ActorClass* Create() { return IEntity::Create<ActorClass>(); } // Create a instance of this object, link to another actor and return a ptr to it template <typename ActorClass> static ActorClass* Create(FActor* _owner) { // Check if the owner is NOT marked to deletion // ... // Create a new actor ActorClass* newActor = new ActorClass; // Link those 2 actors newActor->LinkActors(_owner); // Register the new actor/entity RegisterEntity(newActor); return newActor; } // Release this object (mark it for deletion), also, mark any child for deletion too virtual void Release() { // If we have an owner actor, remove the link // ... TO-BE IMPLEMENTED! // Release all childs while (m_LinkedActors.Size()) { // Release this child m_LinkedActors[0]->Release(); // Remove it from the array m_LinkedActors.Remove(0); } // Set the main release IEntity::Release(); } // Return the owner FActor* GetOwner() { return m_Owner; } protected: // Same as Entity, constructor, copy-constructor and deconstructor are protected FActor(); FActor(const FActor&); virtual ~FActor(); // Update this actor virtual void Update(float _time) = 0; private: /////////////////////// // LINKAGE AND CHILD // /////////////////////// // Link 2 actors (making a relationship between them) void LinkActors(FActor* _owner) { // Set the owner m_Owner = _owner; // Add this (the child) to the owner linked actor array _owner->AddChildActor(this); } // Add a child to this actor void AddChildActor(FActor* _child) { m_LinkedActors.Add(_child); } protected: // Promote this actor physically (allowing it to collide and be picked in the world) void Promote(); private: // The owner (only valid if this actor is linked with another one, else this ptr is null) FActor* m_Owner; // The array of linked actors TArray<FActor*> m_LinkedActors; // If this actor is promoted bool m_Promoted; private: /////////////// // OVERRIDED // /////////////// // Set the actor location public: virtual void SetLocation(WVector3 _location); protected: /////////////// // CALLBACKS // /////////////// // Called when a renderable animation expired public: virtual void OnRenderableAnimationExpired(IRenderable* _who){}; }; #endif
20.396552
90
0.578473
[ "object", "3d" ]
42295607c7ee79d2fe6e963c45cf6d737576d6d6
1,595
h
C
ASE/playground/utils.h
daB0bby/ASE
62cfe021fdbea87feb63808b8e65d387ed5867f1
[ "MIT" ]
1
2020-05-22T13:20:34.000Z
2020-05-22T13:20:34.000Z
ASE/playground/utils.h
dab0bby/ASE
62cfe021fdbea87feb63808b8e65d387ed5867f1
[ "MIT" ]
null
null
null
ASE/playground/utils.h
dab0bby/ASE
62cfe021fdbea87feb63808b8e65d387ed5867f1
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <sstream> #include <vector> inline void split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss; ss.str(s); std::string item; while (std::getline(ss, item, delim)) elems.push_back(item); } inline std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, elems); return elems; } inline std::string trimStart(const std::string& s, char delim) { if (s.empty()) return s; int cnt = 0; while (cnt < s.size() && s[cnt] == delim) cnt++; return cnt == 0 ? s : cnt > s.size() ? "" : s.substr(cnt); } inline std::string trimEnd(const std::string& s, char delim) { if (s.empty()) return s; int cnt = 1; while (cnt <= s.size() && s[s.size() - cnt] == delim) cnt++; cnt--; return cnt == 0 ? s : cnt > s.size() ? "" : s.substr(0, s.size() - cnt); } inline std::string trim(const std::string& s, char delim) { return trimEnd(trimStart(s, delim), delim); } inline std::string removeRepetitions(const std::string s, char delim) { if (s == "") return s; std::string res; res.reserve(s.size() + 1); int cnt = 0; for (char c : s) { cnt = c == delim ? cnt + 1 : 0; if (cnt > 1) continue; res += c; } return res; } template <typename TF, typename... Ts> void for_each_argument(TF&& f, Ts&&... xs) { std::initializer_list<int>{ (f(std::forward<Ts>(xs)), 0)... }; }
19.691358
84
0.549216
[ "vector" ]
4229da9f9f0f32c048ecdeb8a55be9a344fd45d0
642
h
C
catkin_ws/src/srrg2_core/srrg2_core/src/srrg_viewer/active_drawable.h
laaners/progetto-labiagi_pick_e_delivery
3453bfbc1dd7562c78ba06c0f79b069b0a952c0e
[ "MIT" ]
null
null
null
catkin_ws/src/srrg2_core/srrg2_core/src/srrg_viewer/active_drawable.h
laaners/progetto-labiagi_pick_e_delivery
3453bfbc1dd7562c78ba06c0f79b069b0a952c0e
[ "MIT" ]
null
null
null
catkin_ws/src/srrg2_core/srrg2_core/src/srrg_viewer/active_drawable.h
laaners/progetto-labiagi_pick_e_delivery
3453bfbc1dd7562c78ba06c0f79b069b0a952c0e
[ "MIT" ]
null
null
null
#pragma once #include "drawable_base.h" namespace srrg2_core { //! @brief base derivable class that represent an object that could be "drawn" //! using OpenGL and OpenCV class ActiveDrawable: public DrawableBase { public: void addCanvas(ViewerCanvasPtr canvas); void removeCanvas(ViewerCanvasPtr canvas); void draw(); protected: using ViewerCanvasWeakPtr = std::weak_ptr<ViewerCanvas>; std::list<ViewerCanvasWeakPtr> _canvases; std::list<ViewerCanvasWeakPtr>::iterator findCanvas(ViewerCanvasPtr canvas); }; using ActiveDrawablePtr = std::shared_ptr<ActiveDrawable>; } // namespace srrg2_core
29.181818
80
0.741433
[ "object" ]
422e979c31a7f2908d0ca4d1e80b0fcefeffba92
2,311
h
C
Distributor.h
arayq2/utility
85a482c71e8155761e7b62b2b7f0d9be5beac84e
[ "MIT" ]
null
null
null
Distributor.h
arayq2/utility
85a482c71e8155761e7b62b2b7f0d9be5beac84e
[ "MIT" ]
null
null
null
Distributor.h
arayq2/utility
85a482c71e8155761e7b62b2b7f0d9be5beac84e
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <algorithm> namespace Utility { class Indexer { struct Pair { Pair(size_t index = 0) : index_(index) , total_(0) {} struct Comparator { bool operator() ( Pair const& lhs, Pair const& rhs ) { return rhs.total_ < lhs.total_; } }; size_t index_; size_t total_; }; public: Indexer(size_t size) : array_(size) { size_t _ctr(0); for ( auto& _item : array_ ) { _item.index_ = _ctr++; } std::make_heap( array_.begin(), array_.end(), Pair::Comparator() ); } size_t operator() ( size_t size ) { // extract smallest total std::pop_heap( array_.begin(), array_.end(), Pair::Comparator() ); // save index size_t _index(array_.back().index_); // update and reheap array_.back().total_ += size; std::push_heap( array_.begin(), array_.end(), Pair::Comparator() ); return _index; } template<typename Action> void for_each( Action&& action ) const { for ( auto const& _item : array_ ) { action( _item.index_, _item.total_ ); } } private: std::vector<Pair> array_; }; template<typename ValueType> class Distributor { using List = std::vector<ValueType>; using Lists = std::vector<List>; public: Distributor(size_t size) : indexer_(size) , lists_(size) {} void assign( ValueType const& value, size_t size ) { lists_[indexer_( size )].push_back( value ); } template<typename Action> void for_each( Action&& action ) const { indexer_.for_each( [&action, this]( size_t index, size_t total ) { action( total, lists_[index] ); } ); } private: Indexer indexer_; Lists lists_; }; } // namespace Utility
24.849462
88
0.459541
[ "vector" ]
422ecc285b91aecb6c2fcd27893bff3c2c3e73d7
8,957
c
C
src/ccow/tools/blobfind.c
SeanTBooker/edgefs
2e5d4ac1feadac55827f7b452c577b0531293a50
[ "Apache-2.0" ]
18
2020-05-11T20:35:19.000Z
2021-12-16T02:33:11.000Z
src/ccow/tools/blobfind.c
SeanTBooker/edgefs
2e5d4ac1feadac55827f7b452c577b0531293a50
[ "Apache-2.0" ]
null
null
null
src/ccow/tools/blobfind.c
SeanTBooker/edgefs
2e5d4ac1feadac55827f7b452c577b0531293a50
[ "Apache-2.0" ]
16
2020-05-11T19:54:53.000Z
2021-09-09T01:20:13.000Z
/* * Copyright (c) 2015-2018 Nexenta Systems, inc. * * This file is part of EdgeFS Project * (see https://github.com/Nexenta/edgefs). * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses 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. */ #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <getopt.h> #include <time.h> #include "ccowutil.h" #include "ccow.h" #include "ccow-impl.h" #include "blob-lookup.h" #include "reptrans-data.h" const char* ref_type_name[] = { "UNDEFINED", "RT_REF_TYPE_NORMAL", "RT_REF_TYPE_MANIFEST", "RT_REF_TYPE_ZEROBLOCK", "RT_REF_TYPE_INLINE_PAYLOAD", /* content_hash_id is NULL */ "RT_REF_TYPE_INLINE_VERSION", /* content_hash_id points to VM */ "RT_REF_TYPE_INLINE_MANIFEST" /* content_hash_id points to CM */ }; static void opps_get_chunk_manifest_cb(struct getcommon_client_req *r) { if (r->rb) { rtbuf_t *rbcopy = rtbuf_init_alloc(r->rb->bufs, r->rb->nbufs); rtbuf_t **rbuf = r->chunkmap_data; *rbuf = rbcopy; } } static int blobfind_get_chunk(ccow_t cl, type_tag_t ttag, const uint512_t* nhid, const uint512_t* chid, rtbuf_t **rbuf) { int err; struct ccow_op *get_op; struct ccow_io *get_io; ccow_completion_t c; err = ccow_create_completion(cl, NULL, NULL, 1, &c); if (err) return err; err = ccow_operation_create(c, CCOW_GET, &get_op); if (err) { ccow_release(c); return err; } err = ccow_unnamedget_create(c, opps_get_chunk_manifest_cb, get_op, &get_io, NULL); if (err) { ccow_operation_destroy(get_op, 1); ccow_release(c); return err; } struct getcommon_client_req *req = CCOW_IO_REQ(get_io); rtbuf_t *rb = NULL; req->chid = *chid; req->hash_type = HASH_TYPE_DEFAULT; req->chunkmap_data = &rb; if (ttag == TT_CHUNK_MANIFEST) get_io->attributes |= RD_ATTR_CHUNK_MANIFEST; else if (ttag == TT_VERSION_MANIFEST) { assert(nhid); req->ng_chid = *nhid; get_io->attributes |= RD_ATTR_VERSION_MANIFEST; } else get_io->attributes |= RD_ATTR_CHUNK_PAYLOAD; get_io->attributes |= RD_ATTR_RETRY_FAILFAST; err = ccow_start_io(get_io); if (err) { ccow_operation_destroy(get_op, 1); ccow_release(c); return err; } err = ccow_timed_wait(c, 0, 5000); if (err) { if (err == -EBUSY) { uv_mutex_lock(&c->operations_mutex); req->done_cb = NULL; uv_mutex_unlock(&c->operations_mutex); } return err; } if (rb == NULL) return -ENOMEM; *rbuf = rb; return 0; } void usage() { printf("\nUsage: blobfind <CHID> <TYPETAG> <HASHTYPE> [NHID|NAME] [OPTIONS]\n"); printf(" -h, --help\t\t display this help message\n\n"); printf(" -v, --verbose\t\t decode manifest's metadata and refEntries\n\n"); printf(" -n, --name\t\t calculate NHID from object name\n\n"); printf("Lookup for a blob with specified CHID, TYPETAG and HASHTYPE (e.g. HASH_TYPE_BLAKE2B_256)\n\n"); } int main(int argc, char* argv[]) { static struct option long_opts[] = { { "help", 0, 0, 'h'}, { "verbose", 0, 0, 'v'}, { "name", 0, 0, 'n'}, { 0, 0, 0, 0} }; uint512_t chid; uint512_t nhid = uint512_null; type_tag_t ttag = TT_LAST; crypto_hash_t htype = HASH_TYPE_END; int p, i, id = 0, err = 0; int verbose = 0, name = 0; if (argc < 4) { fprintf(stderr, "Wrong number of arguments\n"); usage(); return -EINVAL; } char *chid_in = argv[1]; char *ttag_in = argv[2]; char *htype_in = argv[3]; char *nhid_in = 0; if (argc > 4) { nhid_in = argv[4]; uint512_fromhex(nhid_in, UINT512_BYTES * 2 + 1, &nhid); } uint512_fromhex(chid_in, UINT512_BYTES * 2 + 1, &chid); for (i = TT_NAMEINDEX; i < TT_LAST; ++i) { if (!strncmp(ttag_in, type_tag_name[i], strlen(type_tag_name[i]))) { ttag = (type_tag_t)i; break; } } if (ttag == TT_LAST) { fprintf(stderr, "Wrong TYPETAG\n"); usage(); return -EINVAL; } for (i = HASH_TYPE_DEFAULT; i < HASH_TYPE_END; ++i) { if (!strncmp(htype_in, hash_type_name[i], strlen(hash_type_name[i]))) { htype = (crypto_hash_t)i; break; } } if (htype == HASH_TYPE_END) { fprintf(stderr, "Wrong HASHTYPE\n"); usage(); return -EINVAL; } while ((p = getopt_long (argc, argv, "hvn", long_opts, &id)) >= 0) { switch (p) { case 'h': usage(); return 0; break; case 'v': verbose = 1; break; case 'n': name = 1; break; default: return -EINVAL; } } static ccow_t cl; char path[PATH_MAX]; snprintf(path, sizeof(path), "%s/etc/ccow/ccow.json", nedge_path()); int fd = open(path, O_RDONLY); if (fd < 0) { fprintf(stderr, "Cannot open ccow.json\n"); return err; } char *buf = je_calloc(1, 16384); if (read(fd, buf, 16384) == -1) { fprintf(stderr, "Cannot read ccow.json\n"); close(fd); return -1; } close(fd); err = ccow_admin_init(buf, "", 1, &cl); if (err) { fprintf(stderr, "Cannot create admin context\n"); je_free(buf); return err; } je_free(buf); if (name) { char cid[2048], tid[2048], bid[2048], oid[2048]; if (sscanf(nhid_in, "%2047[^/]/%2047[^/]/%2047[^/]/%2047[^\n]", cid, tid, bid, oid) < 4) { fprintf(stderr, "NHID calc error: wrong object path format\n"); return -1; } load_crypto_lib(); err = ccow_calc_nhid(cid, tid, bid, oid, &nhid); if (err) { fprintf(stderr, "NHID calc error: %d\n", err); return err; } } struct ccow_completion *c; err = ccow_create_completion(cl, NULL, NULL, 1, (ccow_completion_t *)&c); if (err) { fprintf(stderr, "Cannot create CCOW completion\n"); ccow_tenant_term(cl); return err; } size_t n_vdevs = RT_SYSVAL_REPLICATION_COUNT*4; uint128_t vdevs[RT_SYSVAL_REPLICATION_COUNT*4]; err = ccow_blob_lookup_request(cl->netobj, &chid, ttag, htype, c, vdevs, &n_vdevs); if (err) { fprintf(stderr, "Cannot send blob lookup request\n"); ccow_release(c); ccow_tenant_term(cl); return err; } err = ccow_wait(c, 0); if (err) { printf("Error: %d\n", err); } else { if (!n_vdevs) printf("Blob not found\n"); else { char vdevstr[UINT128_BYTES*2+1]; printf("Blob found on %lu VDEVs: ", n_vdevs); for (size_t i = 0; i < n_vdevs; i++) { uint128_dump(vdevs + i, vdevstr, UINT128_BYTES*2+1); if (i < n_vdevs - 1) printf("%s, ", vdevstr); else printf("%s\n", vdevstr); } } if (verbose && (ttag == TT_CHUNK_MANIFEST || ttag == TT_VERSION_MANIFEST)) { /* Trying to get the chunk */ rtbuf_t* rb = NULL; err = blobfind_get_chunk(cl, ttag, &nhid, &chid, &rb); if (err) printf("Manifest get error: %d\n", err); else { printf("Manifest size:\t%lu bytes\n", rb->bufs->len); if (ttag == TT_VERSION_MANIFEST) { struct vmmetadata md; char chidstr[UINT512_BYTES*2+1]; int err = replicast_get_metadata(rb, &md); printf("CID:\t\t%s\n", md.cid); printf("TID:\t\t%s\n", md.tid); printf("BID:\t\t%s\n", md.bid); printf("OID:\t\t%s\n", md.oid); uint512_dump(&md.nhid, chidstr, UINT512_BYTES*2+1); printf("NHID:\t\t%s\n", chidstr); uint128_dump(&md.uvid_src_guid, chidstr, UINT128_BYTES*2+1); printf("SRCGUID:\t\t%s\n", chidstr); printf("Log. size:\t%lu\n", md.logical_size); printf("UVID:\t\t%lu\n", md.uvid_timestamp); printf("GEN:\t\t%lu\n", md.txid_generation); printf("Obj. deleted:\t%u\n", md.object_deleted); printf("RepCount:\t%u\n", md.replication_count); printf("Num.vers:\t%u\n", md.number_of_versions); printf("Btree order:\t%u\n", md.chunkmap_btree_order); printf("Chunk size:\t%u\n", md.chunkmap_chunk_size); printf("Chunk map type:\t%s\n", md.chunkmap_type); } rtbuf_t* refs = NULL; err = ttag == TT_CHUNK_MANIFEST ? replicast_unpack_cm_refs(rb, &refs, 0) : replicast_get_refs(rb, &refs, 0); if (err) fprintf(stderr, "Manifest unpack error\n"); else { assert(refs); printf("refEntries:\n"); for (size_t i = 0; i < refs->nbufs; ++i) { struct refentry* le = (struct refentry *)rtbuf(refs, i).base; int refType = RT_REF_TYPE(le); crypto_hash_t ht = RT_REF_HASH_TYPE(le); char refchidstr[UINT512_BYTES*2+1]; uint512_dump(&le->content_hash_id, refchidstr, UINT512_BYTES*2+1); printf("%lu:\t%s %s %lu %lu\t%s\n", i, ref_type_name[refType], hash_type_name[ht], le->offset, le->length, refchidstr); } } } } } ccow_tenant_term(cl); return 0; }
26.421829
110
0.652339
[ "object" ]
4247fbca03d358b9cc122aa9b6e39944f63e7d91
887
h
C
game-emu-common/include/game-emu/common/coreloader.h
Dudejoe870/game-emu
153b7f9b7bc56042cc6d41187688aa1d9a612830
[ "MIT" ]
1
2022-03-28T21:03:10.000Z
2022-03-28T21:03:10.000Z
game-emu-common/include/game-emu/common/coreloader.h
Dudejoe870/game-emu
153b7f9b7bc56042cc6d41187688aa1d9a612830
[ "MIT" ]
null
null
null
game-emu-common/include/game-emu/common/coreloader.h
Dudejoe870/game-emu
153b7f9b7bc56042cc6d41187688aa1d9a612830
[ "MIT" ]
null
null
null
#pragma once #include <game-emu/common/stdcommon.h> #include <game-emu/common/symbolhelper.h> #include <dynalo/dynalo.hpp> namespace GameEmu::Common { class Core; class CoreLoader { private: std::vector<Core*> cores; std::vector<dynalo::library> coreLibraries; public: /* Loads all the DLL system cores from the coreSubdirectory (relative to the executable directory) Note: There is no guaranty of load order. */ LIBGAMEEMU_COMMON_DLL_EXPORT CoreLoader(std::filesystem::path coreSubdirectory); /* Frees all DLL system cores from memory. */ LIBGAMEEMU_COMMON_DLL_EXPORT ~CoreLoader(); /* Get all the currently loaded cores. */ LIBGAMEEMU_COMMON_DLL_EXPORT const std::vector<Core*>& getLoadedCores(); /* Get a currently loaded core with the specified name. */ LIBGAMEEMU_COMMON_DLL_EXPORT Core* getLoadedCore(std::string name); }; }
22.175
98
0.732807
[ "vector" ]
424dcc46ce12db49e7c993cbbf4693e60b6469f1
3,929
h
C
include/AsciiLineReader.h
inugami-dev64/libdas
66e5892e13ebcbb5d6cdc1314aeb4e7fec42248a
[ "Apache-2.0" ]
null
null
null
include/AsciiLineReader.h
inugami-dev64/libdas
66e5892e13ebcbb5d6cdc1314aeb4e7fec42248a
[ "Apache-2.0" ]
null
null
null
include/AsciiLineReader.h
inugami-dev64/libdas
66e5892e13ebcbb5d6cdc1314aeb4e7fec42248a
[ "Apache-2.0" ]
null
null
null
// libdas: DENG asset handling management library // licence: Apache, see LICENCE file // file: AsciiLineReader.h - Ascii file reading class header // author: Karl-Mihkel Ott #ifndef ASCII_LINE_READER_H #define ASCII_LINE_READER_H #ifdef ASCII_LINE_READER_CPP #include <cstring> #include <string> #include <vector> #include <fstream> #include <utility> #include <Api.h> #include <AsciiStreamReader.h> #endif #define NEWLINE '\n' namespace Libdas { class LIBDAS_API AsciiLineReader : public AsciiStreamReader { private: std::string m_file_name; char *m_line_beg = nullptr; char *m_line_end = nullptr; char *m_rd_ptr = nullptr; protected: /** * Read new line from buffer * @return True if newline was found, false otherwise */ bool _NextLine(); /** * Read all general statement arguments until the end of line */ std::vector<std::string> _ReadStatementArgs(); /** * Skip all skippable characters (' ', 0x00, '\t', '\d' and or '\n') * @param _skip_nl is a boolean flag indicating newline skipping */ void _SkipSkippableCharacters(bool _skip_nl = false); /** * Skip the reading pointer by specified amount * @param _skip_val is a size_t value that specifies the read_ptr offset in bytes * @return true if data skipping was successful, false otherwise */ bool _SkipData(const size_t _skip_val); /** * Extract word statement, assuming that the starting position character is not skippable * @return End position of the word */ char *_ExtractWord(); /** * Extract string value from buffer (value must be in between quotation marks) * @return std::string value that contains the string value without quotation marks */ std::string _ExtractString(); /** * Allocate memory and extract a binary blob from stream to buffer * @param _size specifying the readable blob size in bytes * @param _data is an optional argument specifying a pointer that specifies the memory area, * where data should be written to to. If the specified, no allocation occurs and the same pointer is returned * @return a pointer to the BLOB data memory area or nullptr if the reading failed */ char *_ExtractBlob(uint32_t _size, char *_data = nullptr); /** * Get the current buffer reading pointer * @return current reading pointer */ char *_GetReadPtr(); /** * @return std::pair object where the first element specifies beginning of the line and second element * specifies the end of line */ std::pair<char*, char*> _GetLineBounds(); /** * Explicitly set the new m_rd_ptr value * @param _ptr, new m_rd_ptr value */ void _SetReadPtr(char *_ptr); /** * Explicitly set the line bounds * @param _bounds is a std::pair value, where the first element states line beginning and second element states the line ending */ void _SetLineBounds(const std::pair<char*, char*> &_bounds); public: AsciiLineReader(const std::string &_file_name, size_t _chunk_size = DEFAULT_CHUNK, const std::string &_end = "\n"); /** * Get the current file name that is being read * @return file name in std::string class format */ std::string GetFileName(); }; } #endif
37.778846
139
0.576737
[ "object", "vector" ]
4257c7250365a74a2cbe51eab5c6fd75a16432af
514
h
C
cpp/handlers/requests.h
propaganda-gold/deeprev
0c6ccf83131a879ed858acdb0675e75ebf2f2d3d
[ "BSD-3-Clause" ]
null
null
null
cpp/handlers/requests.h
propaganda-gold/deeprev
0c6ccf83131a879ed858acdb0675e75ebf2f2d3d
[ "BSD-3-Clause" ]
2
2021-05-11T16:29:38.000Z
2022-01-22T12:28:49.000Z
cpp/handlers/requests.h
propaganda-gold/deeprev
0c6ccf83131a879ed858acdb0675e75ebf2f2d3d
[ "BSD-3-Clause" ]
null
null
null
#ifndef HANDLERS_MS_REQUEST #define HANDLERS_MS_REQUEST #include "util/includes.h" #include "handlers/http.pb.h" #include "handlers/api.h" namespace vectorbook { using std::vector; using std::string; // Converts a string-valued request to an internal object. HttpRequest ConvertHttpRequest(const string &original); Option<string> ConvertHttpResponse(const HttpResponse& response); Option<HttpResponse> MakeResponse(int code, const string& content); } // namespace vectorbook #endif /* HANDLERS_MS_REQUEST */
24.47619
67
0.789883
[ "object", "vector" ]
42647dbf64cc32affa806baeb7800cce8744c7c7
1,651
h
C
src/services/pcn-katran/src/MaglevBase.h
Morpheus-compiler/polycube
3e1285bb1ebcb5e609097b2c7750a2741b466f69
[ "ECL-2.0", "Apache-2.0" ]
1
2022-01-24T07:36:56.000Z
2022-01-24T07:36:56.000Z
src/services/pcn-katran/src/MaglevBase.h
Morpheus-compiler/polycube
3e1285bb1ebcb5e609097b2c7750a2741b466f69
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/services/pcn-katran/src/MaglevBase.h
Morpheus-compiler/polycube
3e1285bb1ebcb5e609097b2c7750a2741b466f69
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * 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; version 2 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <cstdint> #include <vector> #include "CHHelpers.h" namespace katran { /** * MaglevBase class implements Maglev's permutation and should be used as a base * class for all versions of Maglev's hashing (more info: * http://research.google.com/pubs/pub44824.html ; section 3.4) */ class MaglevBase : public ConsistentHash { public: MaglevBase() {} /** * @param vector<uint32_t>& container for generated permutations * @param Endpoint& endpoint endpoint for which permutation is going to be * generated * @param uint32_t pos position of specified endpoint * @param uint32_t ring_size size of the hash ring * * helper function which will generate Maglev's permutation array for * specified endpoint on specified possition */ static void genMaglevPermutation( std::vector<uint32_t>& permutation, const Endpoint& endpoint, const uint32_t pos, const uint32_t ring_size); }; } // namespace katran
33.02
80
0.732889
[ "vector" ]
426700df3d151559e685051d97d224a461fe47ba
2,754
c
C
bkarachok/lab5_SPI_OLED/user.c
kpi-keoa/TheConnectedMCU_Labs
6e0f3ec9efd101d002e09250b183c3ae857038ea
[ "MIT" ]
null
null
null
bkarachok/lab5_SPI_OLED/user.c
kpi-keoa/TheConnectedMCU_Labs
6e0f3ec9efd101d002e09250b183c3ae857038ea
[ "MIT" ]
43
2017-10-08T13:57:40.000Z
2017-12-31T00:35:24.000Z
bkarachok/lab5_SPI_OLED/user.c
kpi-keoa/TheConnectedMCU_Labs
6e0f3ec9efd101d002e09250b183c3ae857038ea
[ "MIT" ]
20
2017-09-25T22:21:38.000Z
2017-10-31T10:49:28.000Z
/******************************************************************************/ /* Files to Include */ /******************************************************************************/ #ifdef __XC32 #include <xc.h> /* Defines special function registers, CP0 regs */ #endif #include <stdint.h> /* For uint32_t definition */ #include <stdbool.h> /* For true/false definition */ #include "user.h" /* variables/params used by user.c */ #include <sys/attribs.h> /******************************************************************************/ /* User Functions */ /******************************************************************************/ void DelayMs(int t) { volatile long int count = t*33356; while (count--) ; } void InitTimer2(void) { T2CON = 0; // clear timer settings to defaults T2CONbits.TCKPS = 7; // divide clock by 256 with prescaler TMR2 = 0; PR2 = 39062; // 100 MHz / (256 * 10 Hz) IPC2bits.T2IP = 3; // Priority level 3 IPC2bits.T2IS = 0; IFS0bits.T2IF = 0; // Clear interrupt request flag IEC0bits.T2IE = 1; // Enable timer interrupt } void __ISR(_TIMER_2_VECTOR, IPL3SOFT) ISR_Timer_2 (void) { static int LED_state = 1; // Toggle LED2 LD2_PORT_BIT = LED_state; LED_state = !LED_state; // Reset interrupt flag IFS0bits.T2IF = 0; } void InitGPIO(void) { // Setup functionality and port direction // LED output // Disable analog mode if present ANSELG &= ~((1 << 6) | (1 << 15)); ANSELB &= ~(1 << 11); // Set direction to output TRISG &= ~((1 << 6) | (1 << 15)); TRISB &= ~(1 << 11); TRISD &= ~(1 << 4); // Turn off LEDs for initialization LD1_PORT_BIT = 0; LD2_PORT_BIT = 0; LD3_PORT_BIT = 0; LD4_PORT_BIT = 0; // Button inputs // Disable analog mode ANSELD &= ~(1 << 5); ANSELC &= ~(1 << 3); ANSELF &= ~(1 << 1); ANSELE &= ~(1 << 8); ANSELA &= ~(1 << 2); // Set directions to input TRISD |= (1 << 5); TRISC |= (1 << 3); TRISF |= (1 << 1); TRISE |= (1 << 8); TRISA |= (1 << 2); // TRISDCLR = 1<<11; } void InitApp(void) { // Initialize peripherals InitGPIO(); OledHostInit(); OledDspInit(); #if 0 InitTimer2(); // Set Interrupt Controller for multi-vector mode INTCONSET = _INTCON_MVEC_MASK; // Globally enable interrupts __builtin_enable_interrupts(); // Enable peripherals which can generate an interrupt T2CONbits.ON = 1; // Start Timer 2 #endif }
27.818182
80
0.465868
[ "vector" ]
4272d2479543f85db3352e64a55a8c5f62cb7792
2,517
h
C
src/vkabstractcontainer.h
rusphantom/sailfishVK
65de01708562506ac2b0fb55a5ca4971fbf0f5e9
[ "MIT" ]
1
2020-03-09T05:42:24.000Z
2020-03-09T05:42:24.000Z
src/vkabstractcontainer.h
rusphantom/sailfishVK
65de01708562506ac2b0fb55a5ca4971fbf0f5e9
[ "MIT" ]
null
null
null
src/vkabstractcontainer.h
rusphantom/sailfishVK
65de01708562506ac2b0fb55a5ca4971fbf0f5e9
[ "MIT" ]
null
null
null
#ifndef VKABSTRACTCONTAINER_H #define VKABSTRACTCONTAINER_H #include <QObject> #include <QDebug> #include <QQmlEngine> #include <QJsonObject> #include <QJsonArray> #include "ivkcompletable.h" #define SET_ARG_NOCHECK(param, arg) do{ param = arg; }while(0)/*\ do{ \ param = arg; \ if (!m_objectChanging) { \ qDebug()<<"bad bad boy, inform object that you will change it, before actially changing"; \ Q_ASSERT(0); \ } else { \ emit dataChanged(this); \ } \ }while(0)*/ #define SET_ARG(param, arg) do{ if (param != arg) { param = arg; }else{ return; } }while(0)/*\ do{ \ if (param != arg) { \ SET_ARG_NOCHECK(param, arg); \ } \ }while(0)*/ #define UPDATE_ARG_CHECK(obj, func, sfunc, updated) \ do{\ if (func() != obj->func()) { \ sfunc(obj->func()); \ updated = true; \ } \ }while(0) #define UPDATE_ARG_CHECK_SHARED(obj, func, sfunc, updated) \ do{\ if (*(func().data()) != *(obj->func().data())) { \ sfunc(obj->func()); \ updated = true; \ } \ }while(0) class VKContainerUser; class VKStorage; class VKAbstractContainer : public IVKCompletable { Q_OBJECT public: explicit VKAbstractContainer(VKStorage* storage, QObject *parent = 0); virtual void complete(QSharedPointer<VKContainerUser> c); virtual void copyTo(VKAbstractContainer* container); int type() const; void beginObjectChange(); void endObjectChange(); void emitChange(); VKStorage* storage() const; bool isValid() const; void setValid(); void setInvalid(); void setValid(bool b); void printOwnership(); enum ContainerType { eVKContainerAbstract, eVKContainerAttachment, eVKContainerAudio, eVKContainerChatIcon, eVKContainerDialog, eVKContainerDocument, eVKContainerLink, eVKContainerMessage, eVKContainerMessageAction, eVKContainerPhoto, eVKContainerSticker, eVKContainerUser, eVKContainerVideo, eVKContainerWall, eVKContainerWallReply, }; signals: void dataChanged(VKAbstractContainer* container); public slots: protected: int m_type; private: VKStorage* m_storage; bool m_valid; }; #endif // VKABSTRACTCONTAINER_H
25.683673
103
0.582042
[ "object" ]
427a7ef24faee028eba3b2852ad339ae8472aa79
10,771
h
C
include/odata/client/odata_client.h
avs/odatacpp-client
c2af181468d345aef0c952a8a0182a1ff11b4b57
[ "MIT" ]
39
2015-01-22T08:13:28.000Z
2021-02-03T07:29:56.000Z
include/odata/client/odata_client.h
avs/odatacpp-client
c2af181468d345aef0c952a8a0182a1ff11b4b57
[ "MIT" ]
20
2015-04-27T02:35:31.000Z
2021-01-20T16:47:23.000Z
include/odata/client/odata_client.h
avs/odatacpp-client
c2af181468d345aef0c952a8a0182a1ff11b4b57
[ "MIT" ]
30
2015-01-29T21:23:57.000Z
2021-01-11T14:19:47.000Z
//--------------------------------------------------------------------- // <copyright file="odata_client.h" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- #pragma once #include <functional> #include "odata/client/odata_client_options.h" #include "odata/common/utility.h" #include "odata/communication/http_communication.h" #include "odata/communication/http_implement.h" #include "odata/communication/http_utility.h" #include "odata/core/odata_core.h" #include "odata/edm/odata_edm.h" #include "odata/edm/edm_model_reader.h" namespace odata { namespace client { class odata_client { public: /// <summary> /// Constructor /// </summary> /// <param name="baseAddress">The OData service endpoint used to create the client.</param> odata_client(::utility::string_t baseAddress, client_options options = client_options()) : m_options(options), m_service_root_url(std::move(baseAddress)) { m_client_proxy = std::make_shared<::odata::communication::http_client_proxy<::odata::communication::http_client_impl, ::odata::communication::http_client_response>>(m_service_root_url, options.get_credential_setting()); if (m_service_root_url.back() == '/') { m_service_root_url.pop_back(); } } ::web::http::client::http_client_config& get_client_config(){ return m_client_proxy->get_client_config(); } const ::utility::string_t& get_service_root_url() const { return m_service_root_url; } ::utility::string_t get_relative_path(const ::utility::string_t& full_path) { if (::odata::common::is_relative_path(m_service_root_url, full_path)) { return full_path; } return full_path.substr(m_service_root_url.length() + 1, full_path.length() - m_service_root_url.length()); } /// <summary> /// Retrieve the service's metadata (types, and other information). /// </summary> ODATACPP_CLIENT_API pplx::task<std::shared_ptr<::odata::edm::edm_model>> get_model(); /// <summary> /// Get the elements of a given entity set. /// </summary> /// <param name="edm_entity_set">The entity set metadata record.</param> /// <param name="query_exp">The OData query string to use for the request.</param> /// <returns>The result entities with annotation infomation, possibly empty.</returns> ODATACPP_CLIENT_API pplx::task<std::vector<std::shared_ptr<::odata::core::odata_entity_value>>> get_entities(const ::utility::string_t& edm_entity_set); /// <summary> /// Add an entity to a given entity set. /// </summary> /// <param name="edm_entity_set">The entity set metadata record.</param> /// <param name="record">The entity to add.</param> /// <returns>An entity instance representing the new entity after it was inserted.</returns> ODATACPP_CLIENT_API pplx::task<::web::http::status_code> create_entity(const ::utility::string_t& entity_set_name, const std::shared_ptr<::odata::core::odata_entity_value>& entity_object); /// <summary> /// Update an existing entity of a given entity set. /// </summary> /// <param name="edm_entity_set">The entity set metadata record.</param> /// <param name="key">The primary key of the record that should be modified.</param> /// <param name="record">The entity value to write.</param> /// <returns>An entity instance representing the new entity after it was modified.</returns> /// <remarks>This does a surgical replacement of the record, modifying and adding properties found in the provided record.</remarks> ODATACPP_CLIENT_API pplx::task<::web::http::status_code> patch_entity(const ::utility::string_t& entity_set_name, const std::shared_ptr<::odata::core::odata_entity_value>& entity_object); /// <summary> /// Replace existing entity of a given entity set. /// </summary> /// <param name="edm_entity_set">The entity set metadata record.</param> /// <param name="key">The primary key of the record that should be modified.</param> /// <param name="record">The entity value to write.</param> /// <returns>An entity instance representing the new entity after it was modified.</returns> /// <remarks>This does a total replacement of the existing entity with a given entity value.</remarks> ODATACPP_CLIENT_API pplx::task<::web::http::status_code> put_entity(const ::utility::string_t& entity_set_name, const std::shared_ptr<::odata::core::odata_entity_value>& entity_object); /// <summary> /// Remove an entity from a given entity set. /// </summary> /// <param name="edm_entity_set">The entity set metadata record.</param> /// <param name="key">The primary key of the record that should be deleted.</param> ODATACPP_CLIENT_API pplx::task<::web::http::status_code> delete_entity(const ::utility::string_t& entity_set_name, const std::shared_ptr<::odata::core::odata_entity_value>& entity_object); /// <summary> /// Add a reference to a collection-valued navigation property. /// </summary> /// <param name="edm_entity_set">The path of the navigation property.</param> /// <param name="key">The id of referenced entity.</param> ODATACPP_CLIENT_API pplx::task<::web::http::status_code> add_reference(const ::utility::string_t& path, const ::utility::string_t& referenceEntityId); /// <summary> /// Remove reference to a collection-valued or single-valued navigation property. /// </summary> /// <param name="edm_entity_set">The path of the navigation property.</param> /// <param name="key">The id of referenced entity if the navigation property is collection-values, or empty if it is single-valued.</param> ODATACPP_CLIENT_API pplx::task<::web::http::status_code> remove_reference(const ::utility::string_t& path, const ::utility::string_t& referenceEntityId); /// <summary> /// Update reference to a single-valued navigation property. /// </summary> /// <param name="edm_entity_set">The path of the navigation property.</param> /// <param name="key">The id of referenced entity.</param> ODATACPP_CLIENT_API pplx::task<::web::http::status_code> update_reference(const ::utility::string_t& path, const ::utility::string_t& referenceEntityId); /// <summary> /// Get odata value of any odata type data defined in edm library including primitive, complex, entity type from server. /// </summary> /// <param name="path">The request path which can be set with select, filter, expand or even function or action options.</param> ODATACPP_CLIENT_API pplx::task<std::vector<std::shared_ptr<::odata::core::odata_value>>> get_data_from_server(const ::utility::string_t& path); /// <summary> /// The size of result data of a request maybe too large for one http response, so the server may return the data one page after another /// </summary> /// <param name="path">The request path which can be set with select, filter, expand or even function or action options.</param> /// <param name="path">The result data set.</param> /// <returns>The odata_payload class containing next link url, if no more data next link url is empty.</returns> ODATACPP_CLIENT_API pplx::task<std::shared_ptr<::odata::core::odata_payload>> get_paged_data_from_server(const ::utility::string_t& path); /// <summary> /// Send odata value of any odata type data defined in edm library including primitive, complex, entity type to server. /// </summary> /// <param name="path">Path of OData value.</param> /// <param name="send_value">OData value to be sent to the server.</param> /// <param name="send_type">POST, PATCH or PUT options.</param> ODATACPP_CLIENT_API pplx::task<::web::http::status_code> send_data_to_server(const ::utility::string_t& path, const std::shared_ptr<::odata::core::odata_value>& send_value, const ::utility::string_t& send_type = HTTP_POST); /// <summary> /// Send a vector of odata parameters to server. /// </summary> /// <param name="path">Path to send the parameters, could be function/action path.</param> /// <param name="send_parameters">OData parameters to be sent to the server.</param> /// <param name="send_type">POST, PATCH or PUT options.</param> ODATACPP_CLIENT_API pplx::task<::web::http::status_code> send_data_to_server(const ::utility::string_t& path, const std::vector<std::shared_ptr<::odata::core::odata_parameter>>& send_parameters, std::vector<std::shared_ptr<::odata::core::odata_value>>& returnd_value, const ::utility::string_t& send_type = HTTP_POST); /// <summary> /// Send empty data to server. /// </summary> /// <param name="path">Path of OData value.</param> /// <param name="send_type">POST, PATCH or PUT options.</param> ODATACPP_CLIENT_API pplx::task<::web::http::status_code> send_data_to_server(const ::utility::string_t& path, const ::utility::string_t& send_type = HTTP_POST); private: std::shared_ptr<::odata::edm::edm_model> schema_from_response(const ::odata::communication::http_client_response& response); std::shared_ptr<::odata::core::odata_payload> entity_payload_from_response(const ::odata::communication::http_client_response&, const std::shared_ptr<::odata::edm::edm_entity_set>& set); std::shared_ptr<::odata::core::odata_payload> parse_payload_from_response(const ::odata::communication::http_client_response&); pplx::task<std::vector<std::shared_ptr<::odata::core::odata_entity_value>>> get_entities(const std::shared_ptr<::odata::edm::edm_entity_set>& edm_entity_set, const ::utility::string_t& path = U("")); static std::unordered_map<::utility::string_t, std::shared_ptr<::odata::edm::edm_model>> m_model_cache; std::shared_ptr<::odata::communication::http_client_proxy<::odata::communication::http_client_impl, ::odata::communication::http_client_response>> m_client_proxy; client_options m_options; ::utility::string_t m_service_root_url; std::shared_ptr<::odata::edm::edm_model> m_model; }; }}
60.853107
326
0.663077
[ "vector" ]
428018f695ef14e29d2dfb57eb4115545fa965f4
1,433
h
C
src/core/render/Mesh.h
yeshvvvanth/raccoon-engine
fc9b6544429578b223115c0f8d91c4053e189914
[ "MIT" ]
null
null
null
src/core/render/Mesh.h
yeshvvvanth/raccoon-engine
fc9b6544429578b223115c0f8d91c4053e189914
[ "MIT" ]
null
null
null
src/core/render/Mesh.h
yeshvvvanth/raccoon-engine
fc9b6544429578b223115c0f8d91c4053e189914
[ "MIT" ]
1
2019-12-21T09:53:41.000Z
2019-12-21T09:53:41.000Z
#pragma once #include"Material.h" #include"../data_types/rawmesh.h" #include"physics.h" #include<fstream> struct Renderable{ vec2 tile,tileoff; Texture* texture; char type;Box box; virtual void tick(Transform& trans,float delta=0)=0; virtual ~Renderable(); char flags; }; struct Mesh:Renderable{ RawMesh* rawmesh; float smoothness; vec3 glow;float ff;int f; // animation frame number and frame fraction Mesh(RawMesh* rawmesh,Material* material=0); void setAnimation(int num=-1,std::string tname=""); void tick(Transform& trans,float delta=0); unsigned short anum;float animSpeed,transSpeed; btCollisionShape* getCollider(char type=0); }; struct Quad:Renderable{ char facing; Quad(); short f,sf,ef;float aspeed,timer; void tick(Transform& trans,float delta=0); }; struct Terrain:Renderable{ RawMesh* raw; unsigned int sizex,sizey; Shader* shader; Texture *textures[3]; void tick(Transform& trans,float delta=0); void reNormals(); float* terr(unsigned int x,unsigned int y),maxh,minh,scale; short* data;unsigned char*tdata; Terrain(int sx=128,int sy=128,std::ifstream *ifs=0); btHeightfieldTerrainShape* getCollider(); void write(std::ofstream &ofs); void read(std::ifstream *ifs); void Refresh(); ~Terrain(); }; #define TRANSPARENT 1 #define FACE 2 #define DOSHADOW 4 #define DODEPTH 8 #define UNSHADED 16
28.098039
74
0.695045
[ "mesh", "transform" ]
42923da2354a4b5884dc67f3c91e1d078ba9536f
10,529
c
C
smilelib/src/parsing/parser/parseloanword.c
seanofw/smile
3bc8807513cdb54053134fe2c79c5bf077aa026d
[ "Apache-2.0" ]
15
2016-05-27T14:30:28.000Z
2020-12-09T09:14:18.000Z
smilelib/src/parsing/parser/parseloanword.c
seanofw/smile
3bc8807513cdb54053134fe2c79c5bf077aa026d
[ "Apache-2.0" ]
null
null
null
smilelib/src/parsing/parser/parseloanword.c
seanofw/smile
3bc8807513cdb54053134fe2c79c5bf077aa026d
[ "Apache-2.0" ]
4
2016-01-17T03:52:21.000Z
2019-02-06T19:24:33.000Z
//--------------------------------------------------------------------------------------- // Smile Programming Language Interpreter // Copyright 2004-2019 Sean Werkema // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //--------------------------------------------------------------------------------------- #include <smile/types.h> #include <smile/smiletypes/smileobject.h> #include <smile/smiletypes/smileloanword.h> #include <smile/smiletypes/smilelist.h> #include <smile/stringbuilder.h> #include <smile/smiletypes/text/smilesymbol.h> #include <smile/parsing/parser.h> #include <smile/parsing/identkind.h> #include <smile/parsing/internal/parserinternal.h> #include <smile/parsing/internal/parsedecl.h> #include <smile/parsing/internal/parsescope.h> #include <smile/internal/staticstring.h> #include <smile/regex.h> static void Parser_DeclareCaptures(Parser parser, Regex regex, ParseScope scope, LexerPosition position); STATIC_STRING(MissingLoanwordName, "Expected a name after #loanword."); STATIC_STRING(MissingLoanwordColon, "Expected a ':' after the loanword name."); STATIC_STRING(MissingLoanwordRegex, "Expected regex pattern after the loanword name."); STATIC_STRING(MissingLoanwordImpliesSymbol, "Expected a '=>' (implies symbol) to separate the loanword pattern from its substitution."); /// <summary> /// Tokens that are used during common recovery scenarios to determine the /// likely end of the current error: { } [ ] ( ) /// </summary> static Int _loanwordRecover[] = { TOKEN_RIGHTBRACKET, TOKEN_RIGHTBRACE, TOKEN_RIGHTPARENTHESIS, TOKEN_LEFTBRACKET, TOKEN_LEFTBRACE, TOKEN_LEFTPARENTHESIS, }; static Int _loanwordRecoverCount = sizeof(_loanwordRecover) / sizeof(Int); // loanword_expr :: = . anyname COLON LOANWORD_REGEX IMPLIES raw_list_term ParseResult Parser_ParseLoanword(Parser parser, Int modeFlags) { Token token; Symbol name; SmileObject replacement; LexerPosition rulePosition, impliesPosition; Int templateKind; SmileLoanword loanword; Regex regex; TemplateResult templateResult; // First, read the loanword's name. token = Parser_NextToken(parser); rulePosition = Token_GetPosition(token); if (token->kind != TOKEN_ALPHANAME && token->kind != TOKEN_UNKNOWNALPHANAME) { return ERROR_RESULT(ParseMessage_Create(PARSEMESSAGE_ERROR, rulePosition, MissingLoanwordName)); } name = token->data.symbol; // There must be a colon next. token = Parser_NextToken(parser); if (token->kind != TOKEN_COLON) { return ERROR_RESULT(ParseMessage_Create(PARSEMESSAGE_ERROR, Token_GetPosition(token), MissingLoanwordColon)); } // There must be a regex pattern that follows. token = Parser_NextToken(parser); if (token->kind != TOKEN_LOANWORD_REGEX) { return ERROR_RESULT(ParseMessage_Create(PARSEMESSAGE_ERROR, Token_GetPosition(token), MissingLoanwordRegex)); } regex = (Regex)token->data.ptr; // Now, ensure that the special '=>' (implies) symbol exists. token = Parser_NextToken(parser); if (!(token->kind == TOKEN_PUNCTNAME || token->kind == TOKEN_UNKNOWNPUNCTNAME) || token->data.symbol != Smile_KnownSymbols.implies) { return ERROR_RESULT(ParseMessage_Create(PARSEMESSAGE_ERROR, Token_GetPosition(token), MissingLoanwordImpliesSymbol)); } impliesPosition = Token_GetPosition(token); // Create a new scope for the loanword's substitution expression. Parser_BeginScope(parser, PARSESCOPE_SYNTAX); // Make sure the subsitution expression can "see" the regex capture names in scope. Parser_DeclareCaptures(parser, regex, parser->currentScope, rulePosition); // Parse the substitution expression in the syntax rule's scope. templateResult = Parser_ParseRawListTerm(parser, modeFlags); Parser_EndScope(parser, False); if (IS_PARSE_ERROR(templateResult.parseResult)) RETURN_PARSE_ERROR(templateResult.parseResult); replacement = templateResult.parseResult.expr; templateKind = templateResult.templateKind; // Make sure the template is an evaluable expression form, not just a raw term. replacement = Parser_ConvertItemToTemplateIfNeeded(replacement, templateKind, impliesPosition); // Now make sure that the template is evaluable at parse-time. The set of supported // parse-time template-evaluation forms is intentionally limited: // // - n (where n is any nonterminal symbol) // - [] (i.e., null) // - [$quote x] (for any x) // - [List.of x y z ...] // - [List.join x y z ...] // - [List.cons x y] // // All other computation is expressly prohibited and must be implemented using macros. Parser_VerifySyntaxTemplateIsEvaluableAtParseTime(parser, replacement); // Everything passes muster, so create the new loanword object. loanword = SmileLoanword_Create(name, regex, replacement, rulePosition); // Everything is all set up, so return the finished loanword object. return EXPR_RESULT(loanword); } Inline String GetDollarNameString(Int index) { Byte dollarName[3]; if (index < 10) { // Fast path for the common single-digit forms. dollarName[0] = '$'; dollarName[1] = '0' + (Byte)index; return String_Create(dollarName, 2); } else if (index < 100) { // Fast-ish path for the less-common double-digit forms. dollarName[0] = '$'; dollarName[1] = '0' + (Byte)(index % 10); dollarName[2] = '0' + (Byte)(index / 10); return String_Create(dollarName, 3); } else { // Slow path for the general case. return String_Format("$%u", (UInt32)index); } } /// <summary> /// Skim through the given regex, find all its capture names, and declare them as variables /// in the given scope, along with the special names $0 through $n for the regex's captures. /// </summary> /// <param name="regex">The regex to extract names from.</param> /// <param name="scope">The parse scope in which the new names will be declared.</param> /// <param name="position">The lexical position where the regex was found, so that the new /// variables will be considered to have been declared *there*.</param> static void Parser_DeclareCaptures(Parser parser, Regex regex, ParseScope scope, LexerPosition position) { String *names; Int numNames; Int numCaptures; ParseDecl decl; Int i; String dollarNameString; String name; // Query the regex for its capture names and numbers. numNames = Regex_GetCaptureNames(regex, &names); numCaptures = Regex_GetCaptureCount(regex); // Declare $0 through $n. for (i = 0; i < numCaptures; i++) { dollarNameString = GetDollarNameString(i); ParseScope_Declare(scope, SymbolTable_GetSymbol(Smile_SymbolTable, dollarNameString), PARSEDECL_VARIABLE, position, &decl); } // Declare any named captures, which must not start with '$'. for (i = 0; i < numNames; i++) { name = names[i]; if (String_StartsWithC(name, "$")) { Parser_AddError(parser, position, "Named captures in a loanword must not start with the reserved '$' character."); } else { ParseScope_Declare(scope, SymbolTable_GetSymbol(Smile_SymbolTable, name), PARSEDECL_VARIABLE, position, &decl); } } } typedef struct ReplacementInfoStruct { Int32Dict replacements; RegexMatch match; } *ReplacementInfo; static Bool MakeReplacementValue(String key, Int index, void *param) { ReplacementInfo replacementInfo = (ReplacementInfo)param; Symbol symbol = SymbolTable_GetSymbol(Smile_SymbolTable, key); Int32Dict_Add(replacementInfo->replacements, symbol, RegexMatch_GetCapture(replacementInfo->match, index)); return True; } static Int32Dict Parser_CreateLoanwordReplacementValuesFromMatch(RegexMatch match) { Int32Dict replacements; Int i; struct ReplacementInfoStruct replacementInfo; String dollarNameString; Symbol symbol; replacements = Int32Dict_CreateWithSize((Int32)(match->numIndexedCaptures + StringIntDict_Count(&match->namedCaptures))); for (i = 0; i < match->numIndexedCaptures; i++) { dollarNameString = GetDollarNameString(i); symbol = SymbolTable_GetSymbol(Smile_SymbolTable, dollarNameString); Int32Dict_Add(replacements, symbol, RegexMatch_GetCapture(match, i)); } replacementInfo.match = match; replacementInfo.replacements = replacements; StringIntDict_ForEach(&match->namedCaptures, MakeReplacementValue, &replacementInfo); return replacements; } ParseResult Parser_ApplyCustomLoanword(Parser parser, Token token) { SmileLoanword loanword; Symbol symbol; RegexMatch match; Int32Dict replacements; LexerPosition position; position = Token_GetPosition(token); // First, look up the loanword's definition (if there even exists a loanword that matches). symbol = SymbolTable_GetSymbolNoCreate(Smile_SymbolTable, token->text); if (!symbol || !Int32Dict_TryGetValue(parser->currentScope->loanwordTable->definitions, symbol, (void **)&loanword)) { return ERROR_RESULT(ParseMessage_Create(PARSEMESSAGE_ERROR, Token_GetPosition(token), String_Format("Unknown loanword '#%S'.", token->text))); } // We have a valid loanword, and we're going to lex it using its regex. // But first, if there is any following whitespace at all, consume whitespace characters // up to and including the next newline. This will result in simpler loanword rules, at the // possible cost of losing the ability to treat initial whitespace as meaningful content. Lexer_ConsumeWhitespaceOnThisLine(parser->lexer); match = Lexer_ConsumeRegex(parser->lexer, loanword->regex); // If the regex match failed, this loanword was parsed as an error. if (match == NULL) { return ERROR_RESULT(ParseMessage_Create(PARSEMESSAGE_ERROR, Token_GetPosition(token), String_Format("After loanword '#%S', the source code does not match the loanword's regex pattern.", loanword->name))); } // The regex match succeeded, and we have its data stored in the 'match' dictionary and array. // Now we have to transform those into an appropriate replacement-symbol lookup table. replacements = Parser_CreateLoanwordReplacementValuesFromMatch(match); // Now use the captures against the template to generate the actual result. return EXPR_RESULT(Parser_RecursivelyApplyTemplate(parser, loanword->replacement, replacements, position)); }
38.996296
136
0.748314
[ "object", "transform" ]
42a5ba7242734ca1dbef770883ce1b584b86298c
1,005
h
C
include/game/button.h
inessousacaldas/exercise_opengl
e9afb167efdc29214ba2b791862e4ead9fb4bba6
[ "MIT" ]
null
null
null
include/game/button.h
inessousacaldas/exercise_opengl
e9afb167efdc29214ba2b791862e4ead9fb4bba6
[ "MIT" ]
null
null
null
include/game/button.h
inessousacaldas/exercise_opengl
e9afb167efdc29214ba2b791862e4ead9fb4bba6
[ "MIT" ]
null
null
null
#ifndef BUTTON_H #define BUTTON_H // std includes #include <memory> #include <map> #include <string> #include <functional> // external libs includes #include <glm/vec2.hpp> #include <glm/vec3.hpp> // project includes #include "game/game_object.h" #include "game/game_level.h" #include "game/button_state.h" #include "graphics/texture.h" #include "input/input_mouse.h" class Button : public GameObject { public: Button(const glm::vec2& position, const glm::vec2& size, const glm::vec3& color, Texture* sprite, Texture* spriteFocus, Texture* spritePressed, std::function<void()> const &callback); ~Button(); void destroy(); bool hoverButton(glm::vec2 position, InputMouse action); void render (const SpriteRenderer& renderer) override; private: std::map<ButtonState, std::unique_ptr<Texture>> textures_; ButtonState state_; std::function<void()> callback_; void OnButtonReleased(); // call the function callback }; #endif
22.333333
112
0.694527
[ "render" ]
42a92fa08c63f2e9c9158e24a88aef06925fa5f9
23,685
c
C
DIR819_v1.06/src/opensource/updatedd/updatedd-2.3/src/plugins/gnudip.c
Sirherobrine23/Dir819gpl_code
8af92d65416198755974e3247b7bbe7f1151d525
[ "BSD-2-Clause" ]
1
2022-03-19T06:38:01.000Z
2022-03-19T06:38:01.000Z
DIR819_v1.06/src/opensource/updatedd/updatedd-2.3/src/plugins/gnudip.c
Sirherobrine23/Dir819gpl_code
8af92d65416198755974e3247b7bbe7f1151d525
[ "BSD-2-Clause" ]
null
null
null
DIR819_v1.06/src/opensource/updatedd/updatedd-2.3/src/plugins/gnudip.c
Sirherobrine23/Dir819gpl_code
8af92d65416198755974e3247b7bbe7f1151d525
[ "BSD-2-Clause" ]
1
2022-03-19T06:38:03.000Z
2022-03-19T06:38:03.000Z
/* -- updatedd: dyndns.c -- * * Copyright (C) 2002, 2003, 2004 Philipp Benner * * This file is part of UpdateDD - http://updatedd.philipp-benner.de. * * UpdateDD 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 * any later version. * * UpdateDD 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 UpdateDD; 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 <string.h> #include <stdarg.h> #include <ctype.h> #include <unistd.h> #include <getopt.h> #include <get_connection.h> #include <libexception_handle.h> #include <ret_codes.h> #include <version.h> #include "../updatedd.h" //#include "../../md5/md5.h" #include "gnudip.h" //////////////////////////////////// #ifndef PROTOTYPES #define PROTOTYPES 1 #endif /* POINTER defines a generic pointer type */ typedef unsigned char *POINTER; /* UINT2 defines a two byte word */ typedef unsigned short int UINT2; /* UINT4 defines a four byte word */ typedef unsigned long int UINT4; /* PROTO_LIST is defined depending on how PROTOTYPES is defined above. If using PROTOTYPES, then PROTO_LIST returns the list, otherwise it returns an empty list. */ #if PROTOTYPES #define PROTO_LIST(list) list #else #define PROTO_LIST(list) () #endif /* MD5 context. */ typedef struct { UINT4 state[4]; /* state (ABCD) */ UINT4 count[2]; /* number of bits, modulo 2^64 (lsb first) */ unsigned char buffer[64]; /* input buffer */ } MD5_CTX; void MD5Init PROTO_LIST ((MD5_CTX *)); void MD5Update PROTO_LIST ((MD5_CTX *, unsigned char *, unsigned int)); void MD5Final PROTO_LIST ((unsigned char [16], MD5_CTX *)); /* Constants for MD5Transform routine. */ #define S11 7 #define S12 12 #define S13 17 #define S14 22 #define S21 5 #define S22 9 #define S23 14 #define S24 20 #define S31 4 #define S32 11 #define S33 16 #define S34 23 #define S41 6 #define S42 10 #define S43 15 #define S44 21 static void MD5Transform PROTO_LIST ((UINT4 [4], unsigned char [64])); static void Encode PROTO_LIST ((unsigned char *, UINT4 *, unsigned int)); static void Decode PROTO_LIST ((UINT4 *, unsigned char *, unsigned int)); static void MD5_memcpy PROTO_LIST ((POINTER, POINTER, unsigned int)); static void MD5_memset PROTO_LIST ((POINTER, int, unsigned int)); static unsigned char PADDING[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* F, G, H and I are basic MD5 functions. */ #define F(x, y, z) (((x) & (y)) | ((~x) & (z))) #define G(x, y, z) (((x) & (z)) | ((y) & (~z))) #define H(x, y, z) ((x) ^ (y) ^ (z)) #define I(x, y, z) ((y) ^ ((x) | (~z))) /* ROTATE_LEFT rotates x left n bits. */ #define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n)))) /* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. Rotation is separate from addition to prevent recomputation. */ #define FF(a, b, c, d, x, s, ac) { \ (a) += F ((b), (c), (d)) + (x) + (UINT4)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define GG(a, b, c, d, x, s, ac) { \ (a) += G ((b), (c), (d)) + (x) + (UINT4)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define HH(a, b, c, d, x, s, ac) { \ (a) += H ((b), (c), (d)) + (x) + (UINT4)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define II(a, b, c, d, x, s, ac) { \ (a) += I ((b), (c), (d)) + (x) + (UINT4)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } /* MD5 initialization. Begins an MD5 operation, writing a new context. */ void MD5Init (context) MD5_CTX *context; /* context */ { context->count[0] = context->count[1] = 0; /* Load magic initialization constants. */ context->state[0] = 0x67452301; context->state[1] = 0xefcdab89; context->state[2] = 0x98badcfe; context->state[3] = 0x10325476; } /* MD5 block update operation. Continues an MD5 message-digest operation, processing another message block, and updating the context. */ void MD5Update (context, input, inputLen) MD5_CTX *context; /* context */ unsigned char *input; /* input block */ unsigned int inputLen; /* length of input block */ { unsigned int i, index, partLen; /* Compute number of bytes mod 64 */ index = (unsigned int)((context->count[0] >> 3) & 0x3F); /* Update number of bits */ if ((context->count[0] += ((UINT4)inputLen << 3)) < ((UINT4)inputLen << 3)) context->count[1]++; context->count[1] += ((UINT4)inputLen >> 29); partLen = 64 - index; /* Transform as many times as possible. */ if (inputLen >= partLen) { MD5_memcpy ((POINTER)&context->buffer[index], (POINTER)input, partLen); MD5Transform (context->state, context->buffer); for (i = partLen; i + 63 < inputLen; i += 64) MD5Transform (context->state, &input[i]); index = 0; } else i = 0; /* Buffer remaining input */ MD5_memcpy ((POINTER)&context->buffer[index], (POINTER)&input[i], inputLen-i); } /* MD5 finalization. Ends an MD5 message-digest operation, writing the the message digest and zeroizing the context. */ void MD5Final (digest, context) unsigned char digest[16]; /* message digest */ MD5_CTX *context; /* context */ { unsigned char bits[8]; unsigned int index, padLen; /* Save number of bits */ Encode (bits, context->count, 8); /* Pad out to 56 mod 64. */ index = (unsigned int)((context->count[0] >> 3) & 0x3f); padLen = (index < 56) ? (56 - index) : (120 - index); MD5Update (context, PADDING, padLen); /* Append length (before padding) */ MD5Update (context, bits, 8); /* Store state in digest */ Encode (digest, context->state, 16); /* Zeroize sensitive information. */ MD5_memset ((POINTER)context, 0, sizeof (*context)); } /* MD5 basic transformation. Transforms state based on block. */ static void MD5Transform (state, block) UINT4 state[4]; unsigned char block[64]; { UINT4 a = state[0], b = state[1], c = state[2], d = state[3], x[16]; Decode (x, block, 64); /* Round 1 */ FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */ FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */ FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */ FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */ FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */ FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */ FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */ FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */ FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */ FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */ FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ /* Round 2 */ GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */ GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ /* Round 3 */ HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */ /* Round 4 */ II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */ II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */ II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */ II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */ II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */ state[0] += a; state[1] += b; state[2] += c; state[3] += d; /* Zeroize sensitive information. */ MD5_memset ((POINTER)x, 0, sizeof (x)); } /* Encodes input (UINT4) into output (unsigned char). Assumes len is a multiple of 4. */ static void Encode (output, input, len) unsigned char *output; UINT4 *input; unsigned int len; { unsigned int i, j; for (i = 0, j = 0; j < len; i++, j += 4) { output[j] = (unsigned char)(input[i] & 0xff); output[j+1] = (unsigned char)((input[i] >> 8) & 0xff); output[j+2] = (unsigned char)((input[i] >> 16) & 0xff); output[j+3] = (unsigned char)((input[i] >> 24) & 0xff); } } /* Decodes input (unsigned char) into output (UINT4). Assumes len is a multiple of 4. */ static void Decode (output, input, len) UINT4 *output; unsigned char *input; unsigned int len; { unsigned int i, j; for (i = 0, j = 0; j < len; i++, j += 4) output[i] = ((UINT4)input[j]) | (((UINT4)input[j+1]) << 8) | (((UINT4)input[j+2]) << 16) | (((UINT4)input[j+3]) << 24); } /* Note: Replace "for loop" with standard memcpy if possible. */ static void MD5_memcpy (output, input, len) POINTER output; POINTER input; unsigned int len; { unsigned int i; for (i = 0; i < len; i++) output[i] = input[i]; } /* Note: Replace "for loop" with standard memset if possible. */ static void MD5_memset (output, value, len) POINTER output; int value; unsigned int len; { unsigned int i; for (i = 0; i < len; i++) ((char *)output)[i] = (char)value; } /////////////////////////////////// #define MSG_SIZE 256 #define SALT_SIZE 11 #define PASS_SIZE 33 #define MAX_LOGIN 512 #define PATH_SIZE 128 char table[] = "0123456789abcdef"; char cgipath[PATH_SIZE] = "/gnudip/cgi-bin/gdipupdt.cgi"; char login[MAX_LOGIN]; char user[20]; char pass[20]; #define TRANSFORM(digest, buf) { \ int i; \ for(i = 0; i<16; ++i) { \ buf[i*2] = table[(digest[i]&0xF0)>>4]; \ buf[i*2+1] = table[digest[i]&0x0F]; \ } \ } void hash_password(char* salt, char* pass, char *hashedpwd) { MD5_CTX content; unsigned char digest[16]; char tempbuf[43]; bzero(digest, 16); bzero(tempbuf, 43); MD5Init(&content); MD5Update(&content, pass, strlen(pass)); MD5Final(digest, &content); TRANSFORM(digest, tempbuf); tempbuf[32]= '.'; strncat(tempbuf, salt,10); MD5Init(&content); MD5Update(&content, tempbuf, 43); MD5Final(digest, &content); TRANSFORM(digest, hashedpwd); return; } static void print_usage(char *pname, FILE *fp) { (void)fprintf(fp, "\nUsage: %s [...] %s -- [OPTION]... [USERNAME:PASSWORD] HOSTNAME\n\n", pname, COLORED("dyndns")); (void)fprintf(fp, "For security reasons use the environment variable LOGIN instead of\n" "passing the login information directly.\n\n" "Options:\n" " -4 --ipv4 <address> ip address version 4\n" " -d --domain <domain> update domain\n" " -t --http use http method to communicate.\n" " -b --with-backmx enable backmx\n" " -m --mx <host> hostname of your mail exchange\n" " -o --offline set host to offline mode\n" " -s --system <system> specify the system\n" " (dyndns [default], statdns, custom)\n" " -w --wildcard <on|off> switch wildcard on or off\n" " --help print help and exit\n" " --version display version information and exit\n\n" "Report bugs to <"EMAIL">.\n\n"); return; } static void print_version(FILE *fp) { (void)fprintf(fp, "\n" PNAME " plugin for dyndns.org version " VERSION ",\n" "Copyright (C) 2004 Philipp Benner.\n" HOMEPAGE "\n\n" "This is free software, and you are welcome to redistribute it\n" "under certain conditions; see the source for copying conditions.\n" "There is NO warranty; not even for MERCHANTABILITY or FITNESS\n" "FOR A PARTICULAR PURPOSE.\n\n"); return; } static void ret_msg(int mode, const char *fmt, ...) { va_list az; va_start(az, fmt); (void)vs_warn(ret_msg_buf, BUFSIZE, mode, fmt, az); va_end(az); return; } int dyndns(int argc, char *argv[]) { int port; struct arguments args; int s, ret = RET_WRONG_USAGE; char* ptr = NULL; {//edited by peng FILE* pf; int i=0; char* pargv=NULL; pf = fopen("/var/msg.log", "a+"); if(pf) { for(;i<argc;++i) { pargv = argv[i]; fwrite(pargv, sizeof(char), strlen(pargv), pf); fwrite(" ", sizeof(char), 1, pf); } fwrite("\n", sizeof(char), 1, pf); fclose(pf); } }//end of peng printf("dyndns plugin started ...\n"); #ifdef NSP memset((void *)&args, 0xFF, sizeof(struct arguments)); #else (void)memset(&args, 0, sizeof(struct arguments)); #endif if(get_flags(&args, argc, argv) != RET_OK) { return RET_WRONG_USAGE; } port = strcmp(args.http, yn.yes)==0?HTTP_PORT:TCP_PORT; s = get_connection(args.hostname, args.iface, port, &ptr); if(s == -1) { /*ret_msg(HERR, "%s: %s", ptr, DYNDNSHOST);*/ printf("%s: %s\n", ptr, args.hostname); /*ret = RET_WARNING;*/ exit(EXIT_FAILURE); } else { /*ret = update_dyndns(s, &args); if(ret == RET_OK) { ret = check_server_msg(s, args.hostname); }*/ if(strcmp(args.http, yn.yes) == 0) { ret = http_dyndns(s, &args); } else { //Code for tcp method ret = tcp_dyndns(s, &args); (void)close(s); } //(void)close(s); } return ret; } static void stolower(char *str, char *buf, size_t size) { int n; for(n = 0; n < size && str[n] != '\0'; n++) { buf[n] = tolower(str[n]); } buf[n] = '\0'; return; } static int get_flags(struct arguments *args, int argc, char *argv[]) { int c, n; char buf[BUFSIZE]; args->backmx = yn.no; args->wildcard = "NOCHG"; args->offline = yn.no; args->http = yn.no; args->system = dd_system[0]; args->cgipath = NULL; bzero(login,MAX_LOGIN); if(argc == 1) { print_usage(argv[ARGV_PNAME], stdout); printf("Try `updatedd --help' for more information\n"); exit(EXIT_FAILURE); } for(;;) { int option_index = 0; static struct option long_options[] = { { "ipv4", 1, 0, '4' }, { "help", 0, 0, 'h' }, { "mx", 1, 0, 'm' }, { "reqc", 1, 0, 'r' }, { "system", 1, 0, 's' }, { "wildcard", 1, 0, 'w' }, { "with-backmx", 0, 0, 'b' }, { "version", 0, 0, 'v' }, { "interface", 1, 0, 'i' }, { "user", 1, 0, 'u' }, { "pass", 1, 0, 'p' }, { "domain", 1, 0, 'd' }, { "method", 1, 0, 't' }, { "cgipath", 1, 0, 'c' }, { NULL, 0, 0, 0 } }; c = getopt_long(argc, argv, "4:bm:r:s:w:i:u:p:c:t:d:", long_options, &option_index); if(c == -1) break; switch(c) { case 'd': if(optarg == NULL) { printf("No argument -d <domain> or --domain <domain>.\n"); exit(1); } args->domain = optarg; break; case '4': args->ipv4 = optarg; break; case 'b': args->backmx = yn.yes; break; case 'h': print_usage(argv[ARGV_PNAME], stdout); exit(EXIT_SUCCESS); case 'm': args->mx = optarg; break; case 'r': if(!strcmp(optarg, "offline")) args->offline = yn.yes; else if(!strcmp(optarg, "online")) args->offline = yn.no; else { printf("Invalid value for argument -r:%s\n", optarg); return 1; } break; case 't': if(!strcmp(optarg, "tcp")) args->http = yn.no; else if(!strcmp(optarg, "http")) args->http = yn.yes; else { printf("Invalid value for argument -t:%s\n", optarg); return 1; } break; case 'c': if(strcmp(args->http, yn.yes) ==0) args->cgipath = optarg; else args->cgipath = NULL; break; case 's': stolower(optarg, buf, BUFSIZE); for(n = 0;; n++) { if(dd_system[n] == NULL) { /*ret_msg(NONE,"invalid argument for `-s': %s",optarg);*/ printf("invalid argument for `-s': %s\n",optarg); return 1; } if(strcmp(buf, dd_system[n]) == 0) { args->system = dd_system[n]; break; } } break; case 'v': print_version(stdout); exit(EXIT_SUCCESS); case 'w': stolower(optarg, buf, BUFSIZE); if(strcmp(buf, "on") == 0) { args->wildcard = "ON"; } else if(strcmp(buf, "off") == 0) { args->wildcard = "OFF"; } else { /*ret_msg(NONE, "invalid argument for `-w': %s", optarg);*/ printf("invalid argument for `-w': %s\n", optarg); return 1; } break; case 'i': args->iface = optarg; break; case 'u': bzero(user,20); strcpy(user,optarg); break; case 'p': bzero(pass,20); strcpy(pass,optarg); break; } } if((strcmp(user,"") == 0)||(strcmp(pass,"") == 0)) { strcpy(login, getenv("LOGIN")); if(strcmp(login,"") == 0) { /*ret_msg(NONE, "environment variable LOGIN is empty");*/ printf("environment variable LOGIN is empty\n"); return RET_WRONG_USAGE; } strtok(login,":"); args->uid = login; args->pwd = (char*)(login+strlen(login)+1); } else { args->uid = user; args->pwd = pass; } if(args->cgipath==NULL) { args->cgipath = cgipath; } args->hostname = argv[ARGV_HOSTNAME]; return RET_OK; } static int tcp_dyndns(int s, struct arguments* args) { int reqc; char salt[SALT_SIZE]; char msg[MSG_SIZE]; char hashedpwd[PASS_SIZE]; reqc = 2; //INITIALIZATION bzero(salt, SALT_SIZE); bzero(msg, MSG_SIZE); bzero(hashedpwd, PASS_SIZE); if(strcmp(args->offline, yn.yes)==0) { reqc = 1; } if(recv(s, salt, SALT_SIZE-1, 0) == -1) { strncpy(ret_msg_buf, "Cannot Get Salt String From Server, Failed to recv.\n", BUFSIZE); return RET_ERROR; } hash_password(salt, args->pwd, hashedpwd); sprintf(msg, "%s:%s:%s:%d", args->uid, hashedpwd, args->domain, reqc); if(send(s, msg, strlen(msg), 0) == -1) { strncpy(ret_msg_buf, "Cannot Send Command String to Server, Failed to send.\n", BUFSIZE); return RET_ERROR; } bzero(msg, MSG_SIZE); if(recv(s, msg, MSG_SIZE, 0) == -1) { strncpy(ret_msg_buf, "Cannot Recv ACK MSG from Server, Failed to Recv.\n", BUFSIZE); return RET_ERROR; } else { printf("%s\n", msg); } return RET_OK; } char* strfind(const char* data, const char* target, char*buf, size_t s) { char* p = strstr(data, target); if(!p) return NULL; return strncpy(buf, p+strlen(target), s); } #define HTTPMSG_SIZE 4096 #define REQMSG_SIZE 512 static int http_dyndns(int s, struct arguments* args) { int reqc = 2; int nRet = 0; char hashpwd[PASS_SIZE]; char msg[HTTPMSG_SIZE]; char salt[SALT_SIZE]; char time[SALT_SIZE]; char sign[PASS_SIZE]; char* ptr = NULL; int socketSendUpdate = -1; if(strcmp(args->offline, yn.yes) ==0) { reqc =1; } bzero(msg, sizeof(msg)); sprintf(msg, "GET %s HTTP/1.0\r\n" // "User-Agent: GnuDIP/2.3.5\r\n" "Pragma: no-cache\r\n" // "Host: 172.16.39.146:80\r\n" "\r\n",args->cgipath); if(send(s, msg, strlen(msg), 0) == -1) { printf("Cannot send request msg to DDNS server by HTTP.\n"); return RET_ERROR; } bzero(msg, sizeof(msg)); if(recv(s, msg, 1024, 0) ==-1) { printf("Cannot recv msg from DDNS server.\n"); return RET_ERROR; } bzero(salt, SALT_SIZE); bzero(time, SALT_SIZE); bzero(sign, PASS_SIZE); strfind(msg, "meta name=\"salt\" content=\"", salt, 10); strfind(msg, "meta name=\"time\" content=\"", time, 10); strfind(msg, "meta name=\"sign\" content=\"", sign, 32); bzero(hashpwd,PASS_SIZE); hash_password(salt, args->pwd, hashpwd); (void)close(s); bzero(msg, sizeof(msg)); sprintf(msg, "GET %s?salt=%s&time=%s&sign=%s&user=%s&pass=%s&domn=%s&reqc=%d&192.168.1.1 HTTP/1.0\n\n", args->cgipath,salt,time,sign,args->uid,hashpwd,args->domain,reqc); //########################## socketSendUpdate = get_connection("dyn.you.net", args->iface, HTTP_PORT, &ptr); if(socketSendUpdate == -1) { printf("%s: %s\n", ptr, args->hostname); exit(EXIT_FAILURE); } //########################## if(send(socketSendUpdate, msg, strlen(msg), 0) == -1) { strncpy(ret_msg_buf, "Cannot send request msg to DDNS server.\n", BUFSIZE); (void)close(socketSendUpdate); return RET_ERROR; } //get message from server bzero(msg, sizeof(msg)); nRet = recv(socketSendUpdate, msg, HTTPMSG_SIZE, 0) ; //close socket (void)close(socketSendUpdate); //conclude reset if(nRet == -1) { strncpy(ret_msg_buf, "Cannot Recv msg from DDNS server.\n", BUFSIZE); return RET_ERROR; } else { char szRet[16] = {0}; strfind(msg, "meta name=\"retc\" content=\"", szRet, 16); if (szRet[0] == '0') { //update OK printf("Update good and successful, IP updated.good\n"); return RET_OK; } else if (szRet[0] == '1') { //update fail bad auth printf("Wrong user name or password.error\n"); return RET_ERROR; } else { //update fail return RET_ERROR; } } return RET_OK; }
26.463687
92
0.554655
[ "transform" ]
09517a3084caeaefeb0f0596623c29dc25e3ed0a
9,969
h
C
include/stone/Driver/Command.h
StoneLang/Stone
baf74e460b2c7e03a17d4ec1682b0d5beb3ad6a1
[ "MIT" ]
null
null
null
include/stone/Driver/Command.h
StoneLang/Stone
baf74e460b2c7e03a17d4ec1682b0d5beb3ad6a1
[ "MIT" ]
null
null
null
include/stone/Driver/Command.h
StoneLang/Stone
baf74e460b2c7e03a17d4ec1682b0d5beb3ad6a1
[ "MIT" ]
null
null
null
#ifndef STONE_DRIVER_COMMAND_H #define STONE_DRIVER_COMMAND_H #include "stone/Basic/File.h" #include "stone/Basic/LLVM.h" #include "stone/Basic/OutputFileMap.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/StringSaver.h" namespace stone { struct CommandInputPair final { /// A filename provided from the user, either on the command line or in an /// input file map. Feeds into a Job graph, from InputActions, and is /// _associated_ with a PrimaryInput for a given Job, but may be upstream of /// the Job (and its PrimaryInput) and thus not necessarily passed as a /// filename to the job. Used as a key into the user-provided OutputFileMap /// (of BaseInputs and BaseOutputs), and used to derive downstream names -- /// both temporaries and auxiliaries -- but _not_ used as a key into the /// DerivedOutputFileMap. llvm::StringRef baseInput; /// A filename that _will be passed_ to the command as a designated primary /// input. Typically either equal to BaseInput or a temporary with a name /// derived from the BaseInput it is related to. Also used as a key into /// the DerivedOutputFileMap. llvm::StringRef primaryInput; /// Construct a CmdInputPair from a Base Input and, optionally, a Primary; /// if the Primary is empty, use the Base value for it. explicit CommandInputPair(llvm::StringRef baseInput, llvm::StringRef primaryInput) : baseInput(baseInput), primaryInput(primaryInput.empty() ? baseInput : primaryInput) {} }; class CommandOutput final { /// A CmdOutput designates one type of output as primary, though there /// may be multiple outputs of that type. file::Type primaryOutputType; /// A CmdOutput also restricts its attention regarding additional-outputs /// to a subset of the PrimaryOutputs associated with its PrimaryInputs; /// sometimes multiple commands operate on the same PrimaryInput, in different /// phases (eg. autolink-extract and link both operate on the same .o file), /// so Jobs cannot _just_ rely on the presence of a primary output in the /// DerivedOutputFileMap. llvm::SmallSet<file::Type, 4> additionalOutputTypes; /// The list of inputs for this \c CmdOutput. Each input in the list has /// two names (often but not always the same), of which the second (\c /// CmdInputPair::Primary) acts as a key into \c DerivedOutputMap. Each /// input thus designates an associated _set_ of outputs, one of which (the /// one of type \c PrimaryOutputType) is considered the "primary output" for /// the input. llvm::SmallVector<CommandInputPair, 1> inputs; /// All CmdOutputs in a Compilation share the same \c /// DerivedOutputMap. This is computed both from any user-provided input file /// map, and any inference steps. OutputFileMap &derivedOutputMap; // If there is an entry in the DerivedOutputMap for a given (\p // PrimaryInputFile, \p Type) pair, return a nonempty StringRef, otherwise // return an empty StringRef. llvm::StringRef GetOutputForInputAndType(llvm::StringRef primaryInputFile, file::Type fileType) const; /// Add an entry to the \c DerivedOutputMap if it doesn't exist. If an entry /// already exists for \p PrimaryInputFile of type \p type, then either /// overwrite the entry (if \p overwrite is \c true) or assert that it has /// the same value as \p OutputFile. void EnsureEntry(llvm::StringRef primaryInputFile, file::Type fileType, llvm::StringRef outputFile, bool overwrite); public: CommandOutput(file::Type primaryOutputType, OutputFileMap &derived); /// For testing dependency graphs that use Jobs CommandOutput(llvm::StringRef fakeBaseName, OutputFileMap &); /// Return the primary output type for this CommandOutput. file::Type GetPrimaryOutputType() const; /// Associate a new \p PrimaryOutputFile (of type \c getPrimaryOutputType()) /// with the provided \p Input pair of Base and Primary inputs. void AddPrimaryOutput(CommandInputPair input, llvm::StringRef primaryOutputFile); /// Return true iff the set of additional output types in \c this is /// identical to the set of additional output types in \p other. bool HasSameAdditionalOutputTypes(CommandOutput const &other) const; /// Copy all the input pairs from \p other to \c this. Assumes (and asserts) /// that \p other shares output file map and PrimaryOutputType with \c this /// already, as well as AdditionalOutputTypes if \c this has any. void AddOutputs(CommandOutput const &other); /// Assuming (and asserting) that there is only one input pair, return the /// primary output file associated with it. Note that the returned StringRef /// may be invalidated by subsequent mutations to the \c CmdOutput. llvm::StringRef GetPrimaryOutputFilename() const; /// Return a all of the outputs of type \c getPrimaryOutputType() associated /// with a primary input. The return value will contain one \c StringRef per /// primary input, _even if_ the primary output type is TY_Nothing, and the /// primary output filenames are therefore all empty strings. /// /// FIXME: This is not really ideal behaviour -- it would be better to return /// only nonempty strings in all cases, and have the callers differentiate /// contexts with absent primary outputs another way -- but this is currently /// assumed at several call sites. llvm::SmallVector<llvm::StringRef, 16> GetPrimaryOutputFilenames() const; /// Assuming (and asserting) that there are one or more input pairs, associate /// an additional output named \p OutputFilename of type \p type with the /// first primary input. If the provided \p type is the primary output type, /// overwrite the existing entry assocaited with the first primary input. void SetAdditionalOutputForType(file::Type fileType, llvm::StringRef outputFilename); /// Assuming (and asserting) that there are one or more input pairs, return /// the _additional_ (not primary) output of type \p type associated with the /// first primary input. llvm::StringRef GetAdditionalOutputForType(file::Type fileType) const; /// Assuming (and asserting) that there are one or more input pairs, return /// true if there exists an _additional_ (not primary) output of type \p type /// associated with the first primary input. bool HasAdditionalOutputForType(file::Type fileType) const; /// Return a vector of additional (not primary) outputs of type \p type /// associated with the primary inputs. /// /// In contrast to \c getPrimaryOutputFilenames, this method does _not_ /// return any empty strings or ensure the return vector is matched in /// size with the set of primary inputs; however it _does_ assert that the /// return vector's length is _either_ zero, one, or equal to the size of /// the set of inputs, as these are the only valid arity relationships /// between primary and additional outputs. llvm::SmallVector<llvm::StringRef, 16> GetAdditionalOutputsForType(file::Type fileType) const; /// Assuming (and asserting) that there is only one input pair, return any /// output -- primary or additional -- of type \p type associated with that /// the sole primary input. llvm::StringRef GetAnyOutputForType(file::Type fileType) const; /// Return the whole derived output map. const OutputFileMap &GetDerivedOutputMap() const; /// Return the BaseInput numbered by \p Index. llvm::StringRef GetBaseInput(size_t Index) const; /// Write a file map naming the outputs for each primary input. void WriteOutputFileMap(llvm::raw_ostream &out) const; void Print(raw_ostream &stream) const; /// For use in assertions: check the CmdOutput's state is consistent with /// its invariants. void CheckInvariants() const; }; class Tool; class Context; class Command { private: /// The tool that this command will use const Tool &tool; /// The outputs this command is expected to produce std::unique_ptr<CommandOutput> cmdOutput; public: const char *execPath; llvm::SmallVector<llvm::StringRef, 16> args; llvm::Optional<llvm::ArrayRef<llvm::StringRef>> env = llvm::None; llvm::ArrayRef<llvm::Optional<llvm::StringRef>> redirects; unsigned waitSecs = 0; unsigned memLimit = 0; std::string *errMsg; bool *failed; public: Command(const Tool &tool) : tool(tool) {} public: const Tool &GetTool() const { return tool; } CommandOutput &GetOutput() { return *cmdOutput.get(); } void TakeCommandOutput(std::unique_ptr<CommandOutput> commandOutput) { cmdOutput = std::move(commandOutput); } public: static int ExecuteSync(const Command &c, Context *ctx = nullptr); static int ExecuteAsync(const Command &c, Context *ctx = nullptr); }; class CommandInvocation final { private: /// The tool that this command will use const Tool &tool; /// The outputs this command is expected to produce std::unique_ptr<CommandOutput> cmdOutput; public: llvm::SmallVector<llvm::StringRef, 16> args; llvm::Optional<llvm::ArrayRef<llvm::StringRef>> env = llvm::None; llvm::ArrayRef<llvm::Optional<llvm::StringRef>> redirects; unsigned waitSecs = 0; unsigned memLimit = 0; std::string *errMsg; bool *failed; public: CommandInvocation() = delete; CommandInvocation(const Tool &tool) : CommandInvocation(tool, nullptr) {} CommandInvocation(const Tool &tool, std::unique_ptr<CommandOutput> cmdOutput) : tool(tool), cmdOutput(std::move(cmdOutput)) {} public: const Tool &GetTool() const { return tool; } CommandOutput &GetOutput() const { return *cmdOutput.get(); } }; namespace job { int RunSync(const Command &command, Context *ctx = nullptr); int RunAsync(const Command &command, Context *ctx = nullptr); } // namespace job } // namespace stone #endif
41.886555
80
0.726151
[ "vector" ]
095586ab91582261e1f5e51e18aa653329a6a009
13,587
h
C
editor/spatial_editor_gizmos.h
touilleMan/godo
a75623f436c215e107ede321afa08a1897552deb
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
2
2021-11-08T02:44:36.000Z
2021-11-08T09:41:07.000Z
editor/spatial_editor_gizmos.h
nical/godot
a75623f436c215e107ede321afa08a1897552deb
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
2
2015-12-08T14:13:40.000Z
2016-05-27T20:16:07.000Z
editor/spatial_editor_gizmos.h
nical/godot
a75623f436c215e107ede321afa08a1897552deb
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
/*************************************************************************/ /* spatial_editor_gizmos.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #ifndef SPATIAL_EDITOR_GIZMOS_H #define SPATIAL_EDITOR_GIZMOS_H #include "editor/plugins/spatial_editor_plugin.h" #include "scene/3d/body_shape.h" #include "scene/3d/camera.h" #include "scene/3d/collision_polygon.h" #include "scene/3d/gi_probe.h" #include "scene/3d/light.h" #include "scene/3d/listener.h" #include "scene/3d/mesh_instance.h" #include "scene/3d/navigation_mesh.h" #include "scene/3d/particles.h" #include "scene/3d/physics_joint.h" #include "scene/3d/portal.h" #include "scene/3d/position_3d.h" #include "scene/3d/ray_cast.h" #include "scene/3d/reflection_probe.h" #include "scene/3d/room_instance.h" #include "scene/3d/test_cube.h" #include "scene/3d/vehicle_body.h" #include "scene/3d/visibility_notifier.h" class Camera; class EditorSpatialGizmo : public SpatialEditorGizmo { GDCLASS(EditorSpatialGizmo, SpatialGizmo); struct Instance { RID instance; Ref<Mesh> mesh; RID skeleton; bool billboard; bool unscaled; bool can_intersect; bool extra_margin; Instance() { billboard = false; unscaled = false; can_intersect = false; extra_margin = false; } void create_instance(Spatial *p_base); }; Vector<Vector3> collision_segments; Ref<TriangleMesh> collision_mesh; struct Handle { Vector3 pos; bool billboard; }; Vector<Vector3> handles; Vector<Vector3> secondary_handles; bool billboard_handle; bool valid; Spatial *base; Vector<Instance> instances; Spatial *spatial_node; void _set_spatial_node(Node *p_node) { set_spatial_node(p_node->cast_to<Spatial>()); } protected: void add_lines(const Vector<Vector3> &p_lines, const Ref<Material> &p_material, bool p_billboard = false); void add_mesh(const Ref<Mesh> &p_mesh, bool p_billboard = false, const RID &p_skeleton = RID()); void add_collision_segments(const Vector<Vector3> &p_lines); void add_collision_triangles(const Ref<TriangleMesh> &p_tmesh); void add_unscaled_billboard(const Ref<Material> &p_material, float p_scale = 1); void add_handles(const Vector<Vector3> &p_handles, bool p_billboard = false, bool p_secondary = false); void set_spatial_node(Spatial *p_node); static void _bind_methods(); public: virtual Vector3 get_handle_pos(int p_idx) const; virtual bool intersect_frustum(const Camera *p_camera, const Vector<Plane> &p_frustum); virtual bool intersect_ray(const Camera *p_camera, const Point2 &p_point, Vector3 &r_pos, Vector3 &r_normal, int *r_gizmo_handle = NULL, bool p_sec_first = false); void clear(); void create(); void transform(); virtual void redraw(); void free(); EditorSpatialGizmo(); ~EditorSpatialGizmo(); }; class LightSpatialGizmo : public EditorSpatialGizmo { GDCLASS(LightSpatialGizmo, EditorSpatialGizmo); Light *light; public: virtual String get_handle_name(int p_idx) const; virtual Variant get_handle_value(int p_idx) const; virtual void set_handle(int p_idx, Camera *p_camera, const Point2 &p_point); virtual void commit_handle(int p_idx, const Variant &p_restore, bool p_cancel = false); void redraw(); LightSpatialGizmo(Light *p_light = NULL); }; class CameraSpatialGizmo : public EditorSpatialGizmo { GDCLASS(CameraSpatialGizmo, EditorSpatialGizmo); Camera *camera; public: virtual String get_handle_name(int p_idx) const; virtual Variant get_handle_value(int p_idx) const; virtual void set_handle(int p_idx, Camera *p_camera, const Point2 &p_point); virtual void commit_handle(int p_idx, const Variant &p_restore, bool p_cancel = false); void redraw(); CameraSpatialGizmo(Camera *p_camera = NULL); }; class MeshInstanceSpatialGizmo : public EditorSpatialGizmo { GDCLASS(MeshInstanceSpatialGizmo, EditorSpatialGizmo); MeshInstance *mesh; public: void redraw(); MeshInstanceSpatialGizmo(MeshInstance *p_mesh = NULL); }; class Position3DSpatialGizmo : public EditorSpatialGizmo { GDCLASS(Position3DSpatialGizmo, EditorSpatialGizmo); Position3D *p3d; public: void redraw(); Position3DSpatialGizmo(Position3D *p_p3d = NULL); }; class SkeletonSpatialGizmo : public EditorSpatialGizmo { GDCLASS(SkeletonSpatialGizmo, EditorSpatialGizmo); Skeleton *skel; public: void redraw(); SkeletonSpatialGizmo(Skeleton *p_skel = NULL); }; class TestCubeSpatialGizmo : public EditorSpatialGizmo { GDCLASS(TestCubeSpatialGizmo, EditorSpatialGizmo); TestCube *tc; public: void redraw(); TestCubeSpatialGizmo(TestCube *p_tc = NULL); }; class RoomSpatialGizmo : public EditorSpatialGizmo { GDCLASS(RoomSpatialGizmo, EditorSpatialGizmo); struct _EdgeKey { Vector3 from; Vector3 to; bool operator<(const _EdgeKey &p_with) const { return from == p_with.from ? to < p_with.to : from < p_with.from; } }; Room *room; public: void redraw(); RoomSpatialGizmo(Room *p_room = NULL); }; class PortalSpatialGizmo : public EditorSpatialGizmo { GDCLASS(PortalSpatialGizmo, EditorSpatialGizmo); Portal *portal; public: void redraw(); PortalSpatialGizmo(Portal *p_portal = NULL); }; class VisibilityNotifierGizmo : public EditorSpatialGizmo { GDCLASS(VisibilityNotifierGizmo, EditorSpatialGizmo); VisibilityNotifier *notifier; public: virtual String get_handle_name(int p_idx) const; virtual Variant get_handle_value(int p_idx) const; virtual void set_handle(int p_idx, Camera *p_camera, const Point2 &p_point); virtual void commit_handle(int p_idx, const Variant &p_restore, bool p_cancel = false); void redraw(); VisibilityNotifierGizmo(VisibilityNotifier *p_notifier = NULL); }; class ParticlesGizmo : public EditorSpatialGizmo { GDCLASS(ParticlesGizmo, EditorSpatialGizmo); Particles *particles; public: virtual String get_handle_name(int p_idx) const; virtual Variant get_handle_value(int p_idx) const; virtual void set_handle(int p_idx, Camera *p_camera, const Point2 &p_point); virtual void commit_handle(int p_idx, const Variant &p_restore, bool p_cancel = false); void redraw(); ParticlesGizmo(Particles *p_particles = NULL); }; class ReflectionProbeGizmo : public EditorSpatialGizmo { GDCLASS(ReflectionProbeGizmo, EditorSpatialGizmo); ReflectionProbe *probe; public: virtual String get_handle_name(int p_idx) const; virtual Variant get_handle_value(int p_idx) const; virtual void set_handle(int p_idx, Camera *p_camera, const Point2 &p_point); virtual void commit_handle(int p_idx, const Variant &p_restore, bool p_cancel = false); void redraw(); ReflectionProbeGizmo(ReflectionProbe *p_notifier = NULL); }; class GIProbeGizmo : public EditorSpatialGizmo { GDCLASS(GIProbeGizmo, EditorSpatialGizmo); GIProbe *probe; public: virtual String get_handle_name(int p_idx) const; virtual Variant get_handle_value(int p_idx) const; virtual void set_handle(int p_idx, Camera *p_camera, const Point2 &p_point); virtual void commit_handle(int p_idx, const Variant &p_restore, bool p_cancel = false); void redraw(); GIProbeGizmo(GIProbe *p_notifier = NULL); }; class CollisionShapeSpatialGizmo : public EditorSpatialGizmo { GDCLASS(CollisionShapeSpatialGizmo, EditorSpatialGizmo); CollisionShape *cs; public: virtual String get_handle_name(int p_idx) const; virtual Variant get_handle_value(int p_idx) const; virtual void set_handle(int p_idx, Camera *p_camera, const Point2 &p_point); virtual void commit_handle(int p_idx, const Variant &p_restore, bool p_cancel = false); void redraw(); CollisionShapeSpatialGizmo(CollisionShape *p_cs = NULL); }; class CollisionPolygonSpatialGizmo : public EditorSpatialGizmo { GDCLASS(CollisionPolygonSpatialGizmo, EditorSpatialGizmo); CollisionPolygon *polygon; public: void redraw(); CollisionPolygonSpatialGizmo(CollisionPolygon *p_polygon = NULL); }; class RayCastSpatialGizmo : public EditorSpatialGizmo { GDCLASS(RayCastSpatialGizmo, EditorSpatialGizmo); RayCast *raycast; public: void redraw(); RayCastSpatialGizmo(RayCast *p_raycast = NULL); }; class VehicleWheelSpatialGizmo : public EditorSpatialGizmo { GDCLASS(VehicleWheelSpatialGizmo, EditorSpatialGizmo); VehicleWheel *car_wheel; public: void redraw(); VehicleWheelSpatialGizmo(VehicleWheel *p_car_wheel = NULL); }; class NavigationMeshSpatialGizmo : public EditorSpatialGizmo { GDCLASS(NavigationMeshSpatialGizmo, EditorSpatialGizmo); struct _EdgeKey { Vector3 from; Vector3 to; bool operator<(const _EdgeKey &p_with) const { return from == p_with.from ? to < p_with.to : from < p_with.from; } }; NavigationMeshInstance *navmesh; public: void redraw(); NavigationMeshSpatialGizmo(NavigationMeshInstance *p_navmesh = NULL); }; class PinJointSpatialGizmo : public EditorSpatialGizmo { GDCLASS(PinJointSpatialGizmo, EditorSpatialGizmo); PinJoint *p3d; public: void redraw(); PinJointSpatialGizmo(PinJoint *p_p3d = NULL); }; class HingeJointSpatialGizmo : public EditorSpatialGizmo { GDCLASS(HingeJointSpatialGizmo, EditorSpatialGizmo); HingeJoint *p3d; public: void redraw(); HingeJointSpatialGizmo(HingeJoint *p_p3d = NULL); }; class SliderJointSpatialGizmo : public EditorSpatialGizmo { GDCLASS(SliderJointSpatialGizmo, EditorSpatialGizmo); SliderJoint *p3d; public: void redraw(); SliderJointSpatialGizmo(SliderJoint *p_p3d = NULL); }; class ConeTwistJointSpatialGizmo : public EditorSpatialGizmo { GDCLASS(ConeTwistJointSpatialGizmo, EditorSpatialGizmo); ConeTwistJoint *p3d; public: void redraw(); ConeTwistJointSpatialGizmo(ConeTwistJoint *p_p3d = NULL); }; class Generic6DOFJointSpatialGizmo : public EditorSpatialGizmo { GDCLASS(Generic6DOFJointSpatialGizmo, EditorSpatialGizmo); Generic6DOFJoint *p3d; public: void redraw(); Generic6DOFJointSpatialGizmo(Generic6DOFJoint *p_p3d = NULL); }; class SpatialEditorGizmos { public: Ref<SpatialMaterial> create_line_material(const Color &p_base_color); Ref<SpatialMaterial> create_solid_material(const Color &p_base_color); Ref<SpatialMaterial> handle2_material; Ref<SpatialMaterial> handle2_material_billboard; Ref<SpatialMaterial> handle_material; Ref<SpatialMaterial> handle_material_billboard; Ref<SpatialMaterial> light_material; Ref<SpatialMaterial> light_material_omni; Ref<SpatialMaterial> light_material_omni_icon; Ref<SpatialMaterial> light_material_directional_icon; Ref<SpatialMaterial> camera_material; Ref<SpatialMaterial> skeleton_material; Ref<SpatialMaterial> reflection_probe_material; Ref<SpatialMaterial> reflection_probe_material_internal; Ref<SpatialMaterial> gi_probe_material; Ref<SpatialMaterial> gi_probe_material_internal; Ref<SpatialMaterial> room_material; Ref<SpatialMaterial> portal_material; Ref<SpatialMaterial> raycast_material; Ref<SpatialMaterial> visibility_notifier_material; Ref<SpatialMaterial> particles_material; Ref<SpatialMaterial> car_wheel_material; Ref<SpatialMaterial> joint_material; Ref<SpatialMaterial> navmesh_edge_material; Ref<SpatialMaterial> navmesh_solid_material; Ref<SpatialMaterial> navmesh_edge_material_disabled; Ref<SpatialMaterial> navmesh_solid_material_disabled; Ref<SpatialMaterial> listener_icon; Ref<SpatialMaterial> sample_player_icon; Ref<SpatialMaterial> stream_player_icon; Ref<SpatialMaterial> visibility_notifier_icon; Ref<SpatialMaterial> shape_material; Ref<Texture> handle_t; Ref<Mesh> pos3d_mesh; Ref<Mesh> listener_line_mesh; static SpatialEditorGizmos *singleton; Ref<TriangleMesh> test_cube_tm; Ref<SpatialEditorGizmo> get_gizmo(Spatial *p_spatial); SpatialEditorGizmos(); }; #endif // SPATIAL_EDITOR_GIZMOS_H
29.032051
164
0.735262
[ "mesh", "vector", "transform", "3d" ]
095a31a2a593aa84154a0658caf7b90963afdaa1
1,041
h
C
heekscad/interface/Property.h
JohnyEngine/CNC
e4c77250ab2b749d3014022cbb5eb9924e939993
[ "Apache-2.0" ]
null
null
null
heekscad/interface/Property.h
JohnyEngine/CNC
e4c77250ab2b749d3014022cbb5eb9924e939993
[ "Apache-2.0" ]
null
null
null
heekscad/interface/Property.h
JohnyEngine/CNC
e4c77250ab2b749d3014022cbb5eb9924e939993
[ "Apache-2.0" ]
null
null
null
// Property.h // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. // Base class for all Properties #if !defined Property_HEADER #define Property_HEADER enum{ InvalidPropertyType, StringPropertyType, DoublePropertyType, LengthPropertyType, IntPropertyType, VertexPropertyType, ChoicePropertyType, ColorPropertyType, CheckPropertyType, ListOfPropertyType, TrsfPropertyType, FilePropertyType }; #include <vector> class Property{ public: bool m_highlighted; HeeksObj* m_object; void(*m_selectcallback)(HeeksObj*); Property(HeeksObj* object, void(*selectcallback)(HeeksObj*) = NULL, bool highlighted = false):m_highlighted(highlighted), m_object(object), m_selectcallback(selectcallback) {} virtual ~Property(){} virtual int get_property_type(){return InvalidPropertyType;} virtual bool property_editable()const = 0; virtual Property *MakeACopy(void)const = 0; virtual const wxChar* GetShortString(void)const{return _("Unknown Property");} }; #endif
23.659091
176
0.782901
[ "object", "vector" ]
0964621f79cde75f9bcf8101a801c1b0980c0055
2,082
c
C
lib/wizards/aarrgh/nyxi/altar2.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
lib/wizards/aarrgh/nyxi/altar2.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
lib/wizards/aarrgh/nyxi/altar2.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
inherit "room/room"; reset(arg) { set_light(1); set_not_out(1); add_exit("out", "/wizards/aarrgh/nyxi/cave.c"); short_desc = "Altar room"; long_desc = "This room is the large altar room of prayers. It flows with magical energy and\n" "gains its powers the pool Morfeus has been using for sacrifices. Altar in the\n" "center is sculpted from white and grey bones. The presence of great power can\n" "be definitely noticed. A mist covers the floor and it swirls when you walk in\n" "the room. The altar looks interesting.\n"; items = allocate(4); items[0] = "altar"; items[1] = "This altar is used for praying for the powers of Nyx"; } init() { ::init(); add_action("pray1", "pray"); } int check; pray1(str) { object nyxi; object hiileri; if(str != "altar" ) { write("Pray what?\n"); return 1; } nyxi = clone_object("/wizards/aarrgh/nyxi/mon/nyx"); hiileri = clone_object("/wizards/aarrgh/nyxi/mon/entity"); if(str == "altar" && check == 1 ) { write("You can only pray once.\n"); return 1; } if(str == "altar" && present("nyxi", environment(this_player() ))) { write("The Nyx is present.\n"); return 1; } if(str == "altar" && check != 1 && !present("nyx", environment(this_player() ))) { write("You have summoned the mighty and powerful Nyx!\n\n"); write("Nyx concentrates and suddenly some strange demonic creature raises from the ground!\n"); say(this_player()->query_name()+" prays the altar and suddenly the Nyx has been summoned!\n\n"); say("Nyx chants some runes and suddenly a demonic entity raises from the ground!\n\n"); say("A demonic roars: You shall die, pathetic mortals!\n"); shout("Earth trembles as Nyx the mother of chaos enters this realm!\n"); move_object(nyxi, environment(this_player() )); move_object(hiileri, environment(this_player() )); tell_room("/wizards/aarrgh/nyxi/cave.c", "The Nyx has been summoned!\n"); check = 1; return 1; } }
28.135135
97
0.631124
[ "object" ]
096a17212849c7761f6790fe86c01d9dc56b02e9
8,523
h
C
GDLL/Accounts.h
Physticz/GABB
57dfc4313f0db3476e35e3eda918cfab4de4eb57
[ "MIT" ]
3
2021-03-25T08:35:17.000Z
2022-01-05T22:43:33.000Z
GDLL/Accounts.h
Physticz/GABB
57dfc4313f0db3476e35e3eda918cfab4de4eb57
[ "MIT" ]
3
2021-01-22T15:42:51.000Z
2021-09-13T05:55:35.000Z
GDLL/Accounts.h
Physticz/GABB
57dfc4313f0db3476e35e3eda918cfab4de4eb57
[ "MIT" ]
6
2021-12-27T15:26:02.000Z
2022-03-24T14:47:26.000Z
#pragma once #include <string> #include <vector> #include "registry.h" void cout(std::wstring ctx); namespace Safety { std::string RandomKey(int length, int table); } std::wstring s2ws(const std::string &s) { return std::wstring(s.begin(), s.end()); } std::string toUpperA(std::string text) { for (unsigned int i = 0; i < text.length(); i++) if (text[i] >= 97 && text[i] <= 122) text[i] -= 32; return text; } /*std::wstring s2ws(const std::string& str) { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> converterX; return converterX.from_bytes(str); }*/ std::string ws2s(const std::wstring& wstr) { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> converterX; return converterX.to_bytes(wstr); } int HexCharToInt(char HexChar) { std::string chars = "0123456789abcdefABCDEF"; size_t posX = chars.find(HexChar); return posX == std::string::npos ? 0 : (posX > 15 ? posX - 6 : posX); } std::string IntToHex(int INT) { std::stringstream stream; stream << std::hex << INT; return std::string(stream.str()); } int Multiply(int number, int times) { int result = 1; for (int i = 0; i < times; i++) result = result * number; return result; } struct ACCUSER; class ACCMGR { public: ACCMGR(std::string savedata = ""); bool findMKey(); void setRegAccount(int ID); void setRegAccountRandom(); void setRegKeys(std::pair<std::string, std::string> keys); std::string getRegAccount(); void editAccount(int ID, std::string MAC, std::string Name = ""); void addAccount(std::string MAC, std::string name = ""); void loadAccounts(std::string savedata); std::string toString(); ACCUSER * getAccount(int ID); std::string getAccounts(); std::vector<ACCUSER> getVAccounts(); void delAccount(int ID); int freeID(); std::string KeyAToMAC(std::string key); std::pair<std::string, std::string> MACToKeys(std::string MAC); inline bool isChanged() { return this->changed ? !(this->changed = false) : false; } inline bool isInitialised() { return this->initialised; } inline std::string RandomMAC() { return toUpperA(Safety::RandomKey(12, 3)); } private: std::vector<ACCUSER> items; bool changed = false; bool initialised = false; std::wstring aKey = L"", aValue1 = L"", aValue2 = L"", aMKey = L""; }; ACCMGR::ACCMGR(std::string savedata) { srand((unsigned int)time(NULL)); std::wstring data = FindKey(HKEY_CURRENT_USER, L"", true); if (!data.length()) return; std::vector<std::wstring> values = FindKeyAll(HKEY_CURRENT_USER, data, false); if (values.size() < 2) return; this->aKey = data; this->aValue1 = values[0]; this->aValue2 = values[1]; if (savedata.length()) this->loadAccounts(savedata); this->initialised = true; } bool ACCMGR::findMKey() { std::wstring key = L""; HKEY HK = NULL; if (RegOpenKeyEx(HKEY_CURRENT_USER, L"Software\\Microsoft", 0, KEY_READ | KEY_WOW64_32KEY, &HK) == ERROR_SUCCESS) { key = FindKey(HK, L"", true); RegCloseKey(HK); } if (!key.length() && RegOpenKeyEx(HKEY_CURRENT_USER, L"Software\\Microsoft", 0, KEY_READ | KEY_WOW64_64KEY, &HK) == ERROR_SUCCESS) { key = FindKey(HK, L"", true); RegCloseKey(HK); } if (!key.length()) return false; this->aMKey = key; return true; } void ACCMGR::setRegKeys(std::pair<std::string, std::string> keys) { if(!this->initialised) return; if(!RegKeySetValueBinary(HKEY_CURRENT_USER, this->aKey, this->aValue1, keys.first) || !RegKeySetValueBinary(HKEY_CURRENT_USER, this->aKey, this->aValue2, keys.second)) { cout(L"Inserting device keys failed!"); return; } std::string Rguid = Safety::RandomKey(36, 3); Rguid[8] = '-'; Rguid[13] = '-'; Rguid[18] = '-'; Rguid[23] = '-'; RegKeySetValueRegSz(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Cryptography", L"MachineGuid", s2ws(Rguid)); if (this->aMKey.length() || this->findMKey()) RegDeleteKey(HKEY_CURRENT_USER, std::wstring(L"Software\\Microsoft\\" + this->aMKey).c_str()); this->changed = true; } void ACCMGR::setRegAccount(int ID) { ACCUSER * u = this->getAccount(ID); if (u == NULL) return; this->setRegKeys(this->MACToKeys(u->mac)); } void ACCMGR::setRegAccountRandom() { this->setRegKeys(this->MACToKeys(this->RandomMAC())); } std::string ACCMGR::getRegAccount() { if (this->aKey == L"") return ""; std::wstring key; RegKeyGetValueBinary(HKEY_CURRENT_USER, this->aKey, this->aValue1, key, key, key); if(!key.length()) return ""; return this->KeyAToMAC(ws2s(key)); } void ACCMGR::addAccount(std::string MAC, std::string name) { for (unsigned int i = 0; i < this->items.size(); i++) if (this->items[i].mac == MAC) return; this->items.push_back({ this->freeID(), name, MAC }); this->changed = true; } void ACCMGR::editAccount(int ID, std::string MAC, std::string Name) { for (unsigned int i = 0; i < this->items.size(); i++) { if (this->items[i].id == ID) { this->items[i].mac = MAC; this->items[i].name = Name; this->changed = true; return; } } } void ACCMGR::loadAccounts(std::string savedata) { if (!savedata.length()) return; this->items.clear(); std::size_t pos, a, b; while ((pos = savedata.find("\\|")) != std::string::npos) { if ((a = savedata.find("a|")) < pos && (b = savedata.find("b|")) < pos && a < b) { this->addAccount(savedata.substr(a + 2, b - a - 2), savedata.substr(0, a)); } savedata = savedata.substr(pos + 2); } this->changed = true; } std::string ACCMGR::toString() { std::string ctx; for (unsigned int i = 0; i < this->items.size(); i++) ctx += this->items[i].name + "a|" + this->items[i].mac + "b|\\|"; return ctx; } ACCUSER * ACCMGR::getAccount(int ID) { for (unsigned int i = 0; i < this->items.size(); i++) if (this->items[i].id == ID) return &this->items[i]; return NULL; } std::string ACCMGR::getAccounts() { std::string buffer = ""; for (unsigned int i = 0; i < this->items.size(); i++) buffer += this->items[i].name + "a|" + this->items[i].mac + "b|\\|"; return buffer; } std::vector<ACCUSER> ACCMGR::getVAccounts() { return this->items; } void ACCMGR::delAccount(int ID) { for (unsigned int i = 0; i < this->items.size(); i++) { if (items[i].id == ID) { items.erase(items.begin() + i); this->changed = true; return; } } } int ACCMGR::freeID() { int id = 1; while (this->getAccount(id) != NULL) { id++; } return id; } std::string ACCMGR::KeyAToMAC(std::string key) { if (key.length() != 36) return ""; std::string result = ""; unsigned char val; for (int i = 0; i < 17; i++) { if (i % 3 == 2) continue; val = HexCharToInt(key[i * 2]) * 16 + HexCharToInt(key[(i * 2) + 1]); result += IntToHex((unsigned char)((val >= 0x1f && val <= 0x34) ? (val - (21 + i)) : (val - (238 + i)))); } return toUpperA(result); } std::pair<std::string, std::string> ACCMGR::MACToKeys(std::string MAC) { std::string Rkeya = "", Rkeyb = ""; if (MAC.length() != 12) return { "", "" }; unsigned char values[18]; for (int i = 0; i < 17; i++) values[i] = 238 + i; values[17] = 0; int id = 0; int hex; for (int i = 0; i < 17; i++) { if (i % 3 == 2) { values[i] += 10; continue; } if ((hex = HexCharToInt(MAC[id])) < 10) values[i] += hex; else values[i] -= (217 - hex); id++; } std::string result = ""; for (int i = 0; i < 18; i++) { std::string addi = IntToHex((unsigned char)values[i]); result += addi.length() % 2 == 1 ? '0' + addi : addi; } Rkeya = result; int sum = 0; for (int i = 0; i < 18; i++) if (i % 3 != 2) sum += values[i]; int altems[6] = { 4, 3, 7, 6, 4, 4 }; int offsets[12] = { -1, -1, -1, -1, -1, -1, 8, 7, 5, 4, 2, 1 }; for (int i = 0; i < (int)MAC.length(); i++) { int mass = HexCharToInt(MAC[i]); if (mass == 0) continue; if (mass >= 10) { altems[5] += mass - 7; altems[4] -= 1; altems[3] -= 2; } else if (offsets[i] != -1 && mass > offsets[i]) { altems[5] += mass - 6; altems[4] -= 5; altems[3] -= 2; } else altems[5] += mass; } int val = 0; for (int i = 5; i >= 0; i--) val += (altems[i] * (Multiply(10, 5 - i))); for (int i = 5; i > 0; i--) { altems[i] = val % 10; val -= val % 10; val /= 10; } altems[0] = val; char spacer = '3'; std::string HASH2 = ""; for (int i = 0; i < 6; i++) HASH2 += spacer + std::to_string(altems[i]); HASH2 += "00"; Rkeyb = HASH2; return { Rkeya, Rkeyb }; }
28.69697
142
0.598967
[ "vector" ]
096c5e5b2d8f9aaced878f11cb17038c31ab30e9
2,098
h
C
native/core/group_container.h
49View/event_horizon
9b78c9318e1a785384ab01eb4d90e79f0192c6ad
[ "BSD-3-Clause" ]
null
null
null
native/core/group_container.h
49View/event_horizon
9b78c9318e1a785384ab01eb4d90e79f0192c6ad
[ "BSD-3-Clause" ]
7
2021-09-02T05:58:24.000Z
2022-02-27T07:06:43.000Z
native/core/group_container.h
49View/event_horizon
9b78c9318e1a785384ab01eb4d90e79f0192c6ad
[ "BSD-3-Clause" ]
2
2020-02-06T02:05:15.000Z
2021-11-25T11:35:14.000Z
#pragma once template <typename U, typename K, template< typename > typename Sequencer, template< typename , typename > typename Container > class GroupContainer { protected: template< typename KI = K, typename UI = U > struct Iterator { Iterator(Container<KI, Sequencer<UI>>* _itmap, const bool _begin) : itmap(_itmap) { if ( _begin ) { itm = itmap->begin(); ita = itm->second.begin(); } else { itm = itmap->end(); for ( auto eita = itmap->begin(); eita != itmap->end(); ++eita ) { ita = eita->second.end(); } itmap = nullptr; } } bool operator!=( const Iterator<KI, UI>& _it ) const { return itm!= _it.itm || ita != _it.ita || _it.itmap != _it.itmap; } Iterator<KI, UI>& operator++() { if ( ++ita; ita == itm->second.end() ) { if ( ++itm; itm == itmap->end() ) { itmap = nullptr; } else { ita = itm->second.begin(); } } return *this; } UI operator*() const { //assert(itmap); return *ita; } UI& operator*() { //assert(itmap); return *ita; } Container<KI, Sequencer<UI>>* itmap = nullptr; typename Container<KI, Sequencer<UI>>::iterator itm; typename Sequencer<UI>::iterator ita; }; // end of Iterator public: Iterator<K, U> begin() { return Iterator<K, U>{ &group, true }; } Iterator<K, U> end() { return Iterator<K, U>{ &group, false }; } protected: Container<K, Sequencer<U>> group; }; template<class T> using vector_a = std::vector<T>; template<class T, class T2> using map_a = std::map<T, T2>; template<class T, class T2> using unordered_map_a = std::unordered_map<T, T2>; template<class T> using GroupContainerMSV = GroupContainer<T, std::string, vector_a, unordered_map_a>;
27.605263
91
0.505243
[ "vector" ]
0970cc5500132a0a60c73fb24bd719b23e95d291
15,033
c
C
tests/mymalloc.c
guanlan/luajit-mm
6821a07f9402cd7b9465c5d98c0b8d70a3fb8011
[ "MIT" ]
25
2015-01-08T11:20:12.000Z
2021-08-05T23:03:04.000Z
tests/mymalloc.c
guanlan/luajit-mm
6821a07f9402cd7b9465c5d98c0b8d70a3fb8011
[ "MIT" ]
1
2015-04-17T10:04:00.000Z
2015-05-01T08:16:29.000Z
tests/mymalloc.c
guanlan/luajit-mm
6821a07f9402cd7b9465c5d98c0b8d70a3fb8011
[ "MIT" ]
5
2015-07-10T15:52:44.000Z
2019-03-04T16:03:33.000Z
#include <sys/mman.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <strings.h> /* for bzero() */ #include <string.h> /* for memcpy() */ #ifdef DEBUG // Usage examples: ASSERT(a > b), ASSERT(foo() && "Opps, foo() reutrn 0"); #define ASSERT(c) if (!(c))\ { fprintf(stderr, "%s:%d Assert: %s\n", __FILE__, __LINE__, #c); abort(); } #else #define ASSERT(c) ((void)0) #endif #ifndef FOR_ADAPTOR #define MYMALLOC __wrap_malloc #define MYFREE __wrap_free #define MYCALLOC __wrap_calloc #define MYREALLOC __wrap_realloc #else #define MYMALLOC __adaptor_malloc #define MYFREE __adaptor_free #define MYCALLOC __adaptor_calloc #define MYREALLOC __adaptor_realloc #endif #define MYMALLOC_EXPORT __attribute__ ((visibility ("default"))) void* MYMALLOC(size_t) MYMALLOC_EXPORT; void MYFREE(void*) MYMALLOC_EXPORT; void* MYCALLOC(size_t, size_t) MYMALLOC_EXPORT; void* MYREALLOC(void*, size_t) MYMALLOC_EXPORT; typedef int v4si __attribute__ ((vector_size (16))); static inline int log2_int32(unsigned num) { return 31 - __builtin_clz(num); } static inline int ceil_log2_int32 (unsigned num) { int res = 31 - __builtin_clz(num); res += (num & (num - 1)) ? 1 : 0; return res; } #define ENABLE_TRACE 0 #define EXT_SZ (4096 * 2) #define MIN_ORDER 5 #define MAX_ORDER 31 #define BIN_NUM (MAX_ORDER - MIN_ORDER + 1) #define CHUNK_ALIGN (__alignof__(v4si)) typedef struct my_malloc_chunk my_chunk_t; struct my_malloc_chunk { unsigned prev_size; unsigned this_size; #ifdef DEBUG int magic_number; #endif union { struct { my_chunk_t* prev_free; my_chunk_t* next_free; }; v4si align_data; }; }; #ifdef DEBUG #define MAGIC_NUM 0x5a5a5a #define SET_MAGCI_NUM(c) {(c)->magic_number = MAGIC_NUM; } #define VERIFY_MAGIC_NUM(c) ASSERT((c)->magic_number == MAGIC_NUM) #else #define SET_MAGCI_NUM(c) ((void)0) #define VERIFY_MAGIC_NUM(c) ((void)0) #endif #define IS_CHUNK_FREE(c) ((c)->this_size & 1) #define SET_CHUNK_FREE(c) {(c)->this_size |= 1;} #define RESET_CHUNK_FREE(c) {(c)->this_size &= ~1;} #define IS_CHUNK_MMAP(c) ((c)->this_size & 2) #define SET_CHUNK_MMAP(c) {(c)->this_size |= 2;} #define RESET_CHUNK_MMAP(c) {(c)->this_size &= ~2;} #define IS_LAST_CHUNK(c) ((c)->this_size & 4) #define SET_LAST_CHUNK(c) {(c)->this_size |= 4; } #define RESET_LAST_CHUNK(c) {(c)->this_size &= ~4; } #define CHUNK_SIZE(c) ((c)->this_size & ~7) #define SET_CHUNK_SIZE(c, s) { typeof(c) t = (c);\ t->this_size = (t->this_size & 7) + s; } #define offsetof(st, m) ((size_t)(&((st *)0)->m)) #define CHUNK_OVERHEAD offsetof(my_chunk_t, align_data) typedef struct { my_chunk_t list; int min_size; } bin_t; typedef struct my_malloc_info my_malloc_info_t; struct my_malloc_info { int initialized; bin_t bins[BIN_NUM]; }; static my_malloc_info_t malloc_info; #define MMAP_THRESHOLD (EXT_SZ - sizeof(malloc_info) - CHUNK_ALIGN) /* Return cur's previous adjacent chunk. If the chunk dose not have previous * adjacent chunk, chunk itself is returned. */ static inline my_chunk_t* get_prev_adj_chunk(my_chunk_t* cur) { if (cur->prev_size != 0) { char* p = ((char*)(void*)cur) - cur->prev_size; return (my_chunk_t*)(void*)p; } return NULL; } static inline my_chunk_t* get_next_adj_chunk(my_chunk_t* chunk) { if (!IS_LAST_CHUNK(chunk)) return (my_chunk_t*)(void*)(CHUNK_SIZE(chunk) + (void*)chunk); return NULL; } static inline int is_bin_empty(bin_t* bin) { my_chunk_t* list = &bin->list; return list->next_free == list && list->prev_free == list; } /* Return the min bin index, such that all chunk c in that bin have * CHUNK_SIZE(c) > bin->min_size */ static inline int get_bin_idx_for_chunk(int chunk_size) { int idx = log2_int32(chunk_size) - MIN_ORDER; ASSERT(idx >= 0); if (idx >= BIN_NUM) idx = BIN_NUM - 1; return idx; } /* Return the min bin index, such that all chunk c in the bin have * CHUNK_SIZE(c) > alloc_sz */ static inline int get_bin_idx_for_alloc(int alloc_sz) { int idx = ceil_log2_int32(alloc_sz) - MIN_ORDER; ASSERT(idx >= 0); if (idx >= BIN_NUM) idx = BIN_NUM - 1; return idx; } static inline void append_to_bin(bin_t* bin, my_chunk_t* chunk) { ASSERT((CHUNK_SIZE(chunk) & (CHUNK_ALIGN - 1)) == 0 && (CHUNK_SIZE(chunk) >= bin->min_size)); my_chunk_t* insert_after = bin->list.prev_free; my_chunk_t* insert_before = &bin->list; chunk->prev_free = insert_after; chunk->next_free = insert_before; insert_before->prev_free = chunk; insert_after->next_free = chunk; } static inline my_chunk_t* pop_from_bin(bin_t* bin) { my_chunk_t* first = bin->list.next_free; if (first != &bin->list) { my_chunk_t* before_1st = first->prev_free; my_chunk_t* after_1st = first->next_free; before_1st->next_free = after_1st; after_1st->prev_free = before_1st; first->prev_free = first->next_free = NULL; return first; } return NULL; } static inline void append_free_chunk(my_chunk_t* chunk) { ASSERT(IS_CHUNK_FREE(chunk)); /* look for the right bin for this chunk */ int chunk_size = CHUNK_SIZE(chunk); int bin_idx = get_bin_idx_for_chunk(chunk_size); append_to_bin(malloc_info.bins + bin_idx, chunk); } /* Remove the free chunk from bin */ static inline void remove_free_chunk(my_chunk_t* chunk) { ASSERT(IS_CHUNK_FREE(chunk)); #ifdef DEBUG { int chunk_size = CHUNK_SIZE(chunk); bin_t* bin = malloc_info.bins + get_bin_idx_for_chunk(chunk_size); int found = 0; my_chunk_t* iter, *iter_e = &bin->list; for (iter = bin->list.next_free; iter != iter_e; iter = iter->next_free) { if (iter == chunk) { found = 1; break; } } ASSERT(found); } #endif my_chunk_t* prev = chunk->prev_free; my_chunk_t* next = chunk->next_free; prev->next_free = next; next->prev_free = prev; chunk->prev_free = chunk->next_free = NULL; } static void malloc_init(void) { int i; for (i = 0; i < BIN_NUM; i++) { bin_t* bin = malloc_info.bins + i; my_chunk_t* list = &bin->list; list->prev_free = list->next_free = list; bin->min_size = 1 << (i + MIN_ORDER); } malloc_info.initialized = 1; } /* Split the given chunk into two at the specified splitting point, return * the second one. */ static my_chunk_t* split_chunk(my_chunk_t* chunk, int split_point) { ASSERT((split_point & (CHUNK_ALIGN - 1)) == 0); ASSERT(split_point + CHUNK_OVERHEAD <= CHUNK_SIZE(chunk)); int chunk_sz = CHUNK_SIZE(chunk); int chunk2_sz = chunk_sz - split_point; ASSERT(chunk2_sz >= sizeof(my_chunk_t)); my_chunk_t* chunk2; chunk2 = (my_chunk_t*)(void*)(split_point + (char*)(void*)chunk); chunk2->prev_size = chunk_sz - chunk2_sz; SET_CHUNK_SIZE(chunk2, chunk2_sz); SET_CHUNK_SIZE(chunk, split_point); /* Only the 1st chunk is marked with mapped*/ RESET_CHUNK_MMAP(chunk2); SET_MAGCI_NUM(chunk2); if (!IS_LAST_CHUNK(chunk)) { my_chunk_t* follow; follow = (my_chunk_t*)(void*)(chunk_sz + (char*)(void*)chunk); follow->prev_size = chunk2_sz; RESET_LAST_CHUNK(chunk2); } else { RESET_LAST_CHUNK(chunk); SET_LAST_CHUNK(chunk2); } if (IS_CHUNK_FREE(chunk)) SET_CHUNK_FREE(chunk2); return chunk2; } static my_chunk_t* find_big_enough_chunk(size_t alloc_size, int* bin_idx) { int bin_idx_tmp = get_bin_idx_for_alloc(alloc_size); int i; for (i = bin_idx_tmp; i < BIN_NUM; i++) { bin_t* bin = malloc_info.bins + i; if (is_bin_empty(bin)) continue; break; } *bin_idx = i; if (i < BIN_NUM - 1) return pop_from_bin(malloc_info.bins + i); if (i == BIN_NUM -1) { my_chunk_t* iter, *iter_e; for (iter = malloc_info.bins[i].list.next_free, iter_e = malloc_info.bins[i].list.prev_free; iter != iter_e; iter = iter->next_free) { if (CHUNK_SIZE(iter) >= alloc_size) { remove_free_chunk(iter); return iter; } } } return NULL; } /* The alloc_sz already take into account the chunk-overhead, and is * properly aligned. * * NOTE: before calling this function, chunk should already be removed from bin. */ static void* malloc_helper(my_chunk_t* chunk, size_t alloc_sz) { RESET_CHUNK_FREE(chunk); /* Try to split the chunk. */ unsigned chunk_size = CHUNK_SIZE(chunk); ASSERT(((alloc_sz & (CHUNK_ALIGN - 1)) == 0) && chunk_size >= alloc_sz); unsigned remain_sz = chunk_size - alloc_sz; if (remain_sz > sizeof(my_chunk_t)) { my_chunk_t* split = split_chunk(chunk, alloc_sz); SET_CHUNK_FREE(split); append_free_chunk(split); } return CHUNK_OVERHEAD + ((char*)(void*)chunk); } void* MYMALLOC(size_t size) { if (ENABLE_TRACE) fprintf(stderr, "\nmalloc(%lu)\n", size); if (!malloc_info.initialized) malloc_init(); size_t norm_size = (size + CHUNK_OVERHEAD + CHUNK_ALIGN - 1) & ~(CHUNK_ALIGN - 1); void* result = NULL; int bin_idx; my_chunk_t* chunk = find_big_enough_chunk(norm_size, &bin_idx); if (chunk) { result = malloc_helper(chunk, norm_size); goto malloc_exit; } /* case 2: no free chunk big enough. Create one via mmap() */ size_t mmap_sz = EXT_SZ; if (mmap_sz < norm_size) mmap_sz = norm_size; long page_sz = sysconf(_SC_PAGESIZE); mmap_sz = (mmap_sz + page_sz - 1) & ~(page_sz - 1); result = mmap(NULL, mmap_sz, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); if (ENABLE_TRACE) fprintf(stderr, " > %p = mmap(%ld)\n", result, mmap_sz); if (result == MAP_FAILED) goto malloc_exit; chunk = (my_chunk_t*)result; chunk->prev_size = 0; chunk->this_size = mmap_sz; SET_LAST_CHUNK(chunk); SET_CHUNK_MMAP(chunk); SET_CHUNK_FREE(chunk); SET_MAGCI_NUM(chunk); result = malloc_helper(chunk, norm_size); malloc_exit: if (ENABLE_TRACE) fprintf(stderr, "%p = malloc(%ld)\n", result, size); return result; } void MYFREE(void* ptr) { if (ENABLE_TRACE) fprintf(stderr, "\nfree(%p)\n", ptr); my_chunk_t* chunk = (my_chunk_t*)(void*)(((char*)ptr) - CHUNK_OVERHEAD); ASSERT(!IS_CHUNK_FREE(chunk)); VERIFY_MAGIC_NUM(chunk); while (1) { my_chunk_t* prev_adj = get_prev_adj_chunk(chunk); my_chunk_t* next_adj = get_next_adj_chunk(chunk); int change = 0; /* Consolidate with the adjacent following chunk */ if (next_adj && IS_CHUNK_FREE(next_adj)) { remove_free_chunk(next_adj); if (IS_LAST_CHUNK(next_adj)) SET_LAST_CHUNK(chunk); int new_sz = CHUNK_SIZE(chunk) + CHUNK_SIZE(next_adj); SET_CHUNK_SIZE(chunk, new_sz); change = 1; } /* Consolidate with the previous adjacent chunk */ if (prev_adj && IS_CHUNK_FREE(prev_adj)) { remove_free_chunk(prev_adj); if (IS_LAST_CHUNK(chunk)) SET_LAST_CHUNK(prev_adj); int new_sz = CHUNK_SIZE(chunk) + CHUNK_SIZE(prev_adj); SET_CHUNK_SIZE(prev_adj, new_sz); chunk = prev_adj; change = 1; } if (!change) break; } if (IS_CHUNK_MMAP(chunk) && IS_LAST_CHUNK(chunk)) { if (ENABLE_TRACE) fprintf(stderr, " > munmap(%p, %u)\n", chunk, CHUNK_SIZE(chunk)); munmap((void*)chunk, CHUNK_SIZE(chunk)); return; } SET_CHUNK_FREE(chunk); if (!IS_LAST_CHUNK(chunk)) { my_chunk_t* next_adj = get_next_adj_chunk(chunk); next_adj->prev_size = CHUNK_SIZE(chunk); } append_free_chunk(chunk); } void* MYREALLOC(void* ptr, size_t size) { if (ENABLE_TRACE) fprintf(stderr, "\nrealloc(%p, %lu)\n", ptr, size); void* result = ptr; /* normalize the size */ size_t norm_size = (size + CHUNK_ALIGN - 1) & ~(CHUNK_ALIGN - 1); norm_size += CHUNK_OVERHEAD; my_chunk_t* chunk = (my_chunk_t*)(void*)(((char*)ptr) - CHUNK_OVERHEAD); size_t chunk_sz = CHUNK_SIZE(chunk); if (norm_size > chunk_sz) { result = (my_chunk_t*)MYMALLOC(norm_size); if (result) { memcpy(result, (void*)&chunk->align_data, chunk_sz - CHUNK_OVERHEAD); SET_CHUNK_FREE(chunk); append_free_chunk(chunk); } goto realloc_exit; } if (chunk_sz - norm_size >= sizeof(my_chunk_t)) { /* shrink the allocated block */ my_chunk_t* another = split_chunk(chunk, norm_size); SET_CHUNK_FREE(another); append_free_chunk(another); } realloc_exit: if (ENABLE_TRACE) fprintf(stderr, "%p = realloc(%p, %lu)\n", result, ptr, size); return result; } void* MYCALLOC(size_t nmemb, size_t size) { size_t t = nmemb * size; void* p = MYMALLOC(t); if (p) bzero(p, t); return p; } #if 0 static void my_malloc_verify(void) { if (!malloc_info.initialized) return; int i; for (i = 0; i < BIN_NUM; i++) { bin_t* bin = malloc_info.bins + i; if (is_bin_empty(bin)) continue; my_chunk_t* iter, *iter_e; for (iter = bin->list.next_free, iter_e = &bin->list; iter != iter_e; iter = iter->next_free) { ASSERT(IS_CHUNK_FREE(iter)); ASSERT(iter->next_free && iter->prev_free); } } } #endif void my_malloc_dump(FILE* f) { if (!malloc_info.initialized) { return; } int i; for (i = 0; i < BIN_NUM; i++) { bin_t* bin = malloc_info.bins + i; if (is_bin_empty(bin)) continue; fprintf(f, "BIN:%3d, min_size:%d :", i, bin->min_size); my_chunk_t* iter, *iter_e; for (iter = bin->list.next_free, iter_e = &bin->list; iter != iter_e; iter = iter->next_free) { fprintf(f, "\n\t[chunk %p, size:%d, prev_size:%d, ", iter, CHUNK_SIZE(iter), iter->prev_size); fprintf(f, "prev_free:%p, next_free:%p", iter->prev_free, iter->next_free); if (IS_CHUNK_FREE(iter)) fprintf(f, ", free"); if (IS_CHUNK_MMAP(iter)) fprintf(f, ", mmap"); if (IS_LAST_CHUNK(iter)) fprintf(f, ", last"); fprintf(f, "] "); } fprintf(f, "\n"); } }
27.233696
83
0.608727
[ "3d" ]
097529dd7b60a50365a07849841595473fe830ba
3,534
h
C
source/IPyraNet.h
Dexterp37/ipyranet-cpp
01bab4118926cd2a4000a0fc1b927b0ce882ea14
[ "MIT" ]
1
2019-04-10T13:30:10.000Z
2019-04-10T13:30:10.000Z
source/IPyraNet.h
Dexterp37/ipyranet-cpp
01bab4118926cd2a4000a0fc1b927b0ce882ea14
[ "MIT" ]
null
null
null
source/IPyraNet.h
Dexterp37/ipyranet-cpp
01bab4118926cd2a4000a0fc1b927b0ce882ea14
[ "MIT" ]
null
null
null
/** * ipyranet-cpp * * Copyright (C) 2012 Alessio Placitelli * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #ifndef _IPyraNet_h_ #define _IPyraNet_h_ #include <vector> // forward declarations template<class OutType> class IPyraNetLayer; template <class NetType> class IPyraNet { public: enum TrainingTechnique { Unknown = -1, GradientDescend = 1 }; IPyraNet(); ~IPyraNet(); // XML serialization bool saveToXML(const std::string& fileName); bool loadFromXML(const std::string& fileName); bool saveOutputToXML(const std::string& fileName); // layer management void appendLayer(IPyraNetLayer<NetType>* newLayer); void getOutput(std::vector<NetType>& outputs); void destroy(); // training methods void setTrainingEpochs(int epochs); int getTrainingEpochs() const; void setTrainingTechnique(TrainingTechnique technique); //TrainingTechnique getTrainingTechnique() const; void setLearningRate(NetType rate); NetType getLearningRate() const; void setBatchMode(bool batch); bool getBatchMode() const; void train(const std::string& path); void test(const std::string& path); private: struct LayerDeltas { std::vector<std::vector<NetType> > deltas; }; struct LayerGradient { std::vector<std::vector<NetType> > weightsGrad; std::vector<std::vector<NetType> > biasesGrad; }; std::vector<LayerDeltas> layersDeltas; // deltas storage std::vector<LayerGradient> layersGradient; // gradient storage int trainingEpochs; NetType learningRate; NetType wantedError; TrainingTechnique trainingTechnique; bool batchMode; bool verboseOutput; std::vector<IPyraNetLayer<NetType>*> layers; void appendLayerNoInit(IPyraNetLayer<NetType>* newLayer); void initDeltaStorage(); void initGradientStorage(); void backpropagation(const std::vector<NetType>& errorSignal); void computeErrorSensitivities(const std::vector<NetType>& errorSignal); void computeGradient(); void resetGradient(); void computeErrorSignal(const std::vector<NetType>& output, const NetType* desired, std::vector<NetType>& error); NetType computeCrossEntropyError(const std::vector<NetType>& output, const NetType* desired); void updateWeightsAndBiases(); }; #endif // _IPyraNet_h_
33.339623
118
0.698642
[ "vector" ]
09795fd8629efc1f27c8ccc69ba4d6ebc680b504
2,467
h
C
include/Geometry/Algebraic/Utils/NormalForm/NormalForm.h
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
include/Geometry/Algebraic/Utils/NormalForm/NormalForm.h
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
include/Geometry/Algebraic/Utils/NormalForm/NormalForm.h
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
// NormalForm.h: interface for the NormalForm class. // Copyright (c) 2017-2018 Extreme Computation Technology and Solutions, LLC // All rights reserved // see file License.txt for license details ////////////////////////////////////////////////////////////////////// #if !defined(GEOMETRY_ALGEBRAIC_NORMALFORM_H__INCLUDED_) #define GEOMETRY_ALGEBRAIC_NORMALFORM_H__INCLUDED_ #pragma once #include "../../Indexed/Array/Array.h" #include "../../Indexed/Table/Table.h" using namespace std; namespace Geometry { namespace Algebraic { namespace Utils { ////////////////////////////////////////////////////////////////////// // Class SubTable ////////////////////////////////////////////////////////////////////// class SubTable { public: SubTable(); SubTable( const Geometry::Algebraic::Table &, const unsigned int &); virtual ~SubTable(); const Geometry::Algebraic::Array & operator [] (const unsigned int &) const; Geometry::Algebraic::Array & operator [] (const unsigned int &); void print(ostream *); unsigned int size1() const; unsigned int size2() const; protected: unsigned int n1; unsigned int n2; Geometry::Algebraic::Array **L; private: SubTable(const SubTable &); SubTable & operator = (const SubTable &); }; ////////////////////////////////////////////////////////////////////// // Class NormalForm ////////////////////////////////////////////////////////////////////// class NormalForm { public: NormalForm(); virtual ~NormalForm(); void operator () (Geometry::Algebraic::Table &); void operator () ( Geometry::Algebraic::Table &, Geometry::Algebraic::Table &, Geometry::Algebraic::Table &); private: void Row(SubTable &, unsigned int, unsigned int); void Row(SubTable &, unsigned int); void Row(SubTable &, unsigned int, unsigned int, unsigned int); void Col(SubTable &, unsigned int, unsigned int); void Col(SubTable &, unsigned int); void Col(SubTable &, unsigned int, unsigned int, unsigned int); void Min(SubTable &, unsigned int &, unsigned int &, unsigned int &); private: NormalForm(const NormalForm &); NormalForm & operator = (const NormalForm &); }; } } } ostream & operator<<(ostream &os, Geometry::Algebraic::Utils::SubTable &); void Null(Geometry::Algebraic::Table &); void Identity(Geometry::Algebraic::Table &); #endif // !defined(GEOMETRY_ALGEBRAIC_NORMALFORM_H__INCLUDED_)
24.919192
77
0.586948
[ "geometry" ]
098022b62677d4b209f2080099f08897a253785d
202
h
C
Hemuppgifter/Lecture2/SDLProjekt_Mac_startup/SDLproject/background.h
konglobemeralt/DAT017
a0d3613ef6675fe7e28f27570bfe3a17a711d117
[ "MIT" ]
null
null
null
Hemuppgifter/Lecture2/SDLProjekt_Mac_startup/SDLproject/background.h
konglobemeralt/DAT017
a0d3613ef6675fe7e28f27570bfe3a17a711d117
[ "MIT" ]
null
null
null
Hemuppgifter/Lecture2/SDLProjekt_Mac_startup/SDLproject/background.h
konglobemeralt/DAT017
a0d3613ef6675fe7e28f27570bfe3a17a711d117
[ "MIT" ]
1
2022-02-01T10:37:58.000Z
2022-02-01T10:37:58.000Z
#ifndef BACKGROUND_H #define BACKGROUND_H #include "gameobject.h" extern GameObject background; void updateBackground(GameObject* this); void render(GameObject* this); void createBackground(); #endif
18.363636
40
0.806931
[ "render" ]
0981dd803c1fbe5dbc23c8d9f8c36d929c040a17
6,247
h
C
jamvm-1.5.4/src/thread.h
nmldiegues/jvm-stm
d422d78ba8efc99409ecb49efdb4edf4884658df
[ "Apache-2.0" ]
2
2015-09-08T15:40:04.000Z
2017-02-09T15:19:33.000Z
jamvm-1.5.4/src/thread.h
nmldiegues/jvm-stm
d422d78ba8efc99409ecb49efdb4edf4884658df
[ "Apache-2.0" ]
null
null
null
jamvm-1.5.4/src/thread.h
nmldiegues/jvm-stm
d422d78ba8efc99409ecb49efdb4edf4884658df
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009 * Robert Lougher <rob@jamvm.org.uk>. * * This file is part of JamVM. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef CREATING #include <pthread.h> #include <setjmp.h> #include <stdlib.h> #ifdef HAVE_ALLOCA_H #include <alloca.h> #endif /* Thread states */ #define CREATING 0 #define STARTED 1 #define RUNNING 2 #define WAITING 3 #define TIMED_WAITING 4 #define BLOCKED 5 #define SUSPENDED 6 /* thread priorities */ #define MIN_PRIORITY 1 #define NORM_PRIORITY 5 #define MAX_PRIORITY 10 /* Enable/Disable suspend modes */ #define SUSP_BLOCKING 1 #define SUSP_CRITICAL 2 /* Park states */ #define PARK_BLOCKED 0 #define PARK_RUNNING 1 #define PARK_PERMIT 2 typedef struct thread Thread; typedef struct monitor { pthread_mutex_t lock; Thread *owner; Object *obj; int count; int in_wait; uintptr_t entering; int wait_count; Thread *wait_set; struct monitor *next; } Monitor; struct thread { int id; pthread_t tid; char state; char suspend; char blocking; char park_state; char interrupted; char interrupting; ExecEnv *ee; void *stack_top; void *stack_base; Monitor *wait_mon; Monitor *blocked_mon; Thread *wait_prev; Thread *wait_next; pthread_cond_t wait_cv; pthread_cond_t park_cv; pthread_mutex_t park_lock; long long blocked_count; long long waited_count; Thread *prev, *next; unsigned int wait_id; unsigned int notify_id; }; extern Thread *threadSelf(); extern Thread *jThread2Thread(Object *jThread); extern Thread *vmThread2Thread(Object *vmThread); extern long long javaThreadId(Thread *thread); extern void *getStackTop(Thread *thread); extern void *getStackBase(Thread *thread); extern int getThreadsCount(); extern int getPeakThreadsCount(); extern void resetPeakThreadsCount(); extern long long getTotalStartedThreadsCount(); extern void threadInterrupt(Thread *thread); extern void threadSleep(Thread *thread, long long ms, int ns); extern void threadYield(Thread *thread); extern int threadIsAlive(Thread *thread); extern int threadInterrupted(Thread *thread); extern int threadIsInterrupted(Thread *thread); extern int systemIdle(Thread *self); extern void threadPark(Thread *thread, int absolute, long long time); extern void threadUnpark(Thread *thread); extern void suspendAllThreads(Thread *thread); extern void resumeAllThreads(Thread *thread); extern void createVMThread(char *name, void (*start)(Thread*)); extern void disableSuspend0(Thread *thread, void *stack_top); extern void enableSuspend(Thread *thread); extern void fastEnableSuspend(Thread *thread); extern Thread *attachJNIThread(char *name, char is_daemon, Object *group); extern void detachJNIThread(Thread *thread); extern char *getThreadStateString(Thread *thread); extern Thread *findThreadById(long long id); extern Thread *findRunningThreadByTid(int tid); extern void suspendThread(Thread *thread); extern void resumeThread(Thread *thread); #define disableSuspend(thread) \ { \ sigjmp_buf *env; \ env = alloca(sizeof(sigjmp_buf)); \ sigsetjmp(*env, FALSE); \ disableSuspend0(thread, (void*)env);\ } #define fastDisableSuspend(thread) \ { \ thread->blocking = SUSP_CRITICAL; \ MBARRIER(); \ } typedef struct { pthread_mutex_t lock; pthread_cond_t cv; } VMWaitLock; typedef pthread_mutex_t VMLock; #define initVMLock(lock) pthread_mutex_init(&lock, NULL) #define initVMWaitLock(wait_lock) { \ pthread_mutex_init(&wait_lock.lock, NULL); \ pthread_cond_init(&wait_lock.cv, NULL); \ } #define lockVMLock(lock, self) { \ self->state = BLOCKED; \ pthread_mutex_lock(&lock); \ self->state = RUNNING; \ } #define tryLockVMLock(lock, self) \ (pthread_mutex_trylock(&lock) == 0) #define unlockVMLock(lock, self) if(self) pthread_mutex_unlock(&lock) #define lockVMWaitLock(wait_lock, self) lockVMLock(wait_lock.lock, self) #define unlockVMWaitLock(wait_lock, self) unlockVMLock(wait_lock.lock, self) #define waitVMWaitLock(wait_lock, self) { \ self->state = WAITING; \ pthread_cond_wait(&wait_lock.cv, &wait_lock.lock); \ self->state = RUNNING; \ } #define timedWaitVMWaitLock(wait_lock, self, ms) { \ struct timeval tv; \ struct timespec ts; \ gettimeofday(&tv, 0); \ ts.tv_sec = tv.tv_sec + ms/1000; \ ts.tv_nsec = (tv.tv_usec + ((ms%1000)*1000))*1000; \ if(ts.tv_nsec > 999999999L) { \ ts.tv_sec++; \ ts.tv_nsec -= 1000000000L; \ } \ self->state = TIMED_WAITING; \ pthread_cond_timedwait(&wait_lock.cv, &wait_lock.lock, &ts); \ self->state = RUNNING; \ } #define notifyVMWaitLock(wait_lock, self) pthread_cond_signal(&wait_lock.cv) #define notifyAllVMWaitLock(wait_lock, self) pthread_cond_broadcast(&wait_lock.cv) #endif
30.033654
82
0.642068
[ "object" ]
098384cef3b2eda5214e97a6e11d8a1842ec3d5a
7,253
h
C
lib/marisa/base.h
AdvantechRISC/apq8016_external_marisa-trie
629ed059b1e85cd8e4de363d8b3dc53c15c3e08a
[ "BSD-3-Clause" ]
null
null
null
lib/marisa/base.h
AdvantechRISC/apq8016_external_marisa-trie
629ed059b1e85cd8e4de363d8b3dc53c15c3e08a
[ "BSD-3-Clause" ]
null
null
null
lib/marisa/base.h
AdvantechRISC/apq8016_external_marisa-trie
629ed059b1e85cd8e4de363d8b3dc53c15c3e08a
[ "BSD-3-Clause" ]
null
null
null
#ifndef MARISA_BASE_H_ #define MARISA_BASE_H_ // Visual C++ does not provide stdint.h. #ifndef _MSC_VER #include <stdint.h> #endif // _MSC_VER #ifdef __cplusplus #include <cstddef> #include <new> #else // __cplusplus #include <stddef.h> #endif // __cplusplus #if defined(__ANDROID__) #include <android/log.h> #include <stdio.h> #endif // __ANDROID__ #ifdef __cplusplus extern "C" { #endif // __cplusplus #ifdef _MSC_VER typedef unsigned __int8 marisa_uint8; typedef unsigned __int16 marisa_uint16; typedef unsigned __int32 marisa_uint32; typedef unsigned __int64 marisa_uint64; #else // _MSC_VER typedef uint8_t marisa_uint8; typedef uint16_t marisa_uint16; typedef uint32_t marisa_uint32; typedef uint64_t marisa_uint64; #endif // _MSC_VER #define MARISA_UINT8_MAX ((marisa_uint8)-1) #define MARISA_UINT16_MAX ((marisa_uint16)-1) #define MARISA_UINT32_MAX ((marisa_uint32)-1) #define MARISA_UINT64_MAX ((marisa_uint64)-1) #define MARISA_SIZE_MAX ((size_t)-1) #define MARISA_ZERO_TERMINATED MARISA_UINT32_MAX #define MARISA_NOT_FOUND MARISA_UINT32_MAX #define MARISA_MISMATCH MARISA_UINT32_MAX #define MARISA_MAX_LENGTH (MARISA_UINT32_MAX - 1) #define MARISA_MAX_NUM_KEYS (MARISA_UINT32_MAX - 1) // marisa_status provides a list of error codes. Most of functions in // libmarisa throw or return an error code. typedef enum marisa_status_ { // MARISA_OK means that a requested operation has succeeded. MARISA_OK = 0, // MARISA_HANDLE_ERROR means that a given handle is invalid. MARISA_HANDLE_ERROR = 1, // MARISA_STATE_ERROR means that an object is not ready for a requested // operation. For example, an operation to modify a fixed container throws // an exception with this error code. MARISA_STATE_ERROR = 2, // MARISA_PARAM_ERROR means that a given argument is invalid. For example, // some functions throw an exception with this error code when an // out-of-range value or a NULL pointer is given. MARISA_PARAM_ERROR = 3, // MARISA_SIZE_ERROR means that a size exceeds its limit. This error code // is used when a building dictionary is too large or std::length_error is // catched. MARISA_SIZE_ERROR = 4, // MARISA_MEMORY_ERROR means that a memory allocation has failed. MARISA_MEMORY_ERROR = 5, // MARISA_IO_ERROR means that an I/O failure. MARISA_IO_ERROR = 6, // MARISA_UNEXPECTED_ERROR means that an unexpected error has occurred. MARISA_UNEXPECTED_ERROR = 7 } marisa_status; // marisa_strerror() returns a name of an error code. const char *marisa_strerror(marisa_status status); // Flags and masks for dictionary settings are defined as follows. Please note // that unspecified value/flags will be replaced with default value/flags. typedef enum marisa_flags_ { // A dictionary consinsts of 3 tries in default. If you want to change the // number of tries, please give it with other flags. MARISA_MIN_NUM_TRIES = 0x00001, MARISA_MAX_NUM_TRIES = 0x000FF, MARISA_DEFAULT_NUM_TRIES = 0x00003, // MARISA_PATRICIA_TRIE is usually a better choice. MARISA_PREFIX_TRIE is // provided for comparing prefix/patricia tries. MARISA_PATRICIA_TRIE = 0x00100, MARISA_PREFIX_TRIE = 0x00200, MARISA_DEFAULT_TRIE = MARISA_PATRICIA_TRIE, // There are 3 kinds of TAIL implementations. // - MARISA_WITHOUT_TAIL: // builds a dictionary without a TAIL. Its last trie has only 1-byte // labels. // - MARISA_BINARY_TAIL: // builds a dictionary with a binary-mode TAIL. Its last labels are stored // as binary data. // - MARISA_TEXT_TAIL: // builds a dictionary with a text-mode TAIL if its last labels do not // contain NULL characters. The last labels are stored as zero-terminated // string. Otherwise, a dictionary is built with a binary-mode TAIL. MARISA_WITHOUT_TAIL = 0x01000, MARISA_BINARY_TAIL = 0x02000, MARISA_TEXT_TAIL = 0x04000, MARISA_DEFAULT_TAIL = MARISA_TEXT_TAIL, // libmarisa arranges nodes in ascending order of their labels // (MARISA_LABEL_ORDER) or in descending order of their weights // (MARISA_WEIGHT_ORDER). MARISA_WEIGHT_ORDER is generally a better choice // because it enables faster lookups, but MARISA_LABEL_ORDER is still useful // if an application needs to predict keys in label order. MARISA_LABEL_ORDER = 0x10000, MARISA_WEIGHT_ORDER = 0x20000, MARISA_DEFAULT_ORDER = MARISA_WEIGHT_ORDER, // The default settings. 0 is equivalent to MARISA_DEFAULT_FLAGS. MARISA_DEFAULT_FLAGS = MARISA_DEFAULT_NUM_TRIES | MARISA_DEFAULT_TRIE | MARISA_DEFAULT_TAIL | MARISA_DEFAULT_ORDER, MARISA_NUM_TRIES_MASK = 0x000FF, MARISA_TRIE_MASK = 0x00F00, MARISA_TAIL_MASK = 0x0F000, MARISA_ORDER_MASK = 0xF0000, MARISA_FLAGS_MASK = 0xFFFFF } marisa_flags; #ifdef __cplusplus } // extern "C" #endif // __cplusplus //#include <cstddef> #ifdef __cplusplus namespace marisa { typedef ::marisa_uint8 UInt8; typedef ::marisa_uint16 UInt16; typedef ::marisa_uint32 UInt32; typedef ::marisa_uint64 UInt64; typedef ::marisa_status Status; // An exception object stores a filename, a line number and an error code. class Exception { public: Exception(const char *filename, int line, Status status) : filename_(filename), line_(line), status_(status) {} Exception(const Exception &ex) : filename_(ex.filename_), line_(ex.line_), status_(ex.status_) {} Exception &operator=(const Exception &rhs) { filename_ = rhs.filename_; line_ = rhs.line_; status_ = rhs.status_; return *this; } const char *filename() const { return filename_; } int line() const { return line_; } Status status() const { return status_; } // Same as std::exception, what() returns an error message. const char *what() const { return ::marisa_strerror(status_); } private: const char *filename_; int line_; Status status_; }; // MARISA_THROW adds a filename and a line number to an exception. #if !defined(__ANDROID__) #define MARISA_THROW(status) \ (throw Exception(__FILE__, __LINE__, status)) #else inline int android_log_exception(int status) { char tmpbuf[100]; snprintf(tmpbuf, sizeof(tmpbuf), "marisa exception: %d", status); __android_log_write(ANDROID_LOG_ERROR, "marisa-trie", tmpbuf); return 0; } #define MARISA_THROW(status) \ (android_log_exception(status)) #endif // __ANDROID__ // MARISA_THROW_IF throws an exception with `status' if `cond' is true. #define MARISA_THROW_IF(cond, status) \ (void)((!(cond)) || (MARISA_THROW(status), 0)) // MARISA_DEBUG_IF is used for debugging. For example, MARISA_DEBUG_IF is used // to find out-of-range accesses in marisa::Vector, marisa::IntVector, etc. #ifdef _DEBUG #define MARISA_DEBUG_IF(cond, status) \ MARISA_THROW_IF(cond, status) #else #define MARISA_DEBUG_IF(cond, status) #endif // To not include <algorithm> only for std::swap(). template <typename T> void Swap(T *lhs, T *rhs) { MARISA_THROW_IF((lhs == NULL) || (rhs == NULL), MARISA_PARAM_ERROR); T temp = *lhs; *lhs = *rhs; *rhs = temp; } } // namespace marisa #endif // __cplusplus #endif // MARISA_BASE_H_
30.995726
78
0.730594
[ "object", "vector" ]
099a84e0184c5baf299f117d675812e8ac6f0218
3,813
h
C
SDKs/CryCode/3.8.1/CryEngine/CryAction/Network/ScriptRMI.h
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
4
2017-12-18T20:10:16.000Z
2021-02-07T21:21:24.000Z
SDKs/CryCode/3.8.1/CryEngine/CryAction/Network/ScriptRMI.h
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
null
null
null
SDKs/CryCode/3.8.1/CryEngine/CryAction/Network/ScriptRMI.h
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
3
2019-03-11T21:36:15.000Z
2021-02-07T21:21:26.000Z
/************************************************************************* Crytek Source File. Copyright (C), Crytek Studios, 2001-2004. ------------------------------------------------------------------------- $Id$ $DateTime$ Description: Provides remote method invocation to script ------------------------------------------------------------------------- History: - 30:11:2004 11:30 : Created by Craig Tiller *************************************************************************/ #ifndef __SCRIPTRMI_H__ #define __SCRIPTRMI_H__ #pragma once #include <CryThread.h> #include "ScriptSerialize.h" #include "MultiThread.h" class CGameContext; // this class is a singleton that handles remote method invocation for // script objects class CScriptRMI : private CScriptSerialize { public: CScriptRMI(); bool Init(); void UnloadLevel(); int ExposeClass( IFunctionHandler * pFH ); void SetupEntity( EntityId id, IEntity * pEntity, bool client, bool server ); void RemoveEntity( EntityId id ); INetAtSyncItem * HandleRMI( bool bClient, EntityId objID, uint8 funcID, TSerialize ser, INetChannel * pChannel); bool SerializeScript( TSerialize ser, IEntity * pEntity ); void OnInitClient( uint16 channelId, IEntity * pEntity ); void OnPostInitClient( uint16 channelId, IEntity * pEntity ); void GetMemoryStatistics(ICrySizer * s); void SetContext( CGameContext * pContext ); static void RegisterCVars(); static void UnregisterCVars(); private: enum EDispatchFlags { eDF_ToServer = 0x01, eDF_ToClientOnChannel = 0x02, eDF_ToClientOnOtherChannels = 0x04, }; bool BuildDispatchTable( SmartScriptTable methods, SmartScriptTable methodTableFromCls, SmartScriptTable cls, const char * name ); bool BuildSynchTable( SmartScriptTable vars, SmartScriptTable cls, const char * name ); void AddProxyTable( IScriptTable * pEntityTable, ScriptHandle id, ScriptHandle flags, const char * name, SmartScriptTable dispatchTable ); void AddSynchedTable( IScriptTable * pEntityTable, ScriptHandle id, const char * name, SmartScriptTable metaTable ); static int ProxyFunction( IFunctionHandler* pH, void *pBuffer, int nSize ); static int SynchedNewIndexFunction( IFunctionHandler * pH ); static int SynchedIndexFunction( IFunctionHandler * pH ); static int SerializeFunction( IFunctionHandler * pH, void * pBuffer, int nSize ); class CScriptMessage; class CCallHelper; static void DispatchRMI( INetChannel * pChannel, _smart_ptr<CScriptMessage> pMsg, bool bClient ); CGameContext * m_pParent; static CScriptRMI * m_pThis; struct SFunctionInfo; struct SSynchedPropertyInfo; static const size_t MaxRMIParameters = 31; // must be a multiple of eight minus one static const size_t MaxSynchedPropertyNameLength = 31; // must be a multiple of eight minus one struct SFunctionDispatch { SFunctionDispatch() { format[0] = name[0] = 0; } void GetMemoryUsage(ICrySizer *pSizer) const{} char format[MaxRMIParameters+1]; char name[MaxSynchedPropertyNameLength+1]; }; typedef std::vector<SFunctionDispatch> SFunctionDispatchTable; struct SDispatch { void GetMemoryUsage(ICrySizer *pSizer) const { pSizer->AddObject(server); pSizer->AddObject(client); } SFunctionDispatchTable server; SFunctionDispatchTable client; SmartScriptTable m_serverDispatchScriptTable; SmartScriptTable m_clientDispatchScriptTable; }; bool ValidateDispatchTable( const char * clazz, SmartScriptTable dispatch, SmartScriptTable methods, bool bServerTable ); // everything under here is protected by the following mutex, and is for multithreaded serialization CryCriticalSection m_dispatchMutex; std::map<string, size_t> m_entityClassToEntityTypeID; std::map<EntityId, size_t> m_entities; std::vector<SDispatch> m_dispatch; }; #endif
30.261905
122
0.710202
[ "vector" ]
51bd2e4a5931abf18d5457e2b7a28ad87adb8e4b
6,366
c
C
trans/src/hppa/special.c
dj3vande/tendra
86981ad5574f55821853e3bdf5f82e373f91edb2
[ "BSD-3-Clause" ]
null
null
null
trans/src/hppa/special.c
dj3vande/tendra
86981ad5574f55821853e3bdf5f82e373f91edb2
[ "BSD-3-Clause" ]
null
null
null
trans/src/hppa/special.c
dj3vande/tendra
86981ad5574f55821853e3bdf5f82e373f91edb2
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2011, The TenDRA Project. * Copyright 1997, United Kingdom Secretary of State for Defence. * * See doc/copyright/ for the full copyright terms. */ #include <stdio.h> #include <string.h> #include <shared/bool.h> #include <shared/check.h> #include <shared/error.h> #include <shared/string.h> #include <tdf/nat.h> #include <tdf/shape.h> #include <tdf/tag.h> #include <reader/exp.h> #include <construct/installtypes.h> #include <construct/dec.h> #include <construct/exp.h> #include <construct/machine.h> #include <main/flags.h> #include <main/driver.h> #include <main/print.h> #include <refactor/const.h> #include "procrec.h" #include "translate.h" #include "addr.h" #include "move.h" #include "reg.h" #include "getregs.h" #include "guard.h" #include "code_here.h" #include "inst_fmt.h" #include "hppains.h" #include "labels.h" #include "bits.h" #include "proc.h" #include "frames.h" #include "regexps.h" #include "special.h" /* * these are the procs I could do something about * >0 special, handle inline in specialmake * 0 not special */ static int specno(char * n) { asm_comment("specno(%s)", n); if (streq(n, "___builtin_asm") || streq(n, "___TDF_builtin_asm")) { return 4; } if (streq(n, "___builtin_alloca") || streq(n, "___TDF_builtin_alloca")) { return 5; } return 0; } /* what name to use with call instruction for specials */ char * special_call_name(int i) { switch (i) { case 5: return "_alloca"; default: error(ERR_SERIOUS, "attempting external call to builtin"); return ""; } UNREACHED; } static needs zeroneeds = {0, 0, 0, 0}; /* has no needs */ #if 0 static const needs onefixneeds = {1, 0, 0, 0}; /* one fix reg needs */ static const needs twofixneeds = {2, 0, 0, 0}; /* two fix reg needs */ #endif /* these are the needs for their expansion */ needs specialneeds(int i) { asm_comment("specialneeds(%d,...)", i); switch (i) { case 4: return zeroneeds; /* asm(string) */ case 5: return zeroneeds; /* alloca(n) */ default: asm_comment("specialneeds: unimplemented builtin %d", i); error(ERR_SERIOUS, "unimplemented builtin"); return zeroneeds; } UNREACHED; } /* could I treat this function load specially ? */ int specialfn(exp fn) { if (fn->tag == name_tag && child(fn)->tag == ident_tag && isglob(child(fn)) && child(child(fn)) == NULL) { char *extname = nextg(child(fn))->name; return specno(extname); } return 0; } /* Is a call to this function reason to prohibit optmisation of caller? */ int specialopt(exp fn) { if (fn->tag == name_tag && child(fn)->tag == ident_tag && isglob(child(fn)) && child(child(fn)) == NULL) { char *extname = nextg(child(fn))->name; if (extname == 0) { return 0; } extname += strlen(name_prefix); /* Normalise "_foo" -> "foo" */ asm_comment("specialopt: %s", extname); if ((streq(extname, "vfork")) || (streq(extname, "setjmp")) || (streq(extname, "_setjmp")) || (streq(extname, "sigsetjmp")) ) { asm_comment("specialopt: return 1"); return 1; } } return 0; } int specialmake(int i, exp par, space sp, where dest, int exitlab) { switch (i) { case 4: { /* asm(s) - simply output s */ exp e; char *s; /* "par" is (eval_tag (pack_tag (string_tag no=string-table-index))) */ e = child(child(par)); if (e->tag != string_tag) { error(ERR_SERIOUS, "asm argument not string"); return 0; } s = nostr(e); /* asm is dangerous; as the least precaution, zap register tracking. */ clear_all(); asm_printf("! asm:\n" ); asm_printf( "%s\n", s); break; } case 5: { /* alloca(n) - grow stack frame by n bytes and then grab grab n bytes */ int maxargbytes = max_args >> 3; int dreg; ans aa; dreg = ((discrim(dest.answhere) == inreg) ? regalt(dest.answhere) : getreg(sp.fixed)); if (par->tag == val_tag) { /* n is a constant */ int n = no(par); /* adjust n to be multiple of 64 so stack stays 64 byte aligned */ n = (n + 63) & ~(63); if (n != 0) { /* alloca(n) = %sp - maxargbytes */ if (SIMM14(-maxargbytes)) { ld_ir_ins(i_ldo, cmplt_, fs_, empty_ltrl, -maxargbytes, SP, dreg); } else { ir_ins(i_addil, fs_L, empty_ltrl, -maxargbytes, SP); ld_ir_ins(i_ldo, cmplt_, fs_R, empty_ltrl, -maxargbytes, GR1, dreg); } /* grow stack frame, i.e. %sp -> %sp + n */ if (SIMM14(n)) { ld_ir_ins(i_ldo, cmplt_, fs_, empty_ltrl, n, SP, SP); } else { /* grow stack frame by more than 8192 bytes */ ir_ins(i_addil, fs_L, empty_ltrl, n, SP); ld_ir_ins(i_ldo, cmplt_, fs_R, empty_ltrl, n, GR1, SP); } } } else { int nreg = reg_operand(par, sp); /* adjust nreg so that stack stays 64 byte aligned */ ld_ir_ins(i_ldo, cmplt_, fs_, empty_ltrl, 63, nreg, GR1); riir_ins(i_dep, c_, 0, 31, 6, GR1); /* alloca(n) = %sp - maxargbytes */ if (SIMM14(-maxargbytes)) { ld_ir_ins(i_ldo, cmplt_, fs_, empty_ltrl, -maxargbytes, SP, dreg); } else { ir_ins(i_addil, fs_L, empty_ltrl, -maxargbytes, SP); ld_ir_ins(i_ldo, cmplt_, fs_R, empty_ltrl, -maxargbytes, GR1, dreg); } /* %sp -> %sp + nreg */ rrr_ins(i_add, c_, SP, GR1, SP); } setregalt(aa, dreg); move(aa, dest, guardreg(dreg, sp).fixed, 0); break; } default: asm_comment("specialmake: unimplemented builtin %d", i); error(ERR_SERIOUS, "unimplemented builtin"); return 0; } return exitlab; /* for most cases */ } #define sz_millicode_lib 7 static struct { const char *proc_name; bool called; bool in_library; } millicode_lib [ sz_millicode_lib ] = { { milli_mulU, 0, 1 }, /* $$mulU */ { milli_mulI, 0, 1 }, /* $$mulI */ { milli_divU, 0, 1 }, /* $$mulU */ { milli_divI, 0, 1 }, /* $$divI */ { milli_remU, 0, 1 }, /* $$remU */ { milli_remI, 0, 1 }, /* $$remI */ { milli_dyncall, 0, 1 }, /* $$dyncall */ }; /* * Output a millicode library call */ void call_millicode(int n, int r, char *stub, bool restore_linkage_ptr_reg) { const char *nm = millicode_lib[n].proc_name; millicode_lib[n].called = 1; extj_special_ins(nm, r, stub, 0); if (PIC_code && restore_linkage_ptr_reg) { rr_ins(i_copy, GR5, GR19); } } void import_millicode(void) { int n; for(n = 0; n < sz_millicode_lib; n++) { if (millicode_lib[n].called) { asm_printop(".IMPORT %s,MILLICODE", millicode_lib[n].proc_name); } } }
22.181185
88
0.627396
[ "shape" ]
51c12c8b9cc8b9cd1ad72092b6e06a01b752c2a2
3,845
h
C
Source/Engine/OpenVanilla/OVEventHandlingContext.h
Kent-Liu/McBopomofo
b5bf404225f28612dadebdbb0146dada2bc208ab
[ "MIT" ]
31
2019-05-28T09:08:09.000Z
2022-02-21T02:19:21.000Z
Source/Engine/OpenVanilla/OVEventHandlingContext.h
Kent-Liu/McBopomofo
b5bf404225f28612dadebdbb0146dada2bc208ab
[ "MIT" ]
1
2022-01-12T13:58:03.000Z
2022-01-12T16:20:52.000Z
Source/Engine/OpenVanilla/OVEventHandlingContext.h
Kent-Liu/McBopomofo
b5bf404225f28612dadebdbb0146dada2bc208ab
[ "MIT" ]
19
2019-04-22T09:56:12.000Z
2022-02-27T18:38:40.000Z
// // OVEventHandlingContext.h // // Copyright (c) 2007-2010 Lukhnos D. Liu // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #ifndef OVEventHandlingContext_h #define OVEventHandlingContext_h #if defined(__APPLE__) #include <OpenVanilla/OVBase.h> #include <OpenVanilla/OVCandidateService.h> #include <OpenVanilla/OVStringHelper.h> #include <OpenVanilla/OVTextBuffer.h> #include <OpenVanilla/OVKey.h> #include <OpenVanilla/OVLoaderService.h> #else #include "OVBase.h" #include "OVCandidateService.h" #include "OVStringHelper.h" #include "OVTextBuffer.h" #include "OVKey.h" #include "OVLoaderService.h" #endif namespace OpenVanilla { using namespace std; class OVEventHandlingContext : public OVBase { public: virtual void startSession(OVLoaderService* loaderService) { } virtual void stopSession(OVLoaderService* loaderService) { } virtual void clear(OVLoaderService* loaderService) { stopSession(loaderService); startSession(loaderService); } virtual bool handleKey(OVKey* key, OVTextBuffer* readingText, OVTextBuffer* composingText, OVCandidateService* candidateService, OVLoaderService* loaderService) { return false; } virtual bool handleDirectText(const vector<string>& segments, OVTextBuffer* readingText, OVTextBuffer* composingText, OVCandidateService* candidateService, OVLoaderService* loaderService) { return handleDirectText(OVStringHelper::Join(segments), readingText, composingText, candidateService, loaderService); } virtual bool handleDirectText(const string&, OVTextBuffer* readingText, OVTextBuffer* composingText, OVCandidateService* candidateService, OVLoaderService* loaderService) { return false; } virtual void candidateCanceled(OVCandidateService* candidateService, OVTextBuffer* readingText, OVTextBuffer* composingText, OVLoaderService* loaderService) { } virtual bool candidateSelected(OVCandidateService* candidateService, const string& text, size_t index, OVTextBuffer* readingText, OVTextBuffer* composingText, OVLoaderService* loaderService) { return true; } virtual bool candidateNonPanelKeyReceived(OVCandidateService* candidateService, const OVKey* key, OVTextBuffer* readingText, OVTextBuffer* composingText, OVLoaderService* loaderService) { return false; } virtual const string filterText(const string& inputText, OVLoaderService* loaderService) { return inputText; } }; }; #endif
37.330097
198
0.70091
[ "vector" ]
51e2e40124ced7942e68f6e23c2df62d74f12887
2,044
h
C
src/plume/plumeapi.h
CedricProfit/Sapience
26351ab51fd8c281d54548a2fa56ad415bcdf888
[ "MIT" ]
5
2015-03-30T12:02:00.000Z
2018-06-04T02:04:57.000Z
src/plume/plumeapi.h
CedricProfit/Sapience
26351ab51fd8c281d54548a2fa56ad415bcdf888
[ "MIT" ]
1
2019-06-02T03:41:04.000Z
2019-06-02T03:41:04.000Z
src/plume/plumeapi.h
CedricProfit/Sapience
26351ab51fd8c281d54548a2fa56ad415bcdf888
[ "MIT" ]
5
2015-05-29T13:16:56.000Z
2020-08-29T18:30:33.000Z
// Copyright (c) 2014 The Sapience AIFX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef PLUMEAPI_H #define PLUMEAPI_H #include "dataplume.h" #include "plumecore.h" #include "plumeheader.h" class CPlumeApi { public: CPlumeHeader CreateDataPlume(std::string name, std::string attrOneName, std::string attrTwoName, std::string attrThreeName, int neuralNodesRequested, bool isPublic); uint256 CreateDataReservationRequest(CPlumeHeader header, double kbHours); std::vector<CDataReservationRequest> ListDataReservationRequests(); std::vector<CDataReservationProposal> ListDataReservationProposals(uint256 requestId); std::vector<CDataReservationProposal> ListDataProposalsWaiting(); std::vector<CDataProposalAcceptance> ListProposalsAccepted(); bool AcceptProposal(uint256 proposalId, std::string& err); bool AddRecord(CPlumeDataItem dataItem, std::string& err); std::vector<CDataChunk> GetChunksAvailable(uint256 plumeId); void ClearChunkQueue(uint256 plumeId); bool RequestGetChunk(uint256 plumeId, int64_t chunkStart); bool RequestGet(uint256 infohash); std::vector<uint256> ListDhtGetResponsesAvailable(); bool GetDhtResponse(uint256 infohash, CDhtGetResponse& response); std::vector<CPlumeHeader> ListMyDataPlumes(); std::vector<CPlumeHeader> ListPublicDataPlumes(); std::vector<CPlumeHeader> ListMyServicedDataPlumes(); std::vector<CPlumePeer> ListPlumePeers(); CPlumeHeader GetPlume(uint256 plumeId); CPlumePeer GetPlumePeer(uint256 peerId); bool PreviewPlume(uint256 plumeId, int timeout, CSignedPlumeDataItem& dataItem); std::vector<uint256> GetPlumeInfohashes(uint256 plumeId, int count, int offset, std::string& err); bool GetRecord(uint256 infohash, int timeout, CSignedPlumeDataItem& dataItem, std::string& err); std::vector<uint256> GetLastInfohashes(uint256 plumeId, int count, std::string& err); }; #endif // PLUMEAPI_H
48.666667
169
0.778865
[ "vector" ]
51f610e4c3a56051040416e4f4b9feee84d10981
16,641
c
C
third-party/casadi/external_packages/DSDP/src/sdp/dsdpblock.c
dbdxnuliba/mit-biomimetics_Cheetah
f3b0c0f6a3835d33b7f2f345f00640b3fc256388
[ "MIT" ]
8
2020-02-18T09:07:48.000Z
2021-12-25T05:40:02.000Z
third-party/casadi/external_packages/DSDP/src/sdp/dsdpblock.c
geekfeiw/Cheetah-Software
f3b0c0f6a3835d33b7f2f345f00640b3fc256388
[ "MIT" ]
null
null
null
third-party/casadi/external_packages/DSDP/src/sdp/dsdpblock.c
geekfeiw/Cheetah-Software
f3b0c0f6a3835d33b7f2f345f00640b3fc256388
[ "MIT" ]
13
2019-08-25T12:32:06.000Z
2022-03-31T02:38:12.000Z
#include "dsdpsdp.h" #include "dsdpsys.h" static int sdpvecvecevent=0,sdpdotevent=0; /*! \file dsdpblock.c \brief Operations on a single SDP block. */ #undef __FUNCT__ #define __FUNCT__ "DSDPBlockASum" /*! \fn int DSDPBlockASum(DSDPBlockData *ADATA, double aa, DSDPVec Yk, DSDPVMat XX){ \brief Sum the data matrices. \param ADATA block of data. \param aa scalar \param Yk scalar. \param XX equals aa * sum ( YK[i]* A[i] ) */ int DSDPBlockASum(DSDPBlockData *ADATA, double aa, DSDPVec Yk, DSDPVMat XX){ double *xx,ytmp,scl=ADATA->scl; int ii,vari,n,nn,info; DSDPFunctionBegin; info=DSDPVMatGetSize(XX, &n); DSDPCHKERR(info); info=DSDPVMatGetArray(XX, &xx, &nn); DSDPCHKERR(info); for (ii=0;ii<ADATA->nnzmats;ii++){ vari=ADATA->nzmat[ii]; info=DSDPVecGetElement(Yk,vari,&ytmp);DSDPCHKVARERR(vari,info); if (ytmp==0) continue; info = DSDPDataMatAddMultiple(ADATA->A[ii], -aa*scl*ytmp, xx,nn,n); DSDPCHKVARERR(vari,info); } info=DSDPVMatRestoreArray(XX, &xx, &nn); DSDPCHKERR(info); DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPBlockADot" /*! \fn int DSDPBlockADot(DSDPBlockData *ADATA, double aa, DSDPVec Alpha, DSDPVMat X, DSDPVec AX){ \brief Compute inner product of XX with data matrices. \param ADATA block of data. \param aa scalar \param Alpha scalar. \param X Dense symmetric matrix \param AX Set AX[i] to aa * Alpha[i] * Dot( A[i] * X) */ int DSDPBlockADot(DSDPBlockData *ADATA, double aa, DSDPVec Alpha, DSDPVMat X, DSDPVec AX){ int ii,vari,n,nn,info; double *x,sum=0,aalpha=0,scl=ADATA->scl; DSDPFunctionBegin; DSDPEventLogBegin(sdpdotevent); info=DSDPVMatScaleDiagonal(X,0.5); DSDPCHKERR(info); info=DSDPVMatGetSize(X, &n); DSDPCHKERR(info); info=DSDPVMatGetArray(X, &x, &nn); DSDPCHKERR(info); for (ii=0;ii<ADATA->nnzmats; ii++){ /* Matrix Entries */ vari=ADATA->nzmat[ii]; info=DSDPVecGetElement(Alpha,vari,&aalpha);DSDPCHKVARERR(vari,info); if (aalpha==0.0) continue; info=DSDPDataMatDot(ADATA->A[ii],x,nn,n,&sum);DSDPCHKVARERR(vari,info); info=DSDPVecAddElement(AX,vari,aa*aalpha*sum*scl);DSDPCHKVARERR(vari,info); } info=DSDPVMatRestoreArray(X, &x, &nn); DSDPCHKERR(info); info=DSDPVMatScaleDiagonal(X,2.0); DSDPCHKERR(info); DSDPEventLogEnd(sdpdotevent); DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPBlockvAv" /*! \fn int int DSDPBlockvAv(DSDPBlockData *ADATA, double aa, DSDPVec Alpha, SDPConeVec V, DSDPVec VAV){ \brief Set VAV[i] to aa * Alpha[i] * V' A[i] V \param ADATA block of data. \param aa scalar \param Alpha scalar. \param V vecotr \param VAV the product */ int DSDPBlockvAv(DSDPBlockData *ADATA, double aa, DSDPVec Alpha, SDPConeVec V, DSDPVec VAV){ int ii,vari,info; double sum=0,aalpha=0,scl=ADATA->scl; DSDPFunctionBegin; DSDPEventLogBegin(sdpvecvecevent); if (aa==0){DSDPFunctionReturn(0);} for (ii=0;ii<ADATA->nnzmats; ii++){ /* Matrix Entries */ vari=ADATA->nzmat[ii]; info=DSDPVecGetElement(Alpha,vari,&aalpha);DSDPCHKVARERR(vari,info); if (aalpha==0.0) continue; info=DSDPDataMatVecVec(ADATA->A[ii],V,&sum);DSDPCHKVARERR(vari,info); info=DSDPVecAddElement(VAV,vari,aa*aalpha*sum*scl);DSDPCHKVARERR(vari,info); } DSDPEventLogEnd(sdpvecvecevent); DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPBlockFactorData" /*! \fn int DSDPBlockFactorData(DSDPBlockData *ADATA, DSDPVMat X, SDPConeVec W){ \brief Factor the data matrices \param ADATA block of data. \param X work array \param W Work vector */ int DSDPBlockFactorData(DSDPBlockData *ADATA, DSDPVMat X, SDPConeVec W){ int ii,vari,n,nn,info,*iwork3n,i13,n26; double *x,*dwork3n; DSDPDataMat AA; DSDPFunctionBegin; info=DSDPVMatGetSize(X, &n); DSDPCHKERR(info); i13=13*n+1;n26=26*n+1; DSDPCALLOC2(&dwork3n,double,n26,&info);DSDPCHKERR(info); DSDPCALLOC2(&iwork3n,int,i13,&info);DSDPCHKERR(info); info=DSDPVMatGetArray(X, &x, &nn); DSDPCHKERR(info); for (ii=0;ii<ADATA->nnzmats; ii++){ /* Matrix Entries */ info=DSDPBlockGetMatrix(ADATA,ii,&vari,0,&AA);DSDPCHKVARERR(vari,info); DSDPLogInfo(0,39,"SDP Data Mat Setup: %d\n",vari); if (vari==0) continue; info=DSDPDataMatFactor(AA,W,x,nn,dwork3n,n26,iwork3n,i13); DSDPCHKVARERR(vari,info); } info=DSDPVMatRestoreArray(X, &x, &nn); DSDPCHKERR(info); DSDPFREE(&dwork3n,&info);DSDPCHKERR(info); DSDPFREE(&iwork3n,&info);DSDPCHKERR(info); DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPBlockEventZero" int DSDPBlockEventZero(void){ DSDPFunctionBegin; sdpvecvecevent=0;sdpdotevent=0; DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPBlockEventInitialize" int DSDPBlockEventInitialize(void){ DSDPFunctionBegin; if (sdpvecvecevent==0){DSDPEventLogRegister("SDP VecMatVec",&sdpvecvecevent);} if (sdpdotevent==0){DSDPEventLogRegister("SDP Dot",&sdpdotevent);} DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPBlockDataInitialize" /*! \fn int DSDPBlockDataInitialize(DSDPBlockData *ADATA){ \brief Set pointers to null. \param ADATA block of data. */ int DSDPBlockDataInitialize(DSDPBlockData *ADATA){ DSDPFunctionBegin; ADATA->nnzmats=0; ADATA->maxnnzmats=0; ADATA->nzmat=0; ADATA->A=0; ADATA->r=1.0; ADATA->scl=1.0; /* ADATA->n=0; */ DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPBlockTakeDownData" /*! \fn int DSDPBlockTakeDownData(DSDPBlockData *ADATA){ \brief Free structures in block of data. \param ADATA block of data. */ int DSDPBlockTakeDownData(DSDPBlockData *ADATA){ DSDPFunctionBegin; DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPBlockDataDestroy" /*! \fn int DSDPBlockDataDestroy(DSDPBlockData *ADATA); \brief Free the data matrices \param ADATA block of data. */ int DSDPBlockDataDestroy(DSDPBlockData *ADATA){ int ii,vari,info; DSDPFunctionBegin; if (!ADATA){DSDPFunctionReturn(0);} DSDPLogInfo(0,18,"Destroying All Existing Data Matrices \n"); for (ii=0; ii<ADATA->nnzmats; ii++){ vari=ADATA->nzmat[ii]; info = DSDPDataMatDestroy(&ADATA->A[ii]);DSDPCHKVARERR(vari,info); ADATA->nzmat[ii]=0; } ADATA->nnzmats=0; info=DSDPBlockTakeDownData(ADATA);DSDPCHKERR(info); DSDPFREE(&ADATA->nzmat,&info);DSDPCHKERR(info); DSDPFREE(&ADATA->A,&info);DSDPCHKERR(info); info=DSDPBlockDataInitialize(ADATA);DSDPCHKERR(info); DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPBlockDataAllocate" /*! \fn int DSDPBlockDataAllocate(DSDPBlockData *ADATA, int nnz); \brief Allocate some structures. \param ADATA block of data. \param nnz number of data matrices to allocate space */ int DSDPBlockDataAllocate(DSDPBlockData *ADATA, int nnz){ int j,info,*nzmat; DSDPDataMat *A; DSDPFunctionBegin; if (!ADATA){DSDPFunctionReturn(0);} if (nnz<=ADATA->maxnnzmats){DSDPFunctionReturn(0);} DSDPLogInfo(0,18,"REALLOCATING SPACE FOR %d SDP BLOCK MATRICES! Previously allocated: %d \n",nnz,ADATA->maxnnzmats); DSDPCALLOC2(&A,struct DSDPDataMat_C,nnz,&info);DSDPCHKERR(info); DSDPCALLOC2(&nzmat,int,nnz,&info);DSDPCHKERR(info); for (j=0;j<nnz;j++){nzmat[j]=0;} for (j=0;j<nnz;j++){info = DSDPDataMatInitialize(&A[j]);DSDPCHKERR(info);} if (ADATA->maxnnzmats>0){ for (j=0;j<ADATA->nnzmats;j++){nzmat[j]=ADATA->nzmat[j];} for (j=0;j<ADATA->nnzmats;j++){A[j]=ADATA->A[j];} DSDPFREE(&ADATA->A,&info);DSDPCHKERR(info); DSDPFREE(&ADATA->nzmat,&info);DSDPCHKERR(info); } else { ADATA->nnzmats=0; } ADATA->maxnnzmats=nnz; ADATA->nzmat=nzmat; ADATA->A=A; DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPBlockDataMarkNonzeroMatrices" /*! \fn int DSDPBlockDataMarkNonzeroMatrices(DSDPBlockData *ADATA, int *annz){ \brief Mark which variable in block have a data matrix. \param ADATA block of data. \param annz array of integers to mark. */ int DSDPBlockDataMarkNonzeroMatrices(DSDPBlockData *ADATA,int*annz){ int i; DSDPFunctionBegin; for (i=0; i<ADATA->nnzmats; i++){ annz[ADATA->nzmat[i]]++; } DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPBlockCountNonzerosMatrices" /*! \fn int DSDPBlockCountNonzeroMatrices(DSDPBlockData *ADATA,int*nzmats); \brief Count how many data matrices are in a block of data. \param ADATA block of data. \param nzmats set to number of nonzero matrices. Numbers from 0 to this number can be used as a matrix id in DSDPBlockGetMatrix() */ int DSDPBlockCountNonzeroMatrices(DSDPBlockData *ADATA,int*nzmats){ DSDPFunctionBegin; *nzmats=ADATA->nnzmats; DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPBlockDataRank" int DSDPBlockDataRank(DSDPBlockData *ADATA, int *trank, int n){ int ii,vari,info,ri,r2=0; DSDPDataMat AA; DSDPFunctionBegin; for (ii=0;ii<ADATA->nnzmats;ii++){ info=DSDPBlockGetMatrix(ADATA,ii,&vari,0,&AA);DSDPCHKVARERR(vari,info); if (vari==0) continue; info=DSDPDataMatGetRank(AA,&ri,n); DSDPCHKVARERR(vari,info); r2+=ri; } *trank=r2; DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPBlockGetMatrix" /*! \fn int DSDPBlockGetMatrix(DSDPBlockData *ADATA,int id, int *vari, double *scl, DSDPDataMat *A); \brief Get a data matrix from a block of data. \param ADATA block of data. \param id identfier of the matrices, numbered consecutively from 0. \param vari set to variable number corresponding to A. \param scl scaling \param A data matrix. */ int DSDPBlockGetMatrix(DSDPBlockData *ADATA,int id, int *vari, double *scl, DSDPDataMat *A){ DSDPFunctionBegin; if (id>=0 && id < ADATA->nnzmats){ if (vari) *vari=ADATA->nzmat[id]; if (scl) *scl=ADATA->scl; if (A) *A=ADATA->A[id]; } else { DSDPSETERR2(2,"Invalid Matrix request. 0 <= %d < %d\n",id,ADATA->nnzmats); } DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPBlockDataRowSparsity" /*! \fn int DSDPBlockDataRowSparsity(DSDPBlockData *ADATA,int row, int ai[], int rnnz[],int n); \brief Determine sparsity pattern of data. \param ADATA block of data. \param row from 0 to n. \param ai (input) array of ones and zeros that identify which data matrices to check. \param rnnz (output) array of length m where nonzeros indicate nonzero data. \param n dimension of block. */ int DSDPBlockDataRowSparsity(DSDPBlockData *ADATA,int row, int ai[], int rnnz[],int n){ int info,i,vari,rn; DSDPFunctionBegin; if (ai){ for (i=0; i<ADATA->nnzmats; i++){ vari=ADATA->nzmat[i]; if (ai[vari]==0){continue;} info=DSDPDataMatGetRowNonzeros(ADATA->A[i],row, n, rnnz, &rn); DSDPCHKVARERR(vari,info); } } DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPBlockRemoveDataMatrix" /*! \fn int DSDPBlockRemoveDataMatrix(DSDPBlockData *ADATA, int vari); \brief Remove a data matrix. \param ADATA block of data. \param vari variable corresponding the matrix. */ int DSDPBlockRemoveDataMatrix(DSDPBlockData *ADATA,int vari){ int info,ii,k; DSDPFunctionBegin; for (ii=0;ii<ADATA->nnzmats;ii++){ if (ADATA->nzmat[ii]==vari){ info=DSDPDataMatDestroy(&ADATA->A[ii]);DSDPCHKVARERR(vari,info); info=DSDPSetDataMatZero(&ADATA->A[ii]);DSDPCHKVARERR(vari,info); for (k=ii;k<ADATA->nnzmats;k++){ ADATA->A[k]=ADATA->A[k+1]; ADATA->nzmat[k]=ADATA->nzmat[k+1]; } ADATA->nnzmats--; info=DSDPSetDataMatZero(&ADATA->A[ADATA->nnzmats]);DSDPCHKERR(info); DSDPFunctionReturn(0); } } DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPBlockAddDataMatrix" /*! \fn int DSDPBlockAddDataMatrix(DSDPBlockData *ADATA,int vari, struct DSDPDataMat_Ops* dsdpdataops, void* data){ \brief Add data matrix into SDP block \param ADATA block of data. \param vari the variable to which the matrix corresponds. \param dsdpdataops function pointers \param data opaque pointer to matrix. */ int DSDPBlockAddDataMatrix(DSDPBlockData *ADATA,int vari, struct DSDPDataMat_Ops* dsdpdataops, void* data){ int info,ii; DSDPFunctionBegin; if (ADATA->nnzmats>=ADATA->maxnnzmats){ info=DSDPBlockDataAllocate(ADATA,2*ADATA->maxnnzmats+7);DSDPCHKERR(info); } ii=ADATA->nnzmats; info=DSDPDataMatDestroy(&ADATA->A[ii]);DSDPCHKERR(info); info=DSDPDataMatSetData(&ADATA->A[ii], dsdpdataops, data);DSDPCHKVARERR(vari,info); ADATA->nzmat[ii]=vari; ADATA->nnzmats++; DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPBlockSetDataMatrix" /*! \fn int DSDPBlockSetDataMatrix(DSDPBlockData *ADATA,int vari, struct DSDPDataMat_Ops* dsdpdataops, void* data){ \brief Set data matrix into SDP block \param ADATA block of data. \param vari the variable to which the matrix corresponds. \param dsdpdataops function pointers \param data opaque pointer to matrix. */ int DSDPBlockSetDataMatrix(DSDPBlockData *ADATA,int vari, struct DSDPDataMat_Ops* dsdpdataops, void* data){ int info; DSDPFunctionBegin; info=DSDPBlockRemoveDataMatrix(ADATA,vari);DSDPCHKERR(info); info=DSDPBlockAddDataMatrix(ADATA,vari,dsdpdataops,data);DSDPCHKERR(info); DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPBlockNorm2" int DSDPBlockNorm2(DSDPBlockData *ADATA, int n){ double fn2,tt=0; int ii,info; DSDPFunctionBegin; for (ii=0;ii<ADATA->nnzmats;ii++){ info=DSDPDataMatFNorm2(ADATA->A[ii],n,&fn2); DSDPCHKERR(info); tt+=fn2; } DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPBlockANorm2" int DSDPBlockANorm2(DSDPBlockData *ADATA, DSDPVec ANorm2, int n){ double fn2,scl=ADATA->scl; int ii,vari,info; DSDPFunctionBegin; info=DSDPBlockNorm2(ADATA,n);DSDPCHKERR(info); scl=ADATA->scl; for (ii=0;ii<ADATA->nnzmats;ii++){ vari=ADATA->nzmat[ii]; info=DSDPDataMatFNorm2(ADATA->A[ii],n,&fn2); DSDPCHKVARERR(vari,info); info=DSDPVecAddElement(ANorm2,vari,fn2*scl);DSDPCHKVARERR(vari,info); } DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPBlockView" /*! \fn int DSDPBlockView(DSDPBlockData *ADATA); \brief Print the structure of the block. \param ADATA block of data. */ int DSDPBlockView(DSDPBlockData *ADATA){ int ii,kk; DSDPFunctionBegin; for (ii=0;ii<ADATA->nnzmats;ii++){ kk=ADATA->nzmat[ii]; if (kk==0){ printf("+ C\n");} else { printf(" - A[%d] y%d\n",kk,kk);} } printf(" = S >= 0\n"); DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPBlockView2" /*! \fn int DSDPBlockView2(DSDPBlockData *ADATA); \brief Print the data \param ADATA block of data. */ int DSDPBlockView2(DSDPBlockData *ADATA){ int ii,vari,info; DSDPFunctionBegin; for (ii=0;ii<ADATA->nnzmats;ii++){ vari=ADATA->nzmat[ii]; printf("A[%d] y%d \n",vari,vari); info=DSDPDataMatView(ADATA->A[ii]); DSDPCHKERR(info); } DSDPFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DSDPDataMatCheck" /*! \fn int DSDPDataMatCheck(DSDPDataMat AA, SDPConeVec W, DSDPIndex IS, DSDPVMat XX); \brief Check correctness of operations on the data. \param AA data matrix. \param W work vector \param IS work array \param XX work array */ int DSDPDataMatCheck(DSDPDataMat AA, SDPConeVec W, DSDPIndex IS, DSDPVMat XX){ double *xx,ack,vAv=0,esum=0,sum,eignorm,fnorm22,dnorm,scl=1; int k,n,nn,rank,info; DSDPFunctionBegin; info=SDPConeVecGetSize(W,&n);DSDPCHKERR(info); info=DSDPVMatZeroEntries(XX);DSDPCHKERR(info); info=DSDPDataMatGetRank(AA,&rank,n);DSDPCHKERR(info); for (k=0; k<rank; k++){ info=DSDPDataMatGetEig(AA,k,W,IS,&ack); DSDPCHKERR(info); info=SDPConeVecDot(W,W,&eignorm);DSDPCHKERR(info); info=DSDPVMatAddOuterProduct(XX,scl*ack,W);DSDPCHKERR(info); info=DSDPDataMatVecVec(AA,W,&sum);DSDPCHKERR(info); vAv+=ack*ack*eignorm*eignorm*scl; } info=DSDPDataMatFNorm2(AA,n,&fnorm22); DSDPCHKERR(info); info=DSDPVMatScaleDiagonal(XX,0.5); DSDPCHKERR(info); info=DSDPVMatGetArray(XX, &xx, &nn); DSDPCHKERR(info); info=DSDPDataMatDot(AA,xx,nn,n,&esum);DSDPCHKERR(info); info=DSDPVMatRestoreArray(XX, &xx, &nn); DSDPCHKERR(info); info=DSDPVMatScaleDiagonal(XX,2.0); DSDPCHKERR(info); info=DSDPVMatGetArray(XX, &xx, &nn); DSDPCHKERR(info); info=DSDPDataMatAddMultiple(AA,-1.0,xx,nn,n); DSDPCHKERR(info); info=DSDPVMatRestoreArray(XX, &xx, &nn); DSDPCHKERR(info); if (0==1){info=DSDPVMatView(XX);DSDPCHKERR(info);} info=DSDPVMatNormF2(XX,&dnorm); DSDPCHKERR(info); printf(" %4.4e, %4.4e %4.4e\n",esum,vAv,fnorm22); printf(" error1: %4.4e, error2: %4.4e, error3: %4.4e\n",sqrt(dnorm),fabs(esum-vAv),fabs(fnorm22-vAv)); if (dnorm>1) printf("Check Add or eigs\n"); if (fabs(esum-vAv) > 1.0) printf("Check vAv \n"); if (fabs(fnorm22-vAv) > 1.0) printf("Check fnorm22\n"); DSDPFunctionReturn(0); }
30.988827
130
0.721351
[ "vector" ]
51f913d7aea3d889beb9c321c10380baf9242072
288
h
C
Example/HFDownloadManager/HFTableViewCell.h
CoderHFZhu/HFDownloadManager
2a23f6c3ebb890c1d64afe919daf771b0d7ecea5
[ "Apache-2.0" ]
1
2017-11-18T09:16:33.000Z
2017-11-18T09:16:33.000Z
Example/HFDownloadManager/HFTableViewCell.h
CoderHFZhu/HFDownloadManager
2a23f6c3ebb890c1d64afe919daf771b0d7ecea5
[ "Apache-2.0" ]
null
null
null
Example/HFDownloadManager/HFTableViewCell.h
CoderHFZhu/HFDownloadManager
2a23f6c3ebb890c1d64afe919daf771b0d7ecea5
[ "Apache-2.0" ]
null
null
null
// // HFTableViewCell.h // HFDownloadManager // // Created by zack on 2017/3/29. // Copyright © 2017年 zack. All rights reserved. // #import <UIKit/UIKit.h> @class HFModel; @interface HFTableViewCell : UITableViewCell /** <#属性解释#>*/ @property (nonatomic ,strong) HFModel *model; @end
19.2
48
0.694444
[ "model" ]
a40946d886069a99d82f908bd1d2216abe718bfa
3,261
h
C
dbj++/util/dbj_string_compare.h
dbj-systems/dbj-laboratorium
ea497f9b68b78797d11bdc41b0f23a310c9325a9
[ "CC0-1.0" ]
2
2019-09-22T12:13:20.000Z
2019-10-24T04:17:33.000Z
dbj++/util/dbj_string_compare.h
dbj-systems/dbj-laboratorium
ea497f9b68b78797d11bdc41b0f23a310c9325a9
[ "CC0-1.0" ]
9
2019-03-06T06:52:56.000Z
2021-06-14T16:54:11.000Z
dbj++/util/dbj_string_compare.h
dbj-systems/dbj-laboratorium
ea497f9b68b78797d11bdc41b0f23a310c9325a9
[ "CC0-1.0" ]
1
2019-10-18T14:16:27.000Z
2019-10-18T14:16:27.000Z
#pragma once namespace dbj { /* 2018-04-30 dbj@dbj.org -- created basically as a C code */ extern "C" { /* *Entry: * const char *_string1 = pointer to beginning of the first string * const char *s1e = pointer past end of the first string * const char *_string2 = pointer to beginning of the second string * const char *_end2 = pointer past end of the second string * *Exit: * Less than 0 = first string less than second string * 0 = strings are equal * Greater than 0 = first string greater than second string */ inline int __cdecl dbj_ordinal_compareA( const char *_string1, const char *_end1, const char *_string2, const char *_end2) { const int n1 = (int)((_end1 - _string1)); const int n2 = (int)((_end2 - _string2)); const int ans = memcmp(_string1, _string2, n1 < n2 ? n1 : n2); const int ret = (ans != 0 || n1 == n2 ? ans : n1 < n2 ? -1 : +1); return ret; } inline int __cdecl dbj_ordinal_compareW( const wchar_t *_string1, const wchar_t *_end1, const wchar_t *_string2, const wchar_t *_end2) { const int n1 = (int)((_end1 - _string1)); const int n2 = (int)((_end2 - _string2)); const int ans = wmemcmp(_string1, _string2, n1 < n2 ? n1 : n2); const int ret = (ans != 0 || n1 == n2 ? ans : n1 < n2 ? -1 : +1); return ret; } /* must free the result */ inline char * dbj_lowerize_stringA(const char * the_str_) { _ASSERTE(the_str_); char * dup = _strdup(the_str_); _ASSERTE(dup); const size_t sze_ = strlen(dup); size_t cnt_ = 0; do { dup[cnt_] = (char)tolower(dup[cnt_]); } while (cnt_++ < sze_); return dup; } /* must free the result */ inline wchar_t * dbj_lowerize_stringW(const wchar_t * the_str_) { _ASSERTE(the_str_); wchar_t * dup = _wcsdup(the_str_); _ASSERTE(dup); const size_t sze_ = wcslen(dup); size_t cnt_ = 0; do { dup[cnt_] = towlower(dup[cnt_]); } while (cnt_++ < sze_); return dup; } /// <summary> /// ordinal comparison of two ascii null terminated strings /// </summary> inline bool dbj_ordinal_string_compareA(const char * str1, const char * str2, unsigned char ignore_case) { // much faster, does not transform input strings first typedef int(*char_trans)(int); char_trans transformer; if (ignore_case) transformer = dbj::str::tolower; else transformer = dbj::str::just_copy_char; size_t index_ = 0; while ( str1[index_] && str2[index_]) { if (transformer(str1[index_]) != transformer(str2[index_])) return false; ++index_; } return true; } /// <summary> /// ordinal comparions of two unicode null terminated strings /// </summary> inline bool dbj_ordinal_string_compareW(const wchar_t * str1, const wchar_t * str2, unsigned char ignore_case) { typedef wint_t(*char_trans)(wint_t); char_trans transformer; if (ignore_case) transformer = towlower; else transformer = dbj::str::just_copy_wchar; size_t index_ = 0; while (str1[index_] && str2[index_]) { if (transformer(str1[index_]) != transformer(str2[index_])) return false; ++index_; } return true; } } // extern "C" } // dbj /* inclusion of this file defines the kind of a licence used */ #include "../dbj_license.h"
24.518797
113
0.648574
[ "transform" ]
a4159eb3bed97469fbb837e2257ca224a8810abd
7,508
h
C
glwidget.h
axell-brendow/opengl-3d-visualizer
b016e673324e7568d2fc3ddff53844c8021a307b
[ "MIT" ]
1
2020-11-28T21:20:59.000Z
2020-11-28T21:20:59.000Z
glwidget.h
axell-brendow/opengl-3d-visualizer
b016e673324e7568d2fc3ddff53844c8021a307b
[ "MIT" ]
null
null
null
glwidget.h
axell-brendow/opengl-3d-visualizer
b016e673324e7568d2fc3ddff53844c8021a307b
[ "MIT" ]
null
null
null
#ifndef GLWIDGET_H #define GLWIDGET_H #include <iostream> #include <fstream> #include <limits> #include <QtOpenGL> #include "camera.h" #include "light.h" #include "material.h" #include "trackball.h" class GLWidget : public QGLWidget { /** * @brief Tells Meta Object Compiler (MOC) that this class need to be translated * to a normal C++ class because it contains signals, slots and other * features from Qt framework. */ Q_OBJECT public: /** * @brief Initializes GLWidget parent class and internal fields. * * @param parent Parent widget. */ explicit GLWidget(QWidget *parent = nullptr); /** * @brief Destroy the GLWidget object releasing VBOs and shaders. */ virtual ~GLWidget(); protected: /** * @brief Load and active textures and start main loop using a timer. */ void initializeGL(); /** * @brief Resize projection matrix when widget resizes. * * @param width new widget width. * @param height new widget height. */ void resizeGL(int width, int height); /** * @brief Renders the object including light calculations. */ void paintGL(); /** * @brief Track the mouse movements to properly rotate the object when user * click and drag. */ void mouseMoveEvent ( QMouseEvent * event ); /** * @brief Track the mouse movements and rotate the object. */ void mousePressEvent ( QMouseEvent * event ); /** * @brief Stop tracking the mouse movements. */ void mouseReleaseEvent ( QMouseEvent * event ); /** * @brief Change zoom rate. */ void wheelEvent ( QWheelEvent * event ); /** * @brief Change shaders and textures. * * Press 0 to use Gouraud shading. * * Press 1 to use Phong shading. * * Press 2 to use Phong shading + texture. * * Press 3 to use normal mapping. */ void keyPressEvent ( QKeyEvent * event ); private: /** * @brief Flag that indicates if the GLWidget background is black or not */ bool bgBlack; /** * @brief Number of vertices of the .off object */ unsigned int numVertices; /** * @brief Number of faces of the .off object */ unsigned int numFaces; /** * @brief Array of the vertices of the .off object */ QVector4D *vertices; /** * @brief Array of the normals of the vertices relative to their faces. */ QVector3D *normals; /** * @brief Array of the texture coordinates. */ QVector2D *texCoords; /** * @brief Array of the tangents between the object and its vertices. */ QVector4D *tangents; /** * @brief Array of the indices of the vertices of each face. */ unsigned int *indices; /** * @brief Array of Vertex Buffer Objects (VBOs) for the vertices. */ QGLBuffer * vboVertices ; /** * @brief Array of Vertex Buffer Objects (VBOs) for the vertices normals. */ QGLBuffer * vboNormals ; /** * @brief Array of Vertex Buffer Objects (VBOs) for the texture coordinates. */ QGLBuffer * vboTexCoords ; /** * @brief Array of Vertex Buffer Objects (VBOs) for the vertices tangents. */ QGLBuffer * vboTangents ; /** * @brief Array of Vertex Buffer Objects (VBOs) for the indices * of the vertices of each face. */ QGLBuffer * vboIndices ; /** * @brief Array of Vertex Shader that will handle vertex lightning and * texture calculations. */ QGLShader * vertexShader ; /** * @brief Array of Fragment Shader that will handle pixels lightning and * texture calculations between vertices. */ QGLShader * fragmentShader ; /** * @brief This program receives the shaders it needs to run in your GPU * and run them for each vertex or pixel. */ QGLShaderProgram * shaderProgram ; /** * @brief Number that will select which shader the user wants to use. */ unsigned int currentShader ; /** * @brief Store each texture ID returned by glBindTexture. */ int texID [2]; /** * @brief Matrix that represents the Model to World and World to View * transformations (translation, rotation and scaling). To transform the * object, the shader multiplies each object pixel by this matrix. */ QMatrix4x4 modelViewMatrix ; /** * @brief Matrix that represents the View to Projection transformation (3D to 2D). * To transform the object, the shader multiplies each object pixel by this matrix. */ QMatrix4x4 projectionMatrix ; /** * @brief Camera object that contains the eye position and the lookAt position. * Basically this indicates that your eye is at X and you want to look to Y. */ Camera camera ; /** * @brief Light object that has the position of the light, the multiplication * factor of the ambient, the multiplication factor of diffusion (light strikes * and reflects in multiple directions) and the multiplication factor of specular * highlight. */ Light light ; /** * @brief Material object that has the multiplication factor of the ambient, the * multiplication factor of diffusion (light strikes and reflects in multiple * directions), the multiplication factor of specular highlight and the shininess. */ Material material ; /** * @brief Class that handles rotation based on mouse movement. */ TrackBall trackBall ; /** * @brief Zoom percentage */ double zoom; /** * @brief Would store FPS count. But this is not being used. */ int fpsCounter; /** * @brief Used to paint the scene forever. */ QTimer timer; /** * @brief Change current shader. * @param shaderIndex */ void useShader(int shaderIndex); /** * @brief Change current texture. * @param textureIndex */ void useTexture(int textureIndex); /** * @brief Read uncolored .off objects with triangular faces. * * @param fileName .off filename. */ void readOFFFile(const QString &fileName); /** * @brief Calculate the normals for each vertex in its face. */ void genNormals(); /** * @brief Calculate the texture coordinates for each vertex in its face. */ void genTexCoordsCylinder () ; /** * @brief Calculate the tangents for each vertex in its face. */ void genTangents () ; /** * @brief Create the Vertex Buffer Objects (VBOs) for each vertex, normal, * texture, tangent and index. */ void createVBOs () ; /** * @brief Destroy the Vertex Buffer Objects (VBOs). */ void destroyVBOs () ; /** * @brief Create all shaders for vertices and fragments. */ void createShaders () ; /** * @brief Destroy all shaders. */ void destroyShaders () ; QPointF pixelPosToViewPos ( const QPointF &p); signals: // void takeScreenshot(); void statusBarMessage(QString ns); public slots: void toggleBackgroundColor(); void showOpenFileDialog(); void useShader0(); void useShader1(); void useShader2(); void useShader3(); void useTexture0(); void useTexture1(); void useTexture2(); void useTexture3(); void useTexture4(); void animate(); }; #endif // GLWIDGET_H
26.624113
87
0.62147
[ "object", "model", "transform", "3d" ]
f8f14921a9adeaee0792be547cc1b570edafe68e
1,873
h
C
src/esp/assets/BaseMesh.h
funky23exe/habitat-sim
a72ba43593a57995972ba1521f6f7a20d122761c
[ "MIT" ]
1
2020-05-02T09:07:59.000Z
2020-05-02T09:07:59.000Z
src/esp/assets/BaseMesh.h
funky23exe/habitat-sim
a72ba43593a57995972ba1521f6f7a20d122761c
[ "MIT" ]
null
null
null
src/esp/assets/BaseMesh.h
funky23exe/habitat-sim
a72ba43593a57995972ba1521f6f7a20d122761c
[ "MIT" ]
null
null
null
// Copyright (c) Facebook, Inc. and its affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #pragma once #include <Corrade/Containers/Optional.h> #include <Corrade/Containers/Reference.h> #include <Magnum/GL/Mesh.h> #include <Magnum/Magnum.h> #include <Magnum/Math/Color.h> #include <Magnum/Math/Range.h> #include <Magnum/Mesh.h> #include <Magnum/Trade/MeshData3D.h> #include "CollisionMeshData.h" #include "MeshData.h" #include "esp/core/esp.h" #include "esp/gfx/magnum.h" namespace esp { namespace assets { enum SupportedMeshType { NOT_DEFINED = -1, INSTANCE_MESH = 0, PTEX_MESH = 1, GLTF_MESH = 2, NUM_SUPPORTED_MESH_TYPES = 3, }; class BaseMesh { public: explicit BaseMesh(SupportedMeshType type) : type_(type){}; virtual ~BaseMesh(){}; bool setMeshType(SupportedMeshType type); SupportedMeshType getMeshType() { return type_; } virtual void uploadBuffersToGPU(bool){}; virtual Magnum::GL::Mesh* getMagnumGLMesh() { return nullptr; } virtual Magnum::GL::Mesh* getMagnumGLMesh(int) { return nullptr; } // Accessing non-render mesh data // Usage: (1) physics simulation virtual CollisionMeshData& getCollisionMeshData() { return collisionMeshData_; } //! Any transformations applied to the original mesh after load are stored // here. Magnum::Matrix4 meshTransform_; //! Axis aligned bounding box of the mesh. Computed automatically on mesh //! load. See @ref ResourceMananger::computeMeshBB. Magnum::Range3D BB; protected: SupportedMeshType type_ = SupportedMeshType::NOT_DEFINED; bool buffersOnGPU_ = false; // ==== rendering === Corrade::Containers::Optional<Magnum::Trade::MeshData3D> meshData_; // ==== non-rendering === CollisionMeshData collisionMeshData_; }; } // namespace assets } // namespace esp
27.144928
76
0.729311
[ "mesh", "render" ]
f8f14a6d40e3a8e97613b02ff802d434e638a306
1,215
h
C
FeatherUI/Headers/Window/Window.h
LilPidgey/FeatherUI
5bb42c3c95666c07c4f475b8f855252c3d668f55
[ "MIT" ]
2
2021-01-07T09:51:22.000Z
2021-04-26T22:57:16.000Z
FeatherUI/Headers/Window/Window.h
LilPidgey/FeatherUI
5bb42c3c95666c07c4f475b8f855252c3d668f55
[ "MIT" ]
null
null
null
FeatherUI/Headers/Window/Window.h
LilPidgey/FeatherUI
5bb42c3c95666c07c4f475b8f855252c3d668f55
[ "MIT" ]
1
2021-04-29T19:51:06.000Z
2021-04-29T19:51:06.000Z
#pragma once #include <mutex> #include <vector> #include <Windows.h> #include <Graphics/DirectX9/Structs/FeatherFont.h> #include <DisplayInterface/Components/FeatherContainer.h> #include <concurrent_queue.h> #include <functional> #include "Util/ConcurrentQueue.h" class Window { public: Window(int width, int height, unsigned long flags, const std::string& windowName, DWORD background); void InitializeDirectX(const std::vector<FeatherFont>& fonts); std::shared_ptr<FeatherContainer> container; FeatherTouch keyStateManager; FeatherFont titleFont; D3DCOLOR backgroundColor; POINT position; HWND hwnd; moodycamel::ConcurrentQueue<std::function<void()>> postRenderQueue; std::string windowName; int width; int height; int winFlags; void SetupWindow() const; void CloseWindow() const; void HandleMessage(); void Render(); private: IDirect3D9Ex* pObject = nullptr; IDirect3DDevice9Ex* pDevice = nullptr; D3DPRESENT_PARAMETERS pParams = {NULL}; DWORD lastFrameTime = 0; HINSTANCE hInstance; MSG message = {nullptr}; void Init(); void InitializeDirectx(const std::vector<FeatherFont>& fonts); };
23.823529
104
0.711934
[ "render", "vector" ]
f8f4a7ea4fc66cc99714c638af83679470dc1b2f
118,550
c
C
source/3rd/cpl-7.1.4/cplcore/cpl_image_io.c
ray820328/Funra
99c89a7a40798fb41dd401195fcc4711bec2520b
[ "MIT" ]
null
null
null
source/3rd/cpl-7.1.4/cplcore/cpl_image_io.c
ray820328/Funra
99c89a7a40798fb41dd401195fcc4711bec2520b
[ "MIT" ]
null
null
null
source/3rd/cpl-7.1.4/cplcore/cpl_image_io.c
ray820328/Funra
99c89a7a40798fb41dd401195fcc4711bec2520b
[ "MIT" ]
null
null
null
/* * This file is part of the ESO Common Pipeline Library * Copyright (C) 2001-2017 European Southern Observatory * * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include <config.h> #endif /*----------------------------------------------------------------------------- Includes -----------------------------------------------------------------------------*/ #include "cpl_image_io_impl.h" #include "cpl_error_impl.h" #include "cpl_memory.h" #include "cpl_propertylist_impl.h" #include "cpl_mask_defs.h" #include "cpl_io_fits.h" #include "cpl_cfitsio.h" #include "cpl_image_bpm_impl.h" #include "cpl_image_defs.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <math.h> #include <float.h> #include <assert.h> #include <fitsio.h> /*----------------------------------------------------------------------------- Defines -----------------------------------------------------------------------------*/ #define CPL_IMAGE_IO_GET_PIXELS 1 #define CPL_IMAGE_IO_SET_BADPIXEL 2 #define CPL_IMAGE_IO_GET 3 #define CPL_IMAGE_IO_SET 4 #define CPL_IMAGE_IO_RE_IM 5 #define CPL_IMAGE_IO_RE 6 #define CPL_IMAGE_IO_IM 7 #define CPL_IMAGE_IO_ABS_ARG 8 #define CPL_IMAGE_IO_ABS 9 #define CPL_IMAGE_IO_ARG 10 /* Needed for cpl_image_floodfill() */ #define FFSTACK_MAXLINES 10 #define FFSTACK_STACKSZ(IMAGE) (FFSTACK_MAXLINES * IMAGE->ny) #define FFSTACK_BYTES(IMAGE) \ ((size_t)FFSTACK_STACKSZ(IMAGE) * 4 * sizeof(cpl_size)) #define CPL_MSG "Image with %" CPL_SIZE_FORMAT " X %" CPL_SIZE_FORMAT \ " pixel(s) of type '%s' and %" CPL_SIZE_FORMAT " bad pixel(s)\n" /*----------------------------------------------------------------------------- Private function prototypes -----------------------------------------------------------------------------*/ static void cpl_image_floodfill(cpl_image *, void *, cpl_size, cpl_size, cpl_size); static cpl_image * cpl_image_load_one(const char *, cpl_type, cpl_size, cpl_size, cpl_boolean, cpl_size, cpl_size, cpl_size, cpl_size) CPL_ATTR_ALLOC; #define CPL_CLASS CPL_CLASS_DOUBLE #include "cpl_image_io_body.h" #undef CPL_CLASS #define CPL_CLASS CPL_CLASS_FLOAT #include "cpl_image_io_body.h" #undef CPL_CLASS /*----------------------------------------------------------------------------- Function codes -----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Allocate an image structure and pixel buffer for a image. @param nx Size in x (the number of columns) @param ny Size in y (the number of rows) @param type The pixel type @return 1 newly allocated cpl_image or NULL in case of an error Allocates space for the cpl_image structure and sets the dimensions and type of pixel data. The pixel buffer is allocated and initialised to zero. The pixel array will contain nx*ny values being the image pixels from the lower left to the upper right line by line. Supported pixel types are CPL_TYPE_INT, CPL_TYPE_FLOAT, CPL_TYPE_DOUBLE, CPL_TYPE_FLOAT_COMPLEX and CPL_TYPE_DOUBLE_COMPLEX. The returned cpl_image must be deallocated using cpl_image_delete(). Possible #_cpl_error_code_ set in this function: - CPL_ERROR_ILLEGAL_INPUT if nx or ny is non-positive - CPL_ERROR_INVALID_TYPE if the passed pixel type is not supported */ /*----------------------------------------------------------------------------*/ cpl_image * cpl_image_new(cpl_size nx, cpl_size ny, cpl_type type) { cpl_image * self = cpl_image_wrap_(nx, ny, type, NULL); if (self == NULL) (void)cpl_error_set_where_(); return self; } /*----------------------------------------------------------------------------*/ /** @brief Create an image using an existing pixel buffer of the specified type @param nx Size in x (the number of columns) @param ny Size in y (the number of rows) @param type Pixel type @param pixels Pixel data of the specified type @return 1 newly allocated cpl_image or NULL on error @see cpl_image_new() Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL - CPL_ERROR_ILLEGAL_INPUT if nx or ny is non-positive or their product is too big - CPL_ERROR_INVALID_TYPE if the passed pixel type is not supported */ /*----------------------------------------------------------------------------*/ cpl_image * cpl_image_wrap(cpl_size nx, cpl_size ny, cpl_type type, void * pixels) { cpl_image * self; cpl_ensure(pixels != NULL, CPL_ERROR_NULL_INPUT, NULL); self = cpl_image_wrap_(nx, ny, type, pixels); if (self == NULL) (void)cpl_error_set_where_(); return self; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Create a double image using an existing pixel buffer. @param nx Size in x (the number of columns) @param ny Size in y (the number of rows) @param pixels double * pixel data @return 1 newly allocated cpl_image or NULL in case of an error @see cpl_image_new The pixel array is set to point to that of the argument. The pixel array must contain nx*ny doubles. The allocated image must be deallocated with cpl_image_unwrap(). Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL - CPL_ERROR_ILLEGAL_INPUT if nx or ny is non-positive or zero. */ /*----------------------------------------------------------------------------*/ cpl_image * cpl_image_wrap_double(cpl_size nx, cpl_size ny, double * pixels) { cpl_image * self; cpl_ensure(pixels != NULL, CPL_ERROR_NULL_INPUT, NULL); self = cpl_image_wrap_(nx, ny, CPL_TYPE_DOUBLE, pixels); if (self == NULL) (void)cpl_error_set_where_(); return self; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Create a float image using an existing pixel buffer. @param nx Size in x (the number of columns) @param ny Size in y (the number of rows) @param pixels float * pixel data. @return 1 newly allocated cpl_image or NULL on error @see cpl_image_wrap_double() */ /*----------------------------------------------------------------------------*/ cpl_image * cpl_image_wrap_float(cpl_size nx, cpl_size ny, float * pixels) { cpl_image * self; cpl_ensure(pixels != NULL, CPL_ERROR_NULL_INPUT, NULL); self = cpl_image_wrap_(nx, ny, CPL_TYPE_FLOAT, pixels); if (self == NULL) (void)cpl_error_set_where_(); return self; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Create a double complex image using an existing pixel buffer. @param nx Size in x (the number of columns) @param ny Size in y (the number of rows) @param pixels double complex * pixel data. @return 1 newly allocated cpl_image or NULL on error @see cpl_image_wrap_double() @note This function is available iff the application includes complex.h */ /*----------------------------------------------------------------------------*/ cpl_image * cpl_image_wrap_double_complex(cpl_size nx, cpl_size ny, double complex * pixels) { cpl_image * self; cpl_ensure(pixels != NULL, CPL_ERROR_NULL_INPUT, NULL); self = cpl_image_wrap_(nx, ny, CPL_TYPE_DOUBLE_COMPLEX, pixels); if (self == NULL) (void)cpl_error_set_where_(); return self; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Create a float complex image using an existing pixel buffer. @param nx Size in x (the number of columns) @param ny Size in y (the number of rows) @param pixels float complex * pixel data. @return 1 newly allocated cpl_image or NULL on error @see cpl_image_wrap_double_complex() */ /*----------------------------------------------------------------------------*/ cpl_image * cpl_image_wrap_float_complex(cpl_size nx, cpl_size ny, float complex * pixels) { cpl_image * self; cpl_ensure(pixels != NULL, CPL_ERROR_NULL_INPUT, NULL); self = cpl_image_wrap_(nx, ny, CPL_TYPE_FLOAT_COMPLEX, pixels); if (self == NULL) (void)cpl_error_set_where_(); return self; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Create an integer image using an existing pixel buffer. @param nx Size in x (the number of columns) @param ny Size in y (the number of rows) @param pixels int * pixel data. @return 1 newly allocated cpl_image or NULL on error @see cpl_image_wrap_double() */ /*----------------------------------------------------------------------------*/ cpl_image * cpl_image_wrap_int( cpl_size nx, cpl_size ny, int * pixels) { cpl_image * self; cpl_ensure(pixels != NULL, CPL_ERROR_NULL_INPUT, NULL); self = cpl_image_wrap_(nx, ny, CPL_TYPE_INT, pixels); if (self == NULL) (void)cpl_error_set_where_(); return self; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Load an image from a FITS file. @param filename Name of the file to load from. @param im_type Type of the created image @param pnum Plane number in the Data Unit (0 for first) @param xtnum Extension number in the file (0 for primary HDU) @return 1 newly allocated image or NULL on error This function loads an image from a FITS file (NAXIS=2 or 3). The returned image has to be deallocated with cpl_image_delete(). The passed type for the output image can be : CPL_TYPE_FLOAT, CPL_TYPE_DOUBLE or CPL_TYPE_INT. This type is there to specify the type of the cpl_image that will be created by the function. It is totally independant from the way the data are stored in the FITS file. A FITS image containg float pixels can be loaded as a cpl_image of type double. In this case, the user would specify CPL_TYPE_DOUBLE as im_type. Additionally, CPL_TYPE_UNSPECIFIED can be passed to inherit the FITS file type. The type of the image is defined based on the BITPIX information of the FITS file. After a successful call, the type of the created image can be accessed via cpl_image_get_type(). 'xtnum' specifies from which extension the image should be loaded. This could be 0 for the main data section (files without extension), or any number between 1 and N, where N is the number of extensions present in the file. The requested plane number runs from 0 to nplanes-1, where nplanes is the number of planes present in the requested data section. The created image has an empty bad pixel map. Examples: @code // Load as a float image the only image in FITS file (a.fits) without ext. // and NAXIS=2. cpl_image * im = cpl_image_load("a.fits", CPL_TYPE_FLOAT, 0, 0); // Load as a double image the first plane in a FITS cube (a.fits) without // extension, NAXIS=3 and NAXIS3=128 cpl_image * im = cpl_image_load("a.fits", CPL_TYPE_DOUBLE, 0, 0); // Load as an integer image the third plane in a FITS cube (a.fits) without // extension, NAXIS=3 and NAXIS3=128 cpl_image * im = cpl_image_load("a.fits", CPL_TYPE_INT, 2, 0); // Load as a double image the first plane from extension 5 cpl_image * im = cpl_image_load("a.fits", CPL_TYPE_DOUBLE, 0, 5); // Load as a double image the third plane in extension 5 cpl_image * im = cpl_image_load("a.fits", CPL_TYPE_DOUBLE, 2, 5); @endcode Possible #_cpl_error_code_ set in this function: - CPL_ERROR_FILE_IO if the file cannot be opened or does not exist - CPL_ERROR_BAD_FILE_FORMAT if the data cannot be loaded from the file - CPL_ERROR_INVALID_TYPE if the passed pixel type is not supported - CPL_ERROR_ILLEGAL_INPUT if the passed extension number is negative - CPL_ERROR_DATA_NOT_FOUND if the specified extension has no image data */ /*----------------------------------------------------------------------------*/ cpl_image * cpl_image_load(const char * filename, cpl_type im_type, cpl_size pnum, cpl_size xtnum) { cpl_image * self = cpl_image_load_one(filename, im_type, pnum, xtnum, CPL_FALSE, 0, 0, 0, 0); if (self == NULL) cpl_error_set_where_(); return self; } /*----------------------------------------------------------------------------*/ /** @internal @brief Load an image from a FITS file. @param filename Name of the file to load from. @param im_type Type of the created image @param pnum Plane number in the Data Unit (0 for first) @param xtnum Extension number in the file (0 for primary HDU) @param do_window True for (and only for) a windowed load @param llx Lower left x position (FITS convention, 1 for leftmost) @param lly Lower left y position (FITS convention, 1 for lowest) @param urx Upper right x position (FITS convention) @param ury Upper right y position (FITS convention) @return 1 newly allocated image or NULL on error @see cpl_image_load() */ /*----------------------------------------------------------------------------*/ static cpl_image * cpl_image_load_one(const char * filename, cpl_type im_type, cpl_size pnum, cpl_size xtnum, cpl_boolean do_window, cpl_size llx, cpl_size lly, cpl_size urx, cpl_size ury) { int error = 0; int naxis = 0; /* May read from Data Unit w. NAXIS=[23] */ CPL_FITSIO_TYPE naxes[3] ={0, 0, 0}; cpl_type pix_type = im_type; fitsfile * fptr; cpl_image * self; /* FIXME: Version 3.24 of fits_open_diskfile() seg-faults on NULL. If ever fixed in CFITSIO, this check should be removed */ cpl_ensure(filename != NULL, CPL_ERROR_NULL_INPUT, NULL); cpl_ensure(xtnum >= 0, CPL_ERROR_ILLEGAL_INPUT, NULL); if (cpl_io_fits_open_diskfile(&fptr, filename, READONLY, &error)) { /* If the file did not exist: error = 104 (FILE_NOT_OPENED) */ /* If the file had permission 0: error = 104 (FILE_NOT_OPENED) */ /* If the file was empty: error = 107 (END_OF_FILE) */ /* If the file was a directory: error = 108 (READ_ERROR) */ (void)cpl_error_set_fits(CPL_ERROR_FILE_IO, error, fits_open_diskfile, "filename='%s', im_type=%u, pnum=%" CPL_SIZE_FORMAT ", xtnum=%" CPL_SIZE_FORMAT, filename, im_type, pnum, xtnum); return NULL; } self = cpl_image_load_(fptr, &naxis, naxes, &pix_type, filename, pnum, xtnum, do_window, llx, lly, urx, ury); if (cpl_io_fits_close_file(fptr, &error)) { cpl_image_delete(self); self = NULL; (void)cpl_error_set_fits(CPL_ERROR_BAD_FILE_FORMAT, error, fits_close_file, "filename='%s', " "im_type=%u, pnum=%" CPL_SIZE_FORMAT ", xtnum=%" CPL_SIZE_FORMAT, filename, im_type, pnum, xtnum); } else if (self == NULL) { cpl_error_set_where_(); } return self; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Load an image from a FITS file. @param filename Name of the file to load from. @param im_type Type of the created image @param pnum Plane number in the Data Unit (0 for first) @param xtnum Extension number in the file. @param llx Lower left x position (FITS convention, 1 for leftmost) @param lly Lower left y position (FITS convention, 1 for lowest) @param urx Upper right x position (FITS convention) @param ury Upper right y position (FITS convention) @return 1 newly allocated image or NULL on error @see cpl_image_load() Possible #_cpl_error_code_ set in this function: - CPL_ERROR_FILE_IO if the file does not exist - CPL_ERROR_BAD_FILE_FORMAT if the data cannot be loaded from the file - CPL_ERROR_INVALID_TYPE if the passed pixel type is not supported - CPL_ERROR_ILLEGAL_INPUT if the passed position is invalid */ /*----------------------------------------------------------------------------*/ cpl_image * cpl_image_load_window(const char * filename, cpl_type im_type, cpl_size pnum, cpl_size xtnum, cpl_size llx, cpl_size lly, cpl_size urx, cpl_size ury) { cpl_image * self = cpl_image_load_one(filename, im_type, pnum, xtnum, CPL_TRUE, llx, lly, urx, ury); if (self == NULL) cpl_error_set_where_(); return self; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Create an int image from a mask @param mask the original mask @return 1 newly allocated cpl_image or NULL on error The created image is of type CPL_TYPE_INT. Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL */ /*----------------------------------------------------------------------------*/ cpl_image * cpl_image_new_from_mask(const cpl_mask * mask) { const size_t nx = cpl_mask_get_size_x(mask); const size_t ny = cpl_mask_get_size_y(mask); const cpl_binary * data = cpl_mask_get_data_const(mask); cpl_image * out; int * pout; size_t i; cpl_ensure(mask, CPL_ERROR_NULL_INPUT, NULL); /* Create the INT image */ pout = (int*)cpl_malloc(nx * ny * sizeof(*pout)); out = cpl_image_wrap_int(nx, ny, pout); /* Fill the image */ for (i= 0; i < nx * ny; i++) { pout[i] = (data[i] == CPL_BINARY_0) ? 0 : 1; } return out; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Labelise a mask to differentiate different objects @param in mask to labelise @param nbobjs If non-NULL, number of objects found on success @return A newly allocated label image or NULL on error This function labelises all blobs in a mask. All 4-neighbour connected zones set to 1 in the input mask will end up in the returned integer image as zones where all pixels are set to the same (unique for this blob in this image) label. A non-recursive flood-fill is applied to label the zones. The flood-fill is dimensioned by the number of lines in the image, and the maximal number of lines possibly covered by a blob. The returned image must be deallocated with cpl_image_delete() Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if the input mask is NULL */ /*----------------------------------------------------------------------------*/ cpl_image * cpl_image_labelise_mask_create(const cpl_mask * in, cpl_size * nbobjs) { cpl_image * intimage; int * pio; cpl_size label = 1; /* The first label value */ const size_t nx = cpl_mask_get_size_x(in); const size_t ny = cpl_mask_get_size_y(in); const cpl_binary * pin = cpl_mask_get_data_const(in); size_t i, j; cpl_boolean has_data = CPL_TRUE; /* Duplicated body from cpl_image_new_from_mask() :-((((((((((((((((*/ /* Test entries */ cpl_ensure(in != NULL, CPL_ERROR_NULL_INPUT, NULL); /* Create output integer image and initialise it with the input map */ intimage = cpl_image_new(nx, ny, CPL_TYPE_INT); pio = cpl_image_get_data_int(intimage); for (i = 0; i < nx * ny; i++) { if (pin[i] != CPL_BINARY_0) { pio[i] = -1; has_data = CPL_TRUE; } } if (has_data) { /* Now work on intimage */ /* Allocate temporary work-space for cpl_image_floodfill() */ void * fftemp = cpl_malloc(FFSTACK_BYTES(intimage)); for (j = 0; j < ny; j++, pio += nx) { for (i = 0; i < nx; i++) { /* Look up if unprocessed pixel */ if (pio[i] == -1) { /* Flood fill from this pixel with the assigned label */ cpl_image_floodfill(intimage, fftemp, i, j, label); label++; } } } cpl_free(fftemp); } if (nbobjs!=NULL) *nbobjs = label-1; return intimage; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Get the image type @param img a cpl_image object @return The image type or CPL_TYPE_INVALID on NULL input. Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL */ /*----------------------------------------------------------------------------*/ cpl_type cpl_image_get_type(const cpl_image * img) { cpl_ensure(img, CPL_ERROR_NULL_INPUT, CPL_TYPE_INVALID); return img->type; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Get the image x size @param img a cpl_image object @return The image x size, or -1 on NULL input Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL */ /*----------------------------------------------------------------------------*/ cpl_size cpl_image_get_size_x(const cpl_image * img) { cpl_ensure(img, CPL_ERROR_NULL_INPUT, -1); return img->nx; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Get the image y size @param img a cpl_image object @return The image y size, or -1 on NULL input Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL */ /*----------------------------------------------------------------------------*/ cpl_size cpl_image_get_size_y(const cpl_image * img) { cpl_ensure(img, CPL_ERROR_NULL_INPUT, -1); return img->ny; } #define CPL_OPERATION CPL_IMAGE_IO_GET #define CPL_TYPE_RETURN double /*----------------------------------------------------------------------------*/ /** @internal @ingroup cpl_image @brief Get the value of a pixel at a given position @param image Input image. @param xpos Pixel x position (FITS convention, 1 for leftmost) @param ypos Pixel y position (FITS convention, 1 for lowest) @return The pixel value (cast to a double) @see cpl_image_get() @note No input validation in this function */ /*----------------------------------------------------------------------------*/ double cpl_image_get_(const cpl_image * image, cpl_size xpos, cpl_size ypos) { const cpl_size pos = (xpos - 1) + image->nx * (ypos - 1); double value; assert( image->pixels ); /* Get the value */ switch (image->type) { #define CPL_CLASS CPL_CLASS_DOUBLE #include "cpl_image_io_body.h" #undef CPL_CLASS #define CPL_CLASS CPL_CLASS_FLOAT #include "cpl_image_io_body.h" #undef CPL_CLASS #define CPL_CLASS CPL_CLASS_INT #include "cpl_image_io_body.h" #undef CPL_CLASS default: assert(0); } return value; } #undef CPL_TYPE_RETURN #define CPL_TYPE_RETURN double complex /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Get the value of a pixel at a given position @param image Input image. @param xpos Pixel x position (FITS convention, 1 for leftmost) @param ypos Pixel y position (FITS convention, 1 for lowest) @param pis_rejected 1 if the pixel is bad, 0 if good, negative on error @return The pixel value (cast to a double) or undefined if *pis_rejected @see cpl_image_get_complex() The return value is defined if the pixel is not flagged as rejected, i. e. when *pis_rejected == 0. In case of an error, the #_cpl_error_code_ code is set. Images can be CPL_TYPE_FLOAT, CPL_TYPE_INT or CPL_TYPE_DOUBLE. Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL - CPL_ERROR_ACCESS_OUT_OF_RANGE if the passed position is not in the image - CPL_ERROR_INVALID_TYPE if the image pixel type is not supported */ /*----------------------------------------------------------------------------*/ double cpl_image_get(const cpl_image * image, cpl_size xpos, cpl_size ypos, int * pis_rejected) { cpl_size pos; /* Check entries */ cpl_ensure(pis_rejected != NULL, CPL_ERROR_NULL_INPUT, -1.0); *pis_rejected = -1; cpl_ensure(image != NULL, CPL_ERROR_NULL_INPUT, -2.0); /* Check the validity of image, xpos and ypos */ cpl_ensure(xpos >= 1, CPL_ERROR_ACCESS_OUT_OF_RANGE, -2.0); cpl_ensure(ypos >= 1, CPL_ERROR_ACCESS_OUT_OF_RANGE, -2.0); cpl_ensure(xpos <= image->nx, CPL_ERROR_ACCESS_OUT_OF_RANGE, -2.0); cpl_ensure(ypos <= image->ny, CPL_ERROR_ACCESS_OUT_OF_RANGE, -2.0); cpl_ensure(!(image->type & CPL_TYPE_COMPLEX), CPL_ERROR_INVALID_TYPE, -3.0); pos = (xpos - 1) + image->nx * (ypos - 1); *pis_rejected = image->bpm != NULL && image->bpm->data[pos] != CPL_BINARY_0 ? 1 : 0; return *pis_rejected ? 0.0 : cpl_image_get_(image, xpos, ypos); } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Get the value of a complex pixel at a given position @param image Input complex image. @param xpos Pixel x position (FITS convention, 1 for leftmost) @param ypos Pixel y position (FITS convention, 1 for lowest) @param pis_rejected 1 if the pixel is bad, 0 if good, negative on error @return The pixel value (cast to a double complex) or undefined if *pis_rejected @see cpl_image_get() @note This function is available iff the application includes complex.h The return value is defined if the pixel is not flagged as rejected, i. e. when *pis_rejected == 0. In case of an error, the #_cpl_error_code_ code is set. Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL - CPL_ERROR_ACCESS_OUT_OF_RANGE if the passed position is not in the image */ /*----------------------------------------------------------------------------*/ double complex cpl_image_get_complex(const cpl_image * image, cpl_size xpos, cpl_size ypos, int * pis_rejected) { double complex value; cpl_size pos; /* Check entries */ cpl_ensure(pis_rejected != NULL, CPL_ERROR_NULL_INPUT, -1.0); *pis_rejected = -1; cpl_ensure(image != NULL, CPL_ERROR_NULL_INPUT, -1.0); cpl_ensure(xpos >= 1, CPL_ERROR_ACCESS_OUT_OF_RANGE, -2.0); cpl_ensure(ypos >= 1, CPL_ERROR_ACCESS_OUT_OF_RANGE, -2.0); cpl_ensure(xpos <= image->nx, CPL_ERROR_ACCESS_OUT_OF_RANGE, -2.0); cpl_ensure(ypos <= image->ny, CPL_ERROR_ACCESS_OUT_OF_RANGE, -2.0); pos = (xpos - 1) + image->nx * (ypos - 1); /* Check the validity of image, xpos and ypos */ *pis_rejected = image->bpm != NULL && image->bpm->data[pos] != CPL_BINARY_0 ? 1 : 0; /* The pixel is flagged as rejected */ if (*pis_rejected) return 0.0; assert( image->pixels ); /* Get the value */ switch (image->type) { #define CPL_CLASS CPL_CLASS_DOUBLE #include "cpl_image_io_body.h" #undef CPL_CLASS #define CPL_CLASS CPL_CLASS_FLOAT #include "cpl_image_io_body.h" #undef CPL_CLASS #define CPL_CLASS CPL_CLASS_INT #include "cpl_image_io_body.h" #undef CPL_CLASS #define CPL_CLASS CPL_CLASS_DOUBLE_COMPLEX #include "cpl_image_io_body.h" #undef CPL_CLASS #define CPL_CLASS CPL_CLASS_FLOAT_COMPLEX #include "cpl_image_io_body.h" #undef CPL_CLASS default: (void)cpl_error_set_(CPL_ERROR_INVALID_TYPE); value = -3.0; } return value; } #undef CPL_OPERATION #undef CPL_TYPE_RETURN /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Split a complex image into its real and/or imaginary part(s) @param im_real Pre-allocated image to hold the real part, or @c NULL @param im_imag Pre-allocated image to hold the imaginary part, or @c NULL @param self Complex image to process @return CPL_ERROR_NONE or #_cpl_error_code_ on error @note At least one output image must be non-NULL. The images must match in size and precision Any bad pixels are also processed. Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT If the input image or both output images are @c NULL - CPL_ERROR_INCOMPATIBLE_INPUT If the images have different sizes - CPL_ERROR_INVALID_TYPE If the input image is not of complex type - CPL_ERROR_TYPE_MISMATCH If the images have different precision */ /*----------------------------------------------------------------------------*/ cpl_error_code cpl_image_fill_re_im(cpl_image * im_real, cpl_image * im_imag, const cpl_image * self) { cpl_error_code error = CPL_ERROR_NONE; /* Set locally in this function */ cpl_error_code code = CPL_ERROR_NONE; /* Set in call, propagate */ cpl_ensure_code(self != NULL, CPL_ERROR_NULL_INPUT); cpl_ensure_code(self->type & CPL_TYPE_COMPLEX, CPL_ERROR_INVALID_TYPE); if (im_real != NULL && im_imag != NULL) { cpl_ensure_code(self->nx == im_real->nx, CPL_ERROR_INCOMPATIBLE_INPUT); cpl_ensure_code(self->ny == im_real->ny, CPL_ERROR_INCOMPATIBLE_INPUT); cpl_ensure_code(self->nx == im_imag->nx, CPL_ERROR_INCOMPATIBLE_INPUT); cpl_ensure_code(self->ny == im_imag->ny, CPL_ERROR_INCOMPATIBLE_INPUT); switch (self->type) { case CPL_TYPE_DOUBLE_COMPLEX: code = cpl_image_fill_re_im_double(im_real, im_imag, self); break; case CPL_TYPE_FLOAT_COMPLEX: code = cpl_image_fill_re_im_float(im_real, im_imag, self); break; default: error = cpl_error_set_(CPL_ERROR_INVALID_TYPE); } } else if (im_real != NULL) { cpl_ensure_code(self->nx == im_real->nx, CPL_ERROR_INCOMPATIBLE_INPUT); cpl_ensure_code(self->ny == im_real->ny, CPL_ERROR_INCOMPATIBLE_INPUT); switch (self->type) { case CPL_TYPE_DOUBLE_COMPLEX: code = cpl_image_fill_re_double(im_real, self); break; case CPL_TYPE_FLOAT_COMPLEX: code = cpl_image_fill_re_float(im_real, self); break; default: error = cpl_error_set_(CPL_ERROR_INVALID_TYPE); } } else if (im_imag != NULL) { cpl_ensure_code(self->nx == im_imag->nx, CPL_ERROR_INCOMPATIBLE_INPUT); cpl_ensure_code(self->ny == im_imag->ny, CPL_ERROR_INCOMPATIBLE_INPUT); switch (self->type) { case CPL_TYPE_DOUBLE_COMPLEX: code = cpl_image_fill_im_double(im_imag, self); break; case CPL_TYPE_FLOAT_COMPLEX: code = cpl_image_fill_im_float(im_imag, self); break; default: error = cpl_error_set_(CPL_ERROR_INVALID_TYPE); } } else { error = cpl_error_set_(CPL_ERROR_NULL_INPUT); } return code ? cpl_error_set_where_() : error; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Split a complex image into its absolute and argument part(s) @param im_abs Pre-allocated image to hold the absolute part, or @c NULL @param im_arg Pre-allocated image to hold the argument part, or @c NULL @param self Complex image to process @return CPL_ERROR_NONE or #_cpl_error_code_ on error @note At least one output image must be non-NULL. The images must match in size and precision Any bad pixels are also processed. Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT If the input image or both output images are @c NULL - CPL_ERROR_INCOMPATIBLE_INPUT If the images have different sizes - CPL_ERROR_INVALID_TYPE If the input image is not of complex type - CPL_ERROR_TYPE_MISMATCH If the images have different precision */ /*----------------------------------------------------------------------------*/ cpl_error_code cpl_image_fill_abs_arg(cpl_image * im_abs, cpl_image * im_arg, const cpl_image * self) { cpl_error_code error; cpl_ensure_code(self != NULL, CPL_ERROR_NULL_INPUT); cpl_ensure_code(self->type & CPL_TYPE_COMPLEX, CPL_ERROR_INVALID_TYPE); if (im_abs != NULL && im_arg != NULL) { cpl_ensure_code(self->nx == im_abs->nx, CPL_ERROR_INCOMPATIBLE_INPUT); cpl_ensure_code(self->ny == im_abs->ny, CPL_ERROR_INCOMPATIBLE_INPUT); cpl_ensure_code(self->nx == im_arg->nx, CPL_ERROR_INCOMPATIBLE_INPUT); cpl_ensure_code(self->ny == im_arg->ny, CPL_ERROR_INCOMPATIBLE_INPUT); switch (self->type) { case CPL_TYPE_DOUBLE_COMPLEX: error = cpl_image_fill_abs_arg_double(im_abs, im_arg, self); break; case CPL_TYPE_FLOAT_COMPLEX: error = cpl_image_fill_abs_arg_float(im_abs, im_arg, self); break; default: error = CPL_ERROR_INVALID_TYPE; } } else if (im_abs != NULL) { cpl_ensure_code(self->nx == im_abs->nx, CPL_ERROR_INCOMPATIBLE_INPUT); cpl_ensure_code(self->ny == im_abs->ny, CPL_ERROR_INCOMPATIBLE_INPUT); switch (self->type) { case CPL_TYPE_DOUBLE_COMPLEX: error = cpl_image_fill_abs_double(im_abs, self); break; case CPL_TYPE_FLOAT_COMPLEX: error = cpl_image_fill_abs_float(im_abs, self); break; default: error = CPL_ERROR_INVALID_TYPE; } } else if (im_arg != NULL) { cpl_ensure_code(self->nx == im_arg->nx, CPL_ERROR_INCOMPATIBLE_INPUT); cpl_ensure_code(self->ny == im_arg->ny, CPL_ERROR_INCOMPATIBLE_INPUT); switch (self->type) { case CPL_TYPE_DOUBLE_COMPLEX: error = cpl_image_fill_arg_double(im_arg, self); break; case CPL_TYPE_FLOAT_COMPLEX: error = cpl_image_fill_arg_float(im_arg, self); break; default: error = CPL_ERROR_INVALID_TYPE; } } else { error = CPL_ERROR_NULL_INPUT; } return error ? cpl_error_set_(error) : CPL_ERROR_NONE; } /*----------------------------------------------------------------------------*/ /** @internal @ingroup cpl_image @brief Get the real part of the pixels from a complex image @param self Pre-allocated non-complex image to hold the result @param other The complex image to process @return CPL_ERROR_NONE or #_cpl_error_code_ on error @deprecated Replace this call with cpl_image_fill_re_im() @see cpl_image_fill_re_im() */ /*----------------------------------------------------------------------------*/ cpl_error_code cpl_image_fill_real(cpl_image * self, const cpl_image * other) { const cpl_error_code error = cpl_image_fill_re_im(self, NULL, other); return error ? cpl_error_set_where_() : CPL_ERROR_NONE; } /*----------------------------------------------------------------------------*/ /** @internal @ingroup cpl_image @brief Get the imaginary part of the pixels from a complex image @param self Pre-allocated non-complex image to hold the result @param other The complex image to process @return CPL_ERROR_NONE or #_cpl_error_code_ on error @deprecated Replace this call with cpl_image_fill_re_im() @see cpl_image_fill_re_im() */ /*----------------------------------------------------------------------------*/ cpl_error_code cpl_image_fill_imag(cpl_image * self, const cpl_image * other) { const cpl_error_code error = cpl_image_fill_re_im(NULL, self, other); return error ? cpl_error_set_where_() : CPL_ERROR_NONE; } /*----------------------------------------------------------------------------*/ /** @internal @ingroup cpl_image @brief Get the absolute values of the pixels in a complex image @param self Pre-allocated non-complex image to hold the result @param other The complex image to process @return CPL_ERROR_NONE or #_cpl_error_code_ on error @deprecated Replace this call with cpl_image_fill_abs_arg() @see cpl_image_fill_abs_arg() */ /*----------------------------------------------------------------------------*/ cpl_error_code cpl_image_fill_mod(cpl_image * self, const cpl_image * other) { const cpl_error_code error = cpl_image_fill_abs_arg(self, NULL, other); return error ? cpl_error_set_where_() : CPL_ERROR_NONE; } /*----------------------------------------------------------------------------*/ /** @internal @ingroup cpl_image @brief Get the phase of the pixels in a complex image @param self Pre-allocated non-complex image to hold the result @param other The complex image to process @return CPL_ERROR_NONE or #_cpl_error_code_ on error @deprecated Replace this call with cpl_image_fill_abs_arg() @see cpl_image_fill_abs_arg() */ /*----------------------------------------------------------------------------*/ cpl_error_code cpl_image_fill_phase(cpl_image * self, const cpl_image * other) { const cpl_error_code error = cpl_image_fill_abs_arg(NULL, self, other); return error ? cpl_error_set_where_() : CPL_ERROR_NONE; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Complex conjugate the pixels in a complex image @param self Pre-allocated complex image to hold the result @param other The complex image to conjugate, may equal self @return CPL_ERROR_NONE or #_cpl_error_code_ on error @note The two images must match in size and precision Any bad pixels are also conjugated. Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT If an input pointer is NULL - CPL_ERROR_INCOMPATIBLE_INPUT If the images have different sizes - CPL_ERROR_INVALID_TYPE If an input image is not of complex type - CPL_ERROR_TYPE_MISMATCH If the images have different precision */ /*----------------------------------------------------------------------------*/ cpl_error_code cpl_image_conjugate(cpl_image * self, const cpl_image * other) { cpl_error_code error; cpl_ensure_code(self != NULL, CPL_ERROR_NULL_INPUT); cpl_ensure_code(other != NULL, CPL_ERROR_NULL_INPUT); cpl_ensure_code(self->nx == other->nx, CPL_ERROR_INCOMPATIBLE_INPUT); cpl_ensure_code(self->ny == other->ny, CPL_ERROR_INCOMPATIBLE_INPUT); cpl_ensure_code(self->type == other->type, CPL_ERROR_TYPE_MISMATCH); switch (self->type) { case CPL_TYPE_DOUBLE_COMPLEX: error = cpl_image_conjugate_double(self, other); break; case CPL_TYPE_FLOAT_COMPLEX: error = cpl_image_conjugate_float(self, other); break; default: error = CPL_ERROR_INVALID_TYPE; } return error ? cpl_error_set_(error) : CPL_ERROR_NONE; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Fill an image window with a constant @param self The image to fill @param llx Lower left x position (FITS convention, 1 for leftmost) @param lly Lower left y position (FITS convention, 1 for lowest) @param urx Specifies the window position @param ury Specifies the window position @param value The value to fill with @return The #_cpl_error_code_ or CPL_ERROR_NONE @note Any bad pixels are accepted Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL - CPL_ERROR_ILLEGAL_INPUT if the specified window is not valid */ /*----------------------------------------------------------------------------*/ cpl_error_code cpl_image_fill_window(cpl_image * self, cpl_size llx, cpl_size lly, cpl_size urx, cpl_size ury, double value) { cpl_ensure_code(self != NULL, CPL_ERROR_NULL_INPUT); cpl_ensure_code(llx >= 1, CPL_ERROR_ILLEGAL_INPUT); cpl_ensure_code(lly >= 1, CPL_ERROR_ILLEGAL_INPUT); cpl_ensure_code(llx <= urx, CPL_ERROR_ILLEGAL_INPUT); cpl_ensure_code(lly <= ury, CPL_ERROR_ILLEGAL_INPUT); cpl_ensure_code(urx <= self->nx, CPL_ERROR_ILLEGAL_INPUT); cpl_ensure_code(ury <= self->ny, CPL_ERROR_ILLEGAL_INPUT); cpl_ensure_code(!(self->type & CPL_TYPE_COMPLEX), CPL_ERROR_INVALID_TYPE); for (cpl_size j = lly; j <= ury; j++) { for (cpl_size i = llx; i <= urx; i++) { cpl_image_set_(self, i, j, value); } } if (self->bpm != NULL) { cpl_mask_fill_window(self->bpm, llx, lly, urx, ury, CPL_BINARY_0); } return CPL_ERROR_NONE; } /*----------------------------------------------------------------------------*/ /** @internal @ingroup cpl_image @brief Fill an image of type integer with a constant @param self The image to fill @param value The value to fill with @return The #_cpl_error_code_ or CPL_ERROR_NONE @note Any bad pixels are accepted Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL - CPL_ERROR_TYPE_MISMATCH if the image type is not int */ /*----------------------------------------------------------------------------*/ cpl_error_code cpl_image_fill_int(cpl_image * self, int value) { cpl_ensure_code(self != NULL, CPL_ERROR_NULL_INPUT); cpl_ensure_code(self->type == CPL_TYPE_INT, CPL_ERROR_TYPE_MISMATCH); if (value == 0) { (void)memset(self->pixels, 0, (size_t)self->nx * (size_t)self->ny * sizeof(int)); } else { size_t i = (size_t)(self->nx * self->ny); do { ((int*)self->pixels)[--i] = value; } while (i); } return CPL_ERROR_NONE; } /*----------------------------------------------------------------------------*/ /** @internal @ingroup cpl_image @brief Extract the real part image of a complex image @param image input image @return a newly allocated real image or NULL on error @see cpl_image_fill_real() Image can be CPL_TYPE_FLOAT_COMPLEX or CPL_TYPE_DOUBLE_COMPLEX. The returned image must be deallocated using cpl_image_delete(). Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if the input pointer is NULL - CPL_ERROR_INVALID_TYPE if the passed image type is non-complex */ /*----------------------------------------------------------------------------*/ cpl_image * cpl_image_extract_real(const cpl_image * image) { cpl_image * self; cpl_ensure(image != NULL, CPL_ERROR_NULL_INPUT, NULL); self = cpl_image_new(image->nx, image->ny, image->type & ~CPL_TYPE_COMPLEX); if (cpl_image_fill_real(self, image)) { (void)cpl_error_set_where_(); cpl_image_delete(self); self = NULL; } return self; } /*----------------------------------------------------------------------------*/ /** @internal @ingroup cpl_image @brief Extract the imaginary part image of a complex image @param image input image @return a newly allocated imaginary image or NULL on error @see cpl_image_fill_imag() Image can be CPL_TYPE_FLOAT_COMPLEX or CPL_TYPE_DOUBLE_COMPLEX. The returned image must be deallocated using cpl_image_delete(). Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if the input pointer is NULL - CPL_ERROR_INVALID_TYPE if the passed image type is non-complex */ /*----------------------------------------------------------------------------*/ cpl_image * cpl_image_extract_imag(const cpl_image * image) { cpl_image * self; cpl_ensure(image != NULL, CPL_ERROR_NULL_INPUT, NULL); self = cpl_image_new(image->nx, image->ny, image->type & ~CPL_TYPE_COMPLEX); if (cpl_image_fill_imag(self, image)) { (void)cpl_error_set_where_(); cpl_image_delete(self); self = NULL; } return self; } /*----------------------------------------------------------------------------*/ /** @internal @ingroup cpl_image @brief Extract the absolute part (modulus) of a complex image @param image input image @return a newly allocated imaginary image or NULL on error @see cpl_image_fill_mod() Image can be CPL_TYPE_FLOAT_COMPLEX or CPL_TYPE_DOUBLE_COMPLEX. The returned image must be deallocated using cpl_image_delete(). Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if the input pointer is NULL - CPL_ERROR_INVALID_TYPE if the passed image type is non-complex */ /*----------------------------------------------------------------------------*/ cpl_image * cpl_image_extract_mod(const cpl_image * image) { cpl_image * self; cpl_ensure(image != NULL, CPL_ERROR_NULL_INPUT, NULL); self = cpl_image_new(image->nx, image->ny, image->type & ~CPL_TYPE_COMPLEX); if (cpl_image_fill_mod(self, image)) { (void)cpl_error_set_where_(); cpl_image_delete(self); self = NULL; } return self; } /*----------------------------------------------------------------------------*/ /** @internal @ingroup cpl_image @brief Extract the argument (phase) of a complex image @param image input image @return a newly allocated imaginary image or NULL on error @see cpl_image_fill_phase() Image can be CPL_TYPE_FLOAT_COMPLEX or CPL_TYPE_DOUBLE_COMPLEX. The returned image must be deallocated using cpl_image_delete(). Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if the input pointer is NULL - CPL_ERROR_INVALID_TYPE if the passed image type is non-complex */ /*----------------------------------------------------------------------------*/ cpl_image * cpl_image_extract_phase(const cpl_image * image) { cpl_image * self; cpl_ensure(image != NULL, CPL_ERROR_NULL_INPUT, NULL); self = cpl_image_new(image->nx, image->ny, image->type & ~CPL_TYPE_COMPLEX); if (cpl_image_fill_phase(self, image)) { (void)cpl_error_set_where_(); cpl_image_delete(self); self = NULL; } return self; } #undef CPL_OPERATION #define CPL_OPERATION CPL_IMAGE_IO_SET /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @internal @brief Set the pixel at the given position to the given value @param image input image. @param xpos Pixel x position (FITS convention, 1 for leftmost) @param ypos Pixel y position (FITS convention, 1 for lowest) @param value New pixel value @return Nothing @see cpl_image_set() @note BPM not touched, no input validation */ /*----------------------------------------------------------------------------*/ inline void cpl_image_set_(cpl_image * image, cpl_size xpos, cpl_size ypos, double value) { const cpl_size pos = (xpos - 1) + image->nx * (ypos - 1); assert( image->pixels ); switch (image->type) { #define CPL_CLASS CPL_CLASS_DOUBLE #include "cpl_image_io_body.h" #undef CPL_CLASS #define CPL_CLASS CPL_CLASS_FLOAT #include "cpl_image_io_body.h" #undef CPL_CLASS #define CPL_CLASS CPL_CLASS_INT #include "cpl_image_io_body.h" #undef CPL_CLASS default: assert(0); } } #undef CPL_OPERATION /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Set the pixel at the given position to the given value @param image input image. @param xpos Pixel x position (FITS convention, 1 for leftmost) @param ypos Pixel y position (FITS convention, 1 for lowest) @param value New pixel value @return CPL_ERROR_NONE or the relevant #_cpl_error_code_ on error Images can be CPL_TYPE_FLOAT, CPL_TYPE_INT, CPL_TYPE_DOUBLE. If the pixel is flagged as rejected, this flag is removed. Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL - CPL_ERROR_ACCESS_OUT_OF_RANGE if the passed position is not in the image - CPL_ERROR_INVALID_TYPE if the image pixel type is not supported */ /*----------------------------------------------------------------------------*/ cpl_error_code cpl_image_set(cpl_image * image, cpl_size xpos, cpl_size ypos, double value) { /* Check entries */ cpl_ensure_code(image != NULL, CPL_ERROR_NULL_INPUT); cpl_ensure_code(xpos >= 1, CPL_ERROR_ACCESS_OUT_OF_RANGE); cpl_ensure_code(ypos >= 1, CPL_ERROR_ACCESS_OUT_OF_RANGE); cpl_ensure_code(xpos <= image->nx, CPL_ERROR_ACCESS_OUT_OF_RANGE); cpl_ensure_code(ypos <= image->ny, CPL_ERROR_ACCESS_OUT_OF_RANGE); cpl_ensure_code(!(image->type & CPL_TYPE_COMPLEX), CPL_ERROR_INVALID_TYPE); cpl_image_set_(image, xpos, ypos, value); cpl_image_accept_(image, xpos, ypos); return CPL_ERROR_NONE; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Set the pixel at the given position to the given complex value @param image input image. @param xpos Pixel x position (FITS convention, 1 for leftmost) @param ypos Pixel y position (FITS convention, 1 for lowest) @param value New pixel value @return CPL_ERROR_NONE or the relevant #_cpl_error_code_ on error @see cpl_image_set() @note This function is available iff the application includes complex.h Images can be CPL_TYPE_FLOAT_COMPLEX or CPL_TYPE_DOUBLE_COMPLEX. If the pixel is flagged as rejected, this flag is removed. Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL - CPL_ERROR_ACCESS_OUT_OF_RANGE if the passed position is not in the image - CPL_ERROR_INVALID_TYPE if the image pixel type is not supported */ /*----------------------------------------------------------------------------*/ cpl_error_code cpl_image_set_complex(cpl_image * image, cpl_size xpos, cpl_size ypos, double complex value) { cpl_size pos; /* Check entries */ cpl_ensure_code(image != NULL, CPL_ERROR_NULL_INPUT); cpl_ensure_code(xpos >= 1, CPL_ERROR_ACCESS_OUT_OF_RANGE); cpl_ensure_code(ypos >= 1, CPL_ERROR_ACCESS_OUT_OF_RANGE); cpl_ensure_code(xpos <= image->nx, CPL_ERROR_ACCESS_OUT_OF_RANGE); cpl_ensure_code(ypos <= image->ny, CPL_ERROR_ACCESS_OUT_OF_RANGE); /* cpl_ensure_code(image -> type & CPL_TYPE_COMPLEX, CPL_ERROR_INVALID_TYPE);*/ assert( image->pixels ); pos = (xpos - 1) + image->nx * (ypos - 1); if (image-> type == CPL_TYPE_FLOAT_COMPLEX) { float complex * pi = (float complex *)image->pixels; pi[pos] = (float complex)value; } else { double complex * pi = (double complex *)image->pixels; pi[pos] = value; } cpl_image_accept_(image, xpos, ypos); return CPL_ERROR_NONE; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Gets the pixel data. @param img Image to query. @return A pointer to the image pixel data or NULL on error. The returned pointer refers to already allocated data. Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL */ /*----------------------------------------------------------------------------*/ void * cpl_image_get_data(cpl_image * img) { cpl_ensure(img, CPL_ERROR_NULL_INPUT, NULL); return img->pixels; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Gets the pixel data. @param img Image to query. @return A pointer to the image pixel data or NULL on error. @see cpl_image_get_data */ /*----------------------------------------------------------------------------*/ const void * cpl_image_get_data_const(const cpl_image * img) { cpl_ensure(img, CPL_ERROR_NULL_INPUT, NULL); return img->pixels; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Replace the bad pixel map of the image @param self Image to modfify @param bpm Bad Pixel Map (BPM) to set, replacing the old one, or NULL @return A pointer to the old mask of bad pixels, or NULL @note NULL is returned if the image had no bad pixel map, while a non-NULL returned mask must be deallocated by the caller using cpl_mask_delete(). @see cpl_image_get_bpm_const() Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if self is NULL */ /*----------------------------------------------------------------------------*/ cpl_mask * cpl_image_set_bpm(cpl_image * self, cpl_mask * bpm) { cpl_mask * oldbpm; cpl_ensure(self != NULL, CPL_ERROR_NULL_INPUT, NULL); oldbpm = self->bpm; self->bpm = bpm; return oldbpm; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Remove the bad pixel map from the image @param self image to process @return A pointer to the cpl_mask of bad pixels, or NULL @note NULL is returned if the image has no bad pixel map @note The returned mask must be deallocated using cpl_mask_delete(). @see cpl_image_set_bpm() Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL */ /*----------------------------------------------------------------------------*/ cpl_mask * cpl_image_unset_bpm(cpl_image * self) { cpl_ensure(self != NULL, CPL_ERROR_NULL_INPUT, NULL); /* Cannot fail now */ return cpl_image_set_bpm(self, NULL); } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Gets the bad pixels map @param img Image to query. @return A pointer to the mask identifying the bad pixels or NULL. The returned pointer refers to already allocated data. If the bad pixel map is NULL, an empty one is created. Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL */ /*----------------------------------------------------------------------------*/ cpl_mask * cpl_image_get_bpm(cpl_image * img) { cpl_ensure(img != NULL, CPL_ERROR_NULL_INPUT, NULL); if (img->bpm == NULL) img->bpm = cpl_mask_new(img->nx, img->ny); return img->bpm; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Gets the bad pixels map @param img Image to query. @return A pointer to the mask identifying the bad pixels or NULL. @note NULL is returned if the image has no bad pixel map @see cpl_image_get_bpm Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL */ /*----------------------------------------------------------------------------*/ const cpl_mask * cpl_image_get_bpm_const(const cpl_image * img) { cpl_ensure(img != NULL, CPL_ERROR_NULL_INPUT, NULL); return img->bpm; } #define CPL_OPERATION CPL_IMAGE_IO_GET_PIXELS #define CPL_CONST /* const */ /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Get the data as a double array @param img a cpl_image object @return pointer to the double data array or NULL on error. The returned pointer refers to already allocated data. The pixels are stored in a one dimensional array. The pixel value PIXVAL at position (i, j) in the image - (0, 0) is the lower left pixel, i gives the column position from left to right, j gives the row position from bottom to top - is given by : PIXVAL = array[i + j*nx]; where nx is the x size of the image and array is the data array returned by this function. array can be used to access or modify the pixel value in the image. Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL - CPL_ERROR_TYPE_MISMATCH if the passed image type is not double */ /*----------------------------------------------------------------------------*/ double * cpl_image_get_data_double(cpl_image * img) { #define CPL_CLASS CPL_CLASS_DOUBLE #include "cpl_image_io_body.h" #undef CPL_CLASS } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Get the data as a float array @param img a cpl_image object @return pointer to the float data array or NULL on error. @see cpl_image_get_data_double() */ /*----------------------------------------------------------------------------*/ float * cpl_image_get_data_float(cpl_image * img) { #define CPL_CLASS CPL_CLASS_FLOAT #include "cpl_image_io_body.h" #undef CPL_CLASS } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Get the data as a double complex array @param img a cpl_image object @return pointer to the double complex data array or NULL on error. @see cpl_image_get_data_double() @note This function is available iff the application includes complex.h */ /*----------------------------------------------------------------------------*/ double complex * cpl_image_get_data_double_complex(cpl_image * img) { #define CPL_CLASS CPL_CLASS_DOUBLE_COMPLEX #include "cpl_image_io_body.h" #undef CPL_CLASS } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Get the data as a float complex array @param img a cpl_image object @return pointer to the float complex data array or NULL on error. @see cpl_image_get_data_double_complex() */ /*----------------------------------------------------------------------------*/ float complex * cpl_image_get_data_float_complex(cpl_image * img) { #define CPL_CLASS CPL_CLASS_FLOAT_COMPLEX #include "cpl_image_io_body.h" #undef CPL_CLASS } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Get the data as a integer array @param img a cpl_image object @return pointer to the integer data array or NULL on error. @see cpl_image_get_data_double() */ /*----------------------------------------------------------------------------*/ int * cpl_image_get_data_int(cpl_image * img) { #define CPL_CLASS CPL_CLASS_INT #include "cpl_image_io_body.h" #undef CPL_CLASS } #undef CPL_CONST #define CPL_CONST const /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Get the data as a double array @param img a cpl_image object @return pointer to the double data array or NULL on error. @see cpl_image_get_data_double */ /*----------------------------------------------------------------------------*/ const double * cpl_image_get_data_double_const(const cpl_image * img) { #define CPL_CLASS CPL_CLASS_DOUBLE #include "cpl_image_io_body.h" #undef CPL_CLASS } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Get the data as a float array @param img a cpl_image object @return pointer to the float data array or NULL on error. @see cpl_image_get_data_float() */ /*----------------------------------------------------------------------------*/ const float * cpl_image_get_data_float_const(const cpl_image * img) { #define CPL_CLASS CPL_CLASS_FLOAT #include "cpl_image_io_body.h" #undef CPL_CLASS } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Get the data as a double complex array @param img a cpl_image object @return pointer to the double complex data array or NULL on error. @see cpl_image_get_data_double_complex() */ /*----------------------------------------------------------------------------*/ const double complex * cpl_image_get_data_double_complex_const(const cpl_image * img) { #define CPL_CLASS CPL_CLASS_DOUBLE_COMPLEX #include "cpl_image_io_body.h" #undef CPL_CLASS } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Get the data as a float complex array @param img a cpl_image object @return pointer to the float complex data array or NULL on error. @see cpl_image_get_data_double_complex() */ /*----------------------------------------------------------------------------*/ const float complex * cpl_image_get_data_float_complex_const(const cpl_image * img) { #define CPL_CLASS CPL_CLASS_FLOAT_COMPLEX #include "cpl_image_io_body.h" #undef CPL_CLASS } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Get the data as a integer array @param img a cpl_image object @return pointer to the integer data array or NULL on error. @see cpl_image_get_data_int() */ /*----------------------------------------------------------------------------*/ const int * cpl_image_get_data_int_const(const cpl_image * img) { #define CPL_CLASS CPL_CLASS_INT #include "cpl_image_io_body.h" #undef CPL_CLASS } #undef CPL_OPERATION /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Free memory associated to an cpl_image object. @param d Image to destroy. @return void Frees all memory associated with a cpl_image. If the passed image is NULL, the function returns without doing anything. */ /*----------------------------------------------------------------------------*/ void cpl_image_delete(cpl_image * d) { if (d == NULL) return; /* Delete pixels and bad pixel map */ cpl_free(d->pixels); cpl_mask_delete(d->bpm); cpl_free(d); } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Free memory associated to an cpl_image object, but the pixel buffer. @param d Image to destroy. @return A pointer to the data array or NULL if the input is NULL. Frees all memory associated to an cpl_image, except the pixel buffer. cpl_image_unwrap() is provided for images that are constructed by passing a pixel buffer to one of cpl_image_wrap_{double,float,int}(). @note The pixel buffer must subsequently be deallocated. Failure to do so will result in a memory leak. */ /*----------------------------------------------------------------------------*/ void * cpl_image_unwrap(cpl_image * d) { void * data; if (d == NULL) return NULL; /* Delete bad pixel map */ cpl_mask_delete(d->bpm); data = (void *) d->pixels; cpl_free(d); return data; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Copy an image. @param src Source image. @return 1 newly allocated image, or NULL on error. Copy an image into a new image object. The pixels and the bad pixel map are also copied. The returned image must be deallocated using cpl_image_delete(). Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL */ /*----------------------------------------------------------------------------*/ cpl_image * cpl_image_duplicate(const cpl_image * src) { cpl_image * self; cpl_ensure(src != NULL, CPL_ERROR_NULL_INPUT, NULL); /* Allocate and copy the image properties into a new image - must update all (one or two) non-NULL pointer members */ self = memcpy(cpl_malloc(sizeof(cpl_image)), src, sizeof(cpl_image)); /* 1: Allocate and copy the pixel buffer */ self->pixels = cpl_malloc((size_t)src->nx * (size_t)src->ny * cpl_type_get_sizeof(src->type)); (void)memcpy(self->pixels, src->pixels, (size_t)src->nx * (size_t)src->ny * cpl_type_get_sizeof(src->type)); /* 2: Duplicate the bad pixel map, if any */ if (src->bpm != NULL) self->bpm = cpl_mask_duplicate(src->bpm); return self; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Convert a cpl_image to a given type @param self The image to convert @param type The destination type @return the newly allocated cpl_image or NULL on error Casting to non-complex types is only supported for non-complex types. Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL - CPL_ERROR_ILLEGAL_INPUT if the passed type is invalid - CPL_ERROR_TYPE_MISMATCH if the passed image type is complex and requested casting type is non-complex. - CPL_ERROR_INVALID_TYPE if the passed pixel type is not supported */ /*----------------------------------------------------------------------------*/ cpl_image * cpl_image_cast(const cpl_image * self, cpl_type type) { cpl_image * new_im; void * ppixels; cpl_ensure(self != NULL, CPL_ERROR_NULL_INPUT, NULL); /* The source image has the destination type */ if (self->type == type) return cpl_image_duplicate(self); cpl_ensure(type != CPL_TYPE_INVALID, CPL_ERROR_ILLEGAL_INPUT, NULL); ppixels = cpl_malloc((size_t)(self->nx * self->ny) * cpl_type_get_sizeof(type)); /* Switch on the destination type */ switch (type) { case CPL_TYPE_FLOAT: { float * pfo = (float*)ppixels; /* Switch on the source type */ switch(self->type) { case CPL_TYPE_DOUBLE: { const double * pdi = (const double*)self->pixels; for (cpl_size i = 0; i < self->nx * self->ny; i++) pfo[i] = (float)pdi[i]; break; } case CPL_TYPE_INT: { const int * pii = (const int*)self->pixels; for (cpl_size i = 0; i < self->nx * self->ny; i++) pfo[i] = (float)pii[i]; break; } case CPL_TYPE_FLOAT_COMPLEX: case CPL_TYPE_DOUBLE_COMPLEX: cpl_free(ppixels); (void)cpl_error_set_(CPL_ERROR_TYPE_MISMATCH); return NULL; default: cpl_free(ppixels); (void)cpl_error_set_(CPL_ERROR_INVALID_TYPE); return NULL; } break; } case CPL_TYPE_DOUBLE: { double * pdo = (double*)ppixels; /* Switch on the source type */ switch(self->type) { case CPL_TYPE_FLOAT: { const float * pfi = (const float*)self->pixels; for (cpl_size i = 0; i < self->nx * self->ny; i++) pdo[i] = (double)pfi[i]; break; } case CPL_TYPE_INT: { const int * pii = (const int*)self->pixels; for (cpl_size i = 0; i < self->nx * self->ny; i++) pdo[i] = (double)pii[i]; break; } case CPL_TYPE_FLOAT_COMPLEX: case CPL_TYPE_DOUBLE_COMPLEX: cpl_free(ppixels); (void)cpl_error_set_(CPL_ERROR_TYPE_MISMATCH); return NULL; default: cpl_free(ppixels); (void)cpl_error_set_(CPL_ERROR_INVALID_TYPE); return NULL; } break; } case CPL_TYPE_INT: { int * pio = (int*)ppixels; /* Switch on the source type */ switch(self->type) { case CPL_TYPE_FLOAT: { const float * pfi = (const float*)self->pixels; for (cpl_size i = 0; i < self->nx * self->ny; i++) pio[i] = (int)pfi[i]; break; } case CPL_TYPE_DOUBLE: { const double * pdi = (const double*)self->pixels; for (cpl_size i = 0; i < self->nx * self->ny; i++) pio[i] = (int)pdi[i]; break; } case CPL_TYPE_FLOAT_COMPLEX: case CPL_TYPE_DOUBLE_COMPLEX: cpl_free(ppixels); (void)cpl_error_set_(CPL_ERROR_TYPE_MISMATCH); return NULL; default: cpl_free(ppixels); (void)cpl_error_set_(CPL_ERROR_INVALID_TYPE); return NULL; } break; } case CPL_TYPE_FLOAT_COMPLEX: { float complex * pfco = (float complex*)ppixels; /* Switch on the source type */ switch(self->type) { case CPL_TYPE_DOUBLE_COMPLEX: { const double complex * pdci = (const double complex *)self->pixels; for (cpl_size i = 0; i < self->nx * self->ny; i++) pfco[i] = (float complex)pdci[i]; break; } case CPL_TYPE_INT: { const int * pii = (const int *)self->pixels; for (cpl_size i = 0; i < self->nx * self->ny; i++) pfco[i] = (float complex)pii[i]; break; } case CPL_TYPE_FLOAT: { const float * pfi = (const float*)self->pixels; for (cpl_size i = 0; i < self->nx * self->ny; i++) pfco[i] = (float complex)pfi[i]; break; } case CPL_TYPE_DOUBLE: { const double * pdi = (const double*)self->pixels; for (cpl_size i = 0; i < self->nx * self->ny; i++) pfco[i] = (float complex)pdi[i]; break; } default: cpl_free(ppixels); (void)cpl_error_set_(CPL_ERROR_INVALID_TYPE); return NULL; } break; } case CPL_TYPE_DOUBLE_COMPLEX: { double complex * pdco = (double complex*)ppixels; /* Switch on the source type */ switch(self->type) { case CPL_TYPE_FLOAT_COMPLEX: { const float complex * pfci = (const float complex*)self->pixels; for (cpl_size i = 0; i < self->nx * self->ny; i++) pdco[i] = (double complex)pfci[i]; break; } case CPL_TYPE_INT: { const int * pii = (const int *)self->pixels; for (cpl_size i = 0; i < self->nx * self->ny; i++) pdco[i] = (double complex)pii[i]; break; } case CPL_TYPE_FLOAT: { const float * pfi = (const float*)self->pixels; for (cpl_size i = 0; i < self->nx * self->ny; i++) pdco[i] = (double complex)pfi[i]; break; } case CPL_TYPE_DOUBLE: { const double * pdi = (const double*)self->pixels; for (cpl_size i = 0; i < self->nx * self->ny; i++) pdco[i] = (double complex)pdi[i]; break; } default: cpl_free(ppixels); (void)cpl_error_set_(CPL_ERROR_INVALID_TYPE); return NULL; } break; } default: cpl_free(ppixels); (void)cpl_error_set_message_(CPL_ERROR_INVALID_TYPE, "source: %s <=> %s-destination", cpl_type_get_name(self->type), cpl_type_get_name(type)); return NULL; } new_im = cpl_image_wrap_(self->nx, self->ny, type, ppixels); /* Bad pixel map */ if (self->bpm != NULL) new_im->bpm = cpl_mask_duplicate(self->bpm); return new_im; } #define CPL_OPERATION CPL_IMAGE_IO_SET_BADPIXEL /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Set the bad pixels in an image to a fixed value @param im The image to modify. @param a The fixed value @return the #_cpl_error_code_ or CPL_ERROR_NONE Images can be CPL_TYPE_FLOAT, CPL_TYPE_INT, CPL_TYPE_DOUBLE. Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL - CPL_ERROR_ILLEGAL_INPUT - CPL_ERROR_INVALID_TYPE if the image pixel type is not supported */ /*----------------------------------------------------------------------------*/ cpl_error_code cpl_image_fill_rejected( cpl_image * im, double a) { cpl_binary * pbpm; /* Check entries and Initialise */ cpl_ensure_code(im, CPL_ERROR_NULL_INPUT); /* If no bad pixel */ if (im->bpm == NULL) return CPL_ERROR_NONE; /* Return if no bad pixel map to update */ if (cpl_mask_is_empty(im->bpm)) return CPL_ERROR_NONE; pbpm = cpl_mask_get_data(im->bpm); switch (im->type) { #define CPL_CLASS CPL_CLASS_DOUBLE #include "cpl_image_io_body.h" #undef CPL_CLASS #define CPL_CLASS CPL_CLASS_FLOAT #include "cpl_image_io_body.h" #undef CPL_CLASS #define CPL_CLASS CPL_CLASS_INT #include "cpl_image_io_body.h" #undef CPL_CLASS #define CPL_CLASS CPL_CLASS_DOUBLE_COMPLEX #include "cpl_image_io_body.h" #undef CPL_CLASS #define CPL_CLASS CPL_CLASS_FLOAT_COMPLEX #include "cpl_image_io_body.h" #undef CPL_CLASS default: return cpl_error_set_(CPL_ERROR_INVALID_TYPE); } return CPL_ERROR_NONE; } #undef CPL_OPERATION /*----------------------------------------------------------------------------*/ /** @internal @ingroup cpl_image @brief Save one or more images to a FITS file @param self Image(s) of identical size and type to write to disk @param nz Number of images @param is_cube CPL_TRUE: use NAXIS3, otherwise NAXIS2 (ignored: nz > 1) @param filename Name of the file to write to @param type The type used to represent the data in the file @param pl Property list for the output header or NULL @param mode The desired output options @return CPL_ERROR_NONE or the relevant #_cpl_error_code_ on error @see cpl_image_save() */ /*----------------------------------------------------------------------------*/ cpl_error_code cpl_image_save_(const cpl_image * const* self, cpl_size nz, cpl_boolean is_cube, const char * filename, cpl_type type, const cpl_propertylist * pl, unsigned mode) { int status = 0; /* CFITSIO status, must be set to zero */ /* Count number of compression flags */ const unsigned ncompress = ((mode & CPL_IO_COMPRESS_GZIP) != 0) + ((mode & CPL_IO_COMPRESS_HCOMPRESS) != 0) + ((mode & CPL_IO_COMPRESS_PLIO) != 0) + ((mode & CPL_IO_COMPRESS_RICE) != 0); fitsfile * fptr; cpl_size i; const char * badkeys = mode & CPL_IO_EXTEND ? CPL_FITS_BADKEYS_EXT "|" CPL_FITS_COMPRKEYS : CPL_FITS_BADKEYS_PRIM "|" CPL_FITS_COMPRKEYS; const cpl_image * first = self ? self[0] : NULL; const cpl_size nx = cpl_image_get_size_x(first); const cpl_size ny = cpl_image_get_size_y(first); const cpl_type ftype = cpl_image_get_type(first); const int cfitsiotype = ftype == CPL_TYPE_DOUBLE ? TDOUBLE : (ftype == CPL_TYPE_FLOAT ? TFLOAT : TINT); const CPL_FITSIO_TYPE naxes[3] = {nx, ny, nz}; long plane1 = 0; /* First plane to write */ const int ibpp = cpl_tools_get_bpp(type == CPL_TYPE_UNSPECIFIED ? ftype : type); const int naxis23 = (nz > 1 || is_cube) ? 3 : 2; /* Test entries */ cpl_ensure_code(filename != NULL, CPL_ERROR_NULL_INPUT); cpl_ensure_code(self != NULL, CPL_ERROR_NULL_INPUT); cpl_ensure_code(ibpp != 0, CPL_ERROR_ILLEGAL_INPUT); if (is_cube) { cpl_ensure_code(((mode & CPL_IO_CREATE) != 0) + ((mode & CPL_IO_EXTEND) != 0) + ((mode & CPL_IO_APPEND) != 0) == 1, CPL_ERROR_ILLEGAL_INPUT); } else { cpl_ensure_code(((mode & CPL_IO_CREATE) != 0) + ((mode & CPL_IO_EXTEND) != 0) == 1, CPL_ERROR_ILLEGAL_INPUT); } cpl_ensure_code(mode < CPL_IO_MAX, CPL_ERROR_ILLEGAL_INPUT); cpl_ensure_code(ftype == CPL_TYPE_DOUBLE || ftype == CPL_TYPE_FLOAT || ftype == CPL_TYPE_INT, CPL_ERROR_INVALID_TYPE); if (mode & (CPL_IO_EXTEND | CPL_IO_APPEND)) { if (ncompress > 0) { if (ncompress > 1) { /* Only one type of compression is allowed */ return cpl_error_set_message_(CPL_ERROR_ILLEGAL_INPUT, "Specify one compression method, " "not %d (mode=0x%x)", ncompress, mode); } if (mode & CPL_IO_APPEND) { /* A compression flag is not allowed in append mode - it would at best be redundant or else in conflict with the existing compression method (which includes no compression) */ return cpl_error_set_message_(CPL_ERROR_ILLEGAL_INPUT, "Compression in append mode not " "allowed"); } if (abs(ibpp) < 32) { return cpl_error_set_message_(CPL_ERROR_UNSUPPORTED_MODE, "Compression not supported " "with implicit conversion to " "BITPIX=%d (type='%s'), use e.g. " "type='CPL_TYPE_INT'", ibpp, cpl_type_get_name(type)); } #ifndef CPL_IO_COMPRESSION_LOSSY if (ibpp < 0) { /* No compression of floating-point data - yet */ return cpl_error_set_message_(CPL_ERROR_UNSUPPORTED_MODE, "Lossy compression not supported " "(BITPIX=%d < 0)", ibpp); } #endif } /* Open the file */ if (cpl_io_fits_open_diskfile(&fptr, filename, READWRITE, &status)) { return cpl_error_set_fits(CPL_ERROR_FILE_IO, status, fits_open_diskfile, "filename='%s', " "type=%d, mode=%d", filename, type, mode); } if (mode & CPL_IO_COMPRESS_GZIP) fits_set_compression_type(fptr, GZIP_1, &status); else if (mode & CPL_IO_COMPRESS_HCOMPRESS) fits_set_compression_type(fptr, HCOMPRESS_1, &status); else if (mode & CPL_IO_COMPRESS_PLIO) fits_set_compression_type(fptr, PLIO_1, &status); else if (mode & CPL_IO_COMPRESS_RICE) fits_set_compression_type(fptr, RICE_1, &status); if (status != 0) { int fio_status2 = 0; cpl_io_fits_close_file(fptr, &fio_status2); return cpl_error_set_fits(CPL_ERROR_FILE_IO, status, fits_set_compression_type, "filename='%s', type=%d, mode=%d", filename, type, mode); } } else if (ncompress > 0) { /* Compression is only allowed in extensions */ return cpl_error_set_(CPL_ERROR_ILLEGAL_INPUT); } else { /* Create the file */ char * sval = cpl_sprintf("!%s", filename); cpl_io_fits_create_file(&fptr, sval, &status); cpl_free(sval); if (status != 0) { return cpl_error_set_fits(CPL_ERROR_FILE_IO, status, fits_create_file, "filename='%s', " "type=%d, mode=%d", filename, type, mode); } } if (mode & CPL_IO_APPEND) { int next; int exttype; int naxis; int bitpix; /* Last element read on naxis=2 */ CPL_FITSIO_TYPE fnaxes[3]; if (fits_get_num_hdus(fptr, &next, &status)) { int error2 = 0; cpl_io_fits_close_file(fptr, &error2); return cpl_error_set_fits(CPL_ERROR_FILE_IO, status, fits_get_num_hdus, "filename='%s', " "type=%d, mode=%d", filename, type, mode); } else if (fits_movabs_hdu(fptr, next, &exttype, &status)) { int error2 = 0; cpl_io_fits_close_file(fptr, &error2); return cpl_error_set_fits(CPL_ERROR_FILE_IO, status, fits_movabs_hdu, "filename='%s', type=%d, mode=%d", filename, type, mode); } else if (exttype != IMAGE_HDU) { int error2 = 0; return cpl_io_fits_close_file(fptr, &error2) ? cpl_error_set_fits(CPL_ERROR_FILE_IO, error2, fits_close_file, "filename='%s', " "type=%d, mode=%d", filename, type, mode) : cpl_error_set_message_(CPL_ERROR_ILLEGAL_INPUT, "Data-unit " "%d in file %s is not image-type (%d " "!= %d. type=%d, mode=%d)", next, filename, exttype, IMAGE_HDU, type, mode); } else if (fits_get_img_dim(fptr, &naxis, &status)) { int error2 = 0; cpl_io_fits_close_file(fptr, &error2); return cpl_error_set_fits(CPL_ERROR_FILE_IO, status, fits_get_img_dim, "filename='%s', " "type=%d, mode=%d", filename, type, mode); } else if (naxis < 2 || naxis > 3) { int error2 = 0; return cpl_io_fits_close_file(fptr, &error2) ? cpl_error_set_fits(CPL_ERROR_FILE_IO, error2, fits_close_file, "filename='%s', " "type=%d, mode=%d", filename, type, mode) : cpl_error_set_message_(CPL_ERROR_ILLEGAL_INPUT, "Data-unit " "%d in file %s has wrong NAXIS (%d !=" " 2/3). type=%d, mode=%d)", next, filename, naxis, type, mode); } else if (fits_get_img_type(fptr, &bitpix, &status)) { int error2 = 0; cpl_io_fits_close_file(fptr, &error2); return cpl_error_set_fits(CPL_ERROR_FILE_IO, status, fits_get_img_type, "filename='%s', type=" "%d, mode=%d", filename, type, mode); } else if (bitpix != ibpp) { int error2 = 0; return cpl_io_fits_close_file(fptr, &error2) ? cpl_error_set_fits(CPL_ERROR_FILE_IO, error2, fits_close_file, "filename='%s', " "type=%d, mode=%d", filename, type, mode) : cpl_error_set_message_(CPL_ERROR_ILLEGAL_INPUT, "Data-unit " "%d in file %s has wrong BITPIX (%d " "!= %d). type=%d, mode=%d)", next, filename, bitpix, ibpp, type, mode); } else if (CPL_FITSIO_GET_SIZE(fptr, naxis, fnaxes, &status)) { int error2 = 0; cpl_io_fits_close_file(fptr, &error2); return cpl_error_set_fits(CPL_ERROR_FILE_IO, status, CPL_FITSIO_GET_SIZE, "filename='%s', type=%d, mode=%d", filename, type, mode); } else if (naxes[0] != fnaxes[0] || naxes[1] != fnaxes[1]) { int error2 = 0; return cpl_io_fits_close_file(fptr, &error2) ? cpl_error_set_fits(CPL_ERROR_FILE_IO, error2, fits_close_file, "filename='%s', " "type=%d, mode=%d", filename, type, mode) : cpl_error_set_message_ (CPL_ERROR_ILLEGAL_INPUT, "Data-unit %d in file %s has " "wrong NAXIS1/2 (%ldX%ld != %ldX%ld). type=%d, mode=%d)", next, filename, (long)fnaxes[0], (long)fnaxes[1], (long)naxes[0], (long)naxes[1], type, mode); } else if (fits_is_compressed_image(fptr, &status) && !status) { return cpl_io_fits_close_file(fptr, &status) ? cpl_error_set_fits(CPL_ERROR_FILE_IO, status, fits_close_file, "filename='%s', " "type=%d, mode=%d", filename, type, mode) : cpl_error_set_message_(CPL_ERROR_UNSUPPORTED_MODE, "Data-" "unit %d in file %s is compressed. " "type=%d, mode=%d)", next, filename, type, mode); } else if (status) { int error2 = 0; cpl_io_fits_close_file(fptr, &error2); return cpl_error_set_fits(CPL_ERROR_FILE_IO, status, fits_is_compressed_image, "filename='%s', type=%d, mode=%d", filename, type, mode); } else { plane1 = fnaxes[2]; fnaxes[2] += naxes[2]; if (CPL_FITSIO_RESIZE_IMG(fptr, bitpix, naxis, fnaxes, &status)) { int error2 = 0; cpl_io_fits_close_file(fptr, &error2); return cpl_error_set_fits(CPL_ERROR_FILE_IO, status, CPL_FITSIO_RESIZE_IMG, "filename='%s', type=%d, mode=%d", filename, type, mode); } } } else if /* Create the imagelist in a new HDU appended to the file */ (CPL_FITSIO_CREATE_IMG(fptr, ibpp, naxis23, naxes, &status)) { int error2 = 0; cpl_io_fits_close_file(fptr, &error2); return cpl_error_set_fits(CPL_ERROR_FILE_IO, status, CPL_FITSIO_CREATE_IMG_E, "filename='%s', type=%d, mode=%d", filename, type, mode); } else if /* Add Date, if creating */ ((mode & CPL_IO_CREATE) && fits_write_date(fptr, &status)) { int error2 = 0; cpl_io_fits_close_file(fptr, &error2); return cpl_error_set_fits(CPL_ERROR_FILE_IO, status, fits_write_date, "filename='%s', type=%d, mode=%d", filename, type, mode); } /* Add the property list */ if (cpl_fits_add_properties(fptr, pl, badkeys)) { return cpl_io_fits_close_file(fptr, &status) ? cpl_error_set_fits(CPL_ERROR_FILE_IO, status, fits_close_file, "filename='%s', " "type=%d, mode=%d", filename, type, mode) : cpl_error_set_(CPL_ERROR_ILLEGAL_INPUT); } /* Loop on the images */ for (i = 0; i < nz; i++) { const CPL_FITSIO_TYPE fpixel[3] = {1, 1, plane1 + i + 1}; const cpl_image * image = self[i]; const void * data = cpl_image_get_data_const(image); /* Write the pixels */ if (CPL_FITSIO_WRITE_PIX(fptr, cfitsiotype, fpixel, (LONGLONG)(nx*ny), data, &status)) break; } /* Check */ if (status) { int error2 = 0; cpl_io_fits_close_file(fptr, &error2); return cpl_error_set_fits(CPL_ERROR_FILE_IO, status, CPL_FITSIO_WRITE_PIX_E, "filename='%s', " "type=%d, mode=%d, plane=%u", filename, type, mode, (unsigned)i); } /* Close (and write to disk) */ return cpl_io_fits_close_file(fptr, &status) ? cpl_error_set_fits(CPL_ERROR_FILE_IO, status, fits_close_file, "filename='%s', " "type=%d, mode=%d", filename, type, mode) : CPL_ERROR_NONE; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Save an image to a FITS file @param self Image to write to disk or NULL @param filename Name of the file to write to @param type The type used to represent the data in the file @param pl Property list for the output header or NULL @param mode The desired output options @return CPL_ERROR_NONE or the relevant #_cpl_error_code_ on error @see cpl_propertylist_save() This function saves an image to a FITS file. If a property list is provided, it is written to the header where the image is written. The image may be NULL, in this case only the propertylist is saved. Supported image types are CPL_TYPE_DOUBLE, CPL_TYPE_FLOAT, CPL_TYPE_INT. The type used in the file can be one of: CPL_TYPE_UCHAR (8 bit unsigned), CPL_TYPE_SHORT (16 bit signed), CPL_TYPE_USHORT (16 bit unsigned), CPL_TYPE_INT (32 bit signed), CPL_TYPE_FLOAT (32 bit floating point), or CPL_TYPE_DOUBLE (64 bit floating point). Additionally, the special value CPL_TYPE_UNSPECIFIED is allowed. This value means that the type used for saving is the pixel type of the input image. Using the image pixel type as saving type ensures that the saving incurs no loss of information. Supported output modes are CPL_IO_CREATE (create a new file) and CPL_IO_EXTEND (append a new extension to an existing file). Upon success the image will reside in a FITS data unit with NAXIS = 2. Is it possible to save a single image in a FITS data unit with NAXIS = 3, see cpl_imagelist_save(). When the data written to disk are of an integer type, the output mode CPL_IO_EXTEND can be combined (via bit-wise or) with an option for tile-compression. This compression of integer data is lossless. The options are: CPL_IO_COMPRESS_GZIP, CPL_IO_COMPRESS_RICE, CPL_IO_COMPRESS_HCOMPRESS, CPL_IO_COMPRESS_PLIO. With compression the type must be CPL_TYPE_UNSPECIFIED or CPL_TYPE_INT. Note that in append mode the file must be writable (and do not take for granted that a file is writable just because it was created by the same application, as this depends from the system @em umask). Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL - CPL_ERROR_ILLEGAL_INPUT if the type or the mode is not supported - CPL_ERROR_INVALID_TYPE if the passed pixel type is not supported - CPL_ERROR_FILE_NOT_CREATED if the output file cannot be created - CPL_ERROR_FILE_IO if the data cannot be written to the file */ /*----------------------------------------------------------------------------*/ cpl_error_code cpl_image_save(const cpl_image * self, const char * filename, cpl_type type, const cpl_propertylist * pl, unsigned mode) { const cpl_error_code error = self == NULL ? cpl_propertylist_save(pl, filename, mode) : cpl_image_save_(&self, 1, CPL_FALSE, filename, type, pl, mode); return error ? cpl_error_set_where_() : CPL_ERROR_NONE; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Dump structural information of a CPL image @param self Image to dump @param stream Output stream, accepts @c stdout or @c stderr @return CPL_ERROR_NONE or the relevant #_cpl_error_code_ on error Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL - CPL_ERROR_FILE_IO if a write operation fails */ /*----------------------------------------------------------------------------*/ cpl_error_code cpl_image_dump_structure(const cpl_image * self, FILE * stream) { const int msgmin = (int)(strlen(CPL_MSG) - 2 - 3 * strlen(CPL_SIZE_FORMAT)); cpl_ensure_code(self != NULL, CPL_ERROR_NULL_INPUT); cpl_ensure_code(stream != NULL, CPL_ERROR_NULL_INPUT); cpl_ensure_code( fprintf(stream, CPL_MSG, self->nx, self->ny, cpl_type_get_name(self->type), self->bpm ? cpl_mask_count(self->bpm) : 0) >= msgmin, CPL_ERROR_FILE_IO); return CPL_ERROR_NONE; } /*----------------------------------------------------------------------------*/ /** @ingroup cpl_image @brief Dump pixel values in a CPL image @param self Image to dump @param llx Lower left x position (FITS convention, 1 for leftmost) @param lly Lower left y position (FITS convention, 1 for lowest) @param urx Specifies the window position @param ury Specifies the window position @param stream Output stream, accepts @c stdout or @c stderr @return CPL_ERROR_NONE or the relevant #_cpl_error_code_ on error Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL - CPL_ERROR_FILE_IO if a write operation fails - CPL_ERROR_ACCESS_OUT_OF_RANGE if the defined window is not in the image - CPL_ERROR_ILLEGAL_INPUT if the window definition is wrong (e.g llx > urx) */ /*----------------------------------------------------------------------------*/ cpl_error_code cpl_image_dump_window(const cpl_image * self, cpl_size llx, cpl_size lly, cpl_size urx, cpl_size ury, FILE * stream) { const cpl_error_code err = CPL_ERROR_FILE_IO; cpl_size i, j; cpl_boolean has_bad; cpl_ensure_code(self != NULL, CPL_ERROR_NULL_INPUT); cpl_ensure_code(stream != NULL, CPL_ERROR_NULL_INPUT); cpl_ensure_code(llx > 0 && llx <= self->nx && urx > 0 && urx <= self->nx, CPL_ERROR_ACCESS_OUT_OF_RANGE); cpl_ensure_code(lly > 0 && lly <= self->ny && ury > 0 && ury <= self->ny, CPL_ERROR_ACCESS_OUT_OF_RANGE); cpl_ensure_code(urx >= llx && ury >= lly, CPL_ERROR_ILLEGAL_INPUT); has_bad = self->bpm != NULL && !cpl_mask_is_empty(self->bpm); cpl_ensure_code( fprintf(stream, "#----- image: %" CPL_SIZE_FORMAT " <= x <= %" CPL_SIZE_FORMAT ", %" CPL_SIZE_FORMAT " <= y <= %" CPL_SIZE_FORMAT " -----\n", llx, urx, lly, ury) > 0, err); cpl_ensure_code( fprintf(stream, "\tX\tY\tvalue\n") > 0, err); for (j = lly; j <= ury; j++) { for (i = llx; i <= urx; i++) { const char * badtxt = has_bad && cpl_mask_get(self->bpm, i, j) ? " (rejected)" : ""; if (self->type == CPL_TYPE_INT) { const int * pint = (const int*)self->pixels; const int value = pint[(i-1) + (j-1) * self->nx]; cpl_ensure_code( fprintf(stream, "\t%" CPL_SIZE_FORMAT "\t%" CPL_SIZE_FORMAT "\t%d%s\n", i, j, value, badtxt) > 0, err); } else if (self->type == CPL_TYPE_FLOAT_COMPLEX || self->type == CPL_TYPE_DOUBLE_COMPLEX ) { int dummy; const double complex value = cpl_image_get_complex(self, i, j, &dummy); cpl_ensure_code( fprintf(stream, "\t%" CPL_SIZE_FORMAT "\t%" CPL_SIZE_FORMAT "\t%g + %g I %s\n", i, j, creal(value), cimag(value), badtxt) > 0, err); } else { int dummy; const double value = cpl_image_get(self, i, j, &dummy); cpl_ensure_code( fprintf(stream, "\t%" CPL_SIZE_FORMAT "\t%" CPL_SIZE_FORMAT "\t%g%s\n", i, j, value, badtxt) > 0, err); } } } return CPL_ERROR_NONE; } #define FFSTACK_PUSH(Y, XL, XR, DY) \ if (sp<stack+stacksz && Y+(DY)>=wy1 && Y+(DY)<=wy2) \ {sp->y = Y; sp->xl = XL; sp->xr = XR; sp->dy = DY; sp++;} #define FFSTACK_POP(Y, XL, XR, DY) \ {sp--; Y = sp->y+(DY = sp->dy); XL = sp->xl; XR = sp->xr;} /*----------------------------------------------------------------------------*/ /* @internal @ingroup cpl_image @brief Fill a zone with label. @param intimage input label image @param fftemp Pre-allocated work-space @param x x position @param y y position @param label current label This code was pulled out the Usenet and freely adapted to cpl. Credits - Paul Heckbert (posted on comp.graphics 28 Apr 1988) It is highly unreadable and makes use of goto and other fairly bad programming practices, but works fine and fast. */ /*----------------------------------------------------------------------------*/ static void cpl_image_floodfill(cpl_image * lab, void * fftemp, cpl_size x, cpl_size y, cpl_size label) { struct { cpl_size y, xl, xr, dy; } * stack, * sp; cpl_size wx1, wx2, wy1, wy2; cpl_size l, x1, x2, dy; cpl_size ov; const cpl_size stacksz = FFSTACK_STACKSZ(lab); int * pii; stack = fftemp; sp = stack; wx1 = 0; wx2 = lab->nx-1; wy1 = 0; wy2 = lab->ny-1; pii = cpl_image_get_data_int(lab); ov = pii[x+y*lab->nx]; if (ov==label || x<wx1 || x>wx2 || y<wy1 || y>wy2) return; FFSTACK_PUSH(y, x, x, 1); /* needed in some cases */ FFSTACK_PUSH(y+1, x, x, -1); /* seed segment (popped 1st) */ while (sp>stack) { /* pop segment off stack and fill a neighboring scan line */ FFSTACK_POP(y, x1, x2, dy); /* * segment of scan line y-dy for x1<=x<=x2 was previously filled, * now explore adjacent pixels in scan line y */ for (x=x1; x>=wx1 && pii[x+y*lab->nx]==ov; x--) pii[x+y*lab->nx] = (int)label; /* FIXME: Need cpl_size pixel */ if (x>=x1) goto skip; l = x+1; if (l<x1) FFSTACK_PUSH(y, l, x1-1, -dy); /* leak on left? */ x = x1+1; do { for (; x<=wx2 && pii[x+y*lab->nx]==ov; x++) pii[x+y*lab->nx] = (int)label; /* FIXME: Need cpl_size pixel */ FFSTACK_PUSH(y, l, x-1, dy); if (x>x2+1) FFSTACK_PUSH(y, x2+1, x-1, -dy); /* leak on right? */ skip: for (x++; x<=x2 && pii[x+y*lab->nx]!=ov; x++) { ; } l = x; } while (x<=x2); } } /*----------------------------------------------------------------------------*/ /* @internal @brief Internal image loading function @param fptr CFITSIO structure of the already opened FITS file @param pnaxis If it points to 0, set *pnaxis to NAXIS else use as such @param naxes If 1st is 0, fill w. NAXIS[12[3]] else use as such @param ppix_type If points to _UNSPECIFIED, set else use as such @param filename The named of the opened file (only for error messages) @param pnum Plane number in the Data Unit (0 for first) @param lhdumov Absolute extension number to move to first (0 for primary) @param do_window True for (and only for) a windowed load @param llx Lower left x position (FITS convention, 1 for leftmost) @param lly Lower left y position (FITS convention, 1 for lowest) @param urx Specifies the window position @param ury Specifies the window position @return 1 newly allocated image or NULL if image cannot be loaded. @see cpl_image_load_one() This function reads from an already opened FITS-file, which is useful when multiple images are to be loaded from the same file. To avoid repeated calls to determine NAXIS, NAXISi and optionally the CPL pixel-type most suitable for the the actual FITS data, the parameters pnaxis, naxes and ppix_type can be used both for input and for output. The extension number lhdumov is numbered with 1 for the first extension, i.e. 0 moves to the primary HDU. Any negative value causes no move. Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if an input pointer is NULL - CPL_ERROR_BAD_FILE_FORMAT if a CFITSIO call fails or if in auto-pixel mode the CFITSIO data type is unsupported. - CPL_ERROR_DATA_NOT_FOUND if the specified extension has no image data. This code is relied on as being part of the API! - CPL_ERROR_INCOMPATIBLE_INPUT if NAXIS is OK but the data unit is empty - CPL_ERROR_ILLEGAL_INPUT If the plane number is out of range, or in a windowed read the window is invalid - CPL_ERROR_INVALID_TYPE if the passed pixel type is not supported */ /*----------------------------------------------------------------------------*/ cpl_image * cpl_image_load_(fitsfile * fptr, int * pnaxis, CPL_FITSIO_TYPE naxes[], cpl_type * ppix_type, const char * filename, cpl_size pnum, cpl_size lhdumov, cpl_boolean do_window, cpl_size llx, cpl_size lly, cpl_size urx, cpl_size ury) { const int hdumov = (int)lhdumov; int error = 0; cpl_image * self; void * pixels; const long int inc[3] = {1, 1, 1}; long int fpixel[3]; long int lpixel[3]; int loadtype; cpl_size nx, ny; cpl_ensure(fptr != NULL, CPL_ERROR_NULL_INPUT, NULL); cpl_ensure(pnaxis != NULL, CPL_ERROR_NULL_INPUT, NULL); cpl_ensure(naxes != NULL, CPL_ERROR_NULL_INPUT, NULL); cpl_ensure(ppix_type != NULL, CPL_ERROR_NULL_INPUT, NULL); cpl_ensure(filename != NULL, CPL_ERROR_NULL_INPUT, NULL); /* CFITSIO only supports int */ cpl_ensure((cpl_size)(1+hdumov) == 1+lhdumov, CPL_ERROR_ILLEGAL_INPUT, NULL); /* The open call may be reusing file handle opened for previous I/O, so the file pointer needs to be moved also for hdumov = 0 */ if (hdumov >= 0 && fits_movabs_hdu(fptr, 1+hdumov, NULL, &error)) { (void)cpl_error_set_fits(CPL_ERROR_BAD_FILE_FORMAT, error, fits_movabs_hdu, "filename='%s', pnum=%" CPL_SIZE_FORMAT ", hdumov=%d", filename, pnum, hdumov); return NULL; } /* Get NAXIS, if needed */ if (*pnaxis == 0 && fits_get_img_dim(fptr, pnaxis, &error)) { (void)cpl_error_set_fits(CPL_ERROR_BAD_FILE_FORMAT, error, fits_get_img_dim, "filename='%s', pnum=%" CPL_SIZE_FORMAT ", hdumov=%d", filename, pnum, hdumov); return NULL; } /* Verify NAXIS before trying anything else */ if (*pnaxis != 2 && *pnaxis != 3) { (void)cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "filename='%s', pnum=%" CPL_SIZE_FORMAT ", hdumov=%d, NAXIS=%d", filename, pnum, hdumov, *pnaxis); return NULL; } /* Get NAXIS[12[3]], if needed */ if (naxes[0] == 0 && CPL_FITSIO_GET_SIZE(fptr, *pnaxis, naxes, &error)) { (void)cpl_error_set_fits(CPL_ERROR_BAD_FILE_FORMAT, error, CPL_FITSIO_GET_SIZE, "filename='%s', " "pnum=%" CPL_SIZE_FORMAT ", hdumov=%d, " "NAXIS=%d", filename, pnum, hdumov, *pnaxis); return NULL; } /* Verify NAXIS[123] */ if (naxes[0] == 0 || naxes[1] == 0) { /* FIXME: Is this actually possible with a non-zero NAXIS ? */ (void)cpl_error_set_message_(CPL_ERROR_INCOMPATIBLE_INPUT, "filename='%s', pnum=%" CPL_SIZE_FORMAT ", hdumov=%d, NAXIS=%d, NAXIS1=%ld, " "NAXIS2=%ld", filename, pnum, hdumov, *pnaxis, (long)naxes[0], (long)naxes[1]); return NULL; } if (*pnaxis == 3 && naxes[2] == 0) { /* FIXME: Is this actually possible with a non-zero NAXIS ? */ (void)cpl_error_set_message_(CPL_ERROR_INCOMPATIBLE_INPUT, "filename='%s', pnum=%" CPL_SIZE_FORMAT ", hdumov=%d, NAXIS=%d, NAXIS1=%ld, " "NAXIS2=%ld NAXIS3=0", filename, pnum, hdumov, *pnaxis, (long)naxes[0], (long)naxes[1]); return NULL; } if (do_window) { /* Verify the window size */ /* If the naxes[] passed is from a previous succesful call here, then this check is redundant. Don't rely on that. */ if (llx < 1 || lly < 1 || urx > naxes[0] || ury > naxes[1] || urx < llx || ury < lly) { (void)cpl_error_set_message_(CPL_ERROR_ILLEGAL_INPUT, "filename='%s', pnum=%" CPL_SIZE_FORMAT ", hdumov=%d, " "llx=%" CPL_SIZE_FORMAT ", lly=%" CPL_SIZE_FORMAT ", urx=%" CPL_SIZE_FORMAT ", ury=%" CPL_SIZE_FORMAT ", NAXIS=%d, " "NAXIS1=%ld, NAXIS2=%ld", filename, pnum, hdumov, llx, lly, urx, ury, *pnaxis, (long)naxes[0], (long)naxes[1]); return NULL; } } else { llx = lly = 1; urx = naxes[0]; ury = naxes[1]; } /* Create the zone definition. The 3rd element not defined for NAXIS = 2 */ fpixel[0] = llx; fpixel[1] = lly; lpixel[0] = urx; lpixel[1] = ury; if (*pnaxis == 3) { /* Verify plane number */ if (pnum + 1 > naxes[2]) { (void)cpl_error_set_message_(CPL_ERROR_ILLEGAL_INPUT, "filename='%s', pnum=%" CPL_SIZE_FORMAT ", hdumov=%d, NAXIS=3, NAXIS1=%ld, " "NAXIS2=%ld, NAXIS3=%ld", filename, pnum, hdumov, (long)naxes[0], (long)naxes[1], (long)naxes[2]); return NULL; } fpixel[2] = lpixel[2] = pnum + 1; } else if (pnum != 0) { /* May not ask for any plane but the first when NAXIS == 2 */ (void)cpl_error_set_message_(CPL_ERROR_ILLEGAL_INPUT, "filename='%s', pnum=%" CPL_SIZE_FORMAT ", hdumov=%d, NAXIS=%d, NAXIS1=%ld, " "NAXIS2=%ld", filename, pnum, hdumov, *pnaxis, (long)naxes[0], (long)naxes[1]); return NULL; } if (*ppix_type == CPL_TYPE_UNSPECIFIED) { /* The pixel type of the created image is determined by the pixel type of the loaded FITS image */ int imgtype; if (fits_get_img_type(fptr, &imgtype, &error)) { (void)cpl_error_set_fits(CPL_ERROR_BAD_FILE_FORMAT, error, fits_get_img_type, "filename='%s', " "pnum=%" CPL_SIZE_FORMAT ", hdumov=%d, " "NAXIS=%d, NAXIS1=%ld, NAXIS2=%ld", filename, pnum, hdumov, *pnaxis, (long)naxes[0], (long)naxes[1]); return NULL; } switch (imgtype) { case BYTE_IMG : case SHORT_IMG : case LONG_IMG : case LONGLONG_IMG: *ppix_type = CPL_TYPE_INT; break; case FLOAT_IMG : *ppix_type = CPL_TYPE_FLOAT; break; case DOUBLE_IMG : *ppix_type = CPL_TYPE_DOUBLE; break; default: break; } if (*ppix_type == CPL_TYPE_UNSPECIFIED) { (void)cpl_error_set_message_(CPL_ERROR_BAD_FILE_FORMAT, "filename='%s', pnum=%" CPL_SIZE_FORMAT ", hdumov=%d, NAXIS=%d, NAXIS1=%ld, " "NAXIS2=%ld, imgtype=%d", filename, pnum, hdumov, *pnaxis, (long)naxes[0], (long)naxes[1], imgtype); return NULL; } } if (*ppix_type == CPL_TYPE_DOUBLE) { loadtype = TDOUBLE; } else if (*ppix_type == CPL_TYPE_FLOAT) { loadtype = TFLOAT; } else if (*ppix_type == CPL_TYPE_INT) { loadtype = TINT; } else { (void)cpl_error_set_message_(CPL_ERROR_INVALID_TYPE, "filename='%s', pnum=%" CPL_SIZE_FORMAT ", hdumov=%d, NAXIS=%d, NAXIS1=%ld, " "NAXIS2=%ld, im_type=%d", filename, pnum, hdumov,*pnaxis, (long)naxes[0], (long)naxes[1], *ppix_type); return NULL; } nx = urx - llx + 1; ny = ury - lly + 1; pixels = cpl_malloc((size_t)nx * (size_t)ny * cpl_type_get_sizeof(*ppix_type)); if (nx == (cpl_size)naxes[0]) { const LONGLONG nelem = naxes[0] * (LONGLONG)ny; const LONGLONG firstelem = 1 + naxes[0] * (LONGLONG)(lly - 1) + naxes[0] * naxes[1] * (LONGLONG)pnum; if (fits_read_img(fptr, loadtype, firstelem, nelem, NULL, pixels, NULL, &error)) { cpl_free(pixels); (void)cpl_error_set_fits(CPL_ERROR_BAD_FILE_FORMAT, error, fits_read_img, "filename='%s', " "pnum=%" CPL_SIZE_FORMAT ", hdumov=%d, " "NAXIS=%d, NAXIS1=%ld, NAXIS2=%ld", filename, pnum, hdumov, *pnaxis, (long)naxes[0], (long)naxes[1]); return NULL; } } else if (cpl_fits_read_subset(fptr, loadtype, fpixel, lpixel, inc, NULL, pixels, NULL, &error)) { cpl_free(pixels); (void)cpl_error_set_fits(CPL_ERROR_BAD_FILE_FORMAT, error, fits_read_subset, "filename='%s', " "pnum=%" CPL_SIZE_FORMAT ", hdumov=%d, " "NAXIS=%d, NAXIS1=%ld, NAXIS2=%ld", filename, pnum, hdumov, *pnaxis, (long)naxes[0], (long)naxes[1]); return NULL; } self = cpl_image_wrap_(nx, ny, *ppix_type, pixels); if (self == NULL) { cpl_free(pixels); cpl_error_set_where_(); } return self; } /*----------------------------------------------------------------------------*/ /** @internal @ingroup cpl_image @brief Create an image, optionally using an existing pixel buffer. @param nx Size in x (the number of columns) @param ny Size in y (the number of rows) @param type Pixel type @param pixels Pixel data, or NULL @return 1 newly allocated cpl_image or NULL on error @see cpl_image_new(), cpl_image_wrap_double() @note if pixels is NULL, a new buffer will be cpl_calloc'ed. Possible #_cpl_error_code_ set in this function: - CPL_ERROR_ILLEGAL_INPUT if nx or ny is non-positive or their product is too big - CPL_ERROR_INVALID_TYPE if the passed pixel type is not supported */ /*----------------------------------------------------------------------------*/ cpl_image * cpl_image_wrap_(cpl_size nx, cpl_size ny, cpl_type type, void * pixels) { cpl_image * self; const cpl_size npix = nx * ny; const size_t upix = (size_t)nx * (size_t)ny; cpl_ensure( nx > 0, CPL_ERROR_ILLEGAL_INPUT, NULL); cpl_ensure( ny > 0, CPL_ERROR_ILLEGAL_INPUT, NULL); /* Check for overflow */ cpl_ensure( npix > 0, CPL_ERROR_ILLEGAL_INPUT, NULL); cpl_ensure( (size_t)npix == upix, CPL_ERROR_ILLEGAL_INPUT, NULL); cpl_ensure( type == CPL_TYPE_INT || type == CPL_TYPE_FLOAT || type == CPL_TYPE_DOUBLE || type == CPL_TYPE_FLOAT_COMPLEX || type == CPL_TYPE_DOUBLE_COMPLEX, CPL_ERROR_INVALID_TYPE, NULL); self = cpl_malloc(sizeof(cpl_image)); self->nx = nx; self->ny = ny; self->type = type; self->bpm = NULL; self->pixels = pixels != NULL ? pixels : cpl_calloc(upix, cpl_type_get_sizeof(type)); return self; }
38.365696
85
0.546908
[ "object" ]
f8fda10ea95d44c0d4483b51fe985a0528cdbc0b
14,629
c
C
vendor/samsung/external/ims_voice_engine/codec/evs/float_c/lib_dec/peak_vq_dec.c
cesarmo759/android_kernel_samsung_msm8916
f19717ef6c984b64a75ea600a735dc937b127c25
[ "Apache-2.0" ]
1
2020-06-28T00:49:21.000Z
2020-06-28T00:49:21.000Z
vendor/samsung/external/ims_voice_engine/codec/evs/float_c/lib_dec/peak_vq_dec.c
cesarmo759/android_kernel_samsung_msm8916
f19717ef6c984b64a75ea600a735dc937b127c25
[ "Apache-2.0" ]
null
null
null
vendor/samsung/external/ims_voice_engine/codec/evs/float_c/lib_dec/peak_vq_dec.c
cesarmo759/android_kernel_samsung_msm8916
f19717ef6c984b64a75ea600a735dc937b127c25
[ "Apache-2.0" ]
1
2021-03-05T16:54:52.000Z
2021-03-05T16:54:52.000Z
/*==================================================================================== EVS Codec 3GPP TS26.443 Oct 20, 2015. Version 12.4.0 ====================================================================================*/ #include <math.h> #include "options.h" #include "cnst.h" #include "prot.h" #include "rom_com.h" /*------------------------------------------------------------------------* * Local functions *------------------------------------------------------------------------*/ static void dequant_peaks( Decoder_State *st, float *vect_out, const float *peak_gain ); static short hvq_dec_pos( Decoder_State *st, short *pos_vec, const short length, const short num_peaks ); static short sparse_dec_pos(Decoder_State *st, short *out, const short length ); /*-------------------------------------------------------------------------- * hvq_dec() * * HVQ decoder *--------------------------------------------------------------------------*/ void hvq_dec( Decoder_State *st, /* i/o: decoder state structure */ const short num_bits, /* i : Number of available bits */ const long core_brate, /* i : Core bit-rate */ const short *ynrm, /* i : Envelope coefficients */ short *R, /* i/o: Bit allocation/updated bit allocation */ float *noise_level, /* o : Noise level */ short *peak_idx, /* o : Peak position vector */ short *Npeaks, /* o : Total number of peaks */ float *coefsq_norm, /* o : Output vector */ const short core ) { short i; short bits; short noise_level_idx; bits = num_bits; for( i = 0; i < HVQ_BWE_NOISE_BANDS; i++ ) { noise_level_idx = (short) get_next_indice( st, 2 ); noise_level[i] = usdequant( noise_level_idx, 0.0f, 0.1f ); bits -= 2; } peak_vq_dec( st, coefsq_norm, (short)core_brate, bits, ynrm, R, peak_idx, Npeaks, core ); } /*-------------------------------------------------------------------------- * peak_vq_dec() * * Vector de-quantization of MDCT peaks *--------------------------------------------------------------------------*/ void peak_vq_dec( Decoder_State *st, /* i/o: decoder state structure */ float *coefs_out, /* o : Output coefficient vector */ const short brate, /* i : Core bitrate */ const short num_bits, /* i : Number of bits for HVQ */ const short *ynrm, /* i : Envelope coefficients */ short *R, /* i/o: Bit allocation/updated bit allocation */ short *vq_peak_idx, /* o : Peak position vector */ short *Npeaks, /* o : Number of peaks */ const short core /* i : Core type */ ) { short vq_peaks, i, j, k, FlagN, hcode_l, diff; short bin_th, max_peaks, pvq_bands; short nf_seed = RANDOM_INITSEED; short nf_gains_idx[HVQ_NF_GROUPS], pgain_difidx[HVQ_MAX_PEAKS_32k], pvq_norm[MAX_PVQ_BANDS]; short gain_bits_array[MAX_PVQ_BANDS]; short pos_bits; float nf_gains[HVQ_NF_GROUPS], peak_gains[HVQ_MAX_PEAKS_32k]; int manE_peak, manPkEnrg; /* (man, exp) representation ported from BASOP for interoperability */ short expE_peak, expPkEnrg; float pvq_vector[HVQ_PVQ_BUF_LEN]; short res_vec[HVQ_THRES_BIN_32k]; short k_sort[HVQ_MAX_PVQ_WORDS]; short pvq_inp_vector[HVQ_PVQ_BUF_LEN]; short npulses[MAX_PVQ_BANDS]; short pvq_bits, Rk[MAX_PVQ_BANDS]; float fg_pred[NB_SFM_MAX]; short Rk_f[MAX_PVQ_BANDS]; /* Q3 */ short sel_bnds[HVQ_NUM_SFM_24k]; short n_sel_bnds; short hvq_band_end[MAX_PVQ_BANDS]; short hvq_band_start[MAX_PVQ_BANDS]; short hvq_band_width[MAX_PVQ_BANDS]; short n; short s; float normq; set_s( gain_bits_array, 0, MAX_PVQ_BANDS ); set_f( pvq_vector, 0.0f, HVQ_PVQ_BUF_LEN ); set_s( npulses, 0, MAX_PVQ_BANDS ); set_s( pvq_inp_vector, 0, HVQ_PVQ_BUF_LEN ); /* Set bitrate dependent variables */ if (brate == HQ_24k40) { max_peaks = HVQ_MAX_PEAKS_24k; bin_th = HVQ_THRES_BIN_24k; } else { max_peaks = HVQ_MAX_PEAKS_32k; bin_th = HVQ_THRES_BIN_32k; } /* Get number of peaks */ vq_peaks = (short) get_next_indice( st, 5 ); vq_peaks = max_peaks - vq_peaks; *Npeaks = vq_peaks; diff = 5; /* safety check in case of bit errors */ if( *Npeaks < HVQ_MIN_PEAKS ) { st->BER_detect = 1; vq_peaks = HVQ_MIN_PEAKS; *Npeaks = HVQ_MIN_PEAKS; } /* De-quantize peak positions */ for (i = 0; i < bin_th; i++) { res_vec[i] = 0; } /* Unpack HVQ codewords */ pos_bits = hvq_dec_pos(st, res_vec, bin_th, vq_peaks); diff += pos_bits; for (i = 0, j = 0; i < bin_th && j < vq_peaks; i++) /* safety check in case of bit errors */ { if (res_vec[i]) { vq_peak_idx[j++] = i; } } /* safety check in case of bit errors */ if( j < vq_peaks ) { st->BER_detect = 1; vq_peaks = j - 1; *Npeaks = j - 1; } /* Huffman or differential coding */ FlagN = (short) get_next_indice( st, 1 ); /* De-quantize peak gains */ pgain_difidx[0] = (short) get_next_indice( st, GAIN0_BITS ); /* safety check in case of bit errors */ if( pgain_difidx[0] > 44 ) { st->BER_detect = 1; pgain_difidx[0] = 44; } peak_gains[0] = dicn_pg[pgain_difidx[0]]*sign((float) res_vec[vq_peak_idx[0]]); hcode_l = 0; if(FlagN) { huff_dec( st, vq_peaks-1, MAX_PG_HUFFLEN, NUM_PG_HUFFLEN, hvq_pg_huff_thres, hvq_pg_huff_offset, hvq_pg_huff_tab, &pgain_difidx[1] ); for (i = 1; i < vq_peaks; i++) { hcode_l += pgain_huffsizn[pgain_difidx[i]]; } } else { for (i = 1; i < vq_peaks; i++) { pgain_difidx[i] = (short) get_next_indice( st, GAINI_BITS ); hcode_l += GAINI_BITS; } } for (i = 1; i < vq_peaks; i++) { pgain_difidx[i] += pgain_difidx[i - 1] - 15; /* safety check in case of bit errors */ if( pgain_difidx[i] > 44 || pgain_difidx[i] < 0) { st->BER_detect = 1; pgain_difidx[i] = 44; } peak_gains[i] = dicn_pg[pgain_difidx[i]]*sign((float) res_vec[vq_peak_idx[i]]); } /* Scale up peak gains and accumulate peak energy */ /* Simulating BASOP code for interoperability */ manE_peak = 0; expE_peak = 32; for (i = 0; i < vq_peaks; i++) { peak_gains[i] *= 4.0f; manPkEnrg = manPkEnrg_tbl[pgain_difidx[i]]; expPkEnrg = expPkEnrg_tbl[pgain_difidx[i]]; floating_point_add(&manE_peak, &expE_peak, manPkEnrg, expPkEnrg); } /* Number of bits used for peak gain quantization */ diff += FLAGN_BITS + GAIN0_BITS + hcode_l; /* De-quantize peaks */ for (i = 0; i < vq_peaks; i++) { dequant_peaks( st, &coefs_out[vq_peak_idx[i]-2], &peak_gains[i] ); diff += 9; } for (i = 0; i < HVQ_NF_GROUPS; i++) { nf_gains_idx[i] = (short) get_next_indice( st, 5 ); nf_gains[i] = 0.5f*dicn[nf_gains_idx[i]]; diff += 5; } pvq_bits = num_bits - diff; /* Calculate number of PVQ bands to code and assign bits */ pvq_bands = hvq_pvq_bitalloc(pvq_bits, brate, st->bwidth, ynrm, manE_peak, expE_peak, Rk, R, sel_bnds, &n_sel_bnds ); /* safety check in case of bit errors */ if (pvq_bands == 0) { st->BER_detect = 1; } pvq_bits -= HVQ_PVQ_GAIN_BITS*pvq_bands; /* Get band limits for concatenated PVQ target */ hvq_concat_bands( pvq_bands, sel_bnds, n_sel_bnds, hvq_band_start, hvq_band_width, hvq_band_end ); s = 0; for (k = 0; k < pvq_bands; k++) { k_sort[k] = k; Rk_f[k] = Rk[k] * 8; } pvq_decode_frame( st, pvq_vector, npulses, pvq_inp_vector, hvq_band_start, hvq_band_end, hvq_band_width, pvq_bands, Rk_f, pvq_bits, core ); fine_gain_pred( hvq_band_start, hvq_band_end, hvq_band_width, k_sort, npulses, NULL, NULL, pvq_bands, pvq_vector, pvq_inp_vector, fg_pred, core ); fine_gain_dec( st, k_sort, pvq_bands, gain_bits_array, fg_pred ); apply_gain(k_sort, hvq_band_start, hvq_band_end, pvq_bands, fg_pred, pvq_vector ); i = 0; n = 0; s = 0; for (k = 0; k < pvq_bands; k++) { pvq_norm[k] = (short) get_next_indice( st, HVQ_PVQ_GAIN_BITS ); pvq_norm[k] += 8; diff += HVQ_PVQ_GAIN_BITS; j = 0; if( k >= pvq_bands - n_sel_bnds) { i = band_start_harm[sel_bnds[s++]]; } while (j < hvq_band_width[k]) { normq = dicn[pvq_norm[k]]; if (coefs_out[i] == 0) { coefs_out[i] = pvq_vector[n] * normq; j++; n++; } i++; } } /* Noise fill unqantized coeffs with one gain per group */ for (i = 0; i < HVQ_NF_GROUPS; i++) { for (j = i*(bin_th/HVQ_NF_GROUPS); j < (i+1)*(bin_th/HVQ_NF_GROUPS); j++) { if (coefs_out[j] == 0) { coefs_out[j] = ((float)own_random(&nf_seed)/MAX16B)*nf_gains[i]; } } } return; } /*-------------------------------------------------------------------------- * dequant_peaks() * * Reads codebook vector and scales peak *--------------------------------------------------------------------------*/ static void dequant_peaks( Decoder_State *st, /* i/o: decoder state structure */ float *vect_out, /* o : Quantized vector */ const float *peak_gain /* i : Peak gain */ ) { float xq[4]; const float *tmp; short i, hvq_cb_rev; short cb_idx; hvq_cb_rev = (short) get_next_indice( st, 1 ); cb_idx = (short) get_next_indice( st, 8 ); if( hvq_cb_rev ) { tmp = &hvq_peak_cb[cb_idx*4+3]; for (i = 0; i < 4; i++) { xq[i] = tmp[-i]; } } else { mvr2r(&hvq_peak_cb[cb_idx*4], xq, 4); } if(vect_out[0] == 0) { vect_out[0] = xq[0] **peak_gain; vect_out[1] = xq[1] **peak_gain; } else { if( fabs(peak_gain[-1]) <= fabs(*peak_gain) ) { vect_out[0] = xq[0] **peak_gain; vect_out[1] = xq[1] **peak_gain; } else { if(vect_out[1] == 0 || fabs(peak_gain[-1]) <= fabs(*peak_gain)) { vect_out[1] = xq[1] **peak_gain; } } } vect_out[2] = *peak_gain; vect_out[3] = xq[2] **peak_gain; vect_out[4] = xq[3] **peak_gain; return; } /*-------------------------------------------------------------------------- * hvq_dec_pos() * * HVQ decode peak positions *--------------------------------------------------------------------------*/ static short hvq_dec_pos( Decoder_State *st, /* i/o: decoder state structure */ short *pos_vec, const short length, const short num_peaks ) { short peak_idx[HVQ_MAX_PEAKS_32k]; short delta[HVQ_MAX_PEAKS_32k]; short sign_vec[HVQ_MAX_PEAKS_32k]; short mode; short num_bits; short i, j; num_bits = 0; set_s(pos_vec, 0, length); mode = (short)get_next_indice(st, 1); num_bits += 1; if (mode == HVQ_CP_DELTA) { huff_dec(st, num_peaks, HVQ_CP_HUFF_MAX_CODE, HVQ_CP_HUFF_NUM_LEN, hvq_cp_huff_thres, hvq_cp_huff_offset, hvq_cp_huff_tab, delta); for (i = 0; i < num_peaks; i++) { num_bits += hvq_cp_huff_len[delta[i]]; } peak_idx[0] = delta[0] - HVQ_CP_HUFF_OFFSET; /* safety check in case of bit errors */ if (peak_idx[0] < 2) { peak_idx[0] = 2; st->BER_detect = 1; } for (i = 1; i < num_peaks; i++) { peak_idx[i] = delta[i] + peak_idx[i-1] + HVQ_CP_HUFF_OFFSET; /* safety check in case of bit errors */ if (peak_idx[i] >= HVQ_THRES_BIN_32k) { peak_idx[i] = HVQ_THRES_BIN_32k - 1; st->BER_detect = 1; } } for (i = 0; i < num_peaks; i++) { pos_vec[peak_idx[i]] = 1; } } else { num_bits += sparse_dec_pos(st, pos_vec, length); } for (i = 0; i < num_peaks; i++) { sign_vec[i] = (get_next_indice_1(st) == 0) ? -1 : 1; } num_bits += num_peaks; for (i = 0, j = 0; i < length && j < num_peaks; i++) /* safety check in case of bit errors */ { if (pos_vec[i]) { pos_vec[i] *= sign_vec[j++]; } } return num_bits; } /*-------------------------------------------------------------------------- * sparse_dec_pos() * * Sparse decode positions *--------------------------------------------------------------------------*/ static short sparse_dec_pos( Decoder_State *st, /* i/o: decoder state structure */ short *out, const short length ) { short layer2[HVQ_CP_L2_MAX]; short layer_length; short i, j; short bits; short idx, val; set_s(layer2, 0, HVQ_CP_L2_MAX); set_s(out, 0, length); bits = 0; layer_length = (short)((float)length/HVQ_CP_L1_LEN + 0.5); for (i = 0; i < layer_length; i++) { layer2[i] = (short)get_next_indice_1(st); } bits += layer_length; for (j = 0; j < layer_length; j++) { if (layer2[j]) { idx = (short)get_next_indice(st, HVQ_CP_MAP_IDX_LEN); bits += HVQ_CP_MAP_IDX_LEN; val = hvq_cp_layer1_map5[idx]; /* safety check in case of bit errors */ if ( j == 0 && val > 4 ) /* out[0] and out[1] are invalid positions */ { st->BER_detect = 1; val = 4; } for (i = min((j+1)*HVQ_CP_L1_LEN, length)-1; i >= j*HVQ_CP_L1_LEN; i--) { out[i] = val&1; val >>= 1; } } } return bits; }
29.025794
141
0.49771
[ "vector" ]
5d0540373a35ae6b7ccd4e4487019695d8a0c0d9
7,663
h
C
TNKImagePickerController/TNKImagePickerController.h
shutterstock/TNKImagePickerController
9fcc0ad7a27cd6d7045386b9554b4302659749bf
[ "MIT" ]
null
null
null
TNKImagePickerController/TNKImagePickerController.h
shutterstock/TNKImagePickerController
9fcc0ad7a27cd6d7045386b9554b4302659749bf
[ "MIT" ]
null
null
null
TNKImagePickerController/TNKImagePickerController.h
shutterstock/TNKImagePickerController
9fcc0ad7a27cd6d7045386b9554b4302659749bf
[ "MIT" ]
2
2017-05-19T14:41:22.000Z
2021-03-25T20:58:53.000Z
// // TNKImagePickerController.h // Pods // // Created by David Beck on 2/21/15. // // #import <UIKit/UIKit.h> //! Project version number for TNKImagePickerController. FOUNDATION_EXPORT double TNKImagePickerControllerVersionNumber; //! Project version string for TNKImagePickerController. FOUNDATION_EXPORT const unsigned char TNKImagePickerControllerVersionString[]; @import MobileCoreServices; #import <TNKImagePickerController/NSDate+TNKFormattedDay.h> #import <TNKImagePickerController/PHCollection+TNKThumbnail.h> #import <TNKImagePickerController/PHImageManager+TNKRequestImages.h> #import <TNKImagePickerController/PHPhotoLibrary+TNKBlockObservers.h> #import <TNKImagePickerController/TNKAssetCell.h> #import <TNKImagePickerController/TNKAssetImageView.h> #import <TNKImagePickerController/TNKAssetsDetailViewController.h> #import <TNKImagePickerController/TNKAssetViewController.h> #import <TNKImagePickerController/TNKCollectionCell.h> #import <TNKImagePickerController/TNKCollectionPickerController.h> #import <TNKImagePickerController/TNKCollectionsTitleButton.h> #import <TNKImagePickerController/TNKCollectionViewFloatingHeaderFlowLayout.h> #import <TNKImagePickerController/TNKImagePickerControllerBundle.h> #import <TNKImagePickerController/TNKImageZoomView.h> #import <TNKImagePickerController/TNKMomentHeaderView.h> #import <TNKImagePickerController/UIImage+TNKAspectDraw.h> @class PHAssetCollection; @class TNKImagePickerController; NS_ASSUME_NONNULL_BEGIN @protocol TNKImagePickerControllerDelegate <NSObject> @optional /** Tells the delegate that the user finished picking images and movies. Your delegate object’s implementation of this method should pass the specified media on to any custom code that needs it, and should then dismiss the picker view. Instances of the assets set are `PHAsset` objects. You can request images for all the assets at once using the `TNKRequestImages` category on `PHImageManager` (`tnk_requestImagesForAssets:targetSize:contentMode:options:resultHandler:`). Implementation of this method is optional, but expected. If it is not implemented, the picker will be dismissed as a modal view controller. @param picker The controller object managing the image picker interface. @param assets The assets that were picked. These are the same as selectedAssets. */ - (void)imagePickerController:(TNKImagePickerController *)picker didFinishPickingAssets:(NSArray<PHAsset *> *)assets; /** Tells the delegate that the user cancelled the pick operation. Your delegate’s implementation of this method should dismiss the picker view by calling the `-dismissModalViewControllerAnimated:` method of the parent view controller. Implementation of this method is optional. If it is not implemented, the picker will be dismissed as a modal view controller. @param picker The controller object managing the image picker interface. */ - (void)imagePickerControllerDidCancel:(TNKImagePickerController *)picker; /** Tells the delegate that an image is being displayed fullscreen. Return the passed in viewController to use the default behavior. You can customize the view controller, for instance adding toolbar items and setting the `hidesBottomBarWhenPushed` to `NO`. Alternatively, you can return a different view controller to be pushed instead, or even return nil to cancel the push entirely. @param picker The controller object managing the image picker interface. @param viewController The proposed view controller to be pushed. @param asset The asset being displayed. @return Either a view controller to be pushed, or nil to cancel. */ - (nullable UIViewController *)imagePickerController:(TNKImagePickerController *)picker willDisplayDetailViewController:(TNKAssetsDetailViewController *)viewController forAsset:(PHAsset *)asset; /** Tells the delegate that the camera is about to be used. Return the passed in viewController to use the default behavior. You can customize the view controller, for instance by changing the settings of the camera. Alternatively, you can return a different view controller to be pushed instead, or even return nil to cancel the push entirely. @param picker The controller object managing the image picker interface. @param viewController The proposed view controller to be pushed. @return Either a view controller to be pushed, or nil to cancel. */ - (nullable UIViewController *)imagePickerController:(TNKImagePickerController *)picker willDisplayCameraViewController:(UIImagePickerController *)viewController; /** Asks the delegate for a title for the done button The delegate can use this to change the text used for the done button. The done button is updated whenever the selection changes. @param picker The controller object managing the image picker interface. */ - (NSString *)imagePickerControllerTitleForDoneButton:(TNKImagePickerController *)picker; /** Asks the delegate to confirm or modify a new selection. When the user taps on an asset, or takes a photo or does anything to select assets, this will be called to verify the new selection. You can return `assets` unchanged, modified, or an empty array to block selection entirely. Use this method for things like limiting the number of selected assets. You can perform aditional actions to let the user know why they can't select more photos, or unselect older assets. @param assets The new assets to be added to the selection. @return The assets that the delegate wants to add. */ - (NSArray<PHAsset *> *)imagePickerController:(TNKImagePickerController *)picker shouldSelectAssets:(NSArray<PHAsset *> *)assets; /** Tells the delegate that selection has been changed. @param assets The new assets that were selected. */ - (void)imagePickerController:(TNKImagePickerController *)picker didSelectAssets:(NSArray<PHAsset *> *)assets; @end @interface TNKImagePickerController : UICollectionViewController - (instancetype)init NS_DESIGNATED_INITIALIZER; - (instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER; - (instancetype)initWithNibName:(nullable NSString *)nibNameOrNil bundle:(nullable NSBundle *)nibBundleOrNil NS_UNAVAILABLE; - (instancetype)initWithCollectionViewLayout:(UICollectionViewLayout *)layout NS_UNAVAILABLE; @property (nonatomic, weak, nullable) id<TNKImagePickerControllerDelegate> delegate; @property (nonatomic, readonly) UIBarButtonItem *cancelButton; @property (nonatomic, readonly) UIBarButtonItem *doneButton; @property (nonatomic, readonly) UIBarButtonItem *cameraButton; @property (nonatomic, readonly) UIBarButtonItem *pasteButton; @property (nonatomic, readonly) UIBarButtonItem *selectAllButton; @property (nonatomic) BOOL hideSelectAll; @property (nonatomic, strong, null_resettable) UIImage *selectedAssetBadgeImage; @property (nonatomic, copy) NSArray<NSString *> *mediaTypes; /** The asset collection the picker will display to the user. The user can change this, but you can set this as a default. nil (the default) will cause the picker to display the user's moments. */ @property (nonatomic, strong, nullable) PHAssetCollection *assetCollection; /** The currently selected assets. Instances are `PHAsset` objects. You can set this to provide default assets to be selected, or read them to see what the user has selected. The order will be roughly the same as the order that the user selected them in. */ @property (nonatomic, copy) NSArray<PHAsset *> *selectedAssets; - (void)selectAsset:(PHAsset *)asset; - (void)deselectAsset:(PHAsset *)asset; @end NS_ASSUME_NONNULL_END
47.89375
318
0.799426
[ "object" ]
5d11f3312d4bd4904bc95bac522baa8c62159913
21,565
c
C
dynld/src/mapobj.c
madd-games/glidix
1510d9c3f159bee9d4aa942e715aedc78b7f827c
[ "BSD-2-Clause" ]
98
2015-08-05T22:20:19.000Z
2022-03-11T08:49:24.000Z
dynld/src/mapobj.c
madd-games/glidix
1510d9c3f159bee9d4aa942e715aedc78b7f827c
[ "BSD-2-Clause" ]
5
2016-02-23T12:49:24.000Z
2019-10-11T18:09:47.000Z
dynld/src/mapobj.c
madd-games/glidix
1510d9c3f159bee9d4aa942e715aedc78b7f827c
[ "BSD-2-Clause" ]
11
2015-12-02T05:01:28.000Z
2021-06-25T16:54:18.000Z
/* Glidix dynamic linker Copyright (c) 2014-2017, Madd Games. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/mman.h> #include <unistd.h> #include <signal.h> #include "dynld.h" extern Dl_Library chainHead; uint64_t addrPlacement; void dynld_diag(void *ptr); Dl_Library* dynld_getlib(const char *soname) { if (soname == NULL) { return &chainHead; }; Dl_Library *lib; for (lib=&chainHead; lib!=NULL; lib=lib->next) { if (strcmp(soname, lib->soname) == 0) { lib->refcount++; return lib; }; }; return NULL; }; size_t dynld_addrinfo(void *ptr, Dl_AddrInfo *infoOut, size_t infoSize) { Dl_AddrInfo info; uint64_t addr = (uint64_t) ptr; memset(&info, 0, sizeof(Dl_AddrInfo)); Dl_Library *lib; for (lib=&chainHead; lib!=NULL; lib=lib->next) { int i; for (i=0; i<lib->numSegs; i++) { uint64_t start = (uint64_t) lib->segs[i].base; uint64_t end = start + lib->segs[i].size; if (addr >= start && addr < end) { // this is the correct object info.dl_object = lib; info.dl_addr = ptr; info.dl_offset = addr - lib->base; info.dl_base = lib->base; info.dl_soname = lib->soname; info.dl_path = lib->path; size_t size = sizeof(Dl_AddrInfo); if (size > infoSize) size = infoSize; memcpy(infoOut, &info, size); return size; }; }; }; return 0; }; void* dynld_libsym(Dl_Library *lib, const char *symname, unsigned char binding) { size_t i; for (i=0; i<lib->numSymbols; i++) { Elf64_Sym *symbol = &lib->symtab[i]; const char *name = &lib->strtab[symbol->st_name]; if ((ELF64_S_BINDING(symbol->st_info) == binding) && (symbol->st_shndx != 0)) { if (strcmp(symname, name) == 0) { return (void*) (lib->base + symbol->st_value); }; }; }; return NULL; }; Dl_Library* dynld_dlopen(const char *soname, int mode) { Dl_Library *dep = dynld_getlib(soname); if (dep == NULL) { char path[256]; int depfd = dynld_open(path, soname, "", libraryPath, "", "/usr/local/lib:/usr/lib:/lib", NULL); if (depfd == -1) { strcpy(dynld_errmsg, soname); strcpy(&dynld_errmsg[strlen(soname)], ": library not found"); return NULL; }; dep = mmap(NULL, 0x1000, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); if (dep == MAP_FAILED) { close(depfd); strcpy(dynld_errmsg, soname); strcpy(&dynld_errmsg[strlen(soname)], ": cannot create library description"); return NULL; }; if (mode & RTLD_GLOBAL) { Dl_Library *last = &chainHead; while (last->next != NULL) last = last->next; dep->next = NULL; last->next = dep; dep->prev = last; } else { dep->prev = dep->next = NULL; }; if (dynld_mapobj(dep, depfd, addrPlacement, soname, RTLD_LAZY | RTLD_GLOBAL, path) == 0) { // leave dynld_errmsg as is; we forward the error from the recursive // invocation close(depfd); if (dep->prev != NULL) { dep->prev->next = NULL; }; munmap(dep, 0x1000); return NULL; }; dynld_initlib(dep); close(depfd); }; return dep; }; void* dynld_dlsym(Dl_Library *lib, const char *symname) { void *val = dynld_libsym(lib, symname, STB_GLOBAL); if (val != NULL) return val; return dynld_libsym(lib, symname, STB_WEAK); }; char* dynld_dlerror() { return dynld_errmsg; }; void* dynld_globsym(const char *symname, Dl_Library *lastLib) { Dl_Library *lib; // try global symbols first for (lib=&chainHead; lib!=NULL; lib=lib->next) { void *val = dynld_libsym(lib, symname, STB_GLOBAL); if (val != NULL) return val; }; // now internal symbols if (strcmp(symname, "dlopen") == 0) { return dynld_dlopen; }; if (strcmp(symname, "dlsym") == 0) { return dynld_dlsym; }; if (strcmp(symname, "dlclose") == 0) { return dynld_libclose; }; if (strcmp(symname, "dlerror") == 0) { return dynld_dlerror; }; if (strcmp(symname, "dladdrinfo") == 0) { return dynld_addrinfo; }; // now try the weak symbols for (lib=&chainHead; lib!=NULL; lib=lib->next) { void *val = dynld_libsym(lib, symname, STB_WEAK); if (val != NULL) return val; }; // now the library itself (in case it was RTLD_LOCAL) void *val = dynld_libsym(lastLib, symname, STB_GLOBAL); if (val != NULL) return val; val = dynld_libsym(lastLib, symname, STB_WEAK); if (val != NULL) return val; return NULL; }; void* dynld_globdat(const char *name) { size_t i; for (i=0; i<chainHead.numRela; i++) { Elf64_Rela *rela = &chainHead.rela[i]; Elf64_Xword type = ELF64_R_TYPE(rela->r_info); Elf64_Xword symidx = ELF64_R_SYM(rela->r_info); if (type == R_X86_64_COPY) { Elf64_Sym *sym = &chainHead.symtab[symidx]; char *symname = &chainHead.strtab[sym->st_name]; if (strcmp(name, symname) == 0) { return (void*) sym->st_value; }; }; }; return NULL; }; void* dynld_globdef(const char *name) { Dl_Library *lib; // try global symbols first for (lib=chainHead.next; lib!=NULL; lib=lib->next) { void *val = dynld_libsym(lib, name, STB_GLOBAL); if (val != NULL) return val; }; // now try the weak symbols for (lib=chainHead.next; lib!=NULL; lib=lib->next) { void *val = dynld_libsym(lib, name, STB_WEAK); if (val != NULL) return val; }; return NULL; }; // perform a PLT relocation with the given index on the given library, and return the resulting // address (as well as filling it in the GOT). returns NULL on error. void* dynld_pltreloc(Dl_Library *lib, uint64_t index) { Elf64_Rela *rela = &lib->pltRela[index]; Elf64_Xword symidx = ELF64_R_SYM(rela->r_info); Elf64_Sym *symbol = &lib->symtab[symidx]; const char *symname = &lib->strtab[symbol->st_name]; void *symaddr = dynld_globsym(symname, lib); if (symaddr == NULL) { strcpy(dynld_errmsg, lib->soname); strcpy(&dynld_errmsg[strlen(dynld_errmsg)], ": undefined reference to `"); strcpy(&dynld_errmsg[strlen(dynld_errmsg)], symname); strcpy(&dynld_errmsg[strlen(dynld_errmsg)], "'"); return NULL; }; void **relput = (void**) (lib->base + rela->r_offset); if (debugMode) { dynld_printf("dynld: BIND `%s' at %s+0x%p (0x%p) -> 0x%p\n", symname, lib->soname, rela->r_offset, relput, symaddr); }; *relput = symaddr; return symaddr; }; extern char dynld_lazybind[]; // called by dynld_lazybind if the binding failed void dynld_abort() { dynld_printf("dynld: lazy binding failed: %s\n", dynld_errmsg); raise(SIGABRT); }; void dynld_initlib(Dl_Library *lib) { if (lib->initDone) return; lib->initDone = 1; // call it recursively on dependencies size_t i; for (i=0; i<lib->numDeps; i++) { dynld_initlib(lib->deps[i]); }; // call initialization functions if (debugMode) { dynld_printf("dynld: invoking constructors of %s\n", lib->soname); }; if (lib->initFunc != NULL) lib->initFunc(); for (i=0; i<lib->numInit; i++) { if (lib->initVec[i] != NULL) lib->initVec[i](); }; }; uint64_t dynld_mapobj(Dl_Library *lib, int fd, uint64_t base, const char *name, int flags, const char *path) { if (debugMode) { dynld_printf("dynld: mapping object `%s' into memory at %p (%s)\n", name, base, path); }; Elf64_Ehdr elfHeader; if (pread(fd, &elfHeader, sizeof(Elf64_Ehdr), 0) != sizeof(Elf64_Ehdr)) { strcpy(dynld_errmsg, "failed to read the ELF header"); return 0; }; if (memcmp(elfHeader.e_ident, "\x7f" "ELF", 4) != 0) { strcpy(dynld_errmsg, "invalid ELF64 magic number"); return 0; }; if (elfHeader.e_ident[EI_CLASS] != ELFCLASS64) { strcpy(dynld_errmsg, "not an ELF64 file"); return 0; }; if (elfHeader.e_ident[EI_DATA] != ELFDATA2LSB) { strcpy(dynld_errmsg, "not litte-endian"); return 0; }; if (elfHeader.e_ident[EI_VERSION] != 1) { strcpy(dynld_errmsg, "ELF64 version not set to 1"); return 0; }; if (elfHeader.e_type == ET_EXEC) { if (base != 0) { strcpy(dynld_errmsg, "attempting to load executable at nonzero base"); return 0; }; } else if (elfHeader.e_type != ET_DYN) { strcpy(dynld_errmsg, "not a shared library"); return 0; }; if (elfHeader.e_machine != EM_X86_64) { strcpy(dynld_errmsg, "object does not target x86_64"); return 0; }; if (elfHeader.e_phentsize != sizeof(Elf64_Phdr)) { strcpy(dynld_errmsg, "unexpected program header size"); return 0; }; if (elfHeader.e_phnum == 0) { strcpy(dynld_errmsg, "no segments in this object"); return 0; }; // fill in the library description lib->refcount = 1; lib->base = base; strcpy(lib->soname, name); strcpy(lib->path, path); lib->numSegs = 0; lib->numDeps = 0; lib->flags = flags; lib->dyn = NULL; lib->symtab = NULL; lib->strtab = NULL; lib->numSymbols = 0; lib->rela = NULL; lib->numRela = 0; lib->pltRela = NULL; lib->hashtab = NULL; lib->pltgot = NULL; lib->initFunc = NULL; lib->numInit = 0; lib->finiFunc = NULL; lib->numFini = 0; lib->initDone = 0; // map the segments Elf64_Phdr phdr; size_t i; uint64_t topAddr = 0; for (i=0; i<elfHeader.e_phnum; i++) { if (pread(fd, &phdr, sizeof(Elf64_Phdr), elfHeader.e_phoff + sizeof(Elf64_Phdr) * i) != sizeof(Elf64_Phdr)) { strcpy(dynld_errmsg, "failed to read segment"); for (i=0; i<lib->numSegs; i++) { munmap(lib->segs[i].base, lib->segs[i].size); }; return 0; }; if (phdr.p_type == PT_LOAD) { if ((phdr.p_vaddr + phdr.p_memsz) > topAddr) { topAddr = phdr.p_vaddr + phdr.p_memsz; }; int index = lib->numSegs++; lib->segs[index].base = (void*) ((phdr.p_vaddr & ~0xFFF) + base); lib->segs[index].size = phdr.p_filesz + (phdr.p_vaddr & 0xFFF); int prot = 0; if (phdr.p_flags & PF_R) { prot |= PROT_READ; }; if (phdr.p_flags & PF_W) { prot |= PROT_WRITE; }; if (phdr.p_flags & PF_X) { prot |= PROT_EXEC; }; if (mmap(lib->segs[index].base, lib->segs[index].size, prot, MAP_PRIVATE | MAP_FIXED, fd, phdr.p_offset & ~0xFFF) == MAP_FAILED) { strcpy(dynld_errmsg, "failed to map segment into memory"); for (i=0; i<lib->numSegs-1; i++) { munmap(lib->segs[i].base, lib->segs[i].size); }; return 0; }; uint64_t zeroAddr = (uint64_t) lib->segs[index].base + lib->segs[index].size; uint64_t toZero = (0x1000 - (zeroAddr & 0xFFF)) & 0xFFF; if (prot & PROT_WRITE) { if (toZero != 0) { memset((void*)zeroAddr, 0, toZero); }; }; // calculate the top page-aligned address based on file and memory // sizes, to see if we need to map extra anonymous pages uint64_t fileTop = base + ((phdr.p_vaddr + phdr.p_filesz + 0xFFF) & ~0xFFF); uint64_t memTop = base + ((phdr.p_vaddr + phdr.p_memsz + 0xFFF) & ~0xFFF); uint64_t anonLen = memTop - fileTop; if (anonLen > 0) { index = lib->numSegs++; lib->segs[index].base = (void*) fileTop; lib->segs[index].size = anonLen; if (mmap((void*)fileTop, anonLen, prot, MAP_PRIVATE | MAP_FIXED | MAP_ANON, -1, 0) == MAP_FAILED) { strcpy(dynld_errmsg, "failed to map anonymous pages"); for (i=0; i<lib->numSegs-1; i++) { munmap(lib->segs[i].base, lib->segs[i].size); }; return 0; }; }; } else if (phdr.p_type == PT_DYNAMIC) { lib->dyn = (Elf64_Dyn*) (phdr.p_vaddr + lib->base); }; }; // memory-align the top address topAddr = (topAddr + 0xFFF) & ~0xFFF; if (base == 0) { addrPlacement = 0x200000000; /* 8GB */ } else { addrPlacement += topAddr; }; // if there is no dynamic information, we don't link if (lib->dyn == NULL) { return topAddr; }; // get the symbol table, string table and relocation table Elf64_Dyn *dyn; size_t numPltRela = 0; for (dyn=lib->dyn; dyn->d_tag!=DT_NULL; dyn++) { switch (dyn->d_tag) { case DT_RELA: lib->rela = (Elf64_Rela*) (base + dyn->d_un.d_ptr); break; case DT_RELASZ: lib->numRela = dyn->d_un.d_val / sizeof(Elf64_Rela); break; case DT_JMPREL: lib->pltRela = (Elf64_Rela*) (base + dyn->d_un.d_ptr); break; case DT_STRTAB: lib->strtab = (char*) (base + dyn->d_un.d_ptr); break; case DT_SYMTAB: lib->symtab = (Elf64_Sym*) (base + dyn->d_un.d_ptr); break; case DT_HASH: lib->hashtab = (Elf64_Word*) (base + dyn->d_un.d_ptr); break; case DT_PLTGOT: lib->pltgot = (void**) (base + dyn->d_un.d_ptr); break; case DT_PLTRELSZ: numPltRela = dyn->d_un.d_val / sizeof(Elf64_Rela); break; case DT_INIT: lib->initFunc = (Dl_InitFunc) (base + dyn->d_un.d_ptr); break; case DT_INIT_ARRAY: lib->initVec = (Dl_InitFunc*) (base + dyn->d_un.d_ptr); break; case DT_INIT_ARRAYSZ: lib->numInit = dyn->d_un.d_val >> 3; break; case DT_FINI: lib->finiFunc = (Dl_FiniFunc) (base + dyn->d_un.d_ptr); break; case DT_FINI_ARRAY: lib->finiVec = (Dl_FiniFunc*) (base + dyn->d_un.d_ptr); break; case DT_FINI_ARRAYSZ: lib->numFini = dyn->d_un.d_val >> 3; break; }; }; if (lib->hashtab == NULL) { lib->numSymbols = 0; } else { lib->numSymbols = lib->hashtab[1]; }; // additional library paths const char *rpath = ""; const char *runpath = ""; for (dyn=lib->dyn; dyn->d_tag!=DT_NULL; dyn++) { switch (dyn->d_tag) { case DT_RPATH: rpath = &lib->strtab[dyn->d_un.d_val]; break; case DT_RUNPATH: runpath = &lib->strtab[dyn->d_un.d_val]; break; }; }; // load dependencies if (debugMode) { dynld_printf("dynld: loading dependencies of object `%s'\n", name); }; for (dyn=lib->dyn; dyn->d_tag!=DT_NULL; dyn++) { if (dyn->d_tag == DT_NEEDED) { if (lib->strtab == NULL) { dynld_printf("dynld: no string table found in `%s' (%s)\n", name, path); strcpy(dynld_errmsg, "string table not found"); for (i=0; i<lib->numDeps; i++) { dynld_libclose(lib->deps[i]); }; for (i=0; i<lib->numSegs; i++) { munmap(lib->segs[i].base, lib->segs[i].size); }; return 0; }; const char *depname = &lib->strtab[dyn->d_un.d_val]; if (debugMode) { dynld_printf("dynld: loading dependency `%s'\n", depname); }; Dl_Library *dep = dynld_getlib(depname); if (dep == NULL) { char deppath[256]; int depfd = dynld_open(deppath, depname, rpath, libraryPath, runpath, "/usr/local/lib:/usr/lib:/lib", NULL); if (depfd == -1) { strcpy(dynld_errmsg, depname); strcpy(&dynld_errmsg[strlen(depname)], ": library not found"); for (i=0; i<lib->numDeps; i++) { dynld_libclose(lib->deps[i]); }; for (i=0; i<lib->numSegs; i++) { munmap(lib->segs[i].base, lib->segs[i].size); }; return 0; }; dep = mmap((void*)addrPlacement, 0x1000, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED | MAP_ANON, -1, 0); if (dep == MAP_FAILED) { close(depfd); strcpy(dynld_errmsg, depname); strcpy(&dynld_errmsg[strlen(depname)], ": cannot create library description"); for (i=0; i<lib->numDeps; i++) { dynld_libclose(lib->deps[i]); }; for (i=0; i<lib->numSegs; i++) { munmap(lib->segs[i].base, lib->segs[i].size); }; return 0; }; dep->refcount = 1; dep->next = lib->next; if (dep->next != NULL) dep->next->prev = dep; dep->prev = lib; lib->next = dep; addrPlacement += 0x1000; if (dynld_mapobj(dep, depfd, addrPlacement, depname, RTLD_LAZY | RTLD_GLOBAL, deppath) == 0) { char temp[2048]; strcpy(temp, dynld_errmsg); strcpy(dynld_errmsg, depname); strcpy(&dynld_errmsg[strlen(dynld_errmsg)], ": "); strcpy(&dynld_errmsg[strlen(dynld_errmsg)], temp); close(depfd); for (i=0; i<lib->numDeps; i++) { dynld_libclose(lib->deps[i]); }; for (i=0; i<lib->numSegs; i++) { munmap(lib->segs[i].base, lib->segs[i].size); }; lib->next = dep->next; munmap(dep, 0x1000); return 0; }; close(depfd); }; lib->deps[lib->numDeps++] = dep; }; }; // perform relocations on the object if (debugMode) { dynld_printf("dynld: performing relocations on object `%s' (0x%p relocations)\n", name, lib->numRela); }; for (i=0; i<lib->numRela; i++) { Elf64_Rela *rela = &lib->rela[i]; Elf64_Xword type = ELF64_R_TYPE(rela->r_info); Elf64_Xword symidx = ELF64_R_SYM(rela->r_info); Elf64_Sym *symbol = &lib->symtab[symidx]; const char *symname = &lib->strtab[symbol->st_name]; if (symbol->st_name == 0) symname = "<noname>"; void *symaddr = NULL; if (((symbol->st_shndx == 0) && (type != R_X86_64_RELATIVE)) && (type != R_X86_64_COPY)) { symaddr = dynld_globsym(symname, lib); if (symaddr == NULL) { strcpy(dynld_errmsg, name); strcpy(&dynld_errmsg[strlen(dynld_errmsg)], ": undefined reference to `"); strcpy(&dynld_errmsg[strlen(dynld_errmsg)], symname); strcpy(&dynld_errmsg[strlen(dynld_errmsg)], "'"); return 0; }; } else { symaddr = (void*) (lib->base + symbol->st_value); if (type == R_X86_64_COPY) { // if no libraries define the symbol, we leave 'symaddr' as-is, it will point // to the data in the executable. otherwise, we must point 'symaddr' to the // location to copy from. to find this location, we search all libraries for // for a symbol definition, but not the executable. void *srcaddr = dynld_globdef(symname); if (srcaddr != NULL) { symaddr = srcaddr; }; }; }; // for R_X86_64_GLOB_DAT relocations, use the normal symbol value unless the executable contained // an R_X86_64_COPY relocation for this symbol, in which case use that instead. if (type == R_X86_64_GLOB_DAT) { void *globaddr = dynld_globdat(symname); if (globaddr != NULL) { symaddr = globaddr; }; }; // fill in the resulting value uint64_t *relput = (uint64_t*) (lib->base + rela->r_offset); switch (type) { case R_X86_64_64: if (debugMode) dynld_printf("R_X86_64_64 against `%s' at %s+0x%p (0x%p) -> 0x%p\n", symname, name, rela->r_offset, relput, (uint64_t) symaddr + rela->r_addend); *relput = (uint64_t) symaddr + rela->r_addend; break; case R_X86_64_RELATIVE: if (debugMode) dynld_printf("R_X86_64_RELATIVE against `%s' at %s+0x%p (0x%p) -> 0x%p\n", symname, name, rela->r_offset, relput, lib->base + rela->r_addend); *relput = lib->base + rela->r_addend; break; case R_X86_64_GLOB_DAT: if (debugMode) dynld_printf("R_X86_64_GLOB_DAT against `%s' at %s+0x%p (0x%p) -> 0x%p\n", symname, name, rela->r_offset, relput, symaddr); *relput = (uint64_t) symaddr; break; case R_X86_64_COPY: if (debugMode) dynld_printf("R_X86_64_COPY against `%s' at %s+0x%p (0x%p) <- 0x%p (0x%p bytes)\n", symname, name, rela->r_offset, relput, symaddr, symbol->st_size); memcpy(relput, symaddr, symbol->st_size); break; default: strcpy(dynld_errmsg, name); strcpy(&dynld_errmsg[strlen(dynld_errmsg)], ": invalid relocation"); dynld_libclose(lib); return 0; }; }; // PLT resolution or lazy binding time if (lib->pltRela != NULL) { if ((flags & RTLD_NOW) || (bindNow)) { // we must do all bindings immediately if (debugMode) { dynld_printf("dynld: performing PLT on object `%s' (0x%p relocations)\n", name, numPltRela); }; for (i=0; i<numPltRela; i++) { if (dynld_pltreloc(lib, i) == NULL) { // dynld_errmsg already set to the appropriate message return 0; }; }; } else { for (i=0; i<numPltRela; i++) { lib->pltgot[i+3] += lib->base; }; lib->pltgot[1] = lib; lib->pltgot[2] = dynld_lazybind; }; }; return topAddr; }; int dynld_libclose(Dl_Library *lib) { if ((--lib->refcount) == 0) { if (lib->prev != NULL) { lib->prev->next = lib->next; }; if (lib->next != NULL) { lib->next->prev = lib->prev; }; // call destructors if (lib->finiFunc != NULL) lib->finiFunc(); size_t i; for (i=0; i<lib->numFini; i++) { if (lib->finiVec[i] != NULL) lib->finiVec[i](); }; for (i=0; i<lib->numDeps; i++) { dynld_libclose(lib->deps[i]); }; for (i=0; i<lib->numSegs; i++) { munmap(lib->segs[i].base, lib->segs[i].size); }; munmap(lib, 0x1000); }; return 0; };
23.263215
112
0.623325
[ "object" ]
5d16a18c46a68739e7f4701beaa682d6584c60f8
10,098
h
C
resources/home/dnanexus/root/include/TGDMLWrite.h
edawson/parliament2
2632aa3484ef64c9539c4885026b705b737f6d1e
[ "Apache-2.0" ]
null
null
null
resources/home/dnanexus/root/include/TGDMLWrite.h
edawson/parliament2
2632aa3484ef64c9539c4885026b705b737f6d1e
[ "Apache-2.0" ]
null
null
null
resources/home/dnanexus/root/include/TGDMLWrite.h
edawson/parliament2
2632aa3484ef64c9539c4885026b705b737f6d1e
[ "Apache-2.0" ]
1
2020-05-28T23:01:44.000Z
2020-05-28T23:01:44.000Z
// @(#)root/gdml:$Id$ // Author: Anton Pytel 15/9/2011 /************************************************************************* * Copyright (C) 1995-2011, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TGDMLWRITE #define ROOT_TGDMLWRITE #include "TGeoMatrix.h" #include "TXMLEngine.h" #include "TGeoVolume.h" #include "TGeoParaboloid.h" #include "TGeoSphere.h" #include "TGeoArb8.h" #include "TGeoCone.h" #include "TGeoPara.h" #include "TGeoTrd1.h" #include "TGeoTrd2.h" #include "TGeoTube.h" #include "TGeoPcon.h" #include "TGeoTorus.h" #include "TGeoPgon.h" #include "TGeoXtru.h" #include "TGeoPgon.h" #include "TGeoEltu.h" #include "TGeoHype.h" #include "TGeoBoolNode.h" #include "TGeoCompositeShape.h" #include "TGeoScaledShape.h" #include "TGeoManager.h" #include <map> #include <vector> #include <iostream> //////////////////////////////////////////////////////////////////////////// // // // TGDMLWrite - Class for exporting geometries From ROOT's gGeoManager // // (instance of TGeoManager class) To GDML file. More about GDML // // see http://gdml.web.cern.ch. // // // //////////////////////////////////////////////////////////////////////////// class TGDMLWrite : public TObject { public: TGDMLWrite(); virtual ~TGDMLWrite(); static void StartGDMLWriting(TGeoManager * geomanager, const char* filename, TString option) { //static function - //options: // g - set by default - geant4 compatibility // f,n - if none of this two is set then naming convention is // with incremental suffix, if "f" then suffix is pointer // if "n" then there is no suffix, but uniqness of names // is not secured. TGDMLWrite *writer = new TGDMLWrite; writer->SetFltPrecision(TGeoManager::GetExportPrecision()); writer->WriteGDMLfile(geomanager, filename, option); delete writer; } //wrapper of all main methods for extraction void WriteGDMLfile(TGeoManager * geomanager, const char* filename = "test.gdml", TString option = ""); // Wrapper to only selectively write one branch of the volume hierarchy to file void WriteGDMLfile(TGeoManager * geomanager, TGeoVolume* volume, const char* filename = "test.gdml", TString option = ""); enum ENamingType { kelegantButSlow = 0, kwithoutSufixNotUniq = 1, kfastButUglySufix = 2 }; void SetNamingSpeed(ENamingType naming); void SetG4Compatibility(Bool_t G4Compatible) { fgG4Compatibility = G4Compatible; }; private: struct Xyz { Double_t x; Double_t y; Double_t z; }; typedef std::map<TString, Bool_t> NameList; typedef std::map<TString, TString> NameListS; typedef std::map<TString, Int_t> NameListI; typedef std::map<TString, Float_t> NameListF; struct StructLst { NameList fLst; }; //to store pointers struct NameLst { NameListS fLst; //to map pointers with names NameListI fLstIter; //to store all the iterators for repeating names }; //General lists StructLst *fIsotopeList; //list of isotopes StructLst *fElementList; //list of elements StructLst *fAccPatt; //list of accepted patterns for division StructLst *fRejShape; //list of rejected shapes NameLst *fNameList; //list of names (pointer mapped) //Data members static TGDMLWrite *fgGDMLWrite; //pointer to gdml writer Int_t fgNamingSpeed; //input option for volume and solid naming Bool_t fgG4Compatibility; //input option for Geant4 compatibility XMLDocPointer_t fGdmlFile; //pointer storing xml file TString fTopVolumeName; //name of top volume TXMLEngine *fGdmlE; //xml engine pointer XMLNodePointer_t fDefineNode; //main <define> node... XMLNodePointer_t fMaterialsNode; //main <materials> node... XMLNodePointer_t fSolidsNode; //main <solids> node... XMLNodePointer_t fStructureNode; //main <structure> node... Int_t fVolCnt; //count of volumes Int_t fPhysVolCnt; //count of physical volumes UInt_t fActNameErr; //count of name errors UInt_t fSolCnt; //count of name solids UInt_t fFltPrecision; //! floating point precision when writing static const UInt_t fgkProcBit = BIT(14); //14th bit is set when solid is processed static const UInt_t fgkProcBitVol = BIT(19); //19th bit is set when volume is processed static const UInt_t fgkMaxNameErr = 5; //maximum number of errors for naming //I. Methods processing the gGeoManager geometry object structure //1. Main methods to extract everything from ROOT gGeoManager XMLNodePointer_t ExtractMaterials(TList* materialsLst); //result <materials>... TString ExtractSolid(TGeoShape* volShape); //adds <shape> to <solids> void ExtractVolumes(TGeoVolume* volume); //result <volume> node... + corresp. shape // Combined implementation to extract GDML information from the geometry tree void WriteGDMLfile(TGeoManager * geomanager, TGeoVolume* volume, TList* materialsLst, const char* filename, TString option); //1.1 Materials sub methods - creating Nodes XMLNodePointer_t CreateAtomN(Double_t atom, const char * unit = "g/mole"); XMLNodePointer_t CreateDN(Double_t density, const char * unit = "g/cm3"); XMLNodePointer_t CreateFractionN(Double_t percentage, const char * refName); XMLNodePointer_t CreateIsotopN(TGeoIsotope * isotope, const char * name); XMLNodePointer_t CreateElementN(TGeoElement * element, XMLNodePointer_t materials, const char * name); XMLNodePointer_t CreateMixtureN(TGeoMixture * mixture, XMLNodePointer_t materials, TString mname); XMLNodePointer_t CreateMaterialN(TGeoMaterial * material, TString mname); //1.2 Solids sub methods XMLNodePointer_t ChooseObject(TGeoShape *geoShape); XMLNodePointer_t CreateZplaneN(Double_t z, Double_t rmin, Double_t rmax); XMLNodePointer_t CreateBoxN(TGeoBBox * geoShape); XMLNodePointer_t CreateParaboloidN(TGeoParaboloid * geoShape); XMLNodePointer_t CreateSphereN(TGeoSphere * geoShape); XMLNodePointer_t CreateArb8N(TGeoArb8 * geoShape); XMLNodePointer_t CreateConeN(TGeoConeSeg * geoShape); XMLNodePointer_t CreateConeN(TGeoCone * geoShape); XMLNodePointer_t CreateParaN(TGeoPara * geoShape); XMLNodePointer_t CreateTrapN(TGeoTrap * geoShape); XMLNodePointer_t CreateTwistedTrapN(TGeoGtra * geoShape); XMLNodePointer_t CreateTrdN(TGeoTrd1 * geoShape); XMLNodePointer_t CreateTrdN(TGeoTrd2 * geoShape); XMLNodePointer_t CreateTubeN(TGeoTubeSeg * geoShape); XMLNodePointer_t CreateCutTubeN(TGeoCtub * geoShape); XMLNodePointer_t CreateTubeN(TGeoTube * geoShape); XMLNodePointer_t CreatePolyconeN(TGeoPcon * geoShape); XMLNodePointer_t CreateTorusN(TGeoTorus * geoShape); XMLNodePointer_t CreatePolyhedraN(TGeoPgon * geoShape); XMLNodePointer_t CreateEltubeN(TGeoEltu * geoShape); XMLNodePointer_t CreateHypeN(TGeoHype * geoShape); XMLNodePointer_t CreateXtrusionN(TGeoXtru * geoShape); XMLNodePointer_t CreateEllipsoidN(TGeoCompositeShape * geoShape, TString elName); XMLNodePointer_t CreateElConeN(TGeoScaledShape * geoShape); XMLNodePointer_t CreateCommonBoolN(TGeoCompositeShape *geoShape); //1.3 Volume sub methods XMLNodePointer_t CreatePhysVolN(const char * name, Int_t copyno, const char * volref, const char * posref, const char * rotref, XMLNodePointer_t scaleN); XMLNodePointer_t CreateDivisionN(Double_t offset, Double_t width, Int_t number, const char * axis, const char * unit, const char * volref); XMLNodePointer_t CreateSetupN(const char * topVolName , const char * name = "default", const char * version = "1.0"); XMLNodePointer_t StartVolumeN(const char * name, const char * solid, const char * material); XMLNodePointer_t StartAssemblyN(const char * name); //II. Utility methods Xyz GetXYZangles(const Double_t * rotationMatrix); //nodes to create position, rotation and similar types first-position/rotation... XMLNodePointer_t CreatePositionN(const char * name, Xyz position, const char * type = "position", const char * unit = "cm"); XMLNodePointer_t CreateRotationN(const char * name, Xyz rotation, const char * type = "rotation", const char * unit = "deg"); TGeoCompositeShape* CreateFakeCtub(TGeoCtub * geoShape); //create fake cut tube as intersection //check name (2nd parameter) whether it is in the list (1st parameter) Bool_t IsInList(NameList list, TString name2check); TString GenName(TString oldname); TString GenName(TString oldname, TString objPointer); Bool_t CanProcess(TObject *pointer); TString GetPattAxis(Int_t divAxis, const char * pattName, TString& unit); Bool_t IsNullParam(Double_t parValue, TString parName, TString objName); void UnsetTemporaryBits(TGeoManager * geoMng); UInt_t GetFltPrecision() const { return fFltPrecision; } void SetFltPrecision(UInt_t prec) { fFltPrecision = prec; } ClassDef(TGDMLWrite, 0) //imports GDML using DOM and binds it to ROOT }; #endif /* ROOT_TGDMLWRITE */
47.632075
156
0.650723
[ "geometry", "object", "shape", "vector", "solid" ]
5d23e270f6c32cbc0433854fc528f5123b44ce04
9,121
h
C
eden/fs/testharness/FakeTreeBuilder.h
jmswen/eden
5e0b051703fa946cc77fc43004435ae6b20599a1
[ "BSD-3-Clause" ]
null
null
null
eden/fs/testharness/FakeTreeBuilder.h
jmswen/eden
5e0b051703fa946cc77fc43004435ae6b20599a1
[ "BSD-3-Clause" ]
null
null
null
eden/fs/testharness/FakeTreeBuilder.h
jmswen/eden
5e0b051703fa946cc77fc43004435ae6b20599a1
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #pragma once #include <folly/ExceptionWrapper.h> #include <folly/Range.h> #include <memory> #include "eden/fs/model/TreeEntry.h" #include "eden/fs/utils/PathFuncs.h" #include "eden/fs/utils/PathMap.h" namespace facebook { namespace eden { class Blob; class FakeBackingStore; class Tree; template <typename T> class StoredObject; using StoredTree = StoredObject<Tree>; using StoredBlob = StoredObject<Blob>; /** * FakeTreeBuilder is a helper class for populating Trees and Blobs in a * FakeBackingStore. * * FakeTreeBuilder provides APIs for defining the file structure. The * finalize() method then turns this into Tree and Blob objects in the * FakeBackingStore. * * This class is not thread-safe. Callers are responsible for performing * synchronization, if necessary. (Typically this class is used only in a * single thread when building up the backing store data to use in a test.) */ class FakeTreeBuilder { public: class FileInfo; FakeTreeBuilder(); FakeTreeBuilder(FakeTreeBuilder&&) = default; FakeTreeBuilder& operator=(FakeTreeBuilder&&) = default; /** * Create a new FakeTreeBuilder that starts with the same contents as this * FakeTreeBuilder. * * clone() can be called even on a finalized FakeTreeBuilder. * * This is useful for emulating a normal source control modification * workflow. You can use separate FakeTreeBuilder objects for each commit * you want to create. After you finalize one FakeTreeBuilder to create a * commit's root tree, you can clone it to get a new FakeTreeBuilder that you * can modify to create the root tree for another commit. */ FakeTreeBuilder clone() const; /** * Define a file at the specified path. */ void setFile( folly::StringPiece path, folly::StringPiece contents, bool executable = false) { setFile(RelativePathPiece{path}, folly::ByteRange{contents}, executable); } void setFile( folly::StringPiece path, folly::ByteRange contents, bool executable = false) { setFile(RelativePathPiece{path}, contents, executable); } void setFile( RelativePathPiece path, folly::StringPiece contents, bool executable = false) { setFile(path, folly::ByteRange{contents}, executable); } void setFile( RelativePathPiece path, folly::ByteRange contents, bool executable = false) { setFileImpl( path, contents, false, executable ? TreeEntryType::EXECUTABLE_FILE : TreeEntryType::REGULAR_FILE); } void setFiles(const std::initializer_list<FileInfo>& fileArgs); /** * Replace the contents of a file at the given path. */ void replaceFile( folly::StringPiece path, folly::StringPiece contents, bool executable = false) { replaceFile( RelativePathPiece{path}, folly::ByteRange{contents}, executable); } void replaceFile( folly::StringPiece path, folly::ByteRange contents, bool executable = false) { replaceFile(RelativePathPiece{path}, contents, executable); } void replaceFile( RelativePathPiece path, folly::StringPiece contents, bool executable = false) { replaceFile(path, folly::ByteRange{contents}, executable); } void replaceFile( RelativePathPiece path, folly::ByteRange contents, bool executable = false) { setFileImpl( path, contents, true, executable ? TreeEntryType::EXECUTABLE_FILE : TreeEntryType::REGULAR_FILE); } /** * Define a symlink at the specified path. */ void setSymlink(folly::StringPiece path, folly::StringPiece contents) { setSymlink(RelativePathPiece{path}, contents); } void setSymlink(RelativePathPiece path, folly::StringPiece contents) { setFileImpl(path, contents, false, TreeEntryType::SYMLINK); } /** * Replace any existing file at the given path with a symlink. */ void replaceSymlink(folly::StringPiece path, folly::StringPiece contents) { replaceSymlink(RelativePathPiece{path}, contents); } void replaceSymlink(RelativePathPiece path, folly::StringPiece contents) { setFileImpl(path, contents, true, TreeEntryType::SYMLINK); } /** * Remove a file or symlink at the given path. */ void removeFile(folly::StringPiece path, bool removeEmptyParents = true) { removeFile(RelativePathPiece{path}, removeEmptyParents); } void removeFile(RelativePathPiece path, bool removeEmptyParents = true); /** * Make sure a directory exists at the given path. * * This allows creating empty Tree objects in the backing store. * This does not generally happen in practice, but is potentially useful to * be able to do during testing. */ void mkdir(folly::StringPiece path) { mkdir(RelativePathPiece{path}); } void mkdir(RelativePathPiece path); /** * Call setReady() on the StoredTree or StoredBlob at the given path. */ void setReady(folly::StringPiece path) { setReady(RelativePathPiece{path}); } void setReady(RelativePathPiece path); /** * Call setReady() on all Trees and Blobs used by this FakeTreeBuilder's root * Tree. * * Note that this will mark all Tree and Blob objects as ready if they are * referenced somehow by this builder's root Tree, even if they were already * present in the BackingStore when finalize() was called on this builder. */ void setAllReady(); /** * Call setReady() on all Trees and Blobs under the specified Tree. * * This also calls setReady() in the input Tree itself. */ void setAllReadyUnderTree(StoredTree* tree); void setAllReadyUnderTree(RelativePathPiece path); void setAllReadyUnderTree(folly::StringPiece path) { setAllReadyUnderTree(RelativePathPiece{path}); } /** * Call triggerError() on the StoredTree or StoredBlob at the given path. */ template <class E> void triggerError(RelativePathPiece path, const E& e) { triggerError(path, folly::make_exception_wrapper<E>(e)); } template <class E> void triggerError(folly::StringPiece path, const E& e) { triggerError(RelativePathPiece{path}, folly::make_exception_wrapper<E>(e)); } void triggerError(RelativePathPiece path, folly::exception_wrapper ew); void triggerError(folly::StringPiece path, folly::exception_wrapper ew) { triggerError(RelativePathPiece{path}, std::move(ew)); } /** * Update the FakeBackingStore with Tree and Blob objects from this * FakeTreeBuilder's data. * * Call this to populate the store after calling setFile(), replaceFile(), * and other similar APIs to set up the file state as desired. * * If setReady is true, the objects stored in the FakeBackingStore will be * marked as immediately ready. This applies to new Trees and Blobs created * by finalize, and also to any existing Trees and Blobs found if parts of * the tree are identical to Trees and Blobs already present in the * FakeBackingStore. */ StoredTree* finalize(std::shared_ptr<FakeBackingStore> store, bool setReady); StoredTree* getRoot() const; /** * Get the StoredTree at the specified path. */ StoredTree* getStoredTree(RelativePathPiece path); /** * Get the StoredBlob at the specified path. */ StoredBlob* getStoredBlob(RelativePathPiece path); private: enum ExplicitClone { CLONE }; FakeTreeBuilder(ExplicitClone, const FakeTreeBuilder* orig); struct EntryInfo { explicit EntryInfo(TreeEntryType fileType); EntryInfo(EntryInfo&& other) = default; EntryInfo& operator=(EntryInfo&& other) = default; /** * Create a deep copy of an EntryInfo object */ EntryInfo(ExplicitClone, const EntryInfo& orig); StoredTree* finalizeTree(FakeTreeBuilder* builder, bool setReady) const; StoredBlob* finalizeBlob(FakeTreeBuilder* builder, bool setReady) const; TreeEntryType type; std::unique_ptr<PathMap<EntryInfo>> entries; std::string contents; }; FakeTreeBuilder(FakeTreeBuilder const&) = delete; FakeTreeBuilder& operator=(FakeTreeBuilder const&) = delete; void setFileImpl( RelativePathPiece path, folly::ByteRange contents, bool replace, TreeEntryType type); EntryInfo* getEntry(RelativePathPiece path); EntryInfo* getDirEntry(RelativePathPiece path, bool create); std::shared_ptr<FakeBackingStore> store_{nullptr}; EntryInfo root_{TreeEntryType::TREE}; StoredTree* finalizedRoot_{nullptr}; }; class FakeTreeBuilder::FileInfo { public: RelativePath path; std::string contents; bool executable; FileInfo(folly::StringPiece p, folly::StringPiece c, bool exec = false) : path(p), contents(c.str()), executable(exec) {} }; } // namespace eden } // namespace facebook
30.710438
79
0.707488
[ "object", "model" ]
5d281d7d3f0bc8fd049f02b3300585aede048bc0
4,910
h
C
src/engine/AnimationController.h
foxostro/arbarlith2
820ffc8c3efcb636eb2c639487815fb9aabdc82e
[ "BSD-3-Clause" ]
1
2019-04-09T18:42:00.000Z
2019-04-09T18:42:00.000Z
src/engine/AnimationController.h
foxostro/arbarlith2
820ffc8c3efcb636eb2c639487815fb9aabdc82e
[ "BSD-3-Clause" ]
null
null
null
src/engine/AnimationController.h
foxostro/arbarlith2
820ffc8c3efcb636eb2c639487815fb9aabdc82e
[ "BSD-3-Clause" ]
null
null
null
/* Author: Andrew Fox E-Mail: mailto:foxostro@gmail.com Copyright (c) 2004-2007,2009 Game Creation Society All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Game Creation Society nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE Game Creation Society ``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 Game Creation Society BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _ANIMATION_CONTROLLER_H_ #define _ANIMATION_CONTROLLER_H_ #include "animation.h" namespace Engine { /** Manages a set of animation sequences */ class AnimationController { private: /** Stores a list of all the model's animations */ vector<AnimationSequence> m_Animations; /** Records which of the above animation objects is currently being utilized by the model */ size_t m_nCurrentAnimation; public: /** Constructs a blank animation controller */ AnimationController(void); /** Draws the current frame of the current animation at the current coordinate system's origin */ void draw(void); /** Updates the current animation @param timeStep time since the last tick */ void update(float timeStep); /** Gets the specified animation @param handle the animation to retrieve */ const AnimationSequence& getAnimation(size_t handle) const; /** Gets the current animation @return The current animation */ const AnimationSequence& getAnimation(void) const; /** Gets the current animation @return The current animation */ AnimationSequence& getAnimation(void); /** Adds an animation sequence to the controller @param animation Animation sequence to add @return The animation handle */ size_t addAnimation(AnimationSequence &animation); /** Gets the handle of the current animation @return Current animation's handle */ size_t getAnimationHandle(void) { return m_nCurrentAnimation; } /** Gets the number of animations contained within the controller @return Number of animations */ size_t getNumAnimations(void) const { return m_Animations.size(); } /** Looks up an animation handle @param name The name of the animation @return The animation handle @throws std::invalid_argument When the animation does not exist */ size_t getAnimationHandle(const string &name) const; /** Records an animation request @param name The name of the animation @param speed The speed of the animation */ inline bool requestAnimationChange(const string &name, float speed) { return requestAnimationChange(getAnimationHandle(name), speed); } /** Records an animation request @param handle The handle of the animation @param speed The speed of the animation */ bool requestAnimationChange(size_t handle, float speed); /** Gets the time into the current animation @return time into the animation */ float getTime(void) const { return getAnimation().getTime(); } /** Gets the duration of the current animation @return duration of the current animation */ float getDuration(void) const { return getAnimation().getLength(); } /** Calculates and returns the radius of the smallest sphere entirely enclosing the model @param time The time into the current animation @return radius */ float calculateRadius(float time); /** Calculates and returns the radius of the smallest cylinder entirely enclosing the model @param time The time into the current animation @return cylinder radius */ float calculateCylindricalRadius(float time); /** Calculates and returns the height of the model @param time The time into the current animation @return height */ float calculateHeight(float time); private: /** Reset all variables to their default state; A constructor helper function. */ void clear(void); }; } //namespace Engine #endif
27.897727
98
0.766395
[ "vector", "model" ]
5d284f659f5dbd17e95cd915f5e1c36aa475d3b1
2,459
h
C
Day1/build/iOS/Preview/include/Uno.Time.OffsetDateTime.h
sauvikatinnofied/ExploringFuse
cc272d55c7221d88ba773494f571b6528e5279f8
[ "Apache-2.0" ]
null
null
null
Day1/build/iOS/Preview/include/Uno.Time.OffsetDateTime.h
sauvikatinnofied/ExploringFuse
cc272d55c7221d88ba773494f571b6528e5279f8
[ "Apache-2.0" ]
null
null
null
Day1/build/iOS/Preview/include/Uno.Time.OffsetDateTime.h
sauvikatinnofied/ExploringFuse
cc272d55c7221d88ba773494f571b6528e5279f8
[ "Apache-2.0" ]
null
null
null
// This file was generated based on '/usr/local/share/uno/Packages/UnoCore/0.24.3/Source/Uno/Time/$.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Object.h> #include <Uno.Time.Offset.h> namespace g{namespace Uno{namespace Time{struct LocalDateTime;}}} namespace g{namespace Uno{namespace Time{struct OffsetDateTime;}}} namespace g{ namespace Uno{ namespace Time{ // public sealed class OffsetDateTime :1726 // { uType* OffsetDateTime_typeof(); void OffsetDateTime__ctor__fn(OffsetDateTime* __this, ::g::Uno::Time::LocalDateTime* localDateTime, ::g::Uno::Time::Offset* offset); void OffsetDateTime__get_Day_fn(OffsetDateTime* __this, int* __retval); void OffsetDateTime__Equals_fn(OffsetDateTime* __this, uObject* obj, bool* __retval); void OffsetDateTime__Equals2_fn(OffsetDateTime* __this, OffsetDateTime* other, bool* __retval); void OffsetDateTime__GetHashCode_fn(OffsetDateTime* __this, int* __retval); void OffsetDateTime__get_Hour_fn(OffsetDateTime* __this, int* __retval); void OffsetDateTime__get_Millisecond_fn(OffsetDateTime* __this, int* __retval); void OffsetDateTime__get_Minute_fn(OffsetDateTime* __this, int* __retval); void OffsetDateTime__get_Month_fn(OffsetDateTime* __this, int* __retval); void OffsetDateTime__New1_fn(::g::Uno::Time::LocalDateTime* localDateTime, ::g::Uno::Time::Offset* offset, OffsetDateTime** __retval); void OffsetDateTime__get_Offset_fn(OffsetDateTime* __this, ::g::Uno::Time::Offset* __retval); void OffsetDateTime__op_Equality_fn(OffsetDateTime* left, OffsetDateTime* right, bool* __retval); void OffsetDateTime__get_Second_fn(OffsetDateTime* __this, int* __retval); void OffsetDateTime__ToString_fn(OffsetDateTime* __this, uString** __retval); void OffsetDateTime__get_Year_fn(OffsetDateTime* __this, int* __retval); struct OffsetDateTime : uObject { uStrong< ::g::Uno::Time::LocalDateTime*> _localDateTime; ::g::Uno::Time::Offset _offset; void ctor_(::g::Uno::Time::LocalDateTime* localDateTime, ::g::Uno::Time::Offset offset); int Day(); bool Equals2(OffsetDateTime* other); int Hour(); int Millisecond(); int Minute(); int Month(); ::g::Uno::Time::Offset Offset(); int Second(); int Year(); static OffsetDateTime* New1(::g::Uno::Time::LocalDateTime* localDateTime, ::g::Uno::Time::Offset offset); static bool op_Equality(OffsetDateTime* left, OffsetDateTime* right); }; // } }}} // ::g::Uno::Time
45.537037
134
0.764132
[ "object" ]
5d3da09ad14bed4e5cd0fb2483a6c0892fb053f1
3,231
h
C
Source/Structural/ShapeDatabase.h
craig4096/procgenapp
5253eac7b073f8e1842ceaf9174c807cfbb8dff6
[ "MIT" ]
null
null
null
Source/Structural/ShapeDatabase.h
craig4096/procgenapp
5253eac7b073f8e1842ceaf9174c807cfbb8dff6
[ "MIT" ]
null
null
null
Source/Structural/ShapeDatabase.h
craig4096/procgenapp
5253eac7b073f8e1842ceaf9174c807cfbb8dff6
[ "MIT" ]
null
null
null
#ifndef SHAPEDATABASE_H #define SHAPEDATABASE_H #include "Shape.h" #include <vector> #include <map> #include <list> #include "Mesh.h" /* ShapeDatabase represents a collection of Shape objects, it is used for managing the insertion and removale of shape objects along with perfoming an optimized occlusion test to see if shapes overlap */ class ShapeDatabase { // the shapes array std::list<Shape> shapes; struct Vec3i { int x, y, z; bool operator <(const Vec3i& other) const { return x < other.x && y < other.y && z < other.z; } }; // maps grid cell coordinates to lists of intersecting shapes // used for optimizing the occlusion/intersection test std::map<Vec3i, std::vector<const Shape*> > grid; // the size of a grid cell vec3 gridCellSize; // describes a range of grid cells in the virtual grid // (used for optimizing the occlusion test) struct GridRange { int startX, endX, startY, endY, startZ, endZ; }; // occlusion test will also incorporate a global // anything outside this bounding box will be discarded as a candidate rule BoundingBox globalConstraint; // returns a grid range based off of gridCellSize given a real // valued bounding box GridRange getGridRange(const BoundingBox& aabb) const; // maps shape symbols to mesh objects SymbolMeshMap symbolMeshMap; // maps filenames to mesh objects // for caching mesh objects (so they don;t get loaded more than once) std::map<std::string, Mesh*> meshMap; // intersection test of two bounding boxes - used for occlusion test static bool intersects(const BoundingBox& a, const BoundingBox& b); public: ShapeDatabase(); ~ShapeDatabase(); typedef std::list<Shape>::iterator iterator; iterator begin() { return shapes.begin(); } iterator end() { return shapes.end(); } // loads the file mapping shape symbols to mesh objects void loadSymbolMeshMap(const char* filename); // inserts a shapes into the database at the specific iterator position // returns the position of the newely inserted shape iterator insert(iterator, const Shape& shape); // removes a specific shape at the specified iterator pos iterator remove(iterator); // a shape database is associated with a mapping between shape symbols and // mesh objects, it needs this mapping to calculate shape bounding boxes and // perform occlusion tests const SymbolMeshMap& getSymbolMeshMap() const { return symbolMeshMap; } // determines whether a current shape is intersecting with the specified // bounding box, ignore - address of shape to be ignore from occlusion test // (usually lhs shape of shape rule) bool occlusionTest(const BoundingBox& aabb, const Shape* ignore) const; // returns the number of shapes in the database // int getShapeCount() const { return shapes.size(); } // returns the shape at the specific index //const Shape& getShape(int index) const { return shapes[index]; } // clears all shapes and any entries in shapeBounds map void clear(); void setGlobalConstraint(const BoundingBox&); }; #endif // SHAPEDATABASE_H
32.636364
80
0.700712
[ "mesh", "shape", "vector" ]
5d420710cde798e52af1eaefe6d5c2e4338f61c6
3,220
h
C
code/qttoolkit/contentbrowser/code/widgets/baseitem.h
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
67
2015-03-30T19:56:16.000Z
2022-03-11T13:52:17.000Z
code/qttoolkit/contentbrowser/code/widgets/baseitem.h
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
5
2015-04-15T17:17:33.000Z
2016-02-11T00:40:17.000Z
code/qttoolkit/contentbrowser/code/widgets/baseitem.h
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
34
2015-03-30T15:08:00.000Z
2021-09-23T05:55:10.000Z
#pragma once //------------------------------------------------------------------------------ /** @class Widgets::BaseItem Base item class for special QTreeWidgetItems (C) 2012-2016 Individual contributors, see AUTHORS file */ //------------------------------------------------------------------------------ #include <QTreeWidgetItem> #include <QWidget> #include <QAction> #include <QMenu> #include "core/debug.h" #include "util/string.h" #include "io/ioserver.h" #include "basehandler.h" namespace Widgets { class BaseItem : public QTreeWidgetItem { public: enum ItemType { AnimationItemType, AudioItemType, AudioBankItemType, MeshItemType, ModelItemType, TextureItemType, LayoutItemType, FontItemType }; /// constructor BaseItem(); /// destructor virtual ~BaseItem(); /// discard item virtual void Discard(); /// overrides clone virtual BaseItem* Clone(); /// set the dock widget to where the item should present its data void SetWidget(QWidget* widget); /// get pointer to dock widget QWidget* GetWidget() const; /// handles activate events (double-clicks) virtual void OnActivated(); /// handles deactivate events (if this was clicked and some other item was clicked after) virtual bool OnDeactivated(); /// handles click events (single-clicks) virtual void OnClicked(); /// handles context menu events (right-clicks) virtual void OnRightClicked(const QPoint& pos); /// sets name of model item void SetName(const QString& name); /// gets name of model item const QString& GetName() const; /// gets the item type const ItemType& GetType() const; /// returns handler const Ptr<BaseHandler>& GetHandler() const; /// set pointer to handler void SetHandler(const Ptr<BaseHandler>& handler); protected: ItemType type; Ptr<BaseHandler> itemHandler; QWidget* frame; QString name; }; //------------------------------------------------------------------------------ /** */ inline const Ptr<BaseHandler>& BaseItem::GetHandler() const { return this->itemHandler; } //------------------------------------------------------------------------------ /** */ inline void BaseItem::SetHandler( const Ptr<BaseHandler>& handler ) { this->itemHandler = handler; } //------------------------------------------------------------------------------ /** */ inline void BaseItem::SetWidget( QWidget* widget ) { n_assert(widget); this->frame = widget; } //------------------------------------------------------------------------------ /** */ inline QWidget* BaseItem::GetWidget() const { return this->frame; } //------------------------------------------------------------------------------ /** */ inline const BaseItem::ItemType& BaseItem::GetType() const { return this->type; } //------------------------------------------------------------------------------ /** */ inline void BaseItem::SetName( const QString& name ) { n_assert(!name.isEmpty()); this->name = name; } //------------------------------------------------------------------------------ /** */ inline const QString& BaseItem::GetName() const { return this->name; } } // namespace Widgets //------------------------------------------------------------------------------
21.184211
90
0.527329
[ "model" ]
5d4670122f3c72d023329a2b82a73802bf2269ec
1,886
h
C
ns-3-dev/src/tools/model/event-garbage-collector.h
maxvonhippel/snake
0805773dc34e1480dffaae40174aa1f82d1c6ce8
[ "BSD-3-Clause" ]
11
2015-11-24T11:07:28.000Z
2021-12-23T04:10:29.000Z
ns-3-dev/src/tools/model/event-garbage-collector.h
maxvonhippel/snake
0805773dc34e1480dffaae40174aa1f82d1c6ce8
[ "BSD-3-Clause" ]
null
null
null
ns-3-dev/src/tools/model/event-garbage-collector.h
maxvonhippel/snake
0805773dc34e1480dffaae40174aa1f82d1c6ce8
[ "BSD-3-Clause" ]
6
2016-03-01T06:32:21.000Z
2022-03-24T19:31:41.000Z
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007 INESC Porto * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * 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 * * Author: Gustavo J. A. M. Carneiro <gjc@inescporto.pt> */ #ifndef EVENT_GARBAGE_COLLECTOR_H #define EVENT_GARBAGE_COLLECTOR_H #include <set> #include "ns3/event-id.h" #include "ns3/simulator.h" namespace ns3 { /** * \ingroup tools * * \brief An object that tracks scheduled events and automatically * cancels them when it is destroyed. It is useful in situations * where multiple instances of the same type of event can * simultaneously be scheduled, and when the events should be limited * to the lifetime of a container object. */ class EventGarbageCollector { public: EventGarbageCollector (); /** * \brief Tracks a new event */ void Track (EventId event); ~EventGarbageCollector (); private: struct EventIdLessThanTs { bool operator () (const EventId &a, const EventId &b) const { return (a.GetTs () < b.GetTs ()); } }; typedef std::multiset<EventId, EventIdLessThanTs> EventList; EventList::size_type m_nextCleanupSize; EventList m_events; void Cleanup (); void Grow (); void Shrink (); }; } // namespace ns3 #endif /* EVENT_GARBAGE_COLLECTOR_H */
25.486486
76
0.709968
[ "object" ]
5d4e5a764ed561b145d5bd83efba2d0785b1ff12
1,888
h
C
bitbots_motion/bitbots_quintic_walk/include/bitbots_quintic_walk/walk_visualizer.h
MosHumanoid/bitbots_thmos_meta
f45ccc362dc689b69027be5b0d000d2a08580de4
[ "MIT" ]
3
2020-05-30T07:04:33.000Z
2021-08-07T07:41:27.000Z
bitbots_motion/bitbots_quintic_walk/include/bitbots_quintic_walk/walk_visualizer.h
MosHumanoid/bitbots_thmos_meta
f45ccc362dc689b69027be5b0d000d2a08580de4
[ "MIT" ]
149
2018-12-18T12:49:56.000Z
2022-01-06T10:51:32.000Z
bitbots_motion/bitbots_quintic_walk/include/bitbots_quintic_walk/walk_visualizer.h
MosHumanoid/bitbots_thmos_meta
f45ccc362dc689b69027be5b0d000d2a08580de4
[ "MIT" ]
4
2019-07-28T11:25:02.000Z
2021-12-06T19:04:18.000Z
#ifndef BITBOTS_QUINTIC_WALK_INCLUDE_BITBOTS_QUINTIC_WALK_WALK_VISUALIZER_H_ #define BITBOTS_QUINTIC_WALK_INCLUDE_BITBOTS_QUINTIC_WALK_WALK_VISUALIZER_H_ #include <ros/ros.h> #include <bitbots_quintic_walk/WalkDebug.h> #include <bitbots_quintic_walk/WalkEngineDebug.h> #include <bitbots_quintic_walk/walk_utils.h> #include <bitbots_quintic_walk/walk_engine.h> #include <tf2_eigen/tf2_eigen.h> #include <tf2/LinearMath/Vector3.h> #include <tf2/LinearMath/Quaternion.h> #include <tf2/LinearMath/Transform.h> #include <tf2/LinearMath/Matrix3x3.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <moveit/robot_state/robot_state.h> #include <moveit_msgs/RobotState.h> #include "bitbots_splines/abstract_visualizer.h" #include "bitbots_splines/abstract_ik.h" namespace bitbots_quintic_walk { class WalkVisualizer : public bitbots_splines::AbstractVisualizer { public: explicit WalkVisualizer(); void publishArrowMarker(std::string name_space, std::string frame, geometry_msgs::Pose pose, float r, float g, float b, float a); void publishEngineDebug(WalkResponse response); void publishIKDebug(WalkResponse response, robot_state::RobotStatePtr current_state, bitbots_splines::JointGoals joint_goals); void publishWalkMarkers(WalkResponse response); void init(robot_model::RobotModelPtr kinematic_model); private: int marker_id_; ros::Publisher pub_debug_; ros::Publisher pub_engine_debug_; ros::Publisher pub_debug_marker_; robot_model::RobotModelPtr kinematic_model_; std::string base_link_frame_, l_sole_frame_, r_sole_frame_; }; } // namespace bitbots_quintic_walk #endif //BITBOTS_QUINTIC_WALK_INCLUDE_BITBOTS_QUINTIC_WALK_WALK_VISUALIZER_H_
32.551724
77
0.739936
[ "transform" ]
5d56acfb073b0467697cabeb333763186329d9b1
4,463
h
C
Engine/Code/platform.h
jesusdz/AGP
fc6401f1432313324d6fd07f7aeec411c0857276
[ "Unlicense" ]
null
null
null
Engine/Code/platform.h
jesusdz/AGP
fc6401f1432313324d6fd07f7aeec411c0857276
[ "Unlicense" ]
null
null
null
Engine/Code/platform.h
jesusdz/AGP
fc6401f1432313324d6fd07f7aeec411c0857276
[ "Unlicense" ]
null
null
null
// // platform.h : This file contains basic platform types and tools. Also, it exposes // the necessary functions for the Engine to communicate with the Platform layer. // #pragma once #define _CRT_SECURE_NO_WARNINGS #include <assert.h> #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <vector> #pragma warning(disable : 4267) // conversion from X to Y, possible loss of data typedef char i8; typedef short i16; typedef int i32; typedef long long int i64; typedef unsigned char u8; typedef unsigned short u16; typedef unsigned int u32; typedef unsigned long long int u64; typedef float f32; typedef double f64; struct Arena { u32 size; u32 head; u8* data; }; enum MouseButton { LEFT, RIGHT, MOUSE_BUTTON_COUNT }; enum Key { K_NONE, K_SPACE, K_0, K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9, K_A, K_B, K_C, K_D, K_E, K_F, K_G, K_H, K_I, K_J, K_K, K_L, K_M, K_N, K_O, K_P, K_Q, K_R, K_S, K_T, K_U, K_V, K_W, K_X, K_Y, K_Z, K_ENTER, K_ESCAPE, KEY_COUNT }; enum ButtonState { BUTTON_IDLE, BUTTON_PRESS, BUTTON_PRESSED, BUTTON_RELEASE }; struct Input { glm::vec2 mousePos; glm::vec2 mouseDelta; ButtonState mouseButtons[MOUSE_BUTTON_COUNT]; ButtonState keys[KEY_COUNT]; }; struct String { const char* str; u32 len; }; bool SameString(const char* a, const char *b); bool SameString(String a, String b); String CString(const char *cstr); String MakeString(Arena& arena, const char *cstr); #define InternString(arena, str) MakeString(arena, str) String FormatString(Arena& arena, const char* format, ...); String MakePath(Arena& arena, String dir, String filename); String GetDirectoryPart(String path); /** * Reads a whole file and returns a string with its contents. The returned string * is temporary and should be copied if it needs to persist for several frames. */ String ReadTextFile(const char *filepath); /** * It retrieves a timestamp indicating the last time the file was modified. * Can be useful in order to check for file modifications to implement hot reloads. */ u64 GetFileLastWriteTimestamp(const char *filepath); /** * It logs a string to whichever outputs are configured in the platform layer. * By default, the string is printed in the output console of VisualStudio. */ void LogString(const char* str); /** * It logs a formatted string to whichever outputs are configured in the platform layer. * By default, the string is printed in the output console of VisualStudio. */ void LogFormattedString(const char* format, ...); #define ILOG(...) LogFormattedString(__VA_ARGS__) #define ELOG(...) ILOG(__VA_ARGS__) #define ARRAY_COUNT(array) (sizeof(array)/sizeof(array[0])) #define CASSERT(condition, message) static_assert(condition, message) #define ASSERT(condition, message) assert((condition) && message) #define INVALID_CODE_PATH(message) ASSERT(false, message) #define KB(count) (1024*(count)) #define MB(count) (1024*KB(count)) #define GB(count) (1024*MB(count)) #define PI 3.14159265359f #define TAU 6.28318530718f #define MAKE_DWORD(high, low) (((high&0xffff)<<16) | ((low)&0xffff)) #define LOW_WORD(word) ((word>>0 )&0xffff) #define HIGH_WORD(word) ((word>>16)&0xffff) void MemCopy(void* dst, const void* src, u32 byteCount); Arena CreateArena(u32 sizeInBytes); void DestroyArena(Arena& arena); void ResetArena(Arena& arena); void* PushSize(Arena& arena, u32 byteCount); void* PushData(Arena& arena, const void* data, u32 byteCount); u8* PushChar(Arena& arena, u8 c); void* PushFloat(Arena& arena, float v); void* PushU32(Arena& arena, u32 v); #define PUSH_ARRAY(arena, type, count) (type*)PushSize(arena, sizeof(type) * count) #define PUSH_LVALUE(arena, lvalue) PushData(arena, &lvalue, sizeof(lvalue)) Arena& GetGlobalScratchArena(); struct ScratchArena : public Arena { u32 prevHead; ScratchArena() { Arena& globalScratchArena = GetGlobalScratchArena(); prevHead = globalScratchArena.head; size = MB(1); head = 0; data = globalScratchArena.data + prevHead; PushSize(globalScratchArena, size); } ~ScratchArena() { Arena& globalScratchArena = GetGlobalScratchArena(); globalScratchArena.head = prevHead; } };
26.724551
88
0.688326
[ "vector", "transform" ]
5d5eede45f48eceb864f63cdcfa42c39a157ca12
1,450
c
C
src/matlab/mex/generators.c
martinandersen/EGRSS
9cd36e3ed93d98390ba06cf9491b3074bd24be46
[ "BSD-2-Clause" ]
null
null
null
src/matlab/mex/generators.c
martinandersen/EGRSS
9cd36e3ed93d98390ba06cf9491b3074bd24be46
[ "BSD-2-Clause" ]
null
null
null
src/matlab/mex/generators.c
martinandersen/EGRSS
9cd36e3ed93d98390ba06cf9491b3074bd24be46
[ "BSD-2-Clause" ]
null
null
null
#include "mex.h" #include "egrss.h" #include <math.h> #include <string.h> void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* Check for proper number of arguments. */ if ( nrhs > 2 ) { mexErrMsgIdAndTxt("egrss:generators:invalidNumInputs","Too many input arguments."); } else if (nrhs < 2) { mexErrMsgIdAndTxt("egrss:generators:invalidNumInputs","Not enough input arguments."); } if (nlhs != 2) { mexErrMsgIdAndTxt("egrss:potrf:invalidNumOutputs","Invalid number of output arguments."); } /* Validate input arguments */ if (!mxIsDouble(prhs[0]) || !(mxGetM(prhs[0]) == 1 || mxGetN(prhs[0]) == 1)) { mexErrMsgIdAndTxt("egrss:generators:matchdims","Input t must be a vector."); } if (!mxIsScalar(prhs[1]) || mxGetScalar(prhs[1]) < 1 || (mxGetScalar(prhs[1]) != (int)mxGetScalar(prhs[1]))) { mexErrMsgIdAndTxt("egrss:generators:invalidInput","Input p must be a positive integer."); } mwSize n = mxGetM(prhs[0]) > mxGetN(prhs[0]) ? mxGetM(prhs[0]) : mxGetN(prhs[0]); mwSize p = (mwSize) mxGetScalar(prhs[1]); double * t = mxGetPr(prhs[0]); /* Allocate output arrays Ut and Vt */ plhs[0] = mxCreateDoubleMatrix(p,n,mxREAL); plhs[1] = mxCreateDoubleMatrix(p,n,mxREAL); /* Compute SS generators */ int info; info = egrss_dsplkgr(p,n,mxGetPr(plhs[0]),p,mxGetPr(plhs[1]),p,t,1); if (info > 0) { mexErrMsgIdAndTxt("egrss:generators:failure","Input t must be monotonic."); } }
32.954545
113
0.670345
[ "vector" ]
5d6dc639244c04a0349282687ed833cc3d13adc0
676
h
C
src/swganh_core/combat/buff_interface.h
obi-two/GameServer
7d37024e2291a97d49522610cd8f1dbe5666afc2
[ "MIT" ]
20
2015-02-23T15:11:56.000Z
2022-03-18T20:56:48.000Z
src/swganh_core/combat/buff_interface.h
obi-two/GameServer
7d37024e2291a97d49522610cd8f1dbe5666afc2
[ "MIT" ]
null
null
null
src/swganh_core/combat/buff_interface.h
obi-two/GameServer
7d37024e2291a97d49522610cd8f1dbe5666afc2
[ "MIT" ]
20
2015-04-04T16:35:59.000Z
2022-03-24T14:54:37.000Z
// This file is part of SWGANH which is released under the MIT license. // See file LICENSE or go to http://swganh.com/LICENSE #pragma once #include <memory> #include <swganh/hash_string.h> #include "boost/date_time/posix_time/posix_time_types.hpp" namespace swganh { namespace object { class Creature; } namespace combat { class BuffInterface { public: virtual ~BuffInterface() {} virtual void ApplyBuff(std::shared_ptr<swganh::object::Creature> creature) = 0; virtual void RemoveBuff(std::shared_ptr<swganh::object::Creature> creature) = 0; virtual std::string GetName() = 0; virtual uint32_t GetDuration() = 0; std::string filename; }; } }
18.777778
84
0.721893
[ "object" ]
5d7174b74866860714d5065e0c71c16853a45006
5,438
h
C
Desktop/MgDesktop/Services/Rendering/LegendPlotUtil.h
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
2
2017-04-19T01:38:30.000Z
2020-07-31T03:05:32.000Z
Desktop/MgDesktop/Services/Rendering/LegendPlotUtil.h
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
null
null
null
Desktop/MgDesktop/Services/Rendering/LegendPlotUtil.h
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
1
2021-12-29T10:46:12.000Z
2021-12-29T10:46:12.000Z
#ifndef DESKTOP_LEGEND_PLOT_UTIL_H #define DESKTOP_LEGEND_PLOT_UTIL_H class EPlotRenderer; typedef std::vector<STRING> LayerGroupList; typedef std::map<STRING, LayerGroupList> LayerGroupChildMap; typedef std::map<STRING, int> VisibleLayerCountMap; class MG_DESKTOP_API MgdLegendPlotUtil { public: MgdLegendPlotUtil(MgResourceService* svcResource); virtual ~MgdLegendPlotUtil(); void AddTitleElement(MgdPrintLayout* layout, STRING& mapName, EPlotRenderer& dr); void AddScalebarElement(MgdPrintLayout* layout, RS_Bounds& mapBounds, double dMapScale, double dMetersPerMapUnit, EPlotRenderer& dr, RS_LineStroke& lineStroke); void AddNorthArrowElement(MgdPrintLayout* layout, EPlotRenderer& dr, RS_LineStroke& lineStroke); void AddUrlElement(MgdPrintLayout* layout, STRING& mapURL, EPlotRenderer& dr); void AddDateTimeElement(MgdPrintLayout* layout, EPlotRenderer& dr); void AddCustomLogoElement(MgdPrintLayout* layout, EPlotRenderer& dr); void AddCustomTextElement(MgdPrintLayout* layout, EPlotRenderer& dr); void AddLayoutElements(MgdPrintLayout* layout, STRING mapName, STRING mapURL, MgdMap* map, MgLayerCollection* layers, RS_Bounds& mapBounds, double& dMapScale, double& dMetersPerMapUnit, EPlotRenderer& dr); void ComputeLegendOffsetAndSize(MgdPrintLayout* layout, double mapScale, EPlotRenderer& dr, MgdMap* map, double &legendOffsetX, double& legendOffsetY, double& legendWidth, double& legendHeight); //These have been cleaned up to work with a generic renderer, rather than just EPlot. //Eventually the scale bar and north arrow ones need to be cleaned up also in order //to use them in the AJAX viewer void AddLegendElement(double dMapScale, Renderer& dr, MgdMap* map, MgdPlotSpecification* plotSpec, double legendOffsetX, double legendOffsetY); void ProcessLayersForLegend(MgdMap* map, double mapScale, MgLayerGroup* mggroup, double startX, double& startY, RS_TextDef textDef, Renderer& dr, MgdPlotSpecification* plotSpec, double legendOffsetY, double convertUnits, VisibleLayerCountMap& visibleLayers, LayerGroupChildMap& groupChildren); void BuildLegendContent(MgdMap* map, double scale, MgdPlotSpecification* legendSpec, double legendOffsetX, double legendOffsetY, Renderer& dr, double convertUnits); void ExtentFromMapCenter(MgdMap* map, double metersPerUnit, RS_Bounds& b); void CompileInformation(MgdMap* map, VisibleLayerCountMap& visibleLayers, LayerGroupChildMap& groupChildren); private: static bool HasVisibleLayers(CREFSTRING groupName, VisibleLayerCountMap& visibleLayers, LayerGroupChildMap& groupChildren); MgResourceService* m_svcResource; RS_String m_legendFontName; }; const double M_TO_MI = 0.0006214; const double MI_TO_M = 1609.34721869443738887477; const double MI_TO_IN = 63360; const double IN_TO_MI = 0.0000157828283; const double FT_TO_IN = 12; const double IN_TO_FT = 0.0833333333; const double KM_TO_IN = 39370.0787 ; const double IN_TO_KM = 0.0000254; const double M_TO_IN = 39.3700787 ; const double M_TO_MM = 1000; const double MM_TO_IN = 0.0393700787 ; const double MM_TO_M = 0.001; const double IN_TO_M = 0.0254; const double IN_TO_CM = 2.54; const double IN_TO_MM = 25.4; const double PNT_TO_IN = 0.0138888888889; // 1 font point = 1/72 of an inch const double defaultScalebarWidth = 0.66; // percent of page width const double minScalebarWidth = 3.0; // inch const double maxScalebarWidth = 6.0; // inch const double whiteScaleDivisionHeight = 0.0625; // inch const double blackScaleDivisionStartY = 0.015625; //inch const double blackScaleDivisionEndY = 0.046875; // inch const double scaleBarTickMarkHeight = 0.0573; // inch const double scaleHeaderOffsetY = 0.188; // inch const double scaleHeaderFontHeight = 0.003; // meters const double scaleLabelFontHeight = 0.002; // meters const double scaleLabelOffsetY = 0.1406; // inch const double scaleFooterOffsetY = 0.2344; // inch const STRING scaleLabelPrefix = L"Scale 1 : "; const double northArrowWidth = 1.0; // inch // Relative offset amounts for vertices in North Arrow graphics. Units are in inches. // See MgServerMappingService::AddNorthArrowElement() method below for description // of the vertices. const double northArrowMinVertexX = -0.4062; const double northArrowMidVertexX = -0.25; const double northArrowMaxVertexX = -0.0937; const double northArrowMinVertexY = 0.0; const double northArrowMidVertexY = 0.1563; const double northArrowMaxVertexY = 0.3776; const double northArrowNVertexOffsetMinX = -0.2812; const double northArrowNVertexOffsetMinY = 0.4063; const double northArrowNVertexOffsetMaxX = -0.2187; const double northArrowNVertexOffsetMaxY = 0.5; const INT32 bitmapPixelWidth = 16; const INT32 bitmapPixelHeight = 16; const double bitmapDpi = STANDARD_DISPLAY_DPI; const double legendSpacing = bitmapPixelHeight / bitmapDpi + 0.005; const double defaultLegendMargin = 0.1; // inch const double legendFontHeightMeters = 0.003; const double legendTextVertAdjust = 0.06; // inch const double PrintLegendWidth = 2.0; const double PrintLegendPadding = 0.1; const double PrintHeaderHeight = 1.0; const double PrintScalebarHeight = 0.75; const double PrintScalebarPadding = 0.5; const double PrintFooterHeight = 0.5; const double PrintGroupIndent = 0.3; #endif
49.436364
298
0.770136
[ "vector" ]
f61f958d1153fff9ffdd70f95f245b38ea84b1dc
6,584
h
C
modules/kitefast-controller/src/control/sensor_util.h
OpenFAST/KiteFAST
a7329f7c454aab102fadd77771b741a923abd0a7
[ "Apache-2.0" ]
6
2020-12-22T18:21:36.000Z
2021-11-16T10:13:27.000Z
modules/kitefast-controller/src/control/sensor_util.h
OpenFAST/KiteFAST
a7329f7c454aab102fadd77771b741a923abd0a7
[ "Apache-2.0" ]
null
null
null
modules/kitefast-controller/src/control/sensor_util.h
OpenFAST/KiteFAST
a7329f7c454aab102fadd77771b741a923abd0a7
[ "Apache-2.0" ]
2
2020-10-13T11:39:01.000Z
2021-04-20T21:04:46.000Z
#ifndef CONTROL_SENSOR_UTIL_H_ #define CONTROL_SENSOR_UTIL_H_ #include <stdbool.h> #include <stdint.h> #include "common/c_math/mat3.h" #include "common/c_math/vec3.h" #include "control/sensor_types.h" #include "control/system_types.h" #ifdef __cplusplus extern "C" { #endif // GPS functions. // Converts the GS GPS position reading to the position of the // ground-station origin in ECEF and calculates the transformation // matrix from ECEF to G. void GsGpsPosEcefToGsPosEcef(const Vec3 *gs_gps_pos_ecef, const Vec3 *gs_gps_pos_g, double gs_heading, Vec3 *gs_pos_ecef, Mat3 *dcm_ecef2g); // Converts a position and velocity uncertainties from the ECEF frame // to the ground frame. void ConvSigmaEcefToLocal(const Vec3 *sigma_X_ecef, const Vec3 *sigma_V_ecef, const Mat3 *dcm_ecef2g, Vec3 *sigma_Xg, Vec3 *sigma_Vg); // Tether force functions. // Converts a tension, tether roll, and tether pitch to a tether force // vector in body coordinates. void TetherForceSphToCart(const TetherForceSph *sph, Vec3 *cart); // Converts a tether force vector in body coordinates to a tension, // tether roll, and tether pitch. void TetherForceCartToSph(const Vec3 *cart, TetherForceSph *sph); // Converts the loadcell readings into bridle force vectors, then calculates // tether tension, roll, and pitch. void LoadcellsToTetherForce(const double loadcells[], const WingParams *wing_params, const LoadcellParams loadcell_params[], Vec3 *cart, TetherForceSph *sph, Vec3 *port_force_b, Vec3 *star_force_b); // Apparent wind functions. // Converts airspeed, angle-of-attack, and sideslip angle to the // apparent wind vector in body coordinates. void ApparentWindSphToCart(const ApparentWindSph *sph, Vec3 *cart); // Converts the apparent wind vector to alpha, beta, and airspeed. void ApparentWindCartToSph(const Vec3 *cart, ApparentWindSph *sph); // Converts the pitot measurements to angles and airspeed. void PitotToApparentWindSph(const PitotDifferentialData *diff, const Vec3 *pqr, const PitotParams *params, ApparentWindSph *sph); // Rotates a wind speed measurement in the wind sensor frame into // ground coordinates. // // Args: // wind_ws: Wind measurement [m/s] in the wind sensor frame. // perch_azi_angle: Angle [rad] of the perch to the ground frame. // perch_azi_omega: Rate of change of perch_azi_angle [rad/s]. // params: Wind sensor parameters including location of the sensor. // wind_g: Output wind measurement [m/s] in the ground coordinates. void WindWsToWindG(const Vec3 *wind_ws, double perch_azi_angle, double perch_azi_omega, const WindSensorParams *params, Vec3 *wind_g); // Converts the ground station heading and perch heading to the perch // azimuth angle. // // Args: // gs_heading: Heading [rad] of the ground station relative to NED. Should // lie in [0, 2 pi). // perch_heading: Heading [rad] of the perch relative to NED. Should be // lie in [0, 2 pi). // // Returns: // The perch azimuth angle [rad] in range (-pi, pi). double GsHeadingPerchHeadingToPerchAzi(double gs_heading, double perch_heading); // Converts a winch position [m] to an equivalent drum angle [rad]. double WinchPosToDrumAngle(double winch_pos, const WinchParams *params); // Alternate GLAS-based position functions. // Converts a position in GSG coordinates to perch coordinates. void XgsgToXp(const GsgData *gsg, const Vec3 *X_gsg, double drum_angle, Vec3 *Xp); // Converts wing position in perch coordinates to an equivalent // GSG reading ([azi, ele]') assuming a perfect GSG, and a // straight-line tether. void XpToGsg(const Vec3 *Xp, double drum_angle, GsgData *gsg); // Determines the azimuth and elevation angles that correspond to the vector // describing the departure direction of the tether from the GSG. void TetherDirectionWdToGsgAziEle(const Vec3 *tether_direction_wd, double *azi, double *ele); // Returns true if levelwind should be engaged based on drum angle. bool IsLevelwindEngaged(double drum_angle, const LevelwindParams *params); // Estimates wing position in perch coordinates using levelwind // elevation and winch position. void LevelwindToXp(double payout, double drum_angle, double levelwind_ele, double tension, const LevelwindParams *params, Vec3 *Xp); // Compute the DCM to rotate Drum frame to Gsg0 frame. const Mat3 *CalcDcmWdToGsg0(double detwist_ele, double detwist_pos, Mat3 *dcm_wd2gsg0); // Estimates tether elevation angle, and the detwist angle that places all // tether deflection into the GSG yoke DOF. // // Requires measurements from platform azi, drum angle, detwist angle, // and gsg angles. We also need detwist elevation which is the elevation angle // between the schnozz and the drum's XY plane. void CalcTetherAnglesFromGsg(double perch_azi, double drum_angle, double detwist_ele, double detwist_angle, double gsg_yoke, double gsg_termination, double *tether_elevation, double *tether_detwist_angle); // Converts a position based on a straight line assumption from // line-angle sensing to a position that also accounts for the // catenary in the tether. This function may be used with any // coordinate system where gravity is in the positive z direction. void IncludeCatenary(const Vec3 *X_no_cat, double tension, double free_len, Vec3 *X_including_cat); // Converts static pressure to altitude (positive is up) above mean // sea level. double PressureToAltitude(double pressure, const PhysParams *params); // Calculate air density [kg/m^3] given pressure [Pa] and temperature [°C], // assuming dry air. double CalcDryAirDensity(double pressure_pascals, double temperature_celcius); // Calculate air density [kg/m^3] given pressure [Pa], temperature // [°C], and relative humidity [as a fraction, from 0.0 to 1.0]. The // validity flag, if not NULL, is set indicating whether the input // arguments are in a meteorologically plausible range. double CalcAirDensity(double pressure_pascals, double temperature_celcius, double relative_humidity, bool *valid); #ifdef __cplusplus } // extern "C" #endif #endif // CONTROL_SENSOR_UTIL_H_
41.670886
80
0.711118
[ "vector" ]
f625e6e684fcb2051b61490c7c49ac723af6e495
1,566
h
C
Framework/AI/Inc/AIWorld.h
TheJimmyGod/JimmyGod_Engine
b9752c6fbd9db17dc23f03330b5e4537bdcadf8e
[ "MIT" ]
null
null
null
Framework/AI/Inc/AIWorld.h
TheJimmyGod/JimmyGod_Engine
b9752c6fbd9db17dc23f03330b5e4537bdcadf8e
[ "MIT" ]
null
null
null
Framework/AI/Inc/AIWorld.h
TheJimmyGod/JimmyGod_Engine
b9752c6fbd9db17dc23f03330b5e4537bdcadf8e
[ "MIT" ]
null
null
null
#pragma once #include "Agent.h" #include "PartitionGrid.h" namespace JimmyGod::AI { class AIWorld { public: struct Settings { JimmyGod::Math::Vector2 worldSize = {0.0f, 0.0f}; float partitionGridSize = 0.0f; }; struct WallSettings { JimmyGod::Math::LineSegment line; bool diagonal = false; float degree = 0.0f; }; using Obstacles = std::vector<JimmyGod::Math::Circle>; using Walls = std::vector<WallSettings>; void Initialize(const Settings& settings); void Update(); void Render(); void RegisterEntity(Entity* entity); void UnregisterEntity(Entity* entity); void Clear(); uint32_t GetNextId() { ASSERT(mNextId < UINT32_MAX, "Run out of ids"); return mNextId++; } void AddObstacles(const JimmyGod::Math::Circle& obstacles); void AddWalls(const JimmyGod::Math::LineSegment& walls, bool dia = false, float degree = 0.0f); EntityList GetEntities(const JimmyGod::Math::Circle& range, int typeId); AgentList GetNeighborhood(const JimmyGod::Math::Circle& range, int typeId); void DebugDraw(bool avoidance) const; const Obstacles& GetObstacles() const { return mObstacles; } const Walls& GetWalls() const { return mWalls; } bool HasLineOfSight(const JimmyGod::Math::Vector2& start, const JimmyGod::Math::Vector2& end); private: Settings mSetting; Obstacles mObstacles; Walls mWalls; EntityList mEntityList; PartitionGrid<Entity> mPartitionGrid; uint32_t mNextId = 0; Graphics::TextureId mRockTexture[3]; }; }
25.258065
98
0.683269
[ "render", "vector" ]
f62706a0b35e96da3d433435be7f871ea0efb3ca
1,295
h
C
include/xarm.h
ms-iot/lewansoul_xarm
140d3257a15eaf67bd5a5042099b6db16a44bec5
[ "MIT" ]
null
null
null
include/xarm.h
ms-iot/lewansoul_xarm
140d3257a15eaf67bd5a5042099b6db16a44bec5
[ "MIT" ]
null
null
null
include/xarm.h
ms-iot/lewansoul_xarm
140d3257a15eaf67bd5a5042099b6db16a44bec5
[ "MIT" ]
null
null
null
#ifndef _XARM_ARM_H #define _XARM_ARM_H #include <array> #include <memory> #include "ihid.h" #include "joint.h" namespace xarm { class Arm { public: Arm(); static const int numJoints = 6; void resetJointPositions(); void setJointPositions(const std::array<double, Arm::numJoints>& pos); std::array<double, Arm::numJoints> getJointPositions(); private: enum class Commands { Read = 0x15, Write = 0x03, }; void initializeDevice(); void initializeJoints(); // joint-servo convertion std::array<double, Arm::numJoints> convertToRadian(const std::array<int, Arm::numJoints>& servoReadings); std::array<int, Arm::numJoints> convertToServoReadings(const std::array<double, Arm::numJoints>& radian); // device control void sendCommand(const Arm::Commands& command, const std::vector<unsigned char>& arguments); void setServoPositions(int actionTime, const std::array<int, Arm::numJoints>& positions, int epsilon, bool wait = false); std::vector<int> readServoPositions(const std::vector<int>& ids); std::array<int, Arm::numJoints> readServoPositions(); // bool ready = true; std::unique_ptr<IHid> device; std::array<std::unique_ptr<Joint>, Arm::numJoints> joints; }; } // namespace xarm #endif
25.9
125
0.689575
[ "vector" ]
f62db7c2f5e1630b5fe5e5dd015570e0a9c2f1cb
2,501
h
C
sophia/object/so.h
Passw/pmwkaa-sophia
3f3b9bec792d69b79c28721edd285f010ffc7fd3
[ "BSD-2-Clause" ]
1,380
2015-01-12T17:49:25.000Z
2022-03-26T07:46:28.000Z
sophia/object/so.h
Passw/pmwkaa-sophia
3f3b9bec792d69b79c28721edd285f010ffc7fd3
[ "BSD-2-Clause" ]
131
2015-01-21T22:25:24.000Z
2022-01-29T21:18:27.000Z
sophia/object/so.h
Passw/pmwkaa-sophia
3f3b9bec792d69b79c28721edd285f010ffc7fd3
[ "BSD-2-Clause" ]
143
2015-01-28T18:14:38.000Z
2022-03-06T12:49:34.000Z
#ifndef SO_H_ #define SO_H_ /* * sophia database * sphia.org * * Copyright (c) Dmitry Simonenko * BSD License */ typedef struct soif soif; typedef struct sotype sotype; typedef struct so so; struct soif { int (*open)(so*); int (*destroy)(so*); void (*free)(so*); void *(*document)(so*); int (*setstring)(so*, const char*, void*, int); int (*setint)(so*, const char*, int64_t); void *(*getobject)(so*, const char*); void *(*getstring)(so*, const char*, int*); int64_t (*getint)(so*, const char*); int (*set)(so*, so*); int (*upsert)(so*, so*); int (*del)(so*, so*); void *(*get)(so*, so*); void *(*begin)(so*); int (*prepare)(so*); int (*commit)(so*); void *(*cursor)(so*); }; struct sotype { uint32_t magic; char *name; }; struct so { soif *i; sotype *type; so *parent; so *env; uint8_t destroyed; sslist link; }; static inline void so_init(so *o, sotype *type, soif *i, so *parent, so *env) { o->type = type; o->i = i; o->parent = parent; o->env = env; o->destroyed = 0; ss_listinit(&o->link); } static inline void so_mark_destroyed(so *o) { o->destroyed = 1; } static inline void* so_cast_dynamic(void *ptr, sotype *type, const char *file, const char *function, int line) { int eq = ptr != NULL && ((so*)ptr)->type == type; if (sslikely(eq)) return ptr; fprintf(stderr, "%s:%d %s(%p) expected '%s' object\n", file, line, function, ptr, type->name); abort(); return NULL; } #define so_cast(o, cast, type) \ ((cast)so_cast_dynamic(o, type, __FILE__, __func__, __LINE__)) #define so_open(o) (o)->i->open(o) #define so_destroy(o) (o)->i->destroy(o) #define so_free(o) (o)->i->free(o) #define so_document(o) (o)->i->document(o) #define so_set(o, v) (o)->i->set(o, v) #define so_upsert(o, v) (o)->i->upsert(o, v) #define so_delete(o, v) (o)->i->del(o, v) #define so_get(o, v) (o)->i->get(o, v) #define so_begin(o) (o)->i->begin(o) #define so_prepare(o) (o)->i->prepare(o) #define so_commit(o) (o)->i->commit(o) #define so_cursor(o) (o)->i->cursor(o) #define so_setstring(o, path, pointer, size) \ (o)->i->setstring(o, path, pointer, size) #define so_setint(o, path, v) \ (o)->i->setint(o, path, v) #define so_getobject(o, path) \ (o)->i->getobject(o, path) #define so_getstring(o, path, sizep) \ (o)->i->getstring(o, path, sizep) #define so_getint(o, path) \ (o)->i->getnumber(o, path) #endif
22.944954
63
0.586166
[ "object" ]
f62e65d59b502d6253ae59f34988120aa16186d3
971
h
C
chrome/browser/feature_guide/notifications/config.h
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/feature_guide/notifications/config.h
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/browser/feature_guide/notifications/config.h
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_FEATURE_GUIDE_NOTIFICATIONS_CONFIG_H_ #define CHROME_BROWSER_FEATURE_GUIDE_NOTIFICATIONS_CONFIG_H_ #include <vector> #include "base/time/time.h" #include "chrome/browser/feature_guide/notifications/feature_type.h" namespace feature_guide { // Contains various finch configuration params used by the feature notification // guide. struct Config { Config(); ~Config(); Config(const Config& other); Config& operator=(const Config& other); // The list of features enabled via finch for showing feature notifications. std::vector<FeatureType> enabled_features; // Relative start time for launching the notification. base::TimeDelta notification_deliver_time_delta; }; } // namespace feature_guide #endif // CHROME_BROWSER_FEATURE_GUIDE_NOTIFICATIONS_CONFIG_H_
28.558824
79
0.790937
[ "vector" ]
f6378cd362858e87a0a022019fabb7ce430f71ca
1,898
h
C
Engine/Graphics/OpenGL/Sprite.h
prepare/Mojoc
05d631480b3b1b7b7cba8c65f3a3aacac59ae581
[ "MIT" ]
null
null
null
Engine/Graphics/OpenGL/Sprite.h
prepare/Mojoc
05d631480b3b1b7b7cba8c65f3a3aacac59ae581
[ "MIT" ]
null
null
null
Engine/Graphics/OpenGL/Sprite.h
prepare/Mojoc
05d631480b3b1b7b7cba8c65f3a3aacac59ae581
[ "MIT" ]
null
null
null
/* * Copyright (c) 2012-2018 scott.cgi All Rights Reserved. * * This code is licensed under the MIT License. * * Since : 2013-4-20 * Author: scott.cgi */ #ifndef SPRITE_H #define SPRITE_H #include "Engine/Graphics/Draw/Drawable.h" #include "Engine/Graphics/Draw/Quad.h" #include "Engine/Graphics/OpenGL/Texture.h" #include "Engine/Toolkit/Utils/Array.h" typedef struct { Drawable drawable[1]; /** * Sprite render texture */ Texture* texture; /** * All vertex index count */ int indexCount; /** * If use VBO is NULL else buffer all vertex data */ Array(float)* vertexArr; /** * If use VBO is NULL else buffer all index data */ Array(short)* indexArr; /** * If use VBO is array buffer id */ GLuint vboIds[MeshBuffer_Num]; /** * If use VAO is generated id else 0 */ GLuint vaoId; } Sprite; struct ASprite { Sprite* (*Create) (Texture* texture); void (*Init) (Texture* texture, Sprite* outSprite); Sprite* (*CreateWithFile) (char* filePath); void (*InitWithFile) (char* filePath, Sprite* outSprite); Sprite* (*CreateWithQuad) (Texture* texture, Quad* quad); void (*InitWithQuad) (Texture* texture, Quad* quad, Sprite* outSprite); Sprite* (*CreateWithQuadArray)(Texture* texture, Array(Quad)* quadArr); void (*InitWithQuadArray) (Texture* texture, Array(Quad)* quadArr, Sprite* outSprite); void (*Release) (Sprite* sprite); /** * Sprite implement Drawable's render */ void (*Render) (Drawable* drawable); }; extern struct ASprite ASprite[1]; static inline void ASprite_Draw(Sprite* sprite) { ADrawable->Draw(sprite->drawable); } #endif
20.857143
97
0.582192
[ "render" ]
f63b901a51ca1eaf810ca13a643958ffc033eeba
2,474
h
C
CGConnectionController/CGReachability.h
CGDevHusky92/CGConnectionController
cc19e6e5e14e7ba58a3dca41856588a453b51d51
[ "MIT" ]
null
null
null
CGConnectionController/CGReachability.h
CGDevHusky92/CGConnectionController
cc19e6e5e14e7ba58a3dca41856588a453b51d51
[ "MIT" ]
null
null
null
CGConnectionController/CGReachability.h
CGDevHusky92/CGConnectionController
cc19e6e5e14e7ba58a3dca41856588a453b51d51
[ "MIT" ]
null
null
null
/** To use register for notification [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kCGReachabilityChangedNotification object:nil]; self.reachability = [CGReachability reachabilityWithHostName:remoteHostName]; [self.reachability startNotifier]; - (void)reachabilityChanged:(NSNotification *)note { CGReachability* curReach = [note object]; NSParameterAssert([curReach isKindOfClass:[CGReachability class]]); ...Get data from reachability CGNetworkStatus netStatus = [curReach currentReachabilityStatus]; BOOL connectionRequired = [curReach connectionRequired]; NSString* statusString = @""; switch (netStatus) { case kCGNetworkNotReachable: { // statusString = NSLocalizedString(@"Access Not Available", @"Text field text for access is not available"); // imageView.image = [UIImage imageNamed:@"stop-32.png"]; / * Minor interface detail- connectionRequired may return YES even when the host is unreachable. We cover that up here... * / connectionRequired = NO; break; } case kCGNetworkReachableViaWiFi: { // statusString= NSLocalizedString(@"Reachable WiFi", @""); // imageView.image = [UIImage imageNamed:@"Airport.png"]; break; } case kCGNetworkReachableViaWWAN: { // statusString = NSLocalizedString(@"Reachable WWAN", @""); // imageView.image = [UIImage imageNamed:@"WWAN5.png"]; break; } } } Don't forget to remove the notification in dealloc [[NSNotificationCenter defaultCenter] removeObserver:self name:kCGReachabilityChangedNotification object:nil]; */ #import <Foundation/Foundation.h> #import <SystemConfiguration/SystemConfiguration.h> #import <netinet/in.h> typedef NS_ENUM(NSInteger, CGNetworkStatus) { kCGNetworkNotReachable = 0, kCGNetworkReachableViaWiFi, kCGNetworkReachableViaWWAN }; extern NSString *kCGReachabilityChangedNotification; @interface CGReachability : NSObject + (instancetype)reachabilityWithHostName:(NSString *)hostName; + (instancetype)reachabilityWithAddress:(const struct sockaddr_in *)hostAddress; + (instancetype)reachabilityForInternetConnection; + (instancetype)reachabilityForLocalWiFi; - (BOOL)startNotifier; - (void)stopNotifier; - (CGNetworkStatus)currentReachabilityStatus; - (BOOL)connectionRequired; @end
31.316456
149
0.715441
[ "object" ]
f63c5334a0bea87bda81acece1ed08ef3fa17a1c
8,228
c
C
allProg.c
Veradra/robotc-stuff
3ba62f0c71bed81afd1d0d7981d30c5281e44092
[ "Unlicense" ]
2
2019-01-26T05:13:14.000Z
2020-01-17T19:57:00.000Z
allProg.c
Veradra/robotc-stuff
3ba62f0c71bed81afd1d0d7981d30c5281e44092
[ "Unlicense" ]
null
null
null
allProg.c
Veradra/robotc-stuff
3ba62f0c71bed81afd1d0d7981d30c5281e44092
[ "Unlicense" ]
null
null
null
#pragma config(I2C_Usage, I2C1, i2cSensors) #pragma config(Sensor, in1, armPotent, sensorPotentiometer) #pragma config(Sensor, in2, lineRight, sensorLineFollower) #pragma config(Sensor, in3, lineCenter, sensorLineFollower) #pragma config(Sensor, in4, lineLeft, sensorLineFollower) #pragma config(Sensor, dgtl1, rightEncoder, sensorQuadEncoder) #pragma config(Sensor, dgtl3, leftEncoder, sensorQuadEncoder) #pragma config(Sensor, dgtl5, frontTouch, sensorTouch) #pragma config(Sensor, dgtl6, bumpTouch, sensorTouch) #pragma config(Sensor, dgtl7, sonarSensor, sensorSONAR_cm) #pragma config(Sensor, dgtl12, led, sensorLEDtoVCC) #pragma config(Sensor, I2C_1, rightIME, sensorNone) #pragma config(Sensor, I2C_2, leftIME, sensorNone) #pragma config(Sensor, I2C_3, armIME, sensorQuadEncoderOnI2CPort, , AutoAssign ) #pragma config(Motor, port1, leftMotor, tmotorVex393_HBridge, openLoop, driveLeft, encoderPort, dgtl3) #pragma config(Motor, port6, clawMotor, tmotorVex393_MC29, openLoop) #pragma config(Motor, port7, armMotor, tmotorVex393_MC29, openLoop, reversed, encoderPort, I2C_3) #pragma config(Motor, port10, rightMotor, tmotorVex393_HBridge, openLoop, reversed, driveRight, encoderPort, dgtl1) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// //int variables. Declare before use!// int left = 36; int right = 30; int dist = 15; int turn = 250; int turnspeed = 70; int sl = 600; int sr = 605; int leftc = 60; int rightc = 60; int avoid = 200; int leftCorr = 80; int rightCorr = 80; int lc = 35; int rc = 35; int armspeed = 40; int clawspeed = 40; int sw; int t = 2000; int dnc; //void functions. Declare before use! //Automatically turns left void goLeft() { resetSensor(leftEncoder); resetSensor(rightEncoder); setMotor(leftMotor, turnspeed); setMotor(rightMotor, -turnspeed); waitUntil(SensorValue[rightEncoder] >= turn && SensorValue[leftEncoder] <= -turn); stopMultipleMotors(leftMotor, rightMotor); wait(20, milliseconds); } //Automatically turns right void goRight() { resetSensor(leftEncoder); resetSensor(rightEncoder); setMotor(leftMotor, -turnspeed); setMotor(rightMotor, turnspeed); waitUntil(SensorValue[rightEncoder] <= -turn && SensorValue[leftEncoder] >= turn); stopMultipleMotors(leftMotor, rightMotor); wait(20, milliseconds); } /* Automatically goes forwards. !NOTE! this has a "switch" variable ('sw'). By default, this value is set to 0 but can be changed by putting a number where X is in 'goForward(X);' when needed. Please go 'sw = -1;' when done. This will be cleared and set to 0 shortly after (the default), and stop the motors. */ void goForward(int sw, int encval) { setMotor(leftMotor, left); setMotor(rightMotor, right); //If we set sw to 0, we go forwards until it is dist cm from an object. if(sw == 0) { waitUntil(SensorValue[sonarSensor] <= dist); stopMultipleMotors(leftMotor, rightMotor); } //If we set sw to 1, we set it to go forward for t milliseconds. if(sw == 1) { wait1Msec(t); stopMultipleMotors(leftMotor, rightMotor); } //If we set sw to 2, we just go forwards. You must do the programming to stop it. if(sw == 2) { setMotor(leftMotor, left); setMotor(rightMotor, right); wait(10, milliseconds); } if(sw == 3) { setMotor(leftMotor, left); setMotor(rightMotor, right); waitUntil(SensorValue[leftEncoder] >=encval && SensorValue[rightEncoder] >=encval); } } //Allows for manual left point turns. void leftCTRL() { setMotor(leftMotor, turnspeed); setMotor(rightMotor, -turnspeed); wait1Msec(20); if(vexRT[Btn7L] == 0) { stopMultipleMotors(leftMotor, rightMotor); } } //Allows for manual right point turns. void rightCTRL() { setMotor(leftMotor, -turnspeed); setMotor(rightMotor, turnspeed); wait1Msec(20); if(vexRT[Btn7R] == 0) { stopMultipleMotors(leftMotor, rightMotor); } } //Allows for manual forwards. void forwardCTRL() { setMotor(rightMotor, rightc); setMotor(leftMotor, leftc); wait1Msec(20); if(vexRT[Btn7U] == 0) { stopMultipleMotors(leftMotor, rightMotor); } } //Allows for manual backwards. void backwardsCTRL() { setMotor(rightMotor, -rightc); setMotor(leftMotor, -leftc); wait1Msec(20); if(vexRT[Btn7D] == 0) { stopMultipleMotors(leftMotor, rightMotor); } } //Automatic left swing turn. void swingLeft(int multi) { resetSensor(leftEncoder); resetSensor(rightEncoder); setMotor(leftMotor, 0); setMotor(rightMotor, turnspeed); waitUntil(SensorValue[leftEncoder] >= sl*multi); stopMultipleMotors(leftMotor, rightMotor); wait(20, milliseconds); } //Automatic right swing turn. void swingRight(int multi) { resetSensor(leftEncoder); resetSensor(rightEncoder); setMotor(leftMotor, turnspeed); setMotor(rightMotor, 0); waitUntil(SensorValue[rightEncoder] >= sr*multi); stopMultipleMotors(leftMotor, rightMotor); wait(20, milliseconds); } //Left line follower correction. void correctionL() { setMotor(leftMotor, -lc); setMotor(rightMotor, rightCorr); wait(10, milliseconds); } //Right line follower correction. void correctionR() { setMotor(leftMotor, leftCorr); setMotor(rightMotor, -rc); wait(10, milliseconds); } //Moves the arm out of the way automatically. void afo() { setMotor(armMotor, armspeed); waitUntil(SensorValue[armPotent] <= 1250); stopMotor(armMotor); } /* Sonar task is here! This task will make sure you can toggle "crash mode" aka, if you can run into a wall or not. Not much needs to be done with it. */ task sonar() { while(true) if(SensorValue[sonarSensor] <= dist) { stopMultipleMotors(leftMotor, rightMotor); }else{ wait1Msec(10); } } //Main task, has the bulk of the program in use. task main() { //We wait for the bumpTouch sensor to be pressed to start. waitUntil(SensorValue[bumpTouch] == 1); { //Sets 'sw' to 0. Moves arm out of the way. sw = 0; afo(); repeat(forever) { /*Keeps the arm from going over and flipping itself. If for whatever reason you NEED to do that, make sure to set 'dnc' to 1 with 'dnc = 1;' where needed. Please set to 0 when you don't need to do this. (dnc stands for 'Do Not Check' in this case) */ while(SensorValue[armPotent] <= 1000 && dnc == 0) { setMotor(armMotor, -armspeed); wait1Msec(50); setMotor(armMotor, armspeed/2); wait1Msec(50); stopMotor(armMotor); } while(sw == -1) { sw = 0; stopMultipleMotors(leftMotor, rightMotor); } if(SensorValue[frontTouch] == 1) { setMotor(armMotor, armspeed); wait1Msec(50); stopMotor(armMotor); } if(vexRT[Btn8D] == 1) { goForward(1, 0); } if(vexRT[Btn7U] == 1) { forwardCTRL(); } if(vexRT[Btn7D] == 1) { backwardsCTRL(); } if(vexRT[Btn7R] == 1) { rightCTRL(); } if(vexRT[Btn7L] == 1) { leftCTRL(); } if(vexRT[Ch1] >= 70) { startTask(sonar); } if(vexRT[Ch1] <= -70) { stopTask(sonar); } if(vexRT[Btn5U] == 1 || vexRT[Btn5D] == 1) { armControl(armMotor, Btn5U, Btn5D, armspeed); wait1Msec(10); stopMotor(armMotor); } if(vexRT[Btn6U] == 1 || vexRT[Btn6D] == 1) { armControl(clawMotor, Btn6U, Btn6D, clawspeed); wait1Msec(10); stopMotor(clawMotor); } if(vexRT[Ch2] >= 70) { repeatUntil(vexRT[Ch2] <= -70) { goForward(2, 0); if(SensorValue[lineLeft] >= avoid) { correctionR(); } if(SensorValue[lineRight] >= avoid) { correctionL(); } } sw = -1; } if(vexRT[Btn8U] == 1) { goForward(3, 50); wait1Msec(30); swingLeft(1); goForward(3, 50); wait1Msec(30); swingRight(1); goForward(3, 50); wait1Msec(30); swingLeft(1); goForward(3, 50); wait1Msec(100); goLeft(); goForward(3, 500); goRight(); } } } }
26.203822
129
0.648639
[ "object" ]
f640430602c1ad47dd2521b9df54390fad346e1e
2,751
h
C
src/defaults.h
DouglasRMiles/QuProlog
798d86f87fb4372b8918ef582ef2f0fc0181af2d
[ "Apache-2.0" ]
5
2019-11-20T02:05:31.000Z
2022-01-06T18:59:16.000Z
src/defaults.h
logicmoo/QuProlog
798d86f87fb4372b8918ef582ef2f0fc0181af2d
[ "Apache-2.0" ]
null
null
null
src/defaults.h
logicmoo/QuProlog
798d86f87fb4372b8918ef582ef2f0fc0181af2d
[ "Apache-2.0" ]
2
2022-01-08T13:52:24.000Z
2022-03-07T17:41:37.000Z
// defaults.h - Global default size constants for // all the C++ components of the QP // suite. #include this file whenever // global default values are needed. // This should only be necessary when // command line arguments are being // processed. // Otherwise, extract the correct value // from the *_options object. // // ##Copyright## // // Copyright 2000-2016 Peter Robinson (pjr@itee.uq.edu.au) // // 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.00 // // 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. // // ##Copyright## // // $Id: defaults.h,v 1.5 2001/12/17 04:27:32 qp Exp $ #ifndef DEFAULTS_H #define DEFAULTS_H #include <sys/types.h> #include "defs.h" #include "tcp_qp.h" // // Default size in K for different global areas. // // SIZE_MULTIPLIER is used to double all sizes for 64-bit systems. const word32 SIZE_MULTIPLIER = (sizeof(void *) / sizeof(word32)); const word32 CODE_SIZE = 400 * SIZE_MULTIPLIER; const word32 STRING_TABLE_SIZE = 64; // // Default size in entries for different global hash tables. // const word32 PREDICATE_TABLE_SIZE = 10009; const word32 ATOM_TABLE_SIZE = 10009; // // Default size for different areas local to each thread. // const word32 NAME_TABLE_SIZE = 10000; const word32 HEAP_SIZE = 400; // K const word32 ENVIRONMENT_STACK_SIZE = 64; // K const word32 CHOICE_STACK_SIZE = 64; // K const word32 BINDING_TRAIL_SIZE = 32; // K const word32 OTHER_TRAIL_SIZE = 32; // K const word32 SCRATCHPAD_SIZE = 100; // K const word32 IP_TABLE_SIZE = 10000; // // Default size in K for area used in linking. // const word32 STRING_MAP_SIZE = 64; // // Default size in K entries for the record database reference table. // const word32 RECORD_DB_SIZE = 64; // // Default qx file. // char *QX_FILE = NULL; // // Default stand alone setting. If true, qem won't try to register itself // with the nameserver. Otherwise, it will. // const bool STAND_ALONE = false; // // Default nameserver port. // const u_short PEDRO_PORT = 4550; // // Default process symbol. // char *PROCESS_SYMBOL = NULL; // // Default initial goal // char* INITIAL_GOAL = NULL; // // Default initial file // char* INITIAL_FILE = NULL; // // Default debugging value. // const bool DEBUGGING = false; #endif // DEFAULTS_H
24.131579
75
0.704835
[ "object" ]
f6462b7ff878322d423ea3b7c91dfb2e88547772
5,608
h
C
smtk/extension/paraview/widgets/pqSMTKAttributeItemWidget.h
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
40
2015-02-21T19:55:54.000Z
2022-01-06T13:13:05.000Z
smtk/extension/paraview/widgets/pqSMTKAttributeItemWidget.h
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
127
2015-01-15T20:55:45.000Z
2021-08-19T17:34:15.000Z
smtk/extension/paraview/widgets/pqSMTKAttributeItemWidget.h
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
27
2015-03-04T14:17:51.000Z
2021-12-23T01:05:42.000Z
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #ifndef smtk_extension_paraview_widgets_pqSMTKAttributeItemWidget_h #define smtk_extension_paraview_widgets_pqSMTKAttributeItemWidget_h #include "smtk/extension/paraview/widgets/smtkPQWidgetsExtModule.h" #include "smtk/extension/qt/qtItem.h" class vtkSMProxy; class pqInteractivePropertyWidget; /**\brief A subclass of qtItem common to all ParaView property widgets. * * SMTK's ParaView extensions provide custom qtItem subclasses that allow * users to edit item values with 2-D/3-D widgets in the active view. * This abstract class handles as much of the commonalities between the * ParaView-widget-specific subclasses as possible. * * In particular, it creates Qt widgets to hold the ParaView GUI * components while also matching the style of other qtItem * subclasses; it manages a checkbox enabling/disabling the widget * if the item's IsOptional flag is true, it creates a label showing * the item's title, etc. */ class SMTKPQWIDGETSEXT_EXPORT pqSMTKAttributeItemWidget : public smtk::extension::qtItem { Q_OBJECT public: using qtItem = smtk::extension::qtItem; using qtAttributeItemInfo = smtk::extension::qtAttributeItemInfo; /**\brief Specify when the widget may override values in the item. * */ enum class OverrideWhen { Unset, //!< When the item is unset and FallbackStrategy is Force. Never //!< Do not ever let the widget dictate values in the item without user input. }; /**\brief Specify how to size/place a widget. * */ enum class FallbackStrategy { Hide, //!< Hide the widget rather than show an uninitialized widget. Force //!< Force the widget's size/placement to either the geometry source or the item's default. }; /**\brief Specify how to size/place a widget. * */ enum class GeometrySource { Item, //!< Use the item's current value(s). Associations, //!< Use the attribute's current association(s). Links, //!< Use the attribute-resource's linked resources. Scene, //!< Use all geometric resources in the current scene. BestGuess, //!< Use all of the above, falling back as needed. None //!< Do not use model/mesh resources to initialize the widget. }; // Convert enums to/from strings static OverrideWhen OverrideWhenConvert(const std::string& str); static std::string OverrideWhenConvert(OverrideWhen val); static FallbackStrategy FallbackStrategyConvert(const std::string& str); static std::string FallbackStrategyConvert(FallbackStrategy val); static GeometrySource GeometrySourceConvert(const std::string& str); static std::string GeometrySourceConvert(GeometrySource val); pqSMTKAttributeItemWidget( const qtAttributeItemInfo& info, Qt::Orientation orient = Qt::Horizontal); pqSMTKAttributeItemWidget( smtk::attribute::ItemPtr, QWidget* p, smtk::extension::qtBaseView* bview, Qt::Orientation orient = Qt::Horizontal); ~pqSMTKAttributeItemWidget() override; /// Subclasses must override this method to create the ParaView widget of their choice. virtual bool createProxyAndWidget(vtkSMProxy*& source, pqInteractivePropertyWidget*& widget) = 0; pqInteractivePropertyWidget* propertyWidget(); public slots: virtual void updateItemFromWidget(); virtual void updateWidgetFromItem(); /**\brief Change whether the item is enabled (and thus the widget active). * * Note that subclasses *must* override this method and, at a minimum, * set the underlying smtk::attribute::Item's optional state. * Subclasses must do this because ParaView widgets can represent items * of different types. * * However, subclasses may wish to call this method from within their * override as it will enable/disable the paraview property widget. */ void setOutputOptional(int optionEnabled); protected slots: void updateItemData() override; virtual void ignoreWidgetValues(); virtual void acceptWidgetValues(); virtual void updateItemFromWidgetInternal() = 0; virtual void updateWidgetFromItemInternal() {} protected: /// An event filter that watches for the associated Qt widget to be hidden /// or shown. When this happens, update3DWidgetVisibility() is invoked. bool eventFilter(QObject* obj, QEvent* event) override; /// Hide 3-d widgets when the Qt widget is hidden, show the widget when /// the Qt widget reappears. /// /// Subclasses may override update3DWidgetVisibility() if they do not /// want to inherit the default behavior. virtual void update3DWidgetVisibility(bool visible); void createWidget() override; virtual void clearChildWidgets(); virtual void updateUI(); virtual void createEditor(); /// Subclasses may call this to validate that a string item is /// appropriate for controlling the interaction state of the /// widget (i.e., the possibly tri-state checkbox that ParaView's /// Qt widgets provide to control render-view widget visibility). bool validateControlItem(const smtk::attribute::StringItemPtr& item); class Internal; Internal* m_p; }; #endif // smtk_extension_paraview_widgets_pqSMTKAttributeItemWidget_h
38.944444
101
0.722718
[ "mesh", "geometry", "render", "model" ]
f6498ef398926e674b9ad12750fa7c2af582b0b9
10,056
c
C
drivers/media/video/tiler/tiler-geom.c
tuxafgmur/OLD_Dhollmen_Kernel
90ed4e2e3e6321de246fa193705ae40ede4e2d8e
[ "BSD-Source-Code" ]
null
null
null
drivers/media/video/tiler/tiler-geom.c
tuxafgmur/OLD_Dhollmen_Kernel
90ed4e2e3e6321de246fa193705ae40ede4e2d8e
[ "BSD-Source-Code" ]
null
null
null
drivers/media/video/tiler/tiler-geom.c
tuxafgmur/OLD_Dhollmen_Kernel
90ed4e2e3e6321de246fa193705ae40ede4e2d8e
[ "BSD-Source-Code" ]
null
null
null
/* * tiler-geom.c * * TILER geometry functions for TI TILER hardware block. * * Author: Lajos Molnar <molnar@ti.com> * * Copyright (C) 2009-2010 Texas Instruments, Inc. * * This package is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <linux/module.h> #include "_tiler.h" /* bits representing the same slot in DMM-TILER hw-block */ #define SLOT_WIDTH_BITS 6 #define SLOT_HEIGHT_BITS 6 /* bits reserved to describe coordinates in DMM-TILER hw-block */ #define CONT_WIDTH_BITS 14 #define CONT_HEIGHT_BITS 13 static struct tiler_geom geom[TILER_FORMATS] = { { .x_shft = 0, .y_shft = 0, }, { .x_shft = 0, .y_shft = 1, }, { .x_shft = 1, .y_shft = 1, }, { .x_shft = SLOT_WIDTH_BITS, .y_shft = SLOT_HEIGHT_BITS, }, }; /* tiler space addressing bitfields */ #define MASK_XY_FLIP (1 << 31) #define MASK_Y_INVERT (1 << 30) #define MASK_X_INVERT (1 << 29) #define SHIFT_ACC_MODE 27 #define MASK_ACC_MODE 3 /* calculated constants */ #define TILER_PAGE (1 << (SLOT_WIDTH_BITS + SLOT_HEIGHT_BITS)) #define TILER_WIDTH (1 << (CONT_WIDTH_BITS - SLOT_WIDTH_BITS)) #define TILER_HEIGHT (1 << (CONT_HEIGHT_BITS - SLOT_HEIGHT_BITS)) #define VIEW_SIZE (1u << (CONT_WIDTH_BITS + CONT_HEIGHT_BITS)) #define VIEW_MASK (VIEW_SIZE - 1u) #define MASK(bits) ((1 << (bits)) - 1) #define TILER_FMT(x) ((enum tiler_fmt) \ ((x >> SHIFT_ACC_MODE) & MASK_ACC_MODE)) #define MASK_VIEW (MASK_X_INVERT | MASK_Y_INVERT | MASK_XY_FLIP) /* location of the various tiler views in physical address space */ #define TILVIEW_8BIT 0x60000000u #define TILVIEW_16BIT (TILVIEW_8BIT + VIEW_SIZE) #define TILVIEW_32BIT (TILVIEW_16BIT + VIEW_SIZE) #define TILVIEW_PAGE (TILVIEW_32BIT + VIEW_SIZE) #define TILVIEW_END (TILVIEW_PAGE + VIEW_SIZE) /* create tsptr by adding view orientation and access mode */ #define TIL_ADDR(x, orient, a)\ ((u32) (x) | (orient) | ((a) << SHIFT_ACC_MODE)) bool is_tiler_addr(u32 phys) { return phys >= TILVIEW_8BIT && phys < TILVIEW_END; } EXPORT_SYMBOL(is_tiler_addr); u32 tiler_bpp(const struct tiler_block_t *b) { enum tiler_fmt fmt = tiler_fmt(b->phys); BUG_ON(fmt == TILFMT_INVALID); return geom[fmt].bpp_m; } EXPORT_SYMBOL(tiler_bpp); static void geom_init(void) { struct tiler_geom *g; /* run only if geom has not been completely filled */ if (geom[TILFMT_PAGE].slot_h) return; /* calculate missing members of geometry structure */ for (g = geom; g < geom + TILER_FORMATS; g++) { g->bpp = 1 << (g->x_shft + g->y_shft); if (g - geom == TILFMT_PAGE) /* most applications deal in byte data for page mode */ g->bpp_m = 1; else g->bpp_m = g->bpp; g->slot_w = 1 << (SLOT_WIDTH_BITS - g->x_shft); g->slot_h = 1 << (SLOT_HEIGHT_BITS - g->y_shft); } } u32 tiler_backpages(enum tiler_fmt fmt, u32 width, u32 height) { u32 x, y; geom_init(); if (fmt == TILFMT_PAGE) { /* for 1D area keep the height (1), width is in tiler slots */ x = DIV_ROUND_UP(width, TILER_PAGE); if (x > TILER_WIDTH * TILER_HEIGHT) return 0; return x; } else if (fmt >= TILFMT_8BIT && fmt <= TILFMT_32BIT) { /* adjust to slots */ x = DIV_ROUND_UP(width, geom[fmt].slot_w); y = DIV_ROUND_UP(height, geom[fmt].slot_h); if (x > TILER_WIDTH || y > TILER_HEIGHT) return 0; return x * y; } else { return 0; } } EXPORT_SYMBOL(tiler_backpages); /* return the stride of a tiler-block in tiler space */ static inline s32 tiler_stride(u32 tsptr) { enum tiler_fmt fmt = TILER_FMT(tsptr); if (fmt == TILFMT_PAGE) return 0; else if (tsptr & MASK_XY_FLIP) return 1 << (CONT_HEIGHT_BITS + geom[fmt].x_shft); else return 1 << (CONT_WIDTH_BITS + geom[fmt].y_shft); } u32 tiler_pstride(const struct tiler_block_t *b) { enum tiler_fmt fmt = tiler_fmt(b->phys); BUG_ON(fmt == TILFMT_INVALID); /* return the virtual stride for page mode */ if (fmt == TILFMT_PAGE) return tiler_vstride(b); return tiler_stride(b->phys & ~MASK_VIEW); } EXPORT_SYMBOL(tiler_pstride); enum tiler_fmt tiler_fmt(u32 phys) { if (!is_tiler_addr(phys)) return TILFMT_INVALID; return TILER_FMT(phys); } EXPORT_SYMBOL(tiler_fmt); /* returns the tiler geometry information for a format */ static const struct tiler_geom *get_geom(enum tiler_fmt fmt) { if (fmt >= TILFMT_MIN && fmt <= TILFMT_MAX) return geom + fmt; return NULL; } /** * Returns the natural x and y coordinates for a pixel in tiler space address. * That is, the coordinates for the same pixel in the natural (non-rotated, * non-mirrored) view. This allows to uniquely identify a tiler pixel in any * view orientation. */ static void tiler_get_natural_xy(u32 tsptr, u32 *x, u32 *y) { u32 x_bits, y_bits, offset; enum tiler_fmt fmt; fmt = TILER_FMT(tsptr); x_bits = CONT_WIDTH_BITS - geom[fmt].x_shft; y_bits = CONT_HEIGHT_BITS - geom[fmt].y_shft; offset = (tsptr & VIEW_MASK) >> (geom[fmt].x_shft + geom[fmt].y_shft); /* separate coordinate bitfields based on view orientation */ if (tsptr & MASK_XY_FLIP) { *x = offset >> y_bits; *y = offset & MASK(y_bits); } else { *x = offset & MASK(x_bits); *y = offset >> x_bits; } /* account for mirroring */ if (tsptr & MASK_X_INVERT) *x ^= MASK(x_bits); if (tsptr & MASK_Y_INVERT) *y ^= MASK(y_bits); } /* calculate the tiler space address of a pixel in a view orientation */ static u32 tiler_get_address(u32 orient, enum tiler_fmt fmt, u32 x, u32 y) { u32 x_bits, y_bits, tmp, x_mask, y_mask, alignment; x_bits = CONT_WIDTH_BITS - geom[fmt].x_shft; y_bits = CONT_HEIGHT_BITS - geom[fmt].y_shft; alignment = geom[fmt].x_shft + geom[fmt].y_shft; /* validate coordinate */ x_mask = MASK(x_bits); y_mask = MASK(y_bits); if (x < 0 || x > x_mask || y < 0 || y > y_mask) return 0; /* account for mirroring */ if (orient & MASK_X_INVERT) x ^= x_mask; if (orient & MASK_Y_INVERT) y ^= y_mask; /* get coordinate address */ if (orient & MASK_XY_FLIP) tmp = ((x << y_bits) + y); else tmp = ((y << x_bits) + x); return TIL_ADDR((tmp << alignment), orient, fmt); } void tilview_create(struct tiler_view_t *view, u32 phys, u32 width, u32 height) { BUG_ON(!is_tiler_addr(phys)); view->tsptr = phys & ~MASK_VIEW; view->bpp = geom[TILER_FMT(phys)].bpp_m; view->width = width; view->height = height; view->h_inc = view->bpp; view->v_inc = tiler_stride(view->tsptr); } EXPORT_SYMBOL(tilview_create); void tilview_get(struct tiler_view_t *view, struct tiler_block_t *blk) { view->tsptr = blk->phys & ~MASK_VIEW; view->bpp = tiler_bpp(blk); view->width = blk->width; view->height = blk->height; view->h_inc = view->bpp; view->v_inc = tiler_stride(view->tsptr); } EXPORT_SYMBOL(tilview_get); s32 tilview_crop(struct tiler_view_t *view, u32 left, u32 top, u32 width, u32 height) { /* check for valid crop */ if (left + width < left || left + width > view->width || top + height < top || top + height > view->height) return -EINVAL; view->tsptr += left * view->h_inc + top * view->v_inc; view->width = width; view->height = height; return 0; } EXPORT_SYMBOL(tilview_crop); /* calculate tilerspace address and stride after view orientation change */ static void reorient(struct tiler_view_t *view, u32 orient) { u32 x, y; tiler_get_natural_xy(view->tsptr, &x, &y); view->tsptr = tiler_get_address(orient, TILER_FMT(view->tsptr), x, y); view->v_inc = tiler_stride(view->tsptr); } s32 tilview_rotate(struct tiler_view_t *view, s32 rotation) { u32 orient; if (rotation % 90) return -EINVAL; /* normalize rotation to quarters */ rotation = (rotation / 90) & 3; if (!rotation) return 0; /* nothing to do */ /* PAGE mode view cannot be rotated */ if (TILER_FMT(view->tsptr) == TILFMT_PAGE) return -EPERM; /* * first adjust top-left corner. NOTE: it rotates counter-clockwise: * 0 < 3 * v ^ * 1 > 2 */ if (rotation < 3) view->tsptr += (view->height - 1) * view->v_inc; if (rotation > 1) view->tsptr += (view->width - 1) * view->h_inc; /* then rotate view itself */ orient = view->tsptr & MASK_VIEW; /* rotate first 2 quarters */ if (rotation & 2) { orient ^= MASK_X_INVERT; orient ^= MASK_Y_INVERT; } /* rotate last quarter */ if (rotation & 1) { orient ^= (orient & MASK_XY_FLIP) ? MASK_X_INVERT : MASK_Y_INVERT; /* swap x & y */ orient ^= MASK_XY_FLIP; swap(view->height, view->width); } /* finally reorient view */ reorient(view, orient); return 0; } EXPORT_SYMBOL(tilview_rotate); s32 tilview_flip(struct tiler_view_t *view, bool flip_x, bool flip_y) { u32 orient; orient = view->tsptr & MASK_VIEW; if (!flip_x && !flip_y) return 0; /* nothing to do */ /* PAGE mode view cannot be flipped */ if (TILER_FMT(view->tsptr) == TILFMT_PAGE) return -EPERM; /* adjust top-left corner */ if (flip_x) view->tsptr += (view->width - 1) * view->h_inc; if (flip_y) view->tsptr += (view->height - 1) * view->v_inc; /* flip view orientation */ if (orient & MASK_XY_FLIP) swap(flip_x, flip_y); if (flip_x) orient ^= MASK_X_INVERT; if (flip_y) orient ^= MASK_Y_INVERT; /* finally reorient view */ reorient(view, orient); return 0; } EXPORT_SYMBOL(tilview_flip); /* return the alias address for a coordinate */ static inline u32 alias_address(enum tiler_fmt fmt, u32 x, u32 y) { return tiler_get_address(0, fmt, x, y) + TILVIEW_8BIT; } /* get the coordinates for an alias address */ static inline void alias_xy(u32 ssptr, u32 *x, u32 *y) { tiler_get_natural_xy(ssptr & ~MASK_VIEW, x, y); } /* initialize shared geometric data */ void tiler_geom_init(struct tiler_ops *tiler) { tiler->xy = alias_xy; tiler->addr = alias_address; tiler->geom = get_geom; tiler->page = TILER_PAGE; tiler->width = TILER_WIDTH; tiler->height = TILER_HEIGHT; geom_init(); }
24.407767
79
0.683572
[ "geometry" ]
f657a3cb05e1311ef9cd8f2bc1c7286cb2717381
21,889
c
C
C/main.c
SafraPC/CEPPER
5e3b30846488e3ee526fc35f253aaa566c648ef1
[ "MIT" ]
null
null
null
C/main.c
SafraPC/CEPPER
5e3b30846488e3ee526fc35f253aaa566c648ef1
[ "MIT" ]
null
null
null
C/main.c
SafraPC/CEPPER
5e3b30846488e3ee526fc35f253aaa566c648ef1
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <mysql/mysql.h> #include <time.h> #include <string.h> #include <ctype.h> int main() { //database host ip const char *host = "127.0.0.1"; //database username const char *user = "root"; //database user password const char *password = "admin"; //database table to in const char *database = "cepper"; //database export port const int port = 3306; //LINUX socket to database static char *unix_socket = NULL; //database flag const int flag = 0; //database connection stabilized MYSQL *conn; //init mysql connection conn = mysql_init(NULL); typedef struct { char *name; //define name of Logged user } LoggedUser; LoggedUser loggedUser; //verify if connection its nul for exit program if (conn == NULL) { fprintf(stderr, "%s\n", mysql_error(conn)); exit(1); } //connect to database specified if (!(mysql_real_connect(conn, host, user, password, database, port, unix_socket, flag))) { //show database error. fprintf(stderr, "Error %s [%d]\n", mysql_error(conn), mysql_errno(conn)); } //If we arrived here, the connection is ok and we can make mysql querys! //!Below we have some methods that the program is using //clean bashs alive void clearScreen() { printf("\e[1;1H\e[2J"); } //timeout for C wait a little (special for request) void setTimeout(int milliSec) { //verifying if millisec is negative to stop it if (milliSec <= 0) { return; } //create a clock in 1000 miliSec and /to clock_per_sec time method int sinceMilli = clock() * 1000 / CLOCKS_PER_SEC; //create clockeEnd miliSec to wait int clockEnd = sinceMilli + milliSec; do { //wait when clock have the time sinceMilli = clock() * 1000 / CLOCKS_PER_SEC; } while (sinceMilli <= clockEnd); } //Verify if exist some error in tberror, if exists then CEP Query failed. bool verifyError() { //Making query.. if (mysql_query(conn, "select error from tberror")) { //mysql_query returns 1 if returns an error in mysql query. return true; } MYSQL_RES *result = mysql_store_result(conn); //freedom for result! int num_fields = mysql_num_fields(result); MYSQL_ROW row; char *errors[1]; errors[0] = false; while ((row = mysql_fetch_row(result))) { for (int i = 0; i < num_fields; i++) { errors[i] = row[i] ? row[i] : "-"; } } if (errors[0]) { mysql_query(conn, "truncate table tberror"); return true; } else { return false; } } //Searching in database for see if we have the CEP data bool searchCEP(char *searchQuery, char *cep) { //create mysqlQuery if (mysql_query(conn, searchQuery)) { //if we got an error, return nothing. return false; } //storing result MYSQL_RES *result = mysql_store_result(conn); //getting num of fields like matriz [10] int num_fields = mysql_num_fields(result); //dispatch the rows MYSQL_ROW row; //create an char array to store the result char *cepInfos[10]; //NULL the result for right validation cepInfos[1] = NULL; cepInfos[3] = NULL; //while we have rows to be read, write it in the char array while ((row = mysql_fetch_row(result))) { for (int i = 0; i < num_fields; i++) { cepInfos[i] = row[i] ? row[i] : "-"; } } //if we really found the CEP in database if (cepInfos[1] && cepInfos[3]) { clearScreen(); //CEP FOUNDED! printf("\n\nInformações do CEP : %s\n", cep); printf("\nCEP: %s", cepInfos[1]); printf("\nLOGRADOURO: %s ", cepInfos[2]); printf("\nBAIRRO: %s", cepInfos[3]); printf("\nLOCALIDADE: %s", cepInfos[4]); printf("\nUF: %s", cepInfos[5]); printf("\nIBGE: %s", cepInfos[6]); printf("\nGIA: %s", cepInfos[7]); printf("\nDDD: %s", cepInfos[8]); printf("\nSIAFI: %s", cepInfos[9]); return true; } else { //return false if we dont found nothing in database about that CEP return false; } } //get the cep from database or search CEP in viaCEP external service bool getCEP(char *cep) { //getting cep from table ceps const char *query = "select * from ceps where cep = '"; char selectQueryAux[100]; char selectQuery[100]; //concact string to a right mysql query strcat(strcpy(selectQuery, cep), "'"); strcat(strcpy(selectQueryAux, query), selectQuery); // if search CEP found our CEP, it will return the CEP in a log //so just return true. if (searchCEP(selectQueryAux, cep)) { return true; } //if the CEP didnt found, we need to Sercht it in the //external Services for found CEP else { //create concact cep query to our mysql const char *insertQueryString = "insert into tbquery(query) values('"; char insertQueryAux[100]; char insertQuery[100]; //concact with strcat strcat(strcpy(insertQueryAux, insertQueryString), cep); strcat(strcpy(insertQuery, insertQueryAux), "')"); //craate mysql query if (mysql_query(conn, insertQuery)) { printf("\n\nHouve um erro com o banco."); return false; } //most important part of our program //FAIL OVER to get our CEP data //how the request is Async, we need to wait a little // so we have 14 tryes and some seconds to wait. for (int i = 0; i < 14; i++) { //verify if we got errors in our JS server if (verifyError()) { printf("\n\nPor favor, insira um CEP válido."); return false; } setTimeout(3500); //Searching CEP in our MySQL table if (searchCEP(selectQueryAux, cep)) { return true; } else { //Failver reached the limit.. sorry. if (i + 1 >= 3) { printf("\n\nInfelizmente não conseguimos localizar seu CEP."); return false; } } } //some error ocurred. return false; } } //search login inside database bool searchLoginInDatabase(char *login, char *password) { //getting user from table users char *query = "select name from users where email = '"; char selectQuery[100]; char ConcactQueryAux[100]; char ConcactQueryAuxForCPF[200]; char ConcactQueryAuxForCPF2[200]; char ConcactQueryAuxAux[200]; char ConcactQueryAuxAuxAux[200]; char ConcactQueryAuxAuxAuxAux[200]; char ConcactQueryAuxAuxAuxAuxAux[200]; //concact string to a right mysql query strcat(strcpy(selectQuery, login), "' or cpf = '"); strcat(strcpy(ConcactQueryAux, query), selectQuery); strcat(strcpy(ConcactQueryAuxForCPF, ConcactQueryAux), login); strcat(strcpy(ConcactQueryAuxForCPF2, ConcactQueryAuxForCPF), "' "); strcat(strcpy(ConcactQueryAuxAux, ConcactQueryAuxForCPF2), "and pass = '"); strcat(strcpy(ConcactQueryAuxAuxAux, ConcactQueryAuxAux), password); strcat(strcpy(ConcactQueryAuxAuxAuxAux, ConcactQueryAuxAuxAux), "'"); if (mysql_query(conn, ConcactQueryAuxAuxAuxAux)) { //if we got an error, return nothing. return false; } //storing result MYSQL_RES *result = mysql_store_result(conn); //getting num of fields like matriz [10] int num_fields = mysql_num_fields(result); //dispatch the rows MYSQL_ROW row; //create an char array to store the result char *user[0]; //NULL the result for right validation user[0] = NULL; //while we have rows to be read, write it in the char array while ((row = mysql_fetch_row(result))) { for (int i = 0; i < num_fields; i++) { user[i] = row[i] ? row[i] : "-"; } } //if we really found the USER in database if (user[0]) { //USER FOUNDED! clearScreen(); loggedUser.name = user[0]; printf("Bem-vindo, %s", loggedUser.name); return true; } else { //return false if we dont found nothing in database about that USER return false; } } //sistem interface for login bool makeLogin(bool pass) { if (!pass) { clearScreen(); printf("Bem vindo ao Sistema de Login! por favor preencha os campos abaixo...\n"); } char *login[50]; char *password[50]; printf("\nInsira seu Email ou CPF: "); scanf("%s", &login); if (strlen(login) < 10) { printf("Insira seu CPF ou Email corretamente!"); makeLogin(true); return false; } printf("\nInsira sua senha:"); scanf(" %s", &password); if (strlen(password) < 2) { printf("Senha inválida, tente novamente!"); makeLogin(true); return false; } if (searchLoginInDatabase(login, password)) { return true; } else { return false; } } //method for verify if the arrays are equals bool isDiff(char *array, char *validationArray) { const int arrayLength = strlen(array); const int arrayValLength = strlen(validationArray); bool error = false; for (int i = 0; i < arrayLength; i++) { if (error) { break; } for (int j = 0; j < arrayValLength; j++) { if (array[i] == validationArray[j]) { break; } else if (j + 1 >= arrayValLength) { error = true; break; } } } return error; } //Interface for user navigate in login and register. bool initInterface(bool pass) { //sistem register in database bool makeRegister(bool pass) { if (!pass) { clearScreen(); printf("Bem-vindo ao sistema de Cadastro! preencha os campos abaixo para continuar ...\n"); } //items to validate /* !name !born !cpf !email !pass !rePass */ char name[200]; char born[20]; char cpf[20]; char email[200]; char password[100]; char rePassword[100]; //array for validations char *validLetters = "abcdefghijklmnopqrstuvwxyz"; char *validEmail = "abcdefghijklmnopqrstuvwxyz@.123456789"; char *validNumbers = "0123456789"; char *validDate = "0123456789/"; printf("\nInsira seu primeiro nome (sem espaços): "); scanf("%s", &name); char *auxName = name; for (int i = 0; i < strlen(auxName); i++) { auxName[i] = tolower(auxName[i]); } bool difName = isDiff(name, validLetters); if (difName) { printf("\n Nomes apenas podem conter letras! insira um nome válido, sem espaço. \n"); makeRegister(true); return false; } printf("\nPerfeito! agora insira sua data de Nasc. (DD/MM/YYYY) Respectivamente."); scanf("%s", born); if (born[2] == '/' && born[5] == '/') { bool difDate = isDiff(born, validDate); if (difDate) { printf("\nInsira uma data válida! padrão (DD/MM/YYYY) \n"); makeRegister(true); return false; } } else { printf("\nInsira uma data válida com barras! padrão (DD/MM/YYYY) \n"); makeRegister(true); return false; } printf("\nÓtimo! agora, por favor, insira seu CPF, (apenas números): "); scanf("%s", &cpf); if (strlen(cpf) != 11) { printf("\nATENÇÃO! um CPF contém apenas 11 digitos."); makeRegister(true); return false; } bool cpfDif = isDiff(cpf, validNumbers); if (cpfDif) { printf("ATENÇÃO! CPF, deve conter apenas numeros"); makeRegister(true); return false; } printf("\nIncrível! agora, por favor, insira seu Email: "); scanf("%s", &email); for (int i = 0; i < strlen(email); i++) { email[i] = tolower(email[i]); } bool emailDif = isDiff(email, validEmail); if (emailDif) { printf("\nATENÇÃO! Emails não contém carácteres especiais além do @!"); makeRegister(true); return false; } printf("\nPara finalizar, insira sua senha de login: "); scanf("%s", &password); printf("\nConfirme sua senha: "); scanf("%s", &rePassword); for (int i = 0; i < strlen(password); i++) { if (password[i] != rePassword[i]) { printf("\nATENÇÃO! As senhas são divergentes!"); makeRegister(true); return false; } } for (int i = 0; i < strlen(rePassword); i++) { if (password[i] != rePassword[i]) { printf("\nATENÇÃO! As senhas são divergentes!"); makeRegister(true); return false; } } int confirm = false; clearScreen(); printf("\n\nSeus dados:\nNome: %s\nData de nascimento: %s\nCPF: %s\nEmail: %s\nSenha: %s\n\nConfirma?\n-Pressione 0 para confirmar\n-Pressione 1 para cancelar\n\n", name, born, cpf, email, password); scanf("%i", &confirm); if (confirm == 0) { /* !req model : ?insert into users(name,born,cpf,email,pass) values('Teste','06/10/2002','42413069800','leandrosafra@gmail.com','123'); */ char *query = "insert into users(name,born,cpf,email,pass) values('"; char selectQuery[100]; char ConcactQueryAux[300]; char ConcactQueryAuxAux[300]; char ConcactQueryAuxAuxAux[300]; char ConcactQueryAuxAuxAuxAux[300]; char ConcactQueryAuxAuxAuxAuxAux[400]; char ConcactQueryAuxAuxAuxAuxAuxAux[500]; char ConcactQueryAuxAuxAuxAuxAuxAuxAux[500]; char ConcactQueryAuxAuxAuxAuxAuxAuxAuxAux[600]; char ConcactQueryAuxAuxAuxAuxAuxAuxAuxAuxAux[600]; //concact string to a right mysql query strcat(strcpy(selectQuery, query), name); strcat(strcpy(ConcactQueryAux, selectQuery), "','"); strcat(strcpy(ConcactQueryAuxAux, ConcactQueryAux), born); strcat(strcpy(ConcactQueryAuxAuxAux, ConcactQueryAuxAux), "','"); strcat(strcpy(ConcactQueryAuxAuxAuxAux, ConcactQueryAuxAuxAux), cpf); strcat(strcpy(ConcactQueryAuxAuxAuxAuxAux, ConcactQueryAuxAuxAuxAux), "','"); strcat(strcpy(ConcactQueryAuxAuxAuxAuxAuxAux, ConcactQueryAuxAuxAuxAuxAux), email); strcat(strcpy(ConcactQueryAuxAuxAuxAuxAuxAuxAux, ConcactQueryAuxAuxAuxAuxAuxAux), "','"); strcat(strcpy(ConcactQueryAuxAuxAuxAuxAuxAuxAuxAux, ConcactQueryAuxAuxAuxAuxAuxAuxAux), password); strcat(strcpy(ConcactQueryAuxAuxAuxAuxAuxAuxAuxAuxAux, ConcactQueryAuxAuxAuxAuxAuxAuxAuxAux), "');"); if (mysql_query(conn, ConcactQueryAuxAuxAuxAuxAuxAuxAuxAuxAux)) { //if we got an error, return nothing. return false; } if (searchLoginInDatabase(email, password)) { return true; } else { return false; } } else { clearScreen(); initInterface(true); return false; } } //login interface method bool loginInterface() { int accept = NULL; printf("\nDeseja realmente prosseguir para a tela de login?\n-Pressione 0 para prosseguir\n-Pressione 1 para voltar a tela de início\n"); scanf("%i", &accept); if (accept == 0) { if (makeLogin(false)) { return true; } else { printf("\nCredenciais erradas! por favor, tente novamente.\n"); initInterface(true); return false; } } else if (accept == 1) { initInterface(true); return false; } else { printf("\nPor favor, insira um item válido.. :"); loginInterface(); return false; } } //sistem register interface method bool registerInterface() { clearScreen(); int accept = NULL; printf("\nDeseja realmente prosseguir para a tela de cadastro?\n-Pressione 0 para prosseguir\n-Pressione 1 para voltar a tela de início\n"); scanf("%i", &accept); if (accept == 0) { if (makeRegister(false)) { return true; } else { printf("\nAlgo deu errado..\n"); initInterface(true); return false; } } else if (accept == 1) { initInterface(true); return false; } else { printf("\nPor favor, pressione uma opção válida.. :"); registerInterface(); return false; } } if (!pass) { clearScreen(); printf("\nSeja bem-vindo ao CEPPER! seu pesquisador de CEPS particular."); printf("\npor-favor, faça seu login ou se cadastre para continuar."); } printf("\n- Pressione 0 para realizar seu Login\n- Pressione 1 para realizar um Cadastro\n\n"); int pass1_num_pressed = 2; scanf("%i", &pass1_num_pressed); if (pass1_num_pressed == 0) { if (loginInterface()) { return true; } else { return false; } } else if (pass1_num_pressed == 1) { if (registerInterface()) { return true; } else { return false; } } else { printf("Por favor, selecione um número válido!"); initInterface(true); return false; } } //App program to use the function created above void loggedApp(bool pass) { if (!pass) { clearScreen(); printf("Olá, %s!\nFicamos muito felizes por acessar os serviços CEPPER.\n", loggedUser.name); } printf("\n\n-Pressione 0 para pesquisar um CEP\n-Pressione 1 para sair\n\n"); int pressed = NULL; scanf("%i", &pressed); if (pressed == 0) { char *userCEP[20]; printf("\n\nInsira o CEP que deseja buscar\n"); printf("CEP:"); scanf("%s", &userCEP); getCEP(userCEP); loggedApp(true); } else if (pressed == 1) { exit(1); } else { loggedApp(true); } } bool app() { if (initInterface(false)) { loggedApp(false); } } app(); return 0; }
32.380178
211
0.489881
[ "model" ]
f65aab5cef9d25a44cee1e07dd6fb08760343fb9
3,264
h
C
include/opennsl/multicastX.h
SyncMonk-Technologies/OpenNSL
a3f85f5567f3142755265d32efb22cfe5afdb22e
[ "Apache-2.0" ]
275
2015-03-09T05:06:43.000Z
2022-03-06T22:07:07.000Z
include/opennsl/multicastX.h
SyncMonk-Technologies/OpenNSL
a3f85f5567f3142755265d32efb22cfe5afdb22e
[ "Apache-2.0" ]
51
2015-09-07T07:10:04.000Z
2021-12-09T18:32:21.000Z
include/opennsl/multicastX.h
SyncMonk-Technologies/OpenNSL
a3f85f5567f3142755265d32efb22cfe5afdb22e
[ "Apache-2.0" ]
103
2015-03-10T19:55:34.000Z
2021-09-21T08:01:06.000Z
/** \addtogroup multicast Multicast Traffic Management * @{ */ /***************************************************************************** * * This software is governed by the Broadcom Advanced Switch APIs license. * This license is set out in the * https://github.com/Broadcom-Switch/OpenNSL/Legal/LICENSE-Adv file. * * Copyright 2015-2016 Broadcom Corporation. All rights reserved. * ***************************************************************************//** * \file multicastX.h ******************************************************************************/ #ifndef __OPENNSL_MULTICASTX_H__ #define __OPENNSL_MULTICASTX_H__ #include <opennsl/types.h> /***************************************************************************//** *\brief Get the multicast encapsulation ID for VXLAN replication. * *\description Get the multicast encapsulation ID for VXLAN replication. The * encapsulation ID is an opaque object passed in to * opennsl_multicast_egress_* APIs when adding/removing ports to a * multicast group. * *\param unit [IN] Unit number. *\param group [IN] Multicast group ID *\param port [IN] Physical GPORT ID *\param vxlan_port_id [IN] VXLAN GPORT ID *\param encap_id [OUT] Encapsulation ID * *\retval OPENNSL_E_XXX ******************************************************************************/ extern int opennsl_multicast_vxlan_encap_get( int unit, opennsl_multicast_t group, opennsl_gport_t port, opennsl_gport_t vxlan_port_id, opennsl_if_t *encap_id) LIB_DLL_EXPORTED ; /***************************************************************************//** *\brief Set/get miscellaneous per multicast group controls. * *\description Sets/gets miscellaneous per multicast group parameters. * *\param unit [IN] Unit number. *\param group [IN] Multicast group ID *\param type [IN] Multicast control parameter (see =multicast_controls) *\param arg [IN] (for _set) A parameter whose meaning is dependent on * 'type' * *\retval OPENNSL_E_UNAVAIL Feature not supported. *\retval OPENNSL_E_XXX ******************************************************************************/ extern int opennsl_multicast_control_set( int unit, opennsl_multicast_t group, opennsl_multicast_control_t type, int arg) LIB_DLL_EXPORTED ; /***************************************************************************//** *\brief Set/get miscellaneous per multicast group controls. * *\description Sets/gets miscellaneous per multicast group parameters. * *\param unit [IN] Unit number. *\param group [IN] Multicast group ID *\param type [IN] Multicast control parameter (see =multicast_controls) *\param arg [OUT] (for _set) A parameter whose meaning is dependent on * 'type' * *\retval OPENNSL_E_UNAVAIL Feature not supported. *\retval OPENNSL_E_XXX ******************************************************************************/ extern int opennsl_multicast_control_get( int unit, opennsl_multicast_t group, opennsl_multicast_control_t type, int *arg) LIB_DLL_EXPORTED ; #endif /* __OPENNSL_MULTICASTX_H__ */ /*@}*/
37.953488
81
0.553615
[ "object" ]
f65b0be81e877b78244c3ff32b2b02b518c1b322
3,615
h
C
include/orion/span_gouraud.h
primatelabs/orion
df4393e6f9e2bdf50b74e6ba14f67071cdb7cee6
[ "BSD-3-Clause" ]
null
null
null
include/orion/span_gouraud.h
primatelabs/orion
df4393e6f9e2bdf50b74e6ba14f67071cdb7cee6
[ "BSD-3-Clause" ]
null
null
null
include/orion/span_gouraud.h
primatelabs/orion
df4393e6f9e2bdf50b74e6ba14f67071cdb7cee6
[ "BSD-3-Clause" ]
null
null
null
// Copyright (C) 2002-2005 Maxim Shmanarev (http://www.antigrain.com) // Copyright (c) 2004-2021 Primate Labs Inc. // All rights reserved. // // Use of this source code is governed by the BSD 3-Clause License that can // be found in the LICENSE file. #ifndef ORION_SPAN_GOURAUD_H__ #define ORION_SPAN_GOURAUD_H__ #include "orion/basics.h" #include "orion/math.h" namespace orion { template <class ColorT> class span_gouraud { public: typedef ColorT color_type; struct coord_type { double x; double y; color_type color; }; span_gouraud() : m_vertex(0) { m_cmd[0] = path_cmd_stop; } span_gouraud(const color_type& c1, const color_type& c2, const color_type& c3, double x1, double y1, double x2, double y2, double x3, double y3, double d) : m_vertex(0) { colors(c1, c2, c3); triangle(x1, y1, x2, y2, x3, y3, d); } void colors(ColorT c1, ColorT c2, ColorT c3) { m_coord[0].color = c1; m_coord[1].color = c2; m_coord[2].color = c3; } // Sets the triangle and dilates it if needed. // The trick here is to calculate beveled joins in the vertices of the // triangle and render it as a 6-vertex polygon. // It's necessary to achieve numerical stability. // However, the coordinates to interpolate colors are calculated // as miter joins (calc_intersection). void triangle(double x1, double y1, double x2, double y2, double x3, double y3, double d) { m_coord[0].x = m_x[0] = x1; m_coord[0].y = m_y[0] = y1; m_coord[1].x = m_x[1] = x2; m_coord[1].y = m_y[1] = y2; m_coord[2].x = m_x[2] = x3; m_coord[2].y = m_y[2] = y3; m_cmd[0] = path_cmd_move_to; m_cmd[1] = path_cmd_line_to; m_cmd[2] = path_cmd_line_to; m_cmd[3] = path_cmd_stop; if (d != 0.0) { dilate_triangle(m_coord[0].x, m_coord[0].y, m_coord[1].x, m_coord[1].y, m_coord[2].x, m_coord[2].y, m_x, m_y, d); calc_intersection(m_x[4], m_y[4], m_x[5], m_y[5], m_x[0], m_y[0], m_x[1], m_y[1], &m_coord[0].x, &m_coord[0].y); calc_intersection(m_x[0], m_y[0], m_x[1], m_y[1], m_x[2], m_y[2], m_x[3], m_y[3], &m_coord[1].x, &m_coord[1].y); calc_intersection(m_x[2], m_y[2], m_x[3], m_y[3], m_x[4], m_y[4], m_x[5], m_y[5], &m_coord[2].x, &m_coord[2].y); m_cmd[3] = path_cmd_line_to; m_cmd[4] = path_cmd_line_to; m_cmd[5] = path_cmd_line_to; m_cmd[6] = path_cmd_stop; } } // Vertex Source Interface to feed the coordinates to the rasterizer void rewind(unsigned) { m_vertex = 0; } unsigned vertex(double* x, double* y) { *x = m_x[m_vertex]; *y = m_y[m_vertex]; return m_cmd[m_vertex++]; } protected: void arrange_vertices(coord_type* coord) const { coord[0] = m_coord[0]; coord[1] = m_coord[1]; coord[2] = m_coord[2]; if (m_coord[0].y > m_coord[2].y) { coord[0] = m_coord[2]; coord[2] = m_coord[0]; } coord_type tmp; if (coord[0].y > coord[1].y) { tmp = coord[1]; coord[1] = coord[0]; coord[0] = tmp; } if (coord[1].y > coord[2].y) { tmp = coord[2]; coord[2] = coord[1]; coord[1] = tmp; } } private: coord_type m_coord[3]; double m_x[8]; double m_y[8]; unsigned m_cmd[8]; unsigned m_vertex; }; } // namespace orion #endif
19.972376
91
0.559889
[ "render" ]
34ebe84b3dc55a70e8c61dc95885ffeece967d7e
5,163
h
C
src/time-aux.h
yvs314/dp-monster
15addeb4a4dd8c66302f92a719b849ac99cfbefc
[ "MIT" ]
null
null
null
src/time-aux.h
yvs314/dp-monster
15addeb4a4dd8c66302f92a719b849ac99cfbefc
[ "MIT" ]
1
2022-01-12T23:12:52.000Z
2022-01-12T23:12:52.000Z
src/time-aux.h
yvs314/dp-monster
15addeb4a4dd8c66302f92a719b849ac99cfbefc
[ "MIT" ]
null
null
null
/* (c) Yaroslav Salii & the Parliament of Owls, 2017+ License:sort of CC---if you go commercial, contact me time-aux v.1.0 2017-01-30; added cond.cmpl, to swap localtime_s/_r, etc. timing auxiliaries; for logging etc. everything measured in seconds, that should be enough well one reviewer wants ms, let's indulge */ #ifdef _WIN32 #define mylocaltime(tmp,input) localtime_s(tmp,input) #define mygmtime(tmp,input) gmtime_s(tmp,input) #endif #ifdef __linux__ #define mylocaltime(tmp,input) localtime_r(input,tmp) #define mygmtime(tmp,input) gmtime_r(input,tmp) #endif #ifndef TIME_AUX_H_ #define TIME_AUX_H_ #include<cmath> #include<ctime> #include<vector> #include<iomanip> #include<sstream> #include<chrono> // for millisecond-precise measurements #include"bitset-base.h" //for mtag using myClock = std::chrono::steady_clock;//the simplest in use using t_timeStamp = myClock::time_point; //time stamps using t_msec = std::chrono::milliseconds;//milliseconds duration for more precise measurements t_msec msecDuration(const t_timeStamp from, const t_timeStamp till) { return std::chrono::duration_cast<t_msec>(till - from); } //==========STOPWATCH======for timekeeping using t_stopwatch = struct t_stopwatch { //abs.time, start:calculation started, eopt:found optimal route time_t start; t_timeStamp recoveryDone;//to time solution recovery //timestamps. vlayerDone[0] doubles as DP start time, vlayerDone[dim] doubles as DP end time std::vector<t_timeStamp> vlayerDone; //rel.time, returns time in milliseconds t_msec _rel_time(const mtag from, const mtag till) const { //return msecDuration(this->vlayerDone.at(till) - this->vlayerDone.at(from)); return std::chrono::duration_cast<t_msec> (this->vlayerDone[till] - this->vlayerDone[from]); } }; inline time_t getRelTime(const time_t from, const time_t till) { return std::lround(std::difftime(from,till)); } inline std::string mkTimeStamp(const time_t input)//YYYY/MM/DD HH:MM:SS { struct tm* tmp = new struct tm; mylocaltime(tmp, &input); std::ostringstream foo; foo << std::put_time(tmp, "%Y/%m/%d %H:%M:%S");// std::string out(foo.str()); delete tmp; return (foo.str()); } //HH:MM:SS; modulo 1 day, sort of; ain't designed for more than 1 day-long jobs inline std::string mkDuration(const time_t input) { //GMT for starting from zero struct tm* tmp = new struct tm; mygmtime(tmp, &input); std::ostringstream foo; foo << std::put_time(tmp, "%H:%M:%S"); delete tmp; return (foo.str()); } //from a duration in milliseconds, make a string formatted as HH:MM:SS.MSS inline std::string mkMsecDurationFull(const t_msec inp) { //shouldn't be more than 24 hours anyway, so not checking for days etc. std::chrono::hours hrs = std::chrono::duration_cast<std::chrono::hours>(inp); std::chrono::minutes mns = std::chrono::duration_cast<std::chrono::minutes>(inp % std::chrono::hours(1)); std::chrono::seconds sec = std::chrono::duration_cast<std::chrono::seconds>(inp % std::chrono::minutes(1)); t_msec msec = std::chrono::duration_cast<t_msec>(inp % std::chrono::seconds(1)); std::string sep = ":"; std::ostringstream foo; foo << std::setfill('0') << std::setw(2)<<hrs.count()<<sep << std::setw(2)<<mns.count()<<sep << std::setw(2)<<sec.count()<<"." << std::setw(3)<<msec.count(); return foo.str(); } //SS.MSS inline std::string mkMsecDurationBrief(const t_msec inp) { std::chrono::seconds sec = std::chrono::duration_cast<std::chrono::seconds>(inp); t_msec msec = std::chrono::duration_cast<t_msec>(inp % std::chrono::seconds(1)); std::string sep = ":"; std::ostringstream foo; foo << sec.count() << "." << std::setfill('0')<< std::setw(3) << msec.count(); return foo.str(); } #endif //t_msec layer_took(const mtag nlayer) const //{ // //filter layer no.0, just in case // return (nlayer > 0) ? (_rel_time(nlayer - 1, nlayer)) : (t_msec(0)); //} //AN ATTEMPT AT std::chrono; aborted: must still use time_t for output /*steady_clock may not be as precise but is guaranteed against adjustments that might lead to unexpected negative time differences; time goes ==steadily== forward */ //using clock = std::chrono::steady_clock;//the simplest //using seconds = std::chrono::seconds; // //using t_sw2 = //struct t_sw2 //{ // //startedAt:program start time; doneRecovery: recovered the (opt) sln from BF // clock::time_point startedAt, doneRecovery; // /*records when is the vdoneLayer[l] was computed, including relative to previous // vdoneLayer[0] just might be used for timing input, etc;*/ // std::vector<t_timeRec> vdoneLayer; //}; // //using t_timeRec = //struct t_timeRec //{ // clock::time_point totalTime; // seconds relTime;//duration; since last layer, etc. // // //starting point: take the current time, relTime is irrelevant // t_timeRec() // : totalTime(clock::now()) // , relTime(0) // { // }; // // t_timeRec(const t_timeRec& prev) // : totalTime(clock::now()) // , relTime((totalTime - prev.totalTime).count()) // { // }; //};
32.068323
95
0.679644
[ "vector" ]
34ec074d456c140a7919aac2c154316b167cc933
6,771
h
C
libraries/shared/src/PrioritySortUtil.h
amantley/blendshapes
3f5820266762f9962d9bb5bd91912272005e4f02
[ "Apache-2.0" ]
null
null
null
libraries/shared/src/PrioritySortUtil.h
amantley/blendshapes
3f5820266762f9962d9bb5bd91912272005e4f02
[ "Apache-2.0" ]
null
null
null
libraries/shared/src/PrioritySortUtil.h
amantley/blendshapes
3f5820266762f9962d9bb5bd91912272005e4f02
[ "Apache-2.0" ]
null
null
null
// // PrioritySortUtil.h // // Created by Andrew Meadows on 2017-11-08 // Copyright 2017 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #pragma once #ifndef hifi_PrioritySortUtil_h #define hifi_PrioritySortUtil_h #include <glm/glm.hpp> #include <queue> #include "NumericalConstants.h" #include "shared/ConicalViewFrustum.h" /* PrioritySortUtil is a helper for sorting 3D things relative to a ViewFrustum. To use: (1) Derive a class from pure-virtual PrioritySortUtil::Sortable that wraps a copy of the Thing you want to prioritize and sort: class SortableWrapper: public PrioritySortUtil::Sortable { public: SortableWrapper(const Thing& thing) : _thing(thing) { } glm::vec3 getPosition() const override { return _thing->getPosition(); } float getRadius() const override { return 0.5f * _thing->getBoundingRadius(); } uint64_t getTimestamp() const override { return _thing->getLastTime(); } Thing getThing() const { return _thing; } private: Thing _thing; }; (2) Make a PrioritySortUtil::PriorityQueue<Thing> and add them to the queue: PrioritySortUtil::PriorityQueue<SortableWrapper> sortedThings(viewFrustum); std::priority_queue< PrioritySortUtil::Sortable<Thing> > sortedThings; for (thing in things) { sortedThings.push(SortableWrapper(thing)); } (3) Loop over your priority queue and do timeboxed work: NOTE: Be careful using references to members of instances of T from std::priority_queue<T>. Under the hood std::priority_queue<T> may re-use instances of T. For example, after a pop() or a push() the top T may have the same memory address as the top T before the pop() or push() (but point to a swapped instance of T). This causes a reference to member variable of T to point to a different value when operations taken on std::priority_queue<T> shuffle around the instances of T. uint64_t cutoffTime = usecTimestampNow() + TIME_BUDGET; while (!sortedThings.empty()) { const Thing& thing = sortedThings.top(); // ...do work on thing... sortedThings.pop(); if (usecTimestampNow() > cutoffTime) { break; } } */ namespace PrioritySortUtil { constexpr float DEFAULT_ANGULAR_COEF { 1.0f }; constexpr float DEFAULT_CENTER_COEF { 0.5f }; constexpr float DEFAULT_AGE_COEF { 0.25f / (float)(USECS_PER_SECOND) }; class Sortable { public: virtual glm::vec3 getPosition() const = 0; virtual float getRadius() const = 0; virtual uint64_t getTimestamp() const = 0; void setPriority(float priority) { _priority = priority; } float getPriority() const { return _priority; } bool operator<(const Sortable& other) const { return _priority < other._priority; } private: float _priority { 0.0f }; }; template <typename T> class PriorityQueue { public: PriorityQueue() = delete; PriorityQueue(const ConicalViewFrustums& views) : _views(views) { } PriorityQueue(const ConicalViewFrustums& views, float angularWeight, float centerWeight, float ageWeight) : _views(views), _angularWeight(angularWeight), _centerWeight(centerWeight), _ageWeight(ageWeight) { } void setViews(const ConicalViewFrustums& views) { _views = views; } void setWeights(float angularWeight, float centerWeight, float ageWeight) { _angularWeight = angularWeight; _centerWeight = centerWeight; _ageWeight = ageWeight; } size_t size() const { return _queue.size(); } void push(T thing) { thing.setPriority(computePriority(thing)); _queue.push(thing); } const T& top() const { return _queue.top(); } void pop() { return _queue.pop(); } bool empty() const { return _queue.empty(); } private: float computePriority(const T& thing) const { float priority = std::numeric_limits<float>::min(); for (const auto& view : _views) { priority = std::max(priority, computePriority(view, thing)); } return priority; } float computePriority(const ConicalViewFrustum& view, const T& thing) const { // priority = weighted linear combination of multiple values: // (a) angular size // (b) proximity to center of view // (c) time since last update // where the relative "weights" are tuned to scale the contributing values into units of "priority". glm::vec3 position = thing.getPosition(); glm::vec3 offset = position - view.getPosition(); float distance = glm::length(offset) + 0.001f; // add 1mm to avoid divide by zero const float MIN_RADIUS = 0.1f; // WORKAROUND for zero size objects (we still want them to sort by distance) float radius = glm::min(thing.getRadius(), MIN_RADIUS); float cosineAngle = (glm::dot(offset, view.getDirection()) / distance); float age = (float)(usecTimestampNow() - thing.getTimestamp()); // we modulatate "age" drift rate by the cosineAngle term to make periphrial objects sort forward // at a reduced rate but we don't want the "age" term to go zero or negative so we clamp it const float MIN_COSINE_ANGLE_FACTOR = 0.1f; float cosineAngleFactor = glm::max(cosineAngle, MIN_COSINE_ANGLE_FACTOR); float priority = _angularWeight * glm::max(radius, MIN_RADIUS) / distance + _centerWeight * cosineAngle + _ageWeight * cosineAngleFactor * age; // decrement priority of things outside keyhole if (distance - radius > view.getRadius()) { if (!view.intersects(offset, distance, radius)) { constexpr float OUT_OF_VIEW_PENALTY = -10.0f; priority += OUT_OF_VIEW_PENALTY; } } return priority; } ConicalViewFrustums _views; std::priority_queue<T> _queue; float _angularWeight { DEFAULT_ANGULAR_COEF }; float _centerWeight { DEFAULT_CENTER_COEF }; float _ageWeight { DEFAULT_AGE_COEF }; }; } // namespace PrioritySortUtil // for now we're keeping hard-coded sorted time budgets in one spot const uint64_t MAX_UPDATE_RENDERABLES_TIME_BUDGET = 2000; // usec const uint64_t MIN_SORTED_UPDATE_RENDERABLES_TIME_BUDGET = 1000; // usec #endif // hifi_PrioritySortUtil_h
40.065089
119
0.647467
[ "3d" ]
34f5c6d655d90fbdb4e0c981d64abc15d164fd90
4,522
c
C
lib/glut/include/GL/c/vectormath.c
nbassagoda/3d-game-snake
7ead8d8bb7f2b8d745073b9f08c66bd00ca8b87a
[ "MIT" ]
null
null
null
lib/glut/include/GL/c/vectormath.c
nbassagoda/3d-game-snake
7ead8d8bb7f2b8d745073b9f08c66bd00ca8b87a
[ "MIT" ]
null
null
null
lib/glut/include/GL/c/vectormath.c
nbassagoda/3d-game-snake
7ead8d8bb7f2b8d745073b9f08c66bd00ca8b87a
[ "MIT" ]
1
2019-09-13T16:53:29.000Z
2019-09-13T16:53:29.000Z
// Vector Math Functions // OpenGL SuperBible gltools library // Richard S. Wright Jr. // One note of interest. These REALLY should be inlined. I'm sorry I was too stupid at the time // to figure out how to get inlining to work on all the platforms and different compilers I use. // this seemed simpler than a ton of #ifdef's all over the place. Watch the web site as I may // make frequent improvments to the library. #include "gltools.h" #include <math.h> // Adds two vectors together void gltAddVectors(const GLTVector3 vFirst, const GLTVector3 vSecond, GLTVector3 vResult) { vResult[0] = vFirst[0] + vSecond[0]; vResult[1] = vFirst[1] + vSecond[1]; vResult[2] = vFirst[2] + vSecond[2]; } // Subtract one vector from another void gltSubtractVectors(const GLTVector3 vFirst, const GLTVector3 vSecond, GLTVector3 vResult) { vResult[0] = vFirst[0] - vSecond[0]; vResult[1] = vFirst[1] - vSecond[1]; vResult[2] = vFirst[2] - vSecond[2]; } // Scales a vector by a scalar void gltScaleVector(GLTVector3 vVector, const GLfloat fScale) { vVector[0] *= fScale; vVector[1] *= fScale; vVector[2] *= fScale; } // Gets the length of a vector squared GLfloat gltGetVectorLengthSqrd(const GLTVector3 vVector) { return (vVector[0]*vVector[0]) + (vVector[1]*vVector[1]) + (vVector[2]*vVector[2]); } // Gets the length of a vector GLfloat gltGetVectorLength(const GLTVector3 vVector) { return (GLfloat)sqrt(gltGetVectorLengthSqrd(vVector)); } // Scales a vector by it's length - creates a unit vector void gltNormalizeVector(GLTVector3 vNormal) { GLfloat fLength = 1.0f / gltGetVectorLength(vNormal); gltScaleVector(vNormal, fLength); } // Copies a vector void gltCopyVector(const GLTVector3 vSource, GLTVector3 vDest) { memcpy(vDest, vSource, sizeof(GLTVector3)); } // Get the dot product between two vectors GLfloat gltVectorDotProduct(const GLTVector3 vU, const GLTVector3 vV) { return vU[0]*vV[0] + vU[1]*vV[1] + vU[2]*vV[2]; } // Calculate the cross product of two vectors void gltVectorCrossProduct(const GLTVector3 vU, const GLTVector3 vV, GLTVector3 vResult) { vResult[0] = vU[1]*vV[2] - vV[1]*vU[2]; vResult[1] = -vU[0]*vV[2] + vV[0]*vU[2]; vResult[2] = vU[0]*vV[1] - vV[0]*vU[1]; } // Given three points on a plane in counter clockwise order, calculate the unit normal void gltGetNormalVector(const GLTVector3 vP1, const GLTVector3 vP2, const GLTVector3 vP3, GLTVector3 vNormal) { GLTVector3 vV1, vV2; gltSubtractVectors(vP2, vP1, vV1); gltSubtractVectors(vP3, vP1, vV2); gltVectorCrossProduct(vV1, vV2, vNormal); gltNormalizeVector(vNormal); } // Transform a point by a 4x4 matrix void gltTransformPoint(const GLTVector3 vSrcVector, const GLTMatrix mMatrix, GLTVector3 vOut) { vOut[0] = mMatrix[0] * vSrcVector[0] + mMatrix[4] * vSrcVector[1] + mMatrix[8] * vSrcVector[2] + mMatrix[12]; vOut[1] = mMatrix[1] * vSrcVector[0] + mMatrix[5] * vSrcVector[1] + mMatrix[9] * vSrcVector[2] + mMatrix[13]; vOut[2] = mMatrix[2] * vSrcVector[0] + mMatrix[6] * vSrcVector[1] + mMatrix[10] * vSrcVector[2] + mMatrix[14]; } // Rotates a vector using a 4x4 matrix. Translation column is ignored void gltRotateVector(const GLTVector3 vSrcVector, const GLTMatrix mMatrix, GLTVector3 vOut) { vOut[0] = mMatrix[0] * vSrcVector[0] + mMatrix[4] * vSrcVector[1] + mMatrix[8] * vSrcVector[2]; vOut[1] = mMatrix[1] * vSrcVector[0] + mMatrix[5] * vSrcVector[1] + mMatrix[9] * vSrcVector[2]; vOut[2] = mMatrix[2] * vSrcVector[0] + mMatrix[6] * vSrcVector[1] + mMatrix[10] * vSrcVector[2]; } // Gets the three coefficients of a plane equation given three points on the plane. void gltGetPlaneEquation(GLTVector3 vPoint1, GLTVector3 vPoint2, GLTVector3 vPoint3, GLTVector3 vPlane) { // Get normal vector from three points. The normal vector is the first three coefficients // to the plane equation... gltGetNormalVector(vPoint1, vPoint2, vPoint3, vPlane); // Final coefficient found by back substitution vPlane[3] = -(vPlane[0] * vPoint3[0] + vPlane[1] * vPoint3[1] + vPlane[2] * vPoint3[2]); } // Determine the distance of a point from a plane, given the point and the // equation of the plane. GLfloat gltDistanceToPlane(GLTVector3 vPoint, GLTVector4 vPlane) { return vPoint[0]*vPlane[0] + vPoint[1]*vPlane[1] + vPoint[2]*vPlane[2] + vPlane[3]; }
37.065574
118
0.685537
[ "vector", "transform" ]
550ecf05d483367c77209237f96b0c2b3b8db000
366
h
C
Refureku/Generator/Submodules/Kodgen/Include/Properties/PropertyGroup.h
CrackerCat/Refureku
5b8047c023788dc42be6f8ce0c98edb76f5570ed
[ "MIT" ]
1
2020-07-21T06:37:54.000Z
2020-07-21T06:37:54.000Z
Refureku/Generator/Submodules/Kodgen/Include/Properties/PropertyGroup.h
lineCode/Refureku
5b8047c023788dc42be6f8ce0c98edb76f5570ed
[ "MIT" ]
null
null
null
Refureku/Generator/Submodules/Kodgen/Include/Properties/PropertyGroup.h
lineCode/Refureku
5b8047c023788dc42be6f8ce0c98edb76f5570ed
[ "MIT" ]
1
2020-06-28T20:37:40.000Z
2020-06-28T20:37:40.000Z
#pragma once #include <vector> #include <iostream> #include "Properties/SimpleProperty.h" #include "Properties/ComplexProperty.h" namespace kodgen { struct PropertyGroup { std::vector<SimpleProperty> simpleProperties; std::vector<ComplexProperty> complexProperties; }; std::ostream& operator<<(std::ostream& out_stream, PropertyGroup const&) noexcept; }
20.333333
83
0.76776
[ "vector" ]
5513687f8930f29f11f902f168e30be175f848d8
912
h
C
GameEngine/PathFollowing.h
BenMarshall98/Game-Engine-Uni
cb2e0a75953db0960e3d58a054eb9a6e213ae12a
[ "MIT" ]
null
null
null
GameEngine/PathFollowing.h
BenMarshall98/Game-Engine-Uni
cb2e0a75953db0960e3d58a054eb9a6e213ae12a
[ "MIT" ]
null
null
null
GameEngine/PathFollowing.h
BenMarshall98/Game-Engine-Uni
cb2e0a75953db0960e3d58a054eb9a6e213ae12a
[ "MIT" ]
null
null
null
#pragma once #define GLM_ENABLE_EXPERIMENTAL #include <vector> #include "glm/glm.hpp" #include "glm/gtx/quaternion.hpp" #include "ComponentPhysics.h" struct PathNode { PathNode() : radius(0) {} glm::vec3 position; float radius; }; class PathFollowing { private: std::vector<PathNode *> * pathNodes; int currentNode; bool onPath; public: explicit PathFollowing(std::vector<PathNode *> * const pPathNodes) : pathNodes(pPathNodes), currentNode(-1), onPath(true) {} ~PathFollowing(); PathFollowing& operator=(const PathFollowing&) = delete; PathFollowing(PathFollowing&) = delete; void CalculatePath(const glm::vec3 & currentPosition, const glm::quat & currentDirection, ComponentPhysics * const physicsComponent); //Moves entity off of path inline void MoveOffPath() { onPath = false; } bool OnPath(const glm::vec3 & position); glm::vec3 GetNearestPath(const glm::vec3 & position); };
20.727273
134
0.734649
[ "vector" ]
55136fb3e9619b5047f546bd38a8f93a03efe04c
973
c
C
src/lib/dev/cap/capsset.c
prepare/spice3f5
a0d8c69d43927b7ced9cb619e3faa3d56332566a
[ "BSD-4-Clause-UC" ]
4
2018-02-21T17:31:40.000Z
2022-03-03T01:43:32.000Z
src/lib/dev/cap/capsset.c
prepare/spice3f5
a0d8c69d43927b7ced9cb619e3faa3d56332566a
[ "BSD-4-Clause-UC" ]
null
null
null
src/lib/dev/cap/capsset.c
prepare/spice3f5
a0d8c69d43927b7ced9cb619e3faa3d56332566a
[ "BSD-4-Clause-UC" ]
2
2019-07-20T00:47:29.000Z
2020-01-06T19:18:21.000Z
/********** Copyright 1990 Regents of the University of California. All rights reserved. Author: 1985 Thomas L. Quarles **********/ /* */ /* loop through all the devices and * allocate parameter #s to design parameters */ #include "spice.h" #include <stdio.h> #include "util.h" #include "cktdefs.h" #include "capdefs.h" #include "trandefs.h" #include "sperror.h" #include "suffix.h" int CAPsSetup(info,inModel) register SENstruct *info; GENmodel *inModel; { register CAPmodel *model = (CAPmodel*)inModel; register CAPinstance *here; /* loop through all the capacitor models */ for( ; model != NULL; model = model->CAPnextModel ) { /* loop through all the instances of the model */ for (here = model->CAPinstances; here != NULL ; here=here->CAPnextInstance) { if(here->CAPsenParmNo){ here->CAPsenParmNo = ++(info->SENparms); } } } return(OK); }
20.702128
77
0.609455
[ "model" ]
55215d83dad7cb9d2017f1dfdf24a6bfdf360933
21,749
h
C
FINN/backend/fpga/hls/matrix_vector.h
HyunwooKim2/FINN
fac4ff40aaba1c14aa416738e3d22802649a94f8
[ "BSD-3-Clause" ]
null
null
null
FINN/backend/fpga/hls/matrix_vector.h
HyunwooKim2/FINN
fac4ff40aaba1c14aa416738e3d22802649a94f8
[ "BSD-3-Clause" ]
null
null
null
FINN/backend/fpga/hls/matrix_vector.h
HyunwooKim2/FINN
fac4ff40aaba1c14aa416738e3d22802649a94f8
[ "BSD-3-Clause" ]
1
2021-03-18T01:43:29.000Z
2021-03-18T01:43:29.000Z
#pragma once template<unsigned int SIMDWidth, // number of SIMD lanes per PE unsigned int PECount, // number of PEs unsigned int WeightsPrecision, // Number of bits in thresholds unsigned int ThresholdPrecision, // Number of bits in thresholds unsigned int MatrixW, // width of matrix, multiple of SIMDWidth unsigned int MatrixH, // height of matrix, multiple of PECount unsigned int WMemCount, // entries in weight memory unsigned int TMemCount, // entries in threshold memory unsigned int Precision, // Input data bitwidth unsigned int ActivationPrecision, // Precisions for the activation (Output precision) unsigned int MacPrecision, // Precision of MAC registers unsigned int ActivationType = 0, // Don't use activation template<int> class type_input = ap_uint // For first layer use int value > void MatrixVector_Precision_Batch(stream<ap_uint<SIMDWidth * Precision> > & in, stream<ap_uint<PECount * ActivationPrecision> > & out, const ap_uint<SIMDWidth * WeightsPrecision> weightMem[PECount][WMemCount], const ap_uint<ThresholdPrecision> thresMem[PECount][TMemCount], const unsigned int numReps) { CASSERT_DATAFLOW(MatrixW % SIMDWidth == 0); CASSERT_DATAFLOW(MatrixH % PECount == 0); // how many different rows each neuron will compute // alternatively: number of vertical matrix chunks const unsigned int neuronFold = MatrixH / PECount; // how many synapse groups each row is split into // alternatively: number of horizontal matrix chunks const unsigned int synapseFold = MatrixW / SIMDWidth; // input vector buffer ap_uint<Precision * SIMDWidth> inputBuf[synapseFold]; // PE accumulator registers, initialized to zero on first call to function // why not defined as static? then different calls to StreamingMatrixVector // with the same template parameters would share these accumulator registers ap_int<MacPrecision> macRegisters[PECount]; #pragma HLS ARRAY_PARTITION variable=macRegisters complete dim=1 for(unsigned int i = 0; i < PECount; i++) { #pragma HLS UNROLL macRegisters[i] = 0; } unsigned int nm = 0; unsigned int sf = 0; const unsigned int totalFold = neuronFold * synapseFold; for (unsigned int i = 0; i < totalFold * numReps; i++) { #pragma HLS PIPELINE II=1 ap_uint<SIMDWidth * Precision> inElem; if (nm == 0) { // read input from stream inElem = in.read(); // buffer for reuse inputBuf[sf] = inElem; } else { // reuse buffered input inElem = inputBuf[sf]; } // compute matrix-vector product for each processing element for (unsigned int pe = 0; pe < PECount; pe++) { #pragma HLS UNROLL ap_int<WeightsPrecision * SIMDWidth> memWeight = weightMem[pe][nm * synapseFold + sf]; ap_int<MacPrecision> tmpMac = macRegisters[pe]; for(unsigned int simd = 0; simd < SIMDWidth; simd++){ #pragma HLS UNROLL // Fetch weights // ap_int<WeightsPrecision * SIMDWidth> weightArray = weightMem[pe][nm * synapseFold + sf]; ap_int<WeightsPrecision * SIMDWidth> weightArray = memWeight; // Low and high bit for each input channel unsigned int lowBit = simd * Precision; unsigned int highBit = (simd+1) * Precision - 1; // Low and high bit for weight channel unsigned int lowBitWeight = simd * WeightsPrecision; unsigned int highBitWeight = (simd+1) * WeightsPrecision - 1; // Get weight for the channel type_input<Precision> dataUnsigned = inElem(highBit, lowBit); ap_uint<WeightsPrecision> weightUnsigned = weightArray(highBitWeight, lowBitWeight); // Convert to signed data type // ap_int<Precision> data = dataUnsigned(Precision-1, 0); ap_int<WeightsPrecision> weightCompressed = weightUnsigned(WeightsPrecision-1, 0); ap_int<WeightsPrecision + 1> weightExtended = weightCompressed; ap_int<WeightsPrecision + 1> weight = 2 * weightExtended + 1; // MAC Operation ap_int<MacPrecision> tmpMul = dataUnsigned * weight; #pragma HLS RESOURCE variable=tmpMul core=Mul_LUT //Implement in LUTs tmpMac += tmpMul; } macRegisters[pe] = tmpMac; } sf++; if(sf == synapseFold) { ap_uint<PECount * ActivationPrecision> outElem = 0; for (unsigned int pe = 0; pe < PECount; pe++) { #pragma HLS UNROLL ap_uint<ActivationPrecision> outputPe; if(ActivationType == BINARY_THRESHOLDS){ // Thresholding Operation ap_int<ThresholdPrecision> thresholdPe; thresholdPe(ThresholdPrecision - 1, 0) = thresMem[pe][nm](ThresholdPrecision - 1, 0); outputPe = Binary_Threshold<ActivationPrecision, MacPrecision, ThresholdPrecision>(macRegisters[pe], thresholdPe); } else if(ActivationType == NO_THRESHOLDS){ // Output MAC register, no threshold outputPe(ActivationPrecision-1, 0) = macRegisters[pe](ActivationPrecision-1, 0); } else if(ActivationType == FULL_THRESHOLDS){ // TODO: Reducing precision check is used onl because the compiler tries to compile // this code even when ActivationType!=FULL_THRESHOLDS. // Need to find a way to remove this and set NumberOfThresholds = 1 << ActivationPrecision constexpr unsigned int reducingPrecision = Precision >= ActivationPrecision; constexpr unsigned int NumberOfThresholds = reducingPrecision ? (1 << ActivationPrecision) : 2; ap_int<ThresholdPrecision> thresholdPe; thresholdPe(ThresholdPrecision - 1, 0) = thresMem[pe][nm](ThresholdPrecision - 1, 0); outputPe = ReducedPrecision_Threshold<ActivationPrecision, MacPrecision, ThresholdPrecision/NumberOfThresholds, NumberOfThresholds-1>(macRegisters[pe], thresholdPe); } // Assign to right bits of output buffers unsigned int lowBit = pe * ActivationPrecision; unsigned int highBit = (pe+1) * ActivationPrecision - 1; outElem(highBit, lowBit) = outputPe(ActivationPrecision-1, 0); macRegisters[pe] = 0; // clear the accumulator } out.write(outElem); sf = 0; nm++; } if (nm == neuronFold) { // next image nm = 0; } } } template<unsigned int SIMDWidth, // number of SIMD lanes per PE unsigned int PECount, // number of PEs unsigned int WeightsPrecision, // Number of bits in thresholds unsigned int MatrixW, // width of matrix, multiple of SIMDWidth unsigned int MatrixH, // height of matrix, multiple of PECount unsigned int WMemCount, // entries in weight memory unsigned int Precision, // Input data bitwidth unsigned int ActivationPrecision, // Precisions for the activation (Output precision) unsigned int MacPrecision, // Precision of MAC registers unsigned int ActivationType = 0, // Don't use activation template<int> class type_input = ap_uint // For first layer use int value > void MatrixVector_Precision_NoActivation_Batch(stream<ap_uint<SIMDWidth * Precision> > & in, stream<ap_uint<PECount * ActivationPrecision> > & out, const ap_uint<SIMDWidth * WeightsPrecision> weightMem[PECount][WMemCount], const unsigned int numReps) { CASSERT_DATAFLOW(MatrixW % SIMDWidth == 0); CASSERT_DATAFLOW(MatrixH % PECount == 0); // how many different rows each neuron will compute // alternatively: number of vertical matrix chunks const unsigned int neuronFold = MatrixH / PECount; // how many synapse groups each row is split into // alternatively: number of horizontal matrix chunks const unsigned int synapseFold = MatrixW / SIMDWidth; // input vector buffer ap_uint<Precision * SIMDWidth> inputBuf[synapseFold]; // PE accumulator registers, initialized to zero on first call to function // why not defined as static? then different calls to StreamingMatrixVector // with the same template parameters would share these accumulator registers ap_int<MacPrecision> macRegisters[PECount]; #pragma HLS ARRAY_PARTITION variable=macRegisters complete dim=1 for(unsigned int i = 0; i < PECount; i++) { #pragma HLS UNROLL macRegisters[i] = 0; } unsigned int nm = 0; unsigned int sf = 0; const unsigned int totalFold = neuronFold * synapseFold; for (unsigned int i = 0; i < totalFold * numReps; i++) { #pragma HLS PIPELINE II=1 ap_uint<SIMDWidth * Precision> inElem; if (nm == 0) { // read input from stream inElem = in.read(); // buffer for reuse inputBuf[sf] = inElem; } else { // reuse buffered input inElem = inputBuf[sf]; } // compute matrix-vector product for each processing element for (unsigned int pe = 0; pe < PECount; pe++) { #pragma HLS UNROLL ap_int<WeightsPrecision * SIMDWidth> memWeight = weightMem[pe][nm * synapseFold + sf]; ap_int<MacPrecision> tmpMac = macRegisters[pe]; for(unsigned int simd = 0; simd < SIMDWidth; simd++){ #pragma HLS UNROLL // Fetch weights // ap_int<WeightsPrecision * SIMDWidth> weightArray = weightMem[pe][nm * synapseFold + sf]; ap_int<WeightsPrecision * SIMDWidth> weightArray = memWeight; // Low and high bit for each input channel unsigned int lowBit = simd * Precision; unsigned int highBit = (simd+1) * Precision - 1; // Low and high bit for weight channel unsigned int lowBitWeight = simd * WeightsPrecision; unsigned int highBitWeight = (simd+1) * WeightsPrecision - 1; // Get weight for the channel type_input<Precision> dataUnsigned = inElem(highBit, lowBit); ap_uint<WeightsPrecision> weightUnsigned = weightArray(highBitWeight, lowBitWeight); // Convert to signed data type // ap_int<Precision> data = dataUnsigned(Precision-1, 0); ap_int<WeightsPrecision> weightCompressed = weightUnsigned(WeightsPrecision-1, 0); ap_int<WeightsPrecision + 1> weightExtended = weightCompressed; ap_int<WeightsPrecision + 1> weight = 2 * weightExtended + 1; // MAC Operation ap_int<MacPrecision> tmpMul = dataUnsigned * weight; #pragma HLS RESOURCE variable=tmpMul core=Mul_LUT //Implement in LUTs tmpMac += tmpMul; } macRegisters[pe] = tmpMac; } sf++; if(sf == synapseFold) { ap_uint<PECount * ActivationPrecision> outElem = 0; for (unsigned int pe = 0; pe < PECount; pe++) { #pragma HLS UNROLL ap_uint<ActivationPrecision> outputPe; // Output MAC register, no threshold outputPe(ActivationPrecision-1, 0) = macRegisters[pe](ActivationPrecision-1, 0); // Assign to right bits of output buffers unsigned int lowBit = pe * ActivationPrecision; unsigned int highBit = (pe+1) * ActivationPrecision - 1; outElem(highBit, lowBit) = outputPe(ActivationPrecision-1, 0); macRegisters[pe] = 0; // clear the accumulator } out.write(outElem); sf = 0; nm++; } if (nm == neuronFold) { // next image nm = 0; } } } // popcount implemented as unsigned 1-bit add // HLS automatically balances this into an adder tree template<unsigned int SIMDWidth, unsigned int PopCountWidth> ap_uint<PopCountWidth> NaivePopCount(ap_uint<SIMDWidth> in) { ap_uint<PopCountWidth> pct = 0; for (unsigned int i = 0; i < SIMDWidth; i++) { pct += in(i, i); } return pct; } // streaming matrix-vector multiply component with binarized activation: // binarized inputs, binarized weights, binarized outputs template<unsigned int SIMDWidth, // number of SIMD lanes per PE unsigned int PECount, // number of PEs unsigned int PopCountWidth, // number of bits in popcount accumulator (>=log2(fanin)) unsigned int MatrixW, // width of matrix, multiple of SIMDWidth unsigned int MatrixH, // height of matrix, multiple of PECount unsigned int WMemCount, // entries in weight memory unsigned int TMemCount // entries in threshold memory > void MatrixVector_BNN_Batch(stream<ap_uint<SIMDWidth> > & in, stream<ap_uint<PECount> > & out, const ap_uint<SIMDWidth> weightMem[PECount][WMemCount], const ap_uint<PopCountWidth> thresMem[PECount][TMemCount], const unsigned int numReps) { // how many different rows each neuron will compute // alternatively: number of vertical matrix chunks const unsigned int neuronFold = MatrixH / PECount; // how many synapse groups each row is split into // alternatively: number of horizontal matrix chunks const unsigned int synapseFold = MatrixW / SIMDWidth; // input vector buffer ap_uint<SIMDWidth> inputBuf[synapseFold]; // PE accumulator registers, initialized to zero on first call to function // why not defined as static? then different calls to StreamingMatrixVector // with the same template parameters would share these accumulator registers ap_uint<PopCountWidth> accPopCount[PECount]; for (unsigned int i = 0; i < PECount; i++) { #pragma HLS UNROLL accPopCount[i] = 0; } #pragma HLS ARRAY_PARTITION variable=accPopCount complete dim=1 unsigned int nf = 0; unsigned int sf = 0; const unsigned int totalFold = neuronFold * synapseFold; // everything merged into a common iteration space (one "big" loop instead // of smaller nested loops) to get the pipelinening the way we want for (unsigned int i = 0; i < totalFold * numReps; i++) { #pragma HLS PIPELINE II=1 ap_uint<SIMDWidth> inElem; if (nf == 0) { // read input from stream inElem = in.read(); // buffer for reuse inputBuf[sf] = inElem; } else { // reuse buffered input inElem = inputBuf[sf]; } // compute matrix-vector product for each processing element for (unsigned int pe = 0; pe < PECount; pe++) { #pragma HLS UNROLL ap_uint<SIMDWidth> weight = weightMem[pe][nf * synapseFold + sf]; ap_uint<SIMDWidth> masked = ~(weight ^ inElem); accPopCount[pe] += NaivePopCount<SIMDWidth, PopCountWidth>(masked); } // keep track of which folded synapse/neuron we are processing sf++; if (sf == synapseFold) { // produce output and clear accumulators ap_uint<PECount> outElem = 0; for (unsigned int pe = 0; pe < PECount; pe++) { #pragma HLS UNROLL outElem(pe, pe) = accPopCount[pe] > thresMem[pe][nf] ? 1 : 0; accPopCount[pe] = 0; // clear the accumulator } out.write(outElem); // next folded neuron sf = 0; nf++; } if (nf == neuronFold) { // next image nf = 0; } } } // TODO should be possible to integrate this into the baseline MVTU using a // template parameter // streaming matrix-vector multiply component with no activation: // binarized inputs, binarized weights, PopCountWidth-bit outputs template<unsigned int SIMDWidth, // number of SIMD lanes per PE unsigned int PECount, // number of PEs unsigned int PopCountWidth, // number of bits in popcount accumulator (>=log2(fanin)) unsigned int MatrixW, // width of matrix, multiple of SIMDWidth unsigned int MatrixH, // height of matrix, multiple of PECount unsigned int WMemCount // entries in weight memory > void MatrixVector_BNN_NoActivation_Batch(stream<ap_uint<SIMDWidth> > & in, stream<ap_uint<PECount * PopCountWidth> > & out, const ap_uint<SIMDWidth> weightMem[PECount][WMemCount], const unsigned int numReps) { // how many different rows each neuron will compute // alternatively: number of vertical matrix chunks const unsigned int neuronFold = MatrixH / PECount; // how many synapse groups each row is split into // alternatively: number of horizontal matrix chunks const unsigned int synapseFold = MatrixW / SIMDWidth; // input vector buffer ap_uint<SIMDWidth> inputBuf[synapseFold]; // PE accumulator registers, initialized to zero on first call to function // why not defined as static? then different calls to StreamingMatrixVector // with the same template parameters would share these accumulator registers ap_uint<PopCountWidth> accPopCount[PECount]; for (unsigned int i = 0; i < PECount; i++) { #pragma HLS UNROLL accPopCount[i] = 0; } #pragma HLS ARRAY_PARTITION variable=accPopCount complete dim=1 unsigned int nf = 0; unsigned int sf = 0; const unsigned int totalFold = neuronFold * synapseFold; // everything merged into a common iteration space (one "big" loop instead // of smaller nested loops) to get the pipelinening the way we want for (unsigned int i = 0; i < totalFold * numReps; i++) { #pragma HLS PIPELINE II=1 ap_uint<SIMDWidth> inElem; if (nf == 0) { // read input from stream inElem = in.read(); // buffer for reuse inputBuf[sf] = inElem; } else { // reuse buffered input inElem = inputBuf[sf]; } // compute matrix-vector product for each processing element for (unsigned int pe = 0; pe < PECount; pe++) { #pragma HLS UNROLL ap_uint<SIMDWidth> weight = weightMem[pe][nf * synapseFold + sf]; ap_uint<SIMDWidth> masked = ~(weight ^ inElem); accPopCount[pe] += NaivePopCount<SIMDWidth, PopCountWidth>(masked); } // keep track of which folded synapse/neuron we are processing sf++; if (sf == synapseFold) { // produce output and clear accumulators ap_uint<PECount * PopCountWidth> outElem = 0; for (unsigned int pe = 0; pe < PECount; pe++) { #pragma HLS UNROLL outElem((pe + 1) * PopCountWidth - 1, pe * PopCountWidth) = accPopCount[pe]; accPopCount[pe] = 0; // clear the accumulator } out.write(outElem); // next folded neuron sf = 0; nf++; } if (nf == neuronFold) { // next image nf = 0; } } } // streaming matrix-vector multiply component with binarized activation: // fixed-point inputs, binarized weights, binarized outputs template<unsigned int InpWidth, // number of bits to use as the inputs. unsigned int InpIntWidth, // number of integer bits to use in the input. unsigned int SIMDWidth, // number of SIMD lanes per PE unsigned int PECount, // number of PEs unsigned int AccWidth, // number of bits in the accumulator unsigned int AccIntWidth, // number of integer bits to use in the accumulator. unsigned int MatrixW, // width of matrix, multiple of SIMDWidth unsigned int MatrixH, // height of matrix, multiple of PECount unsigned int WMemCount, // entries in weight memory unsigned int TMemCount // entries in threshold memory > void MatrixVector_Fxd_Batch(stream<ap_uint<SIMDWidth * InpWidth> > & in, stream<ap_uint<PECount> > & out, const ap_uint<SIMDWidth> weightMem[PECount][WMemCount], const ap_fixed<AccWidth, AccIntWidth> thresMem[PECount][TMemCount], const unsigned int numReps) { CASSERT_DATAFLOW(MatrixW % SIMDWidth == 0);CASSERT_DATAFLOW( MatrixH % PECount == 0); // how many different rows each neuron will compute // alternatively: number of vertical matrix chunks const unsigned int neuronFold = MatrixH / PECount; // how many synapse groups each row is split into // alternatively: number of horizontal matrix chunks const unsigned int synapseFold = MatrixW / SIMDWidth; // input vector buffer ap_uint<SIMDWidth * InpWidth> inputBuf[synapseFold]; // PE accumulator registers, initialized to zero on first call to function // why not defined as static? then different calls to StreamingMatrixVector // with the same template parameters would share these accumulator registers ap_fixed<AccWidth, AccIntWidth, AP_TRN, AP_SAT> accReg[PECount]; ap_fixed<AccWidth, AccIntWidth, AP_TRN, AP_SAT> intReg[PECount]; for (unsigned int i = 0; i < PECount; i++) { #pragma HLS UNROLL accReg[i] = 0; } #pragma HLS ARRAY_PARTITION variable=accReg complete dim=1 #pragma HLS ARRAY_PARTITION variable=intReg complete dim=1 unsigned int nf = 0; unsigned int sf = 0; const unsigned int totalFold = neuronFold * synapseFold; // everything merged into a common iteration space (one "big" loop instead // of smaller nested loops) to get the pipelinening the way we want for (unsigned int i = 0; i < totalFold * numReps; i++) { #pragma HLS PIPELINE II=1 ap_uint<SIMDWidth * InpWidth> inElem; if (nf == 0) { // read input from stream inElem = in.read(); // buffer for reuse inputBuf[sf] = inElem; } else { // reuse buffered input inElem = inputBuf[sf]; } // compute matrix-vector product for each processing element for (unsigned int pe = 0; pe < PECount; pe++) { #pragma HLS UNROLL ap_uint<SIMDWidth> weight = weightMem[pe][nf * synapseFold + sf]; //ap_uint<SIMDWidth> masked = ~(weight ^ inElem); //accPopCount[pe] += NaivePopCount<SIMDWidth, PopCountWidth>( // masked); //ap_fixed<InpWidth,InpIntWidth,AP_TRN,AP_SAT> * inVec = reinterpret_cast<ap_fixed<InpWidth,InpIntWidth,AP_TRN,AP_SAT> *>(&inElem); intReg[pe] = 0; for (unsigned int s = 0; s < SIMDWidth; s++) { #pragma HLS UNROLL ap_uint<InpWidth> tmp = inElem.range((s + 1) * InpWidth - 1, s * InpWidth); ap_fixed<InpWidth, InpIntWidth, AP_TRN, AP_SAT> val = *reinterpret_cast<ap_fixed<InpWidth, InpIntWidth, AP_TRN, AP_SAT> *>(&tmp); ap_int<2> w = (weight.range(s, s)) ? 1 : -1; intReg[pe] += w * val; //if (weight.range(s,s)) accReg[pe] += val; // This is slower than the two lines above. //else accReg[pe] -= val; } accReg[pe] += intReg[pe]; } // keep track of which folded synapse/neuron we are processing sf++; if (sf == synapseFold) { // produce output and clear accumulators ap_uint<PECount> outElem = 0; for (unsigned int pe = 0; pe < PECount; pe++) { #pragma HLS UNROLL outElem(pe, pe) = accReg[pe] > thresMem[pe][nf] ? 1 : 0; accReg[pe] = 0; // clear the accumulator } out.write(outElem); // next folded neuron sf = 0; nf++; } if (nf == neuronFold) { // next image nf = 0; } } }
39.046679
171
0.693549
[ "vector" ]
552471fa9b33e6616dfca38d6d05007f0fca413e
317,113
c
C
corpora/train/cmix.c
jman294/ans-compression
a817f5489a71adad427d39a980f7483934e68a3f
[ "MIT" ]
1
2018-12-15T01:33:37.000Z
2018-12-15T01:33:37.000Z
corpora/train/cmix.c
jman294/ans-compression
a817f5489a71adad427d39a980f7483934e68a3f
[ "MIT" ]
null
null
null
corpora/train/cmix.c
jman294/ans-compression
a817f5489a71adad427d39a980f7483934e68a3f
[ "MIT" ]
null
null
null
// `levenshtein.c` - levenshtein // MIT licensed. // Copyright (c) 2015 Titus Wormer <tituswormer@gmail.com> #include <string.h> #include <stdlib.h> #include <stdint.h> // Returns a size_t, depicting the difference between `a` and `b`. // See <http://en.wikipedia.org/wiki/Levenshtein_distance> for more information. size_t levenshtein_n(const char *a, const size_t length, const char *b, const size_t bLength) { size_t *cache = calloc(length, sizeof(size_t)); size_t index = 0; size_t bIndex = 0; size_t distance; size_t bDistance; size_t result; char code; // Shortcut optimizations / degenerate cases. if (a == b) { return 0; } if (length == 0) { return bLength; } if (bLength == 0) { return length; } // initialize the vector. while (index < length) { cache[index] = index + 1; index++; } // Loop. while (bIndex < bLength) { code = b[bIndex]; result = distance = bIndex++; index = SIZE_MAX; while (++index < length) { bDistance = code == a[index] ? distance : distance + 1; distance = cache[index]; cache[index] = result = distance > result ? bDistance > result ? result + 1 : bDistance : bDistance > distance ? distance + 1 : bDistance; } } free(cache); return result; } size_t levenshtein(const char *a, const char *b) { const size_t length = strlen(a); const size_t bLength = strlen(b); return levenshtein_n(a, length, b, bLength); } // SPDX-License-Identifier: GPL-3.0-or-later #include "libnetdata.h" #ifdef __APPLE__ #define INHERIT_NONE 0 #endif /* __APPLE__ */ #if defined(__FreeBSD__) || defined(__APPLE__) # define O_NOATIME 0 # define MADV_DONTFORK INHERIT_NONE #endif /* __FreeBSD__ || __APPLE__*/ struct rlimit rlimit_nofile = { .rlim_cur = 1024, .rlim_max = 1024 }; int enable_ksm = 1; volatile sig_atomic_t netdata_exit = 0; const char *os_type = NETDATA_OS_TYPE; const char *program_version = VERSION; // ---------------------------------------------------------------------------- // memory allocation functions that handle failures // although netdata does not use memory allocations too often (netdata tries to // maintain its memory footprint stable during runtime, i.e. all buffers are // allocated during initialization and are adapted to current use throughout // its lifetime), these can be used to override the default system allocation // routines. #ifdef NETDATA_LOG_ALLOCATIONS static __thread struct memory_statistics { volatile ssize_t malloc_calls_made; volatile ssize_t calloc_calls_made; volatile ssize_t realloc_calls_made; volatile ssize_t strdup_calls_made; volatile ssize_t free_calls_made; volatile ssize_t memory_calls_made; volatile ssize_t allocated_memory; volatile ssize_t mmapped_memory; } memory_statistics = { 0, 0, 0, 0, 0, 0, 0, 0 }; __thread size_t log_thread_memory_allocations = 0; static inline void print_allocations(const char *file, const char *function, const unsigned long line, const char *type, size_t size) { static __thread struct memory_statistics old = { 0, 0, 0, 0, 0, 0, 0, 0 }; fprintf(stderr, "%s iteration %zu MEMORY TRACE: %lu@%s : %s : %s : %zu\n", netdata_thread_tag(), log_thread_memory_allocations, line, file, function, type, size ); fprintf(stderr, "%s iteration %zu MEMORY ALLOCATIONS: (%04lu@%-40.40s:%-40.40s): Allocated %zd KiB (%+zd B), mmapped %zd KiB (%+zd B): %s : malloc %zd (%+zd), calloc %zd (%+zd), realloc %zd (%+zd), strdup %zd (%+zd), free %zd (%+zd)\n", netdata_thread_tag(), log_thread_memory_allocations, line, file, function, (memory_statistics.allocated_memory + 512) / 1024, memory_statistics.allocated_memory - old.allocated_memory, (memory_statistics.mmapped_memory + 512) / 1024, memory_statistics.mmapped_memory - old.mmapped_memory, type, memory_statistics.malloc_calls_made, memory_statistics.malloc_calls_made - old.malloc_calls_made, memory_statistics.calloc_calls_made, memory_statistics.calloc_calls_made - old.calloc_calls_made, memory_statistics.realloc_calls_made, memory_statistics.realloc_calls_made - old.realloc_calls_made, memory_statistics.strdup_calls_made, memory_statistics.strdup_calls_made - old.strdup_calls_made, memory_statistics.free_calls_made, memory_statistics.free_calls_made - old.free_calls_made ); memcpy(&old, &memory_statistics, sizeof(struct memory_statistics)); } static inline void mmap_accounting(size_t size) { if(log_thread_memory_allocations) { memory_statistics.memory_calls_made++; memory_statistics.mmapped_memory += size; } } void *mallocz_int(const char *file, const char *function, const unsigned long line, size_t size) { if(log_thread_memory_allocations) { memory_statistics.memory_calls_made++; memory_statistics.malloc_calls_made++; memory_statistics.allocated_memory += size; print_allocations(file, function, line, "malloc()", size); } size_t *n = (size_t *)malloc(sizeof(size_t) + size); if (unlikely(!n)) fatal("mallocz() cannot allocate %zu bytes of memory.", size); *n = size; return (void *)&n[1]; } void *callocz_int(const char *file, const char *function, const unsigned long line, size_t nmemb, size_t size) { size = nmemb * size; if(log_thread_memory_allocations) { memory_statistics.memory_calls_made++; memory_statistics.calloc_calls_made++; memory_statistics.allocated_memory += size; print_allocations(file, function, line, "calloc()", size); } size_t *n = (size_t *)calloc(1, sizeof(size_t) + size); if (unlikely(!n)) fatal("callocz() cannot allocate %zu bytes of memory.", size); *n = size; return (void *)&n[1]; } void *reallocz_int(const char *file, const char *function, const unsigned long line, void *ptr, size_t size) { if(!ptr) return mallocz_int(file, function, line, size); size_t *n = (size_t *)ptr; n--; size_t old_size = *n; n = realloc(n, sizeof(size_t) + size); if (unlikely(!n)) fatal("reallocz() cannot allocate %zu bytes of memory (from %zu bytes).", size, old_size); if(log_thread_memory_allocations) { memory_statistics.memory_calls_made++; memory_statistics.realloc_calls_made++; memory_statistics.allocated_memory += (size - old_size); print_allocations(file, function, line, "realloc()", size - old_size); } *n = size; return (void *)&n[1]; } char *strdupz_int(const char *file, const char *function, const unsigned long line, const char *s) { size_t size = strlen(s) + 1; if(log_thread_memory_allocations) { memory_statistics.memory_calls_made++; memory_statistics.strdup_calls_made++; memory_statistics.allocated_memory += size; print_allocations(file, function, line, "strdup()", size); } size_t *n = (size_t *)malloc(sizeof(size_t) + size); if (unlikely(!n)) fatal("strdupz() cannot allocate %zu bytes of memory.", size); *n = size; char *t = (char *)&n[1]; strcpy(t, s); return t; } void freez_int(const char *file, const char *function, const unsigned long line, void *ptr) { if(unlikely(!ptr)) return; size_t *n = (size_t *)ptr; n--; size_t size = *n; if(log_thread_memory_allocations) { memory_statistics.memory_calls_made++; memory_statistics.free_calls_made++; memory_statistics.allocated_memory -= size; print_allocations(file, function, line, "free()", size); } free(n); } #else char *strdupz(const char *s) { char *t = strdup(s); if (unlikely(!t)) fatal("Cannot strdup() string '%s'", s); return t; } void freez(void *ptr) { free(ptr); } void *mallocz(size_t size) { void *p = malloc(size); if (unlikely(!p)) fatal("Cannot allocate %zu bytes of memory.", size); return p; } void *callocz(size_t nmemb, size_t size) { void *p = calloc(nmemb, size); if (unlikely(!p)) fatal("Cannot allocate %zu bytes of memory.", nmemb * size); return p; } void *reallocz(void *ptr, size_t size) { void *p = realloc(ptr, size); if (unlikely(!p)) fatal("Cannot re-allocate memory to %zu bytes.", size); return p; } #endif // -------------------------------------------------------------------------------------------------------------------- void json_escape_string(char *dst, const char *src, size_t size) { const char *t; char *d = dst, *e = &dst[size - 1]; for(t = src; *t && d < e ;t++) { if(unlikely(*t == '\\' || *t == '"')) { if(unlikely(d + 1 >= e)) break; *d++ = '\\'; } *d++ = *t; } *d = '\0'; } void json_fix_string(char *s) { unsigned char c; while((c = (unsigned char)*s)) { if(unlikely(c == '\\')) *s++ = '/'; else if(unlikely(c == '"')) *s++ = '\''; else if(unlikely(isspace(c) || iscntrl(c))) *s++ = ' '; else if(unlikely(!isprint(c) || c > 127)) *s++ = '_'; else s++; } } unsigned char netdata_map_chart_names[256] = { [0] = '\0', // [1] = '_', // [2] = '_', // [3] = '_', // [4] = '_', // [5] = '_', // [6] = '_', // [7] = '_', // [8] = '_', // [9] = '_', // [10] = '_', // [11] = '_', // [12] = '_', // [13] = '_', // [14] = '_', // [15] = '_', // [16] = '_', // [17] = '_', // [18] = '_', // [19] = '_', // [20] = '_', // [21] = '_', // [22] = '_', // [23] = '_', // [24] = '_', // [25] = '_', // [26] = '_', // [27] = '_', // [28] = '_', // [29] = '_', // [30] = '_', // [31] = '_', // [32] = '_', // [33] = '_', // ! [34] = '_', // " [35] = '_', // # [36] = '_', // $ [37] = '_', // % [38] = '_', // & [39] = '_', // ' [40] = '_', // ( [41] = '_', // ) [42] = '_', // * [43] = '_', // + [44] = '.', // , [45] = '-', // - [46] = '.', // . [47] = '/', // / [48] = '0', // 0 [49] = '1', // 1 [50] = '2', // 2 [51] = '3', // 3 [52] = '4', // 4 [53] = '5', // 5 [54] = '6', // 6 [55] = '7', // 7 [56] = '8', // 8 [57] = '9', // 9 [58] = '_', // : [59] = '_', // ; [60] = '_', // < [61] = '_', // = [62] = '_', // > [63] = '_', // ? [64] = '_', // @ [65] = 'a', // A [66] = 'b', // B [67] = 'c', // C [68] = 'd', // D [69] = 'e', // E [70] = 'f', // F [71] = 'g', // G [72] = 'h', // H [73] = 'i', // I [74] = 'j', // J [75] = 'k', // K [76] = 'l', // L [77] = 'm', // M [78] = 'n', // N [79] = 'o', // O [80] = 'p', // P [81] = 'q', // Q [82] = 'r', // R [83] = 's', // S [84] = 't', // T [85] = 'u', // U [86] = 'v', // V [87] = 'w', // W [88] = 'x', // X [89] = 'y', // Y [90] = 'z', // Z [91] = '_', // [ [92] = '/', // backslash [93] = '_', // ] [94] = '_', // ^ [95] = '_', // _ [96] = '_', // ` [97] = 'a', // a [98] = 'b', // b [99] = 'c', // c [100] = 'd', // d [101] = 'e', // e [102] = 'f', // f [103] = 'g', // g [104] = 'h', // h [105] = 'i', // i [106] = 'j', // j [107] = 'k', // k [108] = 'l', // l [109] = 'm', // m [110] = 'n', // n [111] = 'o', // o [112] = 'p', // p [113] = 'q', // q [114] = 'r', // r [115] = 's', // s [116] = 't', // t [117] = 'u', // u [118] = 'v', // v [119] = 'w', // w [120] = 'x', // x [121] = 'y', // y [122] = 'z', // z [123] = '_', // { [124] = '_', // | [125] = '_', // } [126] = '_', // ~ [127] = '_', // [128] = '_', // [129] = '_', // [130] = '_', // [131] = '_', // [132] = '_', // [133] = '_', // [134] = '_', // [135] = '_', // [136] = '_', // [137] = '_', // [138] = '_', // [139] = '_', // [140] = '_', // [141] = '_', // [142] = '_', // [143] = '_', // [144] = '_', // [145] = '_', // [146] = '_', // [147] = '_', // [148] = '_', // [149] = '_', // [150] = '_', // [151] = '_', // [152] = '_', // [153] = '_', // [154] = '_', // [155] = '_', // [156] = '_', // [157] = '_', // [158] = '_', // [159] = '_', // [160] = '_', // [161] = '_', // [162] = '_', // [163] = '_', // [164] = '_', // [165] = '_', // [166] = '_', // [167] = '_', // [168] = '_', // [169] = '_', // [170] = '_', // [171] = '_', // [172] = '_', // [173] = '_', // [174] = '_', // [175] = '_', // [176] = '_', // [177] = '_', // [178] = '_', // [179] = '_', // [180] = '_', // [181] = '_', // [182] = '_', // [183] = '_', // [184] = '_', // [185] = '_', // [186] = '_', // [187] = '_', // [188] = '_', // [189] = '_', // [190] = '_', // [191] = '_', // [192] = '_', // [193] = '_', // [194] = '_', // [195] = '_', // [196] = '_', // [197] = '_', // [198] = '_', // [199] = '_', // [200] = '_', // [201] = '_', // [202] = '_', // [203] = '_', // [204] = '_', // [205] = '_', // [206] = '_', // [207] = '_', // [208] = '_', // [209] = '_', // [210] = '_', // [211] = '_', // [212] = '_', // [213] = '_', // [214] = '_', // [215] = '_', // [216] = '_', // [217] = '_', // [218] = '_', // [219] = '_', // [220] = '_', // [221] = '_', // [222] = '_', // [223] = '_', // [224] = '_', // [225] = '_', // [226] = '_', // [227] = '_', // [228] = '_', // [229] = '_', // [230] = '_', // [231] = '_', // [232] = '_', // [233] = '_', // [234] = '_', // [235] = '_', // [236] = '_', // [237] = '_', // [238] = '_', // [239] = '_', // [240] = '_', // [241] = '_', // [242] = '_', // [243] = '_', // [244] = '_', // [245] = '_', // [246] = '_', // [247] = '_', // [248] = '_', // [249] = '_', // [250] = '_', // [251] = '_', // [252] = '_', // [253] = '_', // [254] = '_', // [255] = '_' // }; // make sure the supplied string // is good for a netdata chart/dimension ID/NAME void netdata_fix_chart_name(char *s) { while ((*s = netdata_map_chart_names[(unsigned char) *s])) s++; } unsigned char netdata_map_chart_ids[256] = { [0] = '\0', // [1] = '_', // [2] = '_', // [3] = '_', // [4] = '_', // [5] = '_', // [6] = '_', // [7] = '_', // [8] = '_', // [9] = '_', // [10] = '_', // [11] = '_', // [12] = '_', // [13] = '_', // [14] = '_', // [15] = '_', // [16] = '_', // [17] = '_', // [18] = '_', // [19] = '_', // [20] = '_', // [21] = '_', // [22] = '_', // [23] = '_', // [24] = '_', // [25] = '_', // [26] = '_', // [27] = '_', // [28] = '_', // [29] = '_', // [30] = '_', // [31] = '_', // [32] = '_', // [33] = '_', // ! [34] = '_', // " [35] = '_', // # [36] = '_', // $ [37] = '_', // % [38] = '_', // & [39] = '_', // ' [40] = '_', // ( [41] = '_', // ) [42] = '_', // * [43] = '_', // + [44] = '.', // , [45] = '-', // - [46] = '.', // . [47] = '_', // / [48] = '0', // 0 [49] = '1', // 1 [50] = '2', // 2 [51] = '3', // 3 [52] = '4', // 4 [53] = '5', // 5 [54] = '6', // 6 [55] = '7', // 7 [56] = '8', // 8 [57] = '9', // 9 [58] = '_', // : [59] = '_', // ; [60] = '_', // < [61] = '_', // = [62] = '_', // > [63] = '_', // ? [64] = '_', // @ [65] = 'a', // A [66] = 'b', // B [67] = 'c', // C [68] = 'd', // D [69] = 'e', // E [70] = 'f', // F [71] = 'g', // G [72] = 'h', // H [73] = 'i', // I [74] = 'j', // J [75] = 'k', // K [76] = 'l', // L [77] = 'm', // M [78] = 'n', // N [79] = 'o', // O [80] = 'p', // P [81] = 'q', // Q [82] = 'r', // R [83] = 's', // S [84] = 't', // T [85] = 'u', // U [86] = 'v', // V [87] = 'w', // W [88] = 'x', // X [89] = 'y', // Y [90] = 'z', // Z [91] = '_', // [ [92] = '/', // backslash [93] = '_', // ] [94] = '_', // ^ [95] = '_', // _ [96] = '_', // ` [97] = 'a', // a [98] = 'b', // b [99] = 'c', // c [100] = 'd', // d [101] = 'e', // e [102] = 'f', // f [103] = 'g', // g [104] = 'h', // h [105] = 'i', // i [106] = 'j', // j [107] = 'k', // k [108] = 'l', // l [109] = 'm', // m [110] = 'n', // n [111] = 'o', // o [112] = 'p', // p [113] = 'q', // q [114] = 'r', // r [115] = 's', // s [116] = 't', // t [117] = 'u', // u [118] = 'v', // v [119] = 'w', // w [120] = 'x', // x [121] = 'y', // y [122] = 'z', // z [123] = '_', // { [124] = '_', // | [125] = '_', // } [126] = '_', // ~ [127] = '_', // [128] = '_', // [129] = '_', // [130] = '_', // [131] = '_', // [132] = '_', // [133] = '_', // [134] = '_', // [135] = '_', // [136] = '_', // [137] = '_', // [138] = '_', // [139] = '_', // [140] = '_', // [141] = '_', // [142] = '_', // [143] = '_', // [144] = '_', // [145] = '_', // [146] = '_', // [147] = '_', // [148] = '_', // [149] = '_', // [150] = '_', // [151] = '_', // [152] = '_', // [153] = '_', // [154] = '_', // [155] = '_', // [156] = '_', // [157] = '_', // [158] = '_', // [159] = '_', // [160] = '_', // [161] = '_', // [162] = '_', // [163] = '_', // [164] = '_', // [165] = '_', // [166] = '_', // [167] = '_', // [168] = '_', // [169] = '_', // [170] = '_', // [171] = '_', // [172] = '_', // [173] = '_', // [174] = '_', // [175] = '_', // [176] = '_', // [177] = '_', // [178] = '_', // [179] = '_', // [180] = '_', // [181] = '_', // [182] = '_', // [183] = '_', // [184] = '_', // [185] = '_', // [186] = '_', // [187] = '_', // [188] = '_', // [189] = '_', // [190] = '_', // [191] = '_', // [192] = '_', // [193] = '_', // [194] = '_', // [195] = '_', // [196] = '_', // [197] = '_', // [198] = '_', // [199] = '_', // [200] = '_', // [201] = '_', // [202] = '_', // [203] = '_', // [204] = '_', // [205] = '_', // [206] = '_', // [207] = '_', // [208] = '_', // [209] = '_', // [210] = '_', // [211] = '_', // [212] = '_', // [213] = '_', // [214] = '_', // [215] = '_', // [216] = '_', // [217] = '_', // [218] = '_', // [219] = '_', // [220] = '_', // [221] = '_', // [222] = '_', // [223] = '_', // [224] = '_', // [225] = '_', // [226] = '_', // [227] = '_', // [228] = '_', // [229] = '_', // [230] = '_', // [231] = '_', // [232] = '_', // [233] = '_', // [234] = '_', // [235] = '_', // [236] = '_', // [237] = '_', // [238] = '_', // [239] = '_', // [240] = '_', // [241] = '_', // [242] = '_', // [243] = '_', // [244] = '_', // [245] = '_', // [246] = '_', // [247] = '_', // [248] = '_', // [249] = '_', // [250] = '_', // [251] = '_', // [252] = '_', // [253] = '_', // [254] = '_', // [255] = '_' // }; // make sure the supplied string // is good for a netdata chart/dimension ID/NAME void netdata_fix_chart_id(char *s) { while ((*s = netdata_map_chart_ids[(unsigned char) *s])) s++; } /* // http://stackoverflow.com/questions/7666509/hash-function-for-string uint32_t simple_hash(const char *name) { const char *s = name; uint32_t hash = 5381; int i; while((i = *s++)) hash = ((hash << 5) + hash) + i; // fprintf(stderr, "HASH: %lu %s\n", hash, name); return hash; } */ /* // http://isthe.com/chongo/tech/comp/fnv/#FNV-1a uint32_t simple_hash(const char *name) { unsigned char *s = (unsigned char *) name; uint32_t hval = 0x811c9dc5; // FNV-1a algorithm while (*s) { // multiply by the 32 bit FNV magic prime mod 2^32 // NOTE: No need to optimize with left shifts. // GCC will use imul instruction anyway. // Tested with 'gcc -O3 -S' //hval += (hval<<1) + (hval<<4) + (hval<<7) + (hval<<8) + (hval<<24); hval *= 16777619; // xor the bottom with the current octet hval ^= (uint32_t) *s++; } // fprintf(stderr, "HASH: %u = %s\n", hval, name); return hval; } uint32_t simple_uhash(const char *name) { unsigned char *s = (unsigned char *) name; uint32_t hval = 0x811c9dc5, c; // FNV-1a algorithm while ((c = *s++)) { if (unlikely(c >= 'A' && c <= 'Z')) c += 'a' - 'A'; hval *= 16777619; hval ^= c; } return hval; } */ /* // http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx // one at a time hash uint32_t simple_hash(const char *name) { unsigned char *s = (unsigned char *)name; uint32_t h = 0; while(*s) { h += *s++; h += (h << 10); h ^= (h >> 6); } h += (h << 3); h ^= (h >> 11); h += (h << 15); // fprintf(stderr, "HASH: %u = %s\n", h, name); return h; } */ void strreverse(char *begin, char *end) { while (end > begin) { // clearer code. char aux = *end; *end-- = *begin; *begin++ = aux; } } char *strsep_on_1char(char **ptr, char c) { if(unlikely(!ptr || !*ptr)) return NULL; // remember the position we started char *s = *ptr; // skip separators in front while(*s == c) s++; char *ret = s; // find the next separator while(*s++) { if(unlikely(*s == c)) { *s++ = '\0'; *ptr = s; return ret; } } *ptr = NULL; return ret; } char *mystrsep(char **ptr, char *s) { char *p = ""; while (p && !p[0] && *ptr) p = strsep(ptr, s); return (p); } char *trim(char *s) { // skip leading spaces while (*s && isspace(*s)) s++; if (!*s) return NULL; // skip tailing spaces // this way is way faster. Writes only one NUL char. ssize_t l = strlen(s); if (--l >= 0) { char *p = s + l; while (p > s && isspace(*p)) p--; *++p = '\0'; } if (!*s) return NULL; return s; } inline char *trim_all(char *buffer) { char *d = buffer, *s = buffer; // skip spaces while(isspace(*s)) s++; while(*s) { // copy the non-space part while(*s && !isspace(*s)) *d++ = *s++; // add a space if we have to if(*s && isspace(*s)) { *d++ = ' '; s++; } // skip spaces while(isspace(*s)) s++; } *d = '\0'; if(d > buffer) { d--; if(isspace(*d)) *d = '\0'; } if(!buffer[0]) return NULL; return buffer; } static int memory_file_open(const char *filename, size_t size) { // info("memory_file_open('%s', %zu", filename, size); int fd = open(filename, O_RDWR | O_CREAT | O_NOATIME, 0664); if (fd != -1) { if (lseek(fd, size, SEEK_SET) == (off_t) size) { if (write(fd, "", 1) == 1) { if (ftruncate(fd, size)) error("Cannot truncate file '%s' to size %zu. Will use the larger file.", filename, size); } else error("Cannot write to file '%s' at position %zu.", filename, size); } else error("Cannot seek file '%s' to size %zu.", filename, size); } else error("Cannot create/open file '%s'.", filename); return fd; } // mmap_shared is used for memory mode = map static void *memory_file_mmap(const char *filename, size_t size, int flags) { // info("memory_file_mmap('%s', %zu", filename, size); static int log_madvise = 1; int fd = -1; if(filename) { fd = memory_file_open(filename, size); if(fd == -1) return MAP_FAILED; } void *mem = mmap(NULL, size, PROT_READ | PROT_WRITE, flags, fd, 0); if (mem != MAP_FAILED) { #ifdef NETDATA_LOG_ALLOCATIONS mmap_accounting(size); #endif int advise = MADV_SEQUENTIAL | MADV_DONTFORK; if (flags & MAP_SHARED) advise |= MADV_WILLNEED; if (madvise(mem, size, advise) != 0 && log_madvise) { error("Cannot advise the kernel about shared memory usage."); log_madvise--; } } if(fd != -1) close(fd); return mem; } #ifdef MADV_MERGEABLE static void *memory_file_mmap_ksm(const char *filename, size_t size, int flags) { // info("memory_file_mmap_ksm('%s', %zu", filename, size); static int log_madvise_2 = 1, log_madvise_3 = 1; int fd = -1; if(filename) { fd = memory_file_open(filename, size); if(fd == -1) return MAP_FAILED; } void *mem = mmap(NULL, size, PROT_READ | PROT_WRITE, flags | MAP_ANONYMOUS, -1, 0); if (mem != MAP_FAILED) { #ifdef NETDATA_LOG_ALLOCATIONS mmap_accounting(size); #endif if(fd != -1) { if (lseek(fd, 0, SEEK_SET) == 0) { if (read(fd, mem, size) != (ssize_t) size) error("Cannot read from file '%s'", filename); } else error("Cannot seek to beginning of file '%s'.", filename); } // don't use MADV_SEQUENTIAL|MADV_DONTFORK, they disable MADV_MERGEABLE if (madvise(mem, size, MADV_SEQUENTIAL | MADV_DONTFORK) != 0 && log_madvise_2) { error("Cannot advise the kernel about the memory usage (MADV_SEQUENTIAL|MADV_DONTFORK) of file '%s'.", filename); log_madvise_2--; } if (madvise(mem, size, MADV_MERGEABLE) != 0 && log_madvise_3) { error("Cannot advise the kernel about the memory usage (MADV_MERGEABLE) of file '%s'.", filename); log_madvise_3--; } } if(fd != -1) close(fd); return mem; } #else static void *memory_file_mmap_ksm(const char *filename, size_t size, int flags) { // info("memory_file_mmap_ksm FALLBACK ('%s', %zu", filename, size); if(filename) return memory_file_mmap(filename, size, flags); // when KSM is not available and no filename is given (memory mode = ram), // we just report failure return MAP_FAILED; } #endif void *mymmap(const char *filename, size_t size, int flags, int ksm) { void *mem = NULL; if (filename && (flags & MAP_SHARED || !enable_ksm || !ksm)) // memory mode = map | save // when KSM is not enabled // MAP_SHARED is used for memory mode = map (no KSM possible) mem = memory_file_mmap(filename, size, flags); else // memory mode = save | ram // when KSM is enabled // for memory mode = ram, the filename is NULL mem = memory_file_mmap_ksm(filename, size, flags); if(mem == MAP_FAILED) return NULL; errno = 0; return mem; } int memory_file_save(const char *filename, void *mem, size_t size) { char tmpfilename[FILENAME_MAX + 1]; snprintfz(tmpfilename, FILENAME_MAX, "%s.%ld.tmp", filename, (long) getpid()); int fd = open(tmpfilename, O_RDWR | O_CREAT | O_NOATIME, 0664); if (fd < 0) { error("Cannot create/open file '%s'.", filename); return -1; } if (write(fd, mem, size) != (ssize_t) size) { error("Cannot write to file '%s' %ld bytes.", filename, (long) size); close(fd); return -1; } close(fd); if (rename(tmpfilename, filename)) { error("Cannot rename '%s' to '%s'", tmpfilename, filename); return -1; } return 0; } int fd_is_valid(int fd) { return fcntl(fd, F_GETFD) != -1 || errno != EBADF; } char *fgets_trim_len(char *buf, size_t buf_size, FILE *fp, size_t *len) { char *s = fgets(buf, (int)buf_size, fp); if (!s) return NULL; char *t = s; if (*t != '\0') { // find the string end while (*++t != '\0'); // trim trailing spaces/newlines/tabs while (--t > s && *t == '\n') *t = '\0'; } if (len) *len = t - s + 1; return s; } int vsnprintfz(char *dst, size_t n, const char *fmt, va_list args) { int size = vsnprintf(dst, n, fmt, args); if (unlikely((size_t) size > n)) { // truncated size = (int)n; } dst[size] = '\0'; return size; } int snprintfz(char *dst, size_t n, const char *fmt, ...) { va_list args; va_start(args, fmt); int ret = vsnprintfz(dst, n, fmt, args); va_end(args); return ret; } /* // poor man cycle counting static unsigned long tsc; void begin_tsc(void) { unsigned long a, d; asm volatile ("cpuid\nrdtsc" : "=a" (a), "=d" (d) : "0" (0) : "ebx", "ecx"); tsc = ((unsigned long)d << 32) | (unsigned long)a; } unsigned long end_tsc(void) { unsigned long a, d; asm volatile ("rdtscp" : "=a" (a), "=d" (d) : : "ecx"); return (((unsigned long)d << 32) | (unsigned long)a) - tsc; } */ int recursively_delete_dir(const char *path, const char *reason) { DIR *dir = opendir(path); if(!dir) { error("Cannot read %s directory to be deleted '%s'", reason?reason:"", path); return -1; } int ret = 0; struct dirent *de = NULL; while((de = readdir(dir))) { if(de->d_type == DT_DIR && ( (de->d_name[0] == '.' && de->d_name[1] == '\0') || (de->d_name[0] == '.' && de->d_name[1] == '.' && de->d_name[2] == '\0') )) continue; char fullpath[FILENAME_MAX + 1]; snprintfz(fullpath, FILENAME_MAX, "%s/%s", path, de->d_name); if(de->d_type == DT_DIR) { int r = recursively_delete_dir(fullpath, reason); if(r > 0) ret += r; continue; } info("Deleting %s file '%s'", reason?reason:"", fullpath); if(unlikely(unlink(fullpath) == -1)) error("Cannot delete %s file '%s'", reason?reason:"", fullpath); else ret++; } info("Deleting empty directory '%s'", path); if(unlikely(rmdir(path) == -1)) error("Cannot delete empty directory '%s'", path); else ret++; closedir(dir); return ret; } static int is_virtual_filesystem(const char *path, char **reason) { #if defined(__APPLE__) || defined(__FreeBSD__) (void)path; (void)reason; #else struct statfs stat; // stat.f_fsid.__val[0] is a file system id // stat.f_fsid.__val[1] is the inode // so their combination uniquely identifies the file/dir if (statfs(path, &stat) == -1) { if(reason) *reason = "failed to statfs()"; return -1; } if(stat.f_fsid.__val[0] != 0 || stat.f_fsid.__val[1] != 0) { errno = EINVAL; if(reason) *reason = "is not a virtual file system"; return -1; } #endif return 0; } int verify_netdata_host_prefix() { if(!netdata_configured_host_prefix) netdata_configured_host_prefix = ""; if(!*netdata_configured_host_prefix) return 0; char buffer[FILENAME_MAX + 1]; char *path = netdata_configured_host_prefix; char *reason = "unknown reason"; errno = 0; struct stat sb; if (stat(path, &sb) == -1) { reason = "failed to stat()"; goto failed; } if((sb.st_mode & S_IFMT) != S_IFDIR) { errno = EINVAL; reason = "is not a directory"; goto failed; } path = buffer; snprintfz(path, FILENAME_MAX, "%s/proc", netdata_configured_host_prefix); if(is_virtual_filesystem(path, &reason) == -1) goto failed; snprintfz(path, FILENAME_MAX, "%s/sys", netdata_configured_host_prefix); if(is_virtual_filesystem(path, &reason) == -1) goto failed; if(netdata_configured_host_prefix && *netdata_configured_host_prefix) info("Using host prefix directory '%s'", netdata_configured_host_prefix); return 0; failed: error("Ignoring host prefix '%s': path '%s' %s", netdata_configured_host_prefix, path, reason); netdata_configured_host_prefix = ""; return -1; } char *strdupz_path_subpath(const char *path, const char *subpath) { if(unlikely(!path || !*path)) path = "."; if(unlikely(!subpath)) subpath = ""; // skip trailing slashes in path size_t len = strlen(path); while(len > 0 && path[len - 1] == '/') len--; // skip leading slashes in subpath while(subpath[0] == '/') subpath++; // if the last character in path is / and (there is a subpath or path is now empty) // keep the trailing slash in path and remove the additional slash char *slash = "/"; if(path[len] == '/' && (*subpath || len == 0)) { slash = ""; len++; } else if(!*subpath) { // there is no subpath // no need for trailing slash slash = ""; } char buffer[FILENAME_MAX + 1]; snprintfz(buffer, FILENAME_MAX, "%.*s%s%s", (int)len, path, slash, subpath); return strdupz(buffer); } int path_is_dir(const char *path, const char *subpath) { char *s = strdupz_path_subpath(path, subpath); size_t max_links = 100; int is_dir = 0; struct stat statbuf; while(max_links-- && stat(s, &statbuf) == 0) { if((statbuf.st_mode & S_IFMT) == S_IFDIR) { is_dir = 1; break; } else if((statbuf.st_mode & S_IFMT) == S_IFLNK) { char buffer[FILENAME_MAX + 1]; ssize_t l = readlink(s, buffer, FILENAME_MAX); if(l > 0) { buffer[l] = '\0'; freez(s); s = strdupz(buffer); continue; } else { is_dir = 0; break; } } else { is_dir = 0; break; } } freez(s); return is_dir; } int path_is_file(const char *path, const char *subpath) { char *s = strdupz_path_subpath(path, subpath); size_t max_links = 100; int is_file = 0; struct stat statbuf; while(max_links-- && stat(s, &statbuf) == 0) { if((statbuf.st_mode & S_IFMT) == S_IFREG) { is_file = 1; break; } else if((statbuf.st_mode & S_IFMT) == S_IFLNK) { char buffer[FILENAME_MAX + 1]; ssize_t l = readlink(s, buffer, FILENAME_MAX); if(l > 0) { buffer[l] = '\0'; freez(s); s = strdupz(buffer); continue; } else { is_file = 0; break; } } else { is_file = 0; break; } } freez(s); return is_file; } void recursive_config_double_dir_load(const char *user_path, const char *stock_path, const char *subpath, int (*callback)(const char *filename, void *data), void *data, size_t depth) { if(depth > 3) { error("CONFIG: Max directory depth reached while reading user path '%s', stock path '%s', subpath '%s'", user_path, stock_path, subpath); return; } char *udir = strdupz_path_subpath(user_path, subpath); char *sdir = strdupz_path_subpath(stock_path, subpath); debug(D_HEALTH, "CONFIG traversing user-config directory '%s', stock config directory '%s'", udir, sdir); DIR *dir = opendir(udir); if (!dir) { error("CONFIG cannot open user-config directory '%s'.", udir); } else { struct dirent *de = NULL; while((de = readdir(dir))) { if(de->d_type == DT_DIR || de->d_type == DT_LNK) { if( !de->d_name[0] || (de->d_name[0] == '.' && de->d_name[1] == '\0') || (de->d_name[0] == '.' && de->d_name[1] == '.' && de->d_name[2] == '\0') ) { debug(D_HEALTH, "CONFIG ignoring user-config directory '%s/%s'", udir, de->d_name); continue; } if(path_is_dir(udir, de->d_name)) { recursive_config_double_dir_load(udir, sdir, de->d_name, callback, data, depth + 1); continue; } } if(de->d_type == DT_UNKNOWN || de->d_type == DT_REG || de->d_type == DT_LNK) { size_t len = strlen(de->d_name); if(path_is_file(udir, de->d_name) && len > 5 && !strcmp(&de->d_name[len - 5], ".conf")) { char *filename = strdupz_path_subpath(udir, de->d_name); debug(D_HEALTH, "CONFIG calling callback for user file '%s'", filename); callback(filename, data); freez(filename); continue; } } debug(D_HEALTH, "CONFIG ignoring user-config file '%s/%s' of type %d", udir, de->d_name, (int)de->d_type); } closedir(dir); } debug(D_HEALTH, "CONFIG traversing stock config directory '%s', user config directory '%s'", sdir, udir); dir = opendir(sdir); if (!dir) { error("CONFIG cannot open stock config directory '%s'.", sdir); } else { struct dirent *de = NULL; while((de = readdir(dir))) { if(de->d_type == DT_DIR || de->d_type == DT_LNK) { if( !de->d_name[0] || (de->d_name[0] == '.' && de->d_name[1] == '\0') || (de->d_name[0] == '.' && de->d_name[1] == '.' && de->d_name[2] == '\0') ) { debug(D_HEALTH, "CONFIG ignoring stock config directory '%s/%s'", sdir, de->d_name); continue; } if(path_is_dir(sdir, de->d_name)) { // we recurse in stock subdirectory, only when there is no corresponding // user subdirectory - to avoid reading the files twice if(!path_is_dir(udir, de->d_name)) recursive_config_double_dir_load(udir, sdir, de->d_name, callback, data, depth + 1); continue; } } if(de->d_type == DT_UNKNOWN || de->d_type == DT_REG || de->d_type == DT_LNK) { size_t len = strlen(de->d_name); if(path_is_file(sdir, de->d_name) && !path_is_file(udir, de->d_name) && len > 5 && !strcmp(&de->d_name[len - 5], ".conf")) { char *filename = strdupz_path_subpath(sdir, de->d_name); debug(D_HEALTH, "CONFIG calling callback for stock file '%s'", filename); callback(filename, data); freez(filename); continue; } } debug(D_HEALTH, "CONFIG ignoring stock-config file '%s/%s' of type %d", udir, de->d_name, (int)de->d_type); } closedir(dir); } debug(D_HEALTH, "CONFIG done traversing user-config directory '%s', stock config directory '%s'", udir, sdir); freez(udir); freez(sdir); } /************************************************************************** * * Copyright 2013-2014 RAD Game Tools and Valve Software * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include "miniz.h" typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; #ifdef __cplusplus extern "C" { #endif /* ------------------- zlib-style API's */ mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) { mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552; if (!ptr) return MZ_ADLER32_INIT; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for (; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } return (s2 << 16) + s1; } /* Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ */ #if 0 mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) { static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; mz_uint32 crcu32 = (mz_uint32)crc; if (!ptr) return MZ_CRC32_INIT; crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; } return ~crcu32; } #else /* Faster, but larger CPU cache footprint. */ mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) { static const mz_uint32 s_crc_table[256] = { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D }; mz_uint32 crc32 = (mz_uint32)crc ^ 0xFFFFFFFF; const mz_uint8 *pByte_buf = (const mz_uint8 *)ptr; while (buf_len >= 4) { crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[1]) & 0xFF]; crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[2]) & 0xFF]; crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[3]) & 0xFF]; pByte_buf += 4; buf_len -= 4; } while (buf_len) { crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; ++pByte_buf; --buf_len; } return ~crc32; } #endif void mz_free(void *p) { MZ_FREE(p); } void *miniz_def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); } void miniz_def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); } void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size) { (void)opaque, (void)address, (void)items, (void)size; return MZ_REALLOC(address, items * size); } const char *mz_version(void) { return MZ_VERSION; } #ifndef MINIZ_NO_ZLIB_APIS int mz_deflateInit(mz_streamp pStream, int level) { return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); } int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) { tdefl_compressor *pComp; mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); if (!pStream) return MZ_STREAM_ERROR; if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = MZ_ADLER32_INIT; pStream->msg = NULL; pStream->reserved = 0; pStream->total_in = 0; pStream->total_out = 0; if (!pStream->zalloc) pStream->zalloc = miniz_def_alloc_func; if (!pStream->zfree) pStream->zfree = miniz_def_free_func; pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); if (!pComp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pComp; if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) { mz_deflateEnd(pStream); return MZ_PARAM_ERROR; } return MZ_OK; } int mz_deflateReset(mz_streamp pStream) { if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR; pStream->total_in = pStream->total_out = 0; tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, ((tdefl_compressor *)pStream->state)->m_flags); return MZ_OK; } int mz_deflate(mz_streamp pStream, int flush) { size_t in_bytes, out_bytes; mz_ulong orig_total_in, orig_total_out; int mz_status = MZ_OK; if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR; if (!pStream->avail_out) return MZ_BUF_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if (((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; orig_total_in = pStream->total_in; orig_total_out = pStream->total_out; for (;;) { tdefl_status defl_status; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; defl_status = tdefl_compress((tdefl_compressor *)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (defl_status < 0) { mz_status = MZ_STREAM_ERROR; break; } else if (defl_status == TDEFL_STATUS_DONE) { mz_status = MZ_STREAM_END; break; } else if (!pStream->avail_out) break; else if ((!pStream->avail_in) && (flush != MZ_FINISH)) { if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) break; return MZ_BUF_ERROR; /* Can't make forward progress without some input. */ } } return mz_status; } int mz_deflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) { (void)pStream; /* This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) */ return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); } int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) { int status; mz_stream stream; memset(&stream, 0, sizeof(stream)); /* In case mz_ulong is 64-bits (argh I hate longs). */ if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_deflateInit(&stream, level); if (status != MZ_OK) return status; status = mz_deflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_deflateEnd(&stream); return (status == MZ_OK) ? MZ_BUF_ERROR : status; } *pDest_len = stream.total_out; return mz_deflateEnd(&stream); } int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); } mz_ulong mz_compressBound(mz_ulong source_len) { return mz_deflateBound(NULL, source_len); } typedef struct { tinfl_decompressor m_decomp; mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits; mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; tinfl_status m_last_status; } inflate_state; int mz_inflateInit2(mz_streamp pStream, int window_bits) { inflate_state *pDecomp; if (!pStream) return MZ_STREAM_ERROR; if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = 0; pStream->msg = NULL; pStream->total_in = 0; pStream->total_out = 0; pStream->reserved = 0; if (!pStream->zalloc) pStream->zalloc = miniz_def_alloc_func; if (!pStream->zfree) pStream->zfree = miniz_def_free_func; pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); if (!pDecomp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pDecomp; tinfl_init(&pDecomp->m_decomp); pDecomp->m_dict_ofs = 0; pDecomp->m_dict_avail = 0; pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; pDecomp->m_first_call = 1; pDecomp->m_has_flushed = 0; pDecomp->m_window_bits = window_bits; return MZ_OK; } int mz_inflateInit(mz_streamp pStream) { return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); } int mz_inflateReset(mz_streamp pStream) { inflate_state *pDecomp; if (!pStream) return MZ_STREAM_ERROR; pStream->data_type = 0; pStream->adler = 0; pStream->msg = NULL; pStream->total_in = 0; pStream->total_out = 0; pStream->reserved = 0; pDecomp = (inflate_state *)pStream->state; tinfl_init(&pDecomp->m_decomp); pDecomp->m_dict_ofs = 0; pDecomp->m_dict_avail = 0; pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; pDecomp->m_first_call = 1; pDecomp->m_has_flushed = 0; /* pDecomp->m_window_bits = window_bits */; return MZ_OK; } int mz_inflate(mz_streamp pStream, int flush) { inflate_state *pState; mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; size_t in_bytes, out_bytes, orig_avail_in; tinfl_status status; if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState = (inflate_state *)pStream->state; if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; orig_avail_in = pStream->avail_in; first_call = pState->m_first_call; pState->m_first_call = 0; if (pState->m_last_status < 0) return MZ_DATA_ERROR; if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState->m_has_flushed |= (flush == MZ_FINISH); if ((flush == MZ_FINISH) && (first_call)) { /* MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. */ decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (status < 0) return MZ_DATA_ERROR; else if (status != TINFL_STATUS_DONE) { pState->m_last_status = TINFL_STATUS_FAILED; return MZ_BUF_ERROR; } return MZ_STREAM_END; } /* flush != MZ_FINISH then we must assume there's more input. */ if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; if (pState->m_dict_avail) { n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } for (;;) { in_bytes = pStream->avail_in; out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pState->m_dict_avail = (mz_uint)out_bytes; n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); if (status < 0) return MZ_DATA_ERROR; /* Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). */ else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) return MZ_BUF_ERROR; /* Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. */ else if (flush == MZ_FINISH) { /* The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. */ if (status == TINFL_STATUS_DONE) return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; /* status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. */ else if (!pStream->avail_out) return MZ_BUF_ERROR; } else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) break; } return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } int mz_inflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { mz_stream stream; int status; memset(&stream, 0, sizeof(stream)); /* In case mz_ulong is 64-bits (argh I hate longs). */ if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_inflateInit(&stream); if (status != MZ_OK) return status; status = mz_inflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_inflateEnd(&stream); return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; } *pDest_len = stream.total_out; return mz_inflateEnd(&stream); } const char *mz_error(int err) { static struct { int m_err; const char *m_pDesc; } s_error_descs[] = { { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" }, { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" } }; mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc; return NULL; } #endif /*MINIZ_NO_ZLIB_APIS */ #ifdef __cplusplus } #endif /* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org/> */ /* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * arabic.c: functions for Arabic language * * Author: Nadim Shaikli & Isam Bayazidi */ #include "vim.h" #if defined(FEAT_ARABIC) || defined(PROTO) static int A_firstc_laa(int c1, int c); static int A_is_harakat(int c); static int A_is_iso(int c); static int A_is_formb(int c); static int A_is_ok(int c); static int A_is_valid(int c); static int A_is_special(int c); /* * Returns True if c is an ISO-8859-6 shaped ARABIC letter (user entered) */ static int A_is_a(int cur_c) { switch (cur_c) { case a_HAMZA: case a_ALEF_MADDA: case a_ALEF_HAMZA_ABOVE: case a_WAW_HAMZA: case a_ALEF_HAMZA_BELOW: case a_YEH_HAMZA: case a_ALEF: case a_BEH: case a_TEH_MARBUTA: case a_TEH: case a_THEH: case a_JEEM: case a_HAH: case a_KHAH: case a_DAL: case a_THAL: case a_REH: case a_ZAIN: case a_SEEN: case a_SHEEN: case a_SAD: case a_DAD: case a_TAH: case a_ZAH: case a_AIN: case a_GHAIN: case a_TATWEEL: case a_FEH: case a_QAF: case a_KAF: case a_LAM: case a_MEEM: case a_NOON: case a_HEH: case a_WAW: case a_ALEF_MAKSURA: case a_YEH: return TRUE; } return FALSE; } /* * Returns True if c is an Isolated Form-B ARABIC letter */ static int A_is_s(int cur_c) { switch (cur_c) { case a_s_HAMZA: case a_s_ALEF_MADDA: case a_s_ALEF_HAMZA_ABOVE: case a_s_WAW_HAMZA: case a_s_ALEF_HAMZA_BELOW: case a_s_YEH_HAMZA: case a_s_ALEF: case a_s_BEH: case a_s_TEH_MARBUTA: case a_s_TEH: case a_s_THEH: case a_s_JEEM: case a_s_HAH: case a_s_KHAH: case a_s_DAL: case a_s_THAL: case a_s_REH: case a_s_ZAIN: case a_s_SEEN: case a_s_SHEEN: case a_s_SAD: case a_s_DAD: case a_s_TAH: case a_s_ZAH: case a_s_AIN: case a_s_GHAIN: case a_s_FEH: case a_s_QAF: case a_s_KAF: case a_s_LAM: case a_s_MEEM: case a_s_NOON: case a_s_HEH: case a_s_WAW: case a_s_ALEF_MAKSURA: case a_s_YEH: return TRUE; } return FALSE; } /* * Returns True if c is a Final shape of an ARABIC letter */ static int A_is_f(int cur_c) { switch (cur_c) { case a_f_ALEF_MADDA: case a_f_ALEF_HAMZA_ABOVE: case a_f_WAW_HAMZA: case a_f_ALEF_HAMZA_BELOW: case a_f_YEH_HAMZA: case a_f_ALEF: case a_f_BEH: case a_f_TEH_MARBUTA: case a_f_TEH: case a_f_THEH: case a_f_JEEM: case a_f_HAH: case a_f_KHAH: case a_f_DAL: case a_f_THAL: case a_f_REH: case a_f_ZAIN: case a_f_SEEN: case a_f_SHEEN: case a_f_SAD: case a_f_DAD: case a_f_TAH: case a_f_ZAH: case a_f_AIN: case a_f_GHAIN: case a_f_FEH: case a_f_QAF: case a_f_KAF: case a_f_LAM: case a_f_MEEM: case a_f_NOON: case a_f_HEH: case a_f_WAW: case a_f_ALEF_MAKSURA: case a_f_YEH: case a_f_LAM_ALEF_MADDA_ABOVE: case a_f_LAM_ALEF_HAMZA_ABOVE: case a_f_LAM_ALEF_HAMZA_BELOW: case a_f_LAM_ALEF: return TRUE; } return FALSE; } /* * Change shape - from ISO-8859-6/Isolated to Form-B Isolated */ static int chg_c_a2s(int cur_c) { switch (cur_c) { case a_HAMZA: return a_s_HAMZA; case a_ALEF_MADDA: return a_s_ALEF_MADDA; case a_ALEF_HAMZA_ABOVE: return a_s_ALEF_HAMZA_ABOVE; case a_WAW_HAMZA: return a_s_WAW_HAMZA; case a_ALEF_HAMZA_BELOW: return a_s_ALEF_HAMZA_BELOW; case a_YEH_HAMZA: return a_s_YEH_HAMZA; case a_ALEF: return a_s_ALEF; case a_TEH_MARBUTA: return a_s_TEH_MARBUTA; case a_DAL: return a_s_DAL; case a_THAL: return a_s_THAL; case a_REH: return a_s_REH; case a_ZAIN: return a_s_ZAIN; case a_TATWEEL: return cur_c; /* exceptions */ case a_WAW: return a_s_WAW; case a_ALEF_MAKSURA: return a_s_ALEF_MAKSURA; case a_BEH: return a_s_BEH; case a_TEH: return a_s_TEH; case a_THEH: return a_s_THEH; case a_JEEM: return a_s_JEEM; case a_HAH: return a_s_HAH; case a_KHAH: return a_s_KHAH; case a_SEEN: return a_s_SEEN; case a_SHEEN: return a_s_SHEEN; case a_SAD: return a_s_SAD; case a_DAD: return a_s_DAD; case a_TAH: return a_s_TAH; case a_ZAH: return a_s_ZAH; case a_AIN: return a_s_AIN; case a_GHAIN: return a_s_GHAIN; case a_FEH: return a_s_FEH; case a_QAF: return a_s_QAF; case a_KAF: return a_s_KAF; case a_LAM: return a_s_LAM; case a_MEEM: return a_s_MEEM; case a_NOON: return a_s_NOON; case a_HEH: return a_s_HEH; case a_YEH: return a_s_YEH; } return 0; } /* * Change shape - from ISO-8859-6/Isolated to Initial */ static int chg_c_a2i(int cur_c) { switch (cur_c) { case a_YEH_HAMZA: return a_i_YEH_HAMZA; case a_HAMZA: /* exceptions */ return a_s_HAMZA; case a_ALEF_MADDA: /* exceptions */ return a_s_ALEF_MADDA; case a_ALEF_HAMZA_ABOVE: /* exceptions */ return a_s_ALEF_HAMZA_ABOVE; case a_WAW_HAMZA: /* exceptions */ return a_s_WAW_HAMZA; case a_ALEF_HAMZA_BELOW: /* exceptions */ return a_s_ALEF_HAMZA_BELOW; case a_ALEF: /* exceptions */ return a_s_ALEF; case a_TEH_MARBUTA: /* exceptions */ return a_s_TEH_MARBUTA; case a_DAL: /* exceptions */ return a_s_DAL; case a_THAL: /* exceptions */ return a_s_THAL; case a_REH: /* exceptions */ return a_s_REH; case a_ZAIN: /* exceptions */ return a_s_ZAIN; case a_TATWEEL: /* exceptions */ return cur_c; case a_WAW: /* exceptions */ return a_s_WAW; case a_ALEF_MAKSURA: /* exceptions */ return a_s_ALEF_MAKSURA; case a_BEH: return a_i_BEH; case a_TEH: return a_i_TEH; case a_THEH: return a_i_THEH; case a_JEEM: return a_i_JEEM; case a_HAH: return a_i_HAH; case a_KHAH: return a_i_KHAH; case a_SEEN: return a_i_SEEN; case a_SHEEN: return a_i_SHEEN; case a_SAD: return a_i_SAD; case a_DAD: return a_i_DAD; case a_TAH: return a_i_TAH; case a_ZAH: return a_i_ZAH; case a_AIN: return a_i_AIN; case a_GHAIN: return a_i_GHAIN; case a_FEH: return a_i_FEH; case a_QAF: return a_i_QAF; case a_KAF: return a_i_KAF; case a_LAM: return a_i_LAM; case a_MEEM: return a_i_MEEM; case a_NOON: return a_i_NOON; case a_HEH: return a_i_HEH; case a_YEH: return a_i_YEH; } return 0; } /* * Change shape - from ISO-8859-6/Isolated to Medial */ static int chg_c_a2m(int cur_c) { switch (cur_c) { case a_HAMZA: return a_s_HAMZA; /* exception */ case a_ALEF_MADDA: return a_f_ALEF_MADDA; /* exception */ case a_ALEF_HAMZA_ABOVE: return a_f_ALEF_HAMZA_ABOVE; /* exception */ case a_WAW_HAMZA: return a_f_WAW_HAMZA; /* exception */ case a_ALEF_HAMZA_BELOW: return a_f_ALEF_HAMZA_BELOW; /* exception */ case a_YEH_HAMZA: return a_m_YEH_HAMZA; case a_ALEF: return a_f_ALEF; /* exception */ case a_BEH: return a_m_BEH; case a_TEH_MARBUTA: return a_f_TEH_MARBUTA; /* exception */ case a_TEH: return a_m_TEH; case a_THEH: return a_m_THEH; case a_JEEM: return a_m_JEEM; case a_HAH: return a_m_HAH; case a_KHAH: return a_m_KHAH; case a_DAL: return a_f_DAL; /* exception */ case a_THAL: return a_f_THAL; /* exception */ case a_REH: return a_f_REH; /* exception */ case a_ZAIN: return a_f_ZAIN; /* exception */ case a_SEEN: return a_m_SEEN; case a_SHEEN: return a_m_SHEEN; case a_SAD: return a_m_SAD; case a_DAD: return a_m_DAD; case a_TAH: return a_m_TAH; case a_ZAH: return a_m_ZAH; case a_AIN: return a_m_AIN; case a_GHAIN: return a_m_GHAIN; case a_TATWEEL: return cur_c; /* exception */ case a_FEH: return a_m_FEH; case a_QAF: return a_m_QAF; case a_KAF: return a_m_KAF; case a_LAM: return a_m_LAM; case a_MEEM: return a_m_MEEM; case a_NOON: return a_m_NOON; case a_HEH: return a_m_HEH; case a_WAW: return a_f_WAW; /* exception */ case a_ALEF_MAKSURA: return a_f_ALEF_MAKSURA; /* exception */ case a_YEH: return a_m_YEH; } return 0; } /* * Change shape - from ISO-8859-6/Isolated to final */ static int chg_c_a2f(int cur_c) { /* NOTE: these encodings need to be accounted for * a_f_ALEF_MADDA; * a_f_ALEF_HAMZA_ABOVE; * a_f_ALEF_HAMZA_BELOW; * a_f_LAM_ALEF_MADDA_ABOVE; * a_f_LAM_ALEF_HAMZA_ABOVE; * a_f_LAM_ALEF_HAMZA_BELOW; */ switch (cur_c) { case a_HAMZA: return a_s_HAMZA; /* exception */ case a_ALEF_MADDA: return a_f_ALEF_MADDA; case a_ALEF_HAMZA_ABOVE: return a_f_ALEF_HAMZA_ABOVE; case a_WAW_HAMZA: return a_f_WAW_HAMZA; case a_ALEF_HAMZA_BELOW: return a_f_ALEF_HAMZA_BELOW; case a_YEH_HAMZA: return a_f_YEH_HAMZA; case a_ALEF: return a_f_ALEF; case a_BEH: return a_f_BEH; case a_TEH_MARBUTA: return a_f_TEH_MARBUTA; case a_TEH: return a_f_TEH; case a_THEH: return a_f_THEH; case a_JEEM: return a_f_JEEM; case a_HAH: return a_f_HAH; case a_KHAH: return a_f_KHAH; case a_DAL: return a_f_DAL; case a_THAL: return a_f_THAL; case a_REH: return a_f_REH; case a_ZAIN: return a_f_ZAIN; case a_SEEN: return a_f_SEEN; case a_SHEEN: return a_f_SHEEN; case a_SAD: return a_f_SAD; case a_DAD: return a_f_DAD; case a_TAH: return a_f_TAH; case a_ZAH: return a_f_ZAH; case a_AIN: return a_f_AIN; case a_GHAIN: return a_f_GHAIN; case a_TATWEEL: return cur_c; /* exception */ case a_FEH: return a_f_FEH; case a_QAF: return a_f_QAF; case a_KAF: return a_f_KAF; case a_LAM: return a_f_LAM; case a_MEEM: return a_f_MEEM; case a_NOON: return a_f_NOON; case a_HEH: return a_f_HEH; case a_WAW: return a_f_WAW; case a_ALEF_MAKSURA: return a_f_ALEF_MAKSURA; case a_YEH: return a_f_YEH; } return 0; } /* * Change shape - from Initial to Medial * This code is unreachable, because for the relevant characters ARABIC_CHAR() * is FALSE; */ #if 0 static int chg_c_i2m(int cur_c) { switch (cur_c) { case a_i_YEH_HAMZA: return a_m_YEH_HAMZA; case a_i_BEH: return a_m_BEH; case a_i_TEH: return a_m_TEH; case a_i_THEH: return a_m_THEH; case a_i_JEEM: return a_m_JEEM; case a_i_HAH: return a_m_HAH; case a_i_KHAH: return a_m_KHAH; case a_i_SEEN: return a_m_SEEN; case a_i_SHEEN: return a_m_SHEEN; case a_i_SAD: return a_m_SAD; case a_i_DAD: return a_m_DAD; case a_i_TAH: return a_m_TAH; case a_i_ZAH: return a_m_ZAH; case a_i_AIN: return a_m_AIN; case a_i_GHAIN: return a_m_GHAIN; case a_i_FEH: return a_m_FEH; case a_i_QAF: return a_m_QAF; case a_i_KAF: return a_m_KAF; case a_i_LAM: return a_m_LAM; case a_i_MEEM: return a_m_MEEM; case a_i_NOON: return a_m_NOON; case a_i_HEH: return a_m_HEH; case a_i_YEH: return a_m_YEH; } return 0; } #endif /* * Change shape - from Final to Medial */ static int chg_c_f2m(int cur_c) { switch (cur_c) { /* NOTE: these encodings are multi-positional, no ? * case a_f_ALEF_MADDA: * case a_f_ALEF_HAMZA_ABOVE: * case a_f_ALEF_HAMZA_BELOW: */ case a_f_YEH_HAMZA: return a_m_YEH_HAMZA; case a_f_WAW_HAMZA: /* exceptions */ case a_f_ALEF: case a_f_TEH_MARBUTA: case a_f_DAL: case a_f_THAL: case a_f_REH: case a_f_ZAIN: case a_f_WAW: case a_f_ALEF_MAKSURA: return cur_c; case a_f_BEH: return a_m_BEH; case a_f_TEH: return a_m_TEH; case a_f_THEH: return a_m_THEH; case a_f_JEEM: return a_m_JEEM; case a_f_HAH: return a_m_HAH; case a_f_KHAH: return a_m_KHAH; case a_f_SEEN: return a_m_SEEN; case a_f_SHEEN: return a_m_SHEEN; case a_f_SAD: return a_m_SAD; case a_f_DAD: return a_m_DAD; case a_f_TAH: return a_m_TAH; case a_f_ZAH: return a_m_ZAH; case a_f_AIN: return a_m_AIN; case a_f_GHAIN: return a_m_GHAIN; case a_f_FEH: return a_m_FEH; case a_f_QAF: return a_m_QAF; case a_f_KAF: return a_m_KAF; case a_f_LAM: return a_m_LAM; case a_f_MEEM: return a_m_MEEM; case a_f_NOON: return a_m_NOON; case a_f_HEH: return a_m_HEH; case a_f_YEH: return a_m_YEH; /* NOTE: these encodings are multi-positional, no ? * case a_f_LAM_ALEF_MADDA_ABOVE: * case a_f_LAM_ALEF_HAMZA_ABOVE: * case a_f_LAM_ALEF_HAMZA_BELOW: * case a_f_LAM_ALEF: */ } return 0; } /* * Change shape - from Combination (2 char) to an Isolated */ static int chg_c_laa2i(int hid_c) { switch (hid_c) { case a_ALEF_MADDA: return a_s_LAM_ALEF_MADDA_ABOVE; case a_ALEF_HAMZA_ABOVE: return a_s_LAM_ALEF_HAMZA_ABOVE; case a_ALEF_HAMZA_BELOW: return a_s_LAM_ALEF_HAMZA_BELOW; case a_ALEF: return a_s_LAM_ALEF; } return 0; } /* * Change shape - from Combination-Isolated to Final */ static int chg_c_laa2f(int hid_c) { switch (hid_c) { case a_ALEF_MADDA: return a_f_LAM_ALEF_MADDA_ABOVE; case a_ALEF_HAMZA_ABOVE: return a_f_LAM_ALEF_HAMZA_ABOVE; case a_ALEF_HAMZA_BELOW: return a_f_LAM_ALEF_HAMZA_BELOW; case a_ALEF: return a_f_LAM_ALEF; } return 0; } /* * Do "half-shaping" on character "c". Return zero if no shaping. */ static int half_shape(int c) { if (A_is_a(c)) return chg_c_a2i(c); if (A_is_valid(c) && A_is_f(c)) return chg_c_f2m(c); return 0; } /* * Do Arabic shaping on character "c". Returns the shaped character. * out: "ccp" points to the first byte of the character to be shaped. * in/out: "c1p" points to the first composing char for "c". * in: "prev_c" is the previous character (not shaped) * in: "prev_c1" is the first composing char for the previous char * (not shaped) * in: "next_c" is the next character (not shaped). */ int arabic_shape( int c, int *ccp, int *c1p, int prev_c, int prev_c1, int next_c) { int curr_c; int shape_c; int curr_laa; int prev_laa; /* Deal only with Arabic character, pass back all others */ if (!A_is_ok(c)) return c; /* half-shape current and previous character */ shape_c = half_shape(prev_c); /* Save away current character */ curr_c = c; curr_laa = A_firstc_laa(c, *c1p); prev_laa = A_firstc_laa(prev_c, prev_c1); if (curr_laa) { if (A_is_valid(prev_c) && !A_is_f(shape_c) && !A_is_s(shape_c) && !prev_laa) curr_c = chg_c_laa2f(curr_laa); else curr_c = chg_c_laa2i(curr_laa); /* Remove the composing character */ *c1p = 0; } else if (!A_is_valid(prev_c) && A_is_valid(next_c)) curr_c = chg_c_a2i(c); else if (!shape_c || A_is_f(shape_c) || A_is_s(shape_c) || prev_laa) curr_c = A_is_valid(next_c) ? chg_c_a2i(c) : chg_c_a2s(c); else if (A_is_valid(next_c)) #if 0 curr_c = A_is_iso(c) ? chg_c_a2m(c) : chg_c_i2m(c); #else curr_c = A_is_iso(c) ? chg_c_a2m(c) : 0; #endif else if (A_is_valid(prev_c)) curr_c = chg_c_a2f(c); else curr_c = chg_c_a2s(c); /* Sanity check -- curr_c should, in the future, never be 0. * We should, in the future, insert a fatal error here. */ if (curr_c == NUL) curr_c = c; if (curr_c != c && ccp != NULL) { char_u buf[MB_MAXBYTES + 1]; /* Update the first byte of the character. */ (*mb_char2bytes)(curr_c, buf); *ccp = buf[0]; } /* Return the shaped character */ return curr_c; } /* * A_firstc_laa returns first character of LAA combination if it exists */ static int A_firstc_laa( int c, /* base character */ int c1) /* first composing character */ { if (c1 != NUL && c == a_LAM && !A_is_harakat(c1)) return c1; return 0; } /* * A_is_harakat returns TRUE if 'c' is an Arabic Harakat character * (harakat/tanween) */ static int A_is_harakat(int c) { return (c >= a_FATHATAN && c <= a_SUKUN); } /* * A_is_iso returns TRUE if 'c' is an Arabic ISO-8859-6 character * (alphabet/number/punctuation) */ static int A_is_iso(int c) { return ((c >= a_HAMZA && c <= a_GHAIN) || (c >= a_TATWEEL && c <= a_HAMZA_BELOW) || c == a_MINI_ALEF); } /* * A_is_formb returns TRUE if 'c' is an Arabic 10646-1 FormB character * (alphabet/number/punctuation) */ static int A_is_formb(int c) { return ((c >= a_s_FATHATAN && c <= a_s_DAMMATAN) || c == a_s_KASRATAN || (c >= a_s_FATHA && c <= a_f_LAM_ALEF) || c == a_BYTE_ORDER_MARK); } /* * A_is_ok returns TRUE if 'c' is an Arabic 10646 (8859-6 or Form-B) */ static int A_is_ok(int c) { return (A_is_iso(c) || A_is_formb(c)); } /* * A_is_valid returns TRUE if 'c' is an Arabic 10646 (8859-6 or Form-B) * with some exceptions/exclusions */ static int A_is_valid(int c) { return (A_is_ok(c) && !A_is_special(c)); } /* * A_is_special returns TRUE if 'c' is not a special Arabic character. * Specials don't adhere to most of the rules. */ static int A_is_special(int c) { return (c == a_HAMZA || c == a_s_HAMZA); } #endif /* FEAT_ARABIC */ /* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * Visual Workshop integration by Gordon Prieur * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ #include "vim.h" #if defined(FEAT_BEVAL) || defined(PROTO) /* * Get the text and position to be evaluated for "beval". * If "getword" is true the returned text is not the whole line but the * relevant word in allocated memory. * Returns OK or FAIL. */ int get_beval_info( BalloonEval *beval, int getword, win_T **winp, linenr_T *lnump, char_u **textp, int *colp) { win_T *wp; int row, col; char_u *lbuf; linenr_T lnum; *textp = NULL; # ifdef FEAT_BEVAL_TERM # ifdef FEAT_GUI if (!gui.in_use) # endif { row = mouse_row; col = mouse_col; } # endif # ifdef FEAT_GUI if (gui.in_use) { row = Y_2_ROW(beval->y); col = X_2_COL(beval->x); } #endif wp = mouse_find_win(&row, &col); if (wp != NULL && row >= 0 && row < wp->w_height && col < wp->w_width) { /* Found a window and the cursor is in the text. Now find the line * number. */ if (!mouse_comp_pos(wp, &row, &col, &lnum)) { /* Not past end of the file. */ lbuf = ml_get_buf(wp->w_buffer, lnum, FALSE); if (col <= win_linetabsize(wp, lbuf, (colnr_T)MAXCOL)) { /* Not past end of line. */ if (getword) { /* For Netbeans we get the relevant part of the line * instead of the whole line. */ int len; pos_T *spos = NULL, *epos = NULL; if (VIsual_active) { if (LT_POS(VIsual, curwin->w_cursor)) { spos = &VIsual; epos = &curwin->w_cursor; } else { spos = &curwin->w_cursor; epos = &VIsual; } } col = vcol2col(wp, lnum, col); if (VIsual_active && wp->w_buffer == curwin->w_buffer && (lnum == spos->lnum ? col >= (int)spos->col : lnum > spos->lnum) && (lnum == epos->lnum ? col <= (int)epos->col : lnum < epos->lnum)) { /* Visual mode and pointing to the line with the * Visual selection: return selected text, with a * maximum of one line. */ if (spos->lnum != epos->lnum || spos->col == epos->col) return FAIL; lbuf = ml_get_buf(curwin->w_buffer, VIsual.lnum, FALSE); len = epos->col - spos->col; if (*p_sel != 'e') len += MB_PTR2LEN(lbuf + epos->col); lbuf = vim_strnsave(lbuf + spos->col, len); lnum = spos->lnum; col = spos->col; } else { /* Find the word under the cursor. */ ++emsg_off; len = find_ident_at_pos(wp, lnum, (colnr_T)col, &lbuf, FIND_IDENT + FIND_STRING + FIND_EVAL); --emsg_off; if (len == 0) return FAIL; lbuf = vim_strnsave(lbuf, len); } } *winp = wp; *lnump = lnum; *textp = lbuf; *colp = col; #ifdef FEAT_VARTABS vim_free(beval->vts); beval->vts = tabstop_copy(wp->w_buffer->b_p_vts_array); #endif beval->ts = wp->w_buffer->b_p_ts; return OK; } } } return FAIL; } /* * Show a balloon with "mesg" or "list". */ void post_balloon(BalloonEval *beval UNUSED, char_u *mesg, list_T *list UNUSED) { # ifdef FEAT_BEVAL_TERM # ifdef FEAT_GUI if (!gui.in_use) # endif ui_post_balloon(mesg, list); # endif # ifdef FEAT_BEVAL_GUI if (gui.in_use) /* GUI can't handle a list */ gui_mch_post_balloon(beval, mesg); # endif } /* * Returns TRUE if the balloon eval has been enabled: * 'ballooneval' for the GUI and 'balloonevalterm' for the terminal. * Also checks if the screen isn't scrolled up. */ int can_use_beval(void) { return (0 #ifdef FEAT_BEVAL_GUI || (gui.in_use && p_beval) #endif #ifdef FEAT_BEVAL_TERM || ( # ifdef FEAT_GUI !gui.in_use && # endif p_bevalterm) #endif ) && msg_scrolled == 0; } /* * Common code, invoked when the mouse is resting for a moment. */ void general_beval_cb(BalloonEval *beval, int state UNUSED) { #ifdef FEAT_EVAL win_T *wp; int col; int use_sandbox; linenr_T lnum; char_u *text; static char_u *result = NULL; long winnr = 0; char_u *bexpr; buf_T *save_curbuf; size_t len; win_T *cw; #endif static int recursive = FALSE; /* Don't do anything when 'ballooneval' is off, messages scrolled the * windows up or we have no beval area. */ if (!can_use_beval() || beval == NULL) return; /* Don't do this recursively. Happens when the expression evaluation * takes a long time and invokes something that checks for CTRL-C typed. */ if (recursive) return; recursive = TRUE; #ifdef FEAT_EVAL if (get_beval_info(beval, TRUE, &wp, &lnum, &text, &col) == OK) { bexpr = (*wp->w_buffer->b_p_bexpr == NUL) ? p_bexpr : wp->w_buffer->b_p_bexpr; if (*bexpr != NUL) { /* Convert window pointer to number. */ for (cw = firstwin; cw != wp; cw = cw->w_next) ++winnr; set_vim_var_nr(VV_BEVAL_BUFNR, (long)wp->w_buffer->b_fnum); set_vim_var_nr(VV_BEVAL_WINNR, winnr); set_vim_var_nr(VV_BEVAL_WINID, wp->w_id); set_vim_var_nr(VV_BEVAL_LNUM, (long)lnum); set_vim_var_nr(VV_BEVAL_COL, (long)(col + 1)); set_vim_var_string(VV_BEVAL_TEXT, text, -1); vim_free(text); /* * Temporarily change the curbuf, so that we can determine whether * the buffer-local balloonexpr option was set insecurely. */ save_curbuf = curbuf; curbuf = wp->w_buffer; use_sandbox = was_set_insecurely((char_u *)"balloonexpr", *curbuf->b_p_bexpr == NUL ? 0 : OPT_LOCAL); curbuf = save_curbuf; if (use_sandbox) ++sandbox; ++textlock; vim_free(result); result = eval_to_string(bexpr, NULL, TRUE); /* Remove one trailing newline, it is added when the result was a * list and it's hardly ever useful. If the user really wants a * trailing newline he can add two and one remains. */ if (result != NULL) { len = STRLEN(result); if (len > 0 && result[len - 1] == NL) result[len - 1] = NUL; } if (use_sandbox) --sandbox; --textlock; set_vim_var_string(VV_BEVAL_TEXT, NULL, -1); if (result != NULL && result[0] != NUL) { post_balloon(beval, result, NULL); recursive = FALSE; return; } } } #endif #ifdef FEAT_NETBEANS_INTG if (bevalServers & BEVAL_NETBEANS) netbeans_beval_cb(beval, state); #endif #ifdef FEAT_SUN_WORKSHOP if (bevalServers & BEVAL_WORKSHOP) workshop_beval_cb(beval, state); #endif recursive = FALSE; } #endif /* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. * * Blowfish encryption for Vim; in Blowfish cipher feedback mode. * Contributed by Mohsin Ahmed, http://www.cs.albany.edu/~mosh * Based on http://www.schneier.com/blowfish.html by Bruce Schneier. * * There are two variants: * - The old one "blowfish" has a flaw which makes it much easier to crack the * key. To see this, make a text file with one line of 1000 "x" characters * and write it encrypted. Use "xxd" to inspect the bytes in the file. You * will see that a block of 8 bytes repeats 8 times. * - The new one "blowfish2" is better. It uses an 8 byte CFB to avoid the * repeats. */ #include "vim.h" #if defined(FEAT_CRYPT) || defined(PROTO) #define ARRAY_LENGTH(A) (sizeof(A)/sizeof(A[0])) #define BF_BLOCK 8 #define BF_BLOCK_MASK 7 #define BF_MAX_CFB_LEN (8 * BF_BLOCK) typedef union { UINT32_T ul[2]; char_u uc[8]; } block8; #if defined(WIN3264) /* MS-Windows is always little endian */ #else # ifdef HAVE_CONFIG_H /* in configure.ac AC_C_BIGENDIAN() defines WORDS_BIGENDIAN when needed */ # else error! Please change this code to define WORDS_BIGENDIAN for big-endian machines. # endif #endif /* The state of encryption, referenced by cryptstate_T. */ typedef struct { UINT32_T pax[18]; /* P-array */ UINT32_T sbx[4][256]; /* S-boxes */ int randbyte_offset; int update_offset; char_u cfb_buffer[BF_MAX_CFB_LEN]; /* up to 64 bytes used */ int cfb_len; /* size of cfb_buffer actually used */ } bf_state_T; /* Blowfish code */ static UINT32_T pax_init[18] = { 0x243f6a88u, 0x85a308d3u, 0x13198a2eu, 0x03707344u, 0xa4093822u, 0x299f31d0u, 0x082efa98u, 0xec4e6c89u, 0x452821e6u, 0x38d01377u, 0xbe5466cfu, 0x34e90c6cu, 0xc0ac29b7u, 0xc97c50ddu, 0x3f84d5b5u, 0xb5470917u, 0x9216d5d9u, 0x8979fb1bu }; static UINT32_T sbx_init[4][256] = { {0xd1310ba6u, 0x98dfb5acu, 0x2ffd72dbu, 0xd01adfb7u, 0xb8e1afedu, 0x6a267e96u, 0xba7c9045u, 0xf12c7f99u, 0x24a19947u, 0xb3916cf7u, 0x0801f2e2u, 0x858efc16u, 0x636920d8u, 0x71574e69u, 0xa458fea3u, 0xf4933d7eu, 0x0d95748fu, 0x728eb658u, 0x718bcd58u, 0x82154aeeu, 0x7b54a41du, 0xc25a59b5u, 0x9c30d539u, 0x2af26013u, 0xc5d1b023u, 0x286085f0u, 0xca417918u, 0xb8db38efu, 0x8e79dcb0u, 0x603a180eu, 0x6c9e0e8bu, 0xb01e8a3eu, 0xd71577c1u, 0xbd314b27u, 0x78af2fdau, 0x55605c60u, 0xe65525f3u, 0xaa55ab94u, 0x57489862u, 0x63e81440u, 0x55ca396au, 0x2aab10b6u, 0xb4cc5c34u, 0x1141e8ceu, 0xa15486afu, 0x7c72e993u, 0xb3ee1411u, 0x636fbc2au, 0x2ba9c55du, 0x741831f6u, 0xce5c3e16u, 0x9b87931eu, 0xafd6ba33u, 0x6c24cf5cu, 0x7a325381u, 0x28958677u, 0x3b8f4898u, 0x6b4bb9afu, 0xc4bfe81bu, 0x66282193u, 0x61d809ccu, 0xfb21a991u, 0x487cac60u, 0x5dec8032u, 0xef845d5du, 0xe98575b1u, 0xdc262302u, 0xeb651b88u, 0x23893e81u, 0xd396acc5u, 0x0f6d6ff3u, 0x83f44239u, 0x2e0b4482u, 0xa4842004u, 0x69c8f04au, 0x9e1f9b5eu, 0x21c66842u, 0xf6e96c9au, 0x670c9c61u, 0xabd388f0u, 0x6a51a0d2u, 0xd8542f68u, 0x960fa728u, 0xab5133a3u, 0x6eef0b6cu, 0x137a3be4u, 0xba3bf050u, 0x7efb2a98u, 0xa1f1651du, 0x39af0176u, 0x66ca593eu, 0x82430e88u, 0x8cee8619u, 0x456f9fb4u, 0x7d84a5c3u, 0x3b8b5ebeu, 0xe06f75d8u, 0x85c12073u, 0x401a449fu, 0x56c16aa6u, 0x4ed3aa62u, 0x363f7706u, 0x1bfedf72u, 0x429b023du, 0x37d0d724u, 0xd00a1248u, 0xdb0fead3u, 0x49f1c09bu, 0x075372c9u, 0x80991b7bu, 0x25d479d8u, 0xf6e8def7u, 0xe3fe501au, 0xb6794c3bu, 0x976ce0bdu, 0x04c006bau, 0xc1a94fb6u, 0x409f60c4u, 0x5e5c9ec2u, 0x196a2463u, 0x68fb6fafu, 0x3e6c53b5u, 0x1339b2ebu, 0x3b52ec6fu, 0x6dfc511fu, 0x9b30952cu, 0xcc814544u, 0xaf5ebd09u, 0xbee3d004u, 0xde334afdu, 0x660f2807u, 0x192e4bb3u, 0xc0cba857u, 0x45c8740fu, 0xd20b5f39u, 0xb9d3fbdbu, 0x5579c0bdu, 0x1a60320au, 0xd6a100c6u, 0x402c7279u, 0x679f25feu, 0xfb1fa3ccu, 0x8ea5e9f8u, 0xdb3222f8u, 0x3c7516dfu, 0xfd616b15u, 0x2f501ec8u, 0xad0552abu, 0x323db5fau, 0xfd238760u, 0x53317b48u, 0x3e00df82u, 0x9e5c57bbu, 0xca6f8ca0u, 0x1a87562eu, 0xdf1769dbu, 0xd542a8f6u, 0x287effc3u, 0xac6732c6u, 0x8c4f5573u, 0x695b27b0u, 0xbbca58c8u, 0xe1ffa35du, 0xb8f011a0u, 0x10fa3d98u, 0xfd2183b8u, 0x4afcb56cu, 0x2dd1d35bu, 0x9a53e479u, 0xb6f84565u, 0xd28e49bcu, 0x4bfb9790u, 0xe1ddf2dau, 0xa4cb7e33u, 0x62fb1341u, 0xcee4c6e8u, 0xef20cadau, 0x36774c01u, 0xd07e9efeu, 0x2bf11fb4u, 0x95dbda4du, 0xae909198u, 0xeaad8e71u, 0x6b93d5a0u, 0xd08ed1d0u, 0xafc725e0u, 0x8e3c5b2fu, 0x8e7594b7u, 0x8ff6e2fbu, 0xf2122b64u, 0x8888b812u, 0x900df01cu, 0x4fad5ea0u, 0x688fc31cu, 0xd1cff191u, 0xb3a8c1adu, 0x2f2f2218u, 0xbe0e1777u, 0xea752dfeu, 0x8b021fa1u, 0xe5a0cc0fu, 0xb56f74e8u, 0x18acf3d6u, 0xce89e299u, 0xb4a84fe0u, 0xfd13e0b7u, 0x7cc43b81u, 0xd2ada8d9u, 0x165fa266u, 0x80957705u, 0x93cc7314u, 0x211a1477u, 0xe6ad2065u, 0x77b5fa86u, 0xc75442f5u, 0xfb9d35cfu, 0xebcdaf0cu, 0x7b3e89a0u, 0xd6411bd3u, 0xae1e7e49u, 0x00250e2du, 0x2071b35eu, 0x226800bbu, 0x57b8e0afu, 0x2464369bu, 0xf009b91eu, 0x5563911du, 0x59dfa6aau, 0x78c14389u, 0xd95a537fu, 0x207d5ba2u, 0x02e5b9c5u, 0x83260376u, 0x6295cfa9u, 0x11c81968u, 0x4e734a41u, 0xb3472dcau, 0x7b14a94au, 0x1b510052u, 0x9a532915u, 0xd60f573fu, 0xbc9bc6e4u, 0x2b60a476u, 0x81e67400u, 0x08ba6fb5u, 0x571be91fu, 0xf296ec6bu, 0x2a0dd915u, 0xb6636521u, 0xe7b9f9b6u, 0xff34052eu, 0xc5855664u, 0x53b02d5du, 0xa99f8fa1u, 0x08ba4799u, 0x6e85076au}, {0x4b7a70e9u, 0xb5b32944u, 0xdb75092eu, 0xc4192623u, 0xad6ea6b0u, 0x49a7df7du, 0x9cee60b8u, 0x8fedb266u, 0xecaa8c71u, 0x699a17ffu, 0x5664526cu, 0xc2b19ee1u, 0x193602a5u, 0x75094c29u, 0xa0591340u, 0xe4183a3eu, 0x3f54989au, 0x5b429d65u, 0x6b8fe4d6u, 0x99f73fd6u, 0xa1d29c07u, 0xefe830f5u, 0x4d2d38e6u, 0xf0255dc1u, 0x4cdd2086u, 0x8470eb26u, 0x6382e9c6u, 0x021ecc5eu, 0x09686b3fu, 0x3ebaefc9u, 0x3c971814u, 0x6b6a70a1u, 0x687f3584u, 0x52a0e286u, 0xb79c5305u, 0xaa500737u, 0x3e07841cu, 0x7fdeae5cu, 0x8e7d44ecu, 0x5716f2b8u, 0xb03ada37u, 0xf0500c0du, 0xf01c1f04u, 0x0200b3ffu, 0xae0cf51au, 0x3cb574b2u, 0x25837a58u, 0xdc0921bdu, 0xd19113f9u, 0x7ca92ff6u, 0x94324773u, 0x22f54701u, 0x3ae5e581u, 0x37c2dadcu, 0xc8b57634u, 0x9af3dda7u, 0xa9446146u, 0x0fd0030eu, 0xecc8c73eu, 0xa4751e41u, 0xe238cd99u, 0x3bea0e2fu, 0x3280bba1u, 0x183eb331u, 0x4e548b38u, 0x4f6db908u, 0x6f420d03u, 0xf60a04bfu, 0x2cb81290u, 0x24977c79u, 0x5679b072u, 0xbcaf89afu, 0xde9a771fu, 0xd9930810u, 0xb38bae12u, 0xdccf3f2eu, 0x5512721fu, 0x2e6b7124u, 0x501adde6u, 0x9f84cd87u, 0x7a584718u, 0x7408da17u, 0xbc9f9abcu, 0xe94b7d8cu, 0xec7aec3au, 0xdb851dfau, 0x63094366u, 0xc464c3d2u, 0xef1c1847u, 0x3215d908u, 0xdd433b37u, 0x24c2ba16u, 0x12a14d43u, 0x2a65c451u, 0x50940002u, 0x133ae4ddu, 0x71dff89eu, 0x10314e55u, 0x81ac77d6u, 0x5f11199bu, 0x043556f1u, 0xd7a3c76bu, 0x3c11183bu, 0x5924a509u, 0xf28fe6edu, 0x97f1fbfau, 0x9ebabf2cu, 0x1e153c6eu, 0x86e34570u, 0xeae96fb1u, 0x860e5e0au, 0x5a3e2ab3u, 0x771fe71cu, 0x4e3d06fau, 0x2965dcb9u, 0x99e71d0fu, 0x803e89d6u, 0x5266c825u, 0x2e4cc978u, 0x9c10b36au, 0xc6150ebau, 0x94e2ea78u, 0xa5fc3c53u, 0x1e0a2df4u, 0xf2f74ea7u, 0x361d2b3du, 0x1939260fu, 0x19c27960u, 0x5223a708u, 0xf71312b6u, 0xebadfe6eu, 0xeac31f66u, 0xe3bc4595u, 0xa67bc883u, 0xb17f37d1u, 0x018cff28u, 0xc332ddefu, 0xbe6c5aa5u, 0x65582185u, 0x68ab9802u, 0xeecea50fu, 0xdb2f953bu, 0x2aef7dadu, 0x5b6e2f84u, 0x1521b628u, 0x29076170u, 0xecdd4775u, 0x619f1510u, 0x13cca830u, 0xeb61bd96u, 0x0334fe1eu, 0xaa0363cfu, 0xb5735c90u, 0x4c70a239u, 0xd59e9e0bu, 0xcbaade14u, 0xeecc86bcu, 0x60622ca7u, 0x9cab5cabu, 0xb2f3846eu, 0x648b1eafu, 0x19bdf0cau, 0xa02369b9u, 0x655abb50u, 0x40685a32u, 0x3c2ab4b3u, 0x319ee9d5u, 0xc021b8f7u, 0x9b540b19u, 0x875fa099u, 0x95f7997eu, 0x623d7da8u, 0xf837889au, 0x97e32d77u, 0x11ed935fu, 0x16681281u, 0x0e358829u, 0xc7e61fd6u, 0x96dedfa1u, 0x7858ba99u, 0x57f584a5u, 0x1b227263u, 0x9b83c3ffu, 0x1ac24696u, 0xcdb30aebu, 0x532e3054u, 0x8fd948e4u, 0x6dbc3128u, 0x58ebf2efu, 0x34c6ffeau, 0xfe28ed61u, 0xee7c3c73u, 0x5d4a14d9u, 0xe864b7e3u, 0x42105d14u, 0x203e13e0u, 0x45eee2b6u, 0xa3aaabeau, 0xdb6c4f15u, 0xfacb4fd0u, 0xc742f442u, 0xef6abbb5u, 0x654f3b1du, 0x41cd2105u, 0xd81e799eu, 0x86854dc7u, 0xe44b476au, 0x3d816250u, 0xcf62a1f2u, 0x5b8d2646u, 0xfc8883a0u, 0xc1c7b6a3u, 0x7f1524c3u, 0x69cb7492u, 0x47848a0bu, 0x5692b285u, 0x095bbf00u, 0xad19489du, 0x1462b174u, 0x23820e00u, 0x58428d2au, 0x0c55f5eau, 0x1dadf43eu, 0x233f7061u, 0x3372f092u, 0x8d937e41u, 0xd65fecf1u, 0x6c223bdbu, 0x7cde3759u, 0xcbee7460u, 0x4085f2a7u, 0xce77326eu, 0xa6078084u, 0x19f8509eu, 0xe8efd855u, 0x61d99735u, 0xa969a7aau, 0xc50c06c2u, 0x5a04abfcu, 0x800bcadcu, 0x9e447a2eu, 0xc3453484u, 0xfdd56705u, 0x0e1e9ec9u, 0xdb73dbd3u, 0x105588cdu, 0x675fda79u, 0xe3674340u, 0xc5c43465u, 0x713e38d8u, 0x3d28f89eu, 0xf16dff20u, 0x153e21e7u, 0x8fb03d4au, 0xe6e39f2bu, 0xdb83adf7u}, {0xe93d5a68u, 0x948140f7u, 0xf64c261cu, 0x94692934u, 0x411520f7u, 0x7602d4f7u, 0xbcf46b2eu, 0xd4a20068u, 0xd4082471u, 0x3320f46au, 0x43b7d4b7u, 0x500061afu, 0x1e39f62eu, 0x97244546u, 0x14214f74u, 0xbf8b8840u, 0x4d95fc1du, 0x96b591afu, 0x70f4ddd3u, 0x66a02f45u, 0xbfbc09ecu, 0x03bd9785u, 0x7fac6dd0u, 0x31cb8504u, 0x96eb27b3u, 0x55fd3941u, 0xda2547e6u, 0xabca0a9au, 0x28507825u, 0x530429f4u, 0x0a2c86dau, 0xe9b66dfbu, 0x68dc1462u, 0xd7486900u, 0x680ec0a4u, 0x27a18deeu, 0x4f3ffea2u, 0xe887ad8cu, 0xb58ce006u, 0x7af4d6b6u, 0xaace1e7cu, 0xd3375fecu, 0xce78a399u, 0x406b2a42u, 0x20fe9e35u, 0xd9f385b9u, 0xee39d7abu, 0x3b124e8bu, 0x1dc9faf7u, 0x4b6d1856u, 0x26a36631u, 0xeae397b2u, 0x3a6efa74u, 0xdd5b4332u, 0x6841e7f7u, 0xca7820fbu, 0xfb0af54eu, 0xd8feb397u, 0x454056acu, 0xba489527u, 0x55533a3au, 0x20838d87u, 0xfe6ba9b7u, 0xd096954bu, 0x55a867bcu, 0xa1159a58u, 0xcca92963u, 0x99e1db33u, 0xa62a4a56u, 0x3f3125f9u, 0x5ef47e1cu, 0x9029317cu, 0xfdf8e802u, 0x04272f70u, 0x80bb155cu, 0x05282ce3u, 0x95c11548u, 0xe4c66d22u, 0x48c1133fu, 0xc70f86dcu, 0x07f9c9eeu, 0x41041f0fu, 0x404779a4u, 0x5d886e17u, 0x325f51ebu, 0xd59bc0d1u, 0xf2bcc18fu, 0x41113564u, 0x257b7834u, 0x602a9c60u, 0xdff8e8a3u, 0x1f636c1bu, 0x0e12b4c2u, 0x02e1329eu, 0xaf664fd1u, 0xcad18115u, 0x6b2395e0u, 0x333e92e1u, 0x3b240b62u, 0xeebeb922u, 0x85b2a20eu, 0xe6ba0d99u, 0xde720c8cu, 0x2da2f728u, 0xd0127845u, 0x95b794fdu, 0x647d0862u, 0xe7ccf5f0u, 0x5449a36fu, 0x877d48fau, 0xc39dfd27u, 0xf33e8d1eu, 0x0a476341u, 0x992eff74u, 0x3a6f6eabu, 0xf4f8fd37u, 0xa812dc60u, 0xa1ebddf8u, 0x991be14cu, 0xdb6e6b0du, 0xc67b5510u, 0x6d672c37u, 0x2765d43bu, 0xdcd0e804u, 0xf1290dc7u, 0xcc00ffa3u, 0xb5390f92u, 0x690fed0bu, 0x667b9ffbu, 0xcedb7d9cu, 0xa091cf0bu, 0xd9155ea3u, 0xbb132f88u, 0x515bad24u, 0x7b9479bfu, 0x763bd6ebu, 0x37392eb3u, 0xcc115979u, 0x8026e297u, 0xf42e312du, 0x6842ada7u, 0xc66a2b3bu, 0x12754cccu, 0x782ef11cu, 0x6a124237u, 0xb79251e7u, 0x06a1bbe6u, 0x4bfb6350u, 0x1a6b1018u, 0x11caedfau, 0x3d25bdd8u, 0xe2e1c3c9u, 0x44421659u, 0x0a121386u, 0xd90cec6eu, 0xd5abea2au, 0x64af674eu, 0xda86a85fu, 0xbebfe988u, 0x64e4c3feu, 0x9dbc8057u, 0xf0f7c086u, 0x60787bf8u, 0x6003604du, 0xd1fd8346u, 0xf6381fb0u, 0x7745ae04u, 0xd736fcccu, 0x83426b33u, 0xf01eab71u, 0xb0804187u, 0x3c005e5fu, 0x77a057beu, 0xbde8ae24u, 0x55464299u, 0xbf582e61u, 0x4e58f48fu, 0xf2ddfda2u, 0xf474ef38u, 0x8789bdc2u, 0x5366f9c3u, 0xc8b38e74u, 0xb475f255u, 0x46fcd9b9u, 0x7aeb2661u, 0x8b1ddf84u, 0x846a0e79u, 0x915f95e2u, 0x466e598eu, 0x20b45770u, 0x8cd55591u, 0xc902de4cu, 0xb90bace1u, 0xbb8205d0u, 0x11a86248u, 0x7574a99eu, 0xb77f19b6u, 0xe0a9dc09u, 0x662d09a1u, 0xc4324633u, 0xe85a1f02u, 0x09f0be8cu, 0x4a99a025u, 0x1d6efe10u, 0x1ab93d1du, 0x0ba5a4dfu, 0xa186f20fu, 0x2868f169u, 0xdcb7da83u, 0x573906feu, 0xa1e2ce9bu, 0x4fcd7f52u, 0x50115e01u, 0xa70683fau, 0xa002b5c4u, 0x0de6d027u, 0x9af88c27u, 0x773f8641u, 0xc3604c06u, 0x61a806b5u, 0xf0177a28u, 0xc0f586e0u, 0x006058aau, 0x30dc7d62u, 0x11e69ed7u, 0x2338ea63u, 0x53c2dd94u, 0xc2c21634u, 0xbbcbee56u, 0x90bcb6deu, 0xebfc7da1u, 0xce591d76u, 0x6f05e409u, 0x4b7c0188u, 0x39720a3du, 0x7c927c24u, 0x86e3725fu, 0x724d9db9u, 0x1ac15bb4u, 0xd39eb8fcu, 0xed545578u, 0x08fca5b5u, 0xd83d7cd3u, 0x4dad0fc4u, 0x1e50ef5eu, 0xb161e6f8u, 0xa28514d9u, 0x6c51133cu, 0x6fd5c7e7u, 0x56e14ec4u, 0x362abfceu, 0xddc6c837u, 0xd79a3234u, 0x92638212u, 0x670efa8eu, 0x406000e0u}, {0x3a39ce37u, 0xd3faf5cfu, 0xabc27737u, 0x5ac52d1bu, 0x5cb0679eu, 0x4fa33742u, 0xd3822740u, 0x99bc9bbeu, 0xd5118e9du, 0xbf0f7315u, 0xd62d1c7eu, 0xc700c47bu, 0xb78c1b6bu, 0x21a19045u, 0xb26eb1beu, 0x6a366eb4u, 0x5748ab2fu, 0xbc946e79u, 0xc6a376d2u, 0x6549c2c8u, 0x530ff8eeu, 0x468dde7du, 0xd5730a1du, 0x4cd04dc6u, 0x2939bbdbu, 0xa9ba4650u, 0xac9526e8u, 0xbe5ee304u, 0xa1fad5f0u, 0x6a2d519au, 0x63ef8ce2u, 0x9a86ee22u, 0xc089c2b8u, 0x43242ef6u, 0xa51e03aau, 0x9cf2d0a4u, 0x83c061bau, 0x9be96a4du, 0x8fe51550u, 0xba645bd6u, 0x2826a2f9u, 0xa73a3ae1u, 0x4ba99586u, 0xef5562e9u, 0xc72fefd3u, 0xf752f7dau, 0x3f046f69u, 0x77fa0a59u, 0x80e4a915u, 0x87b08601u, 0x9b09e6adu, 0x3b3ee593u, 0xe990fd5au, 0x9e34d797u, 0x2cf0b7d9u, 0x022b8b51u, 0x96d5ac3au, 0x017da67du, 0xd1cf3ed6u, 0x7c7d2d28u, 0x1f9f25cfu, 0xadf2b89bu, 0x5ad6b472u, 0x5a88f54cu, 0xe029ac71u, 0xe019a5e6u, 0x47b0acfdu, 0xed93fa9bu, 0xe8d3c48du, 0x283b57ccu, 0xf8d56629u, 0x79132e28u, 0x785f0191u, 0xed756055u, 0xf7960e44u, 0xe3d35e8cu, 0x15056dd4u, 0x88f46dbau, 0x03a16125u, 0x0564f0bdu, 0xc3eb9e15u, 0x3c9057a2u, 0x97271aecu, 0xa93a072au, 0x1b3f6d9bu, 0x1e6321f5u, 0xf59c66fbu, 0x26dcf319u, 0x7533d928u, 0xb155fdf5u, 0x03563482u, 0x8aba3cbbu, 0x28517711u, 0xc20ad9f8u, 0xabcc5167u, 0xccad925fu, 0x4de81751u, 0x3830dc8eu, 0x379d5862u, 0x9320f991u, 0xea7a90c2u, 0xfb3e7bceu, 0x5121ce64u, 0x774fbe32u, 0xa8b6e37eu, 0xc3293d46u, 0x48de5369u, 0x6413e680u, 0xa2ae0810u, 0xdd6db224u, 0x69852dfdu, 0x09072166u, 0xb39a460au, 0x6445c0ddu, 0x586cdecfu, 0x1c20c8aeu, 0x5bbef7ddu, 0x1b588d40u, 0xccd2017fu, 0x6bb4e3bbu, 0xdda26a7eu, 0x3a59ff45u, 0x3e350a44u, 0xbcb4cdd5u, 0x72eacea8u, 0xfa6484bbu, 0x8d6612aeu, 0xbf3c6f47u, 0xd29be463u, 0x542f5d9eu, 0xaec2771bu, 0xf64e6370u, 0x740e0d8du, 0xe75b1357u, 0xf8721671u, 0xaf537d5du, 0x4040cb08u, 0x4eb4e2ccu, 0x34d2466au, 0x0115af84u, 0xe1b00428u, 0x95983a1du, 0x06b89fb4u, 0xce6ea048u, 0x6f3f3b82u, 0x3520ab82u, 0x011a1d4bu, 0x277227f8u, 0x611560b1u, 0xe7933fdcu, 0xbb3a792bu, 0x344525bdu, 0xa08839e1u, 0x51ce794bu, 0x2f32c9b7u, 0xa01fbac9u, 0xe01cc87eu, 0xbcc7d1f6u, 0xcf0111c3u, 0xa1e8aac7u, 0x1a908749u, 0xd44fbd9au, 0xd0dadecbu, 0xd50ada38u, 0x0339c32au, 0xc6913667u, 0x8df9317cu, 0xe0b12b4fu, 0xf79e59b7u, 0x43f5bb3au, 0xf2d519ffu, 0x27d9459cu, 0xbf97222cu, 0x15e6fc2au, 0x0f91fc71u, 0x9b941525u, 0xfae59361u, 0xceb69cebu, 0xc2a86459u, 0x12baa8d1u, 0xb6c1075eu, 0xe3056a0cu, 0x10d25065u, 0xcb03a442u, 0xe0ec6e0eu, 0x1698db3bu, 0x4c98a0beu, 0x3278e964u, 0x9f1f9532u, 0xe0d392dfu, 0xd3a0342bu, 0x8971f21eu, 0x1b0a7441u, 0x4ba3348cu, 0xc5be7120u, 0xc37632d8u, 0xdf359f8du, 0x9b992f2eu, 0xe60b6f47u, 0x0fe3f11du, 0xe54cda54u, 0x1edad891u, 0xce6279cfu, 0xcd3e7e6fu, 0x1618b166u, 0xfd2c1d05u, 0x848fd2c5u, 0xf6fb2299u, 0xf523f357u, 0xa6327623u, 0x93a83531u, 0x56cccd02u, 0xacf08162u, 0x5a75ebb5u, 0x6e163697u, 0x88d273ccu, 0xde966292u, 0x81b949d0u, 0x4c50901bu, 0x71c65614u, 0xe6c6c7bdu, 0x327a140au, 0x45e1d006u, 0xc3f27b9au, 0xc9aa53fdu, 0x62a80f00u, 0xbb25bfe2u, 0x35bdd2f6u, 0x71126905u, 0xb2040222u, 0xb6cbcf7cu, 0xcd769c2bu, 0x53113ec0u, 0x1640e3d3u, 0x38abbd60u, 0x2547adf0u, 0xba38209cu, 0xf746ce76u, 0x77afa1c5u, 0x20756060u, 0x85cbfe4eu, 0x8ae88dd8u, 0x7aaaf9b0u, 0x4cf9aa7eu, 0x1948c25cu, 0x02fb8a8cu, 0x01c36ae4u, 0xd6ebe1f9u, 0x90d4f869u, 0xa65cdea0u, 0x3f09252du, 0xc208e69fu, 0xb74e6132u, 0xce77e25bu, 0x578fdfe3u, 0x3ac372e6u } }; #define F1(i) \ xl ^= bfs->pax[i]; \ xr ^= ((bfs->sbx[0][xl >> 24] + \ bfs->sbx[1][(xl & 0xFF0000) >> 16]) ^ \ bfs->sbx[2][(xl & 0xFF00) >> 8]) + \ bfs->sbx[3][xl & 0xFF]; #define F2(i) \ xr ^= bfs->pax[i]; \ xl ^= ((bfs->sbx[0][xr >> 24] + \ bfs->sbx[1][(xr & 0xFF0000) >> 16]) ^ \ bfs->sbx[2][(xr & 0xFF00) >> 8]) + \ bfs->sbx[3][xr & 0xFF]; static void bf_e_block( bf_state_T *bfs, UINT32_T *p_xl, UINT32_T *p_xr) { UINT32_T temp; UINT32_T xl = *p_xl; UINT32_T xr = *p_xr; F1(0) F2(1) F1(2) F2(3) F1(4) F2(5) F1(6) F2(7) F1(8) F2(9) F1(10) F2(11) F1(12) F2(13) F1(14) F2(15) xl ^= bfs->pax[16]; xr ^= bfs->pax[17]; temp = xl; xl = xr; xr = temp; *p_xl = xl; *p_xr = xr; } #ifdef WORDS_BIGENDIAN # define htonl2(x) \ x = ((((x) & 0xffL) << 24) | (((x) & 0xff00L) << 8) | \ (((x) & 0xff0000L) >> 8) | (((x) & 0xff000000L) >> 24)) #else # define htonl2(x) #endif static void bf_e_cblock( bf_state_T *bfs, char_u *block) { block8 bk; memcpy(bk.uc, block, 8); htonl2(bk.ul[0]); htonl2(bk.ul[1]); bf_e_block(bfs, &bk.ul[0], &bk.ul[1]); htonl2(bk.ul[0]); htonl2(bk.ul[1]); memcpy(block, bk.uc, 8); } /* * Initialize the crypt method using "password" as the encryption key and * "salt[salt_len]" as the salt. */ static void bf_key_init( bf_state_T *bfs, char_u *password, char_u *salt, int salt_len) { int i, j, keypos = 0; unsigned u; UINT32_T val, data_l, data_r; char_u *key; int keylen; /* Process the key 1001 times. * See http://en.wikipedia.org/wiki/Key_strengthening. */ key = sha256_key(password, salt, salt_len); for (i = 0; i < 1000; i++) key = sha256_key(key, salt, salt_len); /* Convert the key from 64 hex chars to 32 binary chars. */ keylen = (int)STRLEN(key) / 2; if (keylen == 0) { IEMSG(_("E831: bf_key_init() called with empty password")); return; } for (i = 0; i < keylen; i++) { sscanf((char *)&key[i * 2], "%2x", &u); key[i] = u; } /* Use "key" to initialize the P-array ("pax") and S-boxes ("sbx") of * Blowfish. */ mch_memmove(bfs->sbx, sbx_init, 4 * 4 * 256); for (i = 0; i < 18; ++i) { val = 0; for (j = 0; j < 4; ++j) val = (val << 8) | key[keypos++ % keylen]; bfs->pax[i] = pax_init[i] ^ val; } data_l = data_r = 0; for (i = 0; i < 18; i += 2) { bf_e_block(bfs, &data_l, &data_r); bfs->pax[i + 0] = data_l; bfs->pax[i + 1] = data_r; } for (i = 0; i < 4; ++i) { for (j = 0; j < 256; j += 2) { bf_e_block(bfs, &data_l, &data_r); bfs->sbx[i][j + 0] = data_l; bfs->sbx[i][j + 1] = data_r; } } } /* * Blowfish self-test for corrupted tables or instructions. */ static int bf_check_tables( UINT32_T pax[18], UINT32_T sbx[4][256], UINT32_T val) { int i, j; UINT32_T c = 0; for (i = 0; i < 18; i++) c ^= pax[i]; for (i = 0; i < 4; i++) for (j = 0; j < 256; j++) c ^= sbx[i][j]; return c == val; } typedef struct { char_u password[64]; char_u salt[9]; char_u plaintxt[9]; char_u cryptxt[9]; char_u badcryptxt[9]; /* cryptxt when big/little endian is wrong */ UINT32_T keysum; } struct_bf_test_data; /* * Assert bf(password, plaintxt) is cryptxt. * Assert csum(pax sbx(password)) is keysum. */ static struct_bf_test_data bf_test_data[] = { { "password", "salt", "plaintxt", "\xad\x3d\xfa\x7f\xe8\xea\x40\xf6", /* cryptxt */ "\x72\x50\x3b\x38\x10\x60\x22\xa7", /* badcryptxt */ 0x56701b5du /* keysum */ }, }; /* * Return FAIL when there is something wrong with blowfish encryption. */ static int bf_self_test(void) { int i, bn; int err = 0; block8 bk; UINT32_T ui = 0xffffffffUL; bf_state_T state; vim_memset(&state, 0, sizeof(bf_state_T)); state.cfb_len = BF_MAX_CFB_LEN; /* We can't simply use sizeof(UINT32_T), it would generate a compiler * warning. */ if (ui != 0xffffffffUL || ui + 1 != 0) { err++; EMSG(_("E820: sizeof(uint32_t) != 4")); } if (!bf_check_tables(pax_init, sbx_init, 0x6ffa520a)) err++; bn = ARRAY_LENGTH(bf_test_data); for (i = 0; i < bn; i++) { bf_key_init(&state, (char_u *)(bf_test_data[i].password), bf_test_data[i].salt, (int)STRLEN(bf_test_data[i].salt)); if (!bf_check_tables(state.pax, state.sbx, bf_test_data[i].keysum)) err++; /* Don't modify bf_test_data[i].plaintxt, self test is idempotent. */ memcpy(bk.uc, bf_test_data[i].plaintxt, 8); bf_e_cblock(&state, bk.uc); if (memcmp(bk.uc, bf_test_data[i].cryptxt, 8) != 0) { if (err == 0 && memcmp(bk.uc, bf_test_data[i].badcryptxt, 8) == 0) EMSG(_("E817: Blowfish big/little endian use wrong")); err++; } } return err > 0 ? FAIL : OK; } /* * CFB: Cipher Feedback Mode. */ /* * Initialize with seed "seed[seed_len]". */ static void bf_cfb_init( bf_state_T *bfs, char_u *seed, int seed_len) { int i, mi; bfs->randbyte_offset = bfs->update_offset = 0; vim_memset(bfs->cfb_buffer, 0, bfs->cfb_len); if (seed_len > 0) { mi = seed_len > bfs->cfb_len ? seed_len : bfs->cfb_len; for (i = 0; i < mi; i++) bfs->cfb_buffer[i % bfs->cfb_len] ^= seed[i % seed_len]; } } #define BF_CFB_UPDATE(bfs, c) { \ bfs->cfb_buffer[bfs->update_offset] ^= (char_u)c; \ if (++bfs->update_offset == bfs->cfb_len) \ bfs->update_offset = 0; \ } #define BF_RANBYTE(bfs, t) { \ if ((bfs->randbyte_offset & BF_BLOCK_MASK) == 0) \ bf_e_cblock(bfs, &(bfs->cfb_buffer[bfs->randbyte_offset])); \ t = bfs->cfb_buffer[bfs->randbyte_offset]; \ if (++bfs->randbyte_offset == bfs->cfb_len) \ bfs->randbyte_offset = 0; \ } /* * Encrypt "from[len]" into "to[len]". * "from" and "to" can be equal to encrypt in place. */ void crypt_blowfish_encode( cryptstate_T *state, char_u *from, size_t len, char_u *to) { bf_state_T *bfs = state->method_state; size_t i; int ztemp, t; for (i = 0; i < len; ++i) { ztemp = from[i]; BF_RANBYTE(bfs, t); BF_CFB_UPDATE(bfs, ztemp); to[i] = t ^ ztemp; } } /* * Decrypt "from[len]" into "to[len]". */ void crypt_blowfish_decode( cryptstate_T *state, char_u *from, size_t len, char_u *to) { bf_state_T *bfs = state->method_state; size_t i; int t; for (i = 0; i < len; ++i) { BF_RANBYTE(bfs, t); to[i] = from[i] ^ t; BF_CFB_UPDATE(bfs, to[i]); } } void crypt_blowfish_init( cryptstate_T *state, char_u* key, char_u* salt, int salt_len, char_u* seed, int seed_len) { bf_state_T *bfs = (bf_state_T *)alloc_clear(sizeof(bf_state_T)); state->method_state = bfs; /* "blowfish" uses a 64 byte buffer, causing it to repeat 8 byte groups 8 * times. "blowfish2" uses a 8 byte buffer to avoid repeating. */ bfs->cfb_len = state->method_nr == CRYPT_M_BF ? BF_MAX_CFB_LEN : BF_BLOCK; if (blowfish_self_test() == FAIL) return; bf_key_init(bfs, key, salt, salt_len); bf_cfb_init(bfs, seed, seed_len); } /* * Run a test to check if the encryption works as expected. * Give an error and return FAIL when not. */ int blowfish_self_test(void) { if (sha256_self_test() == FAIL) { EMSG(_("E818: sha256 test failed")); return FAIL; } if (bf_self_test() == FAIL) { EMSG(_("E819: Blowfish test failed")); return FAIL; } return OK; } #endif /* FEAT_CRYPT */ /* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * buffer.c: functions for dealing with the buffer structure */ /* * The buffer list is a double linked list of all buffers. * Each buffer can be in one of these states: * never loaded: BF_NEVERLOADED is set, only the file name is valid * not loaded: b_ml.ml_mfp == NULL, no memfile allocated * hidden: b_nwindows == 0, loaded but not displayed in a window * normal: loaded and displayed in a window * * Instead of storing file names all over the place, each file name is * stored in the buffer list. It can be referenced by a number. * * The current implementation remembers all file names ever used. */ #include "vim.h" static char_u *buflist_match(regmatch_T *rmp, buf_T *buf, int ignore_case); static char_u *fname_match(regmatch_T *rmp, char_u *name, int ignore_case); static void buflist_setfpos(buf_T *buf, win_T *win, linenr_T lnum, colnr_T col, int copy_options); #ifdef UNIX static buf_T *buflist_findname_stat(char_u *ffname, stat_T *st); static int otherfile_buf(buf_T *buf, char_u *ffname, stat_T *stp); static int buf_same_ino(buf_T *buf, stat_T *stp); #else static int otherfile_buf(buf_T *buf, char_u *ffname); #endif #ifdef FEAT_TITLE static int value_changed(char_u *str, char_u **last); #endif static int append_arg_number(win_T *wp, char_u *buf, int buflen, int add_file); static void free_buffer(buf_T *); static void free_buffer_stuff(buf_T *buf, int free_options); static void clear_wininfo(buf_T *buf); #ifdef UNIX # define dev_T dev_t #else # define dev_T unsigned #endif #if defined(FEAT_QUICKFIX) static char *msg_loclist = N_("[Location List]"); static char *msg_qflist = N_("[Quickfix List]"); #endif static char *e_auabort = N_("E855: Autocommands caused command to abort"); /* Number of times free_buffer() was called. */ static int buf_free_count = 0; /* Read data from buffer for retrying. */ static int read_buffer( int read_stdin, /* read file from stdin, otherwise fifo */ exarg_T *eap, /* for forced 'ff' and 'fenc' or NULL */ int flags) /* extra flags for readfile() */ { int retval = OK; linenr_T line_count; /* * Read from the buffer which the text is already filled in and append at * the end. This makes it possible to retry when 'fileformat' or * 'fileencoding' was guessed wrong. */ line_count = curbuf->b_ml.ml_line_count; retval = readfile( read_stdin ? NULL : curbuf->b_ffname, read_stdin ? NULL : curbuf->b_fname, (linenr_T)line_count, (linenr_T)0, (linenr_T)MAXLNUM, eap, flags | READ_BUFFER); if (retval == OK) { /* Delete the binary lines. */ while (--line_count >= 0) ml_delete((linenr_T)1, FALSE); } else { /* Delete the converted lines. */ while (curbuf->b_ml.ml_line_count > line_count) ml_delete(line_count, FALSE); } /* Put the cursor on the first line. */ curwin->w_cursor.lnum = 1; curwin->w_cursor.col = 0; if (read_stdin) { /* Set or reset 'modified' before executing autocommands, so that * it can be changed there. */ if (!readonlymode && !BUFEMPTY()) changed(); else if (retval == OK) unchanged(curbuf, FALSE); if (retval == OK) { #ifdef FEAT_EVAL apply_autocmds_retval(EVENT_STDINREADPOST, NULL, NULL, FALSE, curbuf, &retval); #else apply_autocmds(EVENT_STDINREADPOST, NULL, NULL, FALSE, curbuf); #endif } } return retval; } /* * Open current buffer, that is: open the memfile and read the file into * memory. * Return FAIL for failure, OK otherwise. */ int open_buffer( int read_stdin, /* read file from stdin */ exarg_T *eap, /* for forced 'ff' and 'fenc' or NULL */ int flags) /* extra flags for readfile() */ { int retval = OK; bufref_T old_curbuf; #ifdef FEAT_SYN_HL long old_tw = curbuf->b_p_tw; #endif int read_fifo = FALSE; /* * The 'readonly' flag is only set when BF_NEVERLOADED is being reset. * When re-entering the same buffer, it should not change, because the * user may have reset the flag by hand. */ if (readonlymode && curbuf->b_ffname != NULL && (curbuf->b_flags & BF_NEVERLOADED)) curbuf->b_p_ro = TRUE; if (ml_open(curbuf) == FAIL) { /* * There MUST be a memfile, otherwise we can't do anything * If we can't create one for the current buffer, take another buffer */ close_buffer(NULL, curbuf, 0, FALSE); FOR_ALL_BUFFERS(curbuf) if (curbuf->b_ml.ml_mfp != NULL) break; /* * if there is no memfile at all, exit * This is OK, since there are no changes to lose. */ if (curbuf == NULL) { EMSG(_("E82: Cannot allocate any buffer, exiting...")); getout(2); } EMSG(_("E83: Cannot allocate buffer, using other one...")); enter_buffer(curbuf); #ifdef FEAT_SYN_HL if (old_tw != curbuf->b_p_tw) check_colorcolumn(curwin); #endif return FAIL; } /* The autocommands in readfile() may change the buffer, but only AFTER * reading the file. */ set_bufref(&old_curbuf, curbuf); modified_was_set = FALSE; /* mark cursor position as being invalid */ curwin->w_valid = 0; if (curbuf->b_ffname != NULL #ifdef FEAT_NETBEANS_INTG && netbeansReadFile #endif ) { int old_msg_silent = msg_silent; #ifdef UNIX int save_bin = curbuf->b_p_bin; int perm; #endif #ifdef FEAT_NETBEANS_INTG int oldFire = netbeansFireChanges; netbeansFireChanges = 0; #endif #ifdef UNIX perm = mch_getperm(curbuf->b_ffname); if (perm >= 0 && (S_ISFIFO(perm) || S_ISSOCK(perm) # ifdef OPEN_CHR_FILES || (S_ISCHR(perm) && is_dev_fd_file(curbuf->b_ffname)) # endif )) read_fifo = TRUE; if (read_fifo) curbuf->b_p_bin = TRUE; #endif if (shortmess(SHM_FILEINFO)) msg_silent = 1; retval = readfile(curbuf->b_ffname, curbuf->b_fname, (linenr_T)0, (linenr_T)0, (linenr_T)MAXLNUM, eap, flags | READ_NEW | (read_fifo ? READ_FIFO : 0)); #ifdef UNIX if (read_fifo) { curbuf->b_p_bin = save_bin; if (retval == OK) retval = read_buffer(FALSE, eap, flags); } #endif msg_silent = old_msg_silent; #ifdef FEAT_NETBEANS_INTG netbeansFireChanges = oldFire; #endif /* Help buffer is filtered. */ if (bt_help(curbuf)) fix_help_buffer(); } else if (read_stdin) { int save_bin = curbuf->b_p_bin; /* * First read the text in binary mode into the buffer. * Then read from that same buffer and append at the end. This makes * it possible to retry when 'fileformat' or 'fileencoding' was * guessed wrong. */ curbuf->b_p_bin = TRUE; retval = readfile(NULL, NULL, (linenr_T)0, (linenr_T)0, (linenr_T)MAXLNUM, NULL, flags | (READ_NEW + READ_STDIN)); curbuf->b_p_bin = save_bin; if (retval == OK) retval = read_buffer(TRUE, eap, flags); } /* if first time loading this buffer, init b_chartab[] */ if (curbuf->b_flags & BF_NEVERLOADED) { (void)buf_init_chartab(curbuf, FALSE); #ifdef FEAT_CINDENT parse_cino(curbuf); #endif } /* * Set/reset the Changed flag first, autocmds may change the buffer. * Apply the automatic commands, before processing the modelines. * So the modelines have priority over autocommands. */ /* When reading stdin, the buffer contents always needs writing, so set * the changed flag. Unless in readonly mode: "ls | gview -". * When interrupted and 'cpoptions' contains 'i' set changed flag. */ if ((got_int && vim_strchr(p_cpo, CPO_INTMOD) != NULL) || modified_was_set /* ":set modified" used in autocmd */ #ifdef FEAT_EVAL || (aborting() && vim_strchr(p_cpo, CPO_INTMOD) != NULL) #endif ) changed(); else if (retval == OK && !read_stdin && !read_fifo) unchanged(curbuf, FALSE); save_file_ff(curbuf); /* keep this fileformat */ /* Set last_changedtick to avoid triggering a TextChanged autocommand right * after it was added. */ curbuf->b_last_changedtick = CHANGEDTICK(curbuf); #ifdef FEAT_INS_EXPAND curbuf->b_last_changedtick_pum = CHANGEDTICK(curbuf); #endif /* require "!" to overwrite the file, because it wasn't read completely */ #ifdef FEAT_EVAL if (aborting()) #else if (got_int) #endif curbuf->b_flags |= BF_READERR; #ifdef FEAT_FOLDING /* Need to update automatic folding. Do this before the autocommands, * they may use the fold info. */ foldUpdateAll(curwin); #endif /* need to set w_topline, unless some autocommand already did that. */ if (!(curwin->w_valid & VALID_TOPLINE)) { curwin->w_topline = 1; #ifdef FEAT_DIFF curwin->w_topfill = 0; #endif } #ifdef FEAT_EVAL apply_autocmds_retval(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf, &retval); #else apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf); #endif if (retval == OK) { /* * The autocommands may have changed the current buffer. Apply the * modelines to the correct buffer, if it still exists and is loaded. */ if (bufref_valid(&old_curbuf) && old_curbuf.br_buf->b_ml.ml_mfp != NULL) { aco_save_T aco; /* Go to the buffer that was opened. */ aucmd_prepbuf(&aco, old_curbuf.br_buf); do_modelines(0); curbuf->b_flags &= ~(BF_CHECK_RO | BF_NEVERLOADED); #ifdef FEAT_EVAL apply_autocmds_retval(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf, &retval); #else apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf); #endif /* restore curwin/curbuf and a few other things */ aucmd_restbuf(&aco); } } return retval; } /* * Store "buf" in "bufref" and set the free count. */ void set_bufref(bufref_T *bufref, buf_T *buf) { bufref->br_buf = buf; bufref->br_fnum = buf == NULL ? 0 : buf->b_fnum; bufref->br_buf_free_count = buf_free_count; } /* * Return TRUE if "bufref->br_buf" points to the same buffer as when * set_bufref() was called and it is a valid buffer. * Only goes through the buffer list if buf_free_count changed. * Also checks if b_fnum is still the same, a :bwipe followed by :new might get * the same allocated memory, but it's a different buffer. */ int bufref_valid(bufref_T *bufref) { return bufref->br_buf_free_count == buf_free_count ? TRUE : buf_valid(bufref->br_buf) && bufref->br_fnum == bufref->br_buf->b_fnum; } /* * Return TRUE if "buf" points to a valid buffer (in the buffer list). * This can be slow if there are many buffers, prefer using bufref_valid(). */ int buf_valid(buf_T *buf) { buf_T *bp; /* Assume that we more often have a recent buffer, start with the last * one. */ for (bp = lastbuf; bp != NULL; bp = bp->b_prev) if (bp == buf) return TRUE; return FALSE; } /* * A hash table used to quickly lookup a buffer by its number. */ static hashtab_T buf_hashtab; static void buf_hashtab_add(buf_T *buf) { sprintf((char *)buf->b_key, "%x", buf->b_fnum); if (hash_add(&buf_hashtab, buf->b_key) == FAIL) EMSG(_("E931: Buffer cannot be registered")); } static void buf_hashtab_remove(buf_T *buf) { hashitem_T *hi = hash_find(&buf_hashtab, buf->b_key); if (!HASHITEM_EMPTY(hi)) hash_remove(&buf_hashtab, hi); } /* * Return TRUE when buffer "buf" can be unloaded. * Give an error message and return FALSE when the buffer is locked or the * screen is being redrawn and the buffer is in a window. */ static int can_unload_buffer(buf_T *buf) { int can_unload = !buf->b_locked; if (can_unload && updating_screen) { win_T *wp; FOR_ALL_WINDOWS(wp) if (wp->w_buffer == buf) { can_unload = FALSE; break; } } if (!can_unload) EMSG(_("E937: Attempt to delete a buffer that is in use")); return can_unload; } /* * Close the link to a buffer. * "action" is used when there is no longer a window for the buffer. * It can be: * 0 buffer becomes hidden * DOBUF_UNLOAD buffer is unloaded * DOBUF_DELETE buffer is unloaded and removed from buffer list * DOBUF_WIPE buffer is unloaded and really deleted * When doing all but the first one on the current buffer, the caller should * get a new buffer very soon! * * The 'bufhidden' option can force freeing and deleting. * * When "abort_if_last" is TRUE then do not close the buffer if autocommands * cause there to be only one window with this buffer. e.g. when ":quit" is * supposed to close the window but autocommands close all other windows. */ void close_buffer( win_T *win, /* if not NULL, set b_last_cursor */ buf_T *buf, int action, int abort_if_last UNUSED) { int is_curbuf; int nwindows; bufref_T bufref; int is_curwin = (curwin != NULL && curwin->w_buffer == buf); win_T *the_curwin = curwin; tabpage_T *the_curtab = curtab; int unload_buf = (action != 0); int del_buf = (action == DOBUF_DEL || action == DOBUF_WIPE); int wipe_buf = (action == DOBUF_WIPE); /* * Force unloading or deleting when 'bufhidden' says so. * The caller must take care of NOT deleting/freeing when 'bufhidden' is * "hide" (otherwise we could never free or delete a buffer). */ if (buf->b_p_bh[0] == 'd') /* 'bufhidden' == "delete" */ { del_buf = TRUE; unload_buf = TRUE; } else if (buf->b_p_bh[0] == 'w') /* 'bufhidden' == "wipe" */ { del_buf = TRUE; unload_buf = TRUE; wipe_buf = TRUE; } else if (buf->b_p_bh[0] == 'u') /* 'bufhidden' == "unload" */ unload_buf = TRUE; #ifdef FEAT_TERMINAL if (bt_terminal(buf) && (buf->b_nwindows == 1 || del_buf)) { if (term_job_running(buf->b_term)) { if (wipe_buf || unload_buf) { if (!can_unload_buffer(buf)) return; /* Wiping out or unloading a terminal buffer kills the job. */ free_terminal(buf); } else { /* The job keeps running, hide the buffer. */ del_buf = FALSE; unload_buf = FALSE; } } else { /* A terminal buffer is wiped out if the job has finished. */ del_buf = TRUE; unload_buf = TRUE; wipe_buf = TRUE; } } #endif /* Disallow deleting the buffer when it is locked (already being closed or * halfway a command that relies on it). Unloading is allowed. */ if ((del_buf || wipe_buf) && !can_unload_buffer(buf)) return; /* check no autocommands closed the window */ if (win != NULL && win_valid_any_tab(win)) { /* Set b_last_cursor when closing the last window for the buffer. * Remember the last cursor position and window options of the buffer. * This used to be only for the current window, but then options like * 'foldmethod' may be lost with a ":only" command. */ if (buf->b_nwindows == 1) set_last_cursor(win); buflist_setfpos(buf, win, win->w_cursor.lnum == 1 ? 0 : win->w_cursor.lnum, win->w_cursor.col, TRUE); } set_bufref(&bufref, buf); /* When the buffer is no longer in a window, trigger BufWinLeave */ if (buf->b_nwindows == 1) { ++buf->b_locked; if (apply_autocmds(EVENT_BUFWINLEAVE, buf->b_fname, buf->b_fname, FALSE, buf) && !bufref_valid(&bufref)) { /* Autocommands deleted the buffer. */ aucmd_abort: EMSG(_(e_auabort)); return; } --buf->b_locked; if (abort_if_last && one_window()) /* Autocommands made this the only window. */ goto aucmd_abort; /* When the buffer becomes hidden, but is not unloaded, trigger * BufHidden */ if (!unload_buf) { ++buf->b_locked; if (apply_autocmds(EVENT_BUFHIDDEN, buf->b_fname, buf->b_fname, FALSE, buf) && !bufref_valid(&bufref)) /* Autocommands deleted the buffer. */ goto aucmd_abort; --buf->b_locked; if (abort_if_last && one_window()) /* Autocommands made this the only window. */ goto aucmd_abort; } #ifdef FEAT_EVAL if (aborting()) /* autocmds may abort script processing */ return; #endif } /* If the buffer was in curwin and the window has changed, go back to that * window, if it still exists. This avoids that ":edit x" triggering a * "tabnext" BufUnload autocmd leaves a window behind without a buffer. */ if (is_curwin && curwin != the_curwin && win_valid_any_tab(the_curwin)) { block_autocmds(); goto_tabpage_win(the_curtab, the_curwin); unblock_autocmds(); } nwindows = buf->b_nwindows; /* decrease the link count from windows (unless not in any window) */ if (buf->b_nwindows > 0) --buf->b_nwindows; #ifdef FEAT_DIFF if (diffopt_hiddenoff() && !unload_buf && buf->b_nwindows == 0) diff_buf_delete(buf); /* Clear 'diff' for hidden buffer. */ #endif /* Return when a window is displaying the buffer or when it's not * unloaded. */ if (buf->b_nwindows > 0 || !unload_buf) return; /* Always remove the buffer when there is no file name. */ if (buf->b_ffname == NULL) del_buf = TRUE; /* When closing the current buffer stop Visual mode before freeing * anything. */ if (buf == curbuf && VIsual_active #if defined(EXITFREE) && !entered_free_all_mem #endif ) end_visual_mode(); /* * Free all things allocated for this buffer. * Also calls the "BufDelete" autocommands when del_buf is TRUE. */ /* Remember if we are closing the current buffer. Restore the number of * windows, so that autocommands in buf_freeall() don't get confused. */ is_curbuf = (buf == curbuf); buf->b_nwindows = nwindows; buf_freeall(buf, (del_buf ? BFA_DEL : 0) + (wipe_buf ? BFA_WIPE : 0)); /* Autocommands may have deleted the buffer. */ if (!bufref_valid(&bufref)) return; #ifdef FEAT_EVAL if (aborting()) /* autocmds may abort script processing */ return; #endif /* * It's possible that autocommands change curbuf to the one being deleted. * This might cause the previous curbuf to be deleted unexpectedly. But * in some cases it's OK to delete the curbuf, because a new one is * obtained anyway. Therefore only return if curbuf changed to the * deleted buffer. */ if (buf == curbuf && !is_curbuf) return; if (win_valid_any_tab(win) && win->w_buffer == buf) win->w_buffer = NULL; /* make sure we don't use the buffer now */ /* Autocommands may have opened or closed windows for this buffer. * Decrement the count for the close we do here. */ if (buf->b_nwindows > 0) --buf->b_nwindows; /* * Remove the buffer from the list. */ if (wipe_buf) { #ifdef FEAT_SUN_WORKSHOP if (usingSunWorkShop) workshop_file_closed_lineno((char *)buf->b_ffname, (int)buf->b_last_cursor.lnum); #endif if (buf->b_sfname != buf->b_ffname) VIM_CLEAR(buf->b_sfname); else buf->b_sfname = NULL; VIM_CLEAR(buf->b_ffname); if (buf->b_prev == NULL) firstbuf = buf->b_next; else buf->b_prev->b_next = buf->b_next; if (buf->b_next == NULL) lastbuf = buf->b_prev; else buf->b_next->b_prev = buf->b_prev; free_buffer(buf); } else { if (del_buf) { /* Free all internal variables and reset option values, to make * ":bdel" compatible with Vim 5.7. */ free_buffer_stuff(buf, TRUE); /* Make it look like a new buffer. */ buf->b_flags = BF_CHECK_RO | BF_NEVERLOADED; /* Init the options when loaded again. */ buf->b_p_initialized = FALSE; } buf_clear_file(buf); if (del_buf) buf->b_p_bl = FALSE; } } /* * Make buffer not contain a file. */ void buf_clear_file(buf_T *buf) { buf->b_ml.ml_line_count = 1; unchanged(buf, TRUE); buf->b_shortname = FALSE; buf->b_p_eol = TRUE; buf->b_start_eol = TRUE; #ifdef FEAT_MBYTE buf->b_p_bomb = FALSE; buf->b_start_bomb = FALSE; #endif buf->b_ml.ml_mfp = NULL; buf->b_ml.ml_flags = ML_EMPTY; /* empty buffer */ #ifdef FEAT_NETBEANS_INTG netbeans_deleted_all_lines(buf); #endif } /* * buf_freeall() - free all things allocated for a buffer that are related to * the file. Careful: get here with "curwin" NULL when exiting. * flags: * BFA_DEL buffer is going to be deleted * BFA_WIPE buffer is going to be wiped out * BFA_KEEP_UNDO do not free undo information */ void buf_freeall(buf_T *buf, int flags) { int is_curbuf = (buf == curbuf); bufref_T bufref; int is_curwin = (curwin != NULL && curwin->w_buffer == buf); win_T *the_curwin = curwin; tabpage_T *the_curtab = curtab; /* Make sure the buffer isn't closed by autocommands. */ ++buf->b_locked; set_bufref(&bufref, buf); if (buf->b_ml.ml_mfp != NULL) { if (apply_autocmds(EVENT_BUFUNLOAD, buf->b_fname, buf->b_fname, FALSE, buf) && !bufref_valid(&bufref)) /* autocommands deleted the buffer */ return; } if ((flags & BFA_DEL) && buf->b_p_bl) { if (apply_autocmds(EVENT_BUFDELETE, buf->b_fname, buf->b_fname, FALSE, buf) && !bufref_valid(&bufref)) /* autocommands deleted the buffer */ return; } if (flags & BFA_WIPE) { if (apply_autocmds(EVENT_BUFWIPEOUT, buf->b_fname, buf->b_fname, FALSE, buf) && !bufref_valid(&bufref)) /* autocommands deleted the buffer */ return; } --buf->b_locked; /* If the buffer was in curwin and the window has changed, go back to that * window, if it still exists. This avoids that ":edit x" triggering a * "tabnext" BufUnload autocmd leaves a window behind without a buffer. */ if (is_curwin && curwin != the_curwin && win_valid_any_tab(the_curwin)) { block_autocmds(); goto_tabpage_win(the_curtab, the_curwin); unblock_autocmds(); } #ifdef FEAT_EVAL if (aborting()) /* autocmds may abort script processing */ return; #endif /* * It's possible that autocommands change curbuf to the one being deleted. * This might cause curbuf to be deleted unexpectedly. But in some cases * it's OK to delete the curbuf, because a new one is obtained anyway. * Therefore only return if curbuf changed to the deleted buffer. */ if (buf == curbuf && !is_curbuf) return; #ifdef FEAT_DIFF diff_buf_delete(buf); /* Can't use 'diff' for unloaded buffer. */ #endif #ifdef FEAT_SYN_HL /* Remove any ownsyntax, unless exiting. */ if (curwin != NULL && curwin->w_buffer == buf) reset_synblock(curwin); #endif #ifdef FEAT_FOLDING /* No folds in an empty buffer. */ { win_T *win; tabpage_T *tp; FOR_ALL_TAB_WINDOWS(tp, win) if (win->w_buffer == buf) clearFolding(win); } #endif #ifdef FEAT_TCL tcl_buffer_free(buf); #endif ml_close(buf, TRUE); /* close and delete the memline/memfile */ buf->b_ml.ml_line_count = 0; /* no lines in buffer */ if ((flags & BFA_KEEP_UNDO) == 0) { u_blockfree(buf); /* free the memory allocated for undo */ u_clearall(buf); /* reset all undo information */ } #ifdef FEAT_SYN_HL syntax_clear(&buf->b_s); /* reset syntax info */ #endif #ifdef FEAT_TEXT_PROP clear_buf_prop_types(buf); #endif buf->b_flags &= ~BF_READERR; /* a read error is no longer relevant */ } /* * Free a buffer structure and the things it contains related to the buffer * itself (not the file, that must have been done already). */ static void free_buffer(buf_T *buf) { ++buf_free_count; free_buffer_stuff(buf, TRUE); #ifdef FEAT_EVAL /* b:changedtick uses an item in buf_T, remove it now */ dictitem_remove(buf->b_vars, (dictitem_T *)&buf->b_ct_di); unref_var_dict(buf->b_vars); #endif #ifdef FEAT_LUA lua_buffer_free(buf); #endif #ifdef FEAT_MZSCHEME mzscheme_buffer_free(buf); #endif #ifdef FEAT_PERL perl_buf_free(buf); #endif #ifdef FEAT_PYTHON python_buffer_free(buf); #endif #ifdef FEAT_PYTHON3 python3_buffer_free(buf); #endif #ifdef FEAT_RUBY ruby_buffer_free(buf); #endif #ifdef FEAT_JOB_CHANNEL channel_buffer_free(buf); #endif #ifdef FEAT_TERMINAL free_terminal(buf); #endif #ifdef FEAT_JOB_CHANNEL vim_free(buf->b_prompt_text); free_callback(buf->b_prompt_callback, buf->b_prompt_partial); #endif buf_hashtab_remove(buf); aubuflocal_remove(buf); if (autocmd_busy) { /* Do not free the buffer structure while autocommands are executing, * it's still needed. Free it when autocmd_busy is reset. */ buf->b_next = au_pending_free_buf; au_pending_free_buf = buf; } else vim_free(buf); } /* * Initializes b:changedtick. */ static void init_changedtick(buf_T *buf) { dictitem_T *di = (dictitem_T *)&buf->b_ct_di; di->di_flags = DI_FLAGS_FIX | DI_FLAGS_RO; di->di_tv.v_type = VAR_NUMBER; di->di_tv.v_lock = VAR_FIXED; di->di_tv.vval.v_number = 0; #ifdef FEAT_EVAL STRCPY(buf->b_ct_di.di_key, "changedtick"); (void)dict_add(buf->b_vars, di); #endif } /* * Free stuff in the buffer for ":bdel" and when wiping out the buffer. */ static void free_buffer_stuff( buf_T *buf, int free_options) /* free options as well */ { if (free_options) { clear_wininfo(buf); /* including window-local options */ free_buf_options(buf, TRUE); #ifdef FEAT_SPELL ga_clear(&buf->b_s.b_langp); #endif } #ifdef FEAT_EVAL { varnumber_T tick = CHANGEDTICK(buf); vars_clear(&buf->b_vars->dv_hashtab); /* free all buffer variables */ hash_init(&buf->b_vars->dv_hashtab); init_changedtick(buf); CHANGEDTICK(buf) = tick; } #endif #ifdef FEAT_USR_CMDS uc_clear(&buf->b_ucmds); /* clear local user commands */ #endif #ifdef FEAT_SIGNS buf_delete_signs(buf, (char_u *)"*"); // delete any signs */ #endif #ifdef FEAT_NETBEANS_INTG netbeans_file_killed(buf); #endif #ifdef FEAT_LOCALMAP map_clear_int(buf, MAP_ALL_MODES, TRUE, FALSE); /* clear local mappings */ map_clear_int(buf, MAP_ALL_MODES, TRUE, TRUE); /* clear local abbrevs */ #endif #ifdef FEAT_MBYTE VIM_CLEAR(buf->b_start_fenc); #endif } /* * Free the b_wininfo list for buffer "buf". */ static void clear_wininfo(buf_T *buf) { wininfo_T *wip; while (buf->b_wininfo != NULL) { wip = buf->b_wininfo; buf->b_wininfo = wip->wi_next; if (wip->wi_optset) { clear_winopt(&wip->wi_opt); #ifdef FEAT_FOLDING deleteFoldRecurse(&wip->wi_folds); #endif } vim_free(wip); } } /* * Go to another buffer. Handles the result of the ATTENTION dialog. */ void goto_buffer( exarg_T *eap, int start, int dir, int count) { #if defined(HAS_SWAP_EXISTS_ACTION) bufref_T old_curbuf; set_bufref(&old_curbuf, curbuf); swap_exists_action = SEA_DIALOG; #endif (void)do_buffer(*eap->cmd == 's' ? DOBUF_SPLIT : DOBUF_GOTO, start, dir, count, eap->forceit); #if defined(HAS_SWAP_EXISTS_ACTION) if (swap_exists_action == SEA_QUIT && *eap->cmd == 's') { # if defined(FEAT_EVAL) cleanup_T cs; /* Reset the error/interrupt/exception state here so that * aborting() returns FALSE when closing a window. */ enter_cleanup(&cs); # endif /* Quitting means closing the split window, nothing else. */ win_close(curwin, TRUE); swap_exists_action = SEA_NONE; swap_exists_did_quit = TRUE; # if defined(FEAT_EVAL) /* Restore the error/interrupt/exception state if not discarded by a * new aborting error, interrupt, or uncaught exception. */ leave_cleanup(&cs); # endif } else handle_swap_exists(&old_curbuf); #endif } #if defined(HAS_SWAP_EXISTS_ACTION) || defined(PROTO) /* * Handle the situation of swap_exists_action being set. * It is allowed for "old_curbuf" to be NULL or invalid. */ void handle_swap_exists(bufref_T *old_curbuf) { # if defined(FEAT_EVAL) cleanup_T cs; # endif # ifdef FEAT_SYN_HL long old_tw = curbuf->b_p_tw; # endif buf_T *buf; if (swap_exists_action == SEA_QUIT) { # if defined(FEAT_EVAL) /* Reset the error/interrupt/exception state here so that * aborting() returns FALSE when closing a buffer. */ enter_cleanup(&cs); # endif /* User selected Quit at ATTENTION prompt. Go back to previous * buffer. If that buffer is gone or the same as the current one, * open a new, empty buffer. */ swap_exists_action = SEA_NONE; /* don't want it again */ swap_exists_did_quit = TRUE; close_buffer(curwin, curbuf, DOBUF_UNLOAD, FALSE); if (old_curbuf == NULL || !bufref_valid(old_curbuf) || old_curbuf->br_buf == curbuf) buf = buflist_new(NULL, NULL, 1L, BLN_CURBUF | BLN_LISTED); else buf = old_curbuf->br_buf; if (buf != NULL) { int old_msg_silent = msg_silent; if (shortmess(SHM_FILEINFO)) msg_silent = 1; // prevent fileinfo message enter_buffer(buf); // restore msg_silent, so that the command line will be shown msg_silent = old_msg_silent; # ifdef FEAT_SYN_HL if (old_tw != curbuf->b_p_tw) check_colorcolumn(curwin); # endif } /* If "old_curbuf" is NULL we are in big trouble here... */ # if defined(FEAT_EVAL) /* Restore the error/interrupt/exception state if not discarded by a * new aborting error, interrupt, or uncaught exception. */ leave_cleanup(&cs); # endif } else if (swap_exists_action == SEA_RECOVER) { # if defined(FEAT_EVAL) /* Reset the error/interrupt/exception state here so that * aborting() returns FALSE when closing a buffer. */ enter_cleanup(&cs); # endif /* User selected Recover at ATTENTION prompt. */ msg_scroll = TRUE; ml_recover(); MSG_PUTS("\n"); /* don't overwrite the last message */ cmdline_row = msg_row; do_modelines(0); # if defined(FEAT_EVAL) /* Restore the error/interrupt/exception state if not discarded by a * new aborting error, interrupt, or uncaught exception. */ leave_cleanup(&cs); # endif } swap_exists_action = SEA_NONE; } #endif /* * do_bufdel() - delete or unload buffer(s) * * addr_count == 0: ":bdel" - delete current buffer * addr_count == 1: ":N bdel" or ":bdel N [N ..]" - first delete * buffer "end_bnr", then any other arguments. * addr_count == 2: ":N,N bdel" - delete buffers in range * * command can be DOBUF_UNLOAD (":bunload"), DOBUF_WIPE (":bwipeout") or * DOBUF_DEL (":bdel") * * Returns error message or NULL */ char_u * do_bufdel( int command, char_u *arg, /* pointer to extra arguments */ int addr_count, int start_bnr, /* first buffer number in a range */ int end_bnr, /* buffer nr or last buffer nr in a range */ int forceit) { int do_current = 0; /* delete current buffer? */ int deleted = 0; /* number of buffers deleted */ char_u *errormsg = NULL; /* return value */ int bnr; /* buffer number */ char_u *p; if (addr_count == 0) { (void)do_buffer(command, DOBUF_CURRENT, FORWARD, 0, forceit); } else { if (addr_count == 2) { if (*arg) /* both range and argument is not allowed */ return (char_u *)_(e_trailing); bnr = start_bnr; } else /* addr_count == 1 */ bnr = end_bnr; for ( ;!got_int; ui_breakcheck()) { /* * delete the current buffer last, otherwise when the * current buffer is deleted, the next buffer becomes * the current one and will be loaded, which may then * also be deleted, etc. */ if (bnr == curbuf->b_fnum) do_current = bnr; else if (do_buffer(command, DOBUF_FIRST, FORWARD, (int)bnr, forceit) == OK) ++deleted; /* * find next buffer number to delete/unload */ if (addr_count == 2) { if (++bnr > end_bnr) break; } else /* addr_count == 1 */ { arg = skipwhite(arg); if (*arg == NUL) break; if (!VIM_ISDIGIT(*arg)) { p = skiptowhite_esc(arg); bnr = buflist_findpat(arg, p, command == DOBUF_WIPE, FALSE, FALSE); if (bnr < 0) /* failed */ break; arg = p; } else bnr = getdigits(&arg); } } if (!got_int && do_current && do_buffer(command, DOBUF_FIRST, FORWARD, do_current, forceit) == OK) ++deleted; if (deleted == 0) { if (command == DOBUF_UNLOAD) STRCPY(IObuff, _("E515: No buffers were unloaded")); else if (command == DOBUF_DEL) STRCPY(IObuff, _("E516: No buffers were deleted")); else STRCPY(IObuff, _("E517: No buffers were wiped out")); errormsg = IObuff; } else if (deleted >= p_report) { if (command == DOBUF_UNLOAD) smsg((char_u *)NGETTEXT("%d buffer unloaded", "%d buffers unloaded", deleted), deleted); else if (command == DOBUF_DEL) smsg((char_u *)NGETTEXT("%d buffer deleted", "%d buffers deleted", deleted), deleted); else smsg((char_u *)NGETTEXT("%d buffer wiped out", "%d buffers wiped out", deleted), deleted); } } return errormsg; } /* * Make the current buffer empty. * Used when it is wiped out and it's the last buffer. */ static int empty_curbuf( int close_others, int forceit, int action) { int retval; buf_T *buf = curbuf; bufref_T bufref; if (action == DOBUF_UNLOAD) { EMSG(_("E90: Cannot unload last buffer")); return FAIL; } set_bufref(&bufref, buf); if (close_others) /* Close any other windows on this buffer, then make it empty. */ close_windows(buf, TRUE); setpcmark(); retval = do_ecmd(0, NULL, NULL, NULL, ECMD_ONE, forceit ? ECMD_FORCEIT : 0, curwin); /* * do_ecmd() may create a new buffer, then we have to delete * the old one. But do_ecmd() may have done that already, check * if the buffer still exists. */ if (buf != curbuf && bufref_valid(&bufref) && buf->b_nwindows == 0) close_buffer(NULL, buf, action, FALSE); if (!close_others) need_fileinfo = FALSE; return retval; } /* * Implementation of the commands for the buffer list. * * action == DOBUF_GOTO go to specified buffer * action == DOBUF_SPLIT split window and go to specified buffer * action == DOBUF_UNLOAD unload specified buffer(s) * action == DOBUF_DEL delete specified buffer(s) from buffer list * action == DOBUF_WIPE delete specified buffer(s) really * * start == DOBUF_CURRENT go to "count" buffer from current buffer * start == DOBUF_FIRST go to "count" buffer from first buffer * start == DOBUF_LAST go to "count" buffer from last buffer * start == DOBUF_MOD go to "count" modified buffer from current buffer * * Return FAIL or OK. */ int do_buffer( int action, int start, int dir, /* FORWARD or BACKWARD */ int count, /* buffer number or number of buffers */ int forceit) /* TRUE for :...! */ { buf_T *buf; buf_T *bp; int unload = (action == DOBUF_UNLOAD || action == DOBUF_DEL || action == DOBUF_WIPE); switch (start) { case DOBUF_FIRST: buf = firstbuf; break; case DOBUF_LAST: buf = lastbuf; break; default: buf = curbuf; break; } if (start == DOBUF_MOD) /* find next modified buffer */ { while (count-- > 0) { do { buf = buf->b_next; if (buf == NULL) buf = firstbuf; } while (buf != curbuf && !bufIsChanged(buf)); } if (!bufIsChanged(buf)) { EMSG(_("E84: No modified buffer found")); return FAIL; } } else if (start == DOBUF_FIRST && count) /* find specified buffer number */ { while (buf != NULL && buf->b_fnum != count) buf = buf->b_next; } else { bp = NULL; while (count > 0 || (!unload && !buf->b_p_bl && bp != buf)) { /* remember the buffer where we start, we come back there when all * buffers are unlisted. */ if (bp == NULL) bp = buf; if (dir == FORWARD) { buf = buf->b_next; if (buf == NULL) buf = firstbuf; } else { buf = buf->b_prev; if (buf == NULL) buf = lastbuf; } /* don't count unlisted buffers */ if (unload || buf->b_p_bl) { --count; bp = NULL; /* use this buffer as new starting point */ } if (bp == buf) { /* back where we started, didn't find anything. */ EMSG(_("E85: There is no listed buffer")); return FAIL; } } } if (buf == NULL) /* could not find it */ { if (start == DOBUF_FIRST) { /* don't warn when deleting */ if (!unload) EMSGN(_(e_nobufnr), count); } else if (dir == FORWARD) EMSG(_("E87: Cannot go beyond last buffer")); else EMSG(_("E88: Cannot go before first buffer")); return FAIL; } #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif /* * delete buffer buf from memory and/or the list */ if (unload) { int forward; bufref_T bufref; if (!can_unload_buffer(buf)) return FAIL; set_bufref(&bufref, buf); /* When unloading or deleting a buffer that's already unloaded and * unlisted: fail silently. */ if (action != DOBUF_WIPE && buf->b_ml.ml_mfp == NULL && !buf->b_p_bl) return FAIL; if (!forceit && bufIsChanged(buf)) { #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) if ((p_confirm || cmdmod.confirm) && p_write) { dialog_changed(buf, FALSE); if (!bufref_valid(&bufref)) /* Autocommand deleted buffer, oops! It's not changed * now. */ return FAIL; /* If it's still changed fail silently, the dialog already * mentioned why it fails. */ if (bufIsChanged(buf)) return FAIL; } else #endif { EMSGN(_("E89: No write since last change for buffer %ld (add ! to override)"), buf->b_fnum); return FAIL; } } /* When closing the current buffer stop Visual mode. */ if (buf == curbuf && VIsual_active) end_visual_mode(); /* * If deleting the last (listed) buffer, make it empty. * The last (listed) buffer cannot be unloaded. */ FOR_ALL_BUFFERS(bp) if (bp->b_p_bl && bp != buf) break; if (bp == NULL && buf == curbuf) return empty_curbuf(TRUE, forceit, action); /* * If the deleted buffer is the current one, close the current window * (unless it's the only window). Repeat this so long as we end up in * a window with this buffer. */ while (buf == curbuf && !(curwin->w_closing || curwin->w_buffer->b_locked > 0) && (!ONE_WINDOW || first_tabpage->tp_next != NULL)) { if (win_close(curwin, FALSE) == FAIL) break; } /* * If the buffer to be deleted is not the current one, delete it here. */ if (buf != curbuf) { close_windows(buf, FALSE); if (buf != curbuf && bufref_valid(&bufref) && buf->b_nwindows <= 0) close_buffer(NULL, buf, action, FALSE); return OK; } /* * Deleting the current buffer: Need to find another buffer to go to. * There should be another, otherwise it would have been handled * above. However, autocommands may have deleted all buffers. * First use au_new_curbuf.br_buf, if it is valid. * Then prefer the buffer we most recently visited. * Else try to find one that is loaded, after the current buffer, * then before the current buffer. * Finally use any buffer. */ buf = NULL; /* selected buffer */ bp = NULL; /* used when no loaded buffer found */ if (au_new_curbuf.br_buf != NULL && bufref_valid(&au_new_curbuf)) buf = au_new_curbuf.br_buf; #ifdef FEAT_JUMPLIST else if (curwin->w_jumplistlen > 0) { int jumpidx; jumpidx = curwin->w_jumplistidx - 1; if (jumpidx < 0) jumpidx = curwin->w_jumplistlen - 1; forward = jumpidx; while (jumpidx != curwin->w_jumplistidx) { buf = buflist_findnr(curwin->w_jumplist[jumpidx].fmark.fnum); if (buf != NULL) { if (buf == curbuf || !buf->b_p_bl) buf = NULL; /* skip current and unlisted bufs */ else if (buf->b_ml.ml_mfp == NULL) { /* skip unloaded buf, but may keep it for later */ if (bp == NULL) bp = buf; buf = NULL; } } if (buf != NULL) /* found a valid buffer: stop searching */ break; /* advance to older entry in jump list */ if (!jumpidx && curwin->w_jumplistidx == curwin->w_jumplistlen) break; if (--jumpidx < 0) jumpidx = curwin->w_jumplistlen - 1; if (jumpidx == forward) /* List exhausted for sure */ break; } } #endif if (buf == NULL) /* No previous buffer, Try 2'nd approach */ { forward = TRUE; buf = curbuf->b_next; for (;;) { if (buf == NULL) { if (!forward) /* tried both directions */ break; buf = curbuf->b_prev; forward = FALSE; continue; } /* in non-help buffer, try to skip help buffers, and vv */ if (buf->b_help == curbuf->b_help && buf->b_p_bl) { if (buf->b_ml.ml_mfp != NULL) /* found loaded buffer */ break; if (bp == NULL) /* remember unloaded buf for later */ bp = buf; } if (forward) buf = buf->b_next; else buf = buf->b_prev; } } if (buf == NULL) /* No loaded buffer, use unloaded one */ buf = bp; if (buf == NULL) /* No loaded buffer, find listed one */ { FOR_ALL_BUFFERS(buf) if (buf->b_p_bl && buf != curbuf) break; } if (buf == NULL) /* Still no buffer, just take one */ { if (curbuf->b_next != NULL) buf = curbuf->b_next; else buf = curbuf->b_prev; } } if (buf == NULL) { /* Autocommands must have wiped out all other buffers. Only option * now is to make the current buffer empty. */ return empty_curbuf(FALSE, forceit, action); } /* * make buf current buffer */ if (action == DOBUF_SPLIT) /* split window first */ { /* If 'switchbuf' contains "useopen": jump to first window containing * "buf" if one exists */ if ((swb_flags & SWB_USEOPEN) && buf_jump_open_win(buf)) return OK; /* If 'switchbuf' contains "usetab": jump to first window in any tab * page containing "buf" if one exists */ if ((swb_flags & SWB_USETAB) && buf_jump_open_tab(buf)) return OK; if (win_split(0, 0) == FAIL) return FAIL; } /* go to current buffer - nothing to do */ if (buf == curbuf) return OK; /* * Check if the current buffer may be abandoned. */ if (action == DOBUF_GOTO && !can_abandon(curbuf, forceit)) { #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) if ((p_confirm || cmdmod.confirm) && p_write) { bufref_T bufref; set_bufref(&bufref, buf); dialog_changed(curbuf, FALSE); if (!bufref_valid(&bufref)) /* Autocommand deleted buffer, oops! */ return FAIL; } if (bufIsChanged(curbuf)) #endif { no_write_message(); return FAIL; } } /* Go to the other buffer. */ set_curbuf(buf, action); if (action == DOBUF_SPLIT) { RESET_BINDING(curwin); /* reset 'scrollbind' and 'cursorbind' */ } #if defined(FEAT_EVAL) if (aborting()) /* autocmds may abort script processing */ return FAIL; #endif return OK; } /* * Set current buffer to "buf". Executes autocommands and closes current * buffer. "action" tells how to close the current buffer: * DOBUF_GOTO free or hide it * DOBUF_SPLIT nothing * DOBUF_UNLOAD unload it * DOBUF_DEL delete it * DOBUF_WIPE wipe it out */ void set_curbuf(buf_T *buf, int action) { buf_T *prevbuf; int unload = (action == DOBUF_UNLOAD || action == DOBUF_DEL || action == DOBUF_WIPE); #ifdef FEAT_SYN_HL long old_tw = curbuf->b_p_tw; #endif bufref_T newbufref; bufref_T prevbufref; setpcmark(); if (!cmdmod.keepalt) curwin->w_alt_fnum = curbuf->b_fnum; /* remember alternate file */ buflist_altfpos(curwin); /* remember curpos */ /* Don't restart Select mode after switching to another buffer. */ VIsual_reselect = FALSE; /* close_windows() or apply_autocmds() may change curbuf and wipe out "buf" */ prevbuf = curbuf; set_bufref(&prevbufref, prevbuf); set_bufref(&newbufref, buf); /* Autocommands may delete the curren buffer and/or the buffer we wan to go * to. In those cases don't close the buffer. */ if (!apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, FALSE, curbuf) || (bufref_valid(&prevbufref) && bufref_valid(&newbufref) #ifdef FEAT_EVAL && !aborting() #endif )) { #ifdef FEAT_SYN_HL if (prevbuf == curwin->w_buffer) reset_synblock(curwin); #endif if (unload) close_windows(prevbuf, FALSE); #if defined(FEAT_EVAL) if (bufref_valid(&prevbufref) && !aborting()) #else if (bufref_valid(&prevbufref)) #endif { win_T *previouswin = curwin; if (prevbuf == curbuf) u_sync(FALSE); close_buffer(prevbuf == curwin->w_buffer ? curwin : NULL, prevbuf, unload ? action : (action == DOBUF_GOTO && !buf_hide(prevbuf) && !bufIsChanged(prevbuf)) ? DOBUF_UNLOAD : 0, FALSE); if (curwin != previouswin && win_valid(previouswin)) /* autocommands changed curwin, Grr! */ curwin = previouswin; } } /* An autocommand may have deleted "buf", already entered it (e.g., when * it did ":bunload") or aborted the script processing. * If curwin->w_buffer is null, enter_buffer() will make it valid again */ if ((buf_valid(buf) && buf != curbuf #ifdef FEAT_EVAL && !aborting() #endif ) || curwin->w_buffer == NULL) { enter_buffer(buf); #ifdef FEAT_SYN_HL if (old_tw != curbuf->b_p_tw) check_colorcolumn(curwin); #endif } } /* * Enter a new current buffer. * Old curbuf must have been abandoned already! This also means "curbuf" may * be pointing to freed memory. */ void enter_buffer(buf_T *buf) { /* Copy buffer and window local option values. Not for a help buffer. */ buf_copy_options(buf, BCO_ENTER | BCO_NOHELP); if (!buf->b_help) get_winopts(buf); #ifdef FEAT_FOLDING else /* Remove all folds in the window. */ clearFolding(curwin); foldUpdateAll(curwin); /* update folds (later). */ #endif /* Get the buffer in the current window. */ curwin->w_buffer = buf; curbuf = buf; ++curbuf->b_nwindows; #ifdef FEAT_DIFF if (curwin->w_p_diff) diff_buf_add(curbuf); #endif #ifdef FEAT_SYN_HL curwin->w_s = &(curbuf->b_s); #endif /* Cursor on first line by default. */ curwin->w_cursor.lnum = 1; curwin->w_cursor.col = 0; #ifdef FEAT_VIRTUALEDIT curwin->w_cursor.coladd = 0; #endif curwin->w_set_curswant = TRUE; curwin->w_topline_was_set = FALSE; /* mark cursor position as being invalid */ curwin->w_valid = 0; buflist_setfpos(curbuf, curwin, curbuf->b_last_cursor.lnum, curbuf->b_last_cursor.col, TRUE); /* Make sure the buffer is loaded. */ if (curbuf->b_ml.ml_mfp == NULL) /* need to load the file */ { /* If there is no filetype, allow for detecting one. Esp. useful for * ":ball" used in a autocommand. If there already is a filetype we * might prefer to keep it. */ if (*curbuf->b_p_ft == NUL) did_filetype = FALSE; open_buffer(FALSE, NULL, 0); } else { if (!msg_silent) need_fileinfo = TRUE; /* display file info after redraw */ (void)buf_check_timestamp(curbuf, FALSE); /* check if file changed */ curwin->w_topline = 1; #ifdef FEAT_DIFF curwin->w_topfill = 0; #endif apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf); apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf); } /* If autocommands did not change the cursor position, restore cursor lnum * and possibly cursor col. */ if (curwin->w_cursor.lnum == 1 && inindent(0)) buflist_getfpos(); check_arg_idx(curwin); /* check for valid arg_idx */ #ifdef FEAT_TITLE maketitle(); #endif /* when autocmds didn't change it */ if (curwin->w_topline == 1 && !curwin->w_topline_was_set) scroll_cursor_halfway(FALSE); /* redisplay at correct position */ #ifdef FEAT_NETBEANS_INTG /* Send fileOpened event because we've changed buffers. */ netbeans_file_activated(curbuf); #endif /* Change directories when the 'acd' option is set. */ DO_AUTOCHDIR; #ifdef FEAT_KEYMAP if (curbuf->b_kmap_state & KEYMAP_INIT) (void)keymap_init(); #endif #ifdef FEAT_SPELL /* May need to set the spell language. Can only do this after the buffer * has been properly setup. */ if (!curbuf->b_help && curwin->w_p_spell && *curwin->w_s->b_p_spl != NUL) (void)did_set_spelllang(curwin); #endif #ifdef FEAT_VIMINFO curbuf->b_last_used = vim_time(); #endif redraw_later(NOT_VALID); } #if defined(FEAT_AUTOCHDIR) || defined(PROTO) /* * Change to the directory of the current buffer. * Don't do this while still starting up. */ void do_autochdir(void) { if ((starting == 0 || test_autochdir) && curbuf->b_ffname != NULL && vim_chdirfile(curbuf->b_ffname, "auto") == OK) shorten_fnames(TRUE); } #endif void no_write_message(void) { #ifdef FEAT_TERMINAL if (term_job_running(curbuf->b_term)) EMSG(_("E948: Job still running (add ! to end the job)")); else #endif EMSG(_("E37: No write since last change (add ! to override)")); } void no_write_message_nobang(buf_T *buf UNUSED) { #ifdef FEAT_TERMINAL if (term_job_running(buf->b_term)) EMSG(_("E948: Job still running")); else #endif EMSG(_("E37: No write since last change")); } /* * functions for dealing with the buffer list */ static int top_file_num = 1; /* highest file number */ /* * Return TRUE if the current buffer is empty, unnamed, unmodified and used in * only one window. That means it can be re-used. */ int curbuf_reusable(void) { return (curbuf != NULL && curbuf->b_ffname == NULL && curbuf->b_nwindows <= 1 && (curbuf->b_ml.ml_mfp == NULL || BUFEMPTY()) && !curbufIsChanged()); } /* * Add a file name to the buffer list. Return a pointer to the buffer. * If the same file name already exists return a pointer to that buffer. * If it does not exist, or if fname == NULL, a new entry is created. * If (flags & BLN_CURBUF) is TRUE, may use current buffer. * If (flags & BLN_LISTED) is TRUE, add new buffer to buffer list. * If (flags & BLN_DUMMY) is TRUE, don't count it as a real buffer. * If (flags & BLN_NEW) is TRUE, don't use an existing buffer. * If (flags & BLN_NOOPT) is TRUE, don't copy options from the current buffer * if the buffer already exists. * This is the ONLY way to create a new buffer. */ buf_T * buflist_new( char_u *ffname_arg, // full path of fname or relative char_u *sfname_arg, // short fname or NULL linenr_T lnum, // preferred cursor line int flags) // BLN_ defines { char_u *ffname = ffname_arg; char_u *sfname = sfname_arg; buf_T *buf; #ifdef UNIX stat_T st; #endif if (top_file_num == 1) hash_init(&buf_hashtab); fname_expand(curbuf, &ffname, &sfname); // will allocate ffname /* * If file name already exists in the list, update the entry. */ #ifdef UNIX /* On Unix we can use inode numbers when the file exists. Works better * for hard links. */ if (sfname == NULL || mch_stat((char *)sfname, &st) < 0) st.st_dev = (dev_T)-1; #endif if (ffname != NULL && !(flags & (BLN_DUMMY | BLN_NEW)) && (buf = #ifdef UNIX buflist_findname_stat(ffname, &st) #else buflist_findname(ffname) #endif ) != NULL) { vim_free(ffname); if (lnum != 0) buflist_setfpos(buf, curwin, lnum, (colnr_T)0, FALSE); if ((flags & BLN_NOOPT) == 0) /* copy the options now, if 'cpo' doesn't have 's' and not done * already */ buf_copy_options(buf, 0); if ((flags & BLN_LISTED) && !buf->b_p_bl) { bufref_T bufref; buf->b_p_bl = TRUE; set_bufref(&bufref, buf); if (!(flags & BLN_DUMMY)) { if (apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, buf) && !bufref_valid(&bufref)) return NULL; } } return buf; } /* * If the current buffer has no name and no contents, use the current * buffer. Otherwise: Need to allocate a new buffer structure. * * This is the ONLY place where a new buffer structure is allocated! * (A spell file buffer is allocated in spell.c, but that's not a normal * buffer.) */ buf = NULL; if ((flags & BLN_CURBUF) && curbuf_reusable()) { buf = curbuf; /* It's like this buffer is deleted. Watch out for autocommands that * change curbuf! If that happens, allocate a new buffer anyway. */ if (curbuf->b_p_bl) apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf); if (buf == curbuf) apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf); #ifdef FEAT_EVAL if (aborting()) /* autocmds may abort script processing */ return NULL; #endif if (buf == curbuf) { /* Make sure 'bufhidden' and 'buftype' are empty */ clear_string_option(&buf->b_p_bh); clear_string_option(&buf->b_p_bt); } } if (buf != curbuf || curbuf == NULL) { buf = (buf_T *)alloc_clear((unsigned)sizeof(buf_T)); if (buf == NULL) { vim_free(ffname); return NULL; } #ifdef FEAT_EVAL /* init b: variables */ buf->b_vars = dict_alloc(); if (buf->b_vars == NULL) { vim_free(ffname); vim_free(buf); return NULL; } init_var_dict(buf->b_vars, &buf->b_bufvar, VAR_SCOPE); #endif init_changedtick(buf); } if (ffname != NULL) { buf->b_ffname = ffname; buf->b_sfname = vim_strsave(sfname); } clear_wininfo(buf); buf->b_wininfo = (wininfo_T *)alloc_clear((unsigned)sizeof(wininfo_T)); if ((ffname != NULL && (buf->b_ffname == NULL || buf->b_sfname == NULL)) || buf->b_wininfo == NULL) { if (buf->b_sfname != buf->b_ffname) VIM_CLEAR(buf->b_sfname); else buf->b_sfname = NULL; VIM_CLEAR(buf->b_ffname); if (buf != curbuf) free_buffer(buf); return NULL; } if (buf == curbuf) { /* free all things allocated for this buffer */ buf_freeall(buf, 0); if (buf != curbuf) /* autocommands deleted the buffer! */ return NULL; #if defined(FEAT_EVAL) if (aborting()) /* autocmds may abort script processing */ return NULL; #endif free_buffer_stuff(buf, FALSE); /* delete local variables et al. */ /* Init the options. */ buf->b_p_initialized = FALSE; buf_copy_options(buf, BCO_ENTER); #ifdef FEAT_KEYMAP /* need to reload lmaps and set b:keymap_name */ curbuf->b_kmap_state |= KEYMAP_INIT; #endif } else { /* * put new buffer at the end of the buffer list */ buf->b_next = NULL; if (firstbuf == NULL) /* buffer list is empty */ { buf->b_prev = NULL; firstbuf = buf; } else /* append new buffer at end of list */ { lastbuf->b_next = buf; buf->b_prev = lastbuf; } lastbuf = buf; buf->b_fnum = top_file_num++; if (top_file_num < 0) /* wrap around (may cause duplicates) */ { EMSG(_("W14: Warning: List of file names overflow")); if (emsg_silent == 0) { out_flush(); ui_delay(3000L, TRUE); /* make sure it is noticed */ } top_file_num = 1; } buf_hashtab_add(buf); /* * Always copy the options from the current buffer. */ buf_copy_options(buf, BCO_ALWAYS); } buf->b_wininfo->wi_fpos.lnum = lnum; buf->b_wininfo->wi_win = curwin; #ifdef FEAT_SYN_HL hash_init(&buf->b_s.b_keywtab); hash_init(&buf->b_s.b_keywtab_ic); #endif buf->b_fname = buf->b_sfname; #ifdef UNIX if (st.st_dev == (dev_T)-1) buf->b_dev_valid = FALSE; else { buf->b_dev_valid = TRUE; buf->b_dev = st.st_dev; buf->b_ino = st.st_ino; } #endif buf->b_u_synced = TRUE; buf->b_flags = BF_CHECK_RO | BF_NEVERLOADED; if (flags & BLN_DUMMY) buf->b_flags |= BF_DUMMY; buf_clear_file(buf); clrallmarks(buf); /* clear marks */ fmarks_check_names(buf); /* check file marks for this file */ buf->b_p_bl = (flags & BLN_LISTED) ? TRUE : FALSE; /* init 'buflisted' */ if (!(flags & BLN_DUMMY)) { bufref_T bufref; /* Tricky: these autocommands may change the buffer list. They could * also split the window with re-using the one empty buffer. This may * result in unexpectedly losing the empty buffer. */ set_bufref(&bufref, buf); if (apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, buf) && !bufref_valid(&bufref)) return NULL; if (flags & BLN_LISTED) { if (apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, buf) && !bufref_valid(&bufref)) return NULL; } #ifdef FEAT_EVAL if (aborting()) /* autocmds may abort script processing */ return NULL; #endif } return buf; } /* * Free the memory for the options of a buffer. * If "free_p_ff" is TRUE also free 'fileformat', 'buftype' and * 'fileencoding'. */ void free_buf_options( buf_T *buf, int free_p_ff) { if (free_p_ff) { #ifdef FEAT_MBYTE clear_string_option(&buf->b_p_fenc); #endif clear_string_option(&buf->b_p_ff); clear_string_option(&buf->b_p_bh); clear_string_option(&buf->b_p_bt); } #ifdef FEAT_FIND_ID clear_string_option(&buf->b_p_def); clear_string_option(&buf->b_p_inc); # ifdef FEAT_EVAL clear_string_option(&buf->b_p_inex); # endif #endif #if defined(FEAT_CINDENT) && defined(FEAT_EVAL) clear_string_option(&buf->b_p_inde); clear_string_option(&buf->b_p_indk); #endif #if defined(FEAT_BEVAL) && defined(FEAT_EVAL) clear_string_option(&buf->b_p_bexpr); #endif #if defined(FEAT_CRYPT) clear_string_option(&buf->b_p_cm); #endif clear_string_option(&buf->b_p_fp); #if defined(FEAT_EVAL) clear_string_option(&buf->b_p_fex); #endif #ifdef FEAT_CRYPT clear_string_option(&buf->b_p_key); #endif clear_string_option(&buf->b_p_kp); clear_string_option(&buf->b_p_mps); clear_string_option(&buf->b_p_fo); clear_string_option(&buf->b_p_flp); clear_string_option(&buf->b_p_isk); #ifdef FEAT_VARTABS clear_string_option(&buf->b_p_vsts); if (buf->b_p_vsts_nopaste) vim_free(buf->b_p_vsts_nopaste); buf->b_p_vsts_nopaste = NULL; if (buf->b_p_vsts_array) vim_free(buf->b_p_vsts_array); buf->b_p_vsts_array = NULL; clear_string_option(&buf->b_p_vts); if (buf->b_p_vts_array) vim_free(buf->b_p_vts_array); buf->b_p_vts_array = NULL; #endif #ifdef FEAT_KEYMAP clear_string_option(&buf->b_p_keymap); keymap_clear(&buf->b_kmap_ga); ga_clear(&buf->b_kmap_ga); #endif #ifdef FEAT_COMMENTS clear_string_option(&buf->b_p_com); #endif #ifdef FEAT_FOLDING clear_string_option(&buf->b_p_cms); #endif clear_string_option(&buf->b_p_nf); #ifdef FEAT_SYN_HL clear_string_option(&buf->b_p_syn); clear_string_option(&buf->b_s.b_syn_isk); #endif #ifdef FEAT_SPELL clear_string_option(&buf->b_s.b_p_spc); clear_string_option(&buf->b_s.b_p_spf); vim_regfree(buf->b_s.b_cap_prog); buf->b_s.b_cap_prog = NULL; clear_string_option(&buf->b_s.b_p_spl); #endif #ifdef FEAT_SEARCHPATH clear_string_option(&buf->b_p_sua); #endif clear_string_option(&buf->b_p_ft); #ifdef FEAT_CINDENT clear_string_option(&buf->b_p_cink); clear_string_option(&buf->b_p_cino); #endif #if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT) clear_string_option(&buf->b_p_cinw); #endif #ifdef FEAT_INS_EXPAND clear_string_option(&buf->b_p_cpt); #endif #ifdef FEAT_COMPL_FUNC clear_string_option(&buf->b_p_cfu); clear_string_option(&buf->b_p_ofu); #endif #ifdef FEAT_QUICKFIX clear_string_option(&buf->b_p_gp); clear_string_option(&buf->b_p_mp); clear_string_option(&buf->b_p_efm); #endif clear_string_option(&buf->b_p_ep); clear_string_option(&buf->b_p_path); clear_string_option(&buf->b_p_tags); clear_string_option(&buf->b_p_tc); #ifdef FEAT_INS_EXPAND clear_string_option(&buf->b_p_dict); clear_string_option(&buf->b_p_tsr); #endif #ifdef FEAT_TEXTOBJ clear_string_option(&buf->b_p_qe); #endif buf->b_p_ar = -1; buf->b_p_ul = NO_LOCAL_UNDOLEVEL; #ifdef FEAT_LISP clear_string_option(&buf->b_p_lw); #endif clear_string_option(&buf->b_p_bkc); #ifdef FEAT_MBYTE clear_string_option(&buf->b_p_menc); #endif } /* * Get alternate file "n". * Set linenr to "lnum" or altfpos.lnum if "lnum" == 0. * Also set cursor column to altfpos.col if 'startofline' is not set. * if (options & GETF_SETMARK) call setpcmark() * if (options & GETF_ALT) we are jumping to an alternate file. * if (options & GETF_SWITCH) respect 'switchbuf' settings when jumping * * Return FAIL for failure, OK for success. */ int buflist_getfile( int n, linenr_T lnum, int options, int forceit) { buf_T *buf; win_T *wp = NULL; pos_T *fpos; colnr_T col; buf = buflist_findnr(n); if (buf == NULL) { if ((options & GETF_ALT) && n == 0) EMSG(_(e_noalt)); else EMSGN(_("E92: Buffer %ld not found"), n); return FAIL; } /* if alternate file is the current buffer, nothing to do */ if (buf == curbuf) return OK; if (text_locked()) { text_locked_msg(); return FAIL; } if (curbuf_locked()) return FAIL; /* altfpos may be changed by getfile(), get it now */ if (lnum == 0) { fpos = buflist_findfpos(buf); lnum = fpos->lnum; col = fpos->col; } else col = 0; if (options & GETF_SWITCH) { /* If 'switchbuf' contains "useopen": jump to first window containing * "buf" if one exists */ if (swb_flags & SWB_USEOPEN) wp = buf_jump_open_win(buf); /* If 'switchbuf' contains "usetab": jump to first window in any tab * page containing "buf" if one exists */ if (wp == NULL && (swb_flags & SWB_USETAB)) wp = buf_jump_open_tab(buf); /* If 'switchbuf' contains "split", "vsplit" or "newtab" and the * current buffer isn't empty: open new tab or window */ if (wp == NULL && (swb_flags & (SWB_VSPLIT | SWB_SPLIT | SWB_NEWTAB)) && !BUFEMPTY()) { if (swb_flags & SWB_NEWTAB) tabpage_new(); else if (win_split(0, (swb_flags & SWB_VSPLIT) ? WSP_VERT : 0) == FAIL) return FAIL; RESET_BINDING(curwin); } } ++RedrawingDisabled; if (GETFILE_SUCCESS(getfile(buf->b_fnum, NULL, NULL, (options & GETF_SETMARK), lnum, forceit))) { --RedrawingDisabled; /* cursor is at to BOL and w_cursor.lnum is checked due to getfile() */ if (!p_sol && col != 0) { curwin->w_cursor.col = col; check_cursor_col(); #ifdef FEAT_VIRTUALEDIT curwin->w_cursor.coladd = 0; #endif curwin->w_set_curswant = TRUE; } return OK; } --RedrawingDisabled; return FAIL; } /* * go to the last know line number for the current buffer */ void buflist_getfpos(void) { pos_T *fpos; fpos = buflist_findfpos(curbuf); curwin->w_cursor.lnum = fpos->lnum; check_cursor_lnum(); if (p_sol) curwin->w_cursor.col = 0; else { curwin->w_cursor.col = fpos->col; check_cursor_col(); #ifdef FEAT_VIRTUALEDIT curwin->w_cursor.coladd = 0; #endif curwin->w_set_curswant = TRUE; } } #if defined(FEAT_QUICKFIX) || defined(FEAT_EVAL) || defined(PROTO) /* * Find file in buffer list by name (it has to be for the current window). * Returns NULL if not found. */ buf_T * buflist_findname_exp(char_u *fname) { char_u *ffname; buf_T *buf = NULL; /* First make the name into a full path name */ ffname = FullName_save(fname, #ifdef UNIX TRUE /* force expansion, get rid of symbolic links */ #else FALSE #endif ); if (ffname != NULL) { buf = buflist_findname(ffname); vim_free(ffname); } return buf; } #endif /* * Find file in buffer list by name (it has to be for the current window). * "ffname" must have a full path. * Skips dummy buffers. * Returns NULL if not found. */ buf_T * buflist_findname(char_u *ffname) { #ifdef UNIX stat_T st; if (mch_stat((char *)ffname, &st) < 0) st.st_dev = (dev_T)-1; return buflist_findname_stat(ffname, &st); } /* * Same as buflist_findname(), but pass the stat structure to avoid getting it * twice for the same file. * Returns NULL if not found. */ static buf_T * buflist_findname_stat( char_u *ffname, stat_T *stp) { #endif buf_T *buf; /* Start at the last buffer, expect to find a match sooner. */ for (buf = lastbuf; buf != NULL; buf = buf->b_prev) if ((buf->b_flags & BF_DUMMY) == 0 && !otherfile_buf(buf, ffname #ifdef UNIX , stp #endif )) return buf; return NULL; } /* * Find file in buffer list by a regexp pattern. * Return fnum of the found buffer. * Return < 0 for error. */ int buflist_findpat( char_u *pattern, char_u *pattern_end, /* pointer to first char after pattern */ int unlisted, /* find unlisted buffers */ int diffmode UNUSED, /* find diff-mode buffers only */ int curtab_only) /* find buffers in current tab only */ { buf_T *buf; int match = -1; int find_listed; char_u *pat; char_u *patend; int attempt; char_u *p; int toggledollar; if (pattern_end == pattern + 1 && (*pattern == '%' || *pattern == '#')) { if (*pattern == '%') match = curbuf->b_fnum; else match = curwin->w_alt_fnum; #ifdef FEAT_DIFF if (diffmode && !diff_mode_buf(buflist_findnr(match))) match = -1; #endif } /* * Try four ways of matching a listed buffer: * attempt == 0: without '^' or '$' (at any position) * attempt == 1: with '^' at start (only at position 0) * attempt == 2: with '$' at end (only match at end) * attempt == 3: with '^' at start and '$' at end (only full match) * Repeat this for finding an unlisted buffer if there was no matching * listed buffer. */ else { pat = file_pat_to_reg_pat(pattern, pattern_end, NULL, FALSE); if (pat == NULL) return -1; patend = pat + STRLEN(pat) - 1; toggledollar = (patend > pat && *patend == '$'); /* First try finding a listed buffer. If not found and "unlisted" * is TRUE, try finding an unlisted buffer. */ find_listed = TRUE; for (;;) { for (attempt = 0; attempt <= 3; ++attempt) { regmatch_T regmatch; /* may add '^' and '$' */ if (toggledollar) *patend = (attempt < 2) ? NUL : '$'; /* add/remove '$' */ p = pat; if (*p == '^' && !(attempt & 1)) /* add/remove '^' */ ++p; regmatch.regprog = vim_regcomp(p, p_magic ? RE_MAGIC : 0); if (regmatch.regprog == NULL) { vim_free(pat); return -1; } for (buf = lastbuf; buf != NULL; buf = buf->b_prev) if (buf->b_p_bl == find_listed #ifdef FEAT_DIFF && (!diffmode || diff_mode_buf(buf)) #endif && buflist_match(&regmatch, buf, FALSE) != NULL) { if (curtab_only) { /* Ignore the match if the buffer is not open in * the current tab. */ win_T *wp; FOR_ALL_WINDOWS(wp) if (wp->w_buffer == buf) break; if (wp == NULL) continue; } if (match >= 0) /* already found a match */ { match = -2; break; } match = buf->b_fnum; /* remember first match */ } vim_regfree(regmatch.regprog); if (match >= 0) /* found one match */ break; } /* Only search for unlisted buffers if there was no match with * a listed buffer. */ if (!unlisted || !find_listed || match != -1) break; find_listed = FALSE; } vim_free(pat); } if (match == -2) EMSG2(_("E93: More than one match for %s"), pattern); else if (match < 0) EMSG2(_("E94: No matching buffer for %s"), pattern); return match; } #if defined(FEAT_CMDL_COMPL) || defined(PROTO) /* * Find all buffer names that match. * For command line expansion of ":buf" and ":sbuf". * Return OK if matches found, FAIL otherwise. */ int ExpandBufnames( char_u *pat, int *num_file, char_u ***file, int options) { int count = 0; buf_T *buf; int round; char_u *p; int attempt; char_u *patc; *num_file = 0; /* return values in case of FAIL */ *file = NULL; /* Make a copy of "pat" and change "^" to "\(^\|[\/]\)". */ if (*pat == '^') { patc = alloc((unsigned)STRLEN(pat) + 11); if (patc == NULL) return FAIL; STRCPY(patc, "\\(^\\|[\\/]\\)"); STRCPY(patc + 11, pat + 1); } else patc = pat; /* * attempt == 0: try match with '\<', match at start of word * attempt == 1: try match without '\<', match anywhere */ for (attempt = 0; attempt <= 1; ++attempt) { regmatch_T regmatch; if (attempt > 0 && patc == pat) break; /* there was no anchor, no need to try again */ regmatch.regprog = vim_regcomp(patc + attempt * 11, RE_MAGIC); if (regmatch.regprog == NULL) { if (patc != pat) vim_free(patc); return FAIL; } /* * round == 1: Count the matches. * round == 2: Build the array to keep the matches. */ for (round = 1; round <= 2; ++round) { count = 0; FOR_ALL_BUFFERS(buf) { if (!buf->b_p_bl) /* skip unlisted buffers */ continue; p = buflist_match(&regmatch, buf, p_wic); if (p != NULL) { if (round == 1) ++count; else { if (options & WILD_HOME_REPLACE) p = home_replace_save(buf, p); else p = vim_strsave(p); (*file)[count++] = p; } } } if (count == 0) /* no match found, break here */ break; if (round == 1) { *file = (char_u **)alloc((unsigned)(count * sizeof(char_u *))); if (*file == NULL) { vim_regfree(regmatch.regprog); if (patc != pat) vim_free(patc); return FAIL; } } } vim_regfree(regmatch.regprog); if (count) /* match(es) found, break here */ break; } if (patc != pat) vim_free(patc); *num_file = count; return (count == 0 ? FAIL : OK); } #endif /* FEAT_CMDL_COMPL */ /* * Check for a match on the file name for buffer "buf" with regprog "prog". */ static char_u * buflist_match( regmatch_T *rmp, buf_T *buf, int ignore_case) /* when TRUE ignore case, when FALSE use 'fic' */ { char_u *match; /* First try the short file name, then the long file name. */ match = fname_match(rmp, buf->b_sfname, ignore_case); if (match == NULL) match = fname_match(rmp, buf->b_ffname, ignore_case); return match; } /* * Try matching the regexp in "prog" with file name "name". * Return "name" when there is a match, NULL when not. */ static char_u * fname_match( regmatch_T *rmp, char_u *name, int ignore_case) /* when TRUE ignore case, when FALSE use 'fic' */ { char_u *match = NULL; char_u *p; if (name != NULL) { /* Ignore case when 'fileignorecase' or the argument is set. */ rmp->rm_ic = p_fic || ignore_case; if (vim_regexec(rmp, name, (colnr_T)0)) match = name; else { /* Replace $(HOME) with '~' and try matching again. */ p = home_replace_save(NULL, name); if (p != NULL && vim_regexec(rmp, p, (colnr_T)0)) match = name; vim_free(p); } } return match; } /* * Find a file in the buffer list by buffer number. */ buf_T * buflist_findnr(int nr) { char_u key[VIM_SIZEOF_INT * 2 + 1]; hashitem_T *hi; if (nr == 0) nr = curwin->w_alt_fnum; sprintf((char *)key, "%x", nr); hi = hash_find(&buf_hashtab, key); if (!HASHITEM_EMPTY(hi)) return (buf_T *)(hi->hi_key - ((unsigned)(curbuf->b_key - (char_u *)curbuf))); return NULL; } /* * Get name of file 'n' in the buffer list. * When the file has no name an empty string is returned. * home_replace() is used to shorten the file name (used for marks). * Returns a pointer to allocated memory, of NULL when failed. */ char_u * buflist_nr2name( int n, int fullname, int helptail) /* for help buffers return tail only */ { buf_T *buf; buf = buflist_findnr(n); if (buf == NULL) return NULL; return home_replace_save(helptail ? buf : NULL, fullname ? buf->b_ffname : buf->b_fname); } /* * Set the "lnum" and "col" for the buffer "buf" and the current window. * When "copy_options" is TRUE save the local window option values. * When "lnum" is 0 only do the options. */ static void buflist_setfpos( buf_T *buf, win_T *win, linenr_T lnum, colnr_T col, int copy_options) { wininfo_T *wip; for (wip = buf->b_wininfo; wip != NULL; wip = wip->wi_next) if (wip->wi_win == win) break; if (wip == NULL) { /* allocate a new entry */ wip = (wininfo_T *)alloc_clear((unsigned)sizeof(wininfo_T)); if (wip == NULL) return; wip->wi_win = win; if (lnum == 0) /* set lnum even when it's 0 */ lnum = 1; } else { /* remove the entry from the list */ if (wip->wi_prev) wip->wi_prev->wi_next = wip->wi_next; else buf->b_wininfo = wip->wi_next; if (wip->wi_next) wip->wi_next->wi_prev = wip->wi_prev; if (copy_options && wip->wi_optset) { clear_winopt(&wip->wi_opt); #ifdef FEAT_FOLDING deleteFoldRecurse(&wip->wi_folds); #endif } } if (lnum != 0) { wip->wi_fpos.lnum = lnum; wip->wi_fpos.col = col; } if (copy_options) { /* Save the window-specific option values. */ copy_winopt(&win->w_onebuf_opt, &wip->wi_opt); #ifdef FEAT_FOLDING wip->wi_fold_manual = win->w_fold_manual; cloneFoldGrowArray(&win->w_folds, &wip->wi_folds); #endif wip->wi_optset = TRUE; } /* insert the entry in front of the list */ wip->wi_next = buf->b_wininfo; buf->b_wininfo = wip; wip->wi_prev = NULL; if (wip->wi_next) wip->wi_next->wi_prev = wip; return; } #ifdef FEAT_DIFF /* * Return TRUE when "wip" has 'diff' set and the diff is only for another tab * page. That's because a diff is local to a tab page. */ static int wininfo_other_tab_diff(wininfo_T *wip) { win_T *wp; if (wip->wi_opt.wo_diff) { FOR_ALL_WINDOWS(wp) /* return FALSE when it's a window in the current tab page, thus * the buffer was in diff mode here */ if (wip->wi_win == wp) return FALSE; return TRUE; } return FALSE; } #endif /* * Find info for the current window in buffer "buf". * If not found, return the info for the most recently used window. * When "skip_diff_buffer" is TRUE avoid windows with 'diff' set that is in * another tab page. * Returns NULL when there isn't any info. */ static wininfo_T * find_wininfo( buf_T *buf, int skip_diff_buffer UNUSED) { wininfo_T *wip; for (wip = buf->b_wininfo; wip != NULL; wip = wip->wi_next) if (wip->wi_win == curwin #ifdef FEAT_DIFF && (!skip_diff_buffer || !wininfo_other_tab_diff(wip)) #endif ) break; /* If no wininfo for curwin, use the first in the list (that doesn't have * 'diff' set and is in another tab page). */ if (wip == NULL) { #ifdef FEAT_DIFF if (skip_diff_buffer) { for (wip = buf->b_wininfo; wip != NULL; wip = wip->wi_next) if (!wininfo_other_tab_diff(wip)) break; } else #endif wip = buf->b_wininfo; } return wip; } /* * Reset the local window options to the values last used in this window. * If the buffer wasn't used in this window before, use the values from * the most recently used window. If the values were never set, use the * global values for the window. */ void get_winopts(buf_T *buf) { wininfo_T *wip; clear_winopt(&curwin->w_onebuf_opt); #ifdef FEAT_FOLDING clearFolding(curwin); #endif wip = find_wininfo(buf, TRUE); if (wip != NULL && wip->wi_win != NULL && wip->wi_win != curwin && wip->wi_win->w_buffer == buf) { /* The buffer is currently displayed in the window: use the actual * option values instead of the saved (possibly outdated) values. */ win_T *wp = wip->wi_win; copy_winopt(&wp->w_onebuf_opt, &curwin->w_onebuf_opt); #ifdef FEAT_FOLDING curwin->w_fold_manual = wp->w_fold_manual; curwin->w_foldinvalid = TRUE; cloneFoldGrowArray(&wp->w_folds, &curwin->w_folds); #endif } else if (wip != NULL && wip->wi_optset) { /* the buffer was displayed in the current window earlier */ copy_winopt(&wip->wi_opt, &curwin->w_onebuf_opt); #ifdef FEAT_FOLDING curwin->w_fold_manual = wip->wi_fold_manual; curwin->w_foldinvalid = TRUE; cloneFoldGrowArray(&wip->wi_folds, &curwin->w_folds); #endif } else copy_winopt(&curwin->w_allbuf_opt, &curwin->w_onebuf_opt); #ifdef FEAT_FOLDING /* Set 'foldlevel' to 'foldlevelstart' if it's not negative. */ if (p_fdls >= 0) curwin->w_p_fdl = p_fdls; #endif #ifdef FEAT_SYN_HL check_colorcolumn(curwin); #endif } /* * Find the position (lnum and col) for the buffer 'buf' for the current * window. * Returns a pointer to no_position if no position is found. */ pos_T * buflist_findfpos(buf_T *buf) { wininfo_T *wip; static pos_T no_position = INIT_POS_T(1, 0, 0); wip = find_wininfo(buf, FALSE); if (wip != NULL) return &(wip->wi_fpos); else return &no_position; } /* * Find the lnum for the buffer 'buf' for the current window. */ linenr_T buflist_findlnum(buf_T *buf) { return buflist_findfpos(buf)->lnum; } /* * List all known file names (for :files and :buffers command). */ void buflist_list(exarg_T *eap) { buf_T *buf; int len; int i; int ro_char; int changed_char; #ifdef FEAT_TERMINAL int job_running; int job_none_open; #endif for (buf = firstbuf; buf != NULL && !got_int; buf = buf->b_next) { #ifdef FEAT_TERMINAL job_running = term_job_running(buf->b_term); job_none_open = job_running && term_none_open(buf->b_term); #endif /* skip unlisted buffers, unless ! was used */ if ((!buf->b_p_bl && !eap->forceit && !vim_strchr(eap->arg, 'u')) || (vim_strchr(eap->arg, 'u') && buf->b_p_bl) || (vim_strchr(eap->arg, '+') && ((buf->b_flags & BF_READERR) || !bufIsChanged(buf))) || (vim_strchr(eap->arg, 'a') && (buf->b_ml.ml_mfp == NULL || buf->b_nwindows == 0)) || (vim_strchr(eap->arg, 'h') && (buf->b_ml.ml_mfp == NULL || buf->b_nwindows != 0)) #ifdef FEAT_TERMINAL || (vim_strchr(eap->arg, 'R') && (!job_running || (job_running && job_none_open))) || (vim_strchr(eap->arg, '?') && (!job_running || (job_running && !job_none_open))) || (vim_strchr(eap->arg, 'F') && (job_running || buf->b_term == NULL)) #endif || (vim_strchr(eap->arg, '-') && buf->b_p_ma) || (vim_strchr(eap->arg, '=') && !buf->b_p_ro) || (vim_strchr(eap->arg, 'x') && !(buf->b_flags & BF_READERR)) || (vim_strchr(eap->arg, '%') && buf != curbuf) || (vim_strchr(eap->arg, '#') && (buf == curbuf || curwin->w_alt_fnum != buf->b_fnum))) continue; if (buf_spname(buf) != NULL) vim_strncpy(NameBuff, buf_spname(buf), MAXPATHL - 1); else home_replace(buf, buf->b_fname, NameBuff, MAXPATHL, TRUE); if (message_filtered(NameBuff)) continue; changed_char = (buf->b_flags & BF_READERR) ? 'x' : (bufIsChanged(buf) ? '+' : ' '); #ifdef FEAT_TERMINAL if (term_job_running(buf->b_term)) { if (term_none_open(buf->b_term)) ro_char = '?'; else ro_char = 'R'; changed_char = ' '; /* bufIsChanged() returns TRUE to avoid * closing, but it's not actually changed. */ } else if (buf->b_term != NULL) ro_char = 'F'; else #endif ro_char = !buf->b_p_ma ? '-' : (buf->b_p_ro ? '=' : ' '); msg_putchar('\n'); len = vim_snprintf((char *)IObuff, IOSIZE - 20, "%3d%c%c%c%c%c \"%s\"", buf->b_fnum, buf->b_p_bl ? ' ' : 'u', buf == curbuf ? '%' : (curwin->w_alt_fnum == buf->b_fnum ? '#' : ' '), buf->b_ml.ml_mfp == NULL ? ' ' : (buf->b_nwindows == 0 ? 'h' : 'a'), ro_char, changed_char, NameBuff); if (len > IOSIZE - 20) len = IOSIZE - 20; /* put "line 999" in column 40 or after the file name */ i = 40 - vim_strsize(IObuff); do { IObuff[len++] = ' '; } while (--i > 0 && len < IOSIZE - 18); vim_snprintf((char *)IObuff + len, (size_t)(IOSIZE - len), _("line %ld"), buf == curbuf ? curwin->w_cursor.lnum : (long)buflist_findlnum(buf)); msg_outtrans(IObuff); out_flush(); /* output one line at a time */ ui_breakcheck(); } } /* * Get file name and line number for file 'fnum'. * Used by DoOneCmd() for translating '%' and '#'. * Used by insert_reg() and cmdline_paste() for '#' register. * Return FAIL if not found, OK for success. */ int buflist_name_nr( int fnum, char_u **fname, linenr_T *lnum) { buf_T *buf; buf = buflist_findnr(fnum); if (buf == NULL || buf->b_fname == NULL) return FAIL; *fname = buf->b_fname; *lnum = buflist_findlnum(buf); return OK; } /* * Set the file name for "buf"' to "ffname_arg", short file name to * "sfname_arg". * The file name with the full path is also remembered, for when :cd is used. * Returns FAIL for failure (file name already in use by other buffer) * OK otherwise. */ int setfname( buf_T *buf, char_u *ffname_arg, char_u *sfname_arg, int message) /* give message when buffer already exists */ { char_u *ffname = ffname_arg; char_u *sfname = sfname_arg; buf_T *obuf = NULL; #ifdef UNIX stat_T st; #endif if (ffname == NULL || *ffname == NUL) { /* Removing the name. */ if (buf->b_sfname != buf->b_ffname) VIM_CLEAR(buf->b_sfname); else buf->b_sfname = NULL; VIM_CLEAR(buf->b_ffname); #ifdef UNIX st.st_dev = (dev_T)-1; #endif } else { fname_expand(buf, &ffname, &sfname); /* will allocate ffname */ if (ffname == NULL) /* out of memory */ return FAIL; /* * if the file name is already used in another buffer: * - if the buffer is loaded, fail * - if the buffer is not loaded, delete it from the list */ #ifdef UNIX if (mch_stat((char *)ffname, &st) < 0) st.st_dev = (dev_T)-1; #endif if (!(buf->b_flags & BF_DUMMY)) #ifdef UNIX obuf = buflist_findname_stat(ffname, &st); #else obuf = buflist_findname(ffname); #endif if (obuf != NULL && obuf != buf) { if (obuf->b_ml.ml_mfp != NULL) /* it's loaded, fail */ { if (message) EMSG(_("E95: Buffer with this name already exists")); vim_free(ffname); return FAIL; } /* delete from the list */ close_buffer(NULL, obuf, DOBUF_WIPE, FALSE); } sfname = vim_strsave(sfname); if (ffname == NULL || sfname == NULL) { vim_free(sfname); vim_free(ffname); return FAIL; } #ifdef USE_FNAME_CASE # ifdef USE_LONG_FNAME if (USE_LONG_FNAME) # endif fname_case(sfname, 0); /* set correct case for short file name */ #endif if (buf->b_sfname != buf->b_ffname) vim_free(buf->b_sfname); vim_free(buf->b_ffname); buf->b_ffname = ffname; buf->b_sfname = sfname; } buf->b_fname = buf->b_sfname; #ifdef UNIX if (st.st_dev == (dev_T)-1) buf->b_dev_valid = FALSE; else { buf->b_dev_valid = TRUE; buf->b_dev = st.st_dev; buf->b_ino = st.st_ino; } #endif buf->b_shortname = FALSE; buf_name_changed(buf); return OK; } /* * Crude way of changing the name of a buffer. Use with care! * The name should be relative to the current directory. */ void buf_set_name(int fnum, char_u *name) { buf_T *buf; buf = buflist_findnr(fnum); if (buf != NULL) { if (buf->b_sfname != buf->b_ffname) vim_free(buf->b_sfname); vim_free(buf->b_ffname); buf->b_ffname = vim_strsave(name); buf->b_sfname = NULL; /* Allocate ffname and expand into full path. Also resolves .lnk * files on Win32. */ fname_expand(buf, &buf->b_ffname, &buf->b_sfname); buf->b_fname = buf->b_sfname; } } /* * Take care of what needs to be done when the name of buffer "buf" has * changed. */ void buf_name_changed(buf_T *buf) { /* * If the file name changed, also change the name of the swapfile */ if (buf->b_ml.ml_mfp != NULL) ml_setname(buf); if (curwin->w_buffer == buf) check_arg_idx(curwin); /* check file name for arg list */ #ifdef FEAT_TITLE maketitle(); /* set window title */ #endif status_redraw_all(); /* status lines need to be redrawn */ fmarks_check_names(buf); /* check named file marks */ ml_timestamp(buf); /* reset timestamp */ } /* * set alternate file name for current window * * Used by do_one_cmd(), do_write() and do_ecmd(). * Return the buffer. */ buf_T * setaltfname( char_u *ffname, char_u *sfname, linenr_T lnum) { buf_T *buf; /* Create a buffer. 'buflisted' is not set if it's a new buffer */ buf = buflist_new(ffname, sfname, lnum, 0); if (buf != NULL && !cmdmod.keepalt) curwin->w_alt_fnum = buf->b_fnum; return buf; } /* * Get alternate file name for current window. * Return NULL if there isn't any, and give error message if requested. */ char_u * getaltfname( int errmsg) /* give error message */ { char_u *fname; linenr_T dummy; if (buflist_name_nr(0, &fname, &dummy) == FAIL) { if (errmsg) EMSG(_(e_noalt)); return NULL; } return fname; } /* * Add a file name to the buflist and return its number. * Uses same flags as buflist_new(), except BLN_DUMMY. * * used by qf_init(), main() and doarglist() */ int buflist_add(char_u *fname, int flags) { buf_T *buf; buf = buflist_new(fname, NULL, (linenr_T)0, flags); if (buf != NULL) return buf->b_fnum; return 0; } #if defined(BACKSLASH_IN_FILENAME) || defined(PROTO) /* * Adjust slashes in file names. Called after 'shellslash' was set. */ void buflist_slash_adjust(void) { buf_T *bp; FOR_ALL_BUFFERS(bp) { if (bp->b_ffname != NULL) slash_adjust(bp->b_ffname); if (bp->b_sfname != NULL) slash_adjust(bp->b_sfname); } } #endif /* * Set alternate cursor position for the current buffer and window "win". * Also save the local window option values. */ void buflist_altfpos(win_T *win) { buflist_setfpos(curbuf, win, win->w_cursor.lnum, win->w_cursor.col, TRUE); } /* * Return TRUE if 'ffname' is not the same file as current file. * Fname must have a full path (expanded by mch_FullName()). */ int otherfile(char_u *ffname) { return otherfile_buf(curbuf, ffname #ifdef UNIX , NULL #endif ); } static int otherfile_buf( buf_T *buf, char_u *ffname #ifdef UNIX , stat_T *stp #endif ) { /* no name is different */ if (ffname == NULL || *ffname == NUL || buf->b_ffname == NULL) return TRUE; if (fnamecmp(ffname, buf->b_ffname) == 0) return FALSE; #ifdef UNIX { stat_T st; /* If no stat_T given, get it now */ if (stp == NULL) { if (!buf->b_dev_valid || mch_stat((char *)ffname, &st) < 0) st.st_dev = (dev_T)-1; stp = &st; } /* Use dev/ino to check if the files are the same, even when the names * are different (possible with links). Still need to compare the * name above, for when the file doesn't exist yet. * Problem: The dev/ino changes when a file is deleted (and created * again) and remains the same when renamed/moved. We don't want to * mch_stat() each buffer each time, that would be too slow. Get the * dev/ino again when they appear to match, but not when they appear * to be different: Could skip a buffer when it's actually the same * file. */ if (buf_same_ino(buf, stp)) { buf_setino(buf); if (buf_same_ino(buf, stp)) return FALSE; } } #endif return TRUE; } #if defined(UNIX) || defined(PROTO) /* * Set inode and device number for a buffer. * Must always be called when b_fname is changed!. */ void buf_setino(buf_T *buf) { stat_T st; if (buf->b_fname != NULL && mch_stat((char *)buf->b_fname, &st) >= 0) { buf->b_dev_valid = TRUE; buf->b_dev = st.st_dev; buf->b_ino = st.st_ino; } else buf->b_dev_valid = FALSE; } /* * Return TRUE if dev/ino in buffer "buf" matches with "stp". */ static int buf_same_ino( buf_T *buf, stat_T *stp) { return (buf->b_dev_valid && stp->st_dev == buf->b_dev && stp->st_ino == buf->b_ino); } #endif /* * Print info about the current buffer. */ void fileinfo( int fullname, /* when non-zero print full path */ int shorthelp, int dont_truncate) { char_u *name; int n; char_u *p; char_u *buffer; size_t len; buffer = alloc(IOSIZE); if (buffer == NULL) return; if (fullname > 1) /* 2 CTRL-G: include buffer number */ { vim_snprintf((char *)buffer, IOSIZE, "buf %d: ", curbuf->b_fnum); p = buffer + STRLEN(buffer); } else p = buffer; *p++ = '"'; if (buf_spname(curbuf) != NULL) vim_strncpy(p, buf_spname(curbuf), IOSIZE - (p - buffer) - 1); else { if (!fullname && curbuf->b_fname != NULL) name = curbuf->b_fname; else name = curbuf->b_ffname; home_replace(shorthelp ? curbuf : NULL, name, p, (int)(IOSIZE - (p - buffer)), TRUE); } vim_snprintf_add((char *)buffer, IOSIZE, "\"%s%s%s%s%s%s", curbufIsChanged() ? (shortmess(SHM_MOD) ? " [+]" : _(" [Modified]")) : " ", (curbuf->b_flags & BF_NOTEDITED) #ifdef FEAT_QUICKFIX && !bt_dontwrite(curbuf) #endif ? _("[Not edited]") : "", (curbuf->b_flags & BF_NEW) #ifdef FEAT_QUICKFIX && !bt_dontwrite(curbuf) #endif ? _("[New file]") : "", (curbuf->b_flags & BF_READERR) ? _("[Read errors]") : "", curbuf->b_p_ro ? (shortmess(SHM_RO) ? _("[RO]") : _("[readonly]")) : "", (curbufIsChanged() || (curbuf->b_flags & BF_WRITE_MASK) || curbuf->b_p_ro) ? " " : ""); /* With 32 bit longs and more than 21,474,836 lines multiplying by 100 * causes an overflow, thus for large numbers divide instead. */ if (curwin->w_cursor.lnum > 1000000L) n = (int)(((long)curwin->w_cursor.lnum) / ((long)curbuf->b_ml.ml_line_count / 100L)); else n = (int)(((long)curwin->w_cursor.lnum * 100L) / (long)curbuf->b_ml.ml_line_count); if (curbuf->b_ml.ml_flags & ML_EMPTY) vim_snprintf_add((char *)buffer, IOSIZE, "%s", _(no_lines_msg)); #ifdef FEAT_CMDL_INFO else if (p_ru) /* Current line and column are already on the screen -- webb */ vim_snprintf_add((char *)buffer, IOSIZE, NGETTEXT("%ld line --%d%%--", "%ld lines --%d%%--", curbuf->b_ml.ml_line_count), (long)curbuf->b_ml.ml_line_count, n); #endif else { vim_snprintf_add((char *)buffer, IOSIZE, _("line %ld of %ld --%d%%-- col "), (long)curwin->w_cursor.lnum, (long)curbuf->b_ml.ml_line_count, n); validate_virtcol(); len = STRLEN(buffer); col_print(buffer + len, IOSIZE - len, (int)curwin->w_cursor.col + 1, (int)curwin->w_virtcol + 1); } (void)append_arg_number(curwin, buffer, IOSIZE, !shortmess(SHM_FILE)); if (dont_truncate) { /* Temporarily set msg_scroll to avoid the message being truncated. * First call msg_start() to get the message in the right place. */ msg_start(); n = msg_scroll; msg_scroll = TRUE; msg(buffer); msg_scroll = n; } else { p = msg_trunc_attr(buffer, FALSE, 0); if (restart_edit != 0 || (msg_scrolled && !need_wait_return)) /* Need to repeat the message after redrawing when: * - When restart_edit is set (otherwise there will be a delay * before redrawing). * - When the screen was scrolled but there is no wait-return * prompt. */ set_keep_msg(p, 0); } vim_free(buffer); } void col_print( char_u *buf, size_t buflen, int col, int vcol) { if (col == vcol) vim_snprintf((char *)buf, buflen, "%d", col); else vim_snprintf((char *)buf, buflen, "%d-%d", col, vcol); } #if defined(FEAT_TITLE) || defined(PROTO) static char_u *lasttitle = NULL; static char_u *lasticon = NULL; /* * Put the file name in the title bar and icon of the window. */ void maketitle(void) { char_u *p; char_u *title_str = NULL; char_u *icon_str = NULL; int maxlen = 0; int len; int mustset; char_u buf[IOSIZE]; int off; if (!redrawing()) { /* Postpone updating the title when 'lazyredraw' is set. */ need_maketitle = TRUE; return; } need_maketitle = FALSE; if (!p_title && !p_icon && lasttitle == NULL && lasticon == NULL) return; // nothing to do if (p_title) { if (p_titlelen > 0) { maxlen = p_titlelen * Columns / 100; if (maxlen < 10) maxlen = 10; } title_str = buf; if (*p_titlestring != NUL) { #ifdef FEAT_STL_OPT if (stl_syntax & STL_IN_TITLE) { int use_sandbox = FALSE; int save_called_emsg = called_emsg; # ifdef FEAT_EVAL use_sandbox = was_set_insecurely((char_u *)"titlestring", 0); # endif called_emsg = FALSE; build_stl_str_hl(curwin, title_str, sizeof(buf), p_titlestring, use_sandbox, 0, maxlen, NULL, NULL); if (called_emsg) set_string_option_direct((char_u *)"titlestring", -1, (char_u *)"", OPT_FREE, SID_ERROR); called_emsg |= save_called_emsg; } else #endif title_str = p_titlestring; } else { /* format: "fname + (path) (1 of 2) - VIM" */ #define SPACE_FOR_FNAME (IOSIZE - 100) #define SPACE_FOR_DIR (IOSIZE - 20) #define SPACE_FOR_ARGNR (IOSIZE - 10) /* at least room for " - VIM" */ if (curbuf->b_fname == NULL) vim_strncpy(buf, (char_u *)_("[No Name]"), SPACE_FOR_FNAME); #ifdef FEAT_TERMINAL else if (curbuf->b_term != NULL) { vim_strncpy(buf, term_get_status_text(curbuf->b_term), SPACE_FOR_FNAME); } #endif else { p = transstr(gettail(curbuf->b_fname)); vim_strncpy(buf, p, SPACE_FOR_FNAME); vim_free(p); } #ifdef FEAT_TERMINAL if (curbuf->b_term == NULL) #endif switch (bufIsChanged(curbuf) + (curbuf->b_p_ro * 2) + (!curbuf->b_p_ma * 4)) { case 1: STRCAT(buf, " +"); break; case 2: STRCAT(buf, " ="); break; case 3: STRCAT(buf, " =+"); break; case 4: case 6: STRCAT(buf, " -"); break; case 5: case 7: STRCAT(buf, " -+"); break; } if (curbuf->b_fname != NULL #ifdef FEAT_TERMINAL && curbuf->b_term == NULL #endif ) { /* Get path of file, replace home dir with ~ */ off = (int)STRLEN(buf); buf[off++] = ' '; buf[off++] = '('; home_replace(curbuf, curbuf->b_ffname, buf + off, SPACE_FOR_DIR - off, TRUE); #ifdef BACKSLASH_IN_FILENAME /* avoid "c:/name" to be reduced to "c" */ if (isalpha(buf[off]) && buf[off + 1] == ':') off += 2; #endif /* remove the file name */ p = gettail_sep(buf + off); if (p == buf + off) { /* must be a help buffer */ vim_strncpy(buf + off, (char_u *)_("help"), (size_t)(SPACE_FOR_DIR - off - 1)); } else *p = NUL; /* Translate unprintable chars and concatenate. Keep some * room for the server name. When there is no room (very long * file name) use (...). */ if (off < SPACE_FOR_DIR) { p = transstr(buf + off); vim_strncpy(buf + off, p, (size_t)(SPACE_FOR_DIR - off)); vim_free(p); } else { vim_strncpy(buf + off, (char_u *)"...", (size_t)(SPACE_FOR_ARGNR - off)); } STRCAT(buf, ")"); } append_arg_number(curwin, buf, SPACE_FOR_ARGNR, FALSE); #if defined(FEAT_CLIENTSERVER) if (serverName != NULL) { STRCAT(buf, " - "); vim_strcat(buf, serverName, IOSIZE); } else #endif STRCAT(buf, " - VIM"); if (maxlen > 0) { /* make it shorter by removing a bit in the middle */ if (vim_strsize(buf) > maxlen) trunc_string(buf, buf, maxlen, IOSIZE); } } } mustset = value_changed(title_str, &lasttitle); if (p_icon) { icon_str = buf; if (*p_iconstring != NUL) { #ifdef FEAT_STL_OPT if (stl_syntax & STL_IN_ICON) { int use_sandbox = FALSE; int save_called_emsg = called_emsg; # ifdef FEAT_EVAL use_sandbox = was_set_insecurely((char_u *)"iconstring", 0); # endif called_emsg = FALSE; build_stl_str_hl(curwin, icon_str, sizeof(buf), p_iconstring, use_sandbox, 0, 0, NULL, NULL); if (called_emsg) set_string_option_direct((char_u *)"iconstring", -1, (char_u *)"", OPT_FREE, SID_ERROR); called_emsg |= save_called_emsg; } else #endif icon_str = p_iconstring; } else { if (buf_spname(curbuf) != NULL) p = buf_spname(curbuf); else /* use file name only in icon */ p = gettail(curbuf->b_ffname); *icon_str = NUL; /* Truncate name at 100 bytes. */ len = (int)STRLEN(p); if (len > 100) { len -= 100; #ifdef FEAT_MBYTE if (has_mbyte) len += (*mb_tail_off)(p, p + len) + 1; #endif p += len; } STRCPY(icon_str, p); trans_characters(icon_str, IOSIZE); } } mustset |= value_changed(icon_str, &lasticon); if (mustset) resettitle(); } /* * Used for title and icon: Check if "str" differs from "*last". Set "*last" * from "str" if it does. * Return TRUE if resettitle() is to be called. */ static int value_changed(char_u *str, char_u **last) { if ((str == NULL) != (*last == NULL) || (str != NULL && *last != NULL && STRCMP(str, *last) != 0)) { vim_free(*last); if (str == NULL) { *last = NULL; mch_restore_title( last == &lasttitle ? SAVE_RESTORE_TITLE : SAVE_RESTORE_ICON); } else { *last = vim_strsave(str); return TRUE; } } return FALSE; } /* * Put current window title back (used after calling a shell) */ void resettitle(void) { mch_settitle(lasttitle, lasticon); } # if defined(EXITFREE) || defined(PROTO) void free_titles(void) { vim_free(lasttitle); vim_free(lasticon); } # endif #endif /* FEAT_TITLE */ #if defined(FEAT_STL_OPT) || defined(FEAT_GUI_TABLINE) || defined(PROTO) /* * Build a string from the status line items in "fmt". * Return length of string in screen cells. * * Normally works for window "wp", except when working for 'tabline' then it * is "curwin". * * Items are drawn interspersed with the text that surrounds it * Specials: %-<wid>(xxx%) => group, %= => middle marker, %< => truncation * Item: %-<minwid>.<maxwid><itemch> All but <itemch> are optional * * If maxwidth is not zero, the string will be filled at any middle marker * or truncated if too long, fillchar is used for all whitespace. */ int build_stl_str_hl( win_T *wp, char_u *out, /* buffer to write into != NameBuff */ size_t outlen, /* length of out[] */ char_u *fmt, int use_sandbox UNUSED, /* "fmt" was set insecurely, use sandbox */ int fillchar, int maxwidth, struct stl_hlrec *hltab, /* return: HL attributes (can be NULL) */ struct stl_hlrec *tabtab) /* return: tab page nrs (can be NULL) */ { char_u *p; char_u *s; char_u *t; int byteval; #ifdef FEAT_EVAL win_T *save_curwin; buf_T *save_curbuf; #endif int empty_line; colnr_T virtcol; long l; long n; int prevchar_isflag; int prevchar_isitem; int itemisflag; int fillable; char_u *str; long num; int width; int itemcnt; int curitem; int group_end_userhl; int group_start_userhl; int groupitem[STL_MAX_ITEM]; int groupdepth; struct stl_item { char_u *start; int minwid; int maxwid; enum { Normal, Empty, Group, Middle, Highlight, TabPage, Trunc } type; } item[STL_MAX_ITEM]; int minwid; int maxwid; int zeropad; char_u base; char_u opt; #define TMPLEN 70 char_u tmp[TMPLEN]; char_u *usefmt = fmt; struct stl_hlrec *sp; int save_must_redraw = must_redraw; int save_redr_type = curwin->w_redr_type; #ifdef FEAT_EVAL /* * When the format starts with "%!" then evaluate it as an expression and * use the result as the actual format string. */ if (fmt[0] == '%' && fmt[1] == '!') { usefmt = eval_to_string_safe(fmt + 2, NULL, use_sandbox); if (usefmt == NULL) usefmt = fmt; } #endif if (fillchar == 0) fillchar = ' '; #ifdef FEAT_MBYTE /* Can't handle a multi-byte fill character yet. */ else if (mb_char2len(fillchar) > 1) fillchar = '-'; #endif /* Get line & check if empty (cursorpos will show "0-1"). Note that * p will become invalid when getting another buffer line. */ p = ml_get_buf(wp->w_buffer, wp->w_cursor.lnum, FALSE); empty_line = (*p == NUL); /* Get the byte value now, in case we need it below. This is more * efficient than making a copy of the line. */ if (wp->w_cursor.col > (colnr_T)STRLEN(p)) byteval = 0; else #ifdef FEAT_MBYTE byteval = (*mb_ptr2char)(p + wp->w_cursor.col); #else byteval = p[wp->w_cursor.col]; #endif groupdepth = 0; p = out; curitem = 0; prevchar_isflag = TRUE; prevchar_isitem = FALSE; for (s = usefmt; *s; ) { if (curitem == STL_MAX_ITEM) { /* There are too many items. Add the error code to the statusline * to give the user a hint about what went wrong. */ if (p + 6 < out + outlen) { mch_memmove(p, " E541", (size_t)5); p += 5; } break; } if (*s != NUL && *s != '%') prevchar_isflag = prevchar_isitem = FALSE; /* * Handle up to the next '%' or the end. */ while (*s != NUL && *s != '%' && p + 1 < out + outlen) *p++ = *s++; if (*s == NUL || p + 1 >= out + outlen) break; /* * Handle one '%' item. */ s++; if (*s == NUL) /* ignore trailing % */ break; if (*s == '%') { if (p + 1 >= out + outlen) break; *p++ = *s++; prevchar_isflag = prevchar_isitem = FALSE; continue; } if (*s == STL_MIDDLEMARK) { s++; if (groupdepth > 0) continue; item[curitem].type = Middle; item[curitem++].start = p; continue; } if (*s == STL_TRUNCMARK) { s++; item[curitem].type = Trunc; item[curitem++].start = p; continue; } if (*s == ')') { s++; if (groupdepth < 1) continue; groupdepth--; t = item[groupitem[groupdepth]].start; *p = NUL; l = vim_strsize(t); if (curitem > groupitem[groupdepth] + 1 && item[groupitem[groupdepth]].minwid == 0) { /* remove group if all items are empty and highlight group * doesn't change */ group_start_userhl = group_end_userhl = 0; for (n = groupitem[groupdepth] - 1; n >= 0; n--) { if (item[n].type == Highlight) { group_start_userhl = group_end_userhl = item[n].minwid; break; } } for (n = groupitem[groupdepth] + 1; n < curitem; n++) { if (item[n].type == Normal) break; if (item[n].type == Highlight) group_end_userhl = item[n].minwid; } if (n == curitem && group_start_userhl == group_end_userhl) { p = t; l = 0; } } if (l > item[groupitem[groupdepth]].maxwid) { /* truncate, remove n bytes of text at the start */ #ifdef FEAT_MBYTE if (has_mbyte) { /* Find the first character that should be included. */ n = 0; while (l >= item[groupitem[groupdepth]].maxwid) { l -= ptr2cells(t + n); n += (*mb_ptr2len)(t + n); } } else #endif n = (long)(p - t) - item[groupitem[groupdepth]].maxwid + 1; *t = '<'; mch_memmove(t + 1, t + n, (size_t)(p - (t + n))); p = p - n + 1; #ifdef FEAT_MBYTE /* Fill up space left over by half a double-wide char. */ while (++l < item[groupitem[groupdepth]].minwid) *p++ = fillchar; #endif /* correct the start of the items for the truncation */ for (l = groupitem[groupdepth] + 1; l < curitem; l++) { item[l].start -= n; if (item[l].start < t) item[l].start = t; } } else if (abs(item[groupitem[groupdepth]].minwid) > l) { /* fill */ n = item[groupitem[groupdepth]].minwid; if (n < 0) { /* fill by appending characters */ n = 0 - n; while (l++ < n && p + 1 < out + outlen) *p++ = fillchar; } else { /* fill by inserting characters */ mch_memmove(t + n - l, t, (size_t)(p - t)); l = n - l; if (p + l >= out + outlen) l = (long)((out + outlen) - p - 1); p += l; for (n = groupitem[groupdepth] + 1; n < curitem; n++) item[n].start += l; for ( ; l > 0; l--) *t++ = fillchar; } } continue; } minwid = 0; maxwid = 9999; zeropad = FALSE; l = 1; if (*s == '0') { s++; zeropad = TRUE; } if (*s == '-') { s++; l = -1; } if (VIM_ISDIGIT(*s)) { minwid = (int)getdigits(&s); if (minwid < 0) /* overflow */ minwid = 0; } if (*s == STL_USER_HL) { item[curitem].type = Highlight; item[curitem].start = p; item[curitem].minwid = minwid > 9 ? 1 : minwid; s++; curitem++; continue; } if (*s == STL_TABPAGENR || *s == STL_TABCLOSENR) { if (*s == STL_TABCLOSENR) { if (minwid == 0) { /* %X ends the close label, go back to the previously * define tab label nr. */ for (n = curitem - 1; n >= 0; --n) if (item[n].type == TabPage && item[n].minwid >= 0) { minwid = item[n].minwid; break; } } else /* close nrs are stored as negative values */ minwid = - minwid; } item[curitem].type = TabPage; item[curitem].start = p; item[curitem].minwid = minwid; s++; curitem++; continue; } if (*s == '.') { s++; if (VIM_ISDIGIT(*s)) { maxwid = (int)getdigits(&s); if (maxwid <= 0) /* overflow */ maxwid = 50; } } minwid = (minwid > 50 ? 50 : minwid) * l; if (*s == '(') { groupitem[groupdepth++] = curitem; item[curitem].type = Group; item[curitem].start = p; item[curitem].minwid = minwid; item[curitem].maxwid = maxwid; s++; curitem++; continue; } if (vim_strchr(STL_ALL, *s) == NULL) { s++; continue; } opt = *s++; /* OK - now for the real work */ base = 'D'; itemisflag = FALSE; fillable = TRUE; num = -1; str = NULL; switch (opt) { case STL_FILEPATH: case STL_FULLPATH: case STL_FILENAME: fillable = FALSE; /* don't change ' ' to fillchar */ if (buf_spname(wp->w_buffer) != NULL) vim_strncpy(NameBuff, buf_spname(wp->w_buffer), MAXPATHL - 1); else { t = (opt == STL_FULLPATH) ? wp->w_buffer->b_ffname : wp->w_buffer->b_fname; home_replace(wp->w_buffer, t, NameBuff, MAXPATHL, TRUE); } trans_characters(NameBuff, MAXPATHL); if (opt != STL_FILENAME) str = NameBuff; else str = gettail(NameBuff); break; case STL_VIM_EXPR: /* '{' */ itemisflag = TRUE; t = p; while (*s != '}' && *s != NUL && p + 1 < out + outlen) *p++ = *s++; if (*s != '}') /* missing '}' or out of space */ break; s++; *p = 0; p = t; #ifdef FEAT_EVAL vim_snprintf((char *)tmp, sizeof(tmp), "%d", curbuf->b_fnum); set_internal_string_var((char_u *)"g:actual_curbuf", tmp); save_curbuf = curbuf; save_curwin = curwin; curwin = wp; curbuf = wp->w_buffer; str = eval_to_string_safe(p, &t, use_sandbox); curwin = save_curwin; curbuf = save_curbuf; do_unlet((char_u *)"g:actual_curbuf", TRUE); if (str != NULL && *str != 0) { if (*skipdigits(str) == NUL) { num = atoi((char *)str); VIM_CLEAR(str); itemisflag = FALSE; } } #endif break; case STL_LINE: num = (wp->w_buffer->b_ml.ml_flags & ML_EMPTY) ? 0L : (long)(wp->w_cursor.lnum); break; case STL_NUMLINES: num = wp->w_buffer->b_ml.ml_line_count; break; case STL_COLUMN: num = !(State & INSERT) && empty_line ? 0 : (int)wp->w_cursor.col + 1; break; case STL_VIRTCOL: case STL_VIRTCOL_ALT: /* In list mode virtcol needs to be recomputed */ virtcol = wp->w_virtcol; if (wp->w_p_list && lcs_tab1 == NUL) { wp->w_p_list = FALSE; getvcol(wp, &wp->w_cursor, NULL, &virtcol, NULL); wp->w_p_list = TRUE; } ++virtcol; /* Don't display %V if it's the same as %c. */ if (opt == STL_VIRTCOL_ALT && (virtcol == (colnr_T)(!(State & INSERT) && empty_line ? 0 : (int)wp->w_cursor.col + 1))) break; num = (long)virtcol; break; case STL_PERCENTAGE: num = (int)(((long)wp->w_cursor.lnum * 100L) / (long)wp->w_buffer->b_ml.ml_line_count); break; case STL_ALTPERCENT: str = tmp; get_rel_pos(wp, str, TMPLEN); break; case STL_ARGLISTSTAT: fillable = FALSE; tmp[0] = 0; if (append_arg_number(wp, tmp, (int)sizeof(tmp), FALSE)) str = tmp; break; case STL_KEYMAP: fillable = FALSE; if (get_keymap_str(wp, (char_u *)"<%s>", tmp, TMPLEN)) str = tmp; break; case STL_PAGENUM: #if defined(FEAT_PRINTER) || defined(FEAT_GUI_TABLINE) num = printer_page_num; #else num = 0; #endif break; case STL_BUFNO: num = wp->w_buffer->b_fnum; break; case STL_OFFSET_X: base = 'X'; /* FALLTHROUGH */ case STL_OFFSET: #ifdef FEAT_BYTEOFF l = ml_find_line_or_offset(wp->w_buffer, wp->w_cursor.lnum, NULL); num = (wp->w_buffer->b_ml.ml_flags & ML_EMPTY) || l < 0 ? 0L : l + 1 + (!(State & INSERT) && empty_line ? 0 : (int)wp->w_cursor.col); #endif break; case STL_BYTEVAL_X: base = 'X'; /* FALLTHROUGH */ case STL_BYTEVAL: num = byteval; if (num == NL) num = 0; else if (num == CAR && get_fileformat(wp->w_buffer) == EOL_MAC) num = NL; break; case STL_ROFLAG: case STL_ROFLAG_ALT: itemisflag = TRUE; if (wp->w_buffer->b_p_ro) str = (char_u *)((opt == STL_ROFLAG_ALT) ? ",RO" : _("[RO]")); break; case STL_HELPFLAG: case STL_HELPFLAG_ALT: itemisflag = TRUE; if (wp->w_buffer->b_help) str = (char_u *)((opt == STL_HELPFLAG_ALT) ? ",HLP" : _("[Help]")); break; case STL_FILETYPE: if (*wp->w_buffer->b_p_ft != NUL && STRLEN(wp->w_buffer->b_p_ft) < TMPLEN - 3) { vim_snprintf((char *)tmp, sizeof(tmp), "[%s]", wp->w_buffer->b_p_ft); str = tmp; } break; case STL_FILETYPE_ALT: itemisflag = TRUE; if (*wp->w_buffer->b_p_ft != NUL && STRLEN(wp->w_buffer->b_p_ft) < TMPLEN - 2) { vim_snprintf((char *)tmp, sizeof(tmp), ",%s", wp->w_buffer->b_p_ft); for (t = tmp; *t != 0; t++) *t = TOUPPER_LOC(*t); str = tmp; } break; #if defined(FEAT_QUICKFIX) case STL_PREVIEWFLAG: case STL_PREVIEWFLAG_ALT: itemisflag = TRUE; if (wp->w_p_pvw) str = (char_u *)((opt == STL_PREVIEWFLAG_ALT) ? ",PRV" : _("[Preview]")); break; case STL_QUICKFIX: if (bt_quickfix(wp->w_buffer)) str = (char_u *)(wp->w_llist_ref ? _(msg_loclist) : _(msg_qflist)); break; #endif case STL_MODIFIED: case STL_MODIFIED_ALT: itemisflag = TRUE; switch ((opt == STL_MODIFIED_ALT) + bufIsChanged(wp->w_buffer) * 2 + (!wp->w_buffer->b_p_ma) * 4) { case 2: str = (char_u *)"[+]"; break; case 3: str = (char_u *)",+"; break; case 4: str = (char_u *)"[-]"; break; case 5: str = (char_u *)",-"; break; case 6: str = (char_u *)"[+-]"; break; case 7: str = (char_u *)",+-"; break; } break; case STL_HIGHLIGHT: t = s; while (*s != '#' && *s != NUL) ++s; if (*s == '#') { item[curitem].type = Highlight; item[curitem].start = p; item[curitem].minwid = -syn_namen2id(t, (int)(s - t)); curitem++; } if (*s != NUL) ++s; continue; } item[curitem].start = p; item[curitem].type = Normal; if (str != NULL && *str) { t = str; if (itemisflag) { if ((t[0] && t[1]) && ((!prevchar_isitem && *t == ',') || (prevchar_isflag && *t == ' '))) t++; prevchar_isflag = TRUE; } l = vim_strsize(t); if (l > 0) prevchar_isitem = TRUE; if (l > maxwid) { while (l >= maxwid) #ifdef FEAT_MBYTE if (has_mbyte) { l -= ptr2cells(t); t += (*mb_ptr2len)(t); } else #endif l -= byte2cells(*t++); if (p + 1 >= out + outlen) break; *p++ = '<'; } if (minwid > 0) { for (; l < minwid && p + 1 < out + outlen; l++) { /* Don't put a "-" in front of a digit. */ if (l + 1 == minwid && fillchar == '-' && VIM_ISDIGIT(*t)) *p++ = ' '; else *p++ = fillchar; } minwid = 0; } else minwid *= -1; while (*t && p + 1 < out + outlen) { *p++ = *t++; /* Change a space by fillchar, unless fillchar is '-' and a * digit follows. */ if (fillable && p[-1] == ' ' && (!VIM_ISDIGIT(*t) || fillchar != '-')) p[-1] = fillchar; } for (; l < minwid && p + 1 < out + outlen; l++) *p++ = fillchar; } else if (num >= 0) { int nbase = (base == 'D' ? 10 : (base == 'O' ? 8 : 16)); char_u nstr[20]; if (p + 20 >= out + outlen) break; /* not sufficient space */ prevchar_isitem = TRUE; t = nstr; if (opt == STL_VIRTCOL_ALT) { *t++ = '-'; minwid--; } *t++ = '%'; if (zeropad) *t++ = '0'; *t++ = '*'; *t++ = nbase == 16 ? base : (char_u)(nbase == 8 ? 'o' : 'd'); *t = 0; for (n = num, l = 1; n >= nbase; n /= nbase) l++; if (opt == STL_VIRTCOL_ALT) l++; if (l > maxwid) { l += 2; n = l - maxwid; while (l-- > maxwid) num /= nbase; *t++ = '>'; *t++ = '%'; *t = t[-3]; *++t = 0; vim_snprintf((char *)p, outlen - (p - out), (char *)nstr, 0, num, n); } else vim_snprintf((char *)p, outlen - (p - out), (char *)nstr, minwid, num); p += STRLEN(p); } else item[curitem].type = Empty; if (opt == STL_VIM_EXPR) vim_free(str); if (num >= 0 || (!itemisflag && str && *str)) prevchar_isflag = FALSE; /* Item not NULL, but not a flag */ curitem++; } *p = NUL; itemcnt = curitem; #ifdef FEAT_EVAL if (usefmt != fmt) vim_free(usefmt); #endif width = vim_strsize(out); if (maxwidth > 0 && width > maxwidth) { /* Result is too long, must truncate somewhere. */ l = 0; if (itemcnt == 0) s = out; else { for ( ; l < itemcnt; l++) if (item[l].type == Trunc) { /* Truncate at %< item. */ s = item[l].start; break; } if (l == itemcnt) { /* No %< item, truncate first item. */ s = item[0].start; l = 0; } } if (width - vim_strsize(s) >= maxwidth) { /* Truncation mark is beyond max length */ #ifdef FEAT_MBYTE if (has_mbyte) { s = out; width = 0; for (;;) { width += ptr2cells(s); if (width >= maxwidth) break; s += (*mb_ptr2len)(s); } /* Fill up for half a double-wide character. */ while (++width < maxwidth) *s++ = fillchar; } else #endif s = out + maxwidth - 1; for (l = 0; l < itemcnt; l++) if (item[l].start > s) break; itemcnt = l; *s++ = '>'; *s = 0; } else { #ifdef FEAT_MBYTE if (has_mbyte) { n = 0; while (width >= maxwidth) { width -= ptr2cells(s + n); n += (*mb_ptr2len)(s + n); } } else #endif n = width - maxwidth + 1; p = s + n; STRMOVE(s + 1, p); *s = '<'; /* Fill up for half a double-wide character. */ while (++width < maxwidth) { s = s + STRLEN(s); *s++ = fillchar; *s = NUL; } --n; /* count the '<' */ for (; l < itemcnt; l++) { if (item[l].start - n >= s) item[l].start -= n; else item[l].start = s; } } width = maxwidth; } else if (width < maxwidth && STRLEN(out) + maxwidth - width + 1 < outlen) { /* Apply STL_MIDDLE if any */ for (l = 0; l < itemcnt; l++) if (item[l].type == Middle) break; if (l < itemcnt) { p = item[l].start + maxwidth - width; STRMOVE(p, item[l].start); for (s = item[l].start; s < p; s++) *s = fillchar; for (l++; l < itemcnt; l++) item[l].start += maxwidth - width; width = maxwidth; } } /* Store the info about highlighting. */ if (hltab != NULL) { sp = hltab; for (l = 0; l < itemcnt; l++) { if (item[l].type == Highlight) { sp->start = item[l].start; sp->userhl = item[l].minwid; sp++; } } sp->start = NULL; sp->userhl = 0; } /* Store the info about tab pages labels. */ if (tabtab != NULL) { sp = tabtab; for (l = 0; l < itemcnt; l++) { if (item[l].type == TabPage) { sp->start = item[l].start; sp->userhl = item[l].minwid; sp++; } } sp->start = NULL; sp->userhl = 0; } /* When inside update_screen we do not want redrawing a stausline, ruler, * title, etc. to trigger another redraw, it may cause an endless loop. */ if (updating_screen) { must_redraw = save_must_redraw; curwin->w_redr_type = save_redr_type; } return width; } #endif /* FEAT_STL_OPT */ #if defined(FEAT_STL_OPT) || defined(FEAT_CMDL_INFO) \ || defined(FEAT_GUI_TABLINE) || defined(PROTO) /* * Get relative cursor position in window into "buf[buflen]", in the form 99%, * using "Top", "Bot" or "All" when appropriate. */ void get_rel_pos( win_T *wp, char_u *buf, int buflen) { long above; /* number of lines above window */ long below; /* number of lines below window */ if (buflen < 3) /* need at least 3 chars for writing */ return; above = wp->w_topline - 1; #ifdef FEAT_DIFF above += diff_check_fill(wp, wp->w_topline) - wp->w_topfill; if (wp->w_topline == 1 && wp->w_topfill >= 1) above = 0; /* All buffer lines are displayed and there is an * indication of filler lines, that can be considered * seeing all lines. */ #endif below = wp->w_buffer->b_ml.ml_line_count - wp->w_botline + 1; if (below <= 0) vim_strncpy(buf, (char_u *)(above == 0 ? _("All") : _("Bot")), (size_t)(buflen - 1)); else if (above <= 0) vim_strncpy(buf, (char_u *)_("Top"), (size_t)(buflen - 1)); else vim_snprintf((char *)buf, (size_t)buflen, "%2d%%", above > 1000000L ? (int)(above / ((above + below) / 100L)) : (int)(above * 100L / (above + below))); } #endif /* * Append (file 2 of 8) to "buf[buflen]", if editing more than one file. * Return TRUE if it was appended. */ static int append_arg_number( win_T *wp, char_u *buf, int buflen, int add_file) /* Add "file" before the arg number */ { char_u *p; if (ARGCOUNT <= 1) /* nothing to do */ return FALSE; p = buf + STRLEN(buf); /* go to the end of the buffer */ if (p - buf + 35 >= buflen) /* getting too long */ return FALSE; *p++ = ' '; *p++ = '('; if (add_file) { STRCPY(p, "file "); p += 5; } vim_snprintf((char *)p, (size_t)(buflen - (p - buf)), wp->w_arg_idx_invalid ? "(%d) of %d)" : "%d of %d)", wp->w_arg_idx + 1, ARGCOUNT); return TRUE; } /* * If fname is not a full path, make it a full path. * Returns pointer to allocated memory (NULL for failure). */ char_u * fix_fname(char_u *fname) { /* * Force expanding the path always for Unix, because symbolic links may * mess up the full path name, even though it starts with a '/'. * Also expand when there is ".." in the file name, try to remove it, * because "c:/src/../README" is equal to "c:/README". * Similarly "c:/src//file" is equal to "c:/src/file". * For MS-Windows also expand names like "longna~1" to "longname". */ #ifdef UNIX return FullName_save(fname, TRUE); #else if (!vim_isAbsName(fname) || strstr((char *)fname, "..") != NULL || strstr((char *)fname, "//") != NULL # ifdef BACKSLASH_IN_FILENAME || strstr((char *)fname, "\\\\") != NULL # endif # if defined(MSWIN) || vim_strchr(fname, '~') != NULL # endif ) return FullName_save(fname, FALSE); fname = vim_strsave(fname); # ifdef USE_FNAME_CASE # ifdef USE_LONG_FNAME if (USE_LONG_FNAME) # endif { if (fname != NULL) fname_case(fname, 0); /* set correct case for file name */ } # endif return fname; #endif } /* * Make "*ffname" a full file name, set "*sfname" to "*ffname" if not NULL. * "*ffname" becomes a pointer to allocated memory (or NULL). * When resolving a link both "*sfname" and "*ffname" will point to the same * allocated memory. * The "*ffname" and "*sfname" pointer values on call will not be freed. * Note that the resulting "*ffname" pointer should be considered not allocaed. */ void fname_expand( buf_T *buf UNUSED, char_u **ffname, char_u **sfname) { if (*ffname == NULL) // no file name given, nothing to do return; if (*sfname == NULL) // no short file name given, use ffname *sfname = *ffname; *ffname = fix_fname(*ffname); // expand to full path #ifdef FEAT_SHORTCUT if (!buf->b_p_bin) { char_u *rfname; // If the file name is a shortcut file, use the file it links to. rfname = mch_resolve_shortcut(*ffname); if (rfname != NULL) { vim_free(*ffname); *ffname = rfname; *sfname = rfname; } } #endif } /* * Get the file name for an argument list entry. */ char_u * alist_name(aentry_T *aep) { buf_T *bp; /* Use the name from the associated buffer if it exists. */ bp = buflist_findnr(aep->ae_fnum); if (bp == NULL || bp->b_fname == NULL) return aep->ae_fname; return bp->b_fname; } /* * do_arg_all(): Open up to 'count' windows, one for each argument. */ void do_arg_all( int count, int forceit, /* hide buffers in current windows */ int keep_tabs) /* keep current tabs, for ":tab drop file" */ { int i; win_T *wp, *wpnext; char_u *opened; /* Array of weight for which args are open: * 0: not opened * 1: opened in other tab * 2: opened in curtab * 3: opened in curtab and curwin */ int opened_len; /* length of opened[] */ int use_firstwin = FALSE; /* use first window for arglist */ int split_ret = OK; int p_ea_save; alist_T *alist; /* argument list to be used */ buf_T *buf; tabpage_T *tpnext; int had_tab = cmdmod.tab; win_T *old_curwin, *last_curwin; tabpage_T *old_curtab, *last_curtab; win_T *new_curwin = NULL; tabpage_T *new_curtab = NULL; if (ARGCOUNT <= 0) { /* Don't give an error message. We don't want it when the ":all" * command is in the .vimrc. */ return; } setpcmark(); opened_len = ARGCOUNT; opened = alloc_clear((unsigned)opened_len); if (opened == NULL) return; /* Autocommands may do anything to the argument list. Make sure it's not * freed while we are working here by "locking" it. We still have to * watch out for its size to be changed. */ alist = curwin->w_alist; ++alist->al_refcount; old_curwin = curwin; old_curtab = curtab; # ifdef FEAT_GUI need_mouse_correct = TRUE; # endif /* * Try closing all windows that are not in the argument list. * Also close windows that are not full width; * When 'hidden' or "forceit" set the buffer becomes hidden. * Windows that have a changed buffer and can't be hidden won't be closed. * When the ":tab" modifier was used do this for all tab pages. */ if (had_tab > 0) goto_tabpage_tp(first_tabpage, TRUE, TRUE); for (;;) { tpnext = curtab->tp_next; for (wp = firstwin; wp != NULL; wp = wpnext) { wpnext = wp->w_next; buf = wp->w_buffer; if (buf->b_ffname == NULL || (!keep_tabs && (buf->b_nwindows > 1 || wp->w_width != Columns))) i = opened_len; else { /* check if the buffer in this window is in the arglist */ for (i = 0; i < opened_len; ++i) { if (i < alist->al_ga.ga_len && (AARGLIST(alist)[i].ae_fnum == buf->b_fnum || fullpathcmp(alist_name(&AARGLIST(alist)[i]), buf->b_ffname, TRUE) & FPC_SAME)) { int weight = 1; if (old_curtab == curtab) { ++weight; if (old_curwin == wp) ++weight; } if (weight > (int)opened[i]) { opened[i] = (char_u)weight; if (i == 0) { if (new_curwin != NULL) new_curwin->w_arg_idx = opened_len; new_curwin = wp; new_curtab = curtab; } } else if (keep_tabs) i = opened_len; if (wp->w_alist != alist) { /* Use the current argument list for all windows * containing a file from it. */ alist_unlink(wp->w_alist); wp->w_alist = alist; ++wp->w_alist->al_refcount; } break; } } } wp->w_arg_idx = i; if (i == opened_len && !keep_tabs)/* close this window */ { if (buf_hide(buf) || forceit || buf->b_nwindows > 1 || !bufIsChanged(buf)) { /* If the buffer was changed, and we would like to hide it, * try autowriting. */ if (!buf_hide(buf) && buf->b_nwindows <= 1 && bufIsChanged(buf)) { bufref_T bufref; set_bufref(&bufref, buf); (void)autowrite(buf, FALSE); /* check if autocommands removed the window */ if (!win_valid(wp) || !bufref_valid(&bufref)) { wpnext = firstwin; /* start all over... */ continue; } } /* don't close last window */ if (ONE_WINDOW && (first_tabpage->tp_next == NULL || !had_tab)) use_firstwin = TRUE; else { win_close(wp, !buf_hide(buf) && !bufIsChanged(buf)); /* check if autocommands removed the next window */ if (!win_valid(wpnext)) wpnext = firstwin; /* start all over... */ } } } } /* Without the ":tab" modifier only do the current tab page. */ if (had_tab == 0 || tpnext == NULL) break; /* check if autocommands removed the next tab page */ if (!valid_tabpage(tpnext)) tpnext = first_tabpage; /* start all over...*/ goto_tabpage_tp(tpnext, TRUE, TRUE); } /* * Open a window for files in the argument list that don't have one. * ARGCOUNT may change while doing this, because of autocommands. */ if (count > opened_len || count <= 0) count = opened_len; /* Don't execute Win/Buf Enter/Leave autocommands here. */ ++autocmd_no_enter; ++autocmd_no_leave; last_curwin = curwin; last_curtab = curtab; win_enter(lastwin, FALSE); /* ":drop all" should re-use an empty window to avoid "--remote-tab" * leaving an empty tab page when executed locally. */ if (keep_tabs && BUFEMPTY() && curbuf->b_nwindows == 1 && curbuf->b_ffname == NULL && !curbuf->b_changed) use_firstwin = TRUE; for (i = 0; i < count && i < opened_len && !got_int; ++i) { if (alist == &global_alist && i == global_alist.al_ga.ga_len - 1) arg_had_last = TRUE; if (opened[i] > 0) { /* Move the already present window to below the current window */ if (curwin->w_arg_idx != i) { for (wpnext = firstwin; wpnext != NULL; wpnext = wpnext->w_next) { if (wpnext->w_arg_idx == i) { if (keep_tabs) { new_curwin = wpnext; new_curtab = curtab; } else win_move_after(wpnext, curwin); break; } } } } else if (split_ret == OK) { if (!use_firstwin) /* split current window */ { p_ea_save = p_ea; p_ea = TRUE; /* use space from all windows */ split_ret = win_split(0, WSP_ROOM | WSP_BELOW); p_ea = p_ea_save; if (split_ret == FAIL) continue; } else /* first window: do autocmd for leaving this buffer */ --autocmd_no_leave; /* * edit file "i" */ curwin->w_arg_idx = i; if (i == 0) { new_curwin = curwin; new_curtab = curtab; } (void)do_ecmd(0, alist_name(&AARGLIST(alist)[i]), NULL, NULL, ECMD_ONE, ((buf_hide(curwin->w_buffer) || bufIsChanged(curwin->w_buffer)) ? ECMD_HIDE : 0) + ECMD_OLDBUF, curwin); if (use_firstwin) ++autocmd_no_leave; use_firstwin = FALSE; } ui_breakcheck(); /* When ":tab" was used open a new tab for a new window repeatedly. */ if (had_tab > 0 && tabpage_index(NULL) <= p_tpm) cmdmod.tab = 9999; } /* Remove the "lock" on the argument list. */ alist_unlink(alist); --autocmd_no_enter; /* restore last referenced tabpage's curwin */ if (last_curtab != new_curtab) { if (valid_tabpage(last_curtab)) goto_tabpage_tp(last_curtab, TRUE, TRUE); if (win_valid(last_curwin)) win_enter(last_curwin, FALSE); } /* to window with first arg */ if (valid_tabpage(new_curtab)) goto_tabpage_tp(new_curtab, TRUE, TRUE); if (win_valid(new_curwin)) win_enter(new_curwin, FALSE); --autocmd_no_leave; vim_free(opened); } /* * Open a window for a number of buffers. */ void ex_buffer_all(exarg_T *eap) { buf_T *buf; win_T *wp, *wpnext; int split_ret = OK; int p_ea_save; int open_wins = 0; int r; int count; /* Maximum number of windows to open. */ int all; /* When TRUE also load inactive buffers. */ int had_tab = cmdmod.tab; tabpage_T *tpnext; if (eap->addr_count == 0) /* make as many windows as possible */ count = 9999; else count = eap->line2; /* make as many windows as specified */ if (eap->cmdidx == CMD_unhide || eap->cmdidx == CMD_sunhide) all = FALSE; else all = TRUE; setpcmark(); #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif /* * Close superfluous windows (two windows for the same buffer). * Also close windows that are not full-width. */ if (had_tab > 0) goto_tabpage_tp(first_tabpage, TRUE, TRUE); for (;;) { tpnext = curtab->tp_next; for (wp = firstwin; wp != NULL; wp = wpnext) { wpnext = wp->w_next; if ((wp->w_buffer->b_nwindows > 1 || ((cmdmod.split & WSP_VERT) ? wp->w_height + wp->w_status_height < Rows - p_ch - tabline_height() : wp->w_width != Columns) || (had_tab > 0 && wp != firstwin)) && !ONE_WINDOW && !(wp->w_closing || wp->w_buffer->b_locked > 0)) { win_close(wp, FALSE); wpnext = firstwin; /* just in case an autocommand does something strange with windows */ tpnext = first_tabpage; /* start all over... */ open_wins = 0; } else ++open_wins; } /* Without the ":tab" modifier only do the current tab page. */ if (had_tab == 0 || tpnext == NULL) break; goto_tabpage_tp(tpnext, TRUE, TRUE); } /* * Go through the buffer list. When a buffer doesn't have a window yet, * open one. Otherwise move the window to the right position. * Watch out for autocommands that delete buffers or windows! */ /* Don't execute Win/Buf Enter/Leave autocommands here. */ ++autocmd_no_enter; win_enter(lastwin, FALSE); ++autocmd_no_leave; for (buf = firstbuf; buf != NULL && open_wins < count; buf = buf->b_next) { /* Check if this buffer needs a window */ if ((!all && buf->b_ml.ml_mfp == NULL) || !buf->b_p_bl) continue; if (had_tab != 0) { /* With the ":tab" modifier don't move the window. */ if (buf->b_nwindows > 0) wp = lastwin; /* buffer has a window, skip it */ else wp = NULL; } else { /* Check if this buffer already has a window */ FOR_ALL_WINDOWS(wp) if (wp->w_buffer == buf) break; /* If the buffer already has a window, move it */ if (wp != NULL) win_move_after(wp, curwin); } if (wp == NULL && split_ret == OK) { bufref_T bufref; set_bufref(&bufref, buf); /* Split the window and put the buffer in it */ p_ea_save = p_ea; p_ea = TRUE; /* use space from all windows */ split_ret = win_split(0, WSP_ROOM | WSP_BELOW); ++open_wins; p_ea = p_ea_save; if (split_ret == FAIL) continue; /* Open the buffer in this window. */ #if defined(HAS_SWAP_EXISTS_ACTION) swap_exists_action = SEA_DIALOG; #endif set_curbuf(buf, DOBUF_GOTO); if (!bufref_valid(&bufref)) { /* autocommands deleted the buffer!!! */ #if defined(HAS_SWAP_EXISTS_ACTION) swap_exists_action = SEA_NONE; #endif break; } #if defined(HAS_SWAP_EXISTS_ACTION) if (swap_exists_action == SEA_QUIT) { # if defined(FEAT_EVAL) cleanup_T cs; /* Reset the error/interrupt/exception state here so that * aborting() returns FALSE when closing a window. */ enter_cleanup(&cs); # endif /* User selected Quit at ATTENTION prompt; close this window. */ win_close(curwin, TRUE); --open_wins; swap_exists_action = SEA_NONE; swap_exists_did_quit = TRUE; # if defined(FEAT_EVAL) /* Restore the error/interrupt/exception state if not * discarded by a new aborting error, interrupt, or uncaught * exception. */ leave_cleanup(&cs); # endif } else handle_swap_exists(NULL); #endif } ui_breakcheck(); if (got_int) { (void)vgetc(); /* only break the file loading, not the rest */ break; } #ifdef FEAT_EVAL /* Autocommands deleted the buffer or aborted script processing!!! */ if (aborting()) break; #endif /* When ":tab" was used open a new tab for a new window repeatedly. */ if (had_tab > 0 && tabpage_index(NULL) <= p_tpm) cmdmod.tab = 9999; } --autocmd_no_enter; win_enter(firstwin, FALSE); /* back to first window */ --autocmd_no_leave; /* * Close superfluous windows. */ for (wp = lastwin; open_wins > count; ) { r = (buf_hide(wp->w_buffer) || !bufIsChanged(wp->w_buffer) || autowrite(wp->w_buffer, FALSE) == OK); if (!win_valid(wp)) { /* BufWrite Autocommands made the window invalid, start over */ wp = lastwin; } else if (r) { win_close(wp, !buf_hide(wp->w_buffer)); --open_wins; wp = lastwin; } else { wp = wp->w_prev; if (wp == NULL) break; } } } static int chk_modeline(linenr_T, int); /* * do_modelines() - process mode lines for the current file * * "flags" can be: * OPT_WINONLY only set options local to window * OPT_NOWIN don't set options local to window * * Returns immediately if the "ml" option isn't set. */ void do_modelines(int flags) { linenr_T lnum; int nmlines; static int entered = 0; if (!curbuf->b_p_ml || (nmlines = (int)p_mls) == 0) return; /* Disallow recursive entry here. Can happen when executing a modeline * triggers an autocommand, which reloads modelines with a ":do". */ if (entered) return; ++entered; for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count && lnum <= nmlines; ++lnum) if (chk_modeline(lnum, flags) == FAIL) nmlines = 0; for (lnum = curbuf->b_ml.ml_line_count; lnum > 0 && lnum > nmlines && lnum > curbuf->b_ml.ml_line_count - nmlines; --lnum) if (chk_modeline(lnum, flags) == FAIL) nmlines = 0; --entered; } #include "version.h" /* for version number */ /* * chk_modeline() - check a single line for a mode string * Return FAIL if an error encountered. */ static int chk_modeline( linenr_T lnum, int flags) /* Same as for do_modelines(). */ { char_u *s; char_u *e; char_u *linecopy; /* local copy of any modeline found */ int prev; int vers; int end; int retval = OK; char_u *save_sourcing_name; linenr_T save_sourcing_lnum; #ifdef FEAT_EVAL sctx_T save_current_sctx; #endif prev = -1; for (s = ml_get(lnum); *s != NUL; ++s) { if (prev == -1 || vim_isspace(prev)) { if ((prev != -1 && STRNCMP(s, "ex:", (size_t)3) == 0) || STRNCMP(s, "vi:", (size_t)3) == 0) break; /* Accept both "vim" and "Vim". */ if ((s[0] == 'v' || s[0] == 'V') && s[1] == 'i' && s[2] == 'm') { if (s[3] == '<' || s[3] == '=' || s[3] == '>') e = s + 4; else e = s + 3; vers = getdigits(&e); if (*e == ':' && (s[0] != 'V' || STRNCMP(skipwhite(e + 1), "set", 3) == 0) && (s[3] == ':' || (VIM_VERSION_100 >= vers && isdigit(s[3])) || (VIM_VERSION_100 < vers && s[3] == '<') || (VIM_VERSION_100 > vers && s[3] == '>') || (VIM_VERSION_100 == vers && s[3] == '='))) break; } } prev = *s; } if (*s) { do /* skip over "ex:", "vi:" or "vim:" */ ++s; while (s[-1] != ':'); s = linecopy = vim_strsave(s); /* copy the line, it will change */ if (linecopy == NULL) return FAIL; save_sourcing_lnum = sourcing_lnum; save_sourcing_name = sourcing_name; sourcing_lnum = lnum; /* prepare for emsg() */ sourcing_name = (char_u *)"modelines"; end = FALSE; while (end == FALSE) { s = skipwhite(s); if (*s == NUL) break; /* * Find end of set command: ':' or end of line. * Skip over "\:", replacing it with ":". */ for (e = s; *e != ':' && *e != NUL; ++e) if (e[0] == '\\' && e[1] == ':') STRMOVE(e, e + 1); if (*e == NUL) end = TRUE; /* * If there is a "set" command, require a terminating ':' and * ignore the stuff after the ':'. * "vi:set opt opt opt: foo" -- foo not interpreted * "vi:opt opt opt: foo" -- foo interpreted * Accept "se" for compatibility with Elvis. */ if (STRNCMP(s, "set ", (size_t)4) == 0 || STRNCMP(s, "se ", (size_t)3) == 0) { if (*e != ':') /* no terminating ':'? */ break; end = TRUE; s = vim_strchr(s, ' ') + 1; } *e = NUL; /* truncate the set command */ if (*s != NUL) /* skip over an empty "::" */ { int secure_save = secure; #ifdef FEAT_EVAL save_current_sctx = current_sctx; current_sctx.sc_sid = SID_MODELINE; current_sctx.sc_seq = 0; current_sctx.sc_lnum = 0; #endif // Make sure no risky things are executed as a side effect. ++secure; retval = do_set(s, OPT_MODELINE | OPT_LOCAL | flags); secure = secure_save; #ifdef FEAT_EVAL current_sctx = save_current_sctx; #endif if (retval == FAIL) /* stop if error found */ break; } s = e + 1; /* advance to next part */ } sourcing_lnum = save_sourcing_lnum; sourcing_name = save_sourcing_name; vim_free(linecopy); } return retval; } #if defined(FEAT_VIMINFO) || defined(PROTO) int read_viminfo_bufferlist( vir_T *virp, int writing) { char_u *tab; linenr_T lnum; colnr_T col; buf_T *buf; char_u *sfname; char_u *xline; /* Handle long line and escaped characters. */ xline = viminfo_readstring(virp, 1, FALSE); /* don't read in if there are files on the command-line or if writing: */ if (xline != NULL && !writing && ARGCOUNT == 0 && find_viminfo_parameter('%') != NULL) { /* Format is: <fname> Tab <lnum> Tab <col>. * Watch out for a Tab in the file name, work from the end. */ lnum = 0; col = 0; tab = vim_strrchr(xline, '\t'); if (tab != NULL) { *tab++ = '\0'; col = (colnr_T)atoi((char *)tab); tab = vim_strrchr(xline, '\t'); if (tab != NULL) { *tab++ = '\0'; lnum = atol((char *)tab); } } /* Expand "~/" in the file name at "line + 1" to a full path. * Then try shortening it by comparing with the current directory */ expand_env(xline, NameBuff, MAXPATHL); sfname = shorten_fname1(NameBuff); buf = buflist_new(NameBuff, sfname, (linenr_T)0, BLN_LISTED); if (buf != NULL) /* just in case... */ { buf->b_last_cursor.lnum = lnum; buf->b_last_cursor.col = col; buflist_setfpos(buf, curwin, lnum, col, FALSE); } } vim_free(xline); return viminfo_readline(virp); } void write_viminfo_bufferlist(FILE *fp) { buf_T *buf; win_T *win; tabpage_T *tp; char_u *line; int max_buffers; if (find_viminfo_parameter('%') == NULL) return; /* Without a number -1 is returned: do all buffers. */ max_buffers = get_viminfo_parameter('%'); /* Allocate room for the file name, lnum and col. */ #define LINE_BUF_LEN (MAXPATHL + 40) line = alloc(LINE_BUF_LEN); if (line == NULL) return; FOR_ALL_TAB_WINDOWS(tp, win) set_last_cursor(win); fputs(_("\n# Buffer list:\n"), fp); FOR_ALL_BUFFERS(buf) { if (buf->b_fname == NULL || !buf->b_p_bl #ifdef FEAT_QUICKFIX || bt_quickfix(buf) #endif #ifdef FEAT_TERMINAL || bt_terminal(buf) #endif || removable(buf->b_ffname)) continue; if (max_buffers-- == 0) break; putc('%', fp); home_replace(NULL, buf->b_ffname, line, MAXPATHL, TRUE); vim_snprintf_add((char *)line, LINE_BUF_LEN, "\t%ld\t%d", (long)buf->b_last_cursor.lnum, buf->b_last_cursor.col); viminfo_writestring(fp, line); } vim_free(line); } #endif /* * Return TRUE if "buf" is a normal buffer, 'buftype' is empty. */ int bt_normal(buf_T *buf) { return buf != NULL && buf->b_p_bt[0] == NUL; } /* * Return TRUE if "buf" is the quickfix buffer. */ int bt_quickfix(buf_T *buf) { return buf != NULL && buf->b_p_bt[0] == 'q'; } /* * Return TRUE if "buf" is a terminal buffer. */ int bt_terminal(buf_T *buf) { return buf != NULL && buf->b_p_bt[0] == 't'; } /* * Return TRUE if "buf" is a help buffer. */ int bt_help(buf_T *buf) { return buf != NULL && buf->b_help; } /* * Return TRUE if "buf" is a prompt buffer. */ int bt_prompt(buf_T *buf) { return buf != NULL && buf->b_p_bt[0] == 'p'; } /* * Return TRUE if "buf" is a "nofile", "acwrite", "terminal" or "prompt" * buffer. This means the buffer name is not a file name. */ int bt_nofile(buf_T *buf) { return buf != NULL && ((buf->b_p_bt[0] == 'n' && buf->b_p_bt[2] == 'f') || buf->b_p_bt[0] == 'a' || buf->b_p_bt[0] == 't' || buf->b_p_bt[0] == 'p'); } /* * Return TRUE if "buf" is a "nowrite", "nofile", "terminal" or "prompt" * buffer. */ int bt_dontwrite(buf_T *buf) { return buf != NULL && (buf->b_p_bt[0] == 'n' || buf->b_p_bt[0] == 't' || buf->b_p_bt[0] == 'p'); } int bt_dontwrite_msg(buf_T *buf) { if (bt_dontwrite(buf)) { EMSG(_("E382: Cannot write, 'buftype' option is set")); return TRUE; } return FALSE; } /* * Return TRUE if the buffer should be hidden, according to 'hidden', ":hide" * and 'bufhidden'. */ int buf_hide(buf_T *buf) { /* 'bufhidden' overrules 'hidden' and ":hide", check it first */ switch (buf->b_p_bh[0]) { case 'u': /* "unload" */ case 'w': /* "wipe" */ case 'd': return FALSE; /* "delete" */ case 'h': return TRUE; /* "hide" */ } return (p_hid || cmdmod.hide); } /* * Return special buffer name. * Returns NULL when the buffer has a normal file name. */ char_u * buf_spname(buf_T *buf) { #if defined(FEAT_QUICKFIX) if (bt_quickfix(buf)) { win_T *win; tabpage_T *tp; /* * For location list window, w_llist_ref points to the location list. * For quickfix window, w_llist_ref is NULL. */ if (find_win_for_buf(buf, &win, &tp) == OK && win->w_llist_ref != NULL) return (char_u *)_(msg_loclist); else return (char_u *)_(msg_qflist); } #endif /* There is no _file_ when 'buftype' is "nofile", b_sfname * contains the name as specified by the user. */ if (bt_nofile(buf)) { #ifdef FEAT_TERMINAL if (buf->b_term != NULL) return term_get_status_text(buf->b_term); #endif if (buf->b_fname != NULL) return buf->b_fname; #ifdef FEAT_JOB_CHANNEL if (bt_prompt(buf)) return (char_u *)_("[Prompt]"); #endif return (char_u *)_("[Scratch]"); } if (buf->b_fname == NULL) return (char_u *)_("[No Name]"); return NULL; } #if defined(FEAT_JOB_CHANNEL) \ || defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) \ || defined(PROTO) # define SWITCH_TO_WIN /* * Find a window that contains "buf" and switch to it. * If there is no such window, use the current window and change "curbuf". * Caller must initialize save_curbuf to NULL. * restore_win_for_buf() MUST be called later! */ void switch_to_win_for_buf( buf_T *buf, win_T **save_curwinp, tabpage_T **save_curtabp, bufref_T *save_curbuf) { win_T *wp; tabpage_T *tp; if (find_win_for_buf(buf, &wp, &tp) == FAIL) switch_buffer(save_curbuf, buf); else if (switch_win(save_curwinp, save_curtabp, wp, tp, TRUE) == FAIL) { restore_win(*save_curwinp, *save_curtabp, TRUE); switch_buffer(save_curbuf, buf); } } void restore_win_for_buf( win_T *save_curwin, tabpage_T *save_curtab, bufref_T *save_curbuf) { if (save_curbuf->br_buf == NULL) restore_win(save_curwin, save_curtab, TRUE); else restore_buffer(save_curbuf); } #endif #if defined(FEAT_QUICKFIX) || defined(SWITCH_TO_WIN) || defined(PROTO) /* * Find a window for buffer "buf". * If found OK is returned and "wp" and "tp" are set to the window and tabpage. * If not found FAIL is returned. */ int find_win_for_buf( buf_T *buf, win_T **wp, tabpage_T **tp) { FOR_ALL_TAB_WINDOWS(*tp, *wp) if ((*wp)->w_buffer == buf) goto win_found; return FAIL; win_found: return OK; } #endif #if defined(FEAT_SIGNS) || defined(PROTO) static hashtab_T sg_table; // sign group (signgroup_T) hashtable /* * A new sign in group 'groupname' is added. If the group is not present, * create it. Otherwise reference the group. */ static signgroup_T * sign_group_ref(char_u *groupname) { static int initialized = FALSE; hash_T hash; hashitem_T *hi; signgroup_T *group; if (!initialized) { initialized = TRUE; hash_init(&sg_table); } hash = hash_hash(groupname); hi = hash_lookup(&sg_table, groupname, hash); if (HASHITEM_EMPTY(hi)) { // new group group = (signgroup_T *)alloc( (unsigned)(sizeof(signgroup_T) + STRLEN(groupname))); if (group == NULL) return NULL; STRCPY(group->sg_name, groupname); group->refcount = 1; hash_add_item(&sg_table, hi, group->sg_name, hash); } else { // existing group group = HI2SG(hi); group->refcount++; } return group; } /* * A sign in group 'groupname' is removed. If all the signs in this group are * removed, then remove the group. */ static void sign_group_unref(char_u *groupname) { hashitem_T *hi; signgroup_T *group; hi = hash_find(&sg_table, groupname); if (!HASHITEM_EMPTY(hi)) { group = HI2SG(hi); group->refcount--; if (group->refcount == 0) { // All the signs in this group are removed hash_remove(&sg_table, hi); vim_free(group); } } } /* * Insert a new sign into the signlist for buffer 'buf' between the 'prev' and * 'next' signs. */ static void insert_sign( buf_T *buf, // buffer to store sign in signlist_T *prev, // previous sign entry signlist_T *next, // next sign entry int id, // sign ID char_u *group, // sign group; NULL for global group int prio, // sign priority linenr_T lnum, // line number which gets the mark int typenr) // typenr of sign we are adding { signlist_T *newsign; newsign = (signlist_T *)lalloc_id((long_u)sizeof(signlist_T), FALSE, aid_insert_sign); if (newsign != NULL) { newsign->id = id; newsign->lnum = lnum; newsign->typenr = typenr; if (group != NULL) { newsign->group = sign_group_ref(group); if (newsign->group == NULL) { vim_free(newsign); return; } } else newsign->group = NULL; newsign->priority = prio; newsign->next = next; newsign->prev = prev; if (next != NULL) next->prev = newsign; if (prev == NULL) { // When adding first sign need to redraw the windows to create the // column for signs. if (buf->b_signlist == NULL) { redraw_buf_later(buf, NOT_VALID); changed_cline_bef_curs(); } // first sign in signlist buf->b_signlist = newsign; #ifdef FEAT_NETBEANS_INTG if (netbeans_active()) buf->b_has_sign_column = TRUE; #endif } else prev->next = newsign; } } /* * Insert a new sign sorted by line number and sign priority. */ static void insert_sign_by_lnum_prio( buf_T *buf, // buffer to store sign in signlist_T *prev, // previous sign entry int id, // sign ID char_u *group, // sign group; NULL for global group int prio, // sign priority linenr_T lnum, // line number which gets the mark int typenr) // typenr of sign we are adding { signlist_T *sign; // keep signs sorted by lnum and by priority: insert new sign at // the proper position in the list for this lnum. while (prev != NULL && prev->lnum == lnum && prev->priority <= prio) prev = prev->prev; if (prev == NULL) sign = buf->b_signlist; else sign = prev->next; insert_sign(buf, prev, sign, id, group, prio, lnum, typenr); } /* * Returns TRUE if 'sign' is in 'group'. * A sign can either be in the global group (sign->group == NULL) * or in a named group. If 'group' is '*', then the sign is part of the group. */ int sign_in_group(signlist_T *sign, char_u *group) { return ((group != NULL && STRCMP(group, "*") == 0) || (group == NULL && sign->group == NULL) || (group != NULL && sign->group != NULL && STRCMP(group, sign->group->sg_name) == 0)); } /* * Return information about a sign in a Dict */ dict_T * sign_get_info(signlist_T *sign) { dict_T *d; if ((d = dict_alloc_id(aid_sign_getinfo)) == NULL) return NULL; dict_add_number(d, "id", sign->id); dict_add_string(d, "group", (sign->group == NULL) ? (char_u *)"" : sign->group->sg_name); dict_add_number(d, "lnum", sign->lnum); dict_add_string(d, "name", sign_typenr2name(sign->typenr)); dict_add_number(d, "priority", sign->priority); return d; } /* * Add the sign into the signlist. Find the right spot to do it though. */ void buf_addsign( buf_T *buf, // buffer to store sign in int id, // sign ID char_u *groupname, // sign group int prio, // sign priority linenr_T lnum, // line number which gets the mark int typenr) // typenr of sign we are adding { signlist_T *sign; // a sign in the signlist signlist_T *prev; // the previous sign prev = NULL; FOR_ALL_SIGNS_IN_BUF(buf) { if (lnum == sign->lnum && id == sign->id && sign_in_group(sign, groupname)) { // Update an existing sign sign->typenr = typenr; return; } else if (lnum < sign->lnum) { insert_sign_by_lnum_prio(buf, prev, id, groupname, prio, lnum, typenr); return; } prev = sign; } insert_sign_by_lnum_prio(buf, prev, id, groupname, prio, lnum, typenr); return; } /* * For an existing, placed sign "markId" change the type to "typenr". * Returns the line number of the sign, or zero if the sign is not found. */ linenr_T buf_change_sign_type( buf_T *buf, // buffer to store sign in int markId, // sign ID char_u *group, // sign group int typenr) // typenr of sign we are adding { signlist_T *sign; // a sign in the signlist FOR_ALL_SIGNS_IN_BUF(buf) { if (sign->id == markId && sign_in_group(sign, group)) { sign->typenr = typenr; return sign->lnum; } } return (linenr_T)0; } /* * Return the type number of the sign at line number 'lnum' in buffer 'buf' * which has the attribute specifed by 'type'. Returns 0 if a sign is not found * at the line number or it doesn't have the specified attribute. */ int buf_getsigntype( buf_T *buf, linenr_T lnum, int type) /* SIGN_ICON, SIGN_TEXT, SIGN_ANY, SIGN_LINEHL */ { signlist_T *sign; /* a sign in a b_signlist */ FOR_ALL_SIGNS_IN_BUF(buf) if (sign->lnum == lnum && (type == SIGN_ANY # ifdef FEAT_SIGN_ICONS || (type == SIGN_ICON && sign_get_image(sign->typenr) != NULL) # endif || (type == SIGN_TEXT && sign_get_text(sign->typenr) != NULL) || (type == SIGN_LINEHL && sign_get_attr(sign->typenr, TRUE) != 0))) return sign->typenr; return 0; } /* * Delete sign 'id' in group 'group' from buffer 'buf'. * If 'id' is zero, then delete all the signs in group 'group'. Otherwise * delete only the specified sign. * If 'group' is '*', then delete the sign in all the groups. If 'group' is * NULL, then delete the sign in the global group. Otherwise delete the sign in * the specified group. * Returns the line number of the deleted sign. If multiple signs are deleted, * then returns the line number of the last sign deleted. */ linenr_T buf_delsign( buf_T *buf, // buffer sign is stored in int id, // sign id char_u *group) // sign group { signlist_T **lastp; // pointer to pointer to current sign signlist_T *sign; // a sign in a b_signlist signlist_T *next; // the next sign in a b_signlist linenr_T lnum; // line number whose sign was deleted lastp = &buf->b_signlist; lnum = 0; for (sign = buf->b_signlist; sign != NULL; sign = next) { next = sign->next; if ((id == 0 || sign->id == id) && sign_in_group(sign, group)) { *lastp = next; if (next != NULL) next->prev = sign->prev; lnum = sign->lnum; if (sign->group != NULL) sign_group_unref(sign->group->sg_name); vim_free(sign); // Check whether only one sign needs to be deleted if (group == NULL || (*group != '*' && id != 0)) break; } else lastp = &sign->next; } // When deleted the last sign need to redraw the windows to remove the // sign column. if (buf->b_signlist == NULL) { redraw_buf_later(buf, NOT_VALID); changed_cline_bef_curs(); } return lnum; } /* * Find the line number of the sign with the requested id in group 'group'. If * the sign does not exist, return 0 as the line number. This will still let * the correct file get loaded. */ int buf_findsign( buf_T *buf, // buffer to store sign in int id, // sign ID char_u *group) // sign group { signlist_T *sign; // a sign in the signlist FOR_ALL_SIGNS_IN_BUF(buf) if (sign->id == id && sign_in_group(sign, group)) return sign->lnum; return 0; } /* * Return the sign at line 'lnum' in buffer 'buf'. Returns NULL if a sign is * not found at the line. */ static signlist_T * buf_getsign_at_line( buf_T *buf, // buffer whose sign we are searching for linenr_T lnum) // line number of sign { signlist_T *sign; // a sign in the signlist FOR_ALL_SIGNS_IN_BUF(buf) if (sign->lnum == lnum) return sign; return NULL; } /* * Return the sign with identifier 'id' in group 'group' placed in buffer 'buf' */ signlist_T * buf_getsign_with_id( buf_T *buf, // buffer whose sign we are searching for int id, // sign identifier char_u *group) // sign group { signlist_T *sign; // a sign in the signlist FOR_ALL_SIGNS_IN_BUF(buf) if (sign->id == id && sign_in_group(sign, group)) return sign; return NULL; } /* * Return the identifier of the sign at line number 'lnum' in buffer 'buf'. */ int buf_findsign_id( buf_T *buf, // buffer whose sign we are searching for linenr_T lnum) // line number of sign { signlist_T *sign; // a sign in the signlist sign = buf_getsign_at_line(buf, lnum); if (sign != NULL) return sign->id; return 0; } # if defined(FEAT_NETBEANS_INTG) || defined(PROTO) /* * See if a given type of sign exists on a specific line. */ int buf_findsigntype_id( buf_T *buf, /* buffer whose sign we are searching for */ linenr_T lnum, /* line number of sign */ int typenr) /* sign type number */ { signlist_T *sign; /* a sign in the signlist */ FOR_ALL_SIGNS_IN_BUF(buf) if (sign->lnum == lnum && sign->typenr == typenr) return sign->id; return 0; } # if defined(FEAT_SIGN_ICONS) || defined(PROTO) /* * Return the number of icons on the given line. */ int buf_signcount(buf_T *buf, linenr_T lnum) { signlist_T *sign; // a sign in the signlist int count = 0; FOR_ALL_SIGNS_IN_BUF(buf) if (sign->lnum == lnum) if (sign_get_image(sign->typenr) != NULL) count++; return count; } # endif /* FEAT_SIGN_ICONS */ # endif /* FEAT_NETBEANS_INTG */ /* * Delete signs in group 'group' in buffer "buf". If 'group' is '*', then * delete all the signs. */ void buf_delete_signs(buf_T *buf, char_u *group) { signlist_T *sign; signlist_T **lastp; // pointer to pointer to current sign signlist_T *next; // When deleting the last sign need to redraw the windows to remove the // sign column. Not when curwin is NULL (this means we're exiting). if (buf->b_signlist != NULL && curwin != NULL) { redraw_buf_later(buf, NOT_VALID); changed_cline_bef_curs(); } lastp = &buf->b_signlist; for (sign = buf->b_signlist; sign != NULL; sign = next) { next = sign->next; if (sign_in_group(sign, group)) { *lastp = next; if (next != NULL) next->prev = sign->prev; if (sign->group != NULL) sign_group_unref(sign->group->sg_name); vim_free(sign); } else lastp = &sign->next; } } /* * Delete all signs in all buffers. */ void buf_delete_all_signs(void) { buf_T *buf; /* buffer we are checking for signs */ FOR_ALL_BUFFERS(buf) if (buf->b_signlist != NULL) buf_delete_signs(buf, (char_u *)"*"); } /* * List placed signs for "rbuf". If "rbuf" is NULL do it for all buffers. */ void sign_list_placed(buf_T *rbuf, char_u *sign_group) { buf_T *buf; signlist_T *sign; char lbuf[BUFSIZ]; char group[BUFSIZ]; MSG_PUTS_TITLE(_("\n--- Signs ---")); msg_putchar('\n'); if (rbuf == NULL) buf = firstbuf; else buf = rbuf; while (buf != NULL && !got_int) { if (buf->b_signlist != NULL) { vim_snprintf(lbuf, BUFSIZ, _("Signs for %s:"), buf->b_fname); MSG_PUTS_ATTR(lbuf, HL_ATTR(HLF_D)); msg_putchar('\n'); } FOR_ALL_SIGNS_IN_BUF(buf) { if (got_int) break; if (!sign_in_group(sign, sign_group)) continue; if (sign->group != NULL) vim_snprintf(group, BUFSIZ, " group=%s", sign->group->sg_name); else group[0] = '\0'; vim_snprintf(lbuf, BUFSIZ, _(" line=%ld id=%d%s name=%s " "priority=%d"), (long)sign->lnum, sign->id, group, sign_typenr2name(sign->typenr), sign->priority); MSG_PUTS(lbuf); msg_putchar('\n'); } if (rbuf != NULL) break; buf = buf->b_next; } } /* * Adjust a placed sign for inserted/deleted lines. */ void sign_mark_adjust( linenr_T line1, linenr_T line2, long amount, long amount_after) { signlist_T *sign; /* a sign in a b_signlist */ FOR_ALL_SIGNS_IN_BUF(curbuf) { if (sign->lnum >= line1 && sign->lnum <= line2) { if (amount == MAXLNUM) sign->lnum = line1; else sign->lnum += amount; } else if (sign->lnum > line2) sign->lnum += amount_after; } } #endif /* FEAT_SIGNS */ /* * Set 'buflisted' for curbuf to "on" and trigger autocommands if it changed. */ void set_buflisted(int on) { if (on != curbuf->b_p_bl) { curbuf->b_p_bl = on; if (on) apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf); else apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf); } } /* * Read the file for "buf" again and check if the contents changed. * Return TRUE if it changed or this could not be checked. */ int buf_contents_changed(buf_T *buf) { buf_T *newbuf; int differ = TRUE; linenr_T lnum; aco_save_T aco; exarg_T ea; /* Allocate a buffer without putting it in the buffer list. */ newbuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY); if (newbuf == NULL) return TRUE; /* Force the 'fileencoding' and 'fileformat' to be equal. */ if (prep_exarg(&ea, buf) == FAIL) { wipe_buffer(newbuf, FALSE); return TRUE; } /* set curwin/curbuf to buf and save a few things */ aucmd_prepbuf(&aco, newbuf); if (ml_open(curbuf) == OK && readfile(buf->b_ffname, buf->b_fname, (linenr_T)0, (linenr_T)0, (linenr_T)MAXLNUM, &ea, READ_NEW | READ_DUMMY) == OK) { /* compare the two files line by line */ if (buf->b_ml.ml_line_count == curbuf->b_ml.ml_line_count) { differ = FALSE; for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum) if (STRCMP(ml_get_buf(buf, lnum, FALSE), ml_get(lnum)) != 0) { differ = TRUE; break; } } } vim_free(ea.cmd); /* restore curwin/curbuf and a few other things */ aucmd_restbuf(&aco); if (curbuf != newbuf) /* safety check */ wipe_buffer(newbuf, FALSE); return differ; } /* * Wipe out a buffer and decrement the last buffer number if it was used for * this buffer. Call this to wipe out a temp buffer that does not contain any * marks. */ void wipe_buffer( buf_T *buf, int aucmd UNUSED) /* When TRUE trigger autocommands. */ { if (buf->b_fnum == top_file_num - 1) --top_file_num; if (!aucmd) /* Don't trigger BufDelete autocommands here. */ block_autocmds(); close_buffer(NULL, buf, DOBUF_WIPE, FALSE); if (!aucmd) unblock_autocmds(); } /* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. */ /* * Implements communication through a socket or any file handle. */ #include "vim.h" #if defined(FEAT_JOB_CHANNEL) || defined(PROTO) /* TRUE when netbeans is running with a GUI. */ #ifdef FEAT_GUI # define CH_HAS_GUI (gui.in_use || gui.starting) #endif /* Note: when making changes here also adjust configure.ac. */ #ifdef WIN32 /* WinSock API is separated from C API, thus we can't use read(), write(), * errno... */ # define SOCK_ERRNO errno = WSAGetLastError() # undef ECONNREFUSED # define ECONNREFUSED WSAECONNREFUSED # undef EWOULDBLOCK # define EWOULDBLOCK WSAEWOULDBLOCK # undef EINPROGRESS # define EINPROGRESS WSAEINPROGRESS # ifdef EINTR # undef EINTR # endif # define EINTR WSAEINTR # define sock_write(sd, buf, len) send((SOCKET)sd, buf, len, 0) # define sock_read(sd, buf, len) recv((SOCKET)sd, buf, len, 0) # define sock_close(sd) closesocket((SOCKET)sd) #else # include <netdb.h> # include <netinet/in.h> # include <sys/socket.h> # ifdef HAVE_LIBGEN_H # include <libgen.h> # endif # define SOCK_ERRNO # define sock_write(sd, buf, len) write(sd, buf, len) # define sock_read(sd, buf, len) read(sd, buf, len) # define sock_close(sd) close(sd) # define fd_read(fd, buf, len) read(fd, buf, len) # define fd_write(sd, buf, len) write(sd, buf, len) # define fd_close(sd) close(sd) #endif static void channel_read(channel_T *channel, ch_part_T part, char *func); /* Whether a redraw is needed for appending a line to a buffer. */ static int channel_need_redraw = FALSE; /* Whether we are inside channel_parse_messages() or another situation where it * is safe to invoke callbacks. */ static int safe_to_invoke_callback = 0; static char *part_names[] = {"sock", "out", "err", "in"}; #ifdef WIN32 static int fd_read(sock_T fd, char *buf, size_t len) { HANDLE h = (HANDLE)fd; DWORD nread; if (!ReadFile(h, buf, (DWORD)len, &nread, NULL)) return -1; return (int)nread; } static int fd_write(sock_T fd, char *buf, size_t len) { HANDLE h = (HANDLE)fd; DWORD nwrite; if (!WriteFile(h, buf, (DWORD)len, &nwrite, NULL)) return -1; return (int)nwrite; } static void fd_close(sock_T fd) { HANDLE h = (HANDLE)fd; CloseHandle(h); } #endif /* Log file opened with ch_logfile(). */ static FILE *log_fd = NULL; #ifdef FEAT_RELTIME static proftime_T log_start; #endif void ch_logfile(char_u *fname, char_u *opt) { FILE *file = NULL; if (log_fd != NULL) fclose(log_fd); if (*fname != NUL) { file = fopen((char *)fname, *opt == 'w' ? "w" : "a"); if (file == NULL) { EMSG2(_(e_notopen), fname); return; } } log_fd = file; if (log_fd != NULL) { fprintf(log_fd, "==== start log session ====\n"); #ifdef FEAT_RELTIME profile_start(&log_start); #endif } } int ch_log_active(void) { return log_fd != NULL; } static void ch_log_lead(const char *what, channel_T *ch, ch_part_T part) { if (log_fd != NULL) { #ifdef FEAT_RELTIME proftime_T log_now; profile_start(&log_now); profile_sub(&log_now, &log_start); fprintf(log_fd, "%s ", profile_msg(&log_now)); #endif if (ch != NULL) { if (part < PART_COUNT) fprintf(log_fd, "%son %d(%s): ", what, ch->ch_id, part_names[part]); else fprintf(log_fd, "%son %d: ", what, ch->ch_id); } else fprintf(log_fd, "%s: ", what); } } static int did_log_msg = TRUE; #ifndef PROTO /* prototype is in vim.h */ void ch_log(channel_T *ch, const char *fmt, ...) { if (log_fd != NULL) { va_list ap; ch_log_lead("", ch, PART_COUNT); va_start(ap, fmt); vfprintf(log_fd, fmt, ap); va_end(ap); fputc('\n', log_fd); fflush(log_fd); did_log_msg = TRUE; } } #endif static void ch_error(channel_T *ch, const char *fmt, ...) #ifdef USE_PRINTF_FORMAT_ATTRIBUTE __attribute__((format(printf, 2, 3))) #endif ; static void ch_error(channel_T *ch, const char *fmt, ...) { if (log_fd != NULL) { va_list ap; ch_log_lead("ERR ", ch, PART_COUNT); va_start(ap, fmt); vfprintf(log_fd, fmt, ap); va_end(ap); fputc('\n', log_fd); fflush(log_fd); did_log_msg = TRUE; } } #ifdef _WIN32 # undef PERROR # define PERROR(msg) (void)emsg3((char_u *)"%s: %s", \ (char_u *)msg, (char_u *)strerror_win32(errno)) static char * strerror_win32(int eno) { static LPVOID msgbuf = NULL; char_u *ptr; if (msgbuf) { LocalFree(msgbuf); msgbuf = NULL; } FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, eno, MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT), (LPTSTR) &msgbuf, 0, NULL); if (msgbuf != NULL) /* chomp \r or \n */ for (ptr = (char_u *)msgbuf; *ptr; ptr++) switch (*ptr) { case '\r': STRMOVE(ptr, ptr + 1); ptr--; break; case '\n': if (*(ptr + 1) == '\0') *ptr = '\0'; else *ptr = ' '; break; } return msgbuf; } #endif /* * The list of all allocated channels. */ static channel_T *first_channel = NULL; static int next_ch_id = 0; /* * Allocate a new channel. The refcount is set to 1. * The channel isn't actually used until it is opened. * Returns NULL if out of memory. */ channel_T * add_channel(void) { ch_part_T part; channel_T *channel = (channel_T *)alloc_clear((int)sizeof(channel_T)); if (channel == NULL) return NULL; channel->ch_id = next_ch_id++; ch_log(channel, "Created channel"); for (part = PART_SOCK; part < PART_COUNT; ++part) { channel->ch_part[part].ch_fd = INVALID_FD; #ifdef FEAT_GUI_X11 channel->ch_part[part].ch_inputHandler = (XtInputId)NULL; #endif #ifdef FEAT_GUI_GTK channel->ch_part[part].ch_inputHandler = 0; #endif channel->ch_part[part].ch_timeout = 2000; } if (first_channel != NULL) { first_channel->ch_prev = channel; channel->ch_next = first_channel; } first_channel = channel; channel->ch_refcount = 1; return channel; } int has_any_channel(void) { return first_channel != NULL; } /* * Called when the refcount of a channel is zero. * Return TRUE if "channel" has a callback and the associated job wasn't * killed. */ static int channel_still_useful(channel_T *channel) { int has_sock_msg; int has_out_msg; int has_err_msg; /* If the job was killed the channel is not expected to work anymore. */ if (channel->ch_job_killed && channel->ch_job == NULL) return FALSE; /* If there is a close callback it may still need to be invoked. */ if (channel->ch_close_cb != NULL) return TRUE; /* If reading from or a buffer it's still useful. */ if (channel->ch_part[PART_IN].ch_bufref.br_buf != NULL) return TRUE; /* If there is no callback then nobody can get readahead. If the fd is * closed and there is no readahead then the callback won't be called. */ has_sock_msg = channel->ch_part[PART_SOCK].ch_fd != INVALID_FD || channel->ch_part[PART_SOCK].ch_head.rq_next != NULL || channel->ch_part[PART_SOCK].ch_json_head.jq_next != NULL; has_out_msg = channel->ch_part[PART_OUT].ch_fd != INVALID_FD || channel->ch_part[PART_OUT].ch_head.rq_next != NULL || channel->ch_part[PART_OUT].ch_json_head.jq_next != NULL; has_err_msg = channel->ch_part[PART_ERR].ch_fd != INVALID_FD || channel->ch_part[PART_ERR].ch_head.rq_next != NULL || channel->ch_part[PART_ERR].ch_json_head.jq_next != NULL; return (channel->ch_callback != NULL && (has_sock_msg || has_out_msg || has_err_msg)) || ((channel->ch_part[PART_OUT].ch_callback != NULL || channel->ch_part[PART_OUT].ch_bufref.br_buf != NULL) && has_out_msg) || ((channel->ch_part[PART_ERR].ch_callback != NULL || channel->ch_part[PART_ERR].ch_bufref.br_buf != NULL) && has_err_msg); } /* * Return TRUE if "channel" is closeable (i.e. all readable fds are closed). */ static int channel_can_close(channel_T *channel) { return channel->ch_to_be_closed == 0; } /* * Close a channel and free all its resources. */ static void channel_free_contents(channel_T *channel) { channel_close(channel, TRUE); channel_clear(channel); ch_log(channel, "Freeing channel"); } static void channel_free_channel(channel_T *channel) { if (channel->ch_next != NULL) channel->ch_next->ch_prev = channel->ch_prev; if (channel->ch_prev == NULL) first_channel = channel->ch_next; else channel->ch_prev->ch_next = channel->ch_next; vim_free(channel); } static void channel_free(channel_T *channel) { if (!in_free_unref_items) { if (safe_to_invoke_callback == 0) channel->ch_to_be_freed = TRUE; else { channel_free_contents(channel); channel_free_channel(channel); } } } /* * Close a channel and free all its resources if there is no further action * possible, there is no callback to be invoked or the associated job was * killed. * Return TRUE if the channel was freed. */ static int channel_may_free(channel_T *channel) { if (!channel_still_useful(channel)) { channel_free(channel); return TRUE; } return FALSE; } /* * Decrement the reference count on "channel" and maybe free it when it goes * down to zero. Don't free it if there is a pending action. * Returns TRUE when the channel is no longer referenced. */ int channel_unref(channel_T *channel) { if (channel != NULL && --channel->ch_refcount <= 0) return channel_may_free(channel); return FALSE; } int free_unused_channels_contents(int copyID, int mask) { int did_free = FALSE; channel_T *ch; /* This is invoked from the garbage collector, which only runs at a safe * point. */ ++safe_to_invoke_callback; for (ch = first_channel; ch != NULL; ch = ch->ch_next) if (!channel_still_useful(ch) && (ch->ch_copyID & mask) != (copyID & mask)) { /* Free the channel and ordinary items it contains, but don't * recurse into Lists, Dictionaries etc. */ channel_free_contents(ch); did_free = TRUE; } --safe_to_invoke_callback; return did_free; } void free_unused_channels(int copyID, int mask) { channel_T *ch; channel_T *ch_next; for (ch = first_channel; ch != NULL; ch = ch_next) { ch_next = ch->ch_next; if (!channel_still_useful(ch) && (ch->ch_copyID & mask) != (copyID & mask)) { /* Free the channel struct itself. */ channel_free_channel(ch); } } } #if defined(FEAT_GUI) || defined(PROTO) #if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK) static void channel_read_fd(int fd) { channel_T *channel; ch_part_T part; channel = channel_fd2channel(fd, &part); if (channel == NULL) ch_error(NULL, "Channel for fd %d not found", fd); else channel_read(channel, part, "channel_read_fd"); } #endif /* * Read a command from netbeans. */ #ifdef FEAT_GUI_X11 static void messageFromServerX11(XtPointer clientData, int *unused1 UNUSED, XtInputId *unused2 UNUSED) { channel_read_fd((int)(long)clientData); } #endif #ifdef FEAT_GUI_GTK # if GTK_CHECK_VERSION(3,0,0) static gboolean messageFromServerGtk3(GIOChannel *unused1 UNUSED, GIOCondition unused2 UNUSED, gpointer clientData) { channel_read_fd(GPOINTER_TO_INT(clientData)); return TRUE; /* Return FALSE instead in case the event source is to * be removed after this function returns. */ } # else static void messageFromServerGtk2(gpointer clientData, gint unused1 UNUSED, GdkInputCondition unused2 UNUSED) { channel_read_fd((int)(long)clientData); } # endif #endif static void channel_gui_register_one(channel_T *channel, ch_part_T part) { if (!CH_HAS_GUI) return; /* gets stuck in handling events for a not connected channel */ if (channel->ch_keep_open) return; # ifdef FEAT_GUI_X11 /* Tell notifier we are interested in being called when there is input on * the editor connection socket. */ if (channel->ch_part[part].ch_inputHandler == (XtInputId)NULL) { ch_log(channel, "Registering part %s with fd %d", part_names[part], channel->ch_part[part].ch_fd); channel->ch_part[part].ch_inputHandler = XtAppAddInput( (XtAppContext)app_context, channel->ch_part[part].ch_fd, (XtPointer)(XtInputReadMask + XtInputExceptMask), messageFromServerX11, (XtPointer)(long)channel->ch_part[part].ch_fd); } # else # ifdef FEAT_GUI_GTK /* Tell gdk we are interested in being called when there is input on the * editor connection socket. */ if (channel->ch_part[part].ch_inputHandler == 0) { ch_log(channel, "Registering part %s with fd %d", part_names[part], channel->ch_part[part].ch_fd); # if GTK_CHECK_VERSION(3,0,0) GIOChannel *chnnl = g_io_channel_unix_new( (gint)channel->ch_part[part].ch_fd); channel->ch_part[part].ch_inputHandler = g_io_add_watch( chnnl, G_IO_IN|G_IO_HUP|G_IO_ERR|G_IO_PRI, messageFromServerGtk3, GINT_TO_POINTER(channel->ch_part[part].ch_fd)); g_io_channel_unref(chnnl); # else channel->ch_part[part].ch_inputHandler = gdk_input_add( (gint)channel->ch_part[part].ch_fd, (GdkInputCondition) ((int)GDK_INPUT_READ + (int)GDK_INPUT_EXCEPTION), messageFromServerGtk2, (gpointer)(long)channel->ch_part[part].ch_fd); # endif } # endif # endif } static void channel_gui_register(channel_T *channel) { if (channel->CH_SOCK_FD != INVALID_FD) channel_gui_register_one(channel, PART_SOCK); if (channel->CH_OUT_FD != INVALID_FD && channel->CH_OUT_FD != channel->CH_SOCK_FD) channel_gui_register_one(channel, PART_OUT); if (channel->CH_ERR_FD != INVALID_FD && channel->CH_ERR_FD != channel->CH_SOCK_FD && channel->CH_ERR_FD != channel->CH_OUT_FD) channel_gui_register_one(channel, PART_ERR); } /* * Register any of our file descriptors with the GUI event handling system. * Called when the GUI has started. */ void channel_gui_register_all(void) { channel_T *channel; for (channel = first_channel; channel != NULL; channel = channel->ch_next) channel_gui_register(channel); } static void channel_gui_unregister_one(channel_T *channel, ch_part_T part) { # ifdef FEAT_GUI_X11 if (channel->ch_part[part].ch_inputHandler != (XtInputId)NULL) { ch_log(channel, "Unregistering part %s", part_names[part]); XtRemoveInput(channel->ch_part[part].ch_inputHandler); channel->ch_part[part].ch_inputHandler = (XtInputId)NULL; } # else # ifdef FEAT_GUI_GTK if (channel->ch_part[part].ch_inputHandler != 0) { ch_log(channel, "Unregistering part %s", part_names[part]); # if GTK_CHECK_VERSION(3,0,0) g_source_remove(channel->ch_part[part].ch_inputHandler); # else gdk_input_remove(channel->ch_part[part].ch_inputHandler); # endif channel->ch_part[part].ch_inputHandler = 0; } # endif # endif } static void channel_gui_unregister(channel_T *channel) { ch_part_T part; for (part = PART_SOCK; part < PART_IN; ++part) channel_gui_unregister_one(channel, part); } #endif static char *e_cannot_connect = N_("E902: Cannot connect to port"); /* * Open a socket channel to "hostname":"port". * "waittime" is the time in msec to wait for the connection. * When negative wait forever. * Returns the channel for success. * Returns NULL for failure. */ channel_T * channel_open( char *hostname, int port_in, int waittime, void (*nb_close_cb)(void)) { int sd = -1; struct sockaddr_in server; struct hostent *host; #ifdef WIN32 u_short port = port_in; u_long val = 1; #else int port = port_in; #endif channel_T *channel; int ret; #ifdef WIN32 channel_init_winsock(); #endif channel = add_channel(); if (channel == NULL) { ch_error(NULL, "Cannot allocate channel."); return NULL; } /* Get the server internet address and put into addr structure */ /* fill in the socket address structure and connect to server */ vim_memset((char *)&server, 0, sizeof(server)); server.sin_family = AF_INET; server.sin_port = htons(port); if ((host = gethostbyname(hostname)) == NULL) { ch_error(channel, "in gethostbyname() in channel_open()"); PERROR(_("E901: gethostbyname() in channel_open()")); channel_free(channel); return NULL; } { char *p; /* When using host->h_addr_list[0] directly ubsan warns for it to not * be aligned. First copy the pointer to avoid that. */ memcpy(&p, &host->h_addr_list[0], sizeof(p)); memcpy((char *)&server.sin_addr, p, host->h_length); } /* On Mac and Solaris a zero timeout almost never works. At least wait * one millisecond. Let's do it for all systems, because we don't know why * this is needed. */ if (waittime == 0) waittime = 1; /* * For Unix we need to call connect() again after connect() failed. * On Win32 one time is sufficient. */ while (TRUE) { long elapsed_msec = 0; int waitnow; if (sd >= 0) sock_close(sd); sd = socket(AF_INET, SOCK_STREAM, 0); if (sd == -1) { ch_error(channel, "in socket() in channel_open()."); PERROR(_("E898: socket() in channel_open()")); channel_free(channel); return NULL; } if (waittime >= 0) { /* Make connect() non-blocking. */ if ( #ifdef _WIN32 ioctlsocket(sd, FIONBIO, &val) < 0 #else fcntl(sd, F_SETFL, O_NONBLOCK) < 0 #endif ) { SOCK_ERRNO; ch_error(channel, "channel_open: Connect failed with errno %d", errno); sock_close(sd); channel_free(channel); return NULL; } } /* Try connecting to the server. */ ch_log(channel, "Connecting to %s port %d", hostname, port); ret = connect(sd, (struct sockaddr *)&server, sizeof(server)); if (ret == 0) /* The connection could be established. */ break; SOCK_ERRNO; if (waittime < 0 || (errno != EWOULDBLOCK && errno != ECONNREFUSED #ifdef EINPROGRESS && errno != EINPROGRESS #endif )) { ch_error(channel, "channel_open: Connect failed with errno %d", errno); PERROR(_(e_cannot_connect)); sock_close(sd); channel_free(channel); return NULL; } /* Limit the waittime to 50 msec. If it doesn't work within this * time we close the socket and try creating it again. */ waitnow = waittime > 50 ? 50 : waittime; /* If connect() didn't finish then try using select() to wait for the * connection to be made. For Win32 always use select() to wait. */ #ifndef WIN32 if (errno != ECONNREFUSED) #endif { struct timeval tv; fd_set rfds; fd_set wfds; #ifndef WIN32 int so_error = 0; socklen_t so_error_len = sizeof(so_error); struct timeval start_tv; struct timeval end_tv; #endif FD_ZERO(&rfds); FD_SET(sd, &rfds); FD_ZERO(&wfds); FD_SET(sd, &wfds); tv.tv_sec = waitnow / 1000; tv.tv_usec = (waitnow % 1000) * 1000; #ifndef WIN32 gettimeofday(&start_tv, NULL); #endif ch_log(channel, "Waiting for connection (waiting %d msec)...", waitnow); ret = select((int)sd + 1, &rfds, &wfds, NULL, &tv); if (ret < 0) { SOCK_ERRNO; ch_error(channel, "channel_open: Connect failed with errno %d", errno); PERROR(_(e_cannot_connect)); sock_close(sd); channel_free(channel); return NULL; } #ifdef WIN32 /* On Win32: select() is expected to work and wait for up to * "waitnow" msec for the socket to be open. */ if (FD_ISSET(sd, &wfds)) break; elapsed_msec = waitnow; if (waittime > 1 && elapsed_msec < waittime) { waittime -= elapsed_msec; continue; } #else /* On Linux-like systems: See socket(7) for the behavior * After putting the socket in non-blocking mode, connect() will * return EINPROGRESS, select() will not wait (as if writing is * possible), need to use getsockopt() to check if the socket is * actually able to connect. * We detect a failure to connect when either read and write fds * are set. Use getsockopt() to find out what kind of failure. */ if (FD_ISSET(sd, &rfds) || FD_ISSET(sd, &wfds)) { ret = getsockopt(sd, SOL_SOCKET, SO_ERROR, &so_error, &so_error_len); if (ret < 0 || (so_error != 0 && so_error != EWOULDBLOCK && so_error != ECONNREFUSED # ifdef EINPROGRESS && so_error != EINPROGRESS # endif )) { ch_error(channel, "channel_open: Connect failed with errno %d", so_error); PERROR(_(e_cannot_connect)); sock_close(sd); channel_free(channel); return NULL; } } if (FD_ISSET(sd, &wfds) && so_error == 0) /* Did not detect an error, connection is established. */ break; gettimeofday(&end_tv, NULL); elapsed_msec = (end_tv.tv_sec - start_tv.tv_sec) * 1000 + (end_tv.tv_usec - start_tv.tv_usec) / 1000; #endif } #ifndef WIN32 if (waittime > 1 && elapsed_msec < waittime) { /* The port isn't ready but we also didn't get an error. * This happens when the server didn't open the socket * yet. Select() may return early, wait until the remaining * "waitnow" and try again. */ waitnow -= elapsed_msec; waittime -= elapsed_msec; if (waitnow > 0) { mch_delay((long)waitnow, TRUE); ui_breakcheck(); waittime -= waitnow; } if (!got_int) { if (waittime <= 0) /* give it one more try */ waittime = 1; continue; } /* we were interrupted, behave as if timed out */ } #endif /* We timed out. */ ch_error(channel, "Connection timed out"); sock_close(sd); channel_free(channel); return NULL; } ch_log(channel, "Connection made"); if (waittime >= 0) { #ifdef _WIN32 val = 0; ioctlsocket(sd, FIONBIO, &val); #else (void)fcntl(sd, F_SETFL, 0); #endif } channel->CH_SOCK_FD = (sock_T)sd; channel->ch_nb_close_cb = nb_close_cb; channel->ch_hostname = (char *)vim_strsave((char_u *)hostname); channel->ch_port = port_in; channel->ch_to_be_closed |= (1U << PART_SOCK); #ifdef FEAT_GUI channel_gui_register_one(channel, PART_SOCK); #endif return channel; } /* * Implements ch_open(). */ channel_T * channel_open_func(typval_T *argvars) { char_u *address; char_u *p; char *rest; int port; jobopt_T opt; channel_T *channel = NULL; address = tv_get_string(&argvars[0]); if (argvars[1].v_type != VAR_UNKNOWN && (argvars[1].v_type != VAR_DICT || argvars[1].vval.v_dict == NULL)) { EMSG(_(e_invarg)); return NULL; } /* parse address */ p = vim_strchr(address, ':'); if (p == NULL) { EMSG2(_(e_invarg2), address); return NULL; } *p++ = NUL; port = strtol((char *)p, &rest, 10); if (*address == NUL || port <= 0 || *rest != NUL) { p[-1] = ':'; EMSG2(_(e_invarg2), address); return NULL; } /* parse options */ clear_job_options(&opt); opt.jo_mode = MODE_JSON; opt.jo_timeout = 2000; if (get_job_options(&argvars[1], &opt, JO_MODE_ALL + JO_CB_ALL + JO_WAITTIME + JO_TIMEOUT_ALL, 0) == FAIL) goto theend; if (opt.jo_timeout < 0) { EMSG(_(e_invarg)); goto theend; } channel = channel_open((char *)address, port, opt.jo_waittime, NULL); if (channel != NULL) { opt.jo_set = JO_ALL; channel_set_options(channel, &opt); } theend: free_job_options(&opt); return channel; } static void ch_close_part(channel_T *channel, ch_part_T part) { sock_T *fd = &channel->ch_part[part].ch_fd; if (*fd != INVALID_FD) { if (part == PART_SOCK) sock_close(*fd); else { /* When using a pty the same FD is set on multiple parts, only * close it when the last reference is closed. */ if ((part == PART_IN || channel->CH_IN_FD != *fd) && (part == PART_OUT || channel->CH_OUT_FD != *fd) && (part == PART_ERR || channel->CH_ERR_FD != *fd)) { #ifdef WIN32 if (channel->ch_named_pipe) DisconnectNamedPipe((HANDLE)fd); #endif fd_close(*fd); } } *fd = INVALID_FD; /* channel is closed, may want to end the job if it was the last */ channel->ch_to_be_closed &= ~(1U << part); } } void channel_set_pipes(channel_T *channel, sock_T in, sock_T out, sock_T err) { if (in != INVALID_FD) { ch_close_part(channel, PART_IN); channel->CH_IN_FD = in; # if defined(UNIX) /* Do not end the job when all output channels are closed, wait until * the job ended. */ if (isatty(in)) channel->ch_to_be_closed |= (1U << PART_IN); # endif } if (out != INVALID_FD) { # if defined(FEAT_GUI) channel_gui_unregister_one(channel, PART_OUT); # endif ch_close_part(channel, PART_OUT); channel->CH_OUT_FD = out; channel->ch_to_be_closed |= (1U << PART_OUT); # if defined(FEAT_GUI) channel_gui_register_one(channel, PART_OUT); # endif } if (err != INVALID_FD) { # if defined(FEAT_GUI) channel_gui_unregister_one(channel, PART_ERR); # endif ch_close_part(channel, PART_ERR); channel->CH_ERR_FD = err; channel->ch_to_be_closed |= (1U << PART_ERR); # if defined(FEAT_GUI) channel_gui_register_one(channel, PART_ERR); # endif } } /* * Sets the job the channel is associated with and associated options. * This does not keep a refcount, when the job is freed ch_job is cleared. */ void channel_set_job(channel_T *channel, job_T *job, jobopt_T *options) { channel->ch_job = job; channel_set_options(channel, options); if (job->jv_in_buf != NULL) { chanpart_T *in_part = &channel->ch_part[PART_IN]; set_bufref(&in_part->ch_bufref, job->jv_in_buf); ch_log(channel, "reading from buffer '%s'", (char *)in_part->ch_bufref.br_buf->b_ffname); if (options->jo_set & JO_IN_TOP) { if (options->jo_in_top == 0 && !(options->jo_set & JO_IN_BOT)) { /* Special mode: send last-but-one line when appending a line * to the buffer. */ in_part->ch_bufref.br_buf->b_write_to_channel = TRUE; in_part->ch_buf_append = TRUE; in_part->ch_buf_top = in_part->ch_bufref.br_buf->b_ml.ml_line_count + 1; } else in_part->ch_buf_top = options->jo_in_top; } else in_part->ch_buf_top = 1; if (options->jo_set & JO_IN_BOT) in_part->ch_buf_bot = options->jo_in_bot; else in_part->ch_buf_bot = in_part->ch_bufref.br_buf->b_ml.ml_line_count; } } /* * Find a buffer matching "name" or create a new one. * Returns NULL if there is something very wrong (error already reported). */ static buf_T * find_buffer(char_u *name, int err, int msg) { buf_T *buf = NULL; buf_T *save_curbuf = curbuf; if (name != NULL && *name != NUL) { buf = buflist_findname(name); if (buf == NULL) buf = buflist_findname_exp(name); } if (buf == NULL) { buf = buflist_new(name == NULL || *name == NUL ? NULL : name, NULL, (linenr_T)0, BLN_LISTED | BLN_NEW); if (buf == NULL) return NULL; buf_copy_options(buf, BCO_ENTER); curbuf = buf; #ifdef FEAT_QUICKFIX set_option_value((char_u *)"bt", 0L, (char_u *)"nofile", OPT_LOCAL); set_option_value((char_u *)"bh", 0L, (char_u *)"hide", OPT_LOCAL); #endif if (curbuf->b_ml.ml_mfp == NULL) ml_open(curbuf); if (msg) ml_replace(1, (char_u *)(err ? "Reading from channel error..." : "Reading from channel output..."), TRUE); changed_bytes(1, 0); curbuf = save_curbuf; } return buf; } static void set_callback( char_u **cbp, partial_T **pp, char_u *callback, partial_T *partial) { free_callback(*cbp, *pp); if (callback != NULL && *callback != NUL) { if (partial != NULL) *cbp = partial_name(partial); else { *cbp = vim_strsave(callback); func_ref(*cbp); } } else *cbp = NULL; *pp = partial; if (partial != NULL) ++partial->pt_refcount; } /* * Set various properties from an "opt" argument. */ void channel_set_options(channel_T *channel, jobopt_T *opt) { ch_part_T part; if (opt->jo_set & JO_MODE) for (part = PART_SOCK; part < PART_COUNT; ++part) channel->ch_part[part].ch_mode = opt->jo_mode; if (opt->jo_set & JO_IN_MODE) channel->ch_part[PART_IN].ch_mode = opt->jo_in_mode; if (opt->jo_set & JO_OUT_MODE) channel->ch_part[PART_OUT].ch_mode = opt->jo_out_mode; if (opt->jo_set & JO_ERR_MODE) channel->ch_part[PART_ERR].ch_mode = opt->jo_err_mode; channel->ch_nonblock = opt->jo_noblock; if (opt->jo_set & JO_TIMEOUT) for (part = PART_SOCK; part < PART_COUNT; ++part) channel->ch_part[part].ch_timeout = opt->jo_timeout; if (opt->jo_set & JO_OUT_TIMEOUT) channel->ch_part[PART_OUT].ch_timeout = opt->jo_out_timeout; if (opt->jo_set & JO_ERR_TIMEOUT) channel->ch_part[PART_ERR].ch_timeout = opt->jo_err_timeout; if (opt->jo_set & JO_BLOCK_WRITE) channel->ch_part[PART_IN].ch_block_write = 1; if (opt->jo_set & JO_CALLBACK) set_callback(&channel->ch_callback, &channel->ch_partial, opt->jo_callback, opt->jo_partial); if (opt->jo_set & JO_OUT_CALLBACK) set_callback(&channel->ch_part[PART_OUT].ch_callback, &channel->ch_part[PART_OUT].ch_partial, opt->jo_out_cb, opt->jo_out_partial); if (opt->jo_set & JO_ERR_CALLBACK) set_callback(&channel->ch_part[PART_ERR].ch_callback, &channel->ch_part[PART_ERR].ch_partial, opt->jo_err_cb, opt->jo_err_partial); if (opt->jo_set & JO_CLOSE_CALLBACK) set_callback(&channel->ch_close_cb, &channel->ch_close_partial, opt->jo_close_cb, opt->jo_close_partial); channel->ch_drop_never = opt->jo_drop_never; if ((opt->jo_set & JO_OUT_IO) && opt->jo_io[PART_OUT] == JIO_BUFFER) { buf_T *buf; /* writing output to a buffer. Default mode is NL. */ if (!(opt->jo_set & JO_OUT_MODE)) channel->ch_part[PART_OUT].ch_mode = MODE_NL; if (opt->jo_set & JO_OUT_BUF) { buf = buflist_findnr(opt->jo_io_buf[PART_OUT]); if (buf == NULL) EMSGN(_(e_nobufnr), (long)opt->jo_io_buf[PART_OUT]); } else { int msg = TRUE; if (opt->jo_set2 & JO2_OUT_MSG) msg = opt->jo_message[PART_OUT]; buf = find_buffer(opt->jo_io_name[PART_OUT], FALSE, msg); } if (buf != NULL) { if (opt->jo_set & JO_OUT_MODIFIABLE) channel->ch_part[PART_OUT].ch_nomodifiable = !opt->jo_modifiable[PART_OUT]; if (!buf->b_p_ma && !channel->ch_part[PART_OUT].ch_nomodifiable) { EMSG(_(e_modifiable)); } else { ch_log(channel, "writing out to buffer '%s'", (char *)buf->b_ffname); set_bufref(&channel->ch_part[PART_OUT].ch_bufref, buf); } } } if ((opt->jo_set & JO_ERR_IO) && (opt->jo_io[PART_ERR] == JIO_BUFFER || (opt->jo_io[PART_ERR] == JIO_OUT && (opt->jo_set & JO_OUT_IO) && opt->jo_io[PART_OUT] == JIO_BUFFER))) { buf_T *buf; /* writing err to a buffer. Default mode is NL. */ if (!(opt->jo_set & JO_ERR_MODE)) channel->ch_part[PART_ERR].ch_mode = MODE_NL; if (opt->jo_io[PART_ERR] == JIO_OUT) buf = channel->ch_part[PART_OUT].ch_bufref.br_buf; else if (opt->jo_set & JO_ERR_BUF) { buf = buflist_findnr(opt->jo_io_buf[PART_ERR]); if (buf == NULL) EMSGN(_(e_nobufnr), (long)opt->jo_io_buf[PART_ERR]); } else { int msg = TRUE; if (opt->jo_set2 & JO2_ERR_MSG) msg = opt->jo_message[PART_ERR]; buf = find_buffer(opt->jo_io_name[PART_ERR], TRUE, msg); } if (buf != NULL) { if (opt->jo_set & JO_ERR_MODIFIABLE) channel->ch_part[PART_ERR].ch_nomodifiable = !opt->jo_modifiable[PART_ERR]; if (!buf->b_p_ma && !channel->ch_part[PART_ERR].ch_nomodifiable) { EMSG(_(e_modifiable)); } else { ch_log(channel, "writing err to buffer '%s'", (char *)buf->b_ffname); set_bufref(&channel->ch_part[PART_ERR].ch_bufref, buf); } } } channel->ch_part[PART_OUT].ch_io = opt->jo_io[PART_OUT]; channel->ch_part[PART_ERR].ch_io = opt->jo_io[PART_ERR]; channel->ch_part[PART_IN].ch_io = opt->jo_io[PART_IN]; } /* * Set the callback for "channel"/"part" for the response with "id". */ void channel_set_req_callback( channel_T *channel, ch_part_T part, char_u *callback, partial_T *partial, int id) { cbq_T *head = &channel->ch_part[part].ch_cb_head; cbq_T *item = (cbq_T *)alloc((int)sizeof(cbq_T)); if (item != NULL) { item->cq_partial = partial; if (partial != NULL) { ++partial->pt_refcount; item->cq_callback = callback; } else { item->cq_callback = vim_strsave(callback); func_ref(item->cq_callback); } item->cq_seq_nr = id; item->cq_prev = head->cq_prev; head->cq_prev = item; item->cq_next = NULL; if (item->cq_prev == NULL) head->cq_next = item; else item->cq_prev->cq_next = item; } } static void write_buf_line(buf_T *buf, linenr_T lnum, channel_T *channel) { char_u *line = ml_get_buf(buf, lnum, FALSE); int len = (int)STRLEN(line); char_u *p; int i; /* Need to make a copy to be able to append a NL. */ if ((p = alloc(len + 2)) == NULL) return; memcpy((char *)p, (char *)line, len); if (channel->ch_write_text_mode) p[len] = CAR; else { for (i = 0; i < len; ++i) if (p[i] == NL) p[i] = NUL; p[len] = NL; } p[len + 1] = NUL; channel_send(channel, PART_IN, p, len + 1, "write_buf_line"); vim_free(p); } /* * Return TRUE if "channel" can be written to. * Returns FALSE if the input is closed or the write would block. */ static int can_write_buf_line(channel_T *channel) { chanpart_T *in_part = &channel->ch_part[PART_IN]; if (in_part->ch_fd == INVALID_FD) return FALSE; /* pipe was closed */ /* for testing: block every other attempt to write */ if (in_part->ch_block_write == 1) in_part->ch_block_write = -1; else if (in_part->ch_block_write == -1) in_part->ch_block_write = 1; /* TODO: Win32 implementation, probably using WaitForMultipleObjects() */ #ifndef WIN32 { # if defined(HAVE_SELECT) struct timeval tval; fd_set wfds; int ret; FD_ZERO(&wfds); FD_SET((int)in_part->ch_fd, &wfds); tval.tv_sec = 0; tval.tv_usec = 0; for (;;) { ret = select((int)in_part->ch_fd + 1, NULL, &wfds, NULL, &tval); # ifdef EINTR SOCK_ERRNO; if (ret == -1 && errno == EINTR) continue; # endif if (ret <= 0 || in_part->ch_block_write == 1) { if (ret > 0) ch_log(channel, "FAKED Input not ready for writing"); else ch_log(channel, "Input not ready for writing"); return FALSE; } break; } # else struct pollfd fds; fds.fd = in_part->ch_fd; fds.events = POLLOUT; if (poll(&fds, 1, 0) <= 0) { ch_log(channel, "Input not ready for writing"); return FALSE; } if (in_part->ch_block_write == 1) { ch_log(channel, "FAKED Input not ready for writing"); return FALSE; } # endif } #endif return TRUE; } /* * Write any buffer lines to the input channel. */ static void channel_write_in(channel_T *channel) { chanpart_T *in_part = &channel->ch_part[PART_IN]; linenr_T lnum; buf_T *buf = in_part->ch_bufref.br_buf; int written = 0; if (buf == NULL || in_part->ch_buf_append) return; /* no buffer or using appending */ if (!bufref_valid(&in_part->ch_bufref) || buf->b_ml.ml_mfp == NULL) { /* buffer was wiped out or unloaded */ ch_log(channel, "input buffer has been wiped out"); in_part->ch_bufref.br_buf = NULL; return; } for (lnum = in_part->ch_buf_top; lnum <= in_part->ch_buf_bot && lnum <= buf->b_ml.ml_line_count; ++lnum) { if (!can_write_buf_line(channel)) break; write_buf_line(buf, lnum, channel); ++written; } if (written == 1) ch_log(channel, "written line %d to channel", (int)lnum - 1); else if (written > 1) ch_log(channel, "written %d lines to channel", written); in_part->ch_buf_top = lnum; if (lnum > buf->b_ml.ml_line_count || lnum > in_part->ch_buf_bot) { #if defined(FEAT_TERMINAL) /* Send CTRL-D or "eof_chars" to close stdin on MS-Windows. */ if (channel->ch_job != NULL) term_send_eof(channel); #endif /* Writing is done, no longer need the buffer. */ in_part->ch_bufref.br_buf = NULL; ch_log(channel, "Finished writing all lines to channel"); /* Close the pipe/socket, so that the other side gets EOF. */ ch_close_part(channel, PART_IN); } else ch_log(channel, "Still %ld more lines to write", (long)(buf->b_ml.ml_line_count - lnum + 1)); } /* * Handle buffer "buf" being freed, remove it from any channels. */ void channel_buffer_free(buf_T *buf) { channel_T *channel; ch_part_T part; for (channel = first_channel; channel != NULL; channel = channel->ch_next) for (part = PART_SOCK; part < PART_COUNT; ++part) { chanpart_T *ch_part = &channel->ch_part[part]; if (ch_part->ch_bufref.br_buf == buf) { ch_log(channel, "%s buffer has been wiped out", part_names[part]); ch_part->ch_bufref.br_buf = NULL; } } } /* * Write any lines waiting to be written to "channel". */ static void channel_write_input(channel_T *channel) { chanpart_T *in_part = &channel->ch_part[PART_IN]; if (in_part->ch_writeque.wq_next != NULL) channel_send(channel, PART_IN, (char_u *)"", 0, "channel_write_input"); else if (in_part->ch_bufref.br_buf != NULL) { if (in_part->ch_buf_append) channel_write_new_lines(in_part->ch_bufref.br_buf); else channel_write_in(channel); } } /* * Write any lines waiting to be written to a channel. */ void channel_write_any_lines(void) { channel_T *channel; for (channel = first_channel; channel != NULL; channel = channel->ch_next) channel_write_input(channel); } /* * Write appended lines above the last one in "buf" to the channel. */ void channel_write_new_lines(buf_T *buf) { channel_T *channel; int found_one = FALSE; /* There could be more than one channel for the buffer, loop over all of * them. */ for (channel = first_channel; channel != NULL; channel = channel->ch_next) { chanpart_T *in_part = &channel->ch_part[PART_IN]; linenr_T lnum; int written = 0; if (in_part->ch_bufref.br_buf == buf && in_part->ch_buf_append) { if (in_part->ch_fd == INVALID_FD) continue; /* pipe was closed */ found_one = TRUE; for (lnum = in_part->ch_buf_bot; lnum < buf->b_ml.ml_line_count; ++lnum) { if (!can_write_buf_line(channel)) break; write_buf_line(buf, lnum, channel); ++written; } if (written == 1) ch_log(channel, "written line %d to channel", (int)lnum - 1); else if (written > 1) ch_log(channel, "written %d lines to channel", written); if (lnum < buf->b_ml.ml_line_count) ch_log(channel, "Still %ld more lines to write", (long)(buf->b_ml.ml_line_count - lnum)); in_part->ch_buf_bot = lnum; } } if (!found_one) buf->b_write_to_channel = FALSE; } /* * Invoke the "callback" on channel "channel". * This does not redraw but sets channel_need_redraw; */ static void invoke_callback(channel_T *channel, char_u *callback, partial_T *partial, typval_T *argv) { typval_T rettv; int dummy; if (safe_to_invoke_callback == 0) IEMSG("INTERNAL: Invoking callback when it is not safe"); argv[0].v_type = VAR_CHANNEL; argv[0].vval.v_channel = channel; call_func(callback, (int)STRLEN(callback), &rettv, 2, argv, NULL, 0L, 0L, &dummy, TRUE, partial, NULL); clear_tv(&rettv); channel_need_redraw = TRUE; } /* * Return the first node from "channel"/"part" without removing it. * Returns NULL if there is nothing. */ readq_T * channel_peek(channel_T *channel, ch_part_T part) { readq_T *head = &channel->ch_part[part].ch_head; return head->rq_next; } /* * Return a pointer to the first NL in "node". * Skips over NUL characters. * Returns NULL if there is no NL. */ char_u * channel_first_nl(readq_T *node) { char_u *buffer = node->rq_buffer; long_u i; for (i = 0; i < node->rq_buflen; ++i) if (buffer[i] == NL) return buffer + i; return NULL; } /* * Return the first buffer from channel "channel"/"part" and remove it. * The caller must free it. * Returns NULL if there is nothing. */ char_u * channel_get(channel_T *channel, ch_part_T part) { readq_T *head = &channel->ch_part[part].ch_head; readq_T *node = head->rq_next; char_u *p; if (node == NULL) return NULL; /* dispose of the node but keep the buffer */ p = node->rq_buffer; head->rq_next = node->rq_next; if (node->rq_next == NULL) head->rq_prev = NULL; else node->rq_next->rq_prev = NULL; vim_free(node); return p; } /* * Returns the whole buffer contents concatenated for "channel"/"part". * Replaces NUL bytes with NL. */ static char_u * channel_get_all(channel_T *channel, ch_part_T part) { readq_T *head = &channel->ch_part[part].ch_head; readq_T *node = head->rq_next; long_u len = 0; char_u *res; char_u *p; /* If there is only one buffer just get that one. */ if (head->rq_next == NULL || head->rq_next->rq_next == NULL) return channel_get(channel, part); /* Concatenate everything into one buffer. */ for (node = head->rq_next; node != NULL; node = node->rq_next) len += node->rq_buflen; res = lalloc(len + 1, TRUE); if (res == NULL) return NULL; p = res; for (node = head->rq_next; node != NULL; node = node->rq_next) { mch_memmove(p, node->rq_buffer, node->rq_buflen); p += node->rq_buflen; } *p = NUL; /* Free all buffers */ do { p = channel_get(channel, part); vim_free(p); } while (p != NULL); /* turn all NUL into NL */ while (len > 0) { --len; if (res[len] == NUL) res[len] = NL; } return res; } /* * Consume "len" bytes from the head of "node". * Caller must check these bytes are available. */ void channel_consume(channel_T *channel, ch_part_T part, int len) { readq_T *head = &channel->ch_part[part].ch_head; readq_T *node = head->rq_next; char_u *buf = node->rq_buffer; mch_memmove(buf, buf + len, node->rq_buflen - len); node->rq_buflen -= len; } /* * Collapses the first and second buffer for "channel"/"part". * Returns FAIL if that is not possible. * When "want_nl" is TRUE collapse more buffers until a NL is found. */ int channel_collapse(channel_T *channel, ch_part_T part, int want_nl) { readq_T *head = &channel->ch_part[part].ch_head; readq_T *node = head->rq_next; readq_T *last_node; readq_T *n; char_u *newbuf; char_u *p; long_u len; if (node == NULL || node->rq_next == NULL) return FAIL; last_node = node->rq_next; len = node->rq_buflen + last_node->rq_buflen + 1; if (want_nl) while (last_node->rq_next != NULL && channel_first_nl(last_node) == NULL) { last_node = last_node->rq_next; len += last_node->rq_buflen; } p = newbuf = alloc(len); if (newbuf == NULL) return FAIL; /* out of memory */ mch_memmove(p, node->rq_buffer, node->rq_buflen); p += node->rq_buflen; vim_free(node->rq_buffer); node->rq_buffer = newbuf; for (n = node; n != last_node; ) { n = n->rq_next; mch_memmove(p, n->rq_buffer, n->rq_buflen); p += n->rq_buflen; vim_free(n->rq_buffer); } node->rq_buflen = (long_u)(p - newbuf); /* dispose of the collapsed nodes and their buffers */ for (n = node->rq_next; n != last_node; ) { n = n->rq_next; vim_free(n->rq_prev);
26.091246
335
0.612239
[ "shape", "vector", "3d" ]
5524ca42a067052acfc3d4585ff722fab03a1adf
3,356
h
C
lib/AerisMapKit.xcframework/tvos-arm64_x86_64-simulator/AerisMapKit.framework/Headers/AWFCombinedSource.h
aerisweather/aerisweather-ios
a1d6dcb02b0f4a26edfa1829f4161f21ddc5e5e0
[ "BSD-3-Clause" ]
null
null
null
lib/AerisMapKit.xcframework/tvos-arm64_x86_64-simulator/AerisMapKit.framework/Headers/AWFCombinedSource.h
aerisweather/aerisweather-ios
a1d6dcb02b0f4a26edfa1829f4161f21ddc5e5e0
[ "BSD-3-Clause" ]
null
null
null
lib/AerisMapKit.xcframework/tvos-arm64_x86_64-simulator/AerisMapKit.framework/Headers/AWFCombinedSource.h
aerisweather/aerisweather-ios
a1d6dcb02b0f4a26edfa1829f4161f21ddc5e5e0
[ "BSD-3-Clause" ]
null
null
null
// // AWFCombinedSource.h // AerisMap // // Created by Nicholas Shipes on 8/14/14. // Copyright (c) 2014 AerisWeather, LLC. All rights reserved. // #import <AerisMapKit/AWFPointSource.h> NS_ASSUME_NONNULL_BEGIN @class AWFDataRepresentableStyle; /** An `AWFCombinedSource` object represents a data source that manages a combination of different overlays on a map. Specifically, this layer type manages annotations, overlays, polygons and polylines needed to display a specific data layer. */ @interface AWFCombinedSource : AWFPointSource /** The overlays being managed by the source (readonly). */ @property (readonly, nonatomic, strong, nullable) NSArray *overlays; /** The polygons being managed by the source (readonly). */ @property (readonly, nonatomic, strong, nullable) NSArray<NSObject<AWFPolygon> *> *polygons; /** The polylines being managed by the source (readonly). */ @property (readonly, nonatomic, strong, nullable) NSArray<NSObject<AWFPolyline> *> *polylines; /** The style to apply to the source's overlays. */ @property (nonatomic, strong, nullable) id overlayStyle; @property (nonatomic, strong, nullable) AWFDataRepresentableStyle *styleProvider; /** An array of animations associated with the content source. For combined sources, each map data representable type will have its own animation instance for managing the rendering of data for that map representable type. */ @property (nonatomic, strong, nullable) NSArray<AWFAnimation *> *animations; /** Determines whether the map source should show annotations during an animation, which is `YES` by default. */ @property (nonatomic, assign) BOOL showAnnotationsDuringAnimation; /** Determines whether the map source should show overlays during an animation, which is `NO` by default. */ @property (nonatomic, assign) BOOL showOverlaysDuringAnimation; /** Determines whether the map source should show polygons during an animation, which is `NO` by default. */ @property (nonatomic, assign) BOOL showPolygonsDuringAnimation; /** Determines whether the map source should show polylines during an animation, which is `NO` by default. */ @property (nonatomic, assign) BOOL showPolylinesDuringAnimation; /** Returns a single overlay representing a set of objects on the map based on a specific group identifier. @param identifier The group identifier to return an overlay for. @return Returns a single map overlay object, which varies depending on the map strategy being used. */ - (nullable NSArray *)overlayForIdentifier:(NSString *)identifier; /** Returns an array of polygons representing a set of objects on the map based on a specific group identifier. @param identifier The group identifier to return polygons for. @return Returns an array of map polygon objects, which varies depending on the map strategy being used. */ - (nullable NSArray<NSObject<AWFPolygon> *> *)polygonsForIdentifier:(NSString *)identifier; /** Returns an array of polylines representing a set of objects on the map based on a specific group identifier. @param identifier The group identifier to return polylines for. @return Returns an array of map polyline objects, which varies depending on the map strategy being used. */ - (nullable NSArray<NSObject<AWFPolyline> *> *)polylinesForIdentifier:(NSString *)identifier; @end NS_ASSUME_NONNULL_END
34.958333
155
0.771454
[ "object" ]
5534bd3f3927b2c2567e67168dd31535b214629b
2,116
h
C
SculptEngine/CppLib/src/Mesh/Loop.h
ErwanLeGoffic/Tectrid
81eb17410339c683905c0f7f16dc4f1dd6b6ddeb
[ "MIT" ]
2
2019-12-14T02:06:52.000Z
2022-01-12T19:25:03.000Z
SculptEngine/CppLib/src/Mesh/Loop.h
ErwanLeGoffic/Tectrid
81eb17410339c683905c0f7f16dc4f1dd6b6ddeb
[ "MIT" ]
1
2020-02-08T07:34:49.000Z
2020-02-08T07:34:49.000Z
SculptEngine/CppLib/src/Mesh/Loop.h
ErwanLeGoffic/Tectrid
81eb17410339c683905c0f7f16dc4f1dd6b6ddeb
[ "MIT" ]
1
2019-01-27T22:32:49.000Z
2019-01-27T22:32:49.000Z
#ifndef _LOOPS_H_ #define _LOOPS_H_ #include <memory> #include <vector> #include <map> #include "Collisions\Ray.h" class Mesh; class BSphere; class BBox; class LoopElement { public: LoopElement(unsigned int vtxId): _prev(nullptr), _vtxId(vtxId), _next(nullptr) { } ~LoopElement() { ASSERT((_next == nullptr) || (_vtxId != _next->_vtxId)); if(_prev != nullptr) _prev->_next = nullptr; if(_next != nullptr) _next->_prev = nullptr; delete _next; } LoopElement const* GetPrev() const { return _prev; } void SetPrev(LoopElement* prev, Mesh const& _mesh); unsigned int GetVtxId() const { return _vtxId; } LoopElement const* GetNext() const { return _next; } LoopElement* GrabNext() { return _next; } void SetNext(LoopElement* next, Mesh const& _mesh); void ReverserLinking(LoopElement *source); // Recursively switch next and prev Ray const& GetRayToPrev() const { return _rayToPrev; } Ray const& GetRayToNext() const { return _rayToNext; } private: void ComputeRay(Vector3 const& a, Vector3 const& b, Ray& outRay); LoopElement* _prev; Ray _rayToPrev; // Ray from the vertex to prev vertex // Todo: try to remove it (and keep _rayToNext only) unsigned int _vtxId; Ray _rayToNext; // Ray from the vertex to next vertex LoopElement* _next; }; class Loop { public: Loop(LoopElement* root): _root(root) { } LoopElement const* GetRoot() const { return _root.get(); } bool Intersects(BSphere const& sphere) const; bool Intersects(BBox const& box) const; unsigned int CountElements() const; bool IsEmpty() const { return _root == nullptr; } bool IsClosed() const; bool IsClockwize(Vector3 const& loopCenter, Vector3 const& loopCenterNormal, std::vector<Vector3> const& vertices); private: std::unique_ptr<LoopElement> _root; }; class LoopBuilder { public: LoopBuilder(Mesh const& mesh): _mesh(mesh) {} bool RegisterEdge(unsigned int idVtx1, unsigned int idVtx2); void BuildLoops(std::vector<Loop>& outLoops); private: std::map<unsigned int, LoopElement*> _registeredLoopElements; // associate vtx ID to the loop element Mesh const& _mesh; }; #endif // _LOOPS_H_
24.894118
116
0.724953
[ "mesh", "vector" ]
553c004e0aeead1b4b6828fe645afdf7be592252
5,942
c
C
minix-2.0/fs/usr/src/kernel/dmp.c
jorenvo/minix2
a2a4c092b95f806035d28a1169df68205c599904
[ "BSD-3-Clause" ]
71
2017-04-03T22:37:27.000Z
2022-02-20T04:27:19.000Z
minix-2.0/fs/usr/src/kernel/dmp.c
jorenvo/minix2
a2a4c092b95f806035d28a1169df68205c599904
[ "BSD-3-Clause" ]
3
2017-10-04T12:45:32.000Z
2021-07-16T12:13:49.000Z
minix-2.0/fs/usr/src/kernel/dmp.c
jorenvo/minix2
a2a4c092b95f806035d28a1169df68205c599904
[ "BSD-3-Clause" ]
30
2017-09-26T23:10:58.000Z
2021-10-01T04:46:12.000Z
/* This file contains some dumping routines for debugging. */ #include "kernel.h" #include <minix/com.h> #include "proc.h" FORWARD _PROTOTYPE(char *proc_name, (int proc_nr)); #define click_to_round_k(n) \ ((unsigned) ((((unsigned long) (n) << CLICK_SHIFT) + 512) / 1024)) /*===========================================================================* * p_dmp * *===========================================================================*/ #if (CHIP == INTEL) PUBLIC void p_dmp() { /* Proc table dump */ register struct proc *rp; static struct proc *oldrp = BEG_PROC_ADDR; int n = 0; phys_clicks text, data, size; printf("\n--pid --pc- ---sp- flag -user --sys-- -text- -data- -size- -recv- command\n"); for (rp = oldrp; rp < END_PROC_ADDR; rp++) { if (isemptyp(rp)) continue; if (++n > 20) break; text = rp->p_map[T].mem_phys; data = rp->p_map[D].mem_phys; size = rp->p_map[T].mem_len + ((rp->p_map[S].mem_phys + rp->p_map[S].mem_len) - data); if (rp->p_pid == 0) { printf("(%3d)", proc_number(rp)); } else { printf("%5d", rp->p_pid); } printf(" %5lx %6lx %2x %7lu %7lu %5uK %5uK %5uK ", (unsigned long) rp->p_reg.pc, (unsigned long) rp->p_reg.sp, rp->p_flags, rp->user_time, rp->sys_time, click_to_round_k(text), click_to_round_k(data), click_to_round_k(size)); if (rp->p_flags & RECEIVING) { printf("%-7.7s", proc_name(rp->p_getfrom)); } else if (rp->p_flags & SENDING) { printf("S:%-5.5s", proc_name(rp->p_sendto)); } else if (rp->p_flags == 0) { printf(" "); } printf("%s\n", rp->p_name); } if (rp == END_PROC_ADDR) rp = BEG_PROC_ADDR; else printf("--more--\r"); oldrp = rp; } #endif /* (CHIP == INTEL) */ /*===========================================================================* * map_dmp * *===========================================================================*/ PUBLIC void map_dmp() { register struct proc *rp; static struct proc *oldrp = cproc_addr(HARDWARE); int n = 0; phys_clicks size; printf("\nPROC NAME- -----TEXT----- -----DATA----- ----STACK----- -SIZE-\n"); for (rp = oldrp; rp < END_PROC_ADDR; rp++) { if (isemptyp(rp)) continue; if (++n > 20) break; size = rp->p_map[T].mem_len + ((rp->p_map[S].mem_phys + rp->p_map[S].mem_len) - rp->p_map[D].mem_phys); printf("%3d %-6.6s %4x %4x %4x %4x %4x %4x %4x %4x %4x %5uK\n", proc_number(rp), rp->p_name, rp->p_map[T].mem_vir, rp->p_map[T].mem_phys, rp->p_map[T].mem_len, rp->p_map[D].mem_vir, rp->p_map[D].mem_phys, rp->p_map[D].mem_len, rp->p_map[S].mem_vir, rp->p_map[S].mem_phys, rp->p_map[S].mem_len, click_to_round_k(size)); } if (rp == END_PROC_ADDR) rp = cproc_addr(HARDWARE); else printf("--more--\r"); oldrp = rp; } #if (CHIP == M68000) FORWARD _PROTOTYPE(void mem_dmp, (char *adr, int len)); /*===========================================================================* * p_dmp * *===========================================================================*/ PUBLIC void p_dmp() { /* Proc table dump */ register struct proc *rp; static struct proc *oldrp = BEG_PROC_ADDR; int n = 0; vir_clicks base, limit; printf( "\nproc pid pc sp splow flag user sys recv command\n"); for (rp = oldrp; rp < END_PROC_ADDR; rp++) { if (isemptyp(rp)) continue; if (++n > 20) break; base = rp->p_map[T].mem_phys; limit = rp->p_map[S].mem_phys + rp->p_map[S].mem_len; printf("%4u %4u %6lx %6lx %6lx %4x %5lu %6lu ", proc_number(rp), rp->p_pid, (unsigned long) rp->p_reg.pc, (unsigned long) rp->p_reg.sp, (unsigned long) rp->p_splow, rp->p_flags, rp->user_time, rp->sys_time); if (rp->p_flags & RECEIVING) { printf("%-7.7s", proc_name(rp->p_getfrom)); } else if (rp->p_flags & SENDING) { printf("S:%-5.5s", proc_name(rp->p_sendto)); } else if (rp->p_flags == 0) { printf(" "); } printf("%s\n", rp->p_name); } if (rp == END_PROC_ADDR) rp = BEG_PROC_ADDR; else printf("--more--\r"); oldrp = rp; } /*===========================================================================* * reg_dmp * *===========================================================================*/ PUBLIC void reg_dmp(rp) struct proc *rp; { register int i; static char *regs[NR_REGS] = { "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "a0", "a1", "a2", "a3", "a4", "a5", "a6" }; reg_t *regptr = (reg_t *) & rp->p_reg; printf("reg = %08lx, ", rp); printf("ksp = %08lx\n", (long) &rp + sizeof(rp)); printf(" pc = %08lx, ", rp->p_reg.pc); printf(" sr = %04x, ", rp->p_reg.psw); printf("trp = %2x\n", rp->p_trap); for (i = 0; i < NR_REGS; i++) printf("%3s = %08lx%s",regs[i], *regptr++, (i&3) == 3 ? "\n" : ", "); printf(" a7 = %08lx\n", rp->p_reg.sp); mem_dmp((char *) (((long) rp->p_reg.pc & ~31L) - 96), 128); mem_dmp((char *) (((long) rp->p_reg.sp & ~31L) - 32), 256); } /*===========================================================================* * mem_dmp * *===========================================================================*/ PRIVATE void mem_dmp(adr, len) char *adr; int len; { register i; register long *p; for (i = 0, p = (long *) adr; i < len; i += 4) { #if (CHIP == M68000) if ((i & 31) == 0) printf("\n%lX:", p); printf(" %8lX", *p++); #else if ((i & 31) == 0) printf("\n%X:", p); printf(" %8X", *p++); #endif /* (CHIP == M68000) */ } printf("\n"); } #endif /* (CHIP == M68000) */ /*===========================================================================* * proc_name * *===========================================================================*/ PRIVATE char *proc_name(proc_nr) int proc_nr; { if (proc_nr == ANY) return "ANY"; return proc_addr(proc_nr)->p_name; }
30.010101
90
0.464322
[ "3d" ]