summaryrefslogtreecommitdiffstats
path: root/kviewshell/plugins/djvu/libdjvu/DjVuMessage.cpp
blob: f20c1106ce735ac889c933f8bf796c58a33334d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//C-  -*- C++ -*-
//C- -------------------------------------------------------------------
//C- DjVuLibre-3.5
//C- Copyright (c) 2002  Leon Bottou and Yann Le Cun.
//C- Copyright (c) 2001  AT&T
//C-
//C- This software is subject to, and may be distributed under, the
//C- GNU General Public License, Version 2. The license should have
//C- accompanied the software or you may obtain a copy of the license
//C- from the Free Software Foundation at http://www.fsf.org .
//C-
//C- This program is distributed in the hope that it will be useful,
//C- but WITHOUT ANY WARRANTY; without even the implied warranty of
//C- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//C- GNU General Public License for more details.
//C- 
//C- DjVuLibre-3.5 is derived from the DjVu(r) Reference Library
//C- distributed by Lizardtech Software.  On July 19th 2002, Lizardtech 
//C- Software authorized us to replace the original DjVu(r) Reference 
//C- Library notice by the following text (see doc/lizard2002.djvu):
//C-
//C-  ------------------------------------------------------------------
//C- | DjVu (r) Reference Library (v. 3.5)
//C- | Copyright (c) 1999-2001 LizardTech, Inc. All Rights Reserved.
//C- | The DjVu Reference Library is protected by U.S. Pat. No.
//C- | 6,058,214 and patents pending.
//C- |
//C- | This software is subject to, and may be distributed under, the
//C- | GNU General Public License, Version 2. The license should have
//C- | accompanied the software or you may obtain a copy of the license
//C- | from the Free Software Foundation at http://www.fsf.org .
//C- |
//C- | The computer code originally released by LizardTech under this
//C- | license and unmodified by other parties is deemed "the LIZARDTECH
//C- | ORIGINAL CODE."  Subject to any third party intellectual property
//C- | claims, LizardTech grants recipient a worldwide, royalty-free, 
//C- | non-exclusive license to make, use, sell, or otherwise dispose of 
//C- | the LIZARDTECH ORIGINAL CODE or of programs derived from the 
//C- | LIZARDTECH ORIGINAL CODE in compliance with the terms of the GNU 
//C- | General Public License.   This grant only confers the right to 
//C- | infringe patent claims underlying the LIZARDTECH ORIGINAL CODE to 
//C- | the extent such infringement is reasonably necessary to enable 
//C- | recipient to make, have made, practice, sell, or otherwise dispose 
//C- | of the LIZARDTECH ORIGINAL CODE (or portions thereof) and not to 
//C- | any greater extent that may be necessary to utilize further 
//C- | modifications or combinations.
//C- |
//C- | The LIZARDTECH ORIGINAL CODE is provided "AS IS" WITHOUT WARRANTY
//C- | OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
//C- | TO ANY WARRANTY OF NON-INFRINGEMENT, OR ANY IMPLIED WARRANTY OF
//C- | MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
//C- +------------------------------------------------------------------
// 
// $Id: DjVuMessage.cpp,v 1.16 2005/04/27 16:34:13 leonb Exp $
// $Name: release_3_5_15 $

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#if NEED_GNUG_PRAGMAS
# pragma implementation
#endif

// From: Leon Bottou, 1/31/2002
// All these XML messages are Lizardtech innovations.

#include "DjVuMessage.h"
#include "GOS.h"
#include "XMLTags.h"
#include "ByteStream.h"
#include "GURL.h"
#include "debug.h"
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#ifdef WIN32
# include <tchar.h>
# include <atlbase.h>
# include <windows.h>
# include <winreg.h>
#endif
#ifdef UNIX
# include <unistd.h>
# include <pwd.h>
# include <sys/types.h>
#endif
#include <locale.h>
#ifndef LC_MESSAGES
# define LC_MESSAGES LC_ALL
#endif


#ifdef HAVE_NAMESPACES
namespace DJVU {
# ifdef NOT_DEFINED // Just to fool emacs c++ mode
}
#endif
#endif

GUTF8String &
DjVuMessage::programname(void)
{
  static GUTF8String xprogramname;
  use_language();
  return xprogramname;
}

static const char namestring[]="name";
static const char srcstring[]="src";

