*/}}

la_util.c 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754
  1. /*
  2. * LaGUI: A graphical application framework.
  3. * Copyright (C) 2022-2023 Wu Yiming
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #define _CRT_SEQURE_NO_WARNINGS
  19. #include "la_util.h"
  20. #include "la_interface.h"
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. laSafeStringCollection SSC;
  24. extern LA MAIN;
  25. #define BYTE unsigned char
  26. uint32_t laToUnicode(const unsigned char* ch, int* advance){
  27. if((*ch)<0x80) { *advance=1; return *ch; }
  28. uint32_t u=0;
  29. if(((*ch)>>5)==0x06){ *advance=2; u|=((*(ch+1))&0x3f)|((*(ch)&0x1f)<<6); return u; }
  30. if(((*ch)>>4)==0x0e){ *advance=3; u|=((*(ch+2))&0x3f)|((*(ch+1)&0x3f)<<6)|((*(ch)&0x0f)<<12); return u; }
  31. if(((*ch)>>3)==0x1e){ *advance=4; u|=((*(ch+3))&0x3f)|((*(ch+2)&0x3f)<<6)|((*(ch+1)&0x3f)<<12)|((*(ch)&0x07)<<18); return u; }
  32. *advance=1; return '?';
  33. }
  34. int laToUTF8(const uint32_t ch, unsigned char* out, unsigned char** next){
  35. if(ch>=0x10000){ out[0]=0xf0|(ch>>18); out[1]=0x80|(0x3f&(ch>>12)); out[2]=0x80|(0x3f&(ch>>6)); out[3]=0x80|(0x3f&ch); (*next)+=4;}
  36. elif(ch>=0x800){ out[0]=0xe0|(ch>>12); out[1]=0x80|(0x3f&(ch>>6)); out[2]=0x80|(0x3f&ch); (*next)+=3;}
  37. elif(ch>=0x80){ out[0]=0xc0|(ch>>6); out[1]=0x80|(0x3f&ch); (*next)+=2;}
  38. else { if(!ch){return 0;} out[0]=ch&0x7f; (*next)++;} return 1;
  39. }
  40. int strToUnicode(uint32_t* target, unsigned char* const src){
  41. uint32_t UC,adv,i=0; unsigned char* source=src; while(target[i]=laToUnicode(source, &adv)) { source+=adv; i++; } target[i]=0; return i;
  42. }
  43. int strToUTF8Lim(unsigned char* target, uint32_t* const src, int count){
  44. if(count<=0){ return 0; }
  45. uint32_t* source=src; unsigned char* out=target; int i=0; while(laToUTF8(*source, out, &out)){ source++; i++; if(i>=count) break; } *out=0; return out-target;
  46. }
  47. int strToUTF8(unsigned char* target, uint32_t* const src){
  48. return strToUTF8Lim(target,src,INT_MAX);
  49. }
  50. int strlenU(uint32_t* str){ int i=0; while(str[i]!=0) i++; return i; }
  51. void strcpyU(uint32_t* target, uint32_t* const source ){ int i=0; while(source[i]!=0){ target[i]=source[i]; i++; } target[i]=0; }
  52. void strcatU(uint32_t* target, uint32_t* const source ){ int i=0,tl=strlenU(target); while(source[i]!=0){ target[i+tl]=source[i]; i++; } target[i+tl]=0; }
  53. struct tm *laGetFullTime(){
  54. time_t t = time(0);
  55. return localtime(&t);
  56. }
  57. void laRecordTime(laTimeRecorder *tr){
  58. #if (defined(LA_LINUX) || defined(LAGUI_ANDROID))
  59. clock_gettime(CLOCK_REALTIME, &tr->ts);
  60. #endif
  61. #ifdef _WIN32
  62. QueryPerformanceCounter(&tr->tm);
  63. #endif
  64. }
  65. real laTimeElapsedSecondsf(laTimeRecorder *End, laTimeRecorder *Begin){
  66. real sec=0;
  67. #if (defined(LA_LINUX) || defined(LAGUI_ANDROID))
  68. sec=End->ts.tv_sec-Begin->ts.tv_sec; sec+=((End->ts.tv_nsec-Begin->ts.tv_nsec)/1e9);
  69. #endif
  70. #ifdef _WIN32
  71. LARGE_INTEGER perfCnt; QueryPerformanceFrequency(&perfCnt);
  72. sec = ((real)(End->tm.QuadPart - Begin->tm.QuadPart))/ perfCnt.QuadPart;
  73. #endif
  74. return sec;
  75. }
  76. void laSetAuthorInfo(char *Name, char *CopyrightString){
  77. strSafeSet(&MAIN.Author.Name, Name);
  78. strSafeSet(&MAIN.Author.CopyrightString, CopyrightString);
  79. }
  80. void memCreateNUID(char* buf,laMemNodeHyper* Hyper){
  81. sprintf(buf, "%08X-%hd%02hd%02hd%02hd%02hd%02hd", Hyper, LA_HYPER_CREATED_TIME(Hyper));
  82. }
  83. void memHyperInfo(laPropPack* pp, char* buf){
  84. int level=0;void* head=0;
  85. laMemNodeHyper* hi; laMemNode* mn;
  86. int a=0, count=0, pc;
  87. laProp* p=pp->LastPs->p;
  88. laPropContainer* c=p->Container;
  89. if(c->OtherAlloc){
  90. count=lstCountElements(&c->LocalUsers);
  91. }else{
  92. head=memGetHead(pp->LastPs->UseInstance, &level);
  93. if(!level){
  94. sprintf(buf,"Not HyperData.\n");
  95. }elif(level==1){
  96. mn=head; count=lstCountElements(&mn->Users);
  97. }elif(level==2){
  98. hi=head; count=lstCountElements(&hi->Users);
  99. }
  100. }
  101. a=sprintf(buf,"HyperData:\n\tProperty:%s\n\tContainer:%s (%d users)\n",
  102. pp->LastPs->p->Identifier, pp->LastPs->p->Container->Identifier, count);
  103. if(level==2){
  104. sprintf(buf+a,"\tCreated:%hd-%02hd-%02hd %02hd:%02hd:%02hd\n",LA_HYPER_CREATED_TIME(hi));
  105. }
  106. }
  107. void memMakeHyperData(laMemNodeHyper* hi){
  108. struct tm *time;
  109. hi->Modified = 1;
  110. time = laGetFullTime();
  111. //hi->CreatedBy = &MAIN.Author;
  112. hi->TimeCreated.Year = time->tm_year + 1900;
  113. hi->TimeCreated.Month = time->tm_mon + 1;
  114. hi->TimeCreated.Day = time->tm_mday;
  115. hi->TimeCreated.Hour = time->tm_hour;
  116. hi->TimeCreated.Minute = time->tm_min;
  117. hi->TimeCreated.Second = time->tm_sec;
  118. //memcpy(&hi->TimeModified, &hi->TimeCreated, sizeof(laTimeInfo));
  119. memCreateNUID(hi->NUID.String,hi);
  120. }
  121. void memMarkClean(void* HyperUserMem){
  122. int Hyper=0;
  123. laMemNodeHyper* h = memGetHead(HyperUserMem, &Hyper);
  124. if(Hyper!=2) return;
  125. h->Modified=0;
  126. }
  127. void nutFreeMem(void **ptr){
  128. //free_total+=1;
  129. if (!*ptr) return;
  130. free(*ptr);
  131. *ptr = 0;
  132. }
  133. int nutFloatCompare(real l, real r){
  134. return (l > r - 0.00005 && l < r + 0.00005);
  135. }
  136. int nutSameAddress(void *l, void *r){
  137. return (l == r);
  138. }
  139. //===================================================================[barray]
  140. #ifdef _MSC_VER
  141. # include <intrin.h>
  142. # define __builtin_popcountll __popcnt64
  143. static inline int __builtin_ctzl(u64bit x)
  144. {
  145. #ifdef _WIN64
  146. return (int)_tzcnt_u64(x);
  147. #else
  148. return !!unsigned(x) ? __builtin_ctz((unsigned)x) : 32 + __builtin_ctz((unsigned)(x >> 32));
  149. #endif
  150. }
  151. #endif
  152. barray_t *barray_init(size_t num_bits)
  153. {
  154. size_t num_longs = BITS_TO_LONGS(num_bits);
  155. barray_t *barray = calloc(1,sizeof(u64bit) * num_longs + sizeof(barray_t));
  156. barray->num_bits = num_bits;
  157. barray->num_longs = num_longs;
  158. return barray;
  159. }
  160. void barray_free(barray_t *barray)
  161. {
  162. free(barray);
  163. }
  164. u64bit *barray_data(barray_t *barray)
  165. {
  166. return barray->data;
  167. }
  168. size_t barray_count_set(barray_t *barray)
  169. {
  170. size_t count = 0;
  171. for (int i = 0; i < barray->num_longs; i++)
  172. count += __builtin_popcountll(barray->data[i]);
  173. return count;
  174. }
  175. void barray_set(barray_t *barray, bit_t bit)
  176. {
  177. if (bit >= barray->num_bits)
  178. return;
  179. int index = bit / BITS_PER_LONG;
  180. int shift = bit % BITS_PER_LONG;
  181. barray->data[index] |= ((u64bit)1 << shift);
  182. }
  183. void barray_clear(barray_t *barray, bit_t bit)
  184. {
  185. if (bit >= barray->num_bits)
  186. return;
  187. int index = bit / BITS_PER_LONG;
  188. int shift = bit % BITS_PER_LONG;
  189. barray->data[index] &= ~((u64bit)1 << shift);
  190. }
  191. bool barray_is_set(barray_t *barray, bit_t bit)
  192. {
  193. if (bit >= barray->num_bits)
  194. return false;
  195. int index = bit / BITS_PER_LONG;
  196. int shift = bit % BITS_PER_LONG;
  197. return (barray->data[index] & ((u64bit)1 << shift)) != 0;
  198. }
  199. void barray_foreach_set(barray_t *barray, barray_callback_t callback, void *arg)
  200. {
  201. for (int i = 0; i < barray->num_longs; i++)
  202. {
  203. u64bit bits = barray->data[i];
  204. while (bits != 0)
  205. {
  206. callback(i * BITS_PER_LONG + __builtin_ctzl(bits), arg);
  207. bits ^= (bits & -bits);
  208. }
  209. }
  210. }
  211. //===================================================================[md5]
  212. #define A 0x67452301
  213. #define B 0xefcdab89
  214. #define C 0x98badcfe
  215. #define D 0x10325476
  216. static uint32_t S[] = {7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
  217. 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
  218. 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
  219. 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21};
  220. static uint32_t K[] = {0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
  221. 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
  222. 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
  223. 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
  224. 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
  225. 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
  226. 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
  227. 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
  228. 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
  229. 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
  230. 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
  231. 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
  232. 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
  233. 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
  234. 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
  235. 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391};
  236. static uint8_t PADDING[] = {0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  237. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  238. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  239. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  240. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  241. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  242. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  243. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  244. #define F(X, Y, Z) ((X & Y) | (~X & Z))
  245. #define G(X, Y, Z) ((X & Z) | (Y & ~Z))
  246. #define H(X, Y, Z) (X ^ Y ^ Z)
  247. #define I(X, Y, Z) (Y ^ (X | ~Z))
  248. uint32_t rotateLeft(uint32_t x, uint32_t n){
  249. return (x << n) | (x >> (32 - n));
  250. }
  251. void md5Init(MD5Context *ctx){
  252. ctx->size = (uint64_t)0;
  253. ctx->buffer[0] = (uint32_t)A;
  254. ctx->buffer[1] = (uint32_t)B;
  255. ctx->buffer[2] = (uint32_t)C;
  256. ctx->buffer[3] = (uint32_t)D;
  257. }
  258. void md5Update(MD5Context *ctx, uint8_t *input_buffer, size_t input_len){
  259. uint32_t input[16];
  260. unsigned int offset = ctx->size % 64;
  261. ctx->size += (uint64_t)input_len;
  262. // Copy each byte in input_buffer into the next space in our context input
  263. for(unsigned int i = 0; i < input_len; ++i){
  264. ctx->input[offset++] = (uint8_t)*(input_buffer + i);
  265. // If we've filled our context input, copy it into our local array input
  266. // then reset the offset to 0 and fill in a new buffer.
  267. // Every time we fill out a chunk, we run it through the algorithm
  268. // to enable some back and forth between cpu and i/o
  269. if(offset % 64 == 0){
  270. for(unsigned int j = 0; j < 16; ++j){
  271. // Convert to little-endian
  272. // The local variable `input` our 512-bit chunk separated into 32-bit words
  273. // we can use in calculations
  274. input[j] = (uint32_t)(ctx->input[(j * 4) + 3]) << 24 |
  275. (uint32_t)(ctx->input[(j * 4) + 2]) << 16 |
  276. (uint32_t)(ctx->input[(j * 4) + 1]) << 8 |
  277. (uint32_t)(ctx->input[(j * 4)]);
  278. }
  279. md5Step(ctx->buffer, input);
  280. offset = 0;
  281. }
  282. }
  283. }
  284. void md5Finalize(MD5Context *ctx){
  285. uint32_t input[16];
  286. unsigned int offset = ctx->size % 64;
  287. unsigned int padding_length = offset < 56 ? 56 - offset : (56 + 64) - offset;
  288. // Fill in the padding and undo the changes to size that resulted from the update
  289. md5Update(ctx, PADDING, padding_length);
  290. ctx->size -= (uint64_t)padding_length;
  291. // Do a final update (internal to this function)
  292. // Last two 32-bit words are the two halves of the size (converted from bytes to bits)
  293. for(unsigned int j = 0; j < 14; ++j){
  294. input[j] = (uint32_t)(ctx->input[(j * 4) + 3]) << 24 |
  295. (uint32_t)(ctx->input[(j * 4) + 2]) << 16 |
  296. (uint32_t)(ctx->input[(j * 4) + 1]) << 8 |
  297. (uint32_t)(ctx->input[(j * 4)]);
  298. }
  299. input[14] = (uint32_t)(ctx->size * 8);
  300. input[15] = (uint32_t)((ctx->size * 8) >> 32);
  301. md5Step(ctx->buffer, input);
  302. // Move the result into digest (convert from little-endian)
  303. for(unsigned int i = 0; i < 4; ++i){
  304. ctx->digest[(i * 4) + 0] = (uint8_t)((ctx->buffer[i] & 0x000000FF));
  305. ctx->digest[(i * 4) + 1] = (uint8_t)((ctx->buffer[i] & 0x0000FF00) >> 8);
  306. ctx->digest[(i * 4) + 2] = (uint8_t)((ctx->buffer[i] & 0x00FF0000) >> 16);
  307. ctx->digest[(i * 4) + 3] = (uint8_t)((ctx->buffer[i] & 0xFF000000) >> 24);
  308. }
  309. }
  310. void md5Step(uint32_t *buffer, uint32_t *input){
  311. uint32_t AA = buffer[0];
  312. uint32_t BB = buffer[1];
  313. uint32_t CC = buffer[2];
  314. uint32_t DD = buffer[3];
  315. uint32_t E;
  316. unsigned int j;
  317. for(unsigned int i = 0; i < 64; ++i){
  318. switch(i / 16){
  319. case 0:
  320. E = F(BB, CC, DD);
  321. j = i;
  322. break;
  323. case 1:
  324. E = G(BB, CC, DD);
  325. j = ((i * 5) + 1) % 16;
  326. break;
  327. case 2:
  328. E = H(BB, CC, DD);
  329. j = ((i * 3) + 5) % 16;
  330. break;
  331. default:
  332. E = I(BB, CC, DD);
  333. j = (i * 7) % 16;
  334. break;
  335. }
  336. uint32_t temp = DD;
  337. DD = CC;
  338. CC = BB;
  339. BB = BB + rotateLeft(AA + E + K[i] + input[j], S[i]);
  340. AA = temp;
  341. }
  342. buffer[0] += AA;
  343. buffer[1] += BB;
  344. buffer[2] += CC;
  345. buffer[3] += DD;
  346. }
  347. void md5String(char *input, uint8_t *result){
  348. MD5Context ctx;
  349. md5Init(&ctx);
  350. md5Update(&ctx, (uint8_t *)input, strlen(input));
  351. md5Finalize(&ctx);
  352. memcpy(result, ctx.digest, 16);
  353. }
  354. void md5File(FILE *file, uint8_t *result){
  355. char *input_buffer = malloc(1024);
  356. size_t input_size = 0;
  357. MD5Context ctx;
  358. md5Init(&ctx);
  359. while((input_size = fread(input_buffer, 1, 1024, file)) > 0){
  360. md5Update(&ctx, (uint8_t *)input_buffer, input_size);
  361. }
  362. md5Finalize(&ctx);
  363. free(input_buffer);
  364. memcpy(result, ctx.digest, 16);
  365. }
  366. void toHexString(char* text, char* hex){
  367. int len = strlen(text);
  368. for (int i = 0, j = 0; i < len; ++i, j += 2)
  369. sprintf(hex + j, "%02x", text[i] & 0xff);
  370. }
  371. #undef A
  372. #undef B
  373. #undef C
  374. #undef D
  375. //===================================================================[list]
  376. void* arrElement(void* head, int i, int size){
  377. return ((char*)head+size*i);
  378. }
  379. int arrEnsureLength(void** head, int next, int* max, size_t ElementSize){
  380. int UseMax=*max; int nocopy=(!UseMax);
  381. if(next>=UseMax){
  382. if(!UseMax){ UseMax=50; }
  383. int AllocMax=next>(UseMax*2)?(next+16):(UseMax*2);
  384. void* data = CreateNew_Size(ElementSize* AllocMax);
  385. if(((*head) || next)&&(!nocopy)){ memcpy(data, *head, ElementSize*UseMax); }
  386. if(*head) free(*head);
  387. *head=data;
  388. *max=AllocMax;
  389. return 1;
  390. }
  391. return 0;
  392. }
  393. int arrInitLength(void** head, int max, int* pmax, size_t ElementSize){
  394. if(*head){ free(head); }
  395. *head=CreateNew_Size(ElementSize*max);
  396. *pmax=max;
  397. return 1;
  398. }
  399. void arrFree(void** head, int* max){ free(*head); *head=0; *max=0; }
  400. void lstPushSingle(void **Head, laListSingle *Item){
  401. Item->pNext = *Head;
  402. *Head = Item;
  403. }
  404. void *lstPopSingle(void **Head, laListSingle *Item){
  405. *Head = ((laListSingle *)(*Head))->pNext;
  406. Item->pNext = 0;
  407. return *Head;
  408. }
  409. int lstCountElements(laListHandle* Handle){
  410. int count=0; if(!Handle) return 0;
  411. for(laListItem* i=Handle->pFirst;i;i=i->pNext){count++;}
  412. return count;
  413. }
  414. void lstAppendItem(laListHandle* Handle, void* Item){
  415. laListItem* li = Item;
  416. li->pNext = li->pPrev = 0;
  417. if (!Handle->pFirst) Handle->pFirst = Item;
  418. if (Handle->pLast) ((laListItem*)Handle->pLast)->pNext = li;
  419. li->pPrev = Handle->pLast;
  420. li->pNext = 0;
  421. Handle->pLast = li;
  422. };
  423. void lstPushItem(laListHandle* Handle, void* Item){
  424. laListItem* li = Item;
  425. li->pNext = li->pPrev = 0;
  426. if (!Handle->pLast) Handle->pLast = Item;
  427. li->pNext = Handle->pFirst;
  428. if (Handle->pFirst) ((laListItem*)Handle->pFirst)->pPrev = Item;
  429. Handle->pFirst = li;
  430. };
  431. void* lstPopItem(laListHandle* Handle){
  432. laListItem* popitem;
  433. laListItem* next;
  434. if (!Handle->pFirst) return 0;
  435. popitem = Handle->pFirst;
  436. next = ((laListItem*)Handle->pFirst)->pNext;
  437. if (!next){
  438. Handle->pFirst = 0;
  439. Handle->pLast = 0;
  440. }else{
  441. Handle->pFirst = next;
  442. if (next) next->pPrev = 0;
  443. };
  444. popitem->pNext=popitem->pPrev=0;
  445. return popitem;
  446. };
  447. int lstHaveItemInList(laListHandle *Handle){
  448. if (Handle->pFirst) return 1;
  449. return 0;
  450. };
  451. void lstAppendItem2(laListHandle *Handle, void *Item){
  452. laListItem2 *li = Item;
  453. li->pNext = li->pPrev = 0;
  454. if (!Handle->pFirst) Handle->pFirst = Item;
  455. if (Handle->pLast) ((laListItem2 *)Handle->pLast)->pNext = li;
  456. li->pPrev = Handle->pLast;
  457. li->pNext = 0;
  458. Handle->pLast = li;
  459. };
  460. void lstPushItem2(laListHandle *Handle, void *Item){
  461. laListItem2 *li = Item;
  462. li->pNext = li->pPrev = 0;
  463. if (!Handle->pLast) Handle->pLast = Item;
  464. li->pNext = Handle->pFirst;
  465. if (Handle->pFirst) ((laListItem2 *)Handle->pFirst)->pPrev = Item;
  466. Handle->pFirst = li;
  467. };
  468. void *lstPopItem2(laListHandle *Handle){
  469. void *popitem;
  470. laListItem2 *next;
  471. if (!Handle->pFirst) return 0;
  472. popitem = Handle->pFirst;
  473. next = ((laListItem2 *)Handle->pFirst)->pNext;
  474. if (!next){
  475. Handle->pFirst = 0;
  476. Handle->pLast = 0;
  477. }else{
  478. Handle->pFirst = next;
  479. if (next) next->pPrev = 0;
  480. };
  481. return popitem;
  482. };
  483. void lstAppendItem3(laListHandle *Handle, void *Item){
  484. laListItem3 *li = Item;
  485. li->pNext = li->pPrev = 0;
  486. if (!Handle->pFirst) Handle->pFirst = Item;
  487. if (Handle->pLast) ((laListItem3 *)Handle->pLast)->pNext = li;
  488. li->pPrev = Handle->pLast;
  489. li->pNext = 0;
  490. Handle->pLast = li;
  491. };
  492. void lstPushItem3(laListHandle *Handle, void *Item){
  493. laListItem3 *li = Item;
  494. li->pNext = li->pPrev = 0;
  495. if (!Handle->pLast) Handle->pLast = Item;
  496. li->pNext = Handle->pFirst;
  497. if (Handle->pFirst) ((laListItem3 *)Handle->pFirst)->pPrev = Item;
  498. Handle->pFirst = li;
  499. };
  500. void *lstPopItem3(laListHandle *Handle){
  501. void *popitem;
  502. laListItem3 *next;
  503. if (!Handle->pFirst) return 0;
  504. popitem = Handle->pFirst;
  505. next = ((laListItem3 *)Handle->pFirst)->pNext;
  506. if (!next){
  507. Handle->pFirst = 0;
  508. Handle->pLast = 0;
  509. }else{
  510. Handle->pFirst = next;
  511. if (next) next->pPrev = 0;
  512. };
  513. return popitem;
  514. };
  515. void *lstGetTop(laListHandle *Handle){
  516. return Handle->pFirst;
  517. };
  518. int lstRemoveItem(laListHandle* Handle, laListItem* li) {
  519. if (!li->pPrev && Handle->pFirst != li) return 0;
  520. if (!li->pPrev) Handle->pFirst = li->pNext;
  521. else ((laListItem*)li->pPrev)->pNext = li->pNext;
  522. if (!li->pNext) Handle->pLast = li->pPrev;
  523. else ((laListItem*)li->pNext)->pPrev = li->pPrev;
  524. li->pNext = li->pPrev = 0;
  525. return 1;
  526. }
  527. int lstRemoveItem2(laListHandle *Handle, laListItem2 *li){
  528. if (!li->pPrev) Handle->pFirst = li->pNext;
  529. else ((laListItem2 *)li->pPrev)->pNext = li->pNext;
  530. if (!li->pNext) Handle->pLast = li->pPrev;
  531. else ((laListItem2 *)li->pNext)->pPrev = li->pPrev;
  532. li->pNext = li->pPrev = 0;
  533. return 1;
  534. };
  535. int lstRemoveItem3(laListHandle *Handle, laListItem2 *li){
  536. if (!li->pPrev) Handle->pFirst = li->pNext;
  537. else ((laListItem3 *)li->pPrev)->pNext = li->pNext;
  538. if (!li->pNext) Handle->pLast = li->pPrev;
  539. else ((laListItem3 *)li->pNext)->pPrev = li->pPrev;
  540. li->pNext = li->pPrev = 0;
  541. return 1;
  542. };
  543. int lstRemoveSegment(laListHandle *Handle, laListItem *Begin, laListItem *End){
  544. if (!Begin->pPrev) Handle->pFirst = End->pNext;
  545. else ((laListItem *)Begin->pPrev)->pNext = End->pNext;
  546. if (!End->pNext) Handle->pLast = Begin->pPrev;
  547. else ((laListItem *)End->pNext)->pPrev = Begin->pPrev;
  548. End->pNext = Begin->pPrev = 0;
  549. return 1;
  550. };
  551. void lstInsertItemBefore(laListHandle *Handle, laListItem *toIns, laListItem *pivot){
  552. if (!pivot){
  553. lstPushItem(Handle, toIns);
  554. return;
  555. }
  556. if (pivot->pPrev){
  557. ((laListItem *)pivot->pPrev)->pNext = toIns;
  558. toIns->pPrev = pivot->pPrev;
  559. }else{
  560. Handle->pFirst = toIns;
  561. }
  562. toIns->pNext = pivot;
  563. pivot->pPrev = toIns;
  564. };
  565. void lstInsertItemAfter(laListHandle *Handle, laListItem *toIns, laListItem *pivot){
  566. if (!pivot){
  567. lstAppendItem(Handle, toIns);
  568. return;
  569. }
  570. if (pivot->pNext){
  571. ((laListItem *)pivot->pNext)->pPrev = toIns;
  572. toIns->pNext = pivot->pNext;
  573. }else{
  574. Handle->pLast = toIns;
  575. }
  576. toIns->pPrev = pivot;
  577. pivot->pNext = toIns;
  578. }
  579. void lstInsertSegmentBefore(laListHandle *Handle, laListItem *Begin, laListItem *End, laListItem *pivot){
  580. if (pivot->pPrev){
  581. ((laListItem *)pivot->pPrev)->pNext = Begin;
  582. Begin->pPrev = pivot->pPrev;
  583. }else{
  584. Handle->pFirst = Begin;
  585. }
  586. End->pNext = pivot;
  587. pivot->pPrev = End;
  588. };
  589. void lstInsertSegmentAfter(laListHandle *Handle, laListItem *Begin, laListItem *End, laListItem *pivot){
  590. if (pivot->pNext){
  591. ((laListItem *)pivot->pNext)->pPrev = End;
  592. End->pNext = pivot->pNext;
  593. }else{
  594. Handle->pLast = End;
  595. }
  596. Begin->pPrev = pivot;
  597. pivot->pNext = Begin;
  598. }
  599. void *lstAppendPointerOnly(laListHandle *h, void *p){
  600. laListItemPointer *lip;
  601. if (!h) return 0;
  602. lip = CreateNew(laListItemPointer);
  603. lip->p = p;
  604. lstAppendItem(h, lip);
  605. return lip;
  606. }
  607. void *lstAppendPointerSizedOnly(laListHandle *h, void *p, int size){
  608. laListItemPointer *lip;
  609. if (!h) return 0;
  610. lip = calloc(1, size);
  611. lip->p = p;
  612. lstAppendItem(h, lip);
  613. return lip;
  614. }
  615. void *lstPushPointerOnly(laListHandle *h, void *p){
  616. laListItemPointer *lip = 0;
  617. if (!h) return 0;
  618. lip = CreateNew(laListItemPointer);
  619. lip->p = p;
  620. lstPushItem(h, lip);
  621. return lip;
  622. }
  623. void *lstPushPointerSizedOnly(laListHandle *h, void *p, int size){
  624. laListItemPointer *lip = 0;
  625. if (!h) return 0;
  626. lip = calloc(1, size);
  627. lip->p = p;
  628. lstPushItem(h, lip);
  629. return lip;
  630. }
  631. void lstReverse(laListHandle* h){
  632. laListHandle l={0}; void* i; while(i=lstPopItem(h)){ lstPushItem(&l,i); }
  633. memcpy(h,&l,sizeof(laListHandle));
  634. }
  635. int lstHasPointer(laListHandle* h, void *p){
  636. laListItemPointer *i; for (i = h->pFirst; i; i = i->pNext){
  637. if (i->p == p){return 1;}
  638. } return 0;
  639. }
  640. void *lstAppendPointer(laListHandle *h, void *p){
  641. laListItemPointer *lip;
  642. if (!h) return 0;
  643. lip = memAcquireSimple(sizeof(laListItemPointer));
  644. lip->p = p;
  645. lstAppendItem(h, lip);
  646. return lip;
  647. }
  648. void *lstAppendPointerSized(laListHandle *h, void *p, int size){
  649. laListItemPointer *lip;
  650. if (!h) return 0;
  651. lip = memAcquireSimple(size);
  652. lip->p = p;
  653. lstAppendItem(h, lip);
  654. return lip;
  655. }
  656. void *lstPushPointer(laListHandle *h, void *p){
  657. laListItemPointer *lip = 0;
  658. if (!h) return 0;
  659. lip = memAcquireSimple(sizeof(laListItemPointer));
  660. lip->p = p;
  661. lstPushItem(h, lip);
  662. return lip;
  663. }
  664. void *lstPushPointerSized(laListHandle *h, void *p, int size){
  665. laListItemPointer *lip = 0;
  666. if (!h) return 0;
  667. lip = memAcquireSimple(size);
  668. lip->p = p;
  669. lstPushItem(h, lip);
  670. return lip;
  671. }
  672. void *lstAppendPointerStatic(laListHandle *h, laStaticMemoryPool *smp, void *p){
  673. laListItemPointer *lip;
  674. if (!h) return 0;
  675. lip = memStaticAcquire(smp, sizeof(laListItemPointer));
  676. lip->p = p;
  677. lstAppendItem(h, lip);
  678. return lip;
  679. }
  680. void *lstAppendPointerStaticSized(laListHandle *h, laStaticMemoryPool *smp, void *p, int size){
  681. laListItemPointer *lip;
  682. if (!h) return 0;
  683. lip = memStaticAcquire(smp, size);
  684. lip->p = p;
  685. lstAppendItem(h, lip);
  686. return lip;
  687. }
  688. void *lstPushPointerStatic(laListHandle *h, laStaticMemoryPool *smp, void *p){
  689. laListItemPointer *lip = 0;
  690. if (!h) return 0;
  691. lip = memStaticAcquire(smp, sizeof(laListItemPointer));
  692. lip->p = p;
  693. lstPushItem(h, lip);
  694. return lip;
  695. }
  696. void *lstPushPointerStaticSized(laListHandle *h, laStaticMemoryPool *smp, void *p, int size){
  697. laListItemPointer *lip = 0;
  698. if (!h) return 0;
  699. lip = memStaticAcquire(smp, size);
  700. lip->p = p;
  701. lstPushItem(h, lip);
  702. return lip;
  703. }
  704. void *lstPopPointerOnly(laListHandle *h){
  705. laListItemPointer *lip;
  706. void *rev = 0;
  707. if (!h) return 0;
  708. lip = lstPopItem(h);
  709. rev = lip ? lip->p : 0;
  710. FreeMem(lip);
  711. return rev;
  712. }
  713. void lstRemovePointerItemOnly(laListHandle *h, laListItemPointer *lip){
  714. lstRemoveItem(h, lip);
  715. FreeMem(lip);
  716. }
  717. void lstRemovePointerOnly(laListHandle *h, void *p){
  718. laListItemPointer *i;
  719. for (i = h->pFirst; i; i = i->pNext){
  720. if (i->p == p){
  721. lstRemovePointerItem(h, i);
  722. break;
  723. }
  724. }
  725. }
  726. void lstClearPointerOnly(laListHandle *h){
  727. laListItemPointer *i;
  728. while (h && h->pFirst){
  729. lstPopPointer(h);
  730. }
  731. }
  732. void lstGeneratePointerListOnly(laListHandle *from1, laListHandle *from2, laListHandle *to){
  733. laListItemPointer *lip = from2 ? from2->pLast : 0;
  734. while (lip){
  735. lstPushPointer(to, lip->p);
  736. lip = lip->pPrev;
  737. }
  738. lip = from1 ? from1->pLast : 0;
  739. while (lip){
  740. lstPushPointer(to, lip->p);
  741. lip = lip->pPrev;
  742. }
  743. }
  744. void *lstPopPointer(laListHandle *h){
  745. laListItemPointer *lip;
  746. void *rev = 0;
  747. if (!h) return 0;
  748. lip = lstPopItem(h);
  749. rev = lip ? lip->p : 0;
  750. memFree(lip);
  751. return rev;
  752. }
  753. void lstRemovePointerItem(laListHandle *h, laListItemPointer *lip){
  754. lstRemoveItem(h, lip);
  755. memFree(lip);
  756. }
  757. void lstRemovePointer(laListHandle *h, void *p){
  758. laListItemPointer *i;
  759. for (i = h->pFirst; i; i = i->pNext){
  760. if (i->p == p){ lstRemovePointerItem(h, i); break; }
  761. }
  762. }
  763. void lstRemovePointerLeave(laListHandle *h, void *p){
  764. laListItemPointer *i;
  765. for (i = h->pFirst; i; i = i->pNext){
  766. if (i->p == p){ lstRemoveItem(h, i); memLeave(i); break; }
  767. }
  768. }
  769. void lstClearPointer(laListHandle *h){
  770. laListItemPointer *i;
  771. while (h && h->pFirst){
  772. lstPopPointer(h);
  773. }
  774. }
  775. void lstGeneratePointerList(laListHandle *from1, laListHandle *from2, laListHandle *to){
  776. laListItemPointer *lip = from1 ? from1->pLast : 0;
  777. while (lip){
  778. lstPushPointer(to, lip->p);
  779. lip = lip->pPrev;
  780. }
  781. lip = from2 ? from2->pLast : 0;
  782. while (lip){
  783. lstPushPointer(to, lip->p);
  784. lip = lip->pPrev;
  785. }
  786. }
  787. void *lstAppendPointerStaticPool(laStaticMemoryPool *mph, laListHandle *h, void *p){
  788. laListItemPointer *lip;
  789. if (!h) return 0;
  790. lip = memStaticAcquire(mph, sizeof(laListItemPointer));
  791. lip->p = p;
  792. lstAppendItem(h, lip);
  793. return lip;
  794. }
  795. void *lstPopPointerLeave(laListHandle *h){
  796. laListItemPointer *lip;
  797. void *rev = 0;
  798. if (!h) return 0;
  799. lip = lstPopItem(h); memLeave(lip);
  800. rev = lip ? lip->p : 0;
  801. return rev;
  802. }
  803. void lstRemovePointerItemNoFree(laListHandle *h, laListItemPointer *lip){
  804. lstRemoveItem(h, lip);
  805. }
  806. void lstCopyHandle(laListHandle *target, laListHandle *src){
  807. target->pFirst = src->pFirst;
  808. target->pLast = src->pLast;
  809. };
  810. void lstClearHandle(laListHandle *h){
  811. h->pFirst = 0;
  812. h->pLast = 0;
  813. }
  814. void lstClearPrevNext(laListItem *li){
  815. li->pNext = 0;
  816. li->pPrev = 0;
  817. }
  818. void lstMoveUp(laListHandle *h, laListItem *li){
  819. void *pprev = li->pPrev ? ((laListItem *)li->pPrev)->pPrev : 0;
  820. if (!h || !li) return;
  821. if (li == h->pFirst) return;
  822. else{
  823. if (li == h->pLast) h->pLast = li->pPrev;
  824. ((laListItem *)li->pPrev)->pNext = li->pNext;
  825. ((laListItem *)li->pPrev)->pPrev = li;
  826. if (li->pNext) ((laListItem *)li->pNext)->pPrev = li->pPrev;
  827. li->pNext = li->pPrev;
  828. li->pPrev = pprev;
  829. if (pprev) ((laListItem *)pprev)->pNext = li;
  830. }
  831. if (!li->pPrev) h->pFirst = li;
  832. }
  833. void lstMoveDown(laListHandle *h, laListItem *li){
  834. void *ppnext = li->pNext ? ((laListItem *)li->pNext)->pNext : 0;
  835. if (!h || !li) return;
  836. if (li == h->pLast) return;
  837. else{
  838. if (li == h->pFirst) h->pFirst = li->pNext;
  839. ((laListItem *)li->pNext)->pPrev = li->pPrev;
  840. ((laListItem *)li->pNext)->pNext = li;
  841. if (li->pPrev) ((laListItem *)li->pPrev)->pNext = li->pNext;
  842. li->pPrev = li->pNext;
  843. li->pNext = ppnext;
  844. if (ppnext) ((laListItem *)ppnext)->pPrev = li;
  845. }
  846. if (!li->pNext) h->pLast = li;
  847. }
  848. void lstForAllItemsDo(laListDoFunc func, laListHandle *hList){
  849. laListItem *it = hList->pFirst;
  850. for (; it; it = it->pNext){
  851. func(it);
  852. }
  853. };
  854. void lstForAllItemsDoLNRR(laListNonRecursiveDoFunc func, laListHandle *hList){
  855. laListItem *it = hList->pFirst;
  856. for (; it; it = it->pNext){
  857. func(0, it, 0);
  858. }
  859. };
  860. void lstForAllItemsDo_DirectFree(laListDoFunc func, laListHandle *hList){
  861. laListItem *it;
  862. while (it = lstPopItem(hList)){
  863. if (func) func(it);
  864. FreeMem(it);
  865. }
  866. };
  867. void lstForAllItemsDo_arg_ptr(laListDoFuncArgp func, laListHandle *hList, void *arg){
  868. laListItem *it = hList->pFirst;
  869. for (; it; it = it->pNext){
  870. func(it, arg);
  871. };
  872. };
  873. void lstForAllItemsDo_NonRecursive_Root(laListHandle *FirstHandle, laListNonRecursiveDoFunc func, int bFreeItem, void *custom_data, laListCustomDataRemover remover){
  874. laListItem *li = 0, *NextLi;
  875. laListNonRecursiveRoot root = {0};
  876. laListNonRecursiveItem *nrItem = CreateNew(laListNonRecursiveItem);
  877. nrItem->bFreeList = bFreeItem;
  878. nrItem->func = func;
  879. nrItem->CustomData = custom_data;
  880. nrItem->remover = remover;
  881. lstCopyHandle(&nrItem->handle, FirstHandle);
  882. lstAppendItem(&root.NSItems, nrItem);
  883. while (lstHaveItemInList(&root.NSItems)){
  884. nrItem = lstPopItem(&root.NSItems);
  885. for (li = nrItem->handle.pFirst; li /*!=nrItem->handle.pLast*/; li = NextLi){
  886. if (nrItem->func) nrItem->func(&root, li, custom_data);
  887. NextLi = li->pNext;
  888. if (nrItem->bFreeList){
  889. laListItem *fli = li;
  890. FreeMem(fli);
  891. }
  892. if (li == nrItem->handle.pLast) break;
  893. }
  894. if (nrItem->remover) nrItem->remover(nrItem->CustomData);
  895. FreeMem(nrItem);
  896. }
  897. };
  898. void lstAddNonRecursiveListHandle(laListNonRecursiveRoot *root, laListHandle *newHandle, laListNonRecursiveDoFunc nrFunc, int bFreeList, void *custom_data, laListCustomDataRemover remover){
  899. laListNonRecursiveItem *nrItem = CreateNew(laListNonRecursiveItem);
  900. nrItem->bFreeList = bFreeList;
  901. nrItem->func = nrFunc;
  902. nrItem->CustomData = custom_data;
  903. nrItem->remover = remover;
  904. lstCopyHandle(&nrItem->handle, newHandle);
  905. lstAppendItem(&root->NSItems, nrItem);
  906. };
  907. void lstCopy_NonRecursive_Root(laListHandle *FromHandle, laListHandle *ToHandle, int SizeEachNode, laListNonRecursiveCopyFunc func, void *custom_data, laListCustomDataRemover remover){
  908. laListItem *li = 0, *tli = 0;
  909. laListNonRecursiveRoot root = {0};
  910. laListNonRecursiveItem *nrItem = CreateNew(laListNonRecursiveItem);
  911. laListItem *NextLi;
  912. nrItem->CopyFunc = func;
  913. lstCopyHandle(&nrItem->handle, FromHandle);
  914. nrItem->ToHandle = ToHandle; //Pointer
  915. lstClearHandle(ToHandle);
  916. nrItem->CustomData = custom_data;
  917. nrItem->remover = remover;
  918. nrItem->SizeEachNode = SizeEachNode;
  919. lstAppendItem(&root.NSItems, nrItem);
  920. while (lstHaveItemInList(&root.NSItems)){
  921. nrItem = lstPopItem(&root.NSItems);
  922. if (nrItem->CopyFunc){
  923. for (li = nrItem->handle.pFirst; li; li = li->pNext){
  924. tli = CreateNew_Size(nrItem->SizeEachNode);
  925. nrItem->CopyFunc(&root, li, tli, nrItem->CustomData);
  926. lstClearPrevNext(tli);
  927. lstAppendItem(nrItem->ToHandle, tli);
  928. }
  929. if (nrItem->remover) nrItem->remover(nrItem->CustomData);
  930. }else if (nrItem->func){
  931. for (li = nrItem->handle.pFirst; li /*!=nrItem->handle.pLast*/; li = NextLi){
  932. if (nrItem->func) nrItem->func(&root, li, custom_data);
  933. NextLi = li->pNext;
  934. if (nrItem->bFreeList){
  935. laListItem *fli = li;
  936. FreeMem(fli);
  937. }
  938. if (li == nrItem->handle.pLast) break;
  939. }
  940. if (nrItem->remover) nrItem->remover(nrItem->CustomData);
  941. }
  942. FreeMem(nrItem);
  943. }
  944. };
  945. void lstAddNonRecursiveListCopier(laListNonRecursiveRoot *root, laListHandle *oldHandle, laListHandle *newHandle, int sizeEach, laListNonRecursiveCopyFunc nrCpyFunc, void *custom_data, laListCustomDataRemover remover){
  946. laListNonRecursiveItem *nrItem = CreateNew(laListNonRecursiveItem);
  947. nrItem->CopyFunc = nrCpyFunc;
  948. lstCopyHandle(&nrItem->handle, oldHandle);
  949. nrItem->ToHandle = newHandle;
  950. nrItem->CustomData = custom_data;
  951. nrItem->remover = remover;
  952. nrItem->SizeEachNode = sizeEach;
  953. lstAppendItem(&root->NSItems, nrItem);
  954. };
  955. void *lstFindItem(const void *CmpData, laCompareFunc func, laListHandle *hList){
  956. laListItem *it;
  957. if (!CmpData || !hList) return 0;
  958. it = hList->pFirst;
  959. for (; it; it = it->pNext){
  960. if (func(it, CmpData)) return it;
  961. };
  962. return 0;
  963. };
  964. void lstCombineLists(laListHandle *dest, laListHandle *src){
  965. if ((!dest) || (!src)) return;
  966. if ((!dest->pFirst) && (!dest->pLast)){
  967. dest->pFirst = src->pFirst;
  968. dest->pLast = src->pLast;
  969. }else{
  970. if (src->pLast){
  971. ((laListItem *)src->pFirst)->pPrev = dest->pLast;
  972. ((laListItem *)dest->pLast)->pNext = src->pFirst;
  973. dest->pLast = src->pLast;
  974. }
  975. }
  976. src->pFirst = 0;
  977. src->pLast = 0;
  978. }
  979. void lstDestroyList(laListHandle *hlst){
  980. laListItem *li, *nextli;
  981. for (li = hlst->pFirst; li; li = nextli){
  982. nextli = li->pNext;
  983. memFree(li);
  984. }
  985. }
  986. void lstDestroyListA(laListHandle *hlst){
  987. laListItem *li, *nextli;
  988. for (li = hlst->pFirst; li; li = nextli){
  989. nextli = li->pNext;
  990. FreeMem(li);
  991. }
  992. }
  993. void lstDestroyList_User(laListHandle *hlst, laListDoFunc func){
  994. laListItem *it = hlst->pFirst;
  995. for (; it; it = it->pNext){
  996. func(it);
  997. FreeMem(it);
  998. }
  999. };
  1000. void lstCopyList(laListHandle *hOldlst, laListHandle *hNewList, int SizeEachNode, laCopyListFunc func){
  1001. laListItem *li, *nextli, *newli;
  1002. for (li = hOldlst->pFirst; li; li = nextli){
  1003. newli = (laListItem *)CreateNew_Size(SizeEachNode);
  1004. func(li, newli);
  1005. lstAppendItem(hNewList, newli);
  1006. nextli = li->pNext;
  1007. }
  1008. }
  1009. void *lstReMatch(laListHandle *SearchHandle, laListHandle *CurrentHandle, void *ItemToFind){
  1010. laListItem *sl = 0, *rl = 0;
  1011. if (!SearchHandle || !CurrentHandle || !ItemToFind) return 0;
  1012. sl = SearchHandle->pFirst;
  1013. rl = CurrentHandle->pFirst;
  1014. while (sl && rl){
  1015. if (ItemToFind == sl){
  1016. return rl;
  1017. }else{
  1018. sl = sl->pNext;
  1019. rl = rl->pNext;
  1020. }
  1021. }
  1022. return 0;
  1023. }
  1024. //void* lstReMatchEx(laListHandle* SearchHandle, laListHandle* CurrentHandle, void* ItemToFind, MatcherFunc func){
  1025. // laListItem* sl = 0, *rl = 0;
  1026. //
  1027. // if (!SearchHandle || !CurrentHandle || !ItemToFind) return 0;
  1028. //
  1029. // sl = SearchHandle->pFirst; rl = CurrentHandle->pFirst;
  1030. //
  1031. // while (sl && rl){
  1032. // if (func(ItemToFind, sl)){
  1033. // return rl;
  1034. // }
  1035. // else{
  1036. // sl = sl->pNext;
  1037. // rl = rl->pNext;
  1038. // }
  1039. // }
  1040. // return 0;
  1041. //}
  1042. void lstAddElement(laListHandle *hlst, void *ext){
  1043. laElementListItem *eli = CreateNew(laElementListItem);
  1044. eli->Ext = ext;
  1045. lstAppendItem(hlst, eli);
  1046. }
  1047. void lstDestroyElementList(laListHandle *hlst){
  1048. laElementListItem *eli, *NextEli;
  1049. for (eli = hlst->pFirst; eli; eli = NextEli){
  1050. lstRemoveItem(hlst, eli);
  1051. NextEli = eli->Item.pNext;
  1052. FreeMem(eli);
  1053. }
  1054. }
  1055. uint16_t BKDRHash16bit(char* str){
  1056. unsigned int seed = 131, hash = 0;
  1057. while (*str) { hash = hash * seed + (*str++); }
  1058. return (hash & 0xFFFF);
  1059. }
  1060. void hsh65536Init(laHash65536** h){
  1061. if(!h) return; *h=calloc(1,sizeof(laHash65536));
  1062. }
  1063. void hshFree(laHash65536** h){
  1064. if(!h || !*h) return; free(*h); *h=0;
  1065. }
  1066. laListHandle* hsh65536DoHashLongPtr(laHash65536* hash, u64bit buckle) {
  1067. return &hash->Entries[(unsigned short)(buckle*13)];
  1068. }
  1069. laListHandle* hsh65536DoHashNUID(laHash65536* hash, char * NUID) {
  1070. u64bit Hash;
  1071. return &hash->Entries[BKDRHash16bit(NUID)];
  1072. }
  1073. unsigned char hsh256DoHashSTR(char *buckle){
  1074. int i, len = 0;
  1075. unsigned char rev = 0;
  1076. if (buckle) len = strlen(buckle);
  1077. for (i = 0; i < len; i++){
  1078. rev = rev * 31 + (unsigned char)buckle[i];
  1079. }
  1080. return (unsigned char)rev;
  1081. }
  1082. void hsh256InsertItemCSTR(laHash256 *hash, laListItem *li, char *buckle){
  1083. unsigned char a = hsh256DoHashSTR(buckle);
  1084. lstAppendItem(&hash->Entries[a], li);
  1085. };
  1086. void hsh256InsertItem(laHash256 *hash, laListItem *li, char buckle){
  1087. lstAppendItem(&hash->Entries[(unsigned char)buckle], li);
  1088. };
  1089. void hsh65536InsertItem(laHash65536 *hash, laListItem *li, long buckle){
  1090. lstAppendItem(&hash->Entries[(unsigned short)((buckle >> 10))], li);
  1091. //hsh256InsertItem(&hash->HashHandles[(char)((buckle >> 8) / 8)], li, (char)(buckle/8));
  1092. //printf("%d %d\n", (char)(buckle >> 5), (char)(buckle >> 6));
  1093. };
  1094. laListItem *hsh256FindItemSTR(laHash256 *hash, laCompareFunc func, char *buckle){
  1095. unsigned char hsh;
  1096. hsh = hsh256DoHashSTR(buckle);
  1097. //if(hash->Entries[hsh].pFirst == hash->Entries[hsh].pLast)
  1098. // return hash->Entries[hsh].pFirst;
  1099. laListItem* item=lstFindItem(buckle, func, &hash->Entries[hsh]);
  1100. return item;
  1101. }
  1102. //================================================================ [mem]
  1103. void* memGetHead(void* UserMem, int* HyperLevel){
  1104. laMemoryPoolPart **mpp = (laMemoryPoolPart**)(((char*)UserMem)-sizeof(void*));
  1105. if(!(*mpp)) return 0;
  1106. laMemoryPool* mp = (*mpp)->PoolRoot;
  1107. if(HyperLevel) *HyperLevel= mp->Hyperlevel;
  1108. if(mp->Hyperlevel==2) return ((char*)UserMem)-sizeof(laMemNodeHyper);
  1109. if(mp->Hyperlevel==1) return ((char*)UserMem)-sizeof(laMemNode);
  1110. if(mp->Hyperlevel==0) return ((char*)UserMem)-sizeof(laMemNode0);
  1111. return 0;
  1112. }
  1113. laListHandle* memGetUserList(void* UserMem){
  1114. int level; void* head=memGetHead(UserMem, &level);
  1115. if(level==2) return &((laMemNodeHyper*)head)->Users;
  1116. if(level==1) return &((laMemNode*)head)->Users;
  1117. return 0;
  1118. }
  1119. laMemoryPool *memInitPool(int NodeSize, int HyperLevel){
  1120. if (!NodeSize) return 0;
  1121. laMemoryPool *mph = calloc(1, sizeof(laMemoryPool));
  1122. mph->NodeSize = NodeSize;
  1123. mph->NextCount = 1;
  1124. mph->Hyperlevel = HyperLevel;
  1125. u8bit Buckle = NodeSize;
  1126. lstAppendItem(&MAIN.GlobalMemPool.Entries[Buckle], mph);
  1127. return mph;
  1128. }
  1129. laMemoryPoolPart *memNewPoolPart(laMemoryPool *mph){
  1130. if (!mph->NodeSize) return 0;
  1131. int MemNodeSize=(mph->Hyperlevel==0)?sizeof(laMemNode0):((mph->Hyperlevel==1)?sizeof(laMemNode):sizeof(laMemNodeHyper));
  1132. int PoolRefOffset=MemNodeSize-sizeof(void*);
  1133. int RealNodeSize = mph->NodeSize + MemNodeSize;
  1134. int NodeCount = mph->NextCount;
  1135. int TotalSize = sizeof(laMemoryPoolPart) + NodeCount * RealNodeSize;
  1136. laMemoryPoolPart *mp = calloc(1, TotalSize);
  1137. void *BeginMem = ((BYTE *)mp) + sizeof(laMemoryPoolPart);
  1138. mp->PoolRoot = mph;
  1139. mp->FreeMemoryNodes.pFirst = mp->FreeMemoryNodes.pLast = 0;
  1140. for (int i = 0; i < NodeCount; i++){
  1141. void* mpn = ((BYTE *)BeginMem) + RealNodeSize * i;
  1142. void** ref = ((BYTE *)mpn) + PoolRefOffset;
  1143. (*ref)=mp;
  1144. lstAppendItem(&mp->FreeMemoryNodes, mpn);
  1145. }
  1146. lstPushItem(&mph->Pools, mp);
  1147. return mp;
  1148. }
  1149. void *memAcquireH(laMemoryPool *Handle){
  1150. laMemoryPoolPart *mp = Handle->Pools.pFirst;
  1151. laMemNode *mpn;
  1152. if (!mp || !mp->FreeMemoryNodes.pFirst){
  1153. mp = memNewPoolPart(Handle);
  1154. }
  1155. if (!mp) return 0;
  1156. mpn = mp->FreeMemoryNodes.pFirst;
  1157. lstRemoveItem(&mp->FreeMemoryNodes, mpn);
  1158. mp->UsedCount++;
  1159. //lstAppendItem(&mp->MemoryNodes, mpn);
  1160. return mpn;
  1161. }
  1162. void *memAcquire_(int Size, int Hyper){
  1163. laMemoryPool *mp;
  1164. u8bit Buckle = Size;
  1165. laSpinLock(&MAIN.MemLock);
  1166. mp = MAIN.GlobalMemPool.Entries[Buckle].pFirst;
  1167. while (mp && (mp->NodeSize != Size || mp->Hyperlevel!=Hyper))
  1168. mp = mp->Item.pNext;
  1169. if (!mp) mp = memInitPool(Size, Hyper);
  1170. void* ret=memAcquireH(mp);
  1171. laSpinUnlock(&MAIN.MemLock);
  1172. return ret;
  1173. }
  1174. void *memAcquireSimple(int Size){
  1175. void *mpn = memAcquire_(Size, 0);
  1176. return ((char*)mpn)+sizeof(laMemNode0);
  1177. }
  1178. void *memAcquire(int Size){
  1179. laMemNode *mpn = memAcquire_(Size, 1);
  1180. void* mem = ((char*)mpn)+sizeof(laMemNode);
  1181. return mem;
  1182. }
  1183. void *memAcquireHyperNoAppend(int Size){
  1184. laMemNodeHyper *mpn = memAcquire_(Size, 2);
  1185. void* mem = ((char*)mpn)+sizeof(laMemNodeHyper);
  1186. memMakeHyperData(mpn);
  1187. return mem;
  1188. }
  1189. void *memAcquireHyper(int Size){
  1190. laMemNodeHyper *mpn = memAcquire_(Size, 2);
  1191. void* mem = ((char*)mpn)+sizeof(laMemNodeHyper);
  1192. memMakeHyperData(mpn);
  1193. laListHandle* l=hsh65536DoHashNUID(&MAIN.DBInst2,mpn->NUID.String);
  1194. lstAppendItem(l,mpn);
  1195. return mem;
  1196. }
  1197. void memFree(void *Data){
  1198. if (!Data) return;
  1199. int level; void* head = memGetHead(Data, &level);
  1200. laMemoryPoolPart *mp;
  1201. if(level==2) { mp = ((laMemNodeHyper*)head)->InPool; laDataBlockNoLongerExists(Data,&((laMemNodeHyper*)head)->Users);
  1202. laListHandle* l=hsh65536DoHashNUID(&MAIN.DBInst2,((laMemNodeHyper*)head)->NUID.String); lstRemoveItem(l,head);}
  1203. if(level==1) { mp = ((laMemNode*)head)->InPool; laDataBlockNoLongerExists(Data,&((laMemNode*)head)->Users); }
  1204. if(level==0) { mp = ((laMemNode0*)head)->InPool; }
  1205. laMemoryPool *mph = mp->PoolRoot;
  1206. laSpinLock(&MAIN.MemLock);
  1207. //lstRemoveItem(&mp->MemoryNodes, head);
  1208. mp->UsedCount--;
  1209. void* head_except_item = ((char*)head)+sizeof(laListItem);
  1210. //memset(head_except_item, 0, ((level==2)?sizeof(laMemNodeHyper):((level==1)?sizeof(laMemNode):sizeof(laMemNode0)))+mph->NodeSize-sizeof(laListItem));
  1211. lstAppendItem(&mp->FreeMemoryNodes, head);
  1212. memset(Data, 0, mph->NodeSize);
  1213. MAIN.ByteCount -= mph->NodeSize;
  1214. if (!mp->UsedCount){
  1215. lstRemoveItem(&mph->Pools, mp);
  1216. FreeMem(mp);
  1217. }
  1218. laSpinUnlock(&MAIN.MemLock);
  1219. //if (!mph->Pools.pFirst) {
  1220. // mph->CountPerPool = 0;
  1221. // mph->NodeSize = 0;
  1222. //}
  1223. }
  1224. void memDestroyPool(laMemoryPool *mph){
  1225. laMemoryPool *mp;
  1226. while ((mp = lstPopItem(&mph->Pools))){
  1227. FreeMem(mp);
  1228. }
  1229. FreeMem(mph);
  1230. }
  1231. // Leave memory in an temporary place and if when push difference these are still not acquired, free them.
  1232. void memLeave(void *Data){
  1233. laListHandle* l=hsh65536DoHashLongPtr(MAIN.DBInstMemLeft,Data); lstAppendPointer(l,Data);
  1234. }
  1235. void memTake(void *Data){
  1236. laListHandle* l=hsh65536DoHashLongPtr(MAIN.DBInstMemLeft,Data); lstRemovePointer(l,Data);
  1237. }
  1238. void memFreeRemainingLeftNodes(){
  1239. laListHandle* l; void* m;
  1240. for(int i=0;i<65536;i++){
  1241. l=&MAIN.DBInstMemLeft->Entries[i]; while(m=lstPopPointer(l)){ memFree(m);
  1242. #ifdef DEBUG
  1243. printf("left freed %x\n",m);
  1244. #endif
  1245. }
  1246. }
  1247. }
  1248. void memNoLonger(){
  1249. for(int i=0;i<256;i++){
  1250. laMemoryPool* mp; while(mp=lstPopItem(&MAIN.GlobalMemPool.Entries[i])){ memDestroyPool(mp); }
  1251. }
  1252. }
  1253. laStaticMemoryPoolNode *memNewStaticPool(laStaticMemoryPool *smp){
  1254. laStaticMemoryPoolNode *smpn = calloc(1, LA_MEMORY_POOL_128MB);
  1255. smpn->UsedByte = sizeof(laStaticMemoryPoolNode);
  1256. lstPushItem(&smp->Pools, smpn);
  1257. return smpn;
  1258. }
  1259. void *memStaticAcquire(laStaticMemoryPool *smp, int size){
  1260. laStaticMemoryPoolNode *smpn = smp->Pools.pFirst;
  1261. void *ret;
  1262. if (!smpn || (smpn->UsedByte + size) > LA_MEMORY_POOL_128MB) smpn = memNewStaticPool(smp);
  1263. ret = ((BYTE *)smpn) + smpn->UsedByte;
  1264. smpn->UsedByte += size;
  1265. return ret;
  1266. }
  1267. void *memStaticAcquireThread(laStaticMemoryPool *smp, int size){
  1268. laStaticMemoryPoolNode *smpn = smp->Pools.pFirst;
  1269. void *ret;
  1270. //laSpinLock(&smp->csMem);
  1271. if (!smpn || (smpn->UsedByte + size) > LA_MEMORY_POOL_128MB) smpn = memNewStaticPool(smp);
  1272. ret = ((BYTE *)smpn) + smpn->UsedByte;
  1273. smpn->UsedByte += size;
  1274. //laSpinUnlock(&smp->csMem);
  1275. return ret;
  1276. }
  1277. void *memStaticDestroy(laStaticMemoryPool *smp){
  1278. laStaticMemoryPoolNode *smpn;
  1279. void *ret;
  1280. while (smpn = lstPopItem(&smp->Pools)){
  1281. FreeMem(smpn);
  1282. }
  1283. smp->EachSize = 0;
  1284. return ret;
  1285. }
  1286. void la_ReferencedBlockDeleted(void* This, laItemUserLinker* iul){
  1287. void** user=iul->Pointer.p; if(*user==This){ (*user)=0; } laStopUsingDataBlock(iul->Additional, 0, This); // <<< should always remove.
  1288. }
  1289. void la_ReferrerDeleted(void* This, laItemUserLinker* iul){
  1290. void* instance=iul->Pointer.p; if(instance!=This){ laStopUsingDataBlock(instance, 0, This); }
  1291. }
  1292. void memAssignRef(void* This, void** ptr, void* instance){
  1293. laItemUserLinker* iul;
  1294. if((!This)||(!ptr)) return;
  1295. if(instance){
  1296. laItemUserLinker*iul=laUseDataBlock(instance, 0, 0, ptr, la_ReferencedBlockDeleted, 0); if(iul){iul->Additional=This;}
  1297. laUseDataBlock(This, 0, 0, instance, la_ReferrerDeleted, 0);
  1298. }else{
  1299. laStopUsingDataBlock((*ptr), 0, This);
  1300. laStopUsingDataBlock(This, 0, (*ptr));
  1301. }
  1302. (*ptr)=instance;
  1303. }
  1304. void memAssignRefSafe(laSubProp* sp, void* This, void** ptr, void* instance){
  1305. laPropContainer* pc=sp?la_EnsureSubTarget(sp,instance):0;
  1306. if(pc&&!pc->OtherAlloc) memAssignRef(This,ptr,instance);
  1307. else (*ptr)=instance;
  1308. }
  1309. //=======================================================================[str]
  1310. char *strGetNextString(char **pivot, char *NextMark){
  1311. int lenth = 0;
  1312. char *countP = *pivot;
  1313. char *result = 0;
  1314. int FloatArg = 0;
  1315. int i,advance;
  1316. if (**pivot == U'\0') return 0;
  1317. if (*NextMark == U'~') FloatArg = 1;
  1318. // container@identifier=window container#window contianer%
  1319. int UC=1;
  1320. while (!lenth){
  1321. for (countP; *countP != U'.' && *(*pivot) != U'\0' && UC && *countP && *countP != U'@' && *countP != U'=' && *countP != U'#' && *countP != U'$';){
  1322. if((*countP)=='\\'){
  1323. countP++; lenth++; }
  1324. UC = laToUnicode(countP, &advance);
  1325. lenth+=advance;
  1326. countP+=advance;
  1327. }
  1328. if (lenth || (*countP) == 0) break;
  1329. (*pivot)++; countP++;
  1330. }
  1331. *NextMark = (*pivot)[lenth];
  1332. if (!(*NextMark)) *NextMark = U'.';
  1333. if (lenth){
  1334. result = CreateNewBuffer(char, lenth + 1);
  1335. int pi=0; for (i = 0; i < lenth; i++){
  1336. if((*pivot)[i]=='\\'){ continue; }
  1337. result[pi] = (*pivot)[i]; pi++;
  1338. }
  1339. result[pi] = U'\0';
  1340. if ((*pivot)[lenth] == U'\0') *pivot = &((*pivot)[lenth]);
  1341. else
  1342. (*pivot) += lenth + 1;
  1343. return result;
  1344. }else{
  1345. return 0;
  1346. }
  1347. };
  1348. int strGetStringTerminateBy(char *content, char terminator, char *Out){
  1349. int Ofst = 0;
  1350. int Skip = 0;
  1351. int i = 0, advance;
  1352. if ((!content) || (*content == U'\0')) return 0;
  1353. int UC;
  1354. for (Ofst; content[Ofst] != terminator && content[Ofst] != U'\0'; ){
  1355. UC = laToUnicode(&content[Ofst], &advance);
  1356. for(int a=0;a<advance;a++){
  1357. Out[i] = content[Ofst];
  1358. Ofst++; i++;
  1359. }
  1360. }
  1361. Out[i] = 0;
  1362. return i;
  1363. };
  1364. char *strGetNewStringTerminateBy_PivotOver(char *content, char terminator, char **NewPivot, int IgnoreSpace){
  1365. int Ofst = 0;
  1366. int Skip = 0;
  1367. int i = 0;
  1368. char *NewString;
  1369. if (!content || *content == U'\0') return 0;
  1370. if (IgnoreSpace) for (i; content[i] == U' '; i++) ;
  1371. int UC,advance;
  1372. for (Ofst; content[Ofst] != terminator && content[Ofst] != U'\0';){
  1373. UC = laToUnicode(&content[Ofst], &advance);
  1374. Ofst+=advance;
  1375. }
  1376. NewString = CreateNewBuffer(char, Ofst + 1 - i);
  1377. memcpy(NewString, &content[i], sizeof(char) * (Ofst - i));
  1378. NewString[Ofst - i] = U'\0';
  1379. *NewPivot = content[Ofst]?&content[Ofst + 1]:&content[Ofst];
  1380. return NewString;
  1381. };
  1382. int strHeadOfStringMatch(char *Str, char *SubStr){
  1383. int len = strlen(SubStr);
  1384. int i = 0;
  1385. for (i; i < len; i++){
  1386. if (Str[i] != SubStr[i]) return 0;
  1387. }
  1388. return 1;
  1389. }
  1390. int strSkipSegmet(char **pivot, char *content){
  1391. if (!pivot || !(*pivot) || !(*(*pivot)) || !content) return 0;
  1392. if (strHeadOfStringMatch(*pivot, content)){
  1393. (*pivot) += strlen(content);
  1394. return 1;
  1395. }
  1396. return 0;
  1397. }
  1398. char *strGetLastSegment(char *Content, char Seperator){
  1399. char *p = Content;
  1400. char *pn = Content;
  1401. while (1){
  1402. while (*pn != Seperator){
  1403. if (!(*pn)) return p;
  1404. pn++;
  1405. }
  1406. pn++;
  1407. p = pn;
  1408. }
  1409. }
  1410. void strDiscardLastSegmentSeperateBy(char *Content, char Seperator){
  1411. char *p = Content;
  1412. char *pn = Content;
  1413. while (1){
  1414. while (*pn != Seperator){
  1415. if (!(*pn)){
  1416. *p = 0;
  1417. return;
  1418. }
  1419. pn++;
  1420. }
  1421. p = pn;
  1422. pn++;
  1423. }
  1424. }
  1425. void strDiscardSameBeginningSeperatedBy(char *s1, char *s2, char **Result1, char **Result2, char Seperator){
  1426. int i = 0;
  1427. int p = 0;
  1428. while (s1[i] == s2[i]){
  1429. i++;
  1430. if (s1[i] == Seperator) p = i;
  1431. if (!s1[i]){
  1432. p = i;
  1433. break;
  1434. }
  1435. if (!s2[i]){
  1436. p = i;
  1437. break;
  1438. }
  1439. }
  1440. *Result1 = &s1[p];
  1441. *Result2 = &s2[p];
  1442. }
  1443. int strCountSegmentSeperateBy(char *Content, char Seperator){
  1444. char *p = Content;
  1445. char *pn = Content;
  1446. int c = Content[0] ? (Content[0] == Seperator ? 0 : 1) : 0;
  1447. while (1){
  1448. while (*pn != Seperator){
  1449. if (!(*pn)){
  1450. if ((*p) == Seperator) c--;
  1451. return c;
  1452. }
  1453. p = pn;
  1454. pn++;
  1455. }
  1456. c++;
  1457. pn++;
  1458. }
  1459. return c;
  1460. }
  1461. void strMakeDifferentName(char *Target){
  1462. char *p = strGetLastSegment(Target, '.');
  1463. int Temp;
  1464. if (!sscanf(p, "%d", &Temp)){
  1465. int l = strlen(p);
  1466. if (p[l - 1] != U'.') strcat(p, ".");
  1467. strPrintIntAfter(Target, 0, 001);
  1468. }else{
  1469. sprintf(p, "%d", Temp + 1);
  1470. };
  1471. }
  1472. void strReplaceCharacter(char *Str, char Find, char Replace){
  1473. char *p = Str;
  1474. if (!p) return;
  1475. while (*p){
  1476. if (*p == Find) *p = Replace;
  1477. p++;
  1478. }
  1479. }
  1480. void strToUpper(char *Str){
  1481. char *p = Str; if (!p) return;
  1482. while (*p){
  1483. if (*p >= 'a' && *p <= 'z') *p += 'A' - 'a';
  1484. p++;
  1485. }
  1486. }
  1487. void strToLower(char *Str){
  1488. char *p = Str; if (!p) return;
  1489. while (*p){
  1490. if (*p >= 'A' && *p <= 'Z') *p -= 'A' - 'a';
  1491. p++;
  1492. }
  1493. }
  1494. int tolowerGuarded(int a) {
  1495. if (a >= 'A' && a <= 'Z') a -= 'A' - 'a';
  1496. return a;
  1497. }
  1498. laStringSplitor *strSplitPath(const char *path,char terminator){
  1499. laStringPart *sp;
  1500. laStringSplitor *ss;
  1501. char *pivot = path;
  1502. char *temp_result;
  1503. char Type = terminator?terminator:'.';
  1504. char NextType = '.';
  1505. if (!path || !path[0]) return 0;
  1506. ss = memAcquireSimple(sizeof(laStringSplitor));
  1507. while (temp_result = strGetNextString(&pivot, &NextType)){
  1508. if (*temp_result != U'\0'){
  1509. sp = memAcquireSimple(sizeof(laStringPart));
  1510. sp->Content = temp_result;
  1511. lstAppendItem(&ss->parts, sp);
  1512. ss->NumberParts += 1;
  1513. if (NextType == U'$') sp->Type = U'$';
  1514. else
  1515. sp->Type = Type;
  1516. if (sp->Type == U'='){
  1517. if (sp->Content[0] >= U'0' && sp->Content[0] <= 9){
  1518. sscanf(sp->Content, "%d", &sp->IntValue);
  1519. }
  1520. }
  1521. if (NextType == U'$') NextType = U'.';
  1522. Type = NextType;
  1523. }
  1524. }
  1525. if (ss->NumberParts == 0){
  1526. strDestroyStringSplitor(&ss);
  1527. return 0;
  1528. }
  1529. return ss;
  1530. };
  1531. void DF_ClearStingParts(laStringPart *sp){
  1532. FreeMem(sp->Content);
  1533. };
  1534. int strDestroyStringSplitor(laStringSplitor **ss){
  1535. if (!(*ss)) return 0;
  1536. lstForAllItemsDo(DF_ClearStingParts, &(*ss)->parts);
  1537. lstDestroyList(&(*ss)->parts);
  1538. memFree(*ss);
  1539. *ss = 0;
  1540. return 1;
  1541. }
  1542. char * strSub(const char *input, const char *substring, const char *replace){
  1543. int number_of_matches = 0;
  1544. size_t substring_size = strlen(substring), replace_size = strlen(replace), buffer_size;
  1545. char *buffer, *bp, *ip;
  1546. if (substring_size){
  1547. ip = strstr(input, substring);
  1548. while (ip != NULL){
  1549. number_of_matches++;
  1550. ip = strstr(ip+substring_size, substring);
  1551. }
  1552. }
  1553. else number_of_matches = strlen (input) + 1;
  1554. buffer_size = strlen(input) + number_of_matches*(replace_size - substring_size) + 1;
  1555. if ((buffer = ((char *) malloc(buffer_size))) == NULL){
  1556. return NULL;
  1557. }
  1558. bp = buffer;
  1559. ip = strstr(input, substring);
  1560. while ((ip != NULL) && (*input != '\0')){
  1561. if (ip == input){
  1562. memcpy (bp, replace, replace_size+1);
  1563. bp += replace_size;
  1564. if (substring_size)input += substring_size;
  1565. else*(bp++) = *(input++);
  1566. ip = strstr(input, substring);
  1567. }
  1568. else while (input != ip) *(bp++) = *(input++);
  1569. }
  1570. if (substring_size)strcpy (bp, input);
  1571. else memcpy (bp, replace, replace_size+1);
  1572. return buffer;
  1573. }
  1574. char buff[128]={0};
  1575. int strMakeInstructions(laStringSplitor **result, const char *content){
  1576. laStringPart *sp;
  1577. laStringSplitor *ss = *result;
  1578. char *pivot = content;
  1579. unsigned char *temp_result;
  1580. if (!content || !content[0]) return 0;
  1581. if (!ss) ss = *result = memAcquireSimple(sizeof(laStringSplitor));
  1582. while (temp_result = strGetNewStringTerminateBy_PivotOver(pivot, '=', &pivot, 0)){
  1583. if (*temp_result != U'\0'){
  1584. sp = memAcquireSimple(sizeof(laStringPart));
  1585. sp->Content = temp_result;
  1586. lstAppendItem(&ss->parts, sp);
  1587. ss->NumberParts += 1;
  1588. }
  1589. temp_result = strGetNewStringTerminateBy_PivotOver(pivot, ';', &pivot, 0);
  1590. if (!temp_result) break;
  1591. if (*temp_result != U'\0'){
  1592. sp = memAcquireSimple(sizeof(laStringPart));
  1593. sp->Content = temp_result;
  1594. lstAppendItem(&ss->parts, sp);
  1595. ss->NumberParts += 1;
  1596. if (temp_result[0] >= U'0' && temp_result[0] <= U'9' || temp_result[0]>=128){
  1597. sscanf(temp_result, "%d", &sp->IntValue);
  1598. sscanf(temp_result, "%lf", &sp->FloatValue);
  1599. }
  1600. }
  1601. }
  1602. if (ss->NumberParts == 0){
  1603. strDestroyStringSplitor(&ss);
  1604. return 0;
  1605. }
  1606. return 1;
  1607. }
  1608. laStringPart *strGetArgument(laStringSplitor *ss, const char *content){
  1609. laStringPart *sp;
  1610. if (!ss) return 0;
  1611. for (sp = ss->parts.pFirst; sp; sp = sp->Item.pNext ? ((laListItem *)sp->Item.pNext)->pNext : 0){
  1612. if (strSame(content, sp->Content)) return sp->Item.pNext;
  1613. }
  1614. return 0;
  1615. }
  1616. char *strGetArgumentString(laStringSplitor *ss, const char *content){
  1617. laStringPart *sp;
  1618. if (!ss) return 0;
  1619. for (sp = ss->parts.pFirst; sp; sp = sp->Item.pNext ? ((laListItem *)sp->Item.pNext)->pNext : 0){
  1620. if (strSame(content, sp->Content)) return sp->Item.pNext ? ((laStringPart *)sp->Item.pNext)->Content : 0;
  1621. }
  1622. return 0;
  1623. }
  1624. int strArgumentMatch(laStringSplitor *ss, const char *id, const char *value){
  1625. laStringPart *sp;
  1626. if (!ss) return 0;
  1627. for (sp = ss->parts.pFirst; sp; sp = sp->Item.pNext ? ((laListItem *)sp->Item.pNext)->pNext : 0){
  1628. if (strSame(id, sp->Content)) return (strSame(((laStringPart *)sp->Item.pNext)->Content, value));
  1629. }
  1630. return 0;
  1631. }
  1632. int strGetIntSimple(const char *content){
  1633. int a;
  1634. sscanf(content, "%d", &a);
  1635. return a;
  1636. }
  1637. real strGetFloatSimple(const char *content){
  1638. real a;
  1639. sscanf(content, "%lf", &a);
  1640. return a;
  1641. }
  1642. void strConvInt_CString(int src, char *dest, int lenth){
  1643. sprintf(dest, "%d", src);
  1644. };
  1645. void strConvFloat_CString(real src, char *dest, int lenth){
  1646. sprintf(dest, "%lf", src);
  1647. };
  1648. void strCopyFull(char *dest, const char *src){
  1649. if (src && dest) strcpy(dest, src);
  1650. }
  1651. void strCopySized(char *dest, int LenthLim,const char *src){
  1652. if (src && dest) strcpy(dest, src);
  1653. }
  1654. void strPrintFloatAfter(char *dest, int LenthLim, int bits, real data){
  1655. char temp[64]={0};
  1656. sprintf(temp, "%.*lf", bits, data);
  1657. strcat(dest, temp);
  1658. }
  1659. void strPrintIntAfter(char *dest, int LenthLim, int data){
  1660. char temp[64]={0};
  1661. sprintf(&temp[0], "%d", data);
  1662. strcat(dest, temp);
  1663. }
  1664. void strEscapePath(char* OutCanBeSame, char* path){
  1665. char t[256]={0}; int ti=0;
  1666. for(int i=0;path[i];i++,ti++){
  1667. if(path[i]=='.'){ t[ti]='\\'; ti++; }
  1668. t[ti]=path[i];
  1669. }
  1670. strcpy(OutCanBeSame,t);
  1671. }
  1672. int strSame(const char *src, const char *dest){
  1673. return (src && dest && !strcmp(src, dest));
  1674. }
  1675. void strSafeDestroy(laSafeString **ss){
  1676. if (!*ss) return; lstRemoveItem(&SSC.SafeStrings, *ss);
  1677. if((*ss)->Ptr) memFree((*ss)->Ptr);
  1678. memFree(*ss); *ss=0;
  1679. }
  1680. void strSafeSet(laSafeString **ss, const char *Content){
  1681. int len;
  1682. if (!Content||!Content[0]){ strSafeDestroy(ss); return; }
  1683. len = strlen(Content);
  1684. if (len < 1) return;
  1685. if (*ss){
  1686. char* mem=memAcquireSimple(sizeof(char)*(len+1));
  1687. strcpy(mem, Content);
  1688. memFree((*ss)->Ptr);
  1689. (*ss)->Ptr=mem;
  1690. return;
  1691. }
  1692. (*ss) = memAcquireSimple(sizeof(laSafeString));
  1693. (*ss)->Ptr = memAcquireSimple(sizeof(char)*(len+1));
  1694. strcpy((*ss)->Ptr, Content);
  1695. lstAppendItem(&SSC.SafeStrings, *ss);
  1696. }
  1697. void strSafeAppend(laSafeString **ss, const char *Content){
  1698. if(!ss || !(*ss) || !Content){ strSafeSet(ss, Content); return; }
  1699. int OrigLen=strlen((*ss)->Ptr), ContentLen=strlen(Content);
  1700. char* mem=memAcquireSimple(sizeof(char)*(OrigLen+ContentLen+1));
  1701. memcpy(mem, (*ss)->Ptr, sizeof(char)*OrigLen);
  1702. memcpy(mem+sizeof(char)*OrigLen, Content, sizeof(char)*ContentLen);
  1703. mem[OrigLen+ContentLen]=0;
  1704. memFree((*ss)->Ptr);
  1705. (*ss)->Ptr=mem;
  1706. }
  1707. void strSafePrint(laSafeString **ss, const char *Format, ...){
  1708. char content[1024]; va_list va; va_start(va, Format); vsprintf(content, Format, va); va_end(va);
  1709. strSafeAppend(ss,content);
  1710. }
  1711. void strSafePrintV(laSafeString **ss, const char *Format, va_list args){
  1712. char content[1024]; va_list va; vsprintf(content, Format, args);
  1713. strSafeAppend(ss,content);
  1714. }
  1715. void strSafeDump(){
  1716. laSafeString*ss;
  1717. while(ss=lstPopItem(&SSC.SafeStrings)){
  1718. //if(ss->Ptr) printf("[String not freed] \"%s\"\n", ss->Ptr);
  1719. }
  1720. }
  1721. void strBeginEdit(laStringEdit **se, char *FullStr){
  1722. char *p = FullStr;
  1723. char buf[1024];
  1724. laStringEdit *nse = CreateNew(laStringEdit);
  1725. if(*se){ memcpy(nse,*se,sizeof(laStringEdit)); nse->Lines.pFirst=nse->Lines.pLast=0; nse->TotalLines=0; }
  1726. strEndEdit(se, 1);
  1727. nse->_BeginLine = -1; nse->_BeginBefore = -1;
  1728. if (FullStr && FullStr[0]){
  1729. while ((*p)){
  1730. laStringLine *sl = memAcquireSimple(sizeof(laStringLine));
  1731. p += strGetStringTerminateBy(p, '\n', buf);
  1732. strToUnicode(sl->Buf, buf);
  1733. lstAppendItem(&nse->Lines, sl); nse->TotalLines++;
  1734. if(*p){ p+=1; }
  1735. }
  1736. }
  1737. if (!nse->Lines.pFirst){
  1738. laStringLine *sl = memAcquireSimple(sizeof(laStringLine));
  1739. lstAppendItem(&nse->Lines, sl); nse->TotalLines=1;
  1740. }
  1741. laStringLine *sl = strGetCursorLine(nse, 0); int len=strlenU(sl->Buf);
  1742. if(len<nse->CursorBefore){ nse->CursorBefore=len; }
  1743. *se=nse;
  1744. }
  1745. char* strGetEditString(laStringEdit *se, int SelectionOnly){
  1746. if(!se) return 0; char* result=0; int next=0, max=0, len=0;
  1747. arrEnsureLength(&result, 0, &max, sizeof(char)); int NextChar=0;
  1748. int Line=0, starti=0, endat=INT_MAX;
  1749. for(laStringLine* sl=se->Lines.pFirst;sl;sl=sl->Item.pNext,Line++){
  1750. starti=0;
  1751. if(SelectionOnly && Line<se->BeginLine){ continue; }
  1752. if(SelectionOnly && Line==se->BeginLine){ starti=se->BeginBefore; }
  1753. int tlen=strlenU(&sl->Buf[starti]); int Extra=sl->Item.pNext?2:1;
  1754. if(SelectionOnly){ if(Line<se->EndLine){ Extra=2; }else{ Extra=1; } }
  1755. arrEnsureLength(&result, (len+tlen)*4+Extra, &max, sizeof(char));
  1756. if(SelectionOnly && Line==se->EndLine){ endat=se->EndBefore-starti; }
  1757. NextChar+=strToUTF8Lim(&result[NextChar], &sl->Buf[starti], endat); len+=tlen;
  1758. if(Extra==2){ result[NextChar]='\n'; NextChar+=1; }
  1759. if(SelectionOnly && Line==se->EndLine){ break; }
  1760. }
  1761. return result;
  1762. }
  1763. char* strEndEdit(laStringEdit **se, int FreeString){
  1764. laDisableIME(MAIN.CurrentWindow);
  1765. char *p=0; laStringLine *sl, *NextSl;
  1766. if (!se || !(*se)) return 0;
  1767. p=strGetEditString(*se, 0);
  1768. while (sl=lstPopItem(&(*se)->Lines)){ memFree(sl); }
  1769. FreeMem(*se); *se=0;
  1770. if(FreeString && p){ free(p); p=0; }
  1771. return p;
  1772. }
  1773. void strSetEditViewRange(laStringEdit* se, int Lines, int Cols){
  1774. se->ViewHeight = Lines; se->ViewWidth = Cols;
  1775. }
  1776. void strEnsureCursorVisible(laStringEdit* se){
  1777. if(!se->ViewHeight || !se->ViewWidth || se->CursorLine<0 || se->CursorBefore<0 ){return;}
  1778. if(se->CursorLine>se->ViewHeight+se->ViewStartLine-1){ se->ViewStartLine=se->CursorLine-se->ViewHeight+1; }
  1779. if(se->CursorLine<se->ViewStartLine){ se->ViewStartLine=se->CursorLine; }
  1780. if(se->CursorBefore>se->ViewStartCol+se->ViewWidth-1){ se->ViewStartCol=se->CursorBefore-se->ViewWidth+1; }
  1781. if(se->CursorBefore<se->ViewStartCol){ se->ViewStartCol=se->CursorBefore; }
  1782. }
  1783. void strRemoveLine(laStringEdit *se, laStringLine *sl){
  1784. lstRemoveItem(&se->Lines, sl);
  1785. memFree(sl); se->TotalLines--;
  1786. }
  1787. void strRemoveLineI(laStringEdit *se, int LineIndex){
  1788. int i = 0;
  1789. laStringLine *sl = se->Lines.pFirst, *NextSl;
  1790. while (sl){
  1791. NextSl = sl->Item.pNext;
  1792. if (i == LineIndex){ strRemoveLine(se, sl); break; }
  1793. i++;
  1794. sl = NextSl;
  1795. }
  1796. }
  1797. void strSetCursor(laStringEdit *se, int LineIndex, int BeforeIndex){
  1798. int maxbefore;
  1799. if (!se) return;
  1800. if(LineIndex<0){LineIndex=0;}
  1801. se->CursorLine = LineIndex;
  1802. maxbefore = strlenU(strGetCursorLine(se, &se->CursorLine)->Buf);
  1803. BeforeIndex = BeforeIndex < 0 ? 0 : BeforeIndex > maxbefore ? maxbefore : BeforeIndex;
  1804. se->CursorBefore = BeforeIndex;
  1805. se->BeginLine = -1;
  1806. se->BeginBefore = -1;
  1807. se->EndLine = -1;
  1808. se->EndBefore = -1;
  1809. strEnsureCursorVisible(se);
  1810. }
  1811. void strMoveCursor(laStringEdit *se, int Left, int Select){
  1812. int maxbefore;
  1813. int BeforeIndex;
  1814. int width = 1;
  1815. laStringLine *sl;
  1816. if (!se) return;
  1817. if(Select){ strLazySelect(se); } else { strCancelSelect(se); }
  1818. sl = strGetCursorLine(se, 0);
  1819. maxbefore = strlenU(sl->Buf);
  1820. BeforeIndex = se->CursorBefore - (Left ? 1 : -1);
  1821. if(BeforeIndex<0){
  1822. if(se->CursorLine>0) strSetCursor(se, se->CursorLine-1, INT_MAX);
  1823. }elif(BeforeIndex>maxbefore && se->CursorLine<se->TotalLines-1){
  1824. if(se->CursorLine>0) strSetCursor(se, se->CursorLine+1, 0);
  1825. }else{
  1826. se->CursorBefore = BeforeIndex>=maxbefore?maxbefore:BeforeIndex;
  1827. }
  1828. se->CursorPreferBefore = se->CursorBefore;
  1829. se->BeginLine = -1;
  1830. se->BeginBefore = -1;
  1831. se->EndLine = -1;
  1832. se->EndBefore = -1;
  1833. if(Select){ strEndSelect(se); }
  1834. strEnsureCursorVisible(se);
  1835. }
  1836. void strMoveCursorLine(laStringEdit *se, int Up, int Select){
  1837. int Line, maxbefore, LastIndex=-1;
  1838. laStringLine *sl;
  1839. if (!se) return;
  1840. if(Select){ strLazySelect(se); } else { strCancelSelect(se); }
  1841. Line=se->CursorLine - (Up? 1:-1);
  1842. if(Line<0) {Line=0;}
  1843. se->CursorLine = Line;
  1844. sl = strGetCursorLine(se, &LastIndex);
  1845. if(LastIndex>=0){ se->CursorLine = LastIndex; se->CursorPreferBefore=10000; }
  1846. maxbefore = strlenU(sl->Buf);
  1847. se->CursorBefore = se->CursorPreferBefore;
  1848. if(se->CursorBefore>maxbefore){ se->CursorBefore = maxbefore; }
  1849. if(LastIndex>=0){se->CursorPreferBefore=se->CursorBefore;}
  1850. if(Select){ strEndSelect(se); }
  1851. strEnsureCursorVisible(se);
  1852. }
  1853. int strHasSelection(laStringEdit* se){
  1854. return se->BeginBefore!=se->EndBefore||se->BeginLine!=se->EndLine;
  1855. }
  1856. void strCancelSelect(laStringEdit *se){
  1857. if (!se) return;
  1858. se->_BeginLine = -1;
  1859. se->_BeginBefore = -1;
  1860. se->BeginLine = -1;
  1861. se->EndLine = -1;
  1862. se->BeginBefore = -1;
  1863. se->EndBefore = -1;
  1864. }
  1865. void strLazySelect(laStringEdit *se){
  1866. if (!se || se->_BeginLine>=0) return;
  1867. se->_BeginLine = TNS_MAX2(se->CursorLine,0);
  1868. se->_BeginBefore = se->CursorBefore;
  1869. }
  1870. void strEndSelect(laStringEdit *se){
  1871. if (!se) return;
  1872. se->_EndLine = se->CursorLine;
  1873. se->_EndBefore = se->CursorBefore;
  1874. se->BeginLine = se->_BeginLine;
  1875. se->EndLine = se->_EndLine;
  1876. se->BeginBefore = se->_BeginBefore;
  1877. se->EndBefore = se->_EndBefore;
  1878. if(se->BeginLine>se->EndLine || (se->BeginLine==se->EndLine && se->BeginBefore>se->EndBefore))
  1879. { LA_SWAP(int,se->BeginLine,se->EndLine); LA_SWAP(int,se->BeginBefore,se->EndBefore); }
  1880. }
  1881. void strSelectLineAll(laStringEdit *se){
  1882. if (!se) return;
  1883. laStringLine *sl;
  1884. int len;
  1885. if (se->CursorLine == -1) sl = strGetBeginLine(se);
  1886. else
  1887. sl = strGetCursorLine(se, 0);
  1888. len = strlenU(sl->Buf);
  1889. se->EndBefore = len; se->EndLine=0;
  1890. se->BeginBefore = 0; se->BeginLine=0;
  1891. se->CursorBefore = len;
  1892. se->CursorLine = 0;
  1893. }
  1894. void strDeselectAll(laStringEdit *se){
  1895. if (!se) return;
  1896. laStringLine *sl;
  1897. int len;
  1898. if (se->CursorLine == -1) sl = strGetBeginLine(se);
  1899. else
  1900. sl = strGetCursorLine(se, 0);
  1901. len = strlenU(sl->Buf);
  1902. se->EndBefore = -1;
  1903. se->BeginBefore = -1;
  1904. se->BeginLine = -1;
  1905. se->EndLine = -1;
  1906. se->CursorBefore = len;
  1907. se->CursorLine = -1;
  1908. }
  1909. void strPanFoward(uint32_t *str, int Before, int Offset){
  1910. int len = strlenU(str);
  1911. int i = len + 1;
  1912. for (i; i >= Before; i--){
  1913. str[i + Offset] = str[i];
  1914. }
  1915. }
  1916. void strSquishBackward(uint32_t *str, int Before, int EndBefore){
  1917. int len = strlenU(str);
  1918. int i = Before;
  1919. int Offset = Before - EndBefore;
  1920. if (Before <= 0) return;
  1921. for (i; i <= len; i++){
  1922. str[i - Offset] = str[i];
  1923. }
  1924. }
  1925. void strClearSelection(laStringEdit *se){
  1926. //if (se->EndLine == -1) return;
  1927. if (se->BeginLine != se->EndLine){
  1928. int i = 0; int RemovedLines=0;
  1929. laStringLine *sl = se->Lines.pFirst, *NextSl;
  1930. while (sl){
  1931. NextSl = sl->Item.pNext;
  1932. if (i == se->BeginLine){
  1933. sl->Buf[se->BeginBefore] = U'\0';
  1934. }else if (i > se->BeginLine && i < se->EndLine){
  1935. strRemoveLine(se, sl); RemovedLines++;
  1936. }else if (i == se->EndLine){
  1937. strSquishBackward(sl->Buf, se->EndBefore, 0);
  1938. se->CursorLine = i-RemovedLines;
  1939. se->CursorBefore = 0;
  1940. se->BeginLine = -1;
  1941. se->BeginBefore = -1;
  1942. se->EndLine = -1;
  1943. se->EndBefore = -1;
  1944. strBackspace(se);
  1945. }
  1946. if (i > se->EndLine) break;
  1947. i++;
  1948. sl = NextSl;
  1949. }
  1950. }else{
  1951. int i = 0;
  1952. laStringLine *sl = se->Lines.pFirst, *NextSl;
  1953. while (sl){
  1954. NextSl = sl->Item.pNext;
  1955. if (i == se->EndLine) {
  1956. strSquishBackward(sl->Buf, se->EndBefore, se->BeginBefore);
  1957. se->CursorLine = i;
  1958. se->CursorBefore = se->BeginBefore;
  1959. se->BeginLine = -1;
  1960. se->BeginBefore = -1;
  1961. se->EndLine = -1;
  1962. se->EndBefore = -1;
  1963. break;
  1964. }
  1965. i++; sl = NextSl;
  1966. }
  1967. }
  1968. strEnsureCursorVisible(se);
  1969. }
  1970. laStringLine *strGetCursorLine(laStringEdit *se, int* ReturnIndexIfLast){
  1971. if (!se || se->CursorBefore <= -1) return se->Lines.pFirst;
  1972. int i = 0;
  1973. laStringLine *sl = se->Lines.pFirst, *NextSl;
  1974. while (sl){
  1975. NextSl = sl->Item.pNext;
  1976. if (i == se->CursorLine){
  1977. return sl;
  1978. }
  1979. i++;
  1980. sl = NextSl;
  1981. }
  1982. if(ReturnIndexIfLast){ *ReturnIndexIfLast=i-1;}
  1983. return se->Lines.pLast;
  1984. }
  1985. laStringLine *strGetBeginLine(laStringEdit *se){
  1986. if (!se || se->BeginLine <= -1) return se->Lines.pFirst;
  1987. int i = 0;
  1988. laStringLine *sl = se->Lines.pFirst, *NextSl;
  1989. while (sl){
  1990. NextSl = sl->Item.pNext;
  1991. if (i == se->BeginLine){
  1992. return sl;
  1993. }
  1994. i++;
  1995. sl = NextSl;
  1996. }
  1997. return se->Lines.pFirst;
  1998. }
  1999. void strInsertChar(laStringEdit *se, uint32_t a){
  2000. laStringLine *sl;
  2001. strClearSelection(se);
  2002. sl = strGetCursorLine(se, 0);
  2003. if(a==U'\n'){
  2004. laStringLine* nl=memAcquireSimple(sizeof(laStringLine));
  2005. if(sl->Buf[se->CursorBefore]!=U'\0') strcpyU(nl->Buf, &sl->Buf[se->CursorBefore]);
  2006. sl->Buf[se->CursorBefore]=U'\0';
  2007. se->CursorLine++; se->CursorBefore=0;
  2008. lstInsertItemAfter(&se->Lines, nl, sl); se->TotalLines++;
  2009. }else{
  2010. strPanFoward(sl->Buf, se->CursorBefore, 1);
  2011. sl->Buf[se->CursorBefore] = a;
  2012. se->CursorBefore += 1;
  2013. }
  2014. se->CursorPreferBefore = se->CursorBefore;
  2015. strEnsureCursorVisible(se);
  2016. }
  2017. void strBackspace(laStringEdit *se){
  2018. laStringLine *sl;
  2019. int width = 1;
  2020. if (se->CursorBefore == -1){
  2021. strClearSelection(se);
  2022. }else{
  2023. laStringLine *sl;
  2024. sl = strGetCursorLine(se, 0);
  2025. if (se->CursorBefore > 1 && sl->Buf[se->CursorBefore - 2] < 0) width = 2;
  2026. strSquishBackward(sl->Buf, se->CursorBefore, se->CursorBefore - width);
  2027. se->CursorBefore -= width;
  2028. if (se->CursorBefore <= -1){
  2029. if(sl->Item.pPrev){
  2030. laStringLine* ol=sl->Item.pPrev;
  2031. se->CursorBefore = strlenU(ol->Buf);
  2032. se->CursorLine--;
  2033. strcatU(ol->Buf, sl->Buf);
  2034. strRemoveLine(se, sl);
  2035. }
  2036. else {se->CursorBefore = 0;}
  2037. }
  2038. }
  2039. se->CursorPreferBefore = se->CursorBefore;
  2040. strEnsureCursorVisible(se);
  2041. }
  2042. void strMoveView(laStringEdit *se, int DownLines, int RightCharacters){
  2043. se->ViewStartLine+=DownLines;
  2044. se->ViewStartCol+=RightCharacters;
  2045. if(se->ViewStartLine>=se->TotalLines-1) se->ViewStartLine=se->TotalLines-1;
  2046. if(se->ViewStartLine<0) se->ViewStartLine=0;
  2047. if(se->ViewStartCol<0) se->ViewStartCol=0;
  2048. }
  2049. int laCopyFile(char *to, char *from){
  2050. #ifdef _WIN32
  2051. if(CopyFile(from, to, 0)) return 1; return 0;
  2052. #endif
  2053. #ifdef LA_LINUX
  2054. int fd_to, fd_from; char buf[4096];
  2055. ssize_t nread; int saved_errno;
  2056. fd_from = open(from, O_RDONLY); if (fd_from < 0) return 0;
  2057. fd_to = open(to, O_WRONLY|O_CREAT /* |O_EXCL */, 0666); if (fd_to < 0) goto out_error;
  2058. while (nread=read(fd_from,buf,sizeof(buf)), nread>0) {
  2059. char *out_ptr = buf; ssize_t nwritten;
  2060. do { nwritten = write(fd_to, out_ptr, nread);
  2061. if (nwritten >= 0){ nread -= nwritten; out_ptr += nwritten;}
  2062. else if (errno != EINTR){ goto out_error; }
  2063. }while (nread > 0);
  2064. }
  2065. if (nread == 0){
  2066. if (close(fd_to)<0){ fd_to = -1; goto out_error;}
  2067. close(fd_from);
  2068. return 1;
  2069. }
  2070. out_error:
  2071. saved_errno = errno;
  2072. close(fd_from); if (fd_to >= 0) close(fd_to);
  2073. errno = saved_errno;
  2074. return 0;
  2075. #endif //linux
  2076. }
  2077. int laEnsureDir(const char *dir) {
  2078. #ifdef LA_LINUX
  2079. char tmp[1024]; char *p = NULL; size_t len;
  2080. snprintf(tmp, sizeof(tmp),"%s",dir);
  2081. len = strlen(tmp);
  2082. if (tmp[len - 1] == '/') tmp[len - 1] = 0;
  2083. for (p = tmp + 1; *p; p++){
  2084. if (*p == '/') { *p = 0;
  2085. mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO);
  2086. *p = '/';
  2087. }
  2088. }
  2089. mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO);
  2090. struct stat statbuf;
  2091. if(stat(dir, &statbuf) != 0){ return 0; }
  2092. return S_ISDIR(statbuf.st_mode);
  2093. #endif
  2094. return 0;
  2095. }
  2096. #ifdef LAGUI_ANDROID
  2097. static char* la_FileDoableOrDir(char* file_path,int mode){
  2098. if(!access(file_path,F_OK)){
  2099. if(!access(file_path,mode)){ return file_path; }
  2100. }else{
  2101. char buf[PATH_MAX];
  2102. strcpy(buf,file_path);
  2103. strDiscardLastSegmentSeperateBy(buf,'/');
  2104. struct stat statbuf;
  2105. if(stat(buf, &statbuf) != 0){ return 0; }
  2106. if(S_ISDIR(statbuf.st_mode)){
  2107. if(mode&W_OK){ if(statbuf.st_mode & S_IWUSR) return file_path; }
  2108. if(mode&R_OK){ if(statbuf.st_mode & S_IRUSR) return file_path; }
  2109. }
  2110. }
  2111. return 0;
  2112. }
  2113. char* laAndroidEnsureValidFilePath(char* file_path, int mode){
  2114. static char buf[PATH_MAX];
  2115. MAIN.AndroidLastPath=0;
  2116. char* result=0;
  2117. if(result=la_FileDoableOrDir(file_path, mode)){ MAIN.AndroidLastPath=result; return result; }
  2118. sprintf(buf,"%s/%s", MAIN.InternalDataPath, file_path);
  2119. if(result=la_FileDoableOrDir(buf, mode)){ MAIN.AndroidLastPath=result; return result; }
  2120. sprintf(buf,"%s/%s", MAIN.ExternalDataPath, file_path);
  2121. if(result=la_FileDoableOrDir(buf, mode)){ MAIN.AndroidLastPath=result; return result; }
  2122. return 0;
  2123. }
  2124. #endif
  2125. //======================================================[ translation ]
  2126. void transNewLanguage(const char *LanguageID){
  2127. laTranslationNode *tn = memAcquire(sizeof(laTranslationNode));
  2128. strSafeSet(&tn->LanguageName, LanguageID);
  2129. lstAppendItem(&MAIN.Translation.Languages, tn);
  2130. MAIN.Translation.CurrentLanguage = tn;
  2131. }
  2132. void transSetLanguage(const char *LanguageID){
  2133. laTranslationNode *tn;
  2134. if (!LanguageID){
  2135. MAIN.Translation.CurrentLanguage = 0;
  2136. return;
  2137. }
  2138. for (tn = MAIN.Translation.Languages.pFirst; tn; tn = tn->Item.pNext){
  2139. if (!strcmp(SSTR(tn->LanguageName), LanguageID)){
  2140. MAIN.Translation.CurrentLanguage = tn; return;
  2141. }
  2142. }
  2143. transNewLanguage(LanguageID);
  2144. }
  2145. void transDumpMissMatchRecord(const char *filename){
  2146. laTranslationMatch *tm;
  2147. laListHandle *lst;
  2148. int i;
  2149. FILE *f = fopen(filename, "w"); if (!f) return;
  2150. for (i = 0; i < 256; i++){
  2151. lst = &MAIN.Translation.MisMatches.Entries[i];
  2152. for (tm = lst->pFirst; tm; tm = tm->Item.pNext){ if(tm->Target) fprintf(f, "%s | \n", tm->Target); }
  2153. }
  2154. fclose(f);
  2155. }
  2156. int IsThisTranslationMatch(laTranslationMatch *tm, char *p){
  2157. return (tm->Target && (!strcmp(tm->Target, p)));
  2158. }
  2159. void transNewEntry(const char *Target, const char *replacement){
  2160. laTranslationMatch *tm = memAcquireSimple(sizeof(laTranslationMatch));
  2161. tm->Target = Target; tm->Replacement = replacement;
  2162. hsh256InsertItemCSTR(&MAIN.Translation.CurrentLanguage->Matches, tm, Target);
  2163. }
  2164. void transNewMissEntry(const char *Target){
  2165. if (!hsh256FindItemSTR(&MAIN.Translation.MisMatches, IsThisTranslationMatch, Target)){
  2166. laTranslationMatch *tm = memAcquireSimple(sizeof(laTranslationMatch));
  2167. int len=strlen(Target); tm->Target=memAcquireSimple(len*sizeof(char)+1);
  2168. strcpy(tm->Target,Target);
  2169. hsh256InsertItemCSTR(&MAIN.Translation.MisMatches, tm, Target);
  2170. }
  2171. }
  2172. char *transLate(const char *Target){
  2173. if (!MAIN.Translation.CurrentLanguage || !MAIN.Translation.EnableTranslation || !Target || !Target[0]) return Target;
  2174. laTranslationMatch *tm = hsh256FindItemSTR(&MAIN.Translation.CurrentLanguage->Matches, IsThisTranslationMatch, Target);
  2175. if (!tm){ transNewMissEntry(Target); return Target; }
  2176. return tm->Replacement;
  2177. }
  2178. void transState(void *UNUSED, int val){
  2179. if (val) MAIN.Translation.EnableTranslation = 1;
  2180. else MAIN.Translation.EnableTranslation = 0;
  2181. laRedrawCurrentWindow();
  2182. }
  2183. void laOpenInternetLink(char *url){
  2184. laSafeString* s=0;
  2185. #ifdef LA_LINUX
  2186. strSafePrint(&s, "xdg-open %s", url);
  2187. #endif
  2188. #ifdef _WIN32
  2189. strSafePrint(&s, "start %s", url);
  2190. #endif
  2191. #ifdef LAGUI_ANDROID
  2192. JNIEnv *env = NULL;
  2193. JavaVM *vm = MAIN.app->activity->vm;
  2194. (*vm)->AttachCurrentThread(vm, &env, NULL);
  2195. jstring urlString = (*env)->NewStringUTF(env, url);
  2196. jclass uriClass = (*env)->FindClass(env, "android/net/Uri");
  2197. jmethodID uriParse = (*env)->GetStaticMethodID(env, uriClass, "parse", "(Ljava/lang/String;)Landroid/net/Uri;");
  2198. jobject uri = (*env)->CallStaticObjectMethod(env, uriClass, uriParse, urlString);
  2199. jclass intentClass = (*env)->FindClass(env, "android/content/Intent");
  2200. jfieldID actionViewId = (*env)->GetStaticFieldID(env, intentClass, "ACTION_VIEW", "Ljava/lang/String;");
  2201. jobject actionView = (*env)->GetStaticObjectField(env, intentClass, actionViewId);
  2202. jmethodID newIntent = (*env)->GetMethodID(env, intentClass, "<init>", "(Ljava/lang/String;Landroid/net/Uri;)V");
  2203. jobject intent = (*env)->AllocObject(env, intentClass);
  2204. (*env)->CallVoidMethod(env, intent, newIntent, actionView, uri);
  2205. jclass activityClass = (*env)->FindClass(env, "android/app/Activity");
  2206. jmethodID startActivity = (*env)->GetMethodID(env, activityClass, "startActivity", "(Landroid/content/Intent;)V");
  2207. (*env)->CallVoidMethod(env, MAIN.app->activity->clazz, startActivity, intent);
  2208. (*vm)->DetachCurrentThread(vm);
  2209. return;
  2210. #endif
  2211. system(s->Ptr);
  2212. strSafeDestroy(&s);
  2213. //these were windows stuff
  2214. //HKEY hkRoot, hSubKey;
  2215. //char ValueName[256]={0};
  2216. //char DataValue[256]={0};
  2217. //u64bit cbValueName = 256;
  2218. //u64bit cbDataValue = 256;
  2219. //char ShellChar[512]={0};
  2220. //DWORD dwType;
  2221. //
  2222. //ShellExecute(0, "open", link, 0, 0, SW_SHOWNORMAL);
  2223. //
  2224. //return;
  2225. }
  2226. #ifdef _WIN32
  2227. void usleep(unsigned int usec){
  2228. HANDLE timer;
  2229. LARGE_INTEGER ft;
  2230. static int init = 0;
  2231. if (init == 0){
  2232. init = 1;
  2233. const HINSTANCE ntdll = LoadLibrary("ntdll.dll");
  2234. if (ntdll != NULL){
  2235. typedef long(NTAPI* pNtQueryTimerResolution)(u64bit* MinimumResolution, u64bit* MaximumResolution, u64bit* CurrentResolution);
  2236. typedef long(NTAPI* pNtSetTimerResolution)(u64bit RequestedResolution, char SetResolution, u64bit* ActualResolution);
  2237. pNtQueryTimerResolution NtQueryTimerResolution = (pNtQueryTimerResolution)GetProcAddress(ntdll, "NtQueryTimerResolution");
  2238. pNtSetTimerResolution NtSetTimerResolution = (pNtSetTimerResolution)GetProcAddress(ntdll, "NtSetTimerResolution");
  2239. if (NtQueryTimerResolution != NULL && NtSetTimerResolution != NULL){
  2240. u64bit minimum, maximum, current;
  2241. NtQueryTimerResolution(&minimum, &maximum, &current);
  2242. NtSetTimerResolution(maximum, (char)1, &current);
  2243. }
  2244. FreeLibrary(ntdll);
  2245. }
  2246. }
  2247. ft.QuadPart = -(10 * (__int64)usec);
  2248. timer = CreateWaitableTimer(NULL, TRUE, NULL);
  2249. SetWaitableTimer(timer, &ft, 0, NULL, NULL, 0);
  2250. WaitForSingleObject(timer, INFINITE);
  2251. CloseHandle(timer);
  2252. }
  2253. void laSpinInit(SYSLOCK* lock) {
  2254. InitializeCriticalSection(lock);
  2255. }
  2256. void laSpinDestroy(SYSLOCK* lock) {
  2257. DeleteCriticalSection(lock);
  2258. }
  2259. void laSpinLock(SYSLOCK* lock) {
  2260. EnterCriticalSection(lock);
  2261. }
  2262. void laSpinUnlock(SYSLOCK* lock) {
  2263. LeaveCriticalSection(lock);
  2264. }
  2265. #endif
  2266. #ifdef LA_LINUX
  2267. void laSpinInit(SYSLOCK* lock) {
  2268. pthread_spin_init(lock, 0);
  2269. }
  2270. void laSpinDestroy(SYSLOCK* lock) {
  2271. pthread_spin_destroy(lock);
  2272. }
  2273. void laSpinLock(SYSLOCK* lock) {
  2274. pthread_spin_lock(lock);
  2275. }
  2276. void laSpinUnlock(SYSLOCK* lock) {
  2277. pthread_spin_unlock(lock);
  2278. }
  2279. #endif
  2280. #ifdef LAGUI_ANDROID
  2281. void laSpinInit(SYSLOCK* lock) {
  2282. return;
  2283. }
  2284. void laSpinDestroy(SYSLOCK* lock) {
  2285. return;
  2286. }
  2287. void laSpinLock(SYSLOCK* lock) {
  2288. return;
  2289. }
  2290. void laSpinUnlock(SYSLOCK* lock) {
  2291. return;
  2292. }
  2293. #endif
  2294. //======================================= lua utils
  2295. #ifdef LA_WITH_LUAJIT
  2296. static const char *progname = LUA_PROGNAME;
  2297. static int la_luaTraceback(lua_State *L){
  2298. if (!lua_isstring(L, 1)) { /* Non-string error object? Try metamethod. */
  2299. if (lua_isnoneornil(L, 1) ||
  2300. !luaL_callmeta(L, 1, "__tostring") ||
  2301. !lua_isstring(L, -1))
  2302. return 1; /* Return non-string error object. */
  2303. lua_remove(L, 1); /* Replace object by result of __tostring metamethod. */
  2304. }
  2305. luaL_traceback(L, L, lua_tostring(L, 1), 1);
  2306. return 1;
  2307. }
  2308. static void la_luaMessage(const char *msg){
  2309. if (progname) { logPrint("%s: ",progname); } logPrint("%s\n",msg);
  2310. }
  2311. static int la_luaReport(lua_State *L, int status){
  2312. if (status && !lua_isnil(L, -1)) {
  2313. const char *msg = lua_tostring(L, -1);
  2314. if (msg == NULL) msg = "(error object is not a string)";
  2315. la_luaMessage(msg);
  2316. lua_pop(L, 1);
  2317. }
  2318. return status;
  2319. }
  2320. static int la_luaDoCall(lua_State *L, int narg, int clear){
  2321. int status;
  2322. int base = lua_gettop(L) - narg; /* function index */
  2323. lua_pushcfunction(L, la_luaTraceback); /* push la_luaTraceback function */
  2324. lua_insert(L, base); /* put it under chunk and args */
  2325. status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
  2326. lua_remove(L, base); /* remove la_luaTraceback function */
  2327. /* force a complete garbage collection in case of errors */
  2328. if (status != LUA_OK) lua_gc(L, LUA_GCCOLLECT, 0);
  2329. return status;
  2330. }
  2331. static int la_luaIncomplete(lua_State *L, int status){
  2332. if (status == LUA_ERRSYNTAX) {
  2333. size_t lmsg;
  2334. const char *msg = lua_tolstring(L, -1, &lmsg);
  2335. const char *tp = msg + lmsg - (sizeof(LUA_QL("<eof>")) - 1);
  2336. if (strstr(msg, LUA_QL("<eof>")) == tp) { lua_pop(L, 1); return 1; }
  2337. }
  2338. return 0; /* else... */
  2339. }
  2340. int terLoadLine(char* buf, int firstline){
  2341. lua_State *L=MAIN.L;
  2342. if(!MAIN.TerminalIncomplete){ lua_settop(L, 0); }
  2343. size_t len = strlen(buf); if(len>=512){ buf[512]=0; }
  2344. if(len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
  2345. if(firstline && buf[0] == '=') lua_pushfstring(L, "return %s", buf+1);
  2346. else lua_pushstring(L, buf);
  2347. if(MAIN.TerminalIncomplete){
  2348. lua_pushliteral(L, "\n"); lua_insert(L, -2); lua_concat(L, 3);
  2349. }
  2350. int status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "terLoadLine");
  2351. if(la_luaIncomplete(L,status)){
  2352. MAIN.TerminalIncomplete=1;
  2353. }else{
  2354. MAIN.TerminalIncomplete=0;
  2355. lua_remove(L, 1);
  2356. }
  2357. if(status==LUA_OK && (!MAIN.TerminalIncomplete)){
  2358. status = la_luaDoCall(L, 0, 0);
  2359. la_luaReport(L, status);
  2360. if (status == LUA_OK && lua_gettop(L) > 0) { /* any result to print? */
  2361. lua_getglobal(L, "log");
  2362. lua_insert(L, 1);
  2363. if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
  2364. la_luaMessage(lua_pushfstring(L, "error calling " LUA_QL("log") " (%s)",
  2365. lua_tostring(L, -1)));
  2366. }
  2367. }
  2368. return status;
  2369. }
  2370. static int lalua_Log(lua_State *L) {
  2371. int n = lua_gettop(L); int i;
  2372. lua_getglobal(L, "tostring");
  2373. for (i=1; i<=n; i++) {
  2374. const char *s;
  2375. lua_pushvalue(L, -1); /* tostring function */
  2376. lua_pushvalue(L, i); /* value to print */
  2377. lua_call(L, 1, 1);
  2378. s = lua_tostring(L, -1); /* get result */
  2379. if (s == NULL) return luaL_error(L, LUA_QL("tostring") " must return a string to "LUA_QL("use `log`"));
  2380. if (i>1) logPrint(" ");
  2381. logPrint(s); lua_pop(L, 1); /* pop result */
  2382. }
  2383. logPrint("\n");
  2384. return 0;
  2385. }
  2386. void la_luaLoadLibs(lua_State *L){
  2387. lua_gc(L, LUA_GCSTOP, 0);
  2388. luaL_openlibs(L);
  2389. lua_register(L,"log",lalua_Log);
  2390. if(luaL_loadstring(L, LA_LUA_LIB_COMMON) || lua_pcall(L, 0, 0, 0)){ logPrint(" Error loading lagui lua libs.\n"); };
  2391. if(luaL_loadstring(L, LA_LUA_LIB_AUDIO) || lua_pcall(L, 0, 0, 0)){ logPrint(" Error loading lua libs for audio.\n"); };
  2392. lua_gc(L, LUA_GCRESTART, -1);
  2393. }
  2394. void la_luaPrintStatus(lua_State *L){
  2395. logPrint(LUAJIT_VERSION " -- " LUAJIT_COPYRIGHT ". " LUAJIT_URL "\n");
  2396. int n; const char *s;
  2397. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  2398. lua_getfield(L, -1, "jit"); lua_remove(L, -2); /* Get jit.* module table. */
  2399. lua_getfield(L, -1, "status"); lua_remove(L, -2);
  2400. n = lua_gettop(L);
  2401. lua_call(L, 0, LUA_MULTRET);
  2402. logPrint(lua_toboolean(L, n) ? "JIT: ON" : "JIT: OFF");
  2403. for (n++; (s = lua_tostring(L, n)); n++) { logPrint("%s ",s); }
  2404. logPrint("\n");
  2405. lua_settop(L, 0); /* clear stack */
  2406. }
  2407. void la_luaDumpStack(lua_State *L){
  2408. int top=lua_gettop(L); for (int i=1; i <= top; i++) {
  2409. printf("%d\t%s\t", i, luaL_typename(L,i));
  2410. switch (lua_type(L, i)) {
  2411. case LUA_TNUMBER: printf("%g\n",lua_tonumber(L,i)); break;
  2412. case LUA_TSTRING: printf("%s\n",lua_tostring(L,i)); break;
  2413. case LUA_TBOOLEAN: printf("%s\n", (lua_toboolean(L, i) ? "true" : "false")); break;
  2414. case LUA_TNIL: printf("%s\n", "nil"); break;
  2415. default: printf("%p\n",lua_topointer(L,i)); break;
  2416. }
  2417. }
  2418. }
  2419. #else //luajit
  2420. int terLoadLine(char* buf, int firstline){
  2421. logPrint(buf); return 0;
  2422. }
  2423. #endif //luajit
  2424. #ifdef LAGUI_ANDROID
  2425. void glPointSize(real a){
  2426. return;
  2427. }
  2428. void glDrawBuffer(GLenum mode){
  2429. GLenum b={GL_NONE};
  2430. glDrawBuffers(1,b);
  2431. }
  2432. #endif