*/}}

la_util.c 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759
  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. int level; void* head = memGetHead(Data, &level);
  1235. laMemoryPoolPart *mp;
  1236. if(level==2) { mp = ((laMemNodeHyper*)head)->InPool; laDataBlockNoLongerExists(Data,&((laMemNodeHyper*)head)->Users);
  1237. laListHandle* l=hsh65536DoHashNUID(&MAIN.DBInst2,((laMemNodeHyper*)head)->NUID.String); lstRemoveItem(l,head);}
  1238. if(level==1) { mp = ((laMemNode*)head)->InPool; laDataBlockNoLongerExists(Data,&((laMemNode*)head)->Users); }
  1239. }
  1240. void memTake(void *Data){
  1241. laListHandle* l=hsh65536DoHashLongPtr(MAIN.DBInstMemLeft,Data); lstRemovePointer(l,Data);
  1242. }
  1243. void memFreeRemainingLeftNodes(){
  1244. laListHandle* l; void* m;
  1245. for(int i=0;i<65536;i++){
  1246. l=&MAIN.DBInstMemLeft->Entries[i]; while(m=lstPopPointer(l)){ memFree(m);
  1247. #ifdef DEBUG
  1248. printf("left freed %x\n",m);
  1249. #endif
  1250. }
  1251. }
  1252. }
  1253. void memNoLonger(){
  1254. for(int i=0;i<256;i++){
  1255. laMemoryPool* mp; while(mp=lstPopItem(&MAIN.GlobalMemPool.Entries[i])){ memDestroyPool(mp); }
  1256. }
  1257. }
  1258. laStaticMemoryPoolNode *memNewStaticPool(laStaticMemoryPool *smp){
  1259. laStaticMemoryPoolNode *smpn = calloc(1, LA_MEMORY_POOL_128MB);
  1260. smpn->UsedByte = sizeof(laStaticMemoryPoolNode);
  1261. lstPushItem(&smp->Pools, smpn);
  1262. return smpn;
  1263. }
  1264. void *memStaticAcquire(laStaticMemoryPool *smp, int size){
  1265. laStaticMemoryPoolNode *smpn = smp->Pools.pFirst;
  1266. void *ret;
  1267. if (!smpn || (smpn->UsedByte + size) > LA_MEMORY_POOL_128MB) smpn = memNewStaticPool(smp);
  1268. ret = ((BYTE *)smpn) + smpn->UsedByte;
  1269. smpn->UsedByte += size;
  1270. return ret;
  1271. }
  1272. void *memStaticAcquireThread(laStaticMemoryPool *smp, int size){
  1273. laStaticMemoryPoolNode *smpn = smp->Pools.pFirst;
  1274. void *ret;
  1275. //laSpinLock(&smp->csMem);
  1276. if (!smpn || (smpn->UsedByte + size) > LA_MEMORY_POOL_128MB) smpn = memNewStaticPool(smp);
  1277. ret = ((BYTE *)smpn) + smpn->UsedByte;
  1278. smpn->UsedByte += size;
  1279. //laSpinUnlock(&smp->csMem);
  1280. return ret;
  1281. }
  1282. void *memStaticDestroy(laStaticMemoryPool *smp){
  1283. laStaticMemoryPoolNode *smpn;
  1284. void *ret;
  1285. while (smpn = lstPopItem(&smp->Pools)){
  1286. FreeMem(smpn);
  1287. }
  1288. smp->EachSize = 0;
  1289. return ret;
  1290. }
  1291. void la_ReferencedBlockDeleted(void* This, laItemUserLinker* iul){
  1292. void** user=iul->Pointer.p; if(*user==This){ (*user)=0; } laStopUsingDataBlock(iul->Additional, 0, This); // <<< should always remove.
  1293. }
  1294. void la_ReferrerDeleted(void* This, laItemUserLinker* iul){
  1295. void* instance=iul->Pointer.p; if(instance!=This){ laStopUsingDataBlock(instance, 0, This); }
  1296. }
  1297. void memAssignRef(void* This, void** ptr, void* instance){
  1298. laItemUserLinker* iul;
  1299. if((!This)||(!ptr)) return;
  1300. if(instance){
  1301. laItemUserLinker*iul=laUseDataBlock(instance, 0, 0, ptr, la_ReferencedBlockDeleted, 0); if(iul){iul->Additional=This;}
  1302. laUseDataBlock(This, 0, 0, instance, la_ReferrerDeleted, 0);
  1303. }else{
  1304. laStopUsingDataBlock((*ptr), 0, This);
  1305. laStopUsingDataBlock(This, 0, (*ptr));
  1306. }
  1307. (*ptr)=instance;
  1308. }
  1309. void memAssignRefSafe(laSubProp* sp, void* This, void** ptr, void* instance){
  1310. laPropContainer* pc=sp?la_EnsureSubTarget(sp,instance):0;
  1311. if(pc&&!pc->OtherAlloc) memAssignRef(This,ptr,instance);
  1312. else (*ptr)=instance;
  1313. }
  1314. //=======================================================================[str]
  1315. char *strGetNextString(char **pivot, char *NextMark){
  1316. int lenth = 0;
  1317. char *countP = *pivot;
  1318. char *result = 0;
  1319. int FloatArg = 0;
  1320. int i,advance;
  1321. if (**pivot == U'\0') return 0;
  1322. if (*NextMark == U'~') FloatArg = 1;
  1323. // container@identifier=window container#window contianer%
  1324. int UC=1;
  1325. while (!lenth){
  1326. for (countP; *countP != U'.' && *(*pivot) != U'\0' && UC && *countP && *countP != U'@' && *countP != U'=' && *countP != U'#' && *countP != U'$';){
  1327. if((*countP)=='\\'){
  1328. countP++; lenth++; }
  1329. UC = laToUnicode(countP, &advance);
  1330. lenth+=advance;
  1331. countP+=advance;
  1332. }
  1333. if (lenth || (*countP) == 0) break;
  1334. (*pivot)++; countP++;
  1335. }
  1336. *NextMark = (*pivot)[lenth];
  1337. if (!(*NextMark)) *NextMark = U'.';
  1338. if (lenth){
  1339. result = CreateNewBuffer(char, lenth + 1);
  1340. int pi=0; for (i = 0; i < lenth; i++){
  1341. if((*pivot)[i]=='\\'){ continue; }
  1342. result[pi] = (*pivot)[i]; pi++;
  1343. }
  1344. result[pi] = U'\0';
  1345. if ((*pivot)[lenth] == U'\0') *pivot = &((*pivot)[lenth]);
  1346. else
  1347. (*pivot) += lenth + 1;
  1348. return result;
  1349. }else{
  1350. return 0;
  1351. }
  1352. };
  1353. int strGetStringTerminateBy(char *content, char terminator, char *Out){
  1354. int Ofst = 0;
  1355. int Skip = 0;
  1356. int i = 0, advance;
  1357. if ((!content) || (*content == U'\0')) return 0;
  1358. int UC;
  1359. for (Ofst; content[Ofst] != terminator && content[Ofst] != U'\0'; ){
  1360. UC = laToUnicode(&content[Ofst], &advance);
  1361. for(int a=0;a<advance;a++){
  1362. Out[i] = content[Ofst];
  1363. Ofst++; i++;
  1364. }
  1365. }
  1366. Out[i] = 0;
  1367. return i;
  1368. };
  1369. char *strGetNewStringTerminateBy_PivotOver(char *content, char terminator, char **NewPivot, int IgnoreSpace){
  1370. int Ofst = 0;
  1371. int Skip = 0;
  1372. int i = 0;
  1373. char *NewString;
  1374. if (!content || *content == U'\0') return 0;
  1375. if (IgnoreSpace) for (i; content[i] == U' '; i++) ;
  1376. int UC,advance;
  1377. for (Ofst; content[Ofst] != terminator && content[Ofst] != U'\0';){
  1378. UC = laToUnicode(&content[Ofst], &advance);
  1379. Ofst+=advance;
  1380. }
  1381. NewString = CreateNewBuffer(char, Ofst + 1 - i);
  1382. memcpy(NewString, &content[i], sizeof(char) * (Ofst - i));
  1383. NewString[Ofst - i] = U'\0';
  1384. *NewPivot = content[Ofst]?&content[Ofst + 1]:&content[Ofst];
  1385. return NewString;
  1386. };
  1387. int strHeadOfStringMatch(char *Str, char *SubStr){
  1388. int len = strlen(SubStr);
  1389. int i = 0;
  1390. for (i; i < len; i++){
  1391. if (Str[i] != SubStr[i]) return 0;
  1392. }
  1393. return 1;
  1394. }
  1395. int strSkipSegmet(char **pivot, char *content){
  1396. if (!pivot || !(*pivot) || !(*(*pivot)) || !content) return 0;
  1397. if (strHeadOfStringMatch(*pivot, content)){
  1398. (*pivot) += strlen(content);
  1399. return 1;
  1400. }
  1401. return 0;
  1402. }
  1403. char *strGetLastSegment(char *Content, char Seperator){
  1404. char *p = Content;
  1405. char *pn = Content;
  1406. while (1){
  1407. while (*pn != Seperator){
  1408. if (!(*pn)) return p;
  1409. pn++;
  1410. }
  1411. pn++;
  1412. p = pn;
  1413. }
  1414. }
  1415. void strDiscardLastSegmentSeperateBy(char *Content, char Seperator){
  1416. char *p = Content;
  1417. char *pn = Content;
  1418. while (1){
  1419. while (*pn != Seperator){
  1420. if (!(*pn)){
  1421. *p = 0;
  1422. return;
  1423. }
  1424. pn++;
  1425. }
  1426. p = pn;
  1427. pn++;
  1428. }
  1429. }
  1430. void strDiscardSameBeginningSeperatedBy(char *s1, char *s2, char **Result1, char **Result2, char Seperator){
  1431. int i = 0;
  1432. int p = 0;
  1433. while (s1[i] == s2[i]){
  1434. i++;
  1435. if (s1[i] == Seperator) p = i;
  1436. if (!s1[i]){
  1437. p = i;
  1438. break;
  1439. }
  1440. if (!s2[i]){
  1441. p = i;
  1442. break;
  1443. }
  1444. }
  1445. *Result1 = &s1[p];
  1446. *Result2 = &s2[p];
  1447. }
  1448. int strCountSegmentSeperateBy(char *Content, char Seperator){
  1449. char *p = Content;
  1450. char *pn = Content;
  1451. int c = Content[0] ? (Content[0] == Seperator ? 0 : 1) : 0;
  1452. while (1){
  1453. while (*pn != Seperator){
  1454. if (!(*pn)){
  1455. if ((*p) == Seperator) c--;
  1456. return c;
  1457. }
  1458. p = pn;
  1459. pn++;
  1460. }
  1461. c++;
  1462. pn++;
  1463. }
  1464. return c;
  1465. }
  1466. void strMakeDifferentName(char *Target){
  1467. char *p = strGetLastSegment(Target, '.');
  1468. int Temp;
  1469. if (!sscanf(p, "%d", &Temp)){
  1470. int l = strlen(p);
  1471. if (p[l - 1] != U'.') strcat(p, ".");
  1472. strPrintIntAfter(Target, 0, 001);
  1473. }else{
  1474. sprintf(p, "%d", Temp + 1);
  1475. };
  1476. }
  1477. void strReplaceCharacter(char *Str, char Find, char Replace){
  1478. char *p = Str;
  1479. if (!p) return;
  1480. while (*p){
  1481. if (*p == Find) *p = Replace;
  1482. p++;
  1483. }
  1484. }
  1485. void strToUpper(char *Str){
  1486. char *p = Str; if (!p) return;
  1487. while (*p){
  1488. if (*p >= 'a' && *p <= 'z') *p += 'A' - 'a';
  1489. p++;
  1490. }
  1491. }
  1492. void strToLower(char *Str){
  1493. char *p = Str; if (!p) return;
  1494. while (*p){
  1495. if (*p >= 'A' && *p <= 'Z') *p -= 'A' - 'a';
  1496. p++;
  1497. }
  1498. }
  1499. int tolowerGuarded(int a) {
  1500. if (a >= 'A' && a <= 'Z') a -= 'A' - 'a';
  1501. return a;
  1502. }
  1503. laStringSplitor *strSplitPath(const char *path,char terminator){
  1504. laStringPart *sp;
  1505. laStringSplitor *ss;
  1506. char *pivot = path;
  1507. char *temp_result;
  1508. char Type = terminator?terminator:'.';
  1509. char NextType = terminator?terminator:'.';
  1510. if (!path || !path[0]) return 0;
  1511. ss = memAcquireSimple(sizeof(laStringSplitor));
  1512. while (temp_result = strGetNextString(&pivot, &NextType)){
  1513. if (*temp_result != U'\0'){
  1514. sp = memAcquireSimple(sizeof(laStringPart));
  1515. sp->Content = temp_result;
  1516. lstAppendItem(&ss->parts, sp);
  1517. ss->NumberParts += 1;
  1518. if (NextType == U'$') sp->Type = U'$';
  1519. else
  1520. sp->Type = Type;
  1521. if (sp->Type == U'='){
  1522. if (sp->Content[0] >= U'0' && sp->Content[0] <= 9){
  1523. sscanf(sp->Content, "%d", &sp->IntValue);
  1524. }
  1525. }
  1526. if (NextType == U'$') NextType = U'.';
  1527. Type = NextType;
  1528. }
  1529. }
  1530. if (ss->NumberParts == 0){
  1531. strDestroyStringSplitor(&ss);
  1532. return 0;
  1533. }
  1534. return ss;
  1535. };
  1536. void DF_ClearStingParts(laStringPart *sp){
  1537. FreeMem(sp->Content);
  1538. };
  1539. int strDestroyStringSplitor(laStringSplitor **ss){
  1540. if (!(*ss)) return 0;
  1541. lstForAllItemsDo(DF_ClearStingParts, &(*ss)->parts);
  1542. lstDestroyList(&(*ss)->parts);
  1543. memFree(*ss);
  1544. *ss = 0;
  1545. return 1;
  1546. }
  1547. char * strSub(const char *input, const char *substring, const char *replace){
  1548. int number_of_matches = 0;
  1549. size_t substring_size = strlen(substring), replace_size = strlen(replace), buffer_size;
  1550. char *buffer, *bp, *ip;
  1551. if (substring_size){
  1552. ip = strstr(input, substring);
  1553. while (ip != NULL){
  1554. number_of_matches++;
  1555. ip = strstr(ip+substring_size, substring);
  1556. }
  1557. }
  1558. else number_of_matches = strlen (input) + 1;
  1559. buffer_size = strlen(input) + number_of_matches*(replace_size - substring_size) + 1;
  1560. if ((buffer = ((char *) malloc(buffer_size))) == NULL){
  1561. return NULL;
  1562. }
  1563. bp = buffer;
  1564. ip = strstr(input, substring);
  1565. while ((ip != NULL) && (*input != '\0')){
  1566. if (ip == input){
  1567. memcpy (bp, replace, replace_size+1);
  1568. bp += replace_size;
  1569. if (substring_size)input += substring_size;
  1570. else*(bp++) = *(input++);
  1571. ip = strstr(input, substring);
  1572. }
  1573. else while (input != ip) *(bp++) = *(input++);
  1574. }
  1575. if (substring_size)strcpy (bp, input);
  1576. else memcpy (bp, replace, replace_size+1);
  1577. return buffer;
  1578. }
  1579. char buff[128]={0};
  1580. int strMakeInstructions(laStringSplitor **result, const char *content){
  1581. laStringPart *sp;
  1582. laStringSplitor *ss = *result;
  1583. char *pivot = content;
  1584. unsigned char *temp_result;
  1585. if (!content || !content[0]) return 0;
  1586. if (!ss) ss = *result = memAcquireSimple(sizeof(laStringSplitor));
  1587. while (temp_result = strGetNewStringTerminateBy_PivotOver(pivot, '=', &pivot, 0)){
  1588. if (*temp_result != U'\0'){
  1589. sp = memAcquireSimple(sizeof(laStringPart));
  1590. sp->Content = temp_result;
  1591. lstAppendItem(&ss->parts, sp);
  1592. ss->NumberParts += 1;
  1593. }
  1594. temp_result = strGetNewStringTerminateBy_PivotOver(pivot, ';', &pivot, 0);
  1595. if (!temp_result) break;
  1596. if (*temp_result != U'\0'){
  1597. sp = memAcquireSimple(sizeof(laStringPart));
  1598. sp->Content = temp_result;
  1599. lstAppendItem(&ss->parts, sp);
  1600. ss->NumberParts += 1;
  1601. if (temp_result[0] >= U'0' && temp_result[0] <= U'9' || temp_result[0]>=128){
  1602. sscanf(temp_result, "%d", &sp->IntValue);
  1603. sscanf(temp_result, "%lf", &sp->FloatValue);
  1604. }
  1605. }
  1606. }
  1607. if (ss->NumberParts == 0){
  1608. strDestroyStringSplitor(&ss);
  1609. return 0;
  1610. }
  1611. return 1;
  1612. }
  1613. laStringPart *strGetArgument(laStringSplitor *ss, const char *content){
  1614. laStringPart *sp;
  1615. if (!ss) return 0;
  1616. for (sp = ss->parts.pFirst; sp; sp = sp->Item.pNext ? ((laListItem *)sp->Item.pNext)->pNext : 0){
  1617. if (strSame(content, sp->Content)) return sp->Item.pNext;
  1618. }
  1619. return 0;
  1620. }
  1621. char *strGetArgumentString(laStringSplitor *ss, const char *content){
  1622. laStringPart *sp;
  1623. if (!ss) return 0;
  1624. for (sp = ss->parts.pFirst; sp; sp = sp->Item.pNext ? ((laListItem *)sp->Item.pNext)->pNext : 0){
  1625. if (strSame(content, sp->Content)) return sp->Item.pNext ? ((laStringPart *)sp->Item.pNext)->Content : 0;
  1626. }
  1627. return 0;
  1628. }
  1629. int strArgumentMatch(laStringSplitor *ss, const char *id, const char *value){
  1630. laStringPart *sp;
  1631. if (!ss) return 0;
  1632. for (sp = ss->parts.pFirst; sp; sp = sp->Item.pNext ? ((laListItem *)sp->Item.pNext)->pNext : 0){
  1633. if (strSame(id, sp->Content)) return (strSame(((laStringPart *)sp->Item.pNext)->Content, value));
  1634. }
  1635. return 0;
  1636. }
  1637. int strGetIntSimple(const char *content){
  1638. int a;
  1639. sscanf(content, "%d", &a);
  1640. return a;
  1641. }
  1642. real strGetFloatSimple(const char *content){
  1643. real a;
  1644. sscanf(content, "%lf", &a);
  1645. return a;
  1646. }
  1647. void strConvInt_CString(int src, char *dest, int lenth){
  1648. sprintf(dest, "%d", src);
  1649. };
  1650. void strConvFloat_CString(real src, char *dest, int lenth){
  1651. sprintf(dest, "%lf", src);
  1652. };
  1653. void strCopyFull(char *dest, const char *src){
  1654. if (src && dest) strcpy(dest, src);
  1655. }
  1656. void strCopySized(char *dest, int LenthLim,const char *src){
  1657. if (src && dest) strcpy(dest, src);
  1658. }
  1659. void strPrintFloatAfter(char *dest, int LenthLim, int bits, real data){
  1660. char temp[64]={0};
  1661. sprintf(temp, "%.*lf", bits, data);
  1662. strcat(dest, temp);
  1663. }
  1664. void strPrintIntAfter(char *dest, int LenthLim, int data){
  1665. char temp[64]={0};
  1666. sprintf(&temp[0], "%d", data);
  1667. strcat(dest, temp);
  1668. }
  1669. void strEscapePath(char* OutCanBeSame, char* path){
  1670. char t[256]={0}; int ti=0;
  1671. for(int i=0;path[i];i++,ti++){
  1672. if(path[i]=='.'){ t[ti]='\\'; ti++; }
  1673. t[ti]=path[i];
  1674. }
  1675. strcpy(OutCanBeSame,t);
  1676. }
  1677. int strSame(const char *src, const char *dest){
  1678. return (src && dest && !strcmp(src, dest));
  1679. }
  1680. void strSafeDestroy(laSafeString **ss){
  1681. if (!*ss) return; lstRemoveItem(&SSC.SafeStrings, *ss);
  1682. if((*ss)->Ptr) memFree((*ss)->Ptr);
  1683. memFree(*ss); *ss=0;
  1684. }
  1685. void strSafeSet(laSafeString **ss, const char *Content){
  1686. int len;
  1687. if (!Content||!Content[0]){ strSafeDestroy(ss); return; }
  1688. len = strlen(Content);
  1689. if (len < 1) return;
  1690. if (*ss){
  1691. char* mem=memAcquireSimple(sizeof(char)*(len+1));
  1692. strcpy(mem, Content);
  1693. memFree((*ss)->Ptr);
  1694. (*ss)->Ptr=mem;
  1695. return;
  1696. }
  1697. (*ss) = memAcquireSimple(sizeof(laSafeString));
  1698. (*ss)->Ptr = memAcquireSimple(sizeof(char)*(len+1));
  1699. strcpy((*ss)->Ptr, Content);
  1700. lstAppendItem(&SSC.SafeStrings, *ss);
  1701. }
  1702. void strSafeAppend(laSafeString **ss, const char *Content){
  1703. if(!ss || !(*ss) || !Content){ strSafeSet(ss, Content); return; }
  1704. int OrigLen=strlen((*ss)->Ptr), ContentLen=strlen(Content);
  1705. char* mem=memAcquireSimple(sizeof(char)*(OrigLen+ContentLen+1));
  1706. memcpy(mem, (*ss)->Ptr, sizeof(char)*OrigLen);
  1707. memcpy(mem+sizeof(char)*OrigLen, Content, sizeof(char)*ContentLen);
  1708. mem[OrigLen+ContentLen]=0;
  1709. memFree((*ss)->Ptr);
  1710. (*ss)->Ptr=mem;
  1711. }
  1712. void strSafePrint(laSafeString **ss, const char *Format, ...){
  1713. char content[1024]; va_list va; va_start(va, Format); vsprintf(content, Format, va); va_end(va);
  1714. strSafeAppend(ss,content);
  1715. }
  1716. void strSafePrintV(laSafeString **ss, const char *Format, va_list args){
  1717. char content[1024]; va_list va; vsprintf(content, Format, args);
  1718. strSafeAppend(ss,content);
  1719. }
  1720. void strSafeDump(){
  1721. laSafeString*ss;
  1722. while(ss=lstPopItem(&SSC.SafeStrings)){
  1723. //if(ss->Ptr) printf("[String not freed] \"%s\"\n", ss->Ptr);
  1724. }
  1725. }
  1726. void strBeginEdit(laStringEdit **se, char *FullStr){
  1727. char *p = FullStr;
  1728. char buf[1024];
  1729. laStringEdit *nse = CreateNew(laStringEdit);
  1730. if(*se){ memcpy(nse,*se,sizeof(laStringEdit)); nse->Lines.pFirst=nse->Lines.pLast=0; nse->TotalLines=0; }
  1731. strEndEdit(se, 1);
  1732. nse->_BeginLine = -1; nse->_BeginBefore = -1;
  1733. if (FullStr && FullStr[0]){
  1734. while ((*p)){
  1735. laStringLine *sl = memAcquireSimple(sizeof(laStringLine));
  1736. p += strGetStringTerminateBy(p, '\n', buf);
  1737. strToUnicode(sl->Buf, buf);
  1738. lstAppendItem(&nse->Lines, sl); nse->TotalLines++;
  1739. if(*p){ p+=1; }
  1740. }
  1741. }
  1742. if (!nse->Lines.pFirst){
  1743. laStringLine *sl = memAcquireSimple(sizeof(laStringLine));
  1744. lstAppendItem(&nse->Lines, sl); nse->TotalLines=1;
  1745. }
  1746. laStringLine *sl = strGetCursorLine(nse, 0); int len=strlenU(sl->Buf);
  1747. if(len<nse->CursorBefore){ nse->CursorBefore=len; }
  1748. *se=nse;
  1749. }
  1750. char* strGetEditString(laStringEdit *se, int SelectionOnly){
  1751. if(!se) return 0; char* result=0; int next=0, max=0, len=0;
  1752. arrEnsureLength(&result, 0, &max, sizeof(char)); int NextChar=0;
  1753. int Line=0, starti=0, endat=INT_MAX;
  1754. for(laStringLine* sl=se->Lines.pFirst;sl;sl=sl->Item.pNext,Line++){
  1755. starti=0;
  1756. if(SelectionOnly && Line<se->BeginLine){ continue; }
  1757. if(SelectionOnly && Line==se->BeginLine){ starti=se->BeginBefore; }
  1758. int tlen=strlenU(&sl->Buf[starti]); int Extra=sl->Item.pNext?2:1;
  1759. if(SelectionOnly){ if(Line<se->EndLine){ Extra=2; }else{ Extra=1; } }
  1760. arrEnsureLength(&result, (len+tlen)*4+Extra, &max, sizeof(char));
  1761. if(SelectionOnly && Line==se->EndLine){ endat=se->EndBefore-starti; }
  1762. NextChar+=strToUTF8Lim(&result[NextChar], &sl->Buf[starti], endat); len+=tlen;
  1763. if(Extra==2){ result[NextChar]='\n'; NextChar+=1; }
  1764. if(SelectionOnly && Line==se->EndLine){ break; }
  1765. }
  1766. return result;
  1767. }
  1768. char* strEndEdit(laStringEdit **se, int FreeString){
  1769. laDisableIME(MAIN.CurrentWindow);
  1770. char *p=0; laStringLine *sl, *NextSl;
  1771. if (!se || !(*se)) return 0;
  1772. p=strGetEditString(*se, 0);
  1773. while (sl=lstPopItem(&(*se)->Lines)){ memFree(sl); }
  1774. FreeMem(*se); *se=0;
  1775. if(FreeString && p){ free(p); p=0; }
  1776. return p;
  1777. }
  1778. void strSetEditViewRange(laStringEdit* se, int Lines, int Cols){
  1779. se->ViewHeight = Lines; se->ViewWidth = Cols;
  1780. }
  1781. void strEnsureCursorVisible(laStringEdit* se){
  1782. if(!se->ViewHeight || !se->ViewWidth || se->CursorLine<0 || se->CursorBefore<0 ){return;}
  1783. if(se->CursorLine>se->ViewHeight+se->ViewStartLine-1){ se->ViewStartLine=se->CursorLine-se->ViewHeight+1; }
  1784. if(se->CursorLine<se->ViewStartLine){ se->ViewStartLine=se->CursorLine; }
  1785. if(se->CursorBefore>se->ViewStartCol+se->ViewWidth-1){ se->ViewStartCol=se->CursorBefore-se->ViewWidth+1; }
  1786. if(se->CursorBefore<se->ViewStartCol){ se->ViewStartCol=se->CursorBefore; }
  1787. }
  1788. void strRemoveLine(laStringEdit *se, laStringLine *sl){
  1789. lstRemoveItem(&se->Lines, sl);
  1790. memFree(sl); se->TotalLines--;
  1791. }
  1792. void strRemoveLineI(laStringEdit *se, int LineIndex){
  1793. int i = 0;
  1794. laStringLine *sl = se->Lines.pFirst, *NextSl;
  1795. while (sl){
  1796. NextSl = sl->Item.pNext;
  1797. if (i == LineIndex){ strRemoveLine(se, sl); break; }
  1798. i++;
  1799. sl = NextSl;
  1800. }
  1801. }
  1802. void strSetCursor(laStringEdit *se, int LineIndex, int BeforeIndex){
  1803. int maxbefore;
  1804. if (!se) return;
  1805. if(LineIndex<0){LineIndex=0;}
  1806. se->CursorLine = LineIndex;
  1807. maxbefore = strlenU(strGetCursorLine(se, &se->CursorLine)->Buf);
  1808. BeforeIndex = BeforeIndex < 0 ? 0 : BeforeIndex > maxbefore ? maxbefore : BeforeIndex;
  1809. se->CursorBefore = BeforeIndex;
  1810. se->BeginLine = -1;
  1811. se->BeginBefore = -1;
  1812. se->EndLine = -1;
  1813. se->EndBefore = -1;
  1814. strEnsureCursorVisible(se);
  1815. }
  1816. void strMoveCursor(laStringEdit *se, int Left, int Select){
  1817. int maxbefore;
  1818. int BeforeIndex;
  1819. int width = 1;
  1820. laStringLine *sl;
  1821. if (!se) return;
  1822. if(Select){ strLazySelect(se); } else { strCancelSelect(se); }
  1823. sl = strGetCursorLine(se, 0);
  1824. maxbefore = strlenU(sl->Buf);
  1825. BeforeIndex = se->CursorBefore - (Left ? 1 : -1);
  1826. if(BeforeIndex<0){
  1827. if(se->CursorLine>0) strSetCursor(se, se->CursorLine-1, INT_MAX);
  1828. }elif(BeforeIndex>maxbefore && se->CursorLine<se->TotalLines-1){
  1829. if(se->CursorLine>0) strSetCursor(se, se->CursorLine+1, 0);
  1830. }else{
  1831. se->CursorBefore = BeforeIndex>=maxbefore?maxbefore:BeforeIndex;
  1832. }
  1833. se->CursorPreferBefore = se->CursorBefore;
  1834. se->BeginLine = -1;
  1835. se->BeginBefore = -1;
  1836. se->EndLine = -1;
  1837. se->EndBefore = -1;
  1838. if(Select){ strEndSelect(se); }
  1839. strEnsureCursorVisible(se);
  1840. }
  1841. void strMoveCursorLine(laStringEdit *se, int Up, int Select){
  1842. int Line, maxbefore, LastIndex=-1;
  1843. laStringLine *sl;
  1844. if (!se) return;
  1845. if(Select){ strLazySelect(se); } else { strCancelSelect(se); }
  1846. Line=se->CursorLine - (Up? 1:-1);
  1847. if(Line<0) {Line=0;}
  1848. se->CursorLine = Line;
  1849. sl = strGetCursorLine(se, &LastIndex);
  1850. if(LastIndex>=0){ se->CursorLine = LastIndex; se->CursorPreferBefore=10000; }
  1851. maxbefore = strlenU(sl->Buf);
  1852. se->CursorBefore = se->CursorPreferBefore;
  1853. if(se->CursorBefore>maxbefore){ se->CursorBefore = maxbefore; }
  1854. if(LastIndex>=0){se->CursorPreferBefore=se->CursorBefore;}
  1855. if(Select){ strEndSelect(se); }
  1856. strEnsureCursorVisible(se);
  1857. }
  1858. int strHasSelection(laStringEdit* se){
  1859. return se->BeginBefore!=se->EndBefore||se->BeginLine!=se->EndLine;
  1860. }
  1861. void strCancelSelect(laStringEdit *se){
  1862. if (!se) return;
  1863. se->_BeginLine = -1;
  1864. se->_BeginBefore = -1;
  1865. se->BeginLine = -1;
  1866. se->EndLine = -1;
  1867. se->BeginBefore = -1;
  1868. se->EndBefore = -1;
  1869. }
  1870. void strLazySelect(laStringEdit *se){
  1871. if (!se || se->_BeginLine>=0) return;
  1872. se->_BeginLine = TNS_MAX2(se->CursorLine,0);
  1873. se->_BeginBefore = se->CursorBefore;
  1874. }
  1875. void strEndSelect(laStringEdit *se){
  1876. if (!se) return;
  1877. se->_EndLine = se->CursorLine;
  1878. se->_EndBefore = se->CursorBefore;
  1879. se->BeginLine = se->_BeginLine;
  1880. se->EndLine = se->_EndLine;
  1881. se->BeginBefore = se->_BeginBefore;
  1882. se->EndBefore = se->_EndBefore;
  1883. if(se->BeginLine>se->EndLine || (se->BeginLine==se->EndLine && se->BeginBefore>se->EndBefore))
  1884. { LA_SWAP(int,se->BeginLine,se->EndLine); LA_SWAP(int,se->BeginBefore,se->EndBefore); }
  1885. }
  1886. void strSelectLineAll(laStringEdit *se){
  1887. if (!se) return;
  1888. laStringLine *sl;
  1889. int len;
  1890. if (se->CursorLine == -1) sl = strGetBeginLine(se);
  1891. else
  1892. sl = strGetCursorLine(se, 0);
  1893. len = strlenU(sl->Buf);
  1894. se->EndBefore = len; se->EndLine=0;
  1895. se->BeginBefore = 0; se->BeginLine=0;
  1896. se->CursorBefore = len;
  1897. se->CursorLine = 0;
  1898. }
  1899. void strDeselectAll(laStringEdit *se){
  1900. if (!se) return;
  1901. laStringLine *sl;
  1902. int len;
  1903. if (se->CursorLine == -1) sl = strGetBeginLine(se);
  1904. else
  1905. sl = strGetCursorLine(se, 0);
  1906. len = strlenU(sl->Buf);
  1907. se->EndBefore = -1;
  1908. se->BeginBefore = -1;
  1909. se->BeginLine = -1;
  1910. se->EndLine = -1;
  1911. se->CursorBefore = len;
  1912. se->CursorLine = -1;
  1913. }
  1914. void strPanFoward(uint32_t *str, int Before, int Offset){
  1915. int len = strlenU(str);
  1916. int i = len + 1;
  1917. for (i; i >= Before; i--){
  1918. str[i + Offset] = str[i];
  1919. }
  1920. }
  1921. void strSquishBackward(uint32_t *str, int Before, int EndBefore){
  1922. int len = strlenU(str);
  1923. int i = Before;
  1924. int Offset = Before - EndBefore;
  1925. if (Before <= 0) return;
  1926. for (i; i <= len; i++){
  1927. str[i - Offset] = str[i];
  1928. }
  1929. }
  1930. void strClearSelection(laStringEdit *se){
  1931. //if (se->EndLine == -1) return;
  1932. if (se->BeginLine != se->EndLine){
  1933. int i = 0; int RemovedLines=0;
  1934. laStringLine *sl = se->Lines.pFirst, *NextSl;
  1935. while (sl){
  1936. NextSl = sl->Item.pNext;
  1937. if (i == se->BeginLine){
  1938. sl->Buf[se->BeginBefore] = U'\0';
  1939. }else if (i > se->BeginLine && i < se->EndLine){
  1940. strRemoveLine(se, sl); RemovedLines++;
  1941. }else if (i == se->EndLine){
  1942. strSquishBackward(sl->Buf, se->EndBefore, 0);
  1943. se->CursorLine = i-RemovedLines;
  1944. se->CursorBefore = 0;
  1945. se->BeginLine = -1;
  1946. se->BeginBefore = -1;
  1947. se->EndLine = -1;
  1948. se->EndBefore = -1;
  1949. strBackspace(se);
  1950. }
  1951. if (i > se->EndLine) break;
  1952. i++;
  1953. sl = NextSl;
  1954. }
  1955. }else{
  1956. int i = 0;
  1957. laStringLine *sl = se->Lines.pFirst, *NextSl;
  1958. while (sl){
  1959. NextSl = sl->Item.pNext;
  1960. if (i == se->EndLine) {
  1961. strSquishBackward(sl->Buf, se->EndBefore, se->BeginBefore);
  1962. se->CursorLine = i;
  1963. se->CursorBefore = se->BeginBefore;
  1964. se->BeginLine = -1;
  1965. se->BeginBefore = -1;
  1966. se->EndLine = -1;
  1967. se->EndBefore = -1;
  1968. break;
  1969. }
  1970. i++; sl = NextSl;
  1971. }
  1972. }
  1973. strEnsureCursorVisible(se);
  1974. }
  1975. laStringLine *strGetCursorLine(laStringEdit *se, int* ReturnIndexIfLast){
  1976. if (!se || se->CursorBefore <= -1) return se->Lines.pFirst;
  1977. int i = 0;
  1978. laStringLine *sl = se->Lines.pFirst, *NextSl;
  1979. while (sl){
  1980. NextSl = sl->Item.pNext;
  1981. if (i == se->CursorLine){
  1982. return sl;
  1983. }
  1984. i++;
  1985. sl = NextSl;
  1986. }
  1987. if(ReturnIndexIfLast){ *ReturnIndexIfLast=i-1;}
  1988. return se->Lines.pLast;
  1989. }
  1990. laStringLine *strGetBeginLine(laStringEdit *se){
  1991. if (!se || se->BeginLine <= -1) return se->Lines.pFirst;
  1992. int i = 0;
  1993. laStringLine *sl = se->Lines.pFirst, *NextSl;
  1994. while (sl){
  1995. NextSl = sl->Item.pNext;
  1996. if (i == se->BeginLine){
  1997. return sl;
  1998. }
  1999. i++;
  2000. sl = NextSl;
  2001. }
  2002. return se->Lines.pFirst;
  2003. }
  2004. void strInsertChar(laStringEdit *se, uint32_t a){
  2005. laStringLine *sl;
  2006. strClearSelection(se);
  2007. sl = strGetCursorLine(se, 0);
  2008. if(a==U'\n'){
  2009. laStringLine* nl=memAcquireSimple(sizeof(laStringLine));
  2010. if(sl->Buf[se->CursorBefore]!=U'\0') strcpyU(nl->Buf, &sl->Buf[se->CursorBefore]);
  2011. sl->Buf[se->CursorBefore]=U'\0';
  2012. se->CursorLine++; se->CursorBefore=0;
  2013. lstInsertItemAfter(&se->Lines, nl, sl); se->TotalLines++;
  2014. }else{
  2015. strPanFoward(sl->Buf, se->CursorBefore, 1);
  2016. sl->Buf[se->CursorBefore] = a;
  2017. se->CursorBefore += 1;
  2018. }
  2019. se->CursorPreferBefore = se->CursorBefore;
  2020. strEnsureCursorVisible(se);
  2021. }
  2022. void strBackspace(laStringEdit *se){
  2023. laStringLine *sl;
  2024. int width = 1;
  2025. if (se->CursorBefore == -1){
  2026. strClearSelection(se);
  2027. }else{
  2028. laStringLine *sl;
  2029. sl = strGetCursorLine(se, 0);
  2030. if (se->CursorBefore > 1 && sl->Buf[se->CursorBefore - 2] < 0) width = 2;
  2031. strSquishBackward(sl->Buf, se->CursorBefore, se->CursorBefore - width);
  2032. se->CursorBefore -= width;
  2033. if (se->CursorBefore <= -1){
  2034. if(sl->Item.pPrev){
  2035. laStringLine* ol=sl->Item.pPrev;
  2036. se->CursorBefore = strlenU(ol->Buf);
  2037. se->CursorLine--;
  2038. strcatU(ol->Buf, sl->Buf);
  2039. strRemoveLine(se, sl);
  2040. }
  2041. else {se->CursorBefore = 0;}
  2042. }
  2043. }
  2044. se->CursorPreferBefore = se->CursorBefore;
  2045. strEnsureCursorVisible(se);
  2046. }
  2047. void strMoveView(laStringEdit *se, int DownLines, int RightCharacters){
  2048. se->ViewStartLine+=DownLines;
  2049. se->ViewStartCol+=RightCharacters;
  2050. if(se->ViewStartLine>=se->TotalLines-1) se->ViewStartLine=se->TotalLines-1;
  2051. if(se->ViewStartLine<0) se->ViewStartLine=0;
  2052. if(se->ViewStartCol<0) se->ViewStartCol=0;
  2053. }
  2054. int laCopyFile(char *to, char *from){
  2055. #ifdef _WIN32
  2056. if(CopyFile(from, to, 0)) return 1; return 0;
  2057. #endif
  2058. #ifdef LA_LINUX
  2059. int fd_to, fd_from; char buf[4096];
  2060. ssize_t nread; int saved_errno;
  2061. fd_from = open(from, O_RDONLY); if (fd_from < 0) return 0;
  2062. fd_to = open(to, O_WRONLY|O_CREAT /* |O_EXCL */, 0666); if (fd_to < 0) goto out_error;
  2063. while (nread=read(fd_from,buf,sizeof(buf)), nread>0) {
  2064. char *out_ptr = buf; ssize_t nwritten;
  2065. do { nwritten = write(fd_to, out_ptr, nread);
  2066. if (nwritten >= 0){ nread -= nwritten; out_ptr += nwritten;}
  2067. else if (errno != EINTR){ goto out_error; }
  2068. }while (nread > 0);
  2069. }
  2070. if (nread == 0){
  2071. if (close(fd_to)<0){ fd_to = -1; goto out_error;}
  2072. close(fd_from);
  2073. return 1;
  2074. }
  2075. out_error:
  2076. saved_errno = errno;
  2077. close(fd_from); if (fd_to >= 0) close(fd_to);
  2078. errno = saved_errno;
  2079. return 0;
  2080. #endif //linux
  2081. }
  2082. int laEnsureDir(const char *dir) {
  2083. #ifdef LA_LINUX
  2084. char tmp[1024]; char *p = NULL; size_t len;
  2085. snprintf(tmp, sizeof(tmp),"%s",dir);
  2086. len = strlen(tmp);
  2087. if (tmp[len - 1] == '/') tmp[len - 1] = 0;
  2088. for (p = tmp + 1; *p; p++){
  2089. if (*p == '/') { *p = 0;
  2090. mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO);
  2091. *p = '/';
  2092. }
  2093. }
  2094. mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO);
  2095. struct stat statbuf;
  2096. if(stat(dir, &statbuf) != 0){ return 0; }
  2097. return S_ISDIR(statbuf.st_mode);
  2098. #endif
  2099. return 0;
  2100. }
  2101. #ifdef LAGUI_ANDROID
  2102. static char* la_FileDoableOrDir(char* file_path,int mode){
  2103. if(!access(file_path,F_OK)){
  2104. if(!access(file_path,mode)){ return file_path; }
  2105. }else{
  2106. char buf[PATH_MAX];
  2107. strcpy(buf,file_path);
  2108. strDiscardLastSegmentSeperateBy(buf,'/');
  2109. struct stat statbuf;
  2110. if(stat(buf, &statbuf) != 0){ return 0; }
  2111. if(S_ISDIR(statbuf.st_mode)){
  2112. if(mode&W_OK){ if(statbuf.st_mode & S_IWUSR) return file_path; }
  2113. if(mode&R_OK){ if(statbuf.st_mode & S_IRUSR) return file_path; }
  2114. }
  2115. }
  2116. return 0;
  2117. }
  2118. char* laAndroidEnsureValidFilePath(char* file_path, int mode){
  2119. static char buf[PATH_MAX];
  2120. MAIN.AndroidLastPath=0;
  2121. char* result=0;
  2122. if(result=la_FileDoableOrDir(file_path, mode)){ MAIN.AndroidLastPath=result; return result; }
  2123. sprintf(buf,"%s/%s", MAIN.InternalDataPath, file_path);
  2124. if(result=la_FileDoableOrDir(buf, mode)){ MAIN.AndroidLastPath=result; return result; }
  2125. sprintf(buf,"%s/%s", MAIN.ExternalDataPath, file_path);
  2126. if(result=la_FileDoableOrDir(buf, mode)){ MAIN.AndroidLastPath=result; return result; }
  2127. return 0;
  2128. }
  2129. #endif
  2130. //======================================================[ translation ]
  2131. void transNewLanguage(const char *LanguageID){
  2132. laTranslationNode *tn = memAcquire(sizeof(laTranslationNode));
  2133. strSafeSet(&tn->LanguageName, LanguageID);
  2134. lstAppendItem(&MAIN.Translation.Languages, tn);
  2135. MAIN.Translation.CurrentLanguage = tn;
  2136. }
  2137. void transSetLanguage(const char *LanguageID){
  2138. laTranslationNode *tn;
  2139. if (!LanguageID){
  2140. MAIN.Translation.CurrentLanguage = 0;
  2141. return;
  2142. }
  2143. for (tn = MAIN.Translation.Languages.pFirst; tn; tn = tn->Item.pNext){
  2144. if (!strcmp(SSTR(tn->LanguageName), LanguageID)){
  2145. MAIN.Translation.CurrentLanguage = tn; return;
  2146. }
  2147. }
  2148. transNewLanguage(LanguageID);
  2149. }
  2150. void transDumpMissMatchRecord(const char *filename){
  2151. laTranslationMatch *tm;
  2152. laListHandle *lst;
  2153. int i;
  2154. FILE *f = fopen(filename, "w"); if (!f) return;
  2155. for (i = 0; i < 256; i++){
  2156. lst = &MAIN.Translation.MisMatches.Entries[i];
  2157. for (tm = lst->pFirst; tm; tm = tm->Item.pNext){ if(tm->Target) fprintf(f, "%s | \n", tm->Target); }
  2158. }
  2159. fclose(f);
  2160. }
  2161. int IsThisTranslationMatch(laTranslationMatch *tm, char *p){
  2162. return (tm->Target && (!strcmp(tm->Target, p)));
  2163. }
  2164. void transNewEntry(const char *Target, const char *replacement){
  2165. laTranslationMatch *tm = memAcquireSimple(sizeof(laTranslationMatch));
  2166. tm->Target = Target; tm->Replacement = replacement;
  2167. hsh256InsertItemCSTR(&MAIN.Translation.CurrentLanguage->Matches, tm, Target);
  2168. }
  2169. void transNewMissEntry(const char *Target){
  2170. if (!hsh256FindItemSTR(&MAIN.Translation.MisMatches, IsThisTranslationMatch, Target)){
  2171. laTranslationMatch *tm = memAcquireSimple(sizeof(laTranslationMatch));
  2172. int len=strlen(Target); tm->Target=memAcquireSimple(len*sizeof(char)+1);
  2173. strcpy(tm->Target,Target);
  2174. hsh256InsertItemCSTR(&MAIN.Translation.MisMatches, tm, Target);
  2175. }
  2176. }
  2177. char *transLate(const char *Target){
  2178. if (!MAIN.Translation.CurrentLanguage || !MAIN.Translation.EnableTranslation || !Target || !Target[0]) return Target;
  2179. laTranslationMatch *tm = hsh256FindItemSTR(&MAIN.Translation.CurrentLanguage->Matches, IsThisTranslationMatch, Target);
  2180. if (!tm){ transNewMissEntry(Target); return Target; }
  2181. return tm->Replacement;
  2182. }
  2183. void transState(void *UNUSED, int val){
  2184. if (val) MAIN.Translation.EnableTranslation = 1;
  2185. else MAIN.Translation.EnableTranslation = 0;
  2186. laRedrawCurrentWindow();
  2187. }
  2188. void laOpenInternetLink(char *url){
  2189. laSafeString* s=0;
  2190. #ifdef LA_LINUX
  2191. strSafePrint(&s, "xdg-open %s", url);
  2192. #endif
  2193. #ifdef _WIN32
  2194. strSafePrint(&s, "start %s", url);
  2195. #endif
  2196. #ifdef LAGUI_ANDROID
  2197. JNIEnv *env = NULL;
  2198. JavaVM *vm = MAIN.app->activity->vm;
  2199. (*vm)->AttachCurrentThread(vm, &env, NULL);
  2200. jstring urlString = (*env)->NewStringUTF(env, url);
  2201. jclass uriClass = (*env)->FindClass(env, "android/net/Uri");
  2202. jmethodID uriParse = (*env)->GetStaticMethodID(env, uriClass, "parse", "(Ljava/lang/String;)Landroid/net/Uri;");
  2203. jobject uri = (*env)->CallStaticObjectMethod(env, uriClass, uriParse, urlString);
  2204. jclass intentClass = (*env)->FindClass(env, "android/content/Intent");
  2205. jfieldID actionViewId = (*env)->GetStaticFieldID(env, intentClass, "ACTION_VIEW", "Ljava/lang/String;");
  2206. jobject actionView = (*env)->GetStaticObjectField(env, intentClass, actionViewId);
  2207. jmethodID newIntent = (*env)->GetMethodID(env, intentClass, "<init>", "(Ljava/lang/String;Landroid/net/Uri;)V");
  2208. jobject intent = (*env)->AllocObject(env, intentClass);
  2209. (*env)->CallVoidMethod(env, intent, newIntent, actionView, uri);
  2210. jclass activityClass = (*env)->FindClass(env, "android/app/Activity");
  2211. jmethodID startActivity = (*env)->GetMethodID(env, activityClass, "startActivity", "(Landroid/content/Intent;)V");
  2212. (*env)->CallVoidMethod(env, MAIN.app->activity->clazz, startActivity, intent);
  2213. (*vm)->DetachCurrentThread(vm);
  2214. return;
  2215. #endif
  2216. system(s->Ptr);
  2217. strSafeDestroy(&s);
  2218. //these were windows stuff
  2219. //HKEY hkRoot, hSubKey;
  2220. //char ValueName[256]={0};
  2221. //char DataValue[256]={0};
  2222. //u64bit cbValueName = 256;
  2223. //u64bit cbDataValue = 256;
  2224. //char ShellChar[512]={0};
  2225. //DWORD dwType;
  2226. //
  2227. //ShellExecute(0, "open", link, 0, 0, SW_SHOWNORMAL);
  2228. //
  2229. //return;
  2230. }
  2231. #ifdef _WIN32
  2232. void usleep(unsigned int usec){
  2233. HANDLE timer;
  2234. LARGE_INTEGER ft;
  2235. static int init = 0;
  2236. if (init == 0){
  2237. init = 1;
  2238. const HINSTANCE ntdll = LoadLibrary("ntdll.dll");
  2239. if (ntdll != NULL){
  2240. typedef long(NTAPI* pNtQueryTimerResolution)(u64bit* MinimumResolution, u64bit* MaximumResolution, u64bit* CurrentResolution);
  2241. typedef long(NTAPI* pNtSetTimerResolution)(u64bit RequestedResolution, char SetResolution, u64bit* ActualResolution);
  2242. pNtQueryTimerResolution NtQueryTimerResolution = (pNtQueryTimerResolution)GetProcAddress(ntdll, "NtQueryTimerResolution");
  2243. pNtSetTimerResolution NtSetTimerResolution = (pNtSetTimerResolution)GetProcAddress(ntdll, "NtSetTimerResolution");
  2244. if (NtQueryTimerResolution != NULL && NtSetTimerResolution != NULL){
  2245. u64bit minimum, maximum, current;
  2246. NtQueryTimerResolution(&minimum, &maximum, &current);
  2247. NtSetTimerResolution(maximum, (char)1, &current);
  2248. }
  2249. FreeLibrary(ntdll);
  2250. }
  2251. }
  2252. ft.QuadPart = -(10 * (__int64)usec);
  2253. timer = CreateWaitableTimer(NULL, TRUE, NULL);
  2254. SetWaitableTimer(timer, &ft, 0, NULL, NULL, 0);
  2255. WaitForSingleObject(timer, INFINITE);
  2256. CloseHandle(timer);
  2257. }
  2258. void laSpinInit(SYSLOCK* lock) {
  2259. InitializeCriticalSection(lock);
  2260. }
  2261. void laSpinDestroy(SYSLOCK* lock) {
  2262. DeleteCriticalSection(lock);
  2263. }
  2264. void laSpinLock(SYSLOCK* lock) {
  2265. EnterCriticalSection(lock);
  2266. }
  2267. void laSpinUnlock(SYSLOCK* lock) {
  2268. LeaveCriticalSection(lock);
  2269. }
  2270. #endif
  2271. #ifdef LA_LINUX
  2272. void laSpinInit(SYSLOCK* lock) {
  2273. pthread_spin_init(lock, 0);
  2274. }
  2275. void laSpinDestroy(SYSLOCK* lock) {
  2276. pthread_spin_destroy(lock);
  2277. }
  2278. void laSpinLock(SYSLOCK* lock) {
  2279. pthread_spin_lock(lock);
  2280. }
  2281. void laSpinUnlock(SYSLOCK* lock) {
  2282. pthread_spin_unlock(lock);
  2283. }
  2284. #endif
  2285. #ifdef LAGUI_ANDROID
  2286. void laSpinInit(SYSLOCK* lock) {
  2287. return;
  2288. }
  2289. void laSpinDestroy(SYSLOCK* lock) {
  2290. return;
  2291. }
  2292. void laSpinLock(SYSLOCK* lock) {
  2293. return;
  2294. }
  2295. void laSpinUnlock(SYSLOCK* lock) {
  2296. return;
  2297. }
  2298. #endif
  2299. //======================================= lua utils
  2300. #ifdef LA_WITH_LUAJIT
  2301. static const char *progname = LUA_PROGNAME;
  2302. static int la_luaTraceback(lua_State *L){
  2303. if (!lua_isstring(L, 1)) { /* Non-string error object? Try metamethod. */
  2304. if (lua_isnoneornil(L, 1) ||
  2305. !luaL_callmeta(L, 1, "__tostring") ||
  2306. !lua_isstring(L, -1))
  2307. return 1; /* Return non-string error object. */
  2308. lua_remove(L, 1); /* Replace object by result of __tostring metamethod. */
  2309. }
  2310. luaL_traceback(L, L, lua_tostring(L, 1), 1);
  2311. return 1;
  2312. }
  2313. static void la_luaMessage(const char *msg){
  2314. if (progname) { logPrint("%s: ",progname); } logPrint("%s\n",msg);
  2315. }
  2316. static int la_luaReport(lua_State *L, int status){
  2317. if (status && !lua_isnil(L, -1)) {
  2318. const char *msg = lua_tostring(L, -1);
  2319. if (msg == NULL) msg = "(error object is not a string)";
  2320. la_luaMessage(msg);
  2321. lua_pop(L, 1);
  2322. }
  2323. return status;
  2324. }
  2325. static int la_luaDoCall(lua_State *L, int narg, int clear){
  2326. int status;
  2327. int base = lua_gettop(L) - narg; /* function index */
  2328. lua_pushcfunction(L, la_luaTraceback); /* push la_luaTraceback function */
  2329. lua_insert(L, base); /* put it under chunk and args */
  2330. status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
  2331. lua_remove(L, base); /* remove la_luaTraceback function */
  2332. /* force a complete garbage collection in case of errors */
  2333. if (status != LUA_OK) lua_gc(L, LUA_GCCOLLECT, 0);
  2334. return status;
  2335. }
  2336. static int la_luaIncomplete(lua_State *L, int status){
  2337. if (status == LUA_ERRSYNTAX) {
  2338. size_t lmsg;
  2339. const char *msg = lua_tolstring(L, -1, &lmsg);
  2340. const char *tp = msg + lmsg - (sizeof(LUA_QL("<eof>")) - 1);
  2341. if (strstr(msg, LUA_QL("<eof>")) == tp) { lua_pop(L, 1); return 1; }
  2342. }
  2343. return 0; /* else... */
  2344. }
  2345. int terLoadLine(char* buf, int firstline){
  2346. lua_State *L=MAIN.L;
  2347. if(!MAIN.TerminalIncomplete){ lua_settop(L, 0); }
  2348. size_t len = strlen(buf); if(len>=512){ buf[512]=0; }
  2349. if(len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
  2350. if(firstline && buf[0] == '=') lua_pushfstring(L, "return %s", buf+1);
  2351. else lua_pushstring(L, buf);
  2352. if(MAIN.TerminalIncomplete){
  2353. lua_pushliteral(L, "\n"); lua_insert(L, -2); lua_concat(L, 3);
  2354. }
  2355. int status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "terLoadLine");
  2356. if(la_luaIncomplete(L,status)){
  2357. MAIN.TerminalIncomplete=1;
  2358. }else{
  2359. MAIN.TerminalIncomplete=0;
  2360. lua_remove(L, 1);
  2361. }
  2362. if(status==LUA_OK && (!MAIN.TerminalIncomplete)){
  2363. status = la_luaDoCall(L, 0, 0);
  2364. la_luaReport(L, status);
  2365. if (status == LUA_OK && lua_gettop(L) > 0) { /* any result to print? */
  2366. lua_getglobal(L, "log");
  2367. lua_insert(L, 1);
  2368. if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
  2369. la_luaMessage(lua_pushfstring(L, "error calling " LUA_QL("log") " (%s)",
  2370. lua_tostring(L, -1)));
  2371. }
  2372. }
  2373. return status;
  2374. }
  2375. static int lalua_Log(lua_State *L) {
  2376. int n = lua_gettop(L); int i;
  2377. lua_getglobal(L, "tostring");
  2378. for (i=1; i<=n; i++) {
  2379. const char *s;
  2380. lua_pushvalue(L, -1); /* tostring function */
  2381. lua_pushvalue(L, i); /* value to print */
  2382. lua_call(L, 1, 1);
  2383. s = lua_tostring(L, -1); /* get result */
  2384. if (s == NULL) return luaL_error(L, LUA_QL("tostring") " must return a string to "LUA_QL("use `log`"));
  2385. if (i>1) logPrint(" ");
  2386. logPrint(s); lua_pop(L, 1); /* pop result */
  2387. }
  2388. logPrint("\n");
  2389. return 0;
  2390. }
  2391. void la_luaLoadLibs(lua_State *L){
  2392. lua_gc(L, LUA_GCSTOP, 0);
  2393. luaL_openlibs(L);
  2394. lua_register(L,"log",lalua_Log);
  2395. if(luaL_loadstring(L, LA_LUA_LIB_COMMON) || lua_pcall(L, 0, 0, 0)){ logPrint(" Error loading lagui lua libs.\n"); };
  2396. if(luaL_loadstring(L, LA_LUA_LIB_AUDIO) || lua_pcall(L, 0, 0, 0)){ logPrint(" Error loading lua libs for audio.\n"); };
  2397. lua_gc(L, LUA_GCRESTART, -1);
  2398. }
  2399. void la_luaPrintStatus(lua_State *L){
  2400. logPrint(LUAJIT_VERSION " -- " LUAJIT_COPYRIGHT ". " LUAJIT_URL "\n");
  2401. int n; const char *s;
  2402. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  2403. lua_getfield(L, -1, "jit"); lua_remove(L, -2); /* Get jit.* module table. */
  2404. lua_getfield(L, -1, "status"); lua_remove(L, -2);
  2405. n = lua_gettop(L);
  2406. lua_call(L, 0, LUA_MULTRET);
  2407. logPrint(lua_toboolean(L, n) ? "JIT: ON" : "JIT: OFF");
  2408. for (n++; (s = lua_tostring(L, n)); n++) { logPrint("%s ",s); }
  2409. logPrint("\n");
  2410. lua_settop(L, 0); /* clear stack */
  2411. }
  2412. void la_luaDumpStack(lua_State *L){
  2413. int top=lua_gettop(L); for (int i=1; i <= top; i++) {
  2414. printf("%d\t%s\t", i, luaL_typename(L,i));
  2415. switch (lua_type(L, i)) {
  2416. case LUA_TNUMBER: printf("%g\n",lua_tonumber(L,i)); break;
  2417. case LUA_TSTRING: printf("%s\n",lua_tostring(L,i)); break;
  2418. case LUA_TBOOLEAN: printf("%s\n", (lua_toboolean(L, i) ? "true" : "false")); break;
  2419. case LUA_TNIL: printf("%s\n", "nil"); break;
  2420. default: printf("%p\n",lua_topointer(L,i)); break;
  2421. }
  2422. }
  2423. }
  2424. #else //luajit
  2425. int terLoadLine(char* buf, int firstline){
  2426. logPrint(buf); return 0;
  2427. }
  2428. #endif //luajit
  2429. #ifdef LAGUI_ANDROID
  2430. void glPointSize(real a){
  2431. return;
  2432. }
  2433. void glDrawBuffer(GLenum mode){
  2434. GLenum b={GL_NONE};
  2435. glDrawBuffers(1,b);
  2436. }
  2437. #endif