static const char *failed_to_parse_XML=ERR_MSG("DjVuMessage.failed_to_parse_XML");
static const char bodystring[]="BODY";
static const char languagestring[]="LANGUAGE";
static const char headstring[]="HEAD";
static const char includestring[]="INCLUDE";
static const char messagestring[]="MESSAGE";
static const char localestring[]="locale";


// directory names for searching messages
static const char opensourcedir[]="osi";
#ifdef AUTOCONF
static const char DjVuDataDir[] = DIR_DATADIR "/djvu";
static const char ModuleDjVuDir[] ="share/djvu";
#else /* !AUTOCONF */
static const char ModuleDjVuDir[] ="profiles";
#endif /* !AUTOCONF */
static const char LocalDjVuDir[] =".DjVu";      // relative to ${HOME}
#ifdef LT_DEFAULT_PREFIX
static const char DjVuPrefixDir[] = LT_DEFAULT_PREFIX "/profiles";
#endif
#ifndef NDEBUG
static const char DebugModuleDjVuDir[] ="../TOPDIR/SRCDIR/profiles";
#endif
#ifdef WIN32
static const char RootDjVuDir[] ="C:/Program Files/LizardTech/Profiles";
static const TCHAR registrypath[]= TEXT("Software\\LizardTech\\DjVu\\Profile Path");
#else
static const char RootDjVuDir[] ="/etc/DjVu/";  // global last resort
#endif

static const char DjVuEnv[] = "DJVU_CONFIG_DIR";

//  The name of the message file
static const char MessageFile[]="messages.xml";
static const char LanguageFile[]="languages.xml";

#ifdef WIN32
static GURL
RegOpenReadConfig ( HKEY hParentKey )
{
  GURL retval;
   // To do:  This needs to be shared with SetProfile.cpp
  LPCTSTR path = registrypath;

  HKEY hKey = 0;
  // MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,argv[1],strlen(argv[1])+1,wszSrcFile,sizeof(wszSrcFile));
  if (RegOpenKeyEx(hParentKey, path, 0,
              KEY_READ, &hKey) == ERROR_SUCCESS )
  {
    TCHAR path[1024];
    // Success
    TCHAR *szPathValue = path;
    LPCTSTR lpszEntry = (LPCTSTR &)TEXT("");
    DWORD dwCount = (sizeof(path)/sizeof(TCHAR))-1;
    DWORD dwType;

    LONG lResult = RegQueryValueEx(hKey, lpszEntry, NULL,
             &dwType, (LPBYTE) szPathValue, &dwCount);

    RegCloseKey(hKey);

    if ((lResult == ERROR_SUCCESS))
    {
      szPathValue[dwCount] = 0;
      USES_CONVERSION;
      retval=GURL::Filename::Native(T2CA(path));
    }
  } 
//  if (hKey)  RegCloseKey(hKey); 
  return retval;
}

static GURL
GetModulePath( void )
{
  const GUTF8String cwd(GOS::cwd());
  TCHAR path[1024];
  DWORD dwCount = (sizeof(path)/sizeof(TCHAR))-1;
  GetModuleFileName(0, path, dwCount);
  USES_CONVERSION;
  GURL retval=GURL::Filename::Native(T2CA(path)).base();
  GOS::cwd(cwd);
  return retval;
}
#elif defined(UNIX)

static GList<GURL>
parsePATH(void)
{
  GList<GURL> retval;
  const char *path=getenv("PATH");
  if(path)
  {
    GNativeString p(path);
    int from=0;
    for(int to;(to=p.search(':',from))>0;from=to+1)
    {
      if(to > from)
      {
        retval.append(GURL::Filename::Native(p.substr(from,to-from)));
      }
    }
    if((from+1)<(int)p.length())
    {
      retval.append(GURL::Filename::Native(p.substr(from,-1)));
    }
  }
  return retval;
}

