Debian Codegraph @

dicts.c

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