Debian Codegraph @

dicts.c

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 /*
2 Qxw is a program to help construct and publish crosswords.
3
4 Copyright 2011-2020 Mark Owen; Windows port by Peter Flippant
5 http://www.quinapalus.com
6 E-mail: [email protected]
7
8 This file is part of Qxw.
9
10 Qxw is free software: you can redistribute it and/or modify
11 it under the terms of version 2 of the GNU General Public License
12 as published by the Free Software Foundation.
13
14 Qxw is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with Qxw. If not, see <http://www.gnu.org/licenses/> or
21 write to the Free Software Foundation, Inc., 51 Franklin Street,
22 Fifth Floor, Boston, MA 02110-1301, USA.
23 */
24
25
•26 #define PCRE2_CODE_UNIT_WIDTH 8
27 #include <pcre2.h>
28 #include <glib.h> // required for string conversion functions
29 #include <glib/gstdio.h>
30
31 #include "common.h"
32 #include "qxw.h"
33 #include "gui.h"
34 #include "dicts.h"
35 #include "alphabets.h"
36
37 // default dictionaries
38 #ifdef _WIN32
39 // Windows default dictionaries stored in subfolder of {app} folder
40 #define NDEFDICTS 1
41 char*defdictfn[NDEFDICTS]={
42 "\\Dictionaries\\UKACD18plus.txt"
43 };
44 #else
45 #define NDEFDICTS 4
46 char*defdictfn[NDEFDICTS]={
47 "/usr/dict/words",
48 "/usr/share/dict/words",
49 "/usr/share/dict/british-english",
50 "/usr/share/dict/american-english"};
51 #endif
52
53 // UTILITY FUNCTIONS
54
55 // utf-8 string to uchar string, printable characters only
56 // there appears to be no efficient cross-platform library function to do this
57 // s points to utf-8 string, ucs to output buffer of length l
58 // return number of output uchars
59 // assumes valid input; output guaranteed 0-terminated if l>1; if l==1 but no recognised utf8 writes 0
60 int utf8touchars(uchar*ucs,const char*p,int l) {
61 int i,j,l0,n;
62 uchar c;
63 unsigned char*s=(unsigned char*)p;
64
65 l0=l-1; if(l0==0) l0=1;
66 for(i=0;i<l0;) {
67 if(*s==0) goto done;
68 if(*s>=0x20&&*s<0x7f) {ucs[i++]=*s++; continue;} // ASCII-7 printable
69 if(*s<0xc0) {s++; continue;}
70 if(*s<0xe0) {n=1; c=*s&0x1f;}
71 else if(*s<0xf0) {n=2; c=*s&0x0f;}
72 else if(*s<0xf8) {n=3; c=*s&0x07;}
73 else if(*s<0xfc) {n=4; c=*s&0x03;}
74 else if(*s<0xfe) {n=5; c=*s&0x01;}
75 else {s++; continue;}
76 s++;
77 for(j=0;j<n;j++) {
78 if(*s==0) goto done;
79 c=(c<<6)+(*s++&0x3f);
80 }
81 if(ISUPRINT(c)) ucs[i++]=c;
82 }
83 done:
84 if(i<l) ucs[i]=0;
85 return i;
86 }
87
88 // uchar to utf-8 string, printable characters only; up to 6 bytes + zero termination output
89 char*uchartoutf8(char*q,uchar c) {
90 int n;
91 *q=0;
92 if(!ISUPRINT(c)) return q;
93 if (c< 0x80U) *q++= c ,n=-1;
94 else if(c< 0x800U) *q++=(c>> 6)+0xc0,n= 0;
95 else if(c< 0x10000U) *q++=(c>>12)+0xe0,n= 1;
96 else if(c< 0x200000U) *q++=(c>>18)+0xf0,n= 2;
97 else if(c< 0x4000000U) *q++=(c>>24)+0xf8,n= 3;
98 else if(c<0x80000000U) *q++=(c>>30)+0xfc,n= 4;
99 else return q;
100 for(;n>=0;n--) *q++=((c>>(n*6))&0x3f)+0x80;
101 *q=0;
102 return q;
103 }
104
105 // uchar string to utf-8 string, printable characters only; up to 6 bytes per input uchar + zero termination output
106 char*ucharstoutf8(char*q,uchar*s) {
107 *q=0;
108 for(;*s;s++) q=uchartoutf8(q,*s);
109 return q;
110 }
111
112 // length of a 0-terminated uchar string
113 int ucharslen(uchar*s) {
114 int i;
115 for(i=0;s[i];i++) ;
116 return i;
117 }
118
119 // number of bytes in UTF-8 char pointed to by p
120 int q_mblen(char*p) {
121 if(*p == '\0') return 0;
122 if(!(*p & 0x80)) return 1;
123 else if((*p & 0xe0) == 0xc0) {
124 if ((*(p+1) & 0xc0) != 0x80) return -1;
125 else return 2;
126 }
127 else if((*p & 0xf0) == 0xe0) {
128 if((*(p+1) & 0xc0) != 0x80) return -1;
129 else if((*(p+2) & 0xc0) != 0x80) return -1;
130 else return 3;
131 }
132 else if((*p & 0xf8) == 0xf0) {
133 if((*(p+1) & 0xc0) != 0x80) return -1;
134 else if((*(p+2) & 0xc0) != 0x80) return -1;
135 else if((*(p+3) & 0xc0) != 0x80) return -1;
136 else return 4;
137 }
138 else if((*p & 0xfc) == 0xf8) {
139 if((*(p+1) & 0xc0) != 0x80) return -1;
140 else if((*(p+2) & 0xc0) != 0x80) return -1;
141 else if((*(p+3) & 0xc0) != 0x80) return -1;
142 else if((*(p+4) & 0xc0) != 0x80) return -1;
143 else return 5;
144 }
145 else if((*p & 0xfe) == 0xfc) {
146 if((*(p+1) & 0xc0) != 0x80) return -1;
147 else if((*(p+2) & 0xc0) != 0x80) return -1;
148 else if((*(p+3) & 0xc0) != 0x80) return -1;
149 else if((*(p+4) & 0xc0) != 0x80) return -1;
150 else if((*(p+5) & 0xc0) != 0x80) return -1;
151 else return 6;
152 }
153 else return -1;
154 }
155
156 // CHARACTER MAPPING
157
158 static unsigned char uchartoicctab[MAXUCHAR]; // convert UTF-32 to internal character code
159 uchar icctouchar[MAXICC+1]; // convert internal character code to UTF-32 of canonical representative
160 char icctoutf8[MAXICC+1][16]; // convert internal character code to UTF-8 string of canonical representative, 0-terminated
161 char iccequivs[MAXICC][MAXEQUIV*8+1];
162 char iccseq[MAXICC+1];
163 static unsigned char uchartopair[MAXUCHAR];
164 static uchar pairtouchar[MAXICC][2];
165
166 // The following are largely to help with answer treatments etc.
167 // ICCs are divided into three groups: basically alphabetic (0), numeric (1), symbols (2). These occur in that order
168 // in the alphabet specification. Some answer treatments only look at the alphabetic group, or only
169 // (possibly separately) at alphabetic + numeric.
170 int niccused; // number of ICCs actually used
171 char iccused[MAXICC+1]; // list of ICCs actually used
172 int icctousedindex[MAXICC+1]; // convert ICC to index into iccused[]
173 int iccusedtogroup[MAXICC+1]; // convert iccusedindex to group number
174 int icctogroup[MAXICC+1]; // convert ICC to group number, -1 if not used
175 int iccgroupstart[MAXICCGROUP+1]; // starts of groups within iccused[], plus one after the end
176 int iccgroup=0;
177
178 // in the "pair" case, icctoutf8 contains two characters into which dictionary characters in iccequivs will be expanded
179
180
181 uchar ICCtouchar(char c) { // convert internal character code to UTF-32 or 0 if not represented
182 uchar x;
183 if(c<0||c>MAXICC) return 0;
184 if(c==ICC_DASH) return '-';
185 x=icctouchar[(int)c];
186 if(x=='?') return 0;
187 return icctouchar[(int)c];
188 }
189
190 char uchartoICC(int c) { // convert UTF-32 to internal character code or 0 if not represented
191 if(c<0||c>=MAXUCHAR) return 0;
192 return uchartoicctab[c];
193 }
194
195 // convert bitmap to internal character code
196 // return >0: internal character code
197 // -1: bitmap is zero
198 // -2: more than one bit set
199 int abmtoicc(ABM b) {
200 if(b==0) return -1;
201 if(onebit(b)) return logbase2(b)+1;
202 return -2;
203 }
204
205 int isdisallowed(uchar uc) {
206 if(uc>=MAXUCHAR) return 1;
207 if(!ISUGRAPH(uc)) return 1;
208 if(uc>0x7f) return 0; // all other disallowed characters are 7-bit
209 if(strchr(".-?,[]^\"@#",uc)) return 1;
210 return 0;
211 }
212
213 ABM abm_vow,abm_con,abm_use;
214
215 // add an entry to the current alphabet
216 // characters must be added in ascending order of internal code, so that
217 // iccused[] is set correctly for Caesar ciphers etc.
218 // Returns:
219 // 0: OK (including case of empty rep string or bad icc)
220 // 1: disallowed character in rep string (entire entry ignored)
221 // 2: one or more disallowed character(s) in equiv string (character(s) ignored)
222 int addalphamapentry(int icc,char*rep,char*equiv,int vow,int con,int seq) {
223 uchar uc,s0[3],s1[MAXEQUIV+1];
224 int f,g,i,j;
225
226 if(icc<1||icc>=MAXICC) return 0;
227 DEB_AL printf("rep=%s equiv=%s\n",rep,equiv);
228 i=utf8touchars(s0,rep,3); // convert rep to UTF-32, up to 2 characters
229 DEB_AL {
230 printf(" rep -> %d char(s):",i);
231 for(j=0;j<i;j++) printf(" U+%08x",s0[j]);
232 printf("\n");
233 }
234 if(i==1) { // normal case where representative is single character
235 uc=s0[0];
236 if(isdisallowed(uc)) {
237 DEB_AL printf(" uc=%08x: disallowed\n",uc);
238 icctouchar[icc]='?';
239 strcpy(icctoutf8[icc],"?");
240 return 1;
241 }
242 icctouchar[icc]=uc;
243 if(vow) abm_vow|=ICCTOABM(icc);
244 if(con) abm_con|=ICCTOABM(icc);
245 if(ISUALPHA(uc)) g=0;
246 else if(ISUDIGIT(uc)) g=1;
247 else g=2;
248 abm_use|=ICCTOABM(icc);
249 if(niccused<MAXICC) {
250 if(g<iccgroup) g=2; // if groups do not occur in the right order, count everything from first error as a symbol
251 while(iccgroup<g) iccgroupstart[++iccgroup]=niccused;
252 for(j=iccgroup+1;j<MAXICCGROUP+1;j++) iccgroupstart[j]=niccused+1;
253 iccusedtogroup[niccused]=iccgroup;
254 icctogroup[icc]=iccgroup;
255 icctousedindex[icc]=niccused;
256 iccused[niccused]=icc;
257 DEB_AL printf(" icc=%d usedindex=%d group=%d\n",icc,niccused,iccgroup);
258 niccused++;
259 }
260 iccseq[icc]=seq;
261 strncpy(icctoutf8[icc],rep,7); // guaranteed 0-terminated by memset below
262 i=utf8touchars(s1,equiv,MAXEQUIV+1);
263 strncpy(iccequivs[icc],equiv,MAXEQUIV*8); // guaranteed 0-terminated by memset below
264 uchartoicctab[uc]=icc; // include the character itself
265 f=0;
266 for(i=0;s1[i]&&i<MAXEQUIV;i++) {
267 DEB_AL printf(" %08x",s1[i]);
268 if(s1[i]==0xfeff) continue; // 0xfeff is BOM
269 if(isdisallowed(s1[i])) {f=1; continue;}
270 uchartoicctab[s1[i]]=icc;
271 }
272 DEB_AL printf("\n");
273 if(f) return 2;
274 return 0;
275 }
276 else if(i==2) { // special case of a pair of characters: save pre-map (e.g. of A-umlaut to AE)
277 if(isdisallowed(s0[0])) return 1; // both characters of pair valid?
278 if(isdisallowed(s0[1])) return 1;
279 iccequivs[icc][0]=0;
280 strncpy(icctoutf8[icc],rep,15); // guaranteed 0-terminated by memset below
281 i=utf8touchars(s1,equiv,MAXEQUIV+1);
282 strncpy(iccequivs[icc],equiv,MAXEQUIV*8); // guaranteed 0-terminated by memset below
283 DEB_AL printf("pair %08x %08x: ",s0[0],s0[1]);
284 f=0;
285 for(i=0;s1[i]&&i<MAXEQUIV;i++) {
286 DEB_AL printf(" %08x",s1[i]);
287 if(s1[i]==0xfeff) continue; // 0xfeff is BOM
288 if(isdisallowed(s1[i])) {f=1; continue;}
289 uchartopair[s1[i]]=icc;
290 }
291 pairtouchar[icc][0]=s0[0];
292 pairtouchar[icc][1]=s0[1];
293 DEB_AL printf("\n");
294 if(f) return 2;
295 }
296 else {
297 DEB_AL printf(" replacing with '?'\n");
298 icctouchar[icc]='?';
299 strcpy(icctoutf8[icc],"?");
300 return 0; // empty: OK
301 }
302 return 0;
303 }
304
305
306 void clearalphamap() {
307 int i;
308 memset(uchartoicctab,0,sizeof(uchartoicctab));
309 memset(icctouchar,0,sizeof(icctouchar));
310 memset(icctoutf8,0,sizeof(icctoutf8));
311 memset(iccequivs,0,sizeof(iccequivs));
312 memset(iccseq,0,sizeof(iccseq));
313 memset(uchartopair,0,sizeof(uchartopair));
314 memset(pairtouchar,0,sizeof(pairtouchar));
315 abm_vow=abm_con=abm_use=0;
316 niccused=0;
317 memset(iccused,0,sizeof(iccused));
318 for(i=0;i<MAXICC+1;i++) {
319 icctousedindex[i]=-1;
320 iccusedtogroup[i]=-1;
321 icctogroup[i]=-1;
322 }
323 memset(iccgroupstart,0,sizeof(iccgroupstart));
324 strcpy(icctoutf8[MAXICC],"-");
325 icctouchar[MAXICC]='-';
326 iccgroup=0;
327 }
328
329 void initalphamap(struct alphaentry*a) {
330 int i;
331 clearalphamap();
332 for(i=1;i<MAXICC;i++) if(a[i].rep) addalphamapentry(i,a[i].rep,a[i].eqv,a[i].vow,a[i].con,a[i].seq);
333 initcodeword();
334 }
335
336 // non-zero on not found
337 int initalphamapbycode(char*s) {
338 int i,j;
339 clearalphamap();
340 if(!s) return 1;
341 for(i=0;i<NALPHAINIT;i++)
342 for(j=1;alphaname[i][j][0];j++) {
343 if(!STRCASECMP(s,alphaname[i][j])) {
344 initalphamap(alphainitdata[i]);
345 return 0;
346 }
347 }
348 return 1;
349 }
350
351 // print a character represented as uchar
352 void printU(uchar c) { char s[10]; uchartoutf8(s,c); printf("%s",s); }
353
354 // print a string represented as uchars
355 void printUs(const uchar*s) {for(;*s;s++) printU(*s); }
356
357 // print a character represented in internal character code
358 void printICC(char c) { printf("%s",icctoutf8[(int)c]); }
359
360 // print a string represented in internal character code
361 void printICCs(const char*s) { for(;*s;s++) printICC(*s); }
362
363
364 // DICTIONARY FILES
365
366 // set up possible file encodings for dictionary files
367 #define NFILEENC 6
368
369 struct fileenc {
370 char nenc[12]; // name of encoding for g_convert()
371 char bom[4]; // potential byte order mark at start of file
372 int lbom; // length of byte order mark
373 };
374
375 static struct fileenc fenc[NFILEENC] = {
376 {"ISO-8859-1",{'\x00'}, 0},
377 {"UTF-8" ,{'\xEF','\xBB','\xBF'}, 3},
378 {"UTF-16LE" ,{'\xFF','\xFE'}, 2},
379 {"UTF-16BE" ,{'\xFE','\xFF'}, 2},
380 {"UTF-32LE" ,{'\xFF','\xFE','\x00','\x00'},4},
381 {"UTF-32BE" ,{'\x00','\x00','\xFE','\xFF'},4}
382 };
383
384 static struct memblk*dstrings[MAXNDICTS]={0}; // dictionary string pools
385
386 struct answer*ans=0,**ansp=0;
387 struct light*lts=0;
388
389 int atotal=0; // total answers
390 int ltotal=0; // total lights
391 int ultotal=0; // total uniquified lights
392 unsigned int dusedmask; // set of dictionaries used
393
394 char dfnames[MAXNDICTS][SLEN];
395 char dsfilters[MAXNDICTS][SLEN];
396 char dafilters[MAXNDICTS][SLEN];
397 char lemdesc[NLEM][LEMDESCLEN]={""," (rev.)"," (cyc.)"," (cyc., rev.)","*"};
398 char*lemdescADVP[NLEM]={"normally","reversed","cyclically permuted","cyclically permuted and reversed","with any other permutation"};
399
400 static int line;
401 int dst_lines[MAXNDICTS];
402 int dst_lines_f[MAXNDICTS];
403 int dst_lines_fa[MAXNDICTS];
404 int dst_u_rejline[MAXNDICTS][MAXUCHAR];
405 int dst_u_rejline_count[MAXNDICTS][MAXUCHAR];
406
407 #define HTABSZ 1048576
408 static int ahtab[HTABSZ]={0};
409
410 static int cmpans(const void*p,const void*q) {int u; // string comparison for qsort
411 u=strcmp( (*(struct answer**)p)->ul,(*(struct answer**)q)->ul); if(u) return u;
412 u=strcmp( (*(struct answer**)p)->cf,(*(struct answer**)q)->cf); return u;
413 }
414
415 static void clearcounts(int dn) {
416 int i;
417 line=0;
418 dst_lines[dn]=0;
419 dst_lines_f[dn]=0;
420 dst_lines_fa[dn]=0;
421 for(i=0;i<MAXUCHAR;i++) dst_u_rejline[dn][i]=-1;
422 memset(dst_u_rejline_count[dn],0,sizeof(dst_u_rejline_count[dn]));
423 }
424
425 static void freedstrings(int d) { // free string pool associated with dictionary d
426 struct memblk*p;
427 while(dstrings[d]) {p=dstrings[d]->next;free(dstrings[d]);dstrings[d]=p;}
428 }
429
430 void freedicts(void) { // free all memory allocated by loaddicts, even if it aborted mid-load
431 int i;
432 for(i=0;i<MAXNDICTS;i++) freedstrings(i);
433 FREEX(ans);
434 FREEX(ansp);
435 atotal=0;
436 }
437
438 // answer pool is linked list of `struct memblk's containing
439 // strings:
440 // char 0 of string is word score*10+128 (in range 28..228);
441 // char 1 of string is dictionary number
442 // char 2 onwards:
443 // (0-terminated) citation form, in UTF-8
444 // (0-terminated) untreated light form, in chars
445
446 static struct memblk*memblkp=0;
447 static int memblkl=0;
448
449 // Add a new dictionary word with UTF-8 citation form s0
450 // dictionary number dn, score f. Return 1 if added, 0 if not, -2 for out of memory
•451 static int adddictword(char*s0,int dn,pcre2_code*sre,pcre2_code*are,float f) {
452 int c,c0,i,l0,l1,l2;
453 uchar t[MXLE+1],u;
454 char s1[MXLE*16+1];
455 char s2[MXLE+1];
456 struct memblk*q;
•457 pcre2_match_data * pcremd;
458
459 l0=strlen(s0);
460 utf8touchars(t,s0,MXLE+1);
461 for(i=0,l1=0,l2=0;t[i];i++) {
462 u=t[i];
463 if(!ISUGRAPH(u)) continue; // printable, not a space?
464 if(u>=MAXUCHAR) continue;
465 c=uchartoICC(u);
466 if(c) { // characters is in basic alphabet; could check for "reject" chars here
467 if(l2>=MXLE) return 0; // too long?
468 strcpy(s1+l1,icctoutf8[c]); l1+=strlen(s1+l1);
469 s2[l2++]=c;
470 continue;
471 }
472 else {
473 c=uchartopair[t[i]];
474 if(c) { // represents a pair of characters?
475 c0=uchartoICC(pairtouchar[c][0]);
476 if(c0) {
477 if(l2>=MXLE) return 0; // too long?
478 strcpy(s1+l1,icctoutf8[c0]); l1+=strlen(s1+l1);
479 s2[l2++]=c0;
480 }
481 c0=uchartoICC(pairtouchar[c][1]);
482 if(c0) {
483 if(l2>=MXLE) return 0; // too long?
484 strcpy(s1+l1,icctoutf8[c0]); l1+=strlen(s1+l1);
485 s2[l2++]=c0;
486 }
487 }
488 else {
489 if(dst_u_rejline_count[dn][u]++==0) dst_u_rejline[dn][u]=line; // record first instance of rejected Unicode
490 }
491 }
492 }
493 s1[l1]=0;
494 s2[l2]=0;
495 DEB_DV {
496 printf("adddictword: citation=<%s> canonical UTF-8=<%s> canonical ICC=<",s0,s1);
497 printICCs(s2);
498 printf(">\n Unicode:");
499 for(i=0;s2[i];i++) printf(" U+%06X",icctouchar[(unsigned int)s2[i]]);
500 printf("\n");
501 }
502 if(l2<1) { // too short?
503 DEB_DV printf(" too short\n");
504 return 0;
505 }
506 // here s0 contains citation form in UTF-8
507 // s1 contains canonicalised form in UTF-8, length l1
508 // s2 contains canonicalised form in internal character code, length l2 1<=l2<=MXLE
509
510 dst_lines[dn]++;
•511 pcremd = pcre2_match_data_create(120, NULL);
512 if(sre) {
•513 i=pcre2_match(sre,(PCRE2_SPTR)s0,l0,0,0,pcremd,NULL);
514 DEB_DI if(i<-1) printf("PCRE error %d\n",i);
515 if(i<0) {
516 DEB_DV printf(" failed file filter\n");
•517 pcre2_match_data_free(pcremd);
518 return 0; // failed match
519 }
520 }
521 dst_lines_f[dn]++;
522 if(are) {
•523 i=pcre2_match(are,(PCRE2_SPTR)s1,l1,0,0,pcremd,NULL);
524 DEB_DI if(i<-1) printf("PCRE error %d\n",i);
525 if(i<0) {
526 DEB_DV printf(" failed answer filter\n");
•527 pcre2_match_data_free(pcremd);
528 return 0; // failed match
529 }
530 }
531 dst_lines_fa[dn]++;
•532 pcre2_match_data_free(pcremd);
533
534 if(memblkp==NULL||memblkl+2+l0+1+l2+1>MEMBLK) { // allocate more memory if needed (this always happens on first pass round loop)
535 q=(struct memblk*)malloc(sizeof(struct memblk));
536 if(q==NULL) {return -2;}
537 q->next=NULL;
538 if(memblkp==NULL) dstrings[dn]=q; else memblkp->next=q; // link into list
539 memblkp=q;
540 memblkp->ct=0;
541 memblkl=0;
542 }
543 *(memblkp->s+memblkl++)=(char)floor(f*10.0+128.5); // score with rounding
544 *(memblkp->s+memblkl++)=dn;
545 strcpy(memblkp->s+memblkl,s0);memblkl+=l0+1; // citation form, UTF-8
546 strcpy(memblkp->s+memblkl,s2);memblkl+=l2+1; // canonical form, internal character code
547 memblkp->ct++; // count words in this memblk
548 return 1;
549 }
550
551 // read n bytes from fp and interpret as little-endian integer
552 static int getint(FILE*fp,int n) { int i,u; for(i=0,u=0;i<n;i++) u+=fgetc(fp)<<(i*8); return u; }
553
554 #define MXHNODES 512
555 static int hnodep[2][MXHNODES]; // "0" and "1" pointers or -1 for none
556 static int hnodec[MXHNODES]; // char represented or -1 for none
557 static int nhn;
558
559 // add a new Huffman tree entry for code m of length l representing i
560 static int addhcode(int m,int l,int i) {
561 int *p;
562 int j,n;
563
564 DEB_DI printf("addhcode(%d,%d,%d) nhn=%d\n",m,l,i,nhn);
565 for(n=0,j=l-1;j>=0;j--) { // big-endian...
566 p=hnodep[(m>>j)&1]+n;
567 if(*p==-1) { // node does not exist yet
568 if(nhn>=MXHNODES) return -1;
569 *p=nhn;
570 hnodep[0][nhn]=-1;
571 hnodep[1][nhn]=-1;
572 hnodec[nhn]=-1;
573 nhn++;
574 }
575 n=*p;
576 }
577 hnodec[n]=i;
578 return 0;
579 }
580
581 // Attempt to load a .TSD file. Return number of words >=0 on success, <0 on error.
•582 static int loadtsd(FILE*fp,int format,int dn,pcre2_code*sre,pcre2_code*are) {
583 int c,i,j,l,m,ml,n,u,nw;
584 int hoff[MXLE+1]; // file offsets into Huffman coded block
585 int dcount[MXLE+1]; // number of words of each length
586 char s1[SLEN];
587 GError*error=NULL;
588 gchar*sp=NULL;
589
590 DEB_DI printf("attempting to load TSD format=0x%x\n",format);
591 clearcounts(dn);
592 if(format!='0'&&format!='1') return -1; // only TSD0 and TSD1 supported
593 if(fseek(fp,4,SEEK_SET)<0) return -1;
594 ml=getint(fp,2); // maximum length
595 if(ml<1) return -1;
596 DEB_DI printf("ml=%d\n",ml);
597 if(format=='1') getint(fp,12*ml+12); // skip some bytes
598 for(i=0;i<ml;i++) {
599 u=getint(fp,4);
600 if(u<0) return -1;
601 if(i<=MXLE) hoff[i]=u;
602 }
603 for(i=0;i<ml;i++) {
604 u=getint(fp,4);
605 if(u<0) return -1;
606 if(i<=MXLE) {
607 dcount[i]=u;
608 DEB_DI printf("dcount[%d]=%d\n",i,u);
609 }
610 }
611 if(fseek(fp,format=='0'?80:1000,SEEK_CUR)<0) return -1; // skip comment
612 u=getint(fp,2); // ?
613 u=getint(fp,2); // ?
614 DEB_DI printf("hcode array at %08lx\n",ftell(fp));
615 nhn=1;
616 hnodep[0][0]=-1;
617 hnodep[1][0]=-1;
618 hnodec[0]=-1;
619 for(i=0;i<256;i++) { // loop over ISO-8859-1 characters
620 c=getint(fp,1); // character
621 l=getint(fp,1); // code length
622 u=getint(fp,2); // ?
623 m=getint(fp,4); // code
624 if(l>0) {
625 DEB_DI {
626 printf("%02x %c ",i,isprint(i)?i:'?');
627 for(j=l-1;j>=0;j--) printf("%d",(m>>j)&1);
628 printf("\n");
629 }
630 if(addhcode(m,l,i)<0) return -1;
631 }
632 }
633 nw=0;
634 for(l=1;l<ml;l++) {
635 if(l>MXLE) break;
636 if(hoff[l]==0) continue;
637 if(fseek(fp,hoff[l],SEEK_SET)<0) return -1;
638 DEB_DI printf("starting to read length %d at offset %08x; dstrings[%d]=%p memblkp=%p\n",l,hoff[l],dn,(void*)dstrings[dn],(void*)memblkp);
639 j=8;
640 c=0;
641 for(i=0;i<dcount[l];i++) {
642 m=0;
643 n=0;
644 for(;;) {
645 if(j==8) {j=0;c=fgetc(fp);if(c==EOF) return -1;}
646 DEB_DI printf("%d",(c>>j)&1);
647 n=hnodep[(c>>j)&1][n];
648 j++;
649 u=hnodec[n];
650 if(u!=-1) {
651 DEB_DI printf(" %02x %c\n",u,isprint(u)?u:'?');
652 if((u>=0x01&&u<0x7f)||(u>=0xa0&&u<=0xff)) {
653 s1[m]=u;
654 if(m<SLEN-1) m++; // don't overflow
655 }
656 n=0;
657 }
658 if(u==0) break;
659 }
660 if(format=='1') {
661 if(j==8) {j=0;c=fgetc(fp);if(c==EOF) return -1;} // skip a zero bit for some reason
662 j++;
663 }
664 if(m==SLEN-1) continue; // hit string limit? discard
665 s1[m]=0;
666 for(u=0;u<m;u++) if((unsigned char)s1[u]<0x20) break; // look for any non-printable character
667 s1[u]=0; // stop there
668 sp=g_convert(s1,-1,"UTF-8","ISO-8859-1",NULL,NULL,&error);
669 if(error) continue;
670 u=adddictword(sp,dn,sre,are,0.0);
671 g_free(sp),sp=0;
672 if(u==-2) return -2;
673 if(u==1) nw++;
674 }
675 }
676 return nw;
677 }
678
679
680 // return number of answers loaded or:
681 // -1: file not found or problem with encoding
682 // -2: out of memory error from adddictword
683 static int loadonedict(int dn,int sil) {
684 int at,i,j;
685 FILE *fp=0;
686 char s0[SLEN]; // citation form
687 gchar t[SLEN+1]; // input buffer
688
689 float f;
690 int mode,owd,rc;
•691 pcre2_code*sre,*are;
692 int pcreerr;
693 PCRE2_SIZE pcreerroff;
694 PCRE2_UCHAR pcreerrmsg[256];
695 char sfilter[SLEN+1];
696 char afilter[SLEN+1];
697 GError *error = NULL;
698 gchar *sp = NULL;
699 gsize l0;
700 char bom[5];
701
702 rc=0;
703 owd=0;
704 at=0;
705 freedstrings(dn);
706 memblkl=0; // number of bytes stored so far in current memory block
707 memblkp=0; // current memblk being filled
708 if(dfnames[dn][0]=='\0') {
709 if(dafilters[dn][0]=='\0') return 0; // dictionary slot unused
710 owd=1; // one-word dictionary
711 sre=0;
712 are=0;
713 goto ew3;
714 }
715 strcpy(sfilter,dsfilters[dn]);
716 if(!strcmp(sfilter,"")) sre=0;
717 else {
•718 sre=pcre2_compile((PCRE2_SPTR)sfilter,PCRE2_ZERO_TERMINATED,PCRE2_CASELESS|PCRE2_UTF|PCRE2_UCP,&pcreerr,&pcreerroff,0);
719 if(sre == NULL) {
720 pcre2_get_error_message(pcreerr, pcreerrmsg, sizeof pcreerrmsg);
721 sprintf(t,"Dictionary %d\nBad file filter syntax: %s",dn+1,pcreerrmsg);
722 if(!sil) reperr(t);
723 }
724 }
725 strcpy(afilter,dafilters[dn]);
726 if(!strcmp(afilter,"")) are=0;
727 else {
•728 are=pcre2_compile((PCRE2_SPTR)afilter,PCRE2_ZERO_TERMINATED,PCRE2_CASELESS|PCRE2_UTF|PCRE2_UCP,&pcreerr,&pcreerroff,0);
729 if(are == NULL) {
730 pcre2_get_error_message(pcreerr, pcreerrmsg, sizeof pcreerrmsg);
731 sprintf(t,"Dictionary %d\nBad answer filter syntax: %s",dn+1,pcreerrmsg);
732 if(!sil) reperr(t);
733 }
734 }
735
736 ew3:
737 mode=-1; // Indicates file encoding not set by BOM in file
738 if(owd) { mode=1; goto retry; } // Always set file encoding to UTF-8 for one-word dictionary
739 fp=q_fopen(dfnames[dn],"rb"); // binary mode
740 if(!fp) {
741 sprintf(t,"Dictionary %d\nFile not found",dn+1);
742 if(!sil) reperr(t);
743 rc=-1; goto exit;
744 }
745 if(fread(bom,1,4,fp)<4) {rewind(fp); goto retry;} // too short for a BOM, so use mode -1
746 if(!strncmp(bom,"TSD",3)) {
747 i=loadtsd(fp,bom[3],dn,sre,are);
748 if(i>=0) {at=i; goto exit;} // successfully read
749 }
750 rewind(fp);
751 if(fgets(bom,5,fp)!=NULL) { // re-read BOM at start of file
752 for(i=0; i<NFILEENC; i++) {
753 if(fenc[i].lbom>0) {
754 if(!(memcmp(bom,fenc[i].bom,fenc[i].lbom))) {
755 mode=i; // BOM found so set mode
756 fseek(fp,fenc[i].lbom,SEEK_SET); // and skip past BOM
757 break;
758 }
759 }
760 } // end of for loop
761 if(mode>1) { // Cannot read this file encoding mode
762 sprintf(t,"Dictionary %d\nCannot read file encoding:\ntry UTF-8 or ISO-8859-1 encoding",dn+1);
763 if(!sil) reperr(t);
764 rc=-1; goto exit;
765 }
766 if(mode==-1) rewind(fp); // No BOM, so read words from start of file
767 }
768 retry:
769 at=0;
770 freedstrings(dn);
771 memblkl=0; // number of bytes stored so far in current memory block
772 memblkp=0; // current memblk being filled
773 dstrings[dn]=0;
774 clearcounts(dn);
775 DEB_DI printf("Reading dictionary file %s (in mode %d), owd=%d\n",dfnames[dn],mode,owd);
776 for(;;) { // Loop through dictionary 'words' until EOF
777 if(owd) strcpy(t,dafilters[dn]);
778 else {
779 if(feof(fp)) break;
780 if(fgets(t,SLEN,fp)==NULL) break;
781 line++;
782 }
783 j=strlen(t)-1;
784 if(j<0) goto skipword;
785 while(j>=0&&t[j]>=0&&t[j]<=' ') t[j--]=0; // Strip control characters/white space from end of string
786 while (j>=0&&((t[j]>='0'&&t[j]<='9')||t[j]=='.'||t[j]=='+'||t[j]=='-')) j--; // get score (if any) from end
787 j++;
788 f=0.0;
789 if(j==0||t[j-1]!=' ') j=strlen(t); // all digits, or no space? treat it as a 'word'
790 else {
791 sscanf(t+j,"%f",&f);
792 if(f>= 10.0) f= 10.0;
793 if(f<=-10.0) f=-10.0;
794 t[j--]=0; // rest of input is treated as a 'word' (which may contain spaces)
795 }
796 while(j>=0&&t[j]>=0&&t[j]<=' ') t[j--]=0; // remove trailing white space
797 j++;
798 if(j<1) goto skipword;
799
800 // t now contains 'word' for conversion; convert it first to UTF-8 for use as citation form
801 if(mode>-1) { // Use encoding mode based on BOM
802 sp=g_convert(t,-1,"UTF-8",fenc[mode].nenc,NULL,&l0,&error);
803 if(error) {
804 sprintf(t,"Dictionary %d\nFile not encoded in accordance with its BOM",dn+1);
805 if(!sil) reperr(t);
806 rc=-1; goto exit;
807 }
808 } else { // try fallback encodings in turn
809 if(mode==-1) sp=g_convert(t,-1,"UTF-8","UTF-8",NULL,&l0,&error); // effectively a check for valid UTF-8
810 if(mode==-2) sp=g_convert(t,-1,"UTF-8","ISO-8859-1",NULL,&l0,&error);
811 if(error) {
812 DEB_DI {
813 printf("error: %s\n",error->message);
814 for(i=0;t[i];i++) printf(" %02x",t[i]);
815 printf("\n");
816 }
817 g_clear_error(&error);
818 freedstrings(dn);
819 rewind(fp);
820 mode--;
821 if(mode>-3) goto retry; // go round again and try next encoding
822 // here if none of the encodings worked
823 sprintf(t,"Dictionary %d\nFile does not use a recognised encoding:\ntry UTF-8 or ISO-8859-1",dn+1);
824 if(!sil) reperr(t);
825 rc=-1; goto exit;
826 }
827 }
828 // here we have UTF-8 citation form of string in sp, length in l0
829 if(l0>=SLEN) goto skipword;
830 strcpy(s0,sp);
831 g_free(sp),sp=0;
832
833 i=adddictword(s0,dn,sre,are,f);
834 if(i==-2) {rc=-2; goto exit;}
835 if(i==1) at++;
836
837 skipword:
838 if(sp) g_free(sp),sp=0;
839 g_clear_error(&error);
840 if(owd) break;
841 } // End of 'word' for loop
842
843 exit:
844 if(sp) g_free(sp),sp=0;
•845 if(sre) pcre2_code_free(sre);
846 if(are) pcre2_code_free(are);
847 g_clear_error(&error);
848 if(!owd) if(fp) fclose(fp);
849 if(rc<0) return rc;
850 else return at;
851 }
852
853 int loaddicts(int sil) { // load (or reload) dictionaries from dfnames[]
854 // sil=1 suppresses error reporting
855 // returns: 0=success; 1=bad file; 2=no words; 4=out of memory
856 // sets dusedmask to list of dictionaries with anything in them
857 struct answer*ap;
858 struct memblk*p;
859 int at,dn,i,j,k,l,rc,u;
860 char t[SLEN];
861 unsigned int h;
862
863 freedicts();
864 at=0;
865 rc=0;
866 dusedmask=0;
867
868 for(dn=0;dn<MAXNDICTS;dn++) {
869 u=loadonedict(dn,sil);
870 DEB_DI printf("loadonedict(%d) returned %d\n",dn,u);
871 if(u==-2) goto ew4; // out of memory
872 if(u<0) {
873 rc=1;
874 freedstrings(dn);
875 }
876 else if(u>0) at+=u,dusedmask|=1<<dn;
877 }
878
879 if(at==0) { // No words from any dictionary
880 sprintf(t,"No words available from any dictionary");
881 if(!sil) reperr(t);
882 freedicts();
883 return 2;
884 }
885 // allocate array space from counts
886 atotal=at;
887 DEB_DI printf("atotal=%9d\n",atotal);
888 ans =(struct answer* )malloc(atotal*sizeof(struct answer)); if(ans ==NULL) goto ew4;
889 ansp=(struct answer**)malloc(atotal*sizeof(struct answer*)); if(ansp==NULL) goto ew4; // pointer array for sorting
890
891 k=0;
892 for(dn=0;dn<MAXNDICTS;dn++) {
893 p=dstrings[dn];
894 while(p!=NULL) {
895 for(i=0,l=0;i<p->ct;i++) { // loop over all words
896 ans[k].score =pow(10.0,((float)(*(unsigned char*)(p->s+l++))-128.0)/10.0);
897 ans[k].cfdmask=
898 ans[k].dmask =1<<*(unsigned char*)(p->s+l++);
899 ans[k].cf =p->s+l; l+=strlen(p->s+l)+1;
900 ans[k].acf =0;
901 ans[k].ul =p->s+l; l+=strlen(p->s+l)+1; // in internal character code
902 ans[k].banned =0;
903 k++;
904 }
905 p=p->next;
906 }
907 }
908 DEB_DI printf("k=%9d\n",k);
909 assert(k==atotal);
910 for(i=0;i<atotal;i++) ansp[i]=ans+i;
911
912 qsort(ansp,atotal,sizeof(struct answer*),cmpans);
913 ap=0; // ap points to first of each group of matching citation forms
914 for(i=0,j=-1;i<atotal;i++) { // now remove duplicate entries
915 if(i==0||strcmp(ansp[i]->ul,ansp[i-1]->ul)) {j++;ap=ansp[j]=ansp[i];}
916 else {
917 ansp[j]->dmask|=ansp[i]->dmask; // union masks
918 ansp[j]->score*=ansp[i]->score; // multiply scores over duplicate entries
919 if(strcmp(ansp[i]->cf,ansp[i-1]->cf)) ap->acf=ansp[i],ap=ansp[i]; // different citation forms? link them together
920 else ap->cfdmask|=ansp[i]->cfdmask; // cf:s the same: union masks
921 }
922 }
923 atotal=j+1;
924
925 for(i=0;i<HTABSZ;i++) ahtab[i]=-1;
926 for(i=0;i<atotal;i++) {
927 h=0;
928 for(j=0;ansp[i]->ul[j];j++) h=h*113+ansp[i]->ul[j];
929 h=h%HTABSZ;
930 ansp[i]->ahlink=ahtab[h];
931 ahtab[h]=i;
932 }
933
934 for(i=0;i<atotal;i++) {
935 if(ansp[i]->score>= 1e10) ansp[i]->score= 1e10; // clamp scores
936 if(ansp[i]->score<=-1e10) ansp[i]->score=-1e10;
937 }
938 for(i=0;i<atotal;i++) {
939 if(ansp[i]->acf==0) continue;
940 ap=ansp[i];
941 do {
942 // printf(" \"%s\"",ap->cf);
943 ap=ap->acf;
944 } while(ap);
945 // printf("\n");
946 }
947
948 DEB_DI printf("Total unique answers by entry: %d\n",atotal);
949 return rc; // return 1 if any file failed to load
950 ew4:
951 freedicts();
952 if(!sil) reperr("Out of memory loading dictionaries");
953 return 4;
954 }
955
956 // Run through some likely candidates for default dictionaries
957 // Return
958 // 0: found something
959 // !=0: nothing found
960 int loaddefdicts() {int i;
961 if(startup_dict1[0]) { // do we have a candidate preferred startup dictionary?
962 strcpy(dfnames[0],startup_dict1);
963 strcpy(dsfilters[0],startup_ff1);
964 strcpy(dafilters[0],startup_af1);
965 loaddicts(1);
966 DEB_DI printf("read preferences default, atotal=%d\n",atotal);
967 if(atotal!=0) return 0; // happy if we found any words at all
968 }
969 for(i=0;i<NDEFDICTS;i++) {
970 #ifdef _WIN32 // Set the default dictionary path as subpath of {app} path
971 GetCurrentDirectory(SLEN, dfnames[0]);
972 strcat(dfnames[0],defdictfn[i]);
973 #else
974 strcpy(dfnames[0],defdictfn[i]);
975 #endif
976 strcpy(dsfilters[0],"^.*+(?<!'s)");
977 strcpy(dafilters[0],"");
978 loaddicts(1);
979 if(atotal!=0) return 0; // happy if we found any words at all
980 }
981 // all failed
982 strcpy(dfnames[0],"");
983 strcpy(dsfilters[0],"");
984 strcpy(dafilters[0],"");
985 return 4;
986 }
987
988 // is word (in internal character code) in dictionaries specified by dm?
989 int iswordindm(const char*s,int dm) {
990 int i,p;
991 unsigned int h;
992 h=0;
993 for(i=0;s[i];i++) h=h*113+s[i];
994 h=h%HTABSZ;
995 p=ahtab[h];
996 while(p!=-1) {
997 if(!strcmp(s,ansp[p]->ul)) return !!(ansp[p]->dmask&dm);
998 p=ansp[p]->ahlink;
999 }
1000 return 0;
1001 }