static GURL
GetModulePath( void )
{
 GURL retval;
 GUTF8String &xprogramname=DjVuMessage::programname();
 if(xprogramname.length())
 {
   if(xprogramname[1]=='/'
     ||!xprogramname.cmp("../",3)
     ||!xprogramname.cmp("./",2))
   {
     retval=GURL::Filename::UTF8(xprogramname);
   }
   if(retval.is_empty() || !retval.is_file())
   {
     GList<GURL> paths(parsePATH());
     GMap<GUTF8String,void *> pathMAP;
     for(GPosition pos=paths;pos;++pos)
     {
       retval=GURL::UTF8(xprogramname,paths[pos]);
       const GUTF8String path(retval.get_string());
       if(!pathMAP.tqcontains(path))
       {
         if(retval.is_file())
           break;
         pathMAP[path]=0;
       }
     }
   }
   if (! retval.is_empty() )
     retval = retval.follow_symlinks();
   if (! retval.is_empty() )
     retval = retval.base();
 }
 return retval;
}
#endif

static void
appendPath(const GURL &url, 
           GMap<GUTF8String,void *> &map,
           GList<GURL> &list)
{
  if( !url.is_empty() 
      && !map.tqcontains(url.get_string()) && url.is_dir() )
    {
      map[url.get_string()]=0;
      list.append(url);
    }
}

GList<GURL>
DjVuMessage::GetProfilePaths(void)
{
  static bool first=true;
  static GList<GURL> realpaths;
  if(first)
  {
    first=false;
    GMap<GUTF8String,void *> pathsmap;
    GList<GURL> paths;
    GURL path;
    const GUTF8String envp(GOS::getenv(DjVuEnv));
    if(envp.length())
      appendPath(GURL::Filename::UTF8(envp),pathsmap,paths);
#if defined(WIN32) || defined(UNIX)
    GURL mpath(GetModulePath());
    if(!mpath.is_empty() && mpath.is_dir())
    {
#if defined(UNIX) && !defined(AUTOCONF) && !defined(NDEBUG)
      appendPath(GURL::UTF8(DebugModuleDjVuDir,mpath),pathsmap,paths);
#endif
      appendPath(mpath,pathsmap,paths);
      mpath=mpath.base();
      appendPath(GURL::UTF8(ModuleDjVuDir,mpath),pathsmap,paths);
      mpath=mpath.base();
      appendPath(GURL::UTF8(ModuleDjVuDir,mpath),pathsmap,paths);
    }
#endif
#if defined(AUTOCONF)
    GURL dpath = GURL::Filename::UTF8(DjVuDataDir);
    appendPath(dpath,pathsmap,paths);
#endif
#ifdef WIN32
    appendPath(RegOpenReadConfig(HKEY_CURRENT_USER),pathsmap,paths);
    appendPath(RegOpenReadConfig(HKEY_LOCAL_MACHINE),pathsmap,paths);
#else
    GUTF8String home=GOS::getenv("HOME");
# if HAVE_GETPWUID
    if (! home.length()) {
      struct passwd *pw=0;
      if ((pw = getpwuid(getuid())))
        home=GNativeString(pw->pw_dir);
    }
# endif
    if (home.length()) {
      GURL hpath = GURL::UTF8(LocalDjVuDir,GURL::Filename::UTF8(home));
      appendPath(hpath,pathsmap,paths);
    }
#endif
#ifdef LT_DEFAULT_PREFIX
    appendPath(GURL::Filename::UTF8(DjVuPrefixDir),pathsmap,paths);
#endif
    appendPath(GURL::Filename::UTF8(RootDjVuDir),pathsmap,paths);
    pathsmap.empty();

    GPosition pos;
    GList< GMap<GUTF8String,GP<lt_XMLTags> > > localemaps;
    for(pos=paths;pos;++pos)
    {
      path=GURL::UTF8(LanguageFile,paths[pos]);
      if(path.is_file())
      {
        const GP<lt_XMLTags> xml(lt_XMLTags::create(ByteStream::create(path,"rb")));
        const GPList<lt_XMLTags> Body(xml->get_Tags(bodystring));
        GPosition pos=Body;
        if(!pos || (pos != Body.lastpos()))
        {
          G_THROW( ERR_MSG("XMLAnno.extra_body") );
        }
        const GP<lt_XMLTags> GBody(Body[pos]);
        if(!GBody)
        {
          G_THROW( ERR_MSG("XMLAnno.no_body") );
        }
        GMap<GUTF8String,GP<lt_XMLTags> > localemap;
        lt_XMLTags::get_Maps(languagestring,localestring,Body,localemap);
        localemaps.append(localemap);
      }
    } 
    GList<GURL> localepaths;
    GList<GURL> osilocalepaths;

    // Need to do it the right way!
    GUTF8String defaultlocale = getenv("LANGUAGE");
    if (! defaultlocale) 
      {
        const GUTF8String oldlocale(setlocale(LC_MESSAGES,0));
        defaultlocale = setlocale(LC_MESSAGES,"");
        setlocale(LC_MESSAGES,(const char *)oldlocale);
      }
    // Unfathomable search.
    for(int loop=0; loop<2; loop++)
    {
      static const char sepchars[]=" _.@";
      const char *p=sepchars+sizeof(sepchars)-1;
      do
      {
        int sepcharpos=p[0]?defaultlocale.search(p[0]):defaultlocale.length();
        if(sepcharpos > 0)
        {
          const GUTF8String sublocale(defaultlocale,sepcharpos);
          const GUTF8String downcasesublocale("downcase^"+sublocale.downcase());
          for(pos=localemaps;pos;++pos) 
          {
            const GMap<GUTF8String,GP<lt_XMLTags> > &localemap=localemaps[pos];
            GPosition pos=localemap.tqcontains(sublocale);
            if(!pos)
              pos=localemap.tqcontains(downcasesublocale);
            if(pos)
            {
              const GMap<GUTF8String,GUTF8String>&args
                = localemap[pos]->get_args();
              pos = args.tqcontains(srcstring);
              if (pos)
              {
                const GUTF8String src(args[pos]);
                for(pos=paths;pos;++pos)
                {
                  path=GURL::UTF8(src,paths[pos]);
                  if(path.is_dir())
                    localepaths.append(path);
                  path=GURL::UTF8(GUTF8String(opensourcedir)+"/"+src,paths[pos]);
                  if(path.is_dir())
                    osilocalepaths.append(path);
                }
              }
              // We don't need to check anymore language files.
              p=sepchars;
              break;
            }
          }
          if(!pos)
          {
            for(pos=paths;pos;++pos)
            {
              path=GURL::UTF8(sublocale,paths[pos]);
              if(path.is_dir())
              {
                localepaths.append(path);
              }
              path=GURL::UTF8(GUTF8String(opensourcedir)+"/"+sublocale,paths[pos]);
              if(path.is_dir())
              {
                osilocalepaths.append(path);
              }
            }
          }
        }
      } while(p-- != sepchars);
      if((GPosition) localepaths)
        break;
      defaultlocale="C";
    }
    for(pos=localepaths;pos;++pos)
      appendPath(localepaths[pos],pathsmap,realpaths);
    for(pos=paths;pos;++pos)
      appendPath(paths[pos],pathsmap,realpaths);
    for(pos=osilocalepaths;pos;++pos)
      appendPath(osilocalepaths[pos],pathsmap,realpaths);
    for(pos=paths;pos;++pos)
      {
        path=GURL::UTF8(opensourcedir,paths[pos]);
        appendPath(path,pathsmap,realpaths);
      }
  }
  return realpaths;
}

