source: trunk/libdjvu/DjVuMessageLite.cpp @ 206

Last change on this file since 206 was 206, checked in by Eugene Romanenko, 14 years ago

DJVU plugin: djvulibre updated to version 3.5.19

File size: 14.5 KB
Line 
1//C-  -*- C++ -*-
2//C- -------------------------------------------------------------------
3//C- DjVuLibre-3.5
4//C- Copyright (c) 2002  Leon Bottou and Yann Le Cun.
5//C- Copyright (c) 2001  AT&T
6//C-
7//C- This software is subject to, and may be distributed under, the
8//C- GNU General Public License, either Version 2 of the license,
9//C- or (at your option) any later version. The license should have
10//C- accompanied the software or you may obtain a copy of the license
11//C- from the Free Software Foundation at http://www.fsf.org .
12//C-
13//C- This program is distributed in the hope that it will be useful,
14//C- but WITHOUT ANY WARRANTY; without even the implied warranty of
15//C- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16//C- GNU General Public License for more details.
17//C-
18//C- DjVuLibre-3.5 is derived from the DjVu(r) Reference Library from
19//C- Lizardtech Software.  Lizardtech Software has authorized us to
20//C- replace the original DjVu(r) Reference Library notice by the following
21//C- text (see doc/lizard2002.djvu and doc/lizardtech2007.djvu):
22//C-
23//C-  ------------------------------------------------------------------
24//C- | DjVu (r) Reference Library (v. 3.5)
25//C- | Copyright (c) 1999-2001 LizardTech, Inc. All Rights Reserved.
26//C- | The DjVu Reference Library is protected by U.S. Pat. No.
27//C- | 6,058,214 and patents pending.
28//C- |
29//C- | This software is subject to, and may be distributed under, the
30//C- | GNU General Public License, either Version 2 of the license,
31//C- | or (at your option) any later version. The license should have
32//C- | accompanied the software or you may obtain a copy of the license
33//C- | from the Free Software Foundation at http://www.fsf.org .
34//C- |
35//C- | The computer code originally released by LizardTech under this
36//C- | license and unmodified by other parties is deemed "the LIZARDTECH
37//C- | ORIGINAL CODE."  Subject to any third party intellectual property
38//C- | claims, LizardTech grants recipient a worldwide, royalty-free,
39//C- | non-exclusive license to make, use, sell, or otherwise dispose of
40//C- | the LIZARDTECH ORIGINAL CODE or of programs derived from the
41//C- | LIZARDTECH ORIGINAL CODE in compliance with the terms of the GNU
42//C- | General Public License.   This grant only confers the right to
43//C- | infringe patent claims underlying the LIZARDTECH ORIGINAL CODE to
44//C- | the extent such infringement is reasonably necessary to enable
45//C- | recipient to make, have made, practice, sell, or otherwise dispose
46//C- | of the LIZARDTECH ORIGINAL CODE (or portions thereof) and not to
47//C- | any greater extent that may be necessary to utilize further
48//C- | modifications or combinations.
49//C- |
50//C- | The LIZARDTECH ORIGINAL CODE is provided "AS IS" WITHOUT WARRANTY
51//C- | OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
52//C- | TO ANY WARRANTY OF NON-INFRINGEMENT, OR ANY IMPLIED WARRANTY OF
53//C- | MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
54//C- +------------------------------------------------------------------
55//
56// $Id: DjVuMessageLite.cpp,v 1.14 2007/03/25 20:48:30 leonb Exp $
57// $Name: release_3_5_19 $
58
59#ifdef HAVE_CONFIG_H
60# include "config.h"
61#endif
62#if NEED_GNUG_PRAGMAS
63# pragma implementation
64#endif
65
66// From: Leon Bottou, 1/31/2002
67// All these I18N XML messages are Lizardtech innovations.
68// For DjvuLibre, I changed the path extraction logic
69// and added support for non I18N messages.
70
71#include "DjVuMessageLite.h"
72#include "GOS.h"
73#include "XMLTags.h"
74#include "ByteStream.h"
75#include "GURL.h"
76#include "debug.h"
77#include <ctype.h>
78#include <string.h>
79#include <stdlib.h>
80// #include <stdio.h>
81#ifdef WIN32
82#include <tchar.h>
83#include <atlbase.h>
84#include <windows.h>
85#include <winreg.h>
86#endif
87#ifdef UNIX
88#include <unistd.h>
89#include <pwd.h>
90#include <sys/types.h>
91#endif
92#include <locale.h>
93
94
95#ifdef HAVE_NAMESPACES
96namespace DJVU {
97# ifdef NOT_DEFINED // Just to fool emacs c++ mode
98}
99#endif
100#endif
101
102
103const DjVuMessageLite& (*DjVuMessageLite::create)(void) = 
104  DjVuMessageLite::create_lite; 
105
106static const char *failed_to_parse_XML=
107  ERR_MSG("DjVuMessage.failed_to_parse_XML");
108static const char *unrecognized=
109  ERR_MSG("DjVuMessage.Unrecognized");
110static const char *uparameter=
111  ERR_MSG("DjVuMessage.Parameter");
112#ifdef LIZARDTECH_1_800_NUMBER
113static const char unrecognized_default[] =
114  "** Unrecognized DjVu Message: [Contact LizardTech at " 
115  LIZARDTECH_1_800_NUMBER " \n"
116  "\t** Message name:  %1!s!";
117#else
118static const char unrecognized_default[] =
119  "** Unrecognized DjVu Message:\n"
120  "\t** Message name:  %1!s!";
121#endif
122static const char uparameter_default[] = 
123  "\t   Parameter: %1!s!";
124static const char failed_to_parse_XML_default[]=
125  "Failed to parse XML message file:&#10;&#09;&apos;%1!s!&apos;.";
126
127static const char namestring[]="name";
128static const char valuestring[]="value";
129static const char numberstring[]="number";
130static const char bodystring[]="BODY";
131static const char messagestring[]="MESSAGE";
132
133GPList<ByteStream> &
134DjVuMessageLite::getByteStream(void)
135{
136  static GPList<ByteStream> gbs;
137  return gbs;
138}
139
140GP<DjVuMessageLite> &
141DjVuMessageLite::getDjVuMessageLite(void)
142{
143  static GP<DjVuMessageLite> message;
144  return message;
145}
146
147void
148DjVuMessageLite::AddByteStreamLater(const GP<ByteStream> &bs)
149{
150  getByteStream().append(bs);
151}
152
153//  There is only object of class DjVuMessage in a program, and here it is:
154//DjVuMessage  DjVuMsg;
155const DjVuMessageLite &
156DjVuMessageLite::create_lite(void)
157{
158  GP<DjVuMessageLite> &static_message=getDjVuMessageLite();
159  if(!static_message)
160  {
161    static_message=new DjVuMessageLite;
162  }
163  DjVuMessageLite &m=*static_message;
164  GPList<ByteStream> &bs = getByteStream();
165  for(GPosition pos;(pos=bs);bs.del(pos))
166  {
167    m.AddByteStream(bs[pos]);
168  }
169  return m;
170}
171
172// Constructor
173DjVuMessageLite::DjVuMessageLite( void ) {}
174
175// Destructor
176DjVuMessageLite::~DjVuMessageLite( ) {}
177
178
179void
180DjVuMessageLite::perror( const GUTF8String & MessageList )
181{
182  DjVuPrintErrorUTF8("%s\n",(const char *)DjVuMessageLite::LookUpUTF8(MessageList));
183}
184
185
186//  Expands message lists by looking up the message IDs and inserting
187//  arguments into the retrieved messages.
188//  N.B. The resulting string may be encoded in UTF-8 format (ISO 10646-1 Annex R)
189//       and SHOULD NOT BE ASSUMED TO BE ASCII.
190GUTF8String
191DjVuMessageLite::LookUp( const GUTF8String & MessageList ) const
192{
193//  DEBUG_MSG( "========== DjVuMessageLite::LookUp ==========\n" <<
194//             MessageList <<
195//             "\n========== DjVuMessageLite::LookUp ==========\n" );
196  GUTF8String result;                       // Result string; begins empty
197  if(errors.length())
198  {
199    const GUTF8String err1(errors);
200    (const_cast<GUTF8String &>(errors)).empty();
201    result=LookUp(err1)+"\n";
202  }
203
204  int start = 0;                            // Beginning of next message
205  int end = MessageList.length();           // End of the message string
206
207  //  Isolate single messages and process them
208  while( start < end )
209  {
210    if( MessageList[start] == '\n' )
211    {
212      result += MessageList[start++];       // move the newline to the result
213                                            // and advance to the next message
214    }
215    else
216    {
217      //  Find the end of the next message and process it
218      int next_ending = MessageList.search((unsigned long)'\n', start);
219      if( next_ending < 0 )
220        next_ending = end;
221      result += LookUpSingle( MessageList.substr(start, next_ending-start) );
222      //  Advance to the next message
223      start = next_ending;
224    }
225  }
226
227  //  All done
228  return result;
229}
230
231
232// Expands a single message and inserts the arguments. Single_Message
233// contains no separators (newlines), but includes all the parameters
234// separated by tabs.
235GUTF8String
236DjVuMessageLite::LookUpSingle( const GUTF8String &Single_Message ) const
237{
238#if HAS_CTRL_C_IN_ERR_MSG
239  if (Single_Message[0] != '\003')
240    return Single_Message;
241#endif
242  //  Isolate the message ID and get the corresponding message text
243  int ending_posn = Single_Message.contains("\t\v");
244  if( ending_posn < 0 )
245    ending_posn = Single_Message.length();
246  GUTF8String msg_text;
247  GUTF8String msg_number;
248  const GUTF8String message=Single_Message.substr(0,ending_posn);
249  LookUpID( message, msg_text, msg_number );
250
251  //  Check whether we found anything
252  if( !msg_text.length())
253  {
254    if(message == unrecognized)
255    {
256      msg_text = unrecognized_default;
257    }else if(message == uparameter)
258    {
259      msg_text = uparameter_default;
260    }else if(message == failed_to_parse_XML)
261    {
262      msg_text = failed_to_parse_XML_default;
263    }else
264    {
265      return LookUpSingle(unrecognized + ("\t" + Single_Message));
266    }
267  }
268   
269  //  Insert the parameters (if any)
270  unsigned int param_num = 0;
271  while( (unsigned int)ending_posn < Single_Message.length() )
272  {
273    GUTF8String arg;
274    const int start_posn = ending_posn+1;
275    if(Single_Message[ending_posn] == '\v')
276    {
277      ending_posn=Single_Message.length();
278      arg=LookUpSingle(Single_Message.substr(start_posn,ending_posn));
279    }else
280    {
281      ending_posn = Single_Message.contains("\v\t",start_posn);
282      if( ending_posn < 0 )
283        ending_posn = Single_Message.length();
284      arg=Single_Message.substr(start_posn, ending_posn-start_posn);
285    }
286    InsertArg( msg_text, ++param_num, arg);
287  }
288  //  Insert the message number
289  InsertArg( msg_text, 0, msg_number );
290
291  return msg_text;
292}
293
294
295// Looks up the msgID in the file of messages and returns a pointer to
296// the beginning of the translated message, if found; and an empty string
297// otherwise.
298void
299DjVuMessageLite::LookUpID( const GUTF8String &xmsgID,
300                       GUTF8String &message_text,
301                       GUTF8String &message_number ) const
302{
303  if(!Map.isempty())
304  {
305    GUTF8String msgID = xmsgID;
306#if HAS_CTRL_C_IN_ERR_MSG
307    int start = 0;
308    while (msgID[start] == '\003') 
309      start ++;
310    if (start > 0)
311      msgID = msgID.substr(start, msgID.length() - start);
312#endif
313    GPosition pos=Map.contains(msgID);
314    if(pos)
315    {
316      const GP<lt_XMLTags> tag=Map[pos];
317      GPosition valuepos=tag->get_args().contains(valuestring);
318      if(valuepos)
319      {
320        message_text=tag->get_args()[valuepos];
321      }else
322      {
323        const GUTF8String raw(tag->get_raw());
324        const int start_line=raw.search((unsigned long)'\n',0);
325     
326        const int start_text=raw.nextNonSpace(0);
327        const int end_text=raw.firstEndSpace(0);
328        if(start_line<0 || start_text<0 || start_text < start_line)
329        {
330          message_text=raw.substr(0,end_text).fromEscaped();
331        }else
332        {
333          message_text=raw.substr(start_line+1,end_text-start_line-1).fromEscaped();
334        }
335      }
336      GPosition numberpos=tag->get_args().contains(numberstring);
337      if(numberpos)
338      {
339        message_number=tag->get_args()[numberpos];
340      }
341    }
342  }
343}
344
345
346// Insert a string into the message text. Will insert into any field
347// description.  Except for an ArgId of zero (message number), if the ArgId
348// is not found, the routine adds a line with the parameter so information
349// will not be lost.
350void
351DjVuMessageLite::InsertArg( GUTF8String &message,
352  const int ArgId, const GUTF8String &arg ) const
353{
354    // argument target string
355  const GUTF8String target= "%"+GUTF8String(ArgId)+"!";
356    // location of target string
357  int format_start = message.search( (const char *)target );
358  if( format_start >= 0 )
359  {
360    do
361    {
362      const int n=format_start+target.length()+1;
363      const int format_end=message.search((unsigned long)'!',n);
364      if(format_end > format_start)
365      { 
366        const int len=1+format_end-n;
367        if(len && isascii(message[n-1]))
368        {
369          GUTF8String narg;
370          GUTF8String format="%"+message.substr(n-1,len);
371          switch(format[len])
372          {
373            case 'd':
374            case 'i':
375              narg.format((const char *)format,arg.toInt());
376              break;
377            case 'u':
378            case 'o':
379            case 'x':
380            case 'X':
381              narg.format((const char *)format,(unsigned int)arg.toInt());
382              break;
383            case 'f':
384              {
385                int endpos;
386                narg.format((const char *)format, arg.toDouble(0,endpos));
387                if( endpos < 0 )
388                  narg = arg;
389              }
390              break;
391            default:
392              narg.format((const char *)format,(const char *)arg);
393              break;
394          }
395          message = message.substr( 0, format_start )+narg
396            +message.substr( format_end+1, -1 );
397        }else
398        {
399          message = message.substr( 0, format_start )+arg
400            +message.substr( format_end+1, -1 );
401        }
402      }
403      format_start=message.search((const char*)target, format_start+arg.length());
404    } while(format_start >= 0);
405  }
406  else
407  {
408    //  Not found, fake it
409    if( ArgId != 0 )
410    {
411      message += "\n"+LookUpSingle(uparameter+("\t"+arg));
412    }
413  }
414}
415
416
417//  A C function to perform a message lookup. Arguments are a buffer to received the
418//  translated message, a buffer size (bytes), and a message_list. The translated
419//  result is returned in msg_buffer encoded in UTF-8. In case of error, msg_buffer is
420//  empty (i.e., msg_buffer[0] == '\0').
421void 
422DjVuMessageLite_LookUp( char *msg_buffer, const unsigned int buffer_size, const char *message )
423{
424  GUTF8String converted = DjVuMessageLite::LookUpUTF8( message );
425  if( converted.length() >= buffer_size )
426    msg_buffer[0] = '\0';
427  else
428    strcpy( msg_buffer, converted );
429}
430
431void
432DjVuMessageLite::AddByteStream(const GP<ByteStream> &bs)
433{
434  const GP<lt_XMLTags> gtags(lt_XMLTags::create(bs));
435  lt_XMLTags &tags=*gtags;
436  GPList<lt_XMLTags> Bodies=tags.get_Tags(bodystring);
437  if(! Bodies.isempty())
438  {
439    lt_XMLTags::get_Maps(messagestring,namestring,Bodies,Map);
440  }
441}
442
443
444
445#ifdef HAVE_NAMESPACES
446}
447# ifndef NOT_USING_DJVU_NAMESPACE
448using namespace DJVU;
449# endif
450#endif
451
452void
453DjVuWriteError( const char *message )
454{
455  G_TRY {
456    GP<ByteStream> errout = ByteStream::get_stderr();
457    if (errout)
458      {
459        const GUTF8String external = DjVuMessageLite::LookUpUTF8( message );
460        errout->writestring(external+"\n");
461      }
462    // Need to catch all exceptions because these might be
463    // called from an outer exception handler (with prejudice)
464  } G_CATCH_ALL { } G_ENDCATCH;
465}
466
467void
468DjVuWriteMessage( const char *message )
469{
470  G_TRY {
471    GP<ByteStream> strout = ByteStream::get_stdout();
472    if (strout)
473      {
474        const GUTF8String external = DjVuMessageLite::LookUpUTF8( message );
475        strout->writestring(external+"\n");
476      }
477    // Need to catch all exceptions because these might be
478    // called from an outer exception handler (with prejudice)
479  } G_CATCH_ALL { } G_ENDCATCH;
480}
Note: See TracBrowser for help on using the repository browser.