static GUTF8String
getbodies(
  GList<GURL> &paths,
  const GUTF8String &MessageFileName,
  GPList<lt_XMLTags> &body, 
  GMap<GUTF8String, void *> & map )
{
  GUTF8String errors;
  bool isdone=false;
  GPosition firstpathpos=paths;
  for(GPosition pathpos=firstpathpos;!isdone && pathpos;++pathpos)
  {
    const GURL::UTF8 url(MessageFileName,paths[pathpos]);
    if(url.is_file())
    {
      map[MessageFileName]=0;
      GP<lt_XMLTags> gtags;
      {
        GP<ByteStream> bs=ByteStream::create(url,"rb");
        G_TRY
        {
          gtags=lt_XMLTags::create(bs);
        }
        G_CATCH(ex)
        {
          GUTF8String mesg(failed_to_parse_XML+("\t"+url.get_string()));
          if(errors.length())
          {
            errors+="\n"+mesg;
          }else
          {
            errors=mesg;
          }
          errors+="\n"+GUTF8String(ex.get_cause());
        }
        G_ENDCATCH;
      }
      if(gtags)
      {
        lt_XMLTags &tags=*gtags;
        GPList<lt_XMLTags> Bodies=tags.get_Tags(bodystring);
        if(! Bodies.isempty())
        {
          isdone=true;
          for(GPosition pos=Bodies;pos;++pos)
          {
            body.append(Bodies[pos]);
          }
        }
        GPList<lt_XMLTags> Head=tags.get_Tags(headstring);
        if(! Head.isempty())
        {
          isdone=true;
          GMap<GUTF8String, GP<lt_XMLTags> > includes;
          lt_XMLTags::get_Maps(includestring,namestring,Head,includes);
          for(GPosition pos=includes;pos;++pos)
          {
            const GUTF8String file=includes.key(pos);
            if(! map.tqcontains(file))
            {
              GList<GURL> xpaths;
              xpaths.append(url.base());
              const GUTF8String err2(getbodies(xpaths,file,body,map));
              if(err2.length())
              {
                if(errors.length())
                {
                  errors+="\n"+err2;
                }else
                {
                  errors=err2;
                }
              }
            }
          }
        }
      }
    }
  }
  return errors;
}

static GUTF8String
parse(GMap<GUTF8String,GP<lt_XMLTags> > &retval)
{
  GUTF8String errors;
  GPList<lt_XMLTags> body;
  {
    GList<GURL> paths=DjVuMessage::GetProfilePaths();
    GMap<GUTF8String, void *> map;
    GUTF8String m(MessageFile);
    errors=getbodies(paths,m,body,map);
  }
  if(! body.isempty())
  {
    lt_XMLTags::get_Maps(messagestring,namestring,body,retval);
  }
  return errors;
}


const DjVuMessageLite &
DjVuMessage::create_full(void)
{
  GP<DjVuMessageLite> &static_message=getDjVuMessageLite();
  if(!static_message)
  {
    DjVuMessage *mesg=new DjVuMessage;
    static_message=mesg;
    mesg->init();
  }
  return DjVuMessageLite::create_lite();
}

void
DjVuMessage::set_programname(const GUTF8String &xprogramname)
{
  programname()=xprogramname;
  DjVuMessageLite::create=create_full; 
}

void
DjVuMessage::use_language(void)
{ 
  DjVuMessageLite::create=create_full; 
}


// Constructor
DjVuMessage::DjVuMessage( void ) {}

void
DjVuMessage::init(void)
{
  errors=parse(Map);
}

// Destructor
DjVuMessage::~DjVuMessage( )
{
}


//  A C function to perform a message lookup. Arguments are a buffer to receiv
//  translated message, a buffer size (bytes), and a message_list. The transla
//  result is returned in msg_buffer encoded in Native MBS encoding. In case
// of error, msg_b empty (i.e., msg_buffer[0] == '\0').
void
DjVuMessageLookUpNative( 
  char *msg_buffer, const unsigned int buffer_size, const char *message)
{
  const GNativeString converted(DjVuMessage::LookUpNative( message ));
  if( converted.length() >= buffer_size )
    msg_buffer[0] = '\0';
  else
    strcpy( msg_buffer, converted );
}

//  A C function to perform a message lookup. Arguments are a buffer to receiv
//  translated message, a buffer size (bytes), and a message_list. The transla
//  result is returned in msg_buffer encoded in UTF8 encoding. In case
// of error, msg_b empty (i.e., msg_buffer[0] == '\0').
void
DjVuMessageLookUpUTF8( 
  char *msg_buffer, const unsigned int buffer_size, const char *message)
{
  const GUTF8String converted(DjVuMessage::LookUpUTF8( message ));
  if( converted.length() >= buffer_size )
    msg_buffer[0] = '\0';
  else
    strcpy( msg_buffer, converted );
}



#ifdef HAVE_NAMESPACES
}
# ifndef NOT_USING_DJVU_NAMESPACE
using namespace DJVU;
# endif
#endif

void
DjVuFormatErrorUTF8( const char *fmt, ... )
{
  va_list args;
  va_start(args, fmt); 
  const GUTF8String message(fmt,args);
  DjVuWriteError( message );
}

void
DjVuFormatErrorNative( const char *fmt, ... )
{
  va_list args;
  va_start(args, fmt); 
  const GNativeString message(fmt,args);
  DjVuWriteError( message );
}

const char *
djvu_programname(const char *xprogramname)
{
  if(xprogramname)
    DjVuMessage::programname()=GNativeString(xprogramname);
  return DjVuMessage::programname